我想创建一个命令,在该命令中,如果处于活动状态,则发送该区域;如果不是,则计算当前行/语句,并进一步指向下一个语句。
我从This solution.开始 现在我不能让(python-shell-send-region)工作,因为我不知道如何将区域的开头和结尾传递给它。
到目前为止,我有这个:
(defun my-python-send-region (&optional beg end)
(interactive)
(if (use-region-p)
(python-shell-send-region) (let ((beg (cond (beg beg)
((region-active-p)
(region-beginning))
(t (line-beginning-position))))
(end (cond (end end)
((region-active-p)
(copy-marker (region-end)))
(t (line-end-position)))))
(python-shell-send-region beg end)
(python-nav-forward-statement))))
(add-hook 'python-mode-hook
(lambda ()
(define-key python-mode-map "\C-cn" 'my-python-send-region)))
更新: 根据Andreas和Legoscia的建议,我改变了结构。
现在我收到错误(无效功能:(setq beg(point)):
(defun my-python-send-region (&optional beg end)
(interactive)
(if (use-region-p)
(python-shell-send-region (region-beginning) (region-end))
((setq beg (point))
(python-nav-end-of-statement)
(setq end (point))
(python-shell-send-region (beg) (end)))
(python-nav-forward-statement))))
然而,这有效:
(defun my-python-send-region (&optional beg end)
(interactive)
(setq beg (point))
(python-nav-end-of-statement)
(setq end (point))
(python-shell-send-region beg end))
答案 0 :(得分:3)
可能有效的替代方法是尝试使用melpa的整行或区域包。这个包设置的东西,如果你调用一个期望一个区域但没有定义区域的命令,它将基本上设置一个等于当前行的区域。实质上,这会导致在当前行上没有定义区域时期望区域工作的命令。我在我的init.org文件中有这个
如果不是,则允许面向区域的命令在当前行上工作 区域定义。
#+BEGIN_SRC emacs-lisp
(use-package whole-line-or-region
:ensure t
:diminish whole-line-or-region-mode
:config
(whole-line-or-region-mode t)
(make-variable-buffer-local 'whole-line-or-region-mode))
答案 1 :(得分:1)
在这部分:
(if (use-region-p)
(python-shell-send-region)
您需要将区域的开头和结尾传递给python-shell-send-region
。它仅在交互式调用时自动获取这些值。当您从Lisp代码调用它时,您需要显式传递值:
(python-shell-send-region (region-beginning) (region-end))
答案 2 :(得分:1)
更新的答案:python-shell-send-defun并不总是发送当前语句/行(it is not meant to do that),所以我用elpy中的函数替换它
(defun python-shell-send-region-or-line nil
"Sends from python-mode buffer to a python shell, intelligently."
(interactive)
(cond ((region-active-p)
(setq deactivate-mark t)
(python-shell-send-region (region-beginning) (region-end))
) (t (python-shell-send-current-statement))))
(defun python-shell-send-current-statement ()
"Send current statement to Python shell.
Taken from elpy-shell-send-current-statement"
(interactive)
(let ((beg (python-nav-beginning-of-statement))
(end (python-nav-end-of-statement)))
(python-shell-send-string (buffer-substring beg end)))
(python-nav-forward-statement))
如果我想添加案例,我会使用cond。设置取消激活标记是取消选择区域(如果已选择)。如果没有选择区域,我也会向前导航python语句。