Common Lisp Loops

I can’t think why you wouldn’t use the Common Lisp loop macro in Emacs. Don’t forget to (require ‘cl-lib)

Simple Loops

;; keywords: to, upto, below, downto, above, by
;; keywords: collect, append, nconc, count, sum, maximize, minimize

    do (princ 1))
=> 111111... infinite loop

(cl-loop repeat 5
     do (princ 1)
     (princ 2))
=> 1212121212

(cl-loop for i from 1 below 10
     maximize i)
=> 9

(cl-loop for x from 9 downto 1
     collect x)
=> (9 8 7 6 5 4 3 2 1)

(cl-loop for i from 10 above 1 by 2
     collect i)
=> (10 8 6 4 2)

Looping over Sets and Arrays

;; keywords: in, on, across, by
;; Remember in for lists
;; across for vectors

(cl-loop for l in '(1 2 3 4 5)
     do (princ l))
=> 12345

(cl-loop for l in '(1 2 3 4 5) by #'cddr
     collect l)
=> (1 3 5)

(cl-loop for l on '(1 2 3 4 5)
     collect l)
=> ((1 2 3 4 5) (2 3 4 5) (3 4 5) (4 5) (5))

(cl-loop for l on '(1 2 3 4 5) by #'cddr
     collect l)
=> ((1 2 3 4 5) (3 4 5) (5))

;; Remember that a string is an array in lisp, so...
;; Add up the digits in 90125
(cl-loop for d across "90125"
    sum (- d 48))
=> 17


(cl-loop for (a nil) in '((1 2) (2 3) (3 4))
     collect a)
=> (1 2 3)

(cl-loop for (a b) in '((1 2) (2 3) (3 4))
     collect (* a b))
=> (2 6 12)

(cl-loop for (a b) on '(1 2 3 4 5) while b
      collect (+ a b))
=> (3 5 7 9)

(cl-loop for (a b) on '(1 2 3 4 5) by #'cddr while b
     collect (+ a b))
=> (3 7)


(cl-loop for key being the hash-keys of myhashtable
        using (hash-value value)
        do (princ value))

Parallel fors

(cl-loop for i from 1 to 5
     for l in '(a b c d)
     collect (list i l))
=> ((1 a) (2 b) (3 c) (4 d))

(cl-loop for i from 1 to 5
     for j from 2 to 10 by 2
     collect (* i j))
=> (2 8 18 32 50)

Nested fors

(cl-loop for i from 1 to 5
     collect (cl-loop for j from 1 to 5
             collect (* i j)))
=> ((1 2 3 4 5) (2 4 6 8 10) (3 6 9 12 15) (4 8 12 16 20) (5 10 15 20 25))

(cl-loop for i from 1 to 5
     append (cl-loop for j from 1 to 5
             collect (* i j)))
=> (1 2 3 4 5 2 4 6 8 10 3 6 ...)

(cl-loop for i from 1 to 5
     collect (cl-loop for j from 1 to 5
             sum (* i j)))
=> (15 30 45 60 75)

(cl-loop for i from 1 to 5
     sum (cl-loop for j from 1 to 5
             sum (* i j)))
=> 225


;; if, when, unless

(cl-loop for i from 1 to 20
     unless (cl-evenp i) collect i)
=> (1 3 5 7 9 11 13 15 17 19)

(cl-loop for i from 1 to 20
     when (= (% i 3) 0) collect i into fizz
     when (= (% i 5) 0) collect i into buzz
     finally return (list fizz buzz))
=> ((3 6 9 12 15 18) (5 10 15 20))

(cl-loop for i from 1 to 20
     if (and (= (% i 3) 0) (= (% i 5) 0)) collect i into fizzbuzz
     else if (= (% i 3) 0) collect i into fizz
     else if (= (% i 5) 0) collect i into buzz
     finally return (list fizz buzz fizzbuzz))
=> ((3 6 9 12 18) (5 10 20) (15))

(cl-loop for i from 1 to 10
     if (cl-evenp i)
     collect i into evens
     and sum i into evensum
     collect i into odds
     and sum i into oddsum
     finally return (list evens evensum odds oddsum))
=> ((2 4 6 8 10) 30 (1 3 5 7 9) 25)

Find c from comp where diff is never a member of squares
(cl-loop for c in comp
     if  (cl-loop for p in pri
              for diff = (/ (- c p) 2)
              never (member diff squares))
     collect c)

Then Iteration

(cl-loop for i from 1 to 5
     for square = (* i i)
     collect square)

;; Though you'd be better with
(cl-loop for i from 1 to 5
     collect (* i i))

;; However, this leads to Triangle Numbers
(cl-loop for n from 1 to 10
     for triangle = 1 then (+ triangle n)
     collect triangle)
=> (1 3 6 10 15 21 28 36 45 55)

(cl-loop for x = 0 then y
     for y = 1 then (+ x y)
     while (< y 30)
     collect y)
=> (1 2 4 8 16)

;; Fibonacci Sequence (note the and)
(cl-loop for x = 0 then y
     and y = 1 then (+ x y)
     while (< y 30)
     collect y)
=> (1 1 2 3 5 8 13 21)


;; while, until, always, never, and thereis

while and until are straightforward

(cl-loop for n from 1
for tri = 1 then (+ tri n)
until (> (divs tri) 500)
finally return tri)

never, thereis and always are shorthand for a combination of when-return

(defun isprime(n)
   ((< n 2) nil)
   ((= n 2) t)
   ((cl-evenp n) nil)
    (cl-loop for i from 3 to (sqrt n) by 2
         never (= (% n i) 0)))))

Code is Poetry

Brian Bilston has written a History of Modern Art in Poetry.  I  wondered what it would be like to do something similar in various programming languages.

Here’s the original poem:

Roses are red
Violets are blue
Sugar is sweet
And so are you


Here’s the poem constructed using a zip statement in Haskell

Prelude> zip ["roses","violets","sugar","you"]["red","blue","sweet","sweet"]

The list produced holds the relationship that sugar is sweet and you are sweet. The comparison between “you” and sugar is not made clear.


Here’s the poem stored as an alist in Lisp

(setq poem '(("roses" . "red") ("violets" . "blue") ("sugar" . "sweet")("you" . "sweet")))
(mapcar (lambda (x) (concat (car x) " are " (cdr x))) poem)

I’ve gone one stage further here, using a mapcar function to produce something that looks a little bit more like the original poem, however we’re still missing the connection between “you” and sugar.

("roses are red" "violets are blue" "sugar are sweet" "you are sweet")


Of course, sugar are sweet isn’t right.   Let’s try some Python.

poem = {"roses":"red","violets":"blue","sugar":"sweet","you":"sweet"}

for key, value in poem.items():
    if key == "sugar":
        print(key, "is" ,value)
        print(key, "are", value)

This output is at least grammatically correct.

roses are red
violets are blue
sugar is sweet
you are sweet


Java can do something similar using a HashMap

Map<String, String> poem = new HashMap<String, String>();

        poem.put("roses", "red");
        poem.put("violets", "blue");
        poem.put("sugar", "sweet");
        poem.put("you", "sweet");

        for (Map.Entry<String, String> entry : poem.entrySet()) {
                System.out.println(entry.getKey() + " is " + entry.getValue());
            } else{
                System.out.println(entry.getKey() + " are " + entry.getValue());

But we’re still no closer to conveying the connection between “you” being sweet, just like sugar is sweet.

Fortunately, Java allows us to use some object oriented design to better convey the meaning of the poem.

In the example below I’ve used an interface to allow sweetness to be applied to both sugar and to the special one to whom the poem refers.  The comparison is at last made clear.  As there can only be one true love, it seemed reasonable to make a singleton class for TheOne, inherited from a regular person.

Run the code and the poem is printed out properly, just like the original.  More importantly though, the concepts to which the poem refers are properly encapsulated and related.

The original poem was only 4 lines long.  My implementation takes 80 lines, but I think you’ll agree I’ve done a rather better job, providing clarity and removing any ambiguity.

public class Love {

     * @param args the command line arguments
    public static void main(String[] args) {
        Flower [] rose = new Flower[12]; // 12 roses in a bunch
        Flower [] violet = new Flower[30]; // more violets in bunch
        Sugar sugar = new Sugar();
        TheOne myLove = TheOne.getInstance();  // Singleton class
        // There can only be one true love
        rose[0] = new Flower();
        rose[0].setColour("red");  // colour is static so only need
                                    // to instantiate one here
        violet[0] = new Flower();
        System.out.println("Roses are " + rose[0].getColour());
        System.out.println("Violets are " + violet[0].getColour());

class Flower {
    private static String colour;
    public void setColour(String colour){
        this.colour = colour;
    public String getColour (){
        return colour;

class Sugar implements Sweetness {

    public String sweet() {
        return "Sugar is sweet";

class Person {
    public String sweet()
        return "Not sweet";

class TheOne extends Person implements Sweetness{
    private static TheOne instance = null;
    private TheOne()
    public static TheOne getInstance()
        if(instance == null)
            instance = new TheOne();
        return instance;

    public String sweet() {
         return "And so are you";

interface Sweetness {
    String sweet();

MyKitaab Podcast

The mission of the MyKitaab podcast series is to help answer the question “I have written a book, how do I get it published in India?”
Here, host Amar Vyas talks to me about writing, blogging and Open Source software, especially  Emacs!
You can access the podcast as follows:

Or listen to it here:

Emacs Characters 2

I wrote about inserting characters in Emacs in this post.

There I pointed out that it’s easy to insert characters such as è and ä by using the C-x 8 key combination. So, for example:

C-x 8 ' e prints é
C-x 8 `e prints è
C-x 8 ^ e prints ê
C-x 8 " u prints ü
C-x 8 / / prints ÷
C-x 8 C prints © copyright

What I didn’t realise at the time is there was an easier combination formed by simply entering the Unicode name of a character.

For example, to insert é, use the combination


Capital letters begin, unsurprisingly, with LATIN CAPITAL.

At first glance the above doesn’t look easier, even allowing for the fact that Emacs allows you to use a few shortcuts. With tab completion, I got the key sequence down to…

C-x 8 [return] lat [tab] sm [tab] e [space] a [tab]

… but that’s still not as compact as the original examples.

So why is that an easier combination?

Well, it’s easier in the sense that it’s easier to remember, and therefore it can be quicker to use for obscure characters than having to look up a character code.

Just as an experiment, I tried to put in a British pound sign without using the appropriate key on my UK keyboard.

I used C-x 8 [return] and typed po [tab], and there was pound sign (along with


If you’re interested what POUTING CAT FACE looks like (I certainly was) here’s a link:

Emacs Writing Tips: What to do When You’ve Finished a Novel

Just because the novel is finished, it doesn’t mean the file it was written on is done with. Experience suggests the file is something that I will return to over the coming months. Here are a few reasons:

  • Blurbs, summaries and press releases will need to be written
  • This being the age of Social Media,  Blog and Guest Blog entries will need to be written
  • I may wish to refer to events when writing a sequel
  • There may be another novel or short story to be written in the same setting
  • There will be unused ideas that can be used elsewhere.

The following process is intended to tidy up the file, removing the chaff and sorting the useful stuff into some sort of order. It’s well worth the time.
First, use org-sparse-tree to check for unfinished TODOs.  In my setup, this brings up TODOs and IDEAs

C-c / t

Here’s a short example from Dream Paris, my latest novel

** TODO P.232 More explanation of (2)You and You(2)?
** TODO Get Mr Monagan mentioned earlier
** TODO Do something about the Tu Vous numbers
** TODO Why is Anna the Hero of Dream Paris?
** TODO Where did Kaolin's intelligence come from?
** TODO Kaolin speaks a leetle like this.  Good 'ealth!

Go through and mark those TODOs which have been done as DONE
Find the PAUSED ideas in a similar way and change them to TODOs (they might be useful in other stories)


Now begin the process of sorting. Add three headings at the beginning of the file.

* A General Ideas
* B Blog
* C Sequel

Mark up the remaining TODOs using Shift up and down to give them a priority of A (for General Ideas), B (for Blog) and C (for Sequel) (I don’t use org-mode priorities, so this is just a quick way of marking up)

Now that the notes are categorised, copy them to the appropriate heading, ready for refiling. There are a number of ways this can be done. Here are a couple to get you going.

Use org-sparse-tree to identify the individual entries and then org-refile to the appropriate heading:

C-c / / #A     Find all the #A General ideas
C-c C-w            Refile to appropriate heading

Make a copy of the buffer and then use keep-lines to flush all lines that do not contain the regexp #A. Copy the remaining lines to the appropriate heading.

Repeat for #B and #C

At the end of all that, I’m left with a list of notes ready to be transferred to other files. Here’s an edited sample.

 * A General Ideas
 ** TODO [#A] Vive L'indifference!
 ** TODO [#A] Wallace Fountains
 ** IDEA [#A] Diagonal Anneka
 ** IDEA [#A] Geppetto (8 or 35)
 * B Blog
 ** TODO [#B] This is an adult story.  In real life, kids shouldn't be expected to save their parents.
 ** TODO [#B] Anna and Francis Orangina
 ** IDEA [#B] The wine scene
 * C Sequel
 ** TODO [#C] Soldiers with guns saying (12)Mine
 ** TODO [#C] Dream Paris Courtesans
 ** TODO [#C] Walking around Dream Paris
 ** TODO [#C] German Brass Band Instruments

Now it’s time to start the next novel…

Related Posts


C-x r

I wrote in this post on Evil Emacs about some of the things that vi does well. One feature I particularly like is the ability to store a mark in a register q using the key combination mq. You can then jump back to that point using `q

Compare that with the equivalent Emacs key combinations: C-x r <space> q to store a point in a register, and C-x r j q to jump back.

There are lots of useful, and by me at least, underused Emacs features that begin with C-x r

A handy trick to see them is all to enter

C-x r C-h
which opens a buffer listing all the commands beginning C-x r

Here are the four we’re interested in for the moment

C-x r space q         Store point in register q
C-x r j q               Jump to point stored in register q
C-x r s q               Store region in register q
C-x r i q              Insert text from register q

Could that key sequence be shortened? Well, here’s one way…

C-x r calls the ctl-x-r-map prefix keymap

Adding the following to your .emacs will save you a keystroke:

(global-set-key (kbd "C-`") ctl-x-r-map)

Now C-` is the same hitting C-x r

Which means the key combinations for storing points and regions are as follows

C-` space q        Store point in register q
C-` j q              Jump to point stored in register q
C-` s q              Store region in register q
C-` i q             Insert text from register q

Is it worth it? Well, it makes it easier for me to remember the key combinations, it also makes me more likely to use them. An added bonus is it also makes it easier to remember the rectangle commands.  See this post on rectangles for more details.

Incidentally, this saving of one keystroke and how it makes all the difference is what my wife calls this a Pierre Victoire event. You can see what she means here on my blog

Evil Emacs 1

There’s no denying that vi has a great set of keybindings. For pure editing rather than writing I’ll often use Evil mode – an extensible vi layer for Emacs (See below for installation). Vi key combinations are often easier on the fingers: hitting dd to kill a line is easier than C-S-Backspace any day. I also find navigating with hjkl preferable to C-p, C-f and so on.

That got me thinking. What is it about the vi commands that make them so good for editing? What’s more, as I edit in a different way using vi, can any of those methods make my Emacs use more efficient?

I took a break a moment ago to reflect on what I’d just written and came to the conclusion that I really am as boring as my wife keeps telling me. But what the heck. I find it fun, and the fact that you’re still reading shows that you think this is interesting too.

So here goes.

One vi feature I use a lot is f . to find the end of a sentence. Now I know that you can jump to the end of sentence using M-e, but this only works if there are two spaces after the full stop, and fewer and texts follow this convention nowadays.
You can replicate this in Emacs using C-s . The thing is, I never thought of doing that until I stopped to think about my vi habits. That led me to using M-z . to delete to the end of the sentence (this is similar to df . in vi).

I’ve written elsewhere about using C-s more often. The fastest way I know to jump to a word I can see on the page is to C-s (word).

Bearing that in mind, there’s a nice trick in vi where you c/pattern to clear up to a pattern. So if I wanted to clear all the words from here to this 34 I’d hit c/34
Thinking about that has led me to doing the following in Emacs

C-Space C-s 34 Enter C-w

In other words

C-Space to set the mark; C-s 34 to jump to 34 and then C-w to clear. More keystrokes, true, but you’re not constantly shifting between modes.

There are advantages to modes, of course. I love the fact that jumps back to the last edit in vi. You can partially replicate this in Emacs using C-Space C-Space to push a point to the mark ring, and then you can jump back using C-u C-Space. It’s not the same, but it will do.


(setq set-mark-command-repeat-pop 't)

in your .emacs file allows you to just keep hitting C-Space after that initial C-u C-Space. The mark ring is set to 16 by default. With this setting you can go round and round your last 16 marks as many times as you care to hit C-Space

Installing Evil

You can install Evil using the package manager. Placing the following in your .emacs file enables it by default, and replicates visual-line-mode type navigation.

(require 'evil)
(evil-mode 1)
(define-key evil-normal-state-map (kbd "<remap> <evil-next-line>") 'evil-next-visual-line)
(define-key evil-normal-state-map (kbd "<remap> <evil-previous-line>") 'evil-previous-visual-line)
(setq-default evil-cross-lines t)

Simple Version Control

About once every six months or so I spend the morning happily overwriting an existing piece of work. Either that or I unwittingly delete whole sections, only to discover my mistake later that day or worse, later that week or even month.

That’s were Emacs simple version control comes in handy. Add the following to your .emacs file: (courtesy of the Emacs Wiki)

(setq version-control t ;; Use version numbers for backups
       kept-new-versions 16 ;; Number of newest versions to keep
       kept-old-versions 2 ;; Number of oldest versions to keep
       delete-old-versions t ;; Ask to delete excess backup versions?
       backup-by-copying-when-linked t) ;; Copy linked files, don't rename.
 (defun force-backup-of-buffer ()
   (let ((buffer-backed-up nil))
 (add-hook 'before-save-hook  'force-backup-of-buffer)

You can probably deduce from the comments what the above does, but as an illustration, here’s a sample of what the file I’m currently writing looks like under version control:

-rw-rw-r--  1 XXXX XXXX 29816 Aug 11  2014
.rw-rw-r--  1 XXXX XXXX 29816 Aug 11  2014
-rw-rw-r--  1 XXXX XXXX 28844 Aug 11  2014
-rw-rw-r--  1 XXXX XXXX 29322 Aug 11  2014

The last 16 versions of the file are kept, the versions indicated by ~ ver ~
Having all of those versions can sometimes make it difficult to find files under dired. Fortunately, dired-x has a mode that omits uninteresting files. Add the following to .emacs

(require 'dired-x)
(setq dired-omit-mode t)

Now just hit C-x M-o (or M-o on older versions of Emacs) to omit those files.
16 past versions combined with my regular backup routine have proven enough for me to find the accidentally deleted text.  For a more in depth discussion  see


When writing a worksheet for students, I always include the answers, as follows:

Figure 1 shows the contents of a memory location
#+CAPTION: Figure 1
What is the denary equivalent of the contents of
this memory location if it represents an unsigned
binary integer? (1 mark)
ANS: 167
What is the denary equivalent of the contents of
this memory location if it represents an unsigned
binary fixed point number, with 4 bits before and
4 bits after the binary point? (2 marks)
ANS: 10.4375
What is the denary equivalent of the contents of
this memory location if it represents a two's
complement binary integer? (2 marks)
ANS: -89
What is the hexadecimalequivalent of the binary
pattern shown in Figure 1? (1 mark)

When I’ve finished I save a copy of the sheet and then remove the answers, leaving me with a worksheet and the answer sheet. Emacs makes it easy to remove the answers using

M-x flush-lines  ^ANS:

As it says in the documentation, flush-lines deletes lines containing matches for REGEXP.

Use flush-lines to delete blank lines as follows:

M-x flush-lines ^$

flush-lines is part of replace.el. There are some nice functions in replace.el As it says in the introductory comments:

This package supplies the string and regular-expression replace functions documented in the Emacs user’s manual.

M-x keep-lines is the inverse of flush-lines, handy if you want a sheet with the answers only

M-x how-many returns the number of occurrences of REGEXP following the point. Handy for counting how many ANS: there are.

M-x occur opens a buffer showing all lines in the current buffer containing a match for REGEXP.  See this post on stylesheets for more on this.

Lastly, map-query-replace-regexp will replace a matches for a regexp in rotation. As a simple example, suppose you want assign a group to a collection of students:

gp: Adam
gp: Bella
gp: Carol
gp: Danuta
gp: Ed
gp: Fran

Select the names and

red: blue: green:


red: Adam
blue: Bella
green: Carol
red: Danuta
blue: Ed
green: Fran

Related Posts


I never knew of the existence of stylesheets until the copyedit came back for my first novel. They struck me as such a good idea that ever since I’ve tried (and failed) to keep one up to date as I’m writing a novel.

The reason why they fail is that I change my mind as to what style to use as I’m writing. For example, I couldn’t decide whether the antagonists in DREAM PARIS were pierrots or Pierrots. In COSMOPOLITAN PREDATORS!, I couldn’t decide whether a character was named young man or Young Man.

I came about the solution by using the occur function.

M-x occur pierrot

occur lists lines containing a regexp in a separate buffer. Since Emacs regexps are case insensitive by default, the above finds both pierrot and Pierrot. It opens a buffer rather like the one in the self referential example below:

7 matches in 5 lines for "pierrot" in buffer:
     16:The reason why they fail is that I change my mind
     as to what style to use as I'm writing.  For
     example, I couldn't decide whether the antagonists
     in my most recently completed novel, DREAM PARIS
     were pierrots or Pierrots.  In COSMOPOLITAN
     PREDATORS!, I couldn't decide whether a character
     was named young man or Young Man.
     21:M-x occur pierrot
     24:Emacs regexps are case insensitive by
     default, so the above finds pierrot and Pierrot. It
     opens a buffer rather like the example below:
     31:M-s h l pierrot
     34:highlights lines with pierrot in.

Clicking or hitting enter on a line in the Occur buffer jumps you to the original location in the text.

A big advantage of occur is that you can look at the words in situ before deciding on the final style and running a query-replace-regexp to replace them all.

Another useful mode in when looking at styles is hi-lock mode.

M-s h l pierrot

The above highlights lines containing the regexp pierrot.

A really useful feature of hi-lock mode is that it highlights on the fly, highlighting lines as you type in the words. I use this feature to act as a reminder of whether I’m typing in the right (or wrong) style.

As a bonus, hi-lock mode allows you to choose from a pallete of colours. Use M-n and M-p to scroll through the choices, or enter your own choice – very useful when tracking more than one style.