/** * ==VimperatorPlugin== * @name copy.js * @description enable to copy strings from a template (like CopyURL+) * @description-ja テンプレートから文字列のコピーを可能にします(CopyURL+みたなもの) * @minVersion 1.1 * @author teramako teramako@gmail.com * @version 0.5a * ==/VimperatorPlugin== * * Usage: * :copy {copyString} -> copy the argument replaced some certain string * :copy! {expr} -> evaluate the argument and copy the result * * e.g.) * :copy %TITLE% -> copied the title of the current page * :copy title -> same as `:copy %TITLE%' by default * :copy! liberator.version -> copy the value of liberator.version * * If non-argument, used `default' * * label: template name which is command argument * value: copy string * the certian string is replace to ... * %TITTLE% -> to the title of the current page * %URL% -> to the URL of the current page * %SEL% -> to the string of selection * %HTMLSEL% -> to the html string of selection * * map: key map (optional) * * custom: {function} or {Array} (optional) * {function}: * execute the function and copy return value, if specified. * * {Array}: * replaced to the {value} by normal way at first. * and replace words matched {Array}[0] in the replaced string to {Array}[1]. * {Array}[0] is string or regexp * {Array}[1] is string or function * see http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:String:replace * * The copy_templates is a string variable which can set on * vimperatorrc as following. * * let copy_templates = "[{ label: 'titleAndURL', value: '%TITLE%\n%URL%' }, { label: 'title', value: '%TITLE%' }]" * * or your can set it using inline JavaScript. * * javascript <%TITLE%' }, * { label: 'selanchor', value: '%SEL%' }, * { label: 'htmlblockquote', value: '
%HTMLSEL%
' } * { label: 'ASIN', value: 'copy ASIN code from Amazon', custom: function(){return content.document.getElementById('ASIN').value;} }, * ]; * EOM */ liberator.plugins.exCopy = (function(){ if (!liberator.globalVariables.copy_templates){ liberator.globalVariables.copy_templates = [ { label: 'titleAndURL', value: '%TITLE%\n%URL%' }, { label: 'title', value: '%TITLE%' }, { label: 'anchor', value: '%TITLE%' }, { label: 'selanchor', value: '%SEL%' }, { label: 'htmlblockquote', value: '
%HTMLSEL%
' } ]; } liberator.globalVariables.copy_templates.forEach(function(template){ if (typeof template.map == 'string') addUserMap(template.label, [template.map]); else if (template.map instanceof Array) addUserMap(template.label, template.map); }); // used when argument is none //const defaultValue = templates[0].label; commands.addUserCommand(['copy'],'Copy to clipboard', function(arg, special){ liberator.plugins.exCopy.copy(arg, special); },{ completer: function(filter, special){ if (special){ return completion.javascript(filter); } var templates = liberator.globalVariables.copy_templates.map(function(template) [template.label, template.value] ); if (!filter){ return [0,templates]; } var candidates = []; templates.forEach(function(template){ if (template[0].toLowerCase().indexOf(filter.toLowerCase()) == 0){ candidates.push(template); } }); return [0, candidates]; }, bang: true } ); function addUserMap(label, map){ mappings.addUserMap([modes.NORMAL,modes.VISUAL], map, label, function(){ liberator.plugins.exCopy.copy(label); }, { rhs: label } ); } function getCopyTemplate(label){ var ret = null; liberator.globalVariables.copy_templates.some(function(template) template.label == label ? (ret = template) && true : false); return ret; } function replaceVariable(str){ if (!str) return ''; var win = new XPCNativeWrapper(window.content.window); var sel = '',htmlsel = ''; if (str.indexOf('%SEL%') >= 0 || str.indexOf('%HTMLSEL%') >= 0){ sel = win.getSelection().getRangeAt(0); } if (str.indexOf('%HTMLSEL%') >= 0){ var serializer = new XMLSerializer(); htmlsel = serializer.serializeToString(sel.cloneContents()); } return str.replace(/%TITLE%/g,buffer.title) .replace(/%URL%/g,buffer.URL) .replace(/%SEL%/g,sel.toString()) .replace(/%HTMLSEL%/g,htmlsel); } var exCopyManager = { add: function(label, value, custom, map){ var template = {label: label, value: value, custom: custom, map: map}; liberator.globalVariables.copy_templates.unshift(template); if (map) addUserMap(label, map); return template; }, get: function(label){ return getCopyTemplate(label); }, copy: function(arg, special){ var copyString = ''; var isError = false; if (special && arg){ try { copyString = window.eval('with(liberator){' + arg + '}'); switch (typeof copyString){ case 'object': copyString = copyString === null ? 'null' : copyString.toSource(); break; case 'function': copyString = copyString.toString(); break; case 'number': case 'boolean': copyString = '' + copyString; break; case 'undefined': copyString = 'undefined'; break; } } catch (e){ isError = true; copyString = e.toString(); } } else { if (!arg) arg = liberator.globalVariables.copy_templates[0]; var template = getCopyTemplate(arg) || arg; if (typeof template.custom == 'function'){ copyString = template.custom.call(this, template.value); } else if (template.custom instanceof Array){ copyString = replaceVariable(template.value).replace(tempalte.custom[0], template.custom[1]); } else { copyString = replaceVariable(template.value); } } util.copyToClipboard(copyString); if (isError){ liberator.echoerr('CopiedErrorString: `' + copyString + "'"); } else { liberator.echo('CopiedString: `' + util.escapeHTML(copyString) + "'"); } } }; return exCopyManager; })(); // vim: set fdm=marker sw=4 ts=4 et: id='n111' href='#n111'>111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
// Vimperator plugin: 'Char Hints Mod'
// Last Change: 15-Mar-2008. Jan 2008
// License: GPL
// Version: 0.2
// Maintainer: Trapezoid <trapezoid.g@gmail.com>

// This file is a tweak based on char-hints.js by:
// (c) 2008: marco candrian <mac@calmar.ws>
// This file is a tweak based on hints.js by:
// (c) 2006-2008: Martin Stubenschrott <stubenschrott@gmx.net>

// Tested with vimperator 0.6pre from 2008-03-07
// (won't work with older versions)

// INSTALL: put this file into ~/.vimperator/plugin/  (create folders if necessary)
// and restart firefox or :source that file

// plugin-setup
vimperator.plugins.charhints = {};
var chh = vimperator.plugins.charhints;

//<<<<<<<<<<<<<<<< EDIT USER SETTINGS HERE

//chh.hintchars = "asdfjkl";      // chars to use for generating hints
chh.hintchars = "hjklasdfgyuiopqwertnmzxcvb";      // chars to use for generating hints

chh.showcapitals = true;        // show capital letters, even with lowercase hintchars
chh.timeout = 500;              // in 1/000sec; when set to 0, press <RET> to follow

chh.fgcolor = "black";          // hints foreground color
chh.bgcolor = "yellow";         // hints background color
chh.selcolor = "#99FF00";       // selected/active hints background color

chh.mapNormal = "f";            // trigger normal mode with...
chh.mapNormalNewTab = "F";      // trigger and open in new tab
chh.mapExtended = ";";          // open in extended mode (see notes below)

chh.hinttags = "//*[@onclick or @onmouseover or @onmousedown or @onmouseup or @oncommand or @class='lk' or @class='s'] | " +
"//input[not(@type='hidden')] | //a | //area | //iframe | //textarea | //button | //select | " +
"//xhtml:*[@onclick or @onmouseover or @onmousedown or @onmouseup or @oncommand or @class='lk' or @class='s'] | " +
"//xhtml:input[not(@type='hidden')] | //xhtml:a | //xhtml:area | //xhtml:iframe | //xhtml:textarea | " +
"//xhtml:button | //xhtml:select";

//========================================
//  extended hints mode arguments
//
// ; to focus a link and hover it with the mouse
// a to save its destination (prompting for save location)
// s to save its destination
// o to open its location in the current tab
// t to open its location in a new tab
// O to open its location in an :open query
// T to open its location in a :tabopen query
// v to view its destination source
// w to open its destination in a new window
// W to open its location in a :winopen query
// y to yank its location
// Y to yank its text description

// variables etc//{{{


// ignorecase when showcapitals = true
// (input keys on onEvent gets lowercased too

if (chh.showcapitals)
    chh.hintchars = chh.hintchars.toLowerCase();


chh.submode    = ""; // used for extended mode, can be "o", "t", "y", etc.
chh.hintString = ""; // the typed string part of the hint is in this string
chh.hintNumber = 0;  // only the numerical part of the hint
chh.usedTabKey = false; // when we used <Tab> to select an element

chh.hints = [];
chh.validHints = []; // store the indices of the "hints" array with valid elements

chh.activeTimeout = null;  // needed for hinttimeout > 0
chh.canUpdate = false;

// used in number2hintchars
chh.transval = {"0":0,  "1":1, "2":2,  "3":3,  "4":4,  "5":5,  "6":6,  "7":7,  "8":8,  "9":9,  "a":10, "b":11,
                "c":12, "d":13,"e":14, "f":15, "g":16, "h":17, "i":18, "j":19, "k":20, "l":21, "m":22, "n":23,
                "o":24, "p":25,"q":26, "r":27, "s":28, "t":29, "u":30, "v":31, "w":32, "x":33, "y":34, "z":35};

// used in hintchars2number
chh.conversion = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

// keep track of the documents which we generated the hints for
// docs = { doc: document, start: start_index in hints[], end: end_index in hints[] }
chh.docs = [];
//}}}
// reset all important variables
chh.reset = function ()//{{{
{
    vimperator.statusline.updateInputBuffer("");
    chh.hintString = "";
    chh.hintNumber = 0;
    chh.usedTabKey = false;
    chh.hints = [];
    chh.validHints = [];
    chh.canUpdate = false;
    chh.docs = [];

    if (chh.activeTimeout)
        clearTimeout(chh.activeTimeout);
    chh.activeTimeout = null;
}
//}}}
chh.updateStatusline = function ()//{{{
{
    vimperator.statusline.updateInputBuffer(("") +
            (chh.hintString ? "\"" + chh.hintString + "\"" : "") +
            (chh.hintNumber > 0 ? " <" + chh.hintNumber + ">" : ""));
}
//}}}
// this function 'click' an element, which also works
// for javascript links
chh.hintchars2number = function (hintstr)//{{{
{
    // convert into 'normal number then make it decimal-based

    var converted = "";

    // translate users hintchars into a number (chh.conversion) 0 -> 0, 1 -> 1, ...
    for (var i = 0, l = hintstr.length; i < l; i++)
        converted += "" + chh.conversion[chh.hintchars.indexOf(hintstr[i])];

    // add one, since hints begin with 0;

    return parseInt(converted, chh.hintchars.length); // hintchars.length is the base/radix
}
//}}}
chh.number2hintchars = function (nr)//{{{
{
    var oldnr = nr;
    var converted = "";
    var tmp = "";

    tmp = nr.toString(chh.hintchars.length); // hintchars.length is the base/radix)

    // translate numbers into users hintchars
    // tmp might be 2e -> (chh.transval) 2 and 14 -> (chh.hintchars) according hintchars

    for (var i = 0, l = tmp.length; i < l; i++)
        converted += "" + chh.hintchars[chh.transval[tmp[i]]];

    return converted;
}
//}}}
chh.openHint = function (where)//{{{
{
    if (chh.validHints.length < 1)
        return false;

    var x = 1, y = 1;
    var elem = chh.validHints[chh.hintNumber - 1] || chh.validHints[0];
    var elemTagName = elem.localName.toLowerCase();
    elem.focus();

    vimperator.buffer.followLink(elem, where);
    return true;
}
//}}}
chh.focusHint = function ()//{{{
{
    if (chh.validHints.length < 1)
        return false;

    var elem = chh.validHints[chh.hintNumber - 1] || chh.validHints[0];
    var doc = window.content.document;
    var elemTagName = elem.localName.toLowerCase();
    if (elemTagName == "frame" || elemTagName == "iframe")
    {
        elem.contentWindow.focus();
        return false;
    }
    else
    {
        elem.focus();
    }

    var evt = doc.createEvent("MouseEvents");
    var x = 0;
    var y = 0;
    // for imagemap
    if (elemTagName == "area")
    {
        [x, y] = elem.getAttribute("coords").split(",");
        x = Number(x);
        y = Number(y);
    }

    evt.initMouseEvent("mouseover", true, true, doc.defaultView, 1, x, y, 0, 0, 0, 0, 0, 0, 0, null);
    elem.dispatchEvent(evt);
}
//}}}
chh.yankHint = function (text)//{{{
{
    if (chh.validHints.length < 1)
        return false;

    var elem = chh.validHints[chh.hintNumber - 1] || chh.validHints[0];
    if (text)
        var loc = elem.textContent;
    else
        var loc = elem.href;

    vimperator.copyToClipboard(loc);
    vimperator.echo("Yanked " + loc, vimperator.commandline.FORCE_SINGLELINE);
}
//}}}
chh.saveHint = function (skipPrompt)//{{{
{
    if (chh.validHints.length < 1)
        return false;

    var elem = chh.validHints[chh.hintNumber - 1] || chh.validHints[0];

    try
    {
        vimperator.buffer.saveLink(elem,skipPrompt);
    }
    catch (e)
    {
        vimperator.echoerr(e);
    }
}
//}}}
chh.generate = function (win)//{{{
{
    var startDate = Date.now();

    if (!win)
        win = window.content;

    var doc = win.document;
    var height = win.innerHeight;
    var width  = win.innerWidth;
    var scrollX = doc.defaultView.scrollX;
    var scrollY = doc.defaultView.scrollY;

    var baseNodeAbsolute = doc.createElementNS("http://www.w3.org/1999/xhtml", "span");
    baseNodeAbsolute.style.backgroundColor = "red";
    baseNodeAbsolute.style.color = "white";
    baseNodeAbsolute.style.position = "absolute";
    baseNodeAbsolute.style.fontSize = "10px";
    baseNodeAbsolute.style.fontWeight = "bold";
    baseNodeAbsolute.style.lineHeight = "10px";
    baseNodeAbsolute.style.padding = "0px 1px 0px 0px";
    baseNodeAbsolute.style.zIndex = "10000001";
    baseNodeAbsolute.style.display = "none";
    baseNodeAbsolute.className = "vimperator-hint";

    var elem, tagname, text, span, rect;
    var res = vimperator.buffer.evaluateXPath(chh.hinttags, doc, null, true);
    vimperator.log("shints: evaluated XPath after: " + (Date.now() - startDate) + "ms");

    var fragment = doc.createDocumentFragment();
    var start = chh.hints.length;
    while ((elem = res.iterateNext()) != null)
    {
        // TODO: for frames, this calculation is wrong
        rect = elem.getBoundingClientRect();
        if (!rect || rect.top > height || rect.bottom < 0 || rect.left > width || rect.right < 0)
            continue;

        rect = elem.getClientRects()[0];
        if (!rect)
            continue;

        // TODO: mozilla docs recommend localName instead of tagName
        tagname = elem.tagName.toLowerCase();
        text = "";
        span = baseNodeAbsolute.cloneNode(true);
        span.style.left = (rect.left + scrollX) + "px";
        span.style.top = (rect.top + scrollY) + "px";
        fragment.appendChild(span);

        chh.hints.push([elem, text, span, null, elem.style.backgroundColor, elem.style.color]);
    }

    doc.body.appendChild(fragment);
    chh.docs.push({ doc: doc, start: start, end: chh.hints.length - 1 });

    // also generate hints for frames
    for (var i = 0; i < win.frames.length; i++)
        chh.generate(win.frames[i]);

    vimperator.log("shints: generate() completed after: " + (Date.now() - startDate) + "ms");
    return true;
}
//}}}
// TODO: make it aware of imgspans
chh.showActiveHint = function (newID, oldID)//{{{
{
    var oldElem = chh.validHints[oldID - 1];
    if (oldElem)
        oldElem.style.backgroundColor = chh.bgcolor;

    var newElem = chh.validHints[newID - 1];
    if (newElem)
        newElem.style.backgroundColor = chh.selcolor;
}
//}}}
chh.showHints = function ()//{{{
{
    var startDate = Date.now();
    var win = window.content;
    var height = win.innerHeight;
    var width  = win.innerWidth;


    var elem, tagname, text, rect, span, imgspan;
    var hintnum = 1;
    //var findTokens = chh.hintString.split(/ +/);
    var activeHint = chh.hintNumber || 1;
    chh.validHints = [];

    for (var j = 0; j < chh.docs.length; j++)
    {
        var doc = chh.docs[j].doc;
        var start = chh.docs[j].start;
        var end = chh.docs[j].end;
        var scrollX = doc.defaultView.scrollX;
        var scrollY = doc.defaultView.scrollY;

outer:
        for (let i = start; i <= end; i++)
        {
            [elem, , span, imgspan] = chh.hints[i];
            text = "";

            if (elem.firstChild && elem.firstChild.tagName == "IMG")
            {
                if (!imgspan)
                {
                    rect = elem.firstChild.getBoundingClientRect();
                    if (!rect)
                        continue;

                    imgspan = doc.createElementNS("http://www.w3.org/1999/xhtml", "span");
                    imgspan.style.position = "absolute";
                    imgspan.style.opacity = 0.5;
                    imgspan.style.zIndex = "10000000";
                    imgspan.style.left = (rect.left + scrollX) + "px";
                    imgspan.style.top = (rect.top + scrollY) + "px";
                    imgspan.style.width = (rect.right - rect.left) + "px";
                    imgspan.style.height = (rect.bottom - rect.top) + "px";
                    imgspan.className = "vimperator-hint";
                    chh.hints[i][3] = imgspan;
                    doc.body.appendChild(imgspan);
                }
                imgspan.style.backgroundColor = (activeHint == hintnum) ? chh.selcolor : chh.bgcolor;
                imgspan.style.display = "inline";
            }

            if (!imgspan)
                elem.style.backgroundColor = (activeHint == hintnum) ? chh.selcolor : chh.bgcolor;
            elem.style.color = chh.fgcolor;
            if (chh.showcapitals)
                span.textContent = chh.number2hintchars(hintnum++).toUpperCase();
            else
                span.textContent = chh.number2hintchars(hintnum++);

            span.style.display = "inline";
            chh.validHints.push(elem);
        }
    }

    vimperator.log("shints: showHints() completed after: " + (Date.now() - startDate) + "ms");
    return true;
}
//}}}
chh.removeHints = function (timeout)//{{{
{
    var firstElem = chh.validHints[0] || null;
    var firstElemselcolor = "";
    var firstElemColor = "";

    for (var j = 0; j < chh.docs.length; j++)
    {
        var doc = chh.docs[j].doc;
        var start = chh.docs[j].start;
        var end = chh.docs[j].end;

        for (let i = start; i <= end; i++)
        {
            // remove the span for the numeric display part
            doc.body.removeChild(chh.hints[i][2]);
            if (chh.hints[i][3]) // a transparent span for images
                doc.body.removeChild(chh.hints[i][3]);

            if (timeout && firstElem == chh.hints[i][0])
            {
                firstElemselcolor = chh.hints[i][4];
                firstElemColor = chh.hints[i][5];
            }
            else
            {
                // restore colors
                var elem = chh.hints[i][0];
                elem.style.backgroundColor = chh.hints[i][4];
                elem.style.color = chh.hints[i][5];
            }
        }

        // animate the disappearance of the first hint
        if (timeout && firstElem)
        {
            setTimeout(function () {
                    firstElem.style.backgroundColor = firstElemselcolor;
                    firstElem.style.color = firstElemColor;
                    }, timeout);
        }
    }

    vimperator.log("shints: removeHints() done");
    chh.reset();
}
//}}}
chh.processHints = function (followFirst)//{{{
{
    if (chh.validHints.length == 0)
    {
        vimperator.beep();
        return false;
    }

    if (!followFirst)
    {
        var firstHref = chh.validHints[0].getAttribute("href") || null;
        if (firstHref)
        {
            if (chh.validHints.some(function (e) { return e.getAttribute("href") != firstHref; }))
                return false;
        }
        else if (chh.validHints.length > 1)
            return false;
    }

    var activeNum = chh.hintNumber || 1;
    var loc = chh.validHints[activeNum - 1].href || "";
    switch (chh.submode)
    {
        case ";": chh.focusHint(); break;
        case "a": chh.saveHint(false); break;
        case "s": chh.saveHint(true); break;
        case "o": chh.openHint(vimperator.CURRENT_TAB); break;
        case "O": vimperator.commandline.open(":", "open " + loc, vimperator.modes.EX); break;
        case "t": chh.openHint(vimperator.NEW_TAB); break;
        case "T": vimperator.commandline.open(":", "tabopen " + loc, vimperator.modes.EX); break;
        case "w": chh.openHint(vimperator.NEW_WINDOW);  break;
        case "W": vimperator.commandline.open(":", "winopen " + loc, vimperator.modes.EX); break;
        case "y": chh.yankHint(false); break;
        case "Y": chh.yankHint(true); break;
        default:
        vimperator.echoerr("INTERNAL ERROR: unknown submode: " + chh.submode);
    }

    var timeout = followFirst ? 0 : 500;
    chh.removeHints(timeout);

    if (vimperator.modes.extended & vimperator.modes.ALWAYS_HINT)
    {
        setTimeout(function () {
                chh.canUpdate = true;
                chh.hintString = "";
                chh.hintNumber = 0;
                vimperator.statusline.updateInputBuffer("");
                }, timeout);
    }
    else
    {
        if (timeout == 0 || vimperator.modes.isReplaying)
        {
            // force a possible mode change, based on wheter an input field has focus
            vimperator.events.onFocusChange();
            if (vimperator.mode == vimperator.modes.CUSTOM)
                vimperator.modes.reset(false);
        }
        else
        {
            vimperator.modes.add(vimperator.modes.INACTIVE_HINT);
            setTimeout(function () {
                    if (vimperator.mode == vimperator.modes.CUSTOM)
                        vimperator.modes.reset(false);
                    }, timeout);
        }
    }

    return true;
}
//}}}
// TODO: implement framesets
chh.show = function (mode, minor, filter)//{{{
{
    if (mode == vimperator.modes.EXTENDED_HINT && !/^[;asoOtTwWyY]$/.test(minor))
    {
        vimperator.beep();
        return;
    }

    vimperator.modes.set(vimperator.modes.CUSTOM, mode);
    chh.submode = minor || "o"; // open is the default mode
    chh.hintString = filter || "";
    chh.hintNumber = 0;
    chh.canUpdate = false;

    chh.generate();

    // get all keys from the input queue
    var mt = Components.classes["@mozilla.org/thread-manager;1"].getService().mainThread;
    while (mt.hasPendingEvents())
        mt.processNextEvent(true);

    chh.canUpdate = true;
    chh.showHints();

    if (chh.validHints.length == 0)
    {
        vimperator.beep();
        vimperator.modes.reset();
        return false;
    }
    else if (chh.validHints.length == 1)
    {
        chh.processHints(true);
        return false;
    }
    else // still hints visible
        return true;
}
//}}}
chh.hide = function ()//{{{
{
    chh.removeHints(0);
}
//}}}
chh.onEvent = function (event)//{{{
{
    var key = vimperator.events.toString(event);

    if (chh.showcapitals && key.length == 1)
        key = key.toLowerCase();

    // clear any timeout which might be active after pressing a number
    if (chh.activeTimeout)
    {
        clearTimeout(chh.activeTimeout);
        chh.activeTimeout = null;
    }

    switch (key)
    {
        case "<Return>":
            chh.processHints(true);
            break;

        case "<Tab>":
        case "<S-Tab>":
            chh.usedTabKey = true;
            if (chh.hintNumber == 0)
                chh.hintNumber = 1;

            var oldID = chh.hintNumber;
            if (key == "<Tab>")
            {
                if (++chh.hintNumber > chh.validHints.length)
                    chh.hintNumber = 1;
            }
            else
            {
                if (--chh.hintNumber < 1)
                    chh.hintNumber = chh.validHints.length;
            }
            chh.showActiveHint(chh.hintNumber, oldID);
            return;

        case "<BS>": //TODO: may tweak orig hints.js too (adding 2 lines ...)
            var oldID = chh.hintNumber;
            if (chh.hintNumber > 0)
            {
                chh.hintNumber = Math.floor(chh.hintNumber / chh.hintchars.length);
                chh.hintString = chh.hintString.substr(0, chh.hintString.length - 1);
                chh.usedTabKey = false;
            }
            else
            {
                chh.usedTabKey = false;
                chh.hintNumber = 0;
                vimperator.beep();
                return;
            }
            chh.showActiveHint(chh.hintNumber, oldID);
            break;

        case "<C-w>":
        case "<C-u>":
            chh.hintString = "";
            chh.hintNumber = 0;
            break;

        default:
        // pass any special or ctrl- etc. prefixed key back to the main vimperator loop
            if (/^<./.test(key) || key == ":")
            {
                //FIXME: won't work probably
                var map = null;
                if ((map = vimperator.mappings.get(vimperator.modes.NORMAL, key)) ||
                     (map = vimperator.mappings.get(vimperator.modes.CUSTOM, key))) //TODO
                {
                    map.execute(null, -1);
                    return;
                }

                vimperator.beep();
                return;
            }

            if (chh.hintchars.indexOf(key) >= 0) // TODO: check if in hintchars
            {
                chh.hintString += key;
                var oldHintNumber = chh.hintNumber;
                if (chh.hintNumber == 0 || chh.usedTabKey)
                {
                    chh.usedTabKey = false;
                }

                chh.hintNumber = chh.hintchars2number(chh.hintString);

                chh.updateStatusline();

                if (!chh.canUpdate)
                    return;

                if (chh.docs.length == 0)
                {
                    chh.generate();
                    chh.showHints();
                }
                chh.showActiveHint(chh.hintNumber, oldHintNumber || 1);

                if (chh.hintNumber == 0 || chh.hintNumber > chh.validHints.length)
                {
                    vimperator.beep();
                    return;
                }

                // orig hints.js comment: if we write a numeric part like 3, but we have 45 hints, only follow
                // the hint after a timeout, as the user might have wanted to follow link 34
                if (chh.hintNumber > 0 && chh.hintNumber * chh.hintchars.length <= chh.validHints.length)
                {
                    if (chh.timeout > 0)
                        chh.activeTimeout = setTimeout(function () { chh.processHints(true); }, chh.timeout);

                    return false;
                }
                // we have a unique hint
                chh.processHints(true);
                return;
            }

            if (chh.usedTabKey)
            {
                chh.usedTabKey = false;
                chh.showActiveHint(1, chh.hintNumber);
            }
    }

    chh.updateStatusline();
}//}}}


// <<<<<<<<<<<<<<< registering/setting up this plugin

vimperator.modes.setCustomMode ("CHAR-HINTS", vimperator.plugins.charhints.onEvent,
                                vimperator.plugins.charhints.hide);

vimperator.mappings.addUserMap([vimperator.modes.NORMAL], [chh.mapNormal],
        "Start Custum-QuickHint mode",
        function () { vimperator.plugins.charhints.show(vimperator.modes.QUICK_HINT); },
        { noremap: true }
);

vimperator.mappings.addUserMap([vimperator.modes.NORMAL], [chh.mapNormalNewTab],
        "Start Custum-QuickHint mode, but open link in a new tab",
        function () { vimperator.plugins.charhints.show(vimperator.modes.QUICK_HINT, "t"); },
        { noremap: true }
);

vimperator.mappings.addUserMap([vimperator.modes.NORMAL], [chh.mapExtended],
        "Start an extended hint mode",
        function (arg)
        {
            if (arg == "f")
                vimperator.plugins.charhints.show(vimperator.modes.ALWAYS_HINT, "o");
            else if (arg == "F")
                vimperator.plugins.charhints.show(vimperator.modes.ALWAYS_HINT, "t");
            else
                vimperator.plugins.charhints.show(vimperator.modes.EXTENDED_HINT, arg);
        },
        {
            flags: vimperator.Mappings.flags.ARGUMENT,
            noremap: true
        }
);

// vim: set fdm=marker sw=4 ts=4 et: