obsidian-latex-suite icon indicating copy to clipboard operation
obsidian-latex-suite copied to clipboard

Conditional regex replacement

Open TimeTravelPenguin opened this issue 1 year ago • 0 comments

This feature request is related to PCRE2 Replacement String Conditional, which would be a nice feature addition.

Not only would it make replacement more dynamic, but it would help cut down on a load of duplication.

Example use case: A demo power function that either raises something to a power or defaults to power 1.

Regex:

\\pow{(?<var>[a-zA-Z]+)(?<pow>\d+)?}

Replacement:

${pow:+\{$var\}^\{$pow\}:\{$var\}^\{1\}}

Now, this will replace match \pow{x12} and replace with {x}^{12}. This can already be done with the {[[0]]}^{[[1]]} snippet notation. However, this will also match \pow{x} and replace it with {x}^{1}, which cannot be done by snippets unless you have a separate version for each case.

This is useful for more than just defaults. It can be used to add "optional" to regex matches. For example, rather than having multiple variations for one regex snippet, you can make a single, concise one (albeit more advance; but this is certainly a more advanced tool).

One example would be to make snippets to automatically construct large formulas, such as integrals, where you may or may not wish to include the limits. Perhaps \int{x} can replace to \int {$0} dx where {$0} is a curser placement, and then \int{x}{0}{1} can replace to \int_{0}^{1} {$0} dx.

Additional suggestion:

Perhaps this is worthy of its own feature request, but the main limitation I can see, which I would really like to have, is the option to replace a match that is repeated. For example, something like a simple regex ([a-aA-Z]\d)* will match ABC1A2B3C4. However, suppose I did (([a-aA-Z])*(\d)) instead. It would be nice to be able to loop over these matches to apply a replacement over each inner capture. Perhaps some syntax such as this will elaborate the idea: [[0:{[[0]]}^{[[1]]}]]. Here, the outer [[ ]] is the zeroth parent capture, and the : separates the replacement content for the children [[0]] and [[1]]. This isn't the nicest syntax, however, but it elaborates the idea.

This additional suggestion shows one limitation to this suggested feature: it is incredibly static. That is perfectly fine at times, but it means that there will still be many cases of repetition in snippets. For example, if I wanted to make a variation of the earlier mentioned \pow to \pows which may have a use case that looks like \pows{x1y2z3} to replace to {x}^{1}{y}^{2}{z}^{3}. There is no way to currently do this without making additional snippets. This could work by looping over the captured pattern by the additional suggestion to this limitation, which would fit in well with the suggestion.

TimeTravelPenguin avatar Jun 09 '23 13:06 TimeTravelPenguin