2010-01-18 92 views
4

我想從組織模式表導出到s表達式。組織模式表到s表達式

| first | second | thrid | 
|--------+--------+--------| 
| value1 | value2 | value3 | 
| value4 | value5 | value6 | 

會變成:

((:FIRST "value1" :SECOND "value2" :THIRD "value3") 
(:FIRST "value4" :SECOND "value5" :THIRD "value6")) 

我打算寫這樣的設置,如果不存在,但想我會進軍計算器之前,我開始重新發明輪子。

回答

6

這是訣竅。它具有最小的錯誤檢查。

接口使用或者是編程接口:

(org-table-to-sexp <location-of-beginning-of-table> <location-of-end-of-table>) 

在這種情況下,它會返回您所要求的SEXP。

如果您想要交互式使用,您可以調用以下命令在region中的表上操作。因此,設置標記在表的開頭,移動到結束,並鍵入:

M-x insert-org-table-to-sexp 

這將在當前緩衝區表後立即插入所需SEXP。

下面是代碼:

(defun org-table-to-sexp-parse-line() 
    "Helper, returns the current line as a list of strings" 
    (save-excursion 
    (save-match-data 
     (let ((result nil) 
      (end-of-line (save-excursion (end-of-line) (point)))) 
     (beginning-of-line) 
     (while (re-search-forward "\\([^|]*\\)|" end-of-line t) 
      (let ((match (mapconcat 'identity (split-string (match-string-no-properties 1)) " "))) 
      (if (< 0 (length match)) 
       ;; really want to strip spaces from front and back 
       (push match result)))) 
     (reverse result))))) 

(require 'cl) 
(defun org-table-to-sexp (b e) 
    "Parse an org-mode table to sexp" 
    (save-excursion 
    (save-match-data 
     (goto-char b) 
     (let ((headers (mapcar 
         (lambda (str) 
         (make-symbol (concat ":" (upcase str)))) 
         (org-table-to-sexp-parse-line))) 
      (sexp nil)) 
     (forward-line 1)    ;skip |--+--+--| line 
     (while (< (point) e) 
      (forward-line 1) 
      (let ((line-result nil)) 
      (mapcar* (lambda (h e) 
         (push h line-result) 
         (push e line-result)) 
        headers 
        (org-table-to-sexp-parse-line)) 
      (if line-result 
       (push (reverse line-result) 
         sexp)))) 
     sexp)))) 

(defun insert-org-table-to-sexp (b e) 
    "Convert the table specified by the region and insert the sexp after the table" 
    (interactive "r") 
    (goto-char (max b e)) 
    (print (org-table-to-sexp b e) (current-buffer))) 
+0

我不知道我將如何使用該功能。我將它添加到了我的.emacs評估版中,但我不明白我會如何使用它。 如果你可以擴展如何使用它,我會非常感激。 – Wraithan 2010-01-23 23:48:27

+0

@Chris我添加了一個可以輸入的交互式命令。我認爲更大的問題是:你想如何使用它? – 2010-01-29 20:19:03