how to enable Unicode encoding, lexical scope, and CL functions in an Emacs Lisp file

I recommend Emacs beginners to enable at least three things in their elisp files (such as dotemacs files, a.k.a. init files) that will reduce surprises later. The three things are

  • a Unicode encoding (UTF-8)
  • lexical scope (usually known as lexical binding mode)
  • CL functions

1. how to enable UTF-8 encoding

In order to be able to use Unicode characters (in strings or comments) in your init file, visit the init file, then invoke the command add-file-local-variable-prop-line to add the file local variable coding with utf-8 as its value.

M-x add-file-local-variable-prop-line RET coding RET utf-8 RET

Then save and close the file. You are supposed to use add-file-local-variable-prop-line and not add-file-local-variable.

2. how to enable lexical scope

To make code in your init file to be lexically scoped, visit the init file, then invoke the command add-file-local-variable-prop-line to add the file local variable lexical-binding with t as its value.

M-x add-file-local-variable-prop-line RET lexical-binding RET t RET

Then save and close the file. For this too you are supposed to use add-file-local-variable-prop-line and not add-file-local-variable.

3. how to use CL functions

To use CL functions/macros (with cl prefix) like cl-loop, cl-defun, cl-destructuring-bind in your init file, you can add this line to your init file:

(require 'cl-lib)

That line should not be your first line. Your init file should not look like this:

(require 'cl-lib)
;; -*- coding: utf-8; lexical-binding: t; -*-

...

It should look like this:

;; -*- coding: utf-8; lexical-binding: t; -*-

(require 'cl-lib)

...

Some articles share Emacs Lisp snippets that won’t work if you don’t include the following line when you copy them:

(require 'cl)

To spot such code easily and for relations between cl and cl-lib, see highlighting old style CL function names in Emacs Lisp

This entry was posted in Emacs and tagged , , , . Bookmark the permalink.

4 Responses to how to enable Unicode encoding, lexical scope, and CL functions in an Emacs Lisp file

  1. Pingback: Emacs Lisp lexical binding gotchas and related best practices | Yoo Box

  2. aethanyc says:

    I was wondering why adding a variable by “add-file-local-variable-prop-line” and not by “add-file-local-variable”. Don’t they do the same job except they put the variables in different places? Could you please explain more? Thanks.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s