Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I beautify lisp source code?

My code is a mess many long lines in this language like the following

(defn check-if-installed[x] (:exit(sh "sh" "-c" (str "command -v " x " >/dev/null 2>&1 || { echo >&2 \"\"; exit 1; }"))))

or

(def Open-Action (action :handler (fn [e] (choose-file :type :open :selection-mode :files-only :dir ListDir :success-fn (fn [fc file](setup-list file)))) :name "Open" :key "menu O" :tip "Open spelling list"))

which is terrible. I would like to format it like so

(if (= a something)
    (if (= b otherthing)
        (foo)))

How can I beautify the source code in a better way?

like image 382
Taylor Ramirez Avatar asked Aug 29 '12 07:08

Taylor Ramirez


2 Answers

Now you can do it with Srefactor package.

Some demos:

  • Formatting whole buffer demo in Emacs Lisp (applicable in Common Lisp as well).
  • Transform between one line <--> Multiline demo

Available Commands:

  • srefactor-lisp-format-buffer: format whole buffer
  • srefactor-lisp-format-defun: format current defun cursor is in
  • srefactor-lisp-format-sexp: format the current sexp cursor is in.
  • srefactor-lisp-one-line: turn the current sexp of the same level into one line; with prefix argument, recursively turn all inner sexps into one line.

Scheme variants are not as polished as Emacs Lisp and Common Lisp yet but work for simple and small sexp. If there is any problem, please submit an issue report and I will be happy to fix it.

like image 179
Amumu Avatar answered Oct 06 '22 01:10

Amumu


The real answer hinges on whether you're willing to insert the newlines yourself. Many systems can indent the lines for you in an idiomatic way, once you've broken it up into lines.

If you don't want to insert them manually, Racket provides a "pretty-print" that does some of what you want:

#lang racket

(require racket/pretty)

(parameterize ([pretty-print-columns 20])
  (pretty-print '(b aosentuh onethunoteh (nte huna) oehnatoe unathoe)))

==>

'(b
  aosentuh
  onethunoteh
  (nte huna)
  oehnatoe
  unathoe)

... but I'd be the first to admit that inserting newlines in the right places is hard, because the choice of line breaks has a lot to do with how you want people to read your code.

like image 40
John Clements Avatar answered Oct 06 '22 00:10

John Clements