Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
var zk_get_metadata = function(d, pattern) {
let match = zk_metadata(d)
.match(RegExp("^" + pattern + ": (.*)", 'm'));
if (match !== null) {
return match[1];
} else {
return null;
}
};
var zk_update_metadata = function(d, pattern, value) {
let metadata = zk_metadata(d);
let body = zk_body(d);
let lines = [];
if (metadata == "") {
lines = [`${pattern}: ${value}`];
} else {
lines = metadata.split("\n");
let index = lines.findIndex((meta) => RegExp("^" + pattern + ": (.*)", '').test(meta));
if (index == -1 ) {
lines.push(`${pattern}: ${value}`);
} else {
lines[index] = `${pattern}: ${value}`;
}
}
d.content = lines.join("\n") + "\n\n" + body;
d.update();
};
var zk_add_tag = function(d, tag) {
let tags = zk_get_metadata(d, "tags") || "";
tags = tags.split(/, ?/).filter((a) => a != '');
if (!tags.includes(tag)) {
tags.push(tag);
}
zk_update_metadata(d, "tags", tags.join(", "));
};
var zk_extract_tags = function(d) {
let matches = [...zk_body(d).matchAll(/#\w+/g)].map((m) => m[0]);
for (t of matches) {
zk_add_tag(d, t)
}
}
var zk_title = function(d) {
if (zk_get_metadata(d, "title") != null) {
title = zk_get_metadata(d, "title");
} else if (zk_body(d).split("\n")[0] != "") {
title = zk_body(d).split("\n")[0];
} else {
title = ""
}
return title;
}
var zk_id = function(d) {
if (d.content.search(/^id: (.*)/) != -1) {
id = zk_get_metadata(draft, "id");
}
else {
id = strftime(d.createdAt, "%Y%m%d%H%M%S").toString()
}
return id;
}
var zk_metadata = function(d) {
if ((/^\w+: .*/).test(d.content)) {
let lines = d.content.split("\n");
let i = 0;
// skip metadata
while (/^\w+: .*/.test(lines[i])) {
i++;
}
// skip blank lines
while (/^\s*$/.test(lines[i])) {
i++;
}
return lines.slice(0, i-1).join("\n");
} else {
return "";
}
};
var zk_body = function(d) {
if ((/^\w+: .*/).test(d.content)) {
let lines = d.content.split("\n");
let i = 0;
// skip metadata
while (/^\w+: .*/.test(lines[i])) {
i++;
}
return lines.slice(i+1).join("\n");
} else {
return d.content;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment