feature: add field
See original GitHub issueFeature Suggestion/Request
Support for inserting/adding Field Codes in a word document. They are a handy feature for report generation type applications (originally intended for automatic mailout merges I believe).
In Office, they make it easy to add dynamic features to a document without getting your fingers all slimey with macros/VBA (although, if designed properly they are accessible from VBA using custom DocProperties and clever references). You work with them using text “markups” that form a restricted scripting framework (hit ctrl+F9 to get started within Word).
They can easily work with DocProperties, named elements (tables, lists, headings), and external text documents that will drive the dynamic content. You can still use styles to drive a document, but with field codes you can adjust/apply syles conditionally.But field codes are admittedly ackward to work with (odd syntax, updating, poor UI tools). Thats where python-docx needs to come in.
I think with a little love, working with field codes could actually be neat, organized, readable, and very functional. They would slip in just lile your other elements…
document.add_fcode("ASK", "chap1_caption", "Type in caption for Chaper 1")
Nesting field codes arbitrarily would be important requirement.
Instead of making custom routines in python-docx that help a user hack together structured portions of a document or specific output patterns, let us use field codes to define those structures expliciltly. And then when we export back into an Office driven workflow, all of the glue is still intact and fully functional.
The main weakness of field codes is that they are typically hidden/disabled by default in Word, but in that regard, its not much different than shipping a document with embedded macros: it is understood that you know how to interact with the extended features.
Issue Analytics
- State:
- Created 9 years ago
- Comments:22 (7 by maintainers)

Top Related StackOverflow Question
Dear Author, Dear All, a little bit late, however, beyond the philosophy, for some guys that could be interested, please find my snippet:
If you modify the line
instrText.text = 'SEQ %s \* ARABIC' % nameby
instrText.text = 'TOC \o "1-%d" \h \z \u' % maxlevel # change 1-3 depending on heading levels you needYou can add a TOC.
Hopefully, it could help some guys !
Raphael—
it help me thank you alot!
I have changed the instrText.text to instrText.text = ‘PAGEREF Bookmark_1’
so I can get the page No of a bookmark saved, so now i can make my customized TOC easily.
(I was not able to customize a toc, because libreoffice didn’t save my settings.)