insert element at cursor position in richtextfield

M

michael.totschnig

Hello,

finally I found a cumbersome way to determine the selection and the
cursor position in a rich text control. There probably is a much
simpler solution, but maybe this solution can help people which
stumbled on the same problem than me.

I want to insert a hyperlink at cursor position, and if there is any
selection the selection should become the content of the "a"-element.
The idea is to call ExecuteAction("Cut") from the task-pane, than
retrieve the selected text from the clipboard, then set the clipboard
to a helper string, paste this string into the current position with
ExecuteAction("Paste"). In the view then, I retrieve the current text
node with getcontextnodes, and determine the cursor position by looking
for the helper string, split the text node, remove the helper string
and insert the element.

The code looks like this.
Taskpane:

function insertlink(href,title)
{
try {
gobjXDocument.View.ExecuteAction("Cut");
linkText = window.clipboardData.getData("Text");
}
catch(ex)
{
linkText = title;
}
window.clipboardData.setData("Text","___HELPER_STRING___");
gobjXDocument.Extension.insertlink(href,linkText);
}

script.js:
function insertlink(href,title)
{
objNode = XDocument.View.GetContextNodes().item(0);
if (objNode.namespaceURI != "http://www.w3.org/1999/xhtml")
{
//TODO: only works if there is at least one paragraph in the rich
text box
XDocument.UI.Alert("Hyperlinks can only be inserted into richtext
controls");
return false;
}

XDocument.View.ExecuteAction("Paste");
//request ContextNodes again since it hase change through Paste action
objNode = XDocument.View.GetContextNodes().item(0);
objTextNode = objNode.firstChild;
curspos = objTextNode.text.indexOf("___HELPER_STRING___");
objNewNode = objTextNode.splitText(curspos);
//19 = length of "___HELPER_STRING___"
objNewNode.text = objNewNode.substringData(19,objNewNode.text.length);

var xmlDoc = new ActiveXObject("Msxml2.DOMDocument.5.0");
var aEle =
xmlDoc.createNode("element","a","http://www.w3.org/1999/xhtml");
hrefAtt = xmlDoc.createAttribute("href");
hrefAtt.value = href;
aEle.attributes.setNamedItem(hrefAtt);
aEle.text = title;

objNode.insertBefore(aEle,objNewNode);

return true;
}

Regards,

Michael
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top