Sublime Forum

How to retrieve the current file's absolute path and the cursor's line and character position information?

#1

Is it possible to obtain the absolute path of the currently opened file, the line number where the input cursor is located, and the character position within that line, in the format "filePath:line[:character]" ?

0 Likes

#2

It is, though you need a plugin to be able to collect it. For example the one below, which implements a command named example, will print this information to the console.

Depending on what you want the information for, the command could then invoke some other command with it, copy it to the clipboard, etc. You could also add it to the context menu of the file or its tab to be able to quickly collect it.

import sublime
import sublime_plugin


class ExampleCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        # The full filename is available from the view via the API, but this
        # will only return a value for tabs that represent a file that exists
        # on disk. i.e. for a newly created tab that has never been saved, this
        # would be None.
        filename = self.view.file_name()

        # All carets (cursors) in a file are a Selection, each of which having
        # an "a" and "b" value, where "a" is the starting point and "b" is the
        # ending point. When the two are the same, the selection is just a
        # cursor with no selected text. Either way, the "b" position is the
        # location of the cursor.
        #
        # There can be many cursors, here we deal with just the first one,
        # which is always the one closest to the top of the file.
        cursor_pos = self.view.sel()[0].b

        # Character positions in Sublime are the number of characters from the
        # start of the file they represent, 0 being the first character, 1
        # being the character after, and so on. Using the API, convert this
        # into a row and column offset, which takes the line breaks into
        # account.
        #
        # The generated row and column are 0 based.
        row, col = self.view.rowcol(cursor_pos)

        # Using this data, we can now construct the desired output.
        print(f"{filename}:{row+1}:{col+1}")

    def is_enabled(self):
        # The command should only be enabled if it has a filename, since
        # otherwise there is no file to print. Similarly this could also make
        # the command only active when there is a single selection by also
        # checking: len(self.view.sel()) == 1
        return self.view.file_name() is not None
1 Like