Elisp: How to Write Commands

By Xah Lee. Date: . Last updated: .

Here's the basics of how to write a emacs command that user can call.

Command Template

This is the typical template for user-defined emacs commands.

(defun my-command ()
  "One sentence summary of what this command do.

More details here. Be sure to mention the return value if relevant.
Lines here should not be longer than 70 chars,
and don't indent them."
  (let (var1 var2 …)
    (setq var1 …)
    (setq var2 …)
    ;; do something …

In your doc string, if you want clickable URL, or clickable reference to other commands, etc., See: Elisp: Doc String Markup.

Basic Functions

Get Buffer String

Elisp: Get Buffer String

Mark, Region, Active Region

Elisp: Region, Active Region

Cut, Copy, Paste, kill-ring

Elisp: Cut Copy Paste to/from kill-ring

Working with Lines

Elisp: Functions on Line.

Get User Input

Elisp: Get User Input

Processing String in Temp Buffer

In python, ruby, golang, etc, there are maybe 20 functions that act on string. In elisp, there are only about 5, because elisp has a buffer data type that's more powerful and flexible, and you have over 3 thousand functions that acts on text in a buffer. When you have a string, and you need to do more than just getting substring or number of chars, put it in a temp buffer. Here's a example:

;; process string in a temp buffer

(setq str "some big string here you need to process")
(setq strNew
        (insert str)

        ;; code to manipulate your string as buffer text
        (buffer-string) ; get result

Find Replace Text in Buffer

Elisp: Find Replace String in Buffer

Apply to dired's Marked Files

To apply a function to marked files in dired, use dired-get-marked-files, like this:

;; idiom for processing a list of files in dired's marked files

;; suppose myProcessFile is your function that takes a file path
;; and do some processing on the file

(defun dired-myProcessFile ()
  "apply myProcessFile function to marked files in dired."
  (require 'dired)
  (mapc 'myProcessFile (dired-get-marked-files))

Writing Emacs Command

  1. Elisp: How to Write Commands
  2. Elisp: Region, Active Region
  3. Elisp: Get Buffer String
  4. Elisp: Functions on Line
  5. Elisp: Cut Copy Paste to/from kill-ring
  6. Elisp: Get User Input
  7. Elisp: Get universal-argument
  8. Elisp: Find Replace String in Buffer
  9. Elisp: Using thing-at-point
Patreon me $5 patreon

Or Buy Xah Emacs Tutorial

Or buy a nice keyboard: Best Keyboard for Emacs

If you have a question, put $5 at patreon and message me.