Sublime Forum

Variable substitution ignoring `g` flag?

#1

Hi,

I’m trying to bind a simple fixed find&replace to a keyboard shortcut, but it seems complicated. From what I could read, this is not supported natively, this topic Macros don't record Find/Replace? gives 2 solutions not requiring an external plugin (RegReplace ; why this simple task should require this?), but I have an issue with both of them.

The find_replace (Macros don't record Find/Replace?) and find_replace_selected (Macros don't record Find/Replace?) commands are nice but they don’t support variables in substitution (and by browsing the API https://www.sublimetext.com/docs/api_reference.html#sublime.View, it doesn’t seems to be supported?).

The simple snippet with variable substitution (https://www.sublimetext.com/docs/completions.html#variable-substitution) method found at Macros don't record Find/Replace? would be the simplest, but it seems to ignore the g flag, because only the first match is replaced, is this expected?

Here’s what I’m trying to do: https://regex101.com/r/rEYxx4/1, but here’s the result https://regex101.com/r/EBlGo7/1

Here’s my custom command (which could have been a macro but I want to be able to run on a selection or the whole content automatically):

import sublime_plugin


class MarkdownLinksSelCommand(sublime_plugin.TextCommand):
    """The implementation of 'markdown_links_sel' text command."""

    def run(self, edit):
        view = self.view
        selections = view.sel()
        selection_empty = not any(len(sel) != 0 for sel in selections)
        
        if selection_empty:
            view.run_command("select_all")

        view.run_command(
            "insert_snippet",
            {"contents": "${SELECTION/^(\\s*)(http\\S+)(.*)$/\\1* <\\2>\\3/gm}"}
        )

Thanks for any help,
Alex

0 Likes

#2

It looks like . matches line ending as well. So I would suggest try "${SELECTION/^(\\s*)(http\\S+)([^\n]*)$/\\1* <\\2>\\3/gm}".

0 Likes

#3

Thanks a lot! I though of a possible issue with the regex too but couldn’t find it :no_mouth:

If I may ask, why isn’t there a native find_replace[_all] command like available in the GUI (with the same options)?

0 Likes