13

Whenever I'm editing a shell script in emacs and type three chevrons to redirect a raw string to stdin, emacs inserts the characters 'EOF' and a new line in between them, so

cat <<< 'some string'

becomes

cat <<EOF
< 'some string'

I can go back and delete the extra characters to get the buffer in the state I want, but this is very obnoxious behavior, and it only seems to happen in shell-script mode, which is usually the only time I type this pattern. Is there way to disable this behavior?

13

This is caused by sh-electric-here-document-mode. When enabled, << will insert a here document skeleton.

This is enabled by default. You can disable it with a hook, such as:

(add-hook 'sh-mode-hook (lambda () (sh-electric-here-document-mode -1)))
  • 4
    Another option of course is to insert <<< with C-3 <. – glucas Dec 13 '14 at 2:16
  • 1
    Thank you for showing how to turn it off. This sh-electric-here-document-mode is a rather useless feature, IMO. – Dan Moulding Apr 1 '15 at 17:09
  • Also: sh-mode-hook didn't work for me, but sh-set-shell-hook did. – Felipe Lema May 20 '16 at 16:38
17

glucas is exactly correct, but to supplement his answer I have this piece of code I've used myself to make here doc insertion a little smarter.

This advice, coupled with sh-electric-here-document-mode enabled, make it so that if you type two chevrons the automatic here doc will be created, but then if the next character you type is another chevron, it will revert and you will be left with just <<<.

(defadvice sh--maybe-here-document (around be-smart-about-it activate)
  "Do normal here doc auto insert, but if you type another chevron, revert and leave just <<<."
  (if (and (= (current-column) 1)
           (looking-back "^<")
           (looking-at "\nEOF")
           (save-excursion
             (forward-line -1)
             (end-of-line 1)
             (looking-back "<<EOF")))
      (progn (delete-region (search-backward "EOF") (search-forward "EOF" nil t 2))
             (insert "<"))
    ad-do-it))

Of course this means that if you actually want to start a here doc with a chevron, you'll need to raw insert it, C-q<. So it depends on what you do more of, if you do more here strings than here docs, this can be nice to have, even if you don't, it's rare that you'll want to start a here doc with a chevron and be inconvenienced.

enter image description here

  • Ah, that's nice! – glucas Dec 12 '14 at 21:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.