Solution To The Emacs Programming Challenge

A few days ago, I posed an Elisp programming challenge that asked you to make the record

(record
  (date "2005-02-21T18:57:39")
  (millis 1109041059800)
  (sequence 1)
  (logger nil)
  (level 'SEVERE)
  (class "java.util.logging.LogManager$RootLogger")
  (method 'log)
  (thread 10)
  (emessage "A very very bad thing has happened!")
  (exception
    (emessage "java.lang.Exception")
    (frame
      (class "logtest")
      (method 'main)
      (line 30))))

executable in such a way that it transforms itself into the equivalent XML record when executed.

On the day I posed the challenge, I woke up thinking that making the record transform itself into XML was the proper way to turn it into XML rather than the way I described in Converting S-Expression To XML In Emacs. It seemed like a direct application of the ideas in my More Fun With Log Files Stored As Lisp post and I decided to program it just for fun with no idea of turning it into a post.

A couple of hours later I was still flailing around so maybe the application wasn’t as direct as I thought. Actually, the idea is the same but because you’re not transforming it back into Lisp it’s a little trickier.

In any event, here’s how I solved the problem. First define all the tags except record to be functions of the form

(defun date (&rest args) (toxml 'date args))

As I explained in the Exploratory Programming In Emacs post that involved little more than copying the list of tags and a keyboard macro. The toxml function is

(defun toxml (tag args)
  (with-output-to-string
    (princ (format "\n<%s>" tag))
    (mapc 'princ args)
    (princ (format "</%s>" tag))))

The idea is that each sexpr returns a string of the arguments wrapped in <tag>…</tag> where tag is the symbol in the function slot of the sexpr. That is, (date "2005-02-21T18:57:39") is transformed to "<date>2005-02-21T18:57:39</date>". If we temporarily alias record to list and executed the record sexpr, we get

("
<date>2005-02-21T18:57:39</date>" "
<millis>1109041059800</millis>" "
<sequence>1</sequence>" "
<logger>nil</logger>" "
<level>SEVERE</level>" "
<class>java.util.logging.LogManager$RootLogger</class>" "
<method>log</method>" "
<thread>10</thread>" "
<emessage>A very very bad thing has happened!</emessage>" "
<exception>
<emessage>java.lang.Exception</emessage>
<frame>
<class>logtest</class>
<method>main</method>
<line>30</line></frame></exception>")

which shows what the record function will see when it gets called. Note that each string begins with a newline so the ” ” at the end of each line is a close quote followed by an open quote.

Finally, we need to define a record function to stitch the strings together and get rid of that annoying nil in <logger>nil</logger>.

(defun record (&rest args)
  (princ "<record>")
  (princ (replace-regexp-in-string ">nil<" "><" (apply 'concat args)))
  (princ "</record>"))

The princ on the third line gets rid of the quote marks that the concat places around the final result of the apply.

Now when we execute the record we get

<record>
<date>2005-02-21T18:57:39</date>
<millis>1109041059800</millis>
<sequence>1</sequence>
<logger></logger>
<level>SEVERE</level>
<class>java.util.logging.LogManager$RootLogger</class>
<method>log</method>
<thread>10</thread>
<emessage>A very very bad thing has happened!</emessage>
<exception>
<emessage>java.lang.Exception</emessage>
<frame>
<class>logtest</class>
<method>main</method>
<line>30</line></frame></exception></record>

Update: Let me mention again that the inspiration for this series of posts and the sample record sexpr are from Steve Yegge’s The Emacs Problem. Be sure to give it a read if you haven’t already.

Posted in Programming | Tagged , | 3 Comments

Turnkey Publishing

I’ve written several posts about the challenges facing the publishing industry and how their continued existence—at least in their current form—is looking increasingly tenuous. Just today Charlie Stross described the Internet as a “communication tool that tends to disintermediate supply and demand” and, sadly, disintermediation is biggest threat to publishers.

Jason Crawford has a provocative post entitled Startup idea: Turnkey self-publishing service for authors. In it he tells the story of a friend who self published a book and the things he had to do as his own publisher. Then Crawford throws out a startup idea: Provide a turnkey, fee-for-service publishing service. It would be pretty much like a typical publisher except that the author would pay an up front fee and then keep all the profits from the book.

Yes, there are problems to be solved with this idea but it’s probably not as hard as you might imagine. In the first place, almost everything a publisher does is farmed out: copy editors, technical editors, typesetting, printing, and so on. These people are already free-lance and would, I’m sure, be just as happy to work for a service such as this as they are to work for traditional publishers.

This idea, even if it comes to fruition, isn’t, by itself, a lethal threat to publishers but when you add in all the other threats that I’ve written about before, the threat seems more immediate.

Posted in General | Tagged | 1 Comment

WordPress And Trackbacks

I’m a big fan of WordPress. I know a lot of people disagree but it works very well for me. It allows me to maintain a nicely laid out blog without spending a lot of time with administration. I do almost everything from Emacs and seldom have to go to the administration panel of the blog. Except to deal with spam.

After I reluctantly installed nucaptcha, comment spam ceased to be a problem until the spammers started injecting their links via trackbacks. Once again, I reluctantly reduced the user experience by turning off trackbacks but I noticed that I was still getting occasional trackback spam. Lately, the number of trackback spams have increased so I spent a little time tracking down the problem.

It turns out that when you turn off trackbacks it affects only future posts but leaves it enabled for existing posts. The spammers, of course, don’t care because the point is to get the links into the posts for Google to see not for anyone to read. Thus they were simply adding trackbacks to my older posts.

There are a couple of problems here. First, to my way of thinking, the principle of least surprise dictates that when you turn off trackbacks, WordPress should, you know, turn off trackbacks. There’s no indication that only new posts will be affected, just a check box to enable or disable them. I understand why it works the way it does (WordPress can simply set each post to allow or disallow trackbacks as they’re posted) but it isn’t really that more difficult to spin through the database and turn it off for all posts.

Instead, it has to be done by hand1. First of all, it isn’t easy to figure out how to do that because the option is hidden by default (I know, I know, RTFM but again I use WordPress so I don’t have to spend a lot of time reading manuals or doing administrative things). Then for each old post you have to disable trackbacks and then update the post. No big thing for a single post but a significant amount of work for 300 posts.

I’m working my way through the old posts so in a few days the blog should be spam-free again—at least until the spammers introduce their next trick. I just wish it were easier.

Footnotes:

1 Yes, I know about plugins to do this sort of thing but every plugin is another potential security vulnerability and it’s more administrative effort ongoing.

Posted in Blogging | Tagged | Leave a comment

Emacs’ jump-to-register In Exploratory Programming

I’ve written before about Emacs Registers and how you can store the mark in a register with 【Ctrl+x r Spaceregister. That’s one of those things that’s occasionally useful because you can then jump to that position with 【Ctrl+x r jregister but in my experience, I just don’t use it that often. However, while I was doing exploratory programming for my series on executable log records, I found that it was extraordinarily useful.

As I explained in the exploratory programming post, I developed the code by writing some exploratory functions and then trying them out on a record sexpr. I used the same file for the entire series and as I added additional posts to the series, I just added code to the end of the buffer. Then I would try it out on one of the records that were at the top of the buffer. By storing the mark in a register, I was able to quickly return to the end of the record and execute it with 【Ctrl+x Ctrl+e】. Then I could return to the code I was working on by simply going to the end of the buffer with 【Meta+>】.

None of this is extraordinary or ground breaking but it does show how a simple Emacs command can really speed up development. Without storing the position of the record in a register, I would have had to move to it with a much more complicated series of keystrokes. This is another example of Emacs providing the very tool you need for a specific task.

Posted in Programming | Tagged | Leave a comment

An Emacs Programming Challenge

In Converting S-Expressions To XML In Emacs, I showed how to take a log record expressed as Lisp and turn it into the equivalent XML. In More Fun With Log Files Stored As Lisp, I showed how to take that same log record and make it executable so that it transformed one of the fields when the record was executed.

Here is a challenge for Elisp programmers: take the record

(record
  (date "2005-02-21T18:57:39")
  (millis 1109041059800)
  (sequence 1)
  (logger nil)
  (level 'SEVERE)
  (class "java.util.logging.LogManager$RootLogger")
  (method 'log)
  (thread 10)
  (emessage "A very very bad thing has happened!")
  (exception
    (emessage "java.lang.Exception")
    (frame
      (class "logtest")
      (method 'main)
      (line 30))))

and turn it into XML like this:

<record>
<date>2005-02-21T18:57:39</date>
<millis>1109041059800</millis>
<sequence>1</sequence>
<logger></logger>
<level>SEVERE</level>
<class>java.util.logging.LogManager$RootLogger</class>
<method>log</method>
<thread>10</thread>
<emessage>A very very bad thing has happened!</emessage>
<exception>
<emessage>java.lang.Exception</emessage>
<frame>
<class>logtest</class>
<method>main</method>
<line>30</line></frame></exception></record>

Do this by making the Lisp record executable so that it transforms itself into the XML when executed. Your XML doesn’t have to be formatted exactly like mine and it’s sufficient to have it print out in the echo area or the *Messages* buffer.

I’ll give my solution in a few days so that you have time to work on it. If you get stuck, the wrap-up post has some techniques that may help.

Posted in Programming | Tagged , | 2 Comments

More Details On find-file Vs. with-temp-buffer

Yesterday, I mentioned that Xah Lee had a short post on dramatically differing run times for processing several files with find-file versus processing the same files using with-temp-buffer. His post was fairly short and didn’t have a lot of details. Happily, he’s published an extended post that shows the code and detailed performance of the two approaches.

This is really interesting and if you write Elisp that looks at lots of files at once, you should check out his post.

Posted in Programming | Tagged , | Leave a comment

Timing Execution In Emacs

Xah Lee has a short post on find-file vs. with-temp-buffer for loading a large number of files. The results were sort of surprising, at least to me, so you should take a look if you need to load several files in Emacs. His post was basically a little benchmark and I vaguely wondered how he did the timing. Scheme and Common Lisp have functions for this but I had never seen anything for Elisp.

Just now, while looking at something completely unrelated I came across the benchmark-run command. It does just exactly what its name suggests: if you want to time some Elisp code you just wrap it with benchmark-run and go. It will report the elapsed time for execution, the number of garbage collections that ran, and the time spent in the garbage collector.

For example, suppose we want to run some-function on several files that are marked in a Dired buffer. We could do something like

(benchmark-run 1 (mapc 'some-function (dired-get-marked-files)))

to time how long it takes. The first argument (1) says to run the benchmark 1 time. You can set that to a larger number if you want to time several runs to get a better idea of average performance.

That’s a pretty nifty thing to know and I don’t recall ever seeing it anywhere before. That’s one of the nice things about Emacs: there’s always something new to learn.

Update: Lisp → Common Lisp

Posted in Programming | Tagged , | 1 Comment

The Power Of S-Expressions

In view of the fact that my last few posts have concentrated on the use of S-expressions to represent data—in particular, to represent log file entries—this seems like a good time to link to S-expressions: The most powerful data structure available over at The (λ) Lambda Meme — all things Lisp. This post argues that sexprs are the most powerful data structure currently available and that they can represent arbitrarily complex data.

We saw a small example of that in our exploration of using sexprs to represent log data. Although the record structure we used was fairly simple, it’s obvious that we could represent any log record structure with an sexpr. Combine that will the ability to make them executable in a direct and easy way and you have a powerful tool.

The reason for the power of the sexpr, The Lambda meme argues, is that sexprs can be used to represent graphs and graphs can model the associations among multiple data. They also say that S-expressions are really all there is to understand about Lisp and once you do understand them, the rest is just a few details. I’m not sure it’s quite that simple but it is true that S-expressions are the soul of Lisp.

In any event, the linked post is short and interesting and worth a read.

Posted in Programming | Tagged , | Leave a comment

Exploratory Programming In Emacs

This is the final post of my series on storing data as Lisp programs (see here, here, here, here, and here). I hope that those of you have read the whole series have a new or renewed appreciation for the concept of data as code that is one half of the data/code duality that Lisp provides. Today, I want discuss, just a bit, how I leveraged the power of Emacs to develop and debug the sample code in the series.

I’ve written before about how you can think of Emacs As A Lisp Machine: that is, the power of Lisp is always available to you. As an example of this, consider the “program” file that I used to develop code for the series. Here’s a screen shot of almost the entire buffer. Cut off at the top are 3 more records and an enclosing (log ...) sexpr that is assigned to log-file.

http://irreal.org/blog/wp-content/uploads/2011/12/wpid-filter-log.png

The thing to notice is that there are no real programs there, just a bunch of record and function definitions, a list of the tag names for the record structure and a few other miscellaneous pieces of code.

Walking through the process for the third problem of the previous post will make the process clear. I began by copying the list of tag names to the bottom of the file, narrowing to the list, and then running a keyboard macro on the narrowed buffer that changed each name into a call to defalias that defined the name as an alias for identity. Then I cut exception, frame, and record out of the list and changed the 'identity to 'list. All that’s just basic editing but with Emacs it involved almost no work: probably about 50 keystrokes total.

The next thing I did was to highlight the new function definitions and run eval-region. After that the new functions were defined and I could go to the end of one of the records and type 【Ctrl+x Ctrl+e】 to execute the record. That’s where the block showing the arguments to record came from.

Finally, I wrote the final 6 functions in the file and ran eval-region on them. That completed the solution to the third problem. I tested the solution first on each of the 4 records by running 【Ctrl+x Ctrl+e】 on each of them and then an actual filtering run by typing 【Ctrl+x Ctrl+e】 at the end of

(setq result (remove-if-not 'eval (cdr log-file)))

That resulted in the two records that passed the criteria being put in result.

The whole process is much more trouble to write down then it was to actually do. Emacs’ superb editing powers allowed me to write the support functions with an absolute minimum of effort and then to test and refine them interactively. Notice that there wasn’t even a REPL involved except for the implicit REPL that Emacs is always running as you type things into a buffer. The ability to select some code and execute it is tremendously powerful and liberating. And fast. During this development, I never left the filter-log.el buffer. There was no need to go to a separate REPL buffer, or to run a compile, or anything else.

I don’t program like this all the time, of course. Sometimes you just write a program or part of a program and then test it but when you’re feeling your way along—when you’re doing exploratory programming—it’s very nice to be able to write and try a snippet of code as small as a single statement. After a while, you begin to understand the problem better and you can drop back to the normal process of writing larger segments of code. At least until you need to do a little exploring again. Emacs supports both styles seamlessly and it’s easy to switch back and forth as needed. The power of Emacs can be astounding, even to those of us who are used to it.

Posted in Programming | Tagged , | 1 Comment

Filtering Lisp-Based Log Files With Emacs Wrap-Up

Yesterday’s post discussed some rudimentary methods of having log files stored as Lisp filter themselves. Today I planned to finish that discussion and remark on how Emacs provides a powerful environment for exploratory programming. The discussion of the 3 challenge questions from yesterday turned out to be longer than I anticipated, so I’ll discuss them today and make my final comments about Emacs and exploratory programming in a subsequent post.

The first question wants us to combine queries with or rather than and. In particular, how would you filter on

level equals SEVERE or line > 30

One way of doing this is to make the definitions

(defun level (s)
  (not (eq s 'SEVERE)))

(defun line (l)
  (<= line 30))

and then use remove-if instead of remove-if-not to filter the records.

The second question asks how you would filter on the method field that is part of the frame sexpr. The easiest way of doing that is to change the definition of frame to return the truth value of the condition. For example, if you wanted to filter on method being ‘main, you could define frame as

(defun frame (class method line)
  (eq method 'main))

The third question shows that we’ve just been fooling around so far and that what we really need is access to all the fields. Our record structure looks like

http://irreal.org/blog/wp-content/uploads/2011/12/wpid-log.png

and the record function can’t see the emessage1, class, method, and line fields that are underneath the exception node. To get a general solution we need to arrange for record to have access to all the fields.

We start by having the leaf nodes just return their value. Thus, we define

(defalias 'date 'identity)

and similarly for millis, sequence, logger, level, class, thread, emessage, method, and line.

Next, we define the internal nodes exception and frame to return a list of their leaf values:

(defalias 'exception 'list)

and similarly for frame.

With these definitions, record has access to all the fields. To see what record‘s arguments look like, define record as list and execute one of the records. We get

("2005-02-21T18:57:39" 1109041059800 2 nil SEVERE
"java.util.logging.LogManager$RootLogger" log 10 "A very very bad
thing has happened!" ("java.lang.Exception" ("logtest" main 120)))

To get access to the leaves under exception, we need some accessor functions.

(defun exception.emessage ()
  (car exception))

(defun exception.frame ()
  (cadr exception))

(defun exception.frame.class ()
  (car (exception.frame)))

(defun exception.frame.method ()
  (cadr (exception.frame)))

(defun exception.frame.line ()
  (caddr (exception.frame)))

With these definitions we can filter on conditions by writing the appropriate record function. To filter on

(level equals SEVERE or line > 30) and thread equals 10

as the third question asked, we would define record as

(defun record (date millis sequence logger level class method thread emessage exception)
  (and (or (eq level 'SEVERE) (> (exception.frame.line) 30))
       (= thread 10)))

and then evaluate

(remove-if-not 'eval (cdr log-file))

as before.

Note that given some record structure, everything but the record function is fixed so that filtering on different criteria means that only the record function needs to be changed.

UPDATE: would → wouldn’t

Footnotes:

1 I changed the message field of the record to emessage so that I wouldn’t have to redefine Emacs’ message function.

Posted in Programming | Tagged , , | Leave a comment