Thank you, Tadziu, it is an interesting trick and it does work in the test case posted earlier. Unfortunately, in a more realistic document, I did hit those "unexpected results", e.g. when the string was used inside a macro argument (thank you for the warning).
The final solution I picked was to customize troff source code, adding a new request and a new escape sequence: 1) .scripting command: start scripting subprocess 2) \K'expression': evaluate expression in scripting subprocess This is similar to .pso request (execute subprocess and insert output as text), but has the following advantages: 1) The subprocess is always alive and can be called efficiently thousands of times in the same document. 2) \K escape sequence can be used in macros or in strings. 3) The subprocess can maintain state, if more complex things are needed. An example: .do xflag 3 .scripting python trsrv.py \" use your favorite scripting language .ps 14p .vs 24p . .nr x 0 1 .ds s \R'x \K'0 if \\nx==3 else \\nx''\\n+x \*s \*s \*s \*s \*s \*s \*s \*s \*s Output: 1 2 3 1 2 3 1 2 3 This is not meant to replace the normal troff language, but only to address those rare problems which are impossible or overly complex to express in troff. (Of course, it could be misused, like everything else.) If anyone else is interested, I can share all my work, which is implemented in the Heirloom troff source tree. Any other suggestions are very much appreciated.
