Hacker News new | past | comments | ask | show | jobs | submit login
Moving efficiently in the CLI (clementc.github.io)
434 points by okket on Jan 26, 2018 | hide | past | web | favorite | 165 comments

Here's a few more that the diagram is missing, along with a function I created that inserts these commands (in dark gray so it's not intrusive) every time I start ZSH shell, like flash cards.

Keep in mind, most of these work anywhere in OS X, not just in the terminal.

Put this in your .bashrc or .zshrc

    # MOTD
    function echo_color() {
      local color="$1"
      printf "${color}$2\033[0m\n"
    echo_color "\033[0;90m" "c-f  Move forward"
    echo_color "\033[0;90m" "c-b  Move backward"
    echo_color "\033[0;90m" "c-p  Move up"
    echo_color "\033[0;90m" "c-n  Move down"
    echo_color "\033[0;90m" "c-a  Jump to beginning of line"
    echo_color "\033[0;90m" "c-e  Jump to end of line"
    echo_color "\033[0;90m" "c-d  Delete forward"
    echo_color "\033[0;90m" "c-h  Delete backward"
    echo_color "\033[0;90m" "c-k  Delete forward to end of line"
    echo_color "\033[0;90m" "c-u  Delete entire line"

    Keep in mind, most of these work anywhere in OS X,
    not just in the terminal.
That's one of my absolute favourite things about Mac OS -- because Cmd exists, and takes over what Ctrl is used for on Windows and Linux, I can use these Ctrl commands and they work as I expect.

I wonder if it's possible to get Linux to work the way the Mac does in this regard? Allocate a Meta key to do what Ctrl does move of the time, so that these Ctrl commands became available again? I'd really find it easier to use Linux if that was possible.

Yes, that works out of the box with every KDE application. I recommend Super as modifier key rather than Meta because most keyboards on the market have a physical Super key or two.


Gnome/GTK and KDE both have keybinding themes that can be set to emacs. You can do it for GNOME/GTK from gnome-tweak tool. Otherwise you can use gsettings or edit the config directly. Just google "emacs gnome keybindings".

>>That's one of my absolute favourite things about Mac OS

Mine too, but I'm on Windows where none of this work out of the box. However, I've found XKeymacs [0] which allows Emacs keys system wide. It is not fool proof, but I've found that the movement keys can be used without much trouble.

Currently I use:


C-b C-f backward/forward-char

M-b M-f backward/forward-word

C-p C-n previous/next-line

C-a C-e Home End

C-x h


M-l M-c downcase-word, capitalise-word

M-F12 rollup-window

C-z iconify-deiconify-frame

C-q enable-disable xkeymacs

[0] https://github.com/fujieda/xkeymacs http://xkeymacs.osdn.jp/

I also use TouchCursor [1] to get vim like hjkl movement system wide while Space is pressed

[1] https://martin-stone.github.io/touchcursor/overview.html

  Keep in mind, most of these work anywhere in OS X, not just in the terminal.
Adding on to this - this works in many places in OS X, since many programs happen use NSTextField, which can have shortcuts configured at the OS level.

You can further customize the shortcuts available in a file called DefaultKeyBinding.dict

I use a very slightly modified version of this: https://gist.github.com/cheapRoc/9670905

I highly recommend looking into that, for anyone who is familiar with emacs keybindings and would like them everywhere.

Nice idea and important quick-movements.

However as a Vim user (mostly motivated by the fact that I can move around pressing single keys which I find more "wrist-ergonomic" - potential fast navigation is a nice plus), I always wonder how heavy emacs users deal with CTRL-acrobatics and movement - do you use c-f/c-b for going forward/backward or the usual cursor keys?

For vi users it makes sense to set $readline (~/.inputrc) to vi-style, so for completion here the vi-style bindings (although probably obvious if you used to Vim).

  l "Move forward"
  h "Move backward"
  k "Move up" (step history backward)
  j "Move down" (step history forward)
  ^ "Jump to beginning of line"
  $ "Jump to end of line"
Deleting works as usual with `d` combinations. Furthermore it is convenient to search the history via `/`.

Honestly, I press both ctrl keys with my palms: http://ergoemacs.org/emacs/swap_CapsLock_Ctrl.html

I'm hearing people say that "that's impossible" or "it's weird", but I've used this method for ~2 years now. It has become muscle memory.

It is the BEST method.

I put a little pad over the Ctrl Keys to press it easily with muy palm.

Ctrl-heavy programs are much easier to use when you map the Ctrl key back to its original position, leaving the Ctrl-labeled key for whatever Hyper needs you have.

Yes, the Lisp Machine keyboard layout: https://deskthority.net/wiki/Symbolics_layout

That way you can press Control or Alt/Meta (or both at the same time) with the thumb of either hand without a lot of movement. C-f and C-b can be done with either left hand only, or left hand for f/b and right thumb on Control (what used to be Alt, on PC keyboards). Rebinding Caps Lock to Backspace also saves a lot of hand movement. Only a handful of small changes and you get a much better keyboard layout.

Is it just me or it looks crazy that the Space Cadet keyboard has thumbs up and down? https://deskthority.net/wiki/File:Space-cadet_guts.jpg

Looking at the keys below maybe it was for up/down.

> do you use c-f/c-b for going forward/backward or the usual cursor keys?

I do. With emacs, you usually have a finger near the Ctrl key at all times anyway, so hitting f or b is much more convenient than moving my right hand over to the arrow keys.

I love these shortcuts in Vim, but now that I primarily type in Dvorak, I have since reprogrammed my keyboard to have the home, end, and arrow cluster directly beneath my fingers on the home row. Just need to activate a function layer with my thumb in order to access those keys. The keyboard I use is called an Atreus.

You absolutely have to remap the caps-lock key to your control key... it's so vital. It unlocks a whole paradise of hotkeys that are easily accessible.

I meant to include it in my original post but I can't edit it now.

Here's a version for fish, goes in ~/.config/fish/config.fish

  # MOTD
    function echo_color
      printf "\033[0;90m$argv[1]\033[0m\n"
    echo_color "c-f  Move forward"
    echo_color "c-b  Move backward"
    echo_color "c-p  Move up"
    echo_color "c-n  Move down"
    echo_color "c-a  Jump to beginning of line"
    echo_color "c-e  Jump to end of line"
    echo_color "c-d  Delete forward"
    echo_color "c-h  Delete backward"
    echo_color "c-k  Delete forward to end of line"
    echo_color "c-u  Delete entire line"
And a slightly optimized bash version (YMMV):

  # MOTD
    function echo_color() {
      printf "\033[0;90m$1\033[0m\n"
    echo_color "c-f  Move forward"
    echo_color "c-b  Move backward"
    echo_color "c-p  Move up"
    echo_color "c-n  Move down"
    echo_color "c-a  Jump to beginning of line"
    echo_color "c-e  Jump to end of line"
    echo_color "c-d  Delete forward"
    echo_color "c-h  Delete backward"
    echo_color "c-k  Delete forward to end of line"
    echo_color "c-u  Delete entire line"

C-u deletes everything to the left of the cursor

Can someone explain the benefits of c+(f,b,p,n) instead of plain arrow keys?

Also, for c+h/d there's always a dedicated key/single stroke for at least one of those delete actions.

In addition to the control- versions, there are meta- and control+alt- versions that work the same way in greater logical units. For example, moving forward by 1 character/word/sentence-or-expression uses different modifiers for the same keybinding. In Emacs, these consistenly pervade the interface, so, for example, paragraphs in text modes are akin to blocks in or functions in programming modes (depending on if the language is block or function based). This is one reason that Emacs tends to swallow other user interfaces for dedicated Emacs users — everything is highly consistent, and you get a giant head-start on a new systems. Of course, it helps that Emacs is massively customizable, so when something doesn’t quite do what you want, it’s usually a very small bit of hacking to change that.

Historically, many of those keybindings date back to very crude remote terminals where control codes and tty modes were a real concern. For example, I’ve used systems (in the 90’s) where the delete key could freeze your remote connection. Emacs, because of it’s age and ubiquity, has grown up somewhat “around” those traps.

Your fingers stay near home row so you can type faster. Cursor keys are way to far off and differ very much between different keyboards.

What about any benefits of moving your hands around though?

Unless one is a court typist, where wpm matters fully, maybe moving a little and not keeping one's hands on the home row can help avoid carpal tunnel and RSI?

You can keep your hands in typing position on the keyboard while performing these operations. Using the arrow keys or backspace means you need to move to another part of the keyboard which interrupts your flow.

Point taken, thank you. Though, trying it out now, I realised f,b,p,n are not quite next to each other, and funnily enough, while I can easily type without looking at the keyboard, when I use a modifier key, the muscle memory used for typing doesn't seem to help as much, it seems it needs new training. Seems I need to flex more :)

Ctrl+W Delete word (and following spaces). [works in BASH at least]

    c-t  Swap chars (useful for correcting typos)

Unfortunately a lot of these don't work anymore in Firefox in newer versions. No idea why. (alt-b for example)

In Firefox under Ubuntu/MATE with keyboard theme "emacs", most of these bindings are followed. Ctrl-W is taken up as "close tab".

This is great, does anyone have an equivalent for fish?

One of the other replies to my comments appears to have converted it to Fish!

Fantastic, thanks for the heads up!

    set -o vi
Vi keys in the editor, Emacs on the CLI? This has never made any sense to me.


Its a historical artifact of how in-line edit emerged as a thing for most people. MIT had huge influence in the development of window systems (X10/X11) and adopted emacs string edit mode in most type in boxes. Bash came from a community which had a strong emacs usage. So, the default in both the window system and in the bash shell, was emacs, even if you use ed/ex/vi

Because most people used awk/grep/sed/ed/ex/vi the regex format tended that way. But enough people used tcsh or bash in emacs by default, that shell and omnibox (when browsers eventuated) edit defaulted to emacs.

Thats my theory: accidental happenstance and defaults.

And if I'm not mistaken, during that time, the ctrl key was typically where caps lock is today (maybe just on certain machines?) - and that is what influenced the frequent use of ctrl for key shortcuts in libraries lile readline.

may well be. not that escape is so far away from a pinkie, for the modal people (like me)

It pretty far away, compared to capslock. Especially on modern laptops.. lile touch bar macs that actually remove the the entirely

Hateful. Annoying. Thank goodness for kbd remapping

I am a fan of vi/vim, esp. as a remote shell editor. But the vi support in readline CLIs is overkill IMHO. I don't see the need for the 'extra power' of vi there, esp. the modes. A few well known keyboard short cuts are just fine for a CLI.

This also works the other way around: A few EMACS based shortcuts are the better 'lowest common denominator' than to force vi modes on everyone. Many are not willing to go down the vi/vim path, for various reasons.

I disagree, and find the vi mode (and extended Vim bindings) very useful in the shell.

Consider a long cURL command split over several lines. If every option is on a separate line, removing one is a `dd` keystroke away. Adding a new option is also very efficient.

Extended Vim bindings will also allow you to delete everything within brackets/delimiters (e.g. `di"`) or delete everything up until a character, etc. These are all simple keystrokes that translate well to the shell.

You could also open the command in your $EDITOR anyway (bound to `V` for me), but I reserve that for really long and unwieldy commands.


ed(1) is the standard editor


After years of using Vim and Bash this was a relief that I learned way too late. For the lazy ones

  $ cat >~/.inputrc 
  set editing-mode vi
  set keymap vi

  $if mode=vi
    set keymap vi-insert
    "jj": vi-movement-mode
Obviously you want to change vi-movement-mode to your favorite ESC style. E.g. searching through your last git commands becomes 'jj/git' then (you have to go to movement mode first, as insert mode is the default in the shell - which makes kind of sense).

Thank you for this! I had no idea this existed. It is perfect for vim users. Very happy that I can now jump around to my heart's content without learning a new set of keyboard shortcuts.

Even better is to create a .inputrc configuration file. This is used by readline so it will affect your shell and some other utilities. You can do even more in there too.

For example I use this:

  set editing-mode vi

  # Up and down arrows keys search history based on what is already typed.
  "\e[A": history-search-backward
  "\e[B": history-search-forward

This is actually my preferred config. The reason being emacs shell buffers. I can interact with any shell tool using the full text editing features of emacs. I've had to interact with many Oracle databases via sqlplus. "sqlplus" is not a fun tool to use on the shell. However in emacs it is perfectly fine and works as well as the command line interfaces from PostGRE or MySQL. The inline shell also allows automatic history, block selecting and line truncate/wrapping controls across all tools. However for pure text editing, it's always vim for me. I've even found myself launching emacs+shell within tmux in one pane and vim in another.

Sorry, unrelated nitpick but the name is PostgreSQL or Postgres. Postgres started in 1986 as a followup to Ingres and the name was meant to mean after-Ingres. The query language was later replaced with SQL and the name changed again to a portmanteau of Postgres SQL

It's never PostGRE.


Have you tried sqlcl from Oracle? 20 meg download (requires java). Up down left right work. Use sql hr@ instead of sqlplus hr @ (I am one of the developers.) . I should try it from within Emacs.

Why not just use emacs everywhere? I suppose if you use spacemacs (which has vim keybindings) then you might want to 'set -o vi' on the command line.

Emacs has Org-mode & Magit, each of which should be reason enough to switch. Then there're notmuch, gnus, slack-mode, eww …

Seriously, emacs really is a more powerful environment[0]. Modern vim tries to be as flexible as emacs, but the language isn't as nice.

E.g. Damian Conway's[1] simple example:

    function! ToggleSyntax()
       if exists("g:syntax_on")
          syntax off
          syntax enable
    nmap <silent>  ;s  :call ToggleSyntax()<CR>
would be:

    (defun toggle-syntax ()
      (syntax (not syntax))
    (global-set-key (kbd "M-C-s") toggle-syntax)
in a hypothetical elisp for a vim-like editor[2]. In his article he refers to vimscript a more humane than elisp, but I think this simple example shows he's wrong.

His next example is a command to capitalise a line, centre it, then move down:

    function! CapitalizeCenterAndMoveDown()
       s/\<./\u&/g   "Built-in substitution capitalizes each word
       center        "Built-in center command centers entire line
       +1            "Built-in relative motion (+1 line down)
    nmap <silent>  \C  :call CapitalizeCenterAndMoveDown()<CR>
I think this is a lot clearer:

    (defun capitalize-centre-and-move-down ()
      (upcase-region (line-beginning-position) (line-end-position))
      (center-region (line-beginning-position) (line-end-position))
[0] https://sites.google.com/site/steveyegge2/effective-emacs

[1] https://www.ibm.com/developerworks/library/l-vim-script-1/in...

[2] For the real emacs, it's just font-lock-mode.

I've used Emacs off and on for years now. But I can never get to that place where I get totally emersed because of the clunky terminal/shell story. I've tried eshell but what always gets me is having to C-c while in the terminal or eshell to get back to a different buffer.

I prefer M-x and fuzzy function entry to key bindings and when I'm in a terminal buffer or eshell I always go for M-x which won't work.

Any tips would be appreciated as I really like everything else about Emacs.

term and ansi-term bind the whole keyboard, but eshell and shell don't. Are you sure you are really running eshell?

I used to have a command “vi” in eshell that basically ran find-file. It took some getting used to using Emacs keys after invoking a command vi, but it worked.

If you modify your .inputrc with the following this should propagate to all of readline as well (e.g. python):

    set editing-mode vi

What shell does that work in? On a mac, I have that set in my .inputrc and it does not propagate to python.

Bash. Actually it depends if the program uses libreadline - which should be the case for Python's REPL?

You may try `rlwrap` which wraps programs without readline support.

I came here to post that, glad you beat me to it. Reaching for that control key? Ouch. Though I guess when you use vi keybindings, you are occasionally reaching for the escape key.

But, there is something to be said for meeting people where they are. If folks know the emacs keybindings, let them 'control' away!

Remap that caps lock key that you never use to ctrl. Your life is changed. You are welcome :)

As a dyed in the wool Vi user. I still want ctrl where I can reach it easily.

Ctrl-[ for escape and when in Insert mode, ctrl-h backspace; ctrl-w delete word; ctrl-u delete line; Ctrl-m return; ctrl-i tab, etc.

I once swapped Ctrl and Alt and never looked back. It feels so natural and it happens to match Symbolics Space-Cadet Keyboards layout too http://xahlee.info/kbd/space-cadet_keyboard.html

Advised by http://xahlee.info/kbd/linux_swap_modifier_keys.html

    ! -*- coding: utf-8 -*-
    ! 2013-02-04 swap Alt and Ctrl http://xahlee.info/

    !  xmodmap -pke | egrep '(Control|Super|Alt|Menu)'
    ! keycode  37 = Control_L NoSymbol Control_L
    ! keycode  64 = Alt_L Meta_L Alt_L Meta_L
    ! keycode 105 = Control_R NoSymbol Control_R
    ! keycode 108 = Alt_R Meta_R Alt_R Meta_R
    ! keycode 133 = Super_L NoSymbol Super_L
    ! keycode 134 = Super_R NoSymbol Super_R
    ! keycode 135 = Menu NoSymbol Menu
    ! keycode 147 = XF86MenuKB NoSymbol XF86MenuKB
    ! keycode 204 = NoSymbol Alt_L NoSymbol Alt_L
    ! keycode 206 = NoSymbol Super_L NoSymbol Super_L

    clear control
    clear mod1
    keycode 37 = Alt_L Meta_L
    keycode 105 = Alt_R Meta_R
    keycode 64 = Control_L
    keycode 108 = Control_R
    add control = Control_L Control_R
    add mod1 = Alt_L Meta_L

Im a broken record in this thread right now... for goodness sake, remap capslock to ctrl!!

That's the first thing I do when I start a new MBP.

Yep, me too. The second thing I do is to remap the right alt key (used to be a numeric keypad 'enter' key back on my original MacBook Pro) to a second ctrl key.

I'm always confused by laptop designers who only include one ctrl key. How are we supposed to properly touch type modifiers otherwise?

> I'm always confused ...

Just stating the obvious: you’re not their target consumer.

Maybe, there's probably some truth to that.

Apple do make it easy to remap the Alt key though and include a terminal and CLI commands by default so they must have some interest in business from people like me. ;)

(I would like to start a campaign to get the Mac Unix science page back again https://www.macobserver.com/tmo/article/apple-drops-science-...)

different strokes for different folks. I did not know about those insert mode keystrokes. Thanks!

Yeah, I have some problems with RSI in my right wrist (stop sniggering at the back).

I think it's mostly down to the way I twist to reach backspace rather than move my whole hand from the home row. Ctrl-h, Ctrl-w and Ctrl-m really help with that.

The only problem I have is that I don't know how to remap Ctr-m to return in X windows applications. I use Karabiner on a macOS and Gnome Tweak tool on Linux for the others.

It's somewhat frustrating to have different shortcuts in the terminal, where I spend most of my time and the browser where I spend most of the rest.

Edit: (If anyone can suggest a good way of mapping ctrl-m to return in Linux browsers I'd really appreciate it.)

Also ctrl-c does everything esc does in vim. When capslock is remapped to ctrl, its far easier and faster in most cases than reaching for esc.

Doesn't ctrl-c clear the whole line (maybe SIGINT related?) in vi-mode?

Well, in vanilla vi - I'm not sure (quite frankly, anyone who stands by vanilla vi as a great way to edit text is fudging insane). In typical VIM installs, ctrl-c and esc are aliases of one another.

Yeah, I meant vi(m)-mode in Bash/readline as mentioned in this discussion. When editing or correcting a command it may be inconvenient to destroy the whole line when switching to movement-mode (which does not happen, if it is not ctrl-c).

On the Japanese keyboard, Ctrl is where it should be: above Shift, replacing the useless and memetastic CapsLock.

You can always use ctrl-[ instead of esc.

One thing that annoys me on macOS is that "set -o vi" stops tab completion from working when logging in as root.

  $ sudo -i
  $ cd /va<tab> #results in "cd /var"
  $ set -o vi
  $ cd /va<tab> #results in: "cd /va    "

Not enough people know about this config, bash/zsh compatible.

Those shortcuts are a subset of those offered by GNU Readline, which is e.g. used by Bash and emulated by Zsh. Readline can offer Emacs-like (by default) or Vi-like keybindings:


I recently discovered that macOS has native support for these Emacs key bindings (https://jblevins.org/log/kbd) on it's textfields. This includes things like text editors, browser address bars, input fields and of course all terminal emulators.

I still prefer Vim as my editor, but learned these key combo's because they are just so portable.

Except option as meta (terminal excepted). I just want to M-f and M-b through words and I cannot.

Good news! If you add these shortcuts to the override file in your home directory it will override the alt-special-character behavior.

This is why I use mac, the emacs keybindings I've learned and used for over 20 years.

To memorise moving around the cli:

C-f -> f for forward

C-b -> b for backward

C-p -> p for previous

C-n -> n for next

C-a -> a for Anfang

C-e -> e for Ende

C-k -> k for kill forward

C-u -> just memorise this one. It's the one you use when you suspect you've mistyped a password in ssh or login shell.

Alt/meta sometimes does what Ctrl does, but bigger.

BONUS TIP: In GNU screen, you can use C-a-a for C-a to jump to the beginning of the line. Now you no longer have a reason to passionately hate the default C-a meta-binding for screen. You're welcome.

This is handy. But it would be far more handy to show _exactly_ where the cursor goes. Moving left-ward puts the cursor at the beginning of the word. Moving right-ward puts the cursor one-past-the-end of the word, not at the last letter as is depicted in the diagram.

Anyway, it's far more intuitive to use arrow keys with modifiers:

* control + left-arrow = alt + b

* control + right-arrow = alt + f

* alt + backspace = control + w

I get super upset (pet peeve) when programs don't support word navigation like this.

What I would like would be for someone to build a web app which allows you to select what modifiers you want for each of the shortcuts, and then has a button which would generate configuration files for various programs (vim, emacs, tmux, gnome-terminal, etc) that you can download or copy/paste. That would be grand.

In my inputrc, for the alt-backspace example:

### Line cuts will be remapped to cmd-remove in OSX, shift-remove in Linux

## OSX: Remap with ControllerMate Cmd+Delete to Ctrl-k

"\e[3;2~": kill-line

## OSX: Remap with Controllermate Cmd+Backspace to Ctrl-u

"\e[9;2~": backward-kill-line

### Word cuts will be remapped to opt-remove in OSX, alt-remove in Linux

## OSX: Remap Alt+Delete with ControllerMate to Ctrl-w

"\e[3;3~": kill-word

## OSX: Remap Alt+Backspace with ControllerMate to Esc-d

"\e[9;3~": backward-kill-word

Arrow keys are slower than letters, since you have to move your hand.

Alt+B is not exactly home row friendly (should i use my thumb or ring finger for alt?), and especially switching quickly between Alt+B, Ctrl+F and Alt+F (pinky on ctrl, ring/thumb on alt, long on F and index on B??!) which is one of the most common navigation you do when you want to correct the misspelling of 6 words left and 3 characters forward, then 1 character left again because you accidentally moved 4 characters right instead of 3. Ctrl+Left and then right/left arrow is much easier, more intuitive and works everywhere else, not just linux terminal. Adding shift for selecting while navigating is also super easy. Left/right arrows also have the benefit of being close to up/down arrows which are very useful in multi line inputs.

Not all keyboards are laid out the same.

There's no value in nitpicking. 99% of keyboards are standard qwerty.

And 100% of those keyboards can have simple keys remapped

What does that have to do with anything? The claim is that arrow keys are more intuitive keybindings. If you're remapping keys, then the familiarity of keys is irrelevant.

i don't have to move my hand any further than i would to press ctrl/alt

Yes, you would. Ctrl/alt are within finger range. The arrow keys aren't.

There’s a lot of research in this area. One of the most consistent results of this research is “people don’t feel like moving their hands (off the home row, over to the arrow keys, over to the editing keys, etc) is slower, even though it is slower”. For most people, the feel is more important than the speed.

In other words, this argument topic usually doesn’t end reasonably for either side. :-)

P.S. For extra fun, look up the mouse-vs.-hotkeys discussion. My favorite example is in the research paper for Plan 9’s Acme & 8½ ui.

Again, different keyboards, even QWERTY keyboards, have different layouts. Look at laptops... no single brand has the same keyboard layout for each year's model. It's really f!@#$ing annoying actually.

For example?

Go to any computer store and look at keyboards.

They are simply basic Emacs keystrokes. They also work in Mac text fields.

Exception: ^U and ^W are old unix "cooked" io keystrokes but the relevant Emacs ones also work (e.g. meta-delete instead of ^W).

They're readline keybindings. Anything which uses readline will support them.

I am well aware of this as Brian Fox wrote readline at my suggestion and we were both by then Emacs users of many many years.

However the mac text widget doesn't use readline.


Those too can be hooked up throughout the Mac using the DefaultKeyBinding.dict mechanism

    "^u" = "deleteToBeginningOfLine:";
    "^w" = "deleteWordBackward:";

If you like to use the mouse:

In Terminal.app on macOS, alt + mouse click will move your cursor anywhere. I am not sure how exactly this works. It also seems to work while I am inside Terminal.app and logged on to a remote Linux system.

Also, simply clicking works while running a shell in Emacs using M-x shell

If anyone else likes linux tools explained visually heres one for htop:


Random tidbit: back when Mac OS X first mapped these bindings to Cocoa, it became possible to use them for evil -- to exploit OS X to grant access it wasn't supposed to. [1]

For example if you had a screensaver with a password prompt, you could type some characters, then: 1. ctrl-a 2. ctrl-k 3. ctrl-y ...repeat steps 1-3 several times and hit enter.

The screensaver would crash to desktop, or on the logon prompt, you'd crash to the console mode available by entering >console as a username.

I think these were largely patched by 10.3.0.[2]

[1] https://www.cnet.com/news/mac-os-x-screensaver-security-cras... [2] https://apple.slashdot.org/story/03/07/05/187203/screensaver...

I moved to a 60% keyboard the past year and I wish I'd taken the time to research this. This is a lifesaver.

For Mac (iTerm) users, thanks to this thread https://stackoverflow.com/a/29403520/5233291 you can easily configure

  - alt+arrow to jump words,
  - cmd+arrow to jump to start/end of line,
  - cmd+z/cmd+shift+z for undo/redo,
  - alt+delete to delete word
Just discovered it, it's amazing

I believe these work because of readline, and the standard text controls in MacOS use readline...

Learning keyboard shortcuts is very beneficial, at least in cases where you often do the same things. CMD or Ctrl L is one of my favorites (jump to address text box in most browsers).

It's a bit like coffee^h^h code (wow, autocorrect) optimization; a few improvements in a few places can save an immense amount of work or time.

The standard text boxes on macOS don’t use readline, they use NSText*, which happens to implement similar things to the defaults for readline (because they were created by people who used Emacs a lot, and readline defaults to Emacs style). This is really only important because readline customizations won’t affect macOS text boxes — but it will affect readline programs on macOS, including bash.

As lovely as this diagram is, are there any explanations as to why these are the characters used? I know a few of them but don't see any overall pattern. Is there a logic to it, or do you just have to memorize it?

Update: Never mind. Turns out alt+most keys on macOS just types special characters, making the ones I didn't know useless to me anyway :-D

To your original question: They're emacs bindings. Back and Forward, Word, and such. Not all make perfect sense, but there are mnemonics.

For the update - this is a problem with the built-in terminal. You can use iTerm and get the expected (within a terminal) key bindings, or remap the option binding within its preferences panel.

From Emacs: F/B are forward/back, D=delete, K=kill. E=end, and A was probably used because S was already Search. W=word, maybe? Not sure how U came about here (it's something different in Emacs).

BTW, if you're using Terminal.app, you have to explicitly enable "Use Option as Meta key" in the preferences.

^H comes from ASCII.

Many if not most are from emacs. As to why I have no clue, but could be for historic reasons, i.e no overarching logic.

Bash also has a vim mode which makes sense to use for vim users. This connection with the editor really helps a lot.

My favorite X-windows customization for improving the CLI experience (though it helps with all editing) is cranking up the key repeat rate to a lot higher than is possible in GUI control panels (and lowering the repeat delay):

xset r rate 160 80

I haven't found how to do this in OSX yet, but there is probably a way.

> I haven't found how to do this in OSX yet, but there is probably a way.

  defaults write -g KeyRepeat -int 0.02


I never got that to work somehow. I'm sure I have the wrong OSX version.

Thanks for sharing! I've been using C-A/E a lot, but not really Alt-B/F. Wondering if there is a way to swap Alt-B/F to Ctrl-B/F? Moving between words seems much useful than going one char forward/backward, and arrow keys get those covered.

The terminal might be the most ubiquitous piece of software between *nix flavors, if there's a single application you should probably learn the defaults for, it's gonna be that one.

Last thing you want to do is look like an idiot trying to fix your friend's computer because you can't even remember how to get around in their default bash shell.

This gives me an interesting idea, though... Are there any "portable shell" applications that painlessly provide a mechanism for storing your preferred shell, necessary dependencies and configuration files on a thumb drive that's as easy to use as `/mnt/shelldrive/zsh`?

I want a shortcut that moves from current location to 50% of the remainder.

Ohh, this would be interesting, assuming the jump would diminish by 50% each time the shortcut was hit!

In macOS, you can use Karabiner Elements[1] and enable a set of complex modification rules[2] to remap these to a more intuitive key combinations.

[1] https://github.com/tekezo/Karabiner-Elements [2] https://pqrs.org/osx/karabiner/complex_modifications/#termin...

This is covered within the first 2-3 minutes of the Emacs tutorial, along with some other shortcuts for moving around.

Run "emacs" and then press C-h t (Control-H then T) to start the tutorial.

Or you can read it [1], but the tutorial is interactive, so open it in Emacs if you have it.

[1] http://www.cs.put.poznan.pl/anstroinski/data/uploads/sop1/ma...

I sometimes wish to "delete forward/backward until character X" (where X might be one of the quotes, a dash, period, etc). I know about Ctrl-W, but that will use a fixed definition of what a word is, while what I need will depend on the context. Is this possible in readline's emacs mode, or is it time to bite the bullet and learn vi?

d/X in vi - you'll never go back

Some of these actually work in a surprising number of places, for instance in the URL bar of both Safari and Chrome (assuming OSX). In fact I am so used to them that when they are missing they are the first reminder I am not in my preferred platform (or running a program that does not respect them).

I use cntr -a cntrl e all the time.

I use the default mac terminal. I was excited because I'm always forward and backing up in previous commands.

But alas... Alt F and Alt B just print characters (ĺ). I tried to see if there was a configuration I could set, but to no avail. Maybe I need a better terminal.

The configuration is in Terminal Preferences -> Keyboard -> Use Option as Meta key

That works. Thanks! though you have to set it for each terminal type. (I use 3 colors...). It was a little annoying but done.

Try: `esc F` and `esc B` instead of alt.

Highly, highly recommend iTerm2, it’s a great piece of software and there’s really no reason to use the default terminal over it.

There was also the passwords issue discussed here a while back.

Set option to meta in your terminal preferences.

iTerm handles Alt+f/b correctly.

Here's a gist I made awhile ago for moving around and other useful shortcuts and tools.


I use i3wm and always feel left out of these kinds of tips, because i3wm uses Alt for all kinds of Window Management stuff. If I do Alt-F, my shell goes fullscreen, because i3wm is setup to do that.

Any tips for i3wm users that have these kinds of keybind conflicts ?

I use Super instead of Alt. When I changed to i3 I instantly knew that alt would conflict with everything in terminals.

I use the windows key for the i3 modifier, and leave alt alone. If your keyboard doesn't have a windows key, you can probably map left-alt to mod and leave right-alt alone. Or vice versa.

Basically, find a redundant key to use as your wm mod key.

I don't use i3wm but I use XMonad. I set my (window manager) meta key to the "windows key". You can probably do the same thing. I can't live without alt-. in the shell!

I remapped my modifier to the <Super> (Mod4) key a long time ago. Although I also admit to not using the alt variants of this.

Alt is a common modifier for navigation though, things like qutebrowser use it to navigate tabs and such. It's worthwhile to switch and the "Windows" key hasn't conflicted with anything for me. In my opinion it's a saner default than the current.

I've rebound the modifier key to the Windows key (Mod4) from the default Alt (Mod1).

I'm not sure if it's an option in your setup, but this is why I use the "Windows" key on my keyboard as my i3 modifier. The Alt key then remains available for applications.

Yeah -- set your i3wm command modifier to Super (Windows key).

I've been using i3wm for years with zero conflict with Emacs itself, let alone the shell's Emacs-like keybindings.

Why don’t you use the windows key(Mod4) for i3?

My favorite recent find in iPython is “alt-9-backspace” which deletes 9 “words” back. In my case clearing a uuid string in a Django ORM query:


Alt+<number>, command is Emacs / readline etc for "Repeat this command number times".

The number doesn't have to be a single digit, so Alt-3, Alt-6, Backspace, or Alt-3, Alt-6, Ctrl-H also work (delete 36 characters.)

(Your command would normally be described is Alt-9, Alt-Backspace; or M-9 M-Backspace; to show the Alt/"Meta" key is held for both strokes.)

The diagram is awesome! It helps in remembering these shortcuts better.

Yes VERY nice diagram.

I use most of these on a regular computer but this is very helpful for something like Termux. My smartphone doesn't even have arrow keys! The diagram is very helpful.

More command line tips: https://talk.linuxtoy.org/cli-tips/#2

In the OS X Terminal, is there yet a way to simultaneously get a working alt key and the ability to type characters like []\/ when using an European KB layout?

What about the arrow keys? Home/End? Delete? Backspace?

Seems pretty silly to key CTRL-something when there are dedicated buttons for the functions already.

I always wanted these! I’ve been using cmd/alt and arrow keys by accident many times but no luck. Thank you!

All those, and ctl-r <chars><ret> for searching history.

Also -- ctl-r <chars> ctl-r ctl-r ret

To match two commands containing <chars>

My dream command is

[somekey] + up

that scrolls through history sorted by frequency of use.

I've used this for years:


Not what you asked for, but assuming you use the commands frequently, they'll tend to stay cached, and C-r can access them quickly if they have a unique substring you can remember.

I'll just be over here, using acme.

Hi! Where did you find a good 3-button mouse these days? Are you still living off a hoard collected from back when?

$ set -o vi

lol no.

> set -o vi

set -o vi

set -o vi

oh my god. i cant be the only one here who had no idea these existed. thank you

Chris Pizzi taught me all these little tricks while we worked at Ezyield.com. Thanks Chris!

we need this because first apple and later others ditched the navigation keys from keyboard. good old days with home, end , page up/down delete keys etc. nowadays they fuck with function keys first they replaced it with screen dim and sound now the touchbar , future is not bright!

> they replaced it with screen dim and sound now the touchbar , future is not bright!

Well, sure; that's because you've used the screen dimmer.

Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact