Emacs Align Functions

Tim Visher has a new VimGolf in Emacs up. This time it’s a simple alignment problem using align-regexp, a function that we’ve talked about before. In this case he just used the simple align-regexp case and was done in about 6 keystrokes, much less than the 18 that the best Vim solution took.

It turns out the the align function, of which align-regexp is a special case, is very flexible. It will try to align the region or current group of text in a context dependent way. The action of align is specified by a set of rules that specify context (such as major mode), a regular expression, and some other attributes. The list of rules is in the variable align-rules-list. The documentation for that variable explains the various options and gives its current value. You can also pass in your own list of rules. The align-regexp function basically just prompts you for an ad hoc rule.

Unfortunately, the documentation isn’t very good and the rules can be quite complex. Visher mentions this page from the EmacsWiki that gives some examples but it is by no means a complete explanation. This is a very powerful function and I wish the documentation on it was better. Unfortunately it isn’t even mentioned in the Emacs manual.

Posted in General | Tagged | 1 Comment

Emacs comment-box Revisited

Last week I wrote about Comment Boxes In Emacs and gave some examples of how the comment-box command provides an easy way to draw a box around a comment. The only problem is that I want the boxes to extend almost to the right hand margin. Instead of

##########################################
# get-cred -- Get the user's credentials #
##########################################
(defun get-cred ()
...)

I want

##########################################################################
# get-cred -- Get the user's credentials                                 #
##########################################################################
(defun get-cred ()
...)

One could argue, I suppose, that this adds nothing except some useless blanks to the file but I’ve always done it that way and as Henry Higgins might say, “I’ve grown accustomed to its face.” So, how to do it?

My idea was simple: pad the first line with blanks out to the fill column, and then call comment-box to draw the actual box. There’s nothing special about using the fill column as the right hand edge but it makes the function behave well for any size window.

I thought I’d knock off a quick bit of Elisp and be done. It didn’t work out that way. I kept getting a mysterious error that appeared to come from save-restriction (see the code below). After that lot of mucking about I discovered that the real problem was the call to comment-box. The documentation says that there’s an optional third argument to add extra space and, indeed, the beginning of the function is

(defun comment-box (beg end &optional arg)
...)

so I didn’t bother specifying the third argument. It turns out, though, that in the comment-box function we have this line

(comment-region beg end (+ comment-add arg))

so that the optional argument is always used. It works OK in the interactive case because the call to interactive is

(interactive "*r\np")

which causes the prefix argument to be passed to arg. When no prefix argument is specified, this results in a 1 being passed to arg so arg is never nil the way it is if you call comment-box from Elisp with only two arguments. That’s obviously a bug but it’s a small one. At least it’s a small one once you figure out what’s happening.

In any event, once I solved that problem it was easy to write the function:

(defun jcs-comment-box ()
  "Draw a box comment around the region but arrange for the region
to extend to at least the fill column. Place the point after the
comment box."
  (interactive)
  (with-region-or-buffer (b e)
    (save-restriction
      (narrow-to-region b e)
      (goto-char b)
      (end-of-line)
      (insert-char ?  (- fill-column (current-column)))
      (comment-box b (point-max) 1)
      (goto-char (point-max)))))

As you can see, we first move to the beginning of the first line, then to its end, and then we pad the line with blanks out to fill-column. A few comments on the rest of the code:

  • It would probably be easier to use
    (interactive "r")
    

    rather than the with-region-or-buffer macro but I write that almost automatically when I’m dealing with a possible region so I just kept it.

  • insert-char does nothing if the count is not positive so I didn’t have to worry about whether or not the first line already extended to or past the fill column.
  • Using the narrow-to-region function makes it really easy to move around the buffer and helps deal with the fact that I’m changing the size of the region as I go. This problem was described by Xah Lee.
  • Notice that even the narrow-to-region doesn’t completely insulate me from the effects of changing the buffer size. I have to use (point-max) as the end of the region (instead of b) in the call to comment-box because b no longer points to the end of the region.
Posted in Programming | Tagged | 2 Comments

Xah Lee On Inserting Brackets In Emacs

Xah Lee has an interesting post on inserting bracket pairs in Emacs. This is exactly the same thing that I did using Key Chord Mode as I described in this post. The difference is that Lee uses Elisp code directly and has a function for every imaginable pair of brackets. If you use a lot of brackets in your HTML, as he does, it’s worth while grabbing his code.

For guys like me who use mainly parentheses, square brackets, and the occasional pair of braces, the Key Chord Mode solution works well and is easier to implement. The only pairs I have implemented are the angle brackets for HTML tags and double quotes. I’d definitely do parentheses too except that the Paredit minor mode takes care of that for me.

Lee has 22 little functions to insert these pairs so you might wonder where he finds enough key sequences to bind to them. The answer is the hyper key. None of the standard Emacs functions use the hyper key (or at least don’t use it exclusively) so it’s an ideal modifier to use with private functions. The question for most people is: what key is the hyper key?

That depends on what type of system you’re using. Windows, OS X, and Linux can all be configured with a hyper key but the key and the configuration steps differ. Fortunately, Lee’s post has a section that shows you how to configure it for all three system types. To my mind, that section is probably the most valuable part of his post. If you’d like an extra modifier key, be sure to check it out. He also has a separate page on how to set up the hyper and super keys.

Posted in General | Tagged | Leave a comment

And The Winner Is…

password. SplashID has a list of 2011’s 25 most popular passwords as culled from the various exploits of LulzSec, Anonymous, and others. As expected, the runner up is 123456. Readers of this blog will find none of this surprising but it sure is depressing.

Follow the link and see for yourself. Sadly, I’m sure these people think they’re being clever in their choices. I suppose in a way it makes them low hanging fruit and therefore makes sensible folks marginally safer but that’s small comfort when you look at the list. It’s not as if this was some esoteric subject known only to experts. It doesn’t seem to matter how often the sermon is preached, people just aren’t going to be sensible about their password choices.

Posted in General | Tagged | Leave a comment

Another Emacs Cheat Sheet

Artur Hefczyc has an nice table of the Emacs keybindings. They are listed alphabetically by command name, not by action, so you need to know a good approximation to the name of the command you’re trying to run. It’s a nice table and worth bookmarking or even printing out if you’re inclined to use paper cheat sheets.

Of course, you can always get a complete list of the current keybindings for your Emacs with 【Ctrl+h b】 but I find it difficult to locate the command I’m looking for with it.

Posted in General | Tagged | 1 Comment

Text Replacement In Several Files With Emacs

Just a quickie. I was browsing around in Aaron Hawley’s Giant Emacs Reference Sheet when I came across this little ditty:

C-x d *.c RET Q int RET long    

It was described as “replace ‘long’ for ‘int’ in .c files.” I thought, “Boy, that’s really handy” and then I realized that it’s just

  1. Enter dired and list all the .c files
  2. Do a query replace substituting long for int

something that I’ve probably blogged about in the past.

Still, it does seem to gain power when you think of it as one command. And, if for only a moment, I thought I’d found something new and wonderful.

Posted in General | Tagged | 5 Comments

Administrivia

The scum spammers, who doubtless describe themselves as SEO consultants, have discovered a new way to get links into forum comments: trackbacks and pingbacks. Irreal does have the occasional legitimate trackback and I enjoy them as they give me a sense of who’s reading the blog and what they have to say about the topics we consider here. Lately, though, they’ve all been phony trackbacks designed to get Google to notice a link to some site or another that has nothing to do with Irreal or the things we talk about here.

Therefore, I’ve turned off trackbacks/pingbacks. Comments will remain as they were: unmoderated but requiring a CAPTCHA or registration.

Posted in Blogging | 1 Comment

Comment Boxes In Emacs

Here’s a neat little hack that can save a bit of time. Emacs has the comment-box command that will put a mode-specific comment box around a region. For example, suppose you have the Elisp

A function to do something very profound.
It is called from the top level.
(defun be-profound ()
...)

and that you select the first two lines and call comment-box. You get

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; A function to do something very profound. ;
; It is called from the top level.          ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun be-profound ()
...)

Similarly if you have some C code like

Here is the the main function
that does something or another

int main ( int argc, char **argv)

and select the first two lines and call comment-box you get

/**********************************/
/* Here is the the main function  */
/* that does something or another */
/**********************************/

int main ( int argc, char **argv)

Back when I was writing a lot of C code I used to put a comment box like that in front of every function. I did it by hand so it was sort of pain. I wish I’d had, or known about, something like comment-box to help me out (that was when I was using Vim).

Posted in Programming | Tagged | 3 Comments

It’s Time For Publishers To Get A Clue

Those of you who have been dropping by this blog for a while know that I’ve written several posts about the publishing industry and its consistent failure to accept that things are changing (see The Future Of Books, More Bad News For The Publishing Industry, and More Amazon Disruption). Now, Jon Evans over at Tech Crunch takes up the same theme with Dog Bites Man; Pope Condemns Violence; Publishing Still Doesn’t Get It.

Evans mostly discusses the publishers’ and Authors Guild’s reactions to Amazon’s introduction of the Kindle Owners’ Lending Library but also touches on the publishers’ treatment of ebooks in general. The picture he paints isn’t pretty. It’s a picture of ignoring what their customers want, of refusing to acknowledge that the future is coming, of lost opportunities, and, in general, of behaving stupidly.

He notes all the usual problems: failure to deliver a subscription model desired by their customers, inflated ebook prices, petty behavior when an author shows “disloyalty” by signing a deal with another publisher, and a general failure to deal with the reality of ebooks.

The failure to take ebooks seriously is, to my mind, one of their worst shortcomings. Just as Borders failed to take Internet sales seriously and paid the ultimate price, publishers treat ebooks as a slightly disreputable stepchild, not to be taken as seriously as “real” books; as a problem to be dealt with rather than an opportunity to be seized.

Case in point: the deplorable production values in ebooks. It’s hard to understand how they could do so poorly. The ebook process starts with the same files as a dead tree book but somehow comes out the other end with missing words and letters, poor spacing, fouled up typography, and inconsistent capitalization. Neal Stephenson’s Reamde was so poorly done that it was withdrawn from the Kindle store. Sadly, Stephenson’s book is not a fluke. Thomas Rhiel has a blog post that recounts other examples. (Be sure to follow the ebook typography is terrible link in Rhiel’s post for some graphic examples.)

Rhiel’s post makes a telling point about the publishers’ failure to leverage the opportunities afforded by the ebook format. Historically, publishers print photographs on glossy paper and bind them in the middle of the book because it’s too expensive to bind the individual glossy pages in the proper place. But there’s no excuse for doing the same thing in an ebook. The photo should appear in the logical place in the book or, as Rhiel says, at least at the end of the book in its own section instead of the middle of a chapter to which they bear no relationship.

Clearly, these books are not receiving proper editorial scrutiny. Meanwhile, the publishers are telling us that they have to charge high prices for ebooks because, after all, it’s not the printing and shipping that costs the money but the editorial effort. Please. Produce a competent product that shows some of that editorial effort and we’ll talk. In the mean time you’re just looking clueless and indifferent.

Publishers can continue to pretend that everything is the same as it’s always been, that customers have nowhere else to go, and that there’s no reason—no reason at all—to change their business model but the truth is that things are changing. Amazon is not just threatening to eat their lunch but to steal the crown jewels. Tired of dealing with publishers who don’t want to do anything new or different, they are now offering authors direct deals as I recounted in the More Bad News For The Publishing Industry post. Among the defectors, by the way, is Neal Stephenson. Perhaps he’ll finally get a clean ebook out of the deal.

Posted in General | Leave a comment

Highlighting Regexps, Phrases, And Lines In Emacs

I mostly use isearch-forward, 【Ctrl+s】, and isearch-backward, 【Ctrl+r】, to search for words or phrases in a buffer. Sometimes, though, it’s convenient to see all the matches at once. Emacs has a set of commands that make this easy.

The easiest to use is highlight-phrase, which is bound to the 【Meta+s h p】 sequence. It will ask you for a phrase and highlighting color and then highlight all the matching phrases in the buffer. The nice thing about highlight-phrase is that any whitespace is automatically converted to arbitrary whitespace and initial lower-case letters are made case insensitive so it’s pretty much a “do what I mean” command.

The next command, highlight-regexp, is a little more general. It’s bound to 【Meta+s h r】 and lets you highlight anything that matches an arbitrary regexp.

The command highlight-lines-matching-regexp is similar to highlight-regexp except that it highlights the entire line that contains the match to the regular expression. It is bound to 【Meta+s h l】.

Finally, you can un-highlight the matches with unhighlight-regexp, bound to 【Meta+s h u】.

Summary

Key Sequence Command
Meta+s h p highlight-phrase
Meta+s h r highlight-regexp
Meta+s h l highlight-lines-matching-regexp
Meta+s h u unhighlight-regexp

Update: let → set.

Posted in General | Tagged | 1 Comment