Search code examples
emacslispcommon-lispslime

Emacs SLIME - Common Lisp - evaluating region and printing all the results


I have Emacs+SLIME+SBCL installed, and i'm new in this stuff. So, my question is how to evaluate the whole file or just a selected region of file and print the result of EACH expression to the console. For example, for code

(+ 3 5)
(defun my-first (a) (car a))
(my-first (list 5 7 3))

i want to see in console this:

8
MY_FIRST
5

Thank you for your help.


Solution

  • So, the best and simpliest solution for me is to wrap the code next way:

        (format t "~{~a~%~}" (list
         <code in file>
        ))
    

    And than I do C-x C-e in the end of the file, and get in REPL the results of all of my expressions one by one. Thanks to everyone.

    UPD I used the internet and this answer: How to run Common Lisp code with Slime in Emacs Lisp to write these two functions. This code is situated in my .emacs file. Now I just should press 'C-c e' or 'C-c r' to evaluate all the file or only selected region. Problem is absolutely solved.

    (require 'slime)
    (defun lispy--eval-lisp (str)
      "Eval STR as Common Lisp code."
      (unless (slime-current-connection)
        (let ((wnd (current-window-configuration)))
          (slime)
          (while (not (and (slime-current-connection)
                           (get-buffer-window (slime-output-buffer))))
            (sit-for 0.2))
          (set-window-configuration wnd)))
      (let (deactivate-mark)
        (slime-eval `(swank:eval-and-grab-output ,str))))
    
    (defun feval () 
        "Evaluates the whole file"
        (interactive)
        (message (car (lispy--eval-lisp 
            (concat "(format t \"~{~a~%~}\" (list " (string-make-unibyte (buffer-string)) "))")))))
    (defun reval (from to)
        (interactive "r")
        (message (car (lispy--eval-lisp 
            (concat "(format t \"~{~a~%~}\" (list " (string-make-unibyte (buffer-substring from to)) "))")))))  
    
    (global-set-key "\C-ce" 'feval)
    (global-set-key "\C-cr" 'reval)