2013-08-05 81 views
1

我定義上的順乎自然段工作的主要模式:如何獲取Emacs Lisp中的所有段落?

: Identifier 
1. some text 
2. ... 
3. some more text 

: New Identifier 

: Another Identifier 
some text 

我想寫一個defun稱爲get-paragraphs將返回,看起來像一個列表:

( ("Identifier", ("1. some text", "2. ...", "3. some more text")), 
    ("New Identifier",()), 
    ("Another Identifier", ("some text")) 
) 

怎麼辦我開始在Emacs Lisp中分割這樣的文本:

是否有函數來遍歷它們(並隨後將它們按照我的喜好切分)?我應該使用正則表達式嗎?有更容易的方法嗎?

回答

1

你應該遍歷緩存,並收集您的文本(未經測試):

(defun get-paragraphs() 
    (save-excursion 
    (goto-char (point-min)) 
    (let ((ret '())) 
     (while (search-forward-regexp "^: " nil t) 
     (let ((header (buffer-substring-no-properties (point) (line-end-position))) 
       (body '())) 
      (forward-line) 
      (while (not (looking-at "^$")) 
      (push (buffer-substring-no-properties (point) (line-end-position)) body) 
      (forward-line)) 
      (push (cons header (list (reverse body))) ret))) 
     (nreverse ret)))) 
+0

這幾乎是完美的 - 有一個額外的'='我把':'標題下的行作爲另一個列表。非常感謝! – sdasdadas

0

這裏,藉此Lisp代碼:

(defun chopchop() 
    (mapcar 
    (lambda (x) 
    (destructuring-bind (head &rest tail) 
     (split-string x "\n" t) 
     (list head tail))) 
    (split-string (buffer-substring-no-properties 
        (point-min) 
        (point-max)) "\n?: *" t))) 
+0

我對Emacs Lisp不太熟悉,但我不認爲這正是我想要的。 – sdasdadas

+0

你至少試過了嗎?它和其他答案一樣,只是沒有錯誤(當我嘗試時它仍然掛起)。 –