Sublime文本:如何获取当前视图的文件名

11

我正在尝试编写一个小插件来删除当前文件并关闭活动视图。但不知何故,self.view.file_name() 总是返回 None。

我对 Python 很陌生,不知道为什么它不能像这样工作。根据 API 参考文档,file_name() 函数返回当前视图的文件名。

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


控制台中有任何错误消息吗? - Everton Yoshitani
1
不行。检查 (f is None) 总是为真,因此在到达 send2trash() 之前就返回了。如果没有检查,send2trash() 调用将失败。 当我在控制台中执行 view.file_name() 时,它会返回正确的路径。 - Felix
将输出添加到问题中。 - Felix
你是否在使用实际存在于磁盘上的缓冲区中的命令? - Alex V
1
我刚刚测试了一下,它可以正常工作!你是怎么调用这个命令的? - Talvalin
显示剩余6条评论
1个回答

8
根据非官方文档的插件页面,Sublime Text 按以下方式规范化命令名称:
  1. 去掉 "Command" 后缀
  2. 用下划线分隔驼峰短语
因此,DeleteCurrentFileCommand 应该按以下方式调用: view.run_command("delete_current_file") 使用此命令后,我可以在Python控制台中按照上面列出的方式运行您的插件。
然而,如果我尝试运行view.run_command("DeleteCurrentFile"),则控制台将显示空白行。这可能导致self.view.file_name() 返回None的想法。

1
哦,我现在感觉很蠢。我尝试像这样在窗口对象上运行命令 window.run_command('delete_current_file'),显然是错误的。当我调用 view.run_command() 时它可以工作。谢谢! - Felix

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接