How to properly configure Ctrl-Tab in Emacs - emacs

I converted from Visual Studio to Emacs for most of my development (mainly due to switching programming languages). However, there is one cool feature of Visual Studio that I truly miss: Ctrl-Tab between "buffers".
The ctrl-tab that in Visual Studio is not the same as C-x b in Emacs. So, it's not just a keyboard mapping issue. Here are the features of my ideal Ctrl-Tab:
Hold down ctrl hit tab, you see the next buffer before you let go of ctrl.
There is no need to hit enter.
If this is not the buffer you want, hit tab again until you see the buffer you want.
The moment that ctrl is released, the buffer ring is updated. The next buffer in the ring is the buffer where you first pressed ctrl.
I've seen some Emacs plugins that try to simulate this behavior, but #4 is the most difficult. It seems like Emacs is unable to detect when the ctrl key is released. Instead, the code waits for the user to be in the buffer for a certain time or waits for a buffer to change..and then the buffer is added to the ring. It's different enough to really frustrate me and just never use my beloved ctrl-tab again. For now I just deal with C-x b. ido-mode makes C-x b more tolerable, but I still dream of a day when I can ctrl-tab in emacs.
Has anyone out there found a way to configure Ctrl-Tab in Emacs to work like Visual Studio?

I was searching for exactly the behavior that you describe and came across
the iflipb package: http://www.emacswiki.org/emacs/iflipb and bound it to C-tab, C-S-tab.
Unfortunately it doesn't restart the cycling either after releasing the ctrl key, so in that regard is the same as the my-switch-buffer in the answer above. Any new insights into this issue are highly appreciated.

If you are using GNU Emacs 22.1 or more recent releases, \C-x<Right> fires M-x next-buffer and \C-x<Left> fires M-x previous-buffer. This page on EmacsWiki has a link to C-TAB Windows style buffer cycling. The page also talks about how to bring this behavior on older releases of Emacsen.
This question from yesterday looks very similar to what you want to achieve, except that the question talks about Notepad++ instead of Visual Studio.

I think this is close to what you want. As you mentioned, Emacs doesn't receive events for the control key, so you can't quite get the functionality you want. However, this will not record the buffer switch until you do something other than press C-tab (i.e. scroll, type something, click the mouse, use a command M-x ...):
(global-set-key (kbd "<C-tab>") 'my-switch-buffer)
(defun my-switch-buffer ()
"Switch buffers, but don't record the change until the last one."
(interactive)
(let ((blist (copy-sequence (buffer-list)))
current
(key-for-this (this-command-keys))
(key-for-this-string (format-kbd-macro (this-command-keys)))
done)
(while (not done)
(setq current (car blist))
(setq blist (append (cdr blist) (list current)))
(when (and (not (get-buffer-window current))
(not (minibufferp current)))
(switch-to-buffer current t)
(message "Type %s to continue cycling" key-for-this-string)
(when (setq done (not (equal key-for-this (make-vector 1 (read-event)))))
(switch-to-buffer current)
(clear-this-command-keys t)
(setq unread-command-events (list last-input-event)))))))

I like the cycling and toggling behavior of iflipb too, it's very much like Windows Alt-Tab behavior. However, as previously pointed out, Emacs doesn't make it easy to notice when you release the control key. This makes toggling between the top two buffers imperfect: if you press C-Tab (and release) and then C-Tab (and release), you haven't toggled between the top two. Instead, iflipb just marches further down the buffer list. But if you perform any other Emacs command between the two C-Tab events, then iflipb recognizes that it is starting over in the buffer march, so it does the toggle.
On Windows, AutoHotKey can come to the rescue and send Emacs a keystroke when you release the control key. Here's my script:
#if WinActive("ahk_class Emacs")
^Tab::
Send {Blind}^{Tab}
SetTimer, WaitForCtrlUp, 10
return
WaitForCtrlUp:
if(!GetKeyState("LControl", "P") and !GetKeyState("RControl","P"))
{
if WinActive("ahk_class Emacs")
Send ^c:
SetTimer, WaitForCtrlUp, Off
}
return
Whenever C-Tab is pressed in emacs, the script starts polling the state of the control key. When the key is released, it sends Emacs the C-c : key sequence. I have that key bound to a "null" command, which is enough to get iflipb to notice what's going on.
Here's the relevant .emacs excerpt:
; see http://www.emacswiki.org/emacs/iflipb
(require 'iflipb)
(global-set-key (kbd "<C-tab>") 'iflipb-next-buffer)
(global-set-key
(if (featurep 'xemacs) (kbd "<C-iso-left-tab>") (kbd "<C-S-tab>"))
'iflipb-previous-buffer)
(defun null-command ()
"Do nothing (other than standard command processing such as remembering this was the last command executed)"
(interactive))
(global-set-key "\C-c:" 'null-command)
So, it's kind of hacky, but it does work. Thanks to the posters at http://www.autohotkey.com/board/topic/72433-controltab/, who were trying to solve a similar problem.

Add the following to your .emacs file:
(global-set-key (kbd "<C-tab>") 'next-buffer)

Related

emacs switch to last active window?

I was wondering if there is a way in Emacs lisp to jump back to the last active window, just as popd would do in Linux?
The reason I ask is that in some environments for evaluating code (e.g. babel-repl) the editing area for the source code loses focus to the REPL once the REPL is launched. I'd like to change its behavior and switch the focus back to the editing area, e.g., by adding an additional command in elisp to jump back to the last active window before launching the REPL.
previous-window or get-mru-window should do what you want. You can then switch with
(select-window (previous-window))
If you are interested in switching just the active buffer, you can use:
(defun prev-window ()
(interactive)
(other-window -1))
(global-set-key [(f12)] 'prev-window)
(global-set-key "\C-cp" 'prev-window)
(global-set-key "\C-cn" 'other-window)
I have this in my ~/.emacs file. CTRL+C then p (or F12) to go to the previous buffer. CTRL+C then n to go to the next buffer. The function other-buffer lets you revisit the last visited buffer. By supplying a negative number you can reverse the order that it goes through the buffer list.

Emacs 25 yank from x windows PRIMARY clipboard buffer with keyboard

Using Emacs 25 in a linux environment, I often copy text with the mouse and wish that I could paste the copied text with some command in Emacs, but currently the only way I know of is via the mouse middle click which is bound to mouse-yank-primary.
I've attempted to bind this to a key command, along with setting mouse-yank-at-point set true, but this (as I suspected) requires a mouse event to work correctly and I'm not sure how to get Emacs into believing that a mouse event went off due to a keystroke.
Anyone have any ideas? Or simply know the correct way to yank with the keyboard from the PRIMARY selection?
After looking around thanks to Christian's answer, I found select.el and came up with the following to stick into my .emacs
;; Pull from PRIMARY (same as middle mouse click)
(defun get-primary ()
(interactive)
(insert
(gui-get-primary-selection)))
(global-set-key "\C-c\C-y" 'get-primary)
Edit: As noted by Stefan, gui-get-primary-selection (and more generically, gui-get-selection) are only available in Emacs 25 and up. In Emacs 25.1 x-get-selection was made obsolete.
I just got annoyed by emacs default behavior of inserting the secondary X-selection on S-insert and found this thread. I tried to use the code from Silfheed but emacs 24 has no function like 'gui-get-primary-selection'. So I browsed the source for 'mouse-yank-primary' and came up with this alternative solution:
;; Pull from PRIMARY (same as middle mouse click)
(defun paste-primary-selection ()
(interactive)
(insert
(x-get-selection 'PRIMARY)))
(global-set-key (kbd "S-<insert>") 'paste-primary-selection)
So s-insert will insert the primary X-selection on the cursor position - just as in xterm...
Try setting this:
(setq select-enable-clipboard t)
this way the normal kill/yank commands (eg C-w and C-y) will work with the clipboard. Works both on X11 and OSX (and, I believe, Windows as well).
If you consult the documentation for that variable (for instance via C-h v) you should a sentence like this:
You can customize this variable.
where "customize" is a link you can click. This will bring you to Emacs' customaization system which provides an easier and more guided way of configuring Emacs. In particular, it will show you at lot about the controls that may be relevant to tweak. Even you do not want to control your confuguration that way, you can use it as guide to important variables to set and what they can be set to.
Hopefully this helps. It is shamelessly copied from above, but works both on 24 and 25. I have not tested in in other versions.
(if (< emacs-major-version 25)This w
;; in emacs 24 or previous
(defun paste-primary-selection ()
(interactive)
(insert (x-get-selection 'PRIMARY))
)
;; in emacs 25 and above
(defun paste-primary-selection ()
(interactive)
(insert (gui-get-primary-selection)))
)
(global-set-key (kbd "S-<insert>") 'paste-primary-selection)

How can I load changes of .el file at startup in Emacs?

I have installed Emacs under Windows 7 and want to use it in my everyday work. Unfortunately Emacs world and other text editors world are completely different and I am getting stuck on every third sequence of keys pressed on keyboard - it's doing something that I don't expect it would do.
I want to make a panic command - when I press ESC ESC ESC it stops doing everything, quitting from minibuffer, stops entering command, unhighlight regexps, etc. It already does what I want, except it killing buffers, the layout of my workspace. So I modified keyboard-escape-quit function in simple.el file (found it by C-h k ESC ESC ESC)
(defun keyboard-escape-quit ()
"Exit the current \"mode\" (in a generalized sense of the word).
This command can exit an interactive command such as `query-replace',
can clear out a prefix argument or a region,
can get out of the minibuffer or other recursive edit,
cancel the use of the current buffer (for special-purpose buffers),
or go back to just one window (by deleting all but the selected window)."
(interactive)
; Stop highlighting regexp
(unhighlight-regexp)
(cond ((eq last-command 'mode-exited) nil)
((region-active-p)
(deactivate-mark))
((> (minibuffer-depth) 0)
(abort-recursive-edit))
(current-prefix-arg
nil)
((> (recursion-depth) 0)
(exit-recursive-edit))
(buffer-quit-function
(funcall buffer-quit-function))
;((not (one-window-p t))
; (delete-other-windows))
((string-match "^ \\*" (buffer-name (current-buffer)))
(bury-buffer))))
I have byte-compiled and loaded this file and it works ok. But I can't figure out why it is not loading at startup.
You cannot modify some special built-in libraries, including simple.el. Emacs never actually loads these special libraries from their source or byte code files. Their byte code is directly included in the Emacs executable at build time, by a process called “dumping”. Emacs loads these libraries from its own binary.
Generally, should not modify any built-in libraries anyway. Your risk breakage, and your customizations are lost when you update Emacs.
Instead, do what you are supposed to do: Add custom functions to your init.el.
Hence, instead of modifying the built-in keyboard-escape-quit, create your own function, e.g. my-emergency-quit, in your init.el, and bind it to a global key, e.g. C-c q, with
(global-set-key (kbd "C-c q") #'my-emergency-quit)
Some final words of advice: I do not think that such a panic command does any good. The first rule of Emacs is: Don't panic. If you are stuck, don't try to quit and kill everything. Rather, try to find out why you are stuck, and how to get “un-stuck” by normal means. You'll learn Emacs better this way, imho.

Prevent Emacs from exiting once the exit procedure has initiated?

Is there a way to prevent Emacs from exiting once I initiate the exit process?
I occasionally fat finger C-xC-s as C-xC-c. It isn't an awful process to get back up and running but I am curious if there is a way I can stop the exit process so that I can continue uninterrupted with all my files open.
Using GNU Emacs 24.3.1. Running on Cygwin under Window 7.
There is a built-in variable you can set to a function like so:
(setq confirm-kill-emacs 'y-or-n-p)
scottfrazer's answer's the more appropriate, to me, than what follows.
Enable Emacs Lock minor mode (emacs-lock-mode) on any of the buffers, to prevent Emacs from exiting in case you accidentally hit C-xC-c.
From the Emacs Wiki page:
Emacs cannot exit until the buffer is killed or unlocked
Add (emacs-lock-mode) to your .emacs/init.el file so that this lock is enabled in every Emacs session. Adding this will lock the *scratch* buffer which will have to be unlocked in case you really want to exit Emacs.
Another way/hack of doing this is to start a process in Emacs e.g. M-xshell or have an unsaved file associated to a buffer, doing this will prompt you for confirmations when Emacs is exiting.
Yes one more, unset C-xC-c using global-unset-key. And then if you want to exit Emacs M-xkill-emacs.
Using confirm-kill-emacs, as #scottfrazer suggested, is one approach.
More generally, you can use kill-emacs-query-functions to do whatever you want in this regard. (There was no real need for them to add confirm-kill-emacs, but they did.)
You probably do not want to use kill-emacs-hook in this regard (that's what kill-emacs-query-functions is for), but be aware of it, in case you come across it using apropos etc.
One advantage of kill-emacs-query-functions over justconfirm-kill-emacs is that you can require a better confirmation: yes instead of just hitting key y. For example:
(add-hook 'kill-emacs-query-functions
(lambda () (y-or-n-p "Do you really want to exit Emacs? "))
'append)
That is what I do. It is too easy to be hitting keys and accidentally hit C-x C-c y, especially since I have similar keys bound (e.g., C-x c, C-x C-x, C-x C-y).
If you're looking for a shorter answer, I've had this line at the bottom of all my .emacs files since the last century:
(shell)
I've added the following to my emacs configuration to prevent accidental closes. I didn't like having to confirm close emacs for something like a one off commit, but I hate losing my emacs session accidentally while deep in a problem.
This adds a global state flag to emacs describing whether or not it's locked. This flag is set either automatically after emacs is open for 5 minutes, or manually using the lock-emacs command. The lock can later be removed manually by using the unlock-emacs command.
If emacs is locked, and you attempt to close it (presumably accidentally), emacs will instead give you a message saying that emacs has been locked, and cannot be closed. If it's unlocked, close behaves exactly as it does by default.
;; don't close emacs on accident
(setq emacs-locked nil)
(setq confirm-kill-emacs
(lambda (&rest args)
(if emacs-locked
(progn
(message "%s" "Emacs is locked, and cannot be closed.")
nil)
t)
))
(defun lock-emacs-silently ()
(progn
(setq emacs-locked t))
)
(defun lock-emacs ()
"Prevent emacs from being closed."
(interactive)
(progn
(lock-emacs-silently)
(message "%s" "Emacs is now locked."))
)
(defun unlock-emacs ()
"Allow emacs to be closed."
(interactive)
(progn
(setq emacs-locked 'nil)
(message "%s" "Emacs can now be closed."))
)
(run-at-time "5 minutes" nil 'lock-emacs-silently)
(Open to suggestions on how to make the confirm-kill-emacs portion nicer, I'm a lisp novice :) ).
After using this for a couple of years, I ended up going to something much simpler:
;; Unbind the normal close
(global-unset-key (kbd "C-x C-c"))
;; Require C-c 3 times before closing
(global-set-key (kbd "C-x C-c C-c C-c") 'save-buffers-kill-terminal)

How do I close an automatically opened window in Emacs?

This is probably a very naive Emacs question - I'm new to it.
When I'm evaluating a lisp expression, if there's an error the debugger automatically comes up in another window. If I have *scratch* and *info* open (the former for trying out lisp and the latter for reading about it), then the debugger opens up in the window that *info* was in. At the moment, I have to switch to that window, then change it back to *info*, before returning to *scratch*. (The same thing happens if I do C-x C-b for a list of buffers.) I'm guessing there has to be a way to just close that window without this long sequence of commands. Can anyone enlighten me?
At least here on my emacs (22.3), when the debugger pops up, its window becomes the active one. There, pressing q just quits the debugger, if that's what you want. At that point, it also gets out of recursive editing.
From what I understand, you want to close the buffer in the other window without moving your cursor from the current window.
I don't any existing function does that, so I rolled my own.
(defun other-window-kill-buffer ()
"Kill the buffer in the other window"
(interactive)
;; Window selection is used because point goes to a different window
;; if more than 2 windows are present
(let ((win-curr (selected-window))
(win-other (next-window)))
(select-window win-other)
(kill-this-buffer)
(select-window win-curr)))
You can bind it to something like "C-x K" or some other somewhat difficult-to-press key so you won't press it by mistake.
(global-set-key (kbd "C-x K") 'other-window-kill-buffer)
I use this a LOT! (for Help buffers, Compilation buffers, Grep buffers, and just plain old buffers I want to close now, without moving the point)
I'm usually using the delete-other-windows command. C-x 1.
It's so regullar, that I rebinded to F4.
Official docs: https://www.gnu.org/software/emacs/manual/html_node/emacs/Change-Window.html#Change-Window
HTH
Using winner mode, you can use the keybinding C-C left arrow to return to the previous window configuration. Of course, this doesn't actually kill the new buffer, but it does hide it.
I think you're looking for C-x 4 C-o, which displays a buffer in the "other" window without switching to it.
As mentioned above, in the case of the backtrace buffer you probably want to exit from it with q, to get out of the recursive edit.
Try to use popwin-mode. It is really good about closing windows automatically.
I want to describe how mechanism work|
You open undo-tree-visualize than you find your correct branch, after that when you change your active window which has cursor via switch-window undo-tree related buffer will close other window automatically.
One possible solution is to use a window management package. Store your "preferred" window arrangement, and after the debugger/buffer window pops up and you're done with it, revert to your preferred arrangement.
There are a bunch of packages to choose from, see: switching window configurations on the wiki.
Additionally, you might want to figure out the actions you commonly do that trigger the extra (unwanted) window popping up, and use that to trigger saving your window configuration just before the window pops up.
If you want to roll your own (it's pretty easy), you can just save off the window configuration, and restore it like so:
(setq the-window-configuration-i-want (current-window-configuration))
(global-set-key (kbd "<f7>")
(lambda () (interactive)
(set-window-configuration the-window-configuration-i-want)))
The trick is figuring out where to put the setting of the-window-configuration-i-want.
Thanks go to #spk for a nice function. I merely modified it to also close the window too and bound it to the already nice set of window control functions found in evil-windows (via "C-w"):
(use-package evil
:bind (:map evil-window-map ("O" . delete-most-recent-window))
:preface
(defun delete-most-recent-window ()
"Kill the buffer in the most recent window."
(interactive)
;; Window selection is used because point goes to a different window
;; if more than 2 windows are present
(let ((win-curr (selected-window))
(win-other (next-window)))
(select-window win-other)
(kill-this-buffer)
(delete-window) ; <-- Added this
(select-window win-curr))))