Search code examples
pythonemacsevalelpy

Is there a function like eval-print-last-sexp for Comint-Mode?


Is there an equivalent function to eval-print-last-sexp for comint derived modes in emacs?

Specifically, I'm using python-mode (with elpy) and am looking for a way to send the contents of a region to the Python process and then print the results on the next line of the python script I'm working in.

Printing the results to the Messages buffer would be acceptable as well, however the behavior of eval-print-last-sexp would be preferred.

I'm running Emacs 25.1.1 and elpy 1.13.0.


Solution

  • It would depend on the comint-derived mode, since you would need to redirect the process output. Different modes have different methods of interacting with inferior processes. Python mode already has a function to do this, python-shell-send-string-no-output (other modes have similar functions, but you would need to search for them).

    I'm not sure how exactly you want to define a sexp for python, but here is an example of sending the current line, with output like eval-print-last-sexp.

    (defun python-eval-print-last-sexp ()
      "Print result of evaluating current line into current buffer."
      (interactive)
      (let ((res (python-shell-send-string-no-output
                  ;; modify to get a different sexp
                  (buffer-substring (line-beginning-position)
                                    (line-end-position))))
            (standard-output (current-buffer)))
        (when res
          (terpri)
          (princ res)
          (terpri))))