in my file, I have many instances of ID="XXX", and I want to replace the first one with ID="0", the second one with ID="1", and so on.
When I use regexp-replace interactively, I use ID="[^"]*" as the search string, and ID="\#" as the replacement string, and all is well.
now I want to bind this to a key, so I tried to do it in lisp, like so:
(replace-regexp "ID=\"[^\"]*\"" "ID=\"\\#\"")
but when I try to evaluate it, I get a 'selecting deleted buffer' error. It's probably something to do with escape characters, but I can't figure it out.
Unfortunately, the \# construct is only available in the interactive call to replace-regexp. From the documentation:
In interactive calls, the replacement text may contain `\,'
followed by a Lisp expression used as part of the replacement
text. Inside of that expression, `\&' is a string denoting the
whole match, `\N' a partial match, `\#&' and `\#N' the respective
numeric values from `string-to-number', and `\#' itself for
`replace-count', the number of replacements occurred so far.
And at the end of the documentation you'll see this hint:
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.
Which then leads us to this bit of elisp:
(save-excursion
(goto-char (point-min))
(let ((count 0))
(while (re-search-forward "ID=\"[^\"]*\"" nil t)
(replace-match (format "ID=\"%s\"" (setq count (1+ count)))))))
You could also use a keyboard macro, but I prefer the lisp solution.
Related
Since version 22 of Emacs, we can use \,(function) for manipualting (parts of) the regex-search result before replacing it. But – this is mentioned often, but nonetheless still the truth – we can use this construct only in the standard interactive way. (Interactive like: By pressing C-M-% or calling query-replace-regexp with M-x.)
As an example:
If we have
[Foo Bar 1900]
and want to get
[Foo Bar \function{foo1900}{1900}]
we can use:
M-x query-replace-regexp <return>
\[\([A-Za-z-]+\)\([^0-9]*\) \([0-9]\{4\}\)\]
[\1\2 \\function{\,(downcase \1)\3}{\3}]
to get it done. So this can be done pretty easy.
In my own defun, I can use query only by replacing without freely modifying the match, or modify the prepared replaced string without any querying. The only way I see, is to serialize it in such a way:
(defun form-to-function ()
(interactive)
(goto-char (point-min))
(while (query-replace-regexp
"\\[\\([A-Za-z-]+\\)\\([^0-9]*\\) \\([0-9]\\{4\\}\\)\\]"
"[\\1\\2 \\\\function{\\1\\3}{\\3}]" ))
(goto-char (point-min))
(while (search-forward-regexp "\\([a-z0-9]\\)" nil t)
(replace-match (downcase (match-string 1)) t nil)
)
)
For me the query is important, because I can't be sure, what the buffer offers me (= I can't be sure, the author used this kind of string always in the same manner).
I want to use an elisp function, because it is not the only recurring replacement (and also not only one buffer (I know about dired-do-query-replace-regexp but I prefer working buffer-by-buffer with replace-defuns)).
At first I thought I only miss something like a query-replace-match to use instead of replace-match. But I fear, I am also missing the easy and flexible way of rearrange the string the the query-replace-regexp.
So I think, I need a \, for use in an defun. And I really wonder, if I am the only one, who is missing this feature.
If you want your rsearch&replace to prompt the user, that means you want it to be interactive, so it's perfectly OK to call query-replace-regexp (even if the byte-compiler will tell you that this is meant for interactive use only). If the warning bothers you, you can either wrap the call in with-no-warnings or call perform-replace instead.
The docstring of perform-replace sadly doesn't (or rather "didn't" until today) say what is the format of the replacements argument, but you can see it in the function's code:
;; REPLACEMENTS is either a string, a list of strings, or a cons cell
;; containing a function and its first argument. The function is
;; called to generate each replacement like this:
;; (funcall (car replacements) (cdr replacements) replace-count)
;; It must return a string.
The query-replace-function can handle replacement not only as a string, but as a list including the manipulating elements. The use of concat archives building an string from various elements.
So one who wants to manipulate the search match by a function before inserting the replacement can use query-replace-regexp also in a defun.
(defun form-to-function ()
(interactive)
(goto-char (point-min))
(query-replace-regexp
"\\[\\([A-Za-z-]+\\)\\([^0-9]*\\) \\([0-9]\\{4\\}\\)\\]"
(quote (replace-eval-replacement concat "[\\1\\2 \\\\function{"
(replace-quote (downcase (match-string 1))) "\\3}{\\3}]")) nil ))
match-string 1 returns the first expression of our regexp-search.
`replace-quote' helps us doublequoting the following expression.
concat forms a string from the following elements.
and
replace-eval-replacement is not documented.
Why it is in use here nevertheless, is because of emacs seems to use it internally, while performing the first »interactive« query-replace-regexp call. At least is it given by asking emacs with repeat-complex-command.
I came across repeat-complex-command (bound to [C-x M-:].) while searching for an answer in the source code of query-replace-regexp.
So an easy to create defun could be archieved by performing the standard search and replace way as told in the question and after first sucess pressing [C-x M-:] results in an already Lisp formed command, which can be copied and pasted in a defun.
Edit (perform-replace)
As Stefan mentioned, one can use perform-replace to avoid using query-replace-regexp.
Such a function could be:
(defun form-to-function ()
(interactive)
(goto-char (point-min))
(while (perform-replace
"\\[\\([A-Za-z-]+\\)\\([^0-9]*\\) \\([0-9]\\{4\\}\\)\\]"
(quote (replace-eval-replacement concat "[\\1\\2 \\\\function{"
(replace-quote (downcase (match-string 1))) "\\3}{\\3}]"))
t t nil)))
The first boolean (t) is a query flag, the second is the regexp switch. So it works also perfectly, but it didn't help finding the replacement expression as easy as in using \,.
Is it possible to add own character classes to emacs in order to use them in regular expressions?
Let's say, i want to add a class [[:consonant:]] which matches all letters that are not vowels in order to avoid writing [b-df-hj-np-tv-z] all the time (and yes, i am aware that my shortcut is almost as long as the term i want to avoid, take it as a simplification of my problem).
Is this possible at all or do i have to use format or concat, respectively? If it is possible, how do i do that?
An MWE could be like this:
(defun myfun ()
"Finds clusters of three or more consonants"
(interactive)
(if (search-forward-regexp "[b-df-hj-np-tv-z]\\{3,\\}")
(message "Yepp, here is a consonant cluster.")
))
(defun myfun-1 ()
"Should also find clusters of three or more consonants."
(interactive)
(if (search-forward-regexp "[[:consonant:]]\\{3,\\}")
(message "Yepp, here is a consonant cluster.")
))
Both functions myfun and myfun-1 should do the very same thing.
One step further i'd like to know if it is possible to put whole expressions in such "shortcuts", like
[[:ending:]] ==> "\\(?:en\\|st\\|t\\|e\\)"
Jordon-Biondo is correct, you cannot extend Emacs' character classes for regexp search. If you peek into Emacs' source code, you can see these defined in the routine re_wctype_parse on line 1510(ish) of regex-emacs.c. So adding to these natively would require modifying the .c file and rebuilding.
I do not believe you can do this. But there is something similar that was recently released in the ample-regexp package found HERE. This was taken from the readme as an example:
(define-arx h-w-rx
'((h "Hello, ")
(w "world"))) ;; -> hello-world-rx
(h-w-rx h w) ;; -> "Hello, world"
(h-w-rx (* h w)) ;; -> "\\(?:Hello, world\\)*"
You could use this to define a wide range of aliases in one big define-arx.
What would be a good way to get Emacs to highlight an expression that may include things like balanced brackets -- e.g. something like
\highlightthis{some \textit{text} here
some more text
done now}
highlight-regex works nicely for simple things, but I had real trouble writing an emacs regex to recognize line breaks, and of course it matches till the first closing bracket.
(as a secondary question: pointers to any packages that extend emacs regex syntax would be much appreciated -- I am having pretty hard time with it, and I'm fairly familiar with regexes in perl.)
Edit: For my specific purpose (LaTeX tags highlighting in an AUCTeX buffer), I was able to get this to work by customizing an AUCTeX specific variable font-latex-user-keyword-classes, that adds something like this to custom-set-variables in .emacs:
'(font-latex-user-keyword-classes (quote (("mycommands" (("highlightthis" "{")) (:slant italic :foreground "red") command))))
A more generic solution would still be nice to have though!
You could use functions acting on s-expressions to work with the region you want to highlight, and use one of the solutions mentionned on this question to actually highlight it.
Here is an example :
(defun my/highlight-function ()
(interactive)
(save-excursion
(goto-char (point-min))
(search-forward "\highlightthis")
(let ((end (scan-sexps (point) 1)))
(add-text-properties (point) end '(comment t face highlight)))))
EDIT : Here is an example using a similar function with Emacs' standard font locking system, as explained in the search-based fontification section of the emacs-lisp manual :
(defun my/highlight-function (bound)
(if (search-forward "\highlightthis" bound 'noerror)
(let ((begin (match-end 0))
(end (scan-sexps (point) 1)))
(set-match-data (list begin end))
t)
nil))
(add-hook 'LaTeX-mode-hook
(lambda ()
(font-lock-add-keywords nil '(my/highlight-function))))
When entering code Emacs transiently highlights the matching brace or bracket. With existing code however is there a way to ask it to highlight a matching brace or bracket if I highlight its twin?
I am often trying to do a sanity check when dealing with compiler errors and warnings. I do enter both braces usually when coding before inserting the code in between, but have on occasion unintentionally commented out one brace when commenting out code while debugging.
Any advice with dealing with brace and bracket matching with Emacs?
OS is mostly Linux/Unix, but I do use it also on OS X and Windows.
If you're dealing with a language that supports it, give ParEdit a serious look. If you're not using with a Lisp dialect, it's not nearly as useful though.
For general brace/bracket/paren highlighting, look into highlight-parentheses mode (which color codes multiple levels of braces whenever point is inside them). You can also turn on show-paren-mode through customizations (that is M-x customize-variable show-paren-mode); that one strongly highlights the brace/bracket/paren matching one at point (if the one at point doesn't match anything, you get a different color).
my .emacs currently contains (among other things)
(require 'highlight-parentheses)
(define-globalized-minor-mode global-highlight-parentheses-mode highlight-parentheses-mode
(lambda nil (highlight-parentheses-mode t)))
(global-highlight-parentheses-mode t)
as well as that show-paren-mode customization, which serves me well (of course, I also use paredit when lisping, but these are still marginally useful).
Apart from the answer straight from the manual or wiki, also have a look at autopair.
tried on emacs 26
(show-paren-mode 1)
(setq show-paren-style 'mixed)
enable showing parentheses
set the showing in such as highlit the braces char., or if either one invisible higlight what they enclose
for toggling the cursor position / point between both, put this script in .emacs
(defun swcbrace ()(interactive)
(if (looking-at "(")(forward-list)
(backward-char)
(cond
((looking-at ")")(forward-char)(backward-list))
((looking-at ".)")(forward-char 2)(backward-list))
)))
(global-set-key (kbd "<C-next>") 'swcbrace)
it works toggling by press Control-Pgdn
BTW, for the immediate question: M-x blink-matching-open will "re-blink" for an existing close paren, as if you had just inserted it. Another way to see the matching paren is to use M-C-b and M-C-f (which jump over matched pairs of parens), which are also very useful navigation commands.
I second ParEdit. it is very good atleast for lisp development.
FWIW I use this function often to go to matching paren (back and forth).
;; goto-matching-paren
;; -------------------
;; If point is sitting on a parenthetic character, jump to its match.
;; This matches the standard parenthesis highlighting for determining which
;; one it is sitting on.
;;
(defun goto-matching-paren ()
"If point is sitting on a parenthetic character, jump to its match."
(interactive)
(cond ((looking-at "\\s\(") (forward-list 1))
((progn
(backward-char 1)
(looking-at "\\s\)")) (forward-char 1) (backward-list 1))))
(define-key global-map [(control ?c) ?p] 'goto-matching-paren) ; Bind to C-c p
Declaimer: I am NOT the author of this function, copied from internet.
If you just want to check the balanced delimiters, be them parentheses, square brackets or curly braces, you can use backward-sexp (bound to CtrlAltB) and forward-sexp (bound to CtrlAltF) to skip backward and forward to the corresponding delimiter. These commands are very handy to navigate through source files, skipping structures and function definitions, without any buffer modifications.
You can set the below in your init.el:
(setq show-paren-delay 0)
(show-paren-mode 1)
to ensure matching parenthesis are highlighted.
Note that (setq show-paren-delay 0) needs to be set before (show-paren-mode 1) so that there's no delay in highlighting, as per the wiki.
If you want to do a quick check to see whether brackets in the current file are balanced:
M-x check-parens
Both options tested on Emacs 27.1
My company has recently added some new code styling rules, and I would was wondering if there is an easy way via emacs to change a couple things w/ a regex replace.
if statements now have to look like the following:
if (expression) {
where I have many that look like so:
if(expression){
lacking the spaces. Is there an easy way to fix this?
You might be able to regexp replace it if expression is always on one line, but I'd use a throw-away function just to be safe:
(defun my-fix-style ()
(interactive)
(save-excursion
(goto-char (point-min))
(while (re-search-forward "\\_<if(" nil t)
(backward-char)
(insert " ")
(forward-sexp)
(unless (looking-at "[ \t\n]")
(insert " ")))))
Just my two cents, but if I was going to do this with emacs, I'd probably avoid regular expressions and approach it in two parts. First I'd do the search to replace if( with if ( by doing a Meta-% "if(" "if (" The quote marks are just for delineation, they don't belong in the entered text. Then either answer each individual replacement query, or give it a "!" to tell it to do all replacements. Repeat the process for the closing ){ to ) {.
Off the top of my head, I'd expect the first substituion to work without issue. The second one will also get "){" combinations in loops, but if your new standard demands a space for if statements, I'd expect it to do so for loops as well, so that seems like it should be a good thing.