Programmatically open markdown-preview in when opening a markdown file


#1

##What I want to do

When I open a markdown file, I want Atom to automatically toggle the markdown-preview mode.

##What I did so far

Content of my init.coffee file:

atom.workspace.onDidAddPaneItem (event) ->
    if event.item.getGrammar().name is 'GitHub Markdown'
        atom.commands.dispatch(atom.views.getView(atom.workspace), 'markdown-preview:toggle')

##What could help to solve the problem

If the markdown file tab is open and I run the atom.commands.dispatch(atom.views.getView(atom.workspace), ‘markdown-preview:toggle’) command, it will work.

I think there are 2 possible approaches to do this, I juste need to figure out how to do this:

Switch current tab to the one displaying the markdown file and run the toggle command
OR

Get the markdown tab and apply the toggle command

I’m fairly new to the Atom API. Your help will be appreciated! Thanks.


#2

From the code:

It looks like it expects the active text editor to be the Markdown file. Perhaps onDidAddPaneItem gets called a little early too? You might want to use onDidOpen?


#4

It’s not working with onDidOpen…

atom.workspace.onDidOpen (editor) ->
    if editor.item.getGrammar().name is 'GitHub Markdown'
        atom.commands.dispatch(atom.views.getView(atom.workspace), 'markdown-preview:toggle')

#5

Right now, rather than checking the grammar … just call markdown-preview:toggle on anything that gets opened. The toggle command will do the Markdown checking for you. It’s just one more line of code that could fail and doesn’t prove anything right now.


#6

Thanks for your input, I used the if statement to deal with other things (unnecessary for this problem because they work. I juste removed them for the sake of simplicity ).

Is there an API schema I could find to help me figure out what is the event loop, which eventListener is called when we open a file?


#7

Other than the API documentation, no, there’s just the source:

https://github.com/atom/atom/blob/master/src/workspace.coffee#L433-L481