Sample Header Ad - 728x90

Indent Fortran source code, propagate indentation down to unindented special lines

3 votes
2 answers
212 views
I'm trying to write my own script to improve some auto-formatting before commiting to a remote repository. I use indenting guides in my IDE and the autoformatters available for my language (FORTRAN) do not support indenting empty lines. I essentially want to use sed to run through the lines of a file and if the line is empty, then add spaces to the line until it has the same number of spaces as the line **above it** (therefore ignoring the first line). Because I want to use this as part of a pre-commit hook, it would be fantastic if the file was not modified if it passes the requirements. Example of unformatted file, where > corresponds to a space:
Start of document - First line is ignored
Second line has text and is therefore ignored
>>>>Third line has four spaces so below (empty line) should have 4 spaces added.

>>>>>>>>Third line has 8 spaces so below (empty line) should have 8 spaces added.

End of document
Desired output:
Start of document - First line is ignored
Second line has text and is therefore ignored
>>>>Third line has four spaces so below (empty line) should have 4 spaces added.
>>>>
>>>>>>>>Third line has 8 spaces so below (empty line) should have 8 spaces added.
>>>>>>>>
End of document
Also, related to this is I would like to indent a line that starts with an exclamation mark **in column 1** (without any spaces before it) to level of the line above (as this is not supported by the autoformatter that I use). Example of unformatted file, where > corresponds to a space:
Start of document - First line is ignored
! Second line starts with exclamation mark in column 1 so it is indented to level of above line
>>>>Third line has 4 spaces to start
!This should have 4 spaces added to it because the first character is ‘!’ and above line has 4
>>>>>>>>This line has 8 spaces
>>>>>>>>!This line shouldn’t be changed as it begins with a space, not an exclamation mark.
End of document
Desired output:
Start of document - First line is ignored
! Second line starts with exclamation mark in column 1 so it is indented to level of above line
>>>>Third line has 4 spaces to start
>>>>!This should have 4 spaces added to it because the first character is ‘!’ and above line has 4
>>>>>>>>This line has 8 spaces
>>>>>>>>!This line shouldn’t be changed as it begins with a space, not an exclamation mark.
End of document
I am very new to bash scripting so explanations of how any solutions work would be great and thanks in advance for any help! Edit: replaced images with text as requested by comment!
Asked by Philip Moloney (31 rep)
Feb 11, 2023, 03:28 PM
Last activity: Mar 9, 2023, 11:57 AM