繁体   English   中英

emacs elisp发送行,如果没有区域处于活动状态python-mode

[英]emacs elisp send line if no region active python-mode

我想创建一个命令,如果活动的话,将在其中发送区域,如果不活动,则对当前的行/语句进行评估,然后将指针指向下一条语句。

我从这个解决方案开始 现在我无法使(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求(点)))

 (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))

一种可行的替代方法是尝试使用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))

在这一部分:

(if (use-region-p)
  (python-shell-send-region)

您需要将区域的开头和结尾传递给python-shell-send-region 当以交互方式调用时,它只会自动获取这些值。 从Lisp代码调用它时,您需要显式传递值:

(python-shell-send-region (region-beginning) (region-end))

更新的答案:python-shell-send-defun并不总是发送当前的语句/行( 这并不是要这样做 ),因此我用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语句。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM