一千萬個為什麽

搜索

將列表重新分配到列中的函數

我在 org 文檔中有一個很長的列表

- alpha a
- beta b
- gamma
- delta d
- epsilon e
- zeta z
- eta
- theta
- iota
- kappa
- lambda
- mu

I would like a function that redistributes this block of text into n columns where n is specified by me. So issuing M-x desired-function 2 would return something like

- alpha a    - eta
- beta b     - theta
- gamma      - iota
- delta d    - kappa
- epsilon e  - lambda
- zeta z     - mu

and issuing M-x desired-function 3 would return something like

- alpha a  - epsilon e  - iota
- beta b   - zeta z     - kappa
- gamma    - eta        - lambda
- delta d  - theta      - mu

這樣的函數可能會破壞 org 文檔中列表的功能,但這並不會讓我感到煩惱。

這是否存在於emacs中?

最佳答案

這是我能想到的快速:

(defun my/org-partition-list (n)
  (interactive "nColumns: ")
  (let* ((struct (org-list-struct))
         (prevs (org-list-prevs-alist struct))
         (start (org-list-get-list-begin (point-at-bol) struct prevs))
         (end (org-list-get-list-end (point-at-bol) struct prevs))
         (table 
          (orgtbl-to-orgtbl
           (cl-loop with chunk = nil
                    for item in
                    (cl-loop for item in struct
                             collect (org-trim
                                      (buffer-substring-no-properties
                                       (+ (cl-first item)
                                          (cl-second item)
                                          (length (cl-third item)))
                                       (car (last item)))))
                    for i from 1
                    if (zerop (mod i n))
                    collect (nreverse (cons item chunk)) into result
                    and do (setf chunk nil)
                    else do (push item chunk) end
                    finally (cl-return
                             (if (/= 0 (mod i n))
                                 (append result (list chunk))
                               result)))
           nil)))
    (delete-region start end)
    (insert table)))

要記住的一件事是Org列表可以包含許多其他Org元素,其中大部分都會使這個函數輸出不可預測/不可用的東西。只有當列表包含純文本,每個條目一行時,這才會在微不足道的情況下起作用。

轉載註明原文: 將列表重新分配到列中的函數