Elisp: Cursor Position Functions

By Xah Lee. Date: . Last updated: .

Here's the basic functions for cursor position.

You should memorize these by heart.

Get Cursor Position

;; returns current cursor position
(point)
;; beginning of buffer is 1

;; returns the position of the beginning/end of region
(region-beginning)
(region-end)

;; returns the position for the end of buffer
;; (taking account of narrow-to-region)
(point-max)

;; Use (point-min) to get beginning position of buffer when narrow-to-region is in effect
(point-min)
;; should always use this

(info "(elisp) Positions")

Move Cursor and Search

;; move cursor to position 392
(goto-char 392)

;; move cursor by 9 chars
(forward-char 9)
(backward-char 9)

;; move cursor to the first char that's not a newline or tab
;; Returns the distance traveled
(skip-chars-forward "\n\t")
(skip-chars-backward "\n\t")

;; move cursor to the location of string "cat"
;; returns the new position
(search-forward "cat")
(search-backward "cat")

;; move cursor to the location matched by regex
;; returns the new position
(re-search-forward myRegex)
(search-backward-regexp myRegex)

;; move to beginning/end of line
(beginning-of-line)
(end-of-line)

(info "(elisp) Motion")

Preserve Cursor Position

When your command moves cursor to do some work, you usually want to preserve the cursor position before the command starts, so that when user calls your code, the cursor won't end up somewhere unexpected.

;; preserve {point, mark, current buffer}
(save-excursion
  ;; lisp code here involving moving cursor, mark, changing buffer.
)

;; preserve user's narrow-to-region
;; useful when you want to narrow-to-region in your code to work in just that region
(save-restriction
  (narrow-to-region pos1 pos2)
  ;; lisp code here
)

(info "(elisp) Positions")

Elisp Basic Functions

  1. Elisp: Cursor Position Functions
  2. Elisp: Text Editing Functions
  3. Elisp: Buffer and File Functions
  4. Elisp: File and Directory Functions
Like it? Buy Xah Emacs Tutorial. Thanks.