Skip to content

Commit

Permalink
Reformat code using python black
Browse files Browse the repository at this point in the history
Get rid of all the different coding and quoting styles
by running `black .` on the whole code base
defining a line length of 100.
  • Loading branch information
deathaxe committed Dec 30, 2024
1 parent 149a357 commit 79204d0
Show file tree
Hide file tree
Showing 84 changed files with 3,033 additions and 3,374 deletions.
81 changes: 36 additions & 45 deletions 01_reload_submodules.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@


def _load_module_exports(module):
if 'exports' in module.__dict__:
if "exports" in module.__dict__:
for name in module.exports:
try:
# lift the export to this modules top level
Expand All @@ -27,61 +27,52 @@ def _load_module_exports(module):
print("Error: {0} not defined in {1}.".format(name, module.__name__))


MOD_PREFIX = 'LaTeXTools.'
MOD_PREFIX = "LaTeXTools."

# these modules must be specified in the order they depend on one another
LOAD_ORDER = [
'external',
'external.bibtex',
'external.frozendict',
'external.latex_chars',

'latextools_plugin_internal',

'latextools_utils',

"external",
"external.bibtex",
"external.frozendict",
"external.latex_chars",
"latextools_plugin_internal",
"latextools_utils",
# no internal dependencies
'latextools_utils.activity_indicator',
'latextools_utils.bibformat',
'latextools_utils.logging',
'latextools_utils.parser_utils',
'latextools_utils.settings',
'latextools_utils.utils',

"latextools_utils.activity_indicator",
"latextools_utils.bibformat",
"latextools_utils.logging",
"latextools_utils.parser_utils",
"latextools_utils.settings",
"latextools_utils.utils",
# depend on previous only
'latextools_utils.cache',
'latextools_utils.distro_utils',
'latextools_utils.external_command',
'latextools_utils.internal_types',
'latextools_utils.quickpanel',
'latextools_utils.selectors',

"latextools_utils.cache",
"latextools_utils.distro_utils",
"latextools_utils.external_command",
"latextools_utils.internal_types",
"latextools_utils.quickpanel",
"latextools_utils.selectors",
# depend on any previous
'latextools_utils.sublime_utils',
'latextools_utils.is_tex_file',
'latextools_utils.tex_directives',
'latextools_utils.tex_log',

"latextools_utils.sublime_utils",
"latextools_utils.is_tex_file",
"latextools_utils.tex_directives",
"latextools_utils.tex_log",
# depend on any previous
'latextools_utils.analysis',
'latextools_utils.ana_utils',
'latextools_utils.output_directory',
'latextools_utils.bibcache',

'latextools_plugin',

"latextools_utils.analysis",
"latextools_utils.ana_utils",
"latextools_utils.output_directory",
"latextools_utils.bibcache",
"latextools_plugin",
# ensure latex_fill_all is loaded before the modules that depend on it
'latex_fill_all',

"latex_fill_all",
# preview related modules
'st_preview.preview_utils',
'st_preview.preview_threading',
"st_preview.preview_utils",
"st_preview.preview_threading",
]

EXPORT_MODULES = [
'latextools_utils.input_quickpanel',
'st_preview.preview_math',
'st_preview.preview_image'
"latextools_utils.input_quickpanel",
"st_preview.preview_math",
"st_preview.preview_image",
]

LOAD_ORDER += EXPORT_MODULES
Expand All @@ -107,7 +98,7 @@ def plugin_loaded():
logging.init()

# reload any plugins cached in memory
mods = [m for m in sys.modules if m.startswith('_latextools_')]
mods = [m for m in sys.modules if m.startswith("_latextools_")]
for mod in mods:
del sys.modules[mod]

Expand Down
17 changes: 8 additions & 9 deletions 02_temp_file_cleanup.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,27 +11,26 @@
# here we cleanup any directories listed in the temporary_output_dirs
# file as having been previously created by the plugin


def plugin_loaded():
temporary_output_dirs = os.path.join(
sublime.cache_path(),
'LaTeXTools',
'temporary_output_dirs'
sublime.cache_path(), "LaTeXTools", "temporary_output_dirs"
)

if os.path.exists(temporary_output_dirs):
with open(temporary_output_dirs, 'r') as f:
with open(temporary_output_dirs, "r") as f:
data = json.load(f)

tempdir = tempfile.gettempdir()

try:
for directory in data['directories']:
for directory in data["directories"]:
# shutil.rmtree is a rather blunt tool, so here we try to
# ensure we are only deleting legitimate temporary files
if (
directory is None or
not isinstance(directory, str) or
not directory.startswith(tempdir)
directory is None
or not isinstance(directory, str)
or not directory.startswith(tempdir)
):
continue

Expand All @@ -40,7 +39,7 @@ def plugin_loaded():
except OSError:
pass
else:
logger.info('Deleted old temp directory %s', directory)
logger.info("Deleted old temp directory %s", directory)
except KeyError:
pass

Expand Down
15 changes: 7 additions & 8 deletions auto_label.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"LatextoolsAutoInserLabelListener",
]


def _RE_FIND_SECTION(command_mapping):
return re.compile(
r"\\(?P<command>" + "|".join(command_mapping.keys()) + r"|caption)"
Expand Down Expand Up @@ -72,7 +73,7 @@ def _find_label_content(view, pos, find_region):
else:
label_content = "label"
# change the label if we are inside a equation and it is not set already
if (label_type == "???" and view.match_selector(pos, "meta.environment.math")):
if label_type == "???" and view.match_selector(pos, "meta.environment.math"):
env_mapping = get_setting("auto_label_env_mapping", {})
label_type = env_mapping.get("<math>", "eq")
elif label_type == "???":
Expand Down Expand Up @@ -101,8 +102,7 @@ def run(self, edit):
line_above = view.line(view.line(pos).a - 1)
find_region = sublime.Region(line_above.a, pos)

label_type, label_content = _find_label_content(
view, pos, find_region)
label_type, label_content = _find_label_content(view, pos, find_region)

before_text, after_text = _create_surrounding_text(view, pos)

Expand All @@ -113,16 +113,14 @@ def run(self, edit):
"{before_text}" # leading \label{
"${{1:{label_type}}}:${{2:{label_content}}}"
"{after_text}" # trailing }
"$0"
.format(**locals())
"$0".format(**locals())
)
view.run_command("insert_snippet", {"contents": snippet})
else:
content = (
"{before_text}" # leading \label{
"{label_type}:{label_content}"
"{after_text}" # trailing }
.format(**locals())
"{after_text}".format(**locals()) # trailing }
)
view.insert(edit, pos, content)

Expand All @@ -139,5 +137,6 @@ def on_query_context(self, view, key, operator, operand, match_all):
else:
raise Exception(
"latextools.setting.auto_label_auto_trigger; "
"Invalid operator must be EQUAL or NOT_EQUAL.")
"Invalid operator must be EQUAL or NOT_EQUAL."
)
return result
93 changes: 33 additions & 60 deletions biblatex_crossref_completions.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,34 +14,21 @@
# constructing them here
#
# VALUE_REGEX is a common suffix to hand the `= {<value>,<value>}` part
VALUE_REGEX = (
r'(?!.*\})\s*(?P<ENTRIES>(?:,[^,]*)+\b)?\s*(?P<OPEN>\{)?'
r'(?P<EQUALS>\s*=\s*)?'
)
VALUE_REGEX = r"(?!.*\})\s*(?P<ENTRIES>(?:,[^,]*)+\b)?\s*(?P<OPEN>\{)?" r"(?P<EQUALS>\s*=\s*)?"

CROSSREF_REGEX = re.compile(
VALUE_REGEX + r'crossref'[::-1] + r'\b',
re.IGNORECASE
)
CROSSREF_REGEX = re.compile(VALUE_REGEX + r"crossref"[::-1] + r"\b", re.IGNORECASE)

BIBLATEX_REGEX = re.compile(
VALUE_REGEX +
r'(?:' + r'|'.join((s[::-1] for s in ('xref', 'related'))) + r')' + r'\b',
re.IGNORECASE
VALUE_REGEX + r"(?:" + r"|".join((s[::-1] for s in ("xref", "related"))) + r")" + r"\b",
re.IGNORECASE,
)

ENTRY_SET_REGEX = re.compile(
VALUE_REGEX + r'entryset'[::-1] + r'\b',
re.IGNORECASE
)
ENTRY_SET_REGEX = re.compile(VALUE_REGEX + r"entryset"[::-1] + r"\b", re.IGNORECASE)

XDATA_REGEX = re.compile(
VALUE_REGEX + r'xdata'[::-1] + r'\b',
re.IGNORECASE
)
XDATA_REGEX = re.compile(VALUE_REGEX + r"xdata"[::-1] + r"\b", re.IGNORECASE)

# set indicating entries that have their own special handling...
SPECIAL_ENTRIES = set(['@xdata', '@set'])
SPECIAL_ENTRIES = set(["@xdata", "@set"])


def _get_keys_by_type(view, valid_types):
Expand All @@ -51,19 +38,22 @@ def _get_keys_by_type(view, valid_types):
if callable(valid_types):
validator = valid_types
elif isinstance(valid_types, str):

def validator(s):
return s == valid_types

else:

def validator(s):
return s in valid_types

keys = []

contents = view.substr(sublime.Region(0, view.size()))
for entry_type, key in re.findall(
r'(@(?!preamble|comment|string)[a-zA-Z]+)\s*\{\s*([^,]+)\b',
r"(@(?!preamble|comment|string)[a-zA-Z]+)\s*\{\s*([^,]+)\b",
contents,
re.IGNORECASE
re.IGNORECASE,
):
if validator(entry_type):
keys.append(key)
Expand All @@ -78,15 +68,9 @@ def _get_keys_from_id_field(view):
contents = view.substr(sublime.Region(0, view.size()))
# TODO: Should probably figure out how to work out the entry-type
for ids in re.findall(
r'\bids\s*=\s*\{([^}]+)\}',
contents,
re.IGNORECASE | re.UNICODE | re.DOTALL
r"\bids\s*=\s*\{([^}]+)\}", contents, re.IGNORECASE | re.UNICODE | re.DOTALL
):
for key in re.findall(
r'\b([^,]+)\b',
ids,
re.IGNORECASE | re.UNICODE
):
for key in re.findall(r"\b([^,]+)\b", ids, re.IGNORECASE | re.UNICODE):
keys.append(key)

return keys
Expand All @@ -97,16 +81,15 @@ def _get_cite_keys_validator(s):


def get_cite_keys(view):
return _get_keys_by_type(view, _get_cite_keys_validator) + \
_get_keys_from_id_field(view)
return _get_keys_by_type(view, _get_cite_keys_validator) + _get_keys_from_id_field(view)


def get_xdata_keys(view):
return _get_keys_by_type(view, '@xdata')
return _get_keys_by_type(view, "@xdata")


def get_entryset_keys(view):
return _get_keys_by_type(view, '@set')
return _get_keys_by_type(view, "@set")


def get_text_to_cursor(view):
Expand All @@ -117,59 +100,49 @@ def get_text_to_cursor(view):

# builds the replacement string depending on the current context of the line
def _get_replacement(matcher, key):
if not matcher.group('ENTRIES'):
return '{0}{1}{2}{3}'.format(
'' if matcher.group('EQUALS') else '= ',
'' if matcher.group('OPEN') else '{',
if not matcher.group("ENTRIES"):
return "{0}{1}{2}{3}".format(
"" if matcher.group("EQUALS") else "= ",
"" if matcher.group("OPEN") else "{",
key,
'' if matcher.group('OPEN') else '}'
"" if matcher.group("OPEN") else "}",
)

return '{0}{1}'.format(
',' if matcher.group('ENTRIES')[0] != ',' else '',
key
)
return "{0}{1}".format("," if matcher.group("ENTRIES")[0] != "," else "", key)


def get_completions_if_matches(regex, line, get_key_list_func, view):
matcher = regex.match(line)
if matcher:
return (
[
(key, _get_replacement(matcher, key))
for key in sorted(set(get_key_list_func(view)))
],
sublime.INHIBIT_WORD_COMPLETIONS
[(key, _get_replacement(matcher, key)) for key in sorted(set(get_key_list_func(view)))],
sublime.INHIBIT_WORD_COMPLETIONS,
)
else:
return []


class BiblatexCrossrefCompletions(sublime_plugin.EventListener):
def on_query_completions(self, view, prefix, locations):
if not view.match_selector(locations[0], 'text.bibtex, text.biblatex'):
if not view.match_selector(locations[0], "text.bibtex, text.biblatex"):
return []

current_line = get_text_to_cursor(view)[::-1]

if current_line.startswith(prefix[::-1]):
current_line = current_line[len(prefix):]
current_line = current_line[len(prefix) :]

result = get_completions_if_matches(
CROSSREF_REGEX, current_line, get_cite_keys, view)
result = get_completions_if_matches(CROSSREF_REGEX, current_line, get_cite_keys, view)

if result:
return result

if not view.match_selector(locations[0], 'text.biblatex'):
if not view.match_selector(locations[0], "text.biblatex"):
return []

return (
get_completions_if_matches(
BIBLATEX_REGEX, current_line, get_cite_keys, view) or
get_completions_if_matches(
XDATA_REGEX, current_line, get_xdata_keys, view) or
get_completions_if_matches(
ENTRY_SET_REGEX, current_line, get_entryset_keys, view) or
[]
get_completions_if_matches(BIBLATEX_REGEX, current_line, get_cite_keys, view)
or get_completions_if_matches(XDATA_REGEX, current_line, get_xdata_keys, view)
or get_completions_if_matches(ENTRY_SET_REGEX, current_line, get_entryset_keys, view)
or []
)
Loading

0 comments on commit 79204d0

Please sign in to comment.