Skip to content

Commit c227e89

Browse files
committed
Add source link to listing directive
1 parent 8eafc13 commit c227e89

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

nikola/plugins/compile/rest/listing.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,7 @@ def set_site(self, site):
136136
# leaving these to make the code directive work with
137137
# docutils < 0.9
138138
CodeBlock.site = site
139+
Listing.site = site
139140
directives.register_directive('code', CodeBlock)
140141
directives.register_directive('code-block', CodeBlock)
141142
directives.register_directive('sourcecode', CodeBlock)
@@ -189,8 +190,11 @@ def run(self):
189190
self.content = fileobject.read().splitlines()
190191
self.state.document.settings.record_dependencies.add(fpath)
191192
target = urlunsplit(("link", 'listing', fpath.replace('\\', '/'), '', ''))
193+
src_target = urlunsplit(("link", 'listing-source', fpath.replace('\\', '/'), '', ''))
194+
src_label = self.site.MESSAGES('Source')
192195
generated_nodes = (
193-
[core.publish_doctree('`{0} <{1}>`_'.format(_fname, target))[0]])
196+
[core.publish_doctree('`{0} <{1}>`_ `({2}) <{3}>`_' .format(
197+
_fname, target, src_label, src_target))[0]])
194198
generated_nodes += self.get_code_from_file(fileobject)
195199
return generated_nodes
196200

nikola/plugins/task/listings.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ def register_output_name(self, input_folder, rel_name, rel_output_name):
5454
def set_site(self, site):
5555
"""Set Nikola site."""
5656
site.register_path_handler('listing', self.listing_path)
57+
site.register_path_handler('listing-source', self.listing_source_path)
5758

5859
# We need to prepare some things for the listings path handler to work.
5960

@@ -255,6 +256,22 @@ def render_listing(in_name, out_name, input_folder, output_folder, folders=[], f
255256
'clean': True,
256257
}, self.kw["filters"])
257258

259+
def listing_source_path(self, name, lang):
260+
"""A link to the source code for a listing.
261+
262+
It will try to use the file name if it's not ambiguous, or the file path.
263+
264+
Example:
265+
266+
link://listing-source/hello.py => /listings/tutorial/hello.py
267+
268+
link://listing-source/tutorial/hello.py => /listings/tutorial/hello.py
269+
"""
270+
result = self.listing_path(name, lang)
271+
if result[-1].endswith('.html'):
272+
result[-1] = result[-1][:-5]
273+
return result
274+
258275
def listing_path(self, namep, lang):
259276
"""A link to a listing.
260277

0 commit comments

Comments
 (0)