def help(name, command, just_do_usage=False, do_print=True, **kwargs): ret = "" ret += (_('Usage: {0}{1} {2}').format( name, command.options and _(' [OPTIONS]') or '', ' '.join(get_arg_name(arg) for arg in command.posargs), )) if just_do_usage: if do_print: print(ret) return ret tw = TextWrapper( width=get_terminal_width() ) ret += '\n\n'.join( tw.fill(p) for p in ('',) + command.description) + '\n' if command.posargs: ret += '\n' + _('Positional arguments:') + '\n' ret += print_arguments(command.posargs) + '\n' if command.options: ret += '\n' + _('Options:') + '\n' ret += print_arguments(command.options) + '\n' if command.footnotes: ret += '\n' + '\n\n'.join(tw.fill(p) for p in command.footnotes) ret += '\n' if do_print: print(ret) return ret
class Wrapper(object): #: What to break the words on. It is based on the one inside the #: :class:`textwrap.TextWrapper` class, but without the breaking on '-'. splitExp = re_compile(r'(\s+|(?<=[\w\!\"\'\&\.\,\?])-{2,}(?=\w))') #: How to identify quotes quoteExp = re_compile(r'(>+\ +)') def __init__(self, width): self.email_wrapper = TextWrapper( width=width, expand_tabs=False, replace_whitespace=False, break_on_hyphens=False, break_long_words=False) self.email_wrapper.wordsep_re = self.splitExp self.quote_wrapper = TextWrapper( expand_tabs=False, replace_whitespace=False, break_on_hyphens=False, break_long_words=False) self.quote_wrapper.wordsep_re = self.splitExp def wrap_line(self, l): m = self.quoteExp.match(l) if m: # Quotation wrap quoteChars = m.group(1) self.quote_wrapper.subsequent_indent = quoteChars retval = self.quote_wrapper.fill(l) else: # Normal wrap retval = self.email_wrapper.fill(l) return retval
def _list_verbose(self, migration): if self.verbose: lead = ' ' * 5 wrap = TextWrapper(width=80, initial_indent=lead, subsequent_indent=lead) meta = migration.meta if meta: self.console() for field in ('Author', 'link', 'Description'): value = meta.get(field) if value: self.console(lead + defaultfilters.title(field) + ': ' + value) if migration.flagged: self.console() self.console(lead + 'Flagged: True', 'red') message = meta.get('flag_message') if message: self.console(wrap.fill(message)) last_run = migration.last_run if last_run: meta = last_run.meta if last_run.meta: self.console() meta['date'] = self._local_datetime(last_run.create_date) for field in ('runner', 'date'): value = last_run.meta.get(field) if value: self.console(lead + defaultfilters.title(field) + ': ' + value) notes = meta.get('notes') if notes: self.console(wrap.fill(notes)) if meta or last_run: self.console()
def __classrepr__(cls): """ Note: ipython3 doesn't seem to render class reprs correctly -- may be a bug in the beta version I used. Looks fine in python3 and ipython2. """ def field_items(field_list): return list((attr, getattr(cls, attr, "")) for attr in field_list) def format_fields(field_list): s = ", ".join( "{field}={value!r}".format(field=field.lower(), value=value) for field, value in field_items(field_list) if not value # show only fields without default values ) return s + "," if s else "# <none>" textwrapper = TextWrapper(initial_indent=" " * 4, subsequent_indent=" " * 4) l = [] l.append("\n{cls.__name__}(".format(cls=cls)) l.append(" # Required fields") l.append(textwrapper.fill(format_fields(cls._required))) if getattr(cls, "_conditional", None): for label, fields in cls._conditional.items(): l.append("\n # Required if using " + label) l.append(textwrapper.fill(format_fields(fields))) if cls._discretionary_data_allowed is True: l.append("\n " "# Customer-defined discretionary data may also be included.") l.append("\n # Optional fields") l.append(textwrapper.fill(format_fields(cls._optional))) l.append(")\n") return "\n".join(l)
def display_search_results(self, mixes, s): if self._search_results_page < self.total_pages: next_notification = "--Next-- (Enter)" else: next_notification = "" print('Results for "{}":'.format(s)) wrapper = TextWrapper(width=self.console_width - 5, subsequent_indent=(' ' * 5)) mix_info_tpl = Template('$name ($trackcount tracks, ${hours}h ${minutes}m, by ${user})') page_info_tpl = Template('Page $page on $total_pages. $next_notification') # If this is a new query, reset mixes dictionary if self._search_results_page == 0: self.mixes = {} # Store and show new mix results start_page_no = (self._search_results_page - 1) * self.config['results_per_page'] + 1 for i, mix in enumerate(mixes, start_page_no): # Cache mix self.mixes[i] = mix # Print line prefix = ' {0})'.format(i).ljust(5) hours = mix['duration'] // 60 // 60 minutes = (mix['duration'] // 60) % 60 mix_info = mix_info_tpl.substitute(name=bold(mix['name']), user=mix['user']['login'], trackcount=mix['tracks_count'], hours=hours, minutes=minutes) print(prefix + wrapper.fill(mix_info)) print(wrapper.fill(' Tags: {}'.format(mix['tag_list_cache']))) page_info = page_info_tpl.substitute(page=bold(str(self._search_results_page)), total_pages=bold(str(self.total_pages)), next_notification=next_notification) print(wrapper.fill(page_info))
def describe(self): if self.app.cloudlet_name is None or self.app.blueprint_name is None: print "Usage: nepho blueprint describe <cloudlet> <blueprint>" exit(1) else: scope.print_scope(self) c = _load_cloudlet(self, self.app.cloudlet_name) bp = c.blueprint(self.app.blueprint_name) if bp is None: print colored("Error: ", "red"), "No blueprint by that name.\nFor a list of blueprints run `nepho blueprint list %s`" % (self.app.cloudlet_name) exit(1) wrapper = TextWrapper(width=80, initial_indent=" ", subsequent_indent=" ") wrapper2 = TextWrapper(width=80, initial_indent=" ", subsequent_indent=" ") if bp.definition is not None: print colored(" " + base.DISP_PATH, "yellow"), colored(bp.name, attrs=['underline']), "[", colored(bp.definition['provider'], 'magenta'), "]" print wrapper.fill(bp.definition['summary']) else: print colored(" " + base.DISP_PATH, "yellow"), colored(bp.name, attrs=['underline']) print colored(" Error - missing or malformed blueprint.yaml", "red") return print "\n Description:" print wrapper2.fill(bp.definition['description']) print "\n Default Parameters:" params = bp.definition.pop('parameters', None) for k, v in params.iteritems(): print " %-18s: %s" % (k, v) print return
def usage(self): tw = TextWrapper( width=78, drop_whitespace=True, expand_tabs=True, fix_sentence_endings=True, break_long_words=True, break_on_hyphens=True, ) text = tw.fill(self.__doc__.strip()) + "\n\n" try: options = self.pluginOptions except AttributeError: return text + "This plugin does not support any options.\n" tw.subsequent_indent=' ' * 16, text += "Options supported by this plugin:\n" for opt in sorted(options.keys()): text += "--opt={:<12} ".format(opt) text += tw.fill(options[opt].strip()) + "\n" text += "\n" text += "You can also chain options together, e.g.:\n" text += " --opt=systems,stations,csvonly\n" return text
def show_cache(definer): from textwrap import TextWrapper import inflection def singular_plural(n, word): if word == 0: return ('no', inflection.pluralize(word)) elif word == 1: return (1, word) else: return (str(n), inflection.pluralize(word)) cache_file = definer.cache_file if cache_file is None: print("Caching is not enabled.") else: words = sorted(definer.cache.keys()) n = len(words) wrapper = TextWrapper(width=WRAP_WIDTH) print(wrapper.fill( 'Definition cache "{0}" contains {1} {2}.'.format( cache_file, *singular_plural(n, 'word') )) ) if n > 0: print('\n' + wrapper.fill(', '.join(words)))
class Parser: """ Основной разбор происходит в этом классе, при создании экземпляра класса так же задаются глобальные настройки. При помощи внутреннего парсера разбираем страницу, находим див который содержит больше всего дивов в себе и отдаем его как контент статьи. Для работы обязательно нужно задать настройки для домена """ def __init__(self, raw_data, settings): self.page = raw_data self.settings = settings self.wrapper = TextWrapper(width=self.settings.get('text_width')) self.__parsed_title = None self.__parsed_content = None self.prepare() def prepare(self): removed_tags = [ 'script', 'aside', 'header', 'style', 'nav', 'section', 'footer', 'noindex', ] result = self.page for tag in removed_tags: rx = "<{0}[\s\S]+?/{0}>".format(tag) pattern = re.compile(rx) result = re.sub(pattern, '', result) pattern_link = re.compile(r'<a\s+[^>]*?href="([^"]*)".*?>(.*?)<\/a>', re.DOTALL) result = pattern_link.sub(r'\2[\1]', result) inner_parser = HTMLSourceParser() inner_parser.feed(result) inner_parser.close() divs = {k: len(v) for k, v in inner_parser.div_data.items()} max_divs = max(divs.items(), key=operator.itemgetter(1))[0] self.__parsed_title = inner_parser.header_data[0] self.__parsed_content = inner_parser.div_data[max_divs] def get_title(self): self.wrapper.initial_indent = "" return self.wrapper.fill(self.__parsed_title) def get_article_body(self): text = '' self.wrapper.initial_indent = self.settings.get('article_indent') for paragraph in self.__parsed_content: text += self.wrapper.fill(paragraph) return text
def searchPackages(self, options, search_str): candidates = self.search(search_str) wrapper = TextWrapper(width=80, initial_indent=" ", subsequent_indent=" ") # candidates are dictionary of package name - description for name, desc in candidates.items(): print name print wrapper.fill(desc)
def _print(text): if VERBOSE: text_wrapper = TextWrapper( width=80, initial_indent=(' ' * 4), subsequent_indent=(' ' * 8), ) print text_wrapper.fill(text)
def plot_list(self): """Lists the names of the available figures""" wrapper = TextWrapper(subsequent_indent = " " * 22, width = 78) for method, func in self.get_available_figures(): if method != "list": wrapper.initial_indent = ("%-20s " % method).ljust(22) print wrapper.fill(func.figure_name)
def format_loading_messages_by_lines(errors, warnings): wrapper = TextWrapper(initial_indent='\t\t', subsequent_indent='\t\t', width=80) lines = [] if warnings: lines.append('\t%s' % 'Warnings:') lines.append('\n\n'.join([wrapper.fill(warning) for warning in warnings])) if errors: lines.append('\t%s' % 'Errors:') lines.append('\n\n'.join([wrapper.fill(error) for error in errors])) return lines
def help_msg(err = 0, msg = None): from os.path import basename from sys import stderr, argv, exit from textwrap import fill, TextWrapper from .utils import get_terminal_width w = max(get_terminal_width(), 20) tw = TextWrapper(width = w, subsequent_indent = ' '*18) if msg != None: print(fill(msg, w), file=stderr) print("Usage:") print(tw.fill(" %s input.pts [input2.pts ...] output.pts" % basename(argv[0]))) print("") print("Optional arguments:") print(tw.fill(" -h --help Display this help")) exit(err)
def main(): regex = re.compile(r""" ( (?P<comment>((^\#.*)\n?)+) # consecutive comment lines \n(?P<name>[a-zA-Z0-9._:]+)\s* # variable names =[\t ]*(?P<value>.*) # variable values ) | ( # OR \[(?P<section>[a-zA-Z0-9._ :]+)\] # section names )""", re.VERBOSE | re.MULTILINE) strip_hash = re.compile("^#", re.MULTILINE) current_section = "" keys = {} for match in regex.finditer(CONFIGURATION_FILE_TEMPLATE): if match.group("section"): current_section = match.group('section') if current_section not in keys: keys[current_section] = [] continue comment = re.sub(strip_hash, "", match.group('comment')) comment = dedent(comment) keys[current_section].append( (match.group('name'), match.group('value'), comment) ) wrapper = TextWrapper(initial_indent = " ", subsequent_indent = " ") for section in sorted(keys.keys()): if not keys[section]: continue title = "Section ``%s``" % section print "%s\n%s\n" % (title, "^"*len(title)) for name, value, comment in keys[section]: print "``%s``" % name for para in comment.split("\n\n"): if para[-1] in string.lowercase: para = para+"." print wrapper.fill(para) print " " if value: match = re.match(r"%\(([-a-zA-Z0-9._:]+)\)s$", value) if match: value = "same as ``%s``" % match.group(1) else: value = "``%s``" % value print " Default value: %s" % value print " "
def help(name, command, just_do_usage=False, do_print=True, **kwargs): ret = "" ret += (_('Usage: {name}{options} {args}').format( name=name + (' command' if 'subcommands' in command._fields else ''), options=( _(' [OPTIONS]') if 'options' not in command._fields or command.options else ''), args=( ' '.join(get_arg_name(arg) for arg in command.posargs) if 'posargs' in command._fields else '' ), )) if just_do_usage: if do_print: print(ret) return ret tw = TextWrapper( width=get_terminal_width() ) ret += '\n\n'.join( tw.fill(p) for p in ('',) + command.description) + '\n' if 'subcommands' in command._fields and command.subcommands: ret += '\n' + _('Available commands:') + '\n' ret += print_arguments(command.subcommands) + '\n' if 'posargs' in command._fields and command.posargs: ret += '\n' + _('Positional arguments:') + '\n' ret += print_arguments(command.posargs) + '\n' if 'options' in command._fields and command.options: ret += '\n' + _('Options:') + '\n' ret += print_arguments(command.options) + '\n' if 'subcommands' in command._fields and command.subcommands: ret += '\n' + tw.fill(_( "See '{0} command --help' for more information " "on a specific command.").format(name)) + '\n' if command.footnotes: ret += '\n' + '\n\n'.join(tw.fill(p) for p in command.footnotes) ret += '\n' if do_print: print(ret) return ret
def _split_body(self, text_lines): """Split the body into summary and details. This will assign to self.body_summary the summary text, but it will return the details text for further santization. :return: the raw details text. """ # If there are no non-blank lines, then we're done. if len(text_lines) == 0: self.body_summary = u'' return u'' # If the first line is of a completely arbitrarily chosen reasonable # length, then we'll just use that as the summary. elif len(text_lines[0]) < 60: self.body_summary = text_lines[0] return u'\n'.join(text_lines[1:]) # It could be the case that the text is actually flowed using RFC # 3676 format="flowed" parameters. In that case, just split the line # at the first whitespace after, again, our arbitrarily chosen limit. else: first_line = text_lines.pop(0) wrapper = TextWrapper(width=60) filled_lines = wrapper.fill(first_line).splitlines() self.body_summary = filled_lines[0] text_lines.insert(0, u''.join(filled_lines[1:])) return u'\n'.join(text_lines)
def fill(output_str, indent = " "): from textwrap import TextWrapper console_width = get_console_width() wrapper = TextWrapper(initial_indent = indent, subsequent_indent = indent, width = console_width) return wrapper.fill(output_str)
def refill(msg): """ Refill a changelog message. Normalize the message reducing multiple spaces and newlines to single spaces, recognizing common form of ``bullet lists``, that is paragraphs starting with either a dash "-" or an asterisk "*". """ wrapper = TextWrapper() res = [] items = itemize_re.split(msg.strip()) if len(items)>1: # Remove possible first empty split, when the message immediately # starts with a bullet if not items[0]: del items[0] if len(items)>1: wrapper.initial_indent = '- ' wrapper.subsequent_indent = ' '*2 for item in items: if item: words = filter(None, item.strip().replace('\n', ' ').split(' ')) normalized = ' '.join(words) res.append(wrapper.fill(normalized)) return '\n\n'.join(res)
def format(self, **kargs): self.parse() if self._package_name is not None: kargs['package_name'] = self._package_name if 'version' not in kargs: if len(self.logs) > 0: version = self.logs[0]['version'] reobj = re.match(r"""(.*)(\d+)$""", version) if reobj is None: version += '~1' else: version = reobj.group(1) + str(int(reobj.group(2)) + 1) else: version = '1.0' kargs['version'] = version title = '{package_name} ({version})'.format(**kargs) messages = ' * ' wrapper = TextWrapper(width=80, initial_indent=' * ', subsequent_indent=' ') if 'messages' in kargs: messages = [] for message in kargs['messages']: messages.append(wrapper.fill(message)) messages = '\n'.join(messages) kargs['time'] = strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) tailer = ' -- {author} <{email}> {time}'.format(**kargs) return title + '\n\n' + messages + '\n\n' + tailer + '\n\n'
def wrap(text, width=77, indent='', long_words=False, hyphens=False): """ Wrap text for cleaner output (this is a simple wrapper around `textwrap.TextWrapper` in the standard library). :param text: The text to wrap :param width: The max width of a line before breaking :param indent: String to prefix subsequent lines after breaking :param long_words: Break on long words :param hyphens: Break on hyphens :returns: str(text) """ if sys.version_info[0] < 3: # pragma: no cover # noqa types = [str, unicode] # pragma: no cover # noqa else: # pragma: no cover # noqa types = [str] # pragma: no cover # noqa if type(text) not in types: raise TypeError("Argument `text` must be one of [str, unicode].") wrapper = TextWrapper(subsequent_indent=indent, width=width, break_long_words=long_words, break_on_hyphens=hyphens) return wrapper.fill(text)
def settings(self, short=None): """List available settings.""" types = {v: k for k, v in TYPE_CLASSES.items()} wrapper = TextWrapper(initial_indent='# ', subsequent_indent='# ') for i, section in enumerate(sorted(self._settings)): if not short: print('%s[%s]' % ('' if i == 0 else '\n', section)) for option in sorted(self._settings[section]._settings): meta = self._settings[section].get_meta(option) desc = meta['description'] if short: print('%s.%s -- %s' % (section, option, desc.splitlines()[0])) continue if option == '*': option = '<option>' if 'choices' in meta: value = "{%s}" % ', '.join(meta['choices']) else: value = '<%s>' % types[meta['type_cls']] print(wrapper.fill(desc)) print(';%s=%s' % (option, value))
def list_posts(discussions): t = PrettyTable([ "identifier", "title", "category", "replies", # "votes", "payouts", ]) t.align = "l" t.align["payouts"] = "r" # t.align["votes"] = "r" t.align["replies"] = "c" for d in discussions: identifier = "@%s/%s" % (d["author"], d["permlink"]) identifier_wrapper = TextWrapper() identifier_wrapper.width = 60 identifier_wrapper.subsequent_indent = " " t.add_row([ identifier_wrapper.fill(identifier), identifier_wrapper.fill(d["title"]), d["category"], d["children"], # d["net_rshares"], d["pending_payout_value"], ]) print(t)
def get_text(elements, itemize=False): paragraphs = [] highlight_elements = ['varname', 'parameter'] strip_elements = [ 'returnvalue', 'command', 'link', 'footnote', 'simpara', 'footnoteref', 'function' ] + highlight_elements for element in elements: # put "Since MPD version..." in paranthese etree.strip_tags(element, "application") for e in element.xpath("footnote/simpara"): e.text = "(" + e.text.strip() + ")" for e in element.xpath("|".join(highlight_elements)): e.text = "*" + e.text.strip() + "*" etree.strip_tags(element, *strip_elements) if itemize: initial_indent = " * " subsequent_indent = " " else: initial_indent = " " subsequent_indent = " " wrapper = TextWrapper(subsequent_indent=subsequent_indent, initial_indent=initial_indent) text = element.text.replace("\n", " ").strip() text = re.subn(r'\s+', ' ', text)[0] paragraphs.append(wrapper.fill(text)) return "\n\n".join(paragraphs)
def do_me(self,mdig_model): from textwrap import TextWrapper import re models = mdig.repository.get_models() title_str = "Models in MDiG GRASS db @ " + mdig.repository.db print "-"*len(title_str) print title_str print "model_name [location]" print " description" print "-"*len(title_str) ms=models.keys()[:] ms.sort() for m in ms: try: dm = DispersalModel(models[m],setup=False) tw = TextWrapper(expand_tabs = False, replace_whitespace = True ) tw.initial_indent = " "*4 tw.subsequent_indent = " "*4 desc = dm.get_description() desc = re.sub("[\\s\\t]+"," ",desc) desc = tw.fill(desc) loc = dm.get_location() if not loc: loc = dm.infer_location() if not loc: loc = "unknown" print "%s [%s]:\n%s" % (m,loc,desc) except mdig.model.ValidationError: print "%s [ERROR]" % (m,) sys.exit(0)
def get_data(self): """ If wrapAnswer is set for the box, plain text entered in the text area is stored as one line per paragraph. For display inside a <pre> element it should be wrapped. @return file content """ mt = self.getContentType("file") if re.match("(text/.+)|(application/(.+\+)?xml)", mt): box = self.aq_parent if ((mt == "text/plain") or (mt == "text/x-web-intelligent")) and box.getWrapAnswer(): file = StringIO(self.getField("file").get(self)) wrap = TextWrapper() result = "" for line in file: result += wrap.fill(line) + "\n" return result else: return self.getField("file").get(self) else: return None
def print_arguments(arguments, width=None): if width == None: width = 0 for arg in arguments: width = max(width, len(get_option_names(arg))) help_wrapper = TextWrapper( width=terminal_width, initial_indent=' ' * (width + 5), subsequent_indent=' ' * (width + 5), ) return ('\n'.join( ' ' * 2 + '{0:<{width}} {1}'.format( get_option_names(arg), help_wrapper.fill( arg.help + ( _('(default: {0})').format(arg.default) if arg.default not in (None, False) else _('(required)') if not (arg.optional or arg.positional) else '' ) )[width + 4:] if arg.help else '', width=width, ) for arg in arguments))
def wrap(text, width=77, indent='', long_words=False, hyphens=False): """ Wrap text for cleaner output (this is a simple wrapper around ``textwrap.TextWrapper`` in the standard library). Args: text (str): The text to wrap Keyword Arguments: width (int): The max width of a line before breaking indent (str): String to prefix subsequent lines after breaking long_words (bool): Whether or not to break on long words hyphens (bool): Whether or not to break on hyphens Returns: str: The wrapped string """ types = [str] if type(text) not in types: raise TypeError("Argument `text` must be one of [str, unicode].") wrapper = TextWrapper(subsequent_indent=indent, width=width, break_long_words=long_words, break_on_hyphens=hyphens) return wrapper.fill(text)
def test_whitespace(self): # Whitespace munging and end-of-sentence detection text = """\ This is a paragraph that already has line breaks. But some of its lines are much longer than the others, so it needs to be wrapped. Some lines are \ttabbed too. What a mess! """ expect = [ "This is a paragraph that already has line", "breaks. But some of its lines are much", "longer than the others, so it needs to be", "wrapped. Some lines are tabbed too. What a", "mess!", ] wrapper = TextWrapper(45, fix_sentence_endings=True) result = wrapper.wrap(text) self.check(result, expect) result = wrapper.fill(text) self.check(result, "\n".join(expect))
def CppInitializations(self, Indent=4): """Create initialization list for C++ For example, if the `Variables` object contains atoms m1, m2, t, and x referred to in the `Expressions` object, where m1 and m2 are constant, and t and x are variables, the initialization list should be m1(m1_i), m2(m2_i), t(t_i), x(x_i) The quantities m1_i, etc., appear in the input-argument list output by the method `CppInputArguments`. """ from textwrap import TextWrapper wrapper = TextWrapper(width=120) wrapper.initial_indent = ' '*Indent wrapper.subsequent_indent = wrapper.initial_indent def Initialization(atom): if atom.datatype and (atom.datatype=='std::vector<double>' or atom.datatype=='std::vector<std::complex<double> >'): return '{0}({1})'.format(self.Variables[atom], len(atom.substitution)) if atom.fundamental: return '{0}({0}_i)'.format(self.Variables[atom]) else: return '{0}({1})'.format(self.Variables[atom], atom.ccode()) Initializations = [Initialization(atom) for atom in self.Atoms] return wrapper.fill(', '.join(Initializations))
def make_docstring(fn, override_dict={}): tw = TextWrapper(width=75, initial_indent=" ", subsequent_indent=" ") result = (fn.__doc__ or "") + "\nParameters\n----------\n" for param in getfullargspec(fn)[0]: if override_dict.get(param): param_doc = override_dict[param] else: param_doc = docs[param] param_desc_list = param_doc[1:] param_desc = (tw.fill(" ".join(param_desc_list or "")) if param in docs else "(documentation missing from map)") param_type = param_doc[0] result += "%s: %s\n%s\n" % (param, param_type, param_desc) result += "\nReturns\n-------\n" result += " A `Figure` object." return result
def format_body(sender, body, indent=_("> "), width=WRAP_WIDTH): """ Wrap the text and prepend lines with a prefix. The aim is to get lines with at most `width` chars. But does not wrap if the line is already prefixed. Prepends each line with a localized prefix, even empty lines. Existing line breaks are preserved. Used for quoting messages in replies. """ indent = force_text(indent) # join() doesn't work on lists with lazy translation objects ; nor startswith() wrapper = TextWrapper(width=width, initial_indent=indent, subsequent_indent=indent) # rem: TextWrapper doesn't add the indent on an empty text quote = '\n'.join([line.startswith(indent) and indent+line or wrapper.fill(line) or indent for line in body.splitlines()]) return ugettext("\n\n{sender} wrote:\n{body}\n").format(sender=sender, body=quote)
def wrap(input, wrap=80, initial_indent=""): if len(input) == 0: return initial_indent # TextWrapper collapses newlines into single spaces; we do our own # splitting on newlines to prevent this, so that newlines can actually # be intentionally inserted in text. input_lines = input.split('\n\n') wrapper = TextWrapper(initial_indent=initial_indent, width=wrap) output_lines = [wrapper.fill(line) for line in input_lines] for i in range(len(output_lines)): line = output_lines[i] in_bullet = line.startswith("- ") if in_bullet: output_lines[i] = line.replace("\n", "\n " + initial_indent) return '\n\n'.join(output_lines)
def CppExpressionsAsFunctions(self, Indent=4, Expressions=None): """Define functions to calculate the `Expressions` in C++ The output of this function gives C++ functions to calculate the `Expressions`, assuming the functions are member methods in a class, and so can access the atoms of the expression without explicit arguments. An optional dictionary of expressions allows just a subset of this object's expressions to be output; if this argument is not present, all will be output. """ def dtype(e): if e.datatype: return e.datatype else: return 'double' from textwrap import TextWrapper from PNObjects import PNCollection wrapper = TextWrapper(width=120) wrapper.initial_indent = ' ' * Indent + ' return ' wrapper.subsequent_indent = ' ' * Indent + ' ' Evaluations = [] if not Expressions: Expressions = self.Expressions for Expression in Expressions: ExprColl = PNCollection() for atom in Expression.substitution_atoms: if atom not in self.Variables: try: ExprColl.AddDerivedVariable( str(atom), atom.substitution, substitution_atoms=atom.substitution_atoms, datatype=atom.datatype) except TypeError: pass MiniConstructor = CodeConstructor(self.Variables, ExprColl) Evaluations.append(' ' * Indent + dtype(Expression) + ' ' + Expressions[Expression] + '() {\n' + MiniConstructor.CppEvaluateExpressions(Indent + 2) + '\n' + wrapper.fill(Expression.ccode()) + ';\n' + ' ' * Indent + '}') return '\n'.join(Evaluations)
def template_text(self): wrapper = TextWrapper(subsequent_indent="#%18s" % "", width=78) depends = " && ".join( ["%s in %s" % (d[0], d[1]) for d in self.depends]) if depends == "": depends = None if isinstance(self.candidates, (list, tuple, set)): candidates = " | ".join([str(x) for x in self.candidates]) else: candidates = str(self.candidates) if not self.strict_candidates: candidates += " ..." s = '#\n' s += "# keyword: %s\n" % self.keyword s += "# ----------------------------------------------------------------------------\n" s += "# scopable: %s\n" % str(self.at) s += "# required: %s\n" % str(self.required) if self.top.has_default_section: s += "# provisioning: %s\n" % str(self.provisioning) s += "# default: %s\n" % str(self.default_text) if self.top.has_default_section: s += "# inheritance: %s\n" % str(self.inheritance) s += "# scope order: %s\n" % str(self.scope_order) if self.candidates: s += "# candidates: %s\n" % candidates if depends: s += "# depends: %s\n" % depends if self.convert: s += "# convert: %s\n" % str(self.convert) s += '#\n' if self.text: wrapper = TextWrapper(subsequent_indent="#%9s" % "", width=78) s += wrapper.fill("# desc: " + self.text) + "\n" s += '#\n' if self.default_text is not None: val = self.default_text elif self.candidates and len(self.candidates) > 0: val = self.candidates[0] else: val = self.example s += ";" + self.keyword + " = " + str(val) + "\n\n" return s
def create_docspec(docspec_id, title, tags): title = title.strip() if not title: title = "Docspec %s" % docspec_id title_length = len(title) tags = tags.strip() if not tags: tags = "state:new, priority:normal, untagged" wrapper = TextWrapper(width=80) wrapper.subsequent_indent = ' ' tags = wrapper.fill(tags) return DOCSPEC_TEMPLATE % ('=' * title_length, title, '=' * title_length, NOW.strftime('%Y-%m-%d, %H:%M'), tags)
def draw(self): from textwrap import TextWrapper max_len = max(len(i[0]) for i in self._items) max_len += 3 for i in self._items: i[0] = i[0] + " " * (max_len - 2 - len(i[0])) i[0] += "= " s = " " * max_len msg = "" for i in self._items: wrapper = TextWrapper(initial_indent=i[0], width=88, subsequent_indent=s) msg += wrapper.fill(str(i[1])) + "\n" return msg
def getCommandHelp(self, command_name): """ Get help for a specific command: command_name. Returns: ------- String: <> """ data = self.dbObj.getCommand(command_name) for item in data: try: command_name_lower_case = (item["command"]).lower() if command_name_lower_case == command_name.lower(): command = item["command"] description = item["description"] availability = item["availability"] paramaters = item["paramaters"] basic_info = f""" Command: {command} Description: {description} Availability: {availability} Parameters:""" # dedent, remove spaces basic_info = textwrap.dedent(basic_info).strip() headers = ["Parameter", "Min", "Definition", "Type"] table = [] t = TextWrapper(width=30) for row in paramaters: row_data = [] for key in row: if key == "Definition": row_data.append(t.fill(row[key])) else: row_data.append(row[key]) table.append(row_data) paramaters_table = tabulate(table, headers, tablefmt="fancy_grid") return basic_info + "\n" + paramaters_table except Exception: continue else: return f"Command '{command_name}' not found!"
def myWrapper(intext): f_rpl = re.compile(r'^((.*?\n.*?){1})\n', re.I) # n = len(intext) // 2 n = proCent(48, len(intext)) wrapper = TextWrapper(break_long_words=False, break_on_hyphens=False, width=n) te = wrapper.fill(intext) if te.count('\n') >= 2: te = f_rpl.sub(r'\1 ', te) elif te.count('\n') >= 3: te = f_rpl.sub(r'\1 ', te) elif te.count('\n') >= 4: te = f_rpl.sub(r'\1 ', te) elif te.count('\n') >= 5: te = f_rpl.sub(r'\1 ', te) elif te.count('\n') == 6: te = f_rpl.sub(r'\1 ', te) return te
def print_arguments(arguments, width=None): if width == None: width = 0 for arg in arguments: width = max(width, len(get_option_names(arg))) help_wrapper = TextWrapper( width=get_terminal_width(), initial_indent=' ' * (width + 5), subsequent_indent=' ' * (width + 5), ) return ('\n'.join(' ' * 2 + '{0:<{width}} {1}'.format( get_option_names(arg), arg.help and help_wrapper.fill(arg.help + (arg.default not in ( None, False) and _('(default: {0!r})').format(arg.default) or '')) [width + 4:] or '', width=width, ) for arg in arguments))
def wiprint(text, width=80, subsequent_indent=" ", **kwargs): """ Prints wrapped text. Arguments: text (str): Text to wrap width (int): Width of formatted text subsequent_indent (str): Text with which to prepend lines after the first kwargs (dict): Additional keyword arguments passed to :func:`TextWrapper` """ import re from textwrap import TextWrapper tw = TextWrapper(width=width, subsequent_indent=subsequent_indent, **kwargs) print(tw.fill(re.sub(r"\s+", " ", text)))
def format_deplist(pkgs: str, deptype: str) -> str: """ take a white-space delimited string of pkgs and a deptype it wraps them with a width of 80 by default, but takes care to not break $(vopt_if) blocks in half. actions done for the symbols given: 1. create 'pkgstr' that is pkgs with deptype and formatting for XBPS dependency template 2. replace 'zzopt' with '$(vopt_if' 3. replace '>' with ')' 4. replace '|' with ' ' 5. wrap the text to 80 chars, no long_words or hyphen_breaks also add ' ' as a subsequent_indent 6. use wrap.fill to return a single multi-line string 7. replace '/' with ' ' 8. return the string """ from textwrap import TextWrapper pkgstr: str = deptype + '="' + pkgs.replace('zzopt', '$(vopt_if') + '"' """ Before formatting the string we replace > with ) to match the $(vopt_if and we also replace | with whitespace so that text formatting can separate it into a an whitespace, which is allowed since we put the dependencies inside a ' ' block """ pkgstr = pkgstr.replace('>', ')') pkgstr = pkgstr.replace('|', ' ') text_wrapper = TextWrapper(width=80, break_long_words=False, break_on_hyphens=False, subsequent_indent=' ',) pkgstr = text_wrapper.fill(pkgstr) """ / must be replaced with a space after the string is Formatted because it can't be separated into a newspace, only the dependencies inside the same group marked by the | char """ pkgstr = pkgstr.replace('/', ' ') return pkgstr
def show_messages(self, level='all'): levels = {'error': 0, 'warning': 1, 'notice': 2, 'all': 3} if not self.completed: return parser = HTMLParser() wrapper = TextWrapper(initial_indent='\t', subsequent_indent='\t', width=120) for message in self.messages: if levels[message['type']] > levels[level]: continue msgtype = message['type'][0].upper() + message['type'][1:] print("%s: %s" % (msgtype, message['message'])) print( wrapper.fill(parser.unescape("".join(message['description']))) + "\n")
def printInd(s, level=1, length=70, prefix=''): from textwrap import TextWrapper indents = {1: 0, 2: 4, 3: 8, 4: 12, 5: 16} ind = indents[level] indstr = ' ' * int(ind) wrapper = TextWrapper() wrapper.width = length wrapper.initial_indent = indstr wrapper.subsequent_indent = indstr string = wrapper.fill('%s %s' % (prefix, s)) try: print('\n' + string) except: print('\n' + string.encode('ascii', 'replace')) return
def usage(self, argv): """ Generate the outlying usage text for TD. This tells the user the list of current commands, generated programatically, and the outlying command functionality. """ text = ("Usage: {prog} <command>\n\n" "Where <command> is one of:\n\n".format(prog=argv[0])) # Figure out the pre-indentation cmdFmt = ' {:<12s} ' cmdFmtLen = len(cmdFmt.format('')) # Generate a formatter which will produce nicely formatted text # that wraps at column 78 but puts continuation text one character # indented from where the previous text started, e.g # cmd1 Cmd1 help text stuff # continued cmd1 text # cmd2 Cmd2 help text tw = TextWrapper( subsequent_indent=' ' * (cmdFmtLen + 1), width=78, drop_whitespace=True, expand_tabs=True, fix_sentence_endings=True, break_long_words=False, break_on_hyphens=True, ) # List each command with its help text lastCmdName = None for cmdName, cmd in sorted(commandIndex.items()): tw.initial_indent = cmdFmt.format(cmdName) text += tw.fill(cmd.help) + "\n" lastCmdName = cmdName # Epilog text += ( "\n" "For additional help on a specific command, such as '{cmd}' use\n" " {prog} {cmd} -h".format(prog=argv[0], cmd=lastCmdName)) return text
class ManFormatter: """Formats a list of options into a groff snippet""" def __init__(self): self.__wrapper = TextWrapper(width=80, replace_whitespace=False, break_long_words=False, break_on_hyphens=False) self.__tags = GroffTagReplacer() def __groffize(self, text): """Encode text as groff text""" text = self.__tags.replace(text) text = re.sub(r'(?<!\\)-', r'\\-', text) # remove any leading whitespace return re.sub(r'^\s+', '', text, flags=re.MULTILINE) def __format_option(self, option): """Print a single option""" if option.section and not len(option.desc): return if option.include: return if option.section: print('.TP\n.B {0}\n.br'.format(option.fullname)) else: print('.TP') default = option.default if option.default else '' print('.BR {0} " [{1}]"'.format(option.fullname, default)) for para in option.desc if len(option.desc) < 2 else option.desc[1:]: print(self.__groffize(self.__wrapper.fill(para))) print('') def format(self, options): """Print a list of options""" if not options: return for option in options: if option.section: self.__format_option(option) self.format(option.options) else: self.__format_option(option)
def hexdump(x, indent=False): """ From Scapy's utils.py, modified to return a string instead of print directly, and just use sane() instead of sane_color() """ result = "" x = str(x) l = len(x) i = 0 while i < l: result += "%08x " % i for j in range(16): if i + j < l: result += "%02x " % ord(x[i + j]) else: result += " " if j % 16 == 7: result += " " result += " " result += sane(x[i:i + 16]) + "\n" i += 16 if indent: """ Print hexdump indented 4 spaces, and blue - same as Wireshark """ indent_count = 4 # Same as Wireshark's hex display for following TCP streams tw = TextWrapper(width=78 + indent_count, initial_indent=' ' * indent_count, subsequent_indent=' ' * indent_count) result = tw.fill(result) result = color_string(result, "CYAN") return (result) else: """ Print hexdump left aligned, and red - same as Wireshark """ result = color_string(result.strip(), "RED") return (result)
def rjust_text(text, width=80, indent=0, subsequent=None): """Same as L{wrap_text} with the difference that the text is aligned against the right text border. :param str text: Text to wrap and align. :param int width: Maximum number of characters per line. :param int indent: Indentation of the first line. :type subsequent: int or None :param subsequent: Indentation of all other lines, if it is None, then the indentation will be same as for the first line. """ text = re.sub('\s+', ' ', text).strip() if subsequent is None: subsequent = indent wrapper = TextWrapper(width=width, break_long_words=False, replace_whitespace=True, initial_indent=' ' * (indent + subsequent), subsequent_indent=' ' * subsequent) return wrapper.fill(text)[subsequent:]
def settings(self, short=None): """List available settings.""" if short: for section in sorted(self._settings): for option in sorted(self._settings[section]._settings): short, full = self._settings.option_help(section, option) print('%s.%s -- %s' % (section, option, short)) return wrapper = TextWrapper(initial_indent='# ', subsequent_indent='# ') for section in sorted(self._settings): print('[%s]' % section) for option in sorted(self._settings[section]._settings): short, full = self._settings.option_help(section, option) print(wrapper.fill(full)) if option != '*': print(';%s =' % option) print('')
def _info_tools(): """Print info about command line tools.""" print('\n*** ctapipe tools ***\n') print('the following can be executed by typing ctapipe-<toolname>:') print('') # TODO: how to get a one-line description or # full help text from the docstring or ArgumentParser? # This is the function names, we want the command-line names # that are defined in setup.py !??? from ctapipe.tools.utils import get_all_descriptions from textwrap import TextWrapper wrapper = TextWrapper(width=80, subsequent_indent=" " * 35) scripts = get_all_descriptions() for name, desc in sorted(scripts.items()): text = "{:<30s} - {}".format(name, desc) print(wrapper.fill(text)) print('') print('')
def wrap(text, width=77, indent='', long_words=False, hyphens=False): """ Wrap text for cleaner output (this is a simple wrapper around `textwrap.TextWrapper` in the standard library). :param text: The text to wrap :param width: The max width of a line before breaking :param indent: String to prefix subsequent lines after breaking :param long_words: Break on long words :param hyphens: Break on hyphens :returns: str(text) """ if type(text) != str: raise TypeError("`text` must be a string.") wrapper = TextWrapper(subsequent_indent=indent, width=width, break_long_words=long_words, break_on_hyphens=hyphens) return wrapper.fill(text)
def _handle_show_create_procedure(self, showproc_match): """Handle SHOW CREATE PROCEDURE We send the information from the command as text to the client in a one row/one column result. :param showproc_match: Result of re.match """ group, command = showproc_match.groups() try: command_class = get_command(group, command) except KeyError: # group and/or command does not exists self.send_error( errorcode.ER_UNKNOWN_PROCEDURE, "Fabric command {0}.{1} does not exists".format(group,command), "22000" ) return self.send_packet(self.column_count_packet(1)) self.send_packet(self.column_packet( 'fabric_help', type_=str, table='fabric_help' )) self.send_packet(self.eof_packet()) command_text = command_class.get_signature() paragraphs = [] if command_class.__doc__: wrapper = TextWrapper() paragraphs = [] for para in command_class.__doc__.split("\n\n"): if para: paragraphs.append(wrapper.fill(para.strip())) help_text = command_text + "\n\n" + "\n\n".join(paragraphs) _LOGGER.debug(help_text) self.send_packet(self.row_packet(help_text)) self.send_packet(self.eof_packet())
def get_help(self, method_parts, debug=False): help_lines = [] def w(l): help_lines.append(l) wrapper = TextWrapper(initial_indent="\t", subsequent_indent="\t") method = self.methods[method_parts] w( method.get("httpMethod", "?") + " method: " + " ".join(method_parts) + "\n") if "description" in method: w(method["description"].strip() + "\n") if debug: w(json.dumps(method, indent=4, sort_keys=True)) params = method.get("parameters", {}) if method.get("httpMethod", "") == "POST": params.update({ "body": { "required": True, "type": "JSON" }, "fields": { "type": "JSON" } }) if not params: w("API method takes no parameters") else: w("Parameters (*required):") for param_name in sorted(params): param = params[param_name] descr = param.get("description") descr = "\n" + wrapper.fill(descr) if descr else "" w(" {}: {} {} {}".format( param_name, param["type"], "*" if param.get("required") else "", descr, )) return "\n".join(help_lines)
def print_arguments(arguments, width=None): if width == None: width = 0 for arg in arguments: width = max(width, len(get_option_names(arg))) help_wrapper = TextWrapper( width=get_terminal_width(), initial_indent=' ' * (width + 5), subsequent_indent=' ' * (width + 5), ) return ('\n'.join(' ' * 2 + '{0:<{width}} {1}'.format( get_option_names(arg), help_wrapper.fill(arg.help + ( _('(default: {0})').format(arg.default) if arg.default not in (None, False) else _('(required)') if not ( arg.optional or arg.positional) else ''))[width + 4:] if arg. help else '', width=width, ) for arg in arguments))
def draw(self): from limix import config from textwrap import TextWrapper max_len = max(len(i[0]) for i in self._items) max_len += len(self._sep) + 1 for i in self._items: i[0] = i[0] + " " * (max_len - len(self._sep) - len(i[0])) i[0] += self._sep s = " " * max_len msg = "" width = config["display.text_width"] for i in self._items: wrapper = TextWrapper(initial_indent=i[0], width=width, subsequent_indent=s) msg += wrapper.fill(str(i[1])) + "\n" return msg.rstrip()
def get_help(self, name_parts, debug=False): help_lines = [] def add_line(li): help_lines.append(li) wrapper = TextWrapper(initial_indent="\t", subsequent_indent="\t") ep_info = self.endpoints[name_parts] method = ep_info.get("httpMethod", "?") add_line(f"{method} endpoint: " + " ".join(name_parts) + "\n") if "description" in ep_info: add_line(ep_info["description"].strip() + "\n") if debug: add_line(dumps(ep_info, indent=4, sort_keys=True)) params = ep_info.get("parameters", {}) if method == "POST": params.update({ "body": { "required": True, "type": "JSON" }, "fields": { "type": "JSON" }, }) if not params: add_line("Endpoint takes no parameters") else: add_line("Parameters (*required):") for param_name in sorted(params): param = params[param_name] descr = param.get("description") descr = "\n" + wrapper.fill(descr) if descr else "" add_line(" {}: {} {} {}".format( param_name, param["type"], "*" if param.get("required") else "", descr, )) return "\n".join(help_lines)
def main(): ugly = False if os.sys.platform[0:3] == 'win': ugly = True response = urllib2.urlopen(sys.argv[1]) encoding = response.headers.getparam('charset') html = response.read().decode(encoding) f = StringIO(html) parser = etree.HTMLParser() #create SAX tree tree = etree.parse(f, parser) handler = BoilerpipeHTMLContentHandler() sax.saxify(tree, handler) a = ArticleExtractor() #parses our data and creates TextDocument with TextBlocks doc = handler.toTextDocument() tw = TextWrapper() tw.width = 80 tw.initial_indent = os.linesep + os.linesep parsed_url = urllib2.urlparse.urlparse(sys.argv[1]) filename = parsed_url.netloc + "-" + "".join([ c for c in parsed_url.path if c.isalpha() or c.isdigit() or c == ' ' ]).rstrip() + '.txt' output = [] for line in a.getText(doc).splitlines(): output.append(tw.fill(line)) i = 0 with codecs.open(filename, 'w', encoding='utf8') as f: for line in output: if ugly: line.replace('\n', os.linesep) f.write(line) print "Article saved. Lines: %s. Filename: %s" % (len(output), filename)
def make_docstring(fn, override_dict=None, append_dict=None): override_dict = {} if override_dict is None else override_dict append_dict = {} if append_dict is None else append_dict tw = TextWrapper(width=75, initial_indent=" ", subsequent_indent=" ") result = (fn.__doc__ or "") + "\nParameters\n----------\n" for param in getfullargspec(fn)[0]: if override_dict.get(param): param_doc = list(override_dict[param]) else: param_doc = list(docs[param]) if append_dict.get(param): param_doc += append_dict[param] param_desc_list = param_doc[1:] param_desc = (tw.fill(" ".join(param_desc_list or "")) if param in docs or param in override_dict else "(documentation missing from map)") param_type = param_doc[0] result += "%s: %s\n%s\n" % (param, param_type, param_desc) result += "\nReturns\n-------\n" result += " plotly.graph_objects.Figure" return result
class FastaFormat(SequenceFileFormat): """FASTA SequenceFileFormat. Args: line_length: Max line length (in characters), or None. Determines whether and how lines are wrapped. """ def __init__(self, line_length=None): self.text_wrapper = None if line_length: from textwrap import TextWrapper self.text_wrapper = TextWrapper(width=line_length) def format(self, read): return self.format_entry(read.name, read.sequence) def format_entry(self, name, sequence): """Convert a sequence record to a string. """ if self.text_wrapper: sequence = self.text_wrapper.fill(sequence) return "".join((">", name, "\n", sequence, "\n"))
def test_whitespace(self): # Whitespace munging and end-of-sentence detection text = """\ This is a paragraph that already has line breaks. But some of its lines are much longer than the others, so it needs to be wrapped. Some lines are \ttabbed too. What a mess! """ expect = ["This is a paragraph that already has line", "breaks. But some of its lines are much", "longer than the others, so it needs to be", "wrapped. Some lines are tabbed too. What a", "mess!"] wrapper = TextWrapper(45, fix_sentence_endings=True) result = wrapper.wrap(text) self.check(result, expect) result = wrapper.fill(text) self.check(result, '\n'.join(expect))