Skip to content

Instantly share code, notes, and snippets.

@l04m33
Created October 27, 2014 02:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save l04m33/7e93b0bb3ca0cfc6f2d0 to your computer and use it in GitHub Desktop.
Save l04m33/7e93b0bb3ca0cfc6f2d0 to your computer and use it in GitHub Desktop.
Smarter summary plugin for Pelican
import logging
from pelican import signals
from pelican import contents
logger = logging.getLogger(__name__)
def initialized(pelican):
from pelican.settings import DEFAULT_CONFIG
DEFAULT_CONFIG.setdefault('SUMMARY_BEGIN_MARKER',
'<!-- PELICAN_BEGIN_SUMMARY -->')
DEFAULT_CONFIG.setdefault('SUMMARY_END_MARKER',
'<!-- PELICAN_END_SUMMARY -->')
if pelican:
pelican.settings.setdefault('SUMMARY_BEGIN_MARKER',
'<!-- PELICAN_BEGIN_SUMMARY -->')
pelican.settings.setdefault('SUMMARY_END_MARKER',
'<!-- PELICAN_END_SUMMARY -->')
if hasattr(contents.Content, '_get_content'):
orig_get_content = contents.Content._get_content
else:
orig_get_content = None
contents.Content._get_content = \
lambda instance: get_content(instance, orig_get_content)
orig_summary = contents.Content.summary
contents.Content.summary = \
property(lambda instance:
get_summary(instance, orig_summary, orig_get_content),
orig_summary.fset, orig_summary.fdel,
orig_summary.__doc__)
def get_content(self, orig_get_content):
if orig_get_content is None:
content = self._content
else:
content = orig_get_content(self)
if 'summary' in self.metadata:
return content
if self.settings['SUMMARY_BEGIN_MARKER']:
content = content.replace(
self.settings['SUMMARY_BEGIN_MARKER'], '', 1)
if self.settings['SUMMARY_END_MARKER']:
content = content.replace(
self.settings['SUMMARY_END_MARKER'], '', 1)
return content
def get_summary(self, orig_summary, orig_get_content):
if hasattr(self, '_summary'):
return self._summary
if orig_get_content is not None:
content = orig_get_content(self)
else:
content = self._content
begin_summary = -1
end_summary = -1
if self.settings['SUMMARY_BEGIN_MARKER']:
begin_summary = content.find(self.settings['SUMMARY_BEGIN_MARKER'])
if self.settings['SUMMARY_END_MARKER']:
end_summary = content.find(self.settings['SUMMARY_END_MARKER'])
if begin_summary != -1 or end_summary != -1:
# the beginning position has to take into account the length
# of the marker
if begin_summary != -1:
begin_summary = \
begin_summary + len(self.settings['SUMMARY_BEGIN_MARKER'])
else:
begin_summary = 0
end_summary = end_summary if end_summary != -1 else None
return self._update_content(content[begin_summary:end_summary],
self._context.get('localsiteurl', ''))
else:
return orig_summary.fget(self)
def register():
signals.initialized.connect(initialized)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment