elarson’s posterous

 
Filed under

lisp

 

Finally Learning Lisp

I've tried and failed to learn Lisp more times than I can count. At this point there are no theories as to why it has been such a challenge. Fortunately, I'm pleased to announce this last foray has proved to be much more fruitful.

It started with the simple task of wanting a better view of a csv file. At work we export data and one of the simple formats is csv. Since my computer life increasingly revolves around Emacs, it seemed like it would be nice to find a way to convert a buffer with a CSV file to a table in org-mode. Emacs makes it really easy to send a selection to shell command, so the pattern was already in place to implement this in Python. After my Python version was done though, it seemed clear it should be relatively easy to write it in Lisp.

The first steps involved doing a little string manipulation. Taking a line and turning it into an org-mode table line was pretty easy:


(defun addpipe (line)
  (concat "| " (mapconcat 'identity (split-string line ",") " | " ) " |")))


That effectively splits the line by commas and immediately puts it back together, replacing the comma with a pipe. It then adds a pipe on either end.

Next up was to select the text in the current buffer, split it by new lines, and format each line placing it in another buffer for viewing.


((defun csv2org ( )
  (interactive)
  (setq buffer-text (buffer-substring (point-min) (point-max)))
  (setq prebuffer (delete "" (split-string buffer-text "\n")))
  (setq mapped-buffer (mapcar 'addpipe prebuffer))
  (with-current-buffer (get-buffer-create "*csv2org*") 
    (dolist (line mapped-buffer)
      (insert (format "%s\n" line))))
  (set-buffer "*csv2org*"))


I'm sure smarter folks than me a more elegant way of doing this, but it worked for me and fit my understanding of the problem. For example, creating the "*csv2org*" buffer most likely has its usability issues. That said, I'm pretty happy that I was able to get what I wanted basically working. Obviously there is a great deal more to learn when it come to working with Emacs in Lisp, but this experiment is getting marked down as a success.

While there were not any major revelations, things started clicking more than before. One helpful bit was becoming more comfortable with executing Lisp in Emacs. Using the scratch buffer, it became easy to play with the function and setup a simple development pattern for trying things. Also, all the Emacs and Lisp bookmarks I've recorded over the past couple years ended up providing useful tips for getting further along than before.

For my next trick, I'm going to implement a simple way to paste code to http://rafb.net/paste. Fortunaely, I've already started making progress and despite not finding much information on the URL Package, it seems like it shouldn't take much to get it working good enough.

Filed under  //   lisp   programming