Elisp: Functions on Line

By Xah Lee. Date: . Last updated: .

This page is a tutorial on emacs lisp's functions that manipulate line.

How to get beginning/end positions of current line?

;; return line beginning's position
(line-beginning-position)

;; return line end's position
(line-end-position)

These are written in C.

How to move cursor to beginning/end of current line?

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

(end-of-line)
;; 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.

How to 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. They put 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
      (buffer-substring-no-properties
       (line-beginning-position)
       (line-end-position)
       ))

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. So, you can use (search-forward "\n") if you really need to find the end of line character. 〔►see Emacs: Newline Representations ^M ^J ^L

~2010 Thanks to Uday S Reddy and Alan Mackenzie for tips.

Quiz

Here a quiz that captures what these are confusing to beginners.

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:

Like it? Buy Xah Emacs Tutorial. Thanks.