Latest in Code

Incrementing Search and Replace

Iterate Over An Object In Actionscript 3

Generating Cairngorm code

Flex Compiler Shell Controller, jEdit and Error List

Instant Slideshow JSFL

More pages in Code...

 

Incrementing Search and Replace


Ever want to iterate over your search and replace and maybe change a value? Here's how in jEdit.
2009-11-05

Today I finally, FINALLY figured out how to do something useful with the enigmatic sounding 'Return value of a Beanshell snippet' feature in jEdit. Sure, I understood the basic idea behind it, but really, I couldn't find anything I could DO with it. BUT today I found a great hidden nugget.

Beanshell, while strangely named, is actually just Java. The difference between Beanshell java and normal java is that Beanshell java is interpreted line-by-line instead of compiled. This allows you to write tiny bits of code in java that do useful things.

If you've used jEdit before, you've probably ran into some Beanshell at some point.jEdit macros are written in Beanshell. Beanshell is a large part of the power of jEdit.

But I thought it was almost useless when it came to jEdit's Search and Replace window. Since this is probably one of the most powerful areas of jEdit, I couldn't ever see a use for it. But finally, I figured out some magic that explains more intimately how to use this feature for good.

Say I have this data:

This is a sample, but for my purposes, this data was rather large. And the 'id' attribute needed to be changed to be sequential. After much trial and error, I found that this worked.

Go to Utilities->Beanshell->Evaluate Beanshell Expression...




Enter in 'i=0'

After entering in the expression and pressing 'OK', a confirmation dialog will display the return value, 0.

Ok, now we've initialized a variable, i, to zero. Let's use that in our Search and Replace dialog!! Open up the find dialog and set the settings up like so:

We're searching for our regex above, and then replacing it with the beanshell expression below. Pressing 'Replace All' does the following:

And that is a very basic example of the raw power of this feature. It is possible to set any number of variables before your search, using a macro or any other method. And then within the search dialog you can handle conditions however you like. You can even record this as a macro:

i=0;
SearchAndReplace.setSearchString("id=\\\"\\d*\\\"");
SearchAndReplace.setReplaceString("\"id=\\\"\" + i++ + \"\\\"\"");
SearchAndReplace.setBeanShellReplace(true);
SearchAndReplace.setIgnoreCase(true);
SearchAndReplace.setRegexp(true);
SearchAndReplace.setSearchFileSet(new CurrentBufferSet());
SearchAndReplace.replaceAll(view);

Now that is just damn cool.

 
 

©2004 Chris Hill. All Rights Reserved.Legal Crapola