Emacs, use Delete key to delete selection - emacs

First of all, this is not a dup of
how to delete region with [delete] key in emacs, which is for Emacs 23, and the answer is Emacs cua-mode.
How configure delete-selection-mode to only delete?, which is for Emacs 22, and the issue is not reproducable.
I'm talking about the Emacs Delete Selection Mode, I used to be able to delete selection of text by just pressing Delete key. I found my proof here.
In order to set emacs to delete the selected text when you press DEL, Ctrl-d, or Backspace, add the following to your .emacs file:
(delete-selection-mode t)
However, now, with my Emacs 24, the Delete key doesn't work on the selection anymore (only Backspace does). This is really annoying because for all editors that I use, pressing the Delete key will delete the text selection. I don't understand why Emacs has to be so different and inconvenient. Anyway,
Any easy way to fix it? I don't know whether the comment of the following was a joke or the actual solution:
(setq behave-like-something-actually-usable-by-humans t)
Thanks
PS, my Emacs 24 is from nightly build:
$ emacs --version | head -1
GNU Emacs 24.3.50.1
EDIT: The answer from Drew, if it is unclear to you (I got that on third attempt),
(global-set-key (kbd "<delete>") '(lambda (n) (interactive "p") (if (use-region-p) (delete-region (region-beginning) (region-end)) (delete-char n))))
works for me.

The <delete> key is bound by default to kill-line. It sounds like you want to bind it instead to delete-region. Just do it.
(global-set-key (kbd "<delete>") 'delete-region)

There appears to have been a change to the behavior of delete-char. I experienced that as well as I had bound DEL to that command. I had success binding the key to delete-forward-char instead, which implements the old behavior. See here.

In 21.4.22, I had to use the (region-active-p) function instead of (use-region-p)
(global-set-key `backspace '(lambda (n) (interactive "p") (if (region-active-p) (delete-region (region-beginning) (region-end)) (delete-backward-char n))))

Related

Why doesn't my keymap for C-c C-c work in C++?

I'm new to emacs and using emacs 24 and trying to bind C-c C-c to a function to comment out a single line. I have the following in my init.el file but it doesn't seem to work in c++.
(defun toggle-comment-on-line ()
"comment or uncomment current line"
(interactive)
(comment-or-uncomment-region (line-beginning-position) (line-end-position))
(next-line))
(global-set-key (kbd "C-c C-c") 'toggle-comment-on-line)
When I'm playing around in the scratch page it works fine and when I check with C-h k C-c C-cit displays the right function but when I'm in C++ the same command displays the text:
C-c C-c runs the command comment-region, which is an interactive
compiled Lisp function in `newcomment.el'.
It is bound to C-c C-c, <menu-bar> <C++> <Comment Out Region>.
(comment-region BEG END &optional ARG)
Comment or uncomment each line in the region.
With just C-u prefix arg, uncomment each line in region BEG .. END.
Numeric prefix ARG means use ARG comment characters.
If ARG is negative, delete that many comment characters instead.
The strings used as comment starts are built from `comment-start'
and `comment-padding'; the strings used as comment ends are built
from `comment-end' and `comment-padding'.
By default, the `comment-start' markers are inserted at the
current indentation of the region, and comments are terminated on
each line (even for syntaxes in which newline does not end the
comment and blank lines do not get comments). This can be
changed with `comment-style'.
I assume something else is overriding C++ keybindings but I don't know what or how to fix it? Does anyone have any ideas?
Yes, c++ mode has its own keymap, which overrides the global map. Use the following instead:
(define-key c++-mode-map (kbd "C-c C-c") 'toggle-comment-on-line)
I've improved your code a bit, and below there's also the
code to bind the key without an error
(it happens because you're trying to define a key in
c++-mode-map before it was defined)
(defun toggle-comment-on-line ()
"comment or uncomment current line"
(interactive)
(let ((beg (if (region-active-p)
(region-beginning)
(line-beginning-position)))
(end (if (region-active-p)
(region-end)
(line-end-position))))
(comment-or-uncomment-region beg end)
(next-line)))
(add-hook 'c++-mode-hook
(lambda()
(define-key c++-mode-map (kbd "C-c C-c") 'moo-complete)))
As a side note, I strongly recommend against binding C-c C-c,
as this is a very popular mode specific binding that's different in every mode,
but means generally confirm:
in org-mode it evaluates a babel block of code
in message-mode it sends the email
in python-mode it sends the buffer to the process
in wdired it confirms your edits to the file names
So you'll really have a headache if you bind it, unless you're
using Emacs just for c++-mode.
I've been using Emacs for 3 years now and I have comment-dwim
on C-.. I'm quite happy with it so far.
If you're willing to use a different key binding, you can use the following code:
;; Nothing to see here.
after which you can do C-a C-SPC C-n M-;.

How to Kill buffer in emacs without answering confirmation?

How to kill the buffer in emacs without being questioned.
This will kill the current visible buffer without confirmation unless the buffer has been modified. In this last case, you have to answer y/n.
(global-set-key [(control x) (k)] 'kill-this-buffer)
I use this
(defun volatile-kill-buffer ()
"Kill current buffer unconditionally."
(interactive)
(let ((buffer-modified-p nil))
(kill-buffer (current-buffer))))
(global-set-key (kbd "C-x k") 'volatile-kill-buffer) ;; Unconditionally kill unmodified buffers.
It will kill the buffer unless it's modified.
OK, I've done some poking around in the Emacs manual and found a working solution (as of Emacs 23.4.1). It's almost identical to Noufal's solution:
(defun kill-this-buffer-volatile ()
"Kill current buffer, even if it has been modified."
(interactive)
(set-buffer-modified-p nil)
(kill-this-buffer))
I've renamed the function a bit to make it a closer cousin to kill-this-buffer.
Apparently, the EmacsWiki has a page on this topic at http://www.emacswiki.org/emacs/KillBufferUnconditionally (modified in 2007), but the code is just a copy of Noufal's.
Use (kill-current-buffer) instead of (kill-this-buffer) if you want to bind it to some key. See the docs for (kill-this-buffer)
...
This command can be reliably invoked only from the menu bar,
otherwise it could decide to silently do nothing.
and (kill-current-buffer)
...
This is like ‘kill-this-buffer’, but it doesn’t have to be invoked
via the menu bar, and pays no attention to the menu-bar’s frame.
So I would put the following in my init.el:
(global-set-key (kbd "C-x k") 'kill-current-buffer)
This works at least in emacs 26.1.
I use the following piece of code -- unlike Noufal's solution of ignoring the buffer being modified or not, this will save the buffer and then kill it. It also deletes the window which makes a difference when you have several sub-windows showing -- by default it will remove the window instead of switching to some other buffer. (To use this conveniently, you need to bind some key to it, of course.)
;; Kill the current buffer immediatly, saving it if needed.
(defvar kill-save-buffer-delete-windows t
"*Delete windows when `kill-save-buffer' is used.
If this is non-nil, then `kill-save-buffer' will also delete the corresponding
windows. This is inverted by `kill-save-buffer' when called with a prefix.")
(defun kill-save-buffer (arg)
"Save the current buffer (if needed) and then kill it.
Also, delete its windows according to `kill-save-buffer-delete-windows'.
A prefix argument ARG reverses this behavior."
(interactive "P")
(let ((del kill-save-buffer-delete-windows))
(when arg (setq del (not del)))
(when (and (buffer-file-name) (not (file-directory-p (buffer-file-name))))
(save-buffer))
(let ((buf (current-buffer)))
(when del (delete-windows-on buf))
(kill-buffer buf))))

Code completion key bindings in Emacs

When doing a M-x describe-mode in a .el file, I noticed that the Emacs-Lisp mode actually does code completion. However, lisp-complete-symbol is bound to M-TAB. In Windows, this key binding is taken by Windows for switching the active window. Most IDE's use C-SPC, but that's taken in Emacs as well. What is a good, fairly common key binding for code completion?
If you like completion of all kinds, I recommend M-/ and binding that to hippie-expand.
(global-set-key (kbd "M-/") 'hippie-expand)
It does a variety of completions, which are controlled by the variable hippie-expand-try-functions-list. In the .el files, you can set that to do the 'try-complete-lisp-symbol first to get the behavior you're asking for above, along with all the other expansions hippie-expand provides.
This would do that for you:
(add-hook 'emacs-lisp-mode-hook 'move-lisp-completion-to-front)
(defun move-lisp-completion-to-front ()
"Adjust hippie-expand-try-functions-list to have lisp completion at the front."
(make-local-variable 'hippie-expand-try-functions-list)
(setq hippie-expand-try-functions-list
(cons 'try-complete-lisp-symbol
(delq 'try-complete-lisp-symbol hippie-expand-try-functions-list)))
(setq hippie-expand-try-functions-list
(cons 'try-complete-lisp-symbol-partially
(delq 'try-complete-lisp-symbol-partially hippie-expand-try-functions-list))))
As Trey Jackson mentioned, hippie-expand is the way to go, but along with binding it to M-/, I also like having the TAB key do all my completion work for me. So I have this from the Emacs-Wiki in my .emacs file:
;;function to implement a smarter TAB (EmacsWiki)
(defun smart-tab ()
"This smart tab is minibuffer compliant: it acts as usual in
the minibuffer. Else, if mark is active, indents region. Else if
point is at the end of a symbol, expands it. Else indents the
current line."
(interactive)
(if (minibufferp)
(unless (minibuffer-complete)
(hippie-expand nil))
(if mark-active
(indent-region (region-beginning)
(region-end))
(if (looking-at "\\_>")
(hippie-expand nil)
(indent-for-tab-command)))))
(global-set-key (kbd "TAB") 'smart-tab)
You could have hippie expand settings as follows:
;;settings for hippie-expand
(setq hippie-expand-try-functions-list
'(try-complete-lisp-symbol
try-complete-lisp-symbol-partially
try-expand-dabbrev
try-expand-dabbrev-from-kill
try-expand-dabbrev-all-buffers
try-expand-line
try-complete-file-name-partially
try-complete-file-name))
C-M-i; no customization required.
I use:
(define-key function-key-map [(control tab)] [?\M-\t])
I use M-. and M-/ for the 2 completion modes - hippie-expand and the standard emacs one.
Put this in your .emacs to make Windows give Emacs the use of M-TAB:
(when (fboundp 'w32-register-hot-key) (w32-register-hot-key [M-tab]))

About the forward and backward a word behaviour in Emacs

I don't know if there's something wrong with my settings but when I press M-f (forward a word)
it doesn't matter where I am, it never place the cursor in the next word (just between words). This doesn't happen with M-b which place my cursor in the beginning of the previous word.
Is this a normal behavior? How do I place my cursor at the beginning of the following word?
The macro solution described is a great way to get this behavior in a session, but it's a little inconvenient if that's the default behavior you want, since you have to define it every time you start emacs. If you want M-f to work like this all the time, you can define an elisp function and bind it to the key. Put this in your .emacs file:
(defun next-word (p)
"Move point to the beginning of the next word, past any spaces"
(interactive "d")
(forward-word)
(forward-word)
(backward-word))
(global-set-key "\M-f" 'next-word)
Ok, just so we're clear, Im going to assume you are talking about the commands forward-word and backward-word these are bound by default to Alt+f and Alt+b
eg string: "Hello dolly I am here"
If your cursor is on the "H" of "Hello", and you do forward-word the cursor will move to the space between "Hello" and "dolly", but it sounds like you want the cursor to be on the letter "d" of "dolly" instead of in-front of it.
So, do forward-word twice, then backward-word once.
That will put your cursor on the "d" of "dolly".
This can be automated with a macro.
;; = comments, do not type them
Ctrl+x ( ;;start macro
Alt+f Alt+f Alt+b
Ctrl+x ) ;;end macro
Then to run last defined macro do this:
Ctrl+x e
EDIT: as pascal mentioned in a comment, this can also just be done with
Alt+f Ctrl+f
You could put that into a macro as well, either way the result is the same.
That is correct behavior. According to the Emacs manual, "[f]orward motion stops right after the last letter of the word, while backward motion stops right before the first letter."
Why is it this way? Perhaps to be consistent with kill-word (M-d).
Moving forward twice and backwards once is fine unless you are at the beginning of a line with spaces in the front. Then going forward twice and back once will move you to the next word not the first word. The code below will mimic vi's "w" command perfectly. I've written this quite fast so this code can be cleaned up further.
(defun forward-word-to-beginning (&optional n)
"Move point forward n words and place cursor at the beginning."
(interactive "p")
(let (myword)
(setq myword
(if (and transient-mark-mode mark-active)
(buffer-substring-no-properties (region-beginning) (region-end))
(thing-at-point 'symbol)))
(if (not (eq myword nil))
(forward-word n))
(forward-word n)
(backward-word n)))
(global-set-key (kbd "M-C-f") 'forward-word-to-beginning)
Try something like following:
;; replace common word-operations on same-syntax-operations
(require 'thingatpt)
(global-set-key "\M-f" 'forward-same-syntax)
(global-set-key "\M-b" (lambda()
(interactive)
(forward-same-syntax -1)))
(defun kill-syntax (&optional arg)
"Kill ARG sets of syntax characters after point."
(interactive "p")
(let ((opoint (point)))
(forward-same-syntax arg)
(kill-region opoint (point))))
(global-set-key "\M-d" 'kill-syntax)
(global-set-key [(meta backspace)] (lambda()
(interactive)
(kill-syntax -1)))
You can achieve this behavior by using the forward-to-word and backward-to-word found in misc.el. I have these bound to Meta-F/Meta-B (i.e. with Shift pressed). These are equivalent to Meta-f/Meta-b for forward-word/backward-word
My .emacs has the following bindings
(global-set-key (kbd "M-F") #'forward-to-word)
(global-set-key (kbd "M-B") #'backward-to-word)

How to scroll line by line in GNU Emacs?

To put it simply, I'm trying to get scrolling in emacs like in vim and most other editors; when I'm for example, two lines from the bottom/top, and I press down/up (Ctrl-p,n, ↑,↓) it goes only one line up or down, not half the screen.
See some of the suggestions on the Emacs Wiki:
Emacs Wiki: Smooth Scrolling
(setq scroll-step 1
scroll-conservatively 10000)
If you want to position the screen exactly, you can use Ctrl-L.
By default it positions the current line in the middle of the screen.
ESC 0 Ctrl-L positions the current line at the top.
I'm a bit late to the party, but if you don't mind installing a package then smooth-scrolling (github, also available in MELPA) may be what you're looking for - it certainly works for me.
Once you've installed it you can pop the following in your init.el:
(require 'smooth-scrolling)
(smooth-scrolling-mode 1)
(setq smooth-scroll-margin 5)
The last line is optional; it starts scrolling near the screen edge rather than at it, so you've always got a little context around the point. Adjust to taste.
My solution is not to change Emac's default scrolling, but rather to create a key sequence command from a macro. This way you have a convenient way to scroll one line at a time when you want. Not ideal, but super easy. It just happens that M-(↓) and M-(↑) are available, so that's what I used.
This is how I did it. First, you need to record a macro for one line scrolls, up and down.
Begin macro
C-x (
Scroll down one
C-u 1 C-v
Stop macro
C-x )
For scroll up one, use
C-u 1 M-v
Next you need to name the macro.
M-x name-last-kbd-macro
Give it a name when prompted like:
down-one-line
Then just use the following to bind a key sequence to that command name:
M-x global-set-key
And upon prompting, use something like:
M-(down arrow)
Then it will ask you which command you want to bind, and you should give it the name you invented earlier, e.g., down-one-line.
Here is where I got this information. You can also find instructions below and elsewhere about adding your macro to the .emacs file.
Here for macro definition explanation
Here for how to control scrolling
I've been using these in my .emacs file since 2000.
(global-set-key (quote [M-down]) (quote View-scroll-line-forward))
(global-set-key (quote [M-up]) (quote View-scroll-line-backward))
This way, I can keep the Emacs default behavior as well as scroll one line at a time, depending on what I'm doing.
This worked till at least GNU Emacs 22. I recently upgraded to Emacs 24 and discovered that View-scroll-line-forward and View-scroll-line-backward are no longer available. After some hunting, I discovered that scroll-up-line and scroll-down-line work. So if you're using Emacs 24, you can use this.
(global-set-key (quote [M-down]) (quote scroll-up-line))
(global-set-key (quote [M-up]) (quote scroll-down-line))
I mostly skipped Emacs 23, so if that is the version you're using, you can experiment with both the above.
Note: scroll-up-line actually scrolls one line down, because the buffer is being moved one line up.
I rebind my arrow keys to perform scrolling operations.
(global-set-key [up] (lambda () (interactive) (scroll-down 1)))
(global-set-key [down] (lambda () (interactive) (scroll-up 1)))
(global-set-key [left] (lambda () (interactive) (scroll-right tab-width t)))
(global-set-key [right] (lambda () (interactive) (scroll-left tab-width t)))
Simples do this:
(global-set-key [M-up] (lambda () (interactive) (scroll-up 1)))
(global-set-key [M-down] (lambda () (interactive) (scroll-down 1)))
then meta cursor up moves up and meta cursor down moves down.
QED. Not sure what all the above people were smoking!
I have the following in my .emacs file to enable a nice ctrl-up, ctrl-down scrolling behavior. I also use this for the mousewheel.
(defun scroll-down-in-place (n)
(interactive "p")
(previous-line n)
(scroll-down n))
(defun scroll-up-in-place (n)
(interactive "p")
(next-line n)
(scroll-up n))
(global-set-key [mouse-4] 'scroll-down-in-place)
(global-set-key [mouse-5] 'scroll-up-in-place)
(global-set-key [C-up] 'scroll-down-in-place)
(global-set-key [C-down] 'scroll-up-in-place)
If you are looking for a quick way to create a scroll-like effect, enter in C-n and C-l sequentially which moves the cursor down and then centers it.
To have the "vim" scrolling put this to your .emacs file:
(defun next-line-and-recenter () (interactive) (next-line) (recenter))
(defun previous-line-and-recenter () (interactive) (previous-line) (recenter))
(global-set-key (kbd "C-n") 'next-line-and-recenter)
(global-set-key (kbd "C-p") 'previous-line-and-recenter)
Since it can be annoying to use the M-up, M-down because it interferes with the org-mode which overloads these commands. To avoid this issue I personally use those commands which combine M-page-up M-page-down". Here I defined the scroll up and down to 1 line.
;;;scroll by `number-of-lines' without the cursor attached to the screen
(global-set-key [M-prior] (lambda () (interactive) (let ((number-of-lines 1))
(scroll-down number-of-lines)
(forward-line (- number-of-lines)))))
(global-set-key [M-next] (lambda () (interactive) (let ((number-of-lines 1))
(scroll-up number-of-lines)
(forward-line number-of-lines))))
;;;scroll by `number-of-lines' with the cursor attached to the screen
(global-set-key [S-M-prior] (lambda () (interactive) (let ((number-of-lines 1))
(scroll-down number-of-lines))))
(global-set-key [S-M-next] (lambda () (interactive) (let ((number-of-lines 1))
(scroll-up number-of-lines))))
M-x customize-variable scroll-conservatively
Set it to 1.
You don't really want to do this, though.
If you don't mind using the mouse and have a scroll wheel, you can customize the variable mouse-wheel-scroll-amount by either:
C-h v mouse-wheel-scroll-amount (click on customize, change value to "Specific # of lines" 1, ApplyAndSave.)
or add to .emacs the line:
'(mouse-wheel-scroll-amount '(1 ((shift) . 1) ((meta)) ((control) . text-scale)))
There are lots of possibilities listed at
https://www.emacswiki.org/emacs/Scrolling
If you start emacs in .xsession, in my case setting scroll-conservatively to 100+ will not work, nor scroll-step 1. But if u start emacs after X, it works.
After playing a bit with the available configuration (emacs 26.3), I got to the following set of values:
(setq scroll-step 1
scroll-preserve-screen-position t
scroll-margin 10
scroll-conservatively 10
maximum-scroll-margin 0.0
scroll-up-aggressively 0.0
scroll-down-aggressively 0.0)
I believe the values for scroll-margin and scroll-conservatively do not matter much because the maximum-scroll-margin clamps them down. They just need to be equal (maybe?).
Scroll happens line by line, even on the end of the file (worst case for me). The only missing feature was that with this the margin on top and bottom are lost.
Its a compromise and, for me, smooth scrolling is worth it.