API Reference#
Main instance#
This module describes 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
- 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 – the UID of the error to be deleted
- static check_whitelist()#
Removes errors that are whitelisted.
- static execute_module(module)#
Executes checks for provided module and returns its Problems. This method is used to parallelize the module execution.
- 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[Path]) – a list of the paths for the html output
compile_tex (bool) – boolean if the tex file should be compiled
- static output_file()#
Writes all current problems to the specified output file.
- static output_html()#
Renders all current problem objects as HTML and writes the file.
- static output_json()#
Writes all the current problem objects to the output file.
- static run_tools()#
Runs all modules in the LaTeXBuddy toolchain in parallel
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.
- 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 – 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 (Optional[str]) – regular expression that the config entry is required to match fully (otherwise ConfigOptionVerificationError is raised) Note: this overrides verify_type with ‘AnyStr’
verify_choices (Optional[Union[List[Any], Tuple[Any], Set[Any]]]) – 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 – 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 (Optional[str]) – regular expression that the config entry is required to match fully (otherwise ConfigOptionVerificationError is raised) Note: this overrides verify_type with ‘AnyStr’
verify_choices (Optional[Union[List[Any], Tuple[Any], Set[Any]]]) – 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.
- class latexbuddy.texfile.TexFile(file, compile_tex)#
A simple TeX file. This class reads the file, detects its encoding and saves it as text for future editing.
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.
- 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[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[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[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 probably 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.
- Parameters
- 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)
- Parameters
obj (Any) –
- 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, or p_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 wrong LaTeX syntax
- latexbuddy.problem.set_language(lang)#
Sets the static variable language used for key generation
- Parameters
lang – global language that the modules currently work with
Output#
- 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.
- latexbuddy.output.create_empty_line_interval_list(tex_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.
- latexbuddy.output.mark_intervals_in_tex(tex_lines, line_intervals)#
Adds HTML marker-tags (span) for every interval in line_intervals to the respective line in tex_lines and escapes all HTML control characters in tex_lines.
- latexbuddy.output.mark_intervals_in_tex_line(tex_line, intervals)#
Adds HTML marker-tags (span) for every interval in intervals to the respective tex_line string and returns the resulting line. This method also escapes all HTML control characters included in tex_line.
- 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, 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[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 ProblemFilters are:
of the same type
equal in terms of their custom parameters
This method explicitly 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 with respect to its type and custom parameters, 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 ProblemFilters are:
of the same type
equal in terms of their custom parameters
This method explicitly 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 with respect to its type and custom parameters, 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.
- matches_preprocessor_filter(problem)#
Checks, if the provided Problem matches any filter.
- regex_parse_preprocessor_comments(file)#
This method takes in a TexFile object and parses all contained preprocessor commands resulting in a set of ProblemFilters which are added to this instance’s list of filters to be applied to any given problem.
- Parameters
file (TexFile) – TexFile object containing the LaTeX sourcecode to be parsed
- Return type
None
- class latexbuddy.preprocessor.ProblemFilter(start_line, end_line=None)#
Describes the base class for any filter for Problem objects. ProblemFilter provides functionality to define a start and end line and to match a problem based on its line position.
ProblemFilters can be created open-ended by omitting the end_line parameter resulting in the filter matching any Problem located at or below the start line. Open-ended filters can later be closed by supplying an end line to the end() method.
For more diverse filters ProblemFilter provides the following abstract methods which must be implemented by all subclasses:
- custom_match: Matches a problem based on custom parameters. This method is
only called, if a given problem is located within the filter’s line boundaries
- custom_parameters_equal: determines whether another custom filter is of the
same type and has all equal custom parameters as the current one
- 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 ProblemFilters are:
of the same type
equal in terms of their custom parameters
This method explicitly 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 with respect to its type and custom parameters, False otherwise
- Return type
- end(end_line)#
Sets the end line of ProblemFilter, if not already done.
- match(problem)#
Determines, whether a given problem is located within the ProblemFilter’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) –
- custom_match(problem)#
Matches a given Problem object based on custom parameters of the subclass implementation.
- custom_parameters_equal(other)#
- Determines, if two custom ProblemFilters are:
of the same type
equal in terms of their custom parameters
This method explicitly 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 with respect to its type and custom parameters, False otherwise
- Return type
- class latexbuddy.preprocessor.WhitelistKeyProblemFilter(wl_key, start_line, end_line=None)#
WhitelistKeyProblemFilter implementation that filters problems, if they have been created with a specified whitelist key.
- custom_match(problem)#
Matches a given Problem object based on custom parameters of the subclass implementation.
- custom_parameters_equal(other)#
- Determines, if two custom ProblemFilters are:
of the same type
equal in terms of their custom parameters
This method explicitly 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 with respect to its type and custom parameters, False otherwise
- Return type
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.
Logging#
- class latexbuddy.log.ConsoleFormatter(enable_colour=True)#
Log formatter for console output.
Outputs messages with colours (thanks to colorama) and severities.
- Parameters
enable_colour (bool) –
- format(record)#
Format the specified record as text.
The record’s attribute dictionary is used as the operand to a string formatting operation which yields the returned string. Before formatting the dictionary, a couple of preparatory steps are carried out. The message attribute of the record is computed using LogRecord.getMessage(). If the formatting string uses the time (as determined by a call to usesTime(), formatTime() is called to format the event time. If there is exception information, it is formatted using formatException() and appended to the message.
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.
- class latexbuddy.tools.ToolLogger#
- latexbuddy.tools.absolute_to_linecol(text, position)#
Calculates line and column number for an absolute character position.
- latexbuddy.tools.add_whitelist_console(whitelist_file, to_add)#
Adds a list of keys to the Whitelist. Keys should be valid keys, ideally copied from LaTeXBuddy HTML Output.
- Parameters
whitelist_file – Path to whitelist file
to_add – list of keys
- latexbuddy.tools.add_whitelist_from_file(whitelist_file, file_to_parse, lang)#
Takes in a list of words and creates their respective keys, then adds them to whitelist. Words in the file_to_parse should all be from the same language. Each line represents a single Word.
- Parameters
whitelist_file – Path to whitelist file
file_to_parse – Path to wordlist
lang – language of the words in the wordlist
- 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.convert_file_to_absolute(unchecked_files, root_dir)#
Converts a relative path to an absolute if needed
- 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 (Optional[str]) – 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.ToolLogger (WARNING)>, 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 (Optional[str]) – 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_abs_path(path)#
Gets absolute path of a string :param path: the path :return: the absolute path
- 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
- latexbuddy.tools.get_app_dir()#
Finds the directory for storing application data (mostly logs).
This is a lightweight port of Click’s mononymous function: https://github.com/pallets/click/blob/af0af571cbbd921d3974a0ff9cf58a4b26bb852b/src/click/utils.py#L412-L458
- Returns
path of the application directory
- 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 at least 1024 bytes were read.
- 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
- latexbuddy.tools.match_lines(lines, unchecked_files, checked_files)#
Matches the lines with the given regexes