How do I bind C-= in emacs? - emacs

This s-expression in my .emacs file does not produce the desired result:
(define-key global-map (kbd "C-=") 'djhaskin987-untab-to-tab-stop)
Why can't I bind a command to Ctrl+=?
EDIT for clarification:
I am using emacs23-nox on the standard build of urxvt-256colors for Debian, except that I have recompiled with --disable-iso405776 (or something to that effect) it so that Ctrl+Shift doesn't do the weird 'insert character' thing. I don't know if this affects anything. For example, C-M-i sends M-TAB, which I don't understand.
EDIT II:
I apologize for not making this clear. The function djhaskin987-untab-to-tab-stop has the line (interactive) in it. This part works.

The accepted answer in combination with the link in the first comment to it is enough to get started on a complete solution. The steps are:
make your terminal output escape codes for the key
make Emacs recognise the escape codes as a standard keypress
bind the keypress in a mode map
The first is very terminal and/or operating system dependent.
The link in the first comment shows some examples for X Window System. The key names are available in /usr/X11R6/include/X11/keysymdef.h (or try locate keysymdef.h), prefixed with XK_ (which should be removed for our purposes). I read that symbolic names are preferred over key literals.
I don't currently run X but I think it should look like this in your case:
XTerm.VT100.Translations: #override \
Ctrl ~Meta ~Shift <Key> equal: string(0x1b) string("[emacs-C-=")\n
The first string is the escape, the second is of your choosing.
In iTerm you can use Preferences->Keys and choose Send Escape Sequence as the Action. For example, I have:
Emacs Wiki lists some configuration methods for other terminals.
Now you can teach Emacs to recognize it as a C-=. First define-key into input-decode-map. I have a couple of helper functions:
(defun my/global-map-and-set-key (key command &optional prefix suffix)
"`my/map-key' KEY then `global-set-key' KEY with COMMAND.
PREFIX or SUFFIX can wrap the key when passing to `global-set-key'."
(my/map-key key)
(global-set-key (kbd (concat prefix key suffix)) command))
(defun my/map-key (key)
"Map KEY from escape sequence \"\e[emacs-KEY\."
(define-key function-key-map (concat "\e[emacs-" key) (kbd key)))
So then:
(my/global-map-and-set-key "C-=" 'some-function-to-bind-to)
Some keys (currently: ()\|;'`"#.,) will need escaping in the string, like C-\..

In a terminal, TAB is represented by the same byte sequence as C-i. And typically the terminal has no special byte-sequence for C-=, so it will just send a =. There is nothing that Emacs can do about it. But you might be able to teach your terminal emulator to send some special byte sequence of your choice (check the documentation of your terminal emulator for that), after which you can teach Emacs to recognize it as a C-= (with something like (define-key input-decode-map "...thebytes..." [?\C-=])).

The problem is that you use emacs in the terminal.
The terminal does not allow "C-=".
Try your function in the graphical emacs and it will work.
You will have to find another keybinding for the terminal.

You can map C-= using the default ascii codes: ^[[61;5u. Then you can bind it in Emacs either using:
(global-set-key (kbd "C-=") 'djhaskin987-untab-to-tab-stop))
or let use-package do it, e.g.:
(use-package expand-region
:ensure t
:bind (("C-=" . er/expand-region)))
I do want to thank Sam Brightman, for his wonderful solution. It's a very clean, albeit heavy-handed, approach that will work for any keys that cannot be sent via normal ascii codes. I've been wanting to get C-TAB working inside iterm2 for a long time. I was able to do it by deleting the builtin preferences keys for C-TAB/C-S-TAB and using his approach. With the following, I can be ssh'd into remote Linux boxes and quickly switch through lots of open buffers in projects, just like a desktop editor.
(use-package nswbuff
:defer 1
:after (projectile)
:commands (nswbuff-switch-to-previous-buffer
nswbuff-switch-to-next-buffer)
:config
(progn
(my/global-map-and-set-key "C-TAB" 'nswbuff-switch-to-previous-buffer)
(my/global-map-and-set-key "C-S-TAB" 'nswbuff-switch-to-next-buffer))
:init
(setq nswbuff-display-intermediate-buffers t
nswbuff-exclude-buffer-regexps '("^ "
"^\*.*\*"
"\*Treemacs.*\*"
"^magit.*:.+")
nswbuff-include-buffer-regexps '("^*Org Src")
nswbuff-start-with-current-centered t
nswbuff-buffer-list-function '(lambda ()
(interactive)
(if (projectile-project-p)
(nswbuff-projectile-buffer-list)
(buffer-list)))))

The function you're binding must be interactive. Try:
(define-key global-map (kbd "C-=")
(lambda () (interactive) (djhaskin987-untab-to-tab-stop)))

Related

How to Zoom in /out in emacs -nw (command line only) whithout having a numeric keypad (or mouse wheel)? [duplicate]

This s-expression in my .emacs file does not produce the desired result:
(define-key global-map (kbd "C-=") 'djhaskin987-untab-to-tab-stop)
Why can't I bind a command to Ctrl+=?
EDIT for clarification:
I am using emacs23-nox on the standard build of urxvt-256colors for Debian, except that I have recompiled with --disable-iso405776 (or something to that effect) it so that Ctrl+Shift doesn't do the weird 'insert character' thing. I don't know if this affects anything. For example, C-M-i sends M-TAB, which I don't understand.
EDIT II:
I apologize for not making this clear. The function djhaskin987-untab-to-tab-stop has the line (interactive) in it. This part works.
The accepted answer in combination with the link in the first comment to it is enough to get started on a complete solution. The steps are:
make your terminal output escape codes for the key
make Emacs recognise the escape codes as a standard keypress
bind the keypress in a mode map
The first is very terminal and/or operating system dependent.
The link in the first comment shows some examples for X Window System. The key names are available in /usr/X11R6/include/X11/keysymdef.h (or try locate keysymdef.h), prefixed with XK_ (which should be removed for our purposes). I read that symbolic names are preferred over key literals.
I don't currently run X but I think it should look like this in your case:
XTerm.VT100.Translations: #override \
Ctrl ~Meta ~Shift <Key> equal: string(0x1b) string("[emacs-C-=")\n
The first string is the escape, the second is of your choosing.
In iTerm you can use Preferences->Keys and choose Send Escape Sequence as the Action. For example, I have:
Emacs Wiki lists some configuration methods for other terminals.
Now you can teach Emacs to recognize it as a C-=. First define-key into input-decode-map. I have a couple of helper functions:
(defun my/global-map-and-set-key (key command &optional prefix suffix)
"`my/map-key' KEY then `global-set-key' KEY with COMMAND.
PREFIX or SUFFIX can wrap the key when passing to `global-set-key'."
(my/map-key key)
(global-set-key (kbd (concat prefix key suffix)) command))
(defun my/map-key (key)
"Map KEY from escape sequence \"\e[emacs-KEY\."
(define-key function-key-map (concat "\e[emacs-" key) (kbd key)))
So then:
(my/global-map-and-set-key "C-=" 'some-function-to-bind-to)
Some keys (currently: ()\|;'`"#.,) will need escaping in the string, like C-\..
In a terminal, TAB is represented by the same byte sequence as C-i. And typically the terminal has no special byte-sequence for C-=, so it will just send a =. There is nothing that Emacs can do about it. But you might be able to teach your terminal emulator to send some special byte sequence of your choice (check the documentation of your terminal emulator for that), after which you can teach Emacs to recognize it as a C-= (with something like (define-key input-decode-map "...thebytes..." [?\C-=])).
The problem is that you use emacs in the terminal.
The terminal does not allow "C-=".
Try your function in the graphical emacs and it will work.
You will have to find another keybinding for the terminal.
You can map C-= using the default ascii codes: ^[[61;5u. Then you can bind it in Emacs either using:
(global-set-key (kbd "C-=") 'djhaskin987-untab-to-tab-stop))
or let use-package do it, e.g.:
(use-package expand-region
:ensure t
:bind (("C-=" . er/expand-region)))
I do want to thank Sam Brightman, for his wonderful solution. It's a very clean, albeit heavy-handed, approach that will work for any keys that cannot be sent via normal ascii codes. I've been wanting to get C-TAB working inside iterm2 for a long time. I was able to do it by deleting the builtin preferences keys for C-TAB/C-S-TAB and using his approach. With the following, I can be ssh'd into remote Linux boxes and quickly switch through lots of open buffers in projects, just like a desktop editor.
(use-package nswbuff
:defer 1
:after (projectile)
:commands (nswbuff-switch-to-previous-buffer
nswbuff-switch-to-next-buffer)
:config
(progn
(my/global-map-and-set-key "C-TAB" 'nswbuff-switch-to-previous-buffer)
(my/global-map-and-set-key "C-S-TAB" 'nswbuff-switch-to-next-buffer))
:init
(setq nswbuff-display-intermediate-buffers t
nswbuff-exclude-buffer-regexps '("^ "
"^\*.*\*"
"\*Treemacs.*\*"
"^magit.*:.+")
nswbuff-include-buffer-regexps '("^*Org Src")
nswbuff-start-with-current-centered t
nswbuff-buffer-list-function '(lambda ()
(interactive)
(if (projectile-project-p)
(nswbuff-projectile-buffer-list)
(buffer-list)))))
The function you're binding must be interactive. Try:
(define-key global-map (kbd "C-=")
(lambda () (interactive) (djhaskin987-untab-to-tab-stop)))

Emacs evil-mode and ensime

I am a VIM guy - but evil-mode allowed me to productively use Emacs for my Scala development, and it did it so well that I am sort of hooked... I want to customize the environment to my liking, so I e.g. added these to my .emacs:
(define-key evil-normal-state-map (kbd "<f7>") 'ensime-typecheck-all)
(define-key evil-normal-state-map (kbd "C-]") 'ensime-edit-definition)
While in evil-normal-mode, the first line allows me to do a typecheck of my Scala code by just hitting F7, while the second one navigates me to a type/val definition via the muscle-memoried Ctrl-] (used for tags-based navigation in VIM).
My only problem is that what I've done so far is a "global" assignment - if I open a Python file, I'd want F7 to do a different thing (pyflakes or pylint). How can I assign different actions to the same key based on what kind of file is currently open in the buffer I am viewing?
In case it helps, in my .vimrc, I've done this via sections like these:
au BufNewFile,BufRead *.ml call SetupOCamlEnviron()
function! SetupOCamlEnviron()
se shiftwidth=2
"
" Remap F7 to make if the file is an .ml one
"
noremap <buffer> <special> <F7> :make<CR>
noremap! <buffer> <special> <F7> <ESC>:make<CR>
"
" Thanks to Merlin
"
noremap <buffer> <silent> <F6> :SyntasticCheck<CR>
noremap! <buffer> <silent> <F6> <ESC>:SyntasticCheck<CR>
inoremap <buffer> <C-Space> <C-x><C-o>
noremap <buffer> <C-]> :Locate<CR>
inoremap <buffer> <C-]> <ESC>:Locate<CR>
endfunction
How do I do this kind of thing in Emacs/evil?
EDIT: In search of a way to do this, I realized I can dispatch on different code when F7 is pressed in normal mode - so I wrote this Emacs lisp:
(defun current-buffer-extension ()
(if (stringp (buffer-file-name))
(file-name-extension buffer-file-name)
"Unknown"))
(defun handle-f7 ()
(interactive)
(if (string= (current-buffer-extension) "scala")
(ensime-typecheck-all)))
(define-key evil-normal-state-map (kbd "<f7>") 'handle-f7)
...which can be extended with other tool invocations as I learn more about Emacs, by adding actions based on the file extension.
Being completely new to Emacs, I am open to suggestions...
Am I on the right track here? Is there a better way to do what I want? Have I violated some principle by hooking evil-normal-mode keystrokes?
The thing you are looking for is called hook. There are plenty of hooks that emacs runs is specifics moments, and are fully customizable by user.
For instance, whenever entering a mode, a "mode-hook" is run. So you could do:
(add-hook 'python-mode-hook (lambda ()
(setq fill-column 79)
(local-set-key [(f3)] 'run-flake8)))
Hooks are the canonical way of customizing a lot of things in emacs, and there is plenty of examples around about those. In the example above, I define the key F3 to do something whenever I am in python mode.
Note that the example does not cope with evil keymap, but uses a local key that should have preference. If you want to assign a key to do different things depending on the evil state, you should either add some additional logic or make the evil-X-state-map buffer local and then change it the way you want (you could do that in the hook)
Edit: Regarding your question about if you have "violated some principle"... lets say that because of the hooks and the ability to set local variables, checking file extensions to customize behaviour is never (afaik) done other than for setting the mode (and that is done internally). Even checking the major-mode (that would be preferred to checking extension) is not done, as it is less scalable than just hooking preferences and functionality into modes.
Evil has a useful facility for mode-specific keybindings: evil-define-key. As arguments, it takes:
the state (as a quoted symbol, in your case, 'normal),
an unquoted keymap (I don't use ensime, but it's probably something like ensime-mode-map),
the key sequence, and
the command to bind.
So, to make your bindings ensime-specific (again, fiddle with the specific map name to make sure it's correct):
(evil-define-key 'normal ensime-mode-map (kbd "<f7>") #'ensime-typecheck-all)
(evil-define-key 'normal ensime-mode-map (kbd "C-]") #'ensime-edit-definition)
You can also bind f7 to something else for use with python (again, tinker with the map names and commands accordingly):
(evil-define-key 'normal python-mode-map (kbd "<f7>") #'run-flake8)
(Aside: I'm using the sharp-quote (#', which is lisp-shorthand for "function") in front of command names rather than the plain quote ('). For your purposes the two are basically equivalent, but it's good to get in the habit of the former in case you start byte-compiling your setup files, as the byte-compiler will warn you if the function in question is undefined when you sharp-quote but not if you simple-quote. See a related discussion on the Emacs Stack Exchange site.)

Emacs evil-mode how to change insert-state to emacs-state automatically

I don't like the insert-state, and so I want to replace it with emacs-state. But this setting does not work:
(add-hook 'evil-insert-state-entry-hook 'evil-emacs-state)
After press o or cw, I am still in insert-state.
How about this approach:
(setq evil-insert-state-map (make-sparse-keymap))
(define-key evil-insert-state-map (kbd "<escape>") 'evil-normal-state)
I use it and it seems to do the trick. And since you're not changing the state, you retain state-related configs like cursor-color, etc.
Surprised nobody posted this yet...
(defalias 'evil-insert-state 'evil-emacs-state)
Anything that tries to call evil-insert-state will just end up calling evil-emacs-state. Works for i, a, o, O, etc.
There is now a bulitin way for Evil to do this
(setq evil-disable-insert-state-bindings t)
before loading evil
Reference: https://github.com/noctuid/evil-guide#use-some-emacs-keybindings
Tell me how this works. It's a hack that basically replaces the function evil-insert-state with evil-emacs-state. The problem is figuring out how to exit emacs state with the escape key. For instance, this version works fine when I exit emacs state with the ESC key, but not when I try to do the same with C-[:
; redefine emacs state to intercept the escape key like insert-state does:
(evil-define-state emacs
"Emacs state that can be exited with the escape key."
:tag " <EE> "
:message "-- EMACS WITH ESCAPE --"
:input-method t
;; :intercept-esc nil)
)
(defadvice evil-insert-state (around emacs-state-instead-of-insert-state activate)
(evil-emacs-state))
If the point is that you want to use normal Emacs editing when doing the kind of tasks vi uses insert mode for, then wiping the insert mode dictionary accomplishes this. It is probably desirable that the ESC key gets you back into normal mode and have C-z get you into Emacs state; Leo Alekseyev posts a tiny bit of code that does this:
(setcdr evil-insert-state-map nil)
(define-key evil-insert-state-map
(read-kbd-macro evil-toggle-key) 'evil-emacs-state)
which I use and like. There are two potential disadvantages to being in insert mode rather than emacs mode:
You can't use the ESC key as another, prefixed way of ALT-keymapping; and
There is a risk (so I am told, though I haven't encountered this) if you are accessing Emacs through a tty, that Emacs will interpret ALT-modified keys as ESC followed by the character, which gives a difference in insert mode than in emacs mode.
I don't think either problem is serious.
How I became a unix chad:
;; unix chad setting
(defalias 'evil-insert-state 'evil-emacs-state)
(define-key evil-emacs-state-map (kbd "<escape>") 'evil-normal-state)
(setq evil-emacs-state-cursor '(bar . 1))
From the documentation about evil-emacs-state-entry-hook:
Hooks to run when entering Emacs state.
So the evil-emacs-state function is run when you enter emacs-state (with C-z).
You can, however, do this:
(define-key evil-normal-state-map (kbd "i") 'evil-emacs-state)
The problem now is exiting emacs state. I remember there were some problems binding ESC in emacs state, as ESC is used as META, and (IIRC) Evil uses some "special" code to intercept the ESC key.
EDIT: following your comment: this one should work:
(fset 'evil-insert-state 'evil-emacs-state)

Cannot get to bind Enter to 'newline-and-indent in Emacs !!! Very annoying

Cannot get to bind Enter to newline-and-indent in Emacs !!! Very annoying.
I already tried everything on the following thread by changing 'mode' to ruby and still nothing:
How do I make Emacs auto-indent my C code?
I know that the problem is the RETURN key, since if I bind to something else, works fine.
I tried [enter], (kbd "enter"), (read-kbd-macro "enter"), (kbd "RET")
Follow-up 1.
This is what I get from C-hkRET
RET runs the command newline, which is an interactive compiled Lisp
function.
It is bound to RET.
(newline &optional ARG)
Insert a newline, and move to left margin of the new line if it's blank.
If use-hard-newlines' is non-nil, the newline is marked with the
text-propertyhard'.
With ARG, insert that many newlines.
Call auto-fill-function' if the current column number is greater
than the value offill-column' and ARG is nil.
I dont know what to make of it or how to figure out if it's a global
or local binding that gets in the way. trying to remap C-j
also doesnt work.
As a previous comment says, use C-h k (describe-key) to see what the key is bound to at the point when it's not doing what you want. The (kbd "foo") syntax will be correct for whichever foo describe-key refers to it as.
Chances are that you are simply not defining that key in the appropriate keymap.
Note that major and minor mode keymaps take precedence over the global keymap, so you shouldn't necessarily be surprised if a global binding is overridden.
edit:
Myself, I have a hook function for common behaviours for all the programming modes I use, and it includes the sort of remapping you're after. The relevant part looks like this:
(defun my-coding-config ()
(local-set-key (kbd "RET") (key-binding (kbd "M-j")))
(local-set-key (kbd "<S-return>") 'newline)
)
(mapc
(lambda (language-mode-hook)
(add-hook language-mode-hook 'my-coding-config))
'(cperl-mode-hook
css-mode-hook
emacs-lisp-mode-hook
;; etc...
))
See Daimrod's answer for the explanation of why I'm re-binding RET to the current binding of M-j -- although I'm using comment-indent-new-line (or similar) instead of newline-and-indent (or similar), which does what I want in both comments and non-comments.
In Emacs 24, programming modes seem to derive from prog-mode, so you could probably (un-tested) reduce that list to prog-mode-hook plus any exceptions for third-party modes which don't yet do that.
As said earlier, use C-hkC-j because
C-j is the standard key to do newline-and-indent.
If you open a new file, activate ruby-mode and try the previous
command you will see why it doesn't work. Because ruby-mode doesn't
have newline-and-indent but rather
reindent-then-newline-and-indent. Yes that's stupid but you can either ask
to the maintener to change it, or accept it.
However I suggest you to use C-j to do it because
ruby-mode is not the only mode to do so, like paredit-mode which
uses paredit-newline.

Assign multiple Emacs keybindings to a single command?

I'm giving ErgoEmacs mode a try to see if I can use Emacs more comfortably. Some of its keybindings are fairly intuitive, but in many cases I don't want to outright replace the defaults.
For example, in the context of ErgoEmacs' navigation shortcut structure, M-h makes sense as a replacement for C-a--but I want to be able to use both, not just M-h. I tried simply duplicating the commands:
;; Move to beginning/ending of line
(defconst ergoemacs-move-beginning-of-line-key (kbd "C-a")) ; original
(defconst ergoemacs-move-end-of-line-key (kbd "C-e")) ; original
(defconst ergoemacs-move-beginning-of-line-key (kbd "M-h")) ; ergoemacs
(defconst ergoemacs-move-end-of-line-key (kbd "M-H")) ; ergoemacs
But Emacs simply overwrites the first keybinding with the second. What's the best way to address this?
To re-post reply from ergo-emacs mailing list:
Xah Lee said:
that's very easy.
in the
ergoemacs-mode.el file, there's this
line (load "ergoemacs-unbind") just
comment it out. That should be all
you need to do. However, note that
ErgoEmacs keybinding defines those
common shortcuts such as Open, Close,
New, Save... with keys Ctrl+o,
Ctrl+w, Ctrl+n, Ctrl+s etc. About 7 of
them or so. So, i think some of these
will hit on emacs traditional
bindings with Ctrl. if you are new to
ErgoEmacs and trying to explore it,
you might just try starting with few
keys. this page might have some
useful info:
http://code.google.com/p/ergoemacs/wiki/adoption
thanks for checking out ErgoEmacs!
Xah ∑ http://xahlee.org/
As it turns out, ErgoEmacs uses two files to define the keybinding. One is the main ergoemacs-mode.el file, and the other is the specific keyboard layout you select (e.g. ergoemacs-layout-us.el). The latter document creates a constant, which the former uses to create the keybinding. So while I thought I was duplicating the keybinding, I was actually changing the constant which was subsequently used for that purpose.
Solution:
In ergomacs-mode.el:
;; Move to beginning/ending of line
(define-key ergoemacs-keymap ergoemacs-move-beginning-of-line-key 'move-beginning-of-line)
(define-key ergoemacs-keymap ergoemacs-move-end-of-line-key 'move-end-of-line)
(define-key ergoemacs-keymap ergoemacs-move-beginning-of-line-key2 'move-beginning-of-line) ; new
(define-key ergoemacs-keymap ergoemacs-move-end-of-line-key2 'move-end-of-line) ; new
In ergoemacs-layout-us.el:
;; Move to beginning/ending of line
(defconst ergoemacs-move-beginning-of-line-key (kbd "M-h"))
(defconst ergoemacs-move-end-of-line-key (kbd "M-H"))
(defconst ergoemacs-move-beginning-of-line-key2 (kbd "C-a")) ; new
(defconst ergoemacs-move-end-of-line-key2 (kbd "C-e")) ; new
Huh? Is having one and only one way for every function some golden principle of ErgoEmacs? Because normal keybinding works exactly the opposite way: you name one key at a time and specify what it should do. If a mode defines a global variable to mean "the key that end-of-line is bound to", then of course there can be only one value, but with the normal binding commands you can bind the same function to as many combinations as you like. In fact, every keybinding I have ever seen used looked either like this
(global-set-key [(meta space)] 'just-one-space)
or like this
(add-hook 'c-mode-hook 'my-c-mode-hook)
(defun my-c-mode-hook ()
(define-key c-mode-map [(control c) b] 'c-insert-block))
if it's only for a specific mode.