Say I copy the following codeblock from a .md handbook which incldes some information and a few codeblocks (hence it's not a script file):

⇨⇨⇨⇨Indented commands...

The Zsh preexec function could be used to remove all leading whitespaces (usually tabulations but maybe also spaces) from this original codeblock, and return a unindented version of it:


As far as I understand, the preexec action should include 's/^\s*//g'.

Please share how you would achieve this goal with preexec.

  • How does leading spaces make it not a script file? Leading spaces has no effect on how a script runs. "The Zsh preexec could be used to remove all leading whitespaces" -- No it cannot. Perhaps you can explain what it is you're trying to accomplish. Are you wanting to copy/paste code with leading tabs into your terminal? – Patrick May 3 '17 at 12:42
  • 1
    @Patrick, leading blanks can be significant when inside multi-line quoted strings, or in here documents. – Stéphane Chazelas May 3 '17 at 12:43
  • @StéphaneChazelas yes, but you can also argue that blindly removing leading spaces can break things, such as in multi-line quoted strings or here documents. – Patrick May 3 '17 at 12:46
  • 1
    @Patrick, I'll agree with that. Though the OP seems to have a special case in mind. See his other recent questions. – Stéphane Chazelas May 3 '17 at 12:49
  • Related question by the OP that may bring some context: Making a FIFO that strips all leading whitespaces? – Stéphane Chazelas May 3 '17 at 12:50

Doing it in preexec would be too late. By that time, the code has already been parsed. If you modify it, it would need to be parsed again (and possibly, zsh would need to prompt for more lines to finish the code).

Possibly here you can do it in the accept-line widget, that is just before the line editor feeds the line to the shell parser:

accept-line() {
  emulate -L zsh       # default zsh behaviour locally
  set -o extendedglob  # with extendedglob for ## (= ERE +) below

  BUFFER=${BUFFER##[[:blank:]]##} # remove leading blanks

  # remove blanks after newlines in case a multiline buffer is accepted
  # for instance after a safe-paste or a newline entered with <Alt+Ret>

  # call original accept-line
  zle .$WIDGET
zle -N accept-line
  • If someone works crossplatform from Windows it might consider doing this before the content is copied to Linux, as in this AutoHotkey solution: superuser.com/questions/1205075/… – JohnDoea May 10 '17 at 17:46

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.