Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the name of the active file in Atom?

I want to get the name of the current file in a package for Atom 1.0. I know how to get the full path to the file, but I would like to only get the file name part of the path. This is the code I have so far (taken from atom-terminal):

editor = atom.workspace.getActivePaneItem()
file = editor?.buffer?.file
filepath = file?.path

I tried to read though the docs to see if such an attribute already exists, but the Pane items are not documented as far as I could find. Is there documentation available somewhere else than at https://atom.io/docs/api/v1.0.0?

If there isn't an attribute, is there an appropriate standard function for extracting the file part of the path from filepath in a platform independant way?

like image 910
jacwah Avatar asked Feb 09 '23 17:02

jacwah


2 Answers

The method provided by @jacwah is no longer working in atom 1.18. According to the API docs you can get path using the following code:

atom.workspace.getActiveTextEditor()?.getPath()
like image 199
pragma Avatar answered Feb 26 '23 16:02

pragma


Use file.getBaseName(). This will return only the filename part of the path to file. I found this by logging the file to the console and examining it's properties.

editor = atom.workspace.getActivePaneItem()
file = editor?.buffer?.file
filename = file?.getBaseName()

You can also use the node.js path module's basename function.

path = require('path')

editor = atom.workspace.getActivePaneItem()
file = editor?.buffer?.file
filename = path.basename(file?.path)
like image 31
jacwah Avatar answered Feb 26 '23 17:02

jacwah