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)
44 def reg_starts_white():
45 def starts_white(context, text):
46 if isinstance(text, list):
50 return text[0].isspace()
51 _register_function(starts_white)
55 def ends_white(context, text):
56 if isinstance(text, list):
60 return text[-1].isspace()
61 _register_function(ends_white)
65 def wrap_words(context, text, wrapping):
66 """XPath extension function automatically wrapping words in passed text"""
67 if isinstance(text, list):
72 words = re.split(r'\s', text)
77 line_length += len(word) + 1
78 if line_length > wrapping:
79 # Max line length was exceeded. We create new line
81 line_length = len(word)
82 lines[-1].append(word)
83 return '\n'.join(' '.join(line) for line in lines)
84 _register_function(wrap_words)
87 def reg_person_name():
88 def person_name(context, text):
89 """ Converts "Name, Forename" to "Forename Name" """
90 if isinstance(text, list):
92 return ' '.join([t.strip() for t in text.split(',', 1)[::-1]])
93 _register_function(person_name)