description (sponsor info) in lesson pdf
[librarian.git] / librarian / functions.py
1 # -*- coding: utf-8 -*-
2 #
3 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
5 #
6 from lxml import etree
7 import re
8
9 from librarian.dcparser import Person
10
11
12 def _register_function(f):
13     """ Register extension function with lxml """
14     ns = etree.FunctionNamespace('http://wolnelektury.pl/functions')
15     ns[f.__name__] = lambda context, *args: f(*args)
16
17
18 ENTITY_SUBSTITUTIONS = [
19     (u'---', u'—'),
20     (u'--', u'–'),
21     (u'...', u'…'),
22     (u',,', u'„'),
23     (u'"', u'”'),
24 ]
25
26
27 def substitute_entities(text):
28     """XPath extension function converting all entites in passed text."""
29     if isinstance(text, list):
30         text = ''.join(text)
31     for entity, substitutution in ENTITY_SUBSTITUTIONS:
32         text = text.replace(entity, substitutution)
33     return text
34
35
36 def reg_substitute_entities():
37     _register_function(substitute_entities)
38
39
40 def strip(text):
41     """Remove unneeded whitespace from beginning and end"""
42     if isinstance(text, list):
43         text = ''.join(text)
44     return re.sub(r'\s+', ' ', text).strip()
45
46
47 def reg_strip():
48     _register_function(strip)
49
50
51 def starts_white(text):
52     if isinstance(text, list):
53         text = ''.join(text)
54     if not text:
55         return False
56     return text[0].isspace()
57
58
59 def reg_starts_white():
60     _register_function(starts_white)
61
62
63 def reg_ends_white():
64     def ends_white(text):
65         if isinstance(text, list):
66             text = ''.join(text)
67         if not text:
68             return False
69         return text[-1].isspace()
70     _register_function(ends_white)
71
72
73 def wrap_words(text, wrapping):
74     """XPath extension function automatically wrapping words in passed text"""
75     if isinstance(text, list):
76         text = ''.join(text)
77     if not wrapping:
78         return text
79
80     words = re.split(r'\s', text)
81
82     line_length = 0
83     lines = [[]]
84     for word in words:
85         line_length += len(word) + 1
86         if line_length > wrapping:
87             # Max line length was exceeded. We create new line
88             lines.append([])
89             line_length = len(word)
90         lines[-1].append(word)
91     return '\n'.join(' '.join(line) for line in lines)
92
93
94 def reg_wrap_words():
95     _register_function(wrap_words)
96
97
98 def person_name(text):
99     """ Converts "Name, Forename" to "Forename Name" """
100     if isinstance(text, list):
101         text = ''.join(text)
102     return Person.from_text(text).readable()
103
104
105 def reg_person_name():
106     _register_function(person_name)
107
108
109 def texcommand(text):
110     """Remove non-letters"""
111     if isinstance(text, list):
112         text = ''.join(text)
113     return re.sub(r'[^a-zA-Z]', '', text).strip()
114
115
116 def reg_texcommand():
117     _register_function(texcommand)
118
119
120 def reg_get(format_):
121     def get(*args):
122         obj = format_
123         for arg in args:
124             if hasattr(obj, arg):
125                 obj = getattr(obj, arg)
126             else:
127                 try:
128                     obj = obj[arg]
129                 except (TypeError, KeyError), e:
130                     # Just raise proper AttributeError.
131                     getattr(obj, arg)
132         return obj
133     _register_function(get)