1

Lets say I'm editing a javascript file in emacs that has objects as such scattered through out the file:

foo: [1], foo: [2], foo: [3], foo: [4], foo: [5], foo: [6], foo: [7] obo: [1], obo: [2], obo: [3], obo: [4], obo: [5], obo: [6], obo: [7]

I wanted to increment each object with a number greater then 3 by N, what would be an efficient way to do so?

It would also be nice to know how to perform the same operation but on a specific object or variable?

  • You may want to look into this library graspjs.com/blog/2014/01/07/refactoring-javascript-with-grasp . Since it's in JavaScript, it might be easier to work with to do advanced refactoring. But your question as posed begs another question: why would you even want to do this? One typically wants to reduce code repetitions, not introduce them (i.e. choose some way to do it in a loop / filter / map / reduce etc. instead). – wvxvw Mar 27 '15 at 6:30
  • To answer your questions as to why someone would even want to do this. I have to work within an existing code base that is very brittle and poorly documented. – user2522280 Mar 27 '15 at 11:41
2

You can actually do this with a replace-regexp because in your replacement, you can evaluate elisp.

Given this code:

var stuff = {
  foo: [1],
  foo: [2],
  foo: [3],
  foo: [4],
  foo: [5],
  foo: [6],
  foo: [7]
};

Select all the code in your region then run replace-regexp.

For your regexp: you could use this:

\([a-z]: +\[\)\([4-9]\|[1-90][0-9]\)\(\]\)

This will select all text matching: sometext: [ int over 3 ] and will be grouped as specified.

Then in your replacement string use elisp to increase the number by N.

Your replacement would look something like this:

\1\,(+ (string-to-number \2) N)\3

Where you would replace N with any value you wanted.

This would replace the matched text with the first match group's text, a value N larger than the second match group's text, followed by the third match group's text.

Better yet, since you are updating a brittle old code base, you can use query-replace-regexp with the same patterns listed above. This interactively take you through each match, tell you what the replacement will be and let you accept or skip each one.

Here is what that looks like: Note that I had already used the patterns specifed so it was the default option and I didn't have to enter them again.

In this example I chose specifically NOT to update the last match. So I just press y for each match until the last match, when I pressed n to keep it as is.

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.