1
0
forked from VimPlug/jedi

Merge pull request #86 from dbrgn/docs

Sphinx Docs
This commit is contained in:
David Halter
2012-12-26 08:35:38 -08:00
8 changed files with 685 additions and 63 deletions

1
.gitignore vendored
View File

@@ -3,5 +3,6 @@
.ropeproject .ropeproject
*.pyc *.pyc
/build/ /build/
/docs/build/
/dist/ /dist/
jedi.egg-info/ jedi.egg-info/

153
docs/Makefile Normal file
View File

@@ -0,0 +1,153 @@
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
-rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Jedi.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Jedi.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/Jedi"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Jedi"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."

251
docs/source/conf.py Normal file
View File

@@ -0,0 +1,251 @@
# -*- coding: utf-8 -*-
#
# Jedi documentation build configuration file, created by
# sphinx-quickstart on Wed Dec 26 00:11:34 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('../..'))
sys.path.insert(0, os.path.abspath('../../jedi'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.todo']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
source_encoding = 'utf-8'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Jedi'
copyright = u'2012, Jedi contributors'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.5'
# The full version, including alpha/beta/rc tags.
release = '0.5b5'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'Jedidoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'Jedi.tex', u'Jedi Documentation',
u'Jedi contributors', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'jedi', u'Jedi Documentation',
[u'Jedi contributors'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'Jedi', u'Jedi Documentation',
u'Jedi contributors', 'Jedi', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# -- Options for todo module ---------------------------------------------------
todo_include_todos = False
# -- Options for autodoc module ------------------------------------------------
autodoc_default_flags = ['members', 'undoc-members']

25
docs/source/index.rst Normal file
View File

@@ -0,0 +1,25 @@
Jedi Python autocompletion that works!
========================================
.. automodule:: jedi
:members:
:undoc-members:
Contents
========
.. toctree::
:maxdepth: 1
installation
plugin-api
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

View File

@@ -0,0 +1,45 @@
Installation and Configuration
==============================
You can either include *Jedi* as a submodule in your text editor plugin (like
jedi-vim_ does it by default), or you can install it systemwide.
System-wide installation via a package manager
----------------------------------------------
You can install *Jedi* directly from pypi using pip::
sudo pip install jedi
If you want to install the current development version::
sudo pip install -e git://github.com/davidhalter/jedi.git#egg=jedi
.. note:: This just installs the Jedi library, not the editor plugins. For
information about how to make it work with your editor, refer to the
corresponding documentation.
Manual installation from a downloaded package
---------------------------------------------
If you prefer not to use an automated package installer, you can download a
copy of *Jedi* and install it manually.
To install it, navigate to the directory containing `setup.py` on your console
and type::
sudo python setup.py install
Inclusion as a submodule
------------------------
If you use an editor plugin like jedi-vim_, you can simply include *Jedi* as a
git submodule of the plugin directory. Vim plugin managers like Vundle_ make it
very easy to keep submodules up to date.
.. _jedi-vim: https://github.com/davidhalter/jedi-vim
.. _Vundle: https://github.com/gmarik/vundle

114
docs/source/plugin-api.rst Normal file
View File

@@ -0,0 +1,114 @@
The plugin API
==============
.. currentmodule:: jedi
If you want to set up an editor/IDE-plugin with **Jedi**, you first need to
``import jedi``. You then have direct access to the :class:`.Script`,
:class:`.NotFoundError` and :func:`.set_debug_function` objects.
API documentation
-----------------
Main class
~~~~~~~~~~
.. module:: api
.. autoclass:: Script
API Classes
~~~~~~~~~~~
.. module:: api_classes
.. autoclass:: BaseDefinition
.. autoclass:: Completion
:show-inheritance:
.. autoclass:: Definition
:show-inheritance:
.. autoclass:: RelatedName
:show-inheritance:
Exceptions
~~~~~~~~~~
.. module:: api
.. autoexception:: NotFoundError
Useful functions
~~~~~~~~~~~~~~~~
.. module:: api
.. autofunction:: set_debug_function
Examples
--------
Completions:
.. sourcecode:: python
>>> import jedi
>>> source = '''import json; json.l'''
>>> script = jedi.Script(source, 1, 19, '')
>>> script
<jedi.api.Script object at 0x2121b10>
>>> completions = script.complete()
>>> completions
[<Completion: load>, <Completion: loads>]
>>> completions[1]
<Completion: loads>
>>> completions[1].complete
'oads'
>>> completions[1].word
'loads'
Definitions:
.. sourcecode:: python
>>> import jedi
>>> source = '''def my_func():
... print 'called'
...
... alias = my_func
... my_list = [1, None, alias]
... inception = my_list[2]
...
... inception()'''
>>> script = jedi.Script(source, 8, 1, '')
>>>
>>> script.goto()
[<Definition inception=my_list[2]>]
>>>
>>> script.get_definition()
[<Definition def my_func>]
Related names:
.. sourcecode:: python
>>> import jedi
>>> source = '''x = 3
... if 1 == 2:
... x = 4
... else:
... del x'''
>>> script = jedi.Script(source, 5, 8, '')
>>> rns = script.related_names()
>>> rns
[<RelatedName x@3,4>, <RelatedName x@1,0>]
>>> rns[0].start_pos
(3, 4)
>>> rns[0].is_keyword
False
>>> rns[0].text
'x'

View File

@@ -46,7 +46,7 @@ from _compatibility import next, unicode
class NotFoundError(Exception): class NotFoundError(Exception):
""" A custom error to avoid catching the wrong exceptions """ """A custom error to avoid catching the wrong exceptions."""
pass pass
@@ -54,16 +54,17 @@ class Script(object):
""" """
A Script is the base for a completion, goto or whatever call. A Script is the base for a completion, goto or whatever call.
:param source: The source code of the current file :param source: The source code of the current file, separated by newlines.
:type source: string :type source: string
:param line: The line to complete in. :param line: The line to perform actions on (starting with 1).
:type line: int :type line: int
:param col: The column to complete in. :param col: The column of the cursor (starting with 0).
:type col: int :type col: int
:param source_path: The path in the os, the current module is in. :param source_path: The path of the file in the file system, or ``''`` if
it hasn't been saved yet.
:type source_path: string or None :type source_path: string or None
:param source_encoding: encoding for decoding `source`, if it :param source_encoding: The encoding of ``source``, if it is not a
is not a `unicode` object. ``unicode`` object (default `utf-8`).
:type source_encoding: string :type source_encoding: string
""" """
def __init__(self, source, line, column, source_path, def __init__(self, source, line, column, source_path,
@@ -79,14 +80,16 @@ class Script(object):
@property @property
def parser(self): def parser(self):
""" The lazy parser """ """ The lazy parser."""
return self.module.parser return self.module.parser
def complete(self): def complete(self):
""" """
An auto completer for python files. Return :class:`api_classes.Completion` objects. Those objects contain
information about the completions, more than just names.
:return: list of Completion objects, sorted by name and __ comes last. :return: list of :class:`api_classes.Completion` objects, sorted by
name and __ comes last.
:rtype: list :rtype: list
""" """
def follow_imports_if_possible(name): def follow_imports_if_possible(name):
@@ -207,16 +210,16 @@ class Script(object):
def get_definition(self): def get_definition(self):
""" """
Returns the definitions of a the path under the cursor. This is Return the definitions of a the path under the cursor. This is not a
not a goto function! This follows complicated paths and returns the goto function! This follows complicated paths and returns the end, not
end, not the first definition. the first definition. The big difference between :meth:`goto` and
The big difference of goto and get_definition is that goto doesn't :meth:`get_definition` is that :meth:`goto` doesn't follow imports and
follow imports and statements. statements. Multiple objects may be returned, because Python itself is
Multiple objects may be returned, because Python itself is a dynamic a dynamic language, which means depending on an option you can have two
language, which means depending on an option you can have two different different versions of a function.
versions of a function.
:return: list of Definition objects, which are basically scopes. :return: list of :class:`api_classes.Definition` objects, which are
basically scopes.
:rtype: list :rtype: list
""" """
def resolve_import_paths(scopes): def resolve_import_paths(scopes):
@@ -248,13 +251,13 @@ class Script(object):
def goto(self): def goto(self):
""" """
Returns the first definition found by goto. This means: It doesn't Return the first definition found by goto. Imports and statements
follow imports and statements. aren't followed. Multiple objects may be returned, because Python
Multiple objects may be returned, because Python itself is a dynamic itself is a dynamic language, which means depending on an option you
language, which means depending on an option you can have two different can have two different versions of a function.
versions of a function.
:return: list of Definition objects, which are basically scopes. :return: list of :class:`api_classes.Definition` objects, which are
basically scopes.
""" """
d = [api_classes.Definition(d) for d in set(self._goto()[0])] d = [api_classes.Definition(d) for d in set(self._goto()[0])]
return sorted(d, key=lambda x: (x.module_path, x.start_pos)) return sorted(d, key=lambda x: (x.module_path, x.start_pos))
@@ -305,12 +308,12 @@ class Script(object):
def related_names(self, additional_module_paths=[]): def related_names(self, additional_module_paths=[]):
""" """
Returns `dynamic.RelatedName` objects, which contain all names, that Return :class:`api_classes.RelatedName` objects, which contain all
are defined by the same variable, function, class or import. names that point to the definition of the name under the cursor. This
This function can be used either to show all the usages of a variable is very useful for refactoring (renaming), or to show all usages of a
or for renaming purposes. variable.
TODO implement additional_module_paths .. todo:: Implement additional_module_paths
""" """
user_stmt = self.parser.user_stmt user_stmt = self.parser.user_stmt
definitions, search_name = self._goto(add_import_name=True) definitions, search_name = self._goto(add_import_name=True)
@@ -339,13 +342,17 @@ class Script(object):
def get_in_function_call(self): def get_in_function_call(self):
""" """
Return the function, that the cursor is in, e.g.: Return the function object of the call you're currently in.
>>> isinstance(| # | <-- cursor is here
E.g. if the cursor is here::
This would return the `isinstance` function. In contrary: >>> abs(# <-- cursor is here
>>> isinstance()| # | <-- cursor is here
This would return `None`. This would return the ``abs`` function. On the other hand::
>>> abs()# <-- cursor is here
This would return ``None``.
""" """
def check_user_stmt(user_stmt): def check_user_stmt(user_stmt):
if user_stmt is None \ if user_stmt is None \
@@ -451,7 +458,8 @@ class Script(object):
def set_debug_function(func_cb=debug.print_to_stdout, warnings=True, def set_debug_function(func_cb=debug.print_to_stdout, warnings=True,
notices=True, speed=True): notices=True, speed=True):
""" """
You can define a callback debug function to get all the debug messages. Define a callback debug function to get all the debug messages.
:param func_cb: The callback function for debug messages, with n params. :param func_cb: The callback function for debug messages, with n params.
""" """
debug.debug_function = func_cb debug.debug_function = func_cb

View File

@@ -56,6 +56,7 @@ class BaseDefinition(object):
@property @property
def type(self): def type(self):
"""The type of the definition."""
# generate the type # generate the type
stripped = self.definition stripped = self.definition
if isinstance(self.definition, evaluate.InstanceElement): if isinstance(self.definition, evaluate.InstanceElement):
@@ -64,6 +65,7 @@ class BaseDefinition(object):
@property @property
def path(self): def path(self):
"""The module path."""
path = [] path = []
if not isinstance(self.definition, keywords.Keyword): if not isinstance(self.definition, keywords.Keyword):
par = self.definition par = self.definition
@@ -77,20 +79,24 @@ class BaseDefinition(object):
@property @property
def module_name(self): def module_name(self):
"""The module name."""
path = self.module_path path = self.module_path
sep = os.path.sep sep = os.path.sep
p = re.sub(r'^.*?([\w\d]+)(%s__init__)?.py$' % sep, r'\1', path) p = re.sub(r'^.*?([\w\d]+)(%s__init__)?.py$' % sep, r'\1', path)
return p return p
def in_builtin_module(self): def in_builtin_module(self):
"""Whether this is a builtin module."""
return not self.module_path.endswith('.py') return not self.module_path.endswith('.py')
@property @property
def line_nr(self): def line_nr(self):
"""The line where the definition occurs (starting with 1)."""
return self.start_pos[0] return self.start_pos[0]
@property @property
def column(self): def column(self):
"""The column where the definition occurs (starting with 0)."""
return self.start_pos[1] return self.start_pos[1]
@property @property
@@ -103,7 +109,7 @@ class BaseDefinition(object):
@property @property
def raw_doc(self): def raw_doc(self):
""" Returns the raw docstring `__doc__` for any object """ """The raw docstring ``__doc__`` for any object."""
try: try:
return unicode(self.definition.docstr) return unicode(self.definition.docstr)
except AttributeError: except AttributeError:
@@ -111,13 +117,12 @@ class BaseDefinition(object):
@property @property
def description(self): def description(self):
"""A textual description of the object."""
return unicode(self.definition) return unicode(self.definition)
@property @property
def full_name(self): def full_name(self):
""" """The path to a certain class/function, see #61."""
Returns the path to a certain class/function, see #61.
"""
path = [unicode(p) for p in self.path] path = [unicode(p) for p in self.path]
# TODO add further checks, the mapping should only occur on stdlib. # TODO add further checks, the mapping should only occur on stdlib.
try: try:
@@ -135,8 +140,10 @@ class BaseDefinition(object):
class Completion(BaseDefinition): class Completion(BaseDefinition):
""" `Completion` objects are returned from `Script.complete`. Providing """
some useful functions for IDE's. """ `Completion` objects are returned from :meth:`api.Script.complete`. They
provide additional information about a completion.
"""
def __init__(self, name, needs_dot, like_name_length, base): def __init__(self, name, needs_dot, like_name_length, base):
super(Completion, self).__init__(name.parent, name.start_pos) super(Completion, self).__init__(name.parent, name.start_pos)
@@ -149,11 +156,13 @@ class Completion(BaseDefinition):
@property @property
def complete(self): def complete(self):
""" Delievers the rest of the word, e.g. completing `isinstance` """
>>> isinstan Return the rest of the word, e.g. completing ``isinstance``::
>>> isinstan# <-- Cursor is here
would return the string 'ce'. It also adds additional stuff, depending would return the string 'ce'. It also adds additional stuff, depending
on your `settings.py` on your `settings.py`.
""" """
dot = '.' if self.needs_dot else '' dot = '.' if self.needs_dot else ''
append = '' append = ''
@@ -170,8 +179,10 @@ class Completion(BaseDefinition):
@property @property
def word(self): def word(self):
""" In contrary to `complete` returns the whole word, e.g. """
>>> isinstan Similar to :meth:`Completion.complete`, but return the whole word, e.g. ::
>>> isinstan
would return 'isinstance'. would return 'isinstance'.
""" """
@@ -179,8 +190,11 @@ class Completion(BaseDefinition):
@property @property
def description(self): def description(self):
""" Provides a description of the completion object """
TODO return value is just __repr__ of some objects, improve! """ Provide a description of the completion object.
.. todo:: return value is just __repr__ of some objects, improve!
"""
parent = self.name.parent parent = self.name.parent
if parent is None: if parent is None:
return '' return ''
@@ -194,12 +208,13 @@ class Completion(BaseDefinition):
return '%s: %s%s' % (t, desc, line_nr) return '%s: %s%s' % (t, desc, line_nr)
def follow_definition(self): def follow_definition(self):
""" Returns you the original definitions. I strongly recommend not """
using it for your completions, because it might slow down Jedi. If you Return the original definitions. I strongly recommend not using it for
want to read only a few objects (<=20). I think it might be useful, your completions, because it might slow down *Jedi*. If you want to read
especially to get the original docstrings. only a few objects (<=20), it might be useful, especially to
The basic problem of this function is that it follows all results. This get the original docstrings. The basic problem of this function is
means with 1000 completions (e.g. numpy), it's just PITA slow. that it follows all results. This means with 1000 completions (e.g.
numpy), it's just PITA-slow.
""" """
if self._followed_definitions is None: if self._followed_definitions is None:
if self.definition.isinstance(parsing.Statement): if self.definition.isinstance(parsing.Statement):
@@ -220,15 +235,19 @@ class Completion(BaseDefinition):
class Definition(BaseDefinition): class Definition(BaseDefinition):
""" These are the objects returned by either `Script.goto` or """
`Script.get_definition`. """ *Definition* objects are returned from :meth:`api.Script.goto` or
:meth:`api.Script.get_definition`.
"""
def __init__(self, definition): def __init__(self, definition):
super(Definition, self).__init__(definition, definition.start_pos) super(Definition, self).__init__(definition, definition.start_pos)
@property @property
def description(self): def description(self):
""" A description of the Definition object, which is heavily used in """
testing. e.g. for `isinstance` it returns 'def isinstance' """ A description of the :class:`.Definition` object, which is heavily used
in testing. e.g. for ``isinstance`` it returns ``def isinstance``.
"""
d = self.definition d = self.definition
if isinstance(d, evaluate.InstanceElement): if isinstance(d, evaluate.InstanceElement):
d = d.var d = d.var
@@ -252,10 +271,15 @@ class Definition(BaseDefinition):
@property @property
def desc_with_module(self): def desc_with_module(self):
""" In addition to the Definition, it also returns the module. Don't """
use it yet, its behaviour may change. If you really need it, talk to me In addition to the definition, also return the module.
TODO add full path. This function is should return a
module.class.function path. """ .. warning:: Don't use this function yet, its behaviour may change. If
you really need it, talk to me.
.. todo:: Add full path. This function is should return a
`module.class.function` path.
"""
if self.module_path.endswith('.py') \ if self.module_path.endswith('.py') \
and not isinstance(self.definition, parsing.Module): and not isinstance(self.definition, parsing.Module):
position = '@%s' % (self.line_nr) position = '@%s' % (self.line_nr)
@@ -266,6 +290,7 @@ class Definition(BaseDefinition):
class RelatedName(BaseDefinition): class RelatedName(BaseDefinition):
"""TODO: document this"""
def __init__(self, name_part, scope): def __init__(self, name_part, scope):
super(RelatedName, self).__init__(scope, name_part.start_pos) super(RelatedName, self).__init__(scope, name_part.start_pos)
self.name_part = name_part self.name_part = name_part