How do I mark the current line and then move the cursor to the beginning of the next line? I'd like it to behave like Sublime Text's Ctrl-L.
3 Answers
Below works with brief testing:
- If no region is selected to begin with, the current line will be selected and the cursor will move to the next line (default, if no prefix arg is used).
- If a region is already selected, all this command will do is move the cursor to the next line (default, if no prefix arg is used).
With that functionality, hitting C-l
once will select only the current line. But hitting C-l
consecutive times will keep on adding consecutive lines to the selection.
(defun my/select-current-line-and-forward-line (arg)
"Select the current line and move the cursor by ARG lines IF
no region is selected.
If a region is already selected when calling this command, only move
the cursor by ARG lines."
(interactive "p")
(when (not (use-region-p))
(forward-line 0)
(set-mark-command nil))
(forward-line arg))
;; Note that I would not recommend binding this command to `C-l'.
;; From my personal experience, the default binding to `C-l' to
;; `recenter-top-bottom' is very useful.
(global-set-key (kbd "C-l") #'my/select-current-line-and-forward-line)
I'd like to add that I personally prefer simply doing C-a C-SPC
followed by C-n
or C-p
or M-{
or M-}
.
C-a C-SPC
will take the cursor to the beginning of the line and set the mark.- After that the selection will expand based on the navigation command you use.
Using this generic approach will give you much more flexibility on how you change your selection.
-
1A useful change may be adding an arg
arg
, using(interactive "p")
, and changing(forward-line 1)
to(forward-line arg)
.– nannyAug 25, 2015 at 14:28 -
-
Does changing
use-region-p
byregion-active-p
make difference in the functionmy/select-current-line-and-forward-line
?– NameAug 25, 2015 at 16:37 -
@Name It should work fine even if you use
region-active-p
here. Aug 25, 2015 at 16:55 -
If I don't give
arg
a value as prefix arg andRET
directly, your function will still move down 1 line, does it mean that1
is the default argument?– Chen LiJan 20, 2019 at 12:58
Shift Selection Mode
If the cursor is at the beginning of a line: C-S-n or in another notation C-N.
If not, please type: C-a C-S-n (which is in my notation C-aN, since you have to type the <CTRL>
key just once). By the way shift-selection-mode
is t
by default.
-
This is in most cases a better answer as it does not need any additional configs. Apr 17 at 7:36
Could you mean a combination of C-e
and C-j
? If yes, you can remap it via a keyboard macro :
(global-set-key (kbd "<C-return>") (kbd "C-e C-j"))
M-h
(mark-paragraph
) andC-M-h
(mark-defun
) useful, as they may eliminate the need for such a command much of the time.