2013-10-18 118 views
3

說我有一個代碼緩衝器(在這種情況下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 /光標當前位於即cell。)是Emacs的region(即它突出的小區) 。

我該如何在Emacs中做到這一點?

參考:

  • 的類似於細胞在MATLAB
  • 這裏的概念或code sections是用於實現在Vim的此功能的thread

回答

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

工程確定。 是否有理由不使用縮進級別而不是評論作爲錨點?

+0

感謝。請介紹一下這種方法與@legoscia的區別嗎? – Josh

+1

地雷跳過評論。否則它們是一樣的。 –

+0

謝謝 - 我在縮進'##'時遇到問題。有關如何解決它的任何想法? (我更新了OP中的最後一個單元以顯示此內容) – Josh

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

對於我來說,它並不突出的細胞(可以手動做到這一點與CXCX),即使那是什麼activate-mark應該這樣做,如果我理解正確。