Georg Brandl avatar Georg Brandl committed af21bf1 Merge

Merged in marklodato/sphinx (pull request #4)

Comments (0)

Files changed (6)

doc/markup/code.rst

 
       Some more Ruby code.
 
+Additionally, an ``emphasize-lines`` option can be given to have Pygments
+emphasize particular lines::
+
+    .. code-block:: python
+       :emphasize-lines: 3,5
+
+       def some_function():
+           interesting = False
+           print 'This line is highlighted.'
+           print 'This one is not...'
+           print '...but this one is.'
+
 
 Includes
 ^^^^^^^^
    desired tab width.
 
    The directive also supports the ``linenos`` flag option to switch on line
-   numbers, and a ``language`` option to select a language different from the
-   current file's standard language.  Example with options::
+   numbers, the ``emphasize-lines`` option to emphasize particular lines, and
+   a ``language`` option to select a language different from the current
+   file's standard language.  Example with options::
 
       .. literalinclude:: example.rb
          :language: ruby
+         :emphasize-lines: 12,15-18
          :linenos:
 
    Include files are assumed to be encoded in the :confval:`source_encoding`.

sphinx/directives/code.py

     final_argument_whitespace = False
     option_spec = {
         'linenos': directives.flag,
+        'emphasize-lines': directives.unchanged_required,
     }
 
     def run(self):
         code = u'\n'.join(self.content)
+
+        linespec = self.options.get('emphasize-lines')
+        if linespec:
+            try:
+                nlines = len(self.content)
+                hl_lines = [x+1 for x in parselinenos(linespec, nlines)]
+            except ValueError, err:
+                document = self.state.document
+                return [document.reporter.warning(str(err), line=self.lineno)]
+        else:
+            hl_lines = None
+
         literal = nodes.literal_block(code, code)
         literal['language'] = self.arguments[0]
         literal['linenos'] = 'linenos' in self.options
+        if hl_lines is not None:
+            literal['highlight_args'] = {'hl_lines': hl_lines}
         literal.line = self.lineno
         return [literal]
 
         'end-before': directives.unchanged_required,
         'prepend': directives.unchanged_required,
         'append': directives.unchanged_required,
+        'emphasize-lines': directives.unchanged_required,
     }
 
     def run(self):
                     'Line spec %r: no lines pulled from include file %r' %
                     (linespec, filename), line=self.lineno)]
 
+        linespec = self.options.get('emphasize-lines')
+        if linespec:
+            try:
+                hl_lines = [x+1 for x in parselinenos(linespec, len(lines))]
+            except ValueError, err:
+                return [document.reporter.warning(str(err), line=self.lineno)]
+        else:
+            hl_lines = None
+
         startafter = self.options.get('start-after')
         endbefore  = self.options.get('end-before')
         prepend    = self.options.get('prepend')
             retnode['language'] = self.options['language']
         if 'linenos' in self.options:
             retnode['linenos'] = True
+        if hl_lines is not None:
+            retnode['highlight_args'] = {'hl_lines': hl_lines}
         env.note_dependency(rel_filename)
         return [retnode]
 

sphinx/ext/viewcode.py

         # construct a page name for the highlighted source
         pagename = '_modules/' + modname.replace('.', '/')
         # highlight the source using the builder's highlighter
-        highlighted = highlighter.highlight_block(code, 'python', False)
+        highlighted = highlighter.highlight_block(code, 'python', linenos=False)
         # split the code into lines
         lines = highlighted.splitlines()
         # split off wrap markup from the first line of the actual code

sphinx/highlighting.py

         else:
             style = get_style_by_name(stylename)
         self.trim_doctest_flags = trim_doctest_flags
+        self.formatter_args = {'style' : style}
         if dest == 'html':
-            self.fmter = {False: self.html_formatter(style=style),
-                          True: self.html_formatter(style=style, linenos=True)}
+            self.formatter = self.html_formatter
         else:
-            self.fmter = {False: self.latex_formatter(style=style,
-                                                      commandprefix='PYG'),
-                          True: self.latex_formatter(style=style, linenos=True,
-                                                     commandprefix='PYG')}
+            self.formatter = self.latex_formatter
+            self.formatter_args['commandprefix'] = 'PYG'
 
     def unhighlighted(self, source):
         if self.dest == 'html':
         else:
             return True
 
-    def highlight_block(self, source, lang, linenos=False, warn=None):
+    def highlight_block(self, source, lang, warn=None, **kwargs):
         if not isinstance(source, unicode):
             source = source.decode()
         if not pygments:
 
         # highlight via Pygments
         try:
+            formatter = self.get_formatter(**kwargs)
+            hlsource = highlight(source, lexer, formatter)
             if self.dest == 'html':
-                return highlight(source, lexer, self.fmter[bool(linenos)])
+                return hlsource
+            elif hlsource.startswith(r'\begin{Verbatim}[commandchars=\\\{\}'):
+                # Pygments >= 1.2
+                return hlsource.translate(tex_hl_escape_map_new)
             else:
-                hlsource = highlight(source, lexer, self.fmter[bool(linenos)])
-                if hlsource.startswith(r'\begin{Verbatim}[commandchars=\\\{\}'):
-                    # Pygments >= 1.2
-                    return hlsource.translate(tex_hl_escape_map_new)
                 return hlsource.translate(tex_hl_escape_map_old)
         except ErrorToken:
             # this is most probably not the selected language,
             # so let it pass unhighlighted
             return self.unhighlighted(source)
 
+    def get_formatter(self, **kwargs_orig):
+        kwargs = self.formatter_args.copy()
+        kwargs.update(kwargs_orig)
+        return self.formatter(**kwargs)
+
     def get_stylesheet(self):
         if not pygments:
             if self.dest == 'latex':
                 return _LATEX_STYLES
             # no HTML styles needed
             return ''
+        formatter = self.get_formatter()
         if self.dest == 'html':
-            return self.fmter[0].get_style_defs('.highlight')
+            return formatter.get_style_defs('.highlight')
         else:
-            styledefs = self.fmter[0].get_style_defs()
+            styledefs = formatter.get_style_defs()
             # workaround for Pygments < 0.12
             if styledefs.startswith('\\newcommand\\at{@}'):
                 styledefs += _LATEX_STYLES

sphinx/writers/html.py

             lang = node['language']
         if node.has_key('linenos'):
             linenos = node['linenos']
+        highlight_args = node.get('highlight_args', {})
         def warner(msg):
             self.builder.warn(msg, (self.builder.current_docname, node.line))
         highlighted = self.highlighter.highlight_block(
-            node.rawsource, lang, linenos, warn=warner)
+            node.rawsource, lang, warn=warner, linenos=linenos,
+            **highlight_args)
         starttag = self.starttag(node, 'div', suffix='',
                                  CLASS='highlight-%s' % lang)
         self.body.append(starttag + highlighted + '</div>\n')

sphinx/writers/latex.py

             lang = node['language']
         if 'linenos' in node:
             linenos = node['linenos']
+        highlight_args = node.get('highlight_args', {})
         def warner(msg):
             self.builder.warn(msg, (self.curfilestack[-1], node.line))
-        hlcode = self.highlighter.highlight_block(code, lang, linenos,
-                                                  warn=warner)
+        hlcode = self.highlighter.highlight_block(code, lang, warn=warner,
+                linenos=linenos, **highlight_args)
         # workaround for Unicode issue
         hlcode = hlcode.replace(u'€', u'@texteuro[]')
         # must use original Verbatim environment and "tabular" environment
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.