Set file name programmatically?


#1

I have a package that works forspecific file-names (installer.cfg), rather than extensions (although it can be tricked by certain names, e.g. something.installer.cfg – but that’s a different story!). Now, Atom has the rather annoying behaviour that it saves new files as “Untitled”, without even appending an extension. So I was thinking that I could set the file-name programmatically like this:

atom.workspace.observeTextEditors (editor) =>
  @subscriptions.add editor.onDidChangeGrammar =>
    scope = editor.getGrammar().scopeName
    fileName = editor.getFileName()
        
    if scope is "source.cfg.pynsist" and fileName is null
      # setFileName('installer.cfg')

Unfortunately, there is no method to setFileName() and even getFileName() is undocumented – so my hopes aren’t high.

Does anybody have an idea whether it’s possible and how?


#2

The getFileName() does work - it gives a null as you have it.
I suggest you replace
editor.setFileName('installer.cfg') ------> editor.saveAs('installer.cfg')

There is a problem however. I recommend you find a way to specify the path too. As it is the ‘installer.cfg’ will not svae where you want it. You can check with editor.getPath() (for your above segment).

LATE NOTE: In my case the file would be stored in the Windows path:
C:\Users\Dan\AppData\Local\atom\app-1.18.0

Late note:
Maybe you are looking for editor.setFileName = 'installer.cfg'.
It however does not seem as though the grammar of the file is influenced in any way.

Helpful?


#3

I know that it works, that’s why I’m using it in my code :smirk:

If a package would save a file automatically once I change the syntax scope, I’d be annoyed. So that’s not really an option. What I’d do instead is set a default name, if it was possible.


#4

Well YES that is clear. I am glad your question showed me this trick.

If I tried to save a default “Untitled” file, the save popup is blank at the file name. Pressing the save button does not do anything.

Not to annoy you … just for my own understanding … please explain again what the root issue is that you are trying to overcome?

Would the discussion this discussion help?..


#5

My package serves a very small niche. It provides syntax highlighting and snippets for Pynsist Configuration files. These files are always titled install.cfg, so when I user creates a new file, I want to make sure that’s the name the file will have – even before specifying the exact path. Simply to rule out mistakes. It’s no big deal if it’s not possible, but a nice-to-have feature.

Maybe an improved grammar definition could solve all this, one that differentiates file-extensions and specific file-names (could be useful for Gruntfile.js, .eslintrc, package.json etc.)


#6

You might be able to dig into the source of the New File modal and make an imitator of that modal, but activated by your package and with your own content.