I was lately being teased by a vi user. He said that within few commands, one can do search-replace (both regexp and simple string ), on lines range. And one does not need to do highlight. One inputs start, end, and the string and replacement, pretty much.
Is there a way to do that in emacs? I'd hate to lose in a religious war ;-)
what do you mean by lines range?– Chakravarthy RaghunandanDec 17, 2016 at 10:11
For example: From line 20, to line 2003, on a 3000 lines file. Thanks.– user1134991Dec 17, 2016 at 10:32
In emacs it's not that hard to write your own.
(defun my-query-regexp-replace-lines (start end) (interactive "nStart line (inclusive): \nnEnd line (inclusive): ") (let (start-point end-point) (save-excursion (goto-char (point-min)) (forward-line (- start 1)) (setq start-point (point)) (forward-line (1+ (- end start))) (setq end-point (point))) (save-restriction (narrow-to-region start-point end-point) (call-interactively 'query-replace-regexp))))
As the other answer says evil-mode is great too
I'm not sure I understand what's so great about not highlighting the lines first.
Anyway, selecting them is easy. The vi command
:20,2003s/foo/bar/g<CR> would be something like:
M-g M-g 20 RET C-SPC M-g M-g 2004 RET M-% foo RET bar RET !. Yes, the vi version is a full 3 keypresses shorter, and easier to type, but the Emacs one is not too bad. If you plan on doing lots of stuff to that same range of lines besides the search and replace, I recommend using
Highlighting 2000 lines isn't fun (at least for me). Thanks. Dec 18, 2016 at 18:32
1For your 3 extra keypresses you get visual confirmation that your start and end lines are the correct places.– icarusDec 19, 2016 at 13:57
I don't think it's fun either, @user1134991, I doubt anyone expects that sort of thing to be fun. It is however, fast, effective and easy to do. I'm satisfied with those qualities in a line selection experience. For comparison, I don't think specifying a range is fun in vi either, there it is also merely fast, effective and easy to do.– OmarDec 19, 2016 at 18:23
You can switch to evil-mode and use commands similar to the commands in vi.
- Precondition: Have Emacs package "evil" installed. (See https://melpa.org/#/evil)
Let the buffer be
foo foo foo foo foo foo foo foo foo foo foo foo foo foo foo
Activate evil-mode with
To replace "foo" with "bar" in lines 2 to 4 in a buffer
The result of the replacement:
foo bar bar bar bar bar bar bar bar bar foo foo foo foo foo
Deactivate evil with a further
Would you mind providing the necessary input for the precise example? This could turn some people (me at least) in trying evil-mode (which I never did). Dec 17, 2016 at 14:27
emacs.stackexchange.com/users/9995/jeanpierre See the edited answer. Dec 17, 2016 at 17:50
1I think the same can be achieved with
viper-mode, included in emacs. However exiting viper is with
viper-go-away. Dec 17, 2016 at 18:02