Skip to content

Instantly share code, notes, and snippets.

Created September 3, 2013 22:28
Show Gist options
  • Save anonymous/6430461 to your computer and use it in GitHub Desktop.
Save anonymous/6430461 to your computer and use it in GitHub Desktop.
Attempt to convert tables back and forth between org-mode (with <r> etc tags and |--+--|) and markdown (with |:--|--:| etc).
(defun orgtbl-to-md (start end)
"Convert an org-mode table into markdown format"
(interactive "r")
(save-excursion
(save-restriction
(narrow-to-region start end)
(goto-char (point-min))
;; Locate divider row
(re-search-forward "^\\s-*|-[-+]*|?\\s-*$")
;; Start by replacing the +es
(subst-char-in-region (match-beginning 0) (match-end 0) ?+ ?|)
;; Locate column alignment row (fixme: code below expects this to be next line)
(re-search-forward "^\\s-*\\(|\\s-*<[lcr]>\\s-*\\)*|?\\s-*$")
;; For each tag, adjust the entry above it
(beginning-of-line)
(while (re-search-forward "<[lcr]>" (line-end-position) t)
(pcase (char-before (1- (point)))
(?r (let ((cc (current-column)))
(forward-line -1)
(move-to-column cc)
(skip-chars-forward "-")
(subst-char-in-region (1- (point)) (point) ?- ?:)
(forward-line)
(move-to-column cc)))
(?l (let ((cc (current-column)))
(forward-line -1)
(move-to-column cc)
(skip-chars-backward "-")
(subst-char-in-region (point) (1+ (point)) ?- ?:)
(forward-line)
(move-to-column cc)))
(?c (let ((cc (current-column)))
(forward-line -1)
(move-to-column cc)
(skip-chars-backward "-")
(subst-char-in-region (point) (1+ (point)) ?- ?:)
(skip-chars-forward "-:")
(subst-char-in-region (1- (point)) (point) ?- ?:)
(forward-line)
(move-to-column cc)))
)
)
;; Remove the alignment tag line
(delete-region (line-beginning-position) (line-beginning-position 2))
)))
(defun md-to-orgtbl (start end)
"Convert a markdown table into org-mode format"
(interactive "r")
(save-excursion
(save-restriction
(narrow-to-region start end)
(goto-char (point-min))
(search-forward-regexp "^\\s-*\\(|:?-+:?\\)*|?\\s-*$")
(let (p1 p2 myLine)
(setq p1 (line-beginning-position) )
(setq p2 (line-end-position) )
(setq myLine (buffer-substring-no-properties p1 p2))
(subst-char-in-region p1 p2 ?: ?-)
(insert "\n")
(insert (replace-regexp-in-string "-+" ""
(replace-regexp-in-string "-+:" "<r>"
(replace-regexp-in-string ":-+" "<l>"
(replace-regexp-in-string ":-+:" "<c>"
myLine)))))
))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment