Category Archives: Emacs Lisp

Only One .emacs

I keep my Emacs init files on Dropbox – that way I only have to maintain one set of files no matter how many machines I run Emacs on. My local .emacs file simply loads the init files on Dropbox.

One minor problem is that Dropbox can have a different path according to the operating system.

This is easily resolved using the system-type variable. For my set up, I’m only interested in whether I’m running on a ‘gnu/linux or a ‘windows-nt system.

The following code sets the path of my Dropbox folder and then uses the format function to append the appropriate init files to that location. The individual files are then loaded. I’ve split my .emacs file across several files for tidiness and convenience. Even so, it still manages to degenerate into a mess when I’m not watching it.

1: (if (eq system-type 'windows-nt)
2:     (setq dot-emacs-files "c:/Users/username/Dropbox/emacs")
3:   (setq dot-emacs-files  "~/Dropbox/emacs")
4: )
5: 
6: (load (format "%s/%s" dot-emacs-files "packages-dot-emacs.el"))
7: (load (format "%s/%s" dot-emacs-files "org-dot-emacs.el"))
8: (load (format "%s/%s" dot-emacs-files "common-dot-emacs.el"))
9: (load (format "%s/%s" dot-emacs-files "elisp.el"))

Manipulating Strings: Yodaizer

Let’s make a function that talks like Yoda. It will take a sentence like “This is instructive” and output “Instructive, this is.”

To do this we’ll need to teach Emacs some adjectives:

1: (setq adjectives '("happy" "sad" "fun" "clever" "instructive"))

We’ll split the sentence into a list of words, and we’ll prepare an empty list for the result of the function:

1: let (  (result '()) 
2:         (words (split-string s)) 
3:      )

We’ll use a dolist macro to traverse the words, checking for adjectives, and we’ll use the old lisp trick of concatenating the word we’ve found at the front or the back of the result list, as appropriate.

1: (dolist (element words result)
2: (if (member element adjectives) (setq result (concat (capitalize element) ", " result)) (setq result (concat result " " element))  )
3: )

Lastly, we won’t forget to captalize the first word of the sentence and add a comma…

1: (concat (capitalize element) ", " result)

Put it together and we get the finished function:

 1: (defun yodaizer (s)
 2: "Moves adjective to the front of the sentence."
 3: (interactive "sInput a phrase:")
 4: (setq adjectives '("happy" "sad" "fun" "clever" "instructive")) 
 5: 
 6: (let (  (result '()) 
 7:         (words (split-string s)) 
 8:      )
 9: (dolist (element words result)
10: (if (member element adjectives) (setq result (concat (capitalize element) ", " result)) (setq result (concat result " " element))  )
11: )
12: (message result)))

that was instructive

Instructive, that was

Next: Date and Time

Find and Replace in a Region: Strip Smart Quotes in a Region

These are smart quotes: “ ” ‘ ’

The easiest way to get Emacs to automatically insert smart-quotes is to use smart-quotes mode.

I prefer not to use smart-quotes mode, however. I find it easier when editing to stick to plain quotes (” and ‘) and then to let org-mode export convert to smart quotes.

What makes things awkward is finding text with smart-quotes already included. I wrote the following function to strip those smart-quotes out. It narrows to a region, uses save-restriction to remember how things were before the narrowing and then uses two regex searches to find first double quotes and then single quotes, replacing both with plain quotes.

 1: (defun strip-smart-quotes (rStart rEnd)
 2:   "Replace smart quotes with plain quotes in text"
 3:   (interactive "r")
 4:   (save-restriction
 5:   (narrow-to-region rStart rEnd)
 6:   (goto-char (point-min))
 7:   (while (re-search-forward "[“”]" nil t) (replace-match "\"" nil t))
 8:   (goto-char (point-min))
 9:   (while (re-search-forward "[‘’]" nil t) (replace-match "'" nil t))
10: ))
Before: “You put your smart-quotes in, you take your smart-quotes out… ”
After: "You put your smart-quotes in, you take your smart-quotes out… "

Date and Time

1 Reading Date and Time

This is how elisp stores a time:

(current-time) => (21209 38073 267139)

The first two numbers are the high and low bits of an integer number giving seconds since the epoch (0:00 January 1, 1970 UTC). The last number is microseconds and may be ommitted. There may be a fourth number representing picoseconds.

decode-time puts this into a more user friendly format:

(decode-time (current-time)) => (30 38 20 17 1 2014 5 nil 0)

The individual values are (SEC MINUTE HOUR DAY MONTH YEAR DOW DST ZONE) DOW is DOW of week DST is t if Daylight saving time is in effect ZONE is an integer indicating the number of seconds east of Greenwich.

format-time-string gives a more everyday format:

(format-time-string "%d/%m/%Y %H:%M:%S" (current-time)) => "17/01/2014 20:38:43"

Or, if you’re really in a hurry:

(current-time-string) => "Fri Jan 17 20:38:54 2014"

2 Setting a Date or Time

Set a time using date-to-time

(date-to-time "May 20 2011 19:30:00") => (19926 45864)

Note that the date strings format is dependent on your machine’s locale settings. For example, the following may be necessary. For more about locales, read this post.

(date-to-time "20 May 2011 19:30:00")

Enter a date using parse-time-string

(setq concert (parse-time-string "May 20 2011 19:30:00")) => (0 30 19 20 5 2011 nil nil nil)

Unlike date-to-time, parse-time-string allows you to omit the time value :

(setq birthday (parse-time-string "July 29 1953")) => (nil nil nil 29 7 1953 nil nil nil)

Here are some times:

(setq five-seconds (seconds-to-time 5))

(setq ninety-minutes (seconds-to-time (* 60 90)))

(setq one-day (seconds-to-time (* 60 60 24)))

The last can be more easily entered as:

(setq one-day (days-to-time 1))

Which leads to

(setq one-week (days-to-time 7))

and so on…

3 Converting Time Values

Use encode-time and decode-time to switch between formats

(encode-time 0 30 19 20 5 2011) => (19926 45864)

(decode-time '(19926  45864)) => (0 30 19 20 5 2011 5 t 3600)

4 Calculations on Dates and Times

Use time-add to add two times together.

Here’s the time a concert starts

(setq concert (date-to-time "May 20 2011 19:30:00"))

Suppose the concert lasts two hours (or 2 x 60 x 60 seconds). You can work out the time the concert ends as follows

(time-add concert (seconds-to-time (* 2 60 60)))

Let’s just check that worked

(format-time-string "%d/%m/%Y %H:%M:%S" (time-add concert (seconds-to-time (* 2 60 60)))) => "20/05/2011 21:30:00"

Suppose you know the start and end times of the concert. Use time-subtract to work out the duration:

(setq concert-start (date-to-time "May 20 2011 19:30:00"))

(setq concert-end (date-to-time "May 20 2011 22:25:00"))

(format-time-string "%H:%M:%S"(time-subtract concert-end concert-start)) => "02:55:00"

See Also

3 Interactive Functions that work on Regions

1 Start Point, End Point and Contents of a Region

The following function prints the contents of the selected region, together with its start and end points.

1: (defun region-contents (rStart rEnd)
2:   "Prints region contents of region selected, and the start and end positions of that region"
3:   (interactive "r")
4:   (setq rStr (buffer-substring rStart rEnd))
5:   (message "The string of the selected region is %s.  It starts at  %d and ends at %d"  rStr  rStart rEnd)
6: )

2 Iterate through the words in a region

You might want to iterate through the words in a selected region. The following function gives an example of this, it prints out the words in the region in reverse order.

1: (defun reverse-region-message (rStart rEnd)
2:   "Reverses order of words"
3:   (interactive "r")
4:   (setq myStr (buffer-substring rStart rEnd))
5:   (setq myWords (split-string myStr))
6:   (setq reversed (reverse myWords))
7:   (message (mapconcat 'identity reversed " "))
8: )

Note the use of the following functions:

  • split-string: splits the string into a list of words
  • reverse: reverses a list
  • mapconcat: Convert a list into a string

It’s interesting to compare the mapconcat function with the concat function. Note that concat does not accept lists, as you might expect at first glance. You can get round this using the apply function.

(concat "this" "that" "other") => "thisthatother"
(concat '("this" "that" "other")) => error
(apply 'concat '("this" "that"  "other")) => "thisthatother"
(mapconcat 'identity '("this" "that" "other") " ") => "thisthatother"

Here’s the function, rewritten to delete the selected region and to replace it with the words in reverse order.

1: (defun reverse-region (rStart rEnd)
2:   "Reverses order of words"
3:   (interactive "r")
4:   (setq myStr (buffer-substring rStart rEnd))
5:   (delete-region rStart rEnd)
6:   (setq myWords (split-string myStr))
7:   (setq reversed (reverse myWords))
8:   (insert (mapconcat 'identity reversed " "))
9:  )

3 Iterate through the letters in a region

You can spend a lot of time writing code to solve a problem only to find that Emacs Lisp already provides a function to do what you want.

For example, suppose you want to iterate through the letters in a region to convert SEPARATE to S-E-P-A-R-A-T-E. The easiest way is to use the mapconcat function, as seen in the previous section.

(mapconcat 'string "SEPARATE" "-")

Here’s the separator as a function that operates on the selected region.

1: (defun region-seperator (rStart rEnd)
2:   "Reverses order of words"
3:   (interactive "r")
4:   (setq rStr (buffer-substring rStart rEnd))
5:   (delete-region rStart rEnd)
6:   (insert (mapconcat 'string rStr "-"))
7:  )

3.1 string-to-list, mapcar and apply

The function string-to-list converts a string to characters.

(setq rStr (string-to-list "example")) => (101 120 97 109 112 108 101)

use char-to-string to convert a character code to a string

(char-to-string 101) => "e"

Note the use of apply, as discussed previously.

(apply 'string (reverse (string-to-list "example"))) => "elpmaxe"

Note that apply returns a value. If you want a list of characters, use mapcar

(mapcar 'char-to-string (string-to-list "example")) => ("e" "x" "a" "m" "p" "l" "e")

Remember, mapcar returns a list, apply returns a value. Many of the errors you make when beginning come down to confusing the two return types.

Finally, use a lambda function (discussed later) for complex functions in mapcar

(mapcar 'char-to-string (mapcar '(lambda (x) (+ x 1)) (string-to-list "foo")))

4 Enclose a Region

This tutorial has been written using emacs org mode. The code samples are marked up using the tags

#+BEGIN_SRC emacs-lisp -n  
and 
#+END_SRC

I wrote the following function to make the markup easier. Now I just select the region and run the function. The appropriate tags are placed at the start and end of the region.

1: (defun myMark-elisp-region (rStart rEnd)
2:   "Mark region as Elisp source code for org mode export."
3:   (interactive "r")
4:   (save-excursion
5:     (goto-char rEnd) (insert "\n#+END_SRC\n")
6:     (goto-char rStart) (insert "#+BEGIN_SRC emacs-lisp -n\n"))
7: )

Note the use of the save-excursion function to return the point to where it was before the function was run. Note also the way the above function is laid out. An interesting exercise is to reverse the order of lines 5 and 6. See if you can figure out why the function doesn’t work as you might expect.

5 Find and Replace in a Region: Strip Smart Quotes in a Region

These are smart quotes: “ ” ‘ ’

For editing purposes I sometimes need to replace these with the plain quotes ” and ‘. I only want this to replacement to occur on a specified region of text, not on the whole buffer.

Here’s a function to do this. It narrows to a region, uses save-restriction to remember how things were before the narrowing and then uses two regex searches to find first double quotes and then single quotes, replacing both with plain quotes.

 1: (defun strip-smart-quotes (rStart rEnd)
 2:   "Replace smart quotes with plain quotes in text"
 3:   (interactive "r")
 4:   (save-restriction
 5:   (narrow-to-region rStart rEnd)
 6:   (goto-char (point-min))
 7:   (while (re-search-forward "[“”]" nil t) (replace-match "\"" nil t))
 8:   (goto-char (point-min))
 9:   (while (re-search-forward "[‘’]" nil t) (replace-match "'" nil t))
10: ))

6 Choosing between Operating on a Region or the Whole Buffer

The previous example only stripped smart quotes from the selected region. This function uses the (when (uses-region-p) …) construction to determine whether or not a region is selected. If no region is selected, the whole buffer is operated upon.

 1: (defun region-or-buffer ()
 2:  "Strip smart quotes from region, or whole buffer if region not set"
 3:  (interactive)
 4:  (save-excursion
 5:    (save-restriction
 6:      (when (use-region-p) (narrow-to-region (region-beginning) (region-end)))
 7:      (goto-char (point-min))
 8:      (while (re-search-forward "[“”]" nil t) (replace-match "\"" nil t))
 9:      (goto-char (point-min))
10:      (while (re-search-forward "[‘’]" nil t) (replace-match "'" nil t))
11: )))

Next: Yodaizer – Manipulating Strings Example

2 Functions in Elisp

Here’s how to define a simple LISP function

1: (defun pi ()
2:   "A sample non-interactive function"
3:   3.1415
4: )

The above is a non-interactive function that simply returns 3.1415. Evaluate it (C-x C-e, remember?) and you will see the word pi appear in the echo area. Try M-x pi, though, and Emacs won’t find the function. If you want to be able to call a function using M-x, you have to make it interactive, as follows.

1: (defun print-pi()
2:     "Insert an approximation to pi"
3:     (interactive)
4:     (insert "3.1415")
5: )

So why would you want a non-interactive function? Perhaps because you want it to be called from another function, as follows:

1: (defun circumference-of-circle()
2:     (interactive)
3:     (message "The circumference of a circle diameter 3 is %f" (* pi 3))
4: )

Before evaluating the above function, make sure that you have evaluated the non-interactive function pi.

There are lots of different types of interactive functions. The next interactive function is more useful in that it prompts for the diameter to be input (the n at the start of “nInput diameter of circle:” is what tells Emacs to prompt for a number)

1: (defun circumference-of-circle(diameter)
2:     "Calculate the circumference of a circle given the diameter"
3:     (interactive "nInput diameter of circle:")
4:     (message "The circumference of a circle diameter %d is %f" diameter (* 3.1415 diameter))
5: )

Here’s the same function but this time set up to receive the parameter from the universal argument. That is to say, in the form C-u 4 M-x circumference of circle.

1: (defun circumference-of-circle(diameter)
2: (interactive "p")
3: (message "The circumference of a circle diameter %d is %f" diameter (* 3.1415 diameter))
4: )

Here’s an example of a function that reads strings and tests your knowledge of capital cities.

1: (defun capital-of-france(answer)
2:     "Simple quiz example."
3:     (interactive "sWhat's the Capital of France?")
4:     (if (string= answer "paris") (message "Correct!") (message "Wrong!"))
5: )

Argument codes for interactive functions can be found here http://www.gnu.org/software/emacs/manual/html_node/elisp/Interactive-Codes.html#Interactive-Codes

Next: Interactive Functions that work on Regions

1 Beginning Emacs Lisp

LISP is derived from the term LISt Processing.
A list in LISP looks like this:

(Knife Fork Spoon)

or like these two examples

(set-background-color “yellow”)    <- C-x C-e

(set-background-color “white”)    <- C-x C-e

If the first item in the list is a function you can evaluate the list by placing the cursor just after the bracket at the end of the list and pressing C-x C-e. Try it with the two lists above. Copy them into Emacs and then C-x C-e where indicated to turn the Emacs background yellow and then to set it white again.

If you try to evaluate the (Knife Fork Spoon) list you’ll get an error telling you that Knife is a void function.

Try evaluating the following lists in Emacs by typing C-x C-e after the closing bracket:

(linum-mode)
(message “This is the echo area”)
(* 2 3)
(+ 4 5)

The last three will output their results in the echo area, the area at the bottom of Emacs.

You can also evaluate a function by typing M-x (function name). So M-x visual-line-mode will turn word wrap on and off. Emacs supports TAB completion, so typing M-x visu and pressing TAB is enough to fill in the function name.

You set a variable as follows

(set ‘name ‘John) C-x C-e to set the variable

name C-x C-e to see the contents of the variable “name”

If you press C-x C-e after the following

(name)

you’ll get an error. Remember, name is a variable, (name) is a function, and you haven’t defined a function called name.

It’s a nuisance typing in ‘ all the time, so the following is often used

(setq animal ‘cat)

Evaluate the above and then evaluate animal …

C-u C-x C-e will insert any output directly in the text area, rather than in the echo area.

Here is a list of cheeses called cheese:

(setq cheese ‘(Stilton Wensleydale Cheddar Cheshire))

Evaluate the list.

The first item in a list is called the car, the remaining items are called the cdr (pronounced could-er) The Emacs Lisp tutorial will tell you why. Evaluate the following:

(car cheese)
(cdr cheese)

… and there you are

Next: Functions in Elisp