How to close an atom pane with javascript?


#1

I know you can close a pane with TextEditor.destroy() but this loses unsaved changes in the pane. How can I mimic the tab close button with javascript? I want the “lose unsaved changes” popup to appear as normal.


#2

The following bit of Coffeescript code in my INIT file
closes all panes and asks when to save the file when needed:

# ****************************************************
#  CLOSE ALL OPEN TABS .. REGARDLESS IF IN SEVERAL PANES
# ****************************************************
closeAllTabs: () ->
  console.log 'Close all panes.'  # debug
  _panes = atom.workspace.getPanes()  # grab object representing all items in panes
  _pane.destroy() for _pane in _panes  # not all items can close; tree-view / dev-tools / ++ is kept open
  return true  # confirm to caller: no need to abort action

#3

Interesting. So it looks like pane.destroy() will prompt the user but TextEditor.destroy() will not.

In that case, does anyone know how to get a pane instance from a TextEditor instance?


#4

How about atom.workspace.getActivePane()?


#5

What if the pain ain’t active tho? My script knows the file path and the TextEditor instance but it may not be the active tab.


#6

So how originally would the TextEditor object be created in the first place?
Can the same concept not be used to create a Pane object?


#7

Ah! The Pane.activeItem was the key to solving this. I wrote a function which gets a Pane or a TextEditor instance when given a file path. I can use this now to fine the pane instance and destroy that rather than the text editor. Here’s the function for future googlers!

function  instanceFromFilePath( pathFromRoot, returnEditor ){
	for (pane of atom.workspace.getPanes()){
		var editor = pane.activeItem
		if(editor.constructor.name!="TextEditor") continue
		if(editor.getPath().replace(atom.project.getPaths()[0],'').split('\\').join('/')==pathFromRoot) return returnEditor ? editor : pane
	}
}
//sample use:
console.log(instanceFromFilePath('/myfile.txt'))   //returns the Pane containing myfile.txt
console.log(instanceFromFilePath('/myfile.txt',1))   //returns the TextEditor containing myfile.txt

Thanks for the help danPatric!