Posts Tagged ‘emacs’

Refactoring Configurations

Wednesday, July 29th, 2009

I felt my init.el file was getting too bloated, so I ended up doing a fair amount of refactoring on it. I moved essentially all the code from init.el into a few directories I made in .emacs.d. Structuring your customizations is pretty important if you ever either need to go back to change them or find them to suggest to others; I do both of these a fair amount, so I spend a fair amount of time organizing my files. I probably ended up erring on the side of too many horizontal files, but I think it should be OK for now.

My .emacs.d directory now has four main elisp directories: customizations, major-modes, minor-modes, and utilities. It also has temporary information, documentation, Clojure, and hopefully everything I need to just be able to check it out and have my full working setup. The customizations and utilities directory are currently flat; They contain small files described for what they modify or are for. For example, the Ibuffer customizations I recently suggested are in ibuffer.el. This does sometimes pose organizational problems; Should changing an variable customizing a minor-mode on entering a major-mode be a customization of the minor-mode or major-mode? I currently go for the major-mode, but this could change if I ever have problems finding anything.

Major-modes and minor-modes contain precisely what they describe; All the major and minor modes I have downloaded. Packages that modify other major modes, such as dired+, do not go in these directories; they still go in the customizations file. These two directories can be arbitrarily nested - I just put the modes in however they are distributed.

After moving all the customizations out of init.el, I had the following left:

(let ((default-directory "~/.emacs.d/"))
  (add-to-list 'load-path default-directory)
  (normal-top-level-add-subdirs-to-load-path))
 
(defun load-directory (dir)
  (mapcar '(lambda (x)
             (load-file x))
          (directory-files dir t "\\.el$")))
 
(load-directory "~/.emacs.d/customizations/")
(load-directory "~/.emacs.d/utility/")

The first let expression is a simplification of something I blogged about a while ago; It will add all subdirectories of ~/.emacs.d/ to the load-path; this is necessary so that I don’t have to do manual manipulation of the load-path.

The second function is one I wrote to support my refactorings. It will load every elisp file in a directory. It doesn’t support subdirectories, but this wouldn’t be too hard to add if I ever need it. I then just load up my customizations and utility functions and am good to go. I highly recommend doing something similar to this; Splitting your customizations from one big file and aggregating similarities makes it much easier to manage your configuration.

Emacs Utility Functions

Saturday, July 25th, 2009

I’ve ended up migrating a few of my old functions back to my new setup, as well as creating a few newer ones. These are the ones I’ve added recently - maybe they’ll be useful to you, as well.

I’ve been doing a few book reviews recently, and instead of having to manually add in links I just wrote a function to generate a link based on the ASIN I give it. If you end up using something like this, you’ll probably want to change it so that it links to your Amazon Associate’s account, although I won’t complain if you don’t.

(defun insert-amzn-product (asin)
  "Inserts a link(image + text to an Amazon product using the ASIN"
  (interactive "MAsin:")
  (insert
   (concat "<iframe src=\"http://rcm.amazon.com/e/cm?t=randmusiofaso-20"
           "&o=1&p=8&l=as1&asins="
           (replace-regexp-in-string "\\n" "" asin)
           "&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&"
           "bc1=000000&bg1=FFFFFF&f=ifr\" style=\"width:120px;height:240px;\""
           "scrolling=\"no\" marginwidth=\"0\" marginheight=\"0\""
           "frameborder=\"0\"></iframe>")))

I like to be able to know how many words are in a buffer, so I found the following function somewhere online. It just runs ‘wc -w’ as a shell command on the contents of the current buffer, which outputs the number of words.

(defun wc nil
  "Count words in buffer"
  (interactive)
  (shell-command-on-region (point-min) (point-max) "wc -w"))

I sometimes use different editors on the same files, and end up having broken indentation a lot of the time this happen. I wrote iwb (for indent-whole-buffer) to fix indentation problems.

(defun iwb ()
  "Indents the entire buffer"
  (interactive)
  (indent-region (point-min) (point-max) nil))

This function I picked up from Steve Yegge’s blog. It prompts for a directory and then moves the buffer you are editing and the associated file to that directory

(defun move-buffer-file (dir)
  "Moves both current buffer and file it's visiting to DIR."
  (interactive "DNew directory: ")
  (let* ((name (buffer-name))
	 (filename (buffer-file-name))
	 (dir
	  (if (string-match dir "\\(?:/\\|\\\\)$")
	      (substring dir 0 -1) dir))
	 (newname (concat dir "/" name)))
    (if (not filename)
	(message "Buffer '%s' is not visiting a file!" name)
      (progn
	(copy-file filename newname 1)
	(delete-file filename)
	(set-visited-file-name newname)
	(set-buffer-modified-p nil) 	t))))

Eproject

Friday, July 24th, 2009

Eproject.el is a simplistic project management tool. It doesn’t have much functionality, but what it does have is just what I want: a fast way to switch between files in a project. Eproject also comes with a few other utilities, like the ability to keep track of project metadata, or a utility that opens all files in a project. However, there are two main uses: project-specific hooks and ido-based switching on other project files.

Eproject doesn’t define project types for you; you have to do this yourself. For example, to define a java project you could have the following project definition:

(define-project-type java (generic)
 (look-for "build.xml")
 :relevant-files ("\\.java" ))

Whenever you open a java, this will first look for a build.xml somewhere up the source tree. All files above that in the source tree that match the relevant-files regexp. If the file you opened is in the project, eproject-minor-mode will turn on. You can also define projects to inherit from other projects to look for metadata; inheriting from (generic) will provide all metadata you need for a complete project. You can also define your own selector, using something other than look-for and a regex, although this solution is usually pretty good.

Eproject-minor-mode will bind two additional keys - C-x C-f, and C-x C-b. C-x C-f will call eproject-find-file, which will present an ido menu containing all the files in the project - quite handy if you need to switch to a file in a different directory. C-x C-b will open an ibuffer window containing only files in the current project - I haven’t yet used this, but it will allow you to do things like query-replace over your entire project.

How do you enable eproject? Well, after downloading it and adding it’s location to your load-path, just say:

(require 'eproject)

For more information on it, check out the github page at http://github.com/jrockway/eproject/tree/master. There’s also a lot of usage documentation in the top of eproject.el that you might want to read to get a better idea of how it works.

Dired

Wednesday, July 22nd, 2009

Dired is Emacs’s very powerful directory browsing and management package. To use it, just type ‘C-x d’ and select a directory; the directory will be displayed in a dired buffer. In this dired buffer, you can mark files either with ‘m’ or by more advanced option, such as by regexp. You can perform very powerful commands such as renaming groups of files by regexp. Dired is actually a huge package, so I’ll only go into a few of the most useful parts of it here; you really should read the manual on it.

Dired can perform operations on either individual files or groups of files that you have marked. The main ways of marking files are by selecting individual files and pressing ‘m’ (’u’ unmarks), or ‘% m’, which prompts for a regexp and matches all files matching that regexp. There are also options for marking temporary files, all directories, symlinks, etc.

Dired also lets you operate on either the current file, if no files are marked, or all marked files. The most useful operation is ‘Q’, which does a query-replace on all selected files. You can copy or move groups of files using ‘C’ and ‘R’. You can also execute shell commands on them, using !. This prompts you for a shell command to execute; if you say something without a ‘*’, such as just ‘cat’, it will run the shell command and display the output in a different buffer. Otherwise, a ‘*’ in the command will be replaced with the filenames.

Like I said, there is a huge amount to Dired, and so you should explore it on your own to find out what is available. If you have menus enabled, you can explore those to find out some of the options.

There are also two additional packages that you probably want, both of which come with GNU Emacs. Dired-x adds additional functionality to dired. Really, I mostly just use it for it’s ability to provide default shell commands to execute on files, but this is enough (actually, looking at the documentation, there’s a few other things I use that are actually from it. Just goes to show how well it integrates with dired). To enable dired-x features, add the following to your initialization file:

(require 'dired-x)

The other package you will want to install is wdired, which allows you to edit dired buffers and have the changes reflected in the filesystem. Once you enter wdired-mode, you can edit filenames using all you emacs commands, and they will be saved - including into any subdirectories added by adding ‘/’ to the filepath. If you set the permissions like I do, you can also edit the permissions. You need some way to get to wdired-mode from dired, so add the following to your .emacs file to be able to just press ‘r’ in dired mode. Once you are finished in wdired-mode and want to save your changes, simply do ‘C-x C-s’ like you are saving a regular buffer and you will switch back to dired.

(require 'wdired)
(setq wdired-allow-to-change-permissions 'advanced)
(define-key dired-mode-map	      	      (kbd "r")		'wdired-change-to-wdired-mode)

I use dired a lot, and so find it very annoying when my dired buffers get out of sync with my filesystem. I help fix this problem using the following pieces of advice around the major buffer-switching and buffer-displaying code. Once switching or displaying the buffer, it refreshes the buffer contents if it is dired-mode. This isn’t perfect - if the filesystem gets out of sync while you are in the dired buffer, it will remain out of sync until you switch to a different buffer - but I haven’t had problems with that so far.

(defadvice switch-to-buffer-other-window (after auto-refresh-dired (buffer &optional norecord) activate)
  (if (equal major-mode 'dired-mode)
      (revert-buffer)))
(defadvice switch-to-buffer (after auto-refresh-dired (buffer &optional norecord) activate)
  (if (equal major-mode 'dired-mode)
      (revert-buffer)))
(defadvice display-buffer (after auto-refresh-dired (buffer &optional not-this-window frame)  activate)
  (if (equal major-mode 'dired-mode)
      (revert-buffer)))
(defadvice other-window (after auto-refresh-dired (arg &optional all-frame) activate)
  (if (equal major-mode 'dired-mode)
      (revert-buffer)))

That’s all the customizations I have for dired currently, but there are still other packages that don’t currently come with Emacs that customize it further, such as dired+. I’d recommend going here and looking for further customizations you like, as well as reading the dired manual to find more information on it.

Updating Imenu for Java 1.5

Tuesday, July 21st, 2009

NOTE: In the following regex’s, some strings are broken into two lines. This is due to a C-M character that renders as a newline in wordpress - It looks like ^M in emacs.

While coding in Java for work, I realized that the default imenu indexing for java was not sufficient. I usually use Imenu for jumping to a function in the same file (as opposed to CTags or something like that), and it didn’t load every function into the index. After some experimentation, I found that the problem occurred when either generic types were used or annotations were on the parameters of the functions. Since I’ve started using the @NonNull annotation and Findbugs frequently, this was a problem.

After digging around Imenu’s preferences, it seems the problem was in the variable imenu-generic-expression. If no function is specified for imenu-extract-index-name-function (which is not by default in Java-mode),
imenu-generic-expression is used to determine the name of the function. The implementation is essentially to go to the end of the buffer, repeatedly call beginning-of-defun, and use the regex stored in imenu-generic-expression to parse out the function name. This regex is originally set somewhere in the Emacs code base as the following for java-mode:

"[[:alpha:]_][][.[:alnum:]_]+[ 	\n
]+\\([[:alpha:]_][[:alnum:]_]+\\)[ 	\n
]*([ 	\n
]*\\([][.,[:alnum:]_]+[ 	\n
]+[][.,[:alnum:]_][][.,[:alnum:]_ 	\n
]*\\)?)[.,[:alnum:]_ 	\n
]*{"

Realizing that I would have to modify this regexwas not very encouraging, but breaking it into separate pieces and puzzling over the meaning came up with the following commented regex. While still ugly, it is at least no longer as confusing:

(concat
    "[[:alpha:]_]"                    ;start of type
    "[][.[:alnum:]_]+"                 ;end of type
    "[ \t\n
]+"                      ;whitespace
    "\\([[:alpha:]_][[:alnum:]_]+\\)" ;captured function name
    "[ \t\n
]*"                      ;whitespace
    "("                               ;start of arg list
       "[ \t\n
]*"                   ;whitespace
       "\\("
           "[][.,[:alnum:]_]+"        ;type
           "[ \t\n
]+"               ;whitespace
           "[][.,[:alnum:]_]"         ;start of var name
           "[][.,[:alnum:]_ \t\n
]*" ;end of var name, space
       "\\)?"
    ")"                               ;end of arg space    "[.,[:alnum:]_ \t\n
]"*"         ;throws declarations and whitespace
    "{"                               ;open brace

With this done, it was fairly easy to transform into a regex that accepted generics and annotations by adding <, >, space, and @ in the appropriate places. While this will find some malformed functions, I’m OK with this - It still has to be located at the beginning of a function for a name to come up, in which case even if I made a type I want to be able to jump there. The modified regexp ended up looking like this:

(concat
    "[[:alpha:]_]"                       ;start of type
    "[][.[:alnum:]_<> ]+"                ;type
    "[ \t\n
]+"                         ;whitespace
    "\\([[:alpha:]_][[:alnum:]_]+\\)"    ;funname
    "[ \t\n
]*"                         ;whitespace
    "("
    "[ \t\n
]*"                         ;whitespace
       "\\("                             ;argument list
 
           "[][.,[:alnum:]_@<> ]+"       ;annotations/type
           "[ \t\n
]+"                  ;whitespace
           "[][.,[:alnum:]_]"            ;start of var name
           "[][.,[:alnum:]_@<> \n\t
]*" ;end of var name
       "\\)?"
     ")"
    "[.,[:alnum:]_ \t\n
]*"             ;more whitespace, throws declarations
    "{"                                  ; begin fun
   )
)

This still leaves the problem of having this be automatically defined in java-mode, but any experienced emacs user will know how to do this: hooks! Specifically, adding a function that sets imenu-generic-expression to the correct value to java-mode-hook will automatically execute whenever a java buffer is entered.

(add-hook 'java-mode-hook '(lambda ()
 (setq imenu-generic-expression
 `((nil
    ,(concat
    "[[:alpha:]_]"                       ;start of type
    "[][.[:alnum:]_<> ]+"                ;type
    "[ \t\n
]+"                         ;whitespace
    "\\([[:alpha:]_][[:alnum:]_]+\\)"    ;funname
    "[ \t\n
]*"                         ;whitespace
    "("
    "[ \t\n
]*"                         ;whitespace
       "\\("                             ;argument list
           "[][.,[:alnum:]_@<> ]+"       ;annotations/type
           "[ \t\n
]+"                  ;whitespace
           "[][.,[:alnum:]_]"            ;start of var name
           "[][.,[:alnum:]_@<> \n\t
]*" ;end of var name
       "\\)?"
     ")"
    "[.,[:alnum:]_ \t\n
]*"             ;more whitespace, throws declarations
    "{"                                  ; begin fun
   )
 1)
  ))))

Why the old regex is still in emacs itself I don’t know: It is obviously from Java 1.4, which didn’t have templates or annotations, but Java 1.5 has been out for a while. This new version will catch all the occurrences that would be caught by the old regex, so don’t worry about compatibility issues. I submitted a patch to fix this to the emacs-devel mailing list - this seems like something that should be fixed in the main distro - so we’ll see whether or not this will make it in or not.

Ibuffer: Dired for Buffers

Sunday, July 19th, 2009

Ibuffer is a massive improvement on the buffer-menu function which is brought up by C-x C-b.It allows dried-like manipulations of your buffers, as well as font locks and sorting. It’s actually better than buffer-menu in pretty much every way, so if you haven’t switched to using it instead, I would highly recommend it. One of the more useful things it lets you do are: file buffers by major-mode, and then performing a replace-regexp on all marked files. You can select buffers by major mode using %m, and Q with then start a query-replace.

Another useful feature of ibuffer is it’s filtering, with ‘/’ as a prefix. Once you open ibuffer, you can filter the results down and operate on subgroups of buffers. For example, /n emacs will only show buffers in with ‘emacs’ in the buffer-name. You can also change the sort order with ’s’. Like Dired, * and % prefixes work for marking buffers.

Setting ibuffer up is relatively easy, although there is a ton of configuration you can do if you want. I’ll tell you about what I do, which is fairly minimal, but M-x customize-group ibuffer will give you all the ways to customize ibuffer. To use ibuffer instead of buffer-menu, add the following to your initialization:

(require 'ibuffer)

This just loads ibuffer. It comes with GNU Emacs, so you should already have the library without having to download it.

(setq ibuffer-default-sorting-mode 'major-mode)

This options control how lines in the ibuffer window are grouped. By specifying the sorting mode as ‘major-mode, I indicate that I want ibuffer to group buffers of the same type together. Another common sorting order is ‘recency, which orders them from most recently viewed to last viewed. Other options include ‘lexographic, ‘buffer-size, and ‘file-name.

(setq ibuffer-always-show-last-buffer t)
(setq ibuffer-view-ibuffer t)

These lines specify to ibuffer which buffers should be in the ibuffer menu. The first line specifies that it should always show the last buffer we were in, even if it would usually hide it. The second line specifies that the *Ibuffer* buffer itself should be in the buffer list - I just like having a complete list of my buffers to start with.

(global-set-key  (kbd "C-x C-b")        'ibuffer-other-window)

Since ibuffer is so much better than buffer-menu, you should just replace the C-x C-b keybinding to call ibuffer instead of buffer-menu.

YASnippet - Snippets for Emacs

Saturday, July 18th, 2009

I added another package back to my emacs configuration: yasnippet. Yasnippet is supposed to be based off of TextMate’s snippet system, which I have never used but have heard it is quite good. Yasnippet allows you to define your own ’snippets’ which are inserted into your file when you type a certain phrase and hit the trigger key, which is defaulted to tab. For example, in c, if you type ‘if‘, this gets expanded to

if (__)
{
 
}

Where your point is on the _. Once you finish inserting the condition, you can press TAB again to rotate to the next spot defined in the snippet - in this case, the body of the if statement.

These snippets are all kept in a directory as text files, in a folder heirarchy of modes. For example, to modify that if snippet, you would modify the “snippets/text-mode/cc-mode/if” file in your snippets folder. If you just open it up, you will see:

#name : if (...) { ... }
# --
if (${1:condition})
{
    $0
}

The #’s are just comments, and the rest of the snippet will be inserted, with the $’s being the location where the TAB goes to, with it going from $1 to $2 to … to $0. This snippet will be called by the trigger of ‘if’, which is the file name. For more information on editing snippets, see this.

To add yasnippet to your emacs startup, add the following to your init file:

(require 'yasnippet)
(yas/initialize)
(yas/load-directory "~/.emacs.d/yasnippet-0.5.10/snippets")

Where in the call to yas/load-directory you put the location of your snippets folder.

Imenu

Thursday, July 16th, 2009

Imenu is a built-in emacs package for navigating around source files. It is a feature that allows you to jump around by scanning on predefined regex’s - mostly to variable of function declarations. Imenu is very useful for quickly navigating around a source file - I recommend you start using it whenever you need to navigate to a different function in the same file. The default for imenu is to use emac’s built in completion for variables; however, I much prefer using ido’s completion, and for that you need the following commands and function in your initialization file:

(require 'imenu)

This just allows you to use the imenu commands.

(defun ido-goto-symbol ()
  "Will update the imenu index and then use ido to select a symbol to navigate to"
  (interactive)
  (imenu--make-index-alist)
  (let ((name-and-pos '())
	(symbol-names '()))
    (flet ((addsymbols (symbol-list)
		       (when (listp symbol-list)
			 (dolist (symbol symbol-list)
			   (let ((name nil) (position nil))
			     (cond
			      ((and (listp symbol) (imenu--subalist-p symbol))
			       (addsymbols symbol))
			      ((listp symbol)
			       (setq name (car symbol))
			       (setq position (cdr symbol)))
			      ((stringp symbol)
			       (setq name symbol)
			       (setq position (get-text-property 1 'org-imenu-marker symbol))))
			     (unless (or (null position) (null name))
			       (add-to-list 'symbol-names name)
			       (add-to-list 'name-and-pos (cons name position))))))))
      (addsymbols imenu--index-alist))
    (let* ((selected-symbol (ido-completing-read "Symbol? " symbol-names))
	   (position (cdr (assoc selected-symbol name-and-pos))))
      (if (markerp position)
	  (goto-char position) (goto-char (overlay-start position))))))

This is the function that uses ido for imenu. Since imenu occasionally has multiple levels - you select whether you want functions or variables, etc - this loops through all those sublists and adds all possibilities to a list. Once the list is compiled, it prompts you using ido for which definition you want to go to.

(setq imenu-auto-rescan t)

This just ensures that whenever you call imenu or the new function ido-goto-symbol you get the latest information, and not only functions which may have been cached.

(global-set-key (kbd "M-s") 'ido-goto-symbol)

I use this function quite frequently, so I rebound it to M-s. M-s is usually a prefix key for a few commands, but the only one I use that this interferes with is occur, but I use that rarely enough that I’m fine with just having to M-x occur. I use ido-goto-symbol enough that I really want it to be as few key presses as possible, so using something like M-s M-s would be pretty irritating.

More Random Emacs Config

Saturday, July 11th, 2009

Some more additions to my .emacs file (actually, my init.el file now. I decided it was easier to be able to add my entire .emacs.d directory to source control, and keep all of my customizations in it). Most of these were from my old config files - It turns out there’s a reason I had most of that stuff. I’ll just keep re-adding stuff from them if I need it, it turns out I had a fairly comprehensible structure that allows me to easily find specific customizations I had.

(require 'ansi-color) (add-hook 'shell-mode-hook 'ansi-color-for-comint-mode-on)
(setq comint-prompt-read-only t)
(shell)

A few more customizations to my shell configuration. The first line adds colours, as well as fixing the issues I mentioned last time. I had this in my old .emacs file, but did not realize it was what fixed shell-mode to be readable - part of the reason I started over I suppose, to better understand all of my customizations. The last line just starts a shell buffer - since I primarily use the shell from emacs, I always open one anyway. This just saves me from doing it manually.

(setq default-major-mode 'text-mode)
(add-hook 'text-mode-hook 'flyspell-mode)
(add-hook 'text-mode-hook 'visual-line-mode)
(defadvice ispell-command-loop (before ispell-reverse-miss-list activate)
  "reverse the first argument to ispell-command-loop"
  (ad-set-arg 0 (reverse (ad-get-arg 0))))

I added a few things to make writing this blog and other text documents easier on myself. There are pretty much no downsides to setting the default major mode to text instead of fundamental. While in text mode, I also want spellchecking and line wrapping based on my frame size. The advice is something I picked up from the internet somewhere(actually, after investigating, from here), which reverses the order in which ispell makes suggestions. This tends to offer me better suggestions than just the normal order, for whatever reason.

(require 'uniquify)
(setq uniquify-buffer-name-style 'reverse)
(setq uniquify-separator "/")
(setq uniquify-after-kill-buffer-p t)
(setq uniquify-ignore-buffers-re "^\\*")

Uniquify is an built-in emacs package that renames buffers when you open two files with the same name. In the default case, they will merely be numbered, so for example you would have a .emacs buffer and an .emacs<2> buffer. Uniquify will append part of the file path to the file, so instead you’d have .emacs/nflath and .emacs/emacs buffers. uniquify-buffer-name-style and uniquify-separator control how the buffer names are created; describe-variable uniquify-buffer-name-style in order to see all the possible options. uniquify-after-kill-buffer-p controls whether or not buffers are renamed when other buffers were killed: When set to t, when one of the about duplicate .emacs buffers is closed, the other will rename itself to .emacs. The last line specifies not to perform this for special buffers, such as *scratch*

(defun insert-strong-tags ()
  "Inserts <strong></strong> around the word at point"
  (interactive)
  (save-excursion
    (re-search-backward "\\s ")
    (forward-char 1)
    (insert "<strong>")
    (forward-char 1)
    (re-search-forward "\\s \\|$")
    (if (not (eq (point) (point-max)))
	(backward-char 1))
    (insert "</strong>")))
(global-set-key (kbd "C-c i s") 'insert-strong-tags)

I actually wrote this function while writing this blog post. This is one of the great things about emacs: You can immediately solve inefficiencies once you notice them. This function will insert strong tags around the word you are currently on, leaving the point at the same location. This is great when you forget to add an opening tag to the beginning of the word, or are noticing an error you made afterwords and just need to add the tags.

(global-set-key (kbd "C-a") 'back-to-indentation)

I used to have C-a bound to switch between going to the beginning of the line and back to the indentation, but I realized I pretty much never wanted to go to the actual beginning of a line. I rebound C-a to what usually M-m because it’s much easier to type.

(global-set-key (kbd "C-c j") 'join-line)

A useful function that doesn’t have a default keybinding, so I provided one

(add-hook 'before-save-hook 'delete-trailing-whitespace)
(set-face-attribute 'default nil :height 80)
(column-number-mode)

The first of these customizations will delete trailing whitespace from files every time I save. I really, really hate it when I press C-e and am not at what I want to edit, and I haven’t ever encountered a situation where I need to keep trailing whitespace, so I just automate the process of removing it. The second line just sets the size of the font; you should customize this to your liking, depending on your monitor’s resolution. On some versions and monitors, I’ve had to have this be at 90; others I could set the size to 60 without any problems. column-number-mode puts the current column number on the mode line, which I like to know.

I have made a few more customizations, but they’re big enough to warrant separate posts.

Clojure Setup for Emacs

Thursday, July 9th, 2009

I’ve recently started learning Clojure, and so of course the first thing I did was set up emacs to properly be able to format and code in it. To do this, you should first download clojure-mode. Now, manually load the file, with M-x load-file, and then perform M-x clojure-install. This only needs to be done once. The clojure-install function will install all of the necessary dependencies, including slime integration for clojure. Once this is set, I have the following to configure clojure-mode:

(require 'clojure-mode)
(add-to-list 'auto-mode-alist '("\\.clj$" . clojure-mode))
(setq clojure-src-root "/home/nflath/.emacs.d")
(setq swank-clojure-extra-classpaths '())
(clojure-slime-config)

This is admittedly a fairly minimal install. It requires clojure-mode to be installed and then sets clojure-mode to be used on all .clj files. You also have to specify the directory you specified with clojure-install as clojure-src-root. If you have any extra jar files or anything that you want Slime to know about, you need to add them to swank-clojure-extra-classpaths, and then clojure-slime-config will enable slime. Once this is done, M-x slime will load up Slime using clojure, acting as a Clojure repl. You can also send expressions in your .clj files to the repl to be evaluated with C-x C-e and all the usual emacs-lisp evaluation functions.

One note: learning the S-exp movement commands will help tremendously for editing clojure. I have only recently been using them, and they have sped up moving around the expressions by a huge amount. C-M-f is forward-sexp, which will take you to the next s-exp inside the current one, and C-M-b is backwards-sexp, which will do the opposite.