Pretty print translations.

    If linewrap is set to 0 disble line wrapping.

    Parameters
    ----------
    translations : list
        List of word translations.
    linewrap : int
        Maximum line length before wrapping.
325792
def wrap_text(translations, linewrap=0):
    
    # pylint: disable=too-many-locals

    def wrap(text, width=linewrap, findent=0, sindent=0, bold=False):
        if width == 0:
            text = " " * findent + text
        else:
            text = textwrap.fill(
                text,
                width=width,
                initial_indent=" " * findent,
                subsequent_indent=" " * sindent,
            )
        # don't use bold when stdout is pipe or redirect
        if bold and sys.stdout.isatty():
            text = "\033[0;1m" + text + "\033[0m"
        return text

    indent = 5
    result = []
    for i1, trans in enumerate(translations):
        if i1 > 0:
            result.append("\n")
        for w in trans.word:
            result.append(wrap(w, bold=True))
        for i2, t in enumerate(trans.parts_of_speech):
            if i2 > 0:
                result.append("")
            if t.part:
                result.append("[{part}]".format(part=t.part))
            for i3, m in enumerate(t.meanings, 1):
                if i3 > 1:
                    result.append("")
                meaning = "{index:>3}. {meanings}".format(
                    index=i3, meanings=", ".join(m.meaning)
                )
                result.append(wrap(meaning, sindent=indent, bold=True))
                eindent = indent + 1
                for e in m.examples:
                    result.append("")
                    result.append(wrap(e[0], findent=eindent, sindent=eindent))
                    if len(e) == 2 and e[1]:
                        result.append(wrap(e[1], findent=eindent, sindent=eindent + 1))
    return "\n".join(result)
610123
def wrapped_attributes(list = {}, for_definition = false)
      return unless (bracket = accept :brackets)

      accept_newline
      attributes_assignments list, true, for_definition
      accept_newline

      accept_stripped bracket.to_sym, :*

      list
    end
407283
def word_wrap(self, text, width=1023):
        
        substrings = []

        string = text
        while len(string) > width:
            index = width - 1
            while not string[index].isspace():
                index = index - 1

            line = string[0:index]
            substrings.append(line)

            string = string[index + 1:]

        substrings.append(string)

        return substrings
136940
def wrap(self, text, **kwargs):
        '''
        '''
        pilcrow = re.compile(r'(\n\s*\n)', re.MULTILINE)
        list_prefix = re.compile(r'\s*(?:\w|[0-9]+)[\.\)]\s+')

        paragraphs = pilcrow.split(text)
        wrapped_lines = []
        for paragraph in paragraphs:
            if paragraph.isspace():
                wrapped_lines.append('')
            else:
                wrapper = textwrap.TextWrapper(**vars(self))
                list_item = re.match(list_prefix, paragraph)
                if list_item:
                    wrapper.subsequent_indent += ' ' * len(list_item.group(0))
                wrapped_lines.extend(wrapper.wrap(paragraph))

        return wrapped_lines
143230
def complete_wrap(self, func, *args, **kwargs):
        
        # Workaround readline's one-time-read of terminal width.
        termcols = shutil.get_terminal_size()[0]
        readline.parse_and_bind('set completion-display-width %d' % termcols)
        try:
            return func(*args, **kwargs)
        except:
            traceback.print_exc()
            raise
791363
def doc_to_lines(self, doc, format_func=None):
        
        if format_func:
            for l in format_func(doc).splitlines():
                yield l
        elif self.pretty_print:
            for l in pprint.pformat(doc).splitlines():
                yield l
        else:
            for l in str(doc).splitlines():
                yield l
1102119
def _document_lines(self, text):
        
        inlines = text.split('\n')
        doc_lines = [(re.sub(r'^ +| +$', '', line), num)
                     for line, num
                     in zip(inlines, xrange(1, len(inlines) + 1))]
        return doc_lines
363838
def all_phrase_translations(phrase):
    '''
    
    '''
    if not trees:
        init()
    phrase = phrase.split(string.whitespace)
    for word in phrase:
        for x in range(len(word)):
            for translation in _words_at_the_beginning(
                    word[x+1:],
                    trees['simplified'][word[x]],
                    prefix=word[x]):
                yield translation
404134
def get_line(self, text, on_unicode_error='strict'):
        

        def check(entry):
            if entry.find('\n') != -1:
                raise ValueError(
                    "get_line processes one line at a time (remove \'\\n\')"
                )
            entry += "\n"
            return entry

        if type(text) == list:
            text = [check(entry) for entry in text]
            return self.f.multilineGetLine(text, on_unicode_error)
        else:
            text = check(text)
            return self.f.getLine(text, on_unicode_error)
692958
function translateLineEndings(text, lineEndings) {
        if (lineEndings !== LINE_ENDINGS_CRLF && lineEndings !== LINE_ENDINGS_LF) {
            lineEndings = getPlatformLineEndings();
        }

        var eolStr = (lineEndings === LINE_ENDINGS_CRLF ? "\r\n" : "\n");
        var findAnyEol = /\r\n|\r|\n/g;

        return text.replace(findAnyEol, eolStr);
    }
271563
def last_line(text):
    
    last_line_of_text = ""
    while last_line_of_text == "" and len(text) > 0:
        last_line_start = text.rfind("\n")
        # Handle one-line strings (without \n)
        last_line_start = max(0, last_line_start)
        last_line_of_text = text[last_line_start:].strip("\r\n ")
        text = text[:last_line_start]
    return last_line_of_text
137022
def _detect_encoding(data=None):
    
    import locale
    enc_list = ['utf-8', 'latin-1', 'iso8859-1', 'iso8859-2',
                'utf-16', 'cp720']
    code = locale.getpreferredencoding(False)
    if data is None:
        return code
    if code.lower() not in enc_list:
        enc_list.insert(0, code.lower())
    for c in enc_list:
        try:
            for line in data:
                line.decode(c)
        except (UnicodeDecodeError, UnicodeError, AttributeError):
            continue
        return c
    print("Encoding not detected. Please pass encoding value manually")
94108
def _get_translate():
    
    translate = {}
    model_path = pkg_resources.resource_filename('hwrt', 'misc/')
    translation_csv = os.path.join(model_path, 'latex2writemathindex.csv')
    arguments = {'newline': '', 'encoding': 'utf8'}
    with open(translation_csv, 'rt', **arguments) as csvfile:
        contents = csvfile.read()
    lines = contents.split("\n")
    for csvrow in lines:
        csvrow = csvrow.split(',')
        if len(csvrow) == 1:
            writemathid = csvrow[0]
            latex = ""
        else:
            writemathid, latex = csvrow[0], csvrow[1:]
            latex = ','.join(latex)
        translate[latex] = writemathid
    return translate
936747
def writelines(lines, filename, encoding='utf-8', mode='wb'):
    
    return write(os.linesep.join(lines), filename, encoding, mode)
635994
def readline(self, length=None):
        
        if length == 0:
            return b''

        self._fillbuff()

        if self.empty():
            return b''

        linebuff = self.buff.readline(length)

        # we may be at a boundary
        while not linebuff.endswith(b'\n'):
            if length:
                length -= len(linebuff)
                if length <= 0:
                    break

            self._fillbuff()

            if self.empty():
                break

            linebuff += self.buff.readline(length)

        return linebuff
1318442
def _read_translations(self):
        
        print('Reading original translations')
        self.translations_map = {}
        n_translations = 0
        with open(os.path.join(self.src_dir, 'translations.txt'),
                  'rb') as csvfile:
            reader = csv.DictReader(csvfile)
            for row in reader:
                self.translations_map.setdefault(
                    row['trans_id'], {})[row['lang']] = row['translation']
                n_translations += 1
        print('\ttotal original translations: %s' % n_translations)
271366
def line_width(line):
    
    if six.PY2:
        assert isinstance(line, unicode)
    _line = width_cal_preprocess(line)
    result = sum(map(get_char_width, _line))
    return result