Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

elisp: How to get point one line above the current point?

Tags:

emacs

lisp

elisp

For example, I am trying to return the buffer char location of the position one line above the current (point). My full function is below.

I believe (point) is the character position, so I would like to subtract the number of chars between the current point and the position just above the current point. However, this is dependent on the length of the line above the current point (which is not always equal to the frame-char-height).

I am trying to mimic the Eclipse comment feature, where when an area is selected, the bottom-most line (the line with the pointer) is not included in the commented region:

(defun comment-eclipse (&optional arg)
  (interactive)
  (let ((start (line-beginning-position))
        (end (line-end-position)))
    (when (or (not transient-mark-mode) (region-active-p))
      (setq start (save-excursion
                    (goto-char (region-beginning))
                    (beginning-of-line)
                    (point))
            end (save-excursion
                  (goto-char (region-end))
                  (end-of-line)
                  (point)))) ;; HERE: I want to return something like (- (point) (line-length))
    (comment-or-uncomment-region start end)))

Any suggestions on how to achieve this objective would be appreciated.

UPDATE

Thanks to lunaryorn's answer below, I have improved my function as follows:

(defun comment-eclipse (&optional arg)
  (interactive)
  (let ((start (line-beginning-position))
        (end (line-end-position)))
    (when (or (not transient-mark-mode) (region-active-p))
      (setq start (save-excursion
                    (goto-char (region-beginning))
                    (beginning-of-line)
                    (point))
            end (save-excursion
                  (goto-char (region-end));;move point to region end
                  (end-of-line);;move point to end of line
                  (forward-line -1)
                  (end-of-line)
                  (point))))
    (comment-or-uncomment-region start end)))
like image 763
modulitos Avatar asked Sep 20 '25 02:09

modulitos


1 Answers

Use a combination of current-column to get the current column on a line, forward-line to navigate to another line, and move-to-column to restore the column on the new line:

(let ((column (current-column)))
  (forward-line -1)
  (move-to-column column))

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!