|
#!/usr/bin/env python3 |
|
# encoding=utf8 |
|
""" |
|
**tomboy2markdown**: Convert Tomboy/Gnote notes to Markdown files. |
|
|
|
It uses Markdown formatting when possible and creates subdirectories for notebooks. |
|
|
|
This is a rewritten script of [**tomboy2text**](https://github.com/joh/tomboy2text) |
|
by [Johannes H. Jensen](https://github.com/joh) with improved Markdown compatibility and customizability. |
|
Several known issues reported for tomboy2text are fixed. The output files are tested with Typora. |
|
|
|
## Usage |
|
``` |
|
usage: tomboy2markdown.py [-h] [-o OUTFILE] [-s SUFFIX] [-S] [-f] [-r] notes [notes ...] |
|
|
|
positional arguments: |
|
notes note files or directory |
|
|
|
optional arguments: |
|
-h, --help show this help message and exit |
|
-o OUTFILE, --outfile OUTFILE |
|
output file or directory (default: stdout) |
|
-s SUFFIX, --suffix SUFFIX |
|
output file suffix (default: .md) |
|
-S, --sort-name sort input files according to file name |
|
-f, --force allow to overwrite existing target files |
|
-r, --recursive search the input directory recursively |
|
``` |
|
|
|
Edit the configuration block in this script for more control of the output formats. |
|
|
|
## Notes |
|
Two spaces are inserted at the end of each line by default. Because single line break might not be |
|
interpreted properly in the Markdown editors that do not support Github flavor. |
|
Disable this behavior by setting `hard_linebreak = False` in the script. |
|
|
|
When the formats, e.g., bold, italic, embrace multiple-line texts in Tomboy, the converted Markdown |
|
may or may not interpreted properly. I guess that the original tomboy2text can do a better job |
|
in certain cases because it handles the environments per line. |
|
|
|
When the input is a Tomby backup directory, sorting is recommended to save the latest version of a note. |
|
Multiple versions of a note might be saved separately if they have different titles. |
|
This can be fixed by manually parsing the latest manifest.xml in the directory. |
|
|
|
## References |
|
- https://github.com/joh/tomboy2text |
|
- https://wiki.gnome.org/Apps/Tomboy/NoteXmlFormat |
|
- https://github.github.com/gfm |
|
- http://support.typora.io/Markdown-Reference |
|
|
|
## License |
|
The GPL License |
|
""" |
|
import sys |
|
import os |
|
import xml.sax |
|
import dateutil.parser |
|
import time |
|
import glob |
|
import re |
|
import unicodedata |
|
|
|
|
|
# [configuration] |
|
hard_linebreak = True # add two spaces before new line |
|
tabsize = 2 |
|
format_dict = { |
|
'bold': ['**', '**'], |
|
'italic': ['_', '_'], |
|
'strikethrough': ['~~', '~~'], |
|
'highlight': ['==', '=='], |
|
'monospace': ['`', '`'], |
|
'underline': ['<u>', '</u>'], |
|
'size:small': ['<small>', '</small>'], |
|
'size:large': ['<big>', '</big>'], |
|
'size:huge': ['<big><big>', '</big></big>'], |
|
# 'size:large': ['## ', ''], # interpret `large` as header |
|
# 'size:huge': ['# ', ''], # interpret `huge` as header |
|
} |
|
bullet_table = ['-', '*', '+'] |
|
mapping_dict = { |
|
# Tomboy LaTeX plugin |
|
'\\[': '$$', |
|
'\\]': '$$', |
|
'\\(': '$', |
|
'\\)': '$', |
|
} |
|
write_metadata = True # insert tags, time stamps and original file after header line |
|
timestamp_format = '%Y-%m-%d %H:%M:%S' |
|
# [configuration end] |
|
|
|
|
|
def lstrip(string, prefix): |
|
if string.startswith(prefix): |
|
return string[len(prefix):] |
|
else: |
|
return string |
|
|
|
|
|
def first_linebreak(content): |
|
for i, segment in enumerate(content): |
|
if segment.endswith('\n'): |
|
break |
|
return i |
|
|
|
|
|
def safe_filename(value, max_length=50): |
|
""" |
|
slugify unicode string for legal filename |
|
|
|
keep word characters '_.()[]' |
|
convert all other characters to '_' |
|
trim sequential '.' to single '.' |
|
reduce mixing sequential '.' and '_' to single '_' |
|
cut and add '[…]' if string exceeds max_length |
|
""" |
|
value = unicodedata.normalize('NFKD', value) |
|
|
|
if value.endswith('[…]'): |
|
value, tail = value[:-3], value[-3:] |
|
else: |
|
tail = None |
|
|
|
value = re.sub(r'[^\w\.()[\]]', '_', value) |
|
value = re.sub(r'\.+', '.', value) |
|
value = re.sub(r'(\.?[_]+\.?)+', '_', value) |
|
|
|
if tail is not None: |
|
value = value + tail |
|
else: |
|
value = value.strip('._') |
|
|
|
if len(value) <= max_length: |
|
return value |
|
else: |
|
return value[:max_length - 3] + '[…]' |
|
|
|
|
|
class TomboyContentHandler(xml.sax.ContentHandler): |
|
def __init__(self): |
|
xml.sax.ContentHandler.__init__(self) |
|
|
|
# current status |
|
self.list_level = 0 |
|
self.in_element = None |
|
|
|
# file content |
|
self.title = [] |
|
self.content = [] |
|
self.change_time = None |
|
self.create_time = None |
|
self.notebook = None |
|
self.tags = [] |
|
|
|
def startElement(self, name, attrs): |
|
if name in ('title', 'note-content', 'last-change-date', 'create-date', 'tag'): |
|
self.in_element = name |
|
if name == 'note-content': |
|
self.content.append('# ') # make first line to be header |
|
|
|
if self.in_element == 'note-content': |
|
if name == 'list': |
|
self.list_level += 1 |
|
elif name == 'list-item': |
|
indent = (self.list_level - 1) * tabsize |
|
if not self.content[-1].endswith('\n'): |
|
# do not indent if no line break ahead |
|
indent = 0 |
|
# an alternative solution is inserting a line break manually |
|
# self.content.append('\n') |
|
bullet = bullet_table[(self.list_level - 1) % len(bullet_table)] |
|
self.content.append('{:<{}}{} '.format('', indent, bullet)) |
|
elif name in format_dict: |
|
self.content.append(format_dict[name][0]) |
|
|
|
def endElement(self, name): |
|
if name in ('title', 'note-content', 'last-change-date', 'create-date', 'tag'): |
|
self.in_element = None |
|
if name == 'title': |
|
self.title = ''.join(self.title).strip() |
|
if name == 'note-content': |
|
if not self.content[-1].endswith('\n'): |
|
self.content.append('\n') |
|
|
|
if self.in_element == 'note-content': |
|
if name == 'list': |
|
self.list_level -= 1 |
|
if self.list_level == 0: |
|
# insert newline after the root list |
|
self.content.append('\n') |
|
elif name in format_dict: |
|
self.content.append(format_dict[name][1]) |
|
|
|
def characters(self, content): |
|
if self.in_element == 'title': |
|
self.title.append(content) |
|
elif self.in_element == 'note-content': |
|
for key, value in mapping_dict.items(): |
|
content = content.replace(key, value) |
|
if hard_linebreak and content == '\n': |
|
# add two space before linebreak, |
|
# but not for lists, header or successive new lines |
|
if self.list_level == 0 and len(self.content) > 3 and not self.content[-1].endswith('\n'): |
|
content = ' \n' |
|
self.content.append(content) |
|
elif self.in_element == 'last-change-date': |
|
self.change_time = dateutil.parser.parse(content) |
|
elif self.in_element == 'create-date': |
|
self.create_time = dateutil.parser.parse(content) |
|
elif self.in_element == 'tag': |
|
tag = lstrip(content, "system:") |
|
if tag.startswith("notebook:"): |
|
tag = lstrip(tag, "notebook:") |
|
self.notebook = tag |
|
self.tags.append(tag) |
|
|
|
|
|
def parse_note(filename): |
|
handler = TomboyContentHandler() |
|
with open(filename, 'r') as f: |
|
xml.sax.parse(f, handler) |
|
|
|
return {'title': handler.title, |
|
'content': handler.content, |
|
'change_time': handler.change_time, |
|
'create_time': handler.create_time, |
|
'notebook': handler.notebook, |
|
'tags': handler.tags} |
|
|
|
|
|
def main(args): |
|
if len(args.notes) == 1 and os.path.isdir(args.notes[0]): |
|
# works for Python >= 3.5 |
|
if args.recursive: |
|
notelist = glob.glob(os.path.join(args.notes[0], '**/*.note'), recursive=True) |
|
else: |
|
notelist = glob.glob(os.path.join(args.notes[0], '*.note')) |
|
else: |
|
notelist = args.notes |
|
if args.sort_name: |
|
notelist = sorted(notelist) |
|
# elif args.sort_time: |
|
# notelist = sorted(notelist, key=os.path.getmtime) |
|
|
|
outdir = None |
|
if args.outfile: |
|
if os.path.isdir(args.outfile) or args.outfile[-1] in ['/', '\\']: |
|
outdir = args.outfile[:-1] |
|
elif len(notelist) > 1: |
|
outdir = args.outfile |
|
if os.path.exists(outdir): |
|
# outdir is an existing file |
|
raise TypeError("An output directory is required for multiple notes.") |
|
|
|
for notefile in notelist: |
|
note = parse_note(notefile) |
|
content = note['content'] |
|
|
|
if write_metadata: |
|
meta = [] |
|
if note['tags']: |
|
meta.append(''.join('@{} '.format(tag) for tag in note['tags'])) |
|
if 'template' in note['tags']: |
|
print('Skip template note `{}`: `{}`.'.format(note['title'], notefile)) |
|
continue |
|
if note['create_time']: |
|
meta.append('@created: {} '.format(note['create_time'].astimezone().strftime(timestamp_format))) |
|
if note['change_time']: |
|
meta.append('@changed: {} '.format(note['change_time'].astimezone().strftime(timestamp_format))) |
|
meta.append('@source: {} '.format(notefile)) |
|
meta_string = '\n{}\n********\n'.format('\n'.join(meta)) |
|
|
|
headline_index = first_linebreak(content) # index of the first line break |
|
content.insert(headline_index + 1, meta_string) # insert meta info after the first line |
|
|
|
content_string = ''.join(content) |
|
|
|
if outdir: |
|
subdir = outdir |
|
if note['notebook']: |
|
subdir = os.path.join(outdir, safe_filename(note['notebook'])) |
|
|
|
if not os.path.isdir(subdir): |
|
os.makedirs(subdir) |
|
|
|
filename = safe_filename(note['title'] + args.suffix) |
|
filepath = os.path.join(subdir, filename) |
|
else: |
|
filepath = args.outfile |
|
|
|
if filepath: |
|
if os.path.exists(filepath): |
|
if args.force: |
|
print('Overwrite existing target `{}`: `{}`.'.format(filepath, notefile)) |
|
else: |
|
print('Skip existing target `{}`: `{}`.'.format(filepath, notefile)) |
|
continue |
|
|
|
with open(filepath, 'w') as file: |
|
file.write(content_string) |
|
|
|
if note['change_time']: |
|
mtime = time.mktime(note['change_time'].timetuple()) |
|
os.utime(filepath, (mtime, mtime)) |
|
else: |
|
sys.stdout.write(content_string) |
|
|
|
|
|
if __name__ == '__main__': |
|
import argparse |
|
|
|
parser = argparse.ArgumentParser(description='Convert Tomboy/Gnote notes to Markdown files') |
|
parser.add_argument('notes', nargs='+', help='note files or directory') |
|
parser.add_argument('-o', '--outfile', default='', |
|
help='output file or directory (default: stdout)') |
|
parser.add_argument('-s', '--suffix', default='.md', |
|
help='output file suffix (default: %(default)s)') |
|
parser.add_argument('-S', '--sort-name', default=False, action='store_true', |
|
help='sort input files according to file name') |
|
parser.add_argument('-f', '--force', default=False, action='store_true', |
|
help='allow to overwrite existing target files') |
|
parser.add_argument('-r', '--recursive', default=False, action='store_true', |
|
help='search the input directory recursively') |
|
|
|
args = parser.parse_args() |
|
main(args) |