API Reference#
Main instance#
Contains the main LaTeXBuddy instance class.
- class latexbuddy.buddy.LatexBuddy#
The main instance of the applications that controls all the internal tools.
This is a singleton class with only one instance and exclusively static methods.
- static add_error(problem)#
Adds the error to the errors dictionary.
UID is used as key, the error object is used as value.
- Parameters:
problem (Problem) – problem to add to the dictionary
- Return type:
None
- static add_to_whitelist(uid)#
Adds the error identified by the given UID to the whitelist.
Afterwards this method deletes all other errors that are the same as the one just whitelisted.
- Parameters:
uid (str) – the UID of the error to be deleted
- Return type:
None
- static check_whitelist()#
Removes errors that are whitelisted.
- Return type:
None
- static execute_module(module)#
Executes checks for provided module and returns its Problems. This method is used to parallelize the module execution.
- Parameters:
module (Module) – module to execute
- Returns:
list of resulting problems
- Return type:
- static init(config_loader, module_provider, file_to_check, path_list, *, compile_tex)#
Initializes the LaTeXBuddy instance.
- Parameters:
config_loader (ConfigLoader) – ConfigLoader object to manage config options
module_provider (ModuleProvider) – ModuleProvider instance as a source of Module instances for running checks on the specified file
file_to_check (Path) – file that will be checked
path_list (list[pathlib.Path]) – a list of the paths for the html output
compile_tex (bool) – boolean if the tex file should be compiled
- Return type:
None
- static output_file()#
Writes all current problems to the specified output file.
- Return type:
None
- static output_html()#
Renders all current problem objects as HTML and writes the file.
- Return type:
None
- static output_json()#
Writes all the current problem objects to the output file.
- Return type:
None
- static run_tools()#
Runs all modules in the LaTeXBuddy toolchain in parallel.
- Return type:
None
Configuration#
This module describes the LaTeXBuddy config loader and its properties.
- class latexbuddy.config_loader.ConfigLoader(cli_arguments=None)#
Describes a ConfigLoader object.
The ConfigLoader processes LaTeXBuddy’s cli arguments and loads the specified config file or the default config file, if none is specified. ConfigLoader also offers methods for accessing config entries with the option to specify a default value on Failure.
- Parameters:
cli_arguments (Namespace | None) –
- get_config_option(module, key, verify_type=typing.Any, verify_regex=None, verify_choices=None)#
This method fetches the value of the config entry with the specified key for the specified tool or raises a ConfigOptionNotFoundError, if such an entry doesn’t exist or the retrieved entry does not match a specified verification criterion.
- Parameters:
module (Optional[Union[Type[NamedModule], NamedModule]]) – type or an instance of the module owning the config option; if unspecified, this method will look for a configuration option in the main instance’s dictionary
key (str) – key of the config option
verify_type (Type) – typing type that the config entry is required to be an instance of (otherwise
ConfigOptionVerificationError
is raised)verify_regex (str | None) –
regular expression that the config entry is required to match fully (otherwise
ConfigOptionVerificationError
is raised)Note: this overrides verify_type with ‘AnyStr’
verify_choices (List[Any] | Tuple[Any] | Set[Any] | None) – a list/tuple/set of valid values in which the config entry needs to be contained in order to be valid
- Returns:
the value of the requested config option, if it exists
- Raises:
ConfigOptionNotFoundError, if the requested config option doesn’t exist
- Raises:
ConfigOptionVerificationError, if the requested config option does not meet the specified criteria
- Return type:
- get_config_option_or_default(module, key, default_value, verify_type=typing.Any, verify_regex=None, verify_choices=None)#
This method fetches the value of the config entry with the specified key for the specified tool or returns the specified default value, if such an entry doesn’t exist or the retrieved entry does not match a specified verification criterion.
- Parameters:
module (Optional[Union[Type[NamedModule], NamedModule]]) – type or an instance of the module owning the config option; if unspecified, this method will look for a configuration option in the main instance’s dictionary
key (str) – key of the config option
default_value (Any) – default value in case the requested option doesn’t exist
verify_type (Type) – typing type that the config entry is required to be an instance of (otherwise
ConfigOptionVerificationError
is raised)verify_regex (str | None) –
regular expression that the config entry is required to match fully (otherwise
ConfigOptionVerificationError
is raised).Note: this overrides
verify_type
withtyping.AnyStr
verify_choices (List[Any] | Tuple[Any] | Set[Any] | None) – a list/tuple/set of valid values in which the config entry needs to be contained in order to be valid
- Returns:
the value of the requested config option or
default_value
, if the config option doesn’t exist- Return type:
TeX file#
This module defines new TexFile class used to abstract files LaTeXBuddy is working with.
Modules#
- class latexbuddy.module_loader.ModuleLoader(directory)#
This class encapsulates all features necessary to load LaTeXBuddy modules from a specified directory.
- Parameters:
directory (Path) –
- find_py_files()#
This method finds all .py files within the ModuleLoader’s directory or any subdirectories and returns a list of their paths.
- Returns:
a list of all Python files in the ModuleLoader’s directory (or subfolders)
- Return type:
- import_py_files()#
This method loads a python module from the specified file path for a list of file paths.
- Returns:
a list of python modules ready to be used
- Return type:
list[module]
- load_modules()#
This method loads every module that is found in the ModuleLoader’s directory.
- Returns:
a list of instances of classes implementing the Module API
- Return type:
list[latexbuddy.modules.Module]
- load_selected_modules(cfg)#
This method loads every module that is found in the ModuleLoader’s directory and only returns instances of modules that are enabled in the specified configuration context.
- Parameters:
cfg (ConfigLoader) – ConfigLoader instance containing config options for enabled/disabled tools
- Returns:
a list of instances of classes implementing the Module API which have been enabled in the specified configuration context
- Return type:
list[latexbuddy.modules.Module]
- class latexbuddy.module_loader.ModuleProvider#
This interface class defines all methods necessary to provide a list of instances of modules that implement the Module API, which is required in order for the instances to be executed by the main LatexBuddy instance.
- abstract load_selected_modules(cfg)#
This method loads every module that is found in the ModuleLoader’s directory and only returns instances of modules that are enabled in the specified configuration context.
- Parameters:
cfg (ConfigLoader) – ConfigLoader instance containing config options for enabled/disabled tools
- Returns:
a list of instances of classes implementing the Module API which have been enabled in the specified configuration context
- Return type:
list[latexbuddy.modules.Module]
Problems#
This module describes the LaTeXBuddy Problem class and its properties.
Problems are found by Checkers. Checkers are free to implement their own
Problem
types, however, LaTeXBuddy will most
surely not display extra metadata.
- class latexbuddy.problem.Problem(position, text, checker, file, severity=ProblemSeverity.WARNING, p_type=None, length=None, category=None, description=None, context=None, suggestions=None, key=None)#
Describes a Problem object.
A Problem object contains information about a problem detected by a checker. For example, it can be wrong LaTeX code or a misspelled word.
- class latexbuddy.problem.ProblemJSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)#
Provides JSON serializability for class Problem.
- default(obj)#
Implement this method in a subclass such that it returns a serializable object for
o
, or calls the base implementation (to raise aTypeError
).For example, to support arbitrary iterators, you could implement default like this:
def default(self, o): try: iterable = iter(o) except TypeError: pass else: return list(iterable) # Let the base class default method raise the TypeError return JSONEncoder.default(self, o)
- class latexbuddy.problem.ProblemSeverity(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)#
Defines possible problem severity grades.
Problem severity is usually preset by the checkers themselves. However, a user should be able to redefine the severity of a specific problem, using either
category
,key
, orp_type
."none"
problems are not being highlighted, but are still being output."info"
problems are highlighted with light blue colour. These are suggestions; problems, that aren’t criticising the text. Example: suggestion to use “lots” instead of “a lot”"warning"
problems are highlighted with orange colour. These are warnings about problematic areas in documents. The files compile and work as expected, but some behaviour may be unacceptable. Example: warning about using “$$” in LaTeX"error"
problems are highlighted with red colour. These are errors, that prevent the documents to compile correctly. Example: not closed environment, or plain wrong LaTeX syntax
Output#
- class latexbuddy.output.Interval(problems, start=None, end=None)#
This class describes an interval with problems.
An interval is a section of text, defined byt its start and end positions, that contains
Problem
objects.- Parameters:
- intersects(other)#
Determines whether or not the other interval intersects with ‘self’.
- perform_intersection(other)#
Performs an intersection of two intervals and returns a list of new non-intersecting intervals to replace the two specified intervals ‘self’ and ‘other’, if the intervals actually intersect. Should the intervals not intersect, None is returned, indicating that there is no need to replace the two intervals. The intervals in the returned list are sorted by their start index in ascending order.
- Parameters:
other (Interval) – other interval to intersect with ‘self’
- Return type:
list[latexbuddy.output.Interval] | None
- latexbuddy.output.add_basic_problem_intervals(line_intervals, problems, tex_lines)#
Filters out problems without a position attribute or with length zero and inserts the remaining ones into the line_intervals list.
- Parameters:
line_intervals (list[list[latexbuddy.output.Interval]]) – List of lists of Intervals for any given line
problems (list[latexbuddy.problem.Problem]) – list of problems to be inserted as Intervals
- Return type:
None
- latexbuddy.output.create_empty_line_interval_list(lines)#
Creates and returns a list of (empty) lists of Intervals. The outer list will contain exactly len(tex_lines) + 1 empty lists.
- latexbuddy.output.generate_wrapper_html_tags(interval)#
Generates and returns a pair of HTML
<span>
tags to wrap the text in the specified interval.
- latexbuddy.output.highlight(tex, problems)#
Highlights the TeX code using the problems’ data.
- Parameters:
tex (str) – TeX source
problems (list[latexbuddy.problem.Problem]) – list of problems
- Returns:
HTML string with highlighted errors, ready to be put inside <pre>
- Return type:
- latexbuddy.output.mark_intervals_in_tex(lines, line_intervals)#
Adds HTML marker-tags for every interval in multiple lines of TeX code.
For every line in
lines
, and for every interval inline_intervals
for the respective line, this method wraps it with<span>
tags and returns the resulting line. This method also escapes all HTML control characters included intex_line
.It basically calls
mark_intervals_in_tex_line()
, but the lines are modified in-place.- Parameters:
line_intervals (list[list[latexbuddy.output.Interval]]) – list of non-intersecting intervals to be highlighted for every line
- Return type:
None
- latexbuddy.output.mark_intervals_in_tex_line(line, intervals)#
Adds HTML marker-tags for every interval in a line of TeX code.
For every interval in
intervals
, this method wraps it with<span>
tags and returns the resulting line. This method also escapes all HTML control characters included intex_line
.- Parameters:
line (str) – line from the TeX file
intervals (list[latexbuddy.output.Interval]) – list of non-intersecting intervals to be highlighted in the line
- Returns:
resulting line as a string, containing
<span>
tags- Return type:
- latexbuddy.output.problem_key(problem)#
Returns a number for each problem to be able to sort them.
This puts YaLaFi’s problems on top, followed by errors without location.
- latexbuddy.output.render_general_html(template, file_name, file_text, problems, path_list, pdf_path)#
Renders an HTML page based on file contents and discovered problems.
- Parameters:
template (Template) – HTML template to use for generation
file_name (str) – file name
file_text (str) – contents of the file
problems (dict[str, latexbuddy.problem.Problem]) – dictionary of errors returned from latexbuddy
pdf_path (str) – path of pdf file
path_list (Path) – a list, containing all file paths to the checked files
- Returns:
generated HTML
- Return type:
- latexbuddy.output.resolve_interval_intersections(intervals)#
Finds any intersecting intervals and replaces them with non- intersecting intervals that may contain more than one problem.
- Parameters:
intervals (list[latexbuddy.output.Interval]) – list of intervals in one line to be checked for intersections
- Return type:
None
Preprocessing#
- class latexbuddy.preprocessor.LineProblemFilter(start_line, end_line=None)#
ProblemFilter implementation that only considers a problem’s line position.
- custom_match(problem)#
Matches a given Problem object based on custom parameters of the subclass implementation.
- custom_parameters_equal(other)#
Determines, if two custom
ProblemFilter
objects are equal.Two objects of type
ProblemFilter
are considered equal as long as they are:of the same type
equal in terms of their custom parameters
Caution
This method does not check the equality of start_line` and
end_line
!- Parameters:
other (ProblemFilter) – second custom ProblemFilter to be compared with the current one
- Returns:
True
, if the other custom ProblemFilter is equal to the current one,False
otherwise- Return type:
- class latexbuddy.preprocessor.ModuleProblemFilter(module_name, start_line, end_line=None)#
ProblemFilter implementation that filters problems, if they have been created by a specified LaTeXBuddy module.
- custom_match(problem)#
Matches a given Problem object based on custom parameters of the subclass implementation.
- custom_parameters_equal(other)#
Determines, if two custom
ProblemFilter
objects are equal.Two objects of type
ProblemFilter
are considered equal as long as they are:of the same type
equal in terms of their custom parameters
Caution
This method does not check the equality of start_line` and
end_line
!- Parameters:
other (ProblemFilter) – second custom ProblemFilter to be compared with the current one
- Returns:
True
, if the other custom ProblemFilter is equal to the current one,False
otherwise- Return type:
- class latexbuddy.preprocessor.Preprocessor#
This class represents the LaTeXBuddy in-file preprocessor.
the Preprocessor is capable of parsing buddy commands disguised as LaTeX comments from a TexFile object using regexes and is able to filter any given Problem or list of Problems accordingly.
- apply_preprocessor_filter(problems)#
Applies all parsed ProblemFilters and returns all non- matching Problems.
- Parameters:
problems (list[latexbuddy.problem.Problem]) – list of Problems to filter
- Returns:
filtered list of Problems
- Return type:
- matches_preprocessor_filter(problem)#
Checks, if the provided Problem matches any filter.
- regex_parse_preprocessor_comments(file)#
Parses preprocessor statements in a TeX file.
This method takes a
TexFile
object and parses all preprocessor statements contained in it. This results in a set of ofProblemFilter
objects, which are then added to this instance’s list of filters and later applied to the problems.- Parameters:
file (TexFile) – TeX file object containing the LaTeX source code to be parsed
- Return type:
None
- class latexbuddy.preprocessor.ProblemFilter(start_line, end_line=None)#
Describes the base class for any problem filter.
ProblemFilter
provides functionality to define a start and end line and to match aProblem
based on its line position.ProblemFilter
objects can be made “open-ended” by omitting theend_line
parameter. This results in a filter matching any problem located at or below thestart_line
. Open-ended filters can later be closed by supplying theend_line
via theend()
method.For more diverse filters, ProblemFilter provides the following abstract methods which must be implemented by all subclasses:
custom_match()
andcustom_parameters_equal()
.- Parameters:
- abstract custom_match(problem)#
Matches a given Problem object based on custom parameters of the subclass implementation.
- abstract custom_parameters_equal(other)#
Determines, if two custom
ProblemFilter
objects are equal.Two objects of type
ProblemFilter
are considered equal as long as they are:of the same type
equal in terms of their custom parameters
Caution
This method does not check the equality of start_line` and
end_line
!- Parameters:
other (ProblemFilter) – second custom ProblemFilter to be compared with the current one
- Returns:
True
, if the other custom ProblemFilter is equal to the current one,False
otherwise- Return type:
- end(end_line)#
Sets the end line of ProblemFilter, if not already done.
- match(problem)#
Matches custom filter’s requirements against a problem.
This method determines, whether a given problem is located within the filter’s line boundaries and matches all custom requirements that the subclass implementation imposes.
- class latexbuddy.preprocessor.SeverityProblemFilter(severity, start_line, end_line=None)#
ProblemFilter implementation that filters problems, if they have been created with a specified ProblemSeverity.
- Parameters:
severity (ProblemSeverity) –
start_line (int) –
end_line (int | None) –
- custom_match(problem)#
Matches a given Problem object based on custom parameters of the subclass implementation.
- custom_parameters_equal(other)#
Determines, if two custom
ProblemFilter
objects are equal.Two objects of type
ProblemFilter
are considered equal as long as they are:of the same type
equal in terms of their custom parameters
Caution
This method does not check the equality of start_line` and
end_line
!- Parameters:
other (ProblemFilter) – second custom ProblemFilter to be compared with the current one
- Returns:
True
, if the other custom ProblemFilter is equal to the current one,False
otherwise- Return type:
- class latexbuddy.preprocessor.WhitelistKeyProblemFilter(wl_key, start_line, end_line=None)#
This filter excludes problems, if they have been created with a specified whitelist key.
- Parameters:
- custom_match(problem)#
Matches a given Problem object based on custom parameters of the subclass implementation.
- custom_parameters_equal(other)#
Determines, if two custom
ProblemFilter
objects are equal.Two objects of type
ProblemFilter
are considered equal as long as they are:of the same type
equal in terms of their custom parameters
Caution
This method does not check the equality of start_line` and
end_line
!- Parameters:
other (ProblemFilter) – second custom ProblemFilter to be compared with the current one
- Returns:
True
, if the other custom ProblemFilter is equal to the current one,False
otherwise- Return type:
Whitelist#
- latexbuddy.whitelist.add_to_whitelist(whitelist, keys)#
Adds a list of keys to the whitelist.
Keys should be valid keys, ideally copied from LaTeXBuddy HTML output.
- latexbuddy.whitelist.fill_whitelist_from_wordlist(whitelist, wordlist, language)#
Adds keys to the whitelist based on a list of words.
Words in the wordlist should all be from the same language. Each line should be a single word.
Utilities#
Exceptions#
This module defines standard exceptions that are to be raised when certain application-specific errors occur.
- exception latexbuddy.exceptions.ConfigOptionError#
Base Exception for errors related to loading configurations.
- exception latexbuddy.exceptions.ConfigOptionNotFoundError#
Describes a ConfigOptionNotFoundError.
This error is raised when a requested config entry doesn’t exist.
- exception latexbuddy.exceptions.ConfigOptionVerificationError#
Describes a ConfigOptionVerificationError.
This error is raised when a requested config entry does not meet the specified criteria.
- exception latexbuddy.exceptions.ExecutableNotFoundError#
This error is raised when LaTeXBuddy can not locate a third-party executable dependency on the system it is running on.
- exception latexbuddy.exceptions.LanguageNotSupportedError#
This error is raised when LaTeXBuddy or a submodule does not support the configured language.
Messages#
This module defines standard messages that are to be printed to the command line as well as builders for those.
Tools#
This module contains various utility tools.
- latexbuddy.tools.absolute_to_linecol(text, position)#
Calculates line and column number for an absolute character position.
- class latexbuddy.tools.classproperty(fget=None, fset=None, fdel=None, doc=None)#
Provides a way to implement a python property with class-level accessibility.
- latexbuddy.tools.execute(*cmd, encoding='ISO8859-1')#
Executes a terminal command with subprocess.
See usage example in latexbuddy.aspell.
- latexbuddy.tools.execute_background(*cmd)#
Executes a terminal command in background.
- latexbuddy.tools.execute_no_errors(*cmd, encoding='ISO8859-1')#
Executes a terminal command while suppressing errors.
- latexbuddy.tools.execute_no_exceptions(function_call, error_message='An error occurred while executing lambda function', traceback_log_level=None)#
Calls a function and catches any Exception that is raised during this.
If an Exception is caught, the function is aborted and the error is logged, but as the Exception is caught, the program won’t crash.
- Parameters:
function_call (Callable[[], None]) – function to be executed
error_message (str) – custom error message displayed in the console
traceback_log_level (str | None) – sets the log_level that is used to log the error traceback. If it is None, no traceback will be logged. Valid values are: “DEBUG”, “INFO”, “WARNING”, “ERROR”
- Return type:
None
- latexbuddy.tools.find_executable(name, to_install=None, err_logger=<Logger latexbuddy.tools (DEBUG)>, *, log_errors=True)#
Finds path to an executable.
If the executable can not be located, an error message is logged to the specified logger, otherwise the executable’s path is logged as a debug message.
This uses ‘which’, i.e. the executable should at least be in user’s $PATH
- Parameters:
name (str) – executable name
to_install (str | None) – correct name of the program or project which the requested executable belongs to (used in log messages)
err_logger (Logger) – custom logger to be used for logging debug/error messages
log_errors (bool) – specifies whether or not this method should log an error message, if the executable can not be located; if this is False, a debug message will be logged instead
- Returns:
path to the executable
- Raises:
FileNotFoundError – if the executable couldn’t be found
- Return type:
- latexbuddy.tools.get_all_paths_in_document(file_path)#
Checks files that are included in a file.
If the file includes more files, these files will also be checked.
:param file_path:a string, containing file path :return: the files to check
- Parameters:
file_path (Path) –
- Return type:
- latexbuddy.tools.get_command_string(cmd)#
Constructs a command string from a tuple of arguments.
- latexbuddy.tools.get_line_offsets(text)#
Calculates character offsets for each line in the file.
Indices correspond to the line numbers, but are 0-based. For example, if first 4 lines contain 100 characters (including line breaks), result[4] will be 100. result[0] = 0.
This is a port of YaLaFi’s get_line_starts() function.
- latexbuddy.tools.is_binary(file_bytes)#
Detects whether the bytes of a file contain binary code or not.
For correct detection, it is recommended, that file_bytes is at least 1024 bytes long.
- Sources:
- latexbuddy.tools.kill_background_process(process)#
Kills previously opened background process.
For example, it can accept the return value of
execute_background()
as argument.- Parameters:
process (Popen) – subprocess instance of the process
- Return type:
None
- latexbuddy.tools.match_lines(lines, unchecked_files, checked_files)#
Matches the lines with the given regexes.
- Parameters:
unchecked_files (list[pathlib.Path]) – the unchecked_files
checked_files (list[pathlib.Path]) – the checked_files
- Returns:
the unchecked_files
- Return type: