Next / Previous / Contents / Shipman's homepage

20.5. InputFile.__trimLine(): Implement length changes

# - - -   I n p u t F i l e . _ _ t r i m L i n e

    def __trimLine(self, rawLine):
        '''Adjust line length per Args().

          [ (Args() is valid) and (line is a string) ->
              return rawLine with any changes made to it, as specified
              by Args(), that change its length, and trailing
              whitespace removed if present ]

The first order of business is to remove the trailing newline, if there is one. We don't have to test whether rawLine is empty before extracting the last character, because of the precondition that rawLine is nonempty.

        #-- 1
        # [ if rawLine ends with a newline ->
        #       line  :=  rawLine without that newline
        #   else ->
        #       line  :=  rawLine ]
        line =(rawLine
               if rawLine[-1] != '\n'
               else rawLine[:-1])

An initial formfeed is removed if it is the break string.

        #-- 2
        # [ if (Args().breakString is '\f') and
        #   (line starts with '\f') ->
        #       formTrim  :=  line without the initial '\f'
        #   else ->
        #       formTrim  :=  line ]
        formTrim =(line[1:]
                   if(( Args().breakString == '\f') and
                       (len(line) > 0) and
                       (line[0] == '\f'))
                   else line)

Tab expansion can also change the length of the line. The .expandtabs() method is built-in to the str class.

        #-- 3
        # [ expandedLine  :=  formTrim with tabs expanded using interval
        #                     Args().tabSize ]
        expandedLine = formTrim.expandtabs(Args().tabSize)

Any trailing whitespace is removed at this point.


In the initial release, trailing whitespace was retained, and could cause overflow on a line that would otherwise fit. In October 2010 the author implemented suppression of entirely blank columns. However, this feature leads to the possibility that an entirely blank overflow line will appear at the beginning of a nonblank column, yet it is a continuation of a blank line that does not appear because it is part of a blank column.

For example, suppose that a column is 50 characters wide. In the first release, an input line containing 80 space characters would occupy two lines, and the overflow line would be blank past the shaded indentation. Now, this input line will occupy only one output line. If this is a concern, we can always add another command line option that forces the display of all columns even if they contain no non-whitespace characters.

        #-- 4
        return expandedLine.rstrip()