I want to set a style to a corrected word in MS Word text. Since it's not possible to change text style inside a run, I want to insert a new run with new style into the existing paragraph...
for p in document.paragraphs:
for run in p.runs:
if 'text' in run.text:
new_run= Run()
new_run.text='some new text'
# insert this run into paragraph
# smth like:
p.insert(new_run)
How to do it?
p.add_run()
adds run to the end of paragraph, doesn't it?
The best would be to be able to clone run (and insert it after a certain run). This way we reproduce the original run's style attributes in the new/cloned one.
I could manage that insertion code:
if 'text' in run.text:
new_run_element = CT_R() #._new()
run._element.addnext(new_run_element)
new_run = Run(new_run_element, run._parent)
...
But after that:
len(p.runs)
There's no API support for this, but it can be readily accomplished at the oxml/lxml level:
from docx.text.run import Run
from docx.oxml.text.run import CT_R
# ...
for run in p.runs:
if 'text' in run.text:
new_run_element = p._element._new_r()
run._element.addnext(new_run_element)
new_run = Run(new_run_element, run._parent)
# ---do things with new_run, e.g.---
new_run.text = 'Foobar'
new_run.bold = True
If you want to insert the new run prior to the existing run, use run._element.addprevious(new_run_element)
. These two are methods on the lxml.etree._Element
class which all python-docx
elements subclass.
https://lxml.de/api/lxml.etree._Element-class.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With