Search code examples
sublimetext3sublime-text-plugin

Is there a way to set the fold symbol in sublimetext read only?


If I delete the fold symbol in sublimetext the whole folded text is deleted? I would prefer that the fold symbol unfolds before you can delete it (like in vim). enter image description here


Solution

  • If I understand you want to have the behavior, that it automatically unfolds if you are behind a fold and press backspace. This is easy to archive (in version 3125+) you just need to add a context and a command.

    Create a plugin via Tools >> Developer >> New Plugin..., paste, and save:

    import sublime
    import sublime_plugin
    
    
    class UnfoldBeforeCommand(sublime_plugin.TextCommand):
        def run(self, edit):
            view = self.view
            for sel in view.sel():
                # fold the position before the selection
                view.unfold(sublime.Region(sel.b - 1))
    
    
    class IsBehindFoldContext(sublime_plugin.EventListener):
        def on_query_context(self, view, key, operator, operand, match_all):
            if key != "is_behind_fold":
                return
    
            quantor = all if match_all else any
    
            result = quantor(
                view.is_folded(sel) and view.is_folded(sublime.Region(sel.b - 1))
                for sel in view.sel()
            )
    
            if operator == sublime.OP_EQUAL:
                result = result == operand
            elif operator == sublime.OP_NOT_EQUAL:
                result = result != operand
            else:
                raise Exception("Operator type not supported")
    
            return result
    

    add this to your keymap:

    {
        "keys": ["backspace"],
        "command": "unfold_before",
        "context":
        [
            { "key": "selection_empty" },
            { "key": "is_behind_fold", "operator": "equal", "operand": true }
        ]
    }
    

    Now you should be fine.