How can can I get emacs to insert closing braces automatically - emacs

I've just started using emacs, and there's one feature I'd really like, and searching around a bit was fruitless. I hope someone else has done this because I don't want to learn elisp just yet.
void foo()<cursor>
I would like typing an "{" to cause this to happen
void foo(){
<cursor>
}
I would like this to only happen in cc-mode, and only at the end of a line when not in a string/comment/etc
The first thing that came to mind was rebinding "{" to do this always(I could figure out how to do this myself), but it would be hard to make it only happen at the right time.
any hints would be appreciated.

on latest emacs you can use :
electric-pair-mode is an interactive compiled Lisp function.
(electric-pair-mode &optional ARG)
Automatically pair-up parens when inserting an open paren.
this is integrated in Emacs 24.1 (actually CVS)

This will do it:
(defun my-c-mode-insert-lcurly ()
(interactive)
(insert "{")
(let ((pps (syntax-ppss)))
(when (and (eolp) (not (or (nth 3 pps) (nth 4 pps)))) ;; EOL and not in string or comment
(c-indent-line)
(insert "\n\n}")
(c-indent-line)
(forward-line -1)
(c-indent-line))))
(define-key c-mode-base-map "{" 'my-c-mode-insert-lcurly)

turn on electric-pair-mode in emacs 24 or newer version.
(electric-pair-mode 1)

I heartily recommend you to try out the excellent autopair minor mode - it does a lot more than simply inserting braces and makes Emacs a lot more IDE like in that area. I guess combining it with the electric braces setting in cc-mode will give you more or less the behavior you seek.

Try yasnippet (or on the Emacs Wiki page yasnippet). There are many packages for Emacs which support doing this kind of thing, but yasnippet seems to have momentum currently and is very extensible. Check out the videos.

You will need to delve into emacs-lisp to do this exactly as you wish, since YASnippet will do something nice for you but not exactly what you're asking for.
I think the simplest way to do this would be to bind a function to the RET key, in the cc-mode key-map.
The function should check to that the previous character is an { and if so, perform the required RET, RET, TAB, }, Up, TAB to get the cursor where you want and the closing } inserted.
You can make the feature more robust by having it check for a balanced closing } but this would be more complicated, and I'd recommend seeing how it feels without this additional polishing feature.
If you like I can write the function and the key-map binding for you, but since you asked for an idea of how it's done, I'll leave it up to you to ask for more assistance if you need it.
Alternatively, I find that autopair.el does this nicely enough for me, and I do the newlines myself ;)

You might want to keep the option of an empty function body, in which case you would want the closing brace to stay on the same line. If that is the case, then you can try this alternative solution:
Rely on the packages mentioned in the previous replies to automatically add the closing brace.
When you want to add statements to the function body, you press the Return key (while the automatically added closing brace is still under the cursor). The 'Return' key is bound as follows:
;; automatic first line in function
(defun my-c-mode-insert-funline ()
(interactive)
(newline-and-indent)
(when (looking-at "}")
(newline-and-indent)
(forward-line -1)
(c-indent-line)))
(global-set-key (kbd "RET") 'my-c-mode-insert-funline)

Related

How can I automatically close brackets in Emacs? [duplicate]

I've just started using emacs, and there's one feature I'd really like, and searching around a bit was fruitless. I hope someone else has done this because I don't want to learn elisp just yet.
void foo()<cursor>
I would like typing an "{" to cause this to happen
void foo(){
<cursor>
}
I would like this to only happen in cc-mode, and only at the end of a line when not in a string/comment/etc
The first thing that came to mind was rebinding "{" to do this always(I could figure out how to do this myself), but it would be hard to make it only happen at the right time.
any hints would be appreciated.
on latest emacs you can use :
electric-pair-mode is an interactive compiled Lisp function.
(electric-pair-mode &optional ARG)
Automatically pair-up parens when inserting an open paren.
this is integrated in Emacs 24.1 (actually CVS)
This will do it:
(defun my-c-mode-insert-lcurly ()
(interactive)
(insert "{")
(let ((pps (syntax-ppss)))
(when (and (eolp) (not (or (nth 3 pps) (nth 4 pps)))) ;; EOL and not in string or comment
(c-indent-line)
(insert "\n\n}")
(c-indent-line)
(forward-line -1)
(c-indent-line))))
(define-key c-mode-base-map "{" 'my-c-mode-insert-lcurly)
turn on electric-pair-mode in emacs 24 or newer version.
(electric-pair-mode 1)
I heartily recommend you to try out the excellent autopair minor mode - it does a lot more than simply inserting braces and makes Emacs a lot more IDE like in that area. I guess combining it with the electric braces setting in cc-mode will give you more or less the behavior you seek.
Try yasnippet (or on the Emacs Wiki page yasnippet). There are many packages for Emacs which support doing this kind of thing, but yasnippet seems to have momentum currently and is very extensible. Check out the videos.
You will need to delve into emacs-lisp to do this exactly as you wish, since YASnippet will do something nice for you but not exactly what you're asking for.
I think the simplest way to do this would be to bind a function to the RET key, in the cc-mode key-map.
The function should check to that the previous character is an { and if so, perform the required RET, RET, TAB, }, Up, TAB to get the cursor where you want and the closing } inserted.
You can make the feature more robust by having it check for a balanced closing } but this would be more complicated, and I'd recommend seeing how it feels without this additional polishing feature.
If you like I can write the function and the key-map binding for you, but since you asked for an idea of how it's done, I'll leave it up to you to ask for more assistance if you need it.
Alternatively, I find that autopair.el does this nicely enough for me, and I do the newlines myself ;)
You might want to keep the option of an empty function body, in which case you would want the closing brace to stay on the same line. If that is the case, then you can try this alternative solution:
Rely on the packages mentioned in the previous replies to automatically add the closing brace.
When you want to add statements to the function body, you press the Return key (while the automatically added closing brace is still under the cursor). The 'Return' key is bound as follows:
;; automatic first line in function
(defun my-c-mode-insert-funline ()
(interactive)
(newline-and-indent)
(when (looking-at "}")
(newline-and-indent)
(forward-line -1)
(c-indent-line)))
(global-set-key (kbd "RET") 'my-c-mode-insert-funline)

function similar to other-buffer but with filtering

I'm looking for a way to include some filtering in the other-buffer method in emacs.
Currently calling other-buffer pulls up the last most recent buffer, but the problem with this is that buffers that get modified by external processes keep coming up as other-buffer. I would like to implement some sort of filtering in other-buffer.
Currently I use evil with C-^ bound to other-buffer, and I have some tail.el buffers active, and when I try to switch bufffers the tail buffers keep popping up.
Is there some alternative to other-buffer or could someone scratch up some code to implement this, Thanks.
What has worked for me is winner-mode - it's like an undo, but for window configurations.
Here's my setup:
(winner-mode)
(global-set-key (kbd "<f7>") 'winner-undo)
(global-set-key (kbd "C-<f7>") 'winner-redo)
Also I'd recommend other-window on some very cheap shortcut, since it's
a command that's used a lot.
I've put it on C-p, since I didn't appreciate the inconsistency
that one of the direction keys is so far away from others.
I've got previous-line on C-h instead, so now
my direction keys are n h f b - they're almost together!
And I didn't really miss the defaults on C-h, since f1
has the same functionality.
Ok so I got some workable solution but its not perfect it using bits from this answer:
emacs lisp, how to get buffer major mode?
(defun buffer-mode (buffer-or-string)
"Returns the major mode associated with a buffer."
(with-current-buffer buffer-or-string (format "%s" major-mode)))
(defun other-buffer-ex ()
(interactive)
(switch-to-buffer
(if (string-equal (buffer-mode (other-buffer)) "comint-mode")
(next-buffer) (other-buffer))))

Emacs close paren jumps to already existing close-paren when editing clojure code

If having this piece of code in an emacs buffer:
(if (> x 5
true
false))
When I try to edit it in order to fix the parenthesis, something very annoying is happening! When I try to add a closing parenthesis to the if condition, emacs is making the cursor jump to the closing parenthesis after 'false' instead of adding a new parenthesis after 5.
Is this part of some mode, maybe clojure-mode? Do you know how may I fix this? What is this useful for?
It sounds like you're using paredit. Did you install it like recommended on the project page?
As to what it's good for? It's good for editing lists. But you have to buy
into whe whole system, or you'll end up really confused. See the wiki
page.
Do you have this section in your ~/.emacs.el? Just remove it.
;; (require 'paredit) if you didn't install via package.el
(defun turn-on-paredit () (paredit-mode 1))
(add-hook 'clojure-mode-hook 'turn-on-paredit)
Yes, paredit is "different". It will always make sure your parenthesis balance. See http://www.emacswiki.org/emacs/PareditCheatsheet .
For your code, place the cursor beneath the first closing parenthesis and press C-left. Repeat the exercise and it will have moved to where you want it.
Cut&paste (kill & yank in emacs lingo) also allow you to manually screw with the balanced parenthesis, so until you get used to paredit it may be easier to use. Good luck!
how to verify that paredit is the offender
You can type C-h k ) while in your Lisp buffer to see what ) is bound to. If it is bound to paredit-close-round then yes paredit is the offender.
how to disable paredit when you don't know what's triggering it
Try auramo's answer in another thread
or if that doesn't work, try this:
(eval-after-load 'paredit
'(defalias 'paredit-mode 'ignore))
If you are curious about what is triggering paredit-mode in your Emacs, use M-x debug-on-entry RET paredit-mode RET
learning to live with paredit
But still I must encourage you to continue using paredit. Let's keep using paredit and let's see solutions for problems you posed. You asked "Do you know how may I fix this?" I'll just assume you are asking how to fix that if form. Marius Kjeldahl gave you solution which uses paredit-forward-barf-sexp, now in general, if you have some Lisp code where you see that some parens are in wrong places and you want to fix that, you can simply temporarily disable paredit-mode in that buffer (by typing M-x paredit-mode) and then fix your code and then enable paredit-mode again (by typing M-x paredit-mode again). Another thing to consider is that Emacs has undo, so if you arrive at (if (> x 5 true false)) through some action, you can undo that action and start over. Undo is bound to C-z if you use CUA mode.
Still you might find bindings of C-left, C-right to be weird, so you might want to use the following setup:
(eval-after-load 'paredit
'(progn
;; paredit-forward-barf-sexp is usually bound to <C-left>, C-}.
;; here we unbind it from <C-left>
;; so that one can continue to use <C-left> for movement.
(define-key paredit-mode-map (kbd "<C-left>") nil)
;; paredit-forward-slurp-sexp is usually bound to <C-right>, C-).
;; here we unbind it from <C-right>
;; so that one can continue to use <C-right> for movement.
(define-key paredit-mode-map (kbd "<C-right>") nil)
;; paredit-backward-kill-word is bound to M-DEL but not to <C-backspace>.
;; here we bind it to <C-backspace> as well
;; because most people prefer <C-backspace> to M-DEL.
(define-key paredit-mode-map (kbd "<C-backspace>") 'paredit-backward-kill-word)))
You asked "What is this useful for?" by which you may be asking two things:
Why is paredit-close-round useful?
Why does paredit have to bind paredit-close-round to ) when it could have bound it to better keys?
Best way to think of paredit-close-round is to think of it as a counterpart to C-M-u. Move point to | in the following code and try press C-M-u several times to see what happens, and then move point to | again and try press C-M-- C-M-u (i.e. type -u while Control and Alt are on) several times to see what happens.
(when t
(when t
(blah)
(blah))
(when t
(blah | blah)
(blah))
(when t
(blah)
(blah)))
C-M-u is useful for selecting expressions; in order to select an enclosing form or forms, you press C-M-u several times and then C-M-SPC several times. C-M-- C-M-u is useful for evaluating an enclosing form; you press C-M-- C-M-u several times and then C-x C-e to eval the enclosing form.
paredit-close-round basically does what C-M-- C-M-u does.
Why is it an OK thing that paredit binds ) to a command that does something other than simply inserting a close paren? Because you are not supposed to insert a closing parenthesis by yourself. Whenever you insert an open paren, a close paren is also inserted automatically. Whenever you want to change (blah) (blah) to ((blah) (blah)), you simply select the two blah forms and press (.

Force flyspell to go to the end of the word when autocorrecting word in Emacs

I have found it annoying that flyspell seems to stay in the middle of the word when you do flyspell-auto-correct-word command. Can this be changed to force it to go to the end of the word after running the command? It might be as simple as setting a key binding to auto-complete-word and then move-forward-word which I know how to do. But this won't work in all cases because sometimes it puts the cursor behind the word if the auto-complete word was smaller than the typed word. Any help on this would be great.
Try this code:
(eval-after-load "flyspell"
'(defun flyspell-ajust-cursor-point (save cursor-location old-max)
(when (not (looking-at "\\b"))
(forward-word))))
Tested with flyspell version 1.7k, and with the version shipped with Emacs 23.2.
I looked through the (defun flyspell-auto-correct-word ...) and I can't see any good hooks or other customization points there so I think your best bet is to use C-h f defadvice:
(defadvice flyspell-auto-correct-word (after flyspell-forward-word activate) (flyspell-goto-next-error))

Emacs, changing the default reftex citation

I'd like to modify emacs' behaviour when using reftex, so that after pressing 'C-c [' and choosing a citation format the default regex that comes up is one that will give me the citation I used last (the normal behaviour is to default to the word before the cursor, which is rarely of any use). I often cite the same source many times in a row, particularly when making notes on a single paper, so this would be a nice way to save a few keystrokes, and that's what we're all using emacs for, right :)
I know a little lisp, so I expect I'll end up working out a way to do this myself eventually, but I thought it'd be worth asking around to see if anyone else has done it first, no point re-inventing the wheel. (If you do want this feature, but also don't know how to achieve it, let me know and I'll drop you an email when I've done it.)
Thanks
redifining reftex-get-bibkey-default after you have loaded reftex (e.g. in your AUCTeX mode hook) should do it. The simplest would thus be:
(defun reftex-get-bibkey-default () (car reftex-cite-regexp-hist) )
However, this will destroy the default behaviour and wouldn't return anything if your history is empty, to keep the "previous word at point" behaviour from reftex in that case and then use the history, you can redefine it this way:
(defun reftex-get-bibkey-default () (if reftex-cite-regexp-hist
(car reftex-cite-regexp-hist)
(let* ((macro (reftex-what-macro 1)))
(save-excursion
(if (and macro (string-match "cite" (car macro)))
(goto-char (cdr macro)))
(skip-chars-backward "^a-zA-Z0-9")
(reftex-this-word)))
)
)
(WARNING: This is the first elisp code I've ever written which is more than 3 lines long, it could be terrible code. But it seems to work. But any comments on style or best practices would be most appreciated.)
I've worked it out! Just add the following code to .emacs it behaves exactly as I'd hoped. If you've not cited anything before then it behaves as normal, otherwise the default citation is the last used.
(defvar reftex-last-citation nil)
(defadvice reftex-citation (after reftex-citation-and-remember-citation activate)
"Save last citation to 'reftex-last-citation after running 'reftex-citation"
(setq reftex-last-citation ad-return-value))
(defadvice reftex-get-bibkey-default (around reftex-just-return-last-citation activate)
"If there is a 'reftex-last-citation then just return that instead of running 'reftex-get-bibkey-default"
(if reftex-last-citation
(setq ad-return-value reftex-last-citation)
ad-do-it))
Thanks for the help Mortimer, without your starting point I'd never had got here!
(Just wondering, is there any reason why your solution didn't use defadvice? As I implied above, elisp is all very new to me, so it'd be useful to know the best way of doing things.)