Eval And Replace In Emacs

I was watching another of Tim Visher’s VimGolf videos in which he builds a multiplication table by the clever use of keyboard macros. What got my attention, however, was his use of the function eval-and-replace that evaluates the sexp preceding the point and replaces it with its value. This seemed like a useful thing to be able to do but as Visher explained, eval-and-replace is part of the Emacs Starter Kit and not part of Emacs itself.

I have a fairly large init.el that I’ve developed over time and therefore never installed the starter kit even though I’ve heard good things about it. Rather than hunt up the starter kit to get the function, I just rolled my own:

(defun eval-and-replace (value)
  "Evaluate the sexp at point and replace it with its value"
  (interactive (list (eval-last-sexp nil)))
  (kill-sexp -1)
  (insert (format "%S" value)))

The eval-last-sexp in the interactive declaration evaluates the sexp and passes its value to eval-and-replace. Then the (kill-sexp -1) deletes the sexp from the buffer. Finally the value is inserted into the buffer with the insert function.

I originally wrote the function using a let to capture the value of the sexp instead of using the interactive declaration but this seemed a bit shorter and I wanted to use an expression in the interactive declaration, as I wrote about here, to fix the idea in my mind.

I can see all sorts of uses for eval-and-replace. As a trivial example, suppose I want to say 223=8388608 but I don’t remember the value of 223. I could switch over to my calculator buffer to make the calculation and then cut and paste it to my text or I can just write

2^23=(expt 2 23)

and call eval-and-replace to put the value in the text for me.

I’ve added eval-and-replace to my init.el so that I’ll have it available the next time I have a need for it.

Posted in Programming | Tagged , | 10 Comments

Transposing In Emacs

Most Emacs users know about using 【Ctrl+t】 to transpose two letters and 【Meta+t】 to transpose two words but there are two other useful transposition commands.

You can use the sequence 【Ctrl+x Ctrl+t】 to transpose two lines. As with the other transposition commands, it drags the line preceding the point forward so that you can move a line down any number of lines. For example, if you have

Line 1
Line 2
Line 3
Line 4

and the point is at the end of Line 1 or anywhere one Line 2 and you type 【Ctrl+x Ctrl+t】 twice (or give a a prefix of 2) you get

Line 2
Line 3
Line 1
Line 4

The other transposition command is for balanced expressions or sexps. This is a little more useful than you might think—especially if you’re not a Lisp programmer—because of the definition of “balanced expression.” See the explanation of balanced expression in the Emacs manual. To transpose balanced expressions, use the sequence 【Ctrl+Meta+t】.

One final neat feature: if any of these commands is given a repeat count of 0—which nominally makes no sense—then the objects ending after the mark and point are exchanged.

Posted in General | Tagged | 2 Comments

Emacs Poll On Deleting And The Active Region

Virtually all GUI environments will delete a highlighted region when the 【Backspace】/【Delete】 key is pressed or when a character is inserted into the region. Emacs does not currently do that except in a few minor modes such as CUA mode.

RMS has a post on the help-gnu-emacs list asking for reader input on a proposed change to implement this behavior in Emacs 24. Readers are asked to send an email to emacs-delete-poll at gnu.org answering a few questions about the proposal (basically, whether you’re in favor or not and why). The Emacs 24.0.90 pretest build has this change implemented for those who would like to try it out.

My first reaction when reading it was to be opposed on the grounds that it would be too easy to inadvertently delete a region. After a little thought, though, I realized that I never have any problem with this behavior anywhere else and it’s easy to recover from a mistakenly deleted region in Emacs with 【Ctrl+/】or whatever you use for undo.

RMS doesn’t say, but presumably the change could be disabled for those who don’t want it. (I know, I know everything is configurable in Emacs if you know Emacs Lisp—I mean with a single line in init.el.) If that is the case then it’s hard to see how anyone could object. (Actually, some of the commenters do object even in the face of such a flag on the philosophical grounds.)

My conclusions are that I don’t care whether they make this behavior the default as long as it can be disabled1 and that I will probably disable it on the grounds that I’m used to the old behavior. What do you think?

Footnotes:

1 It looks as if setting delete-active-region to nil disables the change.

Posted in General | Tagged | 1 Comment

R7RS WG1 Update

Via Grant Rettke over at Wisdom and Wonder I found these slides from a talk at LispNYC by John Cowan on September 13. As readers from my old blog will recall, R7RS will be split into a “small Scheme” and a “large Scheme” with the small version being a modest expansion of R5RS and the large version being more like R6RS but still downward compatible with the small version.

Working Group 1 (WG1) is tasked with the small Scheme and has almost completed its work. Cowan expects the final committee draft to be out in a few weeks and after formal comments the final version. Working Group 2 is a subset of WG1 and has pretty much suspended their work until WG1 is completed.

Very often it’s hard to make sense of the slides from a presentation without having heard the actual talk. In this case, however, the slides stand alone very well and are quite informative. If you’re interested in Scheme and want to know what’s coming up, take a few minutes to look through them.

Added at the last minute: Video of Cowan’s talk is here. There’s a nice discussion of it on Slashdot.

Posted in Programming | Tagged | Leave a comment

VimGolf In Emacs

I recently saw a reference to Tim Visher’s VimGolf in Emacs videos on one of my feeds. It looked interesting so I hopped over to take a look. VimGolf is a site that poses editing challenges that are supposed to be done in Vim. As with golf, the winners are those with the lowest number of (key)strokes. Visher uses these challenges as a basis for videos that highlight various Emacs techniques. Why should Vim users have all the fun, after all?

I’ve watched a couple of the videos and already learned something very useful. I’m not sure what people who grew up with computers are doing but when I learned to type in high school—on a typewriter—we were taught to put two spaces after the period at the end of a sentence. This made sense with the monospaced typescript that typewriters produced but is incorrect for proportional fonts. After reading this rant on the practice I started using just a single space. Then one day I read that I could move forward and backward by sentences using 【Meta+a】 and 【Meta+e】. The problem was that it seemed to move by paragraphs instead. Moving by sentences isn’t something I do a lot so I just shrugged my shoulders and moved on.

During one of Visher’s videos, I learned that by default Emacs uses a period and two spaces to delimit sentences. That was why moving by sentence wasn’t working for me. The solution to the problem is trivial: simply put

(setq sentence-end-double-space nil) ;period single space ends sentence

in your .emacs or init.el file. After doing that, moving by sentences worked correctly.

I really recommend these videos. They’re entertaining and full of things that you might not have known. The later videos show the keystrokes on the screen but the earlier ones don’t so you have to pay attention to what Visher is saying. Still, it’s worth the effort. I’m sure I’ll be passing on other tidbits as I learn them.

Posted in General | Tagged | 4 Comments

Using Emacs To Convert Notes For Deft

Yesterday I wrote about Vivek Haldar’s Deft patch that allowed him to integrate his previous notes into Deft. Recall that Deft uses the first line of a note as its subject and names the file for a note deft-XXX whereas Haldar used the filename to describe the subject of the note. After I published that post I thought that it might have been easier to simply convert the existing notes to Deft format by making the file name the first line of the note.

It turns out that it is pretty simple to do that. Let’s assume that the file names are something like /Users/jcs/notes/ideas-for-Hercules-project.txt. We want to take the file name and convert it into a subject line by removing the directory information, removing the extension, changing the dashes to spaces and inserting the result as the first line of the file. Here’s a bit of Emacs Lisp that does that for one file:

(defun file-to-subject (filen)
  (let ((subject (replace-regexp-in-string
                  "-" " "
                  (file-name-sans-extension (file-name-nondirectory filen)))))
    (with-temp-buffer
      (insert-file-contents filen)
      (goto-char 1)
      (insert (concat subject "\n"))
      (write-file filen))))

The let at the beginning of the function converts the file name to a subject line. Then the file is read into a temporary buffer and the subject line is inserted at the beginning of the buffer. Finally the new file is written over the old.

To process all the files in, say, the ~/notes directory we could use the line

(mapc 'file-to-subject (directory-file "~/notes" nil "\\.txt$"))

or for more complicated directory structures we could use Dired to mark the files we want to convert and then use 【w】 (bound to dired-copy-filename-as-kill) to put the file names in the kill ring. Then we could just yank them right into the mapc in place of the (directory-file "~/notes" nil "\\.txt$").

That leaves changing ideas-for-Hercules-project.txt to deft-XXX. That could be done in several ways, with or without Emacs, but if you want to do it in Emacs here’s what you need for one file

(defvar deft-num 0)

(defun deft-name (filen)
  (rename-file filen (format "deft-%03d" (incf deft-num))))

The incf function1 increments deft-num and returns the incremented value so that the first time deft-name is called the format will return deft-001 and then deft-002 and so on.

You can do all the files with a mapc similar to what we used above. Alternatively, we could place the call to deft-name after the call to write-file in the file-to-subject function.

Footnotes:

1 incf is part of the Common Lisp package so you’ll need a (require 'cl) if you don’t already have it.

Posted in Programming | Tagged | Leave a comment

Deft Filenames

I’ve written a couple of times about Deft, which I described as a lightweight alternative to Org Mode. I’m still not using it for the reasons that I gave in those posts but lots of people are. One of those people, Vivek Haldar, liked it very much but had a problem. He had a bunch of pre-existing notes that used the filename as the subject of the note whereas Deft uses names of the form deft-xxx. He wanted to integrate his existing notes with Deft so he wrote a patch for Deft that added an option to use his method. Jason Blevin, the author of Deft, accepted his patch and added it to his source tree. Thus if you’re interested in Deft but were holding back because you already had notes with descriptive filenames, you no longer have an excuse not to try it out.

Posted in General | Tagged | Leave a comment

Inserting Quotation Marks In Emacs Revisited

The other day, I wrote about Inserting Quotation Marks In Emacs Org Mode and I wrote a little bit of elisp to insert \ldquo{}\rdquo in the buffer and then place the point between the two quote commands. I remarked at the time that what I’d really like is to just insert “” so that the quotes would work anywhere not just in an Org mode buffer. When I tested that, however, Org mode thought the buffer encoding was something besides UTF-8 and got confused.

After a bit of prodding by Xah Lee, I decided to figure out what was going on. I couldn’t find anything wrong and when I tested again everything worked fine. Somehow or other I must have set the wrong encoding and that’s why the Org mode exporter complained. When my language environment is set to UTF-8, everything works as expected. Thus I’ve added

(set-language-environment "UTF-8")

to my init.el file and I’ve changed my dq function to

(defun dq ()
  "Insert double quotes in an org buffer."
  (interactive)
  (insert "“”")
  (backward-char))
Posted in Programming | Tagged , | 4 Comments

Steve Jobs

I awoke this morning to the sad new that Steve Jobs had died. Of course, I was shocked but as Charlie Stross points out, I shouldn’t have been

Once his illness became public knowledge his level of activity,
already frenetic, became that of a man desperate to complete his
life’s work. People like that don’t go gently into the dark
night. They don’t leave the office unless they’re dragged away on a
stretcher. When he resigned as CEO of Apple in August, I expected him
to be dead within a week; I’m surprised he lasted this long.

That sounds right to me. Although he was by all accounts a devoted family man there was always “just one more thing.”

There’s been much twaddle in the technical press and blogosphere lately about Steve Jobs being this generation’s Edison; Steve Jobs not being this generation’s Edison and so on. I don’t know about any of that but I do know that he was a visionary unparalleled in his time. A man obsessive about attention to detail and a man who would accept nothing but the best from himself and those around him.

Steven Levy, technology’s biographer, has a touching obituary of Jobs over at Wired and the New York Times has a lengthy story on his life and accomplishments. Like most people, I never met Jobs but his work touches me on a daily basis and I will miss him.

Update: except → accept

Posted in General | Leave a comment

The Emacs interactive Special Form

Xah Lee has an interesting post that taught me something I already knew. The problem that Lee deals with is how to write an Emacs command (that is, a function callable by, say, 【Meta+x】 and the function name) that is also callable directly from elisp code. In general, that’s not hard because interactive functions are always callable from elisp. In Lee’s case, the problem was that the function was called differently in the two cases: when called interactively, the function was passed the beginning and end of a region to work on; when called directly, it was passed a string. Lee has a nice solution and if you write Emacs Lisp you should take a look at how he solved it.

What I want to talk about is the interactive declaration. If you’ve written any Emacs Lisp you know that it specifies how arguments are to be passed to the function when it’s called interactively. Normally this is specified by code letters in a string that makes up the argument to interactive. For example,

(interactive "nEnter a number: ")

says that the function will be passed a number that Emacs will prompt the user for with Enter a number:. Similarly,

(interactive "p")

passes the function the prefix argument. All the prefix codes are in the built in documentation as well as the Emacs Lisp Manual.

You can also pass interactive an expression instead of a string and have the expression return a list of the arguments to pass to the command. That’s the part that I learned but already knew. I already knew it because I read it every time I look up interactive in the built in documentation to check the code letters. Somehow, though, it just never sunk in. Maybe because it’s hard to imagine a realistic use case. Fortunately, Lee has more imagination that I do and came up with a very good use case. Again, you should look at his post to see a nice example of passing interactive an expression instead of a string.

The full story on interactive is in the Section 21.2.1 of the Emacs Lisp Manual. There’s a lot of useful information in there that’s worth reading about.

Posted in Programming | Tagged | Leave a comment