Sometimes I need to change a variable name in the code from foo to bar. I do it using query-replace-regexp. Then I would do some other stuff and I might regret my decision and want to change it back from bar to foo. If I do query-replace-regexp, it will show by default the last replacement performed (default foo -> bar). My question is, is there a quick way to tell Emacs I want the reverse order of the default? Otherwise one would need to type the whole thing again.
Edit: The default replacement is the last replacement (default foo -> bar). What I want now is the opposite: bar to foo. Basically, I want to undo the replacement. Not always can I use the undo feature since I may have a very long history after many other edits.
When you use query-replace, M-p retrieves the default, which is foo -> bar. That is, it puts foo -> bar in the minibuffer.
You can edit that text in the minibuffer. In particular, you can move backward a word (or a sexp), using M-b (or C-M-b), and then use M-t (or C-M-t) to transpose the two words (sexps) there, giving you bar -> foo. (Then hit RET.)
The point is that once you have retrieved a previously used input, or the default input, you can edit it in the minibuffer.
(Normally, in Emacs, it is M-n that retrieves the default value. In this case it is M-p (which (IMHO) is an aberration).)
Wrt accessing previously entered input: You can cycle, by repeating M-p, but you can also search directly, using M-r. If the input you want to retrieve was not very recent, then M-r can be quicker than cycling.
This is probably a horrible way of doing this, but you could create a function like the following and bind it to another key. It seems to work in this specific case but there are tons of other things that this doesn't handle as is (such as the prefix argument).
(defun so-undo-last-query-replace ()
(interactive)
(let ((query-replace-defaults (list (cons (cdar query-replace-defaults)
(caar query-replace-defaults)))))
(call-interactively 'query-replace)))
Related
I pose the question because I think both the question and possible answers might help Emacs users who write Lisp code that defines font-lock-keywords. I'm providing one answer that I think helps. I'm also interested in other answers.
That variable's value is a list of expressions, each of which can specify one or more patterns to match or functions to perform matching, and one or more faces for highlighting the matching text. The possibilities for font-lock-keywords values are numerous and complicated. (The doc describing this is the Elisp manual, node Search-based Fontification.)
In most cases the list has more than one element, which means more than one regexp pattern. These can interact in different ways. Some can prevent others from taking effect, or they can alter the effect of others. My library Dired+, for instance, defines font-lock-keywords in Dired mode with 31 entries (regexps), many of which interact.
How to keep all of that straight? How do you debug such a list when you are defining it or modifying it? You might comment out all but one of the list items, to see its effect when alone. And then repeat for another. And then perhaps add a few together, and maybe in different orders. There are various possibilities, I suppose, but just what do you do?
(OK, I know that most Elisp coders do not write super complex font-lock-keywords definitions. But even for simple definitions this can become complicated. And perhaps if this process were easier then users would not unnecessarily limit themselves to only one or two entries.)
You could use my newly released Font Lock Studio. The following is from the readme-file:
font-lock-studio - interactive debugger for Font Lock keywords
Font Lock Studio is an interactive debugger for Font Lock
keywords (Emacs syntax highlighting rules).
Introduction
Font Lock Studio lets you single-step Font Lock keywords --
matchers, highlights, and anchored rules, so that you can see what
happens when a buffer is fontified. You can set breakpoints on or
inside rules and run until one has been hit. When inside a rule,
matches are visualized using a palette of background colors. The
explainer can describe a rule in plain-text english. Tight
integration with Edebug allows you to step into Lisp expressions
that are part of the Font Lock keywords.
When using the debugger, an interface buffer is displayed, it
contains all the keywords and is used for navigation and
visalization of match data.
When Font Lock Studio is started, comments and strings are
pre-colored, as they are part of the earlier syntactic phase
(which isn't supported by Font Lock Studio).
Start the debugger by typing "M-x font-lock-studio RET". Press ?
or see the menu for available commands.
Example
For a buffer using html-mode, the interface buffer looks the
following. Other major modes typically have more and more complex
rules. The arrow on the left indicates the current active location.
A corresponding arrow in the source buffer is placed at the current
search location.
========================
=== Font Lock Studio ===
========================
--------------------------------------------------
=> "<\\([!?][_:[:alpha:]][-_.:[:alnum:]]*\\)"
(1 font-lock-keyword-face)
--------------------------------------------------
"</?\\([_[:alpha:]][-_.[:alnum:]]*\\)\\(?::\\([_:[:alpha:]]
[-_.:[:alnum:]]*\\)\\)?"
(1
(if
(match-end 2)
sgml-namespace-face font-lock-function-name-face))
(2 font-lock-function-name-face nil t)
--------------------------------------------------
"\\(?:^\\|[ \t]\\)\\([_[:alpha:]][-_.[:alnum:]]*\\)\\(?::
\\([_:[:alpha:]][-_.:[:alnum:]]*\\)\\)?=[\"']"
(1
(if
(match-end 2)
sgml-namespace-face font-lock-variable-name-face))
(2 font-lock-variable-name-face nil t)
--------------------------------------------------
"[&%][_:[:alpha:]][-_.:[:alnum:]]*;?"
(0 font-lock-variable-name-face)
--------------------------------------------------
"<\\(b\\(?:ig\\|link\\)\\|cite\\|em\\|h[1-6]\\|rev\\|s\\(?:
mall\\|trong\\)\\|t\\(?:itle\\|t\\)\\|var\\|[bisu]\\)
\\([ \t][^>]*\\)?>\\([^<]+\\)</\\1>"
(3
(cdr
(assoc-string
(match-string 1)
sgml-tag-face-alist t))
prepend)
==================================================
Public state:
Debug on error : YES
Debug on quit : YES
Explain rules : YES
Show compiled code : NO
Press space to single step through all the keywords. "n" will go
the the next keyword, "b" will set a breakpoint, "g" will run to
the end (or to the next breakpoint) and "q" will quit.
Features
Stepping
You can single step into, over, and out of Font Lock
keywords. Anchored rules are fully supported. In addition, you
can run to the end or to the next breakpoint.
Breakpoints
You can set breakpoints on part of the keyword, like the matcher
(e.g. the regexp), a highlight rule, or inside an anchored highlight
rule.
If you want to step or run without stopping on breakpoints, prefix
the command with C-u.
Note that in an anchored rule, you can set a breakpoints either on
the entire rule or on an individual part. In the former case, only
the outer parentheses are highlighted.
Match Data Visualization
After the matcher of a keyword or anchored highlight has been
executed, the match data (whatever the search found) is visualized
using background colors in the source buffer, in the regexp, and
over the corresponding highlight rule or rules. If part of a regexp
or a highlight didn't match, it is not colored, this can for
example happen when the postfix regexp operator ? is used.
Note that an inner match group gets precedence over an outer group.
This can lead to situations where a highlight rule gets a color
that doesn't appear in the regexp or in the source buffer. For
example, the matcher "\(abc\)" will be colored with the color for
match 1, while the higlight rule `(0 a-face)' gets the color for
match 0.
Normalized keywords
The keywords presented in the interface have been normalized. For
example, instead of
("xyz" . font-lock-type-face)
the keyword
("xyz" (0 font-lock-type-face))
is shown. See font-lock-studio-normalize-keywords for details.
Explainer
The explainer echoes a human-readble description of the current
part of the Font Lock keywords. This help you to understand that
all those nil:s and t:s in the rules actually mean.
When using the auto explainer, Font Lock Studio echoes the
explanation after each command.
Edebug -- the Emacs Lisp debugger
Tight integration with Edebug allows you to single-step expressions
embedded in the keywords in the interface buffer, and it allows you
to instrument called functions for debugging in their source file.
Follow mode awareness
The search location in the source buffer is visualized by an
overlay arrow and by updating the point. If the source buffer is
visible in multiple side-by-side windows and Follow mode is
enabled, the search location will be shown in a suitable windows to
minimize scrolling.
To help with this problem, I coded up an Icicles multi-command, icicle-font-lock-keywords. It lets you do things like the following:
Cycle among the separate font-lock-keywords entries (patterns), applying them individually to see the effect of each alone.
Pick individual entries and apply them separately, to see the same thing.
Pick a set of entries and apply it, in the same order the entries appear in font-lock-keywords. You can do this for any number of sets.
Accumulate the effect of multiple sets of entries, in the order you choose them.
Revert, to see the effect of all entries together, i.e., all of font-lock-keywords.
And you can do all of that, in any order, in a single invocation of the command.
M-o is the prefix key for Facemenu and font-locking, so I put this command on key M-o I, when in Icicle mode.
I use Emacs+AUCTex for writing LaTeX documents. I have specific needs so my typical preamble is quite long. Today, I have a .tex file with only this preamble (a template so) and I use C-x C-w to write a new file from this template. It isn't the best solution because my template localization could be far away from the new file.
So is there a way to call LaTeX templates in Emacs in another (shorter) way?
EDIT : auto-insert-mode offers a way to achieve what I want but it doesn't put automatically my template (LaTeX preamble) when I create a .tex file. I have to launch M-x auto-insert. How can I automatize this based on the file extension?
At the end of VirTeX-common-initialization (essentially) TeX-master-file is added to find-file-hooks. This is the source for the %%% Local Variables: %%% mode: latex %%% TeX-master: t %%% End: stuff. (Note, that VirTeX-common-initialization is the first thing in LaTeX-common-initialization which is called in TeX-latex-mode being an alias for latex-mode.)
To get ride of the automagically added comments you can remove the hook:
(add-hook 'TeX-mode-hook '(lambda ()
(remove-hook 'find-file-hooks (car find-file-hooks) 'local)))
That looks like a hack. But adding TeX-master-file is quite hard-coded without user-options. So, it seems to me that you have no other chance.
After that correction the auto-insert stuff works automagically.
(At least for me.)
But, I have replaced the entries in auto-insert-alist. Meaning, instead of
(define-auto-insert "\\.tex$" "my-latex-template.tex")
I have something like that:
(let ((el (assoc 'latex-mode auto-insert-alist)))
(if el
(setcdr el "/c/temp/autoinsert.tex")
(define-auto-insert "\\.tex$" "/c/temp/autoinsert.tex")))
Maybe, that is important, maybe not. I've got to get home now and I cannot further investigate that.
You're probably looking for auto-insert-mode. This is orthogonal to AUCTeX - for instance, I use it to insert a class-template for .java files.
Put the following in your .emacs file:
(auto-insert-mode)
;; *NOTE* Trailing slash important
(setq auto-insert-directory "/path/to/template/directory/")
(setq auto-insert-query nil)
(define-auto-insert "\\.tex$" "my-latex-template.tex")
Of course, you could make the regular expression used as the first argument to define-auto-insert more complex e.g. to insert different preambles depending on the working directory.
I adapted this code from an example from the EmacsWiki where you can also find additional information.
This is the simplest solution I can think of:
(defun insert-latex-template()
(when (= (point-max) (point-min))
(insert-file "/path/to/your/template/file")))
(add-hook 'latex-mode-hook 'insert-latex-template)
I'm using query-replace-regexp very often and there are very long expressions from time to time.
My problem is the following:
Query replace regexp (default foo -> bar):
Is there a possibility to hide the default expression?
A simple advice does the job:
(defadvice query-replace-read-from (before no-default activate)
(setq query-replace-defaults nil))
If you use minibuffer-electric-default-mode, the default will disappear as soon as you type something into the minibuffer.
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
For context, I am something of an emacs newbie. I haven't used it for very long, but have been using it more and more (I like it a lot). Also I'm comfortable with lisp, but not super familiar with elisp.
What I need to do is bind a regular expression to a keyboard combination because I use this particular regex so often.
What I've been doing:
M-C-s ^.*Table\(\(.*\n\)*?GO\)
Note, I used newline above, but I've found that for isearch-forward-regexp, you really need to replace the \n in the regular expression with the result of C-q Q-j. This inserts a literal newline (without ending the command) enabling me to put a newline into the expression and match across lines.
How can I bind this to a key combination?
I vaguely understand that I need to create an elisp function which executes isearch-forward-regexp with the expression, but I'm fuzzy on the details. I've searched google and found most documentation to be a tad confusing.
How can I bind a regular expression to a key combination in emacs?
Mike Stone had the best answer so far -- not exactly what I was looking for but it worked for what I needed
Edit - this sort of worked, but after storing the macro, when I went back to use it later, I couldn't use it with C-x e. (i.e., if I reboot emacs and then type M-x macro-name, and then C-x e, I get a message in the minibuffer like 'no last kbd macro' or something similar)
#Mike Stone - Thanks for the information. I tried creating a macro like so:
C-x( M-C-s ^.*Table\(\(.*C-q C-J\)*?GO\) C-x)
This created my macro, but when I executed my macro I didn't get the same highlighting that I ordinarily get when I use isearch-forward-regexp. Instead it just jumped to the end of the next match of the expression. So that doesn't really work for what I need. Any ideas?
Edit: It looks like I can use macros to do what I want, I just have to think outside the box of isearch-forward-regexp. I'll try what you suggested.
You can use macros, just do C-x ( then do everything for the macro, then C-x ) to end the macro, then C-x e will execute the last defined macro. Then, you can name it using M-x name-last-kbd-macro which lets you assign a name to it, which you can then invoke with M-x TESTIT, then store the definition using M-x insert-kbd-macro which will put the macro into your current buffer, and then you can store it in your .emacs file.
Example:
C-x( abc *return* C-x)
Will define a macro to type "abc" and press return.
C-xeee
Executes the above macro immediately, 3 times (first e executes it, then following 2 e's will execute it twice more).
M-x name-last-kbd-macro testit
Names the macro to "testit"
M-x testit
Executes the just named macro (prints "abc" then return).
M-x insert-kbd-macro
Puts the following in your current buffer:
(fset 'testit
[?a ?b ?c return])
Which can then be saved in your .emacs file to use the named macro over and over again after restarting emacs.
I've started with solving your problem literally,
(defun search-maker (s)
`(lambda ()
(interactive)
(let ((regexp-search-ring (cons ,s regexp-search-ring)) ;add regexp to history
(isearch-mode-map (copy-keymap isearch-mode-map)))
(define-key isearch-mode-map (vector last-command-event) 'isearch-repeat-forward) ;make last key repeat
(isearch-forward-regexp)))) ;`
(global-set-key (kbd "C-. t") (search-maker "^.*Table\\(\\(.*\\n\\)*?GO\\)"))
(global-set-key (kbd "<f6>") (search-maker "HELLO WORLD"))
The keyboard sequence from (kbd ...) starts a new blank search. To actually search for your string, you press last key again as many times as you need. So C-. t t t or <f6> <f6> <f6>. The solution is basically a hack, but I'll leave it here if you want to experiment with it.
The following is probably the closest to what you need,
(defmacro define-isearch-yank (key string)
`(define-key isearch-mode-map ,key
(lambda ()
(interactive)
(isearch-yank-string ,string)))) ;`
(define-isearch-yank (kbd "C-. t") "^.*Table\\(\\(.*\\n\\)*?GO\\)")
(define-isearch-yank (kbd "<f6>") "HELLO WORLD")
The key combos now only work in isearch mode. You start the search normally, and then press key combos to insert your predefined string.
#Justin:
When executing a macro, it's a little different... incremental searches will just happen once, and you will have to execute the macro again if you want to search again. You can do more powerful and complex things though, such as search for a keyword, jump to the beginning of the line, mark, go to end of the line, M-w (to copy), then jump to another buffer, then C-y (paste), then jump back to the other buffer and end your macro. Then, each time you execute the macro you will be copying a line to the next buffer.
The really cool thing about emacs macros is it will stop when it sees the bell... which happens when you fail to match an incremental search (among other things). So the above macro, you can do C-u 1000 C-x e which will execute the macro 1000 times... but since you did a search, it will only copy 1000 lines, OR UNTIL THE SEARCH FAILS! Which means if there are 100 matches, it will only execute the macro 100 times.
EDIT: Check out C-hf highlight-lines-matching-regexp which will show the help of a command that highlights everything matching a regex... I don't know how to undo the highlighting though... anyways you could use a stored macro to highlight all matching the regex, and then another macro to find the next one...?
FURTHER EDIT: M-x unhighlight-regexp will undo the highlighting, you have to enter the last regex though (but it defaults to the regex you used to highlight)
In general, to define a custom keybinding in Emacs, you'd write
(define-key global-map (kbd "C-c C-f") 'function-name)
define-key is, unsurprisingly, the function to define a new key. global-map is the global keymap, as opposed to individual maps for each mode. (kbd "C-c C-f") returns a string representing the key sequence C-c C-f. There are other ways of doing this, including inputting the string directly, but this is usually the most straightforward since it takes the normal written representation. 'function-name is a symbol that's the name of the function.
Now, unless your function is already defined, you'll want to define it before you use this. To do that, write
(defun function-name (args)
(interactive)
stuff
...)
defun defines a function - use C-h f defun for more specific information. The (interactive) there isn't really a function call; it tells the compiler that it's okay for the function to be called by the user using M-x function-name and via keybindings.
Now, for interactive searching in particular, this is tricky; the isearch module doesn't really seem to be set up for what you're trying to do. But you can use this to do something similar.