Elisp: Simple Emacs Lisp Examples

By Xah Lee. Date: . Last updated: .

This page shows very simple and useful emacs lisp commands that are shorter than 10 lines. They show you the basic programing in elisp.

Insert Text

This code shows how to insert a string, and also position cursor after the insertion.

(defun insert-p-tag ()
  "Insert <p></p> at cursor point."
  (interactive)
  (insert "<p></p>")
  (backward-char 4))

You can use this code to insert your {signature, template, headers, footers, …}.

Put cursor at the last parenthesis, then Alt+x eval-last-sexpCtrl+x Ctrl+e】.

Then, you can call the command you just defined by name. For example, Alt+x insert-p-tag.

[see How to Evaluate Emacs Lisp Code]

To see a function's documentation, Alt+x describe-functionCtrl+h f】.

[see Elisp: Documentation Lookup]

Insert Around Region

This code shows how to place a string at the beginning and end of a region.

(defun wrap-markup-region (start end)
  "Insert a markup <b></b> around a region."
  (interactive "r")
  (save-excursion
    (goto-char end) (insert "</b>")
    (goto-char start) (insert "<b>")))

You can use this code to add HTML begin/end tag on a selected text, or add brackets around a selection.

Select Current Word, Select Current Line

This code shows you how to set a mark (select text) programmatically.

;; turn on highlight selection
(transient-mark-mode 1)

(defun select-current-word ()
  "Select the word under cursor.
“word” here is considered any alphanumeric sequence with “_” or “-”."
  (interactive)
  (let (pt)
    (skip-chars-backward "-_A-Za-z0-9")
    (setq pt (point))
    (skip-chars-forward "-_A-Za-z0-9")
    (set-mark pt)))
(transient-mark-mode 1)

(defun select-current-line ()
  "Select the current line"
  (interactive)
  (end-of-line) ; move to end of line
  (set-mark (line-beginning-position)))

See also: Elisp: Region, Active Region.

For full versions, see: Emacs: Select Line, between Quotes, Extend Selection

Find Replace String in Region

Here's how to do text replacements on a region. Very useful.

(defun replace-greek-region (start end)
  "Replace “alpha” to “α” and other greek letters in current region."
  (interactive "r")
  (save-restriction
    (narrow-to-region start end)
    (goto-char (point-min))
    (while (search-forward " alpha" nil t) (replace-match " α" nil t))
    (goto-char (point-min))
    (while (search-forward " beta" nil t) (replace-match " β" nil t))
    (goto-char (point-min))
    (while (search-forward " gamma" nil t) (replace-match " γ" nil t))
    ))

You can modify the code to do other replacements. For example, HTML XML Entities. [see HTML/XML Entity List]

see also:

Delete Enclosed Text

This code illustrates how to delete a text enclosed by any pairs of delimiters.

For example, if you are editing HTML code, suppose you have text <p>something something long …</p> and your cursor is somewhere in between the tags. You want to quickly delete all texts inside the p tags. The following function will do. It will also, delete any text between quotes or parenthesis.

(defun delete-enclosed-text ()
  "Delete texts between any pair of delimiters."
  (interactive)
  (save-excursion
    (let (p1 p2)
      (skip-chars-backward "^([<>“") (setq p1 (point))
      (skip-chars-forward "^)]<>”") (setq p2 (point))
      (delete-region p1 p2))))

For many related code, see: Emacs: Select Line, between Quotes, Extend Selection

Delete Linebreaks

This example shows how to temporarily change a pre-defined variable's value, then call a function whose behavior depends on the var.

(defun remove-line-breaks ()
  "Remove line endings in current paragraph."
  (interactive)
  (let ((fill-column (point-max)))
    (fill-paragraph nil)))

For detail, see: Emacs: Hard Wrap Lines.

Inserting a Random Number

(random t) ; seed it randomly

(defun insert-random-number ()
  "Insert a random number between 0 to 999999."
  (interactive)
  (insert (number-to-string (random 999999))) )

For more, see: Emacs: Insert Random Number/Hex/String

Reference Lookup

This example shows the use of thing-at-point and browse-url.

It will look up the word under the cursor in a online dictionary.

(defun word-definition-lookup ()
"Look up the word under cursor in a browser."
 (interactive)
 (browse-url
   (concat "http://www.answers.com/main/ntquery?s=" (thing-at-point 'symbol))))

For detail, see: Emacs: Lookup Google, Dictionary, Documentation.

Change Newline Character

This example shows how to define a function that takes a file path and process the file.

(defun to-unix-eol (fPath)
  "Change file's line ending to unix convention."
  (let ((myBuffer (find-file fPath)))
    (set-buffer-file-coding-system 'unix) ; or 'mac or 'dos
    (save-buffer)
    (kill-buffer myBuffer)))

For example, if the file ~/jane/readme.txt is a Windows file, you can change its line ending by evaluating the following:

(to-unix-eol "~/jane/readme.txt")

The following example shows how to apply a file processing function to a list of files.

(mapc 'to-unix-eol
 (list
"~/jane/myfile1"
"~/jane/myfile2"
"~/jane/myfile3"
;   )
)

The following wraps it as a command, so can be called in dired. It acts on all marked files.

(defun dired-2unix-marked-files ()
  "Change to unix line ending for marked (or next arg) files."
  (interactive)
  (mapc 'to-unix-eol (dired-get-marked-files))
)

Delete Current File

This example shows command that lets you delete the current file. Note here that elisp is used to: {manipulate buffer, manipulate file, prompt user}.

(defun delete-current-file ()
  "Delete the file associated with the current buffer.
Delete the current buffer too.
If no file is associated, just close buffer without prompt for save."
  (interactive)
  (let ((currentFile (buffer-file-name)))
    (when (yes-or-no-p (concat "Delete file?: " currentFile))
      (kill-buffer (current-buffer))
      (when currentFile
        (delete-file currentFile)))))

Detail at Emacs: Delete Current File.

Highlighting Lines

This example shows you how to make lines containing the words “ERROR:” or “NOTE:” highlighted, whenever a file ending in “log” is opened.

(defun highlite-it ()
  "Highlight certain lines…"
  (interactive)
  (if (equal "log" (file-name-extension (buffer-file-name)))
      (progn
        (highlight-lines-matching-regexp "ERROR:" 'hi-red-b)
        (highlight-lines-matching-regexp "NOTE:" 'hi-blue-b))))

(add-hook 'find-file-hook 'highlite-it)

The add-hook line will make emacs call “highlite-it” whenever a file is opened. It works by adding the function “highlite-it” to the list in the variable find-file-hook.

find-file is the function that open files. find-file-hook is a variable containing list of functions that will run when find-file is run.

Insert Vertical Column of Numbers

Emacs 24 has a new command rectangle-number-linesCtrl+x r N】. It will insert a vertical column of numbers into a block of text, like this:

1. x
2. x
3. x
4. x

For emacs 23 users, you can define your own, like this:

(defun insert-column-counter (n)
  "Insert a sequence of numbers vertically.
For example, if your text is:

a b
c d
e f

and your cursor is after “a”, then calling this function with argument
3 will change it to become:

a1 b
c2 d
e3 f

If there are not enough existing lines after the cursor
when this function is called, it aborts at the last line.

This command is conveniently used together with `kill-rectangle' and `string-rectangle'."
  (interactive "nEnter the max integer: ")
  (let ((i 1) colpos )
    (setq colpos (- (point) (line-beginning-position)))
    (while (<= i n)
      (insert (number-to-string i))
      (forward-line) (beginning-of-line) (forward-char colpos)
      (setq i (1+ i))
      )
))

Fold, Reduce

The following example shows a basic way to define the Fold (aka “reduce”) function that's commonly found in functional programing languages. For a example documentation of Fold in Mathematica, see: Mathematica: Fold

(defun fold (f x list)
  "Recursively applies (F i j) to LIST starting with X.
For example, (fold F X '(1 2 3)) computes (F (F (F X 1) 2) 3)."
 (let ((li list) (x2 x))
   (while li
     (setq x2 (funcall f x2 (pop li)))
   )
   x2
  )
)

Here's a example of usage:

(defun sum2 (x y) (+ x y)) ; add 2 numbers

(fold 'sum2 1 '(2 3)) ; returns 6

Thanks to Hauke Rehfeld for a improvment of “fold”.

Thanks to Marcin Milewski for correction on “wrap-markup-region”.

Emacs Lisp Basics Topic

  1. Emacs Lisp Basics
  2. Overview of Text-Processing in Emacs Lisp
  3. Emacs Lisp Examples
  4. How to Evaluate Emacs Lisp Code
  5. Elisp: Documentation Lookup
  6. Elisp: Search Documentation
  7. How to Edit Lisp Code with Emacs
Like my tutorial? Put $5 at patreon

Or Buy Xah Emacs Tutorial

Or buy a nice keyboard: Best Keyboard for Emacs