views:

45

answers:

1

I'm attempting to write a Ubiquity command that allows you to replace a selected link or URL pointing to an image with that image itself. However, the CmdUtils.setSelection() function (documented here) seems to do nothing if any html tags are present in the selection, making it useless for replacing any links. When selecting plain text, it functions exactly as intended, replacing the text with an <img src="text"/> tag. Is there something I'm missing, or will this function simply not allow me to replace html? If the latter is the case, is there a function or method that will allow me to do this? Any other advice is welcome as well!

 CmdUtils.CreateCommand({
  name: "fetch-image",
  author: {name: "Josh Timmer"},
  license: "GPL",
  description: "Replaces links or URLs pointing to images with the image itself",
  help: "Highlight text or a hyperlink and execute this command",
  takes: {"image URL": /.*/},

  _getImgUrl: function(itemIq) {
     if (itemIq.html.indexOf("<a ",0) < 0)
        return itemIq.text;
     var refPos = itemIq.html.indexOf("href=\"",0);
     if (refPos < 0)
        return "Error, no URL found!";
     var startPos = itemIq.html.indexOf("\"", refPos);
     var endPos = itemIq.html.indexOf("\"", startPos + 1);
     startPos += 1;
     var url = itemIq.html.substring(startPos, endPos);
     return url;
  },

  preview: function(pblock, input) {
     pblock.innerHTML = "Image URL: " + this._getImgUrl(input) + "<br/><br/><img src='" + this._getImgUrl(input) + "'/>";
  },

  execute: function img_insert(input) {
     CmdUtils.setSelection("<img src='" + this._getImgUrl(input) + "'/>");
     displayMessage("Executed: " + this._getImgUrl(input));
  }
});
+1  A: 

It should work, as long as a valid HTML is passed.

CmdUtils.CreateCommand({
  name: "fetch image",
  authors: [{name: "Josh Timmer"}, "satyr"],
  license: "GPL",
  description: "Replaces links pointing to images with the image itself.",
  help: "Highlight text or a hyperlink and execute this command.",
  preview: function fetch_image_preview(pblock) {
    pblock.innerHTML = this._images() || this.previewDefault();
  },
  execute: function fetch_image_execute() {
    CmdUtils.selection = this._images();
  },
  _images: function fetch_image_urls(){
    var srcs = CmdUtils.getSelectedNodes("a");
    if (!srcs.length) srcs = CmdUtils.selection.match(/\bhttps?:\/+\S+/g);
    return [<img src={s}/>.toXMLString() for each (s in srcs)].join("");
  },
});
matyr