June 25, 2007

Newbie Emacs tip: I spend half of my time in Emacs shell (M-x shell), one of several ways to interact with your command prompt from within Emacs. By default, Emacs shell runs in a "line editing" mode: Typing a command at a shell prompt and pressing Enter does what you'd expect, but you also have access to the entire buffer, including the output of previous commands, and can press Enter on any line. The shell process doesn't actually see you do any of this like it would in a terminal emulator. Instead, Emacs shell lets you play in the buffer, and only sends commands to the shell when you press Enter.

Because the shell doesn't have complete control over the display, one consequence of the line editor is that the shell cannot hide what you type at a password prompt. There are at least two ways to prevent your password from being shown in the line editor. One is to respond to password prompts by typing M-x send-invisible, Enter, your password, then Enter. The password prompt will get your password, but it won't appear on the screen.

Another way is to tell Emacs to watch for password prompts and show the "invisible" prompt automatically. The following configuration for your .emacs file turns on this feature:

(add-hook 'comint-output-filter-functions 'comint-watch-for-password-prompt)

This feature recognizes password prompts that match a pattern, which handles most common cases. You can customize the pattern used in case you run any programs with password prompts that don't match the default. I noticed, for example, that the default pattern in Emacs 22 doesn't notice MySQL password prompts (Enter password:).

To fix this, customize the variable comint-password-prompt-regexp. The value is a nice long intimidating regular expression, and the new value you set it to needs to continue to work for other shell prompts. In the case of the MySQL prompt, I only had to insert Enter \| near the beginning of the pattern. The complete pattern I used is as follows:

\(\(Enter \|[Oo]ld \|[Nn]ew \|'s \|login \|Kerberos \|CVS \|UNIX \| SMB \|^\)[Pp]assword\( (again)\)?\|pass phrase\|\(Enter\|Repeat\|Bad\) passphrase\)\(?:, try again\)?\(?: for [^:]+\)?:\s *\'

Of the several ways to set this variable permanently, I decided to use Customize, the arcane but otherwise nifty user interface that lets you browse and tweak customizable things in Emacs. The quickest way to find and change the password prompt pattern is to use the Help system to find documentation on this variable (C-h v comint-password-prompt-regexp RET) then click the "customize" link. Modify the value, then click "Save for Future Sessions".

comments...

Crisp, to-the-point explanation. Very helpful!

Thank you very much for helping me keeping my passwords to myself when using oracle utilities like imp and exp from within an emacs-shell-buffer.
cheers.

post a comment...