Emacs Lisp: Cursor Position Functions
Here's the most useful cursor related functions.
- Cursor position is considered to be between characters.
- The beginning of buffer has cursor position 1.
Get Cursor Position
Return cursor's current position. (beginning of buffer is 1. Position is best thought of as between characters.)
(point) ;; sample result: ;; 770
Return start position of text selection. [see Emacs Lisp: Region, Active Region]
Return end position of text selection.
Return the start position of visible buffer. (respect
Return the end position of visible buffer. (respect
(info "(elisp) Positions")
Move cursor to a given position.
;; move cursor to position 392 (goto-char 392)
(forward-char &optional N)
Move cursor forward by N characters.
(backward-char &optional N)
Move cursor backward by N characters.
;; move cursor by 9 chars (forward-char 9)
(beginning-of-line &optional N)
Move cursor to beginning of line. If N is given, move forward N-1 lines first. [see Emacs Lisp: Functions on Line]
(end-of-line &optional N)
Move cursor to end of line.
Search Text and Move Cursor
These search functions are used for searchinng text and find replace, but they also move cursor and return cursor position:
See Emacs Lisp: Find Replace String in Buffer
(skip-chars-forward STRING &optional LIM)
Move cursor forward by skip a given set of characters. Returns the distance traveled. Also
;; move cursor to the first char that's not a newline or tab (skip-chars-forward "\n\t")
(info "(elisp) Motion")
Save Cursor Position
When moving cursor, you often want to preserve user's original cursor position, so the cursor won't end up somewhere unexpected when your command is finished.
Run BODY, and restore cursor position and buffer. See also: Emacs Lisp: Save narrow-to-region
(save-excursion ;; lisp code here )