4

假设我有一个带有代码(在本例中为 Python)的缓冲区,其组织如下:

.. cell 1 ..
## 
.. cell 2 ..

# this is a comment

### this is also a comment

.. still cell 2 ..

  ##
  .. cell 3 (code that is indented)

字符序列##旨在分隔cells缓冲区中的(代码区域/块)。字符#在 Python 中开始注释,因此##被语言视为注释。类似的结构可以用例如 Elisp;;或其他编程语言构建。

我想定义一个Emacs 命令,当它被调用时,它将当前cell(即/cursor 当前所在的点)定义为 Emacs cellregion它突出显示单元格)。

我怎样才能在 Emacs 中做到这一点?

以供参考:

4

3 回答 3

3

这是一个解决方案:

(defun python-inside-comment-p ()
  (save-excursion
    (beginning-of-line 1)
    (looking-at "^#")))

(defun python-select-cell ()
  (interactive)
  (goto-char
   (if (re-search-backward "^\\s-*##[^#]" nil t)
       (match-end 0)
     (point-min)))
  (while (and (python-inside-comment-p)
              (eq 0 (forward-line 1)))
    nil)
  (set-mark (point))
  (goto-char
   (if (re-search-forward "^\\s-*\\(##[^#]\\)" nil t)
       (- (match-beginning 1) 2)
     (point-max))))

经测试:

print "Beautiful is better than ugly."
##
print "Explicit is better than implicit."
print "Simple is better than complex."
print "Complex is better than complicated."
# this is a comment
print "Flat is better than nested."
### this is also a comment
print "Sparse is better than dense."
##
print "Readability counts."
print "Special cases aren't special enough to break the rules."
print "Although practicality beats purity."
print "Errors should never pass silently."
print "Unless explicitly silenced."

工作正常。是否有理由不使用缩进级别而不是注释作为锚点?

于 2013-10-18T15:57:07.977 回答
2

那将是这样的:

(defun mark-cell ()
  (interactive)
  (search-backward-regexp "^##\\($\\|[^#]\\)" nil 'noerror)
  (push-mark)
  (end-of-line)
  (search-forward-regexp "^##\\($\\|[^#]\\)" nil 'noerror)
  (beginning-of-line)
  (activate-mark))

对我来说,它不会突出显示单元格(您可以使用 手动执行此操作C-x C-x),即使这是activate-mark应该做的,如果我理解正确的话。

于 2013-10-18T15:47:35.303 回答
1

EmacsWiki,有两个包:

python-x还提供了一些附加功能

python-cell在 python 缓冲区中提供类似 Matlab 的单元格

于 2017-05-19T19:30:15.560 回答