Home > Net >  How to have a table of content for python script inside vs code like in jupyter?
How to have a table of content for python script inside vs code like in jupyter?

Time:10-31

I like jupyter lab since it has a table of content when using markdown cells. so for a big script file, it is easy to navigate the code using table of content. Now if I convert an ipynb file into a normal py file, inside vs code, is it possible to have a table of content like in jupyter? any possible solution inside vs code?

Thank you so much for sharing your idea.

CodePudding user response:

with extension HTML Related Links v1.0.0 you can create a Table of Content in a View in the Explorer Bar (Next to OUTLINE)

Example Python file:

"""Awesome Python book Code"""

# toc Chapter 1
def foo1():
  pass

# toc Chapter 2
def bar2():
  pass
# toc -- Chapter 2.1
def bar2Input():
  pass
# toc -- Chapter 2.2
def bar2Draw():
  pass

# toc Chapter 3
def foobar3():
  pass

Use the following setting:

  "html-related-links.include": {
    "python": [
      {
        "find": "#\\s*toc\\s*(. )",
        "filePath": "${fileBasename}",
        "lineNr": "position.start.line 1",
        "charPos": "1",
        "label": "$1",
        "allowCurrentFile": true
      }
    ]
  },
  "html-related-links.alwaysShow": true

This gives the following view:

  • Chapter 1
  • Chapter 2
  • -- Chapter 2.1
  • -- Chapter 2.2
  • Chapter 3

If you click on one of the lines in the tree the cursor is moved to the line after the toc-comment. Adjust the lineNr expression if needed.

You can change the # toc comment lines and adjust the Regular Expression of the find property.

  • Related