| |
|
|
| |
| |
| |
| |
| |
| |
|
|
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
|
|
| import json |
| import logging |
| import os |
| import re |
| from backrefs import bre |
|
|
| from html import escape |
| from html.parser import HTMLParser |
| from mkdocs import utils |
| from mkdocs.config.config_options import SubConfig |
| from mkdocs.plugins import BasePlugin |
|
|
| from .config import SearchConfig, SearchFieldConfig |
|
|
| try: |
| import jieba |
| except ImportError: |
| jieba = None |
|
|
| |
| |
| |
|
|
| |
| class SearchPlugin(BasePlugin[SearchConfig]): |
|
|
| |
| def __init__(self, *args, **kwargs): |
| super().__init__(*args, **kwargs) |
|
|
| |
| self.is_dirty = False |
| self.is_dirtyreload = False |
|
|
| |
| self.search_index_prev = None |
|
|
| |
| def on_startup(self, *, command, dirty): |
| self.is_dirty = dirty |
|
|
| |
| def on_config(self, config): |
| if not self.config.enabled: |
| return |
|
|
| |
| if not self.config.lang: |
| self.config.lang = [self._translate( |
| config, "search.config.lang" |
| )] |
|
|
| |
| if not self.config.separator: |
| self.config.separator = self._translate( |
| config, "search.config.separator" |
| ) |
|
|
| |
| if self.config.pipeline is None: |
| self.config.pipeline = list(filter(len, re.split( |
| r"\s*,\s*", self._translate(config, "search.config.pipeline") |
| ))) |
|
|
| |
| validator = SubConfig(SearchFieldConfig) |
| for config in self.config.fields.values(): |
| validator.run_validation(config) |
|
|
| |
| if "title" not in self.config.fields: |
| self.config.fields["title"] = { "boost": 1e3 } |
| if "text" not in self.config.fields: |
| self.config.fields["text"] = { "boost": 1e0 } |
| if "tags" not in self.config.fields: |
| self.config.fields["tags"] = { "boost": 1e6 } |
|
|
| |
| self.search_index = SearchIndex(**self.config) |
|
|
| |
| if self.config.jieba_dict: |
| path = os.path.normpath(self.config.jieba_dict) |
| if os.path.isfile(path): |
| jieba.set_dictionary(path) |
| log.debug(f"Loading jieba dictionary: {path}") |
| else: |
| log.warning( |
| f"Configuration error for 'search.jieba_dict': " |
| f"'{self.config.jieba_dict}' does not exist." |
| ) |
|
|
| |
| if self.config.jieba_dict_user: |
| path = os.path.normpath(self.config.jieba_dict_user) |
| if os.path.isfile(path): |
| jieba.load_userdict(path) |
| log.debug(f"Loading jieba user dictionary: {path}") |
| else: |
| log.warning( |
| f"Configuration error for 'search.jieba_dict_user': " |
| f"'{self.config.jieba_dict_user}' does not exist." |
| ) |
|
|
| |
| def on_page_context(self, context, *, page, config, nav): |
| if not self.config.enabled: |
| return |
|
|
| |
| self.search_index.add_entry_from_context(page) |
| page.content = re.sub( |
| r"\s?data-search-\w+=\"[^\"]+\"", |
| "", |
| page.content |
| ) |
|
|
| |
| def on_post_build(self, *, config): |
| if not self.config.enabled: |
| return |
|
|
| |
| base = os.path.join(config.site_dir, "search") |
| path = os.path.join(base, "search_index.json") |
|
|
| |
| data = self.search_index.generate_search_index(self.search_index_prev) |
| utils.write_file(data.encode("utf-8"), path) |
|
|
| |
| if self.is_dirty: |
| self.search_index_prev = self.search_index |
|
|
| |
| def on_serve(self, server, *, config, builder): |
| self.is_dirtyreload = self.is_dirty |
|
|
| |
|
|
| |
| def _translate(self, config, value): |
| env = config.theme.get_env() |
|
|
| |
| language = "partials/language.html" |
| template = env.get_template(language, None, { "config": config }) |
| return template.module.t(value) |
|
|
| |
|
|
| |
| class SearchIndex: |
|
|
| |
| def __init__(self, **config): |
| self.config = config |
| self.entries = [] |
|
|
| |
| def add_entry_from_context(self, page): |
| search = page.meta.get("search") or {} |
| if search.get("exclude"): |
| return |
|
|
| |
| parser = Parser() |
| parser.feed(page.content) |
| parser.close() |
|
|
| |
| for section in parser.data: |
| if not section.is_excluded(): |
| self.create_entry_for_section(section, page.toc, page.url, page) |
|
|
| |
| def create_entry_for_section(self, section, toc, url, page): |
| item = self._find_toc_by_id(toc, section.id) |
| if item: |
| url = url + item.url |
| elif section.id: |
| url = url + "#" + section.id |
|
|
| |
| |
| |
| |
| if not section.title: |
| section.title = [str(page.meta.get("title", page.title))] |
|
|
| |
| title = "".join(section.title).strip() |
| text = "".join(section.text).strip() |
|
|
| |
| if jieba: |
| title = self._segment_chinese(title) |
| text = self._segment_chinese(text) |
|
|
| |
| entry = { |
| "location": url, |
| "title": title, |
| "text": text |
| } |
|
|
| |
| tags = page.meta.get("tags") |
| if isinstance(tags, list): |
| entry["tags"] = [] |
| for name in tags: |
| if name and isinstance(name, (str, int, float, bool)): |
| entry["tags"].append(str(name)) |
|
|
| |
| search = page.meta.get("search") or {} |
| if "boost" in search: |
| entry["boost"] = search["boost"] |
|
|
| |
| self.entries.append(entry) |
|
|
| |
| def generate_search_index(self, prev): |
| config = { |
| key: self.config[key] |
| for key in ["lang", "separator", "pipeline", "fields"] |
| } |
|
|
| |
| |
| |
| |
| |
| |
| if prev and self.entries: |
| path = self.entries[0]["location"] |
|
|
| |
| |
| |
| |
| |
| |
| entries = [ |
| entry for entry in prev.entries |
| if not entry["location"].startswith(path) |
| ] |
|
|
| |
| self.entries = entries + self.entries |
|
|
| |
| if prev and not self.entries: |
| self.entries = prev.entries |
|
|
| |
| data = { "config": config, "docs": self.entries } |
| return json.dumps( |
| data, |
| separators = (",", ":"), |
| default = str |
| ) |
|
|
| |
|
|
| |
| def _find_toc_by_id(self, toc, id): |
| for toc_item in toc: |
| if toc_item.id == id: |
| return toc_item |
|
|
| |
| toc_item = self._find_toc_by_id(toc_item.children, id) |
| if toc_item is not None: |
| return toc_item |
|
|
| |
| return None |
|
|
| |
| def _segment_chinese(self, data): |
| expr = bre.compile(r"(\p{script: Han}+)", bre.UNICODE) |
|
|
| |
| def replace(match): |
| value = match.group(0) |
|
|
| |
| |
| return "".join([ |
| "\u200b", |
| "\u200b".join(jieba.cut(value.encode("utf-8"))), |
| "\u200b", |
| ]) |
|
|
| |
| return expr.sub(replace, data).strip("\u200b") |
|
|
| |
|
|
| |
| class Element: |
| """ |
| An element with attributes, essentially a small wrapper object for the |
| parser to access attributes in other callbacks than handle_starttag. |
| """ |
|
|
| |
| def __init__(self, tag, attrs = None): |
| self.tag = tag |
| self.attrs = attrs or {} |
|
|
| |
| def __repr__(self): |
| return self.tag |
|
|
| |
| def __eq__(self, other): |
| if other is Element: |
| return self.tag == other.tag |
| else: |
| return self.tag == other |
|
|
| |
| def __hash__(self): |
| return hash(self.tag) |
|
|
| |
| def is_excluded(self): |
| return "data-search-exclude" in self.attrs |
|
|
| |
|
|
| |
| class Section: |
| """ |
| A block of text with markup, preceded by a title (with markup), i.e., a |
| headline with a certain level (h1-h6). Internally used by the parser. |
| """ |
|
|
| |
| def __init__(self, el, depth = 0): |
| self.el = el |
| self.depth = depth |
|
|
| |
| self.text = [] |
| self.title = [] |
| self.id = None |
|
|
| |
| def __repr__(self): |
| if self.id: |
| return "#".join([self.el.tag, self.id]) |
| else: |
| return self.el.tag |
|
|
| |
| def is_excluded(self): |
| return self.el.is_excluded() |
|
|
| |
|
|
| |
| class Parser(HTMLParser): |
| """ |
| This parser divides the given string of HTML into a list of sections, each |
| of which are preceded by a h1-h6 level heading. A white- and blacklist of |
| tags dictates which tags should be preserved as part of the index, and |
| which should be ignored in their entirety. |
| """ |
|
|
| |
| def __init__(self, *args, **kwargs): |
| super().__init__(*args, **kwargs) |
|
|
| |
| self.skip = set([ |
| "object", |
| "script", |
| "style" |
| ]) |
|
|
| |
| self.keep = set([ |
| "p", |
| "code", "pre", |
| "li", "ol", "ul", |
| "sub", "sup" |
| ]) |
|
|
| |
| self.context = [] |
| self.section = None |
|
|
| |
| self.data = [] |
|
|
| |
| def handle_starttag(self, tag, attrs): |
| attrs = dict(attrs) |
|
|
| |
| el = Element(tag, attrs) |
| if not tag in void: |
| self.context.append(el) |
| else: |
| return |
|
|
| |
| if tag in ([f"h{x}" for x in range(1, 7)]): |
| depth = len(self.context) |
| if "id" in attrs: |
|
|
| |
| if tag != "h1" and not self.data: |
| self.section = Section(Element("hx"), depth) |
| self.data.append(self.section) |
|
|
| |
| self.section = Section(el, depth) |
| if self.data: |
| self.section.id = attrs["id"] |
|
|
| |
| self.data.append(self.section) |
|
|
| |
| if not self.section: |
| self.section = Section(Element("hx")) |
| self.data.append(self.section) |
|
|
| |
| for key, value in attrs.items(): |
|
|
| |
| if key == "data-search-exclude": |
| self.skip.add(el) |
| return |
|
|
| |
| if key == "class" and value == "linenodiv": |
| self.skip.add(el) |
| return |
|
|
| |
| if not self.skip.intersection(self.context) and tag in self.keep: |
|
|
| |
| data = self.section.text |
| if self.section.el in self.context: |
| data = self.section.title |
|
|
| |
| data.append(f"<{tag}>") |
|
|
| |
| def handle_endtag(self, tag): |
| if not self.context or self.context[-1] != tag: |
| return |
|
|
| |
| |
| |
| |
| if self.section.depth > len(self.context): |
| for section in reversed(self.data): |
| if section.depth <= len(self.context): |
|
|
| |
| |
| self.section.depth = float("inf") |
| self.section = section |
| break |
|
|
| |
| el = self.context.pop() |
| if el in self.skip: |
| if el.tag not in ["script", "style", "object"]: |
| self.skip.remove(el) |
| return |
|
|
| |
| if not self.skip.intersection(self.context) and tag in self.keep: |
|
|
| |
| data = self.section.text |
| if self.section.el in self.context: |
| data = self.section.title |
|
|
| |
| index = data.index(f"<{tag}>") |
| for i in range(index + 1, len(data)): |
| if not data[i].isspace(): |
| index = len(data) |
| break |
|
|
| |
| if len(data) > index: |
| while len(data) > index: |
| data.pop() |
|
|
| |
| else: |
| data.append(f"</{tag}>") |
|
|
| |
| def handle_data(self, data): |
| if self.skip.intersection(self.context): |
| return |
|
|
| |
| if not "pre" in self.context: |
| if not data.isspace(): |
| data = data.replace("\n", " ") |
| else: |
| data = " " |
|
|
| |
| if not self.section: |
| self.section = Section(Element("hx")) |
| self.data.append(self.section) |
|
|
| |
| if self.section.el in self.context: |
| permalink = False |
| for el in self.context: |
| if el.tag == "a" and el.attrs.get("class") == "headerlink": |
| permalink = True |
|
|
| |
| if not permalink: |
| self.section.title.append( |
| escape(data, quote = False) |
| ) |
|
|
| |
| elif data.isspace(): |
| if not self.section.text or not self.section.text[-1].isspace(): |
| self.section.text.append(data) |
| elif "pre" in self.context: |
| self.section.text.append(data) |
|
|
| |
| else: |
| self.section.text.append( |
| escape(data, quote = False) |
| ) |
|
|
| |
| |
| |
|
|
| |
| log = logging.getLogger("mkdocs.material.search") |
|
|
| |
| void = set([ |
| "area", |
| "base", |
| "br", |
| "col", |
| "embed", |
| "hr", |
| "img", |
| "input", |
| "link", |
| "meta", |
| "param", |
| "source", |
| "track", |
| "wbr" |
| ]) |
|
|