I've been experimenting with http://tableflipapp.com/ and found that I needed something to copy tab-delimited text or Excel selections as Markdown tables. (Pipe-delimited, optionally with a ruler line).
You should be able to adapt an earlier KM macro by Chris Stone to do this (for TableFlip, it will need adjusting to flank the pipe characters with spaces).
Here, in the meanwhile, is a version which also adds a Markdown ruler after the first line – useful if you want to paste tables with headers into TableFlip.
This is a JS version – Sierra ES6 JS by default, but you can alternatively activate the pre-Sierra ES5 JS action which I have also put in there (back-compiled from ES6 by Appspot Closure).
USE
- Select the Excel area or tab-delimited text
- Run the macro to copy and rewrite the clipboard to MD
- In TableFlip, choose File > New from Clipboard
( Or, in Marked 2, choose Clipboard > Preview )
Copy tab-delimited lines as Markdown table.kmmacros (22.9 KB)
ES6 JS Code (for ES5 pre Sierra version, see the alternative action in the macro)
(() => {
'use strict';
ObjC.import('AppKit');
// textClip :: () -> Maybe String
let textClip = () => {
let strUTF8Type = "public.utf8-plain-text",
pb = $.NSPasteboard.generalPasteboard;
return ObjC.deepUnwrap(
pb.pasteboardItems.js[0].types
)
.indexOf(strUTF8Type) !== -1 ? ObjC.unwrap(
pb.stringForType(
strUTF8Type
)
) : undefined;
},
// lines :: String -> [String]
lines = s => s.split(/[\r\n]/),
// unlines :: [String] -> String
unlines = xs => xs.join('\n'),
// maximumBy :: (a -> a -> Ordering) -> [a] -> a
maximumBy = (f, xs) => xs.reduce(function (a, x) {
return a === undefined ? x : (
f(x, a) > 0 ? x : a
);
}, undefined),
// replicate :: Int -> a -> [a]
replicate = (n, a) => {
let v = [a],
o = [];
if (n < 1) return o;
while (n > 1) {
if (n & 1) o = o.concat(v);
n >>= 1;
v = v.concat(v);
}
return typeof a === 'string' ? (
o.concat(v).join('')
) : o.concat(v);
},
mbClip = textClip();
if (mbClip && mbClip.indexOf('\t') !== -1) {
let a = Application.currentApplication(),
sa = (a.includeStandardAdditions = true, a),
lstRows = lines(mbClip)
.map(x => x.split('\t')),
lstMDLines = lstRows
.map(lstRow => '| ' + lstRow.join(' | ') + ' |'),
// Including a Markdown table ruler
strClip = unlines(
[lstMDLines[0]]
.concat(replicate(
maximumBy(
(a, b) => a.length - b.length,
lstRows
).length,
"|--"
) + "|").concat(lstMDLines.slice(1))
);
return (
sa.setTheClipboardTo(
strClip
),
strClip
);
}
})();