【问题标题】:Cell mode in EmacsEmacs 中的单元格模式
【发布时间】:2013-10-18 15:28:22
【问题描述】:

假设我有一个代码缓冲区(在本例中为 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(即point/cursor 当前所在的cell)定义为Emacs region(即突出显示单元格)。

如何在 Emacs 中做到这一点?

供参考:

  • 类似于单元格的概念或 MATLAB 中的 code sections
  • 这是一个thread,用于在 Vim 中实现此功能。

【问题讨论】:

    标签: python emacs elisp


    【解决方案1】:

    这里有一个解决方案:

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

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

    【讨论】:

    • 谢谢。您介意详细说明这种方法与@legoscia 方法之间的区别吗?
    • 我的跳过 cmets。否则它们是相同的。
    • 谢谢 - 当 ## 被缩进时,我无法让它工作。关于如何解决它的任何想法? (我更新了 OP 中的最后一个单元格以显示这一点)
    【解决方案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))
    

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

    【讨论】:

      【解决方案3】:

      来自EmacsWiki,有两个包:

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

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

      【讨论】:

        猜你喜欢
        • 2023-03-12
        • 1970-01-01
        • 2011-09-02
        • 1970-01-01
        • 1970-01-01
        • 2014-06-29
        • 2011-01-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多