Common Emacs Lisp Functions

Master emacs+lisp, benefit for life. Testimonials. Thank you for support.
, , …,

This page gives a list of the most useful elisp functions for text processing tasks in elisp programing. Any elisp coder would have memorized every functions in this page. That's how important they are.

Getting Cursor Position

;; current cursor position
(point)

;; returns the position of the beginning/end of region
(region-beginning)
(region-end)

;; returns the position for the end of buffer
;; (taking account of narrow-to-region)
(point-max)

;; beginning of buffer has point of 1.
;; Use (point-min) to get beginning position of buffer when narrow-to-region is in effect
(point-min)

(info "(elisp) Positions")

Moving Cursor and Searching

;; move cursor to position 392
(goto-char 392)

;; move cursor by n chars
(forward-char n)
(backward-char n)

;; move cursor to the first char that's not a newline or tab
;; Returns the distance traveled
(skip-chars-forward "\n\t")
(skip-chars-backward "\n\t")

;; move cursor to the location of myStr
;; returns the new position
(search-forward myStr)
(search-backward myStr)

;; move cursor to the location matched by regex
;; returns the new position
(search-forward-regexp myRegex)
(search-backward-regexp myRegex)

;; move to beginning/end of line
(beginning-of-line)
(end-of-line)

(info "(elisp) Motion")

Text Editing

The following functions all have the Current Buffer as target.

Inserting Text

;; insert string at current cursor position
(insert "i ♥ u")

;; insert part of a buffer
(insert-buffer-substring-no-properties myBuffer myStartPos myEndPos)

;; insert a file's content
(insert-file-contents myPath)

(info "(elisp) Text")

Deleting Text

;; delete 9 chars starting at current cursor pos
(delete-char 9)

;; deleting text
(delete-region myStartPos myEndPos)

;; delete whole buffer content
(erase-buffer)

Find/Replace Text in Buffer

A typical idiom is to use search-forward or search-forward-regexp, then use replace-match. Use while if you want to do more than one replacement. Example:

;; idiom for string replacement in whole buffer

(let ((case-fold-search t)) ; or nil
  (goto-char (point-min))
  (while (search-forward "myStr" nil t)
    (replace-match "myReplaceStr" t t))
)

;; for regex, use search-forward-regex

To control the letter case of search, set case-fold-search to t or nil with let, as in the above. To control letter case of the replacement, use the optional arguments in your replace-match function.

;; the second captured string
(match-string 2)

;; get the positions of the 2nd captured string
(match-beginning 2) (match-end 2)

Grabbing Text

Functions that grab text in a buffer into a string.

;; get the string from buffer
(setq myStr (buffer-substring myStartPos myEndPos))
(setq myStr (buffer-substring-no-properties myStartPos myEndPos))
;; grab a thing at point. The “thing” is a semantic unit. It can be a
; word, symbol, line, sentence, filename, URL and others.

;; grab the current word
(setq myStr (thing-at-point 'word))

;; grab the current word with hyphens or underscore
(setq myStr (thing-at-point 'symbol))

;; grab the current line
(setq myStr (thing-at-point 'line))

;; grab the start and end positions of a word
(setq myBoundaries (bounds-of-thing-at-point 'word))

For more about thing-at-point, see: Emacs Lisp: Using thing-at-point.

(info "(elisp) Buffer Contents")

Strings

Functions that take a string argument.

;; length
(length "abc") ; returns 3

;; Extract a substring
(substring myStr myStartPos myEndPos)

;; join strings
(concat "some" "thing")

;; check if a string matches a pattern
(string-match myRegex myStr)

;; get captured match
;; second argument is optional, but required if the last match is done by “string-match”
(match-string 1 myStr)

;; change a given string using regex. Returns changed string.
(replace-regexp-in-string myRegex myReplacement myStr)

;; split a string into parts, returns a list
(split-string "ry_007_cardioid" "_")

(string-to-number "3") ; change datatype
(number-to-string 3) ; convert to string
(format "%d" 3) ; similar to number-to-string but with fine control

Emacs has only very few functions that takes a string as argument. Any non-trivial string processing is done with a buffer. Use with-temp-buffer, then insert your string, process it, then use buffer-string to get the whole buffer content.

(info "(elisp) Strings and Characters")

Preserving point, mark, buffer, narrow-to-region

When your command moves cursor to do some work, you usually want to preserve the cursor position before the command starts, so that when user calls your code, the cursor won't end up somewhere unexpected.

;; preserve {point, mark, current buffer}
(save-excursion
  ;; lisp code here involving moving cursor, mark, changing buffer.
)

;; preserve user's narrow-to-region
;; useful when you want to narrow-to-region in your code to work in just that region
(save-restriction
  (narrow-to-region pos1 pos2)
  ;; lisp code here
)

(info "(elisp) Positions")

Buffers

Functions that act on the buffer data type. Most buffer function assume the current buffer if no argument is given. Some requires a argument. The argument can usually be a buffer's name, or a buffer object.

;; return the name of current buffer
(buffer-name)

;; return the full path of the file
(buffer-file-name)

;; switch to a given buffer
(set-buffer myBuffer)

;; close a given buffer
(kill-buffer myBuffer)

;; use a temp buffer to manipulate string
(with-temp-buffer
  (insert myStr)
  ;; manipulate the string here
  (buffer-string) ; get result
)

(info "(elisp) Buffers")

Files

{Open, Append, Write} Files

;; open a file (returns a buffer)
(find-file myPath)

;; save current buffer (write to the associated file)
(save-buffer)

;; like “Save As”. Save current buffer, close it, and open the new saved
(write-file myPath)

;; append a text block to file
(append-to-file myStartPos myEndPos myPath)

;; close a buffer
(kill-buffer myBuffName)

(info "(elisp) Files")

{Rename, Copy, Delete} Files

(rename-file fileName newName)

(copy-file oldName newName)

(delete-file fileName)

(copy-directory dirPath newDirPath)

;; delete a whole dir. (new in emacs 23)
(delete-directory dirPath t)

File Name Manipulation

;; get dir path
(file-name-directory myFullPath)

;; get filename part
(file-name-nondirectory myFullPath)

;; get filename's suffix
(file-name-extension myFileName)

;; get filename sans suffix
(file-name-sans-extension myFileName)

;; get relative path
(file-relative-name myFilePath dirPath)

;; get full path
(expand-file-name myFilePath)

(info "(elisp) File Names")

Like what you read?
Buy Xah Emacs Tutorial
or share some
blog comments powered by Disqus