Elisp: Functions on Line

By Xah Lee. Date: . Last updated: .

In emacs lisp, there are lots of ways to move by line or grab lines. Here are some functions or variables that are related to lines:

Do you know the differences? Also, there are issues such as:

Following are best ways to do them.

Get Position of Beginning/End of Line

;; return line beginning's position

;; return line end's position

These are written in C.

Move Cursor to Beginning/End of Line

;; move cursor to beginning/end of current line
;; better than (goto-char (line-beginning-position))

;; better than (goto-char (line-end-position))

These are written in C. So, they are much faster than other functions that are written in elisp.

They don't have problems when the line is at the beginning/end of buffer.

They work by newline char. That is, not soft-wrapped line.

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.

Do not use move-beginning-of-line or move-end-of-line. Because these are designed for interactive use.

Move Cursor to Previous/Next Line

;; move cursor to previous/next line. Cursor will be at beginning of line
(forward-line -1) ; prev line
(forward-line 1)  ; next line

It is written in C. It moves the cursor to the beginning of previous/next line.

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

Do not use (thing-at-point 'line). Normally, thing-at-point will include the newline char, but if the line is at the end of buffer, then it won't. So, if you use it, you have to do extra work to detect special cases. Also, thing-at-point is complex elisp code and is slower.

Get All Lines in a File into a List

Elisp: Read File Content as String or List of Lines

See also: Process a File line-by-line in Emacs Lisp.

Screen Lines

If you want to move cursor across lines as defined by the screen (wrapped at edge of screen), you can use these.

line-move-visual is variable that controls whether next-line and previous-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.

Practical Emacs Lisp


Basic Functions

Writing Command

Writing Script