Debian Codegraph @

docutils/core.py

raw symbols SCIP
1 # $Id: core.py 10267 2025-12-01 22:43:32Z milde $
2 # Author: David Goodger <[email protected]>
3 # Copyright: This module has been placed in the public domain.
4
5 """
6 Calling the ``publish_*`` convenience functions (or instantiating a
7 `Publisher` object) with component names will result in default
8 behavior. For custom behavior (setting component options), create
9 custom component objects first, and pass *them* to
10 ``publish_*``/`Publisher`. See `The Docutils Publisher`_.
11
12 .. _The Docutils Publisher:
13 https://docutils.sourceforge.io/docs/api/publisher.html
14 """
15
16 from __future__ import annotations
17
18 __docformat__ = 'reStructuredText'
19
20 import locale
21 import pprint
22 import os
23 import sys
24 import warnings
25
26 from docutils import (__version__, __version_details__, SettingsSpec,
27 io, utils, readers, parsers, writers)
28 from docutils.frontend import OptionParser
29 from docutils.readers import doctree
30
31 TYPE_CHECKING = False
32 if TYPE_CHECKING:
33 from typing import TextIO
34 from docutils.nodes import StrPath
35
36
37 class Publisher:
38
39 """
40 A facade encapsulating the high-level logic of a Docutils system.
41 """
42
43 def __init__(self, reader=None, parser=None, writer=None,
44 source=None, source_class=io.FileInput,
45 destination=None, destination_class=io.FileOutput,
46 settings=None) -> None:
47 """
48 Initial setup.
49
50 The components `reader`, `parser`, or `writer` should all be
51 specified, either as instances or via their names.
52 """
53 # get component instances from their names:
54 if isinstance(reader, str):
55 reader = readers.get_reader_class(reader)(parser)
56 if isinstance(parser, str):
57 if isinstance(reader, readers.Reader):
58 if reader.parser is None:
59 reader.set_parser(parser)
60 parser = reader.parser
61 else:
62 parser = parsers.get_parser_class(parser)()
63 if isinstance(writer, str):
64 writer = writers.get_writer_class(writer)()
65
66 self.document = None
67 """The document tree (`docutils.nodes` objects)."""
68
69 self.reader = reader
70 """A `docutils.readers.Reader` instance."""
71
72 self.parser = parser
73 """A `docutils.parsers.Parser` instance."""
74
75 self.writer = writer
76 """A `docutils.writers.Writer` instance."""
77
78 self.source = source
79 """The source of input data, a `docutils.io.Input` instance."""
80
81 self.source_class = source_class
82 """The class for dynamically created source objects."""
83
84 self.destination = destination
85 """The destination for docutils output, a `docutils.io.Output`
86 instance."""
87
88 self.destination_class = destination_class
89 """The class for dynamically created destination objects."""
90
91 self.settings = settings
92 """An object containing Docutils settings as instance attributes.
93 Set by `self.process_command_line()` or `self.get_settings()`."""
94
95 self._stderr = io.ErrorOutput()
96
97 def set_reader(self, reader, parser=None, parser_name=None) -> None:
98 """Set `self.reader` by name.
99
100 The "paser_name" argument is deprecated,
101 use "parser" with parser name or instance.
102 """
103 reader_class = readers.get_reader_class(reader)
104 self.reader = reader_class(parser, parser_name)
105 if self.reader.parser is not None:
106 self.parser = self.reader.parser
107 elif self.parser is not None:
108 self.reader.parser = self.parser
109
110 def set_writer(self, writer_name) -> None:
111 """Set `self.writer` by name."""
112 writer_class = writers.get_writer_class(writer_name)
113 self.writer = writer_class()
114
115 def set_components(self, reader_name, parser_name, writer_name) -> None:
116 warnings.warn('`Publisher.set_components()` will be removed in '
117 'Docutils 2.0. Specify component names '
118 'at instantiation.',
119 PendingDeprecationWarning, stacklevel=2)
120 if self.reader is None:
121 self.set_reader(reader_name, self.parser, parser_name)
122 if self.parser is None:
123 if self.reader.parser is None:
124 self.reader.set_parser(parser_name)
125 self.parser = self.reader.parser
126 if self.writer is None:
127 self.set_writer(writer_name)
128
129 def _setup_settings_parser(self, usage=None, description=None,
130 settings_spec=None, config_section=None,
131 **defaults):
132 # Provisional: will change (docutils.frontend.OptionParser will
133 # be replaced by a parser based on arparse.ArgumentParser)
134 # and may be removed later.
135 with warnings.catch_warnings():
136 warnings.filterwarnings('ignore', category=DeprecationWarning)
137 if config_section:
138 if not settings_spec:
139 settings_spec = SettingsSpec()
140 settings_spec.config_section = config_section
141 parts = config_section.split()
142 if len(parts) > 1 and parts[-1] == 'application':
143 settings_spec.config_section_dependencies = ['applications'] # noqa: E501
144 # @@@ Add self.source & self.destination to components in future?
145 return OptionParser(
146 components=(self.parser, self.reader, self.writer,
147 settings_spec),
148 defaults=defaults, read_config_files=True,
149 usage=usage, description=description)
150
151 def get_settings(self, usage=None, description=None,
152 settings_spec=None, config_section=None, **defaults):
153 """
154 Return settings from components and config files.
155
156 Please set components first (`self.set_reader` & `self.set_writer`).
157 Use keyword arguments to override component defaults
158 (before updating from configuration files).
159
160 Calling this function also sets `self.settings` which makes
161 `self.publish()` skip parsing command line options.
162 """
163 option_parser = self._setup_settings_parser(
164 usage, description, settings_spec, config_section, **defaults)
165 self.settings = option_parser.get_default_values()
166 return self.settings
167
168 def process_programmatic_settings(self, settings_spec,
169 settings_overrides,
170 config_section) -> None:
171 if self.settings is None:
172 defaults = settings_overrides.copy() if settings_overrides else {}
173 # Propagate exceptions by default when used programmatically:
174 defaults.setdefault('traceback', True)
175 self.get_settings(settings_spec=settings_spec,
176 config_section=config_section,
177 **defaults)
178
179 def process_command_line(self, argv=None, usage=None, description=None,
180 settings_spec=None, config_section=None,
181 **defaults) -> None:
182 """
183 Parse command line arguments and set ``self.settings``.
184
185 Pass an empty sequence to `argv` to avoid reading `sys.argv`
186 (the default behaviour).
187
188 Set components first (`self.set_reader` & `self.set_writer`).
189 """
190 option_parser = self._setup_settings_parser(
191 usage, description, settings_spec, config_section, **defaults)
192 if argv is None:
193 argv = sys.argv[1:]
194 self.settings = option_parser.parse_args(argv)
195
196 def set_io(self, source_path=None, destination_path=None) -> None:
197 if self.source is None:
198 self.set_source(source_path=source_path)
199 if self.destination is None:
200 self.set_destination(destination_path=destination_path)
201
202 def set_source(self,
203 source: str | None = None,
204 source_path: StrPath | None = None,
205 ) -> None:
206 if source_path is None:
207 source_path = self.settings._source
208 else:
209 source_path = os.fspath(source_path)
210 self.settings._source = source_path
211 self.source = self.source_class(
212 source=source, source_path=source_path,
213 encoding=self.settings.input_encoding,
214 error_handler=self.settings.input_encoding_error_handler)
215
216 def set_destination(self,
217 destination: TextIO | None = None,
218 destination_path: StrPath | None = None,
219 ) -> None:
220 # Provisional: the "_destination" and "output" settings
221 # are deprecated and will be ignored in Docutils 2.0.
222 if destination_path is not None:
223 self.settings.output_path = os.fspath(destination_path)
224 else:
225 # check 'output_path' and legacy settings
226 if getattr(self.settings, 'output', None
227 ) and not self.settings.output_path:
228 self.settings.output_path = self.settings.output
229 if (self.settings.output_path and self.settings._destination
230 and self.settings.output_path != self.settings._destination):
231 raise SystemExit('The --output-path option obsoletes the '
232 'second positional argument (DESTINATION). '
233 'You cannot use them together.')
234 if self.settings.output_path is None:
235 self.settings.output_path = self.settings._destination
236 if self.settings.output_path == '-': # use stdout
237 self.settings.output_path = None
238 self.settings._destination = self.settings.output \
239 = self.settings.output_path
240
241 self.destination = self.destination_class(
242 destination=destination,
243 destination_path=self.settings.output_path,
244 encoding=self.settings.output_encoding,
245 error_handler=self.settings.output_encoding_error_handler)
246
247 def apply_transforms(self) -> None:
248 self.document.transformer.populate_from_components(
249 (self.source, self.reader, self.reader.parser, self.writer,
250 self.destination))
251 self.document.transformer.apply_transforms()
252
253 def publish(self, argv=None, usage=None, description=None,
254 settings_spec=None, settings_overrides=None,
255 config_section=None, enable_exit_status=False):
256 """
257 Process command line options and arguments (if `self.settings` not
258 already set), run `self.reader` and then `self.writer`. Return
259 `self.writer`'s output.
260 """
261 exit_ = None
262 try:
263 if self.settings is None:
264 self.process_command_line(
265 argv, usage, description, settings_spec, config_section,
266 **(settings_overrides or {}))
267 self.set_io()
268 self.prompt()
269 self.document = self.reader.read(self.source, self.parser,
270 self.settings)
271 self.apply_transforms()
272 output = self.writer.write(self.document, self.destination)
273 self.writer.assemble_parts()
274 except SystemExit as error:
275 exit_ = True
276 exit_status = error.code
277 except Exception as error:
278 if not self.settings: # exception too early to report nicely
279 raise
280 if self.settings.traceback: # Propagate exceptions?
281 self.debugging_dumps()
282 raise
283 self.report_Exception(error)
284 exit_ = True
285 exit_status = 1
286 self.debugging_dumps()
287 if (enable_exit_status and self.document
288 and (self.document.reporter.max_level
289 >= self.settings.exit_status_level)):
290 sys.exit(self.document.reporter.max_level + 10)
291 elif exit_:
292 sys.exit(exit_status)
293 return output
294
295 def debugging_dumps(self) -> None:
296 if not self.document:
297 return
298 if self.settings.dump_settings:
299 print('\n::: Runtime settings:', file=self._stderr)
300 print(pprint.pformat(self.settings.__dict__), file=self._stderr)
301 if self.settings.dump_internals:
302 print('\n::: Document internals:', file=self._stderr)
303 print(pprint.pformat(self.document.__dict__), file=self._stderr)
304 if self.settings.dump_transforms:
305 print('\n::: Transforms applied:', file=self._stderr)
306 print(' (priority, transform class, pending node details, '
307 'keyword args)', file=self._stderr)
308 print(pprint.pformat(
309 [(priority, '%s.%s' % (xclass.__module__, xclass.__name__),
310 pending and pending.details, kwargs)
311 for priority, xclass, pending, kwargs
312 in self.document.transformer.applied]), file=self._stderr)
313 if self.settings.dump_pseudo_xml:
314 print('\n::: Pseudo-XML:', file=self._stderr)
315 print(self.document.pformat().encode(
316 'raw_unicode_escape'), file=self._stderr)
317
318 def prompt(self) -> None:
319 """Print info and prompt when waiting for input from a terminal."""
320 try:
321 if not (self.source.isatty() and self._stderr.isatty()):
322 return
323 except AttributeError:
324 return
325 eot_key = 'Ctrl+Z' if os.name == 'nt' else 'Ctrl+D'
326 in_format = ''
327 out_format = 'useful formats'
328 try:
329 in_format = self.parser.supported[0]
330 out_format = self.writer.supported[0]
331 except (AttributeError, IndexError):
332 pass
333 print(f'Docutils {__version__} <https://docutils.sourceforge.io>\n'
334 f'converting "{in_format}" into "{out_format}".\n'
335 f'Call with option "--help" for more info.\n'
336 f'.. Waiting for source text (finish with {eot_key} '
337 'on an empty line):',
338 file=self._stderr)
339
340 def report_Exception(self, error) -> None:
341 if isinstance(error, utils.SystemMessage):
342 self.report_SystemMessage(error)
343 elif isinstance(error, UnicodeEncodeError):
344 self.report_UnicodeError(error)
345 elif isinstance(error, io.InputError):
346 self._stderr.write('Unable to open source file for reading:\n'
347 ' %s\n' % io.error_string(error))
348 elif isinstance(error, io.OutputError):
349 self._stderr.write(
350 'Unable to open destination file for writing:\n'
351 ' %s\n' % io.error_string(error))
352 else:
353 print('%s' % io.error_string(error), file=self._stderr)
354 print(f"""\
355 Exiting due to error. Use "--traceback" to diagnose.
356 Please report errors to <[email protected]>.
357 Include "--traceback" output, Docutils version ({__version__}\
358 {f' [{__version_details__}]' if __version_details__ else ''}),
359 Python version ({sys.version.split()[0]}), your OS type & version, \
360 and the command line used.""", file=self._stderr)
361
362 def report_SystemMessage(self, error) -> None:
363 print('Exiting due to level-%s (%s) system message.' % (
364 error.level, utils.Reporter.levels[error.level]),
365 file=self._stderr)
366
367 def report_UnicodeError(self, error) -> None:
368 data = error.object[error.start:error.end]
369 self._stderr.write(
370 '%s\n'
371 '\n'
372 'The specified output encoding (%s) cannot\n'
373 'handle all of the output.\n'
374 'Try setting "--output-encoding-error-handler" to\n'
375 '\n'
376 '* "xmlcharrefreplace" (for HTML & XML output);\n'
377 ' the output will contain "%s" and should be usable.\n'
378 '* "backslashreplace" (for other output formats);\n'
379 ' look for "%s" in the output.\n'
380 '* "replace"; look for "?" in the output.\n'
381 '\n'
382 '"--output-encoding-error-handler" is currently set to "%s".\n'
383 '\n'
384 'Exiting due to error. Use "--traceback" to diagnose.\n'
385 'If the advice above doesn\'t eliminate the error,\n'
386 'please report it to <[email protected]>.\n'
387 'Include "--traceback" output, Docutils version (%s),\n'
388 'Python version (%s), your OS type & version, and the\n'
389 'command line used.\n'
390 % (io.error_string(error),
391 self.settings.output_encoding,
392 data.encode('ascii', 'xmlcharrefreplace'),
393 data.encode('ascii', 'backslashreplace'),
394 self.settings.output_encoding_error_handler,
395 __version__, sys.version.split()[0]))
396
397
398 default_usage = '%prog [options] [<source> [<destination>]]'
399 default_description = (
400 'Reads from <source> (default is stdin) '
401 'and writes to <destination> (default is stdout). '
402 'See https://docutils.sourceforge.io/docs/user/config.html '
403 'for a detailed settings reference.')
404
405
406 # TODO: or not to do? cf. https://clig.dev/#help
407 #
408 # Display output on success, but keep it brief.
409 # Provide a -q option to suppress all non-essential output.
410 #
411 # Chain several args as input and use --output or redirection for output:
412 # argparser.add_argument('source', nargs='+')
413 #
414 def publish_cmdline(reader=None, reader_name=None,
415 parser=None, parser_name=None,
416 writer=None, writer_name=None,
417 settings=None, settings_spec=None,
418 settings_overrides=None, config_section=None,
419 enable_exit_status=True, argv=None,
420 usage=default_usage, description=default_description):
421 """
422 Set up & run a `Publisher` for command-line-based file I/O (input and
423 output file paths taken automatically from the command line).
424 Also return the output as `str` or `bytes` (for binary output document
425 formats).
426
427 Parameters: see `publish_programmatically()` for the remainder.
428
429 - `argv`: Command-line argument list to use instead of ``sys.argv[1:]``.
430 - `usage`: Usage string, output if there's a problem parsing the command
431 line.
432 - `description`: Program description, output for the "--help" option
433 (along with command-line option descriptions).
434 """
435 # The "*_name" arguments are deprecated.
436 _name_arg_warning(reader_name, parser_name, writer_name)
437 # The default is only used if both arguments are empty
438 reader = reader or reader_name or 'standalone'
439 parser = parser or parser_name or 'restructuredtext'
440 writer = writer or writer_name or 'pseudoxml'
441 publisher = Publisher(reader, parser, writer, settings=settings)
442 output = publisher.publish(
443 argv, usage, description, settings_spec, settings_overrides,
444 config_section=config_section, enable_exit_status=enable_exit_status)
445 return output
446
447
448 def publish_file(source=None, source_path=None,
449 destination=None, destination_path=None,
450 reader=None, reader_name=None,
451 parser=None, parser_name=None,
452 writer=None, writer_name=None,
453 settings=None, settings_spec=None, settings_overrides=None,
454 config_section=None, enable_exit_status=False):
455 """
456 Set up & run a `Publisher` for programmatic use with file-like I/O.
457 Also return the output as `str` or `bytes` (for binary output document
458 formats).
459
460 Parameters: see `publish_programmatically()`.
461 """
462 # The "*_name" arguments are deprecated.
463 _name_arg_warning(reader_name, parser_name, writer_name)
464 # The default is set in publish_programmatically().
465 output, _publisher = publish_programmatically(
466 source_class=io.FileInput, source=source, source_path=source_path,
467 destination_class=io.FileOutput,
468 destination=destination, destination_path=destination_path,
469 reader=reader, reader_name=reader_name,
470 parser=parser, parser_name=parser_name,
471 writer=writer, writer_name=writer_name,
472 settings=settings, settings_spec=settings_spec,
473 settings_overrides=settings_overrides,
474 config_section=config_section,
475 enable_exit_status=enable_exit_status)
476 return output
477
478
479 def publish_string(source, source_path=None, destination_path=None,
480 reader=None, reader_name=None,
481 parser=None, parser_name=None,
482 writer=None, writer_name=None,
483 settings=None, settings_spec=None,
484 settings_overrides=None, config_section=None,
485 enable_exit_status=False):
486 """
487 Set up & run a `Publisher` for programmatic use with string I/O.
488
489 Accepts a `bytes` or `str` instance as `source`.
490
491 The output is encoded according to the `output_encoding`_ setting;
492 the return value is a `bytes` instance (unless `output_encoding`_ is
493 "unicode", cf. `docutils.io.StringOutput.write()`).
494
495 Parameters: see `publish_programmatically()` or
496 https://docutils.sourceforge.io/docs/api/publisher.html#publish-string
497
498 This function is provisional because in Python 3 name and behaviour
499 no longer match.
500
501 .. _output_encoding:
502 https://docutils.sourceforge.io/docs/user/config.html#output-encoding
503 """
504 # The "*_name" arguments are deprecated.
505 _name_arg_warning(reader_name, parser_name, writer_name)
506 # The default is set in publish_programmatically().
507 output, _publisher = publish_programmatically(
508 source_class=io.StringInput, source=source, source_path=source_path,
509 destination_class=io.StringOutput,
510 destination=None, destination_path=destination_path,
511 reader=reader, reader_name=reader_name,
512 parser=parser, parser_name=parser_name,
513 writer=writer, writer_name=writer_name,
514 settings=settings, settings_spec=settings_spec,
515 settings_overrides=settings_overrides,
516 config_section=config_section,
517 enable_exit_status=enable_exit_status)
518 return output
519
520
521 def publish_parts(source, source_path=None, source_class=io.StringInput,
522 destination_path=None,
523 reader=None, reader_name=None,
524 parser=None, parser_name=None,
525 writer=None, writer_name=None,
526 settings=None, settings_spec=None,
527 settings_overrides=None, config_section=None,
528 enable_exit_status=False):
529 """
530 Set up & run a `Publisher`, and return a dictionary of document parts.
531
532 Dictionary keys are the names of parts.
533 Dictionary values are `str` instances; encoding is up to the client,
534 e.g.::
535
536 parts = publish_parts(...)
537 body = parts['body'].encode(parts['encoding'], parts['errors'])
538
539 See the `API documentation`__ for details on the provided parts.
540
541 Parameters: see `publish_programmatically()`.
542
543 __ https://docutils.sourceforge.io/docs/api/publisher.html#publish-parts
544 """
545 # The "*_name" arguments are deprecated.
546 _name_arg_warning(reader_name, parser_name, writer_name)
547 # The default is set in publish_programmatically().
548 _output, publisher = publish_programmatically(
549 source=source, source_path=source_path, source_class=source_class,
550 destination_class=io.StringOutput,
551 destination=None, destination_path=destination_path,
552 reader=reader, reader_name=reader_name,
553 parser=parser, parser_name=parser_name,
554 writer=writer, writer_name=writer_name,
555 settings=settings, settings_spec=settings_spec,
556 settings_overrides=settings_overrides,
557 config_section=config_section,
558 enable_exit_status=enable_exit_status)
559 return publisher.writer.parts
560
561
562 def publish_doctree(source, source_path=None,
563 source_class=io.StringInput,
564 reader=None, reader_name=None,
565 parser=None, parser_name=None,
566 settings=None, settings_spec=None,
567 settings_overrides=None, config_section=None,
568 enable_exit_status=False):
569 """
570 Set up & run a `Publisher` for programmatic use. Return a document tree.
571
572 Parameters: see `publish_programmatically()`.
573 """
574 # The "*_name" arguments are deprecated.
575 _name_arg_warning(reader_name, parser_name, None)
576 # The default is set in publish_programmatically().
577 _output, publisher = publish_programmatically(
578 source=source, source_path=source_path,
579 source_class=source_class,
580 destination=None, destination_path=None,
581 destination_class=io.NullOutput,
582 reader=reader, reader_name=reader_name,
583 parser=parser, parser_name=parser_name,
584 writer='null', writer_name=None,
585 settings=settings, settings_spec=settings_spec,
586 settings_overrides=settings_overrides, config_section=config_section,
587 enable_exit_status=enable_exit_status)
588 return publisher.document
589
590
591 def publish_from_doctree(document, destination_path=None,
592 writer=None, writer_name=None,
593 settings=None, settings_spec=None,
594 settings_overrides=None, config_section=None,
595 enable_exit_status=False):
596 """
597 Set up & run a `Publisher` to render from an existing document tree
598 data structure. For programmatic use with string output
599 (`bytes` or `str`, cf. `publish_string()`).
600
601 Note that ``document.settings`` is overridden; if you want to use the
602 settings of the original `document`, pass ``settings=document.settings``.
603
604 Also, new `document.transformer` and `document.reporter` objects are
605 generated.
606
607 Parameters: `document` is a `docutils.nodes.document` object, an existing
608 document tree.
609
610 Other parameters: see `publish_programmatically()`.
611
612 This function is provisional because in Python 3 name and behaviour
613 of the `io.StringOutput` class no longer match.
614 """
615 # The "writer_name" argument is deprecated.
616 _name_arg_warning(None, None, writer_name)
617 publisher = Publisher(reader=doctree.Reader(),
618 writer=writer or writer_name or 'pseudoxml',
619 source=io.DocTreeInput(document),
620 destination_class=io.StringOutput,
621 settings=settings)
622 publisher.process_programmatic_settings(
623 settings_spec, settings_overrides, config_section)
624 publisher.set_destination(None, destination_path)
625 return publisher.publish(enable_exit_status=enable_exit_status)
626
627
628 def publish_cmdline_to_binary(reader=None, reader_name='standalone',
629 parser=None, parser_name='restructuredtext',
630 writer=None, writer_name='pseudoxml',
631 settings=None,
632 settings_spec=None,
633 settings_overrides=None,
634 config_section=None,
635 enable_exit_status=True,
636 argv=None,
637 usage=default_usage,
638 description=default_description,
639 destination=None,
640 destination_class=io.BinaryFileOutput):
641 """
642 Set up & run a `Publisher` for command-line-based file I/O (input and
643 output file paths taken automatically from the command line).
644 Also return the output as `bytes`.
645
646 This is just like publish_cmdline, except that it uses
647 io.BinaryFileOutput instead of io.FileOutput.
648
649 Parameters: see `publish_programmatically()` for the remainder.
650
651 - `argv`: Command-line argument list to use instead of ``sys.argv[1:]``.
652 - `usage`: Usage string, output if there's a problem parsing the command
653 line.
654 - `description`: Program description, output for the "--help" option
655 (along with command-line option descriptions).
656
657 Deprecated. Use `publish_cmdline()` (works with `bytes` since
658 Docutils 0.20). Will be removed in Docutils 0.24.
659 """
660 warnings.warn('"publish_cmdline_to_binary()" is obsoleted'
661 ' by "publish_cmdline()" and will be removed'
662 ' in Docutils 0.24.', DeprecationWarning, stacklevel=2)
663 publisher = Publisher(reader, parser, writer, settings=settings,
664 destination_class=destination_class)
665 publisher.set_components(reader_name, parser_name, writer_name)
666 output = publisher.publish(
667 argv, usage, description, settings_spec, settings_overrides,
668 config_section=config_section, enable_exit_status=enable_exit_status)
669 return output
670
671
672 def _name_arg_warning(*name_args) -> None:
673 for component, name_arg in zip(('reader', 'parser', 'writer'), name_args):
674 if name_arg is not None:
675 warnings.warn(f'Argument "{component}_name" will be removed in '
676 f'Docutils 2.0. Specify {component} name '
677 f'in the "{component}" argument.',
678 PendingDeprecationWarning, stacklevel=3)
679
680
681 def publish_programmatically(source_class, source, source_path,
682 destination_class, destination, destination_path,
683 reader, reader_name,
684 parser, parser_name,
685 writer, writer_name,
686 settings, settings_spec,
687 settings_overrides, config_section,
688 enable_exit_status):
689 """
690 Set up & run a `Publisher` for custom programmatic use.
691
692 Return the output (as `str` or `bytes`, depending on `destination_class`,
693 writer, and the "output_encoding" setting) and the Publisher object.
694
695 Internal:
696 Applications should not call this function directly. If it does
697 seem to be necessary to call this function directly, please write to the
698 Docutils-develop mailing list
699 <https://docutils.sourceforge.io/docs/user/mailing-lists.html#docutils-develop>.
700
701 Parameters:
702
703 * `source_class` **required**: The class for dynamically created source
704 objects. Typically `io.FileInput` or `io.StringInput`.
705
706 * `source`: Type depends on `source_class`:
707
708 - If `source_class` is `io.FileInput`: Either a file-like object
709 (must have 'read' and 'close' methods), or ``None``
710 (`source_path` is opened). If neither `source` nor
711 `source_path` are supplied, `sys.stdin` is used.
712
713 - If `source_class` is `io.StringInput` **required**:
714 The input as either a `bytes` object (ensure the 'input_encoding'
715 setting matches its encoding) or a `str` object.
716
717 * `source_path`: Type depends on `source_class`:
718
719 - `io.FileInput`: Path to the input file, opened if no `source`
720 supplied.
721
722 - `io.StringInput`: Optional. Path to the file or description of the
723 object that produced `source`. Only used for diagnostic output.
724
725 * `destination_class` **required**: The class for dynamically created
726 destination objects. Typically `io.FileOutput` or `io.StringOutput`.
727
728 * `destination`: Type depends on `destination_class`:
729
730 - `io.FileOutput`: Either a file-like object (must have 'write' and
731 'close' methods), or ``None`` (`destination_path` is opened). If
732 neither `destination` nor `destination_path` are supplied,
733 `sys.stdout` is used.
734
735 - `io.StringOutput`: Not used; pass ``None``.
736
737 * `destination_path`: Type depends on `destination_class`:
738
739 - `io.FileOutput`: Path to the output file. Opened if no `destination`
740 supplied.
741
742 - `io.StringOutput`: Path to the file or object which will receive the
743 output; optional. Used for determining relative paths (stylesheets,
744 source links, etc.).
745
746 * `reader`: A `docutils.readers.Reader` instance, name, or alias.
747 Default: "standalone".
748
749 * `reader_name`: Deprecated. Use `reader`.
750
751 * `parser`: A `docutils.parsers.Parser` instance, name, or alias.
752 Default: "restructuredtext".
753
754 * `parser_name`: Deprecated. Use `parser`.
755
756 * `writer`: A `docutils.writers.Writer` instance, name, or alias.
757 Default: "pseudoxml".
758
759 * `writer_name`: Deprecated. Use `writer`.
760
761 * `settings`: A runtime settings (`docutils.frontend.Values`) object, for
762 dotted-attribute access to runtime settings. It's the end result of the
763 `SettingsSpec`, config file, and option processing. If `settings` is
764 passed, it's assumed to be complete and no further setting/config/option
765 processing is done.
766
767 * `settings_spec`: A `docutils.SettingsSpec` subclass or object. Provides
768 extra application-specific settings definitions independently of
769 components. In other words, the application becomes a component, and
770 its settings data is processed along with that of the other components.
771 Used only if no `settings` specified.
772
773 * `settings_overrides`: A dictionary containing application-specific
774 settings defaults that override the defaults of other components.
775 Used only if no `settings` specified.
776
777 * `config_section`: A string, the name of the configuration file section
778 for this application. Overrides the ``config_section`` attribute
779 defined by `settings_spec`. Used only if no `settings` specified.
780
781 * `enable_exit_status`: Boolean; enable exit status at end of processing?
782 """
783 reader = reader or reader_name or 'standalone'
784 parser = parser or parser_name or 'restructuredtext'
785 writer = writer or writer_name or 'pseudoxml'
786
787 publisher = Publisher(reader, parser, writer, settings=settings,
788 source_class=source_class,
789 destination_class=destination_class)
790 publisher.process_programmatic_settings(
791 settings_spec, settings_overrides, config_section)
792 publisher.set_source(source, source_path)
793 publisher.set_destination(destination, destination_path)
794 output = publisher.publish(enable_exit_status=enable_exit_status)
795 return output, publisher
796
797
798 # "Entry points" with functionality of the "tools/rst2*.py" scripts
799 # cf. https://packaging.python.org/en/latest/specifications/entry-points/
800
801 def rst2something(writer, documenttype, doc_path='') -> None:
802 # Helper function for the common parts of `rst2*()`
803 # writer: writer name
804 # documenttype: output document type
805 # doc_path: documentation path (relative to the documentation root)
806 description = (
807 f'Generate {documenttype} documents '
808 'from standalone reStructuredText sources '
809 f'<https://docutils.sourceforge.io/docs/{doc_path}>. '
810 + default_description)
811 try:
812 locale.setlocale(locale.LC_ALL, '')
813 except locale.Error as e:
814 sys.stderr.write(f'WARNING: Cannot set the default locale: {e}.\n')
815 publish_cmdline(writer=writer, description=description)
816
817
818 def rst2html() -> None:
819 rst2something('html', 'HTML', 'user/html.html#html')
820
821
822 def rst2html4() -> None:
823 rst2something('html4', 'XHTML 1.1', 'user/html.html#html4css1')
824
825
826 def rst2html5() -> None:
827 rst2something('html5', 'HTML5', 'user/html.html#html5-polyglot')
828
829
830 def rst2latex() -> None:
831 rst2something('latex', 'LaTeX', 'user/latex.html')
832
833
834 def rst2man() -> None:
835 rst2something('manpage', 'Unix manual (troff)', 'user/manpage.html')
836
837
838 def rst2odt() -> None:
839 rst2something('odt', 'OpenDocument text (ODT)', 'user/odt.html')
840
841
842 def rst2pseudoxml() -> None:
843 rst2something('pseudoxml', 'pseudo-XML (test)', 'ref/doctree.html')
844
845
846 def rst2s5() -> None:
847 rst2something('s5', 'S5 HTML slideshow', 'user/slide-shows.html')
848
849
850 def rst2xetex() -> None:
851 rst2something('xetex', 'LaTeX (XeLaTeX/LuaLaTeX)', 'user/latex.html')
852
853
854 def rst2xml() -> None:
855 rst2something('xml', 'Docutils-native XML', 'ref/doctree.html')