# Path: hq/hquery/functions/extend_string.py
# def _xpath_flags_to_re_flags(flags):
#     re_flags_map = {
#         'i': re.IGNORECASE,
#         'm': re.MULTILINE,
#         's': re.DOTALL,
#         'x': re.VERBOSE,
#     }
# 
#     try:
#         result = 0
#         for flag in flags:
#             result |= re_flags_map[flag]
#         return result
#     except KeyError as e:
#         raise HqueryEvaluationError('Unexpected regular expression flag "{0}"'.format(e.args[0]))
# 
# def string_join(sequence, *args):
#     if len(args) > 0:
#         delimiter = args[0]
#     else:
#         delimiter = ''
#     return delimiter.join([string_value(x) for x in sequence])
# 
# Path: hq/hquery/object_type.py
# def string_value(obj):
#     if is_tag_node(obj) or is_attribute_node(obj) or is_text_node(obj):
#         return derive_text_from_node(obj, peek_context().preserve_space)
#     elif is_number(obj) or is_boolean(obj):
#         return str(obj)
#     elif is_node_set(obj):
#         return string_value(obj[0]) if len(obj) > 0 else ''
#     elif is_sequence(obj):
#         return ''.join(string_value(item) for item in obj)
#     elif is_string(obj):
#         return obj
#     else:
#         raise NotImplementedError('string_value not implemented for type "{0}"'.format(obj.__class__.__name__))
# 
# def is_sequence(obj):
#     return isinstance(obj, list)
# 
# Path: hq/hquery/syntax_error.py
# class HquerySyntaxError(ValueError):
#     pass
# 
# Path: hq/soup_util.py
# def debug_dump_long_string(s, length=50, one_line=True, suffix='...'):
#     return truncate_string(s, length, one_line, suffix)
# 
# Path: hq/string_util.py
# def truncate_string(s, length, one_line=True, suffix='...'):
#     if len(s) <= length:
#         result = s
#     else:
#         result = s[:length + 1].rsplit(' ', 1)[0] + suffix
#     if one_line:
#         result = result.replace('\n', '\\n')
#     return result
# 
# def html_entity_decode(s):
#     result = re.sub('&(%s);' % '|'.join(name2codepoint), lambda m: str(unichr(name2codepoint[m.group(1)])), s)
#     result = re.sub(r'&#(\d{2,3});', lambda m: chr(int(m.group(1))), result)
#     return result
# 
# Path: hq/verbosity.py
# def verbose_print(text, indent_after=False, outdent_before=False):
#     if settings.VERBOSE:
#         if outdent_before:
#             pop_indent()
#         if not is_a_string(text):
#             text = text()
#         print(u'{0}{1}'.format(' ' * indent_level, text), file=sys.stderr)
#         if indent_after:
#             push_indent()


import re
from hq.hquery.functions.extend_string import _xpath_flags_to_re_flags, string_join
from hq.hquery.object_type import string_value, is_sequence
from hq.hquery.syntax_error import HquerySyntaxError
from hq.soup_util import debug_dump_long_string
from hq.string_util import truncate_string, html_entity_decode
from hq.verbosity import verbose_print

    if len(arguments) == 3:
        flags = _xpath_flags_to_re_flags(arguments[2])
    else:
        flags = 0

    def construct(eval_fn):
        def evaluate():
            value = eval_fn()
            if is_sequence(value):
                return [re.sub(arguments[0], arguments[1], string_value(item), flags=flags) for item in value]
            else:
                return re.sub(arguments[0], arguments[1], string_value(value), flags=flags)
        return evaluate

    return construct


def _truncate_filter_link(arguments):

    def construct(eval_fn):
        length = int(arguments[0])
        if len(arguments) == 1:
            suffix = ''
        else:
            suffix = arguments[1]

        def evaluate():
            value = eval_fn()
            if is_sequence(value):

# Path: hq/hquery/functions/extend_string.py
# def _xpath_flags_to_re_flags(flags):
#     re_flags_map = {
#         'i': re.IGNORECASE,
#         'm': re.MULTILINE,
#         's': re.DOTALL,
#         'x': re.VERBOSE,
#     }
# 
#     try:
#         result = 0
#         for flag in flags:
#             result |= re_flags_map[flag]
#         return result
#     except KeyError as e:
#         raise HqueryEvaluationError('Unexpected regular expression flag "{0}"'.format(e.args[0]))
# 
# def string_join(sequence, *args):
#     if len(args) > 0:
#         delimiter = args[0]
#     else:
#         delimiter = ''
#     return delimiter.join([string_value(x) for x in sequence])
# 
# Path: hq/hquery/object_type.py
# def string_value(obj):
#     if is_tag_node(obj) or is_attribute_node(obj) or is_text_node(obj):
#         return derive_text_from_node(obj, peek_context().preserve_space)
#     elif is_number(obj) or is_boolean(obj):
#         return str(obj)
#     elif is_node_set(obj):
#         return string_value(obj[0]) if len(obj) > 0 else ''
#     elif is_sequence(obj):
#         return ''.join(string_value(item) for item in obj)
#     elif is_string(obj):
#         return obj
#     else:
#         raise NotImplementedError('string_value not implemented for type "{0}"'.format(obj.__class__.__name__))
# 
# def is_sequence(obj):
#     return isinstance(obj, list)
# 
# Path: hq/hquery/syntax_error.py
# class HquerySyntaxError(ValueError):
#     pass
# 
# Path: hq/soup_util.py
# def debug_dump_long_string(s, length=50, one_line=True, suffix='...'):
#     return truncate_string(s, length, one_line, suffix)
# 
# Path: hq/string_util.py
# def truncate_string(s, length, one_line=True, suffix='...'):
#     if len(s) <= length:
#         result = s
#     else:
#         result = s[:length + 1].rsplit(' ', 1)[0] + suffix
#     if one_line:
#         result = result.replace('\n', '\\n')
#     return result
# 
# def html_entity_decode(s):
#     result = re.sub('&(%s);' % '|'.join(name2codepoint), lambda m: str(unichr(name2codepoint[m.group(1)])), s)
#     result = re.sub(r'&#(\d{2,3});', lambda m: chr(int(m.group(1))), result)
#     return result
# 
# Path: hq/verbosity.py
# def verbose_print(text, indent_after=False, outdent_before=False):
#     if settings.VERBOSE:
#         if outdent_before:
#             pop_indent()
#         if not is_a_string(text):
#             text = text()
#         print(u'{0}{1}'.format(' ' * indent_level, text), file=sys.stderr)
#         if indent_after:
#             push_indent()


# Path: hq/hquery/string_interpolation.py
import re
from hq.hquery.functions.extend_string import _xpath_flags_to_re_flags, string_join
from hq.hquery.object_type import string_value, is_sequence
from hq.hquery.syntax_error import HquerySyntaxError
from hq.soup_util import debug_dump_long_string
from hq.string_util import truncate_string, html_entity_decode
from hq.verbosity import verbose_print


    if len(arguments) == 3:
        flags = _xpath_flags_to_re_flags(arguments[2])
    else:
        flags = 0

    def construct(eval_fn):
        def evaluate():
            value = eval_fn()
            if is_sequence(value):
                return [re.sub(arguments[0], arguments[1], string_value(item), flags=flags) for item in value]
            else:
                return re.sub(arguments[0], arguments[1], string_value(value), flags=flags)
        return evaluate

    return construct


def _truncate_filter_link(arguments):

    def construct(eval_fn):
        length = int(arguments[0])
        if len(arguments) == 1:
            suffix = ''
        else:
            suffix = arguments[1]

        def evaluate():
            value = eval_fn()
            if is_sequence(value):

                return [truncate_string(string_value(item), length, suffix=suffix) for item in value]