ELisp: Cursor Position Functions
Here's the most useful cursor related functions.
- Cursor position is between characters. By default, cursor is shown as black square ▮ over a character, the position is to the left of the black square.
- The beginning of buffer has cursor position 1. (unless Narrow to Region is in effect.)
Get Cursor Position
point
-
(point)
Return cursor's current position. (beginning of buffer is 1. Position is best thought of as between characters.)
(point) ;; sample result: ;; 770
region-beginning
-
(region-beginning)
Return start position of region. [see ELisp: Mark, Region, Active Region]
region-end
-
(region-end)
Return end position of region.
point-min
-
(point-min)
Return the start position of visible buffer. (respect Narrow to Region)
point-max
-
(point-max)
Return the end position of visible buffer. (respect Narrow to Region )
Move Cursor
goto-char
-
(goto-char POSITION)
Move cursor to a given position.
;; move cursor to position 392 (goto-char 392)
forward-char
-
(forward-char &optional N)
Move cursor forward by N characters.
see also
backward-char
;; move cursor by 9 chars (forward-char 9)
beginning-of-line
-
(beginning-of-line &optional N)
Move cursor to beginning of line. If N is given, N-1 lines first. [see ELisp: Functions on Line]
see also
end-of-line
skip-chars-forward
-
(skip-chars-forward STRING &optional maxPos)
- Move cursor forward by skip a given set of characters.
- but do not go beyond maxPos
- Returns the distance traveled.
Also
skip-chars-backward
.;; move cursor to the first char that's not a newline or tab (skip-chars-forward "\n\t")
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:
search-forward
•search-backward
re-search-forward
•re-search-backward
(using regex)
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.
save-excursion
-
(save-excursion BODY)
Run BODY, and restore cursor position and buffer. See also: ELisp: Save narrow-to-region
(save-excursion ;; code here that moved cursor )