Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sublime text: How to get the file name of the current view

I'm trying to write a tiny plugin to delete the current file and close the active view. For some reason self.view.file_name() always returns None.

I'm new to Python and I've no idea why it doesn't work like this. According to the API Reference file_name() returns the file name of the current view.

import sublime, sublime_plugin, send2trash

class DeleteCurrentFileCommand(sublime_plugin.TextCommand):
    def run(self, edit):        
        f = self.view.file_name()
        if (f is None):
            return

        send2trash.send2trash(f)
        self.view.window().run_command('close')

Output of dir(self.view):

['class', 'delattr', 'dict', 'doc', 'format', 'getattribute', 'hash', 'init', 'len', 'module', 'new', 'reduce', 'reduce_ex', 'repr', 'setattr', 'sizeof', 'str', 'subclasshook', 'weakref', 'add_regions', 'begin_edit', 'buffer_id', 'classify', 'command_history', 'em_width', 'encoding', 'end_edit', 'erase', 'erase_regions', 'erase_status', 'extract_completions', 'extract_scope', 'file_name', 'find', 'find_all', 'find_all_results', 'find_by_selector', 'fold', 'folded_regions', 'full_line', 'get_regions', 'get_status', 'get_symbols', 'has_non_empty_selection_region', 'id', 'indentation_level', 'indented_region', 'insert', 'is_dirty', 'is_folded', 'is_loading', 'is_read_only', 'is_scratch', 'layout_extent', 'layout_to_text', 'line', 'line_endings', 'line_height', 'lines', 'match_selector', 'meta_info', 'name', 'replace', 'retarget', 'rowcol', 'run_command', 'scope_name', 'score_selector', 'sel', 'set_encoding', 'set_line_endings', 'set_name', 'set_read_only', 'set_scratch', 'set_status', 'set_syntax_file', 'set_viewport_position', 'settings', 'show', 'show_at_center', 'size', 'split_by_newlines', 'substr', 'syntax_name', 'text_point', 'text_to_layout', 'unfold', 'viewport_extent', 'viewport_position', 'visible_region', 'window', 'word']

like image 954
Felix Avatar asked Nov 13 '12 13:11

Felix


1 Answers

According to the Plugins page of the unofficial documentation, Sublime Text normalises command names in the following way:

  1. Strip off the "Command" suffix
  2. Separate camel cased phrases with underscores

Thus, DeleteCurrentFileCommand should be called in the following way: view.run_command("delete_current_file")

With this command, I was able to run your plugin exactly as listed above in the Python console.

However, if I tried running view.run_command("DeleteCurrentFile"), then the console would display a blank line. This may have led to the idea that self.view.file_name() was returning None.

like image 192
Talvalin Avatar answered Nov 15 '22 12:11

Talvalin