Modified deft-mode to multiple directories

After some hacking, I've been able to modify the wonderful Deft mode by Jason R. Blevins to support several directories. I had my notes divided in several directories, including my TO-DO entries, and I thought it would be nice to give Deft the possibility to support several directories, and at the same time, an exercise for my Emacs Lisp.

I tried to make the least modifications as possible to the original source, so that the change can be made with a patch, if the original author considers it (this is also why I didn't change the name of the mode either.) You can download it, and read instructions of installation and usage here:

deft-multidir on GitHub

As always, feedback is highly appreciated.

Using org-mode to create posts

Some time ago I decided to change my Common-Lisp based blog generator to an Emacs-based one. And it was to learn Emacs-Lisp (compared to Common-Lisp, that I had used before), but mostly to use the wonderful org-mode to write posts.

At first I thought that it would be nice to write the posts using Lisp alone. Using some HTML-generating library it would be easy to write posts like I write Lisp. However, posts have much more text than markup, and within lisp (unless you write some reader macro, that I may explore in the future), you have to add all those quotes, backquoting to eliminate special characters, etc. Posts look like this:

(fmb-new-post
 "Let Over Lambda--50 years of Lisp"
 :body (__ (h:p  "Hoy por casualidad he encontrado esta referencia, "
               (h:a '((href . "http://letoverlambda.com/index.cl/guest/chap2.html"))
                  "Let Over Lambda, Closures") " de Doug Hoyte. Es
                  curioso que sin haberlo leído antes, la solución que
                  he dado al problema de extraer la descripción de una
                  entrada del blog sin " (h:em "tags") " HTML ha sido
                  así usando un " (h:em "closure") "."))
 :categories '(español spanish programming lisp common-lisp blog)
 :hours 23
 :minutes 06
 :day 9
 :month 'october
 :year 2011)

I was happy because I could practice Lisp any time I wrote a post. However, this is not very comfortable, and when I had to include code snippets things got worse.

At the same time, I got impressed by the work of Reg Braithwaite with his blog Homoiconic. Thanks to the formatting capabilities of GitHub, he can write just Markdown files, and, with a directory structure that resembles years and months, he can write his blog. The name is representative, also, as it is the characteristic of programming languages that can treat code as data and vice versa (such as Lisp). However, I find much more interesting org-mode than Markdown, so I decided I wanted to do something similar.

Being written in Common Lisp, I had no library or implementation of the complete org-mode, so I decided, also to test other lisps, to use Emacs-Lisp and to use the characteristics of org-mode directly to produce the HTML that goes into posts, and even to support its tangling feature (more on that later). Also, it allowed me to have a directory in which all the posts live, and be able to browse them just using GitHub (where this blog now lives), as now GitHub also renders org-mode content (not quite correctly, but acceptably.)

The code that generates the HTML from the org-mode files is the following. It uses a function to obtain all the .org files, and with them, obtains the file properties, title, date, and categories, and generates the HTML with org-export-region-as-html:

(defun fmb-import-org-posts ()
  "Import all posts written in .org files.
Search all .org files, create a buffer for each of them,
extract all the initial properties (export properties), and then generate
the HTML equivalent of the body. Add it to the list of actual posts, that
will be ordered by date finally."
  (dolist (f (fmb-files-in-below-directory "content/posts"))
    (with-current-buffer (find-file-noselect f)
      (let* ((file-properties (org-infile-export-plist))
             (title (plist-get file-properties :title))
             (date (plist-get file-properties :date))
             (categories (plist-get file-properties :keywords))
             (body-as-html (org-export-region-as-html
                            (point-min)
                            (point-max)
                            t 'string)))
        (multiple-value-bind (secs mins hours day month year)
            (org-parse-time-string date)
          (fmb-new-post title
                        :day day
                        :month month
                        :year year
                        :hours hours
                        :minutes mins
                        :categories (mapcar #'(lambda (s) (intern s))
                                            (split-string categories nil t))
                        :body body-as-html))
      (kill-buffer)))))

Categories are extracted from the #+KEYWORDS option. For example, the few initial lines of this post:

#+TITLE:     Using org-mode to create posts
#+AUTHOR:    Diego Sevilla
#+EMAIL:     dsevilla@ditec.um.es
#+DATE:      2012-03-11 dom
#+DESCRIPTION:
#+KEYWORDS:  general org-mode emacs english
#+LANGUAGE:  en

Some time ago I decided to change my Common-Lisp based blog generator
to an Emacs-based one. And it was to learn Emacs-Lisp (compared

Finally, as the great site nakkaya.com, I can offer, through org-babel-tangle, the generation of the files shown in the entry. See, for example, this entry about the Ferret compiler. This open the world of Literate Programming also to this blog. All in all, a winning configuration.

Macros Emacs para facilitar introducir entradas

Continuando con el formato org-mode, he añadido también un esqueleto que rellena de forma automática los campos de una entrada del blog, para que sólo tenga que escribir el texto y las categorías. Es la siguiente función Emacs-Lisp:

(define-skeleton add-new-post
  "Add a new post with the current date and time. Ask for the post title."
  "Post title: "
  "(new-post" \n
  > "\"" str "\"" \n
  > ":body \"" _  "\"" \n
  > ":categories '('general)" \n
  > ":body-format 'string" \n
  > (format-time-string
     ":hours %H :minutes %M :day %e :month %m :year %Y)"
     (current-time)) \n )

La función new-post me permite añadir una entrada al blog. Es código Common Lisp, por lo que se ve que comienza por un parémtesis. El patrón (definido por el macro de Emacs-Lisp define-skeleton después me pregunta por el título de la entrada (el uso de la variable str hace que me pregunte a la hora de insertar el patrón). Después, añade el cuerpo vacío y también la fecha actual de la entrada obtenida de la función de Emacs-Lisp (current-time). Finalmente, el carácter _ indica la posición en la que queda el cursor, con lo que puedo empezar a escribir el cuerpo de la entrada.

Prueba del formato org-mode

En este caso, he utilizado org-mode para crear escribir esta entrada.

¡Incluso soporta varios párrafos!

El código para hacerlo en Emacs-lisp es el siguiente:

(defun org-to-html ()
  (interactive)
  (when (mark)
    (save-excursion
      (let ((text (buffer-substring-no-properties (point) (mark))))
        (delete-region (point) (mark))
        (insert
         (with-temp-buffer
           (insert text)
           (org-export-region-as-html (point-min) (point-max) t 'string)))))))

Lo que hago pues es seleccionar el texto que escribo en formato org y llamar a esa función org-to-html, que me transforma el texto seleccionado en HTML, incluso el trozo de código anterior, con coloreado de sintaxis que no necesita del embellecedor de código JavaScript de la página…

Translation within Emacs using Google Translate

Just to show a little Emacs-Lisp script I wrote the other day. We're in the process of translating all our class material into English, and thought of getting some help from Google Translator. Selecting a phrase and calling the insert-translation function substitutes current text with its traduction into English. You know, Google Translate fails a fair bit, but it helps, and you don't have to write all the slides again...