pelican Documentation

Static site generator that supports Markdown and reST syntax. Powered by Python.

13,361 stars Python Python 16 files ยท ~58,730 tokens #pelican#python#static-site-generator
RAW Doc

Technical Documentation: getpelican/pelican

โ„น๏ธ Provenance: Multi-Tier Ingestion ยท CodeWiki Reference

Changelog (`docs/changelog.rst`)

Release history
###############

4.12.0 - 2026-04-20

  • Add dark mode to notmyidea template (#3490) <https://github.com/getpelican/pelican/pull/3490>_
  • Support CSS_FILE setting in Simple theme (#3555) <https://github.com/getpelican/pelican/pull/3555>_
  • Improve Simple theme template inheritance (#3570) <https://github.com/getpelican/pelican/pull/3570>_
  • Strip table-of-contents elements from article summaries (#3512) <https://github.com/getpelican/pelican/pull/3512>_
  • Use slug in category/tag feed titles (#3569) <https://github.com/getpelican/pelican/pull/3569>_
  • Fix raising exceptions on filtered logs (#3547) <https://github.com/getpelican/pelican/pull/3547>_
  • Fix disabled category output (#3589) <https://github.com/getpelican/pelican/pull/3589>_
  • Fix default FEED_DOMAIN to fall back to SITEURL (#3477) <https://github.com/getpelican/pelican/pull/3477>_
  • Don't log feed warning if FEED_DOMAIN is set (#3544) <https://github.com/getpelican/pelican/pull/3544>_
  • Fix livereload import in docserve() task (#3583) <https://github.com/getpelican/pelican/pull/3583>_
  • Fix JavaScript MIME detection on Windows (#3594) <https://github.com/getpelican/pelican/pull/3594>_
  • Fix linking to individual settings in docs (#3458) <https://github.com/getpelican/pelican/pull/3458>_
  • Overhaul installation instructions; add pipx and uv (#3549) <https://github.com/getpelican/pelican/pull/3549>_
  • Enhance GitHub Pages workflow (#3452) <https://github.com/getpelican/pelican/pull/3452>_ & (#3529) <https://github.com/getpelican/pelican/pull/3529>_
  • Require Docutils 0.22+ and Sphinx 9.0+ (#3579) <https://github.com/getpelican/pelican/pull/3579>_
  • Require Python 3.11 and above; add Python 3.14 to test matrix (#3514) <https://github.com/getpelican/pelican/pull/3514>_

4.11.0 - 2025-01-15

  • Add setting to selectively omit Typogrify filters (#3439) <https://github.com/getpelican/pelican/pull/3439>_
  • Add more blocks to the Simple themeโ€™s base template, making it easier to create new themes by inheriting from the Simple theme (#3405) <https://github.com/getpelican/pelican/pull/3405>_
  • Fix auto-reload behavior upon changes to the theme, content or settings. Make default IGNORE_FILES recursively ignore all hidden files as well as the default filters <https://watchfiles.helpmanual.io/api/filters/#watchfiles.DefaultFilter.ignore_dirs>_ from watchfiles.DefaultFilter. (#3441) <https://github.com/getpelican/pelican/pull/3441>_
  • Get current year from the SOURCE_DATE_EPOCH environment variable, if available (#3430) <https://github.com/getpelican/pelican/pull/3430>_
  • Add Python 3.13 to test matrix and remove Python 3.8 (#3435) <https://github.com/getpelican/pelican/pull/3435>_
  • Require Typogrify 2.1+ and Pygments <2.19

4.10.2 - 2024-11-27

  • Change IGNORE_FILES setting default to ignore all hidden files
  • Fix SUMMARY_MAX_PARAGRAPHS not being respected in some combinations with SUMMARY_MAX_LENGTH

4.10.1 - 2024-09-28

  • Fix error when running pelican -r -l
  • Fix symlink handling in pelican-themes

4.10.0 - 2024-09-16

  • Add setting to specify summary via paragraph count
  • Add new status to skip generation of a post
  • Add setting to append ref parameter to links in feeds
  • Configure logging handler via --log-handler CLI option
  • Resolve intra-site links in summaries
  • Warn when files are not processed due to disabled readers
  • Add Medium post importer
  • Improve GitHub Pages workflow
  • Improve code test coverage
  • Translate documentation into Simplified Chinese

4.9.1 - 2023-11-15

  • Ensure tzdata dependency is installed on Windows

4.9.0 - 2023-11-12

  • Upgrade code to new minimum supported Python version: 3.8
  • Settings support for pathlib.Path (#2758) <https://github.com/getpelican/pelican/pull/2758>_
  • Various improvements to Simple theme (#2976 <https://github.com/getpelican/pelican/pull/2976>_ & #3234 <https://github.com/getpelican/pelican/pull/3234>_)
  • Use Furo as Sphinx documentation theme (#3023) <https://github.com/getpelican/pelican/pull/3023>_
  • Default to 100 articles maximum in feeds (#3127) <https://github.com/getpelican/pelican/pull/3127>_
  • Add period_archives common context variable (#3148) <https://github.com/getpelican/pelican/pull/3148>_
  • Use watchfiles as the file-watching backend (#3151) <https://github.com/getpelican/pelican/pull/3151>_
  • Add GitHub Actions workflow for GitHub Pages (#3189) <https://github.com/getpelican/pelican/pull/3189>_
  • Allow dataclasses in settings (#3204) <https://github.com/getpelican/pelican/pull/3204>_
  • Switch build tool to PDM instead of Setuptools/Poetry (#3220) <https://github.com/getpelican/pelican/pull/3220>_
  • Provide a plugin_enabled Jinja test for themes (#3235) <https://github.com/getpelican/pelican/pull/3235>_
  • Preserve connection order in Blinker (#3238) <https://github.com/getpelican/pelican/pull/3238>_
  • Remove social icons from default notmyidea theme (#3240) <https://github.com/getpelican/pelican/pull/3240>_
  • Remove unreliable WRITE_SELECTED feature (#3243) <https://github.com/getpelican/pelican/pull/3243>_
  • Importer: Report broken embedded video links when importing from Tumblr (#3177) <https://github.com/getpelican/pelican/issues/3177>_
  • Importer: Remove newline addition when iterating Photo post types (#3178) <https://github.com/getpelican/pelican/issues/3178>_
  • Importer: Force timestamp conversion in Tumblr importer to be UTC with offset (#3221) <https://github.com/getpelican/pelican/pull/3221>_
  • Importer: Use tempfile for intermediate HTML file for Pandoc (#3221) <https://github.com/getpelican/pelican/pull/3221>_
  • Switch linters to Ruff (#3223) <https://github.com/getpelican/pelican/pull/3223>_

4.8.0 - 2022-07-11

  • Use JSON values for extra settings in Invoke tasks template (#2994) <https://github.com/getpelican/pelican/pull/2994>_
  • Add content tag for links, which can help with things like Twitter social cards (#3001) <https://github.com/getpelican/pelican/pull/3001>_
  • Improve word count behavior when generating summary (#3002) <https://github.com/getpelican/pelican/pull/3002>_

4.7.2 - 2022-02-09

  • Fix incorrect parsing of parameters specified via -e / --extra-settings option flags (#2938) <https://github.com/getpelican/pelican/pull/2938>_
  • Add categories.html template to default theme (#2973) <https://github.com/getpelican/pelican/pull/2973>_
  • Document how to use plugins to inject content (#2922) <https://github.com/getpelican/pelican/pull/2922>_

4.7.1 - 2021-10-12

  • Extend rich logging to server component (#2927) <https://github.com/getpelican/pelican/pull/2927>_
  • Fix an issue where metadata flagged to be discarded was being cached (#2926) <https://github.com/getpelican/pelican/pull/2926>_
  • Adjust suffix in server to allow redirection when needed (#2931) <https://github.com/getpelican/pelican/pull/2931>_
  • Add MIME types for web fonts (#2929) <https://github.com/getpelican/pelican/pull/2929>_
  • Distribute sample data used to run tests (#2935) <https://github.com/getpelican/pelican/pull/2935>_
  • Add Python 3.10 to test matrix

4.7.0 - 2021-10-01

  • Improve default theme rendering on mobile and other small screen devices (#2914) <https://github.com/getpelican/pelican/pull/2914>_
  • Add support for hidden articles (#2866) <https://github.com/getpelican/pelican/pull/2866>_
  • Improve word count behavior when generating summary CJK & other locales (#2864) <https://github.com/getpelican/pelican/pull/2864>_
  • Add progress spinner during generation (#2869) <https://github.com/getpelican/pelican/pull/2869>_
    and richer logging (#2897) <https://github.com/getpelican/pelican/pull/2897>, both via Rich <https://github.com/willmcgugan/rich>
  • Invoke tasks serve and livereload now auto-open a web browser pointing to the locally-served web site (#2764) <https://github.com/getpelican/pelican/pull/2764>_
  • Support some date format codes used by ISO dates (#2902) <https://github.com/getpelican/pelican/pull/2902>_
  • Document how to add a new writer (#2901) <https://github.com/getpelican/pelican/pull/2901>_

4.6.0 - 2021-03-23

  • Add new URL pattern to PAGINATION_PATTERNS for the last page in the list (#1401) <https://github.com/getpelican/pelican/issues/1401>_
  • Speed up livereload Invoke task via caching (#2847) <https://github.com/getpelican/pelican/pull/2847>_
  • Ignore None return value from get_generators signal (#2850) <https://github.com/getpelican/pelican/pull/2850>_
  • Relax dependency minimum versions and remove upper bounds

4.5.4 - 2021-01-04

Replace plugin definitions in settings with string representations after registering, so they can be cached correctly (#2828) <https://github.com/getpelican/pelican/issues/2828>_.

4.5.3 - 2020-12-01

Fix a mistake made in PR #2821

4.5.2 - 2020-11-22

Improve logging of generators and writer loaders

4.5.1 - 2020-11-02

  • Refactor intra-site link discovery in order to match more permissively (#2646) <https://github.com/getpelican/pelican/issues/2646>_
  • Fix plugins running twice in auto-reload mode (#2817) <https://github.com/getpelican/pelican/issues/2817>_
  • Add notice to use from pelican import signals instead of import pelican.signals (#2805) <https://github.com/getpelican/pelican/issues/2805>_

4.5.0 - 2020-08-20

  • Add namespace plugin support; list plugins via pelican-plugins command
  • Override settings via -e / --extra-settings CLI option flags
  • Add settings for custom Jinja globals and tests
  • Customize article summary ellipsis via SUMMARY_END_SUFFIX setting
  • Customize Typogrify dash handling via new TYPOGRIFY_DASHES setting
  • Support Unicode when generating slugs
  • Support Asciidoc .adoc file generation in Pelican importer
  • Improve user experience when pelican --listen web server is quit
  • Improve Invoke tasks template
  • Include tests in source distributions
  • Switch CI from Travis to GitHub Actions
  • Remove support for Python 2.7

4.2.0 - 2019-10-17

  • Support inline SVGs; don't treat titles in SVGs as HTML titles
  • Add category to feeds (in addition to tags)
  • Improve content metadata field docs
  • Add docs for including other Markdown/reST files in content

4.1.3 - 2019-10-09

  • Fix quick-start docs regarding pelican --listen
  • Set default listen address to 127.0.0.1
  • Add extra/optional Markdown dependency to setup.py
  • Use correct SSH port syntax for rsync in tasks.py
  • Place all deprecated settings handling together
  • Add related project URLs for display on PyPI
  • Skip some tests on Windows that can't pass due to filesystem differences

4.1.2 - 2019-09-23

Fix pelican.settings.load_source to avoid caching issues - PR #2621

4.1.1 - 2019-08-23

  • Add AutoPub to auto-publish releases on PR merge
  • Add CSS classes for reStructuredText figures
  • Pass argv to Pelican main entrypoint
  • Set default content status to a blank string rather than None

4.1.0 - 2019-07-14

  • Live browser reload upon changed files (provided via Invoke task)
  • Add pyproject.toml, managed by Poetry
  • Support for invoking python -m pelican
  • Add relative source path attribute to content
  • Allow directories in EXTRA_PATH_METADATA
  • Add all_articles variable to period pages (for recent posts functionality)
  • Improve debug mode output
  • Remove blank or duplicate summaries from Atom feed
  • Fix bugs in pagination, pelican-import, pelican-quickstart, and feed importer

4.0.1 (2018-11-30)

  • Refactor pelican.server logging
  • Fix bug in which all static files were processed as "draft"
  • Bug fixes for Invoke/Makefile automation, Importer, and other miscellanea

If upgrading from 3.7.x or earlier, please note that slug-related settings in
4.0+ use {slug} and/or {lang} rather than %s. If %s-style
settings are encountered, Pelican will emit a warning and fall back to the
default setting. Some user-submitted themes might try to format setting values
but fail upon site build with a TypeError. In such cases, the theme needs
to be updated. For example, instead of TAG_FEED_ATOM|format(tag.slug), use
TAG_FEED_ATOM.format(slug=tag.slug)

4.0.0 (2018-11-13)

  • Replace develop_server.sh script with pelican --listen
  • Improved copy/link behavior for large static files (e.g., videos)
  • New {static} syntax to link to static content; content linked to by
    {static} and {attach} is automatically copied over even if not in
    STATIC_PATHS
  • Pages can now have draft status
  • Show current settings via new --print-settings flag
  • All settings for slugs now use {slug} and/or {lang} rather than
    %s. If %s-style settings are encountered, Pelican will emit a warning
    and fallback to the default setting.
  • New signals: feed_generated and page_generated_write_page
  • Replace Fabric with Invoke and fabfile.py template with tasks.py
  • Replace PAGINATED_DIRECT_TEMPLATES by PAGINATED_TEMPLATES, extending
    control over pagination to all templates and making page size variable
  • Replace SLUG_SUBSTITUTIONS (and friends) by SLUG_REGEX_SUBSTITUTIONS
    for more finegrained control
  • '{base_name}' value in PAGINATION_PATTERNS setting no longer strips
    'bar' from 'foo/bar.html' (unless 'bar' == 'index').
  • ARTICLE_ORDER_BY and PAGE_ORDER_BY now also affect 1) category, tag
    and author pages 2) feeds 3) draft and hidden articles and pages
  • New ARTICLE_TRANSLATION_ID and PAGE_TRANSLATION_ID settings to
    specify metadata attributes used to identify/disable translations
  • Make the HTML reader parse multiple occurrences of metadata tags as a list
  • New Blogger XML backup importer
  • Wordpress importer now updates file links to point to local copies if the
    files were downloaded with --wp-attach.
  • Importer no longer inserts extra newlines, to prevent breaking of HTML
    attributes.
  • Pelican server now prioritises foo.html and foo/index.html over
    foo/ when resolving foo.

3.7.1 (2017-01-10)

  • Fix locale issues in Quickstart script
  • Specify encoding for README and CHANGELOG in setup.py

3.7.0 (2016-12-12)

  • Atom feeds output <content> in addition to ````
  • Atom feeds use ```` for the original publication date and
    for modifications
  • Simplify Atom feed ID generation and support URL fragments
  • Produce category feeds with category-specific titles
  • RSS feeds now default to summary instead of full content;
    set RSS_FEED_SUMMARY_ONLY = False to revert to previous behavior
  • Replace MD_EXTENSIONS with MARKDOWN setting
  • Replace JINJA_EXTENSIONS with more-robust JINJA_ENVIRONMENT setting
  • Improve summary truncation logic to handle special characters and tags that
    span multiple lines, using HTML parser instead of regular expressions
  • Include summary when looking for intra-site link substitutions
  • Link to authors and index via {author}name and {index} syntax
  • Override widget names via LINKS_WIDGET_NAME and SOCIAL_WIDGET_NAME
  • Add INDEX_SAVE_AS option to override default index.html value
  • Remove PAGES context variable for themes in favor of pages
  • SLUG_SUBSTITUTIONS now accepts 3-tuple elements, allowing URL slugs to
    contain non-alphanumeric characters
  • Tag and category slugs can be controlled with greater precision using the
    TAG_SUBSTITUTIONS and CATEGORY_SUBSTITUTIONS settings
  • Author slugs can be controlled with greater precision using the
    AUTHOR_SUBSTITUTIONS setting
  • DEFAULT_DATE can be defined as a string
  • Use mtime instead of ctime when DEFAULT_DATE = 'fs'
  • Add --fatal=errors|warnings option for use with continuous integration
  • When using generator-level caching, ensure previously-cached files are
    processed instead of just new files.
  • Add Python and Pelican version information to debug output
  • Improve compatibility with Python 3.5
  • Comply with and enforce PEP8 guidelines
  • Replace tables in settings documentation with data:: directives

3.6.3 (2015-08-14)

  • Fix permissions issue in release tarball

3.6.2 (2015-08-01)

  • Fix installation errors related to Unicode in tests
  • Don't show pagination in notmyidea theme if there's only one page
  • Make hidden pages available in context
  • Improve URLWrapper comparison

3.6.0 (2015-06-15)

  • Disable caching by default in order to prevent potential confusion
  • Improve caching behavior, replacing pickle with cpickle
  • Allow Markdown or reST content in metadata fields other than summary
  • Support semicolon-separated author/tag lists
  • Improve flexibility of article sorting
  • Add --relative-urls argument
  • Support devserver listening on addresses other than localhost
  • Unify HTTP server handlers to pelican.server throughout
  • Handle intra-site links to draft posts
  • Move tag_cloud from core to plugin
  • Load default theme's external resources via HTTPS
  • Import drafts from WordPress XML
  • Improve support for Windows users
  • Enhance logging and test suite
  • Clean up and refactor codebase
  • New signals: all_generators_finalized and page_writer_finalized

3.5.0 (2014-11-04)

  • Introduce ARTICLE_ORDER_BY and PAGE_ORDER_BY settings to control the
    order of articles and pages.
  • Include time zone information in dates rendered in templates.
  • Expose the reader name in the metadata for articles and pages.
  • Add the ability to store static files along with content in the same
    directory as articles and pages using {attach} in the path.
  • Prevent Pelican from raising an exception when there are duplicate pieces of
    metadata in a Markdown file.
  • Introduce the TYPOGRIFY_IGNORE_TAGS setting to add HTML tags to be
    ignored by Typogrify.
  • Add the ability to use - in date formats to strip leading zeros. For
    example, %-d/%-m/%y will now result in the date 9/8/12.
  • Ensure feed generation is correctly disabled during quickstart configuration.
  • Fix PAGE_EXCLUDES and ARTICLE_EXCLUDES from incorrectly matching
    sub-directories.
  • Introduce STATIC_EXCLUDE setting to add static file excludes.
  • Fix an issue when using PAGINATION_PATTERNS while RELATIVE_URLS
    is enabled.
  • Fix feed generation causing links to use the wrong language for month
    names when using other locales.
  • Fix an issue where the authors list in the simple template wasn't correctly
    formatted.
  • Fix an issue when parsing non-string URLs from settings.
  • Improve consistency of debug and warning messages.

3.4.0 (2014-07-01)

  • Speed up content generation via new caching mechanism
  • Add selective post generation (instead of always building entire site)
  • Many documentation improvements, including switching to prettier RtD theme
  • Add support for multiple content and plugin paths
  • Add :modified: metadata field to complement :date:.
    Used to specify the last date and time an article was updated independently
    from the date and time it was published.
  • Add support for multiple authors via new :authors: metadata field
  • Watch for changes in static directories when in auto-regeneration mode
  • Add filters to limit log output when desired
  • Add language support to drafts
  • Add SLUGIFY_SOURCE setting to control how post slugs are generated
  • Fix many issues relating to locale and encoding
  • Apply Typogrify filter to post summary
  • Preserve file metadata (e.g. time stamps) when copying static files to output
  • Move AsciiDoc support from Pelican core into separate plugin
  • Produce inline links instead of reference-style links when importing content
  • Improve handling of IGNORE_FILES setting behavior
  • Properly escape symbol characters in tag names (e.g., C++)
  • Minor tweaks for Python 3.4 compatibility
  • Add several new signals

3.3.0 (2013-09-24)

  • Drop Python 3.2 support in favor of Python 3.3
  • Add Fabfile so Fabric can be used for workflow automation instead of Make
  • OUTPUT_RETENTION setting can be used to preserve metadata (e.g., VCS
    data such as .hg and .git) from being removed from output directory
  • Tumblr import
  • Improve logic and consistency when cleaning output folder
  • Improve documentation versioning and release automation
  • Improve pagination flexibility
  • Rename signals for better consistency (some plugins may need to be updated)
  • Move metadata extraction from generators to readers; metadata extraction no
    longer article-specific
  • Deprecate FILES_TO_COPY in favor of STATIC_PATHS and
    EXTRA_PATH_METADATA
  • Summaries in Markdown posts no longer include footnotes
  • Remove unnecessary whitespace in output via lstrip_blocks Jinja parameter
  • Move PDF generation from core to plugin
  • Replace MARKUP setting with READERS
  • Add warning if img tag is missing alt attribute
  • Add support for {} in relative links syntax, besides ||
  • Add support for {tag} and {category} relative links
  • Add a content_written signal

3.2.1 and 3.2.2

  • Facilitate inclusion in FreeBSD Ports Collection

3.2 (2013-04-24)

  • Support for Python 3!
  • Override page save-to location from meta-data (enables using a static page as
    the site's home page, for example)
  • Time period archives (per-year, per-month, and per-day archives of posts)
  • Posterous blog import
  • Improve WordPress blog import
  • Migrate plugins to separate repository
  • Improve HTML parser
  • Provide ability to show or hide categories from menu using
    DISPLAY_CATEGORIES_ON_MENU option
  • Auto-regeneration can be told to ignore files via IGNORE_FILES setting
  • Improve post-generation feedback to user
  • For multilingual posts, use meta-data to designate which is the original
    and which is the translation
  • Add .mdown to list of supported Markdown file extensions
  • Document-relative URL generation (RELATIVE_URLS) is now off by default

3.1 (2012-12-04)

  • Importer now stores slugs within files by default. This can be disabled with
    the --disable-slugs option.
  • Improve handling of links to intra-site resources
  • Ensure WordPress import adds paragraphs for all types of line endings
    in post content
  • Decode HTML entities within WordPress post titles on import
  • Improve appearance of LinkedIn icon in default theme
  • Add GitHub and Google+ social icons support in default theme
  • Optimize social icons
  • Add FEED_ALL_ATOM and FEED_ALL_RSS to generate feeds containing all
    posts regardless of their language
  • Split TRANSLATION_FEED into TRANSLATION_FEED_ATOM and
    TRANSLATION_FEED_RSS
  • Different feeds can now be enabled/disabled individually
  • Allow for blank author: if AUTHOR setting is not set, author won't
    default to ${USER} anymore, and a post won't contain any author
    information if the post author is empty
  • Move LESS and Webassets support from Pelican core to plugin
  • The DEFAULT_DATE setting now defaults to None, which means that
    articles won't be generated unless date metadata is specified
  • Add FILENAME_METADATA setting to support metadata extraction from
    filename
  • Add gzip_cache plugin to compress common text files into a .gz
    file within the same directory as the original file, preventing the server
    (e.g. Nginx) from having to compress files during an HTTP call
  • Add support for AsciiDoc-formatted content
  • Add USE_FOLDER_AS_CATEGORY setting so that feature can be toggled on/off
  • Support arbitrary Jinja template files
  • Restore basic functional tests
  • New signals: generator_init, get_generators, and
    article_generate_preread

3.0 (2012-08-08)

  • Refactored the way URLs are handled
  • Improved the English documentation
  • Fixed packaging using setuptools entrypoints
  • Added typogrify support
  • Added a way to disable feed generation
  • Added support for DIRECT_TEMPLATES
  • Allow multiple extensions for content files
  • Added LESS support
  • Improved the import script
  • Added functional tests
  • Rsync support in the generated Makefile
  • Improved feed support (easily pluggable with Feedburner for instance)
  • Added support for abbr in reST
  • Fixed a bunch of bugs :-)

2.8 (2012-02-28)

  • Dotclear importer
  • Allow the usage of Markdown extensions
  • Themes are now easily extensible
  • Don't output pagination information if there is only one page
  • Add a page per author, with all their articles
  • Improved the test suite
  • Made the themes easier to extend
  • Removed Skribit support
  • Added a pelican-quickstart script
  • Fixed timezone-related issues
  • Added some scripts for Windows support
  • Date can be specified in seconds
  • Never fail when generating posts (skip and continue)
  • Allow the use of future dates
  • Support having different timezones per language
  • Enhanced the documentation

2.7 (2011-06-11)

  • Use logging rather than echoing to stdout
  • Support custom Jinja filters
  • Compatibility with Python 2.5
  • Added a theme manager
  • Packaged for Debian
  • Added draft support

2.6 (2011-03-08)

  • Changes in the output directory structure
  • Makes templates easier to work with / create
  • Added RSS support (was Atom-only)
  • Added tag support for the feeds
  • Enhance the documentation
  • Added another theme (brownstone)
  • Added translations
  • Added a way to use cleaner URLs with a rewrite url module (or equivalent)
  • Added a tag cloud
  • Added an autoreloading feature: the blog is automatically regenerated each
    time a modification is detected
  • Translate the documentation into French
  • Import a blog from an RSS feed
  • Pagination support
  • Added Skribit support

2.5 (2010-11-20)

  • Import from WordPress
  • Added some new themes (martyalchin / wide-notmyidea)
  • First bug report!
  • Linkedin support
  • Added a FAQ
  • Google Analytics support
  • Twitter support
  • Use relative URLs, not static ones

2.4 (2010-11-06)

  • Minor themes changes
  • Add Disqus support (so we have comments)
  • Another code refactoring
  • Added config settings about pages
  • Blog entries can also be generated in PDF

2.3 (2010-10-31)

  • Markdown support

2.2 (2010-10-30)

  • Prettify output
  • Manages static pages as well

2.1 (2010-10-30)

  • Make notmyidea the default theme

2.0 (2010-10-30)

  • Refactoring to be more extensible
  • Change into the setting variables

1.2 (2010-09-28)

  • Added a debug option
  • Added per-category feeds
  • Use filesystem to get dates if no metadata is provided
  • Add Pygments support

1.1 (2010-08-19)

  • First working version

Content (`docs/content.rst`)

Writing content
###############

Articles and pages

Pelican considers "articles" to be chronological content, such as posts on a
blog, and thus associated with a date.

The idea behind "pages" is that they are usually not temporal in nature and are
used for content that does not change very often (e.g., "About" or "Contact"
pages).

You can find sample content in the repository at samples/content/.

.. _internal_metadata:

File metadata

Pelican tries to be smart enough to get the information it needs from the
file system (for instance, about the category of your articles), but some
information you need to provide in the form of metadata inside your files.

If you are writing your content in reStructuredText format, you can provide
this metadata in text files via the following syntax (give your file the
.rst extension)::

text
My super title
##############

:date: 2010-10-03 10:20
:modified: 2010-10-04 18:40
:tags: thats, awesome
:category: yeah
:slug: my-super-post
:authors: Alexis Metaireau, Conan Doyle
:summary: Short version for index and feeds

Author and tag lists may be semicolon-separated instead, which allows
you to write authors and tags containing commas::

text
:tags: pelican, publishing tool; pelican, bird
:authors: Metaireau, Alexis; Doyle, Conan

Pelican implements an extension to reStructuredText to enable support for the
abbr HTML tag. To use it, write something like this in your post::

text
This will be turned into :abbr:`HTML (HyperText Markup Language)`.

You can also use Markdown syntax (with a file ending in .md, .markdown,
.mkd, or .mdown). Markdown generation requires that you first
explicitly install the Python-Markdown_ package, which can be done via pip install Markdown.

Pelican also supports Markdown Extensions_, which might have to be installed
separately if they are not included in the default Markdown package and can
be configured and loaded via the MARKDOWN setting.

Metadata syntax for Markdown posts should follow this pattern::

text
Title: My super title
Date: 2010-12-03 10:20
Modified: 2010-12-05 19:30
Category: Python
Tags: pelican, publishing
Slug: my-super-post
Authors: Alexis Metaireau, Conan Doyle
Summary: Short version for index and feeds

This is the content of my super blog post.

You can also have your own metadata keys (so long as they don't conflict with
reserved metadata keywords) for use in your templates. The following table
contains a list of reserved metadata keywords:

=============== ===============================================================
Metadata Description
=============== ===============================================================
title Title of the article or page
date Publication date (e.g., YYYY-MM-DD HH:SS)
modified Modification date (e.g., YYYY-MM-DD HH:SS)
tags Content tags, separated by commas
keywords Content keywords, separated by commas (HTML content only)
category Content category (one only โ€” not multiple)
slug Identifier used in URLs and translations
author Content author, when there is only one
authors Content authors, when there are multiple
summary Brief description of content for index pages
lang Content language ID (en, fr, etc.)
translation If content is a translation of another (true or false)
status Content status: draft, hidden, skip, or published
template Name of template to use to generate content (without extension)
save_as Save content to this relative file path
url URL to use for this article/page
=============== ===============================================================

Readers for additional formats (such as AsciiDoc_) are available via plugins,
which you can find via the Pelican Plugins_ collection as well as the legacy
pelican-plugins_ repository.

Pelican can also process HTML files ending in .html and .htm. Pelican
interprets the HTML in a very straightforward manner, reading metadata from
meta tags, the title from the title tag, and the body out from the
body tag::

text
<html>
    <head>
        <title>My super title</title>
        <meta name="tags" content="thats, awesome" />
        <meta name="date" content="2012-07-09 22:28" />
        <meta name="modified" content="2012-07-10 20:14" />
        <meta name="category" content="yeah" />
        <meta name="authors" content="Alexis Mรฉtaireau, Conan Doyle" />
        <meta name="summary" content="Short version for index and feeds" />
    </head>
    
        This is the content of my super blog post.
    
</html>

With HTML, there is one simple exception to the standard metadata: tags can be
specified either via the tags metadata, as is standard in Pelican, or via
the keywords metadata, as is standard in HTML. The two can be used
interchangeably.

Note that, aside from the title, none of this content metadata is mandatory:
if the date is not specified and DEFAULT_DATE is set to 'fs', Pelican
will rely on the file's "mtime" timestamp, and the category can be determined
by the directory in which the file resides. For example, a file located at
python/foobar/myfoobar.rst will have a category of foobar. If you would
like to organize your files in other ways where the name of the subfolder would
not be a good category name, you can set the setting USE_FOLDER_AS_CATEGORY
to False. When parsing dates given in the page metadata, Pelican supports
the W3C's suggested subset ISO 8601__.

So the title is the only required metadata. If that bothers you, worry not.
Instead of manually specifying a title in your metadata each time, you can use
the source content file name as the title. For example, a Markdown source file
named Publishing via Pelican.md would automatically be assigned a title of
Publishing via Pelican. If you would prefer this behavior, add the following
line to your settings file::

text
FILENAME_METADATA = '(?P<title>.*)'

.. note::

When experimenting with different settings (especially the metadata
ones) caching may interfere and the changes may not be visible. In
such cases disable caching with LOAD_CONTENT_CACHE = False or
use the --ignore-cache command-line switch.

__ W3C ISO 8601_

modified should be last time you updated the article, and defaults to
date if not specified. Besides you can show modified in the templates,
feed entries in feed readers will be updated automatically when you set
modified to the current date after you modified your article.

authors is a comma-separated list of article authors. If there's only one
author you can use author field.

If you do not explicitly specify summary metadata for a given post, the
SUMMARY_MAX_LENGTH setting can be used to specify how many words from the
beginning of an article are used as the summary. You can also use an article's
first N paragraphs as its summary using the SUMMARY_MAX_PARAGRAPHS setting.
If both settings are in use, the specified number of paragraphs will
be used but may be truncated to respect the specified maximum length.

You can also extract any metadata from the filename through a regular
expression to be set in the FILENAME_METADATA setting. All named groups
that are matched will be set in the metadata object. The default value for the
FILENAME_METADATA setting will only extract the date from the filename. For
example, if you would like to extract both the date and the slug, you could set
something like: '(?P<date>\d{4}-\d{2}-\d{2})_(?P<slug>.*)'

Please note that the metadata available inside your files takes precedence over
the metadata extracted from the filename.

Pages

If you create a folder named pages inside the content folder, all the
files in it will be used to generate static pages, such as About or
Contact pages. (See example filesystem layout below.)

You can use the DISPLAY_PAGES_ON_MENU setting to control whether all those
pages are displayed in the primary navigation menu. (Default is True.)

If you want to exclude any pages from being linked to or listed in the menu,
then add a status: hidden attribute to its metadata. This is useful for
things like making error pages that fit the generated theme of your site.

Static content

Static files are files other than articles and pages that are copied to the
output folder as-is, without processing. You can control which static files
are copied over with the STATIC_PATHS setting of the project's
pelicanconf.py file. Pelican's default configuration includes the
images directory for this, but others must be added manually. In addition,
static files that are explicitly linked to are included (see below).

.. note::

In the default configuration, all files with a valid content file suffix
(.html, .rst, .md, ...) get processed by the article and page
generators before the static generator. This is avoided by altering the
*_EXCLUDE settings appropriately.

Mixed content in the same directory

Starting with Pelican 3.5, static files can safely share a source directory
with page source files, without exposing the page sources in the generated
site. Any such directory must be added to both STATIC_PATHS and
PAGE_PATHS (or STATIC_PATHS and ARTICLE_PATHS). Pelican will
identify and process the page source files normally, and copy the remaining
files as if they lived in a separate directory reserved for static files.

Note: Placing static and content source files together in the same source
directory does not guarantee that they will end up in the same place in the
generated site. The easiest way to do this is by using the {attach} link
syntax (described below). Alternatively, the STATIC_SAVE_AS,
PAGE_SAVE_AS, and ARTICLE_SAVE_AS settings (and the corresponding
*_URL settings) can be configured to place files of different types
together, just as they could in earlier versions of Pelican.

.. _ref-linking-to-internal-content:

Linking to internal content

From Pelican 3.1 onwards, it is now possible to specify intra-site links to
files in the source content hierarchy instead of files in the generated
hierarchy. This makes it easier to link from the current post to other content
that may be sitting alongside that post (instead of having to determine where
the other content will be placed after site generation).

To link to internal content (files in the content directory), use the
following syntax for the link target: {filename}path/to/file.
Note: forward slashes, /,
are the required path separator in the {filename} directive
on all operating systems, including Windows.

For example, a Pelican project might be structured like this::

text
website/
โ”œโ”€โ”€ content
โ”‚ย ย  โ”œโ”€โ”€ category/
โ”‚ย ย  โ”‚ย ย  โ””โ”€โ”€ article1.rst
โ”‚ย ย  โ”œโ”€โ”€ article2.md
โ”‚   โ””โ”€โ”€ pages
โ”‚ย ย   ย ย  โ””โ”€โ”€ about.md
โ””โ”€โ”€ pelican.conf.py

In this example, article1.rst could look like this::

text
The first article
#################

:date: 2012-12-01 10:02

See below intra-site link examples in reStructuredText format.

`a link relative to the current file <{filename}../article2.md>`_
`a link relative to the content root <{filename}/article2.md>`_

and article2.md::

text
Title: The second article
Date: 2012-12-01 10:02

See below intra-site link examples in Markdown format.

[a link relative to the current file]({filename}category/article1.rst)
[a link relative to the content root]({filename}/category/article1.rst)

Linking to static files

You can link to static content using {static}path/to/file. Files linked to
with this syntax will automatically be copied to the output directory, even if
the source directories containing them are not included in the STATIC_PATHS
setting of the project's pelicanconf.py file.

For example, a project's content directory might be structured like this::

text
content
โ”œโ”€โ”€ images
โ”‚ย ย  โ””โ”€โ”€ han.jpg
โ”œโ”€โ”€ pdfs
โ”‚ย ย  โ””โ”€โ”€ menu.pdf
โ””โ”€โ”€ pages
 ย ย  โ””โ”€โ”€ test.md

test.md would include::

text
[Our Menu]({static}/pdfs/menu.pdf)

Site generation would then copy han.jpg to output/images/han.jpg,
menu.pdf to output/pdfs/menu.pdf, and write the appropriate links
in test.md.

If you use {static} to link to an article or a page, this will be turned
into a link to its source code.

Attaching static files

Starting with Pelican 3.5, static files can be "attached" to a page or article
using this syntax for the link target: {attach}path/to/file. This works
like the {static} syntax, but also relocates the static file into the
linking document's output directory. If the static file originates from a
subdirectory beneath the linking document's source, that relationship will be
preserved on output. Otherwise, it will become a sibling of the linking
document.

This only works for linking to static files.

For example, a project's content directory might be structured like this::

text
content
โ”œโ”€โ”€ blog
โ”‚ย ย  โ”œโ”€โ”€ icons
โ”‚ย ย  โ”‚ย ย  โ””โ”€โ”€ icon.png
โ”‚ย ย  โ”œโ”€โ”€ photo.jpg
โ”‚ย ย  โ””โ”€โ”€ testpost.md
โ””โ”€โ”€ downloads
    โ””โ”€โ”€ archive.zip

pelicanconf.py would include::

text
PATH = 'content'
ARTICLE_PATHS = ['blog']
ARTICLE_SAVE_AS = '{date:%Y}/{slug}.html'
ARTICLE_URL = '{date:%Y}/{slug}.html'

testpost.md would include::

text
Title: Test Post
Category: test
Date: 2014-10-31



[Downloadable File]({attach}/downloads/archive.zip)

Site generation would then produce an output directory structured like this::

text
output
โ””โ”€โ”€ 2014
    โ”œโ”€โ”€ archive.zip
    โ”œโ”€โ”€ icons
    โ”‚ย ย  โ””โ”€โ”€ icon.png
    โ”œโ”€โ”€ photo.jpg
    โ””โ”€โ”€ test-post.html

Notice that all the files linked using {attach} ended up in or beneath
the article's output directory.

If a static file is linked multiple times, the relocating feature of
{attach} will only work in the first of those links to be processed.
After the first link, Pelican will treat {attach} like {static}.
This avoids breaking the already-processed links.

Be careful when linking to a file from multiple documents:
Since the first link to a file finalizes its location and Pelican does
not define the order in which documents are processed, using {attach} on a
file linked by multiple documents can cause its location to change from one
site build to the next. (Whether this happens in practice will depend on the
operating system, file system, version of Pelican, and documents being added,
modified, or removed from the project.) Any external sites linking to the
file's old location might then find their links broken. It is therefore
advisable to use {attach} only if you use it in all links to a file, and only
if the linking documents share a single directory.
Under these conditions,
the file's output location will not change in future builds. In cases where
these precautions are not possible, consider using {static} links instead
of {attach}, and letting the file's location be determined by the project's
STATIC_SAVE_AS and STATIC_URL settings. (Per-file save_as and
url overrides can still be set in EXTRA_PATH_METADATA.)

.. note::
When using {attach}, any parent directory in *_URL / *_SAVE_AS
settings should match each other. See also: :ref:url-settings

Linking to authors, categories, index and tags

You can link to authors, categories, index and tags using the {author}name,
{category}foobar, {index} and {tag}tagname syntax.

To remain compatible with earlier versions, Pelican still supports vertical
bars (||) in addition to curly braces ({}) for internal links. For
example: |filename|an_article.rst, |tag|tagname, |category|foobar.
The syntax was changed from || to {} to avoid collision with Markdown
extensions or reST directives. Similarly, Pelican also still supports linking
to static content with {filename}. The syntax was changed to {static}
to allow linking to both generated articles and pages and their static sources.

Support for the old syntax may eventually be removed.

Including other files

Both Markdown and reStructuredText syntaxes provide mechanisms for this.

Following below are some examples for reStructuredText using the include directive_:

text
.. code-block:: rst

    .. include:: file.rst

Include a fragment of a file delimited by two identifiers, highlighted as C++ (slicing based on line numbers is also possible):

text
.. code-block:: rst

    .. include:: main.cpp
        :code: c++
        :start-after: // begin
        :end-before: // end

Include a raw HTML file (or an inline SVG) and put it directly into the output without any processing:

text
.. code-block:: rst

    .. raw:: html
        :file: table.html

For Markdown, one must rely on an extension. For example, using the mdx_include plugin_:

text
.. code-block:: none

    ```html
    {! template.html !}
    ```

Importing an existing site

It is possible to import your site from several other blogging sites
(like WordPress, Tumblr, ..) using a simple script. See :ref:import.

Translations

It is possible to translate articles. To do so, you need to add a lang meta
attribute to your articles/pages and set a DEFAULT_LANG setting (which is
English [en] by default). With those settings in place, only articles with the
default language will be listed, and each article will be accompanied by a list
of available translations for that article.

.. note::

This core Pelican functionality does not create sub-sites
(e.g. example.com/de) with translated templates for each
language. For such advanced functionality the i18n_subsites plugin_ can be used.

By default, Pelican uses the article's URL "slug" to determine if two or more
articles are translations of one another. (This can be changed with the
ARTICLE_TRANSLATION_ID setting.) The slug can be set manually in the file's
metadata; if not set explicitly, Pelican will auto-generate the slug from the
title of the article.

Here is an example of two articles, one in English and the other in French.

The English article::

text
Foobar is not dead
##################

:slug: foobar-is-not-dead
:lang: en

That's true, foobar is still alive!

And the French version::

text
Foobar n'est pas mort !
#######################

:slug: foobar-is-not-dead
:lang: fr

Oui oui, foobar est toujours vivant !

Post content quality notwithstanding, you can see that only item in common
between the two articles is the slug, which is functioning here as an
identifier. If you'd rather not explicitly define the slug this way, you must
then instead ensure that the translated article titles are identical, since the
slug will be auto-generated from the article title.

If you do not want the original version of one specific article to be detected
by the DEFAULT_LANG setting, use the translation metadata to specify
which posts are translations::

text
Foobar is not dead
##################

:slug: foobar-is-not-dead
:lang: en
:translation: true

That's true, foobar is still alive!

.. _internal_pygments_options:

Syntax highlighting

Pelican can provide colorized syntax highlighting for your code blocks.
To do so, you must use the following conventions inside your content files.

For reStructuredText, use the code-block directive to specify the type
of code to be highlighted (in these examples, we'll use python)::

text
.. code-block:: python

   print("Pelican is a static site generator.")

For Markdown, which utilizes the CodeHilite extension_ to provide syntax
highlighting, include the language identifier just above the code block,
indenting both the identifier and the code::

text
There are two ways to specify the identifier:

    :::python
    print("The triple-colon syntax will *not* show line numbers.")

To display line numbers, use a path-less shebang instead of colons:

    #!python
    print("The path-less shebang syntax *will* show line numbers.")

The specified identifier (e.g. python, ruby) should be one that
appears on the list of available lexers <https://pygments.org/docs/lexers/>_.

When using reStructuredText the following options are available in the
code-block directive:

============= ============ =========================================
Option Valid values Description
============= ============ =========================================
anchorlinenos N/A If present, wrap line numbers in <a> tags.
classprefix string String to prepend to token class names
hl_lines numbers List of lines to be highlighted, where
line numbers to highlight are separated
by a space. This is similar to
emphasize-lines in Sphinx, but it
does not support a range of line numbers
separated by a hyphen, or comma-separated
line numbers.
lineanchors string Wrap each line in an anchor using this
string and -linenumber.
linenos string If present or set to "table", output line
numbers in a table; if set to
"inline", output them inline. "none" means
do not output the line numbers for this
table.
linenospecial number If set, every nth line will be given the
'special' CSS class.
linenostart number Line number for the first line.
linenostep number Print every nth line number.
lineseparator string String to print between lines of code,
'\n' by default.
linespans string Wrap each line in a span using this and
-linenumber.
nobackground N/A If set, do not output background color for
the wrapping element
nowrap N/A If set, do not wrap the tokens at all.
tagsfile string ctags file to use for name definitions.
tagurlformat string format for the ctag links.
============= ============ =========================================

Note that, depending on the version, your Pygments module might not have
all of these options available. Refer to the HtmlFormatter section of the
Pygments documentation <https://pygments.org/docs/formatters/>_ for more
details on each of the options.

For example, the following code block enables line numbers, starting at 153,
and prefixes the Pygments CSS classes with pgcss to make the names
more unique and avoid possible CSS conflicts::

text
.. code-block:: identifier
    :classprefix: pgcss
    :linenos: table
    :linenostart: 153

It is also possible to specify the PYGMENTS_RST_OPTIONS variable in your
Pelican settings file to include options that will be automatically applied to
every code block.

For example, if you want to have line numbers displayed for every code block
and a CSS prefix, you would set this variable to::

text
PYGMENTS_RST_OPTIONS = {'classprefix': 'pgcss', 'linenos': 'table'}

If specified, settings for individual code blocks will override the defaults in
your settings file.

Publishing drafts

If you want to publish an article or a page as a draft (for friends to review
before publishing, for example), you can add a Status: draft attribute to
its metadata. That article will then be output to the drafts folder and not
listed on the index page nor on any category or tag page.

If your articles should be automatically published as a draft (to not
accidentally publish an article before it is finished), include the status in
the DEFAULT_METADATA::

text
DEFAULT_METADATA = {
    'status': 'draft',
}

To publish a post when the default status is draft, update the post's
metadata to include Status: published.

Hidden Posts

Like pages, posts can also be marked as hidden with the Status: hidden
attribute. Hidden posts will be output to ARTICLE_SAVE_AS as expected, but
are not included by default in tag, category, and author indexes, nor in the
main article feed. This has the effect of creating an "unlisted" post.

Skip Posts

Posts marked with skip status are ignored entirely. They are not processed
nor output to the ARTICLE_SAVE_AS path. Such posts will similarly not be
included in indexes or feeds.

.. _W3C ISO 8601: https://www.w3.org/TR/NOTE-datetime
.. _AsciiDoc: https://asciidoc.org
.. _Pelican Plugins: https://github.com/pelican-plugins
.. _pelican-plugins: https://github.com/getpelican/pelican-plugins
.. _Python-Markdown: https://github.com/Python-Markdown/markdown
.. _Markdown Extensions: https://python-markdown.github.io/extensions/
.. _CodeHilite extension: https://python-markdown.github.io/extensions/code_hilite/#syntax
.. _i18n_subsites plugin: https://github.com/getpelican/pelican-plugins/tree/master/i18n_subsites
.. _the include directive: http://docutils.sourceforge.net/docs/ref/rst/directives.html#include
.. _mdx_include plugin: https://github.com/neurobin/mdx_include


Contribute (`docs/contribute.rst`)

Contributing and feedback guidelines
####################################

There are many ways to contribute to Pelican. You can improve the
documentation, add missing features, and fix bugs (or just report them). You
can also help out by reviewing and commenting on
existing issues <https://github.com/getpelican/pelican/issues>_.

Don't hesitate to fork Pelican and submit an issue or pull request on GitHub.
When doing so, please consider the following guidelines.

.. include:: ../CONTRIBUTING.rst

Setting up the development environment

While there are many ways to set up one's development environment, the following
instructions will utilize Pip_ and PDM_. These tools facilitate managing
virtual environments for separate Python projects that are isolated from one
another, so you can use different packages (and package versions) for each.

Please note that Python |min_python| is required for Pelican development.

(Optional) If you prefer to install PDM <https://pdm.fming.dev/latest/#installation>_ once for use with multiple projects,
you can install it via::

text
curl -sSL https://pdm.fming.dev/install-pdm.py | python3 -

Point your web browser to the Pelican repository_ and tap the Fork button
at top-right. Then clone the source for your fork and add the upstream project
as a Git remote::

text
mkdir ~/projects
git clone https://github.com/YOUR_USERNAME/pelican.git ~/projects/pelican
cd ~/projects/pelican
git remote add upstream https://github.com/getpelican/pelican.git

While PDM can dynamically create and manage virtual environments, we're going
to manually create and activate a virtual environment::

text
mkdir ~/virtualenvs && cd ~/virtualenvs
python3 -m venv pelican
source ~/virtualenvs/pelican/*/activate

Install the needed dependencies and set up the project::

text
python -m pip install invoke
invoke setup

Your local environment should now be ready to go!

.. _Pip: https://pip.pypa.io/
.. _PDM: https://pdm.fming.dev/latest/
.. _Pelican repository: https://github.com/getpelican/pelican

Development

Once Pelican has been set up for local development, create a topic branch for
your bug fix or feature::

text
git checkout -b name-of-your-bugfix-or-feature

Now you can make changes to Pelican, its documentation, and/or other aspects of
the project.

Setting up ``git blame`` (optional)

git blame annotates lines in a file with information about the pull request
that last modified it. Sweeping shallow changes (like formatting) can make that
information less useful, so we keep a list of such changes to be ignored. Run the
following command to set this up in your repository, adding --global if you
want this setting to apply to all repositories::

text
git config blame.ignoreRevsFile .git-blame-ignore-revs

As noted in a useful article_ about git blame, there are other related
settings you may find to be beneficial::

text
# Add `?` to any lines that have had a commit skipped using --ignore-rev
git config --global blame.markIgnoredLines true
# Add `*` to any lines that were added in a skipped commit and can not be attributed
git config --global blame.markUnblamableLines true

.. _useful article: https://www.michaelheap.com/git-ignore-rev/

Running the test suite

Each time you make changes to Pelican, there are two things to do regarding
tests: check that the existing tests pass, and add tests for any new features
or bug fixes. The tests are located in pelican/tests, and you can run them
via::

text
invoke tests

(For more on Invoke, see invoke -l to list tasks, or
https://pyinvoke.org for documentation.)

In addition to running the test suite, it is important to also ensure that any
lines you changed conform to code style guidelines. You can check that via::

text
invoke lint

If style violations are found, many of them can be addressed automatically via::

text
invoke lint --fix
invoke format

If code style violations are found in lines you changed, correct those lines
and re-run the invoke lint command until they have all been fixed. You do
not need to address style violations, if any, for code lines you did not touch.

After making your changes and running the tests, you may see a test failure
mentioning that "some generated files differ from the expected functional tests
output." If you have made changes that affect the HTML output generated by
Pelican, and the changes to that output are expected and deemed correct given
the nature of your changes, then you should update the output used by the
functional tests. To do so, make sure you have both en_EN.utf8 and
fr_FR.utf8 locales installed, and then run the following command::

text
invoke update-functional-tests

You may also find that some tests are skipped because some dependency (e.g.,
Pandoc) is not installed. This does not automatically mean that these tests
have passed; you should at least verify that any skipped tests are not affected
by your changes.

You should run the test suite under each of the supported versions of Python.
This is best done by creating a separate Python environment for each version.
Tox_ is a useful tool to automate running tests inside virtualenv
environments.

.. _Tox: https://tox.readthedocs.io/en/latest/

Running a code coverage report

Code is more likely to stay robust if it is tested. Coverage_ is a library that
measures how much of the code is tested. To run it::

text
invoke coverage

This will show overall coverage, coverage per file, and even line-by-line coverage.
There is also an HTML report available::

text
open htmlcov/index.html

.. _Coverage: https://github.com/nedbat/coveragepy

Building the docs

If you make changes to the documentation, you should build and inspect your
changes before committing them::

text
invoke docserve

Open http://localhost:8000 in your browser to review the documentation. While
the above task is running, any changes you make and save to the documentation
should automatically appear in the browser, as it live-reloads when it detects
changes to the documentation source files.

Plugin development

To create a new Pelican plugin, please refer to the plugin template_
repository for detailed instructions.

If you want to contribute to an existing Pelican plugin, follow the steps
above to set up Pelican for local development, and then create a directory to
store cloned plugin repositories::

mkdir -p ~/projects/pelican-plugins

Assuming you wanted to contribute to the Simple Footnotes plugin, you would
first browse to the Simple Footnotes_ repository on GitHub and tap the Fork
button at top-right. Then clone the source for your fork and add the upstream
project as a Git remote::

text
git clone https://github.com/YOUR_USERNAME/simple-footnotes.git ~/projects/pelican-plugins/simple-footnotes
cd ~/projects/pelican-plugins/simple-footnotes
git remote add upstream https://github.com/pelican-plugins/simple-footnotes.git

Install the needed dependencies and set up the project::

text
invoke setup

Create a topic branch for your plugin bug fix or feature::

text
git checkout -b name-of-your-bugfix-or-feature

After writing new tests for your plugin changes, run the plugin test suite and
check for code style compliance via::

text
invoke tests
invoke lint

If style violations are found, many of them can be addressed automatically via::

text
invoke lint --fix
invoke format

If style violations are found even after running the above auto-formatters,
you will need to make additional manual changes until invoke lint no longer
reports any code style violations.

.. _plugin template: https://github.com/getpelican/cookiecutter-pelican-plugin
.. _Simple Footnotes: https://github.com/pelican-plugins/simple-footnotes

Submitting your changes

Assuming linting validation and tests pass, add a RELEASE.md file in the root
of the project that contains the release type (major, minor, patch) and a
summary of the changes that will be used as the release changelog entry.
For example::

text
Release type: patch

Fix browser reloading upon changes to content, settings, or theme

Commit your changes and push your topic branch::

text
git add .
git commit -m "Your detailed description of your changes"
git push origin name-of-your-bugfix-or-feature

Finally, browse to your repository fork on GitHub and submit a pull request.

Logging tips

Try to use logging with appropriate levels.

For logging messages that are not repeated, use the usual Python way::

text
# at top of file
import logging
logger = logging.getLogger(__name__)

# when needed
logger.warning("A warning with %s formatting", arg_to_be_formatted)

Do not format log messages yourself. Use %s formatting in messages and pass
arguments to logger. This is important, because the Pelican logger will
preprocess some arguments, such as exceptions.

Limiting extraneous log messages

If the log message can occur several times, you may want to limit the log to
prevent flooding. In order to do that, use the extra keyword argument for
the logging message in the following format::

text
logger.warning("A warning with %s formatting", arg_to_be_formatted,
    extra={'limit_msg': 'A generic message for too many warnings'})

Optionally, you can also set 'limit_args' as a tuple of arguments in
extra dict if your generic message needs formatting.

Limit is set to 5, i.e, first four logs with the same 'limit_msg' are
outputted normally but the fifth one will be logged using 'limit_msg' (and
'limit_args' if present). After the fifth, corresponding log messages will
be ignored.

For example, if you want to log missing resources, use the following code::

text
for resource in resources:
    if resource.is_missing:
        logger.warning(
            'The resource %s is missing', resource.name,
            extra={'limit_msg': 'Other resources were missing'})

The log messages will be displayed as follows::

text
WARNING: The resource prettiest_cat.jpg is missing
WARNING: The resource best_cat_ever.jpg is missing
WARNING: The resource cutest_cat.jpg is missing
WARNING: The resource lolcat.jpg is missing
WARNING: Other resources were missing

Outputting traceback in the logs

If you're logging inside an except block, you may want to provide the
traceback information as well. You can do that by setting exc_info keyword
argument to True during logging. However, doing so by default can be
undesired because tracebacks are long and can be confusing to regular users.
Try to limit them to --debug mode like the following::

text
try:
    some_action()
except Exception as e:
    logger.error('Exception occurred: %s', e,
        exc_info=settings.get('DEBUG', False))

Faq (`docs/faq.rst`)

Frequently Asked Questions (FAQ)
################################

Here are some frequently asked questions about Pelican.

What's the best way to communicate a problem, question, or suggestion?

Please read our :doc:feedback guidelines <contribute>.

How can I help?

There are several ways to help out. First, you can communicate any Pelican
suggestions or problems you might have via Pelican Discussions <https://github.com/getpelican/pelican/discussions>_. Please first check the
existing list of discussions and issues (both open and closed) in order to
avoid submitting topics that have already been covered before.

If you want to contribute, please fork the Git repository <https://github.com/getpelican/pelican/>_, create a new feature branch, make
your changes, and issue a pull request. Someone will review your changes as
soon as possible. Please refer to the :doc:How to Contribute <contribute>
section for more details.

You can also contribute by creating themes and improving the documentation.

Is the Pelican settings file mandatory?

Configuration files are optional and are just an easy way to configure Pelican.
For basic operations, it's possible to specify options while invoking Pelican
via the command line. See pelican --help for more information.

Changes to the settings file take no effect

When experimenting with different settings (especially the metadata ones)
caching may interfere and the changes may not be visible. In such cases, ensure
that caching is disabled via LOAD_CONTENT_CACHE = False or use the
--ignore-cache command-line switch.

I'm creating my own theme. How do I use Pygments for syntax highlighting?

Pygments adds some classes to the generated content. These classes are used by
themes to style code syntax highlighting via CSS. Specifically, you can
customize the appearance of your syntax highlighting via the .highlight pre
class in your theme's CSS file. To see how various styles can be used to render
Django code, for example, use the style selector drop-down at top-right on the
Pygments project demo site <https://pygments.org/demo/>_.

You can use the following example commands to generate a starting CSS file from
a Pygments built-in style (in this case, "monokai") and then copy the generated
CSS file to your new theme::

text
pygmentize -S monokai -f html -a .highlight > pygment.css
cp pygment.css path/to/theme/static/css/

Don't forget to import your pygment.css file from your main CSS file.

How do I create my own theme?

Please refer to :ref:theming-pelican.

Can I override individual templates without forking the whole theme?

Yes, you can override existing templates of the theme that you are using, or
add new templates, via the THEME_TEMPLATES_OVERRIDES variable. For example,
to override the page template, you can define the location for your templates
like this::

text
THEME_TEMPLATES_OVERRIDES = ["templates"]

You can then define a custom template in templates/page.html.
See :ref:settings/themes for details.

I want to use Markdown, but I got an error.

If you try to generate Markdown content without first installing the Markdown
library, you may see a message that says No valid files found in content.
Markdown is not a hard dependency for Pelican, so if you have content in
Markdown format, you will need to explicitly install the Markdown library. You
can do so by typing the following command, prepending sudo if permissions
require it::

text
python -m pip install markdown

Can I use arbitrary metadata in my templates?

Yes. For example, to include a modified date in a Markdown post, one could
include the following at the top of the article::

text
Modified: 2012-08-08

For reStructuredText, this metadata should of course be prefixed with a colon::

text
:Modified: 2012-08-08

This metadata can then be accessed in templates such as article.html via::

text
{% if article.modified %}
Last modified: {{ article.modified }}
{% endif %}

If you want to include metadata in templates outside the article context (e.g.,
base.html), the if statement should instead be::

text
{% if article and article.modified %}

.. note::

text
Because the colon symbol (``:``) is used as a separator, be aware that
metadata field names *containing* a colon will probably not work.

How do I make my output folder structure identical to my content hierarchy?

Try these settings::

text
USE_FOLDER_AS_CATEGORY = False
PATH_METADATA = r"(?P.*)\..*"
ARTICLE_URL = ARTICLE_SAVE_AS = PAGE_URL = PAGE_SAVE_AS = "{path_no_ext}.html"

How do I assign custom templates on a per-page basis?

It's as simple as adding an extra line of metadata to any page or article that
you want to have its own template. For example, this is how it would be handled
for content in reST format::

text
:template: template_name

For content in Markdown format::

text
Template: template_name

Then just make sure your theme contains the relevant template file (e.g.
template_name.html). If you just want to add a new custom template to an
existing theme, you can also provide it in a directory specified by THEME_TEMPLATES_OVERRIDES (see :ref:settings/themes).

How can I override the generated URL of a specific page or article?

Include url and save_as metadata in any pages or articles that you want
to override the generated URL. Here is an example page in reST format::

text
Override url/save_as page
#########################

:url: override/url/
:save_as: override/url/index.html

With this metadata, the page will be written to override/url/index.html
and Pelican will use the URL override/url/ to link to this page.

How can I use a static page as my home page?

The override feature mentioned above can be used to specify a static page as
your home page. The following Markdown example could be stored in
content/pages/home.md::

text
Title: Welcome to My Site
URL:
save_as: index.html

Thank you for visiting. Welcome!

If the original blog index is still wanted, it can then be saved in a
different location by setting INDEX_SAVE_AS = 'blog_index.html' for
the 'index' direct template.

What if I want to disable feed generation?

To disable feed generation, all feed settings should be set to None. All
but three feed settings already default to None, so if you want to disable
all feed generation, you only need to specify the following settings::

text
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
AUTHOR_FEED_ATOM = None
AUTHOR_FEED_RSS = None

The word None should not be surrounded by quotes. Please note that None
and '' are not the same thing.

I'm getting a warning about feeds generated without SITEURL being set properly

RSS and Atom feeds require all URL links to be absolute <https://validator.w3.org/feed/docs/rss2.html#comments>_. In order to properly
generate links in Pelican you will need to set SITEURL to the full path of
your site.

Feeds are still generated when this warning is displayed, but links within may
be malformed and thus the feed may not validate.

Can I force Atom feeds to show only summaries instead of article content?

Instead of having to open a separate browser window to read articles, the
overwhelming majority of folks who use feed readers prefer to read content
within the feed reader itself. Mainly for that reason, Pelican does not support
restricting Atom feeds to only contain summaries. Unlike Atom feeds, the RSS
feed specification does not include a separate content field, so by default
Pelican publishes RSS feeds that only contain summaries (but can optionally be
set to instead publish full content RSS feeds). So the default feed generation
behavior provides users with a choice: subscribe to Atom feeds for full content
or to RSS feeds for just the summaries.

Is Pelican only suitable for blogs?

No. Pelican can be easily configured to create and maintain any type of static
site. This may require a little customization of your theme and Pelican
configuration. For example, if you are building a launch site for your product
and do not need tags on your site, you could remove the relevant HTML code from
your theme. You can also disable generation of tag-related pages via::

text
TAGS_SAVE_AS = ''
TAG_SAVE_AS = ''

Why does Pelican always write all HTML files even with content caching enabled?

In order to reliably determine whether the HTML output is different before
writing it, a large part of the generation environment including the template
contexts, imported plugins, etc. would have to be saved and compared, at least
in the form of a hash (which would require special handling of unhashable
types), because of all the possible combinations of plugins, pagination, etc.
which may change in many different ways. This would require a lot more
processing time and memory and storage space. Simply writing the files each
time is a lot faster and a lot more reliable.

However, this means that the modification time of the files changes every time,
so a rsync based upload will transfer them even if their content hasn't
changed. A simple solution is to make rsync use the --checksum option,
which will make it compare the file checksums in a much faster way than Pelican
would.

How to process only a subset of all articles?

It is often useful to process only e.g. 10 articles for debugging purposes.
This can be achieved by explicitly specifying only the filenames of those
articles in ARTICLE_PATHS. A list of such filenames could be found using a
command similar to cd content; find -name '*.md' | head -n 10.

My tag cloud is missing/broken since I upgraded Pelican

In an ongoing effort to streamline Pelican, tag cloud generation has been
moved out of Pelican core and into a separate plugin <https://github.com/pelican-plugins/tag-cloud>_. See the :ref:plugins
documentation for further information about the Pelican plugin system.

Since I upgraded Pelican my pages are no longer rendered

Pages were available to themes as lowercase pages and uppercase PAGES.
To bring this inline with the :ref:templates-variables section, PAGES has
been removed. This is quickly resolved by updating your theme to iterate over
pages instead of PAGES. Just replace::

text
{% for pg in PAGES %}

with something like::

text
{% for pg in pages %}

How can I stop Pelican from trying to parse my static files as content?

Pelican's article and page generators run before it's static generator. That
means if you use a setup similar to the default configuration, where a static
source directory is defined inside a *_PATHS setting, all files that have a
valid content file ending (.html, .rst, .md, ...) will be treated
as articles or pages before they get treated as static files.

To circumvent this issue either use the appropriate *_EXCLUDES setting or
disable the offending reader via READERS if you don't need it.

Why is [arbitrary Markdown syntax] not supported?

Pelican does not directly handle Markdown processing and instead delegates that
task to the Python-Markdown_ project, the core of which purposefully follows
the original Markdown syntax rules and not the myriad Markdown "flavors" that
have subsequently propagated. That said, Python-Markdown_ is quite modular, and
the syntax you are looking for may be provided by one of the many available
Markdown Extensions_. Alternatively, some folks have created Pelican plugins
that support Markdown variants, so that may be your best choice if there is a
particular variant you want to use when writing your content.

.. _Python-Markdown: https://github.com/Python-Markdown/markdown
.. _Markdown Extensions: https://python-markdown.github.io/extensions/


Importer (`docs/importer.rst`)

.. _import:

Importing an existing site
##########################

Description

pelican-import is a command-line tool for converting articles from other
software to reStructuredText or Markdown. The supported import formats are:

  • Blogger XML export
  • Dotclear export
  • Medium export
  • Tumblr API
  • WordPress XML export
  • RSS/Atom feed

The conversion from HTML to reStructuredText or Markdown relies on Pandoc_.
For Dotclear, if the source posts are written with Markdown syntax, they will
not be converted (as Pelican also supports Markdown).

.. note::

Unlike Pelican, Wordpress supports multiple categories per article. These
are imported as a comma-separated string. You have to resolve these
manually, or use a plugin such as More Categories_ that enables multiple
categories per article.

.. note::

Imported pages may contain links to images that still point to the original site.
So you might want to download those images into your local content and manually
re-link them from the relevant pages of your site.

Dependencies

pelican-import has some dependencies not required by the rest of Pelican:

  • BeautifulSoup4 and lxml, for WordPress and Dotclear import. Can be
    installed like any other Python package (pip install BeautifulSoup4 lxml).
  • Feedparser, for feed import (pip install feedparser).
  • Pandoc, see the Pandoc site_ for installation instructions on your
    operating system.

.. _Pandoc: https://pandoc.org/
.. _Pandoc site: https://pandoc.org/installing.html

Usage

::

text
pelican-import [-h] [--blogger] [--dotclear] [--tumblr] [--wpfile] [--feed]
               [-o OUTPUT] [-m MARKUP] [--dir-cat] [--dir-page] [--strip-raw] [--wp-custpost]
               [--wp-attach] [--disable-slugs] [-b BLOGNAME]
               input|api_key

Positional arguments

============= ============================================================================
input The input file to read
api_key (Tumblr only) api_key can be obtained from https://www.tumblr.com/oauth/apps
============= ============================================================================

Optional arguments

-h, --help Show this help message and exit
--blogger Blogger XML export (default: False)
--dotclear Dotclear export (default: False)
--medium Medium export (default: False)
--tumblr Tumblr API (default: False)
--wpfile WordPress XML export (default: False)
--feed Feed to parse (default: False)
-o OUTPUT, --output OUTPUT
Output path (default: content)
-m MARKUP, --markup MARKUP
Output markup format: rst, markdown, or asciidoc
(default: rst)
--dir-cat Put files in directories with categories name
(default: False)
--dir-page Put files recognised as pages in "pages/" sub-
directory (blogger and wordpress import only)
(default: False)
--filter-author Import only post from the specified author
--strip-raw Strip raw HTML code that can't be converted to markup
such as flash embeds or iframes (default: False)
--wp-custpost Put wordpress custom post types in directories. If
used with --dir-cat option directories will be created
as "/post_type/category/" (wordpress import only)
--wp-attach Download files uploaded to wordpress as attachments.
Files will be added to posts as a list in the post
header and links to the files within the post will be
updated. All files will be downloaded, even if they
aren't associated with a post. Files will be downloaded
with their original path inside the output directory,
e.g. "output/wp-uploads/date/postname/file.jpg".
(wordpress import only) (requires an internet
connection)
--disable-slugs Disable storing slugs from imported posts within
output. With this disabled, your Pelican URLs may not
be consistent with your original posts. (default:
False)
-b BLOGNAME, --blogname=BLOGNAME
Blog name used in Tumblr API

Examples

For Blogger::

text
$ pelican-import --blogger -o ~/output ~/posts.xml

For Dotclear::

text
$ pelican-import --dotclear -o ~/output ~/backup.txt

For Medium::

text
$ pelican-import --medium -o ~/output ~/medium-export/posts/

The Medium export is a zip file. Unzip it, and point this tool to the
"posts" subdirectory. For more information on how to export, see
https://help.medium.com/hc/en-us/articles/115004745787-Export-your-account-data.

For Tumblr::

text
$ pelican-import --tumblr -o ~/output --blogname= <api_key>

For WordPress::

text
$ pelican-import --wpfile -o ~/output ~/posts.xml

For Medium (an example of using an RSS feed):

text
$ python -m pip install feedparser
$ pelican-import --feed https://medium.com/feed/@username

.. note::

The RSS feed may only return the most recent posts โ€” not all of them.

Tests

To test the module, one can use sample files:

.. _More Categories: https://github.com/pelican-plugins/more-categories


Index (`docs/index.rst`)

Pelican |release|

Pelican is a static site generator, written in Python_. Highlights include:

  • Write your content directly with your editor of choice in reStructuredText_
    or Markdown_ formats
  • Includes a simple CLI tool to (re)generate your site
  • Easy to interface with distributed version control systems and web hooks
  • Completely static output is easy to host anywhere

Ready to get started? Check out the :doc:Quickstart<quickstart> guide.

Features

Pelicanโ€™s feature highlights include:

  • Articles (e.g., blog posts) and pages (e.g., "About", "Projects", "Contact")
  • Integration with external services
  • Site themes (created using Jinja2_ templates)
  • Publication of articles in multiple languages
  • Generation of Atom and RSS feeds
  • Code syntax highlighting
  • Import existing content from WordPress, Dotclear, or RSS feeds
  • Fast rebuild times thanks to content caching and selective output writing
  • Extensible via a rich plugin ecosystem: Pelican Plugins_

Why the name "Pelican"?

"Pelican" is an anagram for calepin, which means "notebook" in French. ;)

Source code

You can access the source code at: https://github.com/getpelican/pelican

How to get help, contribute, or provide feedback

See our :doc:feedback and contribution submission guidelines <contribute>.

Documentation

.. toctree::
:maxdepth: 2

quickstart
install
content
publish
settings
plugins
themes
pelican-themes
importer
faq
tips
contribute
internals
report
changelog

.. Links

.. _Python: https://www.python.org/
.. _reStructuredText: http://docutils.sourceforge.net/rst.html
.. _Markdown: https://daringfireball.net/projects/markdown/
.. _Jinja2: https://palletsprojects.com/p/jinja/
.. _Pelican documentation: https://docs.getpelican.com/latest/
.. _Pelican's internals: https://docs.getpelican.com/en/latest/internals.html
.. _Pelican Plugins: https://github.com/pelican-plugins


Install (`docs/install.rst`)

Installing Pelican
##################

Pelican currently runs best on Python |min_python|; earlier versions of Python are not supported.

Once Pelican is installed, you can run pelican --help to see basic usage
options. For more detail, refer to the :doc:Publish section.

You can install Pelican via several different methods.

Recommended method: Pip <https://pip.pypa.io/>_ User Install

To install Pelican via Pip::

text
python3 -m pip install --user "pelican[markdown]"

Or, if you do not plan to use Markdown <https://pypi.org/project/Markdown/>_,
you can omit the [markdown] suffix::

text
python3 -m pip install --user pelican

Alternate method 1: Pipx <https://github.com/pypa/pipx>_

Pipx lets you execute binaries from Python packages in isolated environments.
You can install Pipx by following its
documentation <https://pipx.pypa.io>_. After Pipx is installed,
you can install Pelican via::

text
pipx install "pelican[markdown]"

Alternate method 2: uv <https://docs.astral.sh/uv/>_

Like Pipx, uv allows you to install tools in isolated environments.
If you have uv installed, you can install Pelican via::

text
uv tool install "pelican[markdown]"

Alternate method 3: Virtual Environment

If you prefer to manually manage a virtual environment, you can create
a virtual environment for Pelican via venv_ before installing Pelican::

text
python3 -m venv ~/virtualenvs/pelican
source ~/virtualenvs/pelican/bin/activate
python3 -m pip install "pelican[markdown]"

Alternatively, if you have the project source, you can replace the last command
with the following to install Pelican using the setuptools method::

text
cd path-to-Pelican-source
python3 -m pip install .

If you have Git installed and prefer to install the latest bleeding-edge
version of Pelican rather than a stable release, use the following command::

text
python3 -m pip install -e "git+https://github.com/getpelican/pelican.git#egg=pelican"

To exit the virtual environment, type deactivate.

Optional packages

If you plan on using Markdown <https://pypi.org/project/Markdown/>_ as a
markup format, you can install Pelican with Markdown support::

text
python3 -m pip install --user "pelican[markdown]"

Typographical enhancements can be enabled in your settings file, but first the
requisite Typogrify <https://github.com/justinmayer/typogrify>_ library must be
installed::

text
python3 -m pip install --user typogrify

If you are using Pipx, you can inject packages into the Pipx-managed virtual
environment. For example, to add Typogrify::

text
pipx inject pelican typogrify

To use uv to install Pelican with additional extra packages, use the
following example command, which like above will also install Typogrify::

text
uv tool install --with typogrify "pelican[markdown]"

Dependencies

When Pelican is installed, the following dependent Python packages should be
automatically installed without any action on your part:

  • feedgenerator <https://pypi.org/project/feedgenerator/>_, to generate the
    Atom feeds
  • jinja2 <https://pypi.org/project/Jinja2/>_, for templating support
  • pygments <https://pypi.org/project/Pygments/>_, for syntax highlighting
  • docutils <https://pypi.org/project/docutils/>_, for supporting
    reStructuredText as an input format
  • blinker <https://pypi.org/project/blinker/>_, an object-to-object and
    broadcast signaling system
  • unidecode <https://pypi.org/project/Unidecode/>_, for ASCII
    transliterations of Unicode text
    utilities
  • MarkupSafe <https://pypi.org/project/MarkupSafe/>_, for a markup-safe
    string implementation
  • python-dateutil <https://pypi.org/project/python-dateutil/>_, to read
    the date metadata

Upgrading

If you installed a stable Pelican release via Pip_ and wish to upgrade to
the latest stable release, you can do so by adding --upgrade::

text
python3 -m pip install --upgrade pelican

If you installed Pelican via setuptools or the bleeding-edge method,
perform the same step to install the most recent version.

If you installed with Pipx, upgrade via::

text
pipx upgrade pelican

If you installed with uv, upgrade via::

text
uv tool upgrade pelican

Kickstart your site

Once Pelican has been installed, you can create a skeleton project via the
pelican-quickstart command, which begins by asking some questions about
your site::

text
pelican-quickstart

If run inside an activated virtual environment, pelican-quickstart will
look for an associated project path inside $VIRTUAL_ENV/.project. If that
file exists and contains a valid directory path, the new Pelican project will
be saved at that location. Otherwise, the default is the current working
directory. To set the new project path on initial invocation, use:
pelican-quickstart --path /your/desired/directory

Once you finish answering all the questions, your project will consist of the
following hierarchy (except for pages โ€” shown in parentheses below โ€” which
you can optionally add yourself if you plan to create non-chronological
content)::

text
yourproject/
โ”œโ”€โ”€ content
โ”‚   โ””โ”€โ”€ (pages)
โ”œโ”€โ”€ output
โ”œโ”€โ”€ tasks.py
โ”œโ”€โ”€ Makefile
โ”œโ”€โ”€ pelicanconf.py       # Main settings file
โ””โ”€โ”€ publishconf.py       # Settings to use when ready to publish

The next step is to begin to adding content to the content folder that has
been created for you.

.. _virtualenv: https://virtualenv.pypa.io/en/latest/
.. _venv: https://docs.python.org/3/library/venv.html


Internals (`docs/internals.rst`)

Pelican internals
#################

This section describe how Pelican works internally. As you'll see, it's quite
simple, but a bit of documentation doesn't hurt. :)

You can also find in the :doc:report section an excerpt of a report the
original author wrote with some software design information.

.. _report: :doc:report

Overall structure

What Pelican does is take a list of files and process them into some sort of
output. Usually, the input files are reStructuredText and Markdown files, and
the output is a blog, but both input and output can be anything you want.

The logic is separated into different classes and concepts:

  • Writers are responsible for writing files: .html files, RSS feeds, and so
    on. Since those operations are commonly used, the object is created once and
    then passed to the generators.

  • Readers are used to read from various formats (HTML, Markdown and
    reStructuredText for now, but the system is extensible). Given a file, they
    return metadata (author, tags, category, etc.) and content (HTML-formatted).

  • Generators generate the different outputs. For instance, Pelican comes
    with ArticlesGenerator and PageGenerator. Given a configuration, they
    can do whatever they want. Most of the time, it's generating files from
    inputs.

  • Pelican also uses templates, so it's easy to write your own theme. The
    syntax is Jinja2 <https://palletsprojects.com/p/jinja/>_ and is very easy to learn, so
    don't hesitate to jump in and build your own theme.

How to implement a new reader?

Is there an awesome markup language you want to add to Pelican? Well, the only
thing you have to do is to create a class with a read method that returns
HTML content and some metadata.

Take a look at the Markdown reader::

text
from pelican.readers import BaseReader
from pelican.utils import pelican_open
from markdown import Markdown

class MarkdownReader(BaseReader):
    enabled = True

    def read(self, source_path):
        """Parse content and metadata of markdown files"""

        with pelican_open(source_path) as text:
            md_extensions = {'markdown.extensions.meta': {},
                             'markdown.extensions.codehilite': {}}
            md = Markdown(extensions=md_extensions.keys(),
                          extension_configs=md_extensions)
            content = md.convert(text)

        metadata = {}
        for name, value in md.Meta.items():
            name = name.lower()
            meta = self.process_metadata(name, value[0])
            metadata[name] = meta
        return content, metadata

Simple, isn't it?

If your new reader requires additional Python dependencies, then you should
wrap their import statements in a try...except block. Then inside the
reader's class, set the enabled class attribute to mark import success or
failure. This makes it possible for users to continue using their favourite
markup method without needing to install modules for formats they don't use.

How to implement a new generator?

Generators have two important methods. You're not forced to create both; only
the existing ones will be called.

  • generate_context, that is called first, for all the generators.
    Do whatever you have to do, and update the global context if needed. This
    context is shared between all generators, and will be passed to the
    templates. For instance, the PageGenerator generate_context method
    finds all the pages, transforms them into objects, and populates the context
    with them. Be careful not to output anything using this context at this
    stage, as it is likely to change by the effect of other generators.

  • generate_output is then called. And guess what is it made for? Oh,
    generating the output. :) It's here that you may want to look at the context
    and call the methods of the writer object that is passed as the first
    argument of this function. In the PageGenerator example, this method will
    look at all the pages recorded in the global context and output a file on the
    disk (using the writer method write_file) for each page encountered.


Pelican Themes (`docs/pelican-themes.rst`)

pelican-themes
##############

Description

pelican-themes is a command line tool for managing themes for Pelican. See
:ref:settings/themes for settings related to themes.

Usage
"""""

| pelican-themes [-h] [-l] [-i theme path [theme path ...]]
| [-r theme name [theme name ...]]
| [-s theme path [theme path ...]] [-v] [--version]

Optional arguments:
"""""""""""""""""""

-h, --help Show the help and exit

-l, --list Show the themes already installed

-i theme_path, --install theme_path One or more themes to install

-r theme_name, --remove theme_name One or more themes to remove

-s theme_path, --symlink theme_path Same as --install, but create a symbolic link instead of copying the theme.
Useful for theme development

-v, --verbose Verbose output

--version Print the version of this script

Examples

Listing the installed themes
""""""""""""""""""""""""""""

With pelican-themes, you can see the available themes by using the -l
or --list option:

.. code-block:: console

text
$ pelican-themes -l
notmyidea
two-column@
simple
$ pelican-themes --list
notmyidea
two-column@
simple

In this example, we can see there are three themes available: notmyidea,
simple, and two-column.

two-column is followed by an @ because this theme is not copied to
the Pelican theme path, but is instead just linked to it (see Creating symbolic links_ for details about creating symbolic links).

Note that you can combine the --list option with the -v or
--verbose option to get more verbose output, like this:

.. code-block:: console

text
$ pelican-themes -v -l
/usr/local/lib/python2.6/dist-packages/pelican-2.6.0-py2.6.egg/pelican/themes/notmyidea
/usr/local/lib/python2.6/dist-packages/pelican-2.6.0-py2.6.egg/pelican/themes/two-column (symbolic link to `/home/skami/Dev/Python/pelican-themes/two-column')
/usr/local/lib/python2.6/dist-packages/pelican-2.6.0-py2.6.egg/pelican/themes/simple

Installing themes
"""""""""""""""""

You can install one or more themes using the -i or --install option.
This option takes as argument the path(s) of the theme(s) you want to install,
and can be combined with the --verbose option:

.. code-block:: console

text
# pelican-themes --install ~/Dev/Python/pelican-themes/notmyidea-cms --verbose

.. code-block:: console

text
# pelican-themes --install ~/Dev/Python/pelican-themes/notmyidea-cms\
                           ~/Dev/Python/pelican-themes/martyalchin \
                           --verbose

.. code-block:: console

text
# pelican-themes -vi ~/Dev/Python/pelican-themes/two-column

Removing themes
"""""""""""""""

The pelican-themes command can also remove themes from the Pelican themes
path. The -r or --remove option takes as argument the name(s) of the
theme(s) you want to remove, and can be combined with the --verbose option.

.. code-block:: console

text
# pelican-themes --remove two-column

.. code-block:: console

text
# pelican-themes -r martyachin notmyidea-cmd -v

Creating symbolic links
"""""""""""""""""""""""

pelican-themes can also install themes by creating symbolic links instead
of copying entire themes into the Pelican themes path.

To symbolically link a theme, you can use the -s or --symlink, which
works exactly as the --install option:

.. code-block:: console

text
# pelican-themes --symlink ~/Dev/Python/pelican-themes/two-column

In this example, the two-column theme is now symbolically linked to the
Pelican themes path, so we can use it, but we can also modify it without having
to reinstall it after each modification.

This is useful for theme development:

.. code-block:: console

text
$ sudo pelican-themes -s ~/Dev/Python/pelican-themes/two-column
$ pelican ~/Blog/content -o /tmp/out -t two-column
$ firefox /tmp/out/index.html
$ vim ~/Dev/Pelican/pelican-themes/two-column/static/css/main.css
$ pelican ~/Blog/content -o /tmp/out -t two-column
$ cp /tmp/bg.png ~/Dev/Pelican/pelican-themes/two-column/static/img/bg.png
$ pelican ~/Blog/content -o /tmp/out -t two-column
$ vim ~/Dev/Pelican/pelican-themes/two-column/templates/index.html
$ pelican ~/Blog/content -o /tmp/out -t two-column

Doing several things at once
""""""""""""""""""""""""""""

The --install, --remove and --symlink options are not mutually
exclusive, so you can combine them in the same command line to do more than one
operation at time, like this:

.. code-block:: console

text
# pelican-themes --remove notmyidea-cms two-column \
                 --install ~/Dev/Python/pelican-themes/notmyidea-cms-fr \
                 --symlink ~/Dev/Python/pelican-themes/two-column \
                 --verbose

In this example, the theme notmyidea-cms is replaced by the theme
notmyidea-cms-fr


Plugins (`docs/plugins.rst`)

.. _plugins:

Plugins
#######

Beginning with version 3.0, Pelican supports plugins. Plugins are a way to add
features to Pelican without having to directly modify the Pelican core.

How to use plugins

Starting with version 4.5, Pelican moved to a new plugin structure utilizing
namespace packages that can be easily installed via Pip_. Plugins supporting
this structure will install under the namespace package pelican.plugins and
can be automatically discovered by Pelican. To see a list of Pip-installed
namespace plugins that are active in your environment, run::

text
pelican-plugins

If you leave the PLUGINS setting as default (None), Pelican will
automatically discover namespace plugins and register them. If, on the other
hand, you specify a PLUGINS setting as a list of plugins, this
auto-discovery will be disabled. At that point, only the plugins you specify
will be registered, and you must explicitly list any namespace plugins as well.

If you are using the PLUGINS setting, you can specify plugins in two ways.
The first method specifies plugins as a list of strings. Namespace plugins can
be specified either by their full names (pelican.plugins.myplugin) or by
their short names (myplugin)::

text
PLUGINS = ['package.myplugin',
           'namespace_plugin1',
           'pelican.plugins.namespace_plugin2']

Alternatively, you can import them in your settings file and pass the modules::

text
from package import myplugin
from pelican.plugins import namespace_plugin1, namespace_plugin2
PLUGINS = [myplugin, namespace_plugin1, namespace_plugin2]

.. note::

When experimenting with different plugins (especially the ones that deal
with metadata and content) caching may interfere and the changes may not be
visible. In such cases disable caching with LOAD_CONTENT_CACHE = False
or use the --ignore-cache command-line switch.

If your plugins are not in an importable path, you can specify a list of paths
via the PLUGIN_PATHS setting. As shown in the following example, paths in
the PLUGIN_PATHS list can be absolute or relative to the settings file::

text
PLUGIN_PATHS = ["plugins", "/srv/pelican/plugins"]
PLUGINS = ["assets", "liquid_tags", "sitemap"]

Where to find plugins

Namespace plugins can be found in the pelican-plugins organization_ as
individual repositories. Legacy plugins are located in the pelican-plugins repository_ and will be gradually phased out in favor of the namespace
versions.

.. _pelican-plugins organization: https://github.com/pelican-plugins
.. _pelican-plugins repository: https://github.com/getpelican/pelican-plugins

Please note that while we do our best to review and maintain these plugins,
they are submitted by the Pelican community and thus may have varying levels of
support and interoperability.

Community plugins can also be found on PyPI tagged with "Framework :: Pelican :: Plugins_".

.. _Framework :: Pelican :: Plugins: https://pypi.org/search/?q=&o=-created&c=Framework+%3A%3A+Pelican+%3A%3A+Plugins

How to create plugins

Plugins are based on the concept of signals. Pelican sends signals, and plugins
subscribe to those signals. The list of available signals is documented in a
subsequent section.

The only rule to follow for plugins is to define a register callable, in
which you map the signals to your plugin logic. Let's take a simple example::

text
import logging

from pelican import signals

log = logging.getLogger(__name__)

def test(sender):
    log.debug("%s initialized !!", sender)

def register():
    signals.initialized.connect(test)

.. note::

text
Signal receivers are weakly-referenced and thus must not be defined within
your ``register`` callable or they will be garbage-collected before the
signal is emitted.

If multiple plugins connect to the same signal, plugins will be invoked in the
order they are registered. When the PLUGINS setting is defined, plugin
invocation order will be the order in which the plugins are listed in the
PLUGINS setting. If you rely on auto-discovered namespace plugins and have
no PLUGINS setting defined, plugins will be invoked in the same order that
they are discovered (the same order as listed in the output of the
pelican-plugins command). If you want to specify the order explicitly,
disable auto-discovery by defining PLUGINS in the desired order.

Namespace plugin structure

Namespace plugins must adhere to a certain structure in order to function
properly. They need to be installable (i.e. contain setup.py or equivalent)
and have a folder structure as follows::

text
myplugin
โ”œโ”€โ”€ pelican
โ”‚ย ย ย โ””โ”€โ”€ plugins
โ”‚ย ย ย ย ย ย ย โ””โ”€โ”€ myplugin
โ”‚ย ย ย ย ย ย ย ย ย ย ย โ”œโ”€โ”€ __init__.py
โ”‚ย ย ย ย ย ย ย ย ย ย ย โ””โ”€โ”€ ...
โ”œโ”€โ”€ ...
โ””โ”€โ”€ setup.py

It is crucial that pelican or pelican/plugins folder not
contain an __init__.py file. In fact, it is best to have those folders
empty besides the listed folders in the above structure and keep your
plugin related files contained solely in the pelican/plugins/myplugin
folder to avoid any issues.

To easily set up the proper structure, a cookiecutter template for plugins_
is provided. Refer to that project's README for instructions on how to use it.

.. _cookiecutter template for plugins: https://github.com/getpelican/cookiecutter-pelican-plugin

List of signals

Here is the list of currently implemented signals:

================================= ============================ ===========================================================================
Signal Arguments Description
================================= ============================ ===========================================================================
initialized pelican object
finalized pelican object invoked after all the generators are executed and just before pelican exits
useful for custom post processing actions, such as:
- minifying js/css assets.
- notify/ping search engines with an updated sitemap.
generator_init generator invoked in the Generator.init
all_generators_finalized generators invoked after all the generators are executed and before writing output
readers_init readers invoked in the Readers.init
article_generator_context article_generator, metadata invoked after the content and metadata for the article has been generated;
use if you need to adjust the article metadata before it gets used by
Pelican.
article_generator_preread article_generator invoked before a article is read in ArticlesGenerator.generate_context;
use if code needs to do something before every article is parsed
article_generator_init article_generator invoked in the ArticlesGenerator.init
article_generator_pretaxonomy article_generator invoked before categories and tags lists are created
useful when e.g. modifying the list of articles to be generated
so that removed articles are not leaked in categories or tags
article_generator_finalized article_generator invoked at the end of ArticlesGenerator.generate_context
article_generator_write_article article_generator, content invoked before writing each article, the article is passed as content
article_writer_finalized article_generator, writer invoked after all articles and related pages have been written, but before
the article generator is closed.
get_generators pelican object invoked in Pelican.get_generator_classes,
can return a Generator, or several
generators in a tuple or in a list.
get_writer pelican object invoked in Pelican.get_writer,
can return a custom Writer.
page_generator_context page_generator, metadata
page_generator_preread page_generator invoked before a page is read in PageGenerator.generate_context;
use if code needs to do something before every page is parsed.
page_generator_init page_generator invoked in the PagesGenerator.init
page_generator_finalized page_generator invoked at the end of PagesGenerator.generate_context
page_generator_write_page page_generator, content invoked before writing each page, the page is passed as content
page_writer_finalized page_generator, writer invoked after all pages have been written, but before the page generator
is closed.
static_generator_context static_generator, metadata
static_generator_preread static_generator invoked before a static file is read in StaticGenerator.generate_context;
use if code needs to do something before every static file is added to the
staticfiles list.
static_generator_init static_generator invoked in the StaticGenerator.init
static_generator_finalized static_generator invoked at the end of StaticGenerator.generate_context
content_object_init content_object invoked at the end of Content.init
content_written path, context invoked each time a content file is written.
feed_generated context, feed invoked each time a feed gets generated. Can be used to modify a feed
object before it gets written.
feed_written path, context, feed invoked each time a feed file is written.
================================= ============================ ===========================================================================

.. warning::

Avoid content_object_init signal if you intend to read summary or
content properties of the content object. That combination can result in
unresolved links when :ref:ref-linking-to-internal-content (see
pelican-plugins bug #314_). Use _summary and _content properties
instead, or, alternatively, run your plugin at a later stage (e.g.
all_generators_finalized).

.. note::

After Pelican 3.2, signal names were standardized. Older plugins may need
to be updated to use the new names:

========================== ===========================
Old name New name
========================== ===========================
article_generate_context article_generator_context
article_generate_finalized article_generator_finalized
article_generate_preread article_generator_preread
pages_generate_context page_generator_context
pages_generate_preread page_generator_preread
pages_generator_finalized page_generator_finalized
pages_generator_init page_generator_init
static_generate_context static_generator_context
static_generate_preread static_generator_preread
========================== ===========================

Recipes

We eventually realised some of the recipes to create plugins would be best
shared in the documentation somewhere, so here they are!

How to create a new reader

One thing you might want is to add support for your very own input format.
While it might make sense to add this feature in Pelican core, we wisely chose
to avoid this situation and instead have the different readers defined via
plugins.

The rationale behind this choice is mainly that plugins are really easy to
write and don't slow down Pelican itself when they're not active.

No more talking โ€” here is an example::

text
from pelican import signals
from pelican.readers import BaseReader

# Create a new reader class, inheriting from the pelican.reader.BaseReader
class NewReader(BaseReader):
    enabled = True  # Yeah, you probably want that :-)

    # The list of file extensions you want this reader to match with.
    # If multiple readers were to use the same extension, the latest will
    # win (so the one you're defining here, most probably).
    file_extensions = ['yeah']

    # You need to have a read method, which takes a filename and returns
    # some content and the associated metadata.
    def read(self, filename):
        metadata = {'title': 'Oh yeah',
                    'category': 'Foo',
                    'date': '2012-12-01'}

        parsed = {}
        for key, value in metadata.items():
            parsed[key] = self.process_metadata(key, value)

        return "Some content", parsed

def add_reader(readers):
    readers.reader_classes['yeah'] = NewReader

# This is how pelican works.
def register():
    signals.readers_init.connect(add_reader)

Adding a new generator

Adding a new generator is also really easy. You might want to have a look at
:doc:internals for more information on how to create your own generator.

::

text
def get_generators(pelican_object):
    # define a new generator here if you need to
    return MyGenerator

def register():
    signals.get_generators.connect(get_generators)

Adding a new writer

Adding a writer will allow you to output additional file formats to disk, or
change how the existing formats are written to disk. Note that only one writer
will be active at a time, so be sure to either subclass the built-in Writer, or
completely re-implement it.

Here is a basic example of how to set up your own writer::

text
from pelican.writers import Writer
from pelican import signals

class MyWriter(Writer):
    # define new writer functionality
    pass


def add_writer(pelican_object):
    # use pelican_instance to setup stuff if needed
    return MyWriter


def register():
    signals.get_writer.connect(add_writer)

Using Plugins to Inject Content

You can programmatically inject articles or pages using plugins. This can be
useful if you plan to fetch articles from an API, for example.

Following is a simple example of how one can build a plugin that injects a
custom article, using the article_generator_pretaxonomy signal::

text
import datetime

from pelican import signals
from pelican.contents import Article
from pelican.readers import BaseReader

def addArticle(articleGenerator):
    settings = articleGenerator.settings

    # Author, category, and tags are objects, not strings, so they need to
    # be handled using BaseReader's process_metadata() function.
    baseReader = BaseReader(settings)

    content = "I am the body of an injected article!"

    newArticle = Article(content, {
        "title": "Injected Article!",
        "date": datetime.datetime.now(),
        "category": baseReader.process_metadata("category", "fromAPI"),
        "tags": baseReader.process_metadata("tags", "tagA, tagB")
    })

    articleGenerator.articles.insert(0, newArticle)

def register():
    signals.article_generator_pretaxonomy.connect(addArticle)

.. _Pip: https://pip.pypa.io/
.. _pelican-plugins bug #314: https://github.com/getpelican/pelican-plugins/issues/314


Publish (`docs/publish.rst`)

Publish your site
#################

.. _site_generation:

Site generation

Once Pelican is installed and you have some content (e.g., in Markdown or reST
format), you can convert your content into HTML via the pelican command,
specifying the path to your content and (optionally) the path to your
:doc:settings<settings> file::

text
pelican /path/to/your/content/ [-s path/to/your/settings.py]

The above command will generate your site and save it in the output/
folder, using the default theme to produce a simple site. The default theme
consists of very simple HTML without styling and is provided so folks may use
it as a basis for creating their own themes.

You can also tell Pelican to watch for your modifications, instead of manually
re-running it every time you want to see your changes. To enable this, run the
pelican command with the -r or --autoreload option. On non-Windows
environments, this option can also be combined with the -l or --listen
option to simultaneously both auto-regenerate and serve the output at
http://localhost:8000::

text
pelican --autoreload --listen

Pelican has other command-line switches available. Have a look at the help to
see all the options you can use::

text
pelican --help

Viewing the generated files

The files generated by Pelican are static files, so you don't actually need
anything special to view them. You can use your browser to open the generated
HTML files directly::

text
firefox output/index.html

Because the above method may have trouble locating your CSS and other linked
assets, running Pelican's simple built-in web server will often provide a more
reliable previewing experience::

text
pelican --listen

Once the web server has been started, you can preview your site at:
http://localhost:8000/

Deployment

After you have generated your site, previewed it in your local development
environment, and are ready to deploy it to production, you might first
re-generate your site with any production-specific settings (e.g., analytics,
feeds, etc.) that you may have defined::

text
pelican content -s publishconf.py

To base your publish configuration on top of your pelicanconf.py, you can
import your pelicanconf settings by including the following line in your
publishconf.py::

text
from pelicanconf import *

If you have generated a publishconf.py using pelican-quickstart, this
line is included by default.

The steps for deploying your site will depend on where it will be hosted. If
you have SSH access to a server running Nginx or Apache, you might use the
rsync tool to transmit your site files::

text
rsync -avc --delete output/ host.example.com:/var/www/your-site/

There are many other deployment options, some of which can be configured when
first setting up your site via the pelican-quickstart command. See the
:doc:Tips<tips> page for detail on publishing via GitHub Pages.

Automation

While the pelican command is the canonical way to generate your site,
automation tools can be used to streamline the generation and publication flow.
One of the questions asked during the pelican-quickstart process pertains
to whether you want to automate site generation and publication. If you
answered "yes" to that question, a tasks.py and Makefile will be
generated in the root of your project. These files, pre-populated with certain
information gleaned from other answers provided during the
pelican-quickstart process, are meant as a starting point and should be
customized to fit your particular needs and usage patterns. If you find one or
both of these automation tools to be of limited utility, these files can
be deleted at any time and will not affect usage of the canonical pelican
command.

Following are automation tools that "wrap" the pelican command and can
simplify the process of generating, previewing, and uploading your site.

Invoke

The advantage of Invoke_ is that it is written in Python and thus can be used
in a wide range of environments. The downside is that it must be installed
separately. Use the following command to install Invoke, prefixing with
sudo if your environment requires it::

text
python -m pip install invoke

Take a moment to open the tasks.py file that was generated in your project
root. You will see a number of commands, any one of which can be renamed,
removed, and/or customized to your liking. Using the out-of-the-box
configuration, you can generate your site via::

text
invoke build

If you'd prefer to have Pelican automatically regenerate your site every time a
change is detected (which is handy when testing locally), use the following
command instead::

text
invoke regenerate

To serve the generated site so it can be previewed in your browser at
http://localhost:8000/::

text
invoke serve

To serve the generated site with automatic browser reloading every time a
change is detected, first python -m pip install livereload, then use the
following command::

text
invoke livereload

If during the pelican-quickstart process you answered "yes" when asked
whether you want to upload your site via SSH, you can use the following command
to publish your site via rsync over SSH::

text
invoke publish

These are just a few of the commands available by default, so feel free to
explore tasks.py and see what other commands are available. More
importantly, don't hesitate to customize tasks.py to suit your specific
needs and preferences.

Make

A Makefile is also automatically created for you when you say "yes" to the
relevant question during the pelican-quickstart process. The advantage of
this method is that the make command is built into most POSIX systems and
thus doesn't require installing anything else in order to use it. The downside
is that non-POSIX systems (e.g., Windows) do not include make, and
installing it on those systems can be a non-trivial task.

If you want to use make to generate your site using the settings in
pelicanconf.py, run::

text
make html

To generate the site for production, using the settings in publishconf.py,
run::

text
make publish

If you'd prefer to have Pelican automatically regenerate your site every time a
change is detected (which is handy when testing locally), use the following
command instead::

text
make regenerate

To serve the generated site so it can be previewed in your browser at
http://localhost:8000/::

text
make serve

Normally you would need to run make regenerate and make serve in two
separate terminal sessions, but you can run both at once via::

text
make devserver

The above command will simultaneously run Pelican in regeneration mode as well
as serve the output at http://localhost:8000.

When you're ready to publish your site, you can upload it via the method(s) you
chose during the pelican-quickstart questionnaire. For this example, we'll
use rsync over ssh::

text
make rsync_upload

That's it! Your site should now be live.

(The default Makefile and devserver.sh scripts use the python and
pelican executables to complete its tasks. If you want to use different
executables, such as python3, you can set the PY and PELICAN
environment variables, respectively, to override the default executable names.)

.. _Invoke: https://www.pyinvoke.org/


Quickstart (`docs/quickstart.rst`)

Quickstart
##########

Reading through all the documentation is highly recommended, but for the truly
impatient, following are some quick steps to get started.

Installation

Install Pelican (and optionally Markdown if you intend to use it) on Python
|min_python| by running the following command in your preferred terminal, prefixing
with sudo if permissions warrant::

text
python -m pip install "pelican[markdown]"

Create a project

First, choose a name for your project, create an appropriately-named directory
for your site, and switch to that directory::

text
mkdir -p ~/projects/yoursite
cd ~/projects/yoursite

Create a skeleton project via the pelican-quickstart command, which begins
by asking some questions about your site::

text
pelican-quickstart

For questions that have default values denoted in brackets, feel free to use
the Return key to accept those default values [#tzlocal_fn]_. When asked for
your URL prefix, enter your domain name as indicated (e.g.,
https://example.com).

Create an article

You cannot run Pelican until you have created some content. Use your preferred
text editor to create your first article with the following content::

text
Title: My First Review
Date: 2010-12-03 10:20
Category: Review

Following is a review of my favorite mechanical keyboard.

Given that this example article is in Markdown format, save it as
~/projects/yoursite/content/keyboard-review.md.

Generate your site

From your project root directory, run the pelican command to generate your site::

text
pelican content

Your site has now been generated inside the output/ directory. (You may see
a warning related to feeds, but that is normal when developing locally and can
be ignored for now.)

Preview your site

Open a new terminal session, navigate to your project root directory, and
run the following command to launch Pelican's web server::

text
pelican --listen

Preview your site by navigating to http://localhost:8000/ in your browser.

Continue reading the other documentation sections for more detail, and check
out the Pelican wiki's Tutorials_ page for links to community-published
tutorials.

.. _Tutorials: https://github.com/getpelican/pelican/wiki/Tutorials

Footnotes

.. [#tzlocal_fn] You can help localize default fields by installing the
optional tzlocal <https://pypi.org/project/tzlocal/>_
module.


Report (`docs/report.rst`)

Some history about Pelican
##########################

.. warning::

text
This page comes from a report the original author (Alexis Mรฉtaireau) wrote
right after writing Pelican, in December 2010. The information may not be
up-to-date.

Pelican is a simple static blog generator. It parses markup files (Markdown or
reStructuredText for now) and generates an HTML folder with all the files in
it. I've chosen to use Python to implement Pelican because it seemed to be
simple and to fit to my needs. I did not wanted to define a class for each
thing, but still wanted to keep my things loosely coupled. It turns out that it
was exactly what I wanted. From time to time, thanks to the feedback of some
users, it took me a very few time to provide fixes on it. So far, I've
re-factored the Pelican code by two
times; each time took less than 30 minutes.

Use case

I was previously using WordPress, a solution you can host on a web server to
manage your blog. Most of the time, I prefer using markup languages such as
Markdown or reStructuredText to type my articles. To do so, I use vim. I think
it is important to let the people choose the tool they want to write the
articles. In my opinion, a blog manager should just allow you to take any kind
of input and transform it to a weblog. That's what Pelican does. You can write
your articles using the tool you want, and the markup language you want, and
then generate a static HTML weblog.

.. image:: _static/overall.png

To be flexible enough, Pelican has template support, so you can easily write
your own themes if you want to.

Design process

Pelican came from a need I have. I started by creating a single file
application, and I have make it grow to support what it does by now. To start,
I wrote a piece of documentation about what I wanted to do. Then, I created the
content I wanted to parse (the reStructuredText files) and started
experimenting with the code. Pelican was 200 lines long and contained almost
ten functions and one class when it was first usable.

I have been facing different problems all over the time and wanted to add
features to Pelican while using it. The first change I have done was to add the
support of a settings file. It is possible to pass the options to the command
line, but can be tedious if there is a lot of them. In the same way, I have
added the support of different things over time: Atom feeds, multiple themes,
multiple markup support, etc. At some point, it appears that the "only one
file" mantra was not good enough for Pelican, so I decided to rework a bit all
that, and split this in multiple different files.

Iโ€™ve separated the logic in different classes and concepts:

  • writers are responsible of all the writing process of the files.
    They are responsible of writing .html files, RSS feeds and so on. Since those
    operations are commonly used, the object is created once, and then passed to
    the generators.

  • readers are used to read from various formats (Markdown and
    reStructuredText for now, but the system is extensible). Given a file, they
    return metadata (author, tags, category, etc) and content (HTML formatted).

  • generators generate the different outputs. For instance, Pelican
    comes with an ArticlesGenerator and PagesGenerator, into others. Given a
    configuration, they can do whatever you want them to do. Most of the time
    it's generating files from inputs (user inputs and files).

I also deal with contents objects. They can be Articles, Pages,
Quotes, or whatever you want. They are defined in the contents.py
module and represent some content to be used by the program.

In more detail

Here is an overview of the classes involved in Pelican.

.. image:: _static/uml.jpg

The interface does not really exist, and I have added it only to clarify the
whole picture. I do use duck typing and not interfaces.

Internally, the following process is followed:

  • First of all, the command line is parsed, and some content from the user is
    used to initialize the different generator objects.

  • A context is created. It contains the settings from the command line and
    a settings file if provided.

  • The generate_context method of each generator is called, updating
    the context.

  • The writer is created and given to the generate_output method of each
    generator.

I make two calls because it is important that when the output is generated by
the generators, the context will not change. In other words, the first method
generate_context should modify the context, whereas the second
generate_output method should not.

Then, it is up to the generators to do what the want, in the
generate_context and generate_content method. Taking the
ArticlesGenerator class will help to understand some others concepts. Here
is what happens when calling the generate_context method:

  • Read the folder โ€œpathโ€, looking for restructured text files, load each of
    them, and construct a content object (Article) with it. To do so, use
    Reader objects.
  • Update the context with all those articles.

Then, the generate_content method uses the context and the writer
to generate the wanted output.


Settings (`docs/settings.rst`)

Settings
########

Pelican is configurable thanks to a settings file you can pass to the command
line::

text
pelican content -s path/to/your/pelicanconf.py

If you used the pelican-quickstart command, your primary settings file will
be named pelicanconf.py by default.

You can also specify settings via -e / --extra-settings option
flags. It will override default settings as well as any defined within the
setting file. Note that values must follow JSON notation::

text
pelican content -e SITENAME='"A site"' READERS='{"html": null}' CACHE_CONTENT=true

Environment variables can also be used here but must be escaped appropriately::

text
pelican content -e API_KEY=''\"$API_KEY\"''

.. note::

When experimenting with different settings (especially the metadata ones)
caching may interfere and the changes may not be visible. In such cases
disable caching with LOAD_CONTENT_CACHE = False or use the
--ignore-cache command-line switch.

Settings are configured in the form of a Python module (a file). There is an
example settings file <https://raw.githubusercontent.com/getpelican/pelican/main/samples/pelican.conf.py>_
available for reference.

To see a list of current settings in your environment, including both default
and any customized values, run the following command (append one or more
specific setting names as arguments to see values for those settings only)::

text
pelican --print-settings

All the setting identifiers must be set in all-caps, otherwise they will not be
processed. Setting values that are numbers (5, 20, etc.), booleans (True,
False, None, etc.), dictionaries, or tuples should not be enclosed in
quotation marks. All other values (i.e., strings) must be enclosed in
quotation marks.

Unless otherwise specified, settings that refer to paths can be either absolute
or relative to the configuration file. The settings you define in the
configuration file will be passed to the templates, which allows you to use
your settings to add site-wide content.

Here is a list of settings for Pelican:

Basic settings

.. data:: USE_FOLDER_AS_CATEGORY

When you don't specify a category in your post metadata, set this setting to
True, and organize your articles in subfolders, the subfolder will
become the category of your post. If set to False, DEFAULT_CATEGORY
will be used as a fallback. The default is True.

.. data:: DEFAULT_CATEGORY

The default category to fall back on. The default is "misc".

To publish articles without any category, set DEFAULT_CATEGORY = None
and USE_FOLDER_AS_CATEGORY = False. Articles will then only have a
category if one is specified in their metadata.

.. data:: DISPLAY_PAGES_ON_MENU

Whether to display pages on the menu of the template. Templates may or may
not honor this setting. The default is True.

.. data:: DISPLAY_CATEGORIES_ON_MENU

Whether to display categories on the menu of the template. Templates may or
not honor this setting. The default is True.

.. data:: DOCUTILS_SETTINGS

Extra configuration settings for the docutils publisher (applicable only to
reStructuredText). See Docutils Configuration_ settings for more details.
The default is {} with no extra configuration settings.

.. data:: DELETE_OUTPUT_DIRECTORY

Delete the output directory, and all of its contents, before generating
new files. This can be useful in preventing older, unnecessary files from
persisting in your output. However, this is a destructive setting and
should be handled with extreme care.
The default is False.

.. data:: OUTPUT_RETENTION

A list of filenames that should be retained and not deleted from the output
directory. One use case would be the preservation of version control data.

Example::

text
OUTPUT_RETENTION = [".hg", ".git", ".bzr"]

The default is [].

.. data:: JINJA_ENVIRONMENT

A dictionary of custom Jinja2 environment variables you want to use. This
also includes a list of extensions you may want to include. See Jinja Environment documentation_. The default is
{"extensions": [], "trim_blocks": True, "lstrip_blocks": True}.

.. data:: JINJA_FILTERS

A dictionary of custom Jinja2 filters you want to use. The dictionary
should map the filtername to the filter function.

Example::

text
import sys
sys.path.append("to/your/path")

from custom_filter import urlencode_filter
JINJA_FILTERS = {"urlencode": urlencode_filter}

See: Jinja custom filters documentation_. The default is {}.

.. data:: JINJA_GLOBALS

A dictionary of custom objects to map into the Jinja2 global environment
namespace. The dictionary should map the global name to the global
variable/function. See: Jinja global namespace documentation_. The
default is {}.

.. data:: JINJA_TESTS

A dictionary of custom Jinja2 tests you want to use. The dictionary should
map test names to test functions. See: Jinja custom tests documentation_.
The default is {}.

.. data:: LOG_FILTER

A list of tuples containing the logging level (up to warning) and the
message to be ignored.

Example::

text
LOG_FILTER = [(logging.WARN, "TAG_SAVE_AS is set to False")]

The default is [].

.. data:: READERS

A dictionary of file extensions / Reader classes for Pelican to process or
ignore.

For example, to avoid processing .html files, set::

text
READERS = {"html": None}

To add a custom reader for the foo extension, set::

text
READERS = {"foo": FooReader}

The default is {}.

.. data:: IGNORE_FILES

A list of Unix glob patterns. Files and directories matching any of these patterns
or any of the commonly hidden files and directories set by watchfiles.DefaultFilter
will be ignored by the processor. For example, the default ["**/.*"] will
ignore "hidden" files and directories, and ["__pycache__"] would ignore
Python 3's bytecode caches.

For a full list of the commonly hidden files set by watchfiles.DefaultFilter,
please refer to the watchfiles documentation_.

The default is ["**/.*"].

.. data:: MARKDOWN

Extra configuration settings for the Markdown processor. Refer to the Python
Markdown documentation's Options section <https://python-markdown.github.io/reference/#markdown>_ for a complete
list of supported options. The extensions option will be automatically
computed from the extension_configs option.

The default is::

text
MARKDOWN = {
        "extension_configs": {
            "markdown.extensions.codehilite": {"css_class": "highlight"},
            "markdown.extensions.extra": {},
            "markdown.extensions.meta": {},
        },
        "output_format": "html5",
    }

.. Note::
The dictionary defined in your settings file will replace this default
one.

.. data:: OUTPUT_PATH

Where to output the generated files. This should correspond to your web
server's virtual host root directory.

The default is "output".

.. data:: PATH

Path to content directory to be processed by Pelican. If undefined, and
content path is not specified via an argument to the pelican command,
Pelican will default to ".", the current working directory.

.. data:: PAGE_PATHS

A list of directories and files to look at for pages, relative to PATH.
The default is ["pages"].

.. data:: PAGE_EXCLUDES

A list of directories to exclude when looking for pages in addition to
ARTICLE_PATHS. The default is [].

.. data:: ARTICLE_PATHS

A list of directories and files to look at for articles, relative to
PATH. The default is [""].

.. data:: ARTICLE_EXCLUDES

A list of directories to exclude when looking for articles in addition to
PAGE_PATHS. The default is [].

.. data:: OUTPUT_SOURCES

Set to True if you want to copy the articles and pages in their original
format (e.g. Markdown or reStructuredText) to the specified OUTPUT_PATH.
The default is False.

.. data:: OUTPUT_SOURCES_EXTENSION

Controls the extension that will be used by the SourcesGenerator. Defaults
to .text. If not a valid string the default value will be used. The
default is ".text".

.. data:: PLUGINS

The list of plugins to load. See :ref:plugins. The default is None.

.. data:: PLUGIN_PATHS

A list of directories where to look for plugins. See :ref:plugins. The
default is [].

.. data:: SITENAME

Your site's name. The default is "A Pelican Blog".

.. data:: SITEURL

Base URL of your web site. Not defined by default, so it is best to specify
your SITEURL; if you do not, feeds will not be generated with
properly-formed URLs. If your site is available via HTTPS, this setting
should begin with https:// โ€” otherwise use http://. Then append your
domain, with no trailing slash at the end. Example: SITEURL = "https://example.com"

The default is "", the blank string.

.. data:: STATIC_PATHS

A list of directories (relative to PATH) in which to look for static
files. Such files will be copied to the output directory without
modification. Articles, pages, and other content source files will normally
be skipped, so it is safe for a directory to appear both here and in
PAGE_PATHS or ARTICLE_PATHS. Pelican's default settings include the
"images" directory here. The default is ["images"].

.. data:: STATIC_EXCLUDES

A list of directories to exclude when looking for static files. The default
is [].

.. data:: STATIC_EXCLUDE_SOURCES

If set to False, content source files will not be skipped when copying files
found in STATIC_PATHS. This setting is for backward compatibility with
Pelican releases before version 3.5. It has no effect unless
STATIC_PATHS contains a directory that is also in ARTICLE_PATHS or
PAGE_PATHS. If you are trying to publish your site's source files,
consider using the OUTPUT_SOURCES setting instead. The default is
True.

.. data:: STATIC_CREATE_LINKS

Create links instead of copying files. If the content and output directories
are on the same device, then create hard links. Falls back to symbolic
links if the output directory is on a different filesystem. If symlinks are
created, don't forget to add the -L or --copy-links option to rsync
when uploading your site. The default is False.

.. data:: STATIC_CHECK_IF_MODIFIED

If set to True, and STATIC_CREATE_LINKS is False, compare mtimes
of content and output files, and only copy content files that are newer than
existing output files. The default is False.

.. data:: TYPOGRIFY

If set to True, several typographical improvements will be incorporated into
the generated HTML via the Typogrify <https://pypi.org/project/typogrify/>_ library, which can be installed
via: python -m pip install typogrify. The default is False.

.. data:: TYPOGRIFY_IGNORE_TAGS

A list of tags for Typogrify to ignore. By default Typogrify will ignore
pre and code tags. This requires that Typogrify version 2.0.4 or
later is installed. The default is [].

.. data:: TYPOGRIFY_OMIT_FILTERS

A list of Typogrify filters to skip. Allowed values are: "amp",
"smartypants", "caps", "initial_quotes", "widont". By
default, no filter is omitted (in other words, all filters get applied). This
setting requires that Typogrify version 2.1.0 or later is installed. The
default is [].

.. data:: TYPOGRIFY_DASHES

This setting controls how Typogrify sets up the Smartypants filter to
interpret multiple dash/hyphen/minus characters. A single ASCII dash
character (-) is always rendered as a hyphen. The default setting
does not handle en-dashes and converts double-hyphens into em-dashes. The
oldschool setting renders both en-dashes and em-dashes when it sees two
(--) and three (---) hyphen characters, respectively. The
oldschool_inverted setting turns two hyphens into an em-dash and three
hyphens into an en-dash. The default is "default".

.. data:: SUMMARY_MAX_LENGTH

When creating a short summary of an article, this will be the default length
(measured in words) of the text created. This only applies if your content
does not otherwise specify a summary. Setting to None will cause the
summary to be a copy of the original content. The default is 50.

.. data:: SUMMARY_MAX_PARAGRAPHS

When creating a short summary of an article, this will be the number of
paragraphs to use as the summary. This only applies if your content
does not otherwise specify a summary. Setting to None will cause the
summary to use the whole text (up to SUMMARY_MAX_LENGTH) instead of just
the first N paragraphs. The default is None.

.. data:: SUMMARY_END_SUFFIX

When creating a short summary of an article and the result was truncated to
match the required word length, this will be used as the truncation suffix.
The default is "โ€ฆ".

.. data:: WITH_FUTURE_DATES

If disabled, content with dates in the future will get a default status of
draft. See :ref:reading_only_modified_content for caveats. The default
is True.

.. data:: INTRASITE_LINK_REGEX

Regular expression that is used to parse internal links. Default syntax when
linking to internal files, tags, etc., is to enclose the identifier, say
filename, in {} or ||. Identifier between { and } goes
into the what capturing group. For details see
:ref:ref-linking-to-internal-content. The default is
"[{|](?P<what>.*?)[|}]".

.. data:: PYGMENTS_RST_OPTIONS

A list of default Pygments settings for your reStructuredText code blocks.
See :ref:internal_pygments_options for a list of supported options. The
default is {}.

.. data:: CACHE_CONTENT

If True, saves content in caches. See
:ref:reading_only_modified_content for details about caching. The default
is False.

.. data:: CONTENT_CACHING_LAYER

If set to "reader", save only the raw content and metadata returned by
readers. If set to "generator", save processed content objects. The
default is "reader".

.. data:: CACHE_PATH

Directory in which to store cache files. The default is "cache".

.. data:: GZIP_CACHE

If True, use gzip to (de)compress the cache files. The default is
True.

.. data:: CHECK_MODIFIED_METHOD

Controls how files are checked for modifications.

  • If set to "mtime", the modification time of the file is
    checked.
  • If set to a name of a function provided by the hashlib
    module, e.g. "md5", the file hash is checked.

The default is "mtime".

.. data:: LOAD_CONTENT_CACHE

If True, load unmodified content from caches. The default is False.

.. data:: FORMATTED_FIELDS

A list of metadata fields containing reST/Markdown content to be parsed and
translated to HTML. The default is ["summary"].

.. data:: PORT

The TCP port to serve content from the output folder via HTTP when pelican
is run with --listen. The default is 8000.

.. data:: BIND

The IP to which to bind the HTTP server. The default is "127.0.0.1".

.. _url-settings:

URL settings

The first thing to understand is that there are currently two supported methods
for URL formation: relative and absolute. Relative URLs are useful when
testing locally, and absolute URLs are reliable and most useful when
publishing. One method of supporting both is to have one Pelican configuration
file for local development and another for publishing. To see an example of
this type of setup, use the pelican-quickstart script as described in the
:doc:Installation section, which will produce two separate
configuration files for local development and publishing, respectively.

You can customize the URLs and locations where files will be saved. The
*_URL and *_SAVE_AS variables use Python's format strings. These
variables allow you to place your articles in a location such as
{slug}/index.html and link to them as {slug} for clean URLs (see
example below). These settings give you the flexibility to place your articles
and pages anywhere you want.

.. note::
If a *_SAVE_AS setting contains a parent directory that doesn't match
the parent directory inside the corresponding *_URL setting, this may
cause Pelican to generate unexpected URLs in a few cases, such as when
using the {attach} syntax.

If you don't want that flexibility and instead prefer that your generated
output paths mirror your source content's filesystem path hierarchy, try the
following settings::

text
PATH_METADATA = r"(?P.*)\..*"
ARTICLE_URL = ARTICLE_SAVE_AS = PAGE_URL = PAGE_SAVE_AS = "{path_no_ext}.html"

Otherwise, you can use a variety of file metadata attributes within URL-related
settings:

  • slug
  • date
  • lang
  • author
  • category

Example usage::

ARTICLE_URL = "posts/{date:%Y}/{date:%b}/{date:%d}/{slug}/"
ARTICLE_SAVE_AS = "posts/{date:%Y}/{date:%b}/{date:%d}/{slug}/index.html"
PAGE_URL = "pages/{slug}/"
PAGE_SAVE_AS = "pages/{slug}/index.html"

This would save your articles into something like
/posts/2011/Aug/07/sample-post/index.html, save your pages into
/pages/about/index.html, and render them available at URLs of
/posts/2011/Aug/07/sample-post/ and /pages/about/, respectively.

.. note::
If you specify a datetime directive, it will be substituted using the
input files' date metadata attribute. If the date is not specified for a
particular file, Pelican will rely on the file's mtime timestamp. Check
the Python datetime documentation_ for more information.

.. _Python datetime documentation:
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior

.. data:: RELATIVE_URLS

Defines whether Pelican should use document-relative URLs or not. Only set
this to True when developing/testing and only if you fully understand
the effect it can have on links/feeds. The default is False.

.. data:: ARTICLE_URL

The URL to refer to an article. The default is "{slug}.html".

.. data:: ARTICLE_SAVE_AS

The place where we will save an article. The default is "{slug}.html".

.. data:: ARTICLE_LANG_URL

The URL to refer to an article which doesn't use the default language.
The default is "{slug}-{lang}.html".

.. data:: ARTICLE_LANG_SAVE_AS

The place where we will save an article which doesn't use the default
language. The default is "{slug}-{lang}.html".

.. data:: DRAFT_URL

The URL to refer to an article draft. The default is
"drafts/{slug}.html".

.. data:: DRAFT_SAVE_AS

The place where we will save an article draft. The default is "drafts/{slug}.html".

.. data:: DRAFT_LANG_URL

The URL to refer to an article draft which doesn't use the default language.
The default is "drafts/{slug}-{lang}.html".

.. data:: DRAFT_LANG_SAVE_AS

The place where we will save an article draft which doesn't use the default
language. The default is "drafts/{slug}-{lang}.html".

.. data:: PAGE_URL

The URL we will use to link to a page. The default is
"pages/{slug}.html".

.. data:: PAGE_SAVE_AS

The location we will save the page. This value has to be the same as
PAGE_URL or you need to use a rewrite in your server config. The default
is "pages/{slug}.html".

.. data:: PAGE_LANG_URL

The URL we will use to link to a page which doesn't use the default
language. The default is "pages/{slug}-{lang}.html".

.. data:: PAGE_LANG_SAVE_AS

The location we will save the page which doesn't use the default language.
The default is "pages/{slug}-{lang}.html".

.. data:: DRAFT_PAGE_URL

The URL used to link to a page draft. The default is
"drafts/pages/{slug}.html".

.. data:: DRAFT_PAGE_SAVE_AS

The actual location a page draft is saved at. The default is
"drafts/pages/{slug}.html".

.. data:: DRAFT_PAGE_LANG_URL

The URL used to link to a page draft which doesn't use the default
language. The default is "drafts/pages/{slug}-{lang}.html".

.. data:: DRAFT_PAGE_LANG_SAVE_AS

The actual location a page draft which doesn't use the default language is
saved at. The default is "drafts/pages/{slug}-{lang}.html".

.. data:: AUTHOR_URL

The URL to use for an author. The default is "author/{slug}.html".

.. data:: AUTHOR_SAVE_AS

The location to save an author. The default is "author/{slug}.html".

.. data:: CATEGORY_URL

The URL to use for a category. The default is "category/{slug}.html".

.. data:: CATEGORY_SAVE_AS

The location to save a category. The default is "category/{slug}.html".
Set this to "" to disable category pages. Articles still keep their
categories, which can be used in URL patterns such as ARTICLE_SAVE_AS.
To disable all category output, also set CATEGORIES_SAVE_AS = None
and CATEGORY_FEED_ATOM = None (as well as CATEGORY_FEED_RSS, if
you have enabled it).

.. data:: TAG_URL

The URL to use for a tag. The default is "tag/{slug}.html".

.. data:: TAG_SAVE_AS

The location to save the tag page. The default is "tag/{slug}.html".

.. note::

text
If you do not want one or more of the default pages to be created (e.g.,
you are the only author on your site and thus do not need an Authors page),
set the corresponding ``*_SAVE_AS`` setting to ``""`` to prevent the
relevant page from being generated.

Pelican can optionally create per-year, per-month, and per-day archives of your
posts. These secondary archives are disabled by default but are automatically
enabled if you supply format strings for their respective _SAVE_AS
settings. Period archives fit intuitively with the hierarchical model of web
URLs and can make it easier for readers to navigate through the posts you've
written over time.

Example usage::

YEAR_ARCHIVE_SAVE_AS = "posts/{date:%Y}/index.html"
YEAR_ARCHIVE_URL = "posts/{date:%Y}/"
MONTH_ARCHIVE_SAVE_AS = "posts/{date:%Y}/{date:%b}/index.html"
MONTH_ARCHIVE_URL = "posts/{date:%Y}/{date:%b}/"

With these settings, Pelican will create an archive of all your posts for the
year at (for instance) posts/2011/index.html and an archive of all your
posts for the month at posts/2011/Aug/index.html. These can be accessed
through the URLs posts/2011/ and posts/2011/Aug/, respectively.

.. note::
Period archives work best when the final path segment is index.html.
This way a reader can remove a portion of your URL and automatically arrive
at an appropriate archive of posts, without having to specify a page name.

.. data:: YEAR_ARCHIVE_SAVE_AS

The location to save per-year archives of your posts. The default is "",
i.e. this is disabled by default.

.. data:: YEAR_ARCHIVE_URL

The URL to use for per-year archives of your posts. You should set this if
you enable per-year archives. The default is "", i.e. this is disabled
by default.

.. data:: MONTH_ARCHIVE_SAVE_AS

The location to save per-month archives of your posts. The default is
"", i.e. this is disabled by default.

.. data:: MONTH_ARCHIVE_URL

The URL to use for per-month archives of your posts. You should set this if
you enable per-month archives. The default is "", i.e. this is disabled
by default.

.. data:: DAY_ARCHIVE_SAVE_AS

The location to save per-day archives of your posts. The default is "",
i.e. this is disabled by default.

.. data:: DAY_ARCHIVE_URL

The URL to use for per-day archives of your posts. You should set this if
you enable per-day archives. The default is "", i.e. this is disabled by
default.

DIRECT_TEMPLATES work a bit differently than noted above. Only the
_SAVE_AS settings are available, but it is available for any direct
template.

.. data:: ARCHIVES_SAVE_AS

The location to save the article archives page. The default is "archives.html".

.. data:: AUTHORS_SAVE_AS

The location to save the author list. The default is "authors.html".

.. data:: CATEGORIES_SAVE_AS

The location to save the category list. The default is "categories.html".

.. data:: TAGS_SAVE_AS

The location to save the tag list. The default is "tags.html".

.. data:: INDEX_SAVE_AS

The location to save the list of all articles. The default is "index.html".

URLs for direct template pages are theme-dependent. Some themes use
corresponding *_URL setting as string, while others hard-code them:
"archives.html", "authors.html", "categories.html",
"tags.html".

.. data:: SLUGIFY_SOURCE

Specifies from where you want the slug to be automatically generated. Can be
set to title to use the "Title:" metadata tag or basename to use the
article's file name when creating the slug. The default is "title".

.. data:: SLUGIFY_USE_UNICODE

Allow Unicode characters in slugs. Set True to keep Unicode characters
in auto-generated slugs. Otherwise, Unicode characters will be replaced
with ASCII equivalents. The default is False.

.. data:: SLUGIFY_PRESERVE_CASE

Preserve uppercase characters in slugs. Set True to keep uppercase
characters from SLUGIFY_SOURCE as-is. The default is False.

.. data:: SLUG_REGEX_SUBSTITUTIONS

Regex substitutions to make when generating slugs of articles and pages.
Specified as a list of pairs of (from, to) which are applied in order,
ignoring case. The default substitutions have the effect of removing
non-alphanumeric characters and converting internal whitespace to dashes.
Apart from these substitutions, slugs are always converted to lowercase
ascii characters and leading and trailing whitespace is stripped. Useful for
backward compatibility with existing URLs. The default is::

text
[
       (r"[^\w\s-]", ""),   # remove non-alphabetical/whitespace/"-" chars
       (r"(?u)\A\s*", ""),  # strip leading whitespace
       (r"(?u)\s*\Z", ""),  # strip trailing whitespace
       (r"[-\s]+", "-"),    # reduce multiple whitespace or "-" to single "-"
   ]

.. data:: AUTHOR_REGEX_SUBSTITUTIONS

Regex substitutions for author slugs. The default is
SLUG_REGEX_SUBSTITUTIONS.

.. data:: CATEGORY_REGEX_SUBSTITUTIONS

Regex substitutions for category slugs. The default is
SLUG_REGEX_SUBSTITUTIONS.

.. data:: TAG_REGEX_SUBSTITUTIONS

Regex substitutions for tag slugs. The default is
SLUG_REGEX_SUBSTITUTIONS.

Time and Date

.. data:: TIMEZONE

The timezone used in the date information, to generate Atom and RSS feeds.

If no timezone is defined, UTC is assumed. This means that the generated
Atom and RSS feeds will contain incorrect date information if your locale is
not UTC.

Pelican issues a warning in case this setting is not defined, as it was not
mandatory in previous versions.

Have a look at the wikipedia page_ to get a list of valid timezone values.

.. _the wikipedia page: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones

.. data:: DEFAULT_DATE

The default date you want to use. If "fs", Pelican will use the file
system timestamp information (mtime) if it can't get date information from
the metadata. If given any other string, it will be parsed by the same
method as article metadata. If set to a tuple object, the default datetime
object will instead be generated by passing the tuple to the
datetime.datetime constructor. The default is None.

.. data:: DEFAULT_DATE_FORMAT

The default date format you want to use. The default is "%a %d %B %Y",
e.g. "Mon 06 April 2026".

.. data:: DATE_FORMATS

If you manage multiple languages, you can set the date formatting here.

If no DATE_FORMATS are set, Pelican will fall back to
DEFAULT_DATE_FORMAT. If you need to maintain multiple languages with
different date formats, you can set the DATE_FORMATS dictionary using
the language name (lang metadata in your post content) as the key.

In addition to the standard C89 strftime format codes that are listed in
Python datetime documentation_, you can use the - character between
% and the format character to remove any leading zeros. For example,
%d/%m/%Y will output 01/01/2014 whereas %-d/%-m/%Y will result
in 1/1/2014.

.. parsed-literal::

text
DATE_FORMATS = {
       "en": "%a, %d %b %Y",
       "jp": "%Y-%m-%d(%a)",
   }

It is also possible to set different locale settings for each language by
using a (locale, format) tuple as a dictionary value which will override
the LOCALE setting:

.. parsed-literal::

text
# On Unix/Linux
  DATE_FORMATS = {
      "en": ("en_US", "%a, %d %b %Y"),
      "jp": ("ja_JP", "%Y-%m-%d(%a)"),
  }

  # On Windows
  DATE_FORMATS = {
      "en": ("usa", "%a, %d %b %Y"),
      "jp": ("jpn", "%Y-%m-%d(%a)"),
  }

The default is {}.

.. data:: LOCALE

Change the locale. A list of locales can be provided here or a single
string representing one locale. When providing a list, all the locales will
be tried until one works.

You can set locale to further control date format:

.. parsed-literal::

text
LOCALE = [
      "usa", "jpn",      # On Windows
      "en_US", "ja_JP"   # On Unix/Linux
  ]

For a list of available locales refer to locales on Windows_ or on
Unix/Linux, use the locale -a command; see manpage
locale(1)_ for more information. The default is the system locale.

.. _Jinja custom filters documentation: https://jinja.palletsprojects.com/en/latest/api/#custom-filters
.. _Jinja global namespace documentation: https://jinja.palletsprojects.com/en/latest/api/#the-global-namespace
.. _Jinja custom tests documentation: https://jinja.palletsprojects.com/en/latest/api/#custom-tests

.. _locales on Windows: https://www.microsoft.com/en-us/download/details.aspx?id=55979

.. _locale(1): https://linux.die.net/man/1/locale

.. _template_pages:

Template pages

.. data:: TEMPLATE_PAGES

A mapping containing template pages that will be rendered with the blog
entries.

If you want to generate custom pages besides your blog entries, you can
point any Jinja2 template file with a path pointing to the file and the
destination path for the generated file.

For instance, if you have a blog with three static pages โ€” a list of books,
your resume, and a contact page โ€” you could have::

text
TEMPLATE_PAGES = {
       "src/books.html": "dest/books.html",
       "src/resume.html": "dest/resume.html",
       "src/contact.html": "dest/contact.html",
   }

The default is {}.

.. data:: TEMPLATE_EXTENSIONS

The extensions to use when looking up template files from template names.
The default is [".html"].

.. data:: DIRECT_TEMPLATES

List of templates that are used directly to render content. Typically direct
templates are used to generate index pages for collections of content (e.g.,
category and tag index pages). If the author, category and tag collections are not
needed, set DIRECT_TEMPLATES = ["index", "archives"]

DIRECT_TEMPLATES are searched for over paths maintained in
THEME_TEMPLATES_OVERRIDES.

The default is ["index", "tags", "categories", "authors", "archives"].

Metadata

.. data:: AUTHOR

Default author (usually your name). The default is None, which removes the byline.

.. data:: DEFAULT_METADATA

The default metadata you want to use for all articles and pages. The default
is {}.

.. data:: FILENAME_METADATA

The regexp that will be used to extract any metadata from the filename. All
named groups that are matched will be set in the metadata object. The
default value is r"(?P<date>\d{4}-\d{2}-\d{2}).*" and will only extract
the date from the filename.

For example, if your source file were titled 2026-04-30_blog-article.md,
you could extract both the date and the slug::

text
FILENAME_METADATA = r"(?P<date>\d{4}-\d{2}-\d{2})_(?P<slug>.*)"

giving you a date of April 30, 2026 and a slug of blog-article.

See also SLUGIFY_SOURCE. The default is
r"(?P<date>\d{4}-\d{2}-\d{2}).*", i.e. it assumed your filenames start
with an ISO-style date, e.g. 2026-04-30.

See also, FILENAME_METADATA.

.. data:: PATH_METADATA

Like FILENAME_METADATA, but parsed from a page's full path relative to
the content source directory, include the source filename. The default
value is "".

For example, if your source files were stored in folders by year and then my
month, with the filename being the day of the month, (e.g.
2026/04/30.rst) you could extract that with::

text
PATH_METADATA = r"(?P<date>\d{4}/\d{2}/\d{2}).*"

(The above works on Windows as well.)

See also FILENAME_METADATA.

.. data:: EXTRA_PATH_METADATA

Extra metadata dictionaries keyed by relative path. Relative paths require
correct OS-specific directory separators (i.e. / in UNIX and \ in Windows)
unlike some other Pelican file settings. Paths to a directory apply to all
files under it. The most-specific path wins conflicts.

Not all metadata needs to be :ref:embedded in source file itself . For example, blog posts are often named following a
YYYY-MM-DD-SLUG.rst pattern, or nested into YYYY/MM/DD-SLUG
directories. To extract metadata from the filename or path, set
FILENAME_METADATA or PATH_METADATA to regular expressions that use
Python's group name notation_ (?P<name>โ€ฆ). If you want to attach
additional metadata but don't want to encode it in the path, you can set
EXTRA_PATH_METADATA:

.. parsed-literal::

text
EXTRA_PATH_METADATA = {
       "relative/path/to/file-1": {
           "key-1a": "value-1a",
           "key-1b": "value-1b",
       },
       "relative/path/to/file-2": {
           "key-2": "value-2",
       },
   }

This can be a convenient way to shift the output location of a particular
file:

.. parsed-literal::

text
# Take advantage of the following defaults:
   # STATIC_SAVE_AS = "{path}"
   # STATIC_URL = "{path}"
   STATIC_PATHS = [
       "static/robots.txt",
   ]
   EXTRA_PATH_METADATA = {
       "static/robots.txt": {"path": "robots.txt"},
   }

.. _group name notation:
https://docs.python.org/3/library/re.html#regular-expression-syntax

The default is {}.

Feed settings

By default, Pelican uses Atom feeds. However, it is also possible to use RSS
feeds if you prefer.

Pelican generates category feeds as well as feeds for all your articles. It
does not generate feeds for tags by default, but it is possible to do so using
the TAG_FEED_ATOM and TAG_FEED_RSS settings:

.. data:: FEED_DOMAIN

The domain prepended to feed URLs. Since feed URLs should always be
absolute, it is highly recommended to define this (e.g.,
"https://feeds.example.com"). The default is SITEURL.

.. data:: FEED_ATOM

The location to save the Atom feed. The default is None, for no Atom
feed.

.. data:: FEED_ATOM_URL

Relative URL of the Atom feed. If not set, FEED_ATOM is used both for
save location and URL. The default is None.

.. data:: FEED_RSS

The location to save the RSS feed. The default is None, for no RSS feed.

.. data:: FEED_RSS_URL

Relative URL of the RSS feed. If not set, FEED_RSS is used both for save
location and URL. The default is None.

.. data:: FEED_ALL_ATOM

The location to save the all-posts Atom feed: this feed will contain all
posts regardless of their language. The default is "feeds/all.atom.xml".

.. data:: FEED_ALL_ATOM_URL

Relative URL of the all-posts Atom feed. If not set, FEED_ALL_ATOM is
used both for save location and URL. The default is None.

.. data:: FEED_ALL_RSS

The location to save the the all-posts RSS feed: this feed will contain all
posts regardless of their language. The default is None, for no
all-posts RSS feed.

.. data:: FEED_ALL_RSS_URL

Relative URL of the all-posts RSS feed. If not set, FEED_ALL_RSS is used
both for save location and URL. The default is None.

.. data:: CATEGORY_FEED_ATOM

The location to save the category Atom feeds. [2]_ The default is
"feeds/{slug}.atom.xml".

.. data:: CATEGORY_FEED_ATOM_URL

Relative URL of the category Atom feeds, including the {slug}
placeholder. [2]_ If not set, CATEGORY_FEED_ATOM is used both for save
location and URL. The default is None.

.. data:: CATEGORY_FEED_RSS

The location to save the category RSS feeds, including the {slug}
placeholder. [2]_ The default is None, for no RSS feed.

.. data:: CATEGORY_FEED_RSS_URL

Relative URL of the category RSS feeds, including the {slug}
placeholder. [2]_ If not set, CATEGORY_FEED_RSS is used both for save
location and URL. The default is None.

.. data:: AUTHOR_FEED_ATOM

The location to save the author Atom feeds. [2]_ The default is
"feeds/{slug}.atom.xml".

.. data:: AUTHOR_FEED_ATOM_URL

Relative URL of the author Atom feeds, including the {slug} placeholder.
[2]_ If not set, AUTHOR_FEED_ATOM is used both for save location and
URL. The default is None (not set).

.. data:: AUTHOR_FEED_RSS

The location to save the author RSS feeds. [2]_ The default is
"feeds/{slug}.rss.xml".

.. data:: AUTHOR_FEED_RSS_URL

Relative URL of the author RSS feeds, including the {slug} placeholder.
[2]_ If not set, AUTHOR_FEED_RSS is used both for save location and URL.
The default is None.

.. data:: TAG_FEED_ATOM

The location to save the tag Atom feed, including the {slug}
placeholder. [2]_ The default is None, for no tag feed.

.. data:: TAG_FEED_ATOM_URL

Relative URL of the tag Atom feed, including the {slug} placeholder.
[2]_ The default is None.

.. data:: TAG_FEED_RSS

Relative URL to output the tag RSS feed, including the {slug}
placeholder. If not set, TAG_FEED_RSS is used both for save location and
URL. The default is None, for no tag feed.

.. data:: FEED_MAX_ITEMS

Maximum number of items allowed in a feed. Setting to None will cause the
feed to contains every article. The default is 100.

.. data:: RSS_FEED_SUMMARY_ONLY

Only include item summaries in the description tag of RSS feeds. If set
to False, the full content will be included instead. This setting
doesn't affect Atom feeds, only RSS ones. The default is True.

.. data:: FEED_APPEND_REF

If set to True, ?ref=feed will be appended to links in generated
feeds for the purpose of referrer tracking. The default is False.

If you don't want to generate some or any of these feeds, set the above
variables to None.

.. [2] {slug} is replaced by name of the category / author / tag.

Pagination

The default behaviour of Pelican is to list all the article titles along with a
short description on the index page. While this works well for small-to-medium
sites, sites with a large quantity of articles will probably benefit from
paginating this list.

You can use the following settings to configure the pagination.

.. data:: DEFAULT_ORPHANS

The minimum number of articles allowed on the last page. Use this when you
don't want the last page to only contain a handful of articles. The default
is 0.

.. data:: DEFAULT_PAGINATION

The maximum number of articles to include on a page, not including orphans.
False to disable pagination. The default is False.

.. data:: PAGINATED_TEMPLATES

The templates to use pagination with, and the number of articles to include
on a page. If this value is None, it defaults to DEFAULT_PAGINATION.
The default is {"index": None, "tag": None, "category": None, "author": None}.

.. data:: PAGINATION_PATTERNS

A set of patterns that are used to determine advanced pagination output. The
default is::

text
(
       (1, "{name}{extension}", "{name}{extension}"),
       (2, "{name}{number}{extension}", "{name}{number}{extension}""),
   )

Using Pagination Patterns

By default, pages subsequent to .../foo.html are created as
.../foo2.html, etc. The PAGINATION_PATTERNS setting can be used to
change this. It takes a sequence of triples, where each triple consists of::

text
(minimum_page, page_url, page_save_as,)

For page_url and page_save_as, you may use a number of variables.
{url} and {save_as} correspond respectively to the *_URL and
*_SAVE_AS values of the corresponding page type (e.g. ARTICLE_SAVE_AS).
If {save_as} == foo/bar.html, then {name} == foo/bar and {extension} == .html. {base_name} equals {name} except that it strips trailing
/index if present. {number} equals the page number.

For example, if you want to leave the first page unchanged, but place
subsequent pages at .../page/2/ etc, you could set PAGINATION_PATTERNS
as follows::

PAGINATION_PATTERNS = (
(1, "{url}", "{save_as}"),
(2, "{base_name}/page/{number}/", "{base_name}/page/{number}/index.html"),
)

If you want a pattern to apply to the last page in the list, use -1
as the minimum_page value::

text
(-1, "{base_name}/last/", "{base_name}/last/index.html"),

Translations

Pelican offers a way to translate articles. See the :doc:Content <content>
section for more information.

.. data:: DEFAULT_LANG

The default language to use. The default is "en".

.. data:: ARTICLE_TRANSLATION_ID

The metadata attribute(s) used to identify which articles are translations
of one another. May be a string or a collection of strings. Set to None
or False to disable the identification of translations. The default is
"slug".

.. data:: PAGE_TRANSLATION_ID

The metadata attribute(s) used to identify which pages are translations of
one another. May be a string or a collection of strings. Set to None or
False to disable the identification of translations. The default is
"slug".

.. data:: TRANSLATION_FEED_ATOM

The location to save the Atom feed for translations. [3]_ The default is
"feeds/all-{lang}.atom.xml".

.. data:: TRANSLATION_FEED_ATOM_URL

Relative URL of the Atom feed for translations, including the {lang}
placeholder. [3]_ If not set, TRANSLATION_FEED_ATOM is used both for
save location and URL. The default is None.

.. data:: TRANSLATION_FEED_RSS

Where to put the RSS feed for translations. The default is None,
meaning no RSS feed.

.. data:: TRANSLATION_FEED_RSS_URL

Relative URL of the RSS feed for translations, including the {lang}
placeholder. [3]_ If not set, TRANSLATION_FEED_RSS is used both for save
location and URL. The default is None.

.. [3] {lang} is the language code

Ordering content

.. data:: NEWEST_FIRST_ARCHIVES

Order archives by newest first by date. (False: orders by date with older
articles first.) The default is True.

.. data:: REVERSE_CATEGORY_ORDER

Reverse the category order. (True: lists by reverse alphabetical order;
default lists alphabetically.) The default is False.

.. data:: ARTICLE_ORDER_BY

Defines how the articles (articles_page.object_list in the template) are
sorted. Valid options are: metadata as a string (use reversed- prefix
to reverse the sort order), special option "basename" which will use
the basename of the file (without path), or a custom function to extract the
sorting key from articles. Using a value of "date" will sort articles in
chronological order, while the default value, "reversed-date", will sort
articles by date in reverse order (i.e., newest article comes first). The
default is "reversed-date".

.. data:: PAGE_ORDER_BY

Defines how the pages (pages variable in the template) are sorted.
Options are same as ARTICLE_ORDER_BY. The default value, "basename"
will sort pages by their basename. The default is "basename".

.. _settings/themes:

Themes

Creating Pelican themes is addressed in a dedicated section (see
:ref:theming-pelican). However, here are the settings that are related to
themes.

.. data:: THEME

Theme to use to produce the output. Can be a relative or absolute path to a
theme folder, or the name of a default theme or a theme installed via
:doc:pelican-themes (see below). The default theme is "notmyidea".

.. data:: THEME_STATIC_DIR

Destination directory in the output path where Pelican will place the files
collected from THEME_STATIC_PATHS. Default is theme. The default is
"theme".

.. data:: THEME_STATIC_PATHS

Static theme paths you want to copy. Default value is static, but if your
theme has other static paths, you can put them here. If files or directories
with the same names are included in the paths defined in this settings, they
will be progressively overwritten. The default is ["static"].

.. data:: THEME_TEMPLATES_OVERRIDES

A list of paths you want Jinja2 to search for templates before searching the
theme's templates/ directory. Allows for overriding individual theme
template files without having to fork an existing theme. Jinja2 searches in
the following order: files in THEME_TEMPLATES_OVERRIDES first, then the
theme's templates/. The default is [].

You can also extend templates from the theme using the {% extends %}
directive utilizing the !theme prefix as shown in the following example:

.. parsed-literal::

text
{% extends '!theme/article.html' %}

.. data:: CSS_FILE

Specify the CSS file you want to load. The default is "main.css".

By default, two themes are available. You can specify them using the THEME
setting or by passing the -t option to the pelican command:

  • notmyidea
  • simple (a synonym for "plain text" :)

There are a number of other themes available at
https://github.com/getpelican/pelican-themes. Pelican comes with
:doc:pelican-themes, a small script for managing themes.

You can define your own theme, either by starting from scratch or by
duplicating and modifying a pre-existing theme. Here is :doc:a guide on how to create your theme .

Following are example ways to specify your preferred theme::

text
# Specify name of a built-in theme
THEME = "notmyidea"
# Specify name of a theme installed via the pelican-themes tool
THEME = "chunk"
# Specify a customized theme, via path relative to the settings file
THEME = "themes/mycustomtheme"
# Specify a customized theme, via absolute path
THEME = "/home/myuser/projects/mysite/themes/mycustomtheme"

Simple Theme

The built-in simple theme can be customized using the following settings:

.. data:: STYLESHEET_URL

The URL of the stylesheet to use. The default is None.

The built-in notmyidea theme can make good use of the following settings.
Feel free to use them in your themes as well.

.. data:: SITESUBTITLE

A subtitle to appear in the header. The default is None.

.. data:: DISQUS_SITENAME

Pelican can handle Disqus comments. Specify the Disqus sitename identifier
here. The default is None.

.. data:: GITHUB_URL

Your GitHub URL (if you have one). It will then use this information to
create a GitHub ribbon. The default is None.

.. data:: ANALYTICS

Put any desired analytics scripts in this setting in publishconf.py.
Example:

.. parsed-literal::

text
ANALYTICS = """
      <script src="/theme/js/primary-analytics.js"></script>
      <script>
          [ โ€ฆ in-line Javascript code for secondary analytics โ€ฆ ]
      </script>
  """

The default is None.

.. data:: MENUITEMS

A list of tuples (Title, URL) for additional menu items to appear at the
beginning of the main menu. The default is None.

.. data:: LINKS

A list of tuples (Title, URL) for links to appear on the header. The
default is None.

.. data:: SOCIAL

A list of tuples (Title, URL) to appear in the "social" section. The
default is None.

.. data:: TWITTER_USERNAME

Allows for adding a button to articles to encourage others to tweet about
them. Add your Twitter username if you want this button to appear. The
default is None.

.. data:: LINKS_WIDGET_NAME

Allows override of the name of the links widget. If not specified, defaults
to "links". The default is None.

.. data:: SOCIAL_WIDGET_NAME

Allows override of the name of the "social" widget. If not specified,
defaults to "social". The default is None.

Notmyidea Theme

In addition, you can use the "wide" version of the notmyidea theme by
adding the following to your configuration::

text
CSS_FILE = "wide.css"

Logging

Sometimes, a long list of warnings may appear during site generation. Finding
the meaningful error message in the middle of tons of annoying log output
can be quite tricky. In order to filter out redundant log messages, Pelican
comes with the LOG_FILTER setting.

LOG_FILTER should be a list of tuples (level, msg), each of them being
composed of the logging level (up to warning) and the message to be
ignored. Simply populate the list with the log messages you want to hide, and
they will be filtered out.

For example::

import logging
LOG_FILTER = [(logging.WARN, "TAG_SAVE_AS is set to False")]

It is possible to filter out messages by a template. Check out source code to
obtain a template.

For example::

import logging
LOG_FILTER = [(logging.WARN, "Empty alt attribute for image %s in %s")]

.. Warning::

Silencing messages by templates is a dangerous feature. It is possible to
unintentionally filter out multiple message types with the same template
(including messages from future Pelican versions). Proceed with caution.

.. note::

text
This option does nothing if ``--debug`` is passed.

.. _reading_only_modified_content:

Reading Only Modified Content

To speed up the build process, Pelican can optionally read only articles and
pages with modified content.

When Pelican is about to read some content source file:

  1. The hash or modification time information for the file from a
    previous build are loaded from a cache file if LOAD_CONTENT_CACHE is
    True. These files are stored in the CACHE_PATH directory. If the
    file has no record in the cache file, it is read as usual.

  2. The file is checked according to CHECK_MODIFIED_METHOD:

    • If set to "mtime", the modification time of the file is
      checked.
    • If set to a name of a function provided by the hashlib
      module, e.g. "md5", the file hash is checked.
    • If set to anything else or the necessary information about the
      file cannot be found in the cache file, the content is read as usual.
  3. If the file is considered unchanged, the content data saved in a
    previous build corresponding to the file is loaded from the cache, and the
    file is not read.

  4. If the file is considered changed, the file is read and the new
    modification information and the content data are saved to the cache if
    CACHE_CONTENT is True.

If CONTENT_CACHING_LAYER is set to "reader" (the default), the raw
content and metadata returned by a reader are cached. If this setting is
instead set to "generator", the processed content object is cached. Caching
the processed content object may conflict with plugins (as some reading related
signals may be skipped) and the WITH_FUTURE_DATES functionality (as the
draft status of the cached content objects would not change automatically
over time).

Checking modification times is faster than comparing file hashes, but it is not
as reliable because mtime information can be lost, e.g., when copying
content source files using the cp or rsync commands without the
mtime preservation mode (which for rsync can be invoked by passing the
--archive flag).

The cache files are Python pickles, so they may not be readable by different
versions of Python as the pickle format often changes. If such an error is
encountered, it is caught and the cache file is rebuilt automatically in the
new format. The cache files will also be rebuilt after the GZIP_CACHE
setting has been changed.

The --ignore-cache command-line option is useful when the whole cache needs
to be regenerated, such as when making modifications to the settings file that
will affect the cached content, or just for debugging purposes. When Pelican
runs in autoreload mode, modification of the settings file will make it ignore
the cache automatically if AUTORELOAD_IGNORE_CACHE is True.

Note that even when using cached content, all output is always written, so the
modification times of the generated *.html files will always change.
Therefore, rsync-based uploading may benefit from the --checksum
option.

Example settings

.. literalinclude:: ../samples/pelican.conf.py
:language: python

.. _Jinja Environment documentation: https://jinja.palletsprojects.com/en/latest/api/#jinja2.Environment
.. _Docutils Configuration: http://docutils.sourceforge.net/docs/user/config.html
.. _watchfiles documentation: https://watchfiles.helpmanual.io/api/filters/#watchfiles.DefaultFilter.ignore_dirs


Themes (`docs/themes.rst`)

.. _theming-pelican:

Themes

There is a community-managed repository of Pelican Themes_ for people to share
and use.

Please note that while we do our best to review and merge theme contributions,
they are submitted by the Pelican community and thus may have varying levels of
support and interoperability.

Community themes can also be found on PyPI tagged with "Framework :: Pelican :: Themes_".

.. _Framework :: Pelican :: Themes: https://pypi.org/search/?q=&o=-created&c=Framework+%3A%3A+Pelican+%3A%3A+Themes

Creating Themes

text
To generate its HTML output, Pelican uses the `Jinja
<https://palletsprojects.com/p/jinja/>`_ templating engine due to its flexibility and
straightforward syntax. If you want to create your own theme, feel free to take
inspiration from the `"simple" theme
<https://github.com/getpelican/pelican/tree/main/pelican/themes/simple/templates>`_.

To generate your site using a theme you have created (or downloaded manually
and then modified), you can specify that theme via the ``-t`` flag::

    pelican content -s pelicanconf.py -t /projects/your-site/themes/your-theme

If you'd rather not specify the theme on every invocation, you can define
``THEME`` in your settings to point to the location of your preferred theme.


Structure
=========

To make your own theme, you must follow the following structure::

    โ”œโ”€โ”€ static
    โ”‚   โ”œโ”€โ”€ css
    โ”‚   โ””โ”€โ”€ images
    โ””โ”€โ”€ templates
        โ”œโ”€โ”€ archives.html         // to display archives
        โ”œโ”€โ”€ article.html          // processed for each article
        โ”œโ”€โ”€ author.html           // processed for each author
        โ”œโ”€โ”€ authors.html          // must list all the authors
        โ”œโ”€โ”€ categories.html       // must list all the categories
        โ”œโ”€โ”€ category.html         // processed for each category
        โ”œโ”€โ”€ index.html            // the index (list all the articles)
        โ”œโ”€โ”€ page.html             // processed for each page
        โ”œโ”€โ”€ period_archives.html  // to display time-period archives
        โ”œโ”€โ”€ tag.html              // processed for each tag
        โ””โ”€โ”€ tags.html             // must list all the tags. Can be a tag cloud.

* `static` contains all the static assets, which will be copied to the output
  `theme` folder. The above filesystem layout includes CSS and image folders,
  but those are just examples. Put what you need here.

* `templates` contains all the templates that will be used to generate the
  content. The template files listed above are mandatory; you can add your own
  templates if it helps you keep things organized while creating your theme.


.. _templates-variables:

Templates and Variables
=======================

The idea is to use a simple syntax that you can embed into your HTML pages.
This document describes which templates should exist in a theme, and which
variables will be passed to each template at generation time.

All templates will receive the variables defined in your settings file, as long
as they are in all-caps. You can access them directly.


.. _common_variables:

Common Variables
----------------

All of these settings will be available to all templates.

=============== ===================================================
Variable        Description
=============== ===================================================
output_file     The name of the file currently being generated. For
                instance, when Pelican is rendering the home page,
                output_file will be "index.html".
articles        The list of articles, ordered descending by date.
                All the elements are `Article` objects, so you can
                access their attributes (e.g. title, summary, author
                etc.). Sometimes this is shadowed (for instance, in
                the tags page). You will then find info about it
                in the `all_articles` variable.
dates           The same list of articles, but ordered by date,
                ascending.
hidden_articles The list of hidden articles
drafts          The list of draft articles
period_archives A dictionary containing elements related to
                time-period archives (if enabled). See the section
                :ref:`Listing and Linking to Period Archives
                ` for details.
authors         A list of (author, articles) tuples, containing all
                the authors and corresponding articles (values)
categories      A list of (category, articles) tuples, containing
                all the categories and corresponding articles (values)
tags            A list of (tag, articles) tuples, containing all
                the tags and corresponding articles (values)
pages           The list of pages
hidden_pages    The list of hidden pages
draft_pages     The list of draft pages
=============== ===================================================


Sorting
-------

URL wrappers (currently categories, tags, and authors), have comparison methods
that allow them to be easily sorted by name::

    {% for tag, articles in tags|sort %}

If you want to sort based on different criteria, `Jinja's sort command`__ has a
number of options.

__ https://jinja.palletsprojects.com/en/latest/templates/#sort


Date Formatting
---------------

Pelican formats the date according to your settings and locale
(``DATE_FORMATS``/``DEFAULT_DATE_FORMAT``) and provides a ``locale_date``
attribute. On the other hand, the ``date`` attribute will be a `datetime`_
object. If you need custom formatting for a date different than your settings,
use the Jinja filter ``strftime`` that comes with Pelican. Usage is same as
Python `strftime`_ format, but the filter will do the right thing and format
your date according to the locale given in your settings::

    {{ article.date|strftime('%d %B %Y') }}

.. _datetime: https://docs.python.org/3/library/datetime.html#datetime-objects
.. _strftime: https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior

Checking Loaded Plugins
-----------------------

Pelican provides a ``plugin_enabled`` Jinja test for checking if a certain plugin
is enabled. This test accepts a plugin name as a string and will return a Boolean.
Namespace plugins can be specified by full name (``pelican.plugins.plugin_name``)
or short name (``plugin_name``). The following example uses the ``webassets`` plugin
to minify CSS if the plugin is enabled and otherwise falls back to regular CSS::

    {% if "webassets" is plugin_enabled %}
        {% assets filters="cssmin", output="css/style.min.css", "css/style.scss" %}
            <link rel="stylesheet" href="{{SITEURL}}/{{ASSET_URL}}">
        {% endassets %}
    {% else %}
        <link rel="stylesheet" href="{{SITEURL}}/css/style.css}">
    {% endif %}


index.html
----------

This is the home page or index of your blog, generated at ``index.html``.

If pagination is active, subsequent pages will reside in
``index{number}.html``.

======================  ===================================================
Variable                Description
======================  ===================================================
articles_paginator      A paginator object for the list of articles
articles_page           The current page of articles
articles_previous_page  The previous page of articles (``None`` if page does
                        not exist)
articles_next_page      The next page of articles (``None`` if page does
                        not exist)
dates_paginator         A paginator object for the article list, ordered by
                        date, ascending.
dates_page              The current page of articles, ordered by date,
                        ascending.
dates_previous_page     The previous page of articles, ordered by date,
                        ascending (``None`` if page does not exist)
dates_next_page         The next page of articles, ordered by date,
                        ascending (``None`` if page does not exist)
page_name               'index' -- useful for pagination links
======================  ===================================================


author.html
-------------

This template will be processed for each of the existing authors, with output
generated according to the ``AUTHOR_SAVE_AS`` setting (`Default:`
``author/{slug}.html``). If pagination is active, subsequent pages will by
default reside at ``author/{slug}{number}.html``.

======================  ===================================================
Variable                Description
======================  ===================================================
author                  The name of the author being processed
articles                Articles by this author
dates                   Articles by this author, but ordered by date,
                        ascending
articles_paginator      A paginator object for the list of articles
articles_page           The current page of articles
articles_previous_page  The previous page of articles (``None`` if page does
                        not exist)
articles_next_page      The next page of articles (``None`` if page does
                        not exist)
dates_paginator         A paginator object for the article list, ordered by
                        date, ascending.
dates_page              The current page of articles, ordered by date,
                        ascending.
dates_previous_page     The previous page of articles, ordered by date,
                        ascending (``None`` if page does not exist)
dates_next_page         The next page of articles, ordered by date,
                        ascending (``None`` if page does not exist)
page_name               AUTHOR_URL where everything after `{slug}` is
                        removed -- useful for pagination links
======================  ===================================================


category.html
-------------

This template will be processed for each of the existing categories, with
output generated according to the ``CATEGORY_SAVE_AS`` setting (`Default:`
``category/{slug}.html``). If pagination is active, subsequent pages will by
default reside at ``category/{slug}{number}.html``.

======================  ===================================================
Variable                Description
======================  ===================================================
category                The name of the category being processed
articles                Articles for this category
dates                   Articles for this category, but ordered by date,
                        ascending
articles_paginator      A paginator object for the list of articles
articles_page           The current page of articles
articles_previous_page  The previous page of articles (``None`` if page does
                        not exist)
articles_next_page      The next page of articles (``None`` if page does
                        not exist)
dates_paginator         A paginator object for the list of articles,
                        ordered by date, ascending
dates_page              The current page of articles, ordered by date,
                        ascending
dates_previous_page     The previous page of articles, ordered by date,
                        ascending (``None`` if page does not exist)
dates_next_page         The next page of articles, ordered by date,
                        ascending (``None`` if page does not exist)
page_name               CATEGORY_URL where everything after `{slug}` is
                        removed -- useful for pagination links
======================  ===================================================


article.html
-------------

This template will be processed for each article, with output generated
according to the ``ARTICLE_SAVE_AS`` setting (`Default:` ``{slug}.html``). The
following variables are available when rendering.

=============   ===================================================
Variable        Description
=============   ===================================================
article         The article object to be displayed
category        The name of the category for the current article
=============   ===================================================

Any metadata that you put in the header of the article source file will be
available as fields on the ``article`` object. The field name will be the same
as the name of the metadata field, except in all-lowercase characters.

For example, you could add a field called `FacebookImage` to your article
metadata, as shown below:

.. code-block:: md

    Title: I love Python more than music
    Date: 2013-11-06 10:06
    Tags: personal, python
    Category: Tech
    Slug: python-je-l-aime-a-mourir
    Author: Francis Cabrel
    FacebookImage: http://franciscabrel.com/images/pythonlove.png

This new metadata will be made available as `article.facebookimage` in your
`article.html` template. This would allow you, for example, to specify an image
for the Facebook open graph tags that will change for each article:

.. code-block:: html+jinja

    <meta property="og:image" content="{{ article.facebookimage }}"/>


page.html
---------

This template will be processed for each page, with output generated according
to the ``PAGE_SAVE_AS`` setting (`Default:` ``pages/{slug}.html``). The
following variables are available when rendering.

=============   ===================================================
Variable        Description
=============   ===================================================
page            The page object to be displayed. You can access its
                title, slug, and content.
=============   ===================================================


tag.html
--------

This template will be processed for each tag, with output generated according
to the ``TAG_SAVE_AS`` setting (`Default:` ``tag/{slug}.html``). If pagination
is active, subsequent pages will by default reside at
``tag/{slug}{number}.html``.

======================  ===================================================
Variable                Description
======================  ===================================================
tag                     The name of the tag being processed
articles                Articles related to this tag
dates                   Articles related to this tag, but ordered by date,
                        ascending
articles_paginator      A paginator object for the list of articles
articles_page           The current page of articles
articles_previous_page  The previous page of articles (``None`` if page does
                        not exist)
articles_next_page      The next page of articles (``None`` if page does
                        not exist)
dates_paginator         A paginator object for the list of articles,
                        ordered by date, ascending
dates_page              The current page of articles, ordered by date,
                        ascending
dates_previous_page     The previous page of articles, ordered by date,
                        ascending (``None`` if page does not exist)
dates_next_page         The next page of articles, ordered by date,
                        ascending (``None`` if page does not exist)
page_name               TAG_URL where everything after `{slug}` is removed
                        -- useful for pagination links
======================  ===================================================


period_archives.html
--------------------

This template will be processed for each year of your posts if a path for
``YEAR_ARCHIVE_SAVE_AS`` is defined, each month if ``MONTH_ARCHIVE_SAVE_AS`` is
defined, and each day if ``DAY_ARCHIVE_SAVE_AS`` is defined.

===================     ===================================================
Variable                Description
===================     ===================================================
period                  A tuple of the form (`year`, `month`, `day`) that
                        indicates the current time period. `year` and `day`
                        are numbers while `month` is a string. This tuple
                        only contains `year` if the time period is a
                        given year. It contains both `year` and `month`
                        if the time period is over years and months and
                        so on.
period_num              A tuple of the form (``year``, ``month``, ``day``),
                        as in ``period``, except all values are numbers.

===================     ===================================================

You can see an example of how to use `period` in the `"simple" theme
period_archives.html template
<https://github.com/getpelican/pelican/blob/main/pelican/themes/simple/templates/period_archives.html>`_.


.. _period_archives_variable:

Listing and Linking to Period Archives
""""""""""""""""""""""""""""""""""""""

The ``period_archives`` variable can be used to generate a list of links to
the set of period archives that Pelican generates. As a :ref:`common variable
<common_variables>`, it is available for use in any template, so you
can implement such an index in a custom direct template, or in a sidebar
visible across different site pages.

``period_archives`` is a dict that may contain ``year``, ``month``, and/or
``day`` keys, depending on which ``*_ARCHIVE_SAVE_AS`` settings are enabled.
The corresponding value is a list of dicts, where each dict in turn represents
a time period (ordered according to the ``NEWEST_FIRST_ARCHIVES`` setting)
with the following keys and values:

===================     ===================================================
Key                     Value
===================     ===================================================
period                  The same tuple as described in
                        ``period_archives.html``, e.g.
                        ``(2023, 'June', 18)``.
period_num              The same tuple as described in
                        ``period_archives.html``, e.g. ``(2023, 6, 18)``.
url                     The URL to the period archive page, e.g.
                        ``posts/2023/06/18/``. This is controlled by the
                        corresponding ``*_ARCHIVE_URL`` setting.
save_as                 The path to the save location of the period archive
                        page file, e.g. ``posts/2023/06/18/index.html``.
                        This is used internally by Pelican and is usually
                        not relevant to themes.
articles                A list of :ref:`Article <object-article>` objects
                        that fall under the time period.
dates                   Same list as ``articles``, but ordered according
                        to the ``NEWEST_FIRST_ARCHIVES`` setting.
===================     ===================================================

Here is an example of how ``period_archives`` can be used in a template:

.. code-block:: html+jinja

    
    {% for archive in period_archives.month %}
        <li>
            <a href="{{ SITEURL }}/{{ archive.url }}">
                {{ archive.period | reverse | join(' ') }} ({{ archive.articles|count }})
            </a>
        </li>
    {% endfor %}
    

You can change ``period_archives.month`` in the ``for`` statement to
``period_archives.year`` or ``period_archives.day`` as appropriate, depending
on the time period granularity desired.


Objects
=======

Detail objects attributes that are available and useful in templates. Not all
attributes are listed here, this is a selection of attributes considered useful
in a template.

.. _object-article:

Article
-------

The string representation of an Article is the `source_path` attribute.

======================  ===================================================
Attribute               Description
======================  ===================================================
author                  The :ref:`Author <object-author_cat_tag>` of
                        this article.
authors                 A list of :ref:`Authors <object-author_cat_tag>`
                        of this article.
category                The :ref:`Category <object-author_cat_tag>`
                        of this article.
content                 The rendered content of the article.
date                    Datetime object representing the article date.
date_format             Either default date format or locale date format.
default_template        Default template name.
in_default_lang         Boolean representing if the article is written
                        in the default language.
lang                    Language of the article.
locale_date             Date formatted by the `date_format`.
metadata                Article header metadata `dict`.
save_as                 Location to save the article page.
slug                    Page slug.
source_path             Full system path of the article source file.
relative_source_path    Relative path from PATH_ to the article source file.
status                  The article status, can be any of 'published' or
                        'draft'.
summary                 Rendered summary content.
tags                    List of :ref:`Tag <object-author_cat_tag>`
                        objects.
template                Template name to use for rendering.
title                   Title of the article.
translations            List of translations
                        :ref:`Article <object-article>` objects.
url                     URL to the article page.
======================  ===================================================

.. _PATH: settings.html#PATH


.. _object-author_cat_tag:

Author / Category / Tag
-----------------------

The string representation of those objects is the `name` attribute.

===================     ===================================================
Attribute               Description
===================     ===================================================
name                    Name of this object [1]_.
page_name               Author page name.
save_as                 Location to save the author page.
slug                    Page slug.
url                     URL to the author page.
===================     ===================================================

.. [1] for Author object, coming from `:authors:` or `AUTHOR`.

.. _object-page:

Page
----

The string representation of a Page is the `source_path` attribute.

=====================  ===================================================
Attribute              Description
=====================  ===================================================
author                 The :ref:`Author <object-author_cat_tag>` of
                       this page.
content                The rendered content of the page.
date                   Datetime object representing the page date.
date_format            Either default date format or locale date format.
default_template       Default template name.
in_default_lang        Boolean representing if the article is written
                       in the default language.
lang                   Language of the article.
locale_date            Date formatted by the `date_format`.
metadata               Page header metadata `dict`.
save_as                Location to save the page.
slug                   Page slug.
source_path            Full system path of the page source file.
relative_source_path   Relative path from PATH_ to the page source file.
status                 The page status, can be any of 'published', 'hidden' or
                       'draft'.
summary                Rendered summary content.
tags                   List of :ref:`Tag <object-author_cat_tag>`
                       objects.
template               Template name to use for rendering.
title                  Title of the page.
translations           List of translations
                       :ref:`Article <object-article>` objects.
url                    URL to the page.
=====================  ===================================================

.. _PATH: settings.html#PATH


Feeds
=====

The feed variables changed in 3.0. Each variable now explicitly lists ATOM or
RSS in the name. ATOM is still the default. Old themes will need to be updated.
Here is a complete list of the feed variables::

    AUTHOR_FEED_ATOM
    AUTHOR_FEED_RSS
    CATEGORY_FEED_ATOM
    CATEGORY_FEED_RSS
    FEED_ALL_ATOM
    FEED_ALL_RSS
    FEED_ATOM
    FEED_RSS
    TAG_FEED_ATOM
    TAG_FEED_RSS
    TRANSLATION_FEED_ATOM
    TRANSLATION_FEED_RSS


Inheritance
===========

Since version 3.0, Pelican supports inheritance from the ``simple`` theme, so
you can re-use the ``simple`` theme templates in your own themes.

If one of the mandatory files in the ``templates/`` directory of your theme is
missing, it will be replaced by the matching template from the ``simple``
theme. So if the HTML structure of a template in the ``simple`` theme is right
for you, you don't have to write a new template from scratch.

You can also extend templates from the ``simple`` theme in your own themes by
using the ``{% extends %}`` directive as in the following example:

.. code-block:: html+jinja

    {% extends "!simple/index.html" %}   

    {% extends "index.html" %}   


Example
-------

With this system, it is possible to create a theme with just one file.

main.css
""""""""

The file is ``static/css/main.css`` (the default ``CSS_FILE``):

.. code-block:: css

    body {
        font-family : monospace ;
        font-size : 100% ;
        background-color : white ;
        color : #111 ;
        width : 80% ;
        min-width : 400px ;
        min-height : 200px ;
        padding : 1em ;
        margin : 5% 10% ;
        border : thin solid gray ;
        border-radius : 5px ;
        display : block ;
    }

    a:link    { color : blue ; text-decoration : none ;      }
    a:hover   { color : blue ; text-decoration : underline ; }
    a:visited { color : blue ;                               }

    h1 a { color : inherit !important }
    h2 a { color : inherit !important }
    h3 a { color : inherit !important }
    h4 a { color : inherit !important }
    h5 a { color : inherit !important }
    h6 a { color : inherit !important }

    pre {
        margin : 2em 1em 2em 4em ;
    }

    #menu li {
        display : inline ;
    }

    #post-list {
        margin-bottom : 1em ;
        margin-top : 1em ;
    }

Custom templates
""""""""""""""""

If you want to customise the templates as well, you can extend them. For
example, to add a custom footer, create a ``templates/base.html``:

.. code-block:: html+jinja

    {% extends "!simple/base.html" %}

    {% block footer %}
        Custom footer
    {{ super() }}
    {% endblock %}

1. On the first line, we extend the ``base.html`` template from the ``simple``
   theme, so we don't have to rewrite the entire file.
2. On the third line, we open the ``footer`` block which has already been
   defined in the ``simple`` theme.
3. On the fourth line, we insert the extra footer content.
4. On the fifth line, the function ``super()`` keeps the content previously
   inserted in the ``head`` block.
5. On the last line, we close the ``footer`` block.

This file will be extended by all the other templates, so the custom footer
will appear on all pages.


.. Links

.. _`Pelican Themes`: https://github.com/getpelican/pelican-themes

---

### Tips (`docs/tips.rst`)

Tips
####

Here are some tips about Pelican that you might find useful.

Custom 404 Pages
================

When a browser requests a resource that the web server cannot find, the web
server usually displays a generic "File not found" (404) error page that can be
stark and unsightly. One way to provide an error page that matches the theme of
your site is to create a custom 404 page (*not* an article), such as this
Markdown-formatted example stored in ``content/pages/404.md``::

    Title: Not Found
    Status: hidden
    Save_as: 404.html

    The requested item could not be located. Perhaps you might want to check
    the [Archives](/archives.html)?

The next step is to configure your web server to display this custom page
instead of its default 404 page. For Nginx, add the following to your
configuration file's ``location`` block::

    error_page 404 /404.html;

For Apache::

    ErrorDocument 404 /404.html

For Amazon S3, first navigate to the ``Static Site Hosting`` menu in the bucket
settings on your AWS console. From there::

    Error Document: 404.html

Publishing to GitHub Pages
==========================

If you use `GitHub <https://github.com/>`_ for your Pelican site you can
publish your site to `GitHub Pages <https://pages.github.com/>`_ for free.
Your site will be published to ``https://.github.io`` if it's a user or
organization site or to ``https://.github.io/<repository>`` if it's a
project site. It's also possible to `use a custom domain with GitHub Pages <https://docs.github.com/en/pages/configuring-a-custom-domain-for-your-github-pages-site>`_.

There are `two ways to publish a site to GitHub Pages <https://docs.github.com/en/pages/getting-started-with-github-pages/configuring-a-publishing-source-for-your-github-pages-site>`_:

1. **Publishing from a branch:** run ``pelican`` locally and push the output
   directory to a special branch of your GitHub repo. GitHub will then publish
   the contents of this branch to your GitHub Pages site.
2. **Publishing with a custom GitHub Actions workflow:** just push the source
   files of your Pelican site to your GitHub repo's default branch and have a
   custom GitHub Actions workflow run ``pelican`` for you to generate the
   output directory and publish it to your GitHub Pages site.  This way you
   don't need to run ``pelican`` locally. You can even edit your site's source
   files using GitHub's web interface and any changes that you commit will be
   published.

Publishing a Project Site to GitHub Pages from a Branch
-------------------------------------------------------

To publish a Pelican site as a Project Page you need to *push* the content of
the ``output`` dir generated by Pelican to a repository's ``gh-pages`` branch
on GitHub.

The excellent `ghp-import <https://github.com/davisp/ghp-import>`_, which can
be installed with ``pip``, makes this process really easy.

For example, if the source of your Pelican site is contained in a GitHub
repository, and if you want to publish that Pelican site in the form of Project
Pages to this repository, you can then use the following::

    $ pelican content -o output -s pelicanconf.py
    $ ghp-import output -b gh-pages
    $ git push origin gh-pages

The ``ghp-import output`` command updates the local ``gh-pages`` branch with
the content of the ``output`` directory (creating the branch if it doesn't
already exist). The ``git push origin gh-pages`` command updates the remote
``gh-pages`` branch, effectively publishing the Pelican site.

.. note::

    The ``github`` target of the Makefile (and the ``gh_pages`` task of
    ``tasks.py``) created by the ``pelican-quickstart`` command publishes the
    Pelican site as Project Pages, as described above.

Publishing a User Site to GitHub Pages from a Branch
----------------------------------------------------

To publish a Pelican site in the form of User Pages, you need to *push* the
content of the ``output`` dir generated by Pelican to the ``main`` branch of
your ``.github.io`` repository on GitHub.

Again, you can take advantage of ``ghp-import``::

    $ pelican content -o output -s pelicanconf.py
    $ ghp-import output -b gh-pages
    $ git push [email protected]:elemoine/elemoine.github.io.git gh-pages:main

The ``git push`` command pushes the local ``gh-pages`` branch (freshly updated
by the ``ghp-import`` command) to the ``elemoine.github.io`` repository's
``main`` branch on GitHub.

.. note::

    To publish your Pelican site as User Pages, feel free to adjust the
    ``github`` target of the Makefile.

Another option for publishing to User Pages is to generate the output files in
the root directory of the project.

For example, your main project folder is ``.github.io`` and you can
create the Pelican project in a subdirectory called ``Pelican``. Then from
inside the ``Pelican`` folder you can run::

    $ pelican content -o .. -s pelicanconf.py

Now you can push the whole project ``.github.io`` to the main
branch of your GitHub repository::

    $ git push origin main

(assuming origin is set to your remote repository).

Publishing to GitHub Pages Using a Custom GitHub Actions Workflow
-----------------------------------------------------------------

Pelican-powered sites can be published to GitHub Pages via a `custom workflow
<https://github.com/getpelican/pelican/blob/main/.github/workflows/github_pages.yml>`_.
To use it:

1. Enable GitHub Pages in your repo: go to **Settings โ†’ Pages** and choose
   **GitHub Actions** for the **Source** setting.

2. Commit a ``.github/workflows/pelican.yml`` file to your repo with these contents:

   .. code-block:: yaml

       name: Deploy to GitHub Pages
       on:
         push:
           branches: ["main"]
         workflow_dispatch:
       jobs:
         deploy:
           uses: "getpelican/pelican/.github/workflows/github_pages.yml@main"
           permissions:
             contents: "read"
             pages: "write"
             id-token: "write"
           with:
             settings: "publishconf.py"

   You may want to replace the ``@main`` with the ID of a specific commit in
   this repo in order to pin the version of the reusable workflow that you're using:
   ``uses: getpelican/pelican/.github/workflows/github_pages.yml@<COMMIT_ID>``.
   If you do this you might want to get Dependabot to send you automated pull
   requests to update that commit ID whenever new versions of this workflow are
   published, like so:

   .. code-block:: yaml

       # .github/dependabot.yml
       version: 2
       updates:
         - package-ecosystem: "github-actions"
           directory: "/"
           schedule:
             interval: "monthly"

   See `GitHub's docs about using Dependabot to keep your actions up to date <https://docs.github.com/en/code-security/dependabot/working-with-dependabot/keeping-your-actions-up-to-date-with-dependabot>`_.

3. Go to the **Actions** tab in your repo
   (``https://github.com//<repository>/actions``) and you should see a
   **Deploy to GitHub Pages** action running.

4. Once the action completes you should see your Pelican site deployed at your
   repo's GitHub Pages URL: ``https://.github.io`` for a user or
   organization site or ``https://.github.io/<repository>>`` for a
   project site.

Notes:

* You don't need to set ``SITEURL`` or ``FEED_DOMAIN`` in your Pelican
  settings: the workflow will set them correctly for you

* You don't need to commit your ``--output`` / ``OUTPUT_PATH`` directory
  (``output/``) to git: the workflow will run ``pelican`` to build the output
  directory for you on GitHub Actions

See `GitHub's docs about reusable workflows <https://docs.github.com/en/actions/using-workflows/reusing-workflows>`_
for more information.

A number of optional inputs can be added to the ``with:`` block when calling
the workflow, for example:

.. code-block:: yaml

    with:
      settings: "publishconf.py"
      requirements: "pelican[markdown] typogrify"
      theme: "https://github.com/seanh/sidecar.git"
      python: "3.12"

Here's the complete list of workflow inputs:

+--------------------+----------+--------------------------------------------+--------+---------------+
| Name               | Required | Description                                | Type   | Default       |
+====================+==========+============================================+========+===============+
| ``settings``       | Yes      | The path to your Pelican settings          | string |               |
|                    |          | file (``pelican``'s                        |        |               |
|                    |          | ``--settings`` option),                    |        |               |
|                    |          | for example: ``"publishconf.py"``          |        |               |
+--------------------+----------+--------------------------------------------+--------+---------------+
| ``requirements``   | No       | The Python requirements to                 | string | ``"pelican"`` |
|                    |          | install, for example to enable             |        |               |
|                    |          | markdown and typogrify use:                |        |               |
|                    |          | ``"pelican[markdown] typogrify"``          |        |               |
|                    |          | or if you have a requirements              |        |               |
|                    |          | file: ``"-r requirements.txt"``            |        |               |
+--------------------+----------+--------------------------------------------+--------+---------------+
| ``output-path``    | No       | Where to output the generated              | string | ``"output/"`` |
|                    |          | files (``pelican``'s ``--output``          |        |               |
|                    |          | option)                                    |        |               |
+--------------------+----------+--------------------------------------------+--------+---------------+
| ``theme``          | No       | The GitHub repo URL of a custom            | string | ``""``        |
|                    |          | theme to use, for example:                 |        |               |
|                    |          | ``"https://github.com/seanh/sidecar.git"`` |        |               |
+--------------------+----------+--------------------------------------------+--------+---------------+
| ``theme-checkout`` | No       | Git ref (branch, tag or commit) of the     | string | ``""``        |
|                    |          | theme repo to checkout. This can be used   |        |               |
|                    |          | to pin the version of your theme. If not   |        |               |
|                    |          | specified defaults to the theme repo's     |        |               |
|                    |          | default branch.                            |        |               |
+--------------------+----------+--------------------------------------------+--------+---------------+
| ``python``         | No       | The version of Python to use to build the  | string | ``"3.12"``    |
|                    |          | site, for example: ``"3.12"`` (to use the  |        |               |
|                    |          | most recent version of Python 3.12, this   |        |               |
|                    |          | is faster) or ``"3.12.1"`` (to use an      |        |               |
|                    |          | exact version, slower)                     |        |               |
+--------------------+----------+--------------------------------------------+--------+---------------+
| ``siteurl``        | No       | The base URL of your web site (Pelican's   | string | The URL of    |
|                    |          | ``SITEURL`` setting). If not passed this   |        | your GitHub   |
|                    |          | will default to the URL of your GitHub     |        | Pages site.   |
|                    |          | Pages site, which is correct in most       |        |               |
|                    |          | cases.                                     |        |               |
+--------------------+----------+--------------------------------------------+--------+---------------+
| ``feed_domain``    | No       | The domain to be prepended to feed URLs    | string | The URL of    |
|                    |          | (Pelican's ``FEED_DOMAIN`` setting). If    |        | your GitHub   |
|                    |          | not passed this will default to the URL of |        | Pages site.   |
|                    |          | your GitHub Pages site, which is correct   |        |               |
|                    |          | in most cases.                             |        |               |
+--------------------+----------+--------------------------------------------+--------+---------------+
| ``deploy``         | No       | This is used to determine whether you will | bool   | ``true``      |
|                    |          | deploy the site or not to GitHub Pages.    |        |               |
|                    |          | This is most useful if you want to test a  |        |               |
|                    |          | change to your website in a pull request   |        |               |
|                    |          | before deploying those change.             |        |               |
+--------------------+----------+--------------------------------------------+--------+---------------+
| ``stork``          | No       | This is used to determine whether Stork    | bool   | ``false``     |
|                    |          | will be installed on the runner to be able |        |               |
|                    |          | to build a site with Stork search enabled  |        |               |
+--------------------+----------+--------------------------------------------+--------+---------------+

Testing Your Build in a GitHub Pull Request
"""""""""""""""""""""""""""""""""""""""""""

If you want to test your build in a pull request before deploying to GitHub, your workflow might look something like this:

.. code-block:: yaml

    name: Build and Deploy Site
    on:
      push:
        branches: ["main"]
      pull_request:
        branches: ["main"]
      workflow_dispatch:
        inputs:
          deploy:
            required: false
            default: true
            type: boolean
    jobs:
      deploy:
        uses: "getpelican/pelican/.github/workflows/github_pages.yml@main"
        permissions:
          id-token: write
          contents: read
          pages: write
        with:
          settings: "publishconf.py"
          requirements: "-r requirements.txt"
          deploy: ${{ (github.event_name == 'workflow_dispatch' && inputs.deploy == true) || (github.event_name == 'push' && github.ref_type == 'branch' && github.ref_name == github.event.repository.default_branch) }}

The ``on`` section of the workflow defines the events that will trigger the workflow. In this example, the workflow will run on pushes to the main branch, pull requests to the main branch, and manual runs of the workflow.

``workflow_dispatch`` defines the deploy boolean to be true by default. This means that if you run the workflow manually, it will deploy the site.

The ``deploy`` input for the job is using a set of standard GitHub workflow variables to control when ``deploy`` will either be true or false (you can customize this to your needs).

In this example, the ``deploy`` will be true if the event is a push to the main branch (or merging into main from a PR) or a manual run of the workflow. If the event is a pull request, the ``deploy`` will be false and it will only build an artifact for the site.

"Insecure content" warnings from browsers
"""""""""""""""""""""""""""""""""""""""""

If your site uses ``https://`` and is broken because the browser is blocking
network requests (for example for CSS files) due to "insecure content" this
may be because GitHub Pages is generating ``http://`` URLs for your site.

To fix this go into your site repo's settings and enable the **Enforce HTTPS** setting:
go to **Settings โ†’ Pages** and check **Enforce HTTPS**.
Then re-run the workflow to re-deploy your site.
Alternatively, you can use the workflow's ``siteurl`` and ``feed_domain`` settings.

Custom 404 Pages
----------------

GitHub Pages will display the custom 404 page described above, as noted in the
relevant `GitHub docs <https://help.github.com/articles/custom-404-pages/>`_.

Update your site on each commit
-------------------------------

To automatically update your Pelican site on each commit, you can create a
post-commit hook. For example, you can add the following to
``.git/hooks/post-commit``::

    pelican content -o output -s pelicanconf.py && ghp-import output && git push origin gh-pages

Copy static files to the root of your site
------------------------------------------

To use a `custom domain
<https://help.github.com/articles/setting-up-a-custom-domain-with-pages>`_ with
GitHub Pages, you need to put the domain of your site (e.g.,
``blog.example.com``) inside a ``CNAME`` file at the root of your site. To do
this, create the ``content/extra/`` directory and add a ``CNAME`` file to it.
Then use the ``STATIC_PATHS`` setting to tell Pelican to copy this file to your
output directory. For example::

    STATIC_PATHS = ['images', 'extra/CNAME']
    EXTRA_PATH_METADATA = {'extra/CNAME': {'path': 'CNAME'},}

Note: use forward slashes, ``/``, even on Windows.

You can also use the ``EXTRA_PATH_METADATA`` mechanism to place a
``favicon.ico`` or ``robots.txt`` at the root of any site.

How to add YouTube or Vimeo Videos
==================================

The easiest way is to paste the embed code of the video from these sites
directly into your source content.

Alternatively, you can also use Pelican plugins like ``liquid_tags``,
``pelican_youtube``, or ``pelican_vimeo`` to embed videos in your content.

Moreover, markup languages like reST and Markdown have plugins that let you
embed videos in the markup. You can use `reST video directive
<https://gist.github.com/dbrgn/2922648>`_ for reST or `mdx_video plugin
<https://github.com/italomaia/mdx-video>`_ for Markdown.


Develop Locally Using SSL
==================================

Here's how you can set up your local pelican server to support SSL.

First, create a self-signed certificate and key using ``openssl`` (this creates ``cert.pem`` and ``key.pem``)::

    $ openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes

And use this command to launch the server (the server starts within your ``output`` directory)::

    python -m pelican.server 8443 --key=../key.pem --cert=../cert.pem

If you are using ``develop-server.sh``,  add this to the top::

    CERT="$BASEDIR/cert.pem"
    KEY="$BASEDIR/key.pem"

and modify the ``pelican.server`` line as follows::

    $PY -m pelican.server $port --ssl --cert="$CERT" --key="$KEY" &

---

--- METRICS ---
- Files Extracted: 16
- Estimated Token Budget: ~58649 tokens
- Canonical Reference: https://codewiki.google/github.com/getpelican/pelican