tags:

views:

36

answers:

2

How can I sort the following buffer data by the second field (author's name) or third field (published date)? I'd like a pure elisp solution, so I'd rather not have a solution that used M-|.

Tom Sawyer|Mark Twain|1876
Harry Potter and the Philosopher's Stone|JK Rowling|1997
Harry Potter and the Half-Blood Prince|JK Rowling|2009
The Da Vinci Code|Dan Brown|2003
A Short History of Nearly Everything|Bill Bryson|2003
+1  A: 

This looks pretty much like an org-mode table. Can you just add a | to the beginning and end of every line? Then you can use the inbuilt org-sort command to sort by a column. If you have to be in another major-mode, you can use orgtbl-mode as a minor mode for just that region.

Noufal Ibrahim
This does work. I was hoping for the actual elisp code. I can "C-h f org-sort" and look through that code provided in the link.
+2  A: 

This function uses sort-regexp-fields to do the work:

(defun my-sort-fields (n)
  "Sort lines by | delimted fields"
  (interactive "nWhich field: ")
  (sort-regexp-fields nil
                      (format "^\\([^|]*|\\)\\{%d\\}\\([^|\n]*\\)\\(|[^|\n]*\\)*$" (- n 1))
                      (format "\\2" )
                      (point-min)
                      (point-max)))
Trey Jackson