[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Different behaviour between M-x replace-regexp in function and in ec
From: |
Peter Dyballa |
Subject: |
Re: Different behaviour between M-x replace-regexp in function and in echo window |
Date: |
Thu, 21 Apr 2005 12:29:28 +0200 |
Am 21.04.2005 um 11:35 schrieb luca.spinacci@seleniacomms.com:
If I use the same
replace-regexp "\(//\)[[:space:]] *" "\1 "
in a function no replacing is done - Replaced 0 occurences -
(defun comment-formatting(start end)
(interactive "*r")
(save-excursion
(save-restriction
(narrow-to-region start end)
(goto-char start)
(replace-regexp "\(//\)[[:space:]] *" "\1 "))))
So M-x comment-formatting has differnt behaviour. Why?
The function's description says it's an interactive function, and ends
with this recommendation:
This function is usually the wrong thing to use in a Lisp program.
What you probably want is a loop like this:
(while (re-search-forward REGEXP nil t)
(replace-match TO-STRING nil nil))
which will run faster and will not set the mark or print anything.
I wonder why you make the REGEXP that complicated: "[[:space:]]*" is
equivalent to "[[:space:]] *", isn't it?
And you don't need to replace "\(//\)" with "\1" since "//" is *always*
"//". This would be sufficient: (replace-regexp "//[[:space:]]*" "//
"). Whenever there are two slashes followed by any amount of white
space, replace it with two (other?) slashes and exactly one space.
The \n mechanism is good when you're searching for an expression that
is variable according to some law. Therefore you can't set a fixed
replacement for it but have to "cite" it.
I have learned basic and extended regular expressions for UNIX shell
use and sed, awk ... The specialities with POSIX (as in Korn shell) or
in Perl and Emacs I do not try to learn actively, they're some special
cases, OK for programmers in those languages. So for me it's overkill
to define special replace functions, I always find a way to do it
interactively -- which helps to learn by practice. Therefore I have two
keys bound to replace-string and to replace-regexp. I hit one of them,
enter FROM, enter RET, enter TO, and a final RET. When I want to apply
the change for the whole buffer, I go to its beginning. When I want to
change the remainder of the buffer, I don't move that much. When I want
to apply a change to some region, I mark it.
Modern Emacsen have a history of replacements done. You can scroll in
that and pick one FROM and one TO ...
--
Greetings
Pete
Make it simple, as simple as possible but no simpler. (Albert Einstein)