For example I have the code:

(println "foo")

With cider-pprint-eval-last-sexp-to-comment I can eval the code and get

(println "foo") ;; nil

in clojure buffer and also it print foo in cider-repl buffer.

I would like to get something like this in the current buffer:

(println "foo") ;; nil foo

How can I do this?


You can use with-out-str to capture the output into a string.

user> (with-out-str
        (print "foo"))

Knowing that you can take the cider-pprint-eval-last-sexp-to-comment function, copy/paste it and make a small change.

(define-key cider-mode-map (kbd "C-c C-p") 
  (lambda ()
    (let* ((insert-before nil)
           (bounds (cider-last-sexp 'bounds))
           (insertion-point (nth (if insert-before 0 1) bounds))
           (comment-postfix (concat cider-comment-postfix
                                    (if insert-before "\n" ""))))
      (cider-interactive-eval (concat "(with-out-str " (cider-last-sexp) " )")
                               (set-marker (make-marker) insertion-point)
                              (cider--nrepl-print-request-map fill-column)))))

This function prints the captured output instead of the value. If you use it on something that doesn't write to *out* it will print the empty string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.