Require plugin from init.coffee?


#1

How do I call methods from plugins in my init.coffee? I tried the following:

mdview = require 'markdown-preview'

atom.workspace.observeActivePaneItem (editor) ->
  if editor.getGrammar().scopeName == 'source.gfm'
    console.log "markdown"
    mdview.toggle()

But I get an error complaining that atom cannot find module 'markdown-preview'.


#2

The init.coffee file gets run after Atom finishes loading, so all of the packages you have active are already available. With that require, Atom thinks it’s looking for a Node module.


#3

In general, you don’t. Atom doesn’t really have a system to call code directly from packages unless they’re exposed as commands or services. Commands you can call from the init.coffee, services are a system for packages to interoperate with other packages.

If you’re trying to automatically launch a Markdown preview when a Markdown file is opened, you could call the markdown-preview:toggle command.


#4

Thank you! I tried the following code:

atom.workspace.observeActivePaneItem (editor) ->
  if editor == undefined
    return

  if editor.getGrammar().scopeName == 'source.gfm'
    console.log "markdown"
    atom.commands.dispatch(editor, 'markdown-preview:toggle')

‘markdown’ gets printed to the console when I switch to a markdown document but the preview doesn’t open. Am calling the command wrong? Maybe I need to pass something else instead of editor?

Thanks!


#5

You have to dispatch commands from a view. (You’ll notice the documentation mentions a DOM node.) The editor object isn’t a view, so you have to get the view object associated with it.


#6

I see. (sorry for noob questions). So I tried this:

atom.workspace.observeActivePaneItem (editor) ->
  if editor == undefined
    return

  if editor.getGrammar().scopeName == 'source.gfm'
    console.log "markdown"
    view = atom.views.getView(editor)
    atom.commands.dispatch(view, 'markdown-preview:toggle')

And now I’m getting an error in the console Uncaught (in promise) Error: Pane has been destroyed.


#7

Interesting. You may have to look at how the markdown-preview:toggle command expects to be called. It may be that you’re calling it in a context that it doesn’t expect and isn’t written for.