What Is The Best Way To Get The Current Active EditorView?


#1

Getting the current Editor is easy (atom.workspace.getActiveEditor()), but there doesn’t seem to be an obvious way to get an Editor’s EditorView, or get the current EditorView. The best I can find is atom.workspaceView.getActiveView() (https://atom.io/docs/api/v0.81.0/api/classes/WorkspaceView.html#getActiveView-instance) - is this the right place to be looking?


#2

This does appear to work and I’ve used it successfully in go-plus.


#3

Have you ensured that it works when say the TreeView is focused?


#4

Yup, it still works when I have the TreeView focused. It even works if I have a directory selected but a file open. The only scenario where it doesn’t work is when you have a folder selected and no files open, so I will add a check for that (I assume in this scenario, EditorView.getEditor()? / EditorView.getEditor()?.getBuffer()? will be undefined.


#5

Actually, it’s just EditorView that is undefined. Easy fix.


#6

It also won’t work if the active pane item is not an editor. For example, if Markdown Preview or Settings View is active.


#7

In this scenario, would atom.workspaceView.getActiveView() be undefined?


#8

It would be an instance of the SettingsView or MarkdownPreviewView class.


#9

OK. Here’s the code I’m using to guard:

editorView = atom.workspaceView.getActiveView()
return unless editorView?
#
# Other code in the middle here
#
editor = editorView?.getEditor()
return unless editor?
buffer = editor.getBuffer()
unless buffer?
  @emit 'syntaxcheck-complete', editorView, saving
  return

#10

Distilled:

isValidEditorView: (editorView) ->
  return false if editorView?.getEditor()?.getGrammar()?.scopeName isnt 'source.go'
  return true

#11

Maybe this would be a little simpler:

isValidEditorView: (editorView) ->
  editorView?.getEditor()?.getGrammar()?.scopeName is 'source.go'

#12

:thumbsup: https://github.com/joefitzgerald/go-plus/blob/master/lib/dispatch.coffee#L147-L148

Thanks for the help.