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.
8 from urllib import quote
10 from librarian.dcparser import Person
12 def _register_function(f):
13 """ Register extension function with lxml """
14 ns = etree.FunctionNamespace('http://wolnelektury.pl/functions')
18 def reg_substitute_entities():
19 ENTITY_SUBSTITUTIONS = [
27 def substitute_entities(context, text):
28 """XPath extension function converting all entites in passed text."""
29 if isinstance(text, list):
31 for entity, substitutution in ENTITY_SUBSTITUTIONS:
32 text = text.replace(entity, substitutution)
35 _register_function(substitute_entities)
39 def strip(context, text):
40 """Remove unneeded whitespace from beginning and end"""
41 if isinstance(text, list):
43 return re.sub(r'\s+', ' ', text).strip()
44 _register_function(strip)
47 def reg_starts_white():
48 def starts_white(context, text):
49 if isinstance(text, list):
53 return text[0].isspace()
54 _register_function(starts_white)
58 def ends_white(context, text):
59 if isinstance(text, list):
63 return text[-1].isspace()
64 _register_function(ends_white)
68 def wrap_words(context, text, wrapping):
69 """XPath extension function automatically wrapping words in passed text"""
70 if isinstance(text, list):
75 words = re.split(r'\s', text)
80 line_length += len(word) + 1
81 if line_length > wrapping:
82 # Max line length was exceeded. We create new line
84 line_length = len(word)
85 lines[-1].append(word)
86 return '\n'.join(' '.join(line) for line in lines)
87 _register_function(wrap_words)
90 def reg_person_name():
91 def person_name(context, text):
92 """ Converts "Name, Forename" to "Forename Name" """
93 if isinstance(text, list):
95 return Person.from_text(text).readable()
96 _register_function(person_name)
100 def texcommand(context, text):
101 """Remove non-letters"""
102 if isinstance(text, list):
104 return re.sub(r'[^a-zA-Z]', '', text).strip()
105 _register_function(texcommand)
109 def urlquote(content, text):
111 if isinstance(text, list):
113 return quote(text.encode('utf-8'), safe="/:")
114 _register_function(urlquote)
117 def breakurl(content, text):
118 """ Allows breaks in urls """
119 if isinstance(text, list):
121 chunks = text.split("/")
122 e = etree.Element("span")
124 ret = etree.Element("span")
126 for chunk in chunks[1:]:
127 ret.append(etree.Element("span", text="/"))
129 ret.append(etree.Element("cmd", {"name": "linebreak"}))
130 ret[-1].append(etree.Element("opt"))
131 ret[-1][-1].text = "1"
134 #return re.sub(r'(/)([^/])', r'\1\\-\2', text)
135 _register_function(breakurl)