Get pretty-printed result in Cider-evaluated expression in Emacs

1.1k views Asked by At

I'd like to insert the result of an evaluated Clojure expression directly in my Emacs buffer, in pretty-printed form.

For example, with something like:

    ;; [emacs lisp]
    (insert (nrepl-dict-get (nrepl-sync-request:eval "(range 30)") "value"))

I get, in the buffer of interest,

    ;;=>
    (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29)

In the past, I've let Clojure pretty-print things for me, as so:

(nrepl-dict-get
  (nrepl-sync-request:eval
    (format "(clojure.core/let [x %s] (with-out-str (clojure.pprint/pprint x)))"
            "(range 30)"))
  "value")
;;=>
"(0\n 1\n 2\n 3\n 4\n 5\n 6\n 7\n 8\n 9\n 10\n 11\n 12\n 13\n 14\n 15\n 16\n 17\n 18\n 19\n 20\n 21\n 22\n 23\n 24\n 25\n 26\n 27\n 28\n 29)\n"

However, the " and \n are being inserted escaped; I want them to be inserted unescaped. In other words, I want the pretty-printed result to be inserted directly without escaping quotes or newlines. This used to work in earlier versions of Cider and cider-nrepl.

2

There are 2 answers

0
Bozhidar Batsov On BEST ANSWER

Wrapping:

(nrepl-dict-get
  (nrepl-sync-request:eval
    (format "(clojure.core/let [x %s] (with-out-str (clojure.pprint/pprint x)))"
            "(range 30)"))
  "value")

in read should solve this.

0
abo-abo On

I've just added this feature to lispy (it's a Paredit-style package that uses Cider for Clojure eval): 2E will to a pretty-printed eval-and-insert, while E will keep doing a plain one.

Here's an example (| represents point):

|(for [x (range 8)] (range x))

After E:

|(for [x (range 8)] (range x))
(() (0) (0 1) (0 1 2) (0 1 2 3) (0 1 2 3 4) (0 1 2 3 4 5) (0 1 2 3 4 5 6))

After 2E:

|(for [x (range 8)] (range x))
(()
 (0)
 (0 1)
 (0 1 2)
 (0 1 2 3)
 (0 1 2 3 4)
 (0 1 2 3 4 5)
 (0 1 2 3 4 5 6))

Of course you can still do EjM to accomplish the same thing:

(for [x (range 8)] (range x))
|(()
 (0)
 (0 1)
 (0 1 2)
 (0 1 2 3)
 (0 1 2 3 4)
 (0 1 2 3 4 5)
 (0 1 2 3 4 5 6))