I ran into this exact problem as well (I'm a recent emacs convert), and I wrote a little AWK script that can convert the "grid tables" you mentioned (i.e. not using org-mode tables) into GFM tables.
There's a couple ways you can use this script. All you have to do is mark the table, then type C-u M-| name-of-awk-script RET
(I learned this trick from this Stackoverflow thread). That will use the region as the stdin of the AWK script and replace the region with the output. I'm very much a noob at writing ELisp, but I also wrote a couple of helper functions. The table-gfm-export
function currently does not replace the text in the same way as doing it interactively with C-u M-|
would, because it still leaves the original table in the buffer.
(defun table-gfm-capture (start end)
"convert Markdown table to Emacs table
there should be no pipes beginning or ending the line,
although this is valid syntax. Loses justification."
(interactive "r")
;; should prompt user for justification
(table-capture start end "|"
"[\n][:|-]*" 'center))
(defun table-gfm-export (start end)
"uses AWK script to convert Emacs table to
GFM Markdown table"
(interactive "r")
;; replace gfm_table_format if necessary
(shell-command-on-region start end "gfm_table_format" t t)
(table-unrecognize))
One neat thing about this script is that it can also recognize the justification of the columns using some simple regexes. The other function table-gfm-capture
, is unable to maintain the justification, so you can't freely switch back and forth. This system is pretty much designed for doing all editing in table mode and then exporting to GFM at the very end. You would Emacs would already have the ability to generate Markdown tables using table-generate-source
, but alas.
#!/usr/bin/env awk -f
# -*- mode: awk -*-
BEGIN {
FS="|";
first=1;
}
function detect_justification(f) {
if (match(f, /^ .* $/)) {
return 0; # center-justified
} else if (match(f, / $/)) {
return -1; # left-justified
} else { return 1; } # right-justified
}
function gen_field(len, just) {
str = sprintf("%*s", len, "");
gsub(/ /, "-", str);
if (just <= 0) {
# left or center, start with :
sub(/-/, ":", str);
}
if (just >= 0) {
# right or center, end with :
sub(/-$/, ":", str);
}
return str;
}
function gen_rule() {
str = "";
# ignore first and last empty fields
for (i=1; i < NF; i++) {
len = length($i);
just = detect_justification($i);
str = sprintf("%s%s|", str, gen_field(len, just));
}
return str;
}
function sanitize_line(line) {
# strip outer pipes and trailing whitespace
if (index(line, "|") == 1) {
line = substr(line, 2);
}
sub(/[ |]*$/, "", line);
return line;
}
! /^\+/ {
print(sanitize_line($0));
if (first) {
print(sanitize_line(gen_rule()));
first = 0;
}
}