// ==UserScript== // @name Top words highlighter // @namespace // @description Enhanced keywords highlight for Search Engines and All ! // @include http://* // @include https://* // @exclude http://maps.google.com/* // @version 1.5.5a Top // ==/UserScript== // great credit for original script wright os0x [http://userscripts.org/scripts/show/43419] // hzhbest modded -style -change add keyword behavior -add support for other common search pages // -add lock function -add indicator bar -add shortcutkey -add input new -add selected // -off and close -keyword sorting -position save -etc.. // 1.5.5 - instant add keyword; addKeyword status; fix add bug; instant_search api; AMO; close "clear" keyword; keyword prep; improve words_off; z-index; fix window name; // 1.5.5a - non-gm compatibility; kw from url fix; comand_close api; // 1.5.5a Top - initialize the dialog with the top words on the page //console.time("highlight"); var l = function(){var len = arguments.length; var tx=''; for(i=0;i From top option to botom one, the compatibility of the script // will be strengthened while the performance of highlight will be lower. var ap_option = 0; // turn off short keywords (one or two letters or number) by default? // 0-no, 1-one letter, 2-one or two letters var off_short_words = 1; // Stop auto-highlight on supported pages? // 0-no, 1-yes, 2-only those from search results, 3-only search results var no_auto_hili = 0; // sort keywords? 0-no, 1-yes // Setting this to "yes" will produce better highlight result, // while "no" will perform faster and support ReExp input better. var sort_keywords = 1; // save panel position? 0-no, 1-yes var save_panel_pos = 0; // show indicator bar when navigating? 0-no, 1-yes var show_indc_bar = 0; // #### Config II #### --------------------------}} // var Ewh_configs = [ap_option, off_short_words, no_auto_hili, sort_keywords, save_panel_pos, show_indc_bar]; } else { var Ewh_configs = GM_getValue(CO_PRE, '0|1|0|1|0|0').split('|'); } for (i in Ewh_configs) {Ewh_configs[i] = Number(Ewh_configs[i]);} // Locked keywords if (gm_ok) var keyword_store = GM_getValue(ST_PRE); // Saved position var panel_pos_arr = ['right:-1px;','bottom:-1px;']; if (Ewh_configs[4] && gm_ok) panel_pos_arr = GM_getValue(PO_PRE, panel_pos_arr.join('|')).split('|'); // Configs menu if (gm_ok) GM_registerMenuCommand(_di.confT[_L], config_box); if (gm_ok) { unsafeWindow.EWH_iSearch = function() {instant_search(false, null);}; unsafeWindow.EWH_cClose = function() {command_close();}; } // main process init_keyboard(); if (load_keyword() !== false || init_keyword() !== false || inher_keyword() !== false) { //window.addEventListener('load', go, false); setTimeout(go, delay); } function go(){ words=[]; GM_setValue(ST_PRE, ''); setup(); // CHECK FOR UPDATE // if (gm_ok) {var SUC_script_num = 64877; try{function updateCheck(forced){if ((forced) || (parseInt(GM_getValue('SUC_last_update', '0')) + 86400000 <= (new Date().getTime()))){try{GM_xmlhttpRequest({method: 'GET',url: 'http://userscripts.org/scripts/source/'+SUC_script_num+'.meta.js?'+new Date().getTime(),headers: {'Cache-Control': 'no-cache'},onload: function(resp){var local_version, remote_version, rt, script_name;rt=resp.responseText;GM_setValue('SUC_last_update', new Date().getTime()+'');remote_version=parseInt(/@uso:version\s*(.*?)\s*$/m.exec(rt)[1]);local_version=parseInt(GM_getValue('SUC_current_version', '-1'));if(local_version!=-1){script_name = (/@name\s*(.*?)\s*$/m.exec(rt))[1];GM_setValue('SUC_target_script_name', script_name);if (remote_version > local_version){if(confirm(_di.update[_L][0]+script_name+_di.update[_L][1])){GM_openInTab('http://userscripts.org/scripts/show/'+SUC_script_num);GM_setValue('SUC_current_version', remote_version);}}else if (forced)alert(_di.update[_L][2]+script_name+_di.update[_L][3]);}else GM_setValue('SUC_current_version', remote_version+'');}});}catch (err){if (forced)alert(_di.update[_L][4]+err);}}}GM_registerMenuCommand(GM_getValue('SUC_target_script_name', 'BPT') + _di.update[_L][5], function(){updateCheck(true);});updateCheck(false);}catch(err){} } } // Functions function highlight(doc, ext_word) { var _words = words.filter(function(w,i){return !words_off[i];}); if (_words.length <= 0) return; var _index; if (ext_word && ext_word.words) { _words = ext_word.words; _index = ext_word.index; } var exd_words, xw; if (_words.length === 1 && _words[0].exp) { exd_words = _words.map(function(e){return e.exp;}); xw = ''; } else { exd_words = _words.map(function(w){return w.test ? w : new RegExp('(' + w.replace(/\W/g,'\\$&') + ')(?!##)', 'ig');}); xw = ' and (' + _words.map(function(w){return ' contains(translate(self::text(),"abcdefghijklmnopqrstuvwxyz","ABCDEFGHIJKLMNOPQRSTUVWXYZ"),'+escapeXPathExpr(w.toUpperCase())+') ';}).join(' or ') + ') '; } $X('descendant::text()[string-length(normalize-space(self::text())) > 0 ' + xw +' and not(ancestor::textarea or ancestor::script or ancestor::style or ancestor::aside)]', doc).forEach(function(text_node) { var df, text = text_node.nodeValue, id_index = 0, parent = text_node.parentNode, range = document.createRange(), replace_strings = [], new_text = reduce(exd_words, function(text,ew,i) { var _i = _index || i; return text.replace(ew,function($0,$1) { replace_strings[id_index] = '' + $1 + ''; return '##'+(id_index++)+'##'; }); }, text). replace(/&/g, '&').replace(//g, '>'). replace(/##(\d+)##/g, function($0,$1) { return replace_strings[$1] || ''; }); if (replace_strings.length) { try { if (isChromium) { range.selectNodeContents(htmlDoc.documentElement); } else { range.selectNode(text_node); } df = range.createContextualFragment(new_text); if (df.firstChild) parent.replaceChild(df, text_node); range.detach(); } catch (e) { error(e); } } }); } function addsheet() { if (!main_sheet) { var hilistyles = STYLE_COLOR.map(function(rgb,i){ return 'span.' + PRE + '_word'+i+',.' + PRE + '_item'+i+'{background:'+rgb+'!important;}'; }); var borderstyles = BORDER_COLOR.map(function(rgb,i){ return 'li.' + PRE + '_item'+i+'{outline:1px solid '+rgb+'!important;}'; }); sheet = addCSS([ //Additional Style 'span[class^="' + PRE + '_word"]{color:black!important;font:inherit!important;display:inline!important;margin:0!important;padding:0!important;text-align:inherit!important;float:none!important;position:static!important;}', //vertical-align:inherit !important; '#' + PRE + '_words, #' + PRE + '_words *{font-family: Arial !important;}', '#' + PRE + '_words{line-height:1;cursor:move;position:fixed;z-index:60000;opacity:0.8;list-style-type:none;margin:0;padding:0;width:auto;max-width:100%;' + panel_pos_arr[0] + panel_pos_arr[1] +'}', '#' + PRE + '_words > section{clear:right;line-height:1;border:1px solid #333;border-left-width:10px;background:#fff;display:block;position:relative;}', '#' + PRE + '_words > section.hide:hover {border-left-width:20px;}', '#' + PRE + '_words * {margin:0;padding:0;width:auto;height:auto;}', '#' + PRE + '_words:hover{opacity:1;}', '#' + PRE + '_words > nav{display:none;width:100%;padding:3px;position:relative;}', '#' + PRE + '_words > nav > canvas.backport{background:rgba(0,0,0,0.5);cursor:pointer;position:absolute;right:6px;z-index:3;}', '#' + PRE + '_words > nav > canvas.viewport{background:rgba(79,168,255,0.7);cursor:default;position:absolute;bottom:0px;right:6px;}',//outline:6px solid rgba(79,168,255,0.7); // '#' + PRE + '_words > nav:hover > canvas.backport{background:rgba(0,0,0,0.5);}', '#' + PRE + '_words:hover > nav{display:block;}', '#' + PRE + '_words:hover > nav > canvas.backport{bottom:0px;}', '#' + PRE + '_words.edit{opacity:1;cursor:default;}', '#' + PRE + '_words.edit #' + PRE + '_word_inputs_list{display:none;}', '#' + PRE + '_words form.' + PRE + '_editor{display:none;}', '#' + PRE + '_words.edit form.' + PRE + '_editor{display:inline-block;}', '#' + PRE + '_words.edit form.' + PRE + '_editor input{min-width:80px;}', '#' + PRE + '_words li{display:inline-block;margin:0.1em 0.2em;line-height:1.3em;font-size:medium;}', '#' + PRE + '_words > section > * {vertical-align:middle;}', '#' + PRE + '_words > section > h3.' + PRE + '_title{display:inline-block;background:#333;color:#fff;padding:0.1em 0.3em;border:none;margin:0 0.2em;}', '#' + PRE + '_words > section form.' + PRE + '_ctrl{display:inline-block;}', '#' + PRE + '_words > section form.' + PRE + '_ctrl > input{display:inline;width:1.3em;margin:0.1em 0.1em;background:'+ but_c +';border:1px solid #996666;cursor:pointer;font-size:10pt;color:black;}', '#' + PRE + '_words > section form.' + PRE + '_ctrl > input._active{background:'+ but_ca +';}', '#' + PRE + '_words > section form.' + PRE + '_ctrl > input._disable{background:'+ but_cd +' !important;cursor:default;}', '#' + PRE + '_words > section form.' + PRE + '_ctrl > input:hover{outline:1px solid #996666!important;}', '#' + PRE + '_word_inputs_list {padding:0!important;margin:0.2em!important;display:inline-block;border:none!important;}', '#' + PRE + '_word_inputs_list > li{position:relative;padding:0 4px;}', '#' + PRE + '_word_inputs_list > li.ewh_disable{background:white!important;outline:1px solid #999!important;}', '#' + PRE + '_word_inputs_list > li > label{cursor:pointer;color:black!important;}', '#' + PRE + '_word_inputs_list > li > input{cursor:pointer;}', // '#' + PRE + '_word_inputs_list > li > label > input[type=image]{vertical-align:top;padding:0;height:12px;}', '#' + PRE + '_word_inputs_list > li > input[type=checkbox]{display:none;position:absolute;right:0px;top:0px;opacity:0.7;}', '#' + PRE + '_word_inputs_list > li:hover{outline-width:2px!important;}', '#' + PRE + '_word_inputs_list > li:hover > input[type=checkbox]{display:block;}', '#' + PRE + '_word_inputs_list > li > input[type=checkbox]:hover{opacity:1;}', ].concat(hilistyles, borderstyles).join('\n')); main_sheet = true; } if (!move_sheet) addmovesheet() } function addmovesheet() { addCSS('.wordhighlight_em{outline:4px solid #FF7B00;-webkit-outline:4px solid #FF7B00;text-decoration:blink;}'); move_sheet = true; } function setup() { setuped = true; addsheet(); // build ui aside = creaElemIn('aside', document.body); aside.id = PRE + '_words'; aside.className = 'fixed'; section = creaElemIn('section', aside); var table_COL = creaElemIn('table', section); table_COL.setAttribute('style', 'border:0;margin:0;padding:0;border-spacing:2px;'); var tbdy_COL = creaElemIn('tbody', table_COL); var tr_COL = creaElemIn('tr', tbdy_COL); var td1 = creaElemIn('td', tr_COL); td1.setAttribute('style', 'border-right: 1px solid black; padding:0.2em 0.3em 0 0;vertical-align:baseline;');//width:7.2em; var td2 = creaElemIn('td', tr_COL); var editor = creaElemIn('form', td2); editor.className = PRE + '_editor'; text_input = creaElemIn('input', editor); text_input.type = 'text'; var ctrl = creaElemIn('form', td1); ctrl.className = PRE + '_ctrl'; var close_button = creaElemIn('input', ctrl); close_button.type = 'button'; close_button.value = 'X'; // close_button.setAttribute('style', 'width: 26px;'); close_button.title = _ti.close[_L]; off = creaElemIn('input', ctrl); off.type = 'button'; off.value = 'O'; // off.setAttribute('style', 'width: 26px;'); off.title = _ti.off[_L]; lock = creaElemIn('input', ctrl); lock.type = 'button'; lock.value = 'L'; // lock.setAttribute('style', 'width: 40px;'); edit = creaElemIn('input', ctrl); edit.type = 'button'; edit.value = 'E'; // edit.setAttribute('style', 'width: 40px;'); edit.title = _ti.edit[_L]; word_inputs_list = creaElemIn('ul', td2); word_inputs_list.id = PRE + '_word_inputs_list'; word_inputs_list.className = PRE + '_inputs'; // add interactivity edit.addEventListener('click',command_edit,false); off.addEventListener('click',command_off,false); close_button.addEventListener('click',command_close,false); editor.addEventListener('submit',function(e){ command_edit(); e.preventDefault(); },false); if (gm_ok) { lock.title = _ti.lock[_L]; lock.className = (keyword_store)? '_active' : ''; lock.addEventListener('click',function(){ if (aside.className == 'edit') return; if (keyword_store) { lock.className = ''; lock.title = _ti.lock[_L]; GM_setValue(ST_PRE, ''); keyword_store = ''; // lock.value = 'Lock: Off'; } else { lock.className = '_active'; lock.title = _ti.lock_a[_L] + ' ' + keyword; GM_setValue(ST_PRE, keyword); keyword_store = keyword; // lock.value = 'Lock: On'; } },false); } else { lock.title = _ti.lock_u[_L]; lock.className = '_disable'; } section.addEventListener('dblclick',function(evt){ if((evt.offsetX || evt.layerX) <= ((panel_hide)?20:10)) { if (panel_hide) { aside.style.right = '0px'; section.className = ''; panel_hide = false; }else{ aside.style.right = (10 - aside.offsetWidth) +'px'; section.className = 'hide'; panel_hide = true; } }//console.log(aside.style.right); }, false); // enable drag var drag = endrag(aside,{x:'right',y:'bottom'}); drag.hook('__drag_begin', function(e){ if ((this.element && this.element.className === 'edit') || /^canvas$/i.test(e.target.localName) || /^lable$/i.test(e.target.localName)) return false; }); // build map nav = document.createElement('nav'); aside.insertBefore(nav,aside.firstChild); canvas = creaElemIn('canvas', nav); canvas.className='backport'; cw = creaElemIn('canvas', nav); cw.className='viewport'; var c2 = c2context = canvas.getContext('2d'); // /+drag codes by grea // scrolling per events this.perf = 2, this.perfic = 0; this.moveTo = function(evt){ if (perfic++ % perf || !window.drgg) return; var x = (evt.offsetX || evt.layerX)/ratio - root.clientWidth/2; var y = (evt.offsetY || evt.layerY)/ratio - root.clientHeight/2; window.scrollTo(x, y); } with(canvas){ addEventListener('mousedown', function(e){ window.drgg = true; moveTo(e); },false); addEventListener('mousemove', function(e){ moveTo(e); },false); addEventListener('mouseup', function(e){ window.drgg = false; moveTo(e); },false); addEventListener('mouseout', function(e){ window.drgg = false; moveTo(e); },false); } // +/codes end // add AutoPager page change detector if (Ewh_configs[0]) { this.pagef = 5, this.pagefic = 0; var docHeight = document.body.scrollHeight, pageChanged; this.checkpage = function(){ if ((pagefic++ % pagef == 0) && (document.body.scrollHeight > docHeight)) { switch (Ewh_configs[0]) { case 1: after_load(); break; case 2: resetup(); break; } docHeight = document.body.scrollHeight; } } } // sync with map & check page window.addEventListener('scroll',function(){ var x = window.pageXOffset * ratio; var y = window.pageYOffset * ratio; cw.style.bottom = (canvas.height - cw.height - y) + 'px'; cw.style.right = (-x + 6) + 'px'; if (Ewh_configs[0]) checkpage(); },false); // go to highlight highlight(document.body); word_lists = create_inputlist(words); layers = xp_all.get(); draw_wordmap(); if (!Ewh_configs[0]) init_autopager(); } function restore_words(words) { (words||xp_all.get()).forEach(function(layer,i){ var parent = layer.parentNode; while (layer.firstChild){ parent.insertBefore(layer.firstChild, layer); } parent.removeChild(layer); }); } function draw_wordmap() { var c2 = c2context; var _height = root.clientHeight * 0.7; if (_height > CanvasWidth * (root.scrollHeight/root.scrollWidth)) { canvas.width = CanvasWidth; canvas.height = CanvasWidth * (root.scrollHeight/root.scrollWidth); ratio = CanvasWidth / root.scrollWidth; } else { canvas.height = _height; canvas.width = _height * (root.scrollWidth/root.scrollHeight); ratio = _height / root.scrollHeight; } cw.width = root.clientWidth * ratio; cw.height = root.clientHeight * ratio; cw.style.bottom = (canvas.height - cw.height - window.pageYOffset * ratio)+'px'; c2.clearRect(0,0,window.innerWidth,window.innerHeight); c2.beginPath(); word_lists.forEach(function(item,i){ if(!words_off[i]) { c2.fillStyle = STYLE_COLOR[i%10]; item.get_w().forEach(function(ly,j){ var recs = ly.getClientRects(); for (var i = 0, l = recs.length;i < l;++i){ var rec = recs[i]; var x = Math.max(ratio*(root.scrollLeft + rec.left), 2); var y = Math.max(ratio*(root.scrollTop + rec.top), 2); var width = Math.max(ratio*(rec.width ||(rec.right-rec.left)), 2); var height = Math.max(ratio*(rec.height||(rec.bottom-rec.top)), 2); c2.fillRect(x, y, width, height); } }); } }); c2.fill(); } function add_word(word) { word_tmp = init_words(word); var word_tmp_len = word_tmp.length, words_len = words.length; for (var m=0;m 40)){ section.className = ''; panel_hide = false; } self.__drag_end(e); }; document.addEventListener('mouseup', this.drag_end, false); }; endrag.proto.prototype = { __drag_begin:function(e){ if (e.button == 0) { var _c = this.computed_style; this.isDragging = isDragging = true; this.position = { _x:parseFloat(_c[this.x]), _y:parseFloat(_c[this.y]), x:e.pageX, y:e.pageY }; e.preventDefault(); } }, __dragging:function(e){ if (!this.isDragging) return; var x = Math.floor(e.pageX), y = Math.floor(e.pageY), p = this.position; if (x - window.pageXOffset > window.innerWidth - 20) x = window.innerWidth - 20 + window.pageXOffset; if (y - window.pageYOffset > window.innerHeight - 20) y = window.innerHeight - 20 + window.pageYOffset; p._x = p._x + (p.x - x) * this.xd; p._y = p._y + (p.y - y) * this.yd; this.style[this.x] = p._x + 'px'; this.style[this.y] = p._y + 'px'; p.x = x; p.y = y; }, __drag_end:function(e){ if (e.button == 0) { if (this.isDragging) this.isDragging = isDragging = false; } }, hook:function(method,func){ if (typeof this[method] === 'function') { var o = this[method]; this[method] = function(){ if (func.apply(this,arguments) === false) return; o.apply(this,arguments); }; } } }; return endrag(element,opt); } function load_keyword() { if (keyword_store) { keyword = keyword_store; prep_keyword(); return true; }else { return false; } } //} function init_keyword() { if (Ewh_configs[2] == 1) return false; var name = window.name; var host = location.host, q = document.location.search.slice(1), e = -1; if (Ewh_configs[2] == 2 || name == (PRE + '::CLOSED::')) var _no_refer = true; if (Ewh_configs[2] != 3) init_KW_SR(); //l(101,keyword); if (!_no_refer && !keyword) innt_KW_RF(); //l(102,keyword); if (Ewh_configs[2] != 3 && !keyword) init_KW_SRo(); //l(103,keyword); keyword = trim(keyword); if (keyword) { window.name = PRE + '::' + encodeURIComponent(keyword); prep_keyword();//l(104,keyword); return true; } else { return false; } } function init_KW_SR() { //for Search Results var host = location.host, q = document.location.search.slice(1), e = -1; for (i = 0; i < urlArr.length; i++) { if (host.indexOf(urlArr[i][2]) != -1 && q.indexOf(urlArr[i][1]) != -1) e = i;//l(e); } if (e >= 0) { keyword = get_KW_from_URL(q, e);//l(keyword); } } function init_KW_SRo() { //for other search result pages var locationhref = escape(document.location.href); for (var z = 0; z < queryArr.length; z++) { var input_query = document.getElementById(queryArr[z][0]); if (!input_query || locationhref.indexOf(queryArr[z][1]) == -1) continue; if (input_query.tagName.toLowerCase() == "input") keyword = clean(input_query.value); if (keyword) break; } } function innt_KW_RF() { //for Pages from Results var host = location.host, ref = document.referrer, e = -1; for (i = 0; i < urlArr.length; i++) { if (Ewh_configs[2] == 3 && host.indexOf(urlArr[i][2]) != -1) return; if (ref.indexOf(urlArr[i][2]) != -1 && ref.indexOf(urlArr[i][1]) != -1) e = i;//l(e); } if (e >= 0) { var _a = document.createElement('a'); _a.href = ref; var q = _a.search.slice(1); keyword = get_KW_from_URL(q, e);//l(keyword); } } function inher_keyword() { if (name.indexOf(PRE) == 0 && name != (PRE + '::CLOSED::')) {//look for keywords in name keyword = (new RegExp(PRE + '\\d*::(.+)').exec(decodeURIComponent(window.name))[1]) || ''; } else { return false; } if (keyword) { prep_keyword(); return true; } else { return false; } } function get_KW_from_URL(urlsearch, _e) { var qspairs = urlsearch.split('&'), kwtmp; for (k = 0; k < qspairs.length; k++) { if (qspairs[k].indexOf(urlArr[_e][1]) == 0) {KW = qspairs[k].substring(urlArr[_e][1].length).replace(/\+/g,' '); break;} }l(KW); if (urlArr[_e][0] =='Baidu' && urlsearch.indexOf('ie=utf-8') == -1) kwtmp = urlDecode(KW); // ???????utf-8 else kwtmp = decodeURIComponent(KW); return clean(kwtmp); } function prep_keyword() { words = init_words(keyword); } function trim(str) { return str.replace(/[\n\r]+/g,' ').replace(/^\s+|\s+$/g,'').replace(/\.+\s|\.+$/g,''); } function clean(str) { return str.replace(/(?:(?:\s?(?:site|(?:all)?in(?:url|title|anchor|text)):|(?:\s|^)-)\S*|(\s)(?:OR|AND)\s|[()])/g,'$1'); } function uniq(arr) { var a = [], o = {}, i, v, len = arr.length; if (len < 2) {return arr;} for (i = 0; i < len; i++) { v = arr[i]; if (o[v] !== 1) { a.push(v); o[v] = 1; } } return a; }; function word_length_Comp(a,b) { return (b.length - a.length); }; function init_words(word) { var erg = word.match(new RegExp("^ ?/(.+)/([gim]+)?$")); if (erg) { var ew = erg[1], flag = erg[2] || ''; var word_s = [{exp:new RegExp('(' + ew + ')(?!##)', flag), text:ew, toString:function(){return ew;}}]; } else if (word) { var ret=[], eword = word.replace(/"([^"]+)"/g,function($0,$1){$1 && ret.push($1);return '';}); var word_s = eword.split(/[\+\s:\|#]/).filter(function(w){return !!w;}).concat(ret); word_s = (Ewh_configs[3])? uniq(word_s).sort(word_length_Comp) : uniq(word_s); if (Ewh_configs[1]) { for (var i in word_s) { if (/^[a-z0-9]$/i.test(word_s[i]) || (Ewh_configs[1] == 2 && /^[a-z0-9]{2}$/i.test(word_s[i]))) words_off[i] = true; else words_off[i] = false; } } }//l(word_s[0].exp); return word_s; } function init_minibuffer() { if (window.Minibuffer) document.removeEventListener('keypress', keyhandler, false); var mini = window.Minibuffer; mini.addCommand({ name: 'keyword-search', command: function(stdin){ keyword += ' ' + this.args.join(' '); keyword = trim(keyword); prep_keyword(); if (setuped) resetup(); else setup(); return stdin; } }); mini.addShortcutkey({ key:KEY_NEXT, command:next, description: 'emphasis next keyword' }); mini.addShortcutkey({ key:KEY_PREV, command:prev, description: 'emphasis prev keyword' }); mini.addShortcutkey({ key:KEY_SEARCH, command:function(e){ instant_search(); }, description: 'emphasis prev keyword' }); } function next(index,_layers) { _layers || (_layers = (layers || (layers = xp_all.get()) )); index || (index = 0); move(_layers[++positions[index]] || (positions[index] = 0, _layers[positions[index]])); position_box(index); } function prev(index,_layers) { _layers || (_layers = (layers || (layers = xp_all.get()) )); index || (index = 0); move(_layers[--positions[index]] || (positions[index] = _layers.length - 1, _layers[positions[index]])); position_box(index); } function position_box(index) { if (!posi_tip) { posi_tip = creaElemIn('div', section); posi_tip.setAttribute('style', 'background:white;color:black;border:1px solid black;text-align:center;position:absolute;left:30px;z-index:1025;font-size:16px;height:20px;top:-20px;width:40px;-moz-box-shadow:0 2px 4px #444444;-Webkit-box-shadow:0 2px 4px #444444;'); } clearTimeout(posi_tip_timer); posi_tip.style.display = 'block'; posi_tip.innerHTML = positions[index]+1; if (index == 0) posi_tip.style.left = '30px'; else posi_tip.style.left = (word_lists[index-1].item.offsetLeft + (word_lists[index-1].item.clientWidth - 40)/2) + 'px'; posi_tip_timer = setTimeout(function(){posi_tip.style.display = 'none';},3000); } function init_keyboard() { if (isOpera) { } else if (window.Minibuffer) { init_minibuffer(); return; } else { window.addEventListener('GM_MinibufferLoaded', init_minibuffer, false); } if (!window.chromium) { document.addEventListener('keypress', keyhandler, false); } else { document.addEventListener('keydown', keyhandler, false); } } function get_key(evt) { var key = String.fromCharCode(evt.which), ctrl = evt.ctrlKey ? 'C-' : '', meta = (evt.metaKey || evt.altKey) ? 'M-' : ''; if (!evt.shiftKey){ key = key.toLowerCase(); } if (evt.ctrlKey && evt.which >= 186 && evt.which < 192) { key = String.fromCharCode(evt.which - 144); } if (evt.keyIdentifier && evt.keyIdentifier !== 'Enter' && !/^U\+/.test(evt.keyIdentifier) ) { key = evt.keyIdentifier; } else if ( evt.which !== evt.keyCode ) { key = keyCodeStr[evt.keyCode] || whichStr[evt.which] || key; } else if (evt.which <= 32) { key = keyCodeStr[evt.keyCode] || whichStr[evt.which]; } return ctrl+meta+key; } function keyhandler(evt) { if (evt.target.id == PRE + '_textinput') var _r = true; else if (/^(?:input|textarea)$/i.test(evt.target.localName)) return; var fullkey = get_key(evt); if (setuped){ switch (fullkey) { case KEY_NEXT: next(); break; case KEY_PREV: prev(); break; case KEY_OFF: command_off(); break; case KEY_CLOSE: command_close(); break; case KEY_EDIT: command_edit(); break; case KEY_REFRESH: resetup(); break; } } switch (fullkey) { case KEY_SEARCH: evt.preventDefault(); evt.stopPropagation(); instant_search(_r, evt.target); break; } } function command_close() { document.body.removeChild(aside); if (document.getElementById(PRE + '_textinputbox')) document.body.removeChild(inputBOX); instant_search.input = null; restore_words(); // sheet.disable = true; if (addCSS.__style.parentNode) addCSS.__root.removeChild(addCSS.__style); window.name = PRE + '::CLOSED::'; word_lists = []; // _words = []; setuped = false; highlight_reset(); } function command_off() { if (aside.className == 'edit') return; var words_check = new Array(), _tmp; for (var i=0;;i++) { _tmp = document.getElementById(ID_PRE + '_check' + i); if (!_tmp) break; words_check[i] = _tmp; } if (!highlight_off) { restore_words(); for (i in words_check) { words_check[i].checked = false; words_check[i].parentNode.className += ' ewh_disable' } // off.value = 'On'; off.className = '_active' highlight_off = true; } else { word_lists = []; word_inputs_list.innerHTML = ''; resetup(); for (i in words_check) { words_check[i].checked = true; words_check[i].parentNode.className = words_check[i].parentNode.className.replace(' ewh_disable', ''); } // off.value = 'Off'; off.className = ''; highlight_off = false; } draw_wordmap(); } function command_edit() { if (aside.className == 'edit') { aside.style.width = 'auto'; // edit.value = 'Edit'; edit.className = ''; edit.title = _ti.edit[_L]; if (gm_ok) lock.className = lock.className.replace(' _disable',''); off.className = ''; highlight_off = false; aside.className = ''; keyword = trim(text_input.value); prep_keyword(); window.name = PRE + '::' + encodeURIComponent(keyword); resetup(); } else { var _aside_w = aside.offsetWidth; // edit.value = 'Set'; edit.className = '_active'; edit.title = _ti.edit_a[_L]; if (gm_ok) lock.className += ' _disable'; off.className += ' _disable'; aside.className = 'edit'; text_input.value = keyword; text_input.focus(); text_input.style.width = (Math.max(320,_aside_w) - 130) +'px'; aside.style.width = Math.max(320,_aside_w) +'px'; } } function instant_search(_r, e_target) { var topWords = function() { if (0< MaxWords) { var doc= document; var text= doc.body.textContent; // remove the nouns at begin of paragraph or after ".!?;" //text=text.replace (/[\.\?\!\;\n\f\r]\s*[A-Z][0-9'\-A-Za-z_\u0080-\u10FFFF]+/g, ""); var re = new RegExp("\\b(['\\-A-Za-z\\u0080-\\u10FFFF]+)\\b", "g"); var searchTerms=[]; $X('descendant::text()[string-length(normalize-space(self::text())) > 0 and not(ancestor::textarea or ancestor::script or ancestor::style or ancestor::aside)]', doc).forEach(function(text_node) { // find the words var text = text_node.nodeValue; var word=re.exec(text); while (word) { var word1 = word[1].toLowerCase(); if ( MinWordLength <=word1.length && word1 != "length") { // otherwise conflicts with the word.length attribute ! var found=false; for (var j in searchTerms) { if (searchTerms[j].word.toLowerCase() == word1) { // because of capture parenthesis found=true; } }; if (! found) { searchTerms[word1] = { c: 1 , word: word1 } } else { searchTerms[word1] = { c: searchTerms[word1].c +1 , word: word1 } }; }; word=re.exec(text); }; }); i=0; // change key var searchTerms2=[ ]; for (word in searchTerms) { if (word != "length" && excludedWords.indexOf(" " + word + " ") ==-1 ) { searchTerms2[i] = searchTerms[word]; i++ }; }; searchTerms2.sort(function (a,b) { return a.c == b.c ? 0 : a.c < b.c ? 1 : -1; } ); topWords = ""; for (i=0; i]=?|[\(\[|,=+-])|([@$])/g; var TERM = 1, OPERATOR = 2, MODIFIER = 3; var tokenType = OPERATOR; prefix += ':'; function replacer(token, identifier, suffix, term, operator, modifier) { if (suffix) { tokenType = (suffix == ':' || (suffix == '::' && (identifier == 'attribute' || identifier == 'namespace'))) ? MODIFIER : OPERATOR; } else if (identifier) { if (tokenType == OPERATOR && identifier != '*') { token = prefix + token; } tokenType = (tokenType == TERM) ? OPERATOR : TERM; } else { tokenType = term ? TERM : operator ? OPERATOR : MODIFIER; } return token; } return xpath.replace(tokenPattern, replacer); } // http://d.hatena.ne.jp/amachang/20090917/1253179486 function escapeXPathExpr(text) { var matches = text.match(/[^"]+|"/g); function esc(t) { return t == '"' ? ('\'' + t + '\'') : ('"' + t + '"'); } if (matches) { if (matches.length == 1) { return esc(matches[0]); } else { var results = []; for (var i = 0, len = matches.length; i < len; i ++) { results.push(esc(matches[i])); } return 'concat(' + results.join(', ') + ')'; } } else { return '""'; } } function $X(exp, context, resolver, result_type) { context || (context = document); var Doc = context.ownerDocument || context; var result = Doc.evaluate(exp, context, resolver, result_type || XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); if (result_type) return result; for (var i = 0, len = result.snapshotLength, res = new Array(len); i < len; i++) { res[i] = result.snapshotItem(i); } return res; } // reduce https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduce#Compatibility function reduce(arr, fun) { var len = arr.length, i = 0, rv; if (arguments.length >= 3) rv = arguments[2]; else {do { if (i in arr) { rv = arr[i++];break; } if (++i >= len) throw new TypeError(); } while (true)}; for (; i < len; i++) if (i in arr) rv = fun.call(null, rv, arr[i], i, arr); return rv; } function error(e) { if (isOpera) { opera.postError(e); } else if (window.console) { console.error(e); } } function addCSS(css) { var sheet, self = arguments.callee; if (document.createStyleSheet) { // for IE sheet = document.createStyleSheet(); sheet.cssText = css; return sheet; } else if (!self.__style || !self.__root) { sheet = document.createElement('style'); sheet.type = 'text/css'; self.__style = sheet; self.__root = document.getElementsByTagName('head')[0] || document.documentElement; } sheet = self.__style.cloneNode(false); sheet.textContent = css; return self.__root.appendChild(sheet).sheet; } function getY(oElement) { var iReturnValue = 0; while (oElement != null) { iReturnValue += oElement.offsetTop; oElement = oElement.offsetParent; } return iReturnValue; } function creaElemIn(tagname, destin) { var theElem = destin.appendChild(document.createElement(tagname)); return theElem; } /** Get elements by className * @function getElementsByClassName * @param string className * @param optional string tag restrict to specified tag * @param optional node restrict to childNodes of specified node * @return Array of nodes * @author Jonathan Snook, http://www.snook.ca/jonathan * @author Robert Nyman, http://www.robertnyman.com */ function getElementsByClassName(className, tag, elm) { var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)"); var tag = tag || "*"; var elm = elm || document; var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag); var returnElements = []; var current; var length = elements.length; for(var i=0; i 0x7f) { ret += asc2str(parseInt("0x" + asc+str.substring(i+4, i+6))); i += 5; } else { ret += asc2str(parseInt("0x"+asc)); i += 2; } } else { ret += chr; } } return ret; } //{ // function target_google(doc,index){ // var as = $X('descendant::a[@href and not(starts-with(@href,"javascript:") or starts-with(@href,"#"))]',doc); // as.forEach(function(a,i){ // if (a.target != 'self') // a.target = PRE + (i + (index || 0) * as.length) + '::' + encodeURIComponent(keyword); // }); // } // alert(urlDecode("%B9%E9%B8%F9%BD%E1%B5%D7")); //} // l(keyword); })(); //console.timeEnd("highlight"); // Bench: http://www.google.com/search?hl=en&q=HTML+5+Markup+Language