author | Nicolas Chauvat <nicolas.chauvat@logilab.fr> |
Tue, 23 Feb 2010 08:41:06 +0100 | |
branch | stable |
changeset 4656 | 027bbff3659f |
parent 4483 | 918fd9931cb7 |
child 4719 | aaed3f813ef8 |
permissions | -rw-r--r-- |
0 | 1 |
"""rest publishing functions |
2 |
||
996 | 3 |
contains some functions and setup of docutils for cubicweb. Provides the |
4 |
following ReST directives: |
|
5 |
||
6 |
* `eid`, create link to entity in the repository by their eid |
|
7 |
||
8 |
* `card`, create link to card entity in the repository by their wikiid |
|
9 |
(proposing to create it when the refered card doesn't exist yet) |
|
10 |
||
11 |
* `winclude`, reference to a web documentation file (in wdoc/ directories) |
|
12 |
||
13 |
* `sourcecode` (if pygments is installed), source code colorization |
|
0 | 14 |
|
15 |
:organization: Logilab |
|
4212
ab6573088b4a
update copyright: welcome 2010
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
4118
diff
changeset
|
16 |
:copyright: 2001-2010 LOGILAB S.A. (Paris, FRANCE), license is LGPL v2. |
0 | 17 |
:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr |
1977
606923dff11b
big bunch of copyright / docstring update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1643
diff
changeset
|
18 |
:license: GNU Lesser General Public License, v2.1 - http://www.gnu.org/licenses |
0 | 19 |
""" |
20 |
__docformat__ = "restructuredtext en" |
|
21 |
||
22 |
from cStringIO import StringIO |
|
23 |
from itertools import chain |
|
24 |
from logging import getLogger |
|
25 |
from os.path import join |
|
26 |
||
27 |
from docutils import statemachine, nodes, utils, io |
|
28 |
from docutils.core import publish_string |
|
29 |
from docutils.parsers.rst import Parser, states, directives |
|
30 |
from docutils.parsers.rst.roles import register_canonical_role, set_classes |
|
31 |
||
2312
af4d8f75c5db
use xml_escape
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2311
diff
changeset
|
32 |
from logilab.mtconverter import ESC_UCAR_TABLE, ESC_CAR_TABLE, xml_escape |
0 | 33 |
|
2467
6983631f5d0d
don't fail on unknown eid, simply issue a warning
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2312
diff
changeset
|
34 |
from cubicweb import UnknownEid |
704
0c2c8f0a6ded
new ext package for modules depending on an option third party package
sylvain.thenault@logilab.fr
parents:
0
diff
changeset
|
35 |
from cubicweb.ext.html4zope import Writer |
0 | 36 |
|
37 |
# We provide our own parser as an attempt to get rid of |
|
38 |
# state machine reinstanciation |
|
39 |
||
40 |
import re |
|
41 |
# compile states.Body patterns |
|
42 |
for k, v in states.Body.patterns.items(): |
|
43 |
if isinstance(v, str): |
|
44 |
states.Body.patterns[k] = re.compile(v) |
|
45 |
||
46 |
# register ReStructured Text mimetype / extensions |
|
47 |
import mimetypes |
|
48 |
mimetypes.add_type('text/rest', '.rest') |
|
49 |
mimetypes.add_type('text/rest', '.rst') |
|
50 |
||
51 |
||
52 |
LOGGER = getLogger('cubicweb.rest') |
|
53 |
||
54 |
def eid_reference_role(role, rawtext, text, lineno, inliner, |
|
55 |
options={}, content=[]): |
|
56 |
try: |
|
57 |
try: |
|
58 |
eid_num, rest = text.split(u':', 1) |
|
59 |
except: |
|
60 |
eid_num, rest = text, '#'+text |
|
61 |
eid_num = int(eid_num) |
|
62 |
if eid_num < 0: |
|
63 |
raise ValueError |
|
64 |
except ValueError: |
|
65 |
msg = inliner.reporter.error( |
|
66 |
'EID number must be a positive number; "%s" is invalid.' |
|
67 |
% text, line=lineno) |
|
68 |
prb = inliner.problematic(rawtext, rawtext, msg) |
|
69 |
return [prb], [msg] |
|
70 |
# Base URL mainly used by inliner.pep_reference; so this is correct: |
|
71 |
context = inliner.document.settings.context |
|
2467
6983631f5d0d
don't fail on unknown eid, simply issue a warning
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2312
diff
changeset
|
72 |
try: |
3418
7b49fa7e942d
[api] use _cw, cw_row, cw_col, cw_rset etc.
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
2680
diff
changeset
|
73 |
refedentity = context._cw.entity_from_eid(eid_num) |
2467
6983631f5d0d
don't fail on unknown eid, simply issue a warning
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2312
diff
changeset
|
74 |
except UnknownEid: |
6983631f5d0d
don't fail on unknown eid, simply issue a warning
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2312
diff
changeset
|
75 |
ref = '#' |
3418
7b49fa7e942d
[api] use _cw, cw_row, cw_col, cw_rset etc.
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
2680
diff
changeset
|
76 |
rest += u' ' + context._cw._('(UNEXISTANT EID)') |
2467
6983631f5d0d
don't fail on unknown eid, simply issue a warning
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2312
diff
changeset
|
77 |
else: |
6983631f5d0d
don't fail on unknown eid, simply issue a warning
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2312
diff
changeset
|
78 |
ref = refedentity.absolute_url() |
0 | 79 |
set_classes(options) |
80 |
return [nodes.reference(rawtext, utils.unescape(rest), refuri=ref, |
|
81 |
**options)], [] |
|
82 |
||
83 |
||
84 |
def winclude_directive(name, arguments, options, content, lineno, |
|
85 |
content_offset, block_text, state, state_machine): |
|
86 |
"""Include a reST file as part of the content of this reST file. |
|
87 |
||
88 |
same as standard include directive but using config.locate_doc_resource to |
|
89 |
get actual file to include. |
|
90 |
||
91 |
Most part of this implementation is copied from `include` directive defined |
|
92 |
in `docutils.parsers.rst.directives.misc` |
|
93 |
""" |
|
94 |
context = state.document.settings.context |
|
95 |
source = state_machine.input_lines.source( |
|
96 |
lineno - state_machine.input_offset - 1) |
|
97 |
#source_dir = os.path.dirname(os.path.abspath(source)) |
|
98 |
fid = arguments[0] |
|
4334
dda74c345b06
3.6 api update
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4252
diff
changeset
|
99 |
for lang in chain((context._cw.lang, context.vreg.property_value('ui.language')), |
0 | 100 |
context.config.available_languages()): |
101 |
rid = '%s_%s.rst' % (fid, lang) |
|
102 |
resourcedir = context.config.locate_doc_file(rid) |
|
103 |
if resourcedir: |
|
104 |
break |
|
105 |
else: |
|
106 |
severe = state_machine.reporter.severe( |
|
107 |
'Problems with "%s" directive path:\nno resource matching %s.' |
|
108 |
% (name, fid), |
|
109 |
nodes.literal_block(block_text, block_text), line=lineno) |
|
110 |
return [severe] |
|
111 |
path = join(resourcedir, rid) |
|
112 |
encoding = options.get('encoding', state.document.settings.input_encoding) |
|
113 |
try: |
|
114 |
state.document.settings.record_dependencies.add(path) |
|
115 |
include_file = io.FileInput( |
|
116 |
source_path=path, encoding=encoding, |
|
117 |
error_handler=state.document.settings.input_encoding_error_handler, |
|
118 |
handle_io_errors=None) |
|
119 |
except IOError, error: |
|
120 |
severe = state_machine.reporter.severe( |
|
121 |
'Problems with "%s" directive path:\n%s: %s.' |
|
122 |
% (name, error.__class__.__name__, error), |
|
123 |
nodes.literal_block(block_text, block_text), line=lineno) |
|
124 |
return [severe] |
|
125 |
try: |
|
126 |
include_text = include_file.read() |
|
127 |
except UnicodeError, error: |
|
128 |
severe = state_machine.reporter.severe( |
|
129 |
'Problem with "%s" directive:\n%s: %s' |
|
130 |
% (name, error.__class__.__name__, error), |
|
131 |
nodes.literal_block(block_text, block_text), line=lineno) |
|
132 |
return [severe] |
|
133 |
if options.has_key('literal'): |
|
134 |
literal_block = nodes.literal_block(include_text, include_text, |
|
135 |
source=path) |
|
136 |
literal_block.line = 1 |
|
137 |
return literal_block |
|
138 |
else: |
|
139 |
include_lines = statemachine.string2lines(include_text, |
|
140 |
convert_whitespace=1) |
|
141 |
state_machine.insert_input(include_lines, path) |
|
142 |
return [] |
|
143 |
||
144 |
winclude_directive.arguments = (1, 0, 1) |
|
145 |
winclude_directive.options = {'literal': directives.flag, |
|
146 |
'encoding': directives.encoding} |
|
147 |
||
996 | 148 |
try: |
149 |
from pygments import highlight |
|
150 |
from pygments.lexers import get_lexer_by_name, LEXERS |
|
151 |
from pygments.formatters import HtmlFormatter |
|
152 |
except ImportError: |
|
4118
8a9a00a9405c
quick and dirty fix trying to avoid rest directive conflicts when using sphinx (which seems to import the code)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2680
diff
changeset
|
153 |
pygments_directive = None |
996 | 154 |
else: |
155 |
_PYGMENTS_FORMATTER = HtmlFormatter() |
|
156 |
||
157 |
def pygments_directive(name, arguments, options, content, lineno, |
|
158 |
content_offset, block_text, state, state_machine): |
|
159 |
try: |
|
160 |
lexer = get_lexer_by_name(arguments[0]) |
|
161 |
except ValueError: |
|
162 |
# no lexer found |
|
163 |
lexer = get_lexer_by_name('text') |
|
164 |
parsed = highlight(u'\n'.join(content), lexer, _PYGMENTS_FORMATTER) |
|
4483
918fd9931cb7
cleanup, don't fail if no context set on the sourcecode directive
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4334
diff
changeset
|
165 |
# don't fail if no context set on the sourcecode directive |
918fd9931cb7
cleanup, don't fail if no context set on the sourcecode directive
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4334
diff
changeset
|
166 |
try: |
918fd9931cb7
cleanup, don't fail if no context set on the sourcecode directive
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4334
diff
changeset
|
167 |
context = state.document.settings.context |
918fd9931cb7
cleanup, don't fail if no context set on the sourcecode directive
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4334
diff
changeset
|
168 |
context._cw.add_css('pygments.css') |
918fd9931cb7
cleanup, don't fail if no context set on the sourcecode directive
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4334
diff
changeset
|
169 |
except AttributeError: |
918fd9931cb7
cleanup, don't fail if no context set on the sourcecode directive
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4334
diff
changeset
|
170 |
# used outside cubicweb |
918fd9931cb7
cleanup, don't fail if no context set on the sourcecode directive
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4334
diff
changeset
|
171 |
pass |
996 | 172 |
return [nodes.raw('', parsed, format='html')] |
1447
a1ca676294f0
don't use a singleton rest parser which may leads to concurrency bugs
sylvain.thenault@logilab.fr
parents:
1323
diff
changeset
|
173 |
|
996 | 174 |
pygments_directive.arguments = (1, 0, 1) |
175 |
pygments_directive.content = 1 |
|
176 |
||
177 |
||
0 | 178 |
class CubicWebReSTParser(Parser): |
179 |
"""The (customized) reStructuredText parser.""" |
|
180 |
||
181 |
def __init__(self): |
|
182 |
self.initial_state = 'Body' |
|
183 |
self.state_classes = states.state_classes |
|
184 |
self.inliner = states.Inliner() |
|
185 |
self.statemachine = states.RSTStateMachine( |
|
186 |
state_classes=self.state_classes, |
|
187 |
initial_state=self.initial_state, |
|
188 |
debug=0) |
|
189 |
||
190 |
def parse(self, inputstring, document): |
|
191 |
"""Parse `inputstring` and populate `document`, a document tree.""" |
|
192 |
self.setup_parse(inputstring, document) |
|
193 |
inputlines = statemachine.string2lines(inputstring, |
|
194 |
convert_whitespace=1) |
|
195 |
self.statemachine.run(inputlines, document, inliner=self.inliner) |
|
196 |
self.finish_parse() |
|
197 |
||
198 |
||
199 |
def rest_publish(context, data): |
|
200 |
"""publish a string formatted as ReStructured Text to HTML |
|
1447
a1ca676294f0
don't use a singleton rest parser which may leads to concurrency bugs
sylvain.thenault@logilab.fr
parents:
1323
diff
changeset
|
201 |
|
0 | 202 |
:type context: a cubicweb application object |
203 |
||
204 |
:type data: str |
|
205 |
:param data: some ReST text |
|
206 |
||
207 |
:rtype: unicode |
|
208 |
:return: |
|
209 |
the data formatted as HTML or the original data if an error occured |
|
210 |
""" |
|
3418
7b49fa7e942d
[api] use _cw, cw_row, cw_col, cw_rset etc.
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
2680
diff
changeset
|
211 |
req = context._cw |
0 | 212 |
if isinstance(data, unicode): |
213 |
encoding = 'unicode' |
|
2311
f178182b1305
actually close #344401 by removing unprintable characters
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
214 |
# remove unprintable characters unauthorized in xml |
f178182b1305
actually close #344401 by removing unprintable characters
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
215 |
data = data.translate(ESC_UCAR_TABLE) |
0 | 216 |
else: |
217 |
encoding = req.encoding |
|
2311
f178182b1305
actually close #344401 by removing unprintable characters
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
218 |
# remove unprintable characters unauthorized in xml |
f178182b1305
actually close #344401 by removing unprintable characters
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
219 |
data = data.translate(ESC_CAR_TABLE) |
0 | 220 |
settings = {'input_encoding': encoding, 'output_encoding': 'unicode', |
221 |
'warning_stream': StringIO(), 'context': context, |
|
222 |
# dunno what's the max, severe is 4, and we never want a crash |
|
223 |
# (though try/except may be a better option...) |
|
1447
a1ca676294f0
don't use a singleton rest parser which may leads to concurrency bugs
sylvain.thenault@logilab.fr
parents:
1323
diff
changeset
|
224 |
'halt_level': 10, |
0 | 225 |
} |
226 |
if context: |
|
227 |
if hasattr(req, 'url'): |
|
228 |
base_url = req.url() |
|
229 |
elif hasattr(context, 'absolute_url'): |
|
230 |
base_url = context.absolute_url() |
|
231 |
else: |
|
232 |
base_url = req.base_url() |
|
233 |
else: |
|
234 |
base_url = None |
|
235 |
try: |
|
236 |
return publish_string(writer=Writer(base_url=base_url), |
|
1447
a1ca676294f0
don't use a singleton rest parser which may leads to concurrency bugs
sylvain.thenault@logilab.fr
parents:
1323
diff
changeset
|
237 |
parser=CubicWebReSTParser(), source=data, |
0 | 238 |
settings_overrides=settings) |
239 |
except Exception: |
|
240 |
LOGGER.exception('error while publishing ReST text') |
|
241 |
if not isinstance(data, unicode): |
|
242 |
data = unicode(data, encoding, 'replace') |
|
2312
af4d8f75c5db
use xml_escape
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2311
diff
changeset
|
243 |
return xml_escape(req._('error while publishing ReST text') |
0 | 244 |
+ '\n\n' + data) |
4118
8a9a00a9405c
quick and dirty fix trying to avoid rest directive conflicts when using sphinx (which seems to import the code)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2680
diff
changeset
|
245 |
|
8a9a00a9405c
quick and dirty fix trying to avoid rest directive conflicts when using sphinx (which seems to import the code)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2680
diff
changeset
|
246 |
|
8a9a00a9405c
quick and dirty fix trying to avoid rest directive conflicts when using sphinx (which seems to import the code)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2680
diff
changeset
|
247 |
_INITIALIZED = False |
8a9a00a9405c
quick and dirty fix trying to avoid rest directive conflicts when using sphinx (which seems to import the code)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2680
diff
changeset
|
248 |
def cw_rest_init(): |
8a9a00a9405c
quick and dirty fix trying to avoid rest directive conflicts when using sphinx (which seems to import the code)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2680
diff
changeset
|
249 |
global _INITIALIZED |
8a9a00a9405c
quick and dirty fix trying to avoid rest directive conflicts when using sphinx (which seems to import the code)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2680
diff
changeset
|
250 |
if _INITIALIZED: |
8a9a00a9405c
quick and dirty fix trying to avoid rest directive conflicts when using sphinx (which seems to import the code)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2680
diff
changeset
|
251 |
return |
8a9a00a9405c
quick and dirty fix trying to avoid rest directive conflicts when using sphinx (which seems to import the code)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2680
diff
changeset
|
252 |
_INITIALIZED = True |
8a9a00a9405c
quick and dirty fix trying to avoid rest directive conflicts when using sphinx (which seems to import the code)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2680
diff
changeset
|
253 |
register_canonical_role('eid', eid_reference_role) |
8a9a00a9405c
quick and dirty fix trying to avoid rest directive conflicts when using sphinx (which seems to import the code)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2680
diff
changeset
|
254 |
directives.register_directive('winclude', winclude_directive) |
8a9a00a9405c
quick and dirty fix trying to avoid rest directive conflicts when using sphinx (which seems to import the code)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2680
diff
changeset
|
255 |
if pygments_directive is not None: |
8a9a00a9405c
quick and dirty fix trying to avoid rest directive conflicts when using sphinx (which seems to import the code)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2680
diff
changeset
|
256 |
directives.register_directive('sourcecode', pygments_directive) |