Sublime Forum

How to get sublime.settings.get working in Sublime Text 3

#1

I am using sublime.settings.get() to get the setting value but it returns none. I read the API reference and it reminds to utilize plugin_loaded(). However, I am not sure how to use it. Below is my code:

[code]settings = sublime.load_settings(‘SynceFile.sublime-settings’)
source1 = ‘’
dest1 = ‘’

def plugin_loaded():
settings = sublime.load_settings(‘SynceFile.sublime-settings’)
source1 = settings.get(‘sf_source_1’)
dest1 = settings.get(‘sf_dest_1’)

class SyncFileCommand(sublime_plugin.TextCommand):
def run(self, edit):
self.view.insert(edit, 0, source1 + ‘\n’)[/code]

However, the source1 is still empty string the time I debug the value. Any suggestions?

1 Like

#2

You need to use global settings before the local assignment in plugin_loaded, otherwise Python will write to a local “settings” identifier instead of the global one. (Same applies to other variables, which I wouldn’t define anyway and instead just call settngs.get("name", default) whenever you need it.

Also, you could change the initial (global) assignment to settings = None to make it easier to debug and reduce redundant code.

1 Like

#3

Thank you for your reply. I am not sure whether I understand it correctly. I changed my code into:

[code]settings = None
source1 = None
dest1 = None

def plugin_loaded():
settings = sublime.load_settings(‘SyncFile.sublime-settings’)
source1 = settings.get(‘sf_source_1’)
dest1 = settings.get(‘sf_dest_1’)[/code]

But it doesn’t work as well. Can you provide a sample code how it should look like?

0 Likes

#4

You’re still missing the global in the local scope of plugin_loaded more info about this here inkling.com/read/learning-p … -statement

settings = None

def plugin_loaded():
    global settings
    settings = sublime.load_settings('SyncFile.sublime-settings')
0 Likes

#5

Thank you for the reply. I tried the following and made it global:

[code]settings = None
source1 = None
dest1 = None

def plugin_loaded():
global settings, source1, dest1
settings = sublime.load_settings(‘SyncFile.sublime-settings’)
source1 = settings.get(‘sf_source_1’, ‘’)
dest1 = settings.get(‘sf_dest_1’, ‘’)[/code]

But it turns out that source1 is still ‘’ after executing this. And I am pretty sure it does have some value in the settings file. Is there any method I can make settings.get() working?

0 Likes

#6

Please share your full code and the contents of SyncFile.sublime-settings (and where you saved it).

0 Likes

#7

I put everything into the run method and it is working fine now. I guess it is not the best practice to do that though… The code at github is: github.com/Lanceshi2/SyncFile

0 Likes

#8

What you’re doing is a perfect job for arrays (or “lists” in Python). They are of arbitrary lenght and allow automating a lot of things you are currently doing manually. Here’s your plugin with arrays:

import shutil

import sublime
import sublime_plugin


class SyncFileCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        settings = sublime.load_settings('SyncFile.sublime-settings')
        src_mappings = settings.get("mappings", ])
        mappings = ]

        # Check if we have the correct value type
        if not isinstance(src_mappings, list):
            print("invalid value type, should be a list: %r" % src_mappings)
            return
        for mapping in src_mappings:
            # Check if we have the correct value types for the mappings
            if not isinstance(mapping, dict):
                print("invalid mapping type, should be a dict: %r" % mapping)
                continue
            # Check if required keys exist
            elif not all(name in mapping for name in ('source', 'dest')):
                print("required key(s) missing: %r" % mapping)
                continue
            # Check if required keys have correct value type
            elif not isinstance(mapping'source'], str) or not isinstance(mapping'dest'], str):
                print("invalid type for required key(s), should be str: %r" % mapping)
                continue
            # Check if required keys are not empty
            elif not mapping'source'] or not mapping'dest']:
                print("required key(s) empty: %r" % mapping)
                continue
            else:
                mappings.append(mapping)

        # Check if there are valid mappings
        if not mappings:
            print("No valid mappings found")
            return

        source_name = self.view.file_name()

        for mapping in mappings:
            if source_name in mapping'source']:
                shutil.copyfile(source_name, source_name.replace(mapping'source'], mapping'dest']))
                return
        else:
            msg = 'Your current file location is not in one of your source locations '
            msg += 'or the relevant dest location is empty. '
            msg += 'Please set the settings file properly and retry.'
            sublime.error_message(msg)

And here is the corresponding settings file:

{
    "mappings": 
        {
            "source": "some/path",
            "dest": "the/real/path",
        },
        {
            "source": "same/shit/here",
            "dest": "but/different/dest",
        }
    ]
}

Edit: And yes, you want to re-load these settings before you use them anyway and since you’re only using the settings’ values once, caching them into a global doesn’t make sense.

0 Likes

#9

Perfect. Thank you FichteFoll. I was thinking of using array/list initially which is extendable - I am just not sure about how to setup the settings document accordingly. Thank you for pointing this out for me.

0 Likes