Sublime Forum

RegReplace Plugin

#45

Two things. Python uses \1 instead of $1. And your regex is in a string so escape literal backslashes.

[pre=#2D2D2D] // CONVERT TO LESS - STEPH
“lessrewrite_width”: {
“find”: “(\t*)^-]\bwidth\b: (-?[0-9]*%|-?[0-9]px|auto|-?[0-9]);”,
“replace”: “\1.w(\2);”
}[/pre]

0 Likes

#46

Thanks for the info about the RegEx, I didn’t realize it was Python.

So I updated my code with your suggestion, but nothing happens when I run it from the Command Palette, or am I supposed to run it from somewhere else?

0 Likes

#47

I verified the code before I posted; that is why I asked for an example.

I did not run it on the ads_ca-fr_home.less you provided because there are no width attributes that need to be converted in it; therefore, it would do nothing. So if that is the file you are testing on, you are wasting your time because width is already converted in every instance in that file.

0 Likes

#48

Also, if you are still having issues, I may need some more info. It should work fine from command palette. But if it isn’t, you may be doing something odd, so I would need to know how you installed the package, are you editing the default version of the settings file, or did you copy it to user and edit that one. I may need to see your settings file to verify what you have done. Based on what you gave me, it should work, and did for me. If it isn’t working for you, then something else isn’t right on your end.

0 Likes

#49

I just found your plugin, and it looks really helpful!

For my needs, I’m trying to simply get a command mapped to a key binding, and have it fold all functions (and only functions) in PHP files, which are structured like:

/**
 * Docblock for function.
 */
function example_function($param) {
  return $param;
}

The built-in code folding folds all comments, too, which is annoying in my workflow. Therefore I’m trying to add the command “fold_functions”, and I think I’m getting hung up somewhere; it’s not clear if I need to define the ‘fold’ action in the command itself, and then how to run the “fold_functions” command without the key binding (which I might also have set up incorrectly).

Here’s my customizations:

Inside Default.sublime-commands (which Sublime opened when I chose Sublime > Preferences > Package Settings > Reg Replace > Commands - User):

{
    {
        "caption": "Code Folding: Fold All Functions",
        "command": "fold_functions",
        "keys": "shift+super+0"],
        "args": {"replacements": "fold_functions"], "action": "fold"}
    },
}

Inside reg_replace.sublime-settings (which Sublime opened when I chose Sublime > Preferences > Package Settings > Reg Replace > Commands - User):

{
    // Fold all functions.
    "fold_functions": {
        "find": "^function\\b(.*?(\\n))+.*?\\}",
        "greedy": false,
        "case": false
    }
}

It’s a little confusing to me, but I’ve also only started using Sublime a few weeks ago, so I’m trying to understand the system.

0 Likes

#50

I have the following usecase:
find hex colors with uppercase letters: #([A-F\d]+)
replace uppercase letters with lower ones: #\L$1\E
I expect to find #FF00AA and replace it with #ff00aa, which works as expected when i test it from sublime’s Find and replace dialog.
Given the following settings I get a literal replace with #\L$1\E

"css_lowercase_hex_colors": {
  "find"    : "#([A-F\\d]+)",
  "replace" : "#\\L$1\\E",
  "greedy"  : true,
  "case"    : true,
  "literal" : false
}

Is this Oniguruma feature supposed to be working with RegReplace?

0 Likes

#51

RegReplace uses the python re engine (mainly because the ST find API is very awkward for RegReplace to access due to the way RegReplace works, and I didn’t want to use the ST API in half of the code, and re in the other half).

[quote=“vitaLee”]I have the following usecase:
find hex colors with uppercase letters: #([A-F\d]+)
replace uppercase letters with lower ones: #\L$1\E [/quote]

RegReplace, since it uses re, requires groups to be specified as \1 not $1. So, #\L\1\E would be more appropriate (in a string you would obviously escape the slashes).

But you still won’t get your desired effect because re does not support Oniguruma.

I can see the desire to use Oniguruma though…maybe down the line I can implement this with a third party package like github.com/mitsuhiko/ponyguruma, or at the very least create some kind of system to allow users to write scripts to manipulate the regex groups format on replace.

Hopefully, that answered your questions, and while I don’t have an immediate fix to allow you to do what you want, maybe down the line. Feel free to make this suggestion on Github at the RegReplace repo.

0 Likes

#52

I guessed that could be the reason for this.
Thanks anyway.

0 Likes

#53

What are my options for running a RegReplace replacement on a batch of 360 files?

0 Likes

#54

Right now? Probably something like sublimes built in batch find/replace, or some other kind of batch search and replace tool, I use grepWin on windows.

0 Likes

#55

Hi, I hope ‘facelessuser’ can answer me this:

i’m trying to use this snippet:

// busca consultas SQL y las encierra en query("consulta") "wrap_sql_in_query": { "scope": "sql", "find" : "((\"|')(delete|select|insert|update)\\s+\\w\\s=,.'\\$;\\(\\)+-<>|]+(\"|'))", "replace": "query(\\1)", "greedy_replace": true, "case" : false },

I have that in /home/user/.config/sublime-text-2/Packages/RegReplace/reg_replace.sublime-settings

in /home/user/.config/sublime-text-2/Packages/RegReplace/Default.sublime-commands

i have:

{ "caption": "Reg Replace: Update PG to ADODB", "command": "reg_replace", "args": {"replacements": "wrap_sql_in_query", "update_pg_to_adodb", "update_pg_to_adodb1", "update_pg_result", "comment_pg_exec"], "find_only": true} },

but no results are highlighted, i tested the regex in both pythex.org/ and it worked fine (removing the escape )

the test case is:

$consulta    = "select consdocdeu,fechacompro from compromi where estado ='A' and fechacompro <= date(now()) -1  ";

and the expected result is:

$consulta    = query("select consdocdeu,fechacompro from compromi where estado ='A' and fechacompro <= date(now()) -1  ");

is like the backslashes aren’t working, but if i remove the backslashes sublime tells:

thank you!

0 Likes

#56

What language (syntax) is your code in?

0 Likes

#57

I threw this in PHP real quick.

Notice I removed the “sql” scope, because at least in PHP, the string did not scope to “sql”.

[pre=#232628] // busca consultas SQL y las encierra en query(“consulta”)
“wrap_sql_in_query”: {
// “scope”: “sql”,
“find” : “((”|’)(delete|select|insert|update)\s+\w\s=,.’\$;\(\)±<>|]+("|’))",
“replace”: “query(\1)”,
“greedy_replace”: true,
“case” : false
},[/pre]

You didn’t provide me with the other commands, so I reformatted the command to only call the wrap command you gave me.

[pre=#232628] {
“caption”: “Reg Replace: Wrap SQL Query”,
“command”: “reg_replace”,
“args”: {“replacements”: “wrap_sql_in_query”], “find_only”: true}
},[/pre]

It turned this:

[pre=#232628]<?

$consulta = "select consdocdeu,fechacompro from compromi where estado =‘A’ and fechacompro <= date(now()) -1 ";

?>[/pre]

To this just fine:

[pre=#232628]<?

$consulta = query("select consdocdeu,fechacompro from compromi where estado =‘A’ and fechacompro <= date(now()) -1 ");

?>[/pre]

Maybe removing the scope is all you need to do? Maybe there is something wrong with the additional commands you did not provide me with? I don’t know since you did not provide me enough information. But there is nothing wrong with the regex, and since I don’t know what syntax language you are using, I cannot be sure whether the sql scope requirement is helpful or not, but it is a hindrance in stock PHP.

0 Likes

#58

is php

0 Likes

#59

Removing the scope did the trick!,
thank you and excellent plugin, i though scope mean ‘group these regex’ its the scope mean for file types??

thank you again

[quote=“facelessuser”]I threw this in PHP real quick.

Notice I removed the “sql” scope, because at least in PHP, the string did not scope to “sql”.

[pre=#232628] // busca consultas SQL y las encierra en query(“consulta”)
“wrap_sql_in_query”: {
// “scope”: “sql”,
“find” : “((”|’)(delete|select|insert|update)\s+\w\s=,.’\$;\(\)±<>|]+("|’))",
“replace”: “query(\1)”,
“greedy_replace”: true,
“case” : false
},[/pre]

You didn’t provide me with the other commands, so I reformatted the command to only call the wrap command you gave me.

[pre=#232628] {
“caption”: “Reg Replace: Wrap SQL Query”,
“command”: “reg_replace”,
“args”: {“replacements”: “wrap_sql_in_query”], “find_only”: true}
},[/pre]

It turned this:

[pre=#232628]<?

$consulta = "select consdocdeu,fechacompro from compromi where estado =‘A’ and fechacompro <= date(now()) -1 ";

?>[/pre]

To this just fine:

[pre=#232628]<?

$consulta = query("select consdocdeu,fechacompro from compromi where estado =‘A’ and fechacompro <= date(now()) -1 ");

?>[/pre]

Maybe removing the scope is all you need to do? Maybe there is something wrong with the additional commands you did not provide me with? I don’t know since you did not provide me enough information. But there is nothing wrong with the regex, and since I don’t know what syntax language you are using, I cannot be sure whether the sql scope requirement is helpful or not, but it is a hindrance in stock PHP.[/quote]

0 Likes

#60

It applies to the highlight scoping. For instance, if you want the regex to only be applied to “strings”, you set the scope as “string”. Then RegReplace finds all of the parts of your file that are of the “string” scope, and applies the regex to them individually.

Like if I want to target strings for changing their quote style:

[pre=#232628] // Swap quotes
“swap_quotes_to_single”: {
“scope”: “string”,
“find” : “^”(.?)"$",
“replace”: “’\1’”,
“greedy_replace”: false
},
“escape_single_quotes”: {
“scope”: “string”,
“find” : “^(”.
?(?<!\\))((?:\\]{2}))’(.?")$",
“replace”: “\1\2\’\3”,
“greedy_replace”: false,
“multi_pass_regex”: true
},
“unescape_double_quotes”: {
“scope”: “string”,
“find” : “^(’.?(?<!\\))((?:\\]{2}))\\”(.*?’)$",
“replace”: “\1\2”\3",
“greedy_replace”: false,
“multi_pass_regex”: true
},[/pre]

[pre=#232628] // Flip Quotes
{
“caption”: “Replace: Swap Quotes to Single”,
“command”: “reg_replace”,
“args”: {“replacements”: “escape_single_quotes”, “swap_quotes_to_single”, “unescape_double_quotes”], “find_only”: true}
},[/pre]

etc.

Hope that helps.

0 Likes

#61

Oh I see, will be usefull for a case I have! thanks, keep the good work!

0 Likes

#62

ST3 only (currently).

RegReplace now allows you to do procedural evaluations on found text via plugins.

// Some defintion "some_definition": { "find": "some regex here", "replace": "some optional replace here", "greedy": true, "case": true, "plugin": "User.rr_modules.force_all_caps", "args": {"some_plugin_rguments": "if_desired"} },

A plugin with path “User/rr_modules/force_all_caps.py” would be specified in your defintion as “User.rr_modules.force_all_caps”.

Built-in RegReplace modules are simply referenced as “rr_modules.my_module” etc. (though there aren’t any provided at this time).

Plugins are very simple:

def run(text, **optional_keyword_arguments): # Do some stuff to text return text

That is it.

You can import RegReplace plugins into other RegReplace plugins if desired by.

[code]from RegReplace.rr_plugin import Plugin

def run(text, **optional_keyword_arguments):
module = Plugin.load(“User.rr_modules.myplugin”)
text = module.run(text)
return text[/code]

If I were creating a User module, I personally would include from a sub-folder in User that does not provide a “init.py”. This just basically means sublime won’t automatically import the plugin file.

I guess you could consider this feature in beta. So, real world feedback may cause some aspects to change in the future, but maybe not.

0 Likes

#63

Got some big changes.

[size=150]Extended Backreferences (Replace Only)[/size]

People occasionally complain that RegReplace can’t use title case back references:

[pre=#232628] “test_case”: {
“find”: “([a-z])(?P[a-z]*)((?:_[a-z]+)+)”,
“replace”: “\u\1\L\g\E\U\g<3>\E”,
“greedy”: true
}[/pre]

Well this is because the regex engine that RegReplace uses is not Sublime’s built in regex engine, but instead uses Python. I won’t go into reasons why, but suffice it to say, I have reasons. Now Python doesn’t support title case backreferences in its regex engine. So I have been thinking about this recently and added some extended back references to handle this.

Now hold up, it isn’t exactly the same! Python strings already use \u, so \u wasn’t an option. So it is a sightly altered notation:

[pre=#232628] “test_case”: {
“find”: “([a-z])(?P[a-z]*)((?:_[a-z]+)+)”,
“replace”: “\c\1\L\g\E\C\g<3>\E”,
“greedy”: true
},[/pre]

See the difference? You have to use \c and \C instead of \u and \U. Now this is disabled by default and only works for the replace string (I’m not re-writing the regex parser for matches), so you have to enable it in your settings file by using:

[pre=#232628] // Use extended backreferences
“extended_back_references”: true[/pre]

There might be more in the future.

[size=150]Updated Plugin System (More Useful)[/size]
Also, I recently realized the plugin system was not that good in its current state. So I simplified it.

You still define a plugin the same way (plugins are referenced like importing a python module with Packages as your root) User.rr_modules.:
[pre=#232628] “some_definition”: {
“find”: “some regex here”,
“replace”: “some optional replace here”,
“greedy”: true,
“case”: true,
“plugin”: “User.rr_modules.useful_stuff”,
“args”: {“some_plugin_rguments”: “if_desired”}
},[/pre]

And I have provided a simple example on the repo you can try out. Now you just define a function called replace and it accepts a match object and optional arguments (I show them in the example just to remind you you can use them):
[pre=#232628]def replace(m, **kwargs):
text = "Here are your groups: "
for group in m.groups():
if group is not None:
text += “(%s)” % group
return text[/pre]

0 Likes

#64

Edit: Posted in wrong thread.

0 Likes