MCPcopy Create free account
hub / github.com/pymupdf/PyMuPDF / clean_rtl

Method clean_rtl

src/__init__.py:16800–16844  ·  view source on GitHub ↗

Revert the sequence of Latin text parts. Text with right-to-left writing direction (Arabic, Hebrew) often contains Latin parts, which are written in left-to-right: numbers, names, etc. For output as PDF text we need *everything* in right-to-left. E.g. an input like "

(self, text)

Source from the content-addressed store, hash-verified

16798 return self.text_rect, self.last_point
16799
16800 def clean_rtl(self, text):
16801 """Revert the sequence of Latin text parts.
16802
16803 Text with right-to-left writing direction (Arabic, Hebrew) often
16804 contains Latin parts, which are written in left-to-right: numbers, names,
16805 etc. For output as PDF text we need *everything* in right-to-left.
16806 E.g. an input like "<arabic> ABCDE FG HIJ <arabic> KL <arabic>" will be
16807 converted to "<arabic> JIH GF EDCBA <arabic> LK <arabic>". The Arabic
16808 parts remain untouched.
16809
16810 Args:
16811 text: str
16812 Returns:
16813 Massaged string.
16814 """
16815 if not text:
16816 return text
16817 # split into words at space boundaries
16818 words = text.split(" ")
16819 idx = []
16820 for i in range(len(words)):
16821 w = words[i]
16822 # revert character sequence for Latin only words
16823 if not (len(w) < 2 or max([ord(c) for c in w]) > 255):
16824 words[i] = "".join(reversed(w))
16825 idx.append(i) # stored index of Latin word
16826
16827 # adjacent Latin words must revert their sequence, too
16828 idx2 = [] # store indices of adjacent Latin words
16829 for i in range(len(idx)):
16830 if idx2 == []: # empty yet?
16831 idx2.append(idx[i]) # store Latin word number
16832
16833 elif idx[i] > idx2[-1] + 1: # large gap to last?
16834 if len(idx2) > 1: # at least two consecutives?
16835 words[idx2[0] : idx2[-1] + 1] = reversed(
16836 words[idx2[0] : idx2[-1] + 1]
16837 ) # revert their sequence
16838 idx2 = [idx[i]] # re-initialize
16839
16840 elif idx[i] == idx2[-1] + 1: # new adjacent Latin word
16841 idx2.append(idx[i])
16842
16843 text = " ".join(words)
16844 return text
16845
16846 def fill_textbox(
16847 writer: 'TextWriter',

Callers 3

appendMethod · 0.95
fill_textboxMethod · 0.80
fill_textboxFunction · 0.80

Calls 1

appendMethod · 0.45

Tested by

no test coverage detected