python - Sublime Text : How to get the file name of the current view

标签 python plugins sublimetext2 filenames delete-file

我正在尝试编写一个小插件来删除当前文件并关闭事件 View 。 出于某种原因,self.view.file_name() 总是返回 None。

我是 Python 的新手,我不知道为什么它不能像这样工作。根据API Reference file_name() 返回当前 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')

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']

最佳答案

根据Plugins page of the unofficial documentation , Sublime Text 通过以下方式规范化命令名称:

  1. 去掉“Command”后缀
  2. 用下划线分隔驼峰式短语

因此,应按以下方式调用 DeleteCurrentFileCommand: view.run_command("delete_current_file")

使用此命令,我能够在 Python 控制台中完全按照上面列出的方式运行您的插件。

但是,如果我尝试运行 view.run_command("DeleteCurrentFile"),那么控制台将显示一个空行。这可能导致了 self.view.file_name() 返回 None 的想法。

关于python - Sublime Text : How to get the file name of the current view,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13361241/

相关文章:

macos - 如何使用 sublime text mac OSX 构建 kivy

python - 有效地计算没有尾随零的阶乘?

python - Docker CLI允许使用标签,但是Docker Python API引发APIError

Python - 比较运算符超过 2 个条件

linux - 跨平台安装约定和最佳实践

plugins - 使用嵌套扩展对象编写 gradle 插件

python - 在 Python 中从具有多个多元时间序列的数据帧创建数组数组

javascript - CakePHP Assets 压缩: Not generating compressed files in cache folders

sublimetext2 - Sublime Text 2 包被忽略

mysql - Sublime Text MySQL 构建系统变量替换问题