Show More
@@ -1,72 +1,72 b'' | |||
|
1 | 1 | """Citation handling for LaTeX output.""" |
|
2 | 2 | |
|
3 | 3 | #----------------------------------------------------------------------------- |
|
4 | 4 | # Copyright (c) 2013, the IPython Development Team. |
|
5 | 5 | # |
|
6 | 6 | # Distributed under the terms of the Modified BSD License. |
|
7 | 7 | # |
|
8 | 8 | # The full license is in the file COPYING.txt, distributed with this software. |
|
9 | 9 | #----------------------------------------------------------------------------- |
|
10 | 10 | |
|
11 | 11 | #----------------------------------------------------------------------------- |
|
12 | 12 | # Code |
|
13 | 13 | #----------------------------------------------------------------------------- |
|
14 | 14 | |
|
15 | 15 | |
|
16 | 16 | __all__ = ['citation2latex'] |
|
17 | 17 | |
|
18 | 18 | |
|
19 | 19 | def citation2latex(s): |
|
20 | 20 | """Parse citations in Markdown cells. |
|
21 | 21 | |
|
22 | 22 | This looks for HTML tags having a data attribute names `data-cite` |
|
23 | 23 | and replaces it by the call to LaTeX cite command. The tranformation |
|
24 | 24 | looks like this: |
|
25 | 25 | |
|
26 | 26 | `<cite data-cite="granger">(Granger, 2013)</cite>` |
|
27 | 27 | |
|
28 | 28 | Becomes |
|
29 | 29 | |
|
30 | 30 | `\\cite{granger}` |
|
31 | 31 | |
|
32 | 32 | Any HTML tag can be used, which allows the citations to be formatted |
|
33 | 33 | in HTML in any manner. |
|
34 | 34 | """ |
|
35 | 35 | try: |
|
36 | 36 | from lxml import html |
|
37 | 37 | except ImportError: |
|
38 | 38 | return s |
|
39 | 39 | |
|
40 | 40 | tree = html.fragment_fromstring(s, create_parent='div') |
|
41 | 41 | _process_node_cite(tree) |
|
42 | 42 | s = html.tostring(tree) |
|
43 | 43 | if s.endswith('</div>'): |
|
44 | 44 | s = s[:-6] |
|
45 | 45 | if s.startswith('<div>'): |
|
46 | 46 | s = s[5:] |
|
47 | 47 | return s |
|
48 | 48 | |
|
49 | 49 | |
|
50 | 50 | def _process_node_cite(node): |
|
51 | 51 | """Do the citation replacement as we walk the lxml tree.""" |
|
52 | 52 | |
|
53 | 53 | def _get(o, name): |
|
54 | value = getattr(o, name) | |
|
54 | value = getattr(o, name, None) | |
|
55 | 55 | return '' if value is None else value |
|
56 | 56 | |
|
57 | 57 | if 'data-cite' in node.attrib: |
|
58 | 58 | cite = '\cite{%(ref)s}' % {'ref': node.attrib['data-cite']} |
|
59 | 59 | prev = node.getprevious() |
|
60 | 60 | if prev is not None: |
|
61 | 61 | prev.tail = _get(prev, 'tail') + cite + _get(node, 'tail') |
|
62 | 62 | else: |
|
63 | 63 | parent = node.getparent() |
|
64 | 64 | if parent is not None: |
|
65 | 65 | parent.text = _get(parent, 'text') + cite + _get(node, 'tail') |
|
66 | 66 | try: |
|
67 | 67 | node.getparent().remove(node) |
|
68 | 68 | except AttributeError: |
|
69 | 69 | pass |
|
70 | 70 | else: |
|
71 | 71 | for child in node: |
|
72 | 72 | _process_node_cite(child) |
General Comments 0
You need to be logged in to leave comments.
Login now