Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
Keyboard shortcuts for GNU Readline (masteringemacs.org)
386 points by donatzsky on Nov 29, 2022 | hide | past | favorite | 167 comments


Friends if you dont know: you can add readline support to LOTS of things, especially custom scripts and tools with a prompt by just calling the program with rlwrap.

> rlwrap is a 'readline wrapper', a small utility that uses the GNU Readline library to allow the editing of keyboard input for any command.

https://github.com/hanslub42/rlwrap


I'm using bash (and thus GNU readline) all day every day at work, and by far the most useful shortcut for me is Ctrl-r (reverse history search).

I also sometimes use Ctrl-a (start of line, if the keyboard doesn't have a convenient Home key) and Ctrl-e (end of line, in lieu of End key).

Btw the post disses Ctrl-s / Ctrl-q for pausing/resuming terminal output, but it can be useful when you're outputting a lot of text (for example tailing a logfile).


>by far the most useful shortcut for me is Ctrl-r

I rarely ever use Ctrl-r since I usually know the starting part of the command I want. So, I type those starting characters and use up/down arrow keys, courtesy these lines in `~/.inputrc`

    "\e[A": history-search-backward
    "\e[B": history-search-forward


a really cool hack I found in an HN thread long ago was to stick "hashtags" (aka bash end-of-line comments) at the ends of commands you want to find in your history quickly:

  sudo systemctl restart myservice #bounce
and then ctrl-r and type your hashtag to get right to it


This is now the HN thread in which I found this really cool hack. Thank you.


I'm officially naming these "bashtags".


That’s a good one.


That's useful, but C-r has its merits too, as you can search for any string in the history. So, even if you run, say, python programs all day, here's a way to find that one time you used a different command line parameter... etc.


You can set bindings for substring search too:

    "\e[A":history-substring-search-backward
    "\e[B":history-substring-search-forward


Cool!


I don't want to discount how valuable this may be to you. However, for the average sysadmin, or developer who spends time in shells on many different machines, I would gently suggest that this is not a good idea. It's not a significant enough improvement over the way it works out-of-the-box to merit both (1) not getting used to Ctrl-r and (2) getting used to a different behavior for the arrow keys. Just my opinion, of course.


If you're the sysadmin, then chances are high you can add this to the base image of all the systems you regularly touch.


Many of my commands start identically but continue and end differently. Here C-r (or ^R if you prefer) is the most convenient.

Sending a looong command to your editor for modification via C-x C-e is also convenient sometimes.


>Many of my commands start identically but continue and end differently. Here C-r (or ^R if you prefer) is the most convenient.

Not sure if I understood this correctly. You can use up/down arrow multiple times, just like Ctrl-r/s - so it is a huge improvement for me.


If you don't already know about it: combining fzf with Ctrl-r is _amazingly good_ https://github.com/junegunn/fzf it's a fuzzy finder combined with reverse history search..


> but it can be useful when you're outputting a lot of text (for example tailing a logfile).

Use "tail +F" and press ^C when you need to pause at some line. Press F to resume tailing.


WAT

I always use -f then cancel out when I think I see what I want, I really need to read man pages for things I use


less(1) provides similar follow/stop-following functionality.


I think I was thinking of less, haha.


Ctrl-r history search is made 1000x better with fzf fuzzy history search. https://github.com/junegunn/fzf


I agree with you. What I have also done is increase the history size:

https://eshlox.net/2017/08/01/bash-increase-command-history-...


A hacked up version of ci"/ca" is my favourite thing, something like this;

set keymap vi-command

"ci\"": "T\"ct\""

I don't think you can do bracket matching/counting, but, even so, ci( is also pretty handy.


"Shame, then, that even serious command line hackers never bother learning about its capabilities, as they can supercharge your command line productivity."

Because it is really confusing if you are not an emacs user.


Not at all.

bash readline is probably the productivity enhancer skill a developer (or system admin) can develop.

Simple things like copy and paste without hitting a mouse. This will make you _prefer_ the cli as it is not slowing you down anymore.


Yes please. Teach me how to copy output of previous command into clipboard using keyboard only and I will love you forever. Bonus if I can have a cursor to only select partial lines of the output.


Many terminals have a different mode, where you can navigate and copy everything displayed in the terminal. Alacritty can do this, for example.


You can pipe to xclip to get it into the copy buffer. Then "shift-insert" is often the right paste when "ctrl-v" doesn't work.


Thanks for tip, but quite far from ideal. Piping into something requires 1. knowing upfront I want to copy the output. 2. Doesn’t allow partial selection of the output. 3. Extra typing | xclip after every command. 4. Xclip is not installed by default.


Unrelated, but you could easily do that on screen with C-a ESC (default key binding)


I'm a vim guy, and I don't find the readline commands confusing. I just think of it as "Insert" mode in Vim (many of the readline commands work there too!!) and it feels pretty natural.


Have you tried vi mode in bash? "set -o vi" I think.

Then you can use vi(m) commands, modal editing, even press v to drop into a full vim instance for doing more advanced editing of a command line.

It's amazing.


TIL `set -o vi` is a shortcut for setting `set editing-mode vi` in .inputrc for bash only - except it seems like the .inputrc version would apply to anything that uses readline (gdb, etc)

https://unix.stackexchange.com/questions/485818/bashs-set-o-...


The thing that bugs me about that mode is that you have no indication of what mode you are in and that is jarring just enough times that it was worse than just using the few emacs keybinds that I could remember. (ctrl-a,e,k basically)

(n.b.: i didn't try to configure this that hard so unless they fixed this in zsh or some configuration thing and that would be great)


I am a VI user but prefer to use emacs keybindings in bash. If I need to do significant editing, VIM is just a C-x C-e away.


> Because it is really confusing if you are not an emacs user.

Or a make user -- the text input widgets on macOS natively interpret ^a, ^f, and other basic Emacs commands, and have since the NeXT days.


Add `set editing-mode vi` to your ~/.inputrc and readline's keybindings resemble vi instead of emacs. You can also define your own keybidings as you like, like `Meta-Control-h: backward-kill-word` as seen in the example file in `info readline -n 'Sample Init File'`. Works with bash and whatever else that's using readline, like the python console, postgresql client, etc.


Similar resource for zle which is used by zsh instead of readline [1].

[1] https://thevaluable.dev/zsh-line-editor-configuration-mousel...


Just enable vim mode (`set -o vi`) and call it a day.


vi bindings aren't worth running into weird problems imo. it took me less than a minute to hit an incompatibility with fzf.

https://github.com/junegunn/fzf/issues/1238


This is it for me. I'd use vi bindings everywhere if I could and it didn't end up breaking other things.


This is actually encouraged by POSIX.

set -o vi: "Allow shell command line editing using the built-in vi editor. Enabling vi mode shall disable any other command line editing mode provided as an implementation extension."

No other mode, specifically emacs mode, is included in the POSIX standard.

Take from this what you will.

https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V...


Not surprising.

Back in the heyday of POSIX standardization, the Emacs camp and the POSIX camp were both very opinionated and not entirely aligned. One example is the standard disk block size used in command line utilities such as du and df. RMS made GNU use 1kb instead of the POSIX standard 512 byte size, but this could be overriden by setting the environment variable POSIX_ME_HARDER.


And add search support, if you're using zsh: https://github.com/soheilpro/zsh-vi-search


Every vi mode that I have ever used in any shell allows search with ESC-/ as the vi editor itself allows.


Can I still use macros with 'q<register>'?


You can edit the current prompt in a full vim by pressing ‘v’. On :wq the content of the file will be run as the command. In that case you can use the macros with q (and any fancy vim plugin you might like)


Best of Both worlds: Normal readline shortcuts, and hold control whilst pressing x and e (C-x,C-e) to open that line in $EDITOR (i.e. vim).


Or e.g. Neovim if `FCEDIT=nvim`


Based on 30 seconds of experimentation, no.


shhh, don't tell them there's a superior text editor out there, it's fun watching emacs users consistently do things the hard way


Yes! I never got the hang of the read line short cuts. Only one I remember and regularly use is reverse history search: ctrl-R.

The downside is that while vim mode works nicely on bash, other commands like gdb etc that also use read line aren’t as easy to get into vim mode, if they support it at all…


ime, most programs using readline parse ~/.inputrc.

  set editing-mode vi
  set keymap vi-command
That does the trick for me in python shell, psql, etc.

First thing I do on any fresh unix box is setting above, and echo "set -o vi" >> ~/.bash_profile.


For programs which use libedit, you can also setup vi mode.

    bind -v


Good one! That covers sqlite3, it was my last straggler. :)


Can't remember why but I am pretty the second line is not needed


gdb also uses readline... And readline is configured with ~/.inputrc

Here is my config from a happy gdb vim mode user :

set editing-mode vi

# If set to ‘on’, Readline performs filename matching and completion in a case-insensitive fashion. The default value is ‘off’.

set completion-ignore-case on

# If set to ‘on’, Readline displays possible completions using different colors to indicate their file type. The color definitions are taken from the

set colored-stats on

# Perform partial (common) completion on the first Tab press, only start # cycling full results on the second Tab press (from bash version 5)

set menu-complete-display-prefix on

### MAPPINGS ###

# Allow to refresh the screen

"\C-l":clear-screen

# If there are multiple matches for completion, Tab should cycle through them

TAB:menu-complete


See the GNU Readline User Manual - https://tiswww.cwru.edu/php/chet/readline/rluserman.html (or 'info rluserman')


For anyone using a Mac, the basic cursor movement commands available in readline and emacs—C-f, C-b, C-a, C-e, C-n, C-p—are also available in virtually any text input in any program, namely web browser inputs, url bars, and textareas, as well as all system UIs.

Once you get used to using these shortcuts that means you can compose and edit text anywhere without ever moving your hands.

I recently switched to using Linux full time for my job and it KILLS me that these shortcuts aren’t available outside of the terminal. I try to navigate to a search suggestion in Chrome using C-n and accidentally open three new windows. I try to add a sentence at the start of Slack message using C-a and accidentally highlight everything and delete it. I try to move my cursor up to edit a previous line using C-p and end up brining up a print dialogue. It’s breaking the muscle memory of my most basic interactions with the computer, and it sucks.


Ugh this destroyed my productivity too for a while. I even wrote an entire blog post about my woes and different experiments to get back to getting consistent shortcuts across terminal and GUI apps here: https://alexdav.id/2020/07/12/text-manipulation-and-modifier.... GTK key themes didn't end up working out for me, and I ended up with a custom QMK solution, but it's not great.

Note for people still using macos, you can enable many more readline shortcuts by creating a special file at ~/Library/KeyBindings/DefaultKeyBinding.dict. I made a repo that simplifies the process to just a single git clone when setting up a new machine: https://github.com/alexdavid/keybindings


Very cool!

What keys do ~ and ^ represent?

    {
      "^w" = "deleteWordBackward:";
      "~f" = "moveWordForward:";
      "~b" = "moveWordBackward:";
      "~d" = "deleteWordForward:";
      "~<" = "moveToBeginningOfDocument:";
      "~>" = "moveToEndOfDocument:";
      "~w" = "copy:";
      "^y" = "yank:";
      "^t" = "transpose:";
      "^p" = "moveUp:";
      "^n" = "moveDown:";
      "^u" = "deleteToBeginningOfLine:";
    }


If it's anything like readline/Emacs, then:

^ = Control

~ = Escape


In this file `~` is meta (option key on macs). Not sure why it's not escape like it is in emacs.


Because on a particular three/four-decade-old physical terminal[0], Alt-$KEY was transmitted as "1B [sequence for $KEY]". Eg, Alt-X was "1B 58"[1]. The escape key happened to also transmit "1B" on its own. Consequently, "Alt-$KEY" and "Esc, $KEY" were indistinguishable unless you went out of your way to engineer a race condition. This has never really been fixed, despite intermittent attempts.

0: I think VT100, but don't quote me on that

1: or possibly "1B 78", depending on how it handled shift; I don't remember exactly.


On Linux, Meta is activated on modern keyboards by both ESC and ALT.


Also on macOS and (at least within emacs) Windows.


I’m not sure about other OSs, but having cmd for standard mac shortcuts and ctrl for all things Linuxy is really useful in general. As you point out, loads of apps support the standard readline controls. I additionally wire ctrl-p / ctrl-n to be more generally useful in Linux and vim, but I find that they just work all over the place in Mac apps too (up / down in Alfred search results for example).


You can enable "Emacs bindings" in a bunch of applications. Enabling that in GTK would let you use the cursor movement keys in Chrome and Firefox.

https://askubuntu.com/a/1280532


Unfortunately, GTK 4 has removed key themes. Eventually, Firefox, Chrom(e|ium) and all actual GTK applications will migrate to GTK 4, so this is not very future-proof.

I use a variant of the emacs key theme, so I'd be happy if there were a workaround...


It's unfortunate that the GTK devs feel they have to remove features which their users find useful to keep GTK maintainable. Keeping software complexity under control is a difficult task, and I can't begrudge them their choice.


You are a hero and have just cured me of a hundred daily paper cuts. My employer should give you a bonus.

It works in Chrome, but unfortunately not in the standalone Slack client. (Maybe an argument for switching to the web version?)

(Uh, does anyone know how I select all (previously C-a) or search (previously C-f) in Chrome now??)

EDIT: Looks like C-/ functions as select all, still looking for a find replacement.

EDIT #2: Oh, silly me, as long as I'm not focused on an input, C-f still works.


> “I try to move my cursor up to edit a previous line using C-p and end up brining up a print dialogue.

I used to be a big enthusiast of keyboard shortcuts, now I’m getting fed up of how many there are, every program has a zillion shortcuts all stacked on top of each other. Someone needs to come up with a better way (cough Jeff Raskin THE?).

This one is notably egregious, hands up anyone who prints often enough to need a keyboard shortcut; someone who prints as often as they new-tab, as often as they Ctrl-s a text file, as often as they copy/paste? Anyone? If only there was a universal way to unbind them.


In KDE one can unbind Ctrl-P from print for all KDE apps, from the web browser to the PDF reader to the mail client.


On Mac Os you can also add some other ones that are not enabled by default, there's various write ups on how to do this.

https://irreal.org/blog/?p=259

I really missed C-w for delete word personally.

There's also a vim plugin by tim pope that adds a few readline keys that don't clash.

https://github.com/tpope/vim-rsi

And if you use the fish shell you can have both vi and Emacs shortcuts activated at the same time for the best of both worlds.


Until you get used to C-w in any text box, and then randomly close browser tabs (ff on Linux) because muscle memory.


Opening the Firefox console with Shift+Ctrl+C is my particular habit. Of course the shortcuts aren't configurable, it's 2022.


Seems quite cool - I don't suppose you have a copy of the .dict file linked in that blog post? the link is 503 :\


There's a link in the comments to it.

https://github.com/jrus/cocoa-text-system/blob/master/KeyBin...

Though I just have:

    "^w"   = "deleteWordBackward:";                            /* C-W        Delete word backward */


Missed that - thanks :)


I switched to Mac full time when I got frustrated with my Linux desktop having (far) worse support for Emacs keybindings than my work Mac. There was a certain amount of irony in it.


If we are doing a survey.

Firefox on openbsd uses the emacs keybindings.

And just checked, it looks like chrome on openbsd uses the emacs keybindings as well. it just reinforces my feeling that openbsd makes the best desktop system.


Anyone using a Mac is probably not using readline but its replacement 'editline'.

So the configuration file is ~/.editrc.

man editrc

Note also that to have a full mapping of keys available to you, you have to be aware of the tty settings (see stty), the terminal emulator and the GUI environment in which it is running. I would appreciate a tool that would dump all this in a comprehensive list.


Don't confuse Mac's Ctrl with Ctrl on Win/Linux. Mac's equivalent to non-Mac's Ctrl is Cmd.


You find these all over the place[0]; I often try them and am unsurprised when they work. Have to train myself not to use ^w though. Try to erase word and it closes the window.

[0] for example in the quakelive console


C-a, C-k are probably my most used shortcuts on the mac


My favorite is that those can combined with the shift key, to get native highlighting. So Ctrl-Shift-a works like Shift-Home on windows (and Ctrl-Shift-e for Shift-End).

So you can do C-s-a and C-s-e, followed by cmd-C, to copy stuff to the native clipboard.

(Kill and yank (C-k and C-y) work too, but not across applications.)


keyd is a really nice key remapping daemon that supports application-specific remappings. You could use it to emulate readline bindings in Chrome. Or if you can't figure out how to emulate something, at least bind it to noop so it doesn't mess you up any more.

https://github.com/rvaiya/keyd


On a linux desktop you can have this in GTK applications with the "gtk-key-theme 'Emacs'" settings.


X11 supports all of this with user configurability but the cool kids threw all of it away.


Command-A isn’t available on Linux in slack?

How do people even function without basic function keys?


Let me introduce you to the Home key: https://en.wikipedia.org/wiki/Home_key


I've always pried this key and other useless keys off my keyboards. TIL.


Command-A does select all. On Linux if you use defaults, ctrl+A will do that. If you change your gtk keyboard shortcut theme to ‘emacs’ it will do the equivalent of ‘home’ instead (which is what ctrl-A does on a Mac). To delete a message under these conditions, you can usually do e.g. C-A C-K. But that’s not so suitable for eg a high-risk text box on a buggy site where you want to regularly select all then copy in case the site crashes or loses your data.


Doesn't ctrl+/ select all in either GTK key theme?


Readline also has the kinkiest sounding line out of any man page: (M-y) Rotate the kill ring, and yank the new top.

Always makes me giggle.


Two settings I always set in my .inputrc which are not listed in the page:

  # Make autocompletion case insensitive and display suggestions after single tab.
  # https://bugs.debian.org/990353
  set completion-ignore-case On
  set show-all-if-ambiguous On


Lots of comments about small improvements to typing efficiency. It is an important topic.

One thing I do, is turn the key repeat speed up as fast as I can stand, and turn the delay to repeat down as low as possible. I have always done this and over the years I've experimented to find the fastest possible settings.

On the Mac, use:

defaults write NSGlobalDomain KeyRepeat -int 1

defaults write -g InitialKeyRepeat -int 7

See: http://hints.macworld.com/article.php?story=2009082319301814...

After getting so used to these fast speeds, when I see folks attempting to type with the slow default speeds ... it is quite hilariously slow and I must confess I feel a little pity for them.


Or just M-42 f to press f 42 times. In vi, 42 i f esc, works for sequences too.


    Less Useful Key Bindings:
    
    C-l     Clear screen
This is the one I use most frequently. All day every day. I hate clutter and unless I need to refer to the output from the previous commands, it's gone.


It's perhaps worth mentioning the smaller and more liberally licensed editline library if you want to embed the same line-editing functionality in your own CLI. It's been used in non-GNU Unixes for decades.

https://troglobit.com/projects/editline/

See also the note at the bottom of that page about other versions of editline/libedit.


In a similar vein there's also Linenoise form the creator of Redis.

https://github.com/antirez/linenoise


"liberal" is in the eye of the beholder.


> C-e, C-f, M-b, M-f

Why these strange shortcuts when any keyboard has arrow keys and they can be used with a control modifier to move by words?

I can understand why to use C-a, C-e, because laptop keyboards tend to have "Home" and "End" keys in strange places, but those... And Emacs documentation for some reason insists on using C-e, C-f instead of arrow keys.


Who has time to move all of the way over to the arrow keys, tap a few times and then find the little tab on the J again?

I have arrows behind a second layer on my keyboard with vim mapping, and I don't think I could give that up. If you spend all day in front of a keyboard you might as well learn to be efficient with it.


> I have arrows behind a second layer on my keyboard with vim mapping

Same here: second layer reachable from the hands' home position on the keyboard. Left thumb for the modifier + ijkl in my case (I like ijkl for it mimics an actual arrows key cluster).

It works everywhere: xterm / command line, Emacs, any editor / IDE really, any dropdown menu...

It's the way.


jkl of course works on youtube, I find it really annoying when viewing other video sites which don't support these basic keybindings


They work everywhere. Decades ago, the Home/End/PgUp etc keys might not work on all terminals.

You can use the standard keyboard movement keys if you prefer.

(The letters are mnemonics, Back, Forward, Next line, Previous line, End of line, start of line uses A as the first letter. The control key tends to do smaller things (like move one letter or line) while the alt/meta key does bigger or less-common things, like move whole words, sentences or paragraphs. See https://www.gnu.org/software/emacs/manual/html_node/emacs/Mo...)


> Decades ago, the Home/End/PgUp etc keys might not work on all terminals.

Decades ago, on real serial terminals, the terminal keyboard likely did not even have Home/End/PgUp/PgDn keys [1].

That is the reason for the seeming odd mappings now in 2022 after almost every computer has a keyboard that contains nearly the same set of 'extra' keys. When readline was developed, there was no IBM-PC keyboard layout (because readline predates the IBM-PC) and besides the basic letters, numbers and punctuation keys there were very few other keys that were available on all keyboards at the time.

[1] https://en.wikipedia.org/wiki/File:Mappa_Teletype_ASR-33.jpg

https://vt100.net/docs/vt100-ug/chapter3.html (see "The Keyboard")


C-f(orwards) C-b(ackwards)

The reason you use them is that they allow you to not leave the home row. So say you're writing something and need to move back and delete a mistype, it's much faster to do that with C-b C-b C-b backspace <letter> M-f than moving your right hand to the arrow keys and moving it back to type the letter and then moving it to the arrow keys again.

Now, lot's of people can't be bothered to take the time to learn them. You need to go through the Emacs tutorial and perhaps spend a day or two getting used to them. That's all it takes.

Similarly, most programmers I personally know can't touch type. That takes a few hours of practice with a fun, gamified touch typing program for a couple of weeks, and then you have set part of your mind free. But people can't be bothered.


>Similarly, most programmers I personally know can't touch type. That takes a few hours of practice with a fun, gamified touch typing program for a couple of weeks, and then you have set part of your mind free. But people can't be bothered.

I would argue that it takes more then a few weeks, be prepared to wait/invest several months into it, but it is absolutely worth the investment. 100%.


>The reason you use them is that they allow you to not leave the home row

How do you press the control key or the alt key while touch typing without loosing home row position? For alt, I try using my thumb, extremely folded down, but for control...?


Your pinky. Many do remap ctrl to caps-lock, though, since it's more ergonomic and caps-lock is a bit useless anyway.


> Similarly, most programmers I personally know can't touch type.

OMG, seriously?


On laptop one requirement I have is having these:

fn+left/right -> home/end

fn+up/down -> page up/down

It's probably been 20 years I have laptops that support it and I'm perfectly fine/fast to manipulate text with the keyboard.


Ctrl used to be where Caps Lock is on some keyboards and today, you can map Caps Lock to Ctrl in Mac OS snd Linux. It will make more sense when you do that as pressing the shortcut will be much easier (home row).


Not a eMacs person, but as a vim user arrow keys are annoying to reach. Using control or vim bindings it is far easier for me


It's Emacs not eMacs! ;)

https://irreal.org/blog/?p=10973)


TIL people write eMacs on purpose. Mine was just iPhone's autocorrector as someone mentioned in the comments.


> Why these strange shortcuts when any keyboard has arrow keys and they can be used with a control modifier to move by words?

There was a time before PC's when keyboards didn't necessarily have Arrow keys


Two issues with readline: it's GPL and it's big. For embedded systems intended to become products you really need something else. My tiny variant is this, but for sure there are many others:

https://github.com/nklabs/libnklabs

("nkreadline" has editing, tab-completion (for embedded "nkcli" commands) and history)


For me as a customer, the GPL is a feature, not an "issue."

Of course, if you ship software for your hardware and want to lock your customers out of their own hardware, then I can see why you'd not choose it.


I don't disagree with you (I've written plenty of GPL-licensed software), but as someone who gets paid to develop products for other companies, it's an issue. Few of my customers are interested in making the embedded software for their product open source.

Actually the MIT open source license (and other similar ones) solves a completely different problem for me. It allows me to reuse this software for many different customers. It's slightly easier to do this when I tell them that I'm going to use "this open source library" vs. "my personal library that I'm granting you a license for this product, but I retain the right to use it for other customers".


Knowledge like this used to spread naturally—physically sitting with a junior engineer, muscle memory would make any shortcut-fu gaps painfully clear. That’s not as visceral in remote pairing, and doesn’t show up at all in async processes like CR. Still, I try to at least share the “greatest hits”:

  ctrl-r: search backwards through command history
  ctrl-a: go to beginning of line
  ctrl-e: go to end of line
If nothing else, it’s a topic to keep us occupied while they hit the left arrow 47 times instead of ctrl-a.


In ~20 years of professional programming, I have never explored much beyond these shortcuts, except for also using:

  * ctrl-left/ctrl-right to go back/forward word by word instead of char by char
  * ^C to cancel the current line


If we're counting ^C, then I'd also add:

  * ^D - Send EOF, which exits most shell-like programs (if you're on an empty line, so try ^C^D)
And the job control bindings:

  * ^Z - Suspend current foreground process and return to shell, use `fg` to resume it in foreground and `bg` to resume it in background (see also `disown`)
  * ^S - "Stop" current process, useful if it's printing a lot of stuff and you want to pause it for a bit, otherwise useless and usually done by mistake
  * ^Q - resume a stopped process, probably after you ^S'ed by mistake


I hated ^S until I disabled it with `stty -ixon`. The thing is, this key is actually bound to a really useful command: the reverse of ^R, ie. search forward in history. It's very useful when you assemble a new command from a few separate ones. You just ^R to the first one you want, mark and copy the part you want with ^Space and Alt+w, then search forward to the next one with ^S. I do use fzf, and it's great, but not for this specific use case.

Also, it's worth noting that you can give a prefix argument to many commands by pressing Alt+1-9 (possibly multiple times). For example, the sequence Alt+2 Alt+. pasted not the last, but second to last word from the previous command.

Oh, and Alt+x also works! With completion under TAB!

The terminal looks simple, and most people prefer GUIs for good reasons. Not to mention the actual complexity of interpreting escape sequence and emulating the teletype (TTY). By the same token, though, terminal is something that was developed and polished by hordes of programmers since the teletypes. It's amazing, and the result is quirky as hell, but also incredibly powerful.


For enough, but yes these are not to do with readline but terminal behaviour


It's mentioned in the linked page, but not really explored: instead of `^C` (aka `C-c`, `Control-c`, &c) use `M-#` (aka `Alt-#` or `option-shift-3`) which adds a `#` before whatever you've typed on the current line and hits `return`, putting the line you're cancelling in the history as a comment so you can go back and `C-a C-d return` to submit it.


Oh my gosh thank you. I once went back by a word and swore I hallucinated, then realized the shortcut probably exists but never bothered to look into it.


The emacs shortcut works here too: Alt-b for back a word and Alt-f for forward a word (at least if your terminal maps alt correctly)


After getting very used to C-w (delete back work) and C-h (delete character backward) on readline, it really bugged me that these aren't default on emacs, even though readline is often advertised as giving emacs muscle memory.

I ended up globally remapping C-w and moving the help prefix, C-h to C-x h and making C-h backspace, because i was pressing it incorrectly that often.


So, to be fair, C-h isn't some crazy invention of readline (and thereby a failure of what it was "advertising") that you got used to: it is the standard key code for backspace. Just like a horizontal tab is ASCII 9 and a carriage return is ASCII 13, ASCII 8--and I realize this might make less sense as this in some sense "undoes" a thing and maybe you would never expect it to be in a file--is backspace.

Meanwhile, all Control does is convert a normal (capital) character into a control character, which is the term for the ASCII characters below 32 (aka, the space character) by essentially subtracting 64 (which is almost but not quite equivalent to masking out a bit). Notably, @ is 64, so C-@ generates ASCII 0, which is why you see ^@ printed for NUL bytes in many editors (including vim). After @, you get A-Z and then [, \, ], ^, and _.

This is why, if you want to get Escape, you can type C-[, as ESC is 27 and [ is 91. And this is also how C-G becomes that annoying bell, because G is the 7th letter of the alphabet and BEL is 7, And so, C-M is equivalent to pressing Enter, C-J is equivalent to pressing Tab... and C-H is equivalent to pressing Backspace!! Now, there is also a DEL, for the Delete key, which is which is 127. As ASCII is designed for 7-bit, that is the same as -1, so you can type it using C-?, as ? is 63 ;P.

OK, so, one might should then wonder how the hell Emacs even works, if they remapped the character code for Backspace to do something silly like Help... right?! And the answer is kind of "it doesn't", which I find amazing! There is actually a FAQ entry for Emacs "Why does the Backspace key invoke help?" and a related section from its manual on "If DEL fails to delete". (It might even be the solution you came up with isn't the ideal one, so you might want to read these.)

https://www.gnu.org/software/emacs/manual/html_node/efaq/Bac...

https://www.gnu.org/software/emacs/manual/html_node/emacs/DE...


> by essentially subtracting 64 (which is almost but not quite equivalent to masking out a bit)

Subtracting 64 is exactly the same as "masking out a bit". The difference between the control characters and their upper case equivalents is that bit 6 (counting from zero) of the byte is zero for the control characters and is one for the upper case equivalents.

On old terminals, the 'control' key more often than not worked by simply forcing bit six of the character mapped to a given key to zero (i.e., it was a direct hardware change).

Another seemingly little known fact, for ASCII, the difference between upper case and lower case letters is again a single bit. Letter A is 65, letter a is 97, the difference there is bit 5 (counting from zero) is zero for "A" and one for "a".


It isn't the same as "masking out a bit" when you are subtracting 64 from 63 to get 127 (the behavior of C-?). I think it is equivalent to Xor-ing it, but I didn't want to go into that for various reasons, including it just being overly complicated (and, in fact, edited that statement three times in an attempt to find something that was all of true, expository, and easy to understand; but, I apparently didn't optimize for "something everyone would appreciate why it was said the way it was said if they liked adding information but hadn't paid as much as attention to all of the examples as I had been forced to while drafting the comment").


> C-h isn't some crazy invention of readline (...) that you got used to: it is the standard key code for backspace.

> C-H is equivalent to pressing Backspace!! Now, there is also a DEL, for the Delete key, which is which is 127

Not anymore on Linux terminals. People wanted to distinguish backspace and C-h, so in some time in 1990s there was great DEL-BS shift, where convention changed to use 127 for BS and some escape sequence for DEL (in direction from terminal to program, in the opposite direction the original convention is still used). That is why there are these sections in Emacs manual (and similar options on other tools) - to handle situations where terminal behavior and information about terminal are mismatched.


Don't mean to be pedantic, but this comment left me very confused, surely you mean carriage return to be ASCII 13? Also, g is the 7th character and BEL is 7.


Ugh. I've gone ahead and fixed it. I am not having a good night. I was actually sitting here typing all of that because my shoulder hurts so much I can't sleep, and apparently I am so tired I can't count.


One thing I wish I knew how to do -- presuming it's possible -- is constraining the reverse/forward history search. Say I know I'm looking for a grep command, I'll do `C-r grep`, but then I want to look through that subset of results for another string (e.g., the pattern, or maybe another part of a pipeline that I half-remember). AFAIK, reverse/forward history search is just an exact string match...and remembering exact strings is hard.


I'd use "history | grep ..." at that point, if I can't remember an old command. Possibly "history | grep ... | less" and finish searching inside less.


I was doing history grep too until someone on HN told me about hstr:

https://github.com/dvorka/hstr


Another similar tool that may be of interest is mcfly

https://github.com/cantino/mcfly


Fzf can probably help here :

https://github.com/junegunn/fzf


As another commenter said, fzf is the way to go.


Huh, by this account I'm apparently a fairly advanced readline user, but I still have some way to go! Thanks for sharing.


Ctrl-R! Ctrl-R! Ctrl-R!

How many people have been on a screen sharing call and watched the other person tediously up-arrow through 5-10 commands to try to rerun what they just did? The single greatest productivity boost you can gift a CLI newbie is searching their command history. Everyone jumps on the Emacs nav keys (C-f, C-b, etc) or other editing trivia. No one has trouble editing a command in place but it certainly takes some people way too long to run a command from one minute ago.

Also, purely selfishly, it's goddamned painful to watch the up-arrow dance and it wastes so much time. I want to scream.


I'm really bad about picking up new keyboard shortcuts (I end up using them little enough that unless I take out time for focused practice, I'll forget them—I'm pretty sure I'm just never gonna get decent at vim or emacs, for this reason, aside from basic navigation keys) but took to this one instantly because it's so damn useful that I used it several times the very first day I learned it, kept using it the rest of the week, and have used it almost daily ever since. Doesn't hurt that it's reasonably mnemonic ("R" for "reverse-search")

Reverse-history-search is amazing and I don't know how I went as long as I did without knowing about it.


For extra boost, add fzf and its shell integration.

https://github.com/junegunn/fzf


I missed the shell integration when switching to Fish a couple of years ago. fzf.fish saved the day, I wouldn't be without the keybindings now (Ctrl+Alt+F is roughly the equivalent of **Tab)

https://github.com/PatrickF1/fzf.fish


ctrl+r is great

so is modifying your inputrc so you can still use up arrows but filter the options by first typing a bit of text

i.e. $ find <up arrow to just show lines starting with find>

tada:

    $if mode=emacs
    "\e[A": history-search-backward
    "\e[B": history-search-forward
    $endif

I do a bit more in that if block, but trimmed it down to make a point


Fun fact: GNU Readline and Bash are maintained by a single person. https://tiswww.case.edu/php/chet/readline/rltop.html#Maintai...

In case you were looking for more examples of "open source being held together by one tireless person somewhere" (obligatory xkcd comic link omitted).


IDK if it's obvious, but GNU readline has a full-blown vi mode, with ESC, insert / command modes, all the ergonomic motions, etc.

The default is Emacs mode, and the author of the post is a Emacs user, but that mode is not the only one supported.


Ahh yes. Freezing your terminal via control flow with Ctrl-s. It’s almost as bad as finding yourself trapped in vi with no obvious way to exit. But if I recall correctly, you can resume flow with Ctrl-q.


Indeed. And you can desactivate it too: I'm just running:

    stty -ixon
in interactive shells and Ctrl-s ain't an issue anymore.

If I do want to "pause" the output, teletype style, as if the seventies called or something, I pipe my command into less instead.

I've been disabling Ctrl+s since literally more than a decade and don't know what I'm missing. Probably not much.


I guess I'm the only one who tried to do this?

There is no ~/Library/KeyBindings/ directory in macOS 12.6.1, and a find . -iname DefaultKeyBinding.dict doesn't return anything either


I have two frustrations with keyboard shortcuts that I think most people generally share:

1. They are usually inconsistent, so muscle memory conflicts.

2. You usually can't edit them.

If only we could just edit them. The possibilities....


Why can't you edit them? Have you looked at .inputrc? If not, read the article ;P. You can also certainly edit anything in vim/Emacs. On macOS, you can even remap the keyboard shortcuts in almost every GUI app--and even sometimes universally across apps due to conventions--because of how they try to model shortcuts as convenience for the menu bar.


Yes, there are quite a few places where you can, but not enough. Most software can't be changed.

And while you can edit (remap) the keybinds in [neo]Vim, there are limitations. You can't edit all of them at the same time without running into race conditions. I've tried and failed.

And even Emacs - a nearly best-case scenario - is a struggle. First, you have to remap all the Emacs functions you want to change. Then you have to remap all the plugins you use. It's a lot of unnecessary work, and it's tricky to find your way around.


I really wish we could get a GNU Readline replacement with much stronger editing capabilities: better multiline support, mouse support, syntax highlighting, etc.


I would double check on GNU realine code sanity, including its SDK before learning its shortcuts. I use busybox shells anyway.


I didn’t know readline had macros! Useful!!!


How to remember "Kill word backward/forward". Is there any mnemonic for C-w, M-d?


C-w is "wipe", and M-d is "delete".

C-d is also "delete" but one character. There are several Emacs combos where C- is for single characters and M- is for whole word, like C-f/M-f, C-b/M-b etc.

M-w also exists in Emacs proper but it's "wipe without delete" or in common parlance, "copy".


TIL

Although GNU readline maintains a kill ring (clipboard), which works much like Emacs’s kill ring, it’s not shared with your system’s clipboard, nor any other instances of GNU readline. It is, in effect, local to the process you’re running.

so it's not just that I didn't copy something...


Has anyone managed to get an RSS Feed from masteringemacs.org ?


I run one on /feed. I merely haven't linked to it, which I ought to fix!


The time has come for gnu console and linux filesystems to support emoji characters for command names and filenames. In Windows 10 you can name your files and folders with emojis.


This has been supported on Linux systems for many, many years, decades in the case of filenames, afaik.


TIL readline has macros.




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

Search: