| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import logging |
| 4 |
import os |
| 5 |
from typing import TYPE_CHECKING, List |
| 6 |
|
| 7 |
from mkdocs import utils |
| 8 |
from mkdocs.config import base |
| 9 |
from mkdocs.config import config_options as c |
| 10 |
from mkdocs.contrib.search.search_index import SearchIndex |
| 11 |
from mkdocs.plugins import BasePlugin |
| 12 |
|
| 13 |
if TYPE_CHECKING: |
| 14 |
from mkdocs.config.defaults import MkDocsConfig |
| 15 |
from mkdocs.structure.pages import Page |
| 16 |
from mkdocs.utils.templates import TemplateContext |
| 17 |
|
| 18 |
|
| 19 |
log = logging.getLogger(__name__) |
| 20 |
base_path = os.path.dirname(os.path.abspath(__file__)) |
| 21 |
|
| 22 |
|
| 23 |
class LangOption(c.OptionallyRequired[List[str]]): |
| 24 |
"""Validate Language(s) provided in config are known languages.""" |
| 25 |
|
| 26 |
def get_lunr_supported_lang(self, lang): |
| 27 |
fallback = {'uk': 'ru'} |
| 28 |
for lang_part in lang.split("_"): |
| 29 |
lang_part = lang_part.lower() |
| 30 |
lang_part = fallback.get(lang_part, lang_part) |
| 31 |
if os.path.isfile(os.path.join(base_path, 'lunr-language', f'lunr.{lang_part}.js')): |
| 32 |
return lang_part |
| 33 |
|
| 34 |
def run_validation(self, value: object): |
| 35 |
if isinstance(value, str): |
| 36 |
value = [value] |
| 37 |
if not isinstance(value, list): |
| 38 |
raise c.ValidationError('Expected a list of language codes.') |
| 39 |
for lang in value[:]: |
| 40 |
if lang != 'en': |
| 41 |
lang_detected = self.get_lunr_supported_lang(lang) |
| 42 |
if not lang_detected: |
| 43 |
log.info(f"Option search.lang '{lang}' is not supported, falling back to 'en'") |
| 44 |
value.remove(lang) |
| 45 |
if 'en' not in value: |
| 46 |
value.append('en') |
| 47 |
elif lang_detected != lang: |
| 48 |
value.remove(lang) |
| 49 |
value.append(lang_detected) |
| 50 |
log.info(f"Option search.lang '{lang}' switched to '{lang_detected}'") |
| 51 |
return value |
| 52 |
|
| 53 |
|
| 54 |
class _PluginConfig(base.Config): |
| 55 |
lang = c.Optional(LangOption()) |
| 56 |
separator = c.Type(str, default=r'[\s\-]+') |
| 57 |
min_search_length = c.Type(int, default=3) |
| 58 |
prebuild_index = c.Choice((False, True, 'node', 'python'), default=False) |
| 59 |
indexing = c.Choice(('full', 'sections', 'titles'), default='full') |
| 60 |
|
| 61 |
|
| 62 |
class SearchPlugin(BasePlugin[_PluginConfig]): |
| 63 |
"""Add a search feature to MkDocs.""" |
| 64 |
|
| 65 |
def on_config(self, config: MkDocsConfig, **kwargs) -> MkDocsConfig: |
| 66 |
"""Add plugin templates and scripts to config.""" |
| 67 |
if config.theme.get('include_search_page'): |
| 68 |
config.theme.static_templates.add('search.html') |
| 69 |
if not config.theme.get('search_index_only'): |
| 70 |
path = os.path.join(base_path, 'templates') |
| 71 |
config.theme.dirs.append(path) |
| 72 |
if 'search/main.js' not in config.extra_javascript: |
| 73 |
config.extra_javascript.append('search/main.js') # type: ignore |
| 74 |
if self.config.lang is None: |
| 75 |
# lang setting undefined. Set default based on theme locale |
| 76 |
validate = _PluginConfig.lang.run_validation |
| 77 |
self.config.lang = validate(config.theme.locale.language) |
| 78 |
# The `python` method of `prebuild_index` is pending deprecation as of version 1.2. |
| 79 |
# TODO: Raise a deprecation warning in a future release (1.3?). |
| 80 |
if self.config.prebuild_index == 'python': |
| 81 |
log.info( |
| 82 |
"The 'python' method of the search plugin's 'prebuild_index' config option " |
| 83 |
"is pending deprecation and will not be supported in a future release." |
| 84 |
) |
| 85 |
return config |
| 86 |
|
| 87 |
def on_pre_build(self, config: MkDocsConfig, **kwargs) -> None: |
| 88 |
"""Create search index instance for later use.""" |
| 89 |
self.search_index = SearchIndex(**self.config) |
| 90 |
|
| 91 |
def on_page_context(self, context: TemplateContext, page: Page, **kwargs) -> None: |
| 92 |
"""Add page to search index.""" |
| 93 |
self.search_index.add_entry_from_context(page) |
| 94 |
|
| 95 |
def on_post_build(self, config: MkDocsConfig, **kwargs) -> None: |
| 96 |
"""Build search index.""" |
| 97 |
output_base_path = os.path.join(config.site_dir, 'search') |
| 98 |
search_index = self.search_index.generate_search_index() |
| 99 |
json_output_path = os.path.join(output_base_path, 'search_index.json') |
| 100 |
utils.write_file(search_index.encode('utf-8'), json_output_path) |
| 101 |
|
| 102 |
assert self.config.lang is not None |
| 103 |
if not config.theme.get('search_index_only'): |
| 104 |
# Include language support files in output. Copy them directly |
| 105 |
# so that only the needed files are included. |
| 106 |
files = [] |
| 107 |
if len(self.config.lang) > 1 or 'en' not in self.config.lang: |
| 108 |
files.append('lunr.stemmer.support.js') |
| 109 |
if len(self.config.lang) > 1: |
| 110 |
files.append('lunr.multi.js') |
| 111 |
if 'ja' in self.config.lang or 'jp' in self.config.lang: |
| 112 |
files.append('tinyseg.js') |
| 113 |
for lang in self.config.lang: |
| 114 |
if lang != 'en': |
| 115 |
files.append(f'lunr.{lang}.js') |
| 116 |
|
| 117 |
for filename in files: |
| 118 |
from_path = os.path.join(base_path, 'lunr-language', filename) |
| 119 |
to_path = os.path.join(output_base_path, filename) |
| 120 |
utils.copy_file(from_path, to_path) |