Subject: bug#69097: [PATCH] Add 'kill-region-or-word' command

From: Juri Linkov <[email-masked]>
Date: Tue, 17 Sep 2024 20:58:07 +0300

Thanks for the new command!  I'd like to use it, but currently can't
because I have customized 'mark-even-if-inactive' to nil.

> +** New user option 'kill-word-dwim'.
> +This option, if non-nil, modifies the fall-back behavior of
> +'kill-region' if no region is active, and will kill the last word
> +instead of raising an error.  Note that if you have disabled Transient
> +Mark mode you might prefer to use 'unix-word-rubout', as this feature
> +relies on there being an active region.

This could mention the default keybindings of 'kill-region' ('C-w').

> +(defcustom kill-region-dwim nil
> +  "Behavior when `kill-region' is invoked without an active region.
> +If set to nil (default), then the behavior `kill-region' will not
> +change.  If set to `emacs-word', then kill the last word as defined by
> +the current major mode.  If set to `unix-word', then kill the last word
> +in the style of a shell like Bash, disregarding the major mode like with
> +`unix-word-rubout'."
> +  :type '(choice (const :tag "Kill a word like `backward-kill-word'" emacs-word)
> +                 (const :tag "Kill a word like Bash would" unix-word)
> +                 (const :tag "Do not kill anything" nil))

Usually the default value 'nil' comes first.
This helps to disable an option by always selecting 0
from the Customization menu.

>  (defun kill-region (beg end &optional region)
>    "Kill (\"cut\") text between point and mark.
>  This deletes the text from the buffer and saves it in the kill ring.
> @@ -5843,21 +5856,35 @@ kill-region
>   (To delete text, use `delete-region'.)
>  Supply two arguments, character positions BEG and END indicating the
>   stretch of text to be killed.  If the optional argument REGION is
> - non-nil, the function ignores BEG and END, and kills the current
> + `region', the function ignores BEG and END, and kills the current
>   region instead.  Interactively, REGION is always non-nil, and so
> - this command always kills the current region."
> + this command always kills the current region.  It is possible to
> + override this behavior by customising the user option
> + `kill-region-dwim'."

I tried to use this command with `emacs -Q`, and typed 'C-w C-w' twice,
but it fails with

  Debugger entered--Lisp error: (wrong-type-argument number-or-marker-p nil)
    kill-region(nil 16 emacs-word)
    funcall-interactively(kill-region nil 16 emacs-word)
    command-execute(kill-region)

because for the second 'C-w' it calls 'kill-append':

  (if (eq last-command 'kill-region)
      (kill-append string (< end beg))
    (kill-new string))