def indent()

in Others_Labs/code/Survey-Survey/yattag/indentation.py [0:0]


def indent(string, indentation = '  ', newline = '\n', indent_text = False, blank_is_text = False):
    """
    takes a string representing a html or xml document and returns
     a well indented version of it
    
    arguments:
    - string: the string to process
    - indentation: the indentation unit (default to two spaces)
    - newline: the string to be use for new lines
      (default to  '\\n', could be set to '\\r\\n' for example)
    - indent_text:
        
        if True, text nodes will be indented:
        
            <p>Hello</p>
            
            would result in
            
            <p>
                hello
            </p>
        
        if False, text nodes won't be indented, and the content
         of any node directly containing text will be unchanged:
         
            <p>Hello</p> will be unchanged
            
            <p><strong>Hello</strong> world!</p> will be unchanged
             since ' world!' is directly contained in the <p> node.
            
            This is the default since that's generally what you want for HTML.
        
    - blank_is_text:
        if False, completely blank texts are ignored. That is the default.
    """ 
    tokens = tokenize(string)
    tag_matcher = TagMatcher(tokens, blank_is_text = blank_is_text)
    ismatched = tag_matcher.ismatched
    directly_contains_text = tag_matcher.directly_contains_text
    result = []
    append = result.append
    level = 0
    sameline = 0
    was_just_opened = False
    tag_appeared = False
    def _indent():
        if tag_appeared:
            append(newline)
        for i in range(level):
            append(indentation)
    for i,token in enumerate(tokens):
        tpe = type(token)
        if tpe is Text:
            if blank_is_text or not token.isblank:
                if not sameline:
                    _indent()
                append(token.content)
                was_just_opened = False
        elif tpe is OpenTag and ismatched(i):
            was_just_opened = True
            if sameline:
                sameline += 1
            else:
                _indent()
            if not indent_text and directly_contains_text(i):
                sameline = sameline or 1
            append(token.content)
            level += 1
            tag_appeared = True
        elif tpe is CloseTag and ismatched(i):
            level -= 1
            tag_appeared = True
            if sameline:
                sameline -= 1
            elif not was_just_opened:
                _indent()
            append(token.content)
            was_just_opened = False
        else:
            if not sameline:
                _indent()
            append(token.content)
            was_just_opened = False
            tag_appeared = True
    return ''.join(result)