Defadvice for Ck in emacs for js-mode

I want to use Ck to kill a block or kill the remaining current line in js mode.

After I searched Google for a while, I think defadvice will be the answer, but I am not familiar with elisp. So I hope someone can help me write :)

The function I mentioned is similar to paredit-mode , but I don't want to include paredit-mode in js-mode , since my requirements will be much simpler. When I write js, sometimes I want to kill the following block, for example:

 function test() { if () { } else { } } 

If the cursor is between function and test , then I use Ck , I can kill the whole block

  test() { if () { } else { } } 

with a single word function on the left. Here, "block" simply means something between "{}".

If the current line does not match the block, Ck should behave as its origin, which should be (kill-line &optional ARG) , by default, delete the rest of the line.

If you are familiar with paredit-mode , you will find it just a very simple version!

I hope you understand what I mean, as my English is broken. Any help would be greatly appreciated!

+4
source share
2 answers

I would recommend not using a tip for this, as you can just rebuild Ck in js-mode-map . For instance.

 (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 [?\Ck] 'my-kill-line-or-block) 
+4
source
 (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, Ck binds to kill-visual-line. If you verify that Ck associates with kill-line (check it with Ch k Ck ), then change kill-visual-line to kill-line in this function.

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

+1
source

Source: https://habr.com/ru/post/1448054/


All Articles