0

Vim builtin indentation seems to get confused with the following script. I cannot get Vim to indent properly the while-loop after the pipe.

#!/bin/bash

while true
do
    # while loop is indented correctly
    while read line
    do
        echo $line
    done < myfile

    # while loop after a pipe is NOT indented correctly despite gg=G
    cat myfile | while read line
do
    echo $line
done
done

Running gg=G does not fix the indentation. Any ideas?

migrated from stackoverflow.com May 18 '16 at 16:55

This question came from our site for professional and enthusiast programmers.

  • 1
    You shouldn't read a file like this in the first place, see mywiki.wooledge.org/BashFAQ/001 – Benjamin W. May 18 '16 at 15:24
  • Thanks for pointing the reference. To me using "cat | while read" more readable that feeding the file at the end of the loop and I am aware of the sub-process restrictions. However the example was just to illustrate the unexpected behaviour. – jbl May 18 '16 at 15:34
  • 2
    Maybe ask on Vi and Vim? – Benjamin W. May 18 '16 at 15:38
  • Thanks for the link. I will consider it eventually. In the meantime I chose to feed the input at the end of the while-loop. – jbl May 18 '16 at 16:44
2

You can't get what you want in this case without writing your own indent script or breaking up the lines like in Nobe4's answer. Take a look at GetShIndent() in $VIMRUNTIME/indent/sh.vim

It looks for the previous non-blank line that starts with while and increases the indent level. However, it checks if the current line starts with do to decrease the indent level. This is how it sets the correct indent if you use the inline while ; do variant. In your case, it finds the do on the current line but not the while on the previous line, so it drops the indent level lower than you expected.

3

I made the indentation works by splitting the cat/while like so:

while true
do
    ...

    cat myfile |
    while read line
    do
        echo $line
    done
done
  • Ok, that's a start I guess. I was wondering if there was not a vim parameter that I could tweak to get the expected behaviour. – jbl May 18 '16 at 15:35

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.