Skip to content
Jamie Mazer edited this page Nov 8, 2021 · 2 revisions

Including these in your init.el will copy (truncated) versions of the commands send to the inferior ipython process into the ipython buffer. Sometimes this makes it easier to follow what's going on if you're aiming for something like reproducible analysis.

(defun python-shell-send-region-with-show-input (start end &optional send-main msg)
  ;; version of python-shell-send-region that inserted cell input
  ;; into the buffer ahead of the output, trimming first if long
  ;; this makes notebook a bit more readable -- can see in/out
  ;;; instead of just out
  (let ((s (buffer-substring start end))
	(lines nil))
    (setq s (replace-regexp-in-string "# %%$" "" s))
    (setq s (replace-regexp-in-string "\n\n" "\n" s))
    (setq lines (split-string s "\n"))
    ;; trim if too many lines
    (if (> (length lines) 7)
	(setq s (concat
		 (string-join (seq-subseq lines 0 6) "\n")
		 "\n------- [trimmed] -------\n"))
      (setq s (concat s "-------------------------\n")))
    (with-current-buffer (python-shell-get-buffer)
      ;(insert s)
      (insert-before-markers s)
      (comint-set-process-mark)))
  (python-shell-send-region start end send-main msg)
  (with-current-buffer (python-shell-get-buffer)
    (goto-char (point-max))))

(defcustom code-cells-eval-region-commands
  '((jupyter-repl-interaction-mode . jupyter-eval-region)
    (python-mode . python-shell-send-region-with-show-input)
    (emacs-lisp-mode . eval-region)
    (lisp-interaction-mode . eval-region))
  "Alist of commands to evaluate a region.
The keys are major or minor modes and the values are functions
taking region bounds as argument."
  :type '(alist :key-type symbol :value-type symbol))
Clone this wiki locally