我也遇到了这个问题(我最近才转用emacs),我编写了一个小的AWK脚本,可以将您提到的“网格表”(即不使用org-mode表)转换为GFM表格。
您可以有几种方法使用此脚本。您只需标记表,然后键入
C-u M-| awk脚本名称RET
(我从
this Stackoverflow thread学到了这个技巧)。这将使用区域作为AWK脚本的stdin,并替换该区域的输出。我在编写ELisp方面非常新手,但我还编写了一些辅助函数。
table-gfm-export
函数目前不会像交互式使用
C-u M-|
那样替换文本,因为它仍然保留原始表格在缓冲区中。
(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")
(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")
(shell-command-on-region start end "gfm_table_format" t t)
(table-unrecognize))
这个脚本的一个好处是它可以使用一些简单的正则表达式来识别列的对齐方式。另一个函数
table-gfm-capture
无法保持对齐,因此您不能自由地来回切换。该系统基本上是为在表格模式下进行所有编辑,然后在最后导出到GFM而设计的。你可能会认为Emacs已经具备了使用
table-generate-source
生成Markdown表格的功能,但不幸的是并没有。
#!/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;
}
}