1 # -*- coding: utf-8 -*-
3 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
9 def _register_function(f):
10 """ Register extension function with lxml """
11 ns = etree.FunctionNamespace('http://wolnelektury.pl/functions')
15 def reg_substitute_entities():
16 ENTITY_SUBSTITUTIONS = [
24 def substitute_entities(context, text):
25 """XPath extension function converting all entites in passed text."""
26 if isinstance(text, list):
28 for entity, substitutution in ENTITY_SUBSTITUTIONS:
29 text = text.replace(entity, substitutution)
32 _register_function(substitute_entities)
36 def strip(context, text):
37 """Remove unneeded whitespace from beginning and end"""
38 if isinstance(text, list):
40 return re.sub(r'\s+', ' ', text).strip()
41 _register_function(strip)
45 def wrap_words(context, text, wrapping):
46 """XPath extension function automatically wrapping words in passed text"""
47 if isinstance(text, list):
52 words = re.split(r'\s', text)
57 line_length += len(word) + 1
58 if line_length > wrapping:
59 # Max line length was exceeded. We create new line
61 line_length = len(word)
62 lines[-1].append(word)
63 return '\n'.join(' '.join(line) for line in lines)
64 _register_function(wrap_words)