• Spell Checking Comments

    I’m notorious for all the typos I make.1 Thankfully Emacs features an awesome built-in mode named flyspell to help poor typists like me. Flyspell highlights misspelled words as you type (a.k.a. on the fly) and has useful keybindings to quickly fix them.

    Most people typically enable flyspell only for major modes derived from text-mode (e.g. markdown-mode, adoc-mode), but it can really help programmers as well by pointing out typos they make in comments. All you need to do is enable flyspell-prog-mode. I typically enable it for all programming modes2 like this:

    (add-hook 'prog-mode-hook #'flyspell-prog-mode)

    Now you’ll get instant feedback when you make some typo in a comment. To fix a word just press C-c $ (M-x flyspell-correct-word-before-point), while your cursor is behind it.3


    That’s all I have for you today! Keep fixing those nasty typos!

    1. Especially in blog posts. 

    2. At least the well-behaved ones that derive from prog-mode that is. 

    3. There are many other ways to correct misspelled words with flyspell, but we’ll ignore them for now for the sake of simplicity. 

  • Dealing with Jekyll Post URLs

    A while ago I wrote about migrating Emacs Redux from Octopress to Jekyll. While I’m really happy with Jekyll overall, there has always been one thing that frustrated me a bit - namely linking to other posts. The syntax for this is the following:

    {% post_url name-of-post %}

    I know this probably doesn’t seem like a problem, but posts in Jekyll are usually prefixed with a timestamp (e.g. 2019-05-21-some-post ) which makes it really hard to get the name right without consulting the list of posts first. Luckily for us it’s trivial to write an Emacs command that helps with this.

    (defun jekyll-insert-post-url ()
      (let* ((files (remove "." (mapcar #'file-name-sans-extension (directory-files "."))))
             (selected-file (completing-read "Select article: " files nil t)))
        (insert (format "{%% post_url %s %%}" selected-file))))

    Here’s how this command looks like in action:


    I don’t know you, but I’m totally loving this. You can easily extend the core idea for all sorts of similar tasks that require transforming a bit the files in the current directory. Here’s a similar helper for dealing with image URLs:

    (defun jekyll-insert-image-url ()
      (let* ((files (directory-files "../assets/images"))
             (selected-file (completing-read "Select image: " files nil t)))
        (insert (format "![%s](/assets/images/%s)" selected-file selected-file))))

    Let’s see this in action:


    That’s all I have for you today! Meta-X forever!

  • Emacs Prelude Gets a User Manual

    This is going to be a really short post.

    For ages I’ve planned to create a user manual for Emacs Prelude, but I never got to doing so. Writing a good manual is a huge amount of work and I was wary (and lazy) to commit to doing it. Today I realized that probably having some manual (even if it’s not good) beats having no manual, so I quickly sliced and diced the old huge README of the project, and compiled it together into this proto-manual.

    I’ll try to find some time to improve it, but I can make no promises. You can certainly help me out by working on the manual yourselves, though. Prelude is pretty simple, so I assume that everyone, who has spent a bit of time using it, is more than qualified to work on improving its documentation. By the way, the manual features a dedicated section for working on the manual! Coincidence? I don’t think so.

    Keep hacking!

  • The Emacs Year in Review

    This post is a brief summary of the past year for Emacs from my perspective.

  • Convert a Keyword to a Symbol

    Recently I needed to convert keywords into symbols in Emacs Lisp and I noticed there was no built-in function for this, so I’ve decided to build one myself. Here’s my approach:

    (defun keyword-to-symbol (keyword)
      "Convert KEYWORD to symbol."
      (intern (substring (symbol-name keyword) 1)))
    (keyword-to-symbol :foo) ; => 'foo

    It’s extremely simple really - using the fact that keywords in Emacs Lisp are actually symbols we can convert them to a string with symbol-name, drop their leading : and then convert them back to symbols.

    For me the most interesting thing here was learning that keywords are symbols:

    (symbolp :foo) ; => t

    This was certainly a surprise the first time I saw it, although it does make sense. That prompted me to check how are keywords differentiated from symbols and I found the answer in the documentation of keywordp:

    keywordp is a built-in function in ‘C source code’.
    (keywordp OBJECT)
    Return t if OBJECT is a keyword.
    This means that it is a symbol with a print name beginning with ‘:’
    interned in the initial obarray.

    While I doubt that you’ll often (ever?) have to deal with keyword to symbol conversion I hope you’ve learned something fun and useful today! Keep hacking!

  • The Perfect Domain for Emacs Projects

    Recently I’ve been working on documentation sites for a couple of my more prominent Emacs packages - CIDER and Projectile. When I got to the point where I needed to register some domains for the sites I realized that picking the right domain is just as hard as naming things.1

    Most open-source projects typically have .org domains and you’d see here and there the use of .net or (more recently) .io. Those are all great domain options, but they have one slight problem - because they’re super popular there aren’t that many free names to choose from if you decide to use them. That would have forced me to go with domains like or, which are OK, but nothing more. I don’t know about you, but I really hate prefixing domain names!

    After struggling with this for a while an unexpected solution presented itself to me. I was on a short business trip to Mexico and I noticed that the country’s top-level domain is .mx. .mx just like in M-x, Emacs’s most iconic keybinding!2 Needless to say I immediately registered and Such a perfect fit!

    I think that every Emacs projects deserves a Meta-X domain, so get one for your project right away, while there are still plenty of free names to choose from!

    1. OK, nothing is quite as hard as naming, but that’s pretty close. 

    2. One can also argue that M-x sounds a lot like Emacs. I’m reasonably sure the choice of M-x was not accidental. 

  • Eldoc Goes Global

    I recently noticed that Emacs 25.1 had added a global variant of the popular eldoc-mode, called global-eldoc-mode. What’s more - unlike eldoc-mode, global-eldoc-mode is enabled by default!

    This means that you can get rid of all the code in your Emacs config that was wiring up eldoc-mode for major modes that support it:

    ;; That code is now redundant
    (add-hook 'emacs-lisp-mode-hook #'eldoc-mode)
    (add-hook 'ielm-mode-hook #'eldoc-mode)
    (add-hook 'cider-mode-hook #'eldoc-mode)
    (add-hook 'cider-repl-mode-hook #'eldoc-mode)

    There are some reports that global-eldoc-mode is causing performance issues in modes that don’t support it. I’ve never experienced this myself, but if you want to disable it you can simply do so like this:

    (global-eldoc-mode -1)

    Now it’s time to clean up my config! Deleting code always feels so good!

  • An easy-kill

    A bit of Terminology

    Emacs has its own terminology for what’s commonly known as copying, pasting and cutting - namely “saving”, “yanking” and “killing”.1

    On top of this, Emacs has its own internal clipboard called the kill-ring. Items that you save or kill end up there and yanking pulls items out of there.

    The kill-ring is much more than a typical clipboard, but that’s a subject for an entire post itself.

  • Back in Black

    After 3 years of “waiting” for Octopress 31, I’ve decided I waited long enough. Today I (spontaneously) migrated my personal blog and Emacs Redux to a vanilla Jekyll setup and I tweaked a bit their appearance. I’m reasonably pleased with the results and I finally don’t have any excuses not to write.2

    I wrote about my experience moving away from Octopress here. If only I had done this a couple of years ago…

    I realized recently that it has been over 10 years since my first blog post.3 I’ve started my humble writing “career” with Wordpress, then switched to Octopress, and now here we are. One thing never really changed, though - the quality of my writing. It was always abysmally bad, as were many of the topics I wrote on. It’s really fun to look back on all of this - I was reading some of my old articles, in the process of migrating the personal blog to Jekyll, and I couldn’t believe some of the things I wrote. I hope this means I’m getting wiser with age…

    I also realized that this year marked Emacs Redux’s fifth birthday!4 As usual I didn’t manage to achieve the objective I’ve set out of myself when I created it - namely produce 10-20 articles per year for many years to come. The first couple of years were pretty good for the blog, but then a combination of work and personal challenges impacted significantly both my open-source work and my writing.

    Anyways, lately I’ve had this burning desire to share so many thoughts and that really got me excited about writing. Let’s see if I’ll do better this time around, or I’ll simply fail one more time…

    P.S. In the mean time I’ve started another blog, called Meta Redux. I plan to do most of my (serious and creative) writing there, so you might want to check it out.

  • super-save 0.3

    After a long period of no development activity1, super-save gets an update today!

    The latest 0.3 version of your favourite auto-saving library makes it easier to customize the hook triggers (see super-save-hook-triggers) and adds an option to ignore remote (TRAMP) files (see super-save-remote-files).

    As a refresher - super-save will save modified files automatically on certain command (e.g. switch-to-buffer) and hook triggers (e.g. focus-out-hook).

    Both of those are configurable via super-save-triggers and (starting with 0.3) super-save-hook-triggers. Here are a couple of examples:

    ;; add integration with ace-window
    (add-to-list 'super-save-triggers 'ace-window)
    ;; save on find-file
    (add-to-list 'super-save-hook-triggers 'find-file-hook)

    You can now turn off super-save for remote files like this:

    (setq super-save-remote-files nil)

    It seems that now super-save is beyond perfect, so don’t expect the next release any time soon!

    P.S. super-save was extracted from Prelude, but for some reason I actually forgot to add it to Prelude. Today that changes as well!

    1. Mostly because it was perfect from the start. 

  • Projectile goes Turbo

    For a while one of the biggest complaints people had about Projectile was that the alien indexing wasn’t fast enough (especially on big projects). The reason for the (relatively) bad performance was pretty simple - even though Projectile would normally obtain the list of project files pretty fast (e.g. by using git ls-files) it always did some post-processing of the results (e.g. filtering, sorting, etc), which is a very slow operation in Elisp on a big dataset.

    Today I’ve added a new indexing method that simply dispenses with all of the post-processing and gives you the raw power you always craved for. It’s called turbo-alien (yeah, yeah - naming is hard!) and it’s going to be the default indexing method going forward (starting with Projectile 1.1 which should be released pretty soon).

    You can read a bit more about it in Projectile’s manual.

    If you find yourself missing Projectile’s old behaviour just add the following to your config:

    (setq projectile-indexing-method 'alien)

    The old tried and true alien method is still around, it’s just no longer the default.

    P.S. I encourage all of you to help out with some of the open tickets marked with “Help Wanted” or “Good First Issue” here. I’m trying to clean-up shop after a long period of stagnation and I can certainly use some help!

    P.P.S. The recent 1.0 release was just a precursor to some bigger changes I had planned to do for quite a while. Stay tuned for more updates!

    Update Shortly after writing this post I’ve reconsidered the turbo-alien naming and I opted to rename the old alien method to hybrid (as it was truly a hybrid of native and alien indexing), and to change the name of turbo-alien to simply alien. Naming is hard!

  • A Crazy Productivity Boost: Remapping Return to Control (2017 Edition)

    Back in 2013 I wrote about my favourite productivity boost in Emacs, namely remapping Return to Control, which in combination with the classic remapping of CapsLock to Control makes it really easy to get a grip on Emacs’s obsession with the Control key.

    In the original article I suggested to OS X (now macOS) users the tool KeyRemap4MacBook, which was eventually renamed to Karabiner. Unfortunately this tool stopped working in macOS Sierra, due to some internal kernel architecture changes.

    That was pretty painful for me as it meant that on my old MacBook I couldn’t upgrade to the newest macOS editions and on my new MacBook I couldn’t type properly in Emacs (as it came with Sierra pre-installed)… Bummer!

    Fortunately 2 years later this is finally solved - the Karabiner team rewrote Karabiner from scratch for newer macOS releases and recently added my dream feature to the new Karabiner Elements. Unlike in the past though, this remapping is not actually bundled with Karabiner by default, so you have to download and enable it manually from here.

    That’s actually even better than what I had originally suggested, as here it’s also suggested to use CapsLock with a dual purpose as well - Control when held down and Escape otherwise. I have no idea how this never came to my mind, but it’s truly epic! A crazy productivity boost just got even crazier!


  • Intro to CIDER

    CIDER is a popular Clojure programming environment for Emacs.

    In a nutshell - CIDER extends Emacs with support for interactive programming in Clojure. The features are centered around cider-mode, an Emacs minor-mode that complements clojure-mode. While clojure-mode supports editing Clojure source files, cider-mode adds support for interacting with a running Clojure process for compilation, debugging, definition and documentation lookup, running tests and so on.

    You can safely think of CIDER as SLIME (a legendary Common Lisp programming environment) for Clojure - after all SLIME was the principle inspiration for CIDER to begin with. If you’re interested in some historical background you can check out my talk on the subject The Evolution of the Emacs tooling for Clojure.

    Many people who are new to Lisps (and Emacs) really struggle with the concept of “interactive programming” and are often asking what’s the easiest (and fastest) way to “grok” (understand) it.

    While CIDER has an extensive manual and a section on interactive programming there, it seems for most people that’s not enough to get a clear understanding of interactive programming fundamentals and appreciate its advantages.

    I always felt what CIDER needed were more video tutorials on the subject, but for one reason or another I never found the time to produce any. In the past this amazing intro to SLIME really changed my perception of SLIME and got me from 0 to 80 in like one hour. I wanted to do the same for CIDER users! And I accidentally did this in a way last year - at a FP conference I was attending to present CIDER, one of the speakers dropped out, and I was invited to fill in for them with a hands-on session on CIDER. It was officially named Deep Dive into CIDER, but probably “Intro to CIDER” would have been a more appropriate name, and it’s likely the best video introduction to CIDER around today. It’s certainly not my finest piece of work, and I definitely have to revisit the idea for proper high-quality tutorials in the future, but it’s better than nothing. I hope at least some of you would find it useful!

    You might also find some of the additional CIDER resources mentioned in the manual helpful.


  • Pimp My Minibuffer Evaluation

    In Emacs you can evaluate Emacs Lisp pretty much anywhere - even in the minibuffer. Writing Emacs Lisp in the minibuffer, however, is not exactly fantastic experience out-of-the-box - there’s TAB completion, but what about eldoc and paredit for instance?

    If only there was a way to enable them… I suggested one trick in my original post on eval-expression, but Emacs 24.4 made things even easier by adding eval-expression-minibuffer-setup-hook. To enable eldoc for minibuffer evaluations use this snippet:

    (add-hook 'eval-expression-minibuffer-setup-hook #'eldoc-mode)

    For paredit you can use this one:

    (add-hook 'eval-expression-minibuffer-setup-hook #'paredit-mode)

    Obviously you can do the same for any other minor mode you might need.

    The best thing about this setup is that it will work with tools like CIDER and SLIME as well (they have similar commands which allow you to evaluate Clojure & Common Lisp code and those command trigger eval-expression-minibuffer-setup-hook).

  • Look up the keybindings for some command

    If you know the name of some command, but you’ve forgotten its keybinding(s) there are 3 common options to look the keybinding(s) up.

    • C-h f command-name

    This will display some information about the command in question in a help buffer. Important bits of this information include where is the command defined, what are its keybindingings if any, and its documentation.

    • C-h w command-name

    This will display the keybindings of the command in the minibuffer. If you’re interested only in the keybindings you should prefer this option over C-h f.

    • M-x command-name

    After you invoke some command using M-x you’ll see a suggestion to use its keybinding instead in the minibuffer.

    That’s all for now, folks!

  • Disable Annoying Audio Notifications

    By default Emacs has some pretty annoying audio notifications for certain events (e.g. trying to move past the end of a buffer). You’ve got two options to get rid of them. Option 1 is to replace them with visual notifications (the Emacs frame will flash):

    (setq visible-bell t)

    This doesn’t work well on OS X and is just as annoying (if not even more), so I’d suggest going with option 2 instead - disable those notifications completely:

    (setq ring-bell-function 'ignore)

    At last - some peace and quiet!

  • Auto-indent your code with aggressive-indent-mode

    One of the things I hate the most while programming, is having to manually adjust the indentation of some code, after I’ve moved or renamed something in it. While it’s pretty easy to do such re-indent operations using commands like crux-indent-defun or advices like crux-with-region-or-buffer (you remember, crux, right?), there’s an even more efficient way to tackle the issue at hand. Enter aggressive-indent-mode.

    aggressive-indent-mode’s name is a bit of a misnomer - it should probably have been named auto-indent-mode, as this is what it does. When you edit your code it will adjust the indentation automatically. It’s easier to show this than to explain it.

    Here’s one example showing agressive-indent-mode enabled in emacs-lisp-mode:

    lisp example

    And another example using cc-mode:

    c example

    Provided you’ve installed the mode, enabling it for particular major modes is a piece of cake:

    (add-hook 'emacs-lisp-mode-hook #'aggressive-indent-mode)
    (add-hook 'clojure-mode-hook #'aggressive-indent-mode)
    (add-hook 'ruby-mode-hook #'aggressive-indent-mode)

    If you want to enable it in all major modes you can do this as well:

    (global-aggressive-indent-mode 1)

    Note that this is not going to work well with modes like python-mode and haml-mode where the proper indentation can’t be reliably determined. When global-aggressive-indent-mode is enabled it will not affect major modes listed in aggressive-indent-excluded-modes.

    For more info - head over to the project’s readme.

  • Display the Keybinding for a Command with substitute-command-keys

    If you ever need to show the keybinding for a particular command to the users of your package (e.g. you’re adding some tips functionality), you should avoid resisting the urge to write something like this:

    (message "Press <C-c p p> to switch between projects.")

    Why is this a bad idea? Because you might change the keybinding of the command in question (e.g. projectile-switch-project, but you might forget to update messages like this. Is there a better way? substitute-command-keys to the rescue:

    (message (substitute-command-keys "Press <\\[projectile-switch-project]> to switch between projects"))

    This will produce exactly the same message as before and you’re guaranteed the keybinding will always be in sync with the command.


    P.S. If you want to check interactively the keybinding of some command use C-h f (describe-function). Here’s an example - C-h f RET projectile-switch-project RET will produce this:

    projectile-switch-project is an interactive compiled Lisp function.
    It is bound to C-c p p, s-p p, <menu-bar> <tools> <Projectile> <Switch
    to project>.
    (projectile-switch-project &optional ARG1)

    You can also check which command is bound to some key with C-h k.

  • Use Tab to Indent or Complete

    By default in Emacs the Tab key does only indentation. If some major mode provides completion of some form, you normally have to trigger it with M-Tab. In most window managers, however, this keybinding is used to switch between open windows, which makes it a bit hard to use out of the box.

    There’s a simple trick to augment the default Tab behavior. Just put this in your Emacs config:

    (setq tab-always-indent 'complete)

    Now, when you press Tab one time it will indent and if you press it again you’ll get completion candidates. If the indentation at point is already correct you’ll get the completion candidates right away. As an added bonus - you don’t really need M-Tab anymore.

    Simple and neat! One really has to wonder why this isn’t the default behavior.

  • imenu-anywhere

    For the longest time Prelude included the function prelude-goto-symbol (bound to C-c i). It basically allowed you to jump to any definition in the current source file using imenu behind the curtains.

    Recently I’ve found an even better option - the package imenu-anywhere. It works in a pretty similar manner but gives you the ability to jump to any definition in any currently open buffer. That’s quite handy and it greatly reduces the need to use something like etags.

    As an added bonus - imenu-anywhere features helm integration.

    This is a very handy package and I encourage you to give it a go!

    P.S. Prelude users should simply upgrade to the latest version of Prelude (it already uses it).

  • My Personal Emacs Configuration

    From time to time people ask me about my personal Emacs configuration. Other just assume that I use Prelude. For a very long time my personal configuration was pretty similar to Prelude - in a way it was a staging ground for things to go into Prelude eventually (although changes would travel both ways when Prelude users suggest some cool things).

    Recently I’ve decided that in the future I want to do a few things with Prelude:

    • extract as much functionality from it as possible into reusable packages (e.g. super-save and crux)
    • adopt there use-package
    • improve the support for Windows (because now I have Windows computer)

    As part of these efforts I reworked my personal config into something pretty simple (it’s a single init.el file) and I’ve started experimenting with ideas for the future. Stay tuned for the results!

    The config is available here. Perhaps some of you will find something useful there.

  • Remap Return to Control in GNU/Linux

    A long time ago I wrote about remapping Return to Control in OS X. This was the best productivity boost for my Emacs experience ever!

    Recently I’ve bought a Windows ultrabook (wanted something as light as MacBook Air, but more powerful and versatile) and I’m doing most of my work there in a Xubuntu VM. The first thing I did while setting up Xubuntu was to figure out how to do the aforementioned remapping.

    In my original post some people suggested the tool xcape, so I took a look at it. The tool can certainly use some documentation improvements (and pre-built packages), but it gets the job done. After you’ve installed it you just need to add the following to your login shell’s init file (e.g. .bash_profile) and you’re in business:

    xmodmap -e "remove Control = Control_R"
    xmodmap -e "keycode 0x69 = Return"
    xmodmap -e "keycode 0x24 = Control_R"
    xmodmap -e "add Control = Control_R"
    xcape -t 10000 -e "Control_R=Return"

    Obviously the first time around you should source .bash_profile after updating it:

    $ . .bash_profile

    This is definitely a lot more work than just clicking in the GUI of the wonderful Karabiner, but it yields the desired results and that’s what’s important at the end of the day.

    Now if only there was a way to achieve the same result in Windows…

    P.S. vim users will love xcape. Its default behaviour is to generate the Escape key when Left Control is pressed and released on its own.

  • crux

    I’d often blog about some useful utility functions here. Pretty much all of them get included in Emacs Prelude, but I’ve decided I can do one better and extract those of them which are most useful/universal into a separate package.

    This package is crux - a Collection of Ridiculously Useful eXtensions for Emacs.

    You can install it from MELPA and MELPA Stable. Once this is done you just have to pick keybindings for the commands shipped with crux. I’ve suggested some keybindings here. And here’s a small configuration snippet showing how to actually bind keys to some of crux’s commands:

    (global-set-key [remap move-beginning-of-line] #'crux-move-beginning-of-line)
    (global-set-key (kbd "C-c o") #'crux-open-with)
    (global-set-key [(shift return)] #'crux-smart-open-line)
    (global-set-key (kbd "s-r") #'crux-recentf-ido-find-file)
    (global-set-key (kbd "C-<backspace>" #'crux-kill-line-backwards))
    (global-set-key [remap kill-whole-line] #'crux-kill-whole-line)

    crux also ships with some handy advises that can enhance the operation of existing commands.

    For instance - you can use crux-with-region-or-buffer to make a command acting normally on a region to operate on the entire buffer in the absense of a region. Here are a few examples you can stuff in your config:

    (crux-with-region-or-buffer indent-region)
    (crux-with-region-or-buffer untabify)

    So, this is crux for you - simple and neat! I’d love it if you contributed more useful commands to it, so we can make it even more versatile!

  • super-save

    A while back I wrote an article on saving buffers when they lose focus.

    Recently I’ve packaged (an improved version of) this functionality into a tiny global minor mode called super-save.

    The package is available on MELPA and MELPA Stable and enabling it is trivial:

    (super-save-mode +1)

    If you want to enable the additional feature of auto-saving buffers when Emacs is idle, add the following as well:

    (setq super-save-auto-save-when-idle t)

    If you’re like me and don’t care about the backups created by the built-in auto-save-mode, you can disable it aftewards:

    (setq auto-save-default nil)

    I’ve been using Emacs for over 10 years now and I’ve never needed the auto-created backups - I’m either very lucky or this is less useful than it’s supposed to be.

  • ace-jump-mode is Dead, Long Live Avy

    People often ask how am I navigating efficiently Emacs windows and buffers. I have the feeling they expect me to share with them some secrets that would turbo-charge common commands like C-s, M-f, C-x o, etc. I don’t, however, use those commands that much. Ever since I saw that vim’s EasyMotion has been ported to Emacs, I’ve been using that port - namely ace-jump-mode.

    Basically, it allows you to navigate to every visible portion of your Emacs (buffers & windows) with only a handful of keystrokes (usually one two activate it and one or two to get where you want to go). You can see it in action in this excellent video. ace-jump served me well for years, but I’ve had a few gripes with it that were never addressed (multi-char targets, CamelCase support, etc). I would have implemented those myself, if the project was maintained at all, but alas - that’s not the case. Seems I wasn’t the only one who was frustrated with ace-jump, as the prolific Oleh Krehel reimplemented it pretty much from scratch for the purposes of his excellent ace-window library. Once I got wind of this, I managed to persuade Oleh to start distributing his rewrite as a standalone project, which he dubbed avy.

    Avy features everything ace-jump does and more. Apart from the many extra features, its codebase is way cleaner and readable and Oleh is a fantastic and very responsive maintainer. So, as far as I’m concerned ace-jump is now a dead project and pretty much everyone who’s using it should try out avy instead. Their usage and interface are pretty similar, so the learning curve is non-existing. By the way, here’s avy in action:


    And what about my usage of avy? Nothing fancy here - I just bind the commands I consider most important to handy keystrokes.

    (global-set-key (kbd "C-c j") 'avy-goto-word-or-subword-1)
    (global-set-key (kbd "s-.") 'avy-goto-word-or-subword-1)
    (global-set-key (kbd "s-w") 'ace-window)

    avy-goto-word-or-subword-1 is aware of CamelCase words and I do a lot of programming in languages that use those extensively.

    avy has one more thing going for it - it’s part of the default Emacs package repo GNU ELPA, which means that you can install it right away without having to setup any third-party repositories (which you’ll probably need sooner or later).

    avy and ace-window are naturally part of Prelude.

    P.S. Oleh, one of those days you should rename ace-window to avy-window.

  • JDEE Reborn

    JDEE (Java Development Environment for Emacs) used to be best way to develop Java apps in Emacs a while back. It offered a ton of cool features, like smart auto-completion and a debugger. Unfortunately at some point the development slowed down significantly and the project went in a catatonic state. There was pretty much no activity for years in the official SourceForge repo and there was also no support for features introduced in Java 5+.

    Recently, however, the project migrated to GitHub and it’s now way easier to get involved. Seems that some people have already started work on updating JDEE to support modern JDKs and modern Emacs functionality.

    That’s a really exciting project, as Java support has traditionally been a weakness of Emacs and I’m writing this post with the hope that more people will help make JDEE great again.

    So what are you waiting for? If you’re into Java and friends (Scala, Clojure, Groovy, etc), check out the new official repo and let’s get this party started!

  • Mastering Emacs (the First Emacs Book in Over a Decade) is Out

    Mickey Petersen just released Mastering Emacs, the first new book about our beloved editor, since Learning GNU Emacs(released way back in 2004).

    Master Emacs cover

    I haven’t had the time to read the book yet, but being familiar with Mickey’s work I have no doubt it’s outstanding. That’s all from me for now - go buy the book and start mastering Emacs.


    I hope we won’t have to wait another decade for the next great Emacs book.

  • Learning Emacs Lisp

    People who have been using Emacs for a while often develop the desire to learn Emacs Lisp, so they can customize Emacs more extensively, develop extra packages and create the ultimate editing experience, uniquely tailored to their needs & preferences.

    There are a ton of Emacs Lisp resources our there, but most people generally need only one - the official Emacs Lisp manual. It’s bundled with Emacs and you can start reading right away by pressing C-h i m Elisp RET. If you’re relatively new to programming in general you might also check out the Introduction to Emacs Lisp (C-h i m Emacs Lisp Intro RET), before diving into the manual.

    There are also plenty of Emacs Lisp tutorials online, but I’d advise against using them, as most of them have never been updated after originally published and Emacs Lisp keeps evolving all the time (albeit not as fast as I would have liked it to). That being said, Learn Emacs Lisp in 15 minutes is a short and sweet intro to the language. You can find more online educational resources on the EmacsWiki.

    Trust me on this - any time invested in learning Emacs Lisp will be time well spent!

  • Pragmatic Emacs

    I recently noticed a new blog targeting beginner and intermediate Emacs users - Pragmatic Emacs by Ben Maughan.

    If you’re relatively new to Emacs you should definitely check it out. Knowing how vast the Emacs ecosystem is, I’m pretty sure that more experienced Emacs users will also learn a thing or two there.

  • Building MELPA packages locally

    Don’t want to wait for the MELPA packages to be automatically rebuilt? Want to try out some package recipe before submitting it upstream? You can totally do this!

    Just clone the MELPA github repo, open a recipe from it in Emacs and press C-c C-c (bound to the command package-build-current-recipe). Once the package is built you’ll be prompted to install it.

    Pretty neat, right?

  • Emacs on OS X


    In this article I’ll share with you a few tips and tricks about running Emacs under the Max OS X operating system. This article will focus on the vanilla GNU Emacs, but if you want a more native OS X experience you might have a look at the enhanced Emacs Mac port.


    While Emacs is available for installation from various sources I recommend you to use the Emacs for Mac OS X binary distribution.

    I always run the latest development version and I use homebrew to install it:

    $ brew install emacs --HEAD --with-cocoa

    Keep in mind there’s an ancient Emacs 22 that ships with OS X. You might want to alter your PATH, so that the new Emacs is picked up in a shell.

    Alternatively you can just create an alias in your shell and when you invoke emacs it will run the newly installed version:

    $ alias emacs="/Applications/ -nw"

    If you installed via Homebrew that path might look like this:

    $ alias emacs="/usr/local/Cellar/emacs/24.5/ -nw"

    To make it permanent, if using bash, add that line to ~/.bash_profile. zsh users will want to update ~/.zshrc instead.

    In case you’re wondering - nw tells Emacs to start in “terminal” mode (instead of in GUI mode).


    I heartily recommend you to remap your Caps Lock key to Control. This can be easily done via Preferences -> Keyboard -> Modifier Keys. If you’re using a laptop keyboard or the bluetooth keyboard you might want to remap your right Option key to Control as well. No one can use effectively Emacs without a right Control key. Remapping it is a bit more involved and requires the use of the third-party utility Karabiner.

    If you’re adventurous you might even try a crazier idea.

    Setting the PATH variable

    Long story short - if you’re running Emacs from Spotlight (or any other launcher for that matter) your PATH and exec-path variables won’t be same as the ones in your shell (and that’s every nasty since you want be able to run some external programs from Emacs). The best way to handle this would be installing the package exec-path-from-shell by Steve Purcell.


    For flyspell to work correctly you’ll need to install aspell plus a few dictionaries.

    $ brew install aspell --lang=en


    The mighty proced doesn’t work on OS X. You can use vkill as a replacement. It’s kind of basic, but it mostly works.


    OS X ships with BSD’s ls command which doesn’t have all the features of GNU ls (used internally by dired). Fortunately, this is easily solvable:

    $ brew install coreutils

    To avoid conflicts the GNU utils are prefixed with g, so ls becomes gls.

    (setq insert-directory-program (executable-find "gls"))


    Dash is the ultimately API documentation browser. I can’t live without it!

    If you’re using it as well, you might want to install dash-at-point.

    More goodies

    If you want to spare yourself part of the headache of configuring Emacs on OSX and get a lot of extra firepower you might want to install Emacs Prelude - an enhanced Emacs 24.x configuration (developed by yours truly) that should make your experience with Emacs both more pleasant and more powerful.

    P.S. I’d like to hear your tips & suggestions about making the Emacs experience on OS X nicer and more powerful!

  • Clear Comint Buffers

    comint provides Emacs infrastructure for building command interpreters. It’s backing a lot of popular shell/REPL modes - like eshell, inferior-lisp, inf-ruby, inf-clojure, etc.

    comint provides a myriad of built-in commands, but somewhat surprisingly it doesn’t feature a command to clear the contents of a comint buffer. Let’s write one such command ourselves!

    While there are several way to tackle it, I feel this is the simplest (and the one that makes the best use of comint’s existing functionality):

    (defun comint-clear-buffer ()
      (let ((comint-buffer-maximum-size 0))
    ;; let's bind the new command to a keycombo
    (define-key comint-mode-map "\C-c\M-o" #'comint-clear-buffer)

    Simple and elegant, right? One day it might even end up being part of comint itself.

  • Customizing the Fringes

    On graphical displays, each Emacs window normally has narrow fringes (gutters/margins) on the left and right edges. The fringes are used to display symbols that provide information about the text in the window. You can type M-x fringe-mode to disable the fringes, or modify their width. This command affects fringes in all frames; to modify fringes on the selected frame only, use M-x set-fringe-style. You can make your changes to the fringes permanent by customizing the variable fringe-mode.

    Out-of-the-box the most common use of the fringes is to indicate a continuation line. When one line of text is split into multiple screen lines, the left fringe shows a curving arrow for each screen line except the first, indicating that “this is not the real beginning”. The right fringe shows a curving arrow for each screen line except the last, indicating that “this is not the real end”. If the line’s direction is right-to-left, the meanings of the curving arrows in the fringes are swapped.

    Third-party modes like flycheck and diff-hl also make use of the fringe to display valuable information there (e.g. lint and VC information).

    By default both fringes have width 8 pixels, but we can easily adjust this:

    ;; make both fringes 4 pixels wide
    (fringe-mode 4)
    ;; make the left fringe 4 pixels wide and the right disappear
    (fringe-mode '(4 . 0))
    ;; restore the default sizes
    (fringe-mode nil)

    As mentioned before, you can also invoke this command interactively and determine the optimal fringe size for you, before making it permanent in your config. The options presented by the fring-mode command are defined in the fringe-styles list:

    (defconst fringe-styles
      '(("default" . nil)
        ("no-fringes" . 0)
        ("right-only" . (0 . nil))
        ("left-only" . (nil . 0))
        ("half-width" . (4 . 4))
        ("minimal" . (1 . 1)))
      "Alist mapping fringe mode names to fringe widths.
    Each list element has the form (NAME . WIDTH), where NAME is a
    mnemonic fringe mode name and WIDTH is one of the following:
    - nil, which means the default width (8 pixels).
    - a cons cell (LEFT . RIGHT), where LEFT and RIGHT are
      respectively the left and right fringe widths in pixels, or
      nil (meaning the default width).
    - a single integer, which specifies the pixel widths of both

    Be careful when playing with the fringe size. Certain info doesn’t look very good when the fringe is too small (e.g. less than 4 pixels).

  • Lossage

    Are you sure you’re using Emacs in an efficient way? Perhaps you’re overusing commands like C-f and C-b to navigate around when you can be using more efficient alternatives like M-f and M-b (or a third-party package like ace-jump-mode). Gaining such insight is somewhat hard, as we generally don’t pay attention to our sub-optimal usage patterns. If we could only see what were the last few hundred keystrokes we entered in our current Emacs session… Turns out we can do this with the aptly-named command view-lossage (C-h l) (lossage means malfunction). It displays the last 300 keystrokes and its output looks like this:

    n e r a l l y SPC d o n ' t SPC n o t i c e SPC o u
    r SPC s u b o p t i m a l SPC s u a g <backspace> <backspace>
    <backspace> <backspace> u s a g e SPC p a t e <backspace>
    t e r n s . SPC I f SPC w e SPC c o u l d SPC o n l
    y <return> s e e SPC w h a t SPC w e r e SPC t h e
    SPC l a s t SPC f <backspace> h e w SPC <backspace>
    <backspace> <backspace> <backspace> f e w SPC h u n
    d r e d SPC k e y s t r o k e s SPC w e SPC i <backspace>
    e n t e r e d SPC i n SPC o u r SPC c u r r e n t SPC
    E m a c s SPC s e s s i o n . . . SPC T u r n s SPC
    o u t SPC <backspace> SPC w e SPC c a n SPC d o SPC
    t h i s <company-dummy-event> . <backspace> SPC w i
    t h SPC t h e SPC m a c <backspace> g i c a l <backspace>
    <backspace> <backspace> <backspace> <backspace> <backspace>
    <backspace> <backspace> SPC c o m m a n d <return>
    ` v i e w - l o s s a g e ` SPC ( b o u n <backspace>
    <backspace> <backspace> <backspace> ` C - h SPC l `
    ) . C-p C-p M-q C-n C-n C-n C-e C-x b l o s s <return>
    C-x b l o s C-g C-h l

    Inspecting it can be super enlightening! I do this all the time.

  • Uptime

    Many Emacs users keep a single Emacs instance running for quite a while. I’ve had instances running for over a month. How do I know this? Unsurprisingly, there’s a built-in command for that:

    M-x emacs-uptime

    Now it’s time to start bragging to your vim-using friends!

  • Converting Between Symbols and Strings

    Sometimes you might need to convert a symbol to string (or vice versa) in Emacs Lisp. You start looking for functions like symbol-to-string and string-to-symbol but, alas, they do not seem exist. Do not despair! Such functions do actually exist, although their names are likely to surprise you:

    (symbol-name 'some-symbol)
    ; => "some-symbol"
    (intern "some-symbol")
    ; => some-symbol
  • Quickly Open an Info Manual

    Every Emacs user knows that Emacs ships with plenty of built-in documentation in the GNU info format (they don’t call it a self-documenting editor for no reason). Most Emacs users know how to access that built-in documentation with C-h i (M-x info) and some Emacs users even know that the Emacs manual can be opened directly with C-h r (M-x info-emacs-manual).

    If you know the name of the manual you’re looking for, however, there’s a nice little-known alternative to using C-h i - the info-display-manual command. When you run it you’ll be prompted in the minibuffer for the name of the manual you’d like to view (manual name completion is available).

    To give you a more concrete example of the command’s advantage over info let’s try to open the Emacs Lisp manual with both commands. With info you’ll have to type the following:

    M-x info RET m elisp RET

    And the alternative would be:

    M-x info-emacs-manual RET elisp RET

    If you like the command I’d suggest binding it to some keybinding:

    (define-key 'help-command (kbd "C-i") 'info-display-manual)
  • Emacs's Development has Migrated to Git

    The long wait is over - Emacs’s development has finally migrated from bazaar to git.

    Now you don’t have any excuses not to contribute to Emacs!

    If you’re wondering where to start I’d suggest taking a look at this short article.

  • Emacs 24.4

    Emacs 24.4 is finally out!

    You can read about all the new features here. I’ve published a series of articles about some of the more interesting features.

    In related news - the Emacs Mac Port based on 24.4 has also been released.

  • Emacs Lisp Style Guide

    I’ve started working on a community Emacs Lisp style guide. My goal is to create a comprehensive document similar to the Clojure and Ruby community style guides.

    Such a document would be a great starting point for many newcomers to the Emacs community and should increase the overall quality of the code produced by it. There’s much to be documented about code layout, preferred syntactic conventions, major and minor mode definitions, etc. and I obviously can’t know the best practices about everything so I’ll need a lot of help.

    Of course, we already have the official coding guidelines, but they are a bit light on examples, rationale, etc. Hopefully the community style guide will manage to fill any gaps in them and in good time portions of it will find their place in the official documentation.

    I’m inviting all members of our community interested in promoting good Emacs Lisp practices to join the development of this document!

  • A peek at Emacs 24.4: superword-mode

    In a previous post I wrote about camel-case aware editing with subword-mode. Emacs 24.4 adds a complementary minor mode called superword-mode, which also alters the behavior of word-based commands when enabled.

    Normally Emacs would consider underscores and dashes word separators (snake_case and lisp-case anyone?). This affects all word commands - forward-word, backward-word, kill-word, etc. Let’s see a couple of examples (| denotes the cursor position):

    ;; word with dash
    ;; press M-f (forward-word) once
    ;; press M-f again
    ;; press M-b (backward-word) once
    ;; word with underscore
    ;; press M-f once
    ;; press M-f again
    ;; press M-b once
    ;; word in camelCase (assuming subword-mode is not enabled)
    ;; press M-f once
    ;; word in camelCase (assuming subword-mode is enabled)
    ;; press M-f once

    Personally I find the default behavior combined with subword-mode great. I do a lot of Ruby and Lisp programming and it also makes a lot of sense to me to be able to navigate the portions of a complex word, but I guess not everyone feels this way. Enter superword-mode - when it’s enabled all “complex/compound” words are treated as a single word:

    ;; word with dash
    ;; press M-f once
    ;; word with underscore
    ;; press M-f once
    ;; word in camelCase
    ;; press M-f once

    Note that you cannot have subword-mode and superword-mode enabled at the same time. Turning one of them on will disable the other.

    Personally, I don’t see much value in superword-mode as a mode that’s enabled all the time, but I can imagine some useful scenarios in which I’d enable it briefly to do some focused editing.

  • A peek at Emacs 24.4: prettify-symbols-mode

    Emacs 24.4 ships with a new minor mode called prettify-symbols-mode. Its purpose is to replace the standard text representation of various identifiers/symbols with a (arguably) more aesthetically pleasing representation (often a single unicode character would replace several ascii characters).

    A classic example would be lambda from various Lisp dialects that many people prefer to replace with the greek letter λ (small lambda). prettify-symbols-mode allows you to achieve this by relying on a simple mapping expressed in the form of an alist that each major mode must initialize (prettify-symbols-alist). Simply put - major modes have to provide the configuration for prettify-symbols-mode.

    Lisp modes do this via lisp--prettify-symbols-alist:

    (defconst lisp--prettify-symbols-alist
      '(("lambda"  . ?λ)))

    This means that out of the box only lambda will get replaced. You can, of course, add more mappings for different major modes:

    (add-hook 'emacs-lisp-mode-hook
                (lambda ()
                  (push '(">=" . ?) prettify-symbols-alist)))

    Let’s see the mode in action. Consider this bit of Emacs Lisp code:

    (lambda (x y)
      (if (>= x y)

    After you do M-x prettify-symbols-mode you’ll end up with:

    (λ (x y)
      (if ( x y)

    To enable this for a particular mode use (add-hook 'some-mode-hook 'prettify-symbols-mode). If you’d like to enable it globally just add the following to your config:

    (global-prettify-symbols-mode +1)

    By the way, sky is the limit for symbol prettification. One fairly extreme example would be vim’s plugin haskell-conceal+ that goes to great lengths to bring proper mathematical notation to Haskell code. We can achieve more or less the same effect with prettify-symbols-mode, but one have to ask themselves where should we draw the border between tasteful and distasteful prettifications.

  • Configure the Scratch Buffer's Mode

    Pretty much every Emacs user knows of the *scratch* buffer - after all it’s always present when you start your Emacs. If you’ve set inhibit-startup-screen to t (which I recommend) it will even be the very first buffer see each time you fire up your beloved editor (unless you alter initial-buffer-choice, that is).

    The scratch buffer was conceived a scratchpad for notes and Emacs Lisp experiments and a lot of Emacs users find it quite handy. On the other hand - even more users don’t really write Emacs Lisp and probably find little value in this buffer.

    One little know fact about the *scratch* buffer is that its initial major mode (by default it’s lisp-interaction-mode) is not hardcoded and you can alter it. If you’re a Ruby developer you might opt to make it use ruby-mode by default:

    (setq initial-major-mode 'ruby-mode)

    If you do this I’d also advise you to change the buffer’s initial contents. By default they are:

    ;; This buffer is for notes you don't want to save, and for Lisp evaluation.
    ;; If you want to create a file, visit that file with C-x C-f,
    ;; then enter the text in that file's own buffer.

    For Ruby something like this might be better:

    (setq initial-scratch-message "\
    # This buffer is for notes you don't want to save, and for Ruby code.
    # If you want to create a file, visit that file with C-x C-f,
    # then enter the text in that file's own buffer.")

    Or you can simply set initial-scratch-message to nil and be done with it.

  • Travel back and forward in git history

    I recently discovered an extremely cool package called git-timemachine that allows you to step though the git history of the file you’re currently editing in Emacs.

    Using it is pretty simple:

    • visit a git-controlled file and issue M-x git-timemachine (or bind it to a keybinding of your choice)
    • use the following keys to navigate historic version of the file:
      • p visit previous historic version
      • n visit next historic version
      • w copy the hash of the current historic version
      • q exit the time machine buffer

    Here you can see git-timemachine in action:



    This package is bundled with Prelude.

  • Become an Emacs Redux patron

    Securing funding for OS projects and blogs (outside of displaying annoying ads) is a hard endeavor. While I’d love to raise enough cash to work on CIDER, projectile and Emacs itself for an entire year through some wildly successful crowdfunding campaign, that’s unlikely to ever happen.

    That said, I recently discovered an interesting alternative to one-off crowdfunding campaigns called gratipay. Self-described as sustainable crowdfunding (meaning people will get microdonations (say half a buck) from their patrons each week) it seems like a reasonable way to raise a modest sum of money so you could work on open-source projects more than your regular schedule might permit.

    So, if you like Emacs Redux and the Emacs projects in which I’m involved like:

    • Prelude - An Emacs distribution built on top of GNU Emacs 24
    • Projectile - Project Interaction Library for Emacs, that stays out of your way
    • clojure-mode - A major mode for programming in Clojure
    • cider - A Clojure programming environment for Emacs
    • guru-mode - An annoying companion on your journey to Emacs mastery
    • rubocop-emacs - Emacs integration for RuboCop
    • zenburn-emacs - The Zenburn color theme, ported to Emacs
    • solarized-emacs - The Solarized color theme, ported to Emacs
    • puppet-mode - A mode for editing Puppet 3 manifests
    • swift-mode - A mode for editing Swift code

    consider supporting my work via Gratipay.

    Support via Gratipay


    Alternatively you can use PayPal.


  • New Emacs blogs

    The problem with Emacs blogs is one can never have enough of them (especially the good ones).

    I’d like to draw my readers attention to two new blogs:


    lunarsite is not exactly new (it was started in March 2014), but I don’t think enough people have come across it, so I’m mentioning it here anyway. It’s operated by one of the most prolific members of the Emacs community in recent years - the great Sebastian Wiesner (of flycheck and cask fame).

    If you’re thinking of writing your first major mode - you’ll find some great advice there.

    Endless Parentheses

    Endless Parentheses is a brand new blog started by Arthur Malabarba. It’s dedicated to concise posts on improving your Emacs productivity.

    The content so far is similar to the articles I write here, so if you like Emacs Redux you’ll likely enjoy Endless Parentheses as well.

  • Quickly find Emacs Lisp sources

    One thing Emacs users deal all the time is looking for the source of various libraries and function or variable definitions. Typically this involves the use of commands like C-h f (describe-function), C-h v (describe-variable) and C-h k (describe-key) and jumping to the source from the help buffer those commands produce. Let’s see if we can improve upon this workflow.


    Enter the built-in Emacs library find-func. It provides a myriad of useful commands to help us quickly locate sources. Let’s take a brief look at some of them.

    • You can find the source of a library with M-x find-library. If you want to find the source of ido you can do so like this:
    M-x find-library RET ido RET

    I’d suggest binding the command to C-h C-l for quick access:

    (define-key 'help-command (kbd "C-l") 'find-library)
    • You can find the source of a function definition with M-x find-function. Here’s an example:
    M-x find-function RET find-function RET

    I’d suggest binding the command to C-h C-f for quick access:

    (define-key 'help-command (kbd "C-f") 'find-function)

    We can actually do one better - we can directly jump to a command definition using a keybinding of the command with M-x find-function-on-key. Here’s how we can find the source the command bound to C-a (beginning-of-line):

    M-x find-function-on-key RET C-a

    I’d suggest binding the command to C-h C-k for quick access:

    (define-key 'help-command (kbd "C-k") 'find-function-on-key)
    • You can find the source of a variable definition with M-x find-variable. Here’s an example:
    M-x find-variable RET large-file-warning-threshold RET

    I’d suggest binding the command to C-h C-v for quick access:

    (define-key 'help-command (kbd "C-v") 'find-variable)

    The library provides other useful commands as well - like find-function-at-point and find-variable-at-point.

    If you don’t like the keybindings I suggested you can use find-function-setup-keys instead. This will give you keybindings like C-x F, C-x V, C-f K (plus a few extra for commands like find-funtion-other-window).


    Another really cool way to browse Elisp sources (and documentation) is the third-party package elisp-slime-nav. Assuming you’ve installed it already you can enabled it like this:

    (require 'elisp-slime-nav)
    (dolist (hook '(emacs-lisp-mode-hook ielm-mode-hook))
    (add-hook hook 'elisp-slime-nav-mode))

    Once this is done you’ll be able to jump to the source of the Emacs Lisp object at point (function or variable) with M-. (as in SLIME and CIDER for Common Lisp and Clojure respectively) and jump back with M-,. You can also see the description of the object at point using C-c C-d (or C-c C-d d).

    That’s all for today, folks!


    All the suggested keybindings are present out-of-the-box in Prelude. elisp-slime-nav is also enabled out-of-the box in Prelude.

  • MELPA Stable

    We all know and love the MELPA package repository. At least we all know it, but not everyone loves the idea of using package snapshots. Some people would rather use only stable package releases and that’s understandable. Unfortunately the major community repository for stable packages Marmalade is often plagued by technical issues (that should be fixed once its elnode-powered rewrite is ready) and stale packages (due to the fact the sometimes people upload packages they don’t own there and stop updating them after a while).

    Now there’s an alternative to Marmalade, which offers a MELPA-like experience - MELPA stable. It offers stable packages built automatically from git tags, meaning the only thing you have to do to release a new version of a package (assuming there’s a MELPA recipe for it, of course) is to tag the release in git. No more stale packages! No more manual package uploads!

    To use the new repo add this to your Emacs config:

    (add-to-list 'package-archives
    '("melpa-stable" . "") t)

    Currently more than 500 packages are available for installation there. That number is bound to grow (a lot).

    By the way, the maintainers of MELPA are looking for help to update the home page of the stable package archive. Currently it’s the same as the one of the snapshot archive, which is a bit confusing (especially regarding installation instructions). If you’d like to help fork and improve the page’s code on GitHub.

  • Opening Large Files

    I guess everyone has seen the following warning (at some point or another) when trying to open a relatively large file in Emacs:

    File is large (XX.XM), really open?

    By default Emacs will display this warning for every file bigger than 10MB, which is quite annoying (conservative), especially given the fact that on any modern computer even much bigger files will be loaded almost instantaneously and won’t slow down Emacs significantly.

    You can adjust this behavior by altering the value of the large-file-warning-threshold variable. I’d suggest setting it to something like 100MB:

    ;; warn when opening files bigger than 100MB
    (setq large-file-warning-threshold 100000000)

    Alternative, you can set it to nil, which will suppress the warning permanently, regardless of the size of the file you’re trying to open.

    P.S. By the way, it’s not particularly wise to edit huge files (say bigger than 1GB) in Emacs directly. If you need to do something like this I’d suggest taking a look at the excellent vlfi package.

  • Emacs Chat Next Monday

    Next Monday (19.05.2014) I’ll take part in Sacha Chua’s Emacs Chat series. Join us at Google Hangouts and feel free to ask me anything you’d like regarding Emacs.

    See you soon!

  • which-function-mode

    Every developer is sometimes in the following situation - you’re inside the definition of something like a class or method, but the name of the class or method is not currently into view, but you’d very much like to know/see it. You can obviously scroll up and see what you need to, but there’s a simpler way to see the name you’re looking for - the built-in mode which-function-mode.

    When which-function-mode is active you’ll see in the center of your modeline the name of the definition your cursor is currently in. Here’s the mode in action:

    which-func modeline

    And here’s how to enable it:


    That way which-function-mode will be active in all major modes that support it. If you want to enable it only in specific modes you can do so like this:

    (add-to-list 'which-func-modes 'ruby-mode)
    (add-to-list 'which-func-modes 'emacs-lisp-mode)

    By default ??? will be displayed when which-function-mode cannot determine the name (perhaps because you’re not actually in a definition or due to implementation limitations). You can change this to something else like this:

    (setq which-func-unknown "n/a")

    And what if you don’t like to have the definition name displayed in the mode-line? There’s a solution for you as well (suggested by Sebastian Wiesner). Use the following bit of code:

    ;; Show the current function name in the header line
    (setq-default header-line-format
                  '((which-func-mode ("" which-func-format " "))))
    (setq mode-line-misc-info
                ;; We remove Which Function Mode from the mode line, because it's mostly
                ;; invisible here anyway.
                (assq-delete-all 'which-func-mode mode-line-misc-info))

    And you’ll get the following result:

    which-func header

    That’s all for today, folks! Hack Emacs Lisp & prosper!

  • A peek at Emacs 24.4: Variadic Numeric Comparison Functions

    In most Lisps numeric comparison functions like =, <, >, <= and >= are variadic - meaning they accept variable number of arguments (as do functions like +, -, *, etc). Here’s an example:

    ;; let's assume that all those are numeric variables
    (= x y z)
    (< a b c d)

    This is pretty cool and save you from writing code like:

    (and (= x y) (= y z))
    (and (< a b) (< b c) (< c d))

    Prefix function position for the win!

    In Emacs Lisp, however, all these comparison functions (unlike +, -, etc) accept just two arguments, which is somewhat unlispy. Luckily this is one of the things that’s going to change with Emacs 24.4. Emacs Lisp takes another small step to becoming a good Lisp dialect!

  • A peek at Emacs 24.4: Focus Hooks

    A couple of years ago I lamented over the lack of frame focus hooks in Emacs. This prohibited us from implemented a feature like IntelliJ IDEA’s “auto-save on focus lost”, which was kind of frustrating as we’re generally assuming that everything is doable in Emacs!

    All this changes in Emacs 24.4 with the introduction of two new hooks - focus-in-hook and focus-out-hook. The first is triggered when the current frame gains focus and the second when the frame loses focus. So, if we want to save our active buffer when the Emacs frame loses focus we can simply do it like this:

    (add-hook 'focus-out-hook 'save-buffer)

    Or you can go a step further and save all the buffers:

    (add-hook 'focus-out-hook (lambda () (save-some-buffers t)))

    I pretty sure you’ll find other creative ways to apply those new hooks to good use!

  • A peek at Emacs 24.4: delete-duplicate-lines

    Emacs 24.4 introduces the command delete-duplicate-lines.

    By default M-x delete-duplicate-lines will delete all but one copy of any identical lines in the region. So assuming this is the region:


    it will be reduced to this:


    When the command is invoked with a C-u prefix, it searches backwards and keeps the last instance of each repeated line. So this:


    will become:


    Identical lines need not be adjacent, unless you’ve invoked the command with a C-u C-u prefix. When the command is invoked with a C-u C-u C-u prefix, it retains repeated blank lines.

  • A peek at Emacs 24.4: hash-table-keys &amp; hash-table-values

    While Emacs has a pretty good hash-table API, two functions were rather mysteriously absent from it - hash-table-keys and hash-table-values (which would return a list of all keys/values in a hash-table).

    Many people who needed them simply defined them in their code directly (usually in terms of maphash), but that’s no longer necessary in Emacs 24.4, as they are now part of the new built-in library subr-x.

    ;; all functions in the library are defined as inline, so you don't
    ;; need to require the library at runtime
    (eval-when-compile (require 'subr-x))
    (setq h (make-hash-table))
    (puthash "Batman" "Bruce Wayne" h)
    (puthash "Spiderman" "Peter Parker" h)
    (puthash "Superman" "Clark Kent" h)
    (hash-table-keys h)
    ; => ("Batman" "Spiderman" "Superman")
    (hash-table-values h)
    ; => ("Bruce Wayne" "Peter Parker" "Clark Kent")

    Nice and simple.

  • A peek at Emacs 24.4: New string manipulation functions

    Emacs has often been criticized for failing to provide a more extensive string manipulation API (compared to that of programming languages like Ruby and Perl, for instance). As many programs (extensions) running on top of it are doing quite a lot of string manipulation, having a good string API is important. To compensate the lack of certain primitives in Emacs itself a lot of package authors are using these days packages like s.el or simply adding the string functions they need directly to their packages (to reduce the number of third-party deps).

    In Emacs 24.4 finally the situation is improving. Finally, we’re getting string-suffix-p, which was mysteriously missing even though string-prefix-p has been part of Emacs for years:

    (string-suffix-p "test" "my_test")
    ; => t
    (string-suffix-p "tester" "my_test")
    ; => nil

    More importantly, Emacs 24.4 ships with a new built-in library called subr-x, which features a bunch of other string manipulation functions:

    • string-blank-p
    • string-empty-p
    • string-join
    • string-reverse
    • string-trim-left
    • string-trim-right
    • string-trim
    • string-remove-prefix
    • string-remove-suffix

    Here’s a brief demo of them in action:

    ;; all functions in the library are defined as inline, so you don't
    ;; need to require the library at runtime
    (eval-when-compile (require 'subr-x))
    (string-empty-p "")
    ; => t
    (string-empty-p "  ")
    ; => nil
    (string-blank-p "  ")
    ; => 0 (#o0, #x0, ?\C-@)
    (string-reverse "Batman")
    ; => "namtaB"
    (string-join '("one" "two" "three"))
    ; => "onetwothree"
    (string-join '("one" "two" "three") ",")
    ; => "one,two,three"
    (string-trim "   Peter Parker ")
    ; => "Peter Parker"
    (string-remove-prefix "Mr. " "Mr. Smith")
    ; => "Smith"
    (string-remove-suffix "Smith" "Mr. Smith")
    ; => "Mr. "

    Sure, subr-x is not as extensive as s.el (and will never be), but I think that it’s a big step in the right direction. It’s likely that subr-x will be extended in subsequent Emacs versions and some of the functions from it will be promoted to built-in.

    That’s all I have for now. Until next time!

  • A peek at Emacs 24.4: auto-indentation by default

    I’ve written in the past about electric-indent-mode, which was added in Emacs 24.1. In Emacs 24.4 one of the most prominent user visible changes is that it’s enabled out-of-the box. That’s a huge step towards the “modernization” of Emacs and one of the bigger changes to the defaults in recent times. Let’s review briefly how the mode works with a couple of Ruby examples (| signifies the cursor position). Without electric-indent-mode:

    def something|

    After you press Return you’ll get:

    def something

    With it:

    def something|

    After you press Return you’ll get:

    def something

    Nice, ah?

    One problem with electric-indent-mode is that it doesn’t play nice with some (mostly third-party) modes (yaml-mode, slim-mode, etc). I guess the situation will improve over time, but for now you can simply disable the mode in such problematic cases:

    (add-hook 'yaml-mode-hook (lambda () (electric-indent-local-mode -1)))

    Note that electric-indent-local-mode was introduced in Emacs 24.4.

    If you want to make a major mode electric-indent aware, have a look at the documentation of electric-indent-functions and electric-indent-chars.


    Dmitry Gutov recently wrote more on the topic in the context of ruby-mode in Emacs 24.4.

  • ido-vertical-mode

    If you like ido, but don’t like the way it displays the available completion candidates you might want to have a look at ido-vertical-mode.

    I won’t duplicate here the installation instructions, but I’ll show you how ido-vertical-mode displays the completion candidates:


    Is this better than the regular ido? Depends on your personal preference I guess. But it’s good to have options, right?

    That’s all for today, folks! Until next time.

  • A peek at Emacs 24.4: sRGB colours on OS X

    A while ago I wrote about a colour theme problem specific to OS X. Thankfully in Emacs 24.4 the OS X (a.k.a. NS) port of Emacs uses sRGB colours by default (at least on OS X Lion (10.7) and newer), so you’ll no longer need to install Emacs from homebrew (or apply an sRGB colour support patch manually). If for some reason you want to stick to the colours add this to your Emacs config:

    (setq ns-use-srgb-colorspace nil)

    I doubt that anyone would want to do that, but the option is there for those of you who want it.

  • A peek at Emacs 24.4: Rectangular selection

    I’m extremely fond of rectangle editing (the ability to select a rectangular region and apply editing commands only to it), but I’ve always disliked the fact there was no way to visually highlight the exact rectangle region you’ve currently selected. Let’s delete some text in a rectangular region (with C-x r d), so you can see where the problem lies:

    old rectangular selection

    It’s not immediately clear where the rectangle bounds are (it’s clear where the rectangle region starts, but it’s not so clear where it ends), which is a source of constant confusion for many people.

    Emacs 24.4 finally fixed this with the introduction of rectangle-mark-mode (bound by default to C-x SPC). Let’s see it in action:

    new rectangular selection


  • A peek at Emacs 24.4: Smarter show-paren-mode

    Some time ago I wrote about highlighting matching delimiters with show-smartparens-mode. In Emacs 24.4, the built-in show-paren-mode is capable of highlighting more complex paired delimiters as well (like do/end in Ruby for instance). There is one limitation to show-paren-mode (compared to show-smartparens-mode) - it requires that the major mode, that it’s used together with (e.g. ruby-mode), is implemented in terms of the new(ish) SMIE (Simple Minded Indentation Engine). SMIE has been around since 23.3, but hasn’t seen much adoption until quite recently. Prior to Emacs 24.4 very few built-in modes were using it (and just about no third-party major modes). In Emacs 24.4, however, a lot of modes were updated to use SMIE (like ruby-mode), so you’ll be able to enjoy the show-paren-mode improvement with them.

    Here’s a glimpse of the enhanced show-paren-mode in action:


    Long term, I still think that betting on smartparens-mode is a good idea, but if you prefer to stick with built-in modes - show-paren-mode is now more capable than ever.

  • A peek at Emacs 24.4

    Emacs 24.4 is now feature frozen and its release is (probably) just a few months away at this point. This makes it a good time to start talking about some of the exciting and not so exciting changes that will be introduced in it.

    Emacs 24.4 is a special for me, since it’s the first Emacs release to which I contributed code. On a related note - I’ve tracked its development much closer than I used to in previous years and I feel I have lots of interesting things to share with you.

    In a series of smallish posts I’ll highlight some of the many new features that are coming in 24.4. Keep in mind that since we’re talking about unreleased code, there’s the chance of changes in the final version of 24.4.

    By the way, if you’re looking for a brief overview of what to expect in Emacs 24.4 you might have a look at Mickey Petersen’s article on the subject.

    The first article in the series will be arriving momentarily!

    Articles in the Series

    P.S. Emacs 24.4 is fairly stable at this point, so can start using it today. I’ve been using it exclusively for about half an year now and I’ve rarely come across any issues whatsoever. If you’re a Prelude user - it is 24.4 compatible.

  • A crazy productivity boost: Remap Return to Control

    People have always complained about the awkward positioning of the two Control keys on modern keyboards. That’s a fact! Effective Emacs usage is heavily dependent on the Control keys (yep, both of them). That’s also a fact!

    A great many Emacs users remap the infrequently used CapsLock key to Control to alleviate partially the problem with the accessibility of the control keys. That, while useful, is not sufficient for the optimal typing experience, since that way you’re breaking the key symmetry on both sides of your keyboard. Also - your right pinky has to go much further than your left one, while you’re typing. Many people seem to be using only the left Control and I guess they’re not particularly bothered by this, but touch typists like me are generally quite bothered by such things.

    A much better idea would be to leverage a little knows capability of keyboard input systems and map the Return key to Control only when it’s held down (it will behave like a normal Return key in all other situations). This sounds a bit crazy, but please bear with me for a while.

    This radical approach has several advantages. First and foremost - it’s much easier to hit Return with your right pinky than it is to hit the regular right Control (especially if you’re using a US layout keyboard - these have long single row Return keys, compared to the short 2 row Returns found on European keyboards). Second, if you’ve already remapped CapsLock to Control (like you should have done) you’re getting a pretty symmetrical mapping on the opposite side of your keyboard. Last, but not least - it’s a great option for people using compact keyboards with no left Control key.

    Obviously you’ll need some keyboard remapping software to make this trick work. OSX users can use KeyRemap4MacBook to do that. In its settings look up the Change Return section and under it Return to Control_R (+ When you type Return only, send Return). As far as I know this remapping can be done on GNU/Linux systems with xcape (though I haven’t checked that myself), but I have no idea if it’s a viable option for Windows users.

    All in all - remapping Return to Control should be a big productivity win for some (the touch typists) of you and should make your right pinky’s life easier.

  • Highlight matching delimiters with smartparens

    Some time ago I wrote about highlighting matching parentheses with show-paren-mode. This is definitely useful, but it’s kind of restrictive, since parentheses are just a specific kind of paired delimiter. Single and double quotes are also paired delimiters (at least in most programmming languages). In the Ruby programmming language, for instance, do and end also constitute paired delimiter.

    smartparens offers extremely customizable handling of paired delimiters and comes with an extra minor mode called show-smartparens-mode to highlight them. This mode totally replaces show-paren-mode and language specific modes like hirb (which highlights Ruby blocks).

    Assuming you’re already using smartparens, enabling show-smartparens-mode is trivial:

    (show-smartparens-global-mode +1)

    Here’s a glimpse of it in action:


    In Prelude show-paren-mode was replaced by show-smartparens-mode some time ago.

  • Instant Access to Your Shell Init File

    A while ago I showed you a way to instantly edit your Emacs init file. Today we’ll adapt the original idea for shell init files like .bashrc and .zshrc. The code required is fairly short and simple:

    (defun er-find-shell-init-file ()
      "Edit the shell init file in another window."
      (let* ((shell (car (reverse (split-string (getenv "SHELL") "/"))))
             (shell-init-file (cond
                               ((string-equal "zsh" shell) ".zshrc")
                               ((string-equal "bash" shell) ".bashrc")
                               (t (error "Unknown shell")))))
        (find-file-other-window (expand-file-name shell-init-file (getenv "HOME")))))

    The shell init file is deduced from your SHELL env variable. While there are different shell init files for most shell (e.g. .bash_profile, .zshenv, .zprofile), here we’re assuming you’re using the most commonly used files. find-file-other-window will open the file in a window adjacent to the one you’re currently in.

    (global-set-key (kbd "C-c S") #'er-find-shell-init-file)

    er-find-shell-init-file is available in crux (but with a crux- prefix).

  • Removing/Altering Key Bindings from Minor Mode Keymaps

    Often minor modes don’t respect standard keybinding conventions and use some user reserved keys (like C-c a). Occasionally two minor modes would have conflicting keybindings or a minor mode would keybindings conflicting with a major mode. I guess you can imagine similar problems. Dealing with them is fairly straight-forward - we have to either unbind or rebind the offending binding:

    ;; remove keybinding
    (define-key minor-mode-map (kbd "C-c c") nil)
    ;; change keybinding
    (define-key minor-mode-map (kbd "C-c c") (kbd "C-c C-c"))

    Generally speaking you can use define-key to alter the keymap of a major mode as well, but those are rarely offenders when it comes to picking appropriate keybindings for their keymaps.

    Normally you’d want to invoke the above code right after the related minor (or major) mode is loaded:

    (eval-after-load "minor-mode"
      '(define-key minor-mode-map (kbd "C-c c") nil))

    Making a minor mode have different keymaps in different major modes is tricky, but possible. Here’s an example that disables some keybindings in the minor prelude-mode, that are conflicting with the major org-mode:

    (defun my-org-mode-hook ()
      (let ((oldmap (cdr (assoc 'prelude-mode minor-mode-map-alist)))
            (newmap (make-sparse-keymap)))
        (set-keymap-parent newmap oldmap)
        (define-key newmap (kbd "C-c +") nil)
        (define-key newmap (kbd "C-c -") nil)
        (make-local-variable 'minor-mode-overriding-map-alist)
        (push `(prelude-mode . ,newmap) minor-mode-overriding-map-alist))
    (add-hook 'org-mode-hook 'my-org-mode-hook)
  • Dired Jump

    Most Emacs users know that they can start dired (Emacs’s file browser) with M-x dired or C-x d. That would display a prompt in the minibuffer asking which directory to open with dired (the current directory will be suggested as a default).

    More often than not you’ll probably want dired to display the directory of file you’re currently editing. You might even want to have the cursor positioned over that very same file in the dired buffer. There’s a cool command that does exactly that - dired-jump. To use it you have to first load the built-in library dired-x:

    (require 'dired-x)

    You can run the command with C-x C-j (M-x dired-jump). No prompts, no wasted time. You’re instantly teleported to the currently edited file’s position in a dired buffer.

    This command works out-of-the-box in Prelude.

  • A Proper Replacement for Flet

    The popular flet macro was deprecated in Emacs 24.3 and replaced with two similar macros - cl-flet and cl-letf.

    flet was used to temporarily override function definitions. This was an analogue of a dynamically scoped let that operates on the function cell of symbols rather than their value cell.

    The ability to dynamically rebind a functions was very useful for stubbing purposes in unit tests (you do write unit tests, don’t you?).

    (flet ((projectile-project-root () "/path/to/project")
           (projectile-project-name () "project"))

    projectile-project-root and projectile-project-name are impure functions (they depend on the current directory) and testing functions that use them internally would normally be problematic. However, flet gives us the ability to override their actual definitions in our tests. flet’s official replacement cl-flet is lexically bound and this is no longer possible with it.

    Fortunately Nic Ferrier created a true drop-in flet replacement (with some extra magic baked in) - noflet. If you’re missing flet, I suggest you to give noflet a try.

  • Version checks

    Often the code you’re writing would be depending on the version of some external tool (say git) or Emacs itself. Version checks in Emacs are pretty easy - just use the built-in functions version=, version<= or version=.

    Let’s illustrate this with an example. Prelude requires at least GNU Emacs 24.1 to run and on startup it performs the following check:

    (when (version< emacs-version "24.1")
      (error "Prelude requires at least GNU Emacs 24.1"))

    Simple and effective. The version functions are pretty smart and recognize most popular version formats correctly. Note that version string “1” is equal to “1.0”, “1.0.0”, “”, etc. That is, the trailing “.0”s are insignificant. Also, version string “1” is higher (newer) than “1pre”, which is higher than “1beta”, which is higher than “1alpha”. Also, “-CVS” and “-NNN” are treated as alpha versions.

    If you’re writing an Emacs package you can also add an explicit Emacs version dependency in the packge metadata:

    ;; Package-Requires: ((emacs "24.1"))

    That way users of older Emacsen would not see a version of your package targeting newer Emacsen.

  • Search Youtube

    Some time ago I showed you how to do Google queries from Emacs. The approach used in that articles is pretty generic and can be used for the creation of various similar commands. Let’s create a command that searches in YouTube:

    (defun er-youtube ()
      "Search YouTube with a query or region if any."
        (url-hexify-string (if mark-active
                               (buffer-substring (region-beginning) (region-end))
                             (read-string "Search YouTube: "))))))

    This command will display the query results in your default browser.

    I’d suggest binding the command to C-c y if you plan to use it regularly.

    (global-set-key (kbd "C-c y") #'er-youtube)

    youtube is available in Prelude (but with a prelude- prefix).

  • Color Themes: Redux


    This is a slightly refreshed version of an article originally published on my personal blog.

    If there is something that people love as much as tweaking their editing configurations it’s probably the selection of color themes. A good color theme can make your work much more pleasant and a bad one that literally impair your vision. It’s a fact of life that I’m a firm supporter of low-contrast color themes with dark backgrounds - I find them easy on the eyes and I feel that they don’t strain the eyes as much as most themes. I’ve even ported a couple of popular themes to Emacs - Zenburn and Solarized.

    In this short article we’ll see how color theming has changed in Emacs 24 and I’ll share with you a few tips on theme creation and distribution.

  • Increment and Decrement Integer at Point

    While editing you often have to increment or decrement some number (usually an integer) by some step. Obviously this is trivial when the number is something like 10, but not pretty pleasant when the number is 2343566 and you want to increment it by 943. Most of the time, however, you’ll probably be incrementing or decrementing by 1.

    A long time ago I found a bit of code by Ryan Thompson to help us deal with such tasks. Here’s a slightly modified version of the original code:

    (require 'thingatpt)
    (defun thing-at-point-goto-end-of-integer ()
      "Go to end of integer at point."
      (let ((inhibit-changing-match-data t))
        ;; Skip over optional sign
        (when (looking-at "[+-]")
          (forward-char 1))
        ;; Skip over digits
        (skip-chars-forward "[[:digit:]]")
        ;; Check for at least one digit
        (unless (looking-back "[[:digit:]]")
          (error "No integer here"))))
    (put 'integer 'beginning-op 'thing-at-point-goto-end-of-integer)
    (defun thing-at-point-goto-beginning-of-integer ()
      "Go to end of integer at point."
      (let ((inhibit-changing-match-data t))
        ;; Skip backward over digits
        (skip-chars-backward "[[:digit:]]")
        ;; Check for digits and optional sign
        (unless (looking-at "[+-]?[[:digit:]]")
          (error "No integer here"))
        ;; Skip backward over optional sign
        (when (looking-back "[+-]")
            (backward-char 1))))
    (put 'integer 'beginning-op 'thing-at-point-goto-beginning-of-integer)
    (defun thing-at-point-bounds-of-integer-at-point ()
      "Get boundaries of integer at point."
        (let (beg end)
          (setq beg (point))
          (setq end (point))
          (cons beg end))))
    (put 'integer 'bounds-of-thing-at-point 'thing-at-point-bounds-of-integer-at-point)
    (defun thing-at-point-integer-at-point ()
      "Get integer at point."
      (let ((bounds (bounds-of-thing-at-point 'integer)))
        (string-to-number (buffer-substring (car bounds) (cdr bounds)))))
    (put 'integer 'thing-at-point 'thing-at-point-integer-at-point)
    (defun increment-integer-at-point (&optional inc)
      "Increment integer at point by one.
    With numeric prefix arg INC, increment the integer by INC amount."
      (interactive "p")
      (let ((inc (or inc 1))
            (n (thing-at-point 'integer))
            (bounds (bounds-of-thing-at-point 'integer)))
        (delete-region (car bounds) (cdr bounds))
        (insert (int-to-string (+ n inc)))))
    (defun decrement-integer-at-point (&optional dec)
      "Decrement integer at point by one.
    With numeric prefix arg DEC, decrement the integer by DEC amount."
      (interactive "p")
      (increment-integer-at-point (- (or dec 1))))

    The code is based on the popular built-in library thing-at-point and extends it to make it aware of integer numbers. The commands increment-integer-at-point and decrement-integer-at-point operate with a step of 1 by default, but with a prefix argument you can select any step you desire. Unlike other similar commands floating in the Internet, these two handle correctly numbers like -3434 and +343.

    I’d suggest binding these commands to C-c + and C-c -:

    (global-set-key (kbd "C-c +") #'increment-integer-at-point)
    (global-set-key (kbd "C-c -") #'decrement-integer-at-point)

    Both commands are available in Prelude (but with a prelude- prefix).

  • Highlight Comment Annotations

    Programming code is often filled with comment annotations indicating stuff that should be done in the future.

    # REFACTOR: Decouple and clean up this crap.
    def foo
      # crappy code omitted

    Normally Emacs doesn’t highlight such comment annotations, unless you’re using some minor mode like fic-mode. I find such mode overkill given the fact we can cook a pretty decent solution in just about 5 lines of code:

    (defun er-font-lock-comment-annotations ()
      "Highlight a bunch of well known comment annotations.
    This functions should be added to the hooks of major modes for programming."
       nil '(("\\<\\(FIX\\(ME\\)?\\|TODO\\|OPTIMIZE\\|HACK\\|REFACTOR\\):"
              1 font-lock-warning-face t))))
    (add-hook 'prog-mode-hook 'font-lock-comment-annotations)

    And that’s all there is to it. This code is not perfect, since it would highlight FIXME: everywhere in the source code (as opposed to only in comments), but it’s extremely highly unlikely that it’ll appear outside of the source comments anyways.

    As usual Prelude users get this functionally for free out-of-the-box.

  • Make use of the Super key

    Emacs users have a lot of power at their disposal, but in one department they are always short - the number of available non-complex keybindings that they can leverage.

    Obviously nobody likes pressing keybindings like C-p C-v k (or something like that). One way to get your hands on some extra keybindings is to utilize the Super key (it’s the Windows key on Win keyboards and the Command key on Mac keyboards (although most people remap Command to Meta and Option to Super)). One great thing about Super is that you generally have two of them, which makes them touch-typing friend. Since almost no packages use those keys you’re left with plenty of options.

    Prelude defines a bunch of global keybindings that use the Super key.

    ;; make some use of the Super key
    (define-key global-map [?\s-d] 'projectile-find-dir)
    (define-key global-map [?\s-e] 'er/expand-region)
    (define-key global-map [?\s-f] 'projectile-find-file)
    (define-key global-map [?\s-g] 'projectile-grep)
    (define-key global-map [?\s-j] 'prelude-top-join-line)
    (define-key global-map [?\s-k] 'prelude-kill-whole-line)
    (define-key global-map [?\s-l] 'goto-line)
    (define-key global-map [?\s-m] 'magit-status)
    (define-key global-map [?\s-o] 'prelude-open-line-above)
    (define-key global-map [?\s-w] 'delete-frame)
    (define-key global-map [?\s-x] 'exchange-point-and-mark)
    (define-key global-map [?\s-p] 'projectile-switch-project)

    If you find pressing Super comfortable obviously you have the potential to add quite a lot more keybindings to this list.

    P.S. Some keyboards (notably laptop ones) have a Fn key as well that’s also usable in Emacs keybindings. Somewhat funny that key is known in Emacs as Hyper (Star Wars fans are undoubtedly adding a Hyper-Space keybinding to their setups right about now).

  • Advise multiple commands in the same manner

    One of the well known features of Prelude is that it saves buffers with changes in them automatically when you jump between windows. This is achieved with several simple defadvices and without going into many details the advice code for that feature might look like this:

    ;; automatically save buffers associated with files on buffer switch
    ;; and on windows switch
    (defadvice switch-to-buffer (before switch-to-buffer-auto-save activate)
    (defadvice other-window (before other-window-auto-save activate)
    (defadvice windmove-up (before other-window-auto-save activate)
    (defadvice windmove-down (before other-window-auto-save activate)
    (defadvice windmove-left (before other-window-auto-save activate)
    (defadvice windmove-right (before other-window-auto-save activate)

    Ouch - that a lot of redundant code! Luckily we can take care of the redundancy by introducing a macro to generate multiple advices with the same body:

    (defmacro er-advise-commands (advice-name commands &rest body)
      "Apply advice named ADVICE-NAME to multiple COMMANDS.
    The body of the advice is in BODY."
         ,@(mapcar (lambda (command)
                     `(defadvice ,command (before ,(intern (concat (symbol-name command) "-" advice-name)) activate)

    Looks a bit scary, doesn’t it? But it allows us to reduce the original code down to:

    ;; advise all window switching functions
    (er-advise-commands "auto-save"
                        (switch-to-buffer other-window windmove-up windmove-down windmove-left windmove-right)

    macroexpand can show us how the macro gets expanded:

    (macroexpand '(er-advise-commands "auto-save"
                     (switch-to-buffer other-window windmove-up windmove-down windmove-left windmove-right)
      (defadvice switch-to-buffer
        (before switch-to-buffer-auto-save activate)
      (defadvice other-window
        (before other-window-auto-save activate)
      (defadvice windmove-up
        (before windmove-up-auto-save activate)
      (defadvice windmove-down
        (before windmove-down-auto-save activate)
      (defadvice windmove-left
        (before windmove-left-auto-save activate)
      (defadvice windmove-right
        (before windmove-right-auto-save activate)

    Obviously if we want the macro to be truly universal we should factor out the hardcoded before and activate defadvice params, but that’s beside the point. The point is that when you need to generate some code Emacs Lisp’s macros have your back.

  • Go To Column

    Almost every Emacs user knows that M-g M-g and M-g g (both bound to go-to-line) will take them to the line of his choosing (provided they knows the number of the target line, of course).

    Surprisingly few Emacs users know that there is a similar way to jump to a column by its number - M-g TAB (bound to move-to-column). Interactively you cannot jump past the end of the line you’re currently on, but you can always cook your own version of the command to get around that limitation:

    (defun er-go-to-column (column)
      (interactive "nColumn: ")
      (move-to-column column t))

    Let’s bind that to some keycombo:

    (global-set-key (kbd "M-g M-c") #'er-go-to-column)
  • Locate

    locate is one extremely popular Unix command that allows you to search for files in a pre-built database.

    One little know fact is that Emacs provides a wrapper around the command you can invoke with M-x locate. You’ll be prompted to enter a search string and you’ll be presented with a list of matching filenames from locate’s database. Many of dired keybindings are available in the results buffer (which will be using locate-mode major mode).

    If you’d like you may change the command invoked by Emacs to supply the results by altering the locate-command variable. Here’s how you can start using OS X’s mdfind (the command-line interface to Spotlight) instead of locate:

    (setq locate-command "mdfind")

    Obviously any command that takes a string argument and returns a list of files would do here. In all likelihood you’ll never want to use anything other than the default locate command, though.

  • Boost Performance by Leveraging Byte-compilation

    Emacs’s Lisp interpreter is able to interpret two kinds of code: humanly readable code (stored in files with .el extension) and machine optimized code (called byte-compiled code), which is not humanly readable. Byte-compiled code runs faster than humanly readable code. Java or .NET developers should already be familiar with the concept of byte-code, since it’s pretty central on those platforms.

    You can transform humanly readable code into byte-compiled code by running one of the compile commands such as byte-compile-file. The resulting byte-code is stored into .elc files. One can also byte-compile Emacs Lisp source files using Emacs in batch mode.

    Here’s how you can compile everything in your .emacs.d folder:

    emacs -batch -f batch-byte-compile ~/.emacs.d/**/*.el

    Of course we can easily create an Emacs command that does the same thing:

    (defun er-byte-compile-init-dir ()
      "Byte-compile all your dotfiles."
      (byte-recompile-directory user-emacs-directory 0))

    user-emacs-directory is an Emacs variable that points to your init dir (usually ~/.emacs.d on UNIX systems). This command will recompile even files that were already compiled before (meaning a file with the same name and the .elc extension instead of .el existed). You can try the new command with M-x byte-compile-init-dir.

    You have to keep in mind that Emacs will load code from the .elc files if present alongside the .el files, so you’ll have to take steps to ensure you don’t have stale .elc files lying around. I’d suggest the following solution:

    (defun er-remove-elc-on-save ()
      "If you're saving an Emacs Lisp file, likely the .elc is no longer valid."
      (add-hook 'after-save-hook
                (lambda ()
                  (if (file-exists-p (concat buffer-file-name "c"))
                      (delete-file (concat buffer-file-name "c"))))
    (add-hook 'emacs-lisp-mode-hook 'er-remove-elc-on-save)

    This code will make Emacs delete the some_file.elc file, every time the some_file.el file in the same folder is saved.

    A couple of closing notes:

    • If you don’t have any custom computationally intensive defuns in your init directory - it probably doesn’t make sense to byte-compile it.
    • Packages installed via package.el will be automatically byte-compiled during the installation process.

    The code presented here is part of Prelude. As a matter of fact Prelude will byte-compile itself during the installation process (if you used the installation script, that is). Prelude will also recompile itself when M-x prelude-update is invoked.

  • Eval and Replace

    Sometimes people tend to overlook how well Emacs and Emacs Lisp are integrated. Basically there is no limit to the places where you can evaluate a bit of Emacs Lisp and reap the associated benefits. From time to time I find myself editing something and thinking - “Hey, it’d be really great of I could just insert the result of some Emacs Lisp expression at point!” (my thoughts are pretty crazy, right?). Here’s a contrived example - I might have to enter somewhere the result of 1984 / 16. I can calculate that manually or I can fire up M-x calc and get the result, or I can play extra smart and devise the following command (which I did not actually devise - I’m pretty sure I saw it in someone else’s config a while back):

    (defun eval-and-replace ()
      "Replace the preceding sexp with its value."
      (condition-case nil
          (prin1 (eval (read (current-kill 0)))
        (error (message "Invalid expression")
               (insert (current-kill 0)))))

    Let’s bind that to C-c e:

    (global-set-key (kbd "C-c e") 'eval-and-replace)

    Now in the buffer I’m currently editing I can type (/ 1984 16) and press C-c e afterwards getting the result 124 replace the original expression. Pretty neat!

    I’ll leave it up to you to think of more creative applications of the command.

    This command is part of Prelude(it’s named prelude-eval-and-replace there).

  • Deleting Windows

    Every Emacs user knows that he can split the current window horizontally (with C-x 2) and vertically (with C-x 3) as much as he desires to. However, some Emacs users don’t know what to do with the extra windows they’ve created when they do not them.

    To delete the selected window, type C-x 0 (delete-window). Once a window is deleted, the space that it occupied is given to an adjacent window (but not the minibuffer window, even if that is the active window at the time). Deleting the window has no effect on the buffer it used to display; the buffer continues to exist, and you can still switch to with C-x b or any other buffer navigation command.

    C-x 4 0 (kill-buffer-and-window) is a stronger (and fairly unknown) command; it kills the current buffer and then deletes the selected window (basically it combines C-x k and C-x 0). Obviously it’s a good idea to use it on windows displaying buffers you’re no longer needing.

    C-x 1 (delete-other-windows) deletes all the windows, except the selected one; the selected window expands to use the whole frame. (This command cannot be used while the minibuffer window is active; attempting to do so signals an error.) In the era of narrow screens I used that command fairly often when I needed to focus on a particular task. Now I keep my screen split in half vertically 99% of the time, but I still use C-x 1 from time to time when I’m about to resplit my screen in some uncommon way.

    Windows displaying help buffers (generally created with commands like C-h ...) warrant a special mention. They can be deleted with a single keystroke - q. That would delete the help window altogether if it was created by the help command, or restore its original content if the window existing beforehand and was reused by the help command.

  • Open line above

    This post continues a topic that was introduced in smarter open-line few months back.

    Often when editing code one wishes to open a line just above the current one, which is properly indented relative to the existing code, and position the cursor at its beginning. Such a feature is present in most IDEs, such as IntelliJ IDEA, Eclipse and NetBeans. It’s sometimes bound to Control+Shift+Enter. Last time I showed you how to implement a similar function called smart-open-line, this time will implement smart-open-line-above. Just add this snippet to your .emacs (or .emacs.d/init.el or whatever):

    (defun smart-open-line-above ()
      "Insert an empty line above the current line.
    Position the cursor at it's beginning, according to the current mode."
      (move-beginning-of-line nil)
      (forward-line -1)
    (global-set-key [(control shift return)] 'smart-open-line-above)

    Evaluate the code (or restart Emacs) and you’ll be able to use M-x smart-open-line-above or Control+Shift+Enter (aka C-S-return).

    Admittedly this keybinding kind of sucks, so here’s another option for you - M-o (used by default as the prefix for some font setting commands nobody ever uses) for smart-open-line and M-O for smart-open-line-above.

    (global-set-key (kbd "M-o") 'smart-open-line)
    (global-set-key (kbd "M-O") 'smart-open-line-above)

    Another good option would be to fold the two commands into one and use a prefix argument to trigger the opening a new line above the current one.

    This command is part of Prelude(it’s named prelude-smart-open-line-above there).

  • Using Emacs as a Database Client

    Most people that use Emacs are programmers - that’s a fact! Most programmers have to deal with relational databases - that’s also a fact!

    Programmers often interact with the database they have to use via some dedicated client - be it a console or a GUI one. One fairly little known fact about Emacs is that it features a mode that wraps around terminal database clients, called SQLi. The mode allows you to interact with a relational database from the comfort of Emacs. Sure, you can run a terminal client like psql directly from ansi-term (for instance) as well - but if you’re using a client with no readline support (like the default clients for Oracle and DB2) you’ll certainly appreciate SQLi.

    Let’s play a bit with SQLi. To create a PostgreSQL connection start by running M-x sql-postgres. You’ll be prompted for username, database, password and host and then you’ll be dropped in a buffer dedicated to the connection you’ve specified. Apart from being able to run all sorts of SQL in that buffer you’ll also be able to send to it SQL from .sql files you’re editing in Emacs.

    Let’s see how you can do that in a bit more detail. First you have to associated an SQL file with a connection. While in some .sql file execute M-x sql-set-product and type postgres. Afterwards do M-x sql-set-sqli-buffer and select the name of the connection buffer you want to use (it’s probably called *SQL* if you have only one connection buffer). Now you’ll be able to use commands like sql-send-region (C-c C-r) from the .sql buffer and the code from the region will be executed in the associated connection buffer.

    Have a look at the documentation of sql-mode for further details.

  • Continue a comment on the next line

    When writing code from time to time we have to write comments as well. Most of the time programmers are using single-line comments, denoted by some special starting character(s), like #, //, etc. When you want to write a few lines of comments in Emacs you have two options:

    Option A

    • Write the first line of the comment.
    • Go to the next line.
    • Insert the comment delimiter.
    • Continue writing the comment.

    Option B (editor’s choice)

    • White the first line of the comment.
    • Press M-j (indent-new-comment-line).
    • Continue writing the comment on the second line.

    The command breaks the line at point and indents the following line, continuing the comment if invoked within one. The indentation on the second line matches the indentation on the first line.

    # first line
    #     indented line|(we press `M-j` here)
    #     |(we get here after pressing `M-j`)

    This command is intended for styles where you write a comment per line, starting a new comment (and terminating it if necessary) on each line. If you want to continue one comment of the type /* */ across several lines, use C-j (newline-and-indent).

    Outside of comments M-j behaves pretty much the same way as C-j.

  • Highlight Lines that Exceed a Certain Length Limit

    When you’re writing code you usually have to take into account the programming language’s convention for maximum line length. Most programming languages urge hackers to keep line length under 80 characters(although in recent years it has often been argued that such rules should be relaxed to 100-120 characters, given the state of current computer displays).

    There are many ways to highlight lines that exceed a certain length in Emacs, but I find one to be particularly elegant - the use of the built-in whitespace-mode. Most people use whitespace-mode to visualize spaces, tabs and trailing whitespace, but it can actually do a bit more that that. Here’s the magic config:

    (require 'whitespace)
    (setq whitespace-line-column 80) ;; limit line length
    (setq whitespace-style '(face lines-tail))
    (add-hook 'prog-mode-hook 'whitespace-mode)

    The above snippet will enable whitespace-mode only in major modes for programming. If you want to enable whitespace-mode everywhere you might want to do this instead:

    (global-whitespace-mode +1)

    whitespace-line-count determines that maximum line length; feel free to set this to whatever value suits you. whitespace-style determines what kind of stuff whitespace-mode is going to highlight. At this example we want to highlight only the part of lines exceeding the line length limit. Take a look at whitespace-style’s documentation for more details(C-h v RET whitespace-style).

    Here’s the result:

    long lines

    It will probably come as no surprise that this functionality is enabled out-of-the-box in Prelude.

  • Joining lines

    Often, while editing, you’ll want to compress a few lines into one. Here’s a simple example to illustrate the problem at hand. We want to convert this bit of Ruby code:



    some_method(arg1, arg2, arg3)

    Doing so is extremely easy. Just go to the last line in the first code block and press 3 times M-^ (delete-indentation, aliased also to join-line).

    If you’re like me and like to join lines from top to bottom - go to the first line and press C-u M-^ three times. This works, but it is kind of hard to press C-u M-^ repeatedly, compared to just M-^. Let’s simplify this a bit:

    (defun top-join-line ()
      "Join the current line with the line beneath it."
      (delete-indentation 1))

    Isn’t this a top way to join lines or what?

    Since delete-indentation is bound both to M-^ it makes sense to use something like C-^ for the new command:

    (global-set-key (kbd "C-^") 'top-join-line)

    That’s mostly a personal preference I guess - feel free to use any other keycombo.

    This command is part of Prelude(it’s named prelude-top-join-line there) and it’s bound to C-^ there.

  • Smarter navigation to the beginning of a line

    In Emacs there are two essential commands when you have to go the beginning of a line - move-beginning-of-line(bound to C-a) and back-to-indentation(bound to M-m). The first takes you to the first column of a line and the latter takes you the first non-whitespace character on a line.

    Generally, I find back-to-indentation more useful, but occasionally it makes sense to go to the real beginning of a line as well. What doesn’t make sense is to have to think all the time what command is the most appropriate in a particular situation. Wouldn’t it be great if C-a initially took you to the first non-whitespace char(as back-to-indentation does) on a line, and if pressed again took you to the actual beginning of the line? It would be! Let’s get it done:

    (defun smarter-move-beginning-of-line (arg)
      "Move point back to indentation of beginning of line.
    Move point to the first non-whitespace character on this line.
    If point is already there, move to the beginning of the line.
    Effectively toggle between the first non-whitespace character and
    the beginning of the line.
    If ARG is not nil or 1, move forward ARG - 1 lines first.  If
    point reaches the beginning or end of the buffer, stop there."
      (interactive "^p")
      (setq arg (or arg 1))
      ;; Move lines first
      (when (/= arg 1)
        (let ((line-move-visual nil))
          (forward-line (1- arg))))
      (let ((orig-point (point)))
        (when (= orig-point (point))
          (move-beginning-of-line 1))))
    ;; remap C-a to `smarter-move-beginning-of-line'
    (global-set-key [remap move-beginning-of-line]

    The command will keep toggling between the first non-whitespace char and the beginning of the line when invoked.

    Here’s a visual example(| is the cursor):

    This is a short example
        # pressing C-a once
        # pressing C-a again
    |   text
        # pressing C-a again

    This functionality could also be implemented with defadvice, but I tend to avoid their use.

    smarter-move-beginning-of-line is part of Prelude.

    P.S. The credit for this tip goes to Sebastian Wiesner.

  • Delete whitespace around point

    One task that often pops when editing text or code is the need to remove some extra whitespace around the point(the cursor). Emacs has your back!

    First, we have the command delete-horizontal-space(bound to M-\) - it deletes all spaces and tabs around the point. With a prefix argument(C-u M-\) the command deletes only the whitespace before the point.

    One similar, although a bit less known, command is just-one-space(bound to M-SPC) - it deletes all spaces and tabs around the point, leaving just one space (or N spaces if you supply N as a prefix argument like C-4 M-SPC). If N is negative, the command deletes newlines as well, leaving -N spaces.

    One minor snafu with just-one-space is that M-SPC is a no-go on OSX since just about everyone uses it for quick access to Spotlight or switching between languages. You might want to use a different keybinding like this one:

    (global-set-key (kbd "C-c j") 'just-one-space)

    Personally, of the two commands I find just-one-space the more useful.

    In Prelude just-one-space is additionally bound to the kk keychord.

  • Instant Access to init.el

    One of the files Emacs users often edit is init.el(especially if they are having all of their configuration inside of it). It might be sensible then to develop a faster way to access init.el:

    (defun er-find-user-init-file ()
      "Edit the `user-init-file', in another window."
      (find-file-other-window user-init-file))

    user-init-file holds the path to your init.el. For mine its value is /Users/bozhidar/.emacs.d/init.el. find-file-other-window will open the file in a window adjacent to the one you’re currently in.

    Short and sweet! You might want to bind it to some keycombo:

    (global-set-key (kbd "C-c I") #'find-user-init-file)

    Thanks to Sebastian Wiesner for bringing this tip to my attention!

  • Whitespace cleanup

    Good developers are very careful about the proper use of whitespace in their files - there should be no empty lines at the beginning of a file, no empty lines at the end of a file, no trailing whitespace, no mixture of tabs and spaces, etc.

    Emacs, naturally, wants to help with every problem possible and provides a very nice solution in the form of the whitespace-cleanup command. It’s a much more powerful alternative to the older delete-trailing-whitespace command, that simply deletes trailing whitespace, and it’s aware of the whitespace-style variable, used by whitespace-mode.

    It usually applies to the whole buffer, but in transient-mark-mode when the mark is active, it applies to the region. It also applies to the region when it is not in transient mark mode, the mark is active and C-u was pressed just before calling whitespace-cleanup interactively. There is also a similar command called whitespace-cleanup-region.

    The problems cleaned up are (borrowed from the official documentation):

    1. Empty lines at beginning of buffer.

    2. Empty lines at end of buffer. If whitespace-style includes the value empty, remove all empty lines at beginning and/or end of buffer.

    3. 8 or more SPACEs at beginning of line. If whitespace-style includes the value indentation: replace 8 or more SPACEs at beginning of line by TABs, if indent-tabs-mode is non-nil; otherwise, replace TABs by SPACEs. If whitespace-style includes the value indentation::tab, replace 8 or more SPACEs at beginning of line by TABs. If whitespace-style includes the value indentation::space, replace TABs by SPACEs.

    4. SPACEs before TAB. If whitespace-style includes the value space-before-tab: replace SPACEs by TABs, if indent-tabs-mode is non-nil; otherwise, replace TABs by SPACEs. If whitespace-style includes the value space-before-tab::tab, replace SPACEs by TABs. If whitespace-style includes the value space-before-tab::space, replace TABs by SPACEs.

    5. SPACEs or TABs at end of line. If whitespace-style includes the value trailing, remove all SPACEs or TABs at end of line.

    6. 8 or more SPACEs after TAB. If whitespace-style includes the value space-after-tab: replace SPACEs by TABs, if indent-tabs-mode is non-nil; otherwise, replace TABs by SPACEs. If whitespace-style includes the value space-after-tab::tab, replace SPACEs by TABs. If whitespace-style includes the value space-after-tab::space, replace TABs by SPACEs.

    It might be a good idea to add whitespace-cleanup to your before-save-hook so that every buffer would be cleaned up before it’s saved:

    (add-hook 'before-save-hook 'whitespace-cleanup)

    For programming languages that rely on tabs being tabs you should enable indent-tabs-mode (as noted above). Here’s an example for makefile-mode:

    (add-hook 'makefile-mode-hook 'indent-tabs-mode)

    Prelude adds whitespace-cleanup to before-save-hook by default.

  • Keep Backup and Auto-save Files Out of the Way

    Emacs has two helpful features, called auto-backup and auto-save (or at least I call them this way).

    Auto-backup is triggered when you save a file - it will keep the old version of the file around, adding a ~ to its name. So if you saved the file foo, you’d get foo~ as well.

    auto-save-mode auto-saves a file every few seconds or every few characters (both settings are configurable - auto-save-interval is set to 300 characters by default and auto-save-timeout is set to 30 seconds). The auto-save files have names like #foo# and are deleted automatically when you manually save a file.

    Although the modes are definitely useful, many Emacs users find the extra files they create quite annoying(especially since they rarely resort to using them) and disable both feature to get rid of the pesky unwanted files:

    ;; disable auto-save and auto-backup
    (setq auto-save-default nil)
    (setq make-backup-files nil)

    Even though I’ve never actually had any use of those backups, I still think it’s a bad idea to disable them.1 I find it much more prudent to simply get them out of sight by storing them in the OS’s tmp directory instead.

    ;; store all backup and autosave files in the tmp dir
    (setq backup-directory-alist
          `((".*" . ,temporary-file-directory)))
    (setq auto-save-file-name-transforms
          `((".*" ,temporary-file-directory t)))

    Now they won’t annoy you constantly, but they will still be around if you need them. Some OSes delete everything in their tmp directories on restart, so if this worries you - consider using another directory.

    Prelude keeps auto-backup and auto-save files in tmp by default.

    1. Most backups are eventually useful. 

  • Erase Buffer

    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:

    ;; 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:

    (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

    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.

  • Manage Processes with proced

    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):

    (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 OS X user. Unfortunately proced does not work on OS X (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

    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:

    (defun visit-ielm ()
      "Create or visit a `ielm' buffer."
      (if (not (get-buffer "*ielm*"))
            (split-window-sensibly (selected-window))
            (other-window 1)
        (switch-to-buffer-other-window "*ielm*")))

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

    (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:

    (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))
            (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."
      (start-or-switch-to (lambda ()
                             (ansi-term (getenv "SHELL")))
    (defun visit-ielm ()
      "Switch to default `ielm' buffer.
    Start `ielm' if it's not already running."
      (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

    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:

    ;; 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

    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:

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

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

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

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

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

    The command and its key chord are part of Prelude.

  • Custom config for shells

    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/

    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

    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).

    ;; 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

    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).

  • Evaluate Emacs Lisp in the Minibuffer

    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:

    (defun er-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 'er-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.

  • Delete selection on insert

    It most text editors if you select a piece of text and press any key(that’s not bound to some command) the selection would be replaced by the character bound to the key(or deleted if you press Backspace). In Emacs things look differently - by default typed text is just inserted at point, regardless of any selection.

    Of course, there is a way to change this:

    (delete-selection-mode +1)

    Now when transient-mark-mode is also enabled(it is enabled by default since Emacs 23) any typed text replaces the selection if the selection is active.

    Personally I find this behavior more useful than the default one. That’s why it should be no surprise that delete-selection-mode is enabled by default in Prelude.

  • Kill whole line

    Let’s continue our exploration of the fascinating topic of killing lines. Apart from killing lines from the cursor to the end of the line(kill-line) and killing lines from the cursor back to the beginning of the line(kill-line with a 0 prefix argument) you can also kill entire lines with a single command - kill-whole-line.

    The command is bound to C-S-Backspace by default and kills the line including its newline. With a prefix argument, it will kill that many lines starting from the current line. If the argument is negative it will kill that many lines backward plus the preceding newline. If the argument is 0, it will kill the current line but exclude the trailing newline. We can improve the command a bit by making it indentation aware(like we did for backward kill line in the previous post):

    (defun smart-kill-whole-line (&optional arg)
      "A simple wrapper around `kill-whole-line' that respects indentation."
      (interactive "P")
      (kill-whole-line arg)

    Now we can rebind C-S-Backspace.

    (global-set-key [remap kill-whole-line] 'smart-kill-whole-line)

    remap is a pretty neat trick in its own right; maybe I’ll write a bit more about it in the future.

    The smart-kill-whole-line command is available out-of-the-box in Prelude.

  • Kill line backward

    Emacs does not have a command backward-kill-line(which would kill the text from the point to the beginning of the line), but it doesn’t really need one anyways. Why so? Simple enough - invoking kill-line with a prefix argument 0 does exactly the same thing!

    C-0 C-k
    M-0 C-k
    C-u 0 C-k

    Take your pick! If you’d rather have a quicker way to do backward line killing you might consider rebinding C-Backspace or M-Backspace(both are bound to backward-word-kill by default). Personally I always do word killing with M-Backspace, so I favor rebinding C-Backspace.

    (global-set-key (kbd "C-<backspace>") (lambda ()
                                            (kill-line 0)))

    This command can be further improved if killing backward factors the current indentation level:

    (global-set-key (kbd "C-<backspace>") (lambda ()
                                            (kill-line 0)

    Thanks to Steve Purcell for suggesting a similar command in the comments.

    The C-Backspace keybinding is available out-of-the-box in Prelude.

  • Display visited file's path in the frame title

    I’m fond of seeing somewhere the full path to the file I’m currently editing(as opposed to just the file name displayed in modeline). Emacs’s frame title seems like a good place to display such information, since by default it doesn’t show anything interesting. Here’s how we can achieve this:

    (setq frame-title-format
          '((:eval (if (buffer-file-name)
                       (abbreviate-file-name (buffer-file-name))

    The path will be displayed in an abbreviated manner(/home/bozhidar/ will be shortened to just ~/). If you’d like to see the expanded path just remove the abbreviate-file-name function invocation. If a buffer is not visiting a file, the buffer’s name would be displayed instead.

    Prelude sets frame-title-format like this by default.

  • Recently Visited Files

    Emacs does not keep track of recently visited files by default. Sad, but true. On a more positive note - it has the feature (courtesy of the built-in recentf package), but it’s simply not enabled out-of-the-box. Let’s see what we can do to change that:

    (require 'recentf)
    (setq recentf-max-saved-items 200
          recentf-max-menu-items 15)
    (recentf-mode +1)

    That wasn’t that hard. Now Emacs will keep track of the last 200 files we visited and will show the last 15 of them in the File->Open recent(this menu entry is added by recentf) menu. That’s it.

    At this point you’re probably feeling let down. After all - who uses the menu bar in Emacs anyways? Fortunately there is also a command named recentf-open-files. Upon invoking it with M-x recentf-open-files you’ll be presented with a list of all recently visited files.

    If you’re an ido user you might prefer to use some command based on it instead. Here’s one:

    (defun er-recentf-ido-find-file ()
      "Find a recent file using ido."
      (let ((file (ido-completing-read "Choose recent file: " recentf-list nil t)))
        (when file
          (find-file file))))

    I’d suggest binding whichever command you prefer to either C-c f or C-x C-r (bound by default to the infrequently used find-file-read-only command):

    (global-set-key (kbd "C-c f") #'er-recentf-ido-find-file)

    As usual - both the command er-recentf-ido-find-file and its keybinding C-c f are available in Prelude (naturally recentf is enabled there out-of-the-box).

  • prog-mode: The Parent of all Programming Modes

    You probably know that major modes in Emacs can derive (inherit) functionality from a parent major mode.

    Emacs 24.1 introduced prog-mode - a new major mode from which all programming modes (e.g. lisp-mode, ruby-mode) should be derived. All of the programming modes that come bundled with Emacs already inherit it (as do most actively maintained third-party modes). Having a common parent for all the programming modes allows us to do some pretty neat stuff - like setting common behavior for all of them. Here’s how we can enable spell-checking in comments:

    (add-hook 'prog-mode-hook 'flyspell-prog-mode)

    That’s all for now. We’ll discuss flyspell in more detail down the road.

  • Easter eggs

    Emacs is packed with an insane amount of cool stuff. With Easter fast approaching (I’m an Orthodox Christian and ours is in the beginning of May this year) I cannot help but think of easter eggs(“secret” commands, inside jokes, etc). Let’s see if we can find some in Emacs!


    M-x snake


    M-x tetris


    M-x zone M-x zone-mode


    M-x doctor

    Butterfly Mode

    M-x butterfly (refer to this xkcd comics if you have no idea what this is)

    Final Words

    This was a short post(and not particularly instructive I guess), but I hope you’ve enjoyed it. Share in the comments section any Emacs easter eggs you know of, that I haven’t mentioned.

  • Delete File and Buffer

    From time to time1 I need to quickly2 delete a file and kill 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-delete-file. Unfortunately the command does not act on the current file and will prompt you for a file to delete. Looks like we need to create a simple wrapper around it to get the job done:

    (defun er-delete-file-and-buffer ()
      "Kill the current buffer and deletes the file it is visiting."
      (let ((filename (buffer-file-name)))
        (when filename
          (if (vc-backend filename)
              (vc-delete-file filename)
              (delete-file filename)
              (message "Deleted file %s" filename)

    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 D:

    (global-set-key (kbd "C-c D")  #'er-delete-file-and-buffer)

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

    1. Most often when I refactor code. 

    2. This removes dired from the equation. 

  • Move current line up or down

    While programming(at least in some languages) I often find myself wishing to drag the current line a couple lines up or down. Emacs does have the means to transpose (switch) lines (courtesy of the transpose-lines command bound to C-x C-t), but I find it unwieldy. That’s why I’ve built a couple of custom commands on top of it:

    (defun move-line-up ()
      "Move up the current line."
      (transpose-lines 1)
      (forward-line -2)
    (defun move-line-down ()
      "Move down the current line."
      (forward-line 1)
      (transpose-lines 1)
      (forward-line -1)

    Those are not the kind of commands you’ll want to invoke with M-x. Therefore I suggest binding them to something like C-S-up and C-S-down(these bindings are often used for the same purpose in other editors and IDEs):

    (global-set-key [(control shift up)]  'move-line-up)
    (global-set-key [(control shift down)]  'move-line-down)

    Since this won’t work on OSX(Control+arrow is used by the window manager) I’d recommend the following alternative to OSX users:

    (global-set-key [(meta shift up)]  'move-line-up)
    (global-set-key [(meta shift down)]  'move-line-down)

    Personally I’m not a fan of any keybindings that require me to move my hands off the home keyboard row, but I wasn’t able to come up with anything better. Suggestions are welcome!

    As usual both commands(and both set of keybindings) are available in Prelude(but with prelude- prefices).

  • Highlight current line

    Just about every modern editor and IDE these days highlights the line you’re currently on, which I find extremely helpful. Emacs doesn’t do this out-of-the-box, but provides the means to do so - the built-in global minor mode global-hl-line-mode. To take it out for a spin just add the following line to your Emacs config:

    (global-hl-line-mode +1)

    In case you don’t like the highlighting color you can change it by adjusting the value of the hl-line-face face. Most decent color themes pick a pretty good value for it, so normally you should not bother changing it manually.

    global-hl-line-mode is enabled out-of-the-box in Prelude.

  • Highlight matching parentheses

    If you’re into programming highlighting the matching parentheses in your code is probably something you find rather desirable. Emacs doesn’t do so by default, but the global minor mode show-paren-mode, that comes bundled with Emacs, does.

    (require 'paren)
    (setq show-paren-style 'parenthesis)
    (show-paren-mode +1)

    Valid styles are parenthesis (meaning highlight the matching parentheses), expression (meaning show the entire expression enclosed by the parentheses) and mixed (meaning show the matching parentheses if both are visible, and the expression otherwise).

    Personally I find parenthesis as the least distracting option and therefore I favor it.

    If you’d like to change the faces used for matching and mismatched parentheses you’d have to alter show-paren-mismatch and show-paren-match. Most decent color themes do this out the box.

    show-paren-mode is enabled out-of-the-box in Prelude.

  • Playing with Font Sizes

    Adjusting interactively the font size is Emacs is pretty easy. Three keybindings refer to the mighty text-scale-adjust command:

    • C-x C-+ (increase font size)
    • C-x C-- (decrease font size)
    • C-x C-0 (reset font size to default)

    After using any of the keybindings you can proceed to adjust the font size further just by pressing +, - or 0 respectively. text-scale-adjust is mostly a wrapper around text-scale-increase and text-scale-decrease.

    You might want to bind them C-+ and C-- (generally a bad idea since you won’t be able to type stuff like C-- some-command anymore) to get more common keybindings for the operations.

    (global-set-key (kbd "C-+") #'text-scale-increase)
    (global-set-key (kbd "C--") #'text-scale-decrease)
  • Go Back to Previous Window

    Every Emacs user knows what C-x o (other-window) does - it moves your cursor to the next window. When you’re out of windows - the command will take you back to the first one.

    Relatively few people are aware that the command takes a prefix argument which allows you to move several windows forward or backward. That’s obviously pretty useful when you’re a heavy window user and like to split your frames into many windows.

    To move 3 windows forward you’d do C-u 3 C-x o. To move 2 windows backwards you’d do C-u -2 C-x o.

    If you’re mostly working with only two windows you probably don’t need to know that much about other-window - after all invoking the command one time will take you to the other window and invoking it a second time will take you back to the window you were originally in. I, however, often employ 3 or windows (blessed be the people who made huge LCD displays so cheap) and I really dislike having to type C-u -1 C-x o (or C-- C-x o, M--1 C-x o or M-- C-x o for that matter) to go back to the previous window. To alleviate that particular nuisance I utilize the following little trick:

    (global-set-key (kbd "C-x O") (lambda ()
                                    (other-window -1)))

    Now pressing C-x O (that’s not a zero, it’s a capital o) will always take me to the previous window, no matter how many windows are currently present.

    The C-x O keybinding is available out-of-the-box in Prelude.

  • Kill other buffers

    Many text editors and IDEs offer the ability to close all open files with the exception of the one you’re currently in. Emacs does not. At least it doesn’t until you add a snippet such as this one to your Emacs setup:

    (defun er-kill-other-buffers ()
      "Kill all buffers but the current one.
    Don't mess with special buffers."
      (dolist (buffer (buffer-list))
        (unless (or (eql buffer (current-buffer)) (not (buffer-file-name buffer)))
          (kill-buffer buffer))))

    Note that the command takes care not to kill special buffers (buffers that do not correspond to files).

    I’d suggest binding kill-other-buffers to C-c k.

    (global-set-key (kbd "C-c k") #'er-kill-other-buffers)

    The command can be implemented in a more elegant manner if one chooses to leverage either the built-in cl.el library or the newer dash.el. Here’s the version of the same command from Prelude, using dash.el:

    (require 'dash)
    (defun prelude-kill-other-buffers ()
      "Kill all buffers but the current one.
    Doesn't mess with special buffers."
       (->> (buffer-list)
         (-filter #'buffer-file-name)
         (--remove (eql (current-buffer) it)))

    According to your personal preference on functional programming the second version might seem either much more elegant, ghastly or just the same as the original.

  • Terminal at your fingertips

    Most of you probably know that you can run a terminal emulator(or simply a shell for that matter) inside Emacs(M-x ansi-term). This is pretty neat on its own, but what I think is even better is to have a quick way to jump to a particular terminal buffer reserved for the occasional command invocation or two. I achieve this goal with the following simple command:

    (defun visit-term-buffer ()
      "Create or visit a terminal buffer."
      (if (not (get-buffer "*ansi-term*"))
            (split-window-sensibly (selected-window))
            (other-window 1)
            (ansi-term (getenv "SHELL")))
        (switch-to-buffer-other-window "*ansi-term*")))

    The first time you run the command it will create a new terminal buffer based on your SHELL environment variable and display it in a window adjacent to the one you’re working in(in other words - it won’t clobber the window you are currently in). On successive invocations the command will simply take you to that existing buffer (it will still be displayed in a separate window).

    Personally, I find this command extremely useful and therefore I bind it to C-c t.

    (global-set-key (kbd "C-c t") 'visit-term-buffer)

    visit-term-buffer is available in Prelude(but with a prelude- prefix).

  • Automatic (electric) Character Pairing

    When editing text (and source code in particular) we often have to deal with characters that are usually paired (like (), [], {}, etc). By default Emacs doesn’t treat such characters in any special manner and that kind of sucks, since it’s quite easy to misplace a closing parenthesis for instance.

    While there are several modes that target that particular problem, in this post I’ll showcase just one of them - the built-in (since Emacs 24.1) global minor mode electric-pair-mode. Enabling it is trivial:

    (electric-pair-mode +1)

    At this point typing an open parenthesis automatically inserts the corresponding closing parenthesis. (Likewise for brackets, etc.) As an added bonus, consider the following scenario (the bar(|) represents your cursor):

    some_fun(param1, param2|)

    Typing a closing parenthesis a this point will not insert a second parenthesis, but will simple move the cursor over the existing one, keeping the expression correct.

    some_fun(param1, param2)|

    Simple, but effective. A little bit down the road we might take a looks at some of the (more powerful) alternatives to electric-pair-mode.

    electric-pair-mode is enabled by default in Prelude.

  • Automatic (Electric) Indentation

    Many newcomers dislike Emacs’s default behavior of not indenting automatically new lines in programming major modes. Usually one has to press Return, followed by Tab to open a new line and indent it according to its context.

    Of course Emacs has a command named newline-and-indent, that’s bound to C-j and many people are into the habit of using it instead of the pressing Return + Tab. Some even rebind Return to newline-and-indent.

    (global-set-key (kbd "RET") 'newline-and-indent)

    What’s little known is that Emacs 24.1 introduced a new global minor mode called electric-indent-mode. When enabled, typing certain characters (like newlines) triggers reindentation. So you can simply add this line to your Emacs config to get to enjoy electric-ident-mode:

    (electric-indent-mode +1)
  • Network Utilities

    A little known feature of Emacs is that it provides basic wrappers for various command-line (unix) network utilities. Here are a few Emacs commands for you to try out:

    • M-x ping
    • M-x telnet
    • M-x dig
    • M-x ifconfig

    Try to find as many related commands as you can!

  • Google

    Wouldn’t it be cool to be able to invoke a Google search from the comfort of your beloved text editor? Here’s a couple of use-cases. You may wish to Google the selected region or to be prompted to enter a query manually. Apart from cool it’s also pretty simple to add such a feature to Emacs.

    (defun er-google ()
      "Google the selected region if any, display a query prompt otherwise."
        (url-hexify-string (if mark-active
             (buffer-substring (region-beginning) (region-end))
           (read-string "Google: "))))))

    This command will display the query results in your default browser.

    I’d suggest binding the command to C-c g if you plan to use it regularly.

    (global-set-key (kbd "C-c g") #'er-google)

    er-google is available in Prelude (but with a prelude- prefix).

  • Indent defun

    As a continuation of our previous topic of indenting a buffer or a region, this time around I’ll show you how to indent a single defun1. So here’s the magic bit of code:

    (defun er-indent-defun ()
      "Indent the current defun."
        (indent-region (region-beginning) (region-end))))

    This function should work in all properly written major programming modes.

    Why would you want to use er-indent-defun instead of er-indent-region-or-buffer? Pretty simple - indenting huge buffers can take quite a while and you might want to save a bit of time if you know that a buffer’s indentation is correct pretty much everywhere else.

    I’d suggest binding the command to C-M-z (since it kind of resembles the keybinding for function evaluation in major modes for dynamic programming languages C-M-x).

    (global-set-key (kbd "C-M-z") #'er-indent-defun)

    Special thanks to Fuco 2 who suggested that command in the previous post.

    er-indent-defun is available in crux (but with a crux- prefix).

    1. Emacs slang/terminology for a function/procedure/method definition, originating from the way functions are defined in Emacs Lisp and a few other Lisp dialects. 

    2. Who I assume is Matus Goljer, of smartparens fame. 

  • Indent Region or Ruffer

    Everyone who’s used Emacs for more than 10 minutes knows that you can indent the selected region in a buffer with C-M-\ (bound to the command indent-region). While this is pretty useful I find that it’s more useful to have a command that indents the current region if present and the entire buffer otherwise. Therefore I’ve devised the simple commands er-indent-buffer and er-indent-region-or-buffer.

    (defun er-indent-buffer ()
      "Indent the currently visited buffer."
      (indent-region (point-min) (point-max)))
    (defun er-indent-region-or-buffer ()
      "Indent a region if selected, otherwise the whole buffer."
        (if (region-active-p)
              (indent-region (region-beginning) (region-end))
              (message "Indented selected region."))
            (message "Indented buffer.")))))

    Now that you have er-indent-region-or-buffer you don’t actually need indent-region or er-indent-buffer that much (if at all). That’s why I typically bind er-indent-region-or-buffer to C-M-\.

    (global-set-key (kbd "C-M-\\") #'er-indent-region-or-buffer)
  • Open File in External Program

    Sometimes it’s useful to be able to open the file you’re editing in Emacs in an external program. For instance - you might be editing some HTML file and you might want to see how is it looking in a browser. I use the following handy command to do so:

    (defun er-open-with (arg)
      "Open visited file in default external program.
    With a prefix ARG always prompt for command to use."
      (interactive "P")
      (when buffer-file-name
        (shell-command (concat
                         ((and (not arg) (eq system-type 'darwin)) "open")
                         ((and (not arg) (member system-type '(gnu gnu/linux gnu/kfreebsd))) "xdg-open")
                         (t (read-shell-command "Open current file with: ")))
                        " "
                        (shell-quote-argument buffer-file-name)))))

    On OS X it will use the built-in open program to decide which program to open the file with. On Linux & *BSD it will use xdg-open. On all other operating systems you’ll be prompted to enter the name of the program in the minibuffer (with autocompletion for the program name). With a prefix argument you’ll always be prompted for the name of the program to use.

    I find it convenient to bind the command to C-c o:

    (global-set-key (kbd "C-c o") #'er-open-with)

    crux features a variant of this commands. (it is named crux-open-with).

  • Copy Filename to the Clipboard

    Sometimes I need to copy the name of the currently visited file to the clipboard. Emacs does not have a built-in command for that, but cooking one is pretty straightforward:

    (defun er-copy-file-name-to-clipboard ()
      "Copy the current buffer file name to the clipboard."
      (let ((filename (if (equal major-mode 'dired-mode)
        (when filename
          (kill-new filename)
          (message "Copied buffer file name '%s' to the clipboard." filename))))

    Evaluate the new bit of code in Emacs (maybe by using C-M-x somewhere in the body of the function definition) and invoke the command with M-x er-copy-file-name-to-clipboard.

  • Repeat Last Command

    Sometimes you’ll want to quickly repeat an Emacs command several times and more often than not it won’t have a convenient keybinding you can use to do this. Enter C-x z (repeat) - it simply repeats the most recently executed command. And the best part? After you’ve pressed C-x z once you can continue repeating the last command simply by pressing z. Vi(m) users will probably note that this is quite similar to the . command there.

    For instance - if you want to execute the mark-word command (bound to M-@) a few times you can do it like this:


    or like this:

    C-x z

    Neat, ah?

    P.S. In that particular case it would probably be easier to keep hitting M-@, but you get the point.

  • Manipulating Word Case

    One operation that we have to do fairly often when editing text is manipulating the case of words. The most popular case manipulations are probably capitalize, convert to lowercase and convert to uppercase. Emacs naturally has built-in commands for all of those.

    Pressing M-c runs the command capitalize-word, which will capitalize the next word and move the cursor after it. Pressing M-- M-c will capitalize the previous word without moving the cursor.

    Pressing M-l runs the command downcase-word, which will lowercase the next word and move the cursor after it. Pressing M-- M-l will lowercase the previous word without moving the cursor.

    Pressing M-u runs the command upcase-word, which will uppercase the next word and move the cursor after it. Pressing M-- M-u will uppercase the previous word without moving the cursor.

  • Remove Variable &amp; Function Definitions

    From time to time you might want to void (unbind) a variable or a function definition in Emacs. Most often you’ll probably be dealing with variables created with defvar, whose values you’ll want to update. The magic functions you need are the following:

    ;; this will make the symbol my-nasty-variable's value void
    (makunbound 'my-nasty-variable)
    ;; this will make the symbol my-nasty-function's
    ;; function definition void
    (fmakunbound 'my-nasty-function)

    The names aren’t exactly intuitive and even I happen to forget them from time to time.

  • Smarter open-line

    Often when editing code one wishes to open a line just under the current one, which is properly indented relative to the existing code, and position the cursor at its beginning. Such a feature is present in most IDEs, such as IntelliJ IDEA, Eclipse and NetBeans. It’s usually bound to Shift+Enter. Emacs has a command open-line, which sadly behave nothing like I’d want it to - it just breaks the current line and inserts one (or more) empty line afterwards. Luckily in the land of Emacs any shortfall is correctable with a bit of Emacs Lisp. Just add this snippet to your .emacs (or .emacs.d/init.el or whatever):

    (defun er-smart-open-line ()
      "Insert an empty line after the current line.
    Position the cursor at its beginning, according to the current mode."
      (move-end-of-line nil)
    (global-set-key [(shift return)] #'er-smart-open-line)

    Evaluate the code (or restart Emacs) and you’ll be able to use M-x smart-open-line or Shift+Enter (a.k.a. S-return).

    This command is part of crux (it’s named crux-smart-open-line there).

  • Blastoff

    While many people consider Emacs (and vim for that matter) a remnant of the Dark Ages of computing, we1 know better! It’s time to bring Emacs under the spotlight once more and showcase its unique advantages over the more “traditional” (conventional) text editors and integrated development environments.

    Welcome to Emacs Redux! In this blog, dedicated to the One True Editor, I’ll be sharing with you useful tips and tricks to make your experience with Emacs more productive and more enjoyable.

    My name is Bozhidar and I’ve been using Emacs for about a decade now for just about everything. I guess you’ll have to hope I spent my time with Emacs in a productive manner and that I’ve uncovered many interesting things to share with you.

    So here we begin…

    1. The crazy Emacs devotees. 

subscribe via RSS