Example #1
0
    def render_code(self, cell):
        if not cell.input:
            return []
        lines = []
        n = self._get_prompt_number(cell)
        if self.show_prompts and not self.inline_prompt:
            lines.extend(['*In[%s]:*' % n, ''])
        if self.show_prompts and self.inline_prompt:
            prompt = 'In[%s]: ' % n
            input_lines = cell.input.split('\n')
            src = (prompt + input_lines[0] + '\n' +
                   indent('\n'.join(input_lines[1:]), nspaces=len(prompt)))
        else:
            src = cell.input
        src = highlight(src) if self.highlight_source else indent(src)
        lines.extend([src, ''])
        if cell.outputs and self.show_prompts and not self.inline_prompt:
            lines.extend(['*Out[%s]:*' % n, ''])
        for output in cell.outputs:
            conv_fn = self.dispatch(output.output_type)
            lines.extend(conv_fn(output))

        #lines.append('----')
        lines.append('')
        return lines
Example #2
0
    def pdoc(self,obj,oname='',formatter = None):
        """Print the docstring for any object.

        Optional:
        -formatter: a function to run the docstring through for specially
        formatted docstrings."""

        head = self.__head  # For convenience
        ds = getdoc(obj)
        if formatter:
            ds = formatter(ds)
        if inspect.isclass(obj):
            init_ds = getdoc(obj.__init__)
            output = "\n".join([head("Class Docstring:"),
                                indent(ds),
                                head("Constructor Docstring:"),
                                indent(init_ds)])
        elif (type(obj) is types.InstanceType or isinstance(obj,object)) \
                 and hasattr(obj,'__call__'):
            call_ds = getdoc(obj.__call__)
            if call_ds:
                output = "\n".join([head("Class Docstring:"),
                                    indent(ds),
                                    head("Calling Docstring:"),
                                    indent(call_ds)])
            else:
                output = ds
        else:
            output = ds
        if output is None:
            self.noinfo('documentation',oname)
            return
        page.page(output)
    def class_get_trait_help(cls, trait, inst=None):
        """Get the help string for a single trait.
        
        If `inst` is given, it's current trait values will be used in place of
        the class default.
        """
        assert inst is None or isinstance(inst, cls)
        lines = []
        header = "--%s.%s=<%s>" % (cls.__name__, trait.name, trait.__class__.__name__)
        lines.append(header)
        if inst is not None:
            lines.append(indent('Current: %r' % getattr(inst, trait.name), 4))
        else:
            try:
                dvr = repr(trait.get_default_value())
            except Exception:
                dvr = None # ignore defaults we can't construct
            if dvr is not None:
                if len(dvr) > 64:
                    dvr = dvr[:61]+'...'
                lines.append(indent('Default: %s' % dvr, 4))
        if 'Enum' in trait.__class__.__name__:
            # include Enum choices
            lines.append(indent('Choices: %r' % (trait.values,)))

        help = trait.get_metadata('help')
        if help is not None:
            help = '\n'.join(wrap_paragraphs(help, 76))
            lines.append(indent(help, 4))
        return '\n'.join(lines)
Example #4
0
    def render_code(self, cell):
        if not cell.input:
            return []
        lines = []

        if 'source' not in self.exclude_cells:
            n = self._get_prompt_number(cell)
            if self.show_prompts:
                if not self.inline_prompt:
                    lines.extend(['*In[%s]:*' % n, ''])
                else:
                    prompt = 'In[%s]: ' % n
                    input_lines = cell.input.split('\n')
                    src = (prompt + input_lines[0] + '\n' + indent(
                        '\n'.join(input_lines[1:]), nspaces=len(prompt)))
            else:
                src = cell.input
            src = highlight(src) if self.highlight_source else indent(src)
            lines.extend([src, ''])

        if 'output' not in self.exclude_cells:
            if cell.outputs and self.show_prompts and not self.inline_prompt:
                lines.extend(['*Out[%s]:*' % n, ''])
            for output in cell.outputs:
                conv_fn = self.dispatch(output.output_type)
                lines.extend(conv_fn(output))

        #lines.append('----')
        lines.append('')
        return lines
    def render_code(self, cell):
        if not cell.input:
            return []
        lines = []
        n = self._get_prompt_number(cell)
        if self.show_prompts:
            if not self.inline_prompt:
                lines.extend(["*In[%s]:*" % n, ""])
            else:
                prompt = "In[%s]: " % n
                input_lines = cell.input.split("\n")
                src = prompt + input_lines[0] + "\n" + indent("\n".join(input_lines[1:]), nspaces=len(prompt))
        else:
            src = cell.input
        src = highlight(src) if self.highlight_source else indent(src)
        lines.extend([src, ""])
        if cell.outputs and self.show_prompts and not self.inline_prompt:
            lines.extend(["*Out[%s]:*" % n, ""])
        for output in cell.outputs:
            conv_fn = self.dispatch(output.output_type)
            lines.extend(conv_fn(output))

        # lines.append('----')
        lines.append("")
        return lines
    def class_get_trait_help(cls, trait, inst=None):
        """Get the help string for a single trait.
        
        If `inst` is given, it's current trait values will be used in place of
        the class default.
        """
        assert inst is None or isinstance(inst, cls)
        lines = []
        header = "--%s.%s=<%s>" % (cls.__name__, trait.name,
                                   trait.__class__.__name__)
        lines.append(header)
        if inst is not None:
            lines.append(indent('Current: %r' % getattr(inst, trait.name), 4))
        else:
            try:
                dvr = repr(trait.get_default_value())
            except Exception:
                dvr = None  # ignore defaults we can't construct
            if dvr is not None:
                if len(dvr) > 64:
                    dvr = dvr[:61] + '...'
                lines.append(indent('Default: %s' % dvr, 4))
        if 'Enum' in trait.__class__.__name__:
            # include Enum choices
            lines.append(indent('Choices: %r' % (trait.values, )))

        help = trait.get_metadata('help')
        if help is not None:
            help = '\n'.join(wrap_paragraphs(help, 76))
            lines.append(indent(help, 4))
        return '\n'.join(lines)
Example #7
0
    def pdoc(self,obj,oname='',formatter = None):
        """Print the docstring for any object.

        Optional:
        -formatter: a function to run the docstring through for specially
        formatted docstrings.
        
        Examples
        --------
        
        In [1]: class NoInit:
           ...:     pass
        
        In [2]: class NoDoc:
           ...:     def __init__(self):
           ...:         pass
        
        In [3]: %pdoc NoDoc
        No documentation found for NoDoc
        
        # This currently fails in Python 3, because it shows the constructor
        # docstring from object.
        #In [4]: %pdoc NoInit
        #No documentation found for NoInit

        In [5]: obj = NoInit()
        
        In [6]: %pdoc obj
        No documentation found for obj

        In [5]: obj2 = NoDoc()
        
        In [6]: %pdoc obj2
        No documentation found for obj2
        """

        head = self.__head  # For convenience
        lines = []
        ds = getdoc(obj)
        if formatter:
            ds = formatter(ds)
        if ds:
            lines.append(head("Class Docstring:"))
            lines.append(indent(ds))
        if inspect.isclass(obj) and hasattr(obj, '__init__'):
            init_ds = getdoc(obj.__init__)
            if init_ds is not None:
                lines.append(head("Constructor Docstring:"))
                lines.append(indent(init_ds))
        elif isinstance(obj,object) and hasattr(obj,'__call__'):
            call_ds = getdoc(obj.__call__)
            if call_ds:
                lines.append(head("Calling Docstring:"))
                lines.append(indent(call_ds))

        if not lines:
            self.noinfo('documentation',oname)
        else:
            page.page('\n'.join(lines))
Example #8
0
    def pdoc(self, obj, oname='', formatter=None):
        """Print the docstring for any object.

        Optional:
        -formatter: a function to run the docstring through for specially
        formatted docstrings.
        
        Examples
        --------
        
        In [1]: class NoInit:
           ...:     pass
        
        In [2]: class NoDoc:
           ...:     def __init__(self):
           ...:         pass
        
        In [3]: %pdoc NoDoc
        No documentation found for NoDoc
        
        In [4]: %pdoc NoInit
        No documentation found for NoInit

        In [5]: obj = NoInit()
        
        In [6]: %pdoc obj
        No documentation found for obj

        In [5]: obj2 = NoDoc()
        
        In [6]: %pdoc obj2
        No documentation found for obj2
        """

        head = self.__head  # For convenience
        lines = []
        ds = getdoc(obj)
        if formatter:
            ds = formatter(ds)
        if ds:
            lines.append(head("Class Docstring:"))
            lines.append(indent(ds))
        if inspect.isclass(obj) and hasattr(obj, '__init__'):
            init_ds = getdoc(obj.__init__)
            if init_ds is not None:
                lines.append(head("Constructor Docstring:"))
                lines.append(indent(init_ds))
        elif (type(obj) is types.InstanceType or isinstance(obj,object)) \
                 and hasattr(obj,'__call__'):
            call_ds = getdoc(obj.__call__)
            if call_ds:
                lines.append(head("Calling Docstring:"))
                lines.append(indent(call_ds))

        if not lines:
            self.noinfo('documentation', oname)
        else:
            page.page('\n'.join(lines))
Example #9
0
    def pdoc(self, obj, oname="", formatter=None):
        """Print the docstring for any object.

        Optional:
        -formatter: a function to run the docstring through for specially
        formatted docstrings.

        Examples
        --------

        In [1]: class NoInit:
           ...:     pass

        In [2]: class NoDoc:
           ...:     def __init__(self):
           ...:         pass

        In [3]: %pdoc NoDoc
        No documentation found for NoDoc

        In [4]: %pdoc NoInit
        No documentation found for NoInit

        In [5]: obj = NoInit()

        In [6]: %pdoc obj
        No documentation found for obj

        In [5]: obj2 = NoDoc()

        In [6]: %pdoc obj2
        No documentation found for obj2
        """

        head = self.__head  # For convenience
        lines = []
        ds = getdoc(obj)
        if formatter:
            ds = formatter(ds).get("plain/text", ds)
        if ds:
            lines.append(head("Class docstring:"))
            lines.append(indent(ds))
        if inspect.isclass(obj) and hasattr(obj, "__init__"):
            init_ds = getdoc(obj.__init__)
            if init_ds is not None:
                lines.append(head("Init docstring:"))
                lines.append(indent(init_ds))
        elif hasattr(obj, "__call__"):
            call_ds = getdoc(obj.__call__)
            if call_ds:
                lines.append(head("Call docstring:"))
                lines.append(indent(call_ds))

        if not lines:
            self.noinfo("documentation", oname)
        else:
            page.page("\n".join(lines))
Example #10
0
    def pdoc(self, obj, oname='', formatter=None):
        """Print the docstring for any object.

        Optional:
        -formatter: a function to run the docstring through for specially
        formatted docstrings.

        Examples
        --------

        In [1]: class NoInit:
           ...:     pass

        In [2]: class NoDoc:
           ...:     def __init__(self):
           ...:         pass

        In [3]: %pdoc NoDoc
        No documentation found for NoDoc

        In [4]: %pdoc NoInit
        No documentation found for NoInit

        In [5]: obj = NoInit()

        In [6]: %pdoc obj
        No documentation found for obj

        In [5]: obj2 = NoDoc()

        In [6]: %pdoc obj2
        No documentation found for obj2
        """

        head = self.__head  # For convenience
        lines = []
        ds = getdoc(obj)
        if formatter:
            ds = formatter(ds).get('plain/text', ds)
        if ds:
            lines.append(head("Class docstring:"))
            lines.append(indent(ds))
        if inspect.isclass(obj) and hasattr(obj, '__init__'):
            init_ds = getdoc(obj.__init__)
            if init_ds is not None:
                lines.append(head("Init docstring:"))
                lines.append(indent(init_ds))
        elif hasattr(obj,'__call__'):
            call_ds = getdoc(obj.__call__)
            if call_ds:
                lines.append(head("Call docstring:"))
                lines.append(indent(call_ds))

        if not lines:
            self.noinfo('documentation',oname)
        else:
            page.page('\n'.join(lines))
Example #11
0
    def print_examples(self):
        """Print usage and examples.

        This usage string goes at the end of the command line help string
        and should contain examples of the application's usage.
        """
        if self.examples:
            print "Examples"
            print "--------"
            print
            print indent(dedent(self.examples.strip()))
            print
Example #12
0
 def print_flag_help(self):
     """print the flag part of the help"""
     if not self.flags:
         return
     
     print "Flags"
     print "-----"
     print self.flag_description
     print
     
     for m, (cfg,help) in self.flags.iteritems():
         print '--'+m
         print indent(help)
     print
Example #13
0
    def render_pyout(self, output):
        lines = ['<tr><td><tt>Out[<b>%s</b>]:</tt></td></tr>' % output.prompt_number, '<td>']

        # output is a dictionary like object with type as a key
        if 'latex' in output:
            lines.append("<pre>")
            lines.extend(indent(output.latex))
            lines.append("</pre>")

        if 'text' in output:
            lines.append("<pre>")
            lines.extend(indent(output.text))
            lines.append("</pre>")

        return lines
Example #14
0
def format_docstring(func):
    docstring = (func.__doc__ or "Undocumented").rstrip()
    docstring = indent(dedent(docstring))
    # Sphinx complains if indented bits have rst headings in, so strip out
    # any underlines in the docstring.
    lines = [_strip_underline(l) for l in docstring.splitlines()]
    return "\n".join(lines)
Example #15
0
def rst_directive(directive, text=''):
    """
    Makes ReST directive block and indents any text passed to it.
    """
    out = [directive, '']
    if text:
        out.extend([indent(text), ''])
    return out
Example #16
0
def rst_directive(directive, text=''):
    """
    Makes ReST directive block and indents any text passed to it.
    """
    out = [directive, '']
    if text:
        out.extend([indent(text), ''])
    return out
Example #17
0
    def render_pyout(self, output):
        lines = ['<tr><td><tt>Out[<b>%s</b>]:</tt></td></tr>' % 
                 output.prompt_number, '<td>']

        # output is a dictionary like object with type as a key
        for out_type in ('text', 'latex'):
            if out_type in output:
                lines.extend(self.in_tag('pre', indent(output[out_type])))

        return lines
Example #18
0
 def asyncio(line, cell):
     code_in_func = "async def __f():\n" + indent(cell)
     mod = ast.parse(code_in_func)
     body = mod.body[0].body
     new_mod = ast.Module([RewriteAwait().visit(n) for n in body])
     ast.fix_missing_locations(new_mod)
     #print(astpp.dump(new_mod))
     co = compile(new_mod, filename="<asyncio_magic>", mode="exec")
     ip.user_global_ns['_asyncio'] = asyncio_mod
     ip.ex(co)
Example #19
0
    def _magic_docs(self, brief=False, rest=False):
        """Return docstrings from magic functions."""
        mman = self.shell.magics_manager
        docs = mman.lsmagic_docs(brief, missing='No documentation')

        if rest:
            format_string = '**%s%s**::\n\n%s\n\n'
        else:
            format_string = '%s%s:\n%s\n'

        return ''.join(
            [format_string % (magic_escapes['line'], fname,
                              indent(dedent(fndoc)))
             for fname, fndoc in sorted(docs['line'].items())]
            +
            [format_string % (magic_escapes['cell'], fname,
                              indent(dedent(fndoc)))
             for fname, fndoc in sorted(docs['cell'].items())]
        )
Example #20
0
    def pinfo(self, obj, oname='', formatter=None, info=None, detail_level=0):
        """Show detailed information about an object.

        Optional arguments:

        - oname: name of the variable pointing to the object.

        - formatter: special formatter for docstrings (see pdoc)

        - info: a structure with some information fields which may have been
        precomputed already.

        - detail_level: if set to 1, more information is given.
        """
        info = self.info(obj,
                         oname=oname,
                         formatter=formatter,
                         info=info,
                         detail_level=detail_level)
        displayfields = []
        for title, key in self.pinfo_fields1:
            field = info[key]
            if field is not None:
                displayfields.append((title, field.rstrip()))

        # Source or docstring, depending on detail level and whether
        # source found.
        if detail_level > 0 and info['source'] is not None:
            displayfields.append(
                ("Source",
                 self.format(py3compat.unicode_to_str(info['source']))))
        elif info['docstring'] is not None:
            displayfields.append(("Docstring", info["docstring"]))

        # Constructor info for classes
        if info['isclass']:
            if info['init_definition'] or info['init_docstring']:
                displayfields.append(("Constructor information", ""))
                if info['init_definition'] is not None:
                    displayfields.append(
                        (" Definition", info['init_definition'].rstrip()))
                if info['init_docstring'] is not None:
                    displayfields.append(
                        (" Docstring", indent(info['init_docstring'])))

        # Info for objects:
        else:
            for title, key in self.pinfo_fields_obj:
                field = info[key]
                if field is not None:
                    displayfields.append((title, field.rstrip()))

        # Finally send to printer/pager:
        if displayfields:
            page.page(self._format_fields(displayfields))
Example #21
0
    def _magic_docs(self, brief=False, rest=False):
        """Return docstrings from magic functions."""
        mman = self.shell.magics_manager
        docs = mman.lsmagic_docs(brief, missing="No documentation")

        if rest:
            format_string = "**%s%s**::\n\n%s\n\n"
        else:
            format_string = "%s%s:\n%s\n"

        return "".join(
            [
                format_string % (magic_escapes["line"], fname, indent(dedent(fndoc)))
                for fname, fndoc in sorted(docs["line"].items())
            ]
            + [
                format_string % (magic_escapes["cell"], fname, indent(dedent(fndoc)))
                for fname, fndoc in sorted(docs["cell"].items())
            ]
        )
Example #22
0
    def print_flag_help(self):
        """Print the flag part of the help."""
        if not self.flags:
            return

        lines = []
        for m, (cfg, help) in self.flags.iteritems():
            lines.append('--' + m)
            lines.append(indent(dedent(help.strip())))
        # lines.append('')
        print os.linesep.join(lines)
Example #23
0
 def print_flag_help(self):
     """Print the flag part of the help."""
     if not self.flags:
         return
     
     lines = []
     for m, (cfg,help) in self.flags.iteritems():
         lines.append('--'+m)
         lines.append(indent(dedent(help.strip())))
     # lines.append('')
     print os.linesep.join(lines)
Example #24
0
    def _magic_docs(self, brief=False, rest=False):
        """Return docstrings from magic functions."""
        mman = self.shell.magics_manager
        docs = mman.lsmagic_docs(brief, missing="No documentation")

        if rest:
            format_string = "**%s%s**::\n\n%s\n\n"
        else:
            format_string = "%s%s:\n%s\n"

        return "".join(
            [
                format_string % (magic_escapes["line"], fname, indent(dedent(fndoc)))
                for fname, fndoc in sorted(docs["line"].items())
            ]
            + [
                format_string % (magic_escapes["cell"], fname, indent(dedent(fndoc)))
                for fname, fndoc in sorted(docs["cell"].items())
            ]
        )
Example #25
0
    def print_flag_help(self):
        """Print the flag part of the help."""
        if not self.flags:
            return

        lines = []
        for m, (cfg, help) in iteritems(self.flags):
            prefix = '--' if len(m) > 1 else '-'
            lines.append(prefix + m)
            lines.append(indent(dedent(help.strip())))
        # lines.append('')
        print(os.linesep.join(lines))
Example #26
0
 def class_get_trait_help(cls, trait):
     """Get the help string for a single trait."""
     lines = []
     header = "%s.%s : %s" % (cls.__name__, trait.name, trait.__class__.__name__)
     lines.append(header)
     try:
         dvr = repr(trait.get_default_value())
     except Exception:
         dvr = None # ignore defaults we can't construct
     if dvr is not None:
         if len(dvr) > 64:
             dvr = dvr[:61]+'...'
         lines.append(indent('Default: %s'%dvr, 4))
     if 'Enum' in trait.__class__.__name__:
         # include Enum choices
         lines.append(indent('Choices: %r'%(trait.values,)))
     
     help = trait.get_metadata('help')
     if help is not None:
         help = '\n'.join(wrap_paragraphs(help, 76))
         lines.append(indent(help, 4))
     return '\n'.join(lines)
Example #27
0
 def print_subcommands(self):
     """Print the subcommand part of the help."""
     if not self.subcommands:
         return
     
     lines = ["Subcommands"]
     lines.append('-'*len(lines[0]))
     for subc, (cls,help) in self.subcommands.items():
         lines.append("%s : %s"%(subc, cls))
         if help:
             lines.append(indent(dedent(help.strip())))
     lines.append('')
     print('\n'.join(lines))
Example #28
0
 def class_get_help(cls):
     """Get the help string for this class in ReST format."""
     cls_traits = cls.class_traits(config=True)
     final_help = []
     final_help.append(u'%s options' % cls.__name__)
     final_help.append(len(final_help[0])*u'-')
     for k, v in cls_traits.items():
         help = v.get_metadata('help')
         header = "%s.%s : %s" % (cls.__name__, k, v.__class__.__name__)
         final_help.append(header)
         if help is not None:
             final_help.append(indent(help))
     return '\n'.join(final_help)
Example #29
0
def closure(line, cell):
    """run the cell in a function, generating a closure
    
    avoids affecting the user's namespace
    """
    ip = get_ipython()
    func_name = "_closure_magic_f"
    block = '\n'.join(
        ["def %s():" % func_name,
         indent(cell),
         "%s()" % func_name])
    ip.run_cell(block)
    ip.user_ns.pop(func_name, None)
Example #30
0
    def print_subcommands(self):
        """Print the subcommand part of the help."""
        if not self.subcommands:
            return

        lines = ["Subcommands"]
        lines.append('-' * len(lines[0]))
        for subc, (cls, help) in self.subcommands.iteritems():
            lines.append("%s : %s" % (subc, cls))
            if help:
                lines.append(indent(dedent(help.strip())))
        lines.append('')
        print '\n'.join(lines)
Example #31
0
    def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0):
        """Show detailed information about an object.

        Optional arguments:
        
        - oname: name of the variable pointing to the object.

        - formatter: special formatter for docstrings (see pdoc)

        - info: a structure with some information fields which may have been
        precomputed already.

        - detail_level: if set to 1, more information is given.
        """
        info = self.info(obj, oname=oname, formatter=formatter,
                            info=info, detail_level=detail_level)
        displayfields = []
        for title, key in self.pinfo_fields1:
            field = info[key]
            if field is not None:
                displayfields.append((title, field.rstrip()))
        
        # Source or docstring, depending on detail level and whether
        # source found.
        if detail_level > 0 and info['source'] is not None:
            displayfields.append(("Source", info['source']))
        elif info['docstring'] is not None:
            displayfields.append(("Docstring", info["docstring"]))
        
        # Constructor info for classes
        if info['isclass']:
            if info['init_definition'] or info['init_docstring']:
                displayfields.append(("Constructor information", ""))
                if info['init_definition'] is not None:
                    displayfields.append((" Definition",
                                    info['init_definition'].rstrip()))
                if info['init_docstring'] is not None:
                    displayfields.append((" Docstring",
                                        indent(info['init_docstring'])))
                                        
        # Info for objects:
        else:
            for title, key in self.pinfo_fields_obj:
                field = info[key]
                if field is not None:
                    displayfields.append((title, field.rstrip()))
        
        # Finally send to printer/pager:
        if displayfields:
            page.page(self._format_fields(displayfields))
Example #32
0
    def render_pyout(self, output, prompt_number=None):
        lines = []

        # output is a dictionary like object with type as a key
        if 'latex' in output:
            pass

        if 'text' in output:
            lines.extend(['<pre>',
                          '*Out[%s]:*' % output.prompt_number, '',
                          indent(output.text),
                          '</pre>'])
        lines.append('')
        return lines
Example #33
0
def closure(line, cell):
    """run the cell in a function, generating a closure
    
    avoids affecting the user's namespace
    """
    ip = get_ipython()
    func_name = "_closure_magic_f"
    block = '\n'.join([
        "def %s():" % func_name,
        indent(cell),
        "%s()" % func_name
    ])
    ip.run_cell(block)
    ip.user_ns.pop(func_name, None)
Example #34
0
    def class_get_trait_help(cls, trait):
        """Get the help string for a single trait."""
        lines = []
        header = "--%s.%s=<%s>" % (cls.__name__, trait.name,
                                   trait.__class__.__name__)
        lines.append(header)
        try:
            dvr = repr(trait.get_default_value())
        except Exception:
            dvr = None  # ignore defaults we can't construct
        if dvr is not None:
            if len(dvr) > 64:
                dvr = dvr[:61] + '...'
            lines.append(indent('Default: %s' % dvr, 4))
        if 'Enum' in trait.__class__.__name__:
            # include Enum choices
            lines.append(indent('Choices: %r' % (trait.values, )))

        help = trait.get_metadata('help')
        if help is not None:
            help = '\n'.join(wrap_paragraphs(help, 76))
            lines.append(indent(help, 4))
        return '\n'.join(lines)
Example #35
0
    def print_subcommands(self):
        """Print the list of subcommands under this application"""

        if not self.subcommands:
            return

        lines = ["Subcommands"]
        lines.append('-' * len(lines[0]))
        for subc, (cls, help) in self.subcommands.iteritems():
            lines.append(subc)
            if help:
                lines.append(indent(dedent(help.strip())))
        lines.append('')

        print(os.linesep.join(lines))
Example #36
0
    def render_pyout(self, output):
        lines = []

        ## if 'text' in output:
        ##     lines.extend(['*Out[%s]:*' % output.prompt_number, ''])

        # output is a dictionary like object with type as a key
        if 'latex' in output:
            pass

        if 'text' in output:
            lines.extend([self.comment(indent(output.text)), ''])

        lines.append('')
        return lines
Example #37
0
 def print_alias_help(self):
     """print the alias part of the help"""
     if not self.aliases:
         return
         
     print "Aliases"
     print "-------"
     print self.alias_description
     print
     
     classdict = {}
     for c in self.classes:
         classdict[c.__name__] = c
     
     for alias, longname in self.aliases.iteritems():
         classname, traitname = longname.split('.',1)
         cls = classdict[classname]
         
         trait = cls.class_traits(config=True)[traitname]
         help = trait.get_metadata('help')
         print alias, "(%s)"%longname, ':', trait.__class__.__name__
         if help:
             print indent(help)
     print
Example #38
0
    def print_subcommands(self):
        """Print the list of subcommands under this application"""

        if not self.subcommands:
            return

        lines = ["Subcommands"]
        lines.append("-" * len(lines[0]))
        for subc, (cls, help) in self.subcommands.iteritems():
            lines.append(subc)
            if help:
                lines.append(indent(dedent(help.strip())))
        lines.append("")

        print(os.linesep.join(lines))
Example #39
0
    def render_pyout(self, output):
        lines = []

        ## if 'text' in output:
        ##     lines.extend(['*Out[%s]:*' % output.prompt_number, ''])

        # output is a dictionary like object with type as a key
        if "latex" in output:
            pass

        if "text" in output:
            lines.extend(["<pre>", indent(output.text), "</pre>"])

        lines.append("")
        return lines
Example #40
0
    def render_pyout(self, output):
        lines = []

        ## if 'text' in output:
        ##     lines.extend(['*Out[%s]:*' % self._get_prompt_number(cell), ''])

        # output is a dictionary like object with type as a key
        if 'latex' in output:
            pass

        if 'text' in output:
            lines.extend(['<pre>', indent(output.text), '</pre>'])

        lines.append('')
        return lines
Example #41
0
    def render_pyout(self, output):
        lines = []

        ## if 'text' in output:
        ##     lines.extend(['*Out[%s]:*' % self._get_prompt_number(cell), ''])

        # output is a dictionary like object with type as a key
        if 'latex' in output:
            pass

        if 'text' in output:
            lines.extend(['<pre>', indent(output.text), '</pre>'])

        lines.append('')
        return lines
Example #42
0
    def print_flag_help(self):
        """Print the flag part of the help."""
        if not self.flags:
            return

        lines = ['Flags']
        lines.append('-' * len(lines[0]))
        lines.append('')
        for p in wrap_paragraphs(self.flag_description):
            lines.append(p)
            lines.append('')

        for m, (cfg, help) in self.flags.iteritems():
            lines.append('--' + m)
            lines.append(indent(dedent(help.strip())))
        lines.append('')
        print '\n'.join(lines)
Example #43
0
    def print_subcommands(self):
        """Print the subcommand part of the help."""
        if not self.subcommands:
            return

        lines = ["Subcommands"]
        lines.append('-' * len(lines[0]))
        lines.append('')
        for p in wrap_paragraphs(self.subcommand_description):
            lines.append(p)
            lines.append('')
        for subc, (cls, help) in iteritems(self.subcommands):
            lines.append(subc)
            if help:
                lines.append(indent(dedent(help.strip())))
        lines.append('')
        print(os.linesep.join(lines))
Example #44
0
def functionize(line):
    shell = get_ipython()
    splits = line.split(' ', 1)
    range_str = splits[0]
    args = splits[1] if len(splits) > 1 else ''

    ranges = parse_ranges(range_str)
    get_range = shell.history_manager.get_range

    blocks = ["def cell_function(%s):" % args]
    for start, stop in ranges:
        cursor = get_range(0, start, stop)
        for session_id, cell_id, code in cursor:
            blocks.append(indent(code))

    code = '\n'.join(blocks)
    shell.set_next_input(code)
Example #45
0
 def print_flag_help(self):
     """Print the flag part of the help."""
     if not self.flags:
         return
     
     lines = ['Flags']
     lines.append('-'*len(lines[0]))
     lines.append('')
     for p in wrap_paragraphs(self.flag_description):
         lines.append(p)
         lines.append('')
     
     for m, (cfg,help) in self.flags.items():
         lines.append('--'+m)
         lines.append(indent(dedent(help.strip())))
     lines.append('')
     print('\n'.join(lines))
Example #46
0
def functionize(line):
    shell = get_ipython()
    splits = line.split(' ', 1)
    range_str = splits[0]
    args = splits[1] if len(splits) > 1 else ''
    
    ranges = parse_ranges(range_str)
    get_range = shell.history_manager.get_range
    
    blocks = ["def cell_function(%s):" % args]
    for start, stop in ranges:
        cursor = get_range(0, start, stop)
        for session_id, cell_id, code in cursor:
            blocks.append(indent(code))
    
    code = '\n'.join(blocks)
    shell.set_next_input(code)
Example #47
0
def document_config_options(classes):
    lines = []
    for cls in classes:
        classname = cls.__name__
        for k, trait in sorted(cls.class_traits(config=True).items()):
            ttype = trait.__class__.__name__

            termline = classname + '.' + trait.name

            # Choices or type
            if 'Enum' in ttype:
                # include Enum choices
                termline += ' : ' + '|'.join(repr(x) for x in trait.values)
            else:
                termline += ' : ' + ttype
            lines.append(termline)

            # Default value
            try:
                dv = trait.get_default_value()
                dvr = repr(dv)
            except Exception:
                dvr = dv = None  # ignore defaults we can't construct
            if (dv is not None) and (dvr is not None):
                if len(dvr) > 64:
                    dvr = dvr[:61] + '...'
                # Double up backslashes, so they get to the rendered docs
                dvr = dvr.replace('\\n', '\\\\n')
                lines.append('    Default: ' + dvr)
                lines.append('')

            help = trait.get_metadata('help')
            if help is not None:
                help = '\n\n'.join(wrap_paragraphs(help, 76))
                lines.append(indent(help, 4))
            else:
                lines.append('    No description')

            lines.append('')
    return '\n'.join(lines)
Example #48
0
 def render_display_format_javascript(self, output):
     return ['JavaScript:', indent(output.javascript)]
Example #49
0
 def render_display_format_text(self, output):
     return [indent(output.text)]
Example #50
0
 def render_display_format_latex(self, output):
     return ['LaTeX::', indent(output.latex)]
    def async_(self, line, cell):
        expr = 'async def __f():\n{cell}'.format(cell=indent(cell))

        self._exec(expr)
    def await_(self, line):
        expr = 'async def __f(): await {line}'.format(line=indent(line))

        self._exec(expr)
Example #53
0
 def render_display_format_json(self, output):
     return ['JSON:', indent(output.json)]
Example #54
0
 def render_raw(self, cell):
     if self.raw_as_verbatim:
         return [indent(cell.source), '']
     else:
         return [cell.source, '']