Skip to content

Commit 80bd53a

Browse files
committed
Refactor localized and user-defined strings
- collect all localized string in Language - remove StringCollection and subclasses - the sections in a template file corresponding to the string collections are replaced by the [STRINGS] section - differentiate between builtin/user-defined strings by means of the @/$ symbols preceding the string identifiers (e.g. in [STRINGS]) - localize more strings: paragraph, section, listing
1 parent c9ff698 commit 80bd53a

32 files changed

+173
-355
lines changed

CHANGES.rst

+6-1
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,11 @@ New Features:
4141

4242
Changed:
4343

44+
* handling of localized strings and user-defined strings has been reworked
45+
* built-in (localized) strings are now indicated by a ``@`` prefix, while
46+
user-defined strings have the ``$`` prefix
47+
* built-in strings can be overridden, and user-defined strings can be set in
48+
a template configuration file in the ``[STRINGS]`` section (with prefix!)
4449
* "words" containing spaces (such as paths and URLs) can now be split before
4550
each forward slash for line wrapping (#188, #416)
4651
* Support for Python 3.7 was dropped (end-of-life in June 2023)
@@ -61,7 +66,7 @@ Changed:
6166

6267
Fixed:
6368

64-
* Caption labels ("Figure" ad "Table") were not localized
69+
* Caption labels ("Figure", "Table", "Listing") were not localized
6570
* Rendering of tables with no body (#420, PR #422 by th0mr)
6671
* Hyphenation of the first word on a line (#188, #416)
6772
* AttributeError: 'ZeroWidthSpace' object has no attribute 'hyphenate' (#415,

doc/api/strings.rst

-12
Original file line numberDiff line numberDiff line change
@@ -5,18 +5,6 @@
55
Strings (:mod:`rinoh.strings`)
66
==============================
77

8-
.. autoclass:: String
9-
:members:
10-
11-
12-
.. autoclass:: StringCollection
13-
:members:
14-
15-
16-
.. autoclass:: UserStrings
17-
:members:
18-
19-
208
.. autoclass:: Strings
219
:members:
2210

doc/api/structure.rst

-4
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,6 @@ Sections
1717
:members:
1818

1919

20-
.. autoclass:: SectionTitles
21-
:members:
22-
23-
2420
Lists
2521
~~~~~
2622

doc/basicstyling.rst

+4-5
Original file line numberDiff line numberDiff line change
@@ -167,11 +167,10 @@ distinction is only visible when using multiple columns for the page contents
167167

168168
The standard document strings configured by the
169169
:attr:`~.DocumentTemplate.language` option described above can be overridden by
170-
user-defined strings in the :class:`~.SectionTitles` and
171-
:class:`~.AdmonitionTitles` sections of the configuration file. For example,
172-
the default title for the table of contents section (*Table of Contents*) is
173-
replaced with *Contents*. The configuration also sets custom titles for the
174-
caution and warning admonitions.
170+
user-defined strings in the ``STRINGS`` section of the configuration file. For
171+
example, the default title for the table of contents section (*Table of
172+
Contents*) is replaced with *Contents*. The configuration also sets custom
173+
titles for the caution and warning admonitions.
175174

176175
The others sections in the configuration file are the ``VARIABLES`` section,
177176
followed by document part and page template sections. Similar to style sheets,

doc/my_book.rtt

+4-6
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,10 @@ parts =
1010
stylesheet = sphinx_base14
1111
language = fr
1212

13-
[SectionTitles]
14-
contents = 'Contents'
15-
16-
[AdmonitionTitles]
17-
caution = 'Careful!'
18-
warning = 'Please be warned'
13+
[STRINGS]
14+
@contents = 'Contents'
15+
@caution = 'Careful!'
16+
@warning = 'Please be warned'
1917

2018
[VARIABLES]
2119
paper_size = A5

doc/rinohtype.rtt

+2-2
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@ parts =
1111
stylesheet = rinohtype.rts
1212

1313

14-
[SectionTitles]
15-
contents='Contents'
14+
[STRINGS]
15+
@contents='Contents'
1616

1717

1818
[VARIABLES]

src/rinoh/__init__.py

-6
Original file line numberDiff line numberDiff line change
@@ -50,9 +50,3 @@
5050

5151
register_template = resource._DISTRIBUTION.register_template
5252
register_typeface = resource._DISTRIBUTION.register_typeface
53-
54-
# list all StringCollection subclasses in its docstring
55-
_ = ['* :class:`.{}`'.format(subclass_name)
56-
for subclass_name in sorted(strings.StringCollection.subclasses)]
57-
strings.StringCollection.__doc__ += ('\n\n :Subclasses: '
58-
+ '\n '.join(_))

src/rinoh/document.py

+21-14
Original file line numberDiff line numberDiff line change
@@ -231,7 +231,8 @@ class Document(object):
231231
document_tree (DocumentTree): a tree of the document's contents
232232
stylesheet (StyleSheet): style sheet used to style document elements
233233
language (Language): the language to use for standard strings
234-
strings (Strings): overrides localized strings provided by `language`
234+
strings (Strings): user-defined string variables and can override
235+
localized strings provided by `language`
235236
backend: the backend used for rendering the document
236237
237238
"""
@@ -380,21 +381,27 @@ def _save_cache(self, filename):
380381
cache = (self.part_page_counts, self.page_references)
381382
pickle.dump(cache, file)
382383

383-
def set_string(self, strings_class, key, value):
384-
self._strings[strings_class][key] = value
385-
386-
def get_string(self, strings_class, key):
387-
if (strings_class in self._strings
388-
and key in self._strings[strings_class]):
389-
return self._strings[strings_class][key]
384+
def set_string(self, key, value, user=False):
385+
if user:
386+
self._strings.set_user_string(key, value)
387+
else:
388+
self._strings.set_builtin_string(key, value)
389+
390+
def get_string(self, key, user=False):
391+
if user:
392+
result = self._strings.user.get(key, None)
393+
if result is None:
394+
warn('The "{}" user string is not defined.')
395+
return result or ''
396+
if key in self._strings.builtin:
397+
return self._strings.builtin[key]
390398
try:
391-
return self.language.strings[strings_class][key]
399+
return self.language.strings[key]
392400
except KeyError:
393-
warn('The {} "{}" string is not defined for {} ({}). Using the '
394-
'English string instead.'.format(strings_class.__name__, key,
395-
self.language.name,
396-
self.language.code))
397-
return EN.strings[strings_class][key]
401+
warn('The "{}" string is not defined for {} ({}). Using the English'
402+
' string instead.'
403+
.format(key, self.language.name, self.language.code))
404+
return EN.strings[key]
398405

399406
def add_sideways_float(self, float):
400407
self.sideways_floats.append(float)

src/rinoh/flowable.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@
2828
from .layout import (InlineDownExpandingContainer, VirtualContainer,
2929
MaybeContainer, ContainerOverflow, EndOfContainer,
3030
PageBreakException, ReflowRequired)
31-
from .strings import UserStrings
3231
from .style import Styled, Style
3332
from .text import StyledText
3433
from .util import clamp, ReadAliasAttribute
@@ -431,7 +430,7 @@ def __init__(self, label, content, parent=None):
431430

432431
def build_document(self, flowable_target):
433432
doc = flowable_target.document
434-
doc.set_string(UserStrings, self.label, self.content)
433+
doc.set_string(self.label, self.content, user=True)
435434

436435

437436
class SetOutOfLineFlowables(DummyFlowable):

src/rinoh/highlight.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ class CodeBlockWithCaptionStyle(FloatStyle, GroupedFlowablesStyle):
5959

6060
class CodeBlockWithCaption(Float, StaticGroupedFlowables):
6161
style_class = CodeBlockWithCaptionStyle
62-
category = 'Listing'
62+
category = 'listing'
6363

6464

6565
def highlight_block(language, text, lexer_getter):

src/rinoh/image.py

+2-9
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
from .layout import ContainerOverflow, EndOfContainer
2424
from .number import NumberFormat
2525
from .paragraph import StaticParagraph, Paragraph, ParagraphStyle
26-
from .strings import StringCollection, String, StringField
26+
from .strings import StringField
2727
from .structure import ListOf, ListOfSection
2828
from .text import MixedStyledText, SingleStyledText, TextStyle, ErrorText
2929
from .util import posix_path, ReadAliasAttribute, PeekIterator
@@ -398,7 +398,7 @@ def referenceable(self):
398398
def text(self, container):
399399
try:
400400
number = self.number(container)
401-
category_label = StringField(FloatLabels, self.referenceable.category)
401+
category_label = StringField(self.referenceable.category)
402402
label = [category_label, ' ', number]
403403
except KeyError:
404404
label = []
@@ -420,10 +420,3 @@ class ListOfFigures(ListOf):
420420

421421
class ListOfFiguresSection(ListOfSection):
422422
list_class = ListOfFigures
423-
424-
425-
class FloatLabels(StringCollection):
426-
"""Collection of localized titles for common sections"""
427-
428-
figure = String('Caption label for figures')
429-
table = String('Caption label for tables')

src/rinoh/index.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
from .paragraph import Paragraph
1212
from .reference import Reference
1313
from .strings import StringField
14-
from .structure import Section, Heading, SectionTitles
14+
from .structure import Section, Heading
1515
from .style import Styled
1616
from .text import MixedStyledText, StyledText
1717
from .util import intersperse
@@ -23,7 +23,7 @@
2323

2424
class IndexSection(Section):
2525
def __init__(self, title=None, flowables=None, style=None):
26-
section_title = title or StringField(SectionTitles, 'index')
26+
section_title = title or StringField('index')
2727
contents = [Heading(section_title, style='unnumbered')]
2828
if flowables:
2929
contents += list(flowables)
@@ -127,7 +127,7 @@ def spans(self, container):
127127

128128

129129
class IndexTarget(IndexTargetBase, DummyFlowable):
130-
category = 'Index'
130+
category = 'index'
131131

132132
def __init__(self, index_terms, parent=None):
133133
super().__init__(index_terms, parent=parent)

src/rinoh/language/__init__.py

+2-6
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,6 @@
2626
for code, language_ref in Language.languages.items():
2727
language = language_ref()
2828
lines = ['Localized strings for {}'.format(language.name)]
29-
for string_collection in language.strings.values():
30-
lines.append("\n.. rubric:: {}\n"
31-
.format(type(string_collection).__name__))
32-
for string in string_collection._strings:
33-
lines.append(":{}: {}".format(string.name,
34-
string_collection[string.name]))
29+
for name, localized_string in language.strings.items():
30+
lines.append(":{}: {}".format(name, localized_string))
3531
language.__doc__ = '\n'.join(lines)

src/rinoh/language/cls.py

+24-9
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
import weakref
1010

1111
from ..attribute import AttributeType
12-
from ..strings import StringCollection
1312

1413

1514
__all__ = ['Language']
@@ -22,27 +21,43 @@ class Language(AttributeType):
2221
code (str): short code identifying the language
2322
name (str): native name of the language
2423
24+
paragraph: label for referencing paragraphs
25+
section: label for referencing sections
26+
chapter: label for top-level sections
27+
figure: caption label for figures
28+
table: caption label for tables
29+
listing: caption label for (source code) listings
30+
contents: title for the table of contents section
31+
list_of_figures: title for the list of figures section
32+
list_of_tables: title for the list of tables section
33+
index: title for the index section
34+
35+
attention: title for attention admonitions
36+
caution: title for caution admonitions
37+
danger: title for danger admonitions
38+
error: title for error admonitions
39+
hint: title for hint admonitions
40+
important: title for important admonitions
41+
note: title for note admonitions
42+
tip: title for tip admonitions
43+
warning: title for warning admonitions
44+
seealso: title for see-also admonitions
45+
2546
"""
2647

2748
languages = {} #: Dictionary mapping codes to :class:`Language`\ s
2849

29-
def __init__(self, code, name):
50+
def __init__(self, code, name, **localized_strings):
3051
self.languages[code] = weakref.ref(self)
3152
self.code = code
3253
self.name = name
33-
self.strings = {}
54+
self.strings = localized_strings
3455
self.no_break_after = []
3556

3657
def __repr__(self):
3758
return "{}('{}', '{}')".format(type(self).__name__,
3859
self.code, self.name)
3960

40-
def __contains__(self, item):
41-
assert isinstance(item, StringCollection)
42-
strings_class = type(item)
43-
assert strings_class not in self.strings
44-
self.strings[strings_class] = item
45-
4661
@classmethod
4762
def parse_string(cls, string, source):
4863
return cls.languages[string.lower()]()

src/rinoh/language/cs.py

+3-11
Original file line numberDiff line numberDiff line change
@@ -7,26 +7,18 @@
77

88

99
from .cls import Language
10-
from ..image import FloatLabels
11-
from ..structure import SectionTitles, AdmonitionTitles
1210

1311

14-
CS = Language('cs', 'Česky')
15-
16-
FloatLabels(
12+
CS = Language('cs', 'Česky',
1713
figure='Obrázek',
1814
table='Tabulka',
19-
) in CS
20-
21-
SectionTitles(
2215
contents='Obsah',
2316
list_of_figures='Seznam obrázků',
2417
list_of_tables='Seznam tabulek',
2518
chapter='Kapitola',
2619
index='Rejstřík',
27-
) in CS
2820

29-
AdmonitionTitles(
21+
# admonitions
3022
attention='Pozor!',
3123
caution='Pozor!',
3224
danger='!NEBEZPEČÍ!',
@@ -37,7 +29,7 @@
3729
tip='Tip',
3830
warning='Varování',
3931
seealso='Viz také',
40-
) in CS
32+
)
4133

4234

4335
CS.no_break_after = ("do od u z ze za k ke o na v ve nad pod za po s se "

src/rinoh/language/de.py

+3-11
Original file line numberDiff line numberDiff line change
@@ -7,26 +7,18 @@
77

88

99
from .cls import Language
10-
from ..image import FloatLabels
11-
from ..structure import SectionTitles, AdmonitionTitles
1210

1311

14-
DE = Language('de', 'Deutsch')
15-
16-
FloatLabels(
12+
DE = Language('de', 'Deutsch',
1713
figure='Abbildung',
1814
table='Tabelle',
19-
) in DE
20-
21-
SectionTitles(
2215
contents='Inhalt',
2316
list_of_figures='Abbildungsverzeichnis',
2417
list_of_tables='Tabellenverzeichnis',
2518
chapter='Kapitel',
2619
index='Index',
27-
) in DE
2820

29-
AdmonitionTitles(
21+
# admonitions
3022
attention='Aufgepasst!',
3123
caution='Vorsicht!',
3224
danger='!GEFAHR!',
@@ -37,4 +29,4 @@
3729
tip='Tipp',
3830
warning='Warnung',
3931
seealso='Siehe auch',
40-
) in DE
32+
)

0 commit comments

Comments
 (0)