# @+leo-ver=5-thin
# @+node:ekr.20170302123956.1: * @file ../doc/leoAttic.txt
# This is Leo's final resting place for dead code.
# New in Leo 6.7.5. The attic will contain only code retired in the present release.

# @@language python
# @@killbeautify
# @+all
# @+node:ekr.20240617085704.1: ** Permanent attic
# @+node:ekr.20260805111552.1: *3* 'insert-qt-icon' & helper
@cmd('insert-qt-icon')
def insertQtIcon(self, event: LeoKeyEvent | None = None) -> None:
    """
    Show a window previewing all standard Qt icons.
    Add each selected icon to c.p.h.
    """
   
    controller = self
    d = g.app.scriptDict
    key = 'insert_qt_icon_window'
    insert_qt_icon_window = d.get(key)
    if not insert_qt_icon_window:
        << define class QtPreviewWindow >>
        d[key] = insert_qt_icon_window = QtPreviewWindow()
    insert_qt_icon_window.show()

# @+node:ekr.20260805111828.1: *4* << define class QtPreviewWindow >>
from PyQt6.QtWidgets import (
    QGridLayout,
    QPushButton,
    QStyle,
    QWidget,
)

# Adapted from https://gist.github.com/ostr00000/30c9e732550baa0c13a73fd3320e7d55
class QtPreviewWindow(QWidget):
    def __init__(self):
        super().__init__()
        icon_names = sorted(
            [z for z in dir(QStyle.StandardPixmap) if z.startswith("SP_")]
        )
        layout = QGridLayout()
        for i, icon_name in enumerate(icon_names):
            button = QPushButton(icon_name)
            pixmap = getattr(QStyle.StandardPixmap, icon_name)
            if pixmap is None:
                g.trace(f"No pixmap for {icon_name=}")
                continue

            def callback(
                icon_name: str = icon_name, pixmap: QStyle.StandardPixmap = pixmap
            ) -> None:
                controller._addPixmapToNode(icon_name, pixmap)

            button.released.connect(callback)
            styled_icon = self.style().standardIcon(pixmap)  # type:ignore
            button.setIcon(styled_icon)
            layout.addWidget(button, int(i / 4), int(i % 4))
        self.setLayout(layout)

# @+node:ekr.20260805114313.1: *4* ec._addPixmapToNode (to do)
def _addPixmapToNode(self, icon_name: str, pixmap: QStyle.StandardPixmap) -> None:
    """Convert the given pixmap to an icon and add it to c.p.h."""
    c = self.c
    assert isinstance(pixmap, QStyle.StandardPixmap)
    g.trace(icon_name)

    # Convert the pixmap to a QIcon?.

    # iconList = self.getIconList(p.v)
    # iconList.extend(aList)
    # self.setIconList(p, iconList)

    c.p.setDirty()
    c.setChanged()
    c.redraw()

# @+node:ekr.20121128031949.12605: *3* class g.SherlockTracer
class SherlockTracer:
    """
    A stand-alone tracer class with many of Sherlock's features.

    This class should work in any environment containing the re, os and sys modules.

    The arguments in the pattern lists determine which functions get traced
    or which stats get printed. Each pattern starts with "+", "-", "+:" or
    "-:", followed by a regular expression::

    "+x"  Enables tracing (or stats) for all functions/methods whose name
          matches the regular expression x.
    "-x"  Disables tracing for functions/methods.
    "+:x" Enables tracing for all functions in the **file** whose name matches x.
    "-:x" Disables tracing for an entire file.

    Enabling and disabling depends on the order of arguments in the pattern
    list. Consider the arguments for the Rope trace::

    patterns=['+.*','+:.*',
        '-:.*\\lib\\.*','+:.*rope.*','-:.*leoGlobals.py',
        '-:.*worder.py','-:.*prefs.py','-:.*resources.py',])

    This enables tracing for everything, then disables tracing for all
    library modules, except for all rope modules. Finally, it disables the
    tracing for Rope's worder, prefs and resources modules.

    Being able to zero in on the code of interest can be a big help in
    studying other people's code. This is a non-invasive method: no tracing
    code needs to be inserted anywhere.

    Usage:

    g.SherlockTracer(patterns).run()
    """
    @others
# @+node:ekr.20121128031949.12602: *4* sherlock.__init__
def __init__(
    self,
    patterns: list[Any],
    indent: bool = True,
    show_args: bool = True,
    show_return: bool = True,
    verbose: bool = True,
) -> None:
    """SherlockTracer ctor."""
    self.bad_patterns: list[str] = []  # List of bad patterns.
    self.indent = indent  # True: indent calls and returns.
    self.contents_d: dict[str, list] = {}  # Keys are file names, values are file lines.
    self.n = 0  # The frame level on entry to run.
    self.stats: dict[str, dict] = {}  # Keys are full file names, values are dicts.
    self.patterns: list[Any] = None  # A list of regex patterns to match.
    self.pattern_stack: list[str] = []
    self.show_args = show_args  # True: show args for each function call.
    self.show_return = show_return  # True: show returns from each function.
    self.trace_lines = True  # True: trace lines in enabled functions.
    self.verbose = verbose  # True: print filename:func
    self.set_patterns(patterns)
    try:  # Don't assume g.app exists.
        from leo.core.leoQt import QtCore
        if QtCore:
            QtCore.pyqtRemoveInputHook()
    except Exception:
        pass
# @+node:ekr.20140326100337.16844: *4* sherlock.__call__
def __call__(self, frame: Any, event: Any, arg: Any) -> Any:
    """Exists so that self.dispatch can return self."""
    return self.dispatch(frame, event, arg)
# @+node:ekr.20140326100337.16846: *4* sherlock.bad_pattern
def bad_pattern(self, pattern: Any) -> None:
    """Report a bad Sherlock pattern."""
    if pattern not in self.bad_patterns:
        self.bad_patterns.append(pattern)
        print(f"\nignoring bad pattern: {pattern}\n")
# @+node:ekr.20140326100337.16847: *4* sherlock.check_pattern
def check_pattern(self, pattern: str) -> bool:
    """Give an error and return False for an invalid pattern."""
    try:
        for prefix in ('+:', '-:', '+', '-'):
            if pattern.startswith(prefix):
                re.match(pattern[len(prefix) :], 'xyzzy')
                return True
        self.bad_pattern(pattern)
        return False
    except Exception:
        self.bad_pattern(pattern)
        return False
# @+node:ekr.20121128031949.12609: *4* sherlock.dispatch
def dispatch(self, frame: Any, event: Any, arg: Any) -> Any:
    """The dispatch method."""
    if event == 'call':
        self.do_call(frame, arg)
    elif event == 'return' and self.show_return:
        self.do_return(frame, arg)
    elif event == 'line' and self.trace_lines:
        self.do_line(frame, arg)
    # Queue the SherlockTracer instance again.
    return self
# @+node:ekr.20121128031949.12603: *4* sherlock.do_call & helper
def do_call(self, frame: Any, unused_arg: Any) -> None:
    """Trace through a function call."""
    frame1 = frame
    code = frame.f_code
    file_name = code.co_filename
    locals_ = frame.f_locals
    function_name = code.co_name
    try:
        full_name = self.get_full_name(locals_, function_name)
    except Exception:
        full_name = function_name
    if not self.is_enabled(file_name, full_name, self.patterns):
        # 2020/09/09: Don't touch, for example, __ methods.
        return
    n = 0  # The number of callers of this def.
    while frame:
        frame = frame.f_back
        n += 1
    indent = ' ' * max(0, n - self.n) if self.indent else ''
    path = f"{os.path.basename(file_name):>20}" if self.verbose else ''
    leadin = '+' if self.show_return else ''
    args_list = self.get_args(frame1)
    if self.show_args and args_list:
        args_s = ','.join(args_list)
        args_s2 = f"({args_s})"
        if len(args_s2) > 100:
            print(f"{path}:{indent}{leadin}{full_name}")
            g.printObj(args_list, indent=len(indent) + 22)
        else:
            print(f"{path}:{indent}{leadin}{full_name}{args_s2}")
    else:
        print(f"{path}:{indent}{leadin}{full_name}")
    # Always update stats.
    d = self.stats.get(file_name, {})
    d[full_name] = 1 + d.get(full_name, 0)
    self.stats[file_name] = d
# @+node:ekr.20130111185820.10194: *5* sherlock.get_args
def get_args(self, frame: Any) -> list[str]:
    """Return a list of string "name=val" for each arg in the function call."""
    code = frame.f_code
    locals_ = frame.f_locals
    name = code.co_name
    n = code.co_argcount
    if code.co_flags & 4:
        n = n + 1
    if code.co_flags & 8:
        n = n + 1
    result = []
    for i in range(n):
        name = code.co_varnames[i]
        if name != 'self':
            arg = locals_.get(name, '*undefined*')
            if arg:
                if isinstance(arg, (list, tuple)):
                    val_s = ','.join([self.show(z) for z in arg if self.show(z)])
                    val = f"[{val_s}]"
                elif isinstance(arg, str):
                    val = arg
                else:
                    val = self.show(arg)
                if val:
                    result.append(f"{name}={val}")
    return result
# @+node:ekr.20140402060647.16845: *4* sherlock.do_line (not used)
bad_fns: list[str] = []

def do_line(self, frame: Any, arg: Any) -> None:
    """print each line of enabled functions."""
    if 1:
        return
    code = frame.f_code
    file_name = code.co_filename
    locals_ = frame.f_locals
    name = code.co_name
    full_name = self.get_full_name(locals_, name)
    if not self.is_enabled(file_name, full_name, self.patterns):
        return
    n = frame.f_lineno - 1  # Apparently, the first line is line 1.
    d = self.contents_d
    lines = d.get(file_name)
    if not lines:
        print(file_name)
        try:
            with open(file_name) as f:
                s = f.read()
        except Exception:
            if file_name not in self.bad_fns:
                self.bad_fns.append(file_name)
                print(f"open({file_name}) failed")
            return
        lines = g.splitLines(s)
        d[file_name] = lines
    line = lines[n].rstrip() if n < len(lines) else '<EOF>'
    if 0:
        print(f"{name:3} {line}")
    else:
        print(f"{g.shortFileName(file_name)} {n} {full_name} {line}")
# @+node:ekr.20130109154743.10172: *4* sherlock.do_return & helper
def do_return(self, frame: Any, arg: Any) -> None:  # Arg *is* used below.
    """Trace a return statement."""
    code = frame.f_code
    fn = code.co_filename
    locals_ = frame.f_locals
    name = code.co_name
    self.full_name = self.get_full_name(locals_, name)
    if not self.is_enabled(fn, self.full_name, self.patterns):
        return
    n = 0
    while frame:
        frame = frame.f_back
        n += 1
    path = f"{os.path.basename(fn):>20}" if self.verbose else ''
    if name and name == '__init__':
        try:
            ret1 = locals_ and locals_.get('self', None)
            self.put_ret(ret1, n, path)
        except NameError:
            self.put_ret(f"<{ret1.__class__.__name__}>", n, path)
    else:
        self.put_ret(arg, n, path)
# @+node:ekr.20220605141445.1: *5* sherlock.put_ret
def put_ret(self, arg: Any, n: int, path: str) -> None:
    """Print arg, the value returned by a "return" statement."""
    indent = ' ' * max(0, n - self.n + 1) if self.indent else ''
    try:
        if isinstance(arg, types.GeneratorType):
            ret = '<generator>'
        elif isinstance(arg, (tuple, list)):
            ret_s = ','.join([self.show(z) for z in arg])
            if len(ret_s) > 40:
                g.printObj(arg, indent=len(indent))
                ret = ''
            else:
                ret = f"[{ret_s}]"
        elif arg:
            ret = self.show(arg)
            if len(ret) > 100:
                ret = f"\n    {ret}"
        else:
            ret = '' if arg is None else repr(arg)
        print(f"{path}:{indent}-{self.full_name} -> {ret}")
    except Exception:
        exctype, value = sys.exc_info()[:2]
        try:  # Be extra careful.
            arg_s = f"arg: {arg!r}"
        except Exception:
            arg_s = ''  # arg.__class__.__name__
        print(
            f"{path}:{indent}-{self.full_name} -> "
            f"{exctype.__name__}, {value} {arg_s}"
        )
# @+node:ekr.20121128111829.12185: *4* sherlock.fn_is_enabled
def fn_is_enabled(self, func: Any, patterns: list[str]) -> bool:
    """Return True if tracing for the given function is enabled."""
    if func in self.ignored_functions:
        return False

    def ignore_function() -> None:
        if func not in self.ignored_functions:
            self.ignored_functions.append(func)
            print(f"Ignore function: {func}")
    #
    # New in Leo 6.3. Never trace dangerous functions.
    table = (
        '_deepcopy.*',
        # Unicode primitives.
        'encode\b', 'decode\b',
        # System functions
        '.*__next\b',
        '<frozen>', '<genexpr>', '<listcomp>',
        # '<decorator-gen-.*>',
        'get\b',
        # String primitives.
        'append\b', 'split\b', 'join\b',
        # File primitives...
        'access_check\b', 'expanduser\b', 'exists\b', 'find_spec\b',
        'abspath\b', 'normcase\b', 'normpath\b', 'splitdrive\b',
    )
    g.trace('=====', func)
    for z in table:
        if re.match(z, func):
            ignore_function()
            return False
    #
    # Legacy code.
    try:
        enabled, pattern = False, None
        for pattern in patterns:
            if pattern.startswith('+:'):
                if re.match(pattern[2:], func):
                    enabled = True
            elif pattern.startswith('-:'):
                if re.match(pattern[2:], func):
                    enabled = False
        return enabled
    except Exception:
        self.bad_pattern(pattern)
        return False
# @+node:ekr.20130112093655.10195: *4* sherlock.get_full_name
def get_full_name(self, locals_: Any, name: str) -> str:
    """Return class_name::name if possible."""
    full_name = name
    try:
        user_self = locals_ and locals_.get('self', None)
        if user_self:
            full_name = user_self.__class__.__name__ + '::' + name
    except Exception:
        pass
    return full_name
# @+node:ekr.20121128111829.12183: *4* sherlock.is_enabled
ignored_files: list[str] = []  # List of files.
ignored_functions: list[str] = []  # List of files.

def is_enabled(
    self,
    file_name: str,
    function_name: str,
    patterns: list[str] = None,
) -> bool:
    """Return True if tracing for function_name in the given file is enabled."""
    #
    # New in Leo 6.3. Never trace through some files.
    if not os:
        return False  # Shutting down.
    base_name = os.path.basename(file_name)
    if base_name in self.ignored_files:
        return False

    def ignore_file() -> None:
        if base_name not in self.ignored_files:
            self.ignored_files.append(base_name)

    def ignore_function() -> None:
        if function_name not in self.ignored_functions:
            self.ignored_functions.append(function_name)

    if f"{os.sep}lib{os.sep}" in file_name:
        ignore_file()
        return False
    if base_name.startswith('<') and base_name.endswith('>'):
        ignore_file()
        return False
    #
    # New in Leo 6.3. Never trace dangerous functions.
    table = (
        '_deepcopy.*',
        # Unicode primitives.
        'encode\b', 'decode\b',
        # System functions
        '.*__next\b',
        '<frozen>', '<genexpr>', '<listcomp>',
        # '<decorator-gen-.*>',
        'get\b',
        # String primitives.
        'append\b', 'split\b', 'join\b',
        # File primitives...
        'access_check\b', 'expanduser\b', 'exists\b', 'find_spec\b',
        'abspath\b', 'normcase\b', 'normpath\b', 'splitdrive\b',
    )
    for z in table:
        if re.match(z, function_name):
            ignore_function()
            return False
    #
    # Legacy code.
    enabled = False
    if patterns is None:
        patterns = self.patterns
    for pattern in patterns:
        try:
            if pattern.startswith('+:'):
                if re.match(pattern[2:], file_name):
                    enabled = True
            elif pattern.startswith('-:'):
                if re.match(pattern[2:], file_name):
                    enabled = False
            elif pattern.startswith('+'):
                if re.match(pattern[1:], function_name):
                    enabled = True
            elif pattern.startswith('-'):
                if re.match(pattern[1:], function_name):
                    enabled = False
            else:
                self.bad_pattern(pattern)
        except Exception:
            self.bad_pattern(pattern)
    return enabled
# @+node:ekr.20121128111829.12182: *4* sherlock.print_stats
def print_stats(self, patterns: list[str] = None) -> None:
    """Print all accumulated statisitics."""
    print('\nSherlock statistics...')
    if not patterns:
        patterns = ['+.*', '+:.*',]
    for fn in sorted(self.stats.keys()):
        d = self.stats.get(fn)
        if self.fn_is_enabled(fn, patterns):
            result = sorted(d.keys())  # type:ignore
        else:
            result = [key for key in sorted(d.keys())  # type:ignore
                if self.is_enabled(fn, key, patterns)]
        if result:
            print('')
            fn = fn.replace('\\', '/')
            parts = fn.split('/')
            print('/'.join(parts[-2:]))
            for key in result:
                print(f"{d.get(key):4} {key}")
# @+node:ekr.20121128031949.12614: *4* sherlock.run
# Modified from pdb.Pdb.set_trace.

def run(self, frame: Any = None) -> None:
    """Trace from the given frame or the caller's frame."""
    print("SherlockTracer.run:patterns:\n%s" % '\n'.join(self.patterns))
    if frame is None:
        frame = sys._getframe().f_back
    # Compute self.n, the number of frames to ignore.
    self.n = 0
    while frame:
        frame = frame.f_back
        self.n += 1
    # Pass self to sys.settrace to give easy access to all methods.
    sys.settrace(self)
# @+node:ekr.20140322090829.16834: *4* sherlock.push & pop
def push(self, patterns: list[str]) -> None:
    """Push the old patterns and set the new."""
    self.pattern_stack.append(self.patterns)  # type:ignore
    self.set_patterns(patterns)
    print(f"SherlockTracer.push: {self.patterns}")

def pop(self) -> None:
    """Restore the pushed patterns."""
    if self.pattern_stack:
        self.patterns = self.pattern_stack.pop()  # type:ignore
        print(f"SherlockTracer.pop: {self.patterns}")
    else:
        print('SherlockTracer.pop: pattern stack underflow')
# @+node:ekr.20140326100337.16845: *4* sherlock.set_patterns
def set_patterns(self, patterns: list[str]) -> None:
    """Set the patterns in effect."""
    self.patterns = [z for z in patterns if self.check_pattern(z)]
# @+node:ekr.20140322090829.16831: *4* sherlock.show
def show(self, item: Any) -> str:
    """return the best representation of item."""
    if not item:
        return repr(item)
    if isinstance(item, dict):
        return 'dict'
    if isinstance(item, str):
        s = repr(item)
        if len(s) <= 20:
            return s
        return s[:17] + '...'
    s = repr(item)
    # A Hack for mypy:
    if s.startswith("<object object"):
        s = "_dummy"
    return s
# @+node:ekr.20121128093229.12616: *4* sherlock.stop
def stop(self) -> None:
    """Stop all tracing."""
    sys.settrace(None)
# @+node:ekr.20181202062518.1: *3* leoFastRedraw.py
"""
Gui-independent fast-redraw code.

For an explanation, see this thread:
https://groups.google.com/forum/#!topic/leo-editor/hpHyHU2sWtM
"""
import difflib
import re
import time
from leo.core import leoGlobals as g

class FastRedraw:
    @others

@language python
@tabwidth -4
@pagewidth 70
# @+node:ekr.20181202060924.4: *4* LeoGui.dump_diff_op_codes
def dump_diff_op_codes(self, a, b, op_codes):
    """Dump the opcodes returned by difflib.SequenceMatcher."""

    def summarize(aList):
        pat = re.compile(r'.*:.*:(.*)')
        return ', '.join([pat.match(z).group(1) for z in aList])

    for tag, i1, i2, j1, j2 in op_codes:
        if tag == 'equal':
            print(f"{tag:7} at {i1}:{i2} (both) ==> {summarize(b[j1:j2])!r}")
        elif tag == 'insert':
            print(f"{tag:7} at {i1}:{i2} (b)    ==> {summarize(b[j1:j2])!r}")
        elif tag == 'delete':
            print(f"{tag:7} at {i1}:{i2} (a)    ==> {summarize(a[i1:i2])!r}")
        elif tag == 'replace':
            print(f"{tag:7} at {i1}:{i2} (a)    ==> {summarize(a[i1:i2])!r}")
            print(f"{tag:7} at {i1}:{i2} (b)    ==> {summarize(b[j1:j2])!r}")
        else:
            print('unknown tag')
# @+node:ekr.20181202060924.5: *4* LeoGui.dump_opcodes
def dump_opcodes(self, opcodes):
    """Dump the opcodes returned by app.peep_hole and app.make_redraw_list."""
    for z in opcodes:
        kind = z[0]
        if kind == 'replace':
            kind, i1, gnxs1, gnxs2 = z
            print(kind, i1)
            print("  a: [%s]" % ',\n    '.join(gnxs1))
            print("  b: [%s]" % ',\n    '.join(gnxs2))
        elif kind in ('delete', 'insert'):
            kind, i1, gnxs = z
            print(kind, i1)
            print("  [%s]" % ',\n    '.join(gnxs))
        else:
            print(z)
# @+node:ekr.20181202060924.2: *4* LeoGui.flatten_outline
def flatten_outline(self, c):
    """Return a flat list of strings "level:gnx" for all *visible* positions."""
    trace = False and not g.unitTesting
    t1 = time.process_time()
    aList: list[str] = []
    for p in c.rootPosition().self_and_siblings():
        self.extend_flattened_outline(aList, p)
    if trace:
        t2 = time.process_time()
        print(f"app.flatten_outline: {len(aList)} entries {t2 - t1:6.4f} sec.")
    return aList

def extend_flattened_outline(self, aList, p):
    """Add p and all p's visible descendants to aList."""
    # Padding the fields causes problems later.
    aList.append(f"{p.level()}:{p.gnx}:{p.h}\n")
    if p.isExpanded():
        for child in p.children():
            self.extend_flattened_outline(aList, child)
# @+node:ekr.20181202060924.3: *4* LeoGui.make_redraw_list
def make_redraw_list(self, a, b):
    """
    Diff the a (old) and b (new) outline lists.
    Then optimize the diffs to create a redraw instruction list.
    """
    trace = False and not g.unitTesting
    if a == b:
        return []

    def gnxs(aList):
        """Return the gnx list. Do not try to remove this!"""
        return [z.strip() for z in aList]
    @others # Define local helpers
    d = difflib.SequenceMatcher(None, a, b)
    op_codes = list(d.get_opcodes())
    # dump_diff_op_codes(a, b, op_codes)
    #
    # Generate the instruction list, and verify the result.
    opcodes, result = [], []
    for tag, i1, i2, j1, j2 in op_codes:
        if tag == 'insert':
            opcodes.append(['insert', i1, gnxs(b[j1:j2])])
        elif tag == 'delete':
            opcodes.append(['delete', i1, gnxs(a[i1:i2])])
        elif tag == 'replace':
            opcodes.append(['replace', i1, gnxs(a[i1:i2]), gnxs(b[j1:j2])])
        result.extend(b[j1:j2])
    assert b == result, (a, b)
    #
    # Run the peephole.
    opcodes = self.peep_hole(opcodes)
    if trace:
        print('app.make_redraw_list: opcodes after peephole...')
        self.dump_opcodes(opcodes)
    return opcodes
# @+node:ekr.20181202060924.6: *4* LeoGui.peep_hole
def peep_hole(self, opcodes):
    """Scan the list of opcodes, merging adjacent op-codes."""
    i, result = 0, []
    while i < len(opcodes):
        op0 = opcodes[i]
        if i == len(opcodes) - 1:
            result.append(op0)
            break
        op1 = opcodes[i + 1]
        kind0, kind1 = op0[0], op1[0]
        # Merge adjacent insert/delete opcodes with the same gnx.
        if (
            kind0 == 'insert' and kind1 == 'delete' or
            kind0 == 'delete' and kind1 == 'insert'
        ):
            kind0, index0, gnxs0 = op0
            kind1, index1, gnxs1 = op1
            if gnxs0[0] == gnxs1[0]:
                result.append(['move', index0, index1, gnxs0, gnxs1])
                i += 2  # Don't scan either op again!
                break
        # The default is to retain the opcode.
        result.append(op0)
        i += 1
    return result
# @+node:ekr.20261109151859.1: *3* TypingBead.must_change_word (deleted)
def begins_new_word(self, w: QTextMixin) -> bool:
    """
    Return True if the incoming character begins a new word.
    This method handles non-backspace characters in an intuitive manner.
    
    Alas, handling backspace or delete can *not* be done intuitively.
    For details, the discussion in PR #5044.
    https://github.com/leo-editor/leo-editor/pull/5044
    """
    s = w.getAllText()
    w_ins = w.getInsertPoint()

    # Get the line per g.get_line.
    i = g.find_line_start(s, w_ins)
    j = g.skip_to_end_of_line(s, w_ins)

    # Compute head, ch, tail.
    head = s[i : max(0, w_ins - 1)]
    ch = s[max(0, w_ins - 1) : w_ins]
    tail = s[w_ins + 1 : j]

    # Compute the result!
    prev_line = self.new_lines.rstrip()
    is_bs = len(s) < len(prev_line)
    result = (
        False if ch in ' \t'
        else False if is_bs  # A quirp: backspace isn't undoable.
        else True if head.endswith((' ', '\t'))
        else True if tail.startswith((' ', '\t'))
        else False
    )  # fmt: skip
    # g.trace(f"bs? {int(is_bs)} new word?: {int(result)}")
    return result

# @+node:ekr.20260423040149.1: *3* TestQtGui.test_bug_4626
def test_bug_4626(self):
    # https://github.com/leo-editor/leo-editor/issues/4626
    self.skipTest('Can hang depending clipboard contents')
    c = self.c
    gui = g.app.gui
    k = c.k
    log = c.frame.log
    qtApp = gui.qtApp
    old_log = g.app.log
    old_clipboard_contents = gui.getTextFromClipboard()
    try:
        # Part 1: Create the 'Completion' tab, and copy it's contents to the clipboard.
        # Force g.es to print to the log.
        event = LeoKeyEvent(c, char='a')
        k.fullCommand(event=event)
        k.extendLabel('a')
        g.app.log = log
        k.doTabCompletion(['a', 'ab', 'abc'])
        wrapper = log.logCtrl
        s = wrapper.getAllText()
        dedent_s = self.prep(s)
        assert dedent_s == 'a\nab\nabc\n', repr(s)
        wrapper.selectAllText()
        # Part 2: Test copyText directly.
        event2 = LeoKeyEvent(c, w=wrapper)
        c.frame.copyText(event2)
        s2 = gui.getTextFromClipboard()
        k.keyboardQuit()
        assert s2 == s, (repr(s), repr(s2))
        # Part 3: Test Ctrl-C in all text widgets.
        << Construct two Qt events >>

        def oops(why, w):
            print(f"{why} {id(w)} {gui.widget_name(w)} {w.__class__.__name__}")

        wrapper_table = (
            # (c.frame.body, c.frame.body.widget),  # Fails.
            (c.frame.log, c.frame.log.logCtrl.widget),  # Good.
        )
        for wrapper, widget in wrapper_table:
            # g.trace(f"widget: {id(widget)} {gui.widget_name(widget)} {widget.__class__.__name__}")
            if hasattr(wrapper, 'ev_filter'):
                filter_ = wrapper.ev_filter
                d = filter_.key_count_dict = {}
                # Test actual Qt Key events.
                for key_event in (key_press_event, key_release_event):
                    qtApp.sendEvent(widget, key_event)
                    if d.get(id(wrapper)) == 0:
                        oops('Fail 1', wrapper)
            else:
                oops('Fail 2', wrapper)
    finally:
        gui.replaceClipboardWith(old_clipboard_contents)
        g.app.log = old_log

# @+node:ekr.20260426165432.1: *4* << Construct two Qt events >>
c_key = QtCore.Qt.Key.Key_C
ctrl_mod = QtCore.Qt.KeyboardModifier.ControlModifier
key_press_t = QtCore.QEvent.Type.KeyPress
key_release_t = QtCore.QEvent.Type.KeyRelease
key_press_event = QtGui.QKeyEvent(key_press_t, c_key, ctrl_mod, '')
key_release_event = QtGui.QKeyEvent(key_release_t, c_key, ctrl_mod, '')
# @+node:ekr.20260820040558.1: ** Temporary attic
# @+node:ekr.20261109032204.1: *3* --- deleted gui code
# @+node:ekr.20110605121601.18503: *4* LeoQtGui.runScrolledMessageDialog (deleted)
def runScrolledMessageDialog(
    self,
    short_title: str = '',
    title: str = 'Message',
    label: str = '',
    msg: str = '',
    c: Cmdr | None = None,
    **keys: Any,
) -> None:
    if g.unitTesting:
        return None

    def send() -> Any:
        return g.doHook(
            'scrolledMessage',
            short_title=short_title,
            title=title,
            label=label,
            msg=msg,
            c=c,
            **keys,
        )

    if not c or not c.exists:
        << no c error>>
    else:
        if retval := send():
            return retval
        << load viewrendered plugin >>
        if retval := send():
            return retval
        << no dialog error >>
    << emergency fallback >>

# @+node:ekr.20110605121601.18504: *5* << no c error>>
g.es_print_error(
    '%s\n%s\n\t%s'
    % (
        "The qt plugin requires calls to g.app.gui.scrolledMessageDialog to include 'c'",
        "as a keyword argument",
        g.callers(),
    )
)
# @+node:ekr.20110605121601.18505: *5* << load viewrendered plugin >>
pc = g.app.pluginsController
# Load viewrendered (and call vr.onCreate) *only* if not already loaded.
if not pc.isLoaded('viewrendered.py') and not pc.isLoaded('viewrendered3.py'):
    if pc.loadOnePlugin('viewrendered.py'):
        g.blue('viewrendered plugin loaded.')
# @+node:ekr.20110605121601.18506: *5* << no dialog error >>
g.es_print_error(f'No handler for the "scrolledMessage" hook.\n\t{g.callers()}')
# @+node:ekr.20110605121601.18507: *5* << emergency fallback >>
dialog = QtWidgets.QMessageBox(None)
# That is, not a fixed size dialog.
dialog.setWindowFlags(WindowType.Dialog)
dialog.setWindowTitle(title)
if msg:
    dialog.setText(msg)
dialog.setIcon(Icon.Information)
dialog.addButton('Ok', ButtonRole.YesRole)
try:
    if c:
        c.in_qt_dialog = True
    dialog.exec()
finally:
    if c:
        c.in_qt_dialog = False
# @+node:ekr.20261109032123.1: *3* --- deleted unit tests
# @+node:ekr.20230714143451.1: *4* TestEditFileCommands.test_diff_two_branches
def test_diff_two_branches(self):
    c = self.c
    u = c.undoer
    x = GitDiffController(c=c)

    # Setup the outline.
    root = c.rootPosition()
    root.h = '@file leoGlobals.py'
    root.deleteAllChildren()
    while root.hasNext():
        root.next().doDelete()
    c.selectPosition(root)

    # Run the test in the leo-editor directory (the parent of the .git directory).
    new_dir = g.finalize_join(g.app.loadDir, '..', '..')
    old_dir = os.getcwd()
    os.chdir(new_dir)
    try:
        # Run the command, suppressing output from git.
        expected_last_headline = 'git-diff-branches 6.8.10 6.8.10.dev1'
        try:
            sys.stdout = open(os.devnull, 'w')
            x.diff_two_branches(
                branch1='main',
                branch2='devel',
                fn='leo/core/leoGlobals.py',  # Don't use backslashes.
            )
        finally:
            sys.stdout = sys.__stdout__
        # #3497: Silently skip the test if nothing has changed.
        if c.lastTopLevel() == root:
            return
        self.assertEqual(c.lastTopLevel().h, expected_last_headline)
        u.undo()
        self.assertEqual(c.lastTopLevel(), root)
        u.redo()
        self.assertEqual(c.lastTopLevel().h, expected_last_headline)
    finally:
        os.chdir(old_dir)

# @+node:ekr.20261018053649.1: *4* --- deleted dual mode unit tests
# An interesting test pattern.
# @+node:ekr.20261014103254.30: *5* TestContextUndo.test_dual_mode_harness_sets_and_restores_switch
def test_dual_mode_harness_sets_and_restores_switch(self):
    seen = []
    old = g.new_undoers

    def exercise(test):
        seen.append(g.new_undoers)
        test.assertIsNotNone(test.c)

    self.run_undo_test(exercise)
    self.assertEqual(seen, [True, False])
    self.assertEqual(g.new_undoers, old)

# @+node:ekr.20261009094252.1: *5*  LeoUnitTest.run_undo_test
def run_undo_test(self, undo_test: Callable) -> None:

    class UndoTester(LeoUnitTest):
        """A class that runs unit test with g.new_undoers = True and False."""
        def __init__(self, method_name: str, undo_test: Callable, new_undoers: bool) -> None:
            super().__init__(method_name)
            self.g_new_undoers = new_undoers
            self.undo_test = undo_test
            test_name = self.undo_test.__name__
            if test_name.startswith('test'):
                message = f"{test_name} should *not* start with 'test'. {g.caller()}"
                g.print_unique_message(message)

        def test_wrapper(self) -> None:
            old = g.new_undoers
            try:
                g.new_undoers = self.g_new_undoers
                self.undo_test(self)
            finally:
                g.new_undoers = old

        def __repr__(self) -> str:
            return f"UndoTester: {self.undo_test.__name__} {self.g_new_undoers=}"

    suite = unittest.TestSuite(
        [
            UndoTester('test_wrapper', undo_test, True),
            UndoTester('test_wrapper', undo_test, False),
        ]
    )
    result = unittest.TestResult()
    suite.run(result)
    if not result.wasSuccessful():
        errs = result.failures + result.errors
        n = len(errs)
        errors = [f"Error {test!r}: {err}" for test, err in errs]
        self.fail(f"{n} Error{g.plural(n)}:\n\n{''.join(errors)}")

# @+node:ekr.20261109032446.1: *4* --- deleted unit test re undo
# @+node:ekr.20261014103254.28: *5* TestContextUndo.test_typing_granularity_and_save_boundary
def test_typing_granularity_and_save_boundary(self):
    c = self.c
    p = c.p
    u = c.undoer

    def _run_test_typing_granularity_and_save_boundary(granularity):
        p.b = ''
        u.clearUndoState()
        c.clearChanged()
        if hasattr(u, 'granularity'):
            u.granularity = granularity
        for old, new in (('', 'a'), ('a', 'ab')):
            w = c.frame.body.wrapper
            w.setAllText(new)
            oldSel = (len(old), len(old))
            newSel = (len(new), len(new))
            w.setSelectionRange(*newSel)
            u.type_text(p, old, new, newInsert=len(new), oldSel=oldSel, newSel=newSel)
        self.assertEqual(len(u.beads), 2 if granularity == 'char' else 1)
        u.undo()
        self.assertEqual(p.b, 'a' if granularity == 'char' else '')
        u.redo()
        c.clearChanged()
        w.setAllText('abc')
        w.setSelectionRange(3, 3)
        u.type_text(p, 'ab', 'abc', newInsert=3, oldSel=(2, 2), newSel=(3, 3))
        self.assertEqual(len(u.beads), 3 if granularity == 'char' else 2)
        u.undo()
        self.assertEqual(p.b, 'ab')
        self.assertTrue(c.changed)

    if hasattr(u, 'granularity'):
        for granularity in ('char', 'line', 'word', 'node'):
            with self.subTest(granularity=granularity):
                _run_test_typing_granularity_and_save_boundary(granularity)
    else:
        _run_test_typing_granularity_and_save_boundary('word')

# @+node:ekr.20261014103254.29: *5* TestContextUndo.test_typing_word_boundary
def test_typing_word_boundary(self):
    c = self.c
    p = c.p
    u = c.undoer
    p.b = ''
    for new in ('a', 'ab', 'ab ', 'ab c', 'ab cd'):
        old = p.b
        w = c.frame.body.wrapper
        w.setAllText(new)
        w.setSelectionRange(len(new), len(new))
        oldSel = (len(old), len(old))
        newSel = (len(new), len(new))
        newInsert = len(new)
        u.type_text(p, oldText=old, oldSel=oldSel, w=w)
    self.assertEqual(len(u.beads), 2)
    u.undo()
    self.assertEqual(p.b, 'ab')
    u.undo()
    self.assertEqual(p.b, '')
    u.redo()
    u.redo()
    self.assertEqual(p.b, 'ab cd')

# @+node:ekr.20261014103254.27: *5* TestContextUndo.xxx_test_typing_preserves_text_mark_and_newlines
def xxx_test_typing_preserves_text_mark_and_newlines(self):
    c = self.c
    p = c.p
    u = c.undoer
    for marked in (False, True):
        for old, new in (('', '\n'), ('a\n\n', 'a\nb\n\n'), ('a\n', ''), ('a\nb', 'a\nb\n')):
            with self.subTest(marked=marked, old=old, new=new):
                u.clearUndoState()
                p.b = old
                p.setMarked() if marked else p.clearMarked()
                w = c.frame.body.wrapper
                w.setAllText(new)
                w.setSelectionRange(len(new), len(new))
                oldSel = (len(old), len(old))
                u.type_text(p, oldSel=oldSel, oldText=old, w=w)
                self.assertIsInstance(u.beads[-1], TypingBead)
                self.cycles(
                    lambda old=old: self.assertEqual(p.b, old),
                    lambda new=new: self.assertEqual(p.b, new),
                )
                self.assertEqual(p.isMarked(), marked)

# @+node:ekr.20210905064816.5: *4* test_dynamicExpandHelper
def test_dynamicExpandHelper(self):
    c = self.c
    # A totally wimpy test.
    # And it somehow prints a newline to the console.
    if 0:
        c.abbrevCommands.dynamicExpandHelper(event=None, prefix='', aList=[], w=None)

# @-all
# @@nosearch
# @-leo
