Sublime Forum

How can I get contents of unsaved file from API

#1

I have a new unsaved file that has text in it. How can I get the text or the file path from the API? The following does not seem to work:

self.view.substr(sublime.Region(0, self.view.size()))

and the following returns None:

self.view.file_name()

0 Likes

#2

view.file_name() is None until the the file has a name on disk; so for a new file that means that the file has saved the file at least once to give it a name. If you’re dealing with an event listener, the event triggers after the user picks the name.

view.substr() is indeed how you would get the text out of any view, regardless of whether it has a name on disk or represents a file at all. Do you have a code snippet that you can share?

0 Likes

#3

Thanks. Here is my code:

import sublime
import sublime_plugin

class FilenamerCommand(sublime_plugin.TextCommand):
	def run(self, edit):

		allcontent = self.view.substr(sublime.Region(0, self.view.size()))
		print(allcontent)

It just returns a couple empty lines in console.

0 Likes

#4

You want to test that with view.run_command("filenamer"); window.run_command() will execute TextCommand commands, but when it does so it chooses the view in the window that currently has the input focus, When you have the console open, the focused view is the input widget in the console itself.

1 Like

#5

Ahhhh! I knew it had to be something simple. Thank you for taking the time to reply and for your awesome youtube videos.

1 Like