@peccul is peccu

(love peccu '(emacs lisp cat outdoor bicycle mac linux coffee))

EmacsでOrg-modeのツリーをMarkdownのリスト形式でコピーする

Markdown形式のREADMEやチャットに貼り付けるときに面倒だったので書いた。

見よう見まねで書いたのでより適切な書き方がありそうだけどわからない。。。

(require 'org)
;; for s-repeat
(require 's)

(defun copy-as-markdown-list ()
  (interactive)
  (if (not (org-current-level))
      (message "not in org headings")
    (save-excursion
      (save-restriction
        (let ((star-count (org-current-level)))
          (org-mark-subtree)
          (narrow-to-region (region-beginning) (region-end))
          (let ((buf (current-buffer))
                (from (point-min))
                (to (point-max)))
            (with-temp-buffer
              (switch-to-buffer (current-buffer) nil t)
              (insert-buffer-substring buf from to)
              (goto-char (point-min))
              (while (re-search-forward "\* " nil t)
                (replace-match "*- "))
              (goto-char (point-min))
              (while (re-search-forward (concat "^" (s-repeat star-count "\\*")) nil t)
                (replace-match "")
                (next-line)
                (beginning-of-line))
              (goto-char (point-min))
              (while (re-search-forward "\*" nil t)
                (replace-match "  "))
              (kill-ring-save (point-min) (point-max))
              (message "markdown list has copied"))))
        (deactivate-mark)))))

以下のような内容でsub headingの行で実行すると

* heading
** sub heading
*** foo
**** bar
***** baz
**** foo
*** bar
**** baz
** 2nd sub heading

以下の内容がkill-ringに入る(クリップボードに入る)

- sub heading
  - foo
    - bar
      - baz
    - foo
  - bar
    - baz