Using Nextcloud Notes with Org mode

The poor mans two-way sync for nextloud notes

One of the apps that ship with Nextcloud is Notes. It is not much more than its name says. You can open a note, type some text, and do some basic formatting stuff in markdown syntax. If you want, you can give each note a tag, which results in a folder, where that note is placed in. Those notes are synced as normal *.txt files to your file system in a folder named Notes, including the tagging subfolders. It's dead simple, but useful, as I described in my blog entry about writing a shopping list with org mode.

Of course you could just open one of those notes in Emacs, edit it, and save it back. But sometimes you want to sort some of your thoughts within a handfull of those notes, Then it would be useful to have all those notes in a single Org file, with a heading for every note, and subtrees for every tag. That is, what I made this (very small) script for.

#!/usr/bin/env python3
# coding: utf-8
from os import walk
for (dirpath, dirnames, filenames) in walk("~/cloud/Notes"):
    print('* ' + dirpath.split('/')[-1].upper())
    for filename in filenames:
        if not filename[0]=='.':
            with open(dirpath + "/" + filename, 'r', encoding='UTF8') as f:
                text = f.readlines()
                if text:
                    print('** ' + text[0].rstrip() + '  [[file://' + dirpath + "/"
                        + filename + '][link]]')
                    print("#+BEGIN_SRC markdown :tangle " + dirpath + "/" + filename) 
                    for line in text:
                        print(line, end = '')

It takes all files in the Notes folder, and builds such an outline. Notes without a tag come first, followed by subtrees for every tag. The script just writes this tree to stdout, so you may pipe it to any file you want. For simplicity I do it in the crontab every hour, but I will try to integrate it with systemd so that it is rebuild everytime one of the notefiles changes.

The magic happens within each of the headings. Instead of just filling the content of each heading with the text fom the note file, I wrapped it in an source block:

** Bucket List
#+BEGIN_SRC markdown :tangle ~/cloud/Notes/personal/Bucket List.txt
Bucket List

Glasbodenboot fahren
Fallschirmsimulator fliegen
Zero-G Flug
Seeed auf der Waldbühne Berlin

Atomium besichtigen


Because the source block is of the type markdown, it is shown using the markdown renderer, so headings are highlighted, links are clickable, etc.. The filename in the :tangle attribute is the original filename of the file, the note is stored in. Using that, it is easy to store all those notes back into its repective files with a single org-tangle-file (C-c C-v t) command within Org mode. I even tied that command to the after-save-hook, so every time I save my org file, all Notes are also updated.

I like to call it the poor mans two-way sync.