plugin.py (2361B)
1 # Copyright (c) 2016-2021 Martin Donath <martin.donath@squidfunk.com> 2 3 # Permission is hereby granted, free of charge, to any person obtaining a copy 4 # of this software and associated documentation files (the "Software"), to 5 # deal in the Software without restriction, including without limitation the 6 # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or 7 # sell copies of the Software, and to permit persons to whom the Software is 8 # furnished to do so, subject to the following conditions: 9 10 # The above copyright notice and this permission notice shall be included in 11 # all copies or substantial portions of the Software. 12 13 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 # FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE 16 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 18 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 19 # IN THE SOFTWARE. 20 21 from mkdocs.contrib.search import SearchPlugin as BasePlugin 22 from mkdocs.contrib.search.search_index import SearchIndex as BaseIndex 23 24 # ----------------------------------------------------------------------------- 25 # Class 26 # ----------------------------------------------------------------------------- 27 28 # Search plugin with custom search index 29 class SearchPlugin(BasePlugin): 30 31 # Override to use a custom search index 32 def on_pre_build(self, config): 33 super().on_pre_build(config) 34 self.search_index = SearchIndex(**self.config) 35 36 # ----------------------------------------------------------------------------- 37 38 # Search index with support for additional fields 39 class SearchIndex(BaseIndex): 40 41 # Override to add additional fields for each page 42 def add_entry_from_context(self, page): 43 index = len(self._entries) 44 super().add_entry_from_context(page) 45 entry = self._entries[index] 46 47 # Add document tags 48 if page.meta.get("tags"): 49 entry["tags"] = page.meta["tags"] 50 51 # Add document boost for search 52 if "search" in page.meta: 53 search = page.meta["search"] 54 if "boost" in search: 55 entry["boost"] = search["boost"]