質問

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 !

役に立ちましたか?

解決

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)

他のヒント

(defadvice kill-visual-line (around cus-kill activate)
  (unless (let ((mark-point (point)))
            (if (search-forward "{" (line-end-position) t)
                (kill-region mark-point (scan-sexps (- (point) 1) 1))))
    ad-do-it))

In my case, C-k is bind to kill-visual-line. If you make sure that C-k is bind to kill-line(check it using C-h k C-k), then change kill-visual-line to kill-line in that function.

PS: The function is not fully tested. If the {} is not balanced an warning is signaled by scan-sexps. You can just ignore it.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top