Code formatting in Python session

Is there a way to format code in a Python session started from TeXmacs? For example, if I do Insert => Session => Python and write the code shown below, then the code is formatted nicely, until the last line return arr:

def sort_array(arr):
    n = len(arr)
    
    # Bubble Sort algorithm
    for i in range(n):
        for j in range(0, n-i-1):
            # Swap if the element found is greater than the next element
            if arr[j] > arr[j+1]:
                arr[j], arr[j+1] = arr[j+1], arr[j]
    
    return arr # this line is note formatted properly in TeXmacs, I have to manually format it

Is there a way to autoformat code in TeXmacs? Of course, one work around is write the code in an editor such as vscode and then paste it in TeXmacs, but I was wondering if any internal plugin is available to do that.

Hi @TDH and welcome to the forum.

I tried with the Octave plugin and it behaved in the same way: it indents the code, but it did not decrease the indent when it should have—I tried an if clause and it aligned the end with the code inside the if.

It looks like either a bug or incomplete coding of the autoformatter. Does @darcy know anything about this code? Should we submit a bug report? Or ask some other member of the TeXmacs team?

1 Like

The TeXmacs editor provides basic auto indention. It is customizable in Scheme.

Autoformatter plugin is a feature request.

1 Like

Thanks @darcy and @pireddag for your response! @darcy is there a way to turn off the current auto indention in scheme then? I have just started using TeXmacs and not an expert user, so any help regarding turning off the auto indention will be much appreciated.

Here is the code snippet for Python mode to customize the indentation:

You can override it in you my-init-texmacs.scm

A rough way would be IMO

    (tm-define (program-compute-indentation doc row col)
      (:mode in-prog-python?)
    0)

One command that would help modifying quickly auto-indenting is (remove-tabstop). I found it looking at the code. It is mapped to "cmd S-tab" (see prog/prog-kbd.scm) but you can remap it with kbd-map (e.g. to "S-tab" with

(kbd-map ("S-tab" (remove-tabstop)))

).

Please write if you need more detailed instructions.

1 Like

Confirmed, it works well.

1 Like

Great, thanks very much!