Skip to content

Commit

Permalink
feat: Set MKDOCS_CONFIG_DIR environment variable to build file path…
Browse files Browse the repository at this point in the history
… relative to it
  • Loading branch information
pawamoy committed Oct 17, 2023
1 parent 6f19f00 commit a2cbea5
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
32 changes: 32 additions & 0 deletions docs/usage/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -409,4 +409,36 @@ That makes for a very meta-markdown markup:
Of course "executing" Markdown (or rather, making it "literate") only makes sense when the source is shown as well.
## MkDocs integration
As seen in the [Configuration section](../index.md#configuration),
Markdown Exec can be configured directly as a MkDocs plugin:
```yaml
# mkdocs.yml
plugins:
- search
- markdown-exec
```
When configured this way, it will set a `MKDOCS_CONFIG_DIR` environment variable
that you can use in your code snippets to compute file paths as relative
to the MkDocs configuration file directory, instead of relative to the current
working directory. This will make it possible to use the `-f` option of MkDocs,
to build the documentation from a different directory than the repository root.
Example:
```python exec="1" source="material-block"
import os
config_dir = os.environ['MKDOCS_CONFIG_DIR']
# This will show my local path since I deploy docs from my machine:
print(f"Configuration file directory: `{config_dir}`")
```
The environment variable will be restored to its previous value, if any,
at the end of the build.
[material]: https://squidfunk.github.io/mkdocs-material/
6 changes: 6 additions & 0 deletions src/markdown_exec/mkdocs_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ def on_config(self, config: MkDocsConfig) -> MkDocsConfig | None:
Returns:
The modified config.
"""
self.mkdocs_config_dir = os.getenv("MKDOCS_CONFIG_DIR")
os.environ["MKDOCS_CONFIG_DIR"] = os.path.dirname(config["config_file_path"])
self.languages = self.config["languages"]
mdx_configs = config.setdefault("mdx_configs", {})
superfences = mdx_configs.setdefault("pymdownx.superfences", {})
Expand Down Expand Up @@ -97,3 +99,7 @@ def on_env( # noqa: D102
def on_post_build(self, *, config: MkDocsConfig) -> None: # noqa: ARG002,D102
MarkdownConverter.counter = 0
markdown_config.reset()
if self.mkdocs_config_dir is None:
os.environ.pop("MKDOCS_CONFIG_DIR", None)
else:
os.environ["MKDOCS_CONFIG_DIR"] = self.mkdocs_config_dir

0 comments on commit a2cbea5

Please sign in to comment.