#language = "V8"
#async = "on"
// This macro retrieves Bing search results using a word at the cursor or the selection. 
// It demonstrates the use of the WebBar object, the onLoad event, and the "web" keyword to 
// access the Document Object Model (DOM) using the EmEditor's Web Browser. It requires
// EmEditor v23.0 or later.
//
// Disclaimer: The format of Bing search results may change at any time in the future, which
// could affect the functionality of this macro. The macro is intended solely to demonstrate 
// the new features of EmEditor v23.0

// onLoad() is called when a web page is finished loading. It is called only once per macro run.
function onLoad() {
	editor.NewFile();
	Redraw = false;
	
	// use "web" to access the Document Object Model (DOM)
	document.write(web.document.documentElement.outerHTML);
	document.selection.StartOfDocument();
	var re = editor.regex;
	re.Pattern = ".*?href=\\\"(.*?)\\\".*?>(.*?)</a>";
	re.IgnoreCase = true;
	re.OnlyWord = false;
	var sResult = "";
	var i = 1;
	for (; ;) {
		bFound = document.selection.Find("<h2><a .*?</h2>", eeFindNext | eeFindReplaceCase | eeFindReplaceRegExp, 0);
		if (!bFound) {
			break;
		}

		sText = document.selection.Text;

		matches = re.Find(sText);
		if (matches && matches.Count >= 2) {
			sResult += i++;   // search ranking
			sResult += ". ";
			sResult += matches.Item(2).Value;  // title
			sResult += "\r\n";
			sResult += matches.Item(1).Value;  // URL
			sResult += "\r\n";
			sResult += "\r\n";   // empty line
		}
	}

	document.selection.SelectAll();
	document.selection.Delete();
	document.write(sResult);
	Redraw = true;
}

if( !WebBar.Visible ) {
	WebBar.Open( "" );
	alert( "Please run this macro again" );
	Quit();
}

if( document.selection.IsEmpty ) {
	document.selection.SelectWord();
}
if (!document.selection.IsEmpty) {
	sURL = "https://www.bing.com/search?q=" + encodeURIComponent(document.selection.Text);
	
	// use "WebBar" to open the URL using the EmEditor's Web Browser
	WebBar.Open(sURL);
}
