Comment Control in Emacs

Looking at my emacs customizations this morning, I realized I had not one or two but three(!) key bindings used solely for comment control. Comments are an important part of what I use emacs for, sure, but I was feeling confident I could bring that number down. My favorite commands are ones that do what you mean- not only do these commands free up real estate in keymaps, but they foster quicker reactions from the user since less thought goes into selecting the right key to press.

My three commands broke down my comment shuffling into the following actions:

1. Comment a region of text
2. Comment a single line
3. Insert a comment on the current line

Fortunately, Emacs comes with a terriffic set of built-in commands. From the doc string:

Insert or realign comment on current line; if the region is active comment or uncomment the region instead.

It looks like our little friend comment-dwim will satisfy all of the required functionality except toggling individual lines. (Well it can- if you feel like marking a one-line region each time.) Instead of writing another command to keep up with something so trivial, lets see if we can enhance this command to do everything we want. Enter this piece of adivce:

This introduces a few changes into comment-dwim‘s default behavior. Primarily, it is now possible to un/comment an individual line. To do so, place the point at the beginning of the current line or the beginning of indentation before hitting M-;. Also, make sure that no region is selected. Second, after un/commenting a selected region, the region will now stay active. This seemed to be the most natural behavior to me, after some experimentation.

Ignoring Windows with (other-window)

I feel Emacs does a great job implementing features in a keyboard-oriented environment. One of the harder ‘new-agey’ features to implement in the modern multi-window system is window navigation. Even with prefixes, other-window only goes so far. Windmove does a nice job picking up the slack, but sometimes I’m still wishing for more.

For example, when I’m using GDB, I like to have the *input/output* buffer open, as a reference. Usually I don’t interact with my programs by feeding them text input, so when I’m doing the window dance I just want to skip over this buffer. Emacs natively provides a way to do this, but it took me a little while to figure out how.

Cycling around the frame with C-x o will ignore any windows where you have run this defun. Now we can enjoy this feature without a second thought!

Hooking Personal Minor Modes

A while back I wrote about the benefits of using a minor mode for personal customizations. Today I stumbled across another jewled side of this story. By using the define-minor-mode macro, we are automatically given a corresponding personal-mode-hook which will be called when our mode is enabled or disabled. This is great news! The only thing that would make this sweeter is finding a way to determing which way our personal mode is being toggled- on, or off?

(and (boundp 'personal-mode) personal-mode)

Is just what we’re looking for. See this handy tidbit for more details. Well I’ve already spilled the news, now how is this a good thing?

The Problem

Presumably, you have a few minor modes you have grown accustomed to, and use on the regular. Yasnippet, flyspell, abbrev-mode, paredit? Some of these, while helpful, can throw the unprepared driver for a loop with dedicated keybindings and what you might call ‘super-standard’ behavior. Now we can include these modes with the content that is toggled along with our personal minor mode. That is, while our minor mode is enabled, so are the minor modes we are most fond of. Disabling our personal minor mode will similarly disable the non-standard modes.

Notice that some modes I enjoy having disabled during my usage of emacs. I can indicate this in my minor mode hook with (dont activate)

Here are the modes I habitually use at this moment in time. Most of these modes take a numeric argument, with a positive number enabling the mode, and every other argument disabling the mode. To turn the test we have for determining the state of the personal mode from a boolean into the numeric prefix we need, see the let statement. If the mode has just been activated, activate becomes a 1. If this hook has been called for cleanup, activate becomes a -1.

Some commands (like setq) require the boolean argument, which we can pass our test for our minor mode state directly.

Since I was getting really into the mode of restoring everything I had changed with my personal mode, I added a simple way to add or remove hooks as necessary, and a simple way to diminish-/un-diminish the cruft too.

Kill Line Backwards- Take 2

Over at Emacs Redux, Bozhidar Batsov has been shredding it up with post after post. Today he posted his take on how to quickly access a reverse kill-line. I immediately took his advice and remapped the (redundant) C-Backspace to (kill-line 0), but was a little unsatisfied with its behavior. This is undoubtedly because of my new appreciation for kill-whole-line, which I feel makes C-k behave a lot more reasonably. Isn’t the goal fewer keystrokes after all? To mimic this hungry behavior with our new backwards-kill-line, let’s make some modifications. Since (kill-line 0) can’t interpret numerical prefixes, I’d like to add that convenience on my own.

I'm a big fan of code documentation. so check out the doc string for a feel of what this command does. In the true Emacs spirit, everything is pushed onto the kill-ring for later yanking.

Minimizing Keystrokes Required by Punctuation (in Emacs, of course)

The emacs community is a pretty tightly-knit one. Wtihin it, there are a few interesting characters to be sure. Xah Lee, who I bet could even deliver a roundhouse kick with emacs, is just one of these characters. Have you examined his resume?

Some of his posts are re-circulated through the emacs blogs I subscribe to, which is nice. I figure the cream of the crop will be delivered to me without having to add yet another source to my list of professional procrastinations. One such article that made it to my living room is his take on punctuation in the English language, obviously influenced by his multilingualism. (You should stop and read the article now, or at least browse it casually, so you understand how far off I was when I proceed to the rest of this post.)

Before I figured out what he was talking about, my mind came to the conclusion that indeed, typing a space after a comma is a waste. But not merely a waste of space! I thought his real concern was the wasted keystroke (as so many emacs users are wont to dispel). The thought had been planted, and it hasn’t died since. Now my concern is the millions of wasted keystrokes I have been content with since I started typing. Why is it necessary to manually insert spaces after typing punctuation? In plain English, when is it ever appropriate to follow a punctuation mark with a non-whitespace character?

…It’s not! And it won’t be. (Wait, did you see what I did there?) Given the trivial nature of conforming emacs to my preferences, it would be a snap to write

But how crazy is that? Honestly, it makes me feel a little insane. I’m a little afraid to try it for some substantial length of time, for the same reason I was afraid of trying dvorak: I don’t want to sound like a sailor every time I sit down at another keyboard, growing frustrated at my lack of ability to type simple constructs. Maybe I’ll give it a shot, maybe I’ll only enable it in certain Major Modes (fundamental, org, text). When I decide how to handle this nascent idea appropriately, I’ll be sure to revisit the topic on this blog. The inception has begun, and now it’s in your mind too. Cheers! :)

Using a Personal Minor Mode for Custom Settings in Emacs

In Emacs, there are just some things I needed to change right off the bat to feel at home. The C-z binding, for instance- undo. No more of that suspend business! Since that first customization, I have devised dozens more. Some people I collaborate with somehow make minimal changes to the default interface, and when one of these Luddites tries driving my setup, will invariably grow confused when certain actions don’t do what he/she is expecting- which is perfectly reasonable! I’m the weirdo, for changing what the Emacs creators have designed, so the onus is on me to provide a quick way back to a machine anybody can drive. Hello, minor modes.

A minor mode is a perfect solution to introduce customizations within Emacs. For one thing, all of my settings can be toggled on or off instantly. When I’m driving, I slip into my familiar vehicle, perfectly molded to my tastes. When I leave the driver’s seat, the same vehicle loses all specificity to my former presence.

Another convenience I didn’t realize I would enjoy until I implemented this feature is that minor mode keymaps have the ability to override Major Mode keymaps. This is quite nice, because now I don’t feel like I’m a backseat driver to certain Major Modes! When I define a keybinding, it will work under just about any conditions. (Some exceptions I have found to this rule are org-mode and flyspell-mode. How irritating!)

So, how’s this implemented? Get to the juicy part! The command we’ll be using is define-minor-mode. The top gist contains the setup- the minor mode itself, and the keymap that we will bind to it. The second will contain a snapshot of my current customizations, all the ones that I can flip on or off with a single command. If you are interested in the latest version, it will be eternally accessible on github. As you can see, we can be quite flexible and creative with the material we provide with this personal mode.

Once this is all set up, to toggle my personal minor mode (and all the jazz that comes with it), all I have to run is M-x esc-mode.

Scrolling Google Results in emacs-w3m

As my previous post hinted, I have been spending more time in emacs-w3m as of late. Some of you may be stuck on the “why,” as in “why use a text browser when you can use chromium,” and if you haven’t seen the light yet my reasons are as follows.

1. My eyes thank me.
I use wombat+ color theme, and this means any web page can be viewed without having to manually contract my pupils. Sure, I stick to high contrast in chrome too, but why would I rather start the compounding process of adding (untrusted) software to improve on other not-good-enough software when I already have emacs open?

2. Saves memory- I already have emacs open.
When I used a MacBook… wow, it’s tough thinking back to those Dark Times. But when that’s all I had, my battery life under the best of conditions was a mere 2 hours. (Now, on my ThinkPad, I get an easy 12+.) I noticed that Chrome, in addition, regularly consumed 70% or more of the available memory. What is to be expected when a laptop is continually forced to update its entire supply of volatile memory..? Battery life tanks. With my MacBook, it indeed became a matter of keeping Chrome closed if I wanted my laptop to last through a single class.

3. Each page is a buffer.
That is, each page is a first-class citizen. Searching, copying, editing-then-copying, copying-then-editing, etc… If you can do it in emacs, you can now do it in emacs on the web. Chrome, beautiful though she is, has never given me such functionality.

Also- syntax highlighting. Evaluating code straight from the browser (which is really the equivalent of a kid scraping bubble gum off the sidewalk and sticking it in his mouth, but in both situations, the convience can’t be beat).

4. Nothing but text = minimal bandwidth requirements.
My first internet connection (until 2008!) was a dial-up connection. Even though I’ve left those speeds behind, sometimes bandwidth hogs are persona non grata. At UT, underlings like myself are kept in line with a paltry 500MB bandwidth limit- per week. It’s all about that payday to them; thankfully, I don’t have to suffer. With emacs, it’s also trivial to ssh into a remote host (say, one that isn’t monitored for bandwidth, at a remote location) and browse without fear of throttling, thought police, whatever.

5. Extending functionality is as easy as elisp.

Now, after I press C-x j to open a google query, I can quickly scroll through the results with n and p. This replaces my previous methods of jumping around google with ace-jump mode and a modified (next-line) that jumped 6 lines instead of one.

I am wary of this code- I find it highly unlikely that this is the first attempt to write code that performs the same task. But it was so trivial to write, and it is so helpful, I couldn’t resist. Bit by bit, emacs is conforming to my ideal working tool.

Burying the Compilation Buffer

Compiling code in emacs takes all the pain away from dealing with compilers. Color, hyperlinks to the offending source code (next-error and previous-error), and quick interaction with Google thanks to w3m are some of my favorite features. One of the best features of any service is the ability to remain completely under the radar without sacrificing utility or function. Wouldn’t it be nice if successful compilations could execute without any interruption to the developer? Enter this snippet, crafted with care in the IEEE basement with [hbave]

Works best with the hook at the bottom, which invokes the defun when appropriate.

Computer Interfaces, “Ease of Use,” and You

Subtitled: Why Emacs is Right for Me

And hopefully for you, too. With the turn of the new year, I witnessed my 20th birthday. I have been programming for a decade! Sounds like a long time when I put it that way- and I figured it was high time to reminisce a little. Here are some of the things I realized.

Computers can be nice additions to our lives. Before utility, though, much of our society ranks computers on other alleles. We’ve all seen people with computers on display to impress, aesthetic appeal surrounding who knows what. We’ve also seen the guy on the bus with 5 year old hardware, glued and fastened in place who knows how to implement dumb terminals and can jive with what others can’t use well enough to produce meaningful action. On the inside, some people decorate their operating systems with widgets and whistles, graphics and shadows and watts because they can. How a computer looks really affects how a person comes at the computer. But why are we assuming any given person knows how this computer works? What happens if this is the first time this fellow has come across a device like this?

I feel every device should be intuitive for the user it was designed for. Sounds like a reasonable statement, right? Sadly, not everybody is capable of pulling that off. I haven’t personally used Windows 8, but I hear for the folks using it without a touch interface, they are really stumped with esoteric key bindings and cryptic interfaces. Everything they were used to was switched around- a common event with graphical managers of any variety- and millions of “power” users were lost adrift. These users could be considered to be ‘first-time users,’ and did the designers of the operating system keep this golden rule in mind? The grumbles and malcontent stirring in the wake of the release of 8 indicate that they did not.

So how can I get into the mindset of the ‘unfamiliar computer user?’

I remember the first time I used my parents computer. I was quite young- 4? This monolith was running Windows ’95, fresh from the printing press. I didn’t know enough to assume I could operate a program, so I fiddled with the remaining visible portion of the screen: the desktop. I right clicked (incidentally on the corner of an icon), because left clicking was boring, and the first item looking unfamiliar was “Set as Desktop Background.” Not knowing any terminology, I had no clue what this could mean. I clicked, not taking into account any potential permanent, un-undoable actions, and was horrified when the entire screen changed color as a new picture assumed the screen. Somebody would know I was there! My heart sank. I can still recall the fear I felt that my parents would think I was intruding on their machine. Machines were personal, attended to, prized companions, right? I instinctively knew I had to revert the picture, and this was the thought path my mind spawned:

Holy smokes! So this picture is the new background- how can I find the old background? I have no clue, it could be in any of these things look like folders! I don’t have time to open them all- can I do sort of reverse image search? Shoot, I don’t know, even if that’s possible I don’t know where to find it. Where can I find help??

I realized just now that to this day, over 15 years later, I think about tasks on the computer in exactly the same way. Figure out some steps that seem plausible, and would solve the problem, and then consult the docs. The superiority of Emacs over other editors is its excellence in each of the above categories of thought- search, help documentation, customization. If I had been able to search for the picture I had in mind, or had been able to revert the change I had made I would have done so with a clear sequence of a subset of the commands provided by Emacs. This breakdown happens to correspond to a well defined algorithm, atomic directives intended for the machine. With Windows as an introduction to computing systems, one might assume a user must manually conduct directives all the time. One also might mistakenly assume that help dialogues don’t get any better than Microsoft’s. Who else says this must be the case? Consider this process.

I take notes in a structured format. I like exporting my notes as \LaTeX (if one takes well enough notes, might one have one’s self a study guide for 10$?) so I usually maintain one monolithic document. To begin each lecture (in each class, 4 times in certain days) I usually create a new block with the text “* Lecture <number of lecture>” and today’s date. When I’m running late, the last thing I want to do is break out the formatting rules before feeling comfortable about transcribing the material I’m missing. In order to compensate for the worst case scenario, and because laziness is the virtue of a true programmer, the process must be automated. In Emacs, this is quite an enjoyable process. The task is simple- and well defined. Does one even need conditionals for this sort of thing? If I consider my above, 4 year old approach, I might end up with a function looking like this

This is a function that algorithmically, step-by-step defines what I want to do at the beginning of each lecture. If today is day 2, I end up with something like

* Lecture 2
..Thursday January 17, 2013

Note: Emacs also provides alternatives to defining a task like this, which can be quite rote. Supposing I want to define a very long task? I would rather take the following approach:

Create a keyboard macro: F3
Run through the desired action
End the keyboard macro: F4
Name the keyboard macro: M-x name-last-kbd-macro demonstration
Insert the macro as Emacs lisp: M-x insert-kbd-macro demonstration

Emacs will give you a more concise rendition than my elisp:

which accomplishes exactly the same result. This binds the function call “demonstration” to the series of keypresses you see before you. They are not stored commands, but rather instructions to play back while masquerading as the user, to be interpreted at run time. In different modes, with different key bindings, the results may vary- so caveat emptor.

My point is this: Emacs is created around a basis of well documented commands. Reading any Emacs literature will inform you that pressing a letter key, “e” will run self-insert-command. Every action you might perform, nay think of, is an Emacs command. How does this benefit the user? Well, imagine you are able to build commands like the one above, though this example is even trivial in nature. What if you were able to lump together simple commands in order to achieve larger, more meaningful actions? How would that change your workflow? Emacs users enjoy the convenience of hundreds of key bindings. Devising novel finger combinations is an old hobby of a real Emacs user*. They have the luxury, see, to bind any function to any keypress. This coincides with their ability to coordinate ideas into functions. How awesome is it when complex actions, like the ability to update all the dev machines at work; or the ability to sort regions of text alphabetically; or the ability to process your Perforce checkin logs at the end of each day with a script to write a work report totaling the number of bugs crushed is just one stroke away.

In the above example, one could expertly define the function manually, or, even if certain commands involved in the process were totally foreign to the user, one could simply record the process with the intent of automating it later (with one key-combo, by the way: C-x e). Can Windows users do that? Why not? It is one of the single biggest time savers of my day! Even not knowing all the magic of Emacs can be very much made up for by some wit with the macros.

This, and much more, is possible with Emacs. Couple that with the best free documentation I’ve ever seen in my entire life, added to the tireless efforts of the wonderful emacs community, multiplied by more modes and packages than one could hope to comprehend, raised to the power of FOSS, is why you should consider using Emacs.

It doesn’t get any more intuitive or fundamental than that. Even a four year old could do it.

* I say this because nobody likes to type out M-x some-command-name, even with all the comforts of auto-completion and packages like smex. The less frequented commands can instead be bound to less frequented (custom, obscure) key bindings.

Adios, Dvorak

Right when my typing skills were improving from ‘noob,’ my sister started using the Dvorak keyboard layout. She said she was terrible at QWERTY, and relearning from scratch the muscle memory required by typing was easier than breaking old habits. That’s as may be, but it sure is inconvenient. I have been tempted to make the switch before, but have never gotten past the first few half-hours of typing tutorials. My sister has admitted to being constantly plagued by the simple task of driving another computer; as her Dvorak skills sharpened her QWERTY went down the drain.

I reexamined my desire to use another keyboard layout, instead asking what deficiencies I found with QWERTY. The only real grievance I could muster was that the delimeters used in programming, ({[ ]}), were awful far from home sweet home and demanded the contortion of one’s fingers. I recently devised a method to provide home-row delimeters, if not everywhere at least right where it helps the most. Whipping up a bit of emacs lisp*,

These anonymous functions grant me the ability to insert any delimeter of my liking, quick as a snap. If you remap the cantankerous Caps Lock with a much more functional Ctrl, that is.


Before I posted this, I looked at the duplicated code with disdain. I tried to diminish the sizable block I had written, but couldn’t get it down any more without loss of structure. I was convinced there was a better way in this language I’ve been growing increasingly fond of, trouble was, I didn’t know how to create it. I decided it was time to sit down and read the manual.

I noticed that Paul Graham, the author of a captivating article I was reading, had mentioned writing a book on Common Lisp. How can that not be a sign? I obtained a copy of his book and shortly came across this passage.

Donald Knuth called his classic series The Art of Computer Programming. In his Turing Award Lecture, he explained that this title was a conscious choice—that what drew him to programming was “the possibility of writing beautiful programs.”

Like architecture, programming has elements of both art and science. A program has to live up to mathematical truth in the same way that a building has to live up to the laws of physics. But the architect’s aim is not simply to make a building that doesn’t fall down. Almost always the real aim is to make something beautiful.

Many programmers feel, like Donald Knuth, that this is also the real aim of programming. Almost all Lisp hackers do. The spirit of Lisp hacking can be expressed in two sentences. Programming should be fun. Programs should be beautiful. That’s the spirit I have tried to convey in this book.

Paul Graham

This appeals to me, but I will elaborate on ideas in a different post. For now, this is what I’ve learned from ANSI Common Lisp. Lisp has the ability, like some other languages, to write code that will be expanded and executed by the processor. These snippets are called macros, and add another layer of abstraction to Lisp. The actions I want to perform can be referenced by one common macro instead of explicitly written three times. The result looks something like this:

The macro churns out code defined by the macro’s parameters, which in this case allow for enough flexibility to throw in the “->” symbol. I’ve been looking for a nice way to do this, since my initial attemps with abbrev-mode ended in failure. This solution is scalable and personal enough to find a steady home in my config files. Even though it doesn’t look like it, this code can still fit on one line and is 80-char compliant, so it comes out to be significantly shorter, and infinitely more extensible, than the former solution.

Perhaps there is a way to shorten this code even further- which I will keep an open mind to- but for the first few hours of day 1 Lisp programming, I’ll consider this a success.

* Well, that’s not exactly verbatim from my .emacs, but we’ll get to that in a later post.