I want to select or highlight a block in emacs without using mouse but doing it from the keyboard like vim\'s visual mode. What is the easiest way to do this from a keyboard
Although C-SPC
is a common way to start marking something from
wherever your point is, there are often quicker/easier ways that don't
involve explicitly moving to start/end points...
M-h
— an important means to mark a paragraph. A "paragraph"
often means a block of code.
C-M-h
and C-M-@
— for marking sexps and defuns,
respectively. This works for several languages, not just lisps.
hold down shift — another slick way to highlight during
movement. E.g., M-S-f
selects forward a whole word. This is
shift-select-mode,
and it is enabled by default in Emacs 24+. On some (non-chiclet)
keyboards, you should be able to hold down C-S-
with a single
pinky.
You can press any of these repeatedly to grow the selection.
There are also a few special ways to mark things:
C-x h
— mark the whole buffer
C-x SPC
— enter rectangle mark mode
(NOTE: use C-g
often to cancel marking while
experimenting.)
There are a few add-on packages that improve selecting regions and things. These are all play nicely together and fit different use cases. Use them all!
expand-region:
Expand region increases the selected region by semantic units. Just
keep pressing the key until it selects what you want. C-=
is a
recommended binding for it. Hit it a few times to get what you
need.
easy-kill: Use M-w
and
a mnemonic to select different types of things, like words, sexps,
lists, etc.
zop-to-char: Like zap-to-char, but provides nice selection and other menu-driven actions.
diff-hl: Highlight uncommitted changed regions. Use diff-hl-mark-hunk
to select/mark a hunk.
symbol-overlay: Select symbol at point with a keystroke (M-i
). Then you can do other things with it, like copy, search, jump, replace, etc.
See the article: "Working with rectangular selections", especially the comments section. See also the section of CUA mode documentation titled "CUA rectangle support". There's also a nice video on vimeo.
Take a look at region-rectangle in emacs.
In short, you start selection like usual with Control-Space, then kill region with Control-x r k and paste (or yank) killed block with Control-x r y.
To expand answer of Edin Salkovic, if you use CUA mode, you can use to begin a visual block selection. There are plenty of shortcuts to control block selection described in documentation of CUA.
... and in case you are using Ubuntu and C-spc is not working for you: you need to clear the IBus "next input method" keybinding, as in
run
ibus-setup
and change the key binding for "next input method" to something else (or delete it entirely by clicking the "..." button and then the "Delete" button).
Quote taken from an answer to a SO question.
With Emacs 25, simply press C-Space and then move your cursor wherever you want to highlight/select the region of text which interests you. After that, you may need these commands: