Extracting all Python code blocks in a .tm file and save them in a seperate .py file

Is there a way to extract all the codes in .tm and save them as a separate text file? For example consider the following test.tm document.


Now I want to extract all the codes in this test.tm file in another text file (say test.py) which will contain all the code in the test.tm file, i.e., the .py file will contain:

def hello_world():
    print("Hello World)
hello_world()
def print_numbers():
    for i in range(1, 11):
        print(i)

What would be the best way to achieve that in TeXmacs? Of course, the manual way would be creating a .py file and copying and pasting all code blocks from TeXmacs file, but for a .tm file with many code blocks this will be very tedious.

Let me describe the way I see one can operate on TeXmacs documents.

In TeXmacs there are Scheme functions to extract information from the document; I think the one you need is tree-search. Learning Scheme itself can be either fun or not :slight_smile:; Scheme programs are the most straightforward way to operate on TeXmacs documents. It is documented in part in the TEXMACS Scheme developer guide and also on the book on TeXmacs (the Jolly Writer).

Operating on TeXmacs documents is possible with any other language, but one would need to write the code that searches the document tree.

I think we can write a Scheme program that does what you want; at the same time, if you want to operate on the document, it would be good for you to become familiar either with Scheme or with the TeXmacs document format.

1 Like

Okay thank you very much for the references, I will read them carefully and try to figure out how to extract the codes using Scheme. I will look into the tree-search option that you referred to.

There is already session exporter for scheme, for Python, changing the parameter from Python to Scheme should work fine (haven’t tried, I guess). Here is the related code snippet:

1 Like

Thanks very much for the info. Your suggestion works great!

You can also try the Literate package. But I’m not sure if you can execute the code blocks with it.

You can definitely save the code blocks into a file of your choosing.

1 Like

See this and this. Replace the parameter mma in the later script by the one for python, which you should be able to see when you look into the source format of a tm file.

2 Likes