`(blog ,garaemon)

ポップカルチャーを摂取して、コードを吐き出す機械

emacsで選択範囲or現在行のpythonを評価する

elpyを使っています. elpyやemacs付属のpython-modeでも, pythonインタプリタemacs上で起動することができ、大変便利だ.

elpyの場合はM-x elpy-shell-switch-to-shell, python-modeならM-x run-pythonpythonインタプリタを立ち上げることができる.

emacs lispだと、S式もしくはregionの評価がC-x C-eでできて、とても便利。それと似たような挙動をpythonでも実現したい.

emacsでregionを選択していたらその範囲、選択していなかったら現在行のpythonを評価するようなelisp.

(elpy-enable) ;; enable elpy
(defun elpy-shell-send-region-or-statement ()
  "Send region or statement to python shell."
  (interactive)
  (if (use-region-p)
      (progn
        (elpy-shell-send-region-or-buffer)
        (deactivate-mark))
    (elpy-shell-send-statement)
    ))
(define-key python-mode-map "\C-x\C-E" 'elpy-shell-send-region-or-statement)

ついでに、個人的にはpython shellの立ち上げを以下のようなキーバインドに設定している.

(define-key python-mode-map "\C-cE" 'elpy-shell-switch-to-shell)
(global-set-key "\C-cE" 'elpy-shell-switch-to-shell)