#!/usr/bin/env python3 """ Print the path to the Markdown file which is currently open in Obsidian (if any). This relies on knowing the on-disk locations of my Obsidian vaults, so you won't be able to use this without changing it for your own setup. Note: this will print the *first* file with the same name as your open note, which may cause issues if you have multiple notes with the same title. """ import os import subprocess def get_file_paths_under(root=".", *, suffix=""): """ Generates the absolute paths to every matching file under ``root``. """ if not os.path.isdir(root): raise ValueError(f"Cannot find files under non-existent directory: {root!r}") for dirpath, _, filenames in os.walk(root): for f in filenames: p = os.path.join(dirpath, f) if os.path.isfile(p) and f.lower().endswith(suffix): yield p def get_applescript_output(script): """ Run an AppleScript command and return the output. """ cmd = ["osascript", "-e", script] return subprocess.check_output(cmd).strip().decode("utf8") if __name__ == "__main__": window_title = get_applescript_output(""" tell application "System Events" tell process "Obsidian" to get title of front window end tell """) # The window title will be something of the form: # # Short story ideas - textfiles - Obsidian v1.4.16 # note_title, vault_name, _ = window_title.rsplit(" - ", 2) # Match the vault name to a path on disk. # # This is very specific to my setup, so if you want to use it on # your computer, you'll need to customise this bit. if vault_name == "textfiles": vault_root = os.path.join(os.environ["HOME"], "textfiles") else: raise ValueError(f"Unrecognised vault name: {vault_name}") # Find Markdown files that match the name of this note. for path in get_file_paths_under(vault_root, suffix=".md"): expected = f"{note_title}.md".replace('📗 ', '📗 ') if os.path.basename(path) == expected: print(path, end="") break else: # no break raise RuntimeError(f"Could not find note with title {note_title}")