Automatically link functions/classes in code example in Sphinx documentation - python-sphinx

I am building code documentation with Sphinx.
Let's say at some point there is documentation for a class foobar.Foo, i.e. something like
.. autoclass:: foobar.Foo
:members:
At some other place, I have a code example (included using literalinclude), which contains the line
foo = foobar.Foo()
Is there a way to make the foobar.Foo in the code example automatically link to the documentation of that class like when using
:class:`foobar.Foo`
in normal text?

Related

Sphinx add hyperlink to referenced modules [duplicate]

I have installed Sphinx in order to document some Python modules and class I'm working on. While the markup language looks very nice, I haven't managed to auto-document a Python code.
Basically, I have the following Python module:
SegLib.py
And A class called Seg in it. I would like to display the docstrings of the class and module within the generated Sphinx document, and add further formatted text to it.
My index.rst looks like this:
Contents:
.. toctree::
:maxdepth: 2
chapter1.rst
and chapter1.rst:
This is a header
================
Some text, *italic text*, **bold text**
* bulleted list. There needs to be a space right after the "*"
* item 2
.. note::
This is a note.
See :class:`Seg`
But Seg is just printed in bold, and not linked to an auto-generated documentation of the class.
Trying the following didn't help, either:
See :class:`Seg`
Module :mod:'SegLib'
Module :mod:'SegLib.py'
Edit: changed SegLib to segments (thanks, iElectric!), and changed chapter1.rst to:
The :mod:`segments` Module
--------------------------
.. automodule:: segments.segments
.. autoclass:: segments.segments.Seg
Still, can't get Sphinx to directly document functions within a class, or better - to automatically add all the functions within a class to the document. Tried:
.. autofunction:: segments.segments.Seg.sid
and got:
autodoc can't import/find function 'segments.segments.Seg.sid', it reported error: "No module named Seg"
Any ideas how to auto-document the functions and classes with a short command?
Add to the beginning of the file:
.. module:: SegLib
Try using :autoclass: directive for class doc.
BTW: module names should be lower_case.
EDIT: I learned a lot from reading other source files.

How to reference an *.rst file from the docstring of a module using sphinx

I wrote a little tutorial in rst format. Now for the documentation generated by apidoc, I would like to reference that tutorial in the docstring using:
:any:`<my_tut>`
Where my_tut.rst is in the top level directory of my Sphinx-documentation source-folder. However, I get the error
WARNING: 'any' reference target not found: my_tut
Added info:
The output of apidoc is not in the toplevel source folder, but in a subfolder called code.
The :doc: role can be used to create a cross-reference to my_tut.rst:
:doc:`my_tut`
If the link source and the link target are in different folders, that needs to be taken into account. With a target one level above the source, it would look like this:
:doc:`../my_tut`
An alternative is to add a label immediately before the relevant heading in my_tut.rst and use that as the cross-reference target. If the label definition is .. _my_label:, you would reference it like this:
:any:`my_label`
You could also use :ref:`my_label`.

In a TextMate snippet, how can I pull in the current class and/or method name?

Just like I can pull in the currently selected text into a snippet using the $TM_SELECTED_TEXT, is there any way I can retrieve text from my code like the method name or class name containing the current caret position?
This'd be super useful for quickly creating useful log messages.
So, if I had some, say, JavaScript code (with | representing the cursor/caret location):
function doSomething() {
somethingElse();
|
}
I'd love to be able to spit out doSomething via a snippet.
Something like,
console.log($TM_CURRENT_METHOD_NAME + "() $1");
Is something like this possible?
In my fork of the Ember bundle, I put this script in Support/bin/camelize_filename:
#!/usr/bin/env ruby
c=%w{config helpers mixins controllers models routes templates views}.join('|')
r = %r{.*/(?:#{c})/(.*)\.js}
puts ENV['TM_FILEPATH'].sub(%r{.*/(?:#{c})/(.*)\.js},'\1').
gsub(/(?:_|(\/)|^)([a-z\d]*)/){|s| "#{$1}#{$2.capitalize}" }.gsub('/','')
Then I use it in snippets thusly:
console.groupCollapsed("`camelize_filename`#model");
You could adapt this for other frameworks by adapting the regex to match which directory segments belong in a class's namespace and which do not, and changing gsub('/','') if the language you are interested uses a namespace delimiter like '::'.

How to extend redcarpet to support auto linking user mentions?

On my rails3 application I want to use redcarpet to handle user's posts and the user comment section. As such I'd like to extend redcarpet to support turning #username into a link to a user on my site. I know redcarpet is written in C but is there anyway easy way to extend it in ruby? How hard would it be to write it in C? Should I just do this outside of redcarpet?
Also I'm intrested in some other extensions of redcarpet that would be shorthand for linking to other models in my app. I'm not sure the syntax yet but I'm guessing it would be similar to how github handles linking to issues.
I found it pretty easy to extend redcarpet's parser in Ruby for my rails 3 app. It wasn't scary at all.
First, start by deriving a class from Redcarpet's HTML renderer and override the preprocess method as recommended in the docs. In Rails 3.2 and Rails 4, this file can go anywhere and you don't need to require it. I use a 'services' folder to hold code like this.
# app/services/my_flavored_markdown.rb
class MyFlavoredMarkdown < Redcarpet::Render::HTML
def preprocess(text)
text
end
end
Next step is to add methods that do text substitutions you want. Here I use regex to wrap text that looks like "#mention" in an HTML span tag with a css class 'mention'.
# app/services/my_flavored_markdown.rb
class MyFlavoredMarkdown < Redcarpet::Render::HTML
def preprocess(text)
wrap_mentions(text)
end
def wrap_mentions(text)
text.gsub! /(^|\s)(#\w+)/ do
"#{$1}<span class='mention'>#{$2}</span>"
end
text
end
end
You could just as easily look up a user's profile page and wrap the #mention in an anchor tag instead. In my case, I also made methods for emoticons and hashtags that worked the same way and chained the methods together.
The last step is to add a helper that accepts some text, creates an instance of your Redcarpet-derived class, passes the text into that for processing, and returns the html result.
# app/helpers/application_helper.rb
def flavored_markdown_to_html(text)
renderer = MyFlavoredMarkdown.new()
# These options might be helpful but are not required
options = {
safe_links_only: true,
no_intra_emphasis: true,
autolink: true
}
Redcarpet::Markdown.new(renderer, options).render(text)
}
In your views you can call it like this:
<%= flavored_markdown_to_html("This is something worth #mentioning") %>
The output would then be:
This is something worth <span class='mention'>#mentioning</span>.
I once tried to extend redcarpet, but found it very difficult. If there are no other dependencies on redcarpet I'd recommend you try rpeg-markdown which is a (somewhat outdated) Ruby gem providing bindings to the excellent peg-markdown.
peg-markdown is a markdown interpreter written as a formal grammar. This means that it is very easy to extend it with own syntax. I've successfully extended peg-markdown for my own projects (see my fork here) and I found it to be much simpler than fiddling with redcarpet's custom parser code.
I also found peg-markdown to have fewer bugs.
The Ruby bindings may have to be made current by updating the git submodule. (I'm planning to submit a pull request to update rpeg-markdown to the latest version of peg-markdown.)

render individual file in middleman

I am writing a helper and I need to get a rendered file as String.
I see that the method that I need exists in the middleman's library: http://rubydoc.info/github/middleman/middleman/Middleman/CoreExtensions/Rendering/InstanceMethods#render_individual_file-instance_method
How do I call this function from my helper class?
I tried:
require "middleman-core/lib/middleman-core/core_extensions/rendering.rb"
...
puts Middleman::CoreExtensions::Rendering::InstanceMethods.render_individual_file(filepath)
But it does not seem to find the file, any idea?
I'm not sure 3.0 beta is quite ready for primetime.
That said, it does sound like the partial method is what you're looking for.
Unless I'm missing something, the Middleman method seems like an overly-complex solution. For one of my sites I wanted to load entire text files into my templates, so I wrote this helper:
# Shortcut for loading raw text files. Obviously assumes that given file is in a valid format.
# #return [String] File contents
def load_textfile(filename)
File.read filename.to_s
end
Also, you should clarify if you are intending to use this within a template, or within Ruby code. It's not clear to me based on your question.
Here is an example of how one would use above helper:
Currently of note, Middleman is in the process of transitioning to version 4, and the conventions for loading helpers will change. The most straightforward way to define a helper is within a helper block in your config.rb file, as follows:
helpers do
# Define helper functions here to make them available in templates
end
I use Slim for templating. It really is the best. In slim you would appply helper as thus:
= load_textfile 'path'
p You can embed helper output in your page with interpolation, too: #{load_textfile 'path'}

Resources