Defadvice for C-k in emacs for js-mode

elisp, emacs, paredit

Solution

I'd recommend against using an advice for that, since you can just rebind `C-k` in `js-mode-map` instead. E.g.

(defun my-kill-line-or-block (&optional arg)
  "Kill line or whole block if line ends with a block opener."
  (interactive "P")
  (if (looking-at ".*\\({[^{}\n]*$\\)")
      (kill-region (point)
                   (progn (goto-char (match-beginning 1))
                          (forward-sexp 1)
                          (point)))
    (kill-line arg)))

(define-key js-mode-map [?\C-k] 'my-kill-line-or-block)

Problem

I want to use the C-k to kill a block or kill the rest of current line in js-mode. After I search google for a while, I think `defadvice` will be the answer but I am not familiar with elisp. So I hope somebody can help me write it :) The function I mentioned is something like `paredit-mode` but I don't want to enable `paredit-mode` in `js-mode` as my requirements will be much simpler. When I am writing js, sometimes I want to kill the follow block like: ``` function test() { if () { } else { } } ``` If the cursor is now between `function` and `test`, then I use C-k I can kill the whole block ``` test() { if () { } else { } } ``` with the only word `function` left. Here 'block' simply means something between '{}'. If current line is not followed by a block, C-k should behave as its origin behavior, which should be `(kill-line &optional ARG)`, kill the rest of line by default. If you are familiar with `paredit-mode`, you will find it just a very simple version of it! I hope you can understand what I mean since my English is broken. Any help will be greatly appreciated !

Original source