ELisp: Functions on Line
Get Position of Beginning of Line
line-beginning-position
-
(line-beginning-position &optional N)
Return the character position of the first character on the current line.
With optional argument N, scan forward N - 1 lines first.
If the scan reaches the end of the buffer, return that position.
;; return line beginning position (line-beginning-position)
line-end-position
-
(line-end-position &optional N)
return the line end position.
Move Cursor to Beginning of Line
beginning-of-line
-
(beginning-of-line &optional N)
- Move point to beginning of current line.
- N means move forward by N - 1 lines first. N can be negative. If point reaches the beginning or end of buffer, it stops there.
;; move cursor to beginning of current line (beginning-of-line) ;; better than (goto-char (line-beginning-position))
end-of-line
-
(end-of-line &optional N)
like
beginning-of-line
but end of line.
💡 TIP:
Do not use (search-forward "\n")
for moving cursor to end of line. Because you'll have special cases if the line is at the end of buffer and doesn't have a newline char. It is also slower.
💡 TIP:
Do not use move-beginning-of-line
or move-end-of-line
. Because these are designed for interactive use.
Move Cursor to Next Line
forward-line
-
(forward-line &optional N)
- Move cursor to the next line, or N lines.
- N default to 1.
- If N is negative, move in the other direction.
- Cursor ends at the beginning of line.
;; move cursor to previous line, and at the beginning (forward-line -1)
💡 TIP:
Do not use next-line
or previous-line
. Because these are for interactive use. Their behavior changes depending on the variable line-move-visual.
Get Current Line as String
To grab current line, use:
(setq myLine (buffer-substring-no-properties (line-beginning-position) (line-end-position) ))
💡 TIP:
Do not use (thing-at-point 'line)
.
thing-at-point
normally include the newline char, but if the line is at the end of buffer, then it won't.
Also, thing-at-point
is complex elisp code and is slower.
[see ELisp: thing-at-point]
Screen Lines
If you want to move cursor across lines as defined by the screen (wrapped at edge of screen), you can use these.
next-line
previous-line
line-move-visual
- line-move-visual → A variable that controls whether
next-line
andprevious-line
move by newline char or screen.
What Character Does Emacs Use for Newline
In emacs buffer, newline char is "\n"
, in any operating system (Mac, Linux, Microsoft Windows ). So, you can use (search-forward "\n")
. However, if you are on the last line, there may not be a ending "\n"
.
~2010 Thanks to Uday S Reddy [http://www.cs.bham.ac.uk/~udr/] and Alan Mackenzie [http://www.emacswiki.org/emacs/AlanMackenzie] for tips.