|
|
|
@@ -10,6 +10,7 @@ import builtins
|
|
|
|
|
from pathlib import Path
|
|
|
|
|
import re
|
|
|
|
|
import unicodedata
|
|
|
|
|
import difflib
|
|
|
|
|
from collections import Counter
|
|
|
|
|
from typing import List, Union, Optional, Dict, Any
|
|
|
|
|
from urllib.parse import quote
|
|
|
|
@@ -91,6 +92,26 @@ def _iter_notes(vault_path: Path):
|
|
|
|
|
yield path
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _match_notes(vault_path: Path, name: str, folder: Optional[str] = None) -> List[tuple]:
|
|
|
|
|
"""(path, alias) for notes whose filename (alias None) or one of whose aliases equals
|
|
|
|
|
`name`, case and accents ignored, sorted by path. No fuzzy matching."""
|
|
|
|
|
wanted = _fold(name)
|
|
|
|
|
prefix = folder.strip('/') + '/' if folder else None
|
|
|
|
|
matches = []
|
|
|
|
|
for note in sorted(_iter_notes(vault_path)):
|
|
|
|
|
if prefix and not note.relative_to(vault_path).as_posix().startswith(prefix):
|
|
|
|
|
continue
|
|
|
|
|
if _fold(note.stem) == wanted:
|
|
|
|
|
matches.append((note, None))
|
|
|
|
|
continue
|
|
|
|
|
aliases = _read_frontmatter(note.read_text(encoding='utf-8-sig'), needed='aliases').get('aliases') or []
|
|
|
|
|
aliases = aliases if isinstance(aliases, list) else [aliases]
|
|
|
|
|
alias = next((str(a) for a in aliases if a is not None and _fold(a) == wanted), None)
|
|
|
|
|
if alias is not None:
|
|
|
|
|
matches.append((note, alias))
|
|
|
|
|
return matches
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
_HEADING = re.compile(r'^(#{1,6})[ \t]+(.*?)[ \t]*$')
|
|
|
|
|
_FENCE = re.compile(r'^[ \t]*(`{3,}|~{3,})')
|
|
|
|
|
_LIST_ITEM = re.compile(r'^[ \t]*([-*+]|\d+[.)])[ \t]')
|
|
|
|
@@ -440,41 +461,18 @@ class OnyxCLI:
|
|
|
|
|
def open_note(self, note_name: str, vault: str = None):
|
|
|
|
|
vault_name, vault_path = self._get_vault_and_path(vault)
|
|
|
|
|
|
|
|
|
|
# Try exact path first
|
|
|
|
|
note_path = vault_path / note_name
|
|
|
|
|
|
|
|
|
|
# Check if it's a directory first
|
|
|
|
|
if note_path.is_dir():
|
|
|
|
|
# Open directory in system explorer
|
|
|
|
|
# A folder opens in the system file explorer
|
|
|
|
|
folder_path = vault_path / note_name
|
|
|
|
|
if folder_path.is_dir():
|
|
|
|
|
if sys.platform == 'win32':
|
|
|
|
|
os.startfile(note_path)
|
|
|
|
|
os.startfile(folder_path)
|
|
|
|
|
elif sys.platform == 'darwin':
|
|
|
|
|
subprocess.run(['open', note_path])
|
|
|
|
|
subprocess.run(['open', folder_path])
|
|
|
|
|
else:
|
|
|
|
|
subprocess.run(['xdg-open', note_path])
|
|
|
|
|
subprocess.run(['xdg-open', folder_path])
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
if not note_path.suffix:
|
|
|
|
|
note_path = note_path.with_suffix('.md')
|
|
|
|
|
|
|
|
|
|
# If not found, try in daily notes folder if configured
|
|
|
|
|
# if not note_path.exists():
|
|
|
|
|
# settings = self._get_daily_note_settings(vault_path)
|
|
|
|
|
# if settings['folder']:
|
|
|
|
|
# daily_note_path = vault_path / settings['folder'] / f"{note_name}.md"
|
|
|
|
|
# if daily_note_path.exists():
|
|
|
|
|
# note_path = daily_note_path
|
|
|
|
|
|
|
|
|
|
# If still not found, try searching the entire vault
|
|
|
|
|
if not note_path.exists():
|
|
|
|
|
matches = list(vault_path.rglob(f"{note_name}.md"))
|
|
|
|
|
if matches:
|
|
|
|
|
note_path = matches[0] # Use first match
|
|
|
|
|
|
|
|
|
|
if not note_path.exists():
|
|
|
|
|
raise click.UsageError(f"Note {note_name} does not exist")
|
|
|
|
|
|
|
|
|
|
# Get the relative path from the vault root for the URI
|
|
|
|
|
note_path = self._find_note(vault_path, note_name)
|
|
|
|
|
relative_path = note_path.relative_to(vault_path)
|
|
|
|
|
# URL encode both the vault name and file path to handle special characters
|
|
|
|
|
encoded_vault = self._url_encode(vault_name)
|
|
|
|
@@ -700,30 +698,16 @@ class OnyxCLI:
|
|
|
|
|
"""Print notes whose filename or one of whose aliases equals `name` (case and accents
|
|
|
|
|
ignored, no fuzzy matching). Returns the number of matches."""
|
|
|
|
|
vault_name, vault_path = self._get_vault_and_path(vault)
|
|
|
|
|
notes = list(_iter_notes(vault_path))
|
|
|
|
|
stems = Counter(p.stem.casefold() for p in notes)
|
|
|
|
|
wanted = _fold(name)
|
|
|
|
|
matches = 0
|
|
|
|
|
for note in sorted(notes):
|
|
|
|
|
if folder and not note.relative_to(vault_path).as_posix().startswith(folder.strip('/') + '/'):
|
|
|
|
|
continue
|
|
|
|
|
if _fold(note.stem) == wanted:
|
|
|
|
|
display = None
|
|
|
|
|
else:
|
|
|
|
|
text = note.read_text(encoding='utf-8-sig')
|
|
|
|
|
aliases = _read_frontmatter(text, needed='aliases').get('aliases') or []
|
|
|
|
|
aliases = aliases if isinstance(aliases, list) else [aliases]
|
|
|
|
|
display = next((str(a) for a in aliases if a is not None and _fold(a) == wanted), None)
|
|
|
|
|
if display is None:
|
|
|
|
|
continue
|
|
|
|
|
matches += 1
|
|
|
|
|
matches = _match_notes(vault_path, name, folder)
|
|
|
|
|
stems = Counter(p.stem.casefold() for p in _iter_notes(vault_path)) if link else None
|
|
|
|
|
for note, alias in matches:
|
|
|
|
|
rel = note.relative_to(vault_path).with_suffix('').as_posix()
|
|
|
|
|
if link:
|
|
|
|
|
target = note.stem if stems[note.stem.casefold()] == 1 else rel
|
|
|
|
|
click.echo(f"[[{target}|{display}]]" if display else f"[[{target}]]")
|
|
|
|
|
click.echo(f"[[{target}|{alias}]]" if alias else f"[[{target}]]")
|
|
|
|
|
else:
|
|
|
|
|
click.echo(rel)
|
|
|
|
|
return matches
|
|
|
|
|
return len(matches)
|
|
|
|
|
|
|
|
|
|
def _notes_in(self, vault_path: Path, folder: Optional[str]) -> List[Path]:
|
|
|
|
|
base = vault_path / folder if folder else vault_path
|
|
|
|
@@ -782,14 +766,7 @@ class OnyxCLI:
|
|
|
|
|
|
|
|
|
|
def print_note(self, note_name: str, vault: str = None):
|
|
|
|
|
vault_name, vault_path = self._get_vault_and_path(vault)
|
|
|
|
|
note_path = vault_path / note_name
|
|
|
|
|
if not note_path.suffix:
|
|
|
|
|
note_path = note_path.with_suffix('.md')
|
|
|
|
|
|
|
|
|
|
if not note_path.exists():
|
|
|
|
|
raise click.UsageError(f"Note {note_name} does not exist")
|
|
|
|
|
|
|
|
|
|
click.echo(note_path.read_text(encoding='utf-8-sig'))
|
|
|
|
|
click.echo(self._find_note(vault_path, note_name).read_text(encoding='utf-8-sig'))
|
|
|
|
|
|
|
|
|
|
def move_note(self, current_path: str, new_path: str, vault: str = None, open_after: bool = False):
|
|
|
|
|
"""Move/rename a note and rewrite wikilinks that resolve to it.
|
|
|
|
@@ -893,17 +870,38 @@ class OnyxCLI:
|
|
|
|
|
return {}, content, 0
|
|
|
|
|
|
|
|
|
|
def _find_note(self, vault_path: Path, note_name: str) -> Path:
|
|
|
|
|
"""Exact vault-relative path first, then the first note with that name anywhere."""
|
|
|
|
|
"""Exact vault-relative path first; otherwise the single note whose filename or alias
|
|
|
|
|
matches (case and accents ignored), or whose path ends with `note_name` when it
|
|
|
|
|
contains '/'. Filename matches win over alias matches. Several candidates or none
|
|
|
|
|
raise a UsageError listing candidates or close filenames; nothing is guessed."""
|
|
|
|
|
note_path = vault_path / note_name
|
|
|
|
|
if not note_path.suffix:
|
|
|
|
|
note_path = note_path.with_suffix('.md')
|
|
|
|
|
if not note_path.exists():
|
|
|
|
|
matches = list(vault_path.rglob(f"{note_name}.md"))
|
|
|
|
|
if matches:
|
|
|
|
|
note_path = matches[0]
|
|
|
|
|
if not note_path.exists():
|
|
|
|
|
raise click.UsageError(f"Note {note_name} does not exist")
|
|
|
|
|
return note_path
|
|
|
|
|
if note_path.is_file():
|
|
|
|
|
return note_path
|
|
|
|
|
|
|
|
|
|
name = note_name[:-3] if note_name.lower().endswith('.md') else note_name
|
|
|
|
|
if '/' in name.replace('\\', '/'):
|
|
|
|
|
wanted = _fold(name.replace('\\', '/').strip('/'))
|
|
|
|
|
candidates = [p for p in sorted(_iter_notes(vault_path))
|
|
|
|
|
if (rel := _fold(p.relative_to(vault_path).with_suffix('').as_posix())) == wanted
|
|
|
|
|
or rel.endswith('/' + wanted)]
|
|
|
|
|
else:
|
|
|
|
|
matches = _match_notes(vault_path, name)
|
|
|
|
|
candidates = [p for p, alias in matches if alias is None] or [p for p, _ in matches]
|
|
|
|
|
|
|
|
|
|
if len(candidates) == 1:
|
|
|
|
|
return candidates[0]
|
|
|
|
|
if candidates:
|
|
|
|
|
listing = '\n'.join(f" {p.relative_to(vault_path).with_suffix('').as_posix()}" for p in candidates)
|
|
|
|
|
raise click.UsageError(f"Note {note_name} is ambiguous; use one of these paths:\n{listing}")
|
|
|
|
|
stems = sorted({p.stem for p in _iter_notes(vault_path)})
|
|
|
|
|
by_fold = {}
|
|
|
|
|
for stem in stems:
|
|
|
|
|
by_fold.setdefault(_fold(stem), stem)
|
|
|
|
|
close = difflib.get_close_matches(_fold(name), list(by_fold), n=3, cutoff=0.6)
|
|
|
|
|
hint = f" Did you mean: {', '.join(by_fold[c] for c in close)}?" if close else ""
|
|
|
|
|
raise click.UsageError(f"Note {note_name} does not exist.{hint}")
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def _split_keys(keys: tuple) -> List[str]:
|
|
|
|
@@ -1222,7 +1220,7 @@ def _periodic_output_options(command):
|
|
|
|
|
help="Don't open Obsidian; a newly created note keeps raw Templater syntax "
|
|
|
|
|
"until Obsidian processes it")(command)
|
|
|
|
|
|
|
|
|
|
@click.version_option(version='0.4.2', prog_name='onyx')
|
|
|
|
|
@click.version_option(version='0.4.3', prog_name='onyx')
|
|
|
|
|
@click.group(name='onyx')
|
|
|
|
|
def cli():
|
|
|
|
|
"""Onyx - Interact with Obsidian vaults from the command line
|
|
|
|
@@ -1266,11 +1264,16 @@ def print_default():
|
|
|
|
|
def open(note_name, vault):
|
|
|
|
|
"""Open a note in Obsidian
|
|
|
|
|
|
|
|
|
|
Searches for the note in the vault and opens it in Obsidian. Supports nested directories.
|
|
|
|
|
Exact vault-relative path first; otherwise the one note whose filename or alias
|
|
|
|
|
matches (case and accents ignored), or whose path ends with the given partial
|
|
|
|
|
path. Filename matches win over aliases. When several notes match, nothing is
|
|
|
|
|
opened and the candidate paths are listed; when none match, close filenames are
|
|
|
|
|
suggested. No fuzzy opening. A folder opens in the file explorer.
|
|
|
|
|
|
|
|
|
|
USAGE:
|
|
|
|
|
onyx open "my-note"
|
|
|
|
|
onyx open "folder/my-note"
|
|
|
|
|
onyx open "an alias"
|
|
|
|
|
"""
|
|
|
|
|
OnyxCLI().open_note(note_name, vault)
|
|
|
|
|
|
|
|
|
|