Skip to content

Instantly share code, notes, and snippets.

@Sigafoos
Last active September 30, 2019 16:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sigafoos/9b542509f4c4306a564a8eda89e9a589 to your computer and use it in GitHub Desktop.
Save Sigafoos/9b542509f4c4306a564a8eda89e9a589 to your computer and use it in GitHub Desktop.
JavaScript to parse todo.txt (todotxt.org) formatted todos into objects
const date = '\\d{4}-\\d{2}-\\d{2}',
contextre = /\B@\w+/g;
projectre = /\B\+\w+/g,
tagre = /[\w\-_]+:[\w\-_]+/g;
const pluckAll = (raw, re) => {
let matches = raw.match(re);
if (matches) {
matches.forEach(p => {
let position = raw.indexOf(p);
raw = raw.substr(0, position) + raw.substr(position + p.length);
});
}
return [raw, matches];
}
const parse = raw => {
let todo = {};
if (raw.indexOf('x ') === 0) {
todo.done = true;
raw = raw.substr(2);
let completed = new RegExp('^' + date + ' ').exec(raw);
if (completed) {
todo.completed = completed[0].trim();
raw = raw.substr(11);
}
}
let priority = /^\(([a-z])\) /.exec(raw);
if (priority) {
todo.priority = priority[1].toUpperCase()
raw = raw.substr(4);
}
let created = new RegExp('^' + date + ' ').exec(raw);
if (created) {
todo.created = created[0].trim();
raw = raw.substr(11);
}
let projects = [];
[raw, projects] = pluckAll(raw, projectre);
if (projects) {
todo.projects = projects;
}
let contexts = [];
[raw, contexts] = pluckAll(raw, contextre);
if (contexts) {
todo.contexts = contexts;
}
let tags = [];
[raw, tags] = pluckAll(raw, tagre);
if (tags) {
tags.forEach(t => {
let [k, v] = t.split(':');
todo[k] = v;
});
}
raw = raw.trim();
raw = raw.replace(/\s{2,}/g, ' ');
todo.text = raw;
return todo;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment