view textshaper/indent.py @ 19:70dde00a4df0

selectable, albeit single, input
author Jeff Hammel <k0scist@gmail.com>
date Sun, 23 Feb 2014 00:26:19 -0800
parents 0d0db0d79bfd
children 0930c6884f8a
line wrap: on
line source

#!/usr/bin/env python

"""
indentation of text blocks
"""

import optparse
import os
import sys

def indent(text, indentation=4, space=' ', strict=False):
    """
    indent a block of text

    text -- lines of text to indent
    indentation -- number of spaces to indent
    space -- what to indent with
    strict -- whether to enforce required whitespace for negative indentation
    """

    if not indentation:
        # nothing to do
        return text

    if indentation > 0:
        retval = [space * indentation + line for line in text]
    else:
        # negative indentation
        indentation = -indentation
        retval = []
        for line in text:
            prefix = line[:indentation]
            for index, char in enumerate(prefix):
                if not char == space:
                    if strict:
                        raise AssertionError("Found non-'%s' charcter at column %d for indentation -%d" % (space, index, indentation))
                    break
            else:
                index = indentation
            retval.append(line[index:])

    return retval


def main(args=sys.argv[1:]):
    # TODO : refactor to be more general and stuff

    # parse command line
    usage = '%prog [options] [file] [file2] [...]'
    description = """indent files or stdin if no files given"""
    parser = optparse.OptionParser(usage=usage, description=__doc__)
    parser.add_option('-o', '--output', dest='output',
                      help="output file or stdout if not given")
    options, files = parser.parse_args(args)

    # input from files or stdin
    if files:
        missing = [not os.path.exists(filename) for filename in files]
        if missing:
            parser.error("File(s) not found: %s" % ', '.join(missing))
        def _files():
            for filename in files:
                with open(f, 'r') as f:
                    yield f
    else:
        def _files():
            yield sys.stdin

    # process input
    for f in _files():
        print f

if __name__ == '__main__':
    main()