Exemple #1
0
 def update_image(self, s, keywords):
     '''Update an image in the vr pane.'''
     pc = self
     if not s.strip():
         return
     lines = g.splitLines(s) or []
     fn = lines and lines[0].strip()
     if not fn:
         return
     w = pc.ensure_text_widget()
     ok, path = pc.get_fn(fn, '@image')
     if not ok:
         w.setPlainText('@image: file not found: %s' % (path))
         return
     path = path.replace('\\', '/')
     template = '''\
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 <head></head>
 <body bgcolor="#fffbdc">
 <img src="%s">
 </body>
 </html>
 ''' % (path)
     # Only works in Python 3.x.
     template = g.adjustTripleString(template, pc.c.tab_width).strip() # Sensitive to leading blank lines.
     # template = g.toUnicode(template)
     pc.show()
     w.setReadOnly(False)
     w.setHtml(template)
     w.setReadOnly(True)
Exemple #2
0
    def update_svg (self,s,keywords):

        pc = self
        
        if pc.must_change_widget(pc.svg_class):
            w = pc.svg_class()
            pc.embed_widget(w)
            assert (w == pc.w)
        else:
            w = pc.w
        
        if s.strip().startswith('<'):
            # Assume it is the svg (xml) source.
            s = g.adjustTripleString(s,pc.c.tab_width).strip() # Sensitive to leading blank lines.
            s = g.toEncodedString(s)
            pc.show()
            w.load(QtCore.QByteArray(s))
            w.show()
        else:
            # Get a filename from the headline or body text.
            ok,path = pc.get_fn(s,'@svg')
            if ok:
                pc.show()
                w.load(path)
                w.show()
Exemple #3
0
 def default_metadata(self):
     '''Return the top-level metadata to use if there is no {prefix} node.'''
     s = '''\
 "metadata": {
  "kernelspec": {
   "display_name": "Python %(version)s",
   "language": "python",
   "name": "python%(version)s"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": %(version)s
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "%(long_version)s"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0'''
     n1, n2 = sys.version_info[0], sys.version_info[1]
     s = s % {
        'version': n1,
        'long_version': '%s.%s' % (n1, n2),
     }
     return g.adjustTripleString(s, 1)
Exemple #4
0
 def default_metadata(self):
     '''Return the top-level metadata to use if there is no {prefix} node.'''
     s = '''\
 "metadata": {
  "kernelspec": {
   "display_name": "Python %(version)s",
   "language": "python",
   "name": "python%(version)s"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": %(version)s
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "%(long_version)s"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0'''
     n1, n2 = sys.version_info[0], sys.version_info[1]
     s = s % {
         'version': n1,
         'long_version': '%s.%s' % (n1, n2),
     }
     return g.adjustTripleString(s, 1)
Exemple #5
0
    def update_svg (self,s,keywords):

        pc = self
        
        if pc.must_change_widget(pc.svg_class):
            w = pc.svg_class()
            pc.embed_widget(w)
            assert (w == pc.w)
        else:
            w = pc.w
        
        if s.strip().startswith('<'):
            # Assume it is the svg (xml) source.
            s = g.adjustTripleString(s,pc.c.tab_width).strip() # Sensitive to leading blank lines.
            s = g.toEncodedString(s)
            pc.show()
            w.load(QtCore.QByteArray(s))
            w.show()
        else:
            # Get a filename from the headline or body text.
            ok,path = pc.get_fn(s,'@svg')
            if ok:
                pc.show()
                w.load(path)
                w.show()
Exemple #6
0
    def update_image (self,s,keywords):
        '''Update an image in the vr pane.'''
        pc = self
        if not s.strip():
            return
        lines = g.splitLines(s) or []
        fn = lines and lines[0].strip()
        if not fn:
            return
        w = pc.ensure_text_widget()
        ok,path = pc.get_fn(fn,'@image')
        if not ok:
            w.setPlainText('@image: file not found: %s' % (fn))
            return
        path = fn.replace('\\','/')
        template = '''\
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head></head>
    <body bgcolor="#fffbdc">
    <img src="%s">
    </body>
    </html>
    ''' % (path)

        # Only works in Python 3.x.
        template = g.adjustTripleString(template,pc.c.tab_width).strip() # Sensitive to leading blank lines.
        # template = g.toUnicode(template)
        pc.show()
        w.setReadOnly(False)
        w.setHtml(template)
        w.setReadOnly(True)
Exemple #7
0
 def clean_all_nodes(self, parent):
     """Remove common leading whitespace from all nodes."""
     c = self.c
     for p in parent.subtree():
         lines = self.get_lines(p)
         s = ''.join(lines)
         s = g.adjustTripleString(s, tab_width=c.tab_width)
         self.set_lines(p, g.splitLines(s))
Exemple #8
0
 def __init__ (self,rc,s):
     ropeResources.File.__init__(self,rc,'<string-resource')
     for ivar in ('c','rc','s'):
         assert not hasattr(self,ivar),ivar
     self.c = rc.c
     self.rc = rc
     s = g.toUnicode(s, encoding='utf-8',reportErrors=True)
     self.s = g.adjustTripleString(s,self.c.tab_width)
Exemple #9
0
    def warning_message(self):
        '''Return the warning message.'''
        c = self.c
        s = '''\
    Loading big text (%s characters, limit is %s characters)

    Beware of a Qt bug: You will **lose data** if you change the text
    before it is fully loaded (before the scrollbar stops moving).
    '''
        s = s.rstrip() % (len(self.s),c.max_pre_loaded_body_chars)
        return g.adjustTripleString(s,c.tab_width)
Exemple #10
0
    def warning_message(self):
        '''Return the warning message.'''
        c = self.c
        s = '''\
    Loading big text (%s characters, limit is %s characters)

    Beware of a Qt bug: You will **lose data** if you change the text
    before it is fully loaded (before the scrollbar stops moving).

    To disable these buttons set @int max-pre-loaded-body-chars = 0
    '''
        s = s.rstrip() % (len(self.s), c.max_pre_loaded_body_chars)
        return g.adjustTripleString(s, c.tab_width)
Exemple #11
0
    def warning_message(self):
        '''Return the warning message.'''
        c = self.c
        s = '''\
    Loading big text: %s characters. Limit is %s.

    Beware of a Qt bug: You will **lose data** if you change the text
    before it is fully loaded (before the scrollbar stops moving).

    To disable these buttons set @int max-pre-loaded-body-chars = 0
    '''
        s = s.rstrip() % (len(self.s), c.max_pre_loaded_body_chars)
        return g.adjustTripleString(s, c.tab_width)
Exemple #12
0
 def create_latex_html(self, s):
     '''Create an html page embedding the latex code s.'''
     trace = False and not g.unitTesting
     c = self.c
     # pylint: disable=deprecated-method
     try:
         import html
         escape = html.escape
     except AttributeError:
         import cgi
         escape = cgi.escape
     html_s = escape(s)
     template = latex_template % (html_s)
     template = g.adjustTripleString(template, c.tab_width).strip()
     if trace:
         g.trace()
         g.printList(g.splitLines(template))
     return template
Exemple #13
0
    def test_get_trailing_comments(self):

        table = (
            # Test 1
            ("""\
    head
    // tail""", 1),

            # Test 2
            ("""\
    head
    /* comment 1
     * comment 2
     */""", 3),

            # Test 3
            ("""\
    head
    /* comment 1
     * comment 2
     */
    tail""", 0),  # no tail

            # Test 4
            ("""\
    head
    // comment
    tail""", 0),  # no tail
        )  # End table.
        for s, expected_length in table:
            x = JS_Importer(None)
            s = g.adjustTripleString(s, -4)
            lines = g.splitLines(s)
            head, tail = x.get_trailing_comments(lines)
            expected_lines = lines[
                -expected_length:] if expected_length else []
            assert tail == expected_lines, (repr(tail), repr(expected_lines))
Exemple #14
0
 def update_image(self, s, keywords):
     '''Update an image in the vr pane.'''
     pc = self
     if not s.strip():
         return
     lines = g.splitLines(s) or []
     fn = lines and lines[0].strip()
     if not fn:
         return
     w = pc.ensure_text_widget()
     ok, path = pc.get_fn(fn, '@image')
     if not ok:
         w.setPlainText('@image: file not found: %s' % (path))
         return
     path = path.replace('\\', '/')
     template = image_template % (path)
     # Only works in Python 3.x.
     template = g.adjustTripleString(template, pc.c.tab_width).strip()
     # Sensitive to leading blank lines.
     # template = g.toUnicode(template)
     pc.show()
     w.setReadOnly(False)
     w.setHtml(template)
     w.setReadOnly(True)
Exemple #15
0
def make_tips(c):
    '''
    A script to make entries in the global tips array.
    
    Each printed entry has the form:
        
        UserTip(
            n=anInt
            tags=[list of tags],
            title=aString,
            text="""
            
            aString
            
            """)
        
    After running this script, copy the result from the console to the
    <define tips> section of leoTips.py.
    '''
    import requests
    url = 'https://api.github.com/repos/leo-editor/leo-editor/issues?labels=Tip&state='
    
    def get_tips(data):
        """get_tips - get tips from GitHub issues
        :param dict data: GitHub API issues list
        :return: list of Tips
        """
        tips = []
        for issue in data:
            body, n, title = issue['body'], issue['number'], issue['title']
            lines = g.splitLines(body)
            for i, s in enumerate(lines):
                if s.strip().lower().startswith('tags:'):
                    lines = lines[:i] + lines[i+1:]
                    text = ''.join(lines).strip()
                    s = s.strip().rstrip('.').strip()
                    s = s[len('tags:'):].strip()
                    tags = [z.strip() for z in s.split(',')]
                    break
            else:
                tags = []
                text = body.strip()
            tips.append(
                UserTip(
                    n=n,
                    tags=tags,
                    text=text.strip(),
                    title=title.strip(),
                ))
        return tips
    
    g.cls()
    template = '''\
UserTip(
    n=%s,
    tags=%s,
    title="%s",
    text="""\
    
%s

"""),
'''
    template = g.adjustTripleString(template, c.tab_width)
    for kind in ('open',): # 'closed':
        data = requests.get(url+kind).json()
        for tip in get_tips(data):
            tags = ["%s" % (z) for z in tip.tags or []]
            title = tip.title.lstrip('Tip:').lstrip('tip:').strip()
            print(template % (tip.n, tags, title, tip.text))
Exemple #16
0
def make_tips(c):
    """
    A script to make entries in the global tips array.
    
    Each printed entry has the form:
        
        UserTip(
            n=anInt
            tags=[list of tags],
            title=aString,
            text='''
            
            aString
            
            ''')
        
    After running this script, copy the result from the console to the
    <define tips> section of leoTips.py.
    """
    import requests
    url = 'https://api.github.com/repos/leo-editor/leo-editor/issues?labels=Tip&state='

    def get_tips(data):
        """get_tips - get tips from GitHub issues
        :param dict data: GitHub API issues list
        :return: list of Tips
        """
        tips = []
        for issue in data:
            body, n, title = issue['body'], issue['number'], issue['title']
            lines = g.splitLines(body)
            for i, s in enumerate(lines):
                if s.strip().lower().startswith('tags:'):
                    lines = lines[:i] + lines[i + 1:]
                    text = ''.join(lines).strip()
                    s = s.strip().rstrip('.').strip()
                    s = s[len('tags:'):].strip()
                    tags = [z.strip() for z in s.split(',')]
                    break
            else:
                tags = []
                text = body.strip()
            tips.append(
                UserTip(
                    n=n,
                    tags=tags,
                    text=text.strip(),
                    title=title.strip(),
                ))
        return tips

    g.cls()
    template = '''\
UserTip(
    n=%s,
    tags=%s,
    title="%s",
    text="""\
    
%s

"""),
'''
    template = g.adjustTripleString(template, c.tab_width)
    for kind in ('open', ):  # 'closed':
        data = requests.get(url + kind).json()
        for tip in get_tips(data):
            tags = [f"{z}" for z in tip.tags or []]
            title = tip.title.lstrip('Tip:').lstrip('tip:').strip()
            print(template % (tip.n, tags, title, tip.text))
Exemple #17
0
    def helpForCommandFinisher(self, commandName):
        c, s = self.c, None
        if commandName and commandName.startswith('help-for-'):
            # Execute the command itself.
            c.k.simulateCommand(commandName)
        else:
            if commandName:
                bindings = self.getBindingsForCommand(commandName)
                func = c.commandsDict.get(commandName)
                s = g.getDocStringForFunction(func)
                if s:
                    s = self.replaceBindingPatterns(s)
                else:
                    s = 'no docstring available'
                # Create the title.
                s2 = '%s (%s)' % (commandName, bindings) if bindings else commandName
                underline = '+' * len(s2)
                title = '%s\n%s\n\n' % (s2, underline)
                if 1: # 2015/03/24
                    s = title + g.adjustTripleString(s, c.tab_width)
                else:
                    # Fixes bug 618570:
                    s = title + ''.join([
                        line.lstrip() if line.strip() else '\n'
                            for line in g.splitLines(s)])
            else:
                #@+<< set s to about help-for-command >>
                #@+node:ekr.20150514063305.384: *4* << set s to about help-for-command >>
                s = '''\

                ++++++++++++++++++++++++
                About Leo's help command
                ++++++++++++++++++++++++

                Invoke Leo's help-for-command as follows::

                    <F1>
                    <Alt-X>help-for-command<return>

                Next, type the name of one of Leo's commands.
                You can use tab completion.  Examples::

                    <F1><tab>           shows all commands.
                    <F1>help-for<tab>   shows all help-for- commands.

                Here are the help-for commands::

                    help-for-abbreviations
                    help-for-autocompletion
                    help-for-bindings
                    help-for-command
                    help-for-debugging-commands
                    help-for-dynamic-abbreviations
                    help-for-find-commands
                    help-for-minibuffer
                    help-for-python
                    help-for-regular-expressions

                '''
                #@-<< set s to about help-for-command >>
            c.putHelpFor(s) # calls g.adjustTripleString.
Exemple #18
0
    def helpForCommandFinisher(self, commandName):
        c, s = self.c, None
        if commandName and commandName.startswith('help-for-'):
            # Execute the command itself.
            c.k.simulateCommand(commandName)
        else:
            if commandName:
                bindings = self.getBindingsForCommand(commandName)
                func = c.commandsDict.get(commandName)
                s = g.getDocStringForFunction(func)
                if s:
                    s = self.replaceBindingPatterns(s)
                else:
                    s = 'no docstring available'
                # Create the title.
                s2 = '%s (%s)' % (commandName,
                                  bindings) if bindings else commandName
                underline = '+' * len(s2)
                title = '%s\n%s\n\n' % (s2, underline)
                if 1:  # 2015/03/24
                    s = title + g.adjustTripleString(s, c.tab_width)
                else:
                    # Fixes bug 618570:
                    s = title + ''.join([
                        line.lstrip() if line.strip() else '\n'
                        for line in g.splitLines(s)
                    ])
            else:
                #@+<< set s to about help-for-command >>
                #@+node:ekr.20150514063305.384: *4* << set s to about help-for-command >>
                s = '''\

                ++++++++++++++++++++++++
                About Leo's help command
                ++++++++++++++++++++++++

                Invoke Leo's help-for-command as follows::

                    <F1>
                    <Alt-X>help-for-command<return>

                Next, type the name of one of Leo's commands.
                You can use tab completion.  Examples::

                    <F1><tab>           shows all commands.
                    <F1>help-for<tab>   shows all help-for- commands.

                Here are the help-for commands::

                    help-for-abbreviations
                    help-for-autocompletion
                    help-for-bindings
                    help-for-command
                    help-for-debugging-commands
                    help-for-dynamic-abbreviations
                    help-for-find-commands
                    help-for-minibuffer
                    help-for-python
                    help-for-regular-expressions

                '''
                #@-<< set s to about help-for-command >>
            c.putHelpFor(s)  # calls g.adjustTripleString.
Exemple #19
0
    def test_1(self):
        #@+<< define expected_s >>
        #@+node:ekr.20210327092210.1: *4* << define expected_s >>
        expected_s = '''\
        .. rst3: filename: @rst test.html

        .. _http-node-marker-1:

        #####
        Title
        #####

        This is test.html

        .. _http-node-marker-2:

        section
        +++++++

        #@+at This is a doc part
        # it has two lines.
        #@@c
        This is the body of the section.

        '''
        #@-<< define expected_s >>
        c = self.c
        rc = c.rstCommands
        root = c.rootPosition().insertAfter()
        root.h = fn = '@rst test.html'
        #@+<< define root_b >>
        #@+node:ekr.20210327092818.1: *4* << define root_b >>
        root_b = '''\
        #####
        Title
        #####

        This is test.html
        '''
        #@-<< define root_b >>
        root.b = g.adjustTripleString(root_b, -4)
        child = root.insertAsLastChild()
        child.h = 'section'
        #@+<< define child_b >>
        #@+node:ekr.20210327093238.1: *4* << define child_b >>
        child_b = '''\
        #@+at This is a doc part
        # it has two lines.
        #@@c
        This is the body of the section.
        '''
        #@-<< define child_b >>
        child.b = g.adjustTripleString(child_b, -4)
        expected_source = g.adjustTripleString(expected_s, -4)
        #
        # Compute the result.
        rc.nodeNumber = 0
        rc.http_server_support = True  # Override setting for testing.
        source = rc.write_rst_tree(root, fn)
        html = rc.writeToDocutils(root, source, ext='.html')
        #
        # Tests...
        # Don't bother testing the html. It will depend on docutils.
        self.assertEqual(expected_source, source, msg='expected_source != source')
        assert html and html.startswith('<?xml') and html.strip().endswith('</html>')