How to create new file/textEditor/buffer in package?


I am writing a package to support filter functionality which will input the filtered file in a new textEditor/buffer. I searched through the api document and it seems to be atom.workspace.buildTextEditor(). But I tried the below code but it doesn’t seem to work for me.

>       var newEditor = atom.workspace.buildTextEditor();
>       newEditor.insertText("Hello World!");

I can’t find any other method to create buffer/TextEditor in the API doc. Did I miss anything? Or is the text editor created via workspace.buildTextEditor somehow hidden after creation which I need to show in the later code.

Another a bit of off-topic question is, it seems there are some properties missing in the API document. For example, I am using Atom.workspace.getActivePaneItem().buffer.file to get the current file. However, it doesn’t seem to get well documented about this. And getActivePaneItem’s return type is pretty vague in the document. Am I missing something here?


In atom, a text editor actually has two (actually three, but really four and a few more) “parts”:

  1. A TextEditor instance deals with the editor’s logic (typing, managing selections, etc.).

  2. A TextEditorElement is what you see on your screen.

  3. A TextBuffer contains the contents of a file.

  4. A File represents the file on your disk.

atom.workspace.buildTextEditor returns a TextEditor object and editor.getBuffer() returns the TextBuffer of an editor. It does not provide a File (because your editor has no file path to load/save) or TextEditorElement.
To get the TextEditorElement of a TextEditor, use atom.views.getView(editor). This will still not display anything on your screen because now it’s your job to insert the element into the DOM.

There is a much easier way: Calling without a URI returns a promise that resolves to an untitled text editor (on your screen). (editor) ->
  editor.insertText('Hello, World!')

That is because the active pane may not be a text editor. You should probably use atom.workspace.getActiveTextEditor:

ed = atom.workspace.getActiveTextEditor()
if ed isnt null # getActiveTextEditor returns null if the active pane isn't a text editor (it could be the settings-view or a markdown-preview)
  # ...


Found another helpful related answer