artyhedgehog · 2022-05-18 12:37
I'm starting to really use emacs for some tasks (org-mode mostly), but one thing confusing me is how eager emacs jumps/kills over words. Say, I have a few lines of code:
```
(goto-char beg-line-point)
(backward-kill-word 1))
```
If my cursor is at the beginning of `backward-...` and I start jumping or killing words backward, what I expect (and have in, say, my VSCode editor) is first jump to beginning of text (`(`), then to the beginning of line, then to the closing parenthesis on the previous line, then to the end of `...-point` (after `t`) - and only then to before `p`. But what I get in emacs is it jumps to before `p` in `...-point` immediately on first press.
Can I somehow reconfigure emacs' word recognition for it to jump words more accurately? Maybe configure word beginning/ending regexp to add symbols/newline to them?
ndamee · 2022-05-18 16:31
You can change the definition of a word, that is making `-` a punctuation character instead of a word character:
https://ftp.gnu.org/old-gnu/Manuals/emacs/html_node/emacs_504.html#SEC504
oantolin · 2022-05-18 22:50
Try the command `forward-same-syntax`, I think it is pretty close to what you want. It has no default keybinding, so I guess that means you're in the minority in wanting that behavior. :P
artyhedgehog · 2022-05-18 23:25
It actually is, thanks!
```
(global-set-key (kbd "M-f") (lambda () (interactive) (forward-same-syntax 1)))
(global-set-key (kbd "M-b") (lambda () (interactive) (forward-same-syntax -1)))
```
Just couldn't figure out yet, how to set killing back and forth in similar manner, but I think I have some leads.
oantolin · 2022-05-18 23:31
I'd recommend doing this instead, so you can specify a numeric prefix argument to the commands:
(defun backward-same-syntax (arg)
"Move point backwards past all characters with the same syntax class.
With prefix argument ARG, do it ARG times if positive, or move
forwards ARG times if negative."
(interactive "^p")
(forward-same-syntax (- arg)))
(global-set-key (kbd "M-f") #'forward-same-syntax)
(global-set-key (kbd "M-b") #'backward-same-syntax)
artyhedgehog · 2022-05-18 23:53
Looks good, thx!
Could you possibly suggest how to make a sequence for `set-mark-command` -> `forward-same-syntax` -> `kill-region`? I'm not really getting how to call set-mark-command inside lambda:
```
(global-set-key (kbd "M-DEL") (
lambda ()
(interactive)
;; I guess I need some arg instead of nil here:
(set-mark-command nil)
(forward-same-syntax -1)
(kill-region)))
```
Phil-Hudson · 2022-05-19 10:39
As a generally useful tip, when editing and navigating Lisp code, you will really benefit from learning and using Paredit minor mode, or one of its mutations/competitors.
oantolin · 2022-05-21 17:58
Sorry, I missed this question earlier. I'd do it this way instead:
(defun backward-kill-same-syntax (arg)
(interactive "p")
(kill-region (point) (progn (forward-same-syntax (- arg)) (point))))