python - Emacs 中的单元模式

标签 python emacs elisp

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

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

# this is a comment

### this is also a comment

.. still cell 2 ..

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

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

我想定义一个 Emacs 命令,当被调用时,它定义了当前的 cell(即 cellpoint 所在的 cell/cursor 当前位于。)成为 Emacs region (即突出显示单元格)。

我如何在 Emacs 中执行此操作?

供引用:

  • 类似于细胞的概念或 code sections在 MATLAB 中
  • 这是一个thread在 Vim 中实现此功能。

最佳答案

这是一个解决方案:

(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."

工作正常。 是否有理由不使用缩进级别而不是评论作为 anchor ?

关于python - Emacs 中的单元模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19453360/

相关文章:

elisp - 如何诊断涉及间接缓冲区的 emacs lisp 问题?

python - python中的BFS来自预序和中序

python - 如何在 Python 中打开 AIFC 文件以将标记数据附加到该文件?

python - "is"运算符对整数的行为异常

testing - 我可以运行 JUnit 4 以从命令行测试 Scala 代码吗?

emacs - 将列表传递给 &rest args

emacs - 在 emacs 中显示重复选定的文本

python - 如何获取有效 Numpy 数据类型的范围?

emacs - 在窗口内居中 Emacs 缓冲区

emacs - 如何使用elisp将十六进制字符串转换为ASCII?