Created
December 10, 2013 07:47
-
-
Save ShingoFukuyama/7887053 to your computer and use it in GitHub Desktop.
Convert Emacs org style table to csv/tsv/html/etc on the spot, instead of creating a new file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defun org-table-convert-on-the-spot (&optional format) | |
(interactive) | |
(unless (org-at-table-p) (user-error "No table at point")) | |
(org-table-align) ;; make sure we have everything we need | |
(let* ((beg (org-table-begin)) | |
(end (org-table-end)) | |
(txt (buffer-substring-no-properties beg end)) | |
(formats '("orgtbl-to-tsv" "orgtbl-to-csv" | |
"orgtbl-to-latex" "orgtbl-to-html" | |
"orgtbl-to-generic" "orgtbl-to-texinfo" | |
"orgtbl-to-orgtbl")) | |
(format (or format | |
(org-entry-get beg "TABLE_EXPORT_FORMAT" t))) | |
buf deffmt-readable) | |
(unless format | |
(setq deffmt-readable | |
org-table-export-default-format) | |
(while (string-match "\t" deffmt-readable) | |
(setq deffmt-readable (replace-match "\\t" t t deffmt-readable))) | |
(while (string-match "\n" deffmt-readable) | |
(setq deffmt-readable (replace-match "\\n" t t deffmt-readable))) | |
(setq format (org-completing-read "Format: " formats nil nil deffmt-readable))) | |
(if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format) | |
(let* ((transform (intern (match-string 1 format))) | |
(params (if (match-end 2) | |
(read (concat "(" (match-string 2 format) ")")))) | |
(skip (plist-get params :skip)) | |
(skipcols (plist-get params :skipcols)) | |
(lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*"))) | |
(lines (org-table-clean-before-export lines)) | |
(i0 (if org-table-clean-did-remove-column 2 1)) | |
(table (mapcar | |
(lambda (x) | |
(if (string-match org-table-hline-regexp x) | |
'hline | |
(org-remove-by-index | |
(org-split-string (org-trim x) "\\s-*|\\s-*") | |
skipcols i0))) | |
lines)) | |
(fun (if (= i0 2) 'cdr 'identity)) | |
(org-table-last-alignment | |
(org-remove-by-index (funcall fun org-table-last-alignment) | |
skipcols i0)) | |
(org-table-last-column-widths | |
(org-remove-by-index (funcall fun org-table-last-column-widths) | |
skipcols i0))) | |
(unless (fboundp transform) | |
(user-error "No such transformation function %s" transform)) | |
(setq txt (funcall transform table params)) | |
(delete-region beg end) | |
(insert txt "\n") | |
(message "Export done.")) | |
(user-error "TABLE_EXPORT_FORMAT invalid")))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment