Happy Anniversary To Mastering Emacs

Happy Anniversary to Mickey Petersen and Mastering Emacs. Mickey has been posting really great material for a year now and we should all hope he continues. As I’ve said before, Mickey always has something interesting to say and I invariably learn something from each of his posts.

As an anniversary gift from him to us, Mickey has created a reading guide that serves as an index of sorts to the articles on his blog. Hop on over there and take a look, pick an area that interests you, and read some of the articles in that area. You’re sure to learn something worthwhile.

Posted in Blogging | Tagged | Leave a comment

Emacs Key Chord Mode

Magnar Sveen has a new episode of Emacs Rocks up. This time he talks about key-chord.el, a package that lets you press two keys simultaneously (or a single key twice in quick succession) to run a command. For example, I could bind prettify-key-sequence to the key chord 【p+k】 and avoid having to run it with 【Meta+x】.

I probably wouldn’t do that because smex makes calling prettify-key-sequence fast enough for the relatively few times that I call it. There are other cases where it’s just what you need, though. I see its real utility in two areas.

The first, as explored in the Emacs Rocks video is for commands that you run all the time and want to be able to invoke as quickly as possible. Of course, you could just bind those commands to a function key or something like 【Ctrl+c κ】 where 【κ】 is some arbitrary key. The problem with that solution is that there are a lot of useful commands but all except a few of the convenient key sequences are already used, especially if you’re in something like org-mode.

This is an ideal situation in which to use key-chord.el. Suppose, for example, that I was writing fiction with a lot of dialog. It would be great to be able to press 【d+q】 to run the dq command that I’ve written about previously to insert open and close quotes. Actually, key-chord.el lets you do that directly by adding an expression such as

(key-chord-define-global "dq" "“”\C-b")

to your .emacs or init.el file.

In summary, I see key-chord.el being useful to

  • Bind a fast two-key sequence to a frequently used command that is bound to a less convenient key sequence.
  • Extend the number of convenient key sequences.
Posted in General | Tagged | 4 Comments

Three Trees

Scott Chacon, author of Pro Git, gave an interesting talk at Strange Loop entitled A Tale of Three Trees. The idea is to understand how Git works by understanding how it manipulates the three trees: head, index, and working directory.

The talk is a little over 45 minutes and worth a look. It will help you understand some of the fine points of Git. If you do watch it, don’t view it full screen as you won’t be able to see his slides that are displayed in a secondary window.

Posted in General | Tagged | Leave a comment

Unix V6 Lives!

If you’re a Unix nerd like me, you probably like reading through the Unix sources. These days, that’s remarkably easy to do. We have Linux, BSD, Open Solaris, and even some of the ancient Unix sources to peruse. It wasn’t always like that. I remember my excitement when the famous Lions Book was finally made available to the public. I ran right out and got myself a copy the same day I heard about it. For those who don’t know, John Lions’ A Commentary of the Sixth Edition UNIX Operating System was a line-by-line exegesis of V6 Unix. For years it was restricted to Unix source code licensees so it was a moment for celebration when it was finally unencumbered.

Today I learned—or maybe relearned—via OS Blog that V6 Unix has been ported to the X86 architecture and ANSI C. The original V6 sources were written in a pre-ANSI C and don’t compile with a modern C compiler. The nice thing about V6 is that it was a small OS (less than 9000 lines) and pretty easy to understand. The downside was that it was targeted at the PDP-11 so most of the low level machine details and the assembly language bits are opaque to younger1 readers.

Now Russ Cox, Frans Kaashoek, and Robert Morris have resurected it for the X86. The system is bootable or you can run it under QEMU. Even nicer, the authors have a commentary to go along with it. It’s not a line-by-line commentary like Lions’ book but it does explain the details of the X86 that you need to understand the code. There’s also a printed version of the code with line numbers that goes along with the commentary.

If you’re interested in learning some of the low level details of Unix-like systems but find slogging through the Linux or BSD code base too daunting, this could be just what you need. It’s a really great resource and it’s all free. If you want to read about the code but aren’t interested in compiling and running it you can just download the two PDFs. If you want the code itself, that’s available too. The code was ported for use in the MIT 6.828 Operating Systems Engineering course and the course notes are available too.

Footnotes:

1 Younger ≡ Not working on computer systems 30 years ago.

Posted in General | Tagged | Leave a comment

VimGolf In Emacs 19 And A New Trick

Tim Visher has a new version of VimGolf in Emacs up. There are a couple of interesting things in this episode. First, Visher is working on a VimGolf minor mode that loads the challenge into Emacs and provides special functionality useful in working on VimGolf challenges. It’s still very early in the development process, but it’s already functional and looking very nice. Just the thing if you’re interested in joining the fun.

The second thing of interest in the video is a very efficient way of deleting the current line. We all know how to do this with 【Ctrl+a Ctrl+k Ctrl+k】 and probably use it several times a day. Visher’s discovery is that you can do this with a single (modified) keystroke by typing 【Ctrl+Shift+Backspace】. That’s a lot more efficient but will take, at least for me, some muscle memory retraining because 【Ctrl+a Ctrl+k Ctrl+k】 is second nature.

Posted in General | Tagged | 6 Comments

A New Trick For Marking Up Key Sequences in Emacs

Frozenlock left a comment to an old post of mine about Marking Up Key Sequences For HTML. He said he liked the way Xah Lee and I mark up Emacs keys sequences but that he didn’t like having to write ctrl+x b to get 【Ctrl+x b】 so he wrote a little hack that allows him to enter the actual key strokes and have the appropriate markup inserted at the point.

It turns out to be pretty easy to do. If I were starting from scratch (or weren’t so lazy) I’d modify my prettify-key-sequence function to accept the actual keystrokes and output the markup. Frozenlock uses the macro method that I used before I wrote prettify-key-sequence so there isn’t quite as much control over the final output but it works well for most cases. If you want to use markedup key sequences, I’d look at Frozenlock’s method and consider integrating it into something like prettify-key-sequence.

Posted in Blogging | Tagged , | 5 Comments

Using The Emacs save-restriction Special Form

Emacs has the ability to “narrow” a buffer to a region thereby making the parts of the buffer outside the region invisible. The invisible part of the buffer is completely inaccessible: you can’t move into it, you can’t change it, and, of course, you can’t see it. The table below shows the commands to narrow and widen (cancel the narrowing) buffers1.

Key Sequence Function Action
Ctrl+x n n narrow-to-region Narrow to region between point and mark
Ctrl+x n w widen Widen the buffer
Ctrl+x n p narrow-to-page Narrow to current page
Ctrl+x n d narrow-to-defun Narrow to current function

These functions are sometimes useful during interactive editing. For example, you might want to narrow to the function you’re working on so you won’t be distracted by the other code. I find, however, that they’re mostly useful in Emacs Lisp code. That brings me to the point of this post.

Xah Lee has an excellent—and, if you’re an Elisp programmer, important—post on using narrowing to avoid changing the boundaries of a region while you work in it. If you haven’t read his post, go do that now before continuing with this one.

Lee’s post is an excellent example of using narrowing in Elisp code but what I really want to talk about is the special form save-restriction. This form merely saves the current narrowing, if any, executes its body, and then restores the saved narrowing. The template is

(save-restriction
  (narrow-to-region beg end)
  (do stuff)
  (do-more stuff))

so that you can temporarily narrow to some region without affecting any narrowing already in effect. You might wonder why you would want to narrow in Elisp. Lee gives an excellent example of its usefulness but I most often use it as a sort of “set it and forget it” device when I’m writing code that can operate on a region or the entire buffer.

For example, consider the following function that counts lines in a Scheme source code file:

(defun jcs-count-scheme-lines ()
  "Count non-comment, non-blank lines in a Scheme program"
  (interactive)
  (with-region-or-buffer (b e)
    (let ((cnt 0))
      (save-excursion
        (save-restriction
          (narrow-to-region b e)
          (goto-char (point-min))
          (while (not (eobp))
            (unless (looking-at "^\\s-*$\\|\\s-*;")
              (setq cnt (1+ cnt)))
            (forward-line 1))
          (message "%d code lines" cnt))))))

The with-region-or-buffer macro binds the beginning and end of the current region if there is one or the beginning and end of buffer if there isn’t to its first and second arguments. I wrote about it here and here. I narrow to the region defined by b and e so that I don’t have to worry about whether I’m working in the whole buffer or a smaller region. In effect, I set the area I’m working in and then just pretend I’m working in the whole buffer so that I don’t have to write a lot of code worrying about whether I’m acting on a buffer or smaller region.

This is a really handy technique that can save a lot of code and effort. I use it all the time because I try to make most of my Elisp functions work on either regions or the entire buffer.

The code above illustrates another point. The save-excursion special form is similar to save-restriction except that it saves and restores the point, mark, state of mark activation, and current buffer. When you use them together, as I did here, you should put the save-excursion in the outermost position.

Footnotes:

1 Narrowing is disabled by default. When you first use it, Emacs will ask you if you want to enable it temporarily or permanently. You can enable it yourself by putting (put 'narrow-to-region 'disabled nil) in your .emacs or init.el file.

Posted in Programming | Tagged , | 2 Comments

More Amazon Disruption

Back in September while everyone was waiting for Amazon to announce the Kindle Fire, Sebastian Anthony over at ExtremeTech speculated that Amazon would also roll out a digital library that would let Kindle/Amazon Prime users check out books for free. He went on to discuss what this would mean for public libraries and concluded that it could easily mean their death.

The announcement for the Fire came and went and there was nothing about the digital library so I forgot about the post. Just recently, however, Amazon announced the Kindle Owners’ Lending Library that does pretty much what Anthony had predicted. You can borrow one book at a time and can keep it as long as you like but you can borrow a new book only once a month. Not ideal for the voracious reader but still a pretty good deal and who knows how the details of the plan will evolve in the future.

What interests me about this is not so much what it will mean for libraries—I’m pretty sure they will evolve to deal with the digitization of media—but what it means for publishers. The publishers, of course, hate the plan and none of the big six are participating according to an article by Jeffrey Trachtenberg and Stu Woo at the Wall Street Journal. Those that are participating are typically paid a flat fee by Amazon.

Doubtless the big publishing houses will resist as long as they can but in the end they will be dragged kicking and screaming into the program. Sadly, this is another missed opportunity for them. Rather than accept the inevitable and find a new business model that leverages what Amazon and others are doing, they continue to try to fend off the forces of change.

As I wrote a couple of weeks ago, Amazon is already storming the ramparts of the publishing industry and if the big houses can’t find a place in the new ecology they will surely wither and die. I’ve said before that I hope that doesn’t happen but, really, time is running short.

Update: Mathew Ingram has a nice analysis on this over at Gigaom that’s well worth a read.

Posted in General | Leave a comment

Emacs Rocks

Tim Visher has started a growth industry with his VimGolf in Emacs videos. First, some of us starting writing about the videos, then people started issuing their own challenges, and now he has a direct competitor with Emacs Rocks. I don’t know how Visher feels about that but I’m delighted. It’s more fun and more opportunities to learn some nifty Emacs tricks.

For example, the second and third episodes reconsider the problem explored in VimGolf in Emacs e006. The final solution solves the problem in an incredible 10 keystrokes, beating the best Vim score by 7 strokes.

Not all the Emacs Rocks episodes discuss VimGolf problems through. Episode 1 deals with a small refactoring of some JavaScript code. In that video he needs to mark a rectangle and uses a nice trick that could be brought to bear on yesterday’s post. Recall that the problem was to sort

California             423,970 km²
Taiwan                  36,008 km²
Japan                  377,944 km²
Germany                357,021 km²
Iraq                   438,317 km²
Iran                 1,648,195 km²
Korea (North+South)    219,140 km²
Mexico               1,964,375 km²

by the number of square kilometers. I did that by marking the rectangle containing the numbers and calling sort-columns. I wasn’t really thinking about VimGolf so I didn’t mark the rectangle in an optimum way; I just said put the point here, set the mark, put the point there and call sort-columns. Here’s how the trick from Emacs Rocks can be used to mark the rectangle.

Let’s assume that after the first part of the problem, the point is left at the end of the last line. If we do a 【Ctrl+r␣␣42Return】 (where ␣ is a space), we end up two spaces in front of the the 423,970 in the first line, which is just where we want to be. Furthermore, since incremental search sets the mark at the starting point, we have marked the rectangle in only 6 keystrokes. A similar trick works if we begin with the point at the beginning of the first line: type 【Ctrl+e】 to move to the end of the line, then 【Ctrl+s1,9Return】 【Ctrl+3 Ctrl+b】 to move the point right before the 1,964,375.

I already knew that incremental search sets the mark, of course, because it tells me every time I do an incremental search. The insight I gained from Episode 1 of Emacs Rocks is that it can be a quick and easy way of marking a rectangle.

So welcome to Emacs Rocks. There are 6 episodes so far and I’ve enjoyed them all and am looking forward to more. It’s always nice to see Emacs in action.

Update ⌴ → ␣ (Thanks to Xah Lee for telling me the correct character for space)

Posted in General | Tagged | 2 Comments

The Emacs sort-columns Command

Xah Lee has caught the VimGolf with Emacs bug and proposed an interesting challenge. The final part of the solution involved sorting the following list by the number of square kilometers.

California             423,970 km²
Taiwan                  36,008 km²
Japan                  377,944 km²
Germany                357,021 km²
Iraq                   438,317 km²
Iran                 1,648,195 km²
Korea (North+South)    219,140 km²
Mexico               1,964,375 km²

Normally this wouldn’t be much of a problem but two things make it more difficult than usual. First, the line for Korea has an extra field so commands like sort-fields or sort-numeric-fields don’t work. Second, the numbers have commas in them so the numeric sorts don’t work.

I remarked on Xah’s blog that I had tried sort-regexp-fields but that that didn’t work because the sort was lexicographic rather than numeric. Then jm commented that the lexicographic sort will work if you include the spaces in front of the shorter numbers. He proposed using sort-regexp-fields with the regular expression .*\([0-9 ,]\{9\}\) km. That did the trick and I thought it was probably as simple a solution as we were apt to find.

Later I suddenly realized that an even simpler solution based on the same idea was to use sort-columns. To use that function, you mark the rectangle containing the columns you want to sort on and then just call sort-columns. Thus, I placed the point two spaces before 423,970 on the first line, typed 【Ctrl+Space】 to set the mark, moved the point to right after 1,964,375 on the last line, and typed 【Meta+xsort-columns to sort the list. That worked perfectly and is a reasonably concise solution.

As usual, Emacs had the right tool to get the job done even if it took a little effort to find it. Maybe next time this solution will jump right into my head. Or not.

Posted in General | Tagged | 5 Comments