Debian Codegraph @

citeproc/source/bibtex/bibtex.py

raw
1 
2 import re
3 import unicodedata
4
5 from warnings import warn
6
7 from ...types import (ARTICLE, ARTICLE_JOURNAL, BOOK, CHAPTER, MANUSCRIPT,
8 PAMPHLET, PAPER_CONFERENCE, REPORT, THESIS)
9 from ...string import String, MixedString, NoCase
10 from .. import BibliographySource, Reference, Name, Date, DateRange
11 from .bibparse import BibTeXParser
12 from .latex import parse_latex
13 from .latex.macro import NewCommand, Macro
14
15
16 class BibTeX(BibliographySource):
17 fields = {'abstract': 'abstract',
18 'address': 'publisher_place',
19 'annote': 'annote',
20 'author': 'author',
21 'booktitle': 'container_title',
22 'chapter': 'chapter_number',
23 'doi': 'DOI',
24 'edition': 'edition',
25 'editor': 'editor',
26 # 'howpublished': None,
27 # 'institution': None,
28 'journal': 'container_title',
29 # 'month': None,
30 'note': 'note',
31 'number': 'issue',
32 # 'organization': None,
33 'pages': 'page',
34 'pmid': 'PMID',
35 'publisher': 'publisher',
36 # 'school': None,
37 'series': 'collection_title',
38 'title': 'title',
39 # 'type': None,
40 # 'year': None,
41 'volume': 'volume',
42
43 # non-standard fields
44 'isbn': 'ISBN',
45 'issn': 'ISSN'}
46
47 types = {# standard entry types
48 'article': ARTICLE_JOURNAL,
49 'book': BOOK,
50 'booklet': PAMPHLET,
51 'conference': PAPER_CONFERENCE,
52 'inbook': CHAPTER,
53 'incollection': ARTICLE_JOURNAL,
54 'inproceedings': PAPER_CONFERENCE,
55 'manual': BOOK,
56 'mastersthesis': THESIS,
57 'misc': ARTICLE,
58 'phdthesis': THESIS,
59 'proceedings': BOOK,
60 'techreport': REPORT,
61 'unpublished': MANUSCRIPT,
62
63 # non-standard entry types
64 'thesis': THESIS,
65 'report': REPORT,
66 }
67
68 def __init__(self, filename, encoding='ascii'):
69 bibtex_database = BibTeXParser(filename, encoding)
70 self.preamble_macros = {}
71 parse_latex(bibtex_database.preamble,
72 {'newcommand': NewCommand(self.preamble_macros),
73 'mbox': Macro(1, '{0}'),
74 'cite': Macro(1, 'CITE({0})')})
75 for key, entry in bibtex_database.items():
76 self.add(self.create_reference(key, entry))
77
78 def _bibtex_to_csl(self, bibtex_entry):
79 csl_dict = {}
80 for field, value in bibtex_entry.items():
81 try:
82 value = value.strip()
83 except AttributeError:
84 pass
85 try:
86 csl_field = self.fields[field]
87 except KeyError:
88 if field not in ('year', 'month', 'filename'):
89 warn("Unsupported BibTeX field '{}'".format(field))
90 continue
91 if field in ('number', 'volume'):
92 try:
93 value = int(value)
94 except ValueError:
95 pass
96 elif field == 'pages':
97 value = self._bibtex_to_csl_pages(value)
98 elif field in ('author', 'editor'):
99 value = [name for name in self._parse_author(value)]
100 else:
101 try:
102 value = self._parse_string(value)
103 except TypeError:
104 value = str(value)
105 csl_dict[csl_field] = value
106 return csl_dict
107
108 @staticmethod
109 def _bibtex_to_csl_pages(value):
110 value = value.replace(' ', '')
111 if '-' in value:
112 try:
113 first, last = value.split('--')
114 except ValueError:
115 first, last = value.split('-')
116 pages = '-'.join((first, last))
117 else:
118 pages = value[:-1] if value.endswith('+') else value
119 return pages
120
121 def _bibtex_to_csl_date(self, bibtex_entry):
122 if 'month' in bibtex_entry:
123 begin_dict, end_dict = self._parse_month(bibtex_entry['month'])
124 else:
125 begin_dict, end_dict = {}, {}
126 if 'year' in bibtex_entry:
127 begin_dict['year'], end_dict['year'] \
128 = self._parse_year(bibtex_entry['year'])
129 if not begin_dict:
130 return None
131 if begin_dict == end_dict:
132 return Date(**begin_dict)
133 else:
134 return DateRange(begin=Date(**begin_dict), end=Date(**end_dict))
135
136 def _parse_year(self, year):
137 try:
138 year_str = parse_latex(year, self.preamble_macros)
139 except TypeError:
140 year_str = str(year)
141 if EN_DASH in year_str:
142 begin_year, end_year = year_str.split(EN_DASH)
143 begin_len, end_len = len(begin_year), len(end_year)
144 if end_len < begin_len:
145 end_year = begin_year[:begin_len - end_len] + end_year
146 else:
147 begin_year = end_year = int(year_str)
148 return begin_year, end_year
149
150 MONTHS = ('jan', 'feb', 'mar', 'apr', 'may', 'jun',
151 'jul', 'aug', 'sep', 'oct', 'nov', 'dec')
152 RE_DAY = r'(?P<day>\d+)'
153 RE_MONTH = r'(?P<month>\w+)'
154
155 @staticmethod
156 def _parse_month(month):
157 def month_name_to_index(name):
158 try:
159 return BibTeX.MONTHS.index(name[:3].lower()) + 1
160 except ValueError:
161 return int(name)
162
163 begin = {}
164 end = {}
165 month = month.strip()
166 month = month.replace(', ', '-')
167 if month.isdecimal():
168 begin['month'] = end['month'] = month
169 elif month.replace('-', '').isalpha():
170 if '-' in month:
171 begin['month'], end['month'] = month.split('-')
172 else:
173 begin['month'] = end['month'] = month
174 else:
175 m = re.match(BibTeX.RE_DAY + '[ ~]*' + BibTeX.RE_MONTH, month)
176 if m is None:
177 m = re.match(BibTeX.RE_MONTH + '[ ~]*' + BibTeX.RE_DAY, month)
178 begin['day'] = end['day'] = int(m.group('day'))
179 begin['month'] = end['month'] = m.group('month')
180 begin['month'] = month_name_to_index(begin['month'])
181 end['month'] = month_name_to_index(end['month'])
182 return begin, end
183
184 def _parse_string(self, title):
185 def make_string(string, top_level_group=False):
186 unlatexed = parse_latex(string, self.preamble_macros)
187 fixed_case = top_level_group and not string.startswith('\\')
188 string_cls = NoCase if fixed_case else String
189 return string_cls(unlatexed)
190
191 output = MixedString()
192 level = 0
193 string = ''
194 for char in title:
195 if char == '{':
196 if level == 0:
197 if string:
198 output += make_string(string)
199 string = ''
200 level += 1
201 elif char == '}':
202 level -= 1
203 if level == 0:
204 output += make_string(string, True)
205 string = ''
206 else:
207 string += char
208 if level != 0:
209 raise SyntaxError('Non-matching braces in "{}"'.format(title))
210 if string:
211 output += make_string(string)
212 return output
213
214 def _parse_author(self, authors):
215 csl_authors = []
216 for author in split_names(authors):
217 first, von, last, jr = parse_name(author)
218 csl_parts = {}
219 for part, csl_label in [(first, 'given'),
220 (von, 'non-dropping-particle'),
221 (last, 'family'),
222 (jr, 'suffix')]:
223 if part is not None:
224 csl_parts[csl_label] = parse_latex(part,
225 self.preamble_macros)
226 name = Name(**csl_parts)
227 csl_authors.append(name)
228 return csl_authors
229
230 def create_reference(self, key, bibtex_entry):
231 csl_type = self.types[bibtex_entry.document_type]
232 csl_fields = self._bibtex_to_csl(bibtex_entry)
233 csl_date = self._bibtex_to_csl_date(bibtex_entry)
234 if csl_date:
235 csl_fields['issued'] = csl_date
236 return Reference(key, csl_type, **csl_fields)
237
238
239 # BibTeX name handling
240 #
241 # references
242 # - BibTeXing by Oren Patashnik (Feb 8, 1988), 4. Helpful Hints, item 18
243 # (BibTeX 0.99d - http://www.ctan.org/tex-archive/biblio/bibtex/base/btxdoc.pdf)
244 # - A summary of BibTex by Xavier Décoret
245 # (http://maverick.inria.fr/~Xavier.Decoret/resources/xdkbibtex/bibtex_summary.html)
246 # - Tame the BeaST by Nicolas Markey
247 # (http://tug.ctan.org/info/bibtex/tamethebeast/ttb_en.pdf)
248
249 AND = ' and '
250
251 def split_names(string):
252 """Split a string of names separated by 'and' into a list of names."""
253 brace_level = 0
254 names = []
255 last_index = 0
256 for i in range(len(string)):
257 char = string[i]
258 if brace_level == 0 and string[i:].startswith(AND):
259 names.append(string[last_index:i])
260 last_index = i + len(AND)
261 elif char == '{':
262 brace_level += 1
263 elif char == '}':
264 brace_level -= 1
265 last_name = string[last_index:]
266 if last_name:
267 names.append(last_name)
268 return names
269
270
271 def parse_name(name):
272 """Parse a BibTeX name string and split it into First, von, Last and Jr
273 parts.
274 """
275 parts = split_name(name)
276 if len(parts) == 1: # First von Last
277 first_von_last, = parts
278 index = 0
279 first, jr = [], []
280 for word in first_von_last[:-1]:
281 if is_capitalized(word) not in (True, None):
282 break
283 first.append(word)
284 index += 1
285 von_last = first_von_last[index:]
286 elif len(parts) == 2: # von Last, First
287 jr = []
288 von_last, first = parts
289 elif len(parts) == 3: # von Last, Jr, First
290 von_last, jr, first = parts
291 von, last = split_von_last(von_last)
292 join = ' '.join
293 return join(first) or None, join(von) or None, join(last), join(jr) or None
294
295
296 def split_name(name):
297 """Split a name in into parts delimited by commas (at brace-level 0), and
298 each part into words.
299
300 Returns a list of of lists of words.
301 """
302 brace_level = 0
303 parts = []
304 current_part = []
305 word = ''
306 for char in name:
307 if char in ' \t,':
308 if brace_level == 0:
309 if word:
310 current_part.append(word)
311 word = ''
312 if char == ',':
313 parts.append(current_part)
314 current_part = []
315 continue
316 elif char == '{':
317 brace_level += 1
318 elif char == '}':
319 brace_level -= 1
320 word += char
321 if word:
322 current_part.append(word)
323 parts.append(current_part)
324 return parts
325
326
327 def is_capitalized(string):
328 """Check if a BibTeX substring is capitalized.
329
330 A string can be "case-less", in which case `None` is returned.
331 """
332 brace_level = 0
333 special_char = False
334 for char, next_char in lookahead_iter(string):
335 if (brace_level == 0 or special_char) and char.isalpha():
336 return char.isupper()
337 elif char == '{':
338 brace_level += 1
339 if brace_level == 1 and next_char == '\\':
340 special_char = True
341 elif char == '}':
342 brace_level -= 1
343 if brace_level == 0:
344 special_char = False
345 return None # case-less
346
347
348 def split_von_last(words):
349 """Split "von Last" name into von and Last parts."""
350 if len(words) > 1 and is_capitalized(words[0]) is False:
351 for j, word in enumerate(reversed(words[:-1])):
352 if is_capitalized(word) not in (True, None):
353 return words[:-j - 1], words[-j - 1:]
354 return [], words
355
356
357 def lookahead_iter(iterable):
358 """Iterator that also yields the next item along with each item. The next
359 item is `None` when yielding the last item.
360 """
361 items = iter(iterable)
362 item = next(items)
363 for next_item in items:
364 yield item, next_item
365 item = next_item
366 yield item, None
367
368
369 EN_DASH = unicodedata.lookup('EN DASH')