Shell – Auto-completion of words from the terminal buffer

autocompleteshell

In editors like vim and emacs, one can use hotkeys like C-p (vim) or M-/ (emacs) to perform auto-completion on the current word using other words in the same buffer.

Is it possible to achieve the same functionality within a shell? If I see some word in output from a previous command and I'd like to quickly auto-complete it when typing out another command.

Just to be clear, an example:

$ ls
Desktop/  Mail/  music/  osx@  something_with_a_pretty_long_name

$ someth

From here, I'd like to be able to hit a hotkey and have it automatically complete what I'm typing to something_with_a_pretty_long_name.

EDIT: Shoot. Using a filename was a poor example for what I'm after. Consider the following, second example:

$ cat /var/log/something.log
[19:30] Service started
[19:35] Something else happened

$ happ

Where I could auto-complete 'happ' to 'happened' merely because it appeared in my terminal buffer. I hope this clarifies what I'm after.

Best Answer

Short answer: No, not with classical shells like zsh or bash as typically your shell and terminal are different entities.

Long answer: Maybe. What typical happens is you enter a command and press Enter - now your shell forks and executes the specified command. Then the shell has no idea what is happening, the shell does not know what will be written to the terminal or what the executed program did, if it started other programs, wrote to your terminal or anything.

There are two possible solutions to your problem:

  1. Capture all the output from your executed commands and use it somehow for completion purpose (can be done but probably shouldn't be done)
  2. Use a different Terminal supporting 'completing' from your "shell buffer".

A solution for 2 is for example using emacs and multi-term and just using M-/ like you normal would to complete things from the terminal. Other terminals may offer a similar solution.

But do you really need this kind of completion? shell completion nowadays can complete man pages, commands, pids, sockets, command options, file paths from remote systems, and many more. This may be already sufficient for your use case or could be enhanced for your specific problem.

Related Question