1

I am trying to make emacs function somewhat like sublime text, where C-x cuts text that is selected and cuts the whole line when nothing is selected. I got the full-line cut to work using

(global-set-key (kbd "C-x") 'kill-whole-line)

but I'm not sure how to get C-w's functionality (kill-region) to happen when text is selected and then use C-x. Is there a way to say something like

(if region-selected
    ('kill-region)
  ('kill-whole-line))

(And yes, I know I'm rebinding C-x, but I'm sick of trying to switch mental muscle memory modes from sublime text to terminal editing.)

Drew
  • 75,699
  • 9
  • 109
  • 225

1 Answers1

1
  1. To invoke a function, don't quote it: (kill-whole-line), not ('kill-whole-line).

  2. You're looking for function use-region-p, so (use-region-p), not region-selected. (There is no predefined variable region-selected.)

  3. You need to pass functions the arguments they require. So (kill-region (region-beginning) (region-end).

  4. If you want it to be a function then define it, giving it a name, with defun.

  5. If you want it to be a command, so you can bind it to a key, then give it an interactive spec: (interactive).

(defun my-kill-cmd ()
  (interactive)
  "Kill region if it's active and nonempty.  Else kill whole line."
  (if (use-region-p)
      (kill-region (region-beginning) (region-end))
    (kill-whole-line)))

To learn more:

  • Use C-h f kill-region to see what it does and what args it expects. Likewise, region-beginning, region-end, interactive (a special form), and defun (a macro).

  • Spend some time with the manual "An Introduction to Programming in Emacs Lisp". Use C-h i, then choose Emacs Lisp Intro. When in the manual, you can use i to look things up in the Index, using completion. E.g., i interactive RET.


You probably don't want to bind your command to C-x, as that's a prefix key in vanilla Emacs. Better to choose another key. For example:

(global-set-key (kbd "C-x C-j") 'my-kill-cmd)
Drew
  • 75,699
  • 9
  • 109
  • 225