Matching braces in Emacs - emacs

In GNU Emacs there is a feature to highlight matching brackets in code with the same colour.
However when the code which the brackets enclose is really long with several nested if's for's etc. then this feature is not really useful since one of the brackets will not be visible.
Say I have the following,
for(int i=0; i< N; ++i)
{
/*Long code*/
}
If my cursor is on the } brace I would like to have some feature which will enable me to jump / see the { brace, and then , if satisfied, come back to the } brace for any future coding.
Is this possible in Emacs?

This is actually a very standard binding: C-M-f and C-M-b to go back and forwards by default. In most modes C-M-f will take you forwards to the matching brace and C-M-b will take you backwards to the matching brace. This also works for things like quotes, pretty much the same way.
These bindings are easy to remember if you already use C-f and C-b for navigation. (If you don't, you should.) They're just like moving forward and backwards by a character lifted to moving by expression (which depends on mode).

The first thing that might help is knowing about this option, if you don't already: blink-matching-paren-distance. If the sexp is very large then you need to increase the option value, or else paren matching gives up too soon and it shows a mismatch when there is no mismatch.
The second thing that can help is to be sure that blink-matching-paren and blink-matching-paren-on-screen are both non-nil. Then, to see the opening delimiter, just delete the closing delimiter and then type it again. When you insert it, the opening one will be made evident.

backward-sexp is what I use. bound to ESC-left. Then ESC-right to get back to where you were

Try mic paren which shows matching parenthesis code even if found outside the present screen.

(defun px-match-paren (arg)
"Go to the matching paren if on a paren; otherwise insert <key>."
(interactive "p")
(cond
((char-equal 41 (char-before)) (backward-list 1))
((char-equal 125 (char-before)) (backward-list 1))
((and
(char-equal 123 (char-before))
(char-equal 10 (char-after)))
(backward-char 1) (forward-list 1))
((looking-at "\\s\(") (forward-list 1))
((looking-at "\\s\)") (backward-list 1))
(t (self-insert-command (or arg 1)))))
The <key> to witch you bind this command will toggle opening and closing brace if point is before or after it, otherwise insert <key> (much like vi's "%")
I also bind C-<key> to forward-sexp and C-S-<key> to backward-sexp so I can really quickly navigate through functions in the file.

Related

emacs equivalent of ct

looking for an equivalent cut and paste strategy that would replicate vim's 'cut til'. I'm sure this is googleable if I actually knew what it was called in vim, but heres what i'm looking for:
if i have a block of text like so:
foo bar (baz)
and I was at the beginning of the line and i wanted to cut until the first paren, in visual mode, I'd do:
ct (
I think there is probably a way to look back and i think you can pass more specific regular expressions. But anyway, looking for some emacs equivalents to doing this kind of text replacement. Thanks.
Here are three ways:
Just type M-dM-d to delete two words. This will leave the final space, so you'll have to delete it yourself and then add it back if you paste the two words back elsewhere.
M-z is zap-to-char, which deletes text from the cursor up to and including a character you specify. In this case you'd have to do something like M-2M-zSPC to zap up to and including the second space character.
Type C-SPC to set the mark, then go into incremental search with C-s, type a space to jump to the first space, then C-s to search forward for the next space, RET to terminate the search, and finally C-w to kill the text you selected.
Personally I'd generally go with #1.
as ataylor said zap-to-char is the way to go, The following modification to the zap-to-char is what exactly you want
(defun zap-up-to-char (arg char)
"Like standard zap-to-char, but stops just before the given character."
(interactive "p\ncZap up to char: ")
(kill-region (point)
(progn
(search-forward (char-to-string char) nil nil arg)
(forward-char (if (>= arg 0) -1 1))
(point))))
(define-key global-map [(meta ?z)] 'zap-up-to-char) ; Rebind M-z to our version
BTW don't forget that it has the ability to go backward with a negative prefix
That sounds like zap-to-char in emacs, bound to M-z by default. Note that zap-to-char will cut all the characters up to and including the one you've selected.

How can you modify two matching delimiters at once with Emacs?

While this question concerns the formatting of LaTeX within Emacs (and maybe Auctex), I believe this can be applied to more general situations in Emacs concerning delimiters like parentheses, brackets, and braces.
I am looking to be able to do the following with Emacs (and elisp), and don't know where to begin. Say I have:
(This is in parentheses)
With some keybinding in Emacs, I want Emacs to find the matching delimiter to whichever one is by my cursor (something I know Emacs can do since it can highlight matching delimiters in various modes) and be able to change both of them to
\left( This is in parentheses \right)
The delimiters I would like this to work with are: (...), [...], \lvert ... \rvert, \langle ... \rangle, \{ ... \}. What elisp would I need to accomplish this task?
More general ways to handle matching delimiters are welcome.
Evaluate the command below in Emacs. After reloading you can put the point (text cursor) immediately after a closing paren. Then do M-x replace-matching-parens to replace the closing ) with \right) and the matching start paren ( with \left(.
(defun replace-matching-parens ()
(interactive)
(save-excursion
(let ((end-point (point)))
(backward-list)
(let ((start-point (point)))
(goto-char end-point)
(re-search-backward ")" nil t)
(replace-match " \\\\right)" nil nil)
(goto-char start-point)
(re-search-forward "(" nil t)
(replace-match "\\\\left( " nil nil)))))
The interactive bit indicates that I want a "command", so it can be executed using M-x. To avoid the cursor ending up in a strange place after execution I'm wrapping the logic in save-excursion. The point jumps back to the opening paren using backward-list and holds on to the start and end positions of the paren-matched region. Lastly, starting at the end and working backwards I replace the strings. By replacing backwards rather than forwards I avoid invalidating end-point before I need it.
Generalizing this to handle different kinds of delimiters shouldn't be too bad. backward-list ought to work with any pair of strings emacs recognizes as analogues of ( and ). To add more parenthesis-like string pairs, check out set-syntax-table in this Parenthesis Matching article.
Use global-set-key to setup a key binding to replace-matching-parens.
Fair warning: replace-matching-parens is the first elisp command I've implemented, so it may not align with best practices. To all the gurus out there, I'm open to constructive criticism.

emacs: evaluate blink-matching-open when cursor highlights a parenthesis

Recently while editing lisp code in emacs, I have been frustrated in tracking matching parenthesis. (show-paren-mode t) helps when the matching parenthesis is visable within the buffer along with its match, and (setq blink-matching-paren t) is helpful when writing the matching parenthesis. Is there a way to hook show-paren-mode so that the blink-mathing-open function evaluates as part of the "show" process? In this manner, I can place the cursor up to a parenthesis and know what it matches against without deleting and retyping it.
Thanks,
SetJmp
Try this
(defadvice show-paren-function (after blink activate)
(when (= ?\) (char-before (point)))
(blink-matching-open)))
Or, just use C-M-b and C-M-f to move back and forth between the point and the corresponding parenthesis.
My favorite paren package is mic-paren, which shows you the matching paren like you describe - it even works when the matching paren is offscreen (it shows some info in the echo area).
Download and put somewhere in your load-path, and add this to your .emacs:
(require 'mic-paren)
(paren-activate)
There are a number of configuration options you can choose from, read the comments at the top of the package.

How do you comment out all or part of a Lisp s-exp using Paredit?

When editing Lisp code, occasionally it's useful to entirely comment out a top-level definition, like this:
;(defun some-fn-which-is-broken (x)
; ...)
... or comment out only part of an s-expression, like this:
(foo x
; y
z)
... and then recompile the file and test something in the REPL, etc.
With paredit-mode enabled, this doesn't work. Here's what happens, if the point is right before the first paren below:
(defun some-fn (x)
...)
and you type a semicolon, what is entered is a semicolon and a newline:
;
(defun some-fn (x)
...)
Same with commenting out part of the s-expression:
(foo x
;
y
z)
I think that if the definition is all on one line, this works:
;(defparameter *foo* 10)
... but otherwise I can't find out how to do this. Paredit is great, I would really like to keep using it. Are there any Lispers who know a way around this, or Emacs-wizards who can whip up a bit of Emacs Lisp to bind to something like paredit-comment-out-s-expr?
If there is a more Lispy or Emacsy way of accomplishing essentially the same thing, commenting out parts of source to recompile, please, don't hesitate to suggest them!
Position the point on the first character of the whole sexp, mark the whole sexp with C-M-space, and issue M-; to do the commenting. If it is necessary to do so, your source code will also be re-formatted so that only the sexp you marked, and nothing that was also on the same line, is in a comment.
You can very easily make a simple command or even a macro to do that:
(defun comment-sexp ()
"Comment out the sexp at point."
(interactive)
(save-excursion
(mark-sexp)
(paredit-comment-dwim)))
Just a side note:
The #+ and #- reader macros are pretty nice for commenting out sexps. They allow ignoring the following sexp, if the given symbol isn't/is found in *FEATURES*. Just pick a symbol not in *FEATURES*, and use it with #+ like this:
#+nil
(defun foo ()
...)
Now, the function definition will be ignored (unless NIL is in *FEATURES*, which is not very likely).
As a stopgap measure, you can use C-q (quoted-insert) to insert an arbitrary character without triggering any mode-related magic. For example, in java-mode, typing parentheses reindents the current line, which is not always what I want; in such cases, I'll insert a parenthesis with C-q to preserve my indentation. (Or more often, I'll type a parenthesis, observe the indentation change, curse, undo, and re-enter with C-q.)
For commenting in general, it would probably be easier to use M-; (comment-dwim) rather than typing the semicolons manually.
You can use C-M-SPC M-; to mark the S-expression (C-M-SPC for mark-sexp) and then comment it (M-; for comment-dwim).
In paredit 23, just typing ; won't push anything it doesn't have to off the line. So it will do the right thing for your second example. And if you wanted to comment out z instead of y it would push only the closing delimiter to another line.

How to get Emacs to unwrap a block of code?

Say I have a line in an emacs buffer that looks like this:
foo -option1 value1 -option2 value2 -option3 value3 \
-option4 value4 ...
I want it to look like this:
foo -option1 value1 \
-option2 value2 \
-option3 value3 \
-option4 value4 \
...
I want each option/value pair on a separate line. I also want those subsequent lines indented appropriately according to mode rather than to add a fixed amount of whitespace. I would prefer that the code work on the current block, stopping at the first non-blank line or line that does not contain an option/value pair though I could settle for it working on a selected region.
Anybody know of an elisp function to do this?
Nobody had what I was looking for so I decided to dust off my elisp manual and do it myself. This seems to work well enough, though the output isn't precisely what I asked for. In this version the first option goes on a line by itself instead of staying on the first line like in my original question.
(defun tcl-multiline-options ()
"spread option/value pairs across multiple lines with continuation characters"
(interactive)
(save-excursion
(tcl-join-continuations)
(beginning-of-line)
(while (re-search-forward " -[^ ]+ +" (line-end-position) t)
(goto-char (match-beginning 0))
(insert " \\\n")
(goto-char (+(match-end 0) 3))
(indent-according-to-mode)
(forward-sexp))))
(defun tcl-join-continuations ()
"join multiple continuation lines into a single physical line"
(interactive)
(while (progn (end-of-line) (char-equal (char-before) ?\\))
(forward-line 1))
(while (save-excursion (end-of-line 0) (char-equal (char-before) ?\\))
(end-of-line 0)
(delete-char -1)
(delete-char 1)
(fixup-whitespace)))
In this case I would use a macro. You can start recording a macro with C-x (, and stop recording it with C-x ). When you want to replay the macro type C-x e.
In this case, I would type, C-a C-x ( C-s v a l u e C-f C-f \ RET SPC SPC SPC SPC C-x )
That would record a macro that searches for "value", moves forward 2, inserts a slash and newline, and finally spaces the new line over to line up. Then you could repeat this macro a few times.
EDIT: I just realized, your literal text may not be as easy to search as "value1". You could also search for spaces and cycle through the hits. For example, hitting, C-s a few times after the first match to skip over some of the matches.
Note: Since your example is "ad-hoc" this solution will be too. Often you use macros when you need an ad-hoc solution. One way to make the macro apply more consistently is to put the original statement all on one line (can also be done by a macro or manually).
EDIT: Thanks for the comment about ( versus C-(, you were right my mistake!
Personally, I do stuff like this all the time.
But I don't write a function to do it unless I'll be doing it
every day for a year.
You can easily do it with query-replace, like this:
m-x (query-replace " -option" "^Q^J -option")
I say ^Q^J as that is what you'll type to quote a newline and put it in
the string.
Then just press 'y' for the strings to replace, and 'n' to skip the wierd
corner cases you'd find.
Another workhorse function is query-replace-regexp that can do
replacements of regular expressions.
and also grep-query-replace, which will perform query-replace by parsing
the output of a grep command. This is useful because you can search
for "foo" in 100 files, then do the query-replace on each occurrence
skipping from file to file.
Your mode may support this already. In C mode and Makefile mode, at least, M-q (fill-paragraph) will insert line continuations in the fill-column and wrap your lines.
What mode are you editing this in?