Sublime Forum

How to access tmPreferences from python plugin

#1

hello, I have several snippets where I make use of the variables defined in tmPreferences.

Due to some limitations I made a simple python plugin instead of a snippet to achieve what I want. Now, is there a way to access these variables with the plugin?

I want to output $TM_PROJECT_NAME

0 Likes

#2

P.S.: it would be even better if I could retrieve this information from my project file such as

{
   "name" : "Project X"
}

but I am not aware of this possibility.

0 Likes

#3

ok, this works well:

print (window.project_data()[‘name’])

but if I use this in my plugin i get the following:

NameError: global name ‘window’ is not defined

0 Likes

#4

the APIs you are looking for are window.project_data() and view.meta_info

if you need a window reference, you can use sublime.active_window() or if you have a view, view.window()

0 Likes

#5

The following did not work:

import datetime, getpass
import sublime, sublime_plugin

class AddHeader(sublime_plugin.TextCommand):
    def run(self, edit):
        f = self.view.file_name()
        filename = f.split('\\')[-1].split('.')[0]
        self.view.run_command("insert_snippet", { "contents": """
some text {1} ... {2} ...

""" .format(
  # sublime.window.project_data()['name']
  window.project_file_name()

) } )

NameError: global name ‘window’ is not defined. Can someone help? I am new to this.

0 Likes

#6

A TextCommand has a property named view that represents the file that the command is executing inside, and in turn the view has a method called window() that tells you what Sublime window the view is currently contained in.

As such, the line you want is self.view.window().project_file_name() to get at the information that you desire.

Note however that if you do this in a window that doesn’t have an associated project, it’s going to return None, which is probably not what you want.

I would recommend adding something like:

    def is_enabled(self):
        return self.view.window().project_file_name() is not None

That will make your command disable itself if you try to run it in a window without a project file associated. When a command is disabled it will appear grayed out in the menu, it won’t appear in the command palette (if you have added it there) and any key bindings for it also will not trigger.

2 Likes