Ned Martin
Ned Martin

Reputation: 532

Use Windows environment variables in Sublime Text settings files

I have a need to reference Windows environment variables from within Sublime Text 2 settings files (Package-Name.sublime-settings files), specifically %APPDATA% and %TMP%

Is this possible, and if so, how?

For example, here is a line from one package setting, which needs to work on multiple users, so with different usernames:

"backup_dir": "C:\\Users\\Username\\AppData\\Local\\Temp\\SublimeBackup"

As an example, here is a problem I just had: I have an install of Sublime Text 2 which runs from multiple computers (i.e. I copy its data around to keep settings etc. up to date between multiple installs), but I have the below command:

{ "caption": "Backup to Server (Local to Server)", "command": "exec", "args": { "cmd": ["local-to-server.cmd"] } },

Unfortunately, the file "local-to-server.cmd" is relative to the currently opened file in Sublime Edit, so this command rarely works. What I need is:

{ "caption": "Backup to Server (Local to Server)", "command": "exec", "args": { "cmd": ["%APPDATA%\Sublime Text 2\Packages\User\local-to-server.cmd"] } },

Or some similar way of referencing a common location that I can then build a relative path from.

Upvotes: 8

Views: 3325

Answers (2)

skuroda
skuroda

Reputation: 19744

Thanks to @schlamar for the correction on settings. I didn't realize they persisted across the session. All my plugins use them locally, and I don't do any modification to them but that's good to know. Here's a plugin to expand the variables when ST loads. Should work in both ST2 and ST3.

import os
import sublime

VERSION = int(sublime.version())

def expand_settings():
    expand_settings = {
        "<setting file names>": [
            "<setting keys to expand>"
        ]
    }
    for filename, setting_keys in expand_settings.items():
        s = sublime.load_settings(filename)
        for key in setting_keys:
            value = s.get(key)
            s.set(key, os.path.expandvars(value))

def plugin_loaded():
    expand_settings()

if VERSION < 3006:
    expand_settings()

Upvotes: 3

schlamar
schlamar

Reputation: 9511

@skuroda is wrong in his comment. Setting changes are persistent across plugins and multiple load_settings calls. Simple test case:

s = sublime.load_settings('Preferences.sublime-settings')
s.set('test', 'x')
s = sublime.load_settings('Preferences.sublime-settings')
print (s.get('test'))  # prints x

If you split this across two plugins it will still print x (assuming the setting plugin runs before the printing plugin).

So you can load and re-write some paths with os.path.expandvars which will be persistent for the current session.

Upvotes: 1

Related Questions