Vim in Mac OS X Terminal: Move cursor word by word - macos

I have followed the guidance in Is there any way in the OS X Terminal to move the cursor word by word? and now in terminal I can move cursor word by word.
However, in Vim, I am only able to move backward word by word. I cannot move forward word by word, no matter I set \033f to option+cursor-right or shift+cursor-right. The only workaround I figured out is to go to normal mode and click <w> to move to next word. Any idea about how to fix that? Thanks.

w is not a workaround. It's the primary way to move word by word (see also: W, b, B, e, E). What you want is a workaround that won't help you learn Vim at all.

Some may argue that moving around with VIM native keyboard shortcuts is not a workaround, but for me it sure is both very inconvenient and very inefficient. Especially the part where you need to switch between insert mode and normal mode just to move to the next word.
That's why I came up with a solution based on this answer on SuperUser. The idea is to map input provided by the Terminal.app directly in VIM. The answer on SU shows what to put into your vimrc file for the Home/End keys to work as expected.
My tweaked version below includes the Option+arrow (or Alt+arrow) navigation on words. I've tried to mimic the behavior of Terminal's moving around as close as I could get. So pressing Option+Right (Alt+Right) will move the caret to the next character after the word (as opposed to the last character of the word, which is VIMs w native bahavior).
let tp=$TERM_PROGRAM
if tp == 'Apple_Terminal'
:" map Mac OS X Terminal.app
" map Home/End:
:map <ESC>[H <Home>
:map <ESC>[F <End>
" small 'o' letter in <C-o> means no exit from the insert mode
:imap <ESC>[H <C-o><Home>
:imap <ESC>[F <C-o><End>
:cmap <ESC>[H <Home>
:cmap <ESC>[F <End>
" map Option+Left/Option+Right:
" for this to work you must have the bindings in Settings > Keyboard set
" as follows:
" 'option cursor left' to '\033b'
" 'option cursor right' to '\033f'
:map <ESC>f el
:imap <ESC>b <C-o>b
:imap <ESC>f <C-o>el
:cmap <ESC>f el
endif
As a small, but significant bonus you get Home/End navigation without exiting the insert mode. Tested on 10.8.5.

Let me clear a few things up for you. Bash (the shell program running inside the terminal) has the behavior you are used to. (Using Alt+f to move forward by word, and Alt+b to move backward by word.) This was originally done to be like Emacs. You can use the command
set -o vi
to switch to vim behavior. In this mode, you can use Esc to switch to normal mode, and move around like in vim; then press i to go back to insert mode.
So don't be surprised that Vim isn't trying to act like Emacs. The whole power behind vim lies behind these simple motions.

Related

Is there any way of using normal keyboard text selection with a terminal on MacOS?

For the last ~10 years I've been used to manipulating text with the alt/⇧/⌘ keys. For instance, alt+← to jump back a word instead, alt+⇧+← to select that word, ⌘+→ to jump to the end of line, etc.
I understand that terminals have different conventions and historically came first, but I'm used to these shortcuts, they work great and work everywhere else. Is there any way of getting the same controls for selecting and manipulating text in the terminal?
I have seen the following questions:
How to move the cursor word by word in the OS X Terminal
How do I clear/delete the current line in terminal?
But they only address moving the cursor, and not selection.
Depending on the macOS version - your default shell may be zsh.
Shortcuts options are ctrl + a/e to move to beginning/end of line and esc + W/B to move one word backward/forward
Other popular alternatives are -
a. bash - with the shortcuts listed in the answer by #Hossein Amiri
b. iterm2 - From - https://coderwall.com/p/a8uxma/zsh-iterm2-osx-shortcuts
Put this in your .zshrc
bindkey "[D" backward-word
bindkey "[C" forward-word
bindkey "^[a" beginning-of-line
bindkey "^[e" end-of-line
And set iterm preferences.
Moving the cursor:
Ctrl+A Go to the beginning of the line (Home)
Ctrl+E Go to the End of the line (End)
Hold the Option key option and click on the current line = Jump Backwards
Ctrl+P Previous command (Up arrow)
Ctrl+N Next command (Down arrow)
Hold the Option key option and click on a previous line = Jump upwards
Ctrl+F Forward one character
Ctrl+B Backward one character
Alt+B Back (left) one word or use Option+→
Alt+F Forward (right) one word or use Option+←
Ctrl+xx Toggle between the start of line and current cursor position
More information : https://ss64.com/osx/syntax-bashkeyboard.html
You can't, I've beed looking for long time. This is why people use iTerm they have more flexibility with keyboard only.
https://iterm2.com/features.html
Copy Mode
Use the keyboard to make and modify selections.

Keyboard-only column block selection in GVim Win32, or why does Ctrl-Q not emulate Ctrl-V when mswin.vim is included?

I want to be able to select columnar blocks using only the keyboard when I use GVim on Windows, but I do not seem to be able to do so when using gvim (7.2) on Windows XP. Edit: For convenience, it is preferable to make the selection with arrow keys as is commonly done in other versions of vi/vim.
In a terminal, when using vim, to define a block, one may select columnar blocks by pressing Ctrl-V and by conveniently moving the cursor with the arrow keys.
When using GVim on mswin, Ctrl-V is mapped to a paste operation. Every reference found on this topic mentions that on mswin, Ctrl-Q is set to act the same way that Ctrl-V works on other platforms, but this does not work for me.
After research indicated that the Ctrl-Q behavior is implemented through the inclusion of mswin.vim, it seemed that perhaps mswin.vim was not being loaded by GVim. mswin.vim is apparently loaded via _vimrc. It seemed that perhaps mswin.vim was not loading, so perhaps _vimrc was not setup correctly, but...
C:\Program Files\Vim\_vimrc exists contains:
source $VIMRUNTIME/mswin.vim
behave mswin
C:\Program Files\Vim\vim72\mswin.vim exists and contains:
" Use CTRL-Q to do what CTRL-V used to do
noremap <C-Q> <C-V>
C:\Program Files\Vim\_vimrc should load since Edit | Settings Window in the GVim graphical menu loads this file for editing, and it is clear that C:\Program Files\Vim\vim72\mswin.vim is loading because one can insert a syntax error in that file and GVim will complain about it when it starts up (it was backed it up for testing and restored to prevent accidental corruption).
When Ctrl-Q is pressed, the cursor changes in the same way that it changes when you block select text using the mouse, but any cursor movement at this point causes the cursor to change back to a normal cursor. It does not matter whether one continues to hold Ctrl, Ctrl-Q, or not.
Edit: Ctrl-Q enters block selection mode as indicated by the cursor change since other cursor movement commands extend the block, however, the original intent of this question was to learn how to use the arrow keys (in the same manner that they are able to be used in other implementations of the editor) though this was not explicitly stated in the original, unanswered revisions of the question.
It is possible to visually select columnar blocks by pressing Alt while holding down the left-mouse button, but Alt during arrow key motion after pressing Ctrl-Q also does not work.
Research also seemed to indicate that pressing v in command-mode would enter visual-mode, and that perhaps this was relevant, but using this does not seem to help the situation.
C:\Program Files\Vim\vimfiles does not contain anything except an empty directory structure. C:\Documents and Settings\username does not contain vim configuration files, nor does C:\Documents and Settings\username\My Documents. Other C:\Documents and Settings\username locations, where application-specific or local settings are commonly stored, also appear not to have vim settings. The same is true for %HOMEDRIVE% and for the environment variables.
One way to visually select column blocks in GVim on Win32 using only the keyboard is to press Ctrl-Q, release it, then press and hold down the Shift key while using the arrow keys to select the column block.
Why Ctrl-Q columnar selection behaves this way is not known, but it does not really matter since the goal was to select column blocks using only the keyboard. In Vim, Shift is not used when using Ctrl-V to select blocks.
:help mswin does not mention this nuance of the CTRL-V alternative.
The best thing to do is to remove these lines from your vimrc. They are totally unecessary and change too many basic Vim features.
The noremap <C-Q> <C-V> in mswin.vim remaps the original command to Ctrl + Q.
If mswin.vim is included, after pressing Ctrl + Q, the indicated mode should switch to Visual Block, and any movement (e.g. j, l, w) extends the visual selection. If that doesn't work for you, you may have something interfering.
Are those movement commands itself remapped, or is there an autocmd on CursorMoved?! Try disabling your plugins (vim --noplugin) and most parts of your .vimrc.
Note that cursor keys do not normally constitute proper movement (and their use in Vim is frowned upon).
What you perceive as the right (and only) way to extend the selection (with shifted cursor keys) is just a consequence of :set selectmode=key, as done by :behave mswin.

Getting "complete" and "menu-complete" to work together

I found out that the Bash shell supports a type of autocompletion that is different from the "traditional" autocompletion, where all possibilities get listed on the following line.
With the "traditional" autocompletion, if I type ch and then press the Tab key, I get something like:
$ ch
chacl chgrp chmod chown chvt
But if I add the following line to my /etc/inputrc (which remaps the Tab key to the built-in menu-complete function):
Tab: menu-complete
then the behavior of the shell changes: the word to be completed is replaced "inline" with a single match from the list of possible completions, and if I press the Tab key again, the word gets replaced with the next match.
I found this useful, but I still wanted to keep the traditional autocompletion and have it bound to the key combination Ctrl + Tab. So I added the following line to my /etc/inputrc file, according to what the readline library documentation suggests:
Ctrl-Tab: complete
However, adding this line only seems to make both Tab and Ctrl-Tab call the traditional complete function.
Does anyone know what I am doing wrong?
Thanks in advance!
To start with, I'm not a massive expert in this area, but I think I can answer your question. First of all, while you are using Bash, Bash is a shell which interprets keyboard commands that it receives from a terminal / console. While you are informing Bash how to react to specific key combinations in the inputrc file, your Terminal determines precisely which character is 'sent' to the Shell before the inputrc file even enters the equation.
Unfortunately, on my system (granted, it's OSX - but I don't think this is strange behaviour when compared to Linux), both Tab and Ctrl-Tab send the same keyboard input to the shell. Infact, both Tab and Ctrl-Tab send a Ctrl-I command to the shell, and indeed, if I enter Ctrl-I when using the terminal, it performs the completion as if I hit Tab.
The software (installed on most Linux systems by default), showkey will tell you what keys the shell is receiving when you press specific keyboard inputs as you push them.
Anyway, my suggestion to you is to use Shift-Tab, which does appear to send it's own key-code to the shell. Shift-Tab on my computer shows up (using showkey) as '<ESC>[Z', which I think is pretty standard across the board. As such, your inputrc file with the following bindings should allow you to use shift-tab instead of ctrl-tab to achieve what you desire:
Tab: menu-complete
"\e[Z": complete
The \e in the second binding represents the escape character, and the [Z are simply the characters as shown using showkey. You can get a similar effect on OSX by simply using cat, running cat from within a terminal and pressing Shift-Tab will show you "^[[Z", where ^[ represents the escape character and the other characters are as before.
I know this doesn't resolve your question precisely, but as I don't think you are able to use Ctrl-Tab as a key combination, without re-mapping Ctrl-Tab to another keybinding within your terminal (more likely to be easier if you are using a GUI terminal), this is likely as close as you can get without significant effort!
I have ShiftTab bound to menu-complete-backward, so it goes back one step if I skipped the right completion, and I've mapped Ctrlq to complete, so if there are several possible completions I hit Ctrlq to list them without having to cycle through them.
# Make Tab cycle between possible completions
# Cycle forward: Tab
# Cycle backward: Shift-Tab
TAB: menu-complete
"\e[Z": menu-complete-backward
# Make C-q display the list of possible completions
Control-q: complete
# Display the list of matches when no further completion is possible
set show-all-if-unmodified on
Edit: Ctrlq is bound to quoted-insert by default, that is, it tells the shell to take the next key literally. quoted-insert is also bound to Ctrlv, so you don't lose that functionality if you rebind Ctrlq. Anyway, I've found that AltESC also works, by default, for showing the possible completions (as far as I can tell it is equivalent to TAB); note that it may be seized by Gnome, then either double press ESC or rebind "Switch windows directly" in Settings → Devices → Keyboard → Navigation.
The following should achieve what you're looking for (if I understand correctly!)
In your .inputrc
# display all possible matches for an ambiguous pattern at first tab
set show-all-if-ambiguous on
# next tab(s) will cycle through matches
TAB: menu-complete
# shift tab cycles backward
"\e[Z": menu-complete-backward
Where to start, if you can or cant do this is dependent your keyboard and your drivers and there isn't one catch all answer. Each key press and release generates a sequenced key pair (key down and release) (scancode) these codes are then translated by the kernel into keycodes for example on my laptop keyboard 0x3a 0xba are translated to keycode 15 (down and up) these are then translated into actions such as return letter c a / you can assign actions to keysyms using the keycode/hex/binary/octal notation which codes match which letters is determined by the kernel translation table which is fairly standardized, however the first part signal that's translated to keycodes is different for most keyboards.
Continuing with the earlier example for me shift tab (and alt and control and any combination) produce keycode 15 however in hex it produces 0x2a 0x2a 0x2a 0x2a 0x2a 0x2a 0x2a 0x2a 0x2a 0x2a 0x2a and this is because shift alt and control are special keys (modifiers) these multiply out against the keycodes and fill out the dumpkeys table the kernel is limited to the number of assignments as well this is determined by your choice of keymap and shares resources with your terminal colors (if your char set its defined above the threshold it limits your terminal color scope). And this all goes out the window if your in an xserver and has a whole new system. Most of these things can be changed,modified and manipulated by the user and programs installed. My point to all this is to emphasize that there is no catch all for the mapping of the tab key and its going to vary keyboard drivers to kbd drivers (now if you find a solution that happens to work for you excellent :)) but chances are it won't be portable and might not work if you change keyboards and might not translate between xserver and tui. What i recommend is learning the steps to modify your kbd on the go.
will give you the decimal octal hex notation for a key press on the same line
--full-table -1 >> keytable
will give you a documented with your full list of keycode->keysym pairing in a format that will give you a better picture of your layout and from there you can either use loadkey to change a keys value or ad an entry in .inputrc or your main rc file. You can also create a custom key.map file.
Further escape sequence translation is determined by the "$TERM" variable and each virtual terminal emulator can be different
infocmp "$TERM"
will give you a list of your terminal escape sequences
Resources:
https://man7.org/linux/man-pages/man4/console_codes.4.html
https://www.gnu.org/software/screen/manual/html_node/Input-Translation.html
http://kbd-project.org/docs/scancodes/scancodes.html
https://www.vt100.net/
So to sum up.
Your keyboard drivers
Your kemap choice
Your virtual terminal emulator
and your kernel
form the backbone of remapping dificult keys (tab/s-tab/a-tab)
I'm not sure Ctrl-Tab is a real character; my terminal, for instance, ignores the combination. I think the only way to use Ctrl-Tab is to use your terminal emulator to map it to some otherwise unused escape sequence, then bind that sequence to complete.

Fastest way(s) to move the cursor on a terminal command line?

What is the best way to move around on a given very long command line in the terminal?
Say I used the arrow key or Ctrl-R to get this long command line:
./cmd --option1 --option2 --option3 --option4 --option5 --option6 --option7 --option8 --option9 --option10 --option11 --option12 --option13 --option14 --option15 --option16 --option17 --option18 --option19 --option20 --option21 --option22 --option23 --option24 --option25 --option26 --option27 --option28 --option29 --option30 --option31 --option32 --option33 --option34 --option35 --option36 --option37 --option38 --option39 --option40 --option41 --option42 --option43 --option44 --option45 --option46 --option47 --option48 --option49 --option50
Now I need to move (starting from the beginning or the end of the line) the cursor to --option25 to modify something there.
What is the fastest way to get there? What I usually do is Ctrl-A to get to the beginning and then repeatedly Alt-F to move forward, word by word (or Ctrl-E to go the end and Alt-B to then go backward). But on a long line that takes too much time. There must be a way to search and jump directly to the part I need to modify, e.g. option25?
To be clear, you don't want a "fast way to move the cursor on a terminal command line".
What you actually want is a fast way to navigate over command line in you shell program.
Bash is very common shell, for example.
It uses Readline library to implement command line input. And so to say, it is very convenient to know Readline bindings since it is used not only in bash. For example, gdb also uses Readline to process input.
In Readline documentation you can find all navigation related bindings (and more):
http://www.gnu.org/software/bash/manual/bash.html#Readline-Interaction
Short copy-paste if the link above goes down:
Bare Essentials
Ctrl-b Move back one character.
Ctrl-f Move forward one character.
[DEL] or [Backspace] Delete the character to the left of the cursor.
Ctrl-d Delete the character underneath the cursor.
Ctrl-_ or C-x C-u Undo the last editing command. You can undo all the way back to an empty line.
Movement
Ctrl-a Move to the start of the line.
Ctrl-e Move to the end of the line.
Meta-f Move forward a word, where a word is composed of letters and digits.
Meta-b Move backward a word.
Ctrl-l Clear the screen, reprinting the current line at the top.
Kill and yank
Ctrl-k Kill the text from the current cursor position to the end of the line.
M-d Kill from the cursor to the end of the current word, or, if between words, to the end of the next word. Word boundaries are the same as those used by M-f.
M-[DEL] Kill from the cursor the start of the current word, or, if between words, to the start of the previous word. Word boundaries are the same as those used by M-b.
Ctrl-w Kill from the cursor to the previous whitespace. This is different than M- because the word boundaries differ.
Ctrl-y Yank the most recently killed text back into the buffer at the cursor.
M-y Rotate the kill-ring, and yank the new top. You can only do this if the prior command is C-y or M-y.
M is Meta key.
For Max OS X Terminal you can enable "Use option as meta key" in Settings/Keyboard for that.
For Linux its more complicated.
Update
Also note, that Readline can operate in two modes:
emacs mode (which is the default)
vi mode
To switch Bash to use vi mode:
$ set -o vi
Personaly I prefer vi mode since I use vim for text editing.
Bonus
In macOS Terminal app (and in iTerm too) you can Option-Click to move the cursor (cursor will move to clicked position). This even works inside vim.
Since this hasn't been closed yet, here are a few more options.
Use Ctrl+x followed by Ctrl+e to open the current line in the editor specified by $FCEDIT or $EDITOR or emacs (tried in that order).
If you ran the command earlier, hit Ctrl+r for a reverse history search and type option25 (in this case). The line will be displayed. Hit Tab to start editing at this point.
Use history expansion with the s/// modifier. E.g. !-2:s/--option25/--newoption/ would rerun the second-to-last command, but replace option25. To modify the last ./cmd command, use the !string syntax: !./cmd:s/--option25/--newoption/
Any delimiter may be used in place of / in the substitution.
If editing the previous line, you can use quick substitution: ^--option25^--newoption
Character search. This was mentioned by Pax, and can be done in regular emacs-mode with Ctrl+] for forward search, and Ctrl+Alt+] for backward search.
I recommend the second option. Ctrl+r is really handy and fast, no mucking about with editors, and you see the results before the command is run (unlike the history expansions).
Hold down the Option key and click where you'd like the cursor to move, and Terminal rushes the cursor that precise spot.
I tend to prefer vi editing mode (since those keystrokes are embedded into my spinal cord now (the brain's not used at all), along with the CTRL-K, CTRL-X from WordStar 3.3 :-). You can use the command line set -o vi to activate it (and set -o emacs to revert).
In Vi, it would be (ESC-K to get the line up first of course) "f5;;B" (without the double quotes).
Of course, you have to understand what's on the line to get away with this. Basically, it's
f5 to find the first occurrence of "5" (in --option5).
; to find the next one (in --option15).
; to find the next one (in --option25).
B to back up to the start of the word.
Let's see if the emacs aficionados can come up with a better solution, less than 5 keystrokes (although I don't want to start a religious war).
Have you thought about whether you'd maybe like to put this horrendously long command into a script? :-)
Actually, I can go one better than that: "3f5B" to find the third occurrence of "5" then back up to the start of the word.
Use Meta-b / Meta-f to move backward/forward by a word respectively.
In OSX, Meta translates as ESC, which sucks.
But alternatively, you can open terminal preferences -> settings -> profile -> keyboard and check "use option as meta key"
After running the command once, run fc
It will launch $EDITOR with the previous command, then you can use your regular editor to modify the command. When you save and exit, the file will be executed.
..but, as Pax said - the command line isn't particularly good for editing absurdly long lines - why not make the command into a script?
If you want to move forward a certain number of words, hit M-<n> (M- is for Meta and its usually the escape key) then hit a number. This sends a repeat argument to readline, so you can repeat whatever command you want - if you want to go forward then hit M-<n> M-f and the cursor will move forward <n> number of words.
E.g.
$|echo "two three four five six seven"
$ M-4
(arg: 4) echo "two three four five six seven"
$ M-f
$ echo "two three four| five six seven"
So for your example from the cursor at the beginning of the line you would hit, M-26 M-f and your cursor would be at --option25| -or- from the end of the line M-26 M-b would put your cursor at --|option25
Incremental history searching
in terminal enter:
gedit ~/.inputrc
then copy paste and save
"\e[A": history-search-backward
"\e[B": history-search-forward
"\e[C": forward-char
"\e[D": backward-char
all you need to do to find a previous command is to enter say the first 2 or 3 letters and upward arrow will take you there quickly say i want:
for f in *.mid ; do timidity "$f"; done
all i need to do is enter
fo
and hit upward arrow command will soon appear
It might not be the fastest, but this need to be here, some reading about ANSI cursor movements
ANSI escape sequences allow you to move the cursor around the screen at will. This is more useful for full screen user interfaces generated by shell scripts, but can also be used in prompts. The movement escape sequences are as follows:
- Position the Cursor:
\033[<L>;<C>H
Or
\033[<L>;<C>f
puts the cursor at line L and column C.
- Move the cursor up N lines:
\033[<N>A
- Move the cursor down N lines:
\033[<N>B
- Move the cursor forward N columns:
\033[<N>C
- Move the cursor backward N columns:
\033[<N>D
- Clear the screen, move to (0,0):
\033[2J or \033c
- Erase to end of line:
\033[K
- Save cursor position:
\033[s
- Restore cursor position:
\033[u
(...)
Try putting in the following line of code at the prompt (it's a little clearer what it does if the prompt is several lines down the terminal when you put this in): echo -en "\033[7A\033[1;35m BASH \033[7B\033[6D" This should move the cursor seven lines up screen, print the word " BASH ", and then return to where it started to produce a normal prompt.
Examples:
Move the cursor back 7 lines:
echo -e "\033[7A"
Move the cursor to line 10, column 5:
echo -e "\033[10;5H"
Quickly echo colors codes, to colorize a program:
echo -e "\033[35;42m" ; ifconfig
using option key and using a click the place you want to place the cursor with mouse or touchpad is you are using Mac build-in terminal.
One option is to use M-x shell in emacs. That provides all editing facilities and keystrokes that emacs has, so C-s can be used to search the text option25, for example.
(But I'd still prefer to be in the real terminal shell instead if someone can point me to good search and edit facilities.)
Use the mouse
Sometimes, the easiest way to edit a commandline is using a mouse. Some previous answers give a command to open your current line in your $EDITOR. For me (zhs with grml config) that combination is Alt+e. If you enable mouse in your editor, you can make use of it.
To enable mouse in Vim, add this to your ~/.vimrc
set mouse=a
set ttymouse=xterm2
If you then want to do a text selection in terminal (instead of passing the mouseclick to vim), hold Shift when you click; this is terminal specific, of course.
Sysadmins should not be afraid of the mouse.
In Cygwin, you can activate such feature by right-clicking the window. In the pop-up window, select Options... -> Mouse -> activate Clicks place command line cursor -> Apply.
From now on, simply clicking the left mouse button at some position within the command line will place the cursor there.
first:
export EDITOR='nano -m'
then:
CTRL+X CTRL+E in sequence.
You current line will open in nano editor with mouse enable. You can click in any part of text and edit
then CTRL+X to exit and y to confirm saving.
I made a script to make the command line cursor move on mouse click :
Enable xterm mouse tracking reporting
Set readline bindings to consume the escape sequence generated by clicks
It can be found on github
More info on another post
Will work if echo -e "\e[?1000;1006;1015h" # Enable tracking print escape sequences on terminal when clicking with mouse

How to move the cursor word by word in the OS X Terminal

I know the combination Ctrl+A to jump to the beginning of the current command, and Ctrl+E to jump to the end.
But is there any way to jump word by word, like Alt+←/→ in Cocoa applications does?
Out of the box you can use the quite bizarre Esc+F to move to the beginning of the next word and Esc+B to move to the beginning of the current word.
On macOS (all versions) the following keyboard shortcuts work by default.
ALT+F to jump Forward by a word.
ALT+B to jump Backward by a word.
Note that you have to make set the Option key to act like the Meta key. You can do this in Terminal by accessing preferences (CMD+,) and selecting Profiles -> Keyboard. In iTerm2 Pselect rofiles -> Keys -> General and select "Option key as Esc+."
Additionally some Emacs-style key bindings for simple text navigation seem to work on bash shells. You can use:
CTRL+F to move forward by a char
CTRL+B to move backward by a char
CTRL+A to jump to start of the line
CTRL+E to jump to end of the line
CTRL+K to kill the line starting from the cursor position
ALT+D to delete a word starting from the current cursor position
CTRL+W to remove the word backwards from cursor position
CTRL+Y to paste text from the kill buffer
CTRL+R to reverse search for commands you typed in the past from your history.
CTRL+S to forward search (works in ZSH for me but not bash)
Here's how you can do it
By default, the Terminal has these shortcuts to move (left and right) word-by-word:
esc+B (left)
esc+F (right)
You can configure alt+← and → to generate those sequences for you:
Open Terminal preferences (cmd+,);
At Settings tab, select Keyboard and double-click ⌥ ← if it's there, or add it if it's not.
Set the modifier as desired, and type the shortcut key in the box: esc+B, generating the text \033b (you can't type this text manually).
Repeat for word-right (esc+F becomes \033f)
Alternatively, you can refer to this blog post over at textmate:
http://blog.macromates.com/2006/word-movement-in-terminal/
Switch to iTerm2. It's free and much nicer than plain old terminal. Also it has a lot more options for customization, like keyboard shortcuts.
Also I love that you can use cmd and 1-9 to switch between tabs. Try it and you will never go back to regular terminal :)
How to set up custom keyboard preferences in iterm2
Install iTerm2
Launch and then go to preference pane.
Choose the keyboard profiles tab
You will either need to copy the profile to something new and then delete the arrow key shortcuts such as ^+ Right/Left or if you don't care about a backup just delete them from the default profile.
Next make sure your modified profile is selected (starred)
Now choose the keyboard tab (very top row)
Click on the plus button to add a new keyboard shortcut
In the first box type CMD+Left arrow
In the second box choose "send escape code"
In the third box type the letter B
Repeat with desired key combinations. escape+B moves one word to the left, escape+f moves one word to the right.
you may also wish to set up cmd+d to delete the word in front of the cursor with escape+d
I often hit the wrong button (cmd / control / alt) with an arrow key and so i have my arrow key combinations with those buttons all set to jump forward and back words, but please do what fits you best.
Actually there is a much better approach. Hold option ( alt on some keyboards) and press the arrow keys left or right to move by word. Simple as that.
option←
option→
Also ctrle will take you to the end of the line and ctrla will take you to the start.
I have Alt+←/→ working: open Preferences » Settings » Keyboard, set the entry for option cursor left to send string to shell: \033b, and set option cursor right to send string to shell: \033f. You can also use this for other Control key combinations.
Use Natural Text Editing preset!
Essentially it binds, among other key sequences, Option + LeftArrow to ^[b sequence and Option + RightArrow to ^[f
This works in fish and bash, as well as in psql terminal.
Actually it depends on what shell you use, however most shells have similar bindings. The bindings you are referring to (e.g. Ctrl+A and Ctrl+E) are bindings you will find in many other programs and they are used for ages, BTW also work in most UI apps.
Here's a look of default bindings for Bash:
Most Important Bash Keyboard Shortcuts
Please also note that you can customize them. You need to create a file, name as you wish, I named mine .bash_key_bindings and put it into my home directory. There you can set some general bash options and you can also set key bindings. To make sure they are applied, you need to modify a file named ".bashrc" that bash reads in upon start-up (you must create it, if it does not exist) and make the following call there:
bind -f ~/.bash_key_bindings
~ means home directory in bash, as stated above, you can name the file as you like and also place it where you like as long as you feed the right path+name to bind.
Let me show you some excerpts of my .bash_key_bindings file:
set meta-flag on
set input-meta on
set output-meta on
set convert-meta off
set show-all-if-ambiguous on
set bell-style none
set print-completions-horizontally off
These just set a couple of options (e.g. disable the bell; this can be all looked up on the bash webpage).
"A": self-insert
"B": self-insert
"C": self-insert
"D": self-insert
"E": self-insert
"F": self-insert
"G": self-insert
"H": self-insert
"I": self-insert
"J": self-insert
These make sure that the characters alone just do nothing but making sure the character is "typed" (they insert themselves on the shell).
"\C-dW": kill-word
"\C-dL": kill-line
"\C-dw": backward-kill-word
"\C-dl": backward-kill-line
"\C-da": kill-line
This is quite interesting. If I hit Ctrl+D alone (I selected d for delete), nothing happens. But if I then type a lower case w, the word to the left of the cursor is deleted. If I type an upper case, however, the word to the right of the cursor is killed. Same goes for l and L regarding the whole line starting from the cursor. If I type an "a", the whole line is actually deleted (everything before and after the cursor).
I placed jumping one word forward on Ctrl+F and one word backward on Ctrl+B
"\C-f": forward-word
"\C-b": backward-word
As you can see, you can make a shortcut, that leads to an action immediately, or you can make one, that just inits a character sequence and then you have to type one (or more) characters to cause an action to take place as shown in the example further above.
So if you are not happy with the default bindings, feel free to customize them as you like. Here's a link to the bash manual for more information.
Hold down the Option key and click where you'd like the cursor to move
If you happen to be a Vim user, you could try bash's vim mode. Run this or put it in your ~/.bashrc file:
set -o vi
By default you're in insert mode; hit escape and you can move around just like you can in normal-mode Vim, so movement by word is w or b, and the usual movement keys also work.
If you check Use option as meta key in the keyboard tab of the preferences, then the default emacs style commands for forward- and backward-word and ⌥F (Alt+F) and ⌥B (Alt+B) respectively.
I'd recommend reading From Bash to Z-Shell. If you want to increase your bash/zsh prowess!
As of Mac OS X Lion 10.7, Terminal maps Option-Left/Right Arrow to Esc-b/f by default, so this is now built-in for bash and other programs that use these emacs-compatible keybindings.
In Bash, these are bound to Esc-B and Esc-F.
Bash has many, many more keyboard shortcuts; have a look at the output of bind -p to see what they are.
Under iterm2's Preferences > Profile > Keys, you click the + below Key Mappings and record a new shortcut. For Action, select Send Escape Sequence and type b or f for backwards and forwards respectively.
When I tried to record one for (Ctrl+←), I noticed in the Keyboard Shortcut field that the arrow never showed up. Turns out I had to disable the default mac's System Preferences > Keyboard > Shortcuts > Mission Control shorcuts first to get things to work, as they'll override iterm2's default shortcuts. Should be true for the standard terminal app, too.
For some reason, my terminal's option+arrow weren't working. To fix this on macOS 10.15.6, I opened the terminal app's preferences, and had to set the bindings.
Option-left = \033b
Option-right = \033e
For some reason, the option-right I had was set up to be \033f. Now that it's fixed, I can freely skip around words in the termianl again.
Here's the CLI way to do so, verified it works on bash.
Add the following to your ~/.inputrc:
# macOS Option + Left/Right arrow keys to move the cursor wordwise
"\e\e[C": forward-word
"\e\e[D": backward-word
The advantage of this method is that it is terminal application agnostic - doesn't matter whether you use Terminal.app, iTerm2, or any other application.
Inspiration got from this other answer.
New answer for iTerm2 Build 3.3.4 users:
Step 1: (macOS X) System Preferences > Keyboard > Shortcuts tab > Select Mission Control (left panel) > Uncheck shortcuts that labeled as "Move left a space" and "Move right a space"
Step 2: (iTerm2 Build 3.3.4) Preferences > Profiles > Select * Default (left panel) > Keys tab > Delete both "⌥->" and "⌥<-" entries > Set both "Left Option (⌥) Key:" and "Right Option (⌥) Key:" to Esc+
No messing around with shell profiles, no messing around with inferior masOS (default) Terminal, no awkwards Esc+F/B, rinse & repeat non-sense.
Done deal!!!
Enjoy this tip, my fellow PROGRAMMERS!
As answered previously, you can add set -o vi in your ~/.bashrc to use vi/vim key bindings, or else you can add following part in .bashrc to move with Ctrl and arrow keys:
# bindings to move 1 word left/right with ctrl+left/right in terminal, just some apple stuff!
bind '"\e[5C": forward-word'
bind '"\e[5D": backward-word'
# bindings to move 1 word left/right with ctrl+left/right in iTerm2, just some apple stuff!
bind '"\e[1;5C": forward-word'
bind '"\e[1;5D": backward-word'
To start effect of these lines of code, either source ~/.bashrc or start a new terminal session.
Just check the "Use Option as meta key" option in Terminal > Preferences > Settings > [profile] > Keyboard, as mentioned here already by #cris-page.
Note however, that in macOS Catalina (10.15) and newer, zsh becomes the default shell for newly added users: its default configuration considers only whitespaces as word-boundaries, whereas the old bash makes meta-left/right jump to the nearest non-alphanumerical character (similar to B/W as opposed to b/w for those familiar with vim):
v----v- bash jumps here
$ vim some-folder/what.txt_<- jump left twice from here
^---^- zsh jumps here by default
(similar motions are true for meta-backspace as well)
There are more than one ways to make zsh command line editor navigation work similarly to bash's - here is one such method:
# Place in your profile init script, e.g. `~/.zshrc`
autoload -U select-word-style
select-word-style bash

Resources