163 lines
6.8 KiB
Python
163 lines
6.8 KiB
Python
|
|
#!/usr/bin/env python3
|
||
|
|
"""
|
||
|
|
Normalize nested-list indentation in Markdown notes (e.g. after a Logseq -> Obsidian import).
|
||
|
|
|
||
|
|
Obsidian's Logseq Importer writes each nesting level as 2 columns, encoded "tabs then spaces"
|
||
|
|
with a tab worth 4 columns:
|
||
|
|
|
||
|
|
level 1: " - " level 2: "\t- " level 3: "\t - " level 4: "\t\t- "
|
||
|
|
|
||
|
|
That renders correctly, but it mixes tabs and spaces and doesn't match what Obsidian inserts
|
||
|
|
when you press Tab, so editing those lists gets messy. This script rewrites every list item so
|
||
|
|
that each level uses exactly one indent unit (a tab by default, matching Obsidian's default
|
||
|
|
"Indent using tabs"), and keeps the nesting the same.
|
||
|
|
|
||
|
|
How levels are worked out: within a list, a line indented further than the item above it is a
|
||
|
|
child of that item; one indented the same as an earlier item is its sibling. A paragraph or
|
||
|
|
heading at column 0 ends the list. Lines that belong to an item but aren't items themselves
|
||
|
|
(block ids like "^abc123", wrapped text, fenced code inside an item) move with their item and
|
||
|
|
keep their offset from it, so code inside items stays aligned.
|
||
|
|
|
||
|
|
Left untouched: YAML frontmatter, fenced code blocks outside lists, indented lines that aren't
|
||
|
|
in a list, lists inside blockquotes.
|
||
|
|
|
||
|
|
python3 normalize_list_indent.py --dry-run -r <vault> # list files that would change
|
||
|
|
python3 normalize_list_indent.py --diff note.md # show the exact changes
|
||
|
|
python3 normalize_list_indent.py -r <vault> # apply
|
||
|
|
python3 normalize_list_indent.py --indent 2 -r <vault> # 2 spaces per level instead
|
||
|
|
"""
|
||
|
|
import argparse
|
||
|
|
import difflib
|
||
|
|
import re
|
||
|
|
import sys
|
||
|
|
from pathlib import Path
|
||
|
|
|
||
|
|
LIST_ITEM = re.compile(r"^([ \t]*)([-*+]|\d{1,9}[.)])([ \t]+|$)")
|
||
|
|
FENCE = re.compile(r"^[ \t]*(?:(?:[-*+]|\d{1,9}[.)])[ \t]+)?(`{3,}|~{3,})")
|
||
|
|
|
||
|
|
|
||
|
|
def lead(line: str) -> str:
|
||
|
|
return line[: len(line) - len(line.lstrip(" \t"))]
|
||
|
|
|
||
|
|
|
||
|
|
class Normalizer:
|
||
|
|
def __init__(self, unit: str, tab_width: int):
|
||
|
|
self.unit = unit # one indent level in the output: "\t" or N spaces
|
||
|
|
self.tab_width = tab_width # how wide a tab is in the *input*
|
||
|
|
|
||
|
|
def col(self, line: str) -> int:
|
||
|
|
return len(lead(line).expandtabs(self.tab_width))
|
||
|
|
|
||
|
|
def normalize(self, text: str) -> str:
|
||
|
|
lines = text.split("\n")
|
||
|
|
start = 0
|
||
|
|
if lines and lines[0] == "---": # YAML frontmatter
|
||
|
|
for i in range(1, len(lines)):
|
||
|
|
if lines[i] in ("---", "..."):
|
||
|
|
start = i + 1
|
||
|
|
break
|
||
|
|
out = lines[:start]
|
||
|
|
stack = [] # open items as (input column, output level), outermost first
|
||
|
|
fence = None # (marker, owner item or None) while inside a fenced code block
|
||
|
|
for line in lines[start:]:
|
||
|
|
if fence:
|
||
|
|
marker, owner = fence
|
||
|
|
out.append(self.attach(line, owner) if owner else line)
|
||
|
|
stripped = line.strip()
|
||
|
|
if stripped.startswith(marker[0] * len(marker)) and not stripped.strip(marker[0]):
|
||
|
|
fence = None
|
||
|
|
continue
|
||
|
|
|
||
|
|
if not line.strip():
|
||
|
|
out.append("") # blank lines don't end a list
|
||
|
|
continue
|
||
|
|
|
||
|
|
c = self.col(line)
|
||
|
|
m = LIST_ITEM.match(line)
|
||
|
|
if m:
|
||
|
|
while stack and stack[-1][0] > c:
|
||
|
|
stack.pop()
|
||
|
|
if not stack or stack[-1][0] < c:
|
||
|
|
stack.append((c, len(stack)))
|
||
|
|
level = stack[-1][1]
|
||
|
|
new = self.unit * level + line[len(lead(line)):]
|
||
|
|
owner = (c, level)
|
||
|
|
elif c == 0:
|
||
|
|
stack.clear() # paragraph/heading ends the list
|
||
|
|
new, owner = line, None
|
||
|
|
else:
|
||
|
|
# Continuation text: belongs to the deepest item indented less than it.
|
||
|
|
owners = [s for s in stack if s[0] < c]
|
||
|
|
owner = owners[-1] if owners else None
|
||
|
|
new = self.attach(line, owner) if owner else line
|
||
|
|
out.append(new)
|
||
|
|
|
||
|
|
if fm := FENCE.match(line):
|
||
|
|
fence = (fm.group(1), owner)
|
||
|
|
return "\n".join(out)
|
||
|
|
|
||
|
|
def attach(self, line: str, owner) -> str:
|
||
|
|
"""Re-indent a non-item line so it keeps its offset from its (moved) owner item."""
|
||
|
|
if not line.strip():
|
||
|
|
return ""
|
||
|
|
orig_col, level = owner
|
||
|
|
extra = max(0, self.col(line) - orig_col)
|
||
|
|
return self.unit * level + " " * extra + line[len(lead(line)):]
|
||
|
|
|
||
|
|
|
||
|
|
def collect(target: Path, recursive: bool):
|
||
|
|
if target.is_file():
|
||
|
|
return [target]
|
||
|
|
if not target.is_dir():
|
||
|
|
sys.exit(f"Error: {target} is not a valid file or directory")
|
||
|
|
files = target.rglob("*.md") if recursive else target.glob("*.md")
|
||
|
|
return sorted(f for f in files if ".obsidian" not in f.parts and ".trash" not in f.parts)
|
||
|
|
|
||
|
|
|
||
|
|
def main():
|
||
|
|
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||
|
|
ap.add_argument("path", type=Path, help="file or directory to process")
|
||
|
|
ap.add_argument("-r", "--recursive", action="store_true", help="process directories recursively")
|
||
|
|
ap.add_argument("--dry-run", action="store_true", help="report changes without writing")
|
||
|
|
ap.add_argument("--diff", action="store_true", help="print a unified diff (implies --dry-run)")
|
||
|
|
ap.add_argument("--indent", default="tab",
|
||
|
|
help='output indent per level: "tab" (default, Obsidian\'s default) or a number of spaces')
|
||
|
|
ap.add_argument("--tab-width", type=int, default=4,
|
||
|
|
help="columns a tab is worth in the input (default 4, what the Importer assumes)")
|
||
|
|
a = ap.parse_args()
|
||
|
|
|
||
|
|
if a.indent == "tab":
|
||
|
|
unit = "\t"
|
||
|
|
elif a.indent.isdigit() and int(a.indent) > 0:
|
||
|
|
unit = " " * int(a.indent)
|
||
|
|
else:
|
||
|
|
sys.exit('--indent must be "tab" or a positive number of spaces')
|
||
|
|
dry = a.dry_run or a.diff
|
||
|
|
norm = Normalizer(unit, a.tab_width)
|
||
|
|
|
||
|
|
files = collect(a.path, a.recursive)
|
||
|
|
changed = 0
|
||
|
|
for f in files:
|
||
|
|
try:
|
||
|
|
text = f.read_text(encoding="utf-8")
|
||
|
|
except (OSError, UnicodeDecodeError) as e:
|
||
|
|
print(f" ERROR reading {f}: {e}")
|
||
|
|
continue
|
||
|
|
new = norm.normalize(text)
|
||
|
|
if new == text:
|
||
|
|
continue
|
||
|
|
changed += 1
|
||
|
|
n = sum(1 for x, y in zip(text.split("\n"), new.split("\n")) if x != y)
|
||
|
|
print(f" {'WOULD fix' if dry else 'Fixed'} {n} line(s) in {f}")
|
||
|
|
if a.diff:
|
||
|
|
sys.stdout.writelines(difflib.unified_diff(
|
||
|
|
text.splitlines(keepends=True), new.splitlines(keepends=True),
|
||
|
|
fromfile=f"{f} (before)", tofile=f"{f} (after)"))
|
||
|
|
if not dry:
|
||
|
|
f.write_text(new, encoding="utf-8")
|
||
|
|
print(f"\n{'Would modify' if dry else 'Modified'} {changed} of {len(files)} file(s)")
|
||
|
|
|
||
|
|
|
||
|
|
if __name__ == "__main__":
|
||
|
|
main()
|