'use babel';

const {CompositeDisposable} = require('atom');
const validUrl = require('valid-url');

class mdwrap {
  constructor() {
    this.subscriptions = new CompositeDisposable;

    this.subscriptions.add(
      atom.commands.add(
        'atom-workspace', {
          'atom-markdown-wrapper:paste': this.paste,
          'atom-markdown-wrapper:image': this.image,
          'atom-markdown-wrapper:bold': this.bold,
          'atom-markdown-wrapper:italic': this.italic
        }
      )
    )
  }

  destroy() {
    this.subscriptions.dispose();
  }

  paste(editor, selection, clipboard) {
    let insert;

    if (editor && selection && clipboard) {
      insert = '[$selection]($href)'
        .replace('$selection', selection)
        .replace('$href', clipboard);
    }

    if (!validUrl.isWebUri(clipboard) && !clipboard.match(/^\#/)) {
      throw new Error('Not a valid URL or #anchor');
    }

    editor.insertText(insert);

    return insert;
  }

  image(editor, selection, clipboard) {
    let insert;

    if (editor && clipboard) {
      insert = '![$selection]($href)'
        .replace('$selection', selection || '')
        .replace('$href', clipboard);
    }

    if (!validUrl.isWebUri(clipboard)) {
      throw new Error('Not a valid image URL');
    }

    editor.insertText(insert);

    return insert;
  }

  bold(editor, selection) {
    let insert;

    if (editor && selection) {
      insert = '**$selection**'
        .replace('$selection', selection);
    }
    editor.insertText(insert);

    return insert;
  }

  italic(editor, selection) {
    let insert;

    if (editor && selection) {
      insert = '_$selection_'
        .replace('$selection', selection);
    }
    editor.insertText(insert);

    return insert;
  }
}

module.exports = mdwrap;

@@ -230,25 +230,16 @@
 nds.add(
-%0A        
 'atom-wo
@@ -250,18 +250,16 @@
 ace', %7B%0A
-  
         
@@ -301,18 +301,16 @@
 .paste,%0A
-  
         
@@ -352,34 +352,32 @@
 .image,%0A        
-  
 'atom-markdown-w
@@ -401,18 +401,16 @@
 s.bold,%0A
-  
         
@@ -463,18 +463,9 @@
     
-  %7D%0A      
+%7D
 )%0A  
@@ -558,32 +558,116 @@
 n, clipboard) %7B%0A
+    // abort early%0A    if (!editor.insertText %7C%7C !clipboard) %7B%0A      return;%0A    %7D%0A%0A
     let insert;%0A
@@ -1055,24 +1055,108 @@
 lipboard) %7B%0A
+    // abort early%0A    if (!editor.insertText %7C%7C !clipboard) %7B%0A      return;%0A    %7D%0A%0A
     let inse
@@ -1494,32 +1494,102 @@
 r, selection) %7B%0A
+    // abort early%0A    if (!editor.insertText) %7B%0A      return;%0A    %7D%0A%0A
     let insert;%0A
@@ -1757,16 +1757,16 @@
 t;%0A  %7D%0A%0A
-
   italic
@@ -1783,24 +1783,94 @@
 election) %7B%0A
+    // abort early%0A    if (!editor.insertText) %7B%0A      return;%0A    %7D%0A%0A
     let inse

Fix editor.insertText is not a function bug