(Re)Naming Functions

This is another note to myself. Quite often we want to give a function another name. Sometimes this is because we want a shorter name for a function that we use a lot. For example, even though I use smex I have several lines in my init.el file to quickly switch modes

(defalias 'om 'org-mode)
(defalias 'am 'abbrev-mode)
...

Another reason to rename a function is to change its functionality. The common example that everyone knows (even if they don’t do it) is to rename yes-or-no-p to y-or-n-p. We do this because we want to eliminate Emacs’ annoying insistence that we type “yes” or “no” in answer to certain questions.

There are two ways to rename functions

  1. Use defalias
  2. Use fset

Either one works where the other would but their operation is not identical. I can never remember the rules for when to use defalias versus fset, hence this note to myself.

Almost always, you want to use defalias because it records the file where the definition was made. Use it where a specific function name is being defined. The Elisp manual’s rule of thumb is that if you think of DEFINITION in

(defalias 'SYMBOL 'DEFINITION)

as the definition of the new function SYMBOL then you should use defalias.

Use fset for manipulation of function names. For example, if you want to change a function’s definition, you can use fset to save the old definition:

(fset 'old-some-func (symbol-function 'some-func))
(defalias 'some-func 'some-other-func-definition)

We use symbol-function in the fset so that we get the actual definition of some-func and not just its name, which is about to have its definition changed.

Posted in Programming | Tagged , | Leave a comment

Generalized Variables and Macros 2

Yesterday we talked about some of the difficulties in using setf in a macro and how these difficulties can sometimes be overcome by using the mysterious define-modify-macro. Today, I want to look at a more general approach that will also explain how define-modify-macro works.

Last time, we wrote the += macro to implement the C += operator. That worked out well so we might decide to do a -= and then a *= and so on. After awhile we realize that we’re repeating the same pattern over and over so we decide to write a general version, op=, that will take the operator we want as an argument. That is we want to write

(op= + x y)

instead of

(+= x y)

That way we have only one macro and it works for any operator:

(op= floor x y) → (setf x (floor x y))

We can’t use define-modify-macro here because it requires the name of the function at the time of the call to define-modify-macro and we want to make op= take the function as an argument. We also can’t write

(defmacro op= (op x y)
  `(setf ,x (,op ,x ,y)))

because of the problems we discussed last time.

To help us with problems like this, Common Lisp provides the function get-setf-expansion. To see how it works, let’s call it on the place we used last time, (aref a i):

CL-USER> (get-setf-expansion '(aref a i))
(#:G1409 #:G1410)
(A I)
(#:G1408)
(CCL::ASET #:G1409 #:G1410 #:G1408)
(AREF #:G1409 #:G1410)

The call returns 5 values. The second is a list of input arguments for the aref and the first is a list of corresponding temporaries into which those arguments should be evaluated. The third is a list (always of length 1) of a temporary into which the final value to be stored should be put. The fourth value is code to store the final value and the fifth is code to retrieve the value referenced by the setf argument.

We want our macro to expand into something like

(let* ((#:G1409 A)
       (#:G1410 I)
       (#:1408 (op (aref #:G1409 #:G1410) y)))
  (CCL::ASET #:G1409 #:G1410 #:G1408))

Notice that if the i variable is something like (incf i) this still works because i is evaluated only once.

With that skeleton, it’s pretty easy to write the macro

(defmacro op= (op place y)
  (multiple-value-bind (temps args val setter getter)
      (get-setf-expansion place)
    `(let* ,(append (mapcar #'list temps args)
                    `((,(car val) (,op ,getter ,y))))
       ,setter)))

When we expand it we get

CL-USER> (macroexpand '(op= + (aref a i) 3))
(LET* ((#:G1470 A) (#:G1471 I) (#:G1469 (+ (AREF #:G1470 #:G1471) 3))) (CCL::ASET #:G1470 #:G1471 #:G1469))
T

which is a slightly less well-formatted version of our skeleton. When we try it out, we get the expected result

CL-USER> (let ((a #(2 4 6 8)) (i 2))
           (op= + (aref a i) 3)
           a)
#(2 4 9 8‍)

The idea for the op= macro is based on Paul Graham’s _f macro from On Lisp, a great book for learning about macros.

We’re now in a position to understand define-modify-macro. What it does is to take its arguments and then build a defmacro much like op=‘s. The resulting macro calls get-setf-expansion, sets up a let* just like op=, and then inserts ,setter as the body of the let*.

Posted in Programming | Tagged | Leave a comment

Generalized Variables and Macros 1

One of the wonders of Common Lisp is the generalized variable. Roughly speaking, a generalized variable is an expression that can serve as the first argument to setf. The official explanation, as given in Common Lisp the Language, 2ed., is here. A convenient way of thinking about generalized variables is that they name a place that can contain a Lisp object.

The easiest such case is a simple variable such as x. In the expression

(setf x (* x 3))

x is the name of a place that will hold a value 3 times larger than its current value after the setf is executed. Notice that since x can occur as the first argument to setf it is a (trivial) example of a generalized variable.

A meatier example is (car x). The (car x) names a place (the car of the cons x) that can hold a value. As with the previous example, we can use the name of that place to both get and set the object it contains:

(setf (car x) (* (car x) 3))

Things get interesting when we try to use setf in macros. For example, suppose we want to write a macro that implements the C += operator. We might try something like

(defmacro += (x y)
  `(setf ,x (+ ,x ,y)))

This seems to work pretty well.

CL-USER> (let ((a #(2 4 6 8)) (i 2))
           (+= (aref a i) 3)
           a)
#(2 4 9 8‍)

But suppose we want to increment two entries in a row

(defun incr2 (a i)         
  (+= (aref a i) 3)
  (+= (aref a (incf i)) 3))

CL-USER> (let ((a #(2 4 6 8)) (i 1))
           (incr2 a i)
           a)
#(2 7 11 8‍)

What happened? Instead of #(2 7 9 8‍) we got #(2 7 11 8‍). The experienced macro writer will see immediately that the problem is that the += macro evaluates its first argument twice. Most of the time, as in the example before last, that doesn’t matter but in the last example it causes i to be incremented twice. Expanding the macro call (+= (aref a (incf i)) 3) shows what happened

CL-USER> (macroexpand '(+= (aref a (incf i)) 3))
(CCL::ASET A (INCF I) (+ (AREF A (INCF I)) 3))
T

The first (incf i) increments i to 2 so that the result will be stored in the 3rd slot of the array. The second (incf i) increments i to 3 so that we add 3 to the 4th slot of the array and store 11 in slot 3.

The usual way of handling this sort of thing is to evaluate the variable once into a temporary and then use the temporary in the rest of the macro. But that doesn’t work here because setf is itself a macro and needs the name of the place to figure out how to get and store the value. Fortunately, there’s an easy way of addressing this problem for the += macro. Instead of our previous definition, we use

(define-modify-macro += (y) +)

What’s happening here is not obvious but this says to create a macro named += that takes two arguments, the place to be set and y, operates on them with +, and stores the result in place. See the Common Lisp HyperSpec for the details on define-modify-macro.

With this definition of += things work correctly

CL-USER> (let ((a #(2 4 6 8)) (i 1))
           (+= (aref a (incf i)) 3)
           a)
#(2 4 9 8‍)

In this example, place is (aref a (incf i)) so the result is equivalent to

(let ((i (incf i)))
  (setf (aref a i) (+ (aref a i) 3)))

although that is not the actual expansion.

Next time, we’ll look at some macros using setf that require more general methods. After that, it will be easier to see what define-modify-macro is actually doing.

Posted in Programming | Tagged | Leave a comment

Some RSA Public Keys Are Insecure

According to The New York Times, a team of European and American researchers have discovered that some (about 0.2%) RSA public keys are insecure. The insecurity is the result of using prime factors that aren’t cryptographically random. I’m still reading the paper but it appears that poor random number generation resulted in shared factors between many of the keys and in many cases shared moduli. One group of keys sharing a modulus had 16,489 keys in it.

It’s an interesting paper and worth a read if you’re interested in cryptography and security. One startling fact from the paper is that the authors used “unsophisticated methods” in their work and said they find it hard to believe that their results haven’t already been used for exploits.

Posted in General | Tagged | Leave a comment

UTF-8 Characters In Emacs

I’ve mentioned several times that I use Xah Lee’s excellent HTML/XML Entities List page to look up the code points for UTF-8 characters that I sometimes use in my blog posts. For example, in writing about Emacs Registers I wrote that you can save the point to register ρ with 【Ctrl+x r Space ρ】. My usually way of doing this is to type 【Ctrl+x 8 Return】, lookup the code point on Lee’s page, enter it, and then press 【Return】. That’s a fairly long process but I don’t do it that often so I never really minded all that much.

Now, once again, Emacs-Fu shows us the way. I’ve long been aware of abbrev-mode, of course, but I hadn’t investigated it or thought much about it because, in general, I find automatic abbreviations annoying. They’re always overriding what you type whether or not it’s really what you want. DJCB suggests a nice trick. He adds a 0 to the end of each abbreviation so that you aren’t likely to have it expanded unintentionally. In the unlikely event that I actually wanted rho0 in the buffer I would just type rho0 followed immediately by 【Ctrl+q】 (that is, by quoting the following space or punctuation mark).

As DJCB explains, the easiest way to set this up is to simply type 【Meta+xedit-abbrevs and then add whatever abbreviations you need to either the global section or whatever mode you want them in. Save the file and turn on abbrev-mode if it’s not already on and the substitutions happen automatically unless you quote the following character. It’s probably a good idea to take a look at user level Abbrevs in the Emacs manual too.

Update: mark → point (【ctrx+x r Space ρ】 saves the point not the mark.)

Posted in General | Tagged | 2 Comments

Centering Text In Emacs

I was watching another one of Kurt Schwehr’s Emacs videos and came across something I didn’t know (or at least something I’d forgotten). You can center text on the line with 【Meta+o Meta+s】. By default it will center the line the point is on but you can center N lines by specifying a prefix. Thus to center the next 3 lines you would type 【Meta+3 Meta+o Meta+s】.

That’s handy for those times when you’re producing a text file and want to center text for headings or whatever. The centering respects the fill column so it’s always accurate.

Posted in General | Tagged | Leave a comment

More Org Header Searching

The little Org-mode header searching functions that I wrote about in Finding Org Headers And Links turned out to be pretty useful so I added another one. This function is like find-all-org-headers except that it limits the search to those headers that contain a search term.

(defun find-an-org-header (term)
  (interactive "sSearch Term: ")
  (find-org-markers (concat "^\\*+ .*" term)))

The find-org-markers function is described in the Finding Org Headers And Links post. As before, it’s a very simple function but makes it easy to find the header you’re looking for, especially if the trees are collapsed.

Posted in Programming | Tagged , , | Leave a comment

A Short Coda To Yesterday’s Post

Yesterday I wrote about Finding Org Headers And Links and gave some Elisp functions to aid in searching for them. Today, my bank statement came and I entered information from the statement into my Org tax file. The tax file has several headings and subheadings for various kinds of data. Typically, the subheadings contain an Org table with information on expenses such as the date, check number, expense, and amount.

That gave me a chance to use the find-all-org-headers function. I called the function and the frame split with an *Occur* buffer opened in the other window. The focus was in the *Occur* buffer so I did a 【Ctrl+s】 to search for the proper subheading for the first expense, hit 【Return】 and I was popped right into the tax buffer at the proper place. I typed 【Tab】 to expand the heading, entered the data in the table, and then typed 【Ctrl+x o】 to return to the *Occur* buffer and repeat the process for the next expense. It was much quicker than my old method of hunting around in the tax file by hand.

Posted in General | Tagged , | Leave a comment

Org Mode Video

Looking through the ErgoEmacs Google+ Page, I found this post about Kurt Schwehr’s video on Org Mode. It’s a nice video that covers some of the basics of Org Mode and Babel. It’s just shy of 30 minutes so he covers a good amount of material but it’s still short enough to watch between other tasks.

The video is for a course in Research Tools that Schwehr taught at the University of New Hampshire. All together there are 20 videos, many of them about Emacs. There are also mp3s available for the classes as well as all the other material so anyone who’s interested can take the class on their own. Some of the individual lectures look interesting and appear to stand on their own so even if your aren’t interested in the entire course, you may find parts of it useful.

I haven’t watched the other Emacs videos yet but I plan to. I’ll post about any that I think Irreal readers would enjoy.

Posted in General | Tagged , | 1 Comment

Finding Org Headers And Links

Today I was looking through Xah Lee’s ErgoEmacs Google+ Page (there’s a ton of interesting stuff there—you should check it out) when I came across this post in which someone asks how to find links in an Org mode buffer. Later, in the comments, someone else asks how to locate the headers in an Org mode buffer. Serendipitously, a bit later I came across this post in the Org Mode mailing list that gives a partial answer to the question.

That got me thinking that being able to find these quickly would be very useful. For example, I have all my tax information in an Org Mode file with lots of headings and subheadings for various categories. Being able to show a list of all the headings and then being able to click on one and go right to it is a real time saver, especially when the trees are collapsed. As Marc-Oliver Ihm suggest in his post to the mailing list, the easy way to do this is with occur.

My solution involves 4 functions. The first is a utility function that does all the work:

(defun find-org-markers (regexp)
  (occur regexp)
  (pop-to-buffer "*Occur*"))

It takes a regular expression as input, searches for matching lines with occur, and then pops to the *Ocurr* buffer so that you can choose one.

The next two functions search for Org headers

(defun find-top-org-headers ()
  (interactive)
  (find-org-markers "^\\*[^*]"))

(defun find-all-org-headers ()
  (interactive)
  (find-org-markers "^\\*+"))

The first, find-top-org-headers, finds all the top level headers (those beginning with a single star). The second, find-all-org-headers, finds all the headers.

Finally, find-org-links locates the outbound links in an Org Mode buffer:

(defun find-org-links ()
  (interactive)
  (find-org-markers "\\[\\["))

I’m not completely satisfied with this function because it just searches for the [[ that begins a link. I would rather use the regexp \\[\\[.*\\]\\] but occur won’t match over more than one line and links frequently span two or more lines. Still, it works well enough to be useful.

These are very simple functions but useful nonetheless. Perhaps you will find them useful too.

Update: Jonathan notes that it’s a good idea to add a \\b to the end of the regexps in find-top-org-headers and find-all-org-headers so that they won’t match, for example, bold text that comes at the beginning of a line.

Update 2: Well that seemed like a good idea but the \\b doesn’t work. Instead, replace the [^*] in find-top-org-headers with a space and add a space after the + in find-all-org-headers.

Posted in Programming | Tagged , , | 4 Comments