Meta and # in a UK mac terminal - macos

In the mac terminal application there is a setting (preferences -> keyboard) that lets you set "use option as meta key". This is useful as a lot of unix boxes use bash as default shell and that has emacs keybindings M-f and M-b that let you skip words.
Problem is that on a Mac with a UK keyboard the # symbol is tricky to get to - normally it can be typed with alt-3, but not if you are in a terminal and alt=meta.
Anyone have a nice way round this?

I am using zsh and the following saved my day:
bindkey -s '^[3' \#

Set your keyboard language ( System Preferences->International->InputMenu ) to Australian
It is the same as UK except shift-3 gives #. You do lose the pound sign but if I do currency I use the ISO three character code GBP

The Australian layout is identical as mentioned except # is mapped to Shift 3 and £ is mapped to Alt 3.
Swap to Aus and the swap your ALT behaviour. This has annoyed me for while especially as it is in a non UK position to start with.

Earlier today I stumbled on a great solution to this on Graeme Sutherland's blog so thought I'd summarise it here in case it disappears.
If you want to stick with the built-in Terminal and don't want to lose the £ sign, you can use Ukelele roll your own keyboard layout to switch the section (§) key for hash instead. Quite a handy location for typing '#!' too :)
The keymap file Graeme created is here, but if you want to make your own you can simply take the British one as a base it's pretty straightforward to create the new keymap file.
Copy your new keymap file to ~/Library/Keyboard Layouts
Go to System Preferences - Language & Text - Input Sources
Scroll down to 'British with # for §' (or whatever you put as its name in Ukelele) and check the box
Check 'Show Input menu in menu bar'
Click on the flag in your menu bar at the top of the screen and choose your new input source
This input source can then be used in all apps, or just the ones you want it for.
I appreciate this and the linked question are quite old but thought this might help someone else.

ESC is another meta shortcut :). You don't have to keep pressing it though.
So in your situation, you might just need to press ESC once, and then press alt-3.

See image to get the details as to how to setup a shortcut in your terminal and fly free

I'm using iTerm2 and I was having this problem. With iTerm2 you can use the left alt key as a meta key, and the right as a normal key. So ralt-3 does the # key.

Based on ericteubert answer for zsh for bash you bind the key, I've added this to my .bash_profile:
bind '"\e3":"#"'
For vim you can add the following to your .vimrc
inoremap <ESC>3 #

Related

Is there a way to make alt-f and alt-b jump word forward and backward instead of printing ƒ and ∫ on Mac?

I understand that Mac has some Emacs keybindings enabled by default (e.g. Ctrl+A move to beginning of line etc.). If I open TextEdit for example I can navigate like in Emacs.
But when I try Alt+F or Alt+b for move to next word or last word it does not work. It prints out ƒ and ∫ instead.
Is there a way to jump words instead?
I think that I did not tinker with the keybindings and I use the US layout on a german keyboard.
If you want to re-enable them for the terminal
Terminal -> Preferences -> Keyboard
Check 'Use Option as Meta key'
my iTerm2 version is 3.1.6, profile -> keys -> set Esc+
Maybe one of these helps? (I don't use OSX myself, so I can't test anything).
http://blog.sensible.io/2012/10/19/mac-os-x-emacs-style-keybindings-everywhere.html
http://aufflick.com/blog/2006/01/10/emacs-keybindings-everywhere
Summary from first URL:
Create file ~/Library/Keybindings/DefaultKeyBinding.dict with the following content and restart all apps.
{
"~d" = "deleteWordForward:";
"^w" = "deleteWordBackward:";
"~f" = "moveWordForward:";
"~b" = "moveWordBackward:";
}
I'm a little confused if you're talking about the keys (within different apps on OS X) or specifically Emacs. On OS X the standard keys you would use to jump between words is:
option/alt + Left Arrow or Right Arrow
If it's specific to Emacs for OS X:
For Terminal.app, starting from Snow Leopard: Go to Preferences > Settings > Keyboard > Use option as meta key.
For iTerm: Go to Manage Profiles > Keyboard profiles > (your profile) > Option Key as…
If you want to use Option key for both international characters and
Meta key in Emacs, see info below for iTerm 0.10.x patch and/or binary.
Alt-b and Alt-f for navigating by word also works for your shell now.
UPDATE: The link the original website providing the patch is no longer online, however I was able to retrieve the cached information from the archive.org:
OSX + terminal + Meta key + national characters
Quite a mix, right? If you’re user of one of those keyboard layouts that have hidden some non-ISO1 characters under Option-key shortcuts and you use command line – read on, I might have a treat for you.
As it stands today, if you’re OSX user, and would like to use your Option (Alt) keys for both national characters and Meta-* shortcuts, you’re in for an unpleasant surprise – you can’t. It’s one or the other: both iTerm and Terminal.app allow you to flip between Option keys role, but neither of them allows you to use Option for both. Under Linux, it’s customary to use left Alt for Meta-* and right Alt for any national characters you might require. Same goes for Windows. Of course you can just train yourself in using ESC key in a prefix manner, but that’s avoiding the real problem.
Getting annoyed by this state of things, and faced with some Emacs usage, I decided to take advantage of the fact that iTerm is opensource software, and see if I can make a tiny change, to cater for my needs. Surely enough, after ~25 minutes I got a trivial patch: just changed the mask that iTerm uses for detecting that Option key is pressed down. It took few hours and 5 chapters of Cocoa book, to turn that into fully-fledged option in Keyboard Profiles section of iTerm. This was my first foray into lands of Objective C; while I came back victorious, I don’t see myself writing anything bigger in Objective C in nearest future.
Here’s the meat: ( https://sourceforge.net/p/iterm/patches/44/ )
“right Option is Normal” patch;
full patch allows you to pick which keys should be treated as Meta (both, only left, only right);
The patches were made against 0.10.x branch, at revision
1871.
Once you have the binary, launch it and go to Bookmarks > Manage profiles > Keyboard profiles. If you select a keyboard profile, you should see a new dropdown at the bottom of the keybindings list.
The options should be pretty much self-explanatory. The configuration shown above is the one I’m using — this way I get all Meta-* shortcuts with my left Option key, and all Polish characters with right Option key. Which is the way it Should Be™ :)
I haven’t heard from iTerm authors yet, so I have no idea whether this patch is going to merged upstream or not. I’ve been using my patched version for almost week and a half now, and nothing major exploded. Yes, iTerm is slower to redraw the screen on larger terminals (say, 130×80), but there are certain features (like 256 colors support) that make up for that.
more info: http://www.emacswiki.org/emacs/EmacsForMacOS
On iTerm2 3.0.15, go to:
Preferences -> Default -> Keys tab ->"Left option() key acts as:"
and change the value to:
+Esc
Solved this at the OS level as follows,
⟶ System preferences
⟶ Keyboard
⟶ Input Sources Tab
⟶ + at bottom left
⟶ Others in the left panel
⟶ add and select Unicode Hex Input from right panel
 ✓  Mac no longer prints anything on alt+letter|number
 ✓  enter unicode characters via alt+[code]
 ✅ the OS does not grab alt key shortcuts!
You should use KeyRemap4MacBook. In the Emacs Mode section, you will find numerous options to use the Option key as Meta including Option+BF to Option+Left/Right.
However, if you're a hardcore Dvorak user like myself who wants to use key bindings such as M-b and M-f using the original Dvorak layout, there's a problem. You can only "move backward/forward one word" in QWERTY layout. I use version 8.4.0 so I don't know about the latest version for Mavericks.
I use BetterTouchTool. Works like this:
Basically remaps Option-F and Option-B to Option-Right and Option Left, and I turned this on for any apps that I want the shortcut in, e.g., Firefox, Obsidian, Slack. Works great!
For Hyper you can fix the option key by setting the following configuration to your ~/.hyper.js file:
module.exports = {
config: {
modifierKeys: { altIsMeta: true }
}
}
source

iTerm2: delete line?

I'm trying to map ⌘+Delete (backspace) to delete to the beginning of the line (like it works in browsers and text editors) in iTerm2 and I'm unable to find a working escape code for it. I tried 1K (^[1K) based on what I read in Wikipedia. It just prints a "K".
Edit: I found Ctrl+U. Now to find out how to map it. Maybe Hex code 21 (U being 21st letter), so 0x15?
I got it. I have no idea why Hex Code mappings in iTerm2 produce the associated Ctrl+key mappings, but they do. No idea what 0x00 means, either, as it's not assigned to A as might be expected. (though I do believe Unix has its own conventions relating to treating null bytes -- we have e.g. xargs accepting a null byte delimiting format from find for example -- It would be neat if we can bind this to a hotkey with iTerm2)
I was able to find that Ctrl+U does nearly the exact task I want (it deletes the entire line rather than deleting only what is before cursor, but whatever... Ctrl+Y as a bonus can bring it all back). Then I curiously saw that I had hex codes 0x1 and 0x5 mapped to ^A and ^E respectively, for my Cmd+Left and Cmd+Right... so 0x15 is for ^U!
For Mac OS, most editor share the common shortcut ⌘ + Delete: delete to start of the line, in iTerm2 we can switch to this key configuration
Mapping hex code 0x15 to ⌘ + ←Delete in most shells deletes the entire line (content to the left and right of the cursor). While sometimes not as compatible, I find that mapping:
⌘+←Delete to Send Hex Codes:
0x18 0x7f
performs the desired functionality. If you're running ZSH, you'll likely also need to add this to your .zshrc file:
$ echo 'bindkey "^X\\x7f" backward-kill-line' >> ~/.zshrc
as by default ZSH doesn't map backward-kill-line to anything.
Furthermore, you can also delete everything to the right of your cursor by mapping:
⌘+fn+←Delete or ⌘+Delete→ to Send Hex Codes:
0x0b
I wrote a comprehensive guide to adding most of OSX's standard keybinding to your terminal here
In OSX, ⌥+⌫ and ⌘+⌫ are the shortcuts for deleting a word and deleting a line respectively. ⌘+ ← and ⌘+ → are for going to the beginning and end of lines. By default, iTerm2 isn't configured this way, and there are a lot of misleading guides online. The following is what I've found to work on my machine.
Open the preferences (⌘+,) and go to the Keys tab.
Add a global shortcut key, and just type in your shortcut
In the Action dropdown, select Send Hex Code
The hex codes for...
Deleting a word: 0x17.
Deleting a line: 0x15.
Moving to the beginning of the line: 0x01.
Moving to the end of the line: 0x05.
Just open a new tab, and it should work!
Here is a screenshot, for clarity:
I hope this may help you
map ⌥ <- Delete to Send Hex Codes: 0x1B 0x08
I had test for it, and it is correct.
18.09.2013 update
this delete one word, not a line.
As pointed ^U deletes the line. You can easily remap the command by using Better Touch Tool.
It also has cool features for automation, mouse, pad and keyboard mapping. Also includes a window feature for smart borders.
On iTerm2 you can set the exact same shortcuts of your OS. In this case, as the default shortcut to delete a line on Mac OS is ⌘+Delete (backspace), you can do so.
To set the default keybindings of iTerm you have to:
Go to Preferences (or ⌘+,)
Profiles
Keys
Key Mappings
Presets...
Select the "Natural text editing" option
The location has changed. In order to enable natural editing go to:
Preferences -> Profile -> Keys -> Load Presets... -> and select Natural Text Editing
For more info and tweeks go https://blog.arturofm.com/install-iterm-terminal-emulator-on-macos/

Textmate: remap Escape for word completion

In the Textmate code-editor I use the Escape-key, for word completion, alot.
Is there a way to bind another key-shortcut to its functionality ?
(ps: my CAPSLOCK is already CTRL)
A much better way to do this (and this applies to all Mac apps in general) is to
Open System Preferences > Keyboard & Mouse > Keyboard shortcuts
Click the + sign at the bottom
Choose TextMate from the application menu
Type the exact name of the menu command for next completion and previous completion
Now type the shortcut you want to use and click the Add button
To remap the esc key you have to copy
/Applications/TextMate.app/Contents/Resources/KeyBindings.dict
to
~/Library/Application Support/TextMate/KeyBindings.dict
and then edit it, preferably using TextMate :) as Property List Editor messes up the codes.
Look for nextCompletion and previousCompletion and replace their values with whatever suits your needs best. For example, you could replace \033 (code for esc) to \t (->|).

OS X Terminal: Meta key + alt functionality at the same time

Is there a way to use an alt / option key as a meta key but still be able to use it to make some characters which need it?
For example, in my local keyboard layout:
# is alt + 2
\ is alt + shift + 7
| is alt + 7
etc.
So, if I set alt as a meta key, I can't make those characters anymore. On the other hand, using "press esc, release esc, press a key" to make meta key sequences makes my hands hurt.
Any Emacs users with international keyboards who have solved this, please give any tips you might have! :)
Edit:
It appears that I can set alt as a meta key and then add these kind of settings in inputrc: "\e2": "#" This works in the bash shell but it still won't work with Emacs though, so no good.
I use a Swedish keyboard in Mac OS X and use the following setup for Emacs.app:
First I have KeyRemap4MacBook installed and I have it setup to change the left Option key to Command.
I then have the following in my .emacs:
(setq mac-option-modifier 'none)
(setq mac-command-modifier 'meta)
This makes Emacs treat command as Meta and ignore Option. Since the left Alt/Option key is remapped to command, this makes it work lite meta while the right Alt/Option key still works for entering special characters like # [] and {}.
App specific Mac shortcuts like Cmd+C and Cmd+V no longer work, but global shortcuts like Cmd+space for Spotlight and Cmd+Tab for app switching do.
Update:
If you use iTerm2 as a Terminal, that has support for mapping only the left Alt/Option key to meta, which means you can still use the right AltGr/Option key for entering special characters. This also means you can use meta as normal inside Emacs running in the iTerm2 terminal.
I have a Swedish keyboard on my Mac and I'm using Aquamacs. Adding the two lines (attribution goes to Joakim Hårsman)
(setq mac-option-modifier 'none)
(setq mac-command-modifier 'meta)
in .emacs (and restarting Aquamacs) did the trick for me.
with iTerm2 you can map the left option key to ESC/meta and leave the mapping of the right option key to "normal". This way you can use the right option key to type accents etc.
Think about using a full featured Emacs for Mac OS X. I use Carbon Emacs but I believe others (say Aqua Emacs or X11 Emacs) would do the trick.
If you insist on using Emacs in a terminal you can use the C-x 8 prefix as a compose key. Try C-x 8 C-h to get a list of possibilities.
See http://www.emacswiki.org/emacs/EmacsForMacOS
Two work-arounds I use:
I use xterm running under X11.app. X11.app uses the command key as meta.
When running emacs in Terminal.app, I just use the rfc1345 input-method, which allows me to enter all kinds of crazy non-ascii characters without needing an option key.
Check out cmd-key-happy. This little app has worked wonders for me. It allows you to use command as meta, with exceptions that you can configure.
Author's info follows:
This program allows you to swap the command and alt (or option) keys
in any application, but in particular Terminal.app.
http://github.com/aim-stuff/cmd-key-happy
This is an old post but adding an alternatives for Robots to find.
I borrowed a couple of files from Aquamacs(emulate-mac-keyboard-mode.el, aquamacs-tools.el) that fixes the problem (I have a Italian-Pro keyboard) :
(defun aq-binding (any)
nil)
(load "~/.emacs.d/emulate-mac-keyboard-mode.el") ;; 'noerror
this provides:
few minor modes (emulate-mac-italian-keyboard-mode,
emulate-mac-french-keyboard-mode,
mulate-mac-swiss-german-keyboard-mode, etc)
a menu to play with all the options provided by Aquamacs
Tested with Emacs-23.3-universal-10.6.6 and seems to work ok for me.
Thanks Aquamacs for this, what about pushing this upstream if not already done.
It's worth thinking about the assumption behind the question. I mean to say that the real problem is making the characters that currently seem to need the option key. This problem can be solved without achieving simultaneous 'meta key + alt functionality'.
Let me explain: I have a similar problem. On my UK keyboard, shift-3 is mapped to the pound sign, £, which means that I generally need to hit option-3 to get the very useful # - a real problem in Terminal, where I use option as meta. However, I find most of the above solutions to be a little over-the-top. I don't want to change to another version of Emacs (eg. Aquamacs), to switch to a different Terminal application (eg. iTerm or xterm), or to install a key-remapping application (eg. KeyRemap4MacBook) all for the sake of one symbol! Perhaps that would suit some people, but I thought it was worth pointing out that if the problem is just one character, it can be solved with a nine-character text file.
With regard to my personal version of this problem, I find the simplest solution is to create a file called .inputrc in my home directory, consisting of the following single line:
"§": "#"
This re-maps the (to me, quite useless) § that can be found to the left of the 1 on the current Mac keyboard to the (almost indispensable) #. That suits me even better than the default setup, because I can now get # with a single keypress. If there were any other characters I needed to remap, it would just be a matter of adding an extra line for each one.
Anyway, that deals with how to get the missing character in the shell, but if you also want it in Emacs (which you didn't say but is probably the case) then you can add something like this to your .emacs file (where 35 is the ASCII for the character I happen to want, ie. #):
(global-set-key (kbd "§") 'insert-hash)
(defun insert-hash ()
(interactive)
(insert 35))
It might not be such a neat solution if there were dozens of characters that I routinely wanted to access via the option key, but there aren't.
I hope this helps somebody. As a mere weekend hacker, I ordinarily wouldn't dare post an answer to a question on Stack Overflow...
Special keyboard layout with option deadkey
My solution to this problem is a special keyboard layout I have written, U.S. custom. It provides an option deadkey that produces option combos without having to use the physical ⌥ Option modifier key. For instance, the character ⟨ç⟩ is produced as follows on a normal U.S. keyboard layout:
Hit ⌥ Option+c.
The U.S. custom keyboard layout adds a second way of producing ⟨ç⟩:
Hit ⇧ Shift+§ (the option deadkey), then release it, then hit c.
This works even in Terminal.app when Use option as meta key has been checked.
Note that the U.S. custom keyboard layout does two additional things:
It converts plain § into a ⎄ Compose key (so you could also produce ⟨ç⟩ by hitting §, then ,, then c).
It replaces the CapsLock mapping by a (significantly extended) U.S. Extended keyboard layout.
Remap option deadkey to right option modifier key
If you have a physical ANSI keyboard, then you lack the § key. In that case, I recommend assigning the § key to some other key, for instance to the right ⌥ Option modifier key. Install KeyRemap4MacBook, open ~/Library/Application\ Support/KeyRemap4MacBook/private.xml and paste the following code:
<?xml version="1.0"?>
<root>
<item>
<name>Send ISO Section for right Option</name>
<identifier>private.send_iso_section_for_right_option</identifier>
<autogen>--KeyToKey-- KeyCode::OPTION_R, KeyCode::UK_SECTION</autogen>
</item>
<item>
<name>Send Shift+ISO Section for Shift+right Option (keep normal right Option without Shift)</name>
<identifier>private.send_shift_iso_section_for_shift_right_option</identifier>
<autogen>--KeyToKey-- KeyCode::OPTION_R, ModifierFlag::SHIFT_R, KeyCode::UK_SECTION, ModifierFlag::SHIFT_L</autogen>
<autogen>--KeyToKey-- KeyCode::OPTION_R, ModifierFlag::SHIFT_L, KeyCode::UK_SECTION, ModifierFlag::SHIFT_L</autogen>
</item>
</root>
Then, open the KeyRemap4MacBook preference pane, hit ReloadXML and then select “Send ISO Section for right option”. Now, your ⌥ Right Option key is remapped to §, so while the U.S. custom keyboard layout is active, hitting ⇧ Shift+⌥ Right Option will give you the option deadkey state (hitting ⌥ Right Option without additional modifiers will give you a deadkey state equivalent to the option modifier.
If want to keep ⌥ Right Option when ⇧ Shift is not pressed (instead of the ⎄ Compose key), then select “Send Shift+ISO Section for Shift+right Option (keep normal right Option without Shift)” in the KeyRemap4MacBook preference pane (instead of “Send ISO Section for right Option”). Like that, only ⇧ Shift+⌥ Right Option will produce the option deadkey, while plain ⌥ Right Option will continue to work as an option modifier. You can even continue using ⌥ Right Option+⇧ Shift modifier combos (for instance ⌥ Right Option+⇧ Shift+c→⟨Ç⟩) as long as you don’t hit ⇧ Shift first.
The above answers mention ways to enter non-ascii input, but that's not really the problem here. The C-x 8 method lets you enter a bunch of non-ascii, but the problem is that you need the option key on mac just to enter the (ascii) character `|' (vertical bar)!
So how do you then enter stuff like M-| (region to shell command) when running emacs in ssh under Terminal.app? No way for it but to use the escape key, since | is option-7 and Terminal.app for some stupid reason won't let you use Cmc as meta :-(
(If anyone knows of a hack (SIMBL perhaps?) that actually does let Terminal.app use Cmd as meta, I'd be very grateful...)
The following solution works, is UNOBTRUSIVE and you don't need iTerm2 or Aquamacs or whatever.
Step 1
Keep "Use option as meta key" turned ON in the Terminal.app Settings.
Step 2
Edit ~/.inputrc (make it if it doesn't exist already), add the following line:
"\e3": '#'
This will remap ⌥ alt + 3 so that you produce a # character as expected in the terminal, instead of it annoyingly coming back with the prompt (arg: 3).
Step 3
Edit ~/.emacs, add the following line:
(global-set-key (kbd "M-3") "#")
This will remap ⌥ alt + 3 so that you produce a # character as expected inside emacs, instead of it annoyingly doing nothing.
Caveat 1, This is just 1 re-map. So ⌥ alt + ? (other keys) won't be remapped, e.g. you may wish to remap ⌥ alt + n to produce the tilde key ~. Simply follow the same steps outlined above obviously switching 3 with whichever key you need going forward.
Caveat 2, When you ssh into another box, you will face the same difficulties, but all you have to do there is edit the ~/.inputrc and ~/.emacs files on that box.
Caveat 3, I'm British, on a British MacBook. So I can't vouch for foreign MacBooks.
Aquamacs supports that, at least for my (french) keyboard. Once Aquamacs is installed (via drag'n'drop), you can go to Options -> Option, Command, Meta keys and choose an appropriate setting for your keyboard (in my case, ...Meta & French). I am not proficient with Emacs, but all the useful combinations I have tried seem to work ([, {, |, and so forth).
Supported keyboards, according to the menu items as of version 2.1, are :
British
US
Swiss-french
Swiss-german
Finnish
Italian-Pro
Italian
Spanish
French
German
I would guess the Aquamacs team would be grateful for any contribution, though, should your keyboard not appear in the list.
I bit the grass and started hitting the escape key instead. You get use to it...
I would like to mod this question up or something because i also use a Swedish keyboard where i must press alt+7 or alt+shift+7 to make | and \ respectively.
I also use Irssi in Terminal.app and these don't mix well.
I'm a long time vim user though so emacs is not an issue to me.
Isn't there some way to remap CMD to be Meta in Terminal.app?
So far i've been surviving by simply typing /wg N in Irssi because having those characters in my Terminal is much more important than IRC.
A solution would be worth gold to me though! :)
This is years late, but for people coming across this page whilst searching for a solution, as I did, I have decided to build one myself, one that doesn't require abandoning Terminal.app in favour of iTerm 2.
It is a simple status bar app that runs in the background and rewrites all left-Alt + $KEY key events to two key events in rapid succession, Esc, then $KEY; however, it only does this if Terminal.app is the focused application.
You can find it here at https://github.com/habibalamin/Metalt.
I assigned escape to the caps lock key and it works quite good. You can configure it easily in the mac system preferences > keyboard > modifier keys.
https://apple.stackexchange.com/a/282092/236382

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