# Klammertext_indent.py
#
# EXPERIMENTAL.  Reindentation for Klammertext files — the Sublime Text
# counterpart of doc/edit/emacs/klammertext-indent.el.  This file is a
# separate unit: delete it (or move it out of the package folder) to disable
# indentation entirely; the rest of the Klammertext package is unaffected.
#
# Command name (for keymaps / the command palette): klammertext_reindent
# Keybinding: Ctrl+Alt+I (in Default.sublime-keymap), scoped to Klammertext
# files.  It reindents the line(s) touched by the selection — the current
# line when there is just a caret.  Nothing reformats automatically (no
# on-Enter auto-indent), because whitespace is content in Klammertext.
#
# The algorithm, the indentation convention, and the policy lists
# (TRANSPARENT_KLAMMERS, CODE_KLAMMERS, INDENT_OFFSET, ...) live in the
# shared core, doc/edit/shared/klammertext_edit.py — the single Python
# implementation used by the Sublime, Vim, and VS Code integrations and by
# the language server.  This file is only the Sublime command wrapper.
#
# The shared core is located next to this file (a vendored copy — the
# installed-package layout produced by doc/make_editing_zip.sh), or in
# ../shared (the repository layout), or under $KLAMMERTEXT_HOME.

import os
import sys

try:
    import sublime
    import sublime_plugin
    _IN_SUBLIME = True
except ImportError:          # standalone import outside Sublime Text
    _IN_SUBLIME = False


def _import_shared():
    here = os.path.dirname(os.path.abspath(__file__))
    candidates = [here, os.path.join(os.path.dirname(here), 'shared')]
    kh = os.environ.get('KLAMMERTEXT_HOME')
    if kh:
        candidates.append(os.path.join(kh, 'doc', 'edit', 'shared'))
    for d in candidates:
        if os.path.isfile(os.path.join(d, 'klammertext_edit.py')):
            if d not in sys.path:
                sys.path.insert(0, d)
            break
    import klammertext_edit
    return klammertext_edit


KE = _import_shared()


if _IN_SUBLIME:

    class KlammertextReindentCommand(sublime_plugin.TextCommand):
        """Reindent the line(s) touched by the selection per the Klammertext
        convention.  Sublime equivalent of TAB in the Emacs mode (which has no
        Sublime analogue: TAB there always inserts).  Bound to Ctrl+Alt+I."""

        def run(self, edit):
            view = self.view
            s = view.substr(sublime.Region(0, view.size()))
            bols = []
            seen = set()
            for region in view.sel():
                for line in view.lines(region):
                    if line.a not in seen:
                        seen.add(line.a)
                        bols.append(line.a)
            # Compute all edits from the original text, then apply from the
            # bottom up so earlier offsets stay valid.
            for a, b, new in sorted(KE.reindent_lines(s, bols), reverse=True):
                view.replace(edit, sublime.Region(a, b), new)

        def is_enabled(self):
            return self.view.match_selector(0, "text.klammertext")
