Sublime Forum

Python syntax specific symbol for GoTo

#1

Hello all,

I would like to add: if __name__ == '__main__': as a symbol in the Python syntax so I can quickly snap to the location, as is possible with functions and classes.

I followed the directions from: How to add a global custom symbol marker?

in summary:

  1. edit Symbol List.tmPreferences: (edit in ** ** brackets)
<?xml version="1.0" encoding="UTF-8"?>
<plist version="1.0">
<dict>
	<key>scope</key>
	<string>
		source.python entity.name.class,
		source.python entity.name.function,
		**source.python entity.name.if-name**
	</string>
	<key>settings</key>
	<dict>
		<key>showInIndexedSymbolList</key>
		<integer>1</integer>
		<key>showInSymbolList</key>
		<integer>1</integer>
	</dict>
</dict>
</plist>
  1. edit Python.sublime-syntax, adding a new entry under contexts, at the end of the document:

if-name:
- match: "if __name__ == '__main__':"
push:
- match: “(?={{identifier}})”
push:
- meta_content_scope: entity.name.if-name.python
- match: ‘’
pop: true

Not sure this is right, just copying and replacing what is there for functions and classes. File saved without errors and does not show up in the GoTo symbol list?

1 Like

#2

The statement should be scoped meta.ifmain with all other highlightings untouched.

You could either create an inherit syntax with required modfication:

%YAML 1.2
---
name: Python (If-Main)
scope: source.python


extends: Packages/Python/Python.sublime-syntax

contexts:
  statements:
    - include: ifmain
    - include: more-statements

  ifmain:
    - match: (?=if\s+__name__\s*==\s*["']__main__["'])
      push:
        - meta_scope: meta.ifmain.python
        - include: more-statements
        - match: ''
          pop: 1

  more-statements:
    - include: Packages/Python/Python.sublime-syntax#statements

…or copy original python and add relevant rules…

  statements:
    - include: ifmain
    - include: more-statements

  ifmain:
    - match: (?=if\s+__name__\s*==\s*["']__main__["'])
      push:
        - meta_scope: meta.ifmain.python
        - include: more-statements
        - match: ''
          pop: 1

  more-statements:

Add meta.ifmain to Symbol List …

<?xml version="1.0" encoding="UTF-8"?>
<plist version="1.0">
<dict>
	<key>scope</key>
	<string>
		source.python meta.ifmain,
		source.python entity.name.class,
		source.python entity.name.function
	</string>
	<key>settings</key>
	<dict>
		<key>showInIndexedSymbolList</key>
		<integer>1</integer>
		<key>showInSymbolList</key>
		<integer>1</integer>
	</dict>
</dict>
</plist>

3 Likes

#3

is more statements representative of the rest of the document or actually a fundamental part of this addition? That line of is causing me an error on saving Python.sublime-syntax.

0 Likes

#4

more-statemetns: takes everything original statements: context contained.

It’s just a way to prepend the ifmain context to original statements.

Those lines are just inserted into Python.

1 Like