kill9/emacs/1_Introduction/4_Emacs_Lisp/4.1.md

2.1 KiB

A few words on emacs lisp

Emacs lisp is what makes Emacs as extensible as it is. Everything you do in Emacs, is, in fact, written in emacs-lisp, even moving the cursor.

As it name says, Emacs lisp is part of the family of Lisp programming languages. Meaning it has their "weird" syntax:

(setq y 3)
(defun square (x) (* x x))
(square y)

This is a simple lisp function. which first, defines a variable using setq, in this case, sets y to 3.

Then, it defines a square function, which takes x as parameter, then, in the function body, it multiplies x by x.

In the third line, we call the square function with the value of the variable y. which is the same as doing (square 3). Calling this function will return the value 9.

As Emacs is a Emacs Lisp interpeter, you can execute Emacs-lisp code whenever which any of this functions:

  • eval-buffer, this one evaluates the whole buffer, it's not really useful
  • eval-region, this one takes your region (selected with C-SPC, for example) and evaluates it. This can be used in any mode.
  • (eval-last-sexp), (Or C-x C-e), evaluates any emacs lisp expression. for example (square y) is a emacs lisp expression. which you can evaluate with C-x C-e, the return value will print the returned value in the minibuffer.

You do not neet to save the file to evaluate.

Hello world

If you want to use Emacs Lisp, open your scratch buffer, whith C-x b and select *scratch* and begin typing your emacs lisp expressions. For example:

(princ "Hello world!")

This will print "Hello world" in the minibuffer. Which is what we wanted.

Now try:

(insert "Hello world")

This will insert "Hello world" in the buffer you're in.

Variables

Emacs lisp has no types. Meaning you can use the same function to define variables.

Emacs Lisp, like Common Lisp, has a gorillion ways to define a variable:

(setq x 3)
(defvar y x)

You can also define variables with operations. Which have polish notation.

(defvar z (+ 3 4)) ;; z = 7

Exercises

4.1: Define z using (define) and operations, then insert the value in the buffer, using (insert)