假设我有一个包含代码的缓冲区(在本例中为Python),其组织如下:
.. cell 1 ..
##
.. cell 2 ..
# this is a comment
### this is also a comment
.. still cell 2 ..
##
.. cell 3 (code that is indented)
字符序列##
用于在缓冲区中分隔cells
(代码区/块)。 caracter #
在Python中启动注释,因此##
被语言视为注释。类似的结构可以构建在例如Elisp使用;;
或其他编程语言。
我想定义一个 Emacs命令,在调用时,它定义当前cell
(即point /光标当前所在的cell
。)成为Emacs region
(即突出显示单元格)。
如何在Emacs中执行此操作?
供参考:
答案 0 :(得分:2)
这是一个解决方案:
(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."
工作正常。 是否有理由不使用缩进级别而不是注释作为锚点?
答案 1 :(得分:1)
这将是这样的:
(defun mark-cell ()
(interactive)
(search-backward-regexp "^##\\($\\|[^#]\\)" nil 'noerror)
(push-mark)
(end-of-line)
(search-forward-regexp "^##\\($\\|[^#]\\)" nil 'noerror)
(beginning-of-line)
(activate-mark))
对我来说,它不会突出显示单元格(您可以使用 Cx Cx 手动执行此操作),即使这是activate-mark
应该执行的操作,如果我理解正确的话。
答案 2 :(得分:1)