Emacs Redux

Return to the Essence of Text Editing

Erase Buffer

| Comments

Some Emacs users find themselves wondering what’s the fastest way to erase the contents of a buffer. As you know, I’m fond of delete-selection-mode and I find the combination of C-x h (mark-whole-buffer) + inserting anything afterwards pretty potent.

Another pretty quick way to erase a buffer would be the built-in erase-buffer command. It’s disabled by default since it’s considered that beginners find it confusing(although I’m not sure why), so you’ll be prompted to enable it the first time you run M-x erase-buffer. Alternative you can simply put this snippet in your config:

1
2
;; enable erase-buffer command
(put 'erase-buffer 'disabled nil)

You should note that any narrowing restrictions would have no effect over erase-buffer and the buffer would be truly empty after invoking the command. Conversely - narrowing has an effect over mark-whole-buffer.

If you like the command you might want to bind it to some keybinding like C-c E:

1
(global-set-key (kbd "C-c E")  'erase-buffer)

Personally, I rarely need it, so I don’t bind it to anything.

The erase-buffer command is enabled by default in Prelude.

Rename File and Buffer

| Comments

A few weeks ago I wrote an article called “Delete file and buffer”. Today we’ll revisit the article in a way, by exploring a pretty similar topic - renaming of a file and its associated buffer. I’ve taken the liberty to use pretty much the same wording I used in the aforementioned post to spare me the effort of thinking up something original.


From time to time(most often when I refactor code) I need to quickly(this removes dired from the equation) rename a file and the buffer associated with it. Since most of the files I work with are under version control I can just use the tried and true M-x vc-rename-file. Unfortunately the command does not act on the current file and will prompt you for a file to rename. Looks like we need to create a simple wrapper around it to get the job done:

1
2
3
4
5
6
7
8
9
10
11
12
(defun rename-file-and-buffer ()
  "Rename the current buffer and file it is visiting."
  (interactive)
  (let ((filename (buffer-file-name)))
    (if (not (and filename (file-exists-p filename)))
        (message "Buffer is not visiting a file!")
      (let ((new-name (read-file-name "New name: " filename)))
        (cond
         ((vc-backend filename) (vc-rename-file filename new-name))
         (t
          (rename-file filename new-name t)
          (set-visited-file-name new-name t t)))))))

The wrapper is extra smart and will work on files that are not under version control as well! I’m pretty fond of commands that do what you mean instead of throwing errors. Now that we have this neat little command we should probably bind it to some each to press keys, like C-c r:

1
(global-set-key (kbd "C-c r")  'rename-file-and-buffer)

As usual both the command and its keybinding are available in Prelude.

Manage Processes With Proced

| Comments

One extremely cool (but little known) new feature in Emacs 23 was the addition of proced.

proced basically allows you to run top inside Emacs and monitor/control processes via it. Here’s how it looks in action:

Normally you’d use M-x proced to start the command, but as mentioned earlier I find it extremely useful and therefore I bind it to C-x p (inspired by dired’s C-x d):

1
(global-set-key (kbd "C-x p") 'proced)

See proced-mode(C-h f proced-mode) for a description of features available in Proced buffers.

Some of you might have noticed that the screenshot in the post is taken under GNOME, which is kind of strange considering I’m an OSX user. Unfortunately proced does not work on OSX(but perhaps surprisingly it works on Windows).

The C-x p keybinding works out-of-the box on Prelude.

Start Command or Switch to Its Buffer

| Comments

Few weeks ago I showed you a handy way to run term-mode. You might have noticed that it makes sense for many commands to be run in a similar manner. Here’s a quick example - I often like to jump between an Emacs Lisp source buffer and an ielm (interactive Emacs Lisp shell - M-x ielm) buffer to try out stuff. I could reuse the code I showed you for ansi-term to create a similar command called visit-ielm:

1
2
3
4
5
6
7
8
9
(defun visit-ielm ()
  "Create or visit a `ielm' buffer."
  (interactive)
  (if (not (get-buffer "*ielm*"))
      (progn
        (split-window-sensibly (selected-window))
        (other-window 1)
        (ielm))
    (switch-to-buffer-other-window "*ielm*")))

You might want to bind this to C-c C-z (a-la SLIME):

1
(define-key emacs-lisp-mode-map (kbd "C-c C-z") 'visit-ielm)

I don’t know about you, but I hate code repetition. Having that in mind we can factor out the duplication like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
(defun start-or-switch-to (function buffer-name)
  "Invoke FUNCTION if there is no buffer with BUFFER-NAME.
Otherwise switch to the buffer named BUFFER-NAME.  Don't clobber
the current buffer."
  (if (not (get-buffer buffer-name))
      (progn
        (split-window-sensibly (selected-window))
        (other-window 1)
        (funcall function))
    (switch-to-buffer-other-window buffer-name)))

(defun visit-term-buffer ()
  "Create or visit a terminal buffer."
  (interactive)
  (start-or-switch-to (lambda ()
                         (ansi-term (getenv "SHELL")))
                      "*ansi-term*"))

(defun visit-ielm ()
  "Switch to default `ielm' buffer.
Start `ielm' if it's not already running."
  (interactive)
  (prelude-start-or-switch-to 'ielm "*ielm*"))

Much better! We can now use start-or-switch-to to build any number of similar commands!

start-or-switch-to and visit-ielm are available in Prelude(but with a prelude- prefix).

P.S. If you’d like some nice SLIME-like code navigation command in emacs-lisp-mode you might check out elisp-slime-nav.

SLIME allows very convenient navigation to the symbol at point (using M-.), and the ability to pop back to previous marks (using M-,).

This plugin provides similar navigation for Emacs Lisp, supporting navigation to the definitions of variables, functions, libraries and faces.

Additionally, elisp-slime-nav provides a way to describe the symbol at point, whatever its type. As with slime-describe-symbol, this functionality is bound both to C-c C-d d and C-c C-d C-d by default.

It’s pretty useful if you hack Emacs Lisp yourselves. If you don’t hack Emacs Lisp (yet) you probably can do without it.

elisp-slime-nav comes bundled with Prelude.

Execute Commands Ninja-style With Key-chord-mode

| Comments

One of my bigger problems as an Emacs user is that there only so many good keybindings available. At some point you’re out of good options, but there are still plenty of commands you’d rather be able to execute faster than you’d be able to do with M-x command-name.

key-chord-mode to the rescue! It’s a pretty handy minor mode which allows you to bind commands to keys that should be pressed together or consecutively(with little time between the keystrokes - by default 0.3 seconds). This gives you some pretty good opportunities to increase your productivity. Assuming you’ve installed the mode somehow, you can start playing with it:

1
2
3
4
5
6
7
8
;; key chords
(require 'key-chord)

(key-chord-define-global "BB" 'iswitchb)
(key-chord-define-global "FF" 'find-file)
(key-chord-define-global "jk" 'beginning-of-buffer)

(key-chord-mode +1)

The examples above illustrate global key-chords. Major mode specific key chords are also available.

One should be careful about the key-chord he chooses - it should definitely be something you’re unlikely to type normally. This also means that if you’re writing in Emacs in several languages with common letters, key chords that make sense in say English, might not make sense in French (for instance). Luckily for me - I write almost exclusively in English or some programming language (and Bulgarian and English are nothing alike).

One other note - key chords don’t play very well with evil-mode(Emacs’s vim emulation layer) for obvious reasons. vim is kind of key-chord-mode’s principle inspiration. If you’re an evil-mode user you probably don’t need key-chord-mode anyways.

Prelude enables key-chord-mode out of the box and makes some creative use of it with jj and JJ (which I’d advise you try out if you didn’t know about them).

Switch to Previous Buffer

| Comments

Jumping between the current buffer and the one you were in before is a pretty common task. It’s also one you can solve in a multitude of way - the most popular being simply the use of switch-to-buffer and ido-switch-to-buffer. Both commands (which are generally bound to C-x b) would suggest to select the previous buffer when you invoke them. While this was good enough for me for many years, recently Luke Randall suggested me a neat alternative:

1
2
3
4
5
(defun switch-to-previous-buffer ()
  "Switch to previously open buffer.
Repeated invocations toggle between the two most recently open buffers."
  (interactive)
  (switch-to-buffer (other-buffer (current-buffer) 1)))

When you pair this command with a handy key chord it becomes a great performance booster:

1
(key-chord-define-global "JJ" 'switch-to-previous-buffer)

If you’re not fond of key chords I’d suggest a good old keybinding instead:

1
(global-set-key (kbd "C-c b") 'switch-to-previous-buffer)

The command and its key chord are part of Prelude.

Custom Config for Shells

| Comments

Anybody knows that you can run a shell inside Emacs with M-x shell. Few people know you can have Emacs run some additional configuration for the shell after it’s started.

Emacs sends the new shell the contents of the file ~/.emacs_shellname as input, if it exists, where shellname is the name of the name if your shell - bash, zsh, etc. For example, if you use bash, the file sent to it is ~/.emacs_bash. If this file is not found, Emacs tries with ~/.emacs.d/init_shellname.sh.

One popular application of such custom configuration is to have a simpler shell prompt in Emacs, compared to the one you usually employ, since shell-mode doesn’t deal well with fancy prompts.

You can find out more about running interactive shells in Emacs here or by typing C-h r m Interactive Shell RET in your favorite text editor.

CamelCase Aware Editing

| Comments

One common hurdle Emacs users experience when hacking in Emacs is that many programming languages use CamelCase for class names, method names, identifiers, etc, but Emacs (unlike most IDEs) doesn’t treat CamelCase words the same special way it treats lisp-case and snake_case words. Let me illustrate this with an example.

If you invoke kill-word(M-d) when your cursor is before lisp-case this would kill just lisp and leave you with -case. If you do the same with CamelCase the entire “word” CamelCase will be killed. Same goes for navigation-by-word commands like forward-word, backward-word, etc - they are aware of the subwords that comprise a lisp-case or a snake_case word, but are oblivious to CamelCase. So, what can we do? The answer is surprisingly simple - just use the built-in minor mode subword-mode (formerly known as c-subword-mode).

1
2
3
4
5
;; enable just in ruby-mode
(add-hook 'ruby-mode-hook 'subword-mode)

;; enable for all programming modes
(add-hook 'prog-mode-hook 'subword-mode)

At this point you can try again kill-word before CamelCase. Only Camel is killed now. Sweet!

Prelude enables subword-mode out of the box for programming modes that make use of CamelCase.

Edit Files as Root

| Comments

One area where Emacs traditionally falls short by default is editing files that require root permissions. Since most Emacs users just use a single Emacs frame they never leave, they have the problem of having started it with their current user’s privileges(and it’s unlikely this user is root). In this post I’ll describe two ways to alleviate that particular problem (note that emacsclient users have other options to pick from as well - one is mentioned at the very end of the post).

Here’s Option A - a simple command that allows you to reopen the currently visited file with root permissions(obtained via tramp and sudo) and prompts you for a file name if you’re not currently visiting a file or supply a prefix argument:

1
2
3
4
5
6
7
8
9
10
11
(defun sudo-edit (&optional arg)
  "Edit currently visited file as root.

With a prefix ARG prompt for a file to visit.
Will also prompt for a file to visit if current
buffer is not visiting a file."
  (interactive "P")
  (if (or arg (not buffer-file-name))
      (find-file (concat "/sudo:root@localhost:"
                         (ido-read-file-name "Find file(as root): ")))
    (find-alternate-file (concat "/sudo:root@localhost:" buffer-file-name))))

I came across a similar command a few years back and it’s been pretty useful to me ever since. If you like it, I’d suggest binding it to C-x C-r (kind of like find-file’s binding C-x C-f).

1
(global-set-key (kbd "C-x C-r") 'sudo-edit)

Option B

Lately I’ve decided that such a command is a bit of an overhead, since we can check the file permissions automatically anyways. While I’m not quite fond of advising commands (debugging advised commands is no fun) this was an excellent opportunity to exploit them (for great good):

1
2
3
4
5
(defadvice ido-find-file (after find-file-sudo activate)
  "Find file as root if necessary."
  (unless (and buffer-file-name
               (file-writable-p buffer-file-name))
    (find-alternate-file (concat "/sudo:root@localhost:" buffer-file-name))))

This advises ido-find-file(you might want to advise find-file instead if you’re not using ido) to reopen the selected file as root(you’ll be prompted for your sudo password) if you don’t have write permissions for it. Extremely cool!

The first command has been part of Prelude since forever. As of late, the ido-find-file advice is also present there and it generally voids the need for sudo-edit.

P.S.

emacsclient users have it easy. They just need the following shell alias(I generally alias e to emacsclient -t):

1
alias E="SUDO_EDITOR=\"emacsclient -t -a emacs\" sudoedit"

This should(will) finally save you from reaching for vim in the terminal.

Evaluate Emacs Lisp in the Minibuffer

| Comments

The Emacs Lisp interpreter’s integration with Emacs is pervasive. One can evaluate Emacs Lisp just about everywhere in so many different ways. One way I find particularly handy(especially for short snippets of code) is evaluating Emacs Lisp directly in the minibuffer. This is done with M-:(bound to the command eval-expression).

Upon typing this magic keycombo you’ll be presented with the prompt Eval: in the minibuffer and there you can enter any Lisp expression. Hitting Return will result in the expression’s evaluation.

There is one minor snafu with this, though - I’m addicted to Paredit(for editing Lisp code at least) and Paredit is not automatically enabled in the minibuffer. Let’s change that:

1
2
3
4
5
6
(defun conditionally-enable-paredit-mode ()
  "Enable `paredit-mode' in the minibuffer, during `eval-expression'."
  (if (eq this-command 'eval-expression)
      (paredit-mode 1)))

(add-hook 'minibuffer-setup-hook 'conditionally-enable-paredit-mode)

Evaluate this snippet and try M-: again. If you’re like me - the results will please you.

It should come as no surprise that Prelude enables Paredit by default for eval-expression.