You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@couchdb.apache.org by be...@apache.org on 2014/01/09 01:07:16 UTC

[01/96] [abbrv] [partial] move sources to src

Updated Branches:
  refs/heads/1994-merge-rcouch cc362741e -> 96057002e


http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/test/mocha/sinon.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/test/mocha/sinon.js b/apps/fauxton/test/mocha/sinon.js
deleted file mode 100644
index 26c4bd9..0000000
--- a/apps/fauxton/test/mocha/sinon.js
+++ /dev/null
@@ -1,4290 +0,0 @@
-/**
- * Sinon.JS 1.7.3, 2013/06/20
- *
- * @author Christian Johansen (christian@cjohansen.no)
- * @author Contributors: https://github.com/cjohansen/Sinon.JS/blob/master/AUTHORS
- *
- * (The BSD License)
- * 
- * Copyright (c) 2010-2013, Christian Johansen, christian@cjohansen.no
- * All rights reserved.
- * 
- * Redistribution and use in source and binary forms, with or without modification,
- * are permitted provided that the following conditions are met:
- * 
- *     * Redistributions of source code must retain the above copyright notice,
- *       this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above copyright notice,
- *       this list of conditions and the following disclaimer in the documentation
- *       and/or other materials provided with the distribution.
- *     * Neither the name of Christian Johansen nor the names of his contributors
- *       may be used to endorse or promote products derived from this software
- *       without specific prior written permission.
- * 
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-this.sinon = (function () {
-var buster = (function (setTimeout, B) {
-    var isNode = typeof require == "function" && typeof module == "object";
-    var div = typeof document != "undefined" && document.createElement("div");
-    var F = function () {};
-
-    var buster = {
-        bind: function bind(obj, methOrProp) {
-            var method = typeof methOrProp == "string" ? obj[methOrProp] : methOrProp;
-            var args = Array.prototype.slice.call(arguments, 2);
-            return function () {
-                var allArgs = args.concat(Array.prototype.slice.call(arguments));
-                return method.apply(obj, allArgs);
-            };
-        },
-
-        partial: function partial(fn) {
-            var args = [].slice.call(arguments, 1);
-            return function () {
-                return fn.apply(this, args.concat([].slice.call(arguments)));
-            };
-        },
-
-        create: function create(object) {
-            F.prototype = object;
-            return new F();
-        },
-
-        extend: function extend(target) {
-            if (!target) { return; }
-            for (var i = 1, l = arguments.length, prop; i < l; ++i) {
-                for (prop in arguments[i]) {
-                    target[prop] = arguments[i][prop];
-                }
-            }
-            return target;
-        },
-
-        nextTick: function nextTick(callback) {
-            if (typeof process != "undefined" && process.nextTick) {
-                return process.nextTick(callback);
-            }
-            setTimeout(callback, 0);
-        },
-
-        functionName: function functionName(func) {
-            if (!func) return "";
-            if (func.displayName) return func.displayName;
-            if (func.name) return func.name;
-            var matches = func.toString().match(/function\s+([^\(]+)/m);
-            return matches && matches[1] || "";
-        },
-
-        isNode: function isNode(obj) {
-            if (!div) return false;
-            try {
-                obj.appendChild(div);
-                obj.removeChild(div);
-            } catch (e) {
-                return false;
-            }
-            return true;
-        },
-
-        isElement: function isElement(obj) {
-            return obj && obj.nodeType === 1 && buster.isNode(obj);
-        },
-
-        isArray: function isArray(arr) {
-            return Object.prototype.toString.call(arr) == "[object Array]";
-        },
-
-        flatten: function flatten(arr) {
-            var result = [], arr = arr || [];
-            for (var i = 0, l = arr.length; i < l; ++i) {
-                result = result.concat(buster.isArray(arr[i]) ? flatten(arr[i]) : arr[i]);
-            }
-            return result;
-        },
-
-        each: function each(arr, callback) {
-            for (var i = 0, l = arr.length; i < l; ++i) {
-                callback(arr[i]);
-            }
-        },
-
-        map: function map(arr, callback) {
-            var results = [];
-            for (var i = 0, l = arr.length; i < l; ++i) {
-                results.push(callback(arr[i]));
-            }
-            return results;
-        },
-
-        parallel: function parallel(fns, callback) {
-            function cb(err, res) {
-                if (typeof callback == "function") {
-                    callback(err, res);
-                    callback = null;
-                }
-            }
-            if (fns.length == 0) { return cb(null, []); }
-            var remaining = fns.length, results = [];
-            function makeDone(num) {
-                return function done(err, result) {
-                    if (err) { return cb(err); }
-                    results[num] = result;
-                    if (--remaining == 0) { cb(null, results); }
-                };
-            }
-            for (var i = 0, l = fns.length; i < l; ++i) {
-                fns[i](makeDone(i));
-            }
-        },
-
-        series: function series(fns, callback) {
-            function cb(err, res) {
-                if (typeof callback == "function") {
-                    callback(err, res);
-                }
-            }
-            var remaining = fns.slice();
-            var results = [];
-            function callNext() {
-                if (remaining.length == 0) return cb(null, results);
-                var promise = remaining.shift()(next);
-                if (promise && typeof promise.then == "function") {
-                    promise.then(buster.partial(next, null), next);
-                }
-            }
-            function next(err, result) {
-                if (err) return cb(err);
-                results.push(result);
-                callNext();
-            }
-            callNext();
-        },
-
-        countdown: function countdown(num, done) {
-            return function () {
-                if (--num == 0) done();
-            };
-        }
-    };
-
-    if (typeof process === "object" &&
-        typeof require === "function" && typeof module === "object") {
-        var crypto = require("crypto");
-        var path = require("path");
-
-        buster.tmpFile = function (fileName) {
-            var hashed = crypto.createHash("sha1");
-            hashed.update(fileName);
-            var tmpfileName = hashed.digest("hex");
-
-            if (process.platform == "win32") {
-                return path.join(process.env["TEMP"], tmpfileName);
-            } else {
-                return path.join("/tmp", tmpfileName);
-            }
-        };
-    }
-
-    if (Array.prototype.some) {
-        buster.some = function (arr, fn, thisp) {
-            return arr.some(fn, thisp);
-        };
-    } else {
-        // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some
-        buster.some = function (arr, fun, thisp) {
-                        if (arr == null) { throw new TypeError(); }
-            arr = Object(arr);
-            var len = arr.length >>> 0;
-            if (typeof fun !== "function") { throw new TypeError(); }
-
-            for (var i = 0; i < len; i++) {
-                if (arr.hasOwnProperty(i) && fun.call(thisp, arr[i], i, arr)) {
-                    return true;
-                }
-            }
-
-            return false;
-        };
-    }
-
-    if (Array.prototype.filter) {
-        buster.filter = function (arr, fn, thisp) {
-            return arr.filter(fn, thisp);
-        };
-    } else {
-        // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter
-        buster.filter = function (fn, thisp) {
-                        if (this == null) { throw new TypeError(); }
-
-            var t = Object(this);
-            var len = t.length >>> 0;
-            if (typeof fn != "function") { throw new TypeError(); }
-
-            var res = [];
-            for (var i = 0; i < len; i++) {
-                if (i in t) {
-                    var val = t[i]; // in case fun mutates this
-                    if (fn.call(thisp, val, i, t)) { res.push(val); }
-                }
-            }
-
-            return res;
-        };
-    }
-
-    if (isNode) {
-        module.exports = buster;
-        buster.eventEmitter = require("./buster-event-emitter");
-        Object.defineProperty(buster, "defineVersionGetter", {
-            get: function () {
-                return require("./define-version-getter");
-            }
-        });
-    }
-
-    return buster.extend(B || {}, buster);
-}(setTimeout, buster));
-if (typeof buster === "undefined") {
-    var buster = {};
-}
-
-if (typeof module === "object" && typeof require === "function") {
-    buster = require("buster-core");
-}
-
-buster.format = buster.format || {};
-buster.format.excludeConstructors = ["Object", /^.$/];
-buster.format.quoteStrings = true;
-
-buster.format.ascii = (function () {
-    
-    var hasOwn = Object.prototype.hasOwnProperty;
-
-    var specialObjects = [];
-    if (typeof global != "undefined") {
-        specialObjects.push({ obj: global, value: "[object global]" });
-    }
-    if (typeof document != "undefined") {
-        specialObjects.push({ obj: document, value: "[object HTMLDocument]" });
-    }
-    if (typeof window != "undefined") {
-        specialObjects.push({ obj: window, value: "[object Window]" });
-    }
-
-    function keys(object) {
-        var k = Object.keys && Object.keys(object) || [];
-
-        if (k.length == 0) {
-            for (var prop in object) {
-                if (hasOwn.call(object, prop)) {
-                    k.push(prop);
-                }
-            }
-        }
-
-        return k.sort();
-    }
-
-    function isCircular(object, objects) {
-        if (typeof object != "object") {
-            return false;
-        }
-
-        for (var i = 0, l = objects.length; i < l; ++i) {
-            if (objects[i] === object) {
-                return true;
-            }
-        }
-
-        return false;
-    }
-
-    function ascii(object, processed, indent) {
-        if (typeof object == "string") {
-            var quote = typeof this.quoteStrings != "boolean" || this.quoteStrings;
-            return processed || quote ? '"' + object + '"' : object;
-        }
-
-        if (typeof object == "function" && !(object instanceof RegExp)) {
-            return ascii.func(object);
-        }
-
-        processed = processed || [];
-
-        if (isCircular(object, processed)) {
-            return "[Circular]";
-        }
-
-        if (Object.prototype.toString.call(object) == "[object Array]") {
-            return ascii.array.call(this, object, processed);
-        }
-
-        if (!object) {
-            return "" + object;
-        }
-
-        if (buster.isElement(object)) {
-            return ascii.element(object);
-        }
-
-        if (typeof object.toString == "function" &&
-            object.toString !== Object.prototype.toString) {
-            return object.toString();
-        }
-
-        for (var i = 0, l = specialObjects.length; i < l; i++) {
-            if (object === specialObjects[i].obj) {
-                return specialObjects[i].value;
-            }
-        }
-
-        return ascii.object.call(this, object, processed, indent);
-    }
-
-    ascii.func = function (func) {
-        return "function " + buster.functionName(func) + "() {}";
-    };
-
-    ascii.array = function (array, processed) {
-        processed = processed || [];
-        processed.push(array);
-        var pieces = [];
-
-        for (var i = 0, l = array.length; i < l; ++i) {
-            pieces.push(ascii.call(this, array[i], processed));
-        }
-
-        return "[" + pieces.join(", ") + "]";
-    };
-
-    ascii.object = function (object, processed, indent) {
-        processed = processed || [];
-        processed.push(object);
-        indent = indent || 0;
-        var pieces = [], properties = keys(object), prop, str, obj;
-        var is = "";
-        var length = 3;
-
-        for (var i = 0, l = indent; i < l; ++i) {
-            is += " ";
-        }
-
-        for (i = 0, l = properties.length; i < l; ++i) {
-            prop = properties[i];
-            obj = object[prop];
-
-            if (isCircular(obj, processed)) {
-                str = "[Circular]";
-            } else {
-                str = ascii.call(this, obj, processed, indent + 2);
-            }
-
-            str = (/\s/.test(prop) ? '"' + prop + '"' : prop) + ": " + str;
-            length += str.length;
-            pieces.push(str);
-        }
-
-        var cons = ascii.constructorName.call(this, object);
-        var prefix = cons ? "[" + cons + "] " : ""
-
-        return (length + indent) > 80 ?
-            prefix + "{\n  " + is + pieces.join(",\n  " + is) + "\n" + is + "}" :
-            prefix + "{ " + pieces.join(", ") + " }";
-    };
-
-    ascii.element = function (element) {
-        var tagName = element.tagName.toLowerCase();
-        var attrs = element.attributes, attribute, pairs = [], attrName;
-
-        for (var i = 0, l = attrs.length; i < l; ++i) {
-            attribute = attrs.item(i);
-            attrName = attribute.nodeName.toLowerCase().replace("html:", "");
-
-            if (attrName == "contenteditable" && attribute.nodeValue == "inherit") {
-                continue;
-            }
-
-            if (!!attribute.nodeValue) {
-                pairs.push(attrName + "=\"" + attribute.nodeValue + "\"");
-            }
-        }
-
-        var formatted = "<" + tagName + (pairs.length > 0 ? " " : "");
-        var content = element.innerHTML;
-
-        if (content.length > 20) {
-            content = content.substr(0, 20) + "[...]";
-        }
-
-        var res = formatted + pairs.join(" ") + ">" + content + "</" + tagName + ">";
-
-        return res.replace(/ contentEditable="inherit"/, "");
-    };
-
-    ascii.constructorName = function (object) {
-        var name = buster.functionName(object && object.constructor);
-        var excludes = this.excludeConstructors || buster.format.excludeConstructors || [];
-
-        for (var i = 0, l = excludes.length; i < l; ++i) {
-            if (typeof excludes[i] == "string" && excludes[i] == name) {
-                return "";
-            } else if (excludes[i].test && excludes[i].test(name)) {
-                return "";
-            }
-        }
-
-        return name;
-    };
-
-    return ascii;
-}());
-
-if (typeof module != "undefined") {
-    module.exports = buster.format;
-}
-/*jslint eqeqeq: false, onevar: false, forin: true, nomen: false, regexp: false, plusplus: false*/
-/*global module, require, __dirname, document*/
-/**
- * Sinon core utilities. For internal use only.
- *
- * @author Christian Johansen (christian@cjohansen.no)
- * @license BSD
- *
- * Copyright (c) 2010-2013 Christian Johansen
- */
-
-var sinon = (function (buster) {
-    var div = typeof document != "undefined" && document.createElement("div");
-    var hasOwn = Object.prototype.hasOwnProperty;
-
-    function isDOMNode(obj) {
-        var success = false;
-
-        try {
-            obj.appendChild(div);
-            success = div.parentNode == obj;
-        } catch (e) {
-            return false;
-        } finally {
-            try {
-                obj.removeChild(div);
-            } catch (e) {
-                // Remove failed, not much we can do about that
-            }
-        }
-
-        return success;
-    }
-
-    function isElement(obj) {
-        return div && obj && obj.nodeType === 1 && isDOMNode(obj);
-    }
-
-    function isFunction(obj) {
-        return typeof obj === "function" || !!(obj && obj.constructor && obj.call && obj.apply);
-    }
-
-    function mirrorProperties(target, source) {
-        for (var prop in source) {
-            if (!hasOwn.call(target, prop)) {
-                target[prop] = source[prop];
-            }
-        }
-    }
-
-    function isRestorable (obj) {
-        return typeof obj === "function" && typeof obj.restore === "function" && obj.restore.sinon;
-    }
-
-    var sinon = {
-        wrapMethod: function wrapMethod(object, property, method) {
-            if (!object) {
-                throw new TypeError("Should wrap property of object");
-            }
-
-            if (typeof method != "function") {
-                throw new TypeError("Method wrapper should be function");
-            }
-
-            var wrappedMethod = object[property];
-
-            if (!isFunction(wrappedMethod)) {
-                throw new TypeError("Attempted to wrap " + (typeof wrappedMethod) + " property " +
-                                    property + " as function");
-            }
-
-            if (wrappedMethod.restore && wrappedMethod.restore.sinon) {
-                throw new TypeError("Attempted to wrap " + property + " which is already wrapped");
-            }
-
-            if (wrappedMethod.calledBefore) {
-                var verb = !!wrappedMethod.returns ? "stubbed" : "spied on";
-                throw new TypeError("Attempted to wrap " + property + " which is already " + verb);
-            }
-
-            // IE 8 does not support hasOwnProperty on the window object.
-            var owned = hasOwn.call(object, property);
-            object[property] = method;
-            method.displayName = property;
-
-            method.restore = function () {
-                // For prototype properties try to reset by delete first.
-                // If this fails (ex: localStorage on mobile safari) then force a reset
-                // via direct assignment.
-                if (!owned) {
-                    delete object[property];
-                }
-                if (object[property] === method) {
-                    object[property] = wrappedMethod;
-                }
-            };
-
-            method.restore.sinon = true;
-            mirrorProperties(method, wrappedMethod);
-
-            return method;
-        },
-
-        extend: function extend(target) {
-            for (var i = 1, l = arguments.length; i < l; i += 1) {
-                for (var prop in arguments[i]) {
-                    if (arguments[i].hasOwnProperty(prop)) {
-                        target[prop] = arguments[i][prop];
-                    }
-
-                    // DONT ENUM bug, only care about toString
-                    if (arguments[i].hasOwnProperty("toString") &&
-                        arguments[i].toString != target.toString) {
-                        target.toString = arguments[i].toString;
-                    }
-                }
-            }
-
-            return target;
-        },
-
-        create: function create(proto) {
-            var F = function () {};
-            F.prototype = proto;
-            return new F();
-        },
-
-        deepEqual: function deepEqual(a, b) {
-            if (sinon.match && sinon.match.isMatcher(a)) {
-                return a.test(b);
-            }
-            if (typeof a != "object" || typeof b != "object") {
-                return a === b;
-            }
-
-            if (isElement(a) || isElement(b)) {
-                return a === b;
-            }
-
-            if (a === b) {
-                return true;
-            }
-
-            if ((a === null && b !== null) || (a !== null && b === null)) {
-                return false;
-            }
-
-            var aString = Object.prototype.toString.call(a);
-            if (aString != Object.prototype.toString.call(b)) {
-                return false;
-            }
-
-            if (aString == "[object Array]") {
-                if (a.length !== b.length) {
-                    return false;
-                }
-
-                for (var i = 0, l = a.length; i < l; i += 1) {
-                    if (!deepEqual(a[i], b[i])) {
-                        return false;
-                    }
-                }
-
-                return true;
-            }
-
-            if (aString == "[object Date]") {
-                return a.valueOf() === b.valueOf();
-            }
-
-            var prop, aLength = 0, bLength = 0;
-
-            for (prop in a) {
-                aLength += 1;
-
-                if (!deepEqual(a[prop], b[prop])) {
-                    return false;
-                }
-            }
-
-            for (prop in b) {
-                bLength += 1;
-            }
-
-            return aLength == bLength;
-        },
-
-        functionName: function functionName(func) {
-            var name = func.displayName || func.name;
-
-            // Use function decomposition as a last resort to get function
-            // name. Does not rely on function decomposition to work - if it
-            // doesn't debugging will be slightly less informative
-            // (i.e. toString will say 'spy' rather than 'myFunc').
-            if (!name) {
-                var matches = func.toString().match(/function ([^\s\(]+)/);
-                name = matches && matches[1];
-            }
-
-            return name;
-        },
-
-        functionToString: function toString() {
-            if (this.getCall && this.callCount) {
-                var thisValue, prop, i = this.callCount;
-
-                while (i--) {
-                    thisValue = this.getCall(i).thisValue;
-
-                    for (prop in thisValue) {
-                        if (thisValue[prop] === this) {
-                            return prop;
-                        }
-                    }
-                }
-            }
-
-            return this.displayName || "sinon fake";
-        },
-
-        getConfig: function (custom) {
-            var config = {};
-            custom = custom || {};
-            var defaults = sinon.defaultConfig;
-
-            for (var prop in defaults) {
-                if (defaults.hasOwnProperty(prop)) {
-                    config[prop] = custom.hasOwnProperty(prop) ? custom[prop] : defaults[prop];
-                }
-            }
-
-            return config;
-        },
-
-        format: function (val) {
-            return "" + val;
-        },
-
-        defaultConfig: {
-            injectIntoThis: true,
-            injectInto: null,
-            properties: ["spy", "stub", "mock", "clock", "server", "requests"],
-            useFakeTimers: true,
-            useFakeServer: true
-        },
-
-        timesInWords: function timesInWords(count) {
-            return count == 1 && "once" ||
-                count == 2 && "twice" ||
-                count == 3 && "thrice" ||
-                (count || 0) + " times";
-        },
-
-        calledInOrder: function (spies) {
-            for (var i = 1, l = spies.length; i < l; i++) {
-                if (!spies[i - 1].calledBefore(spies[i]) || !spies[i].called) {
-                    return false;
-                }
-            }
-
-            return true;
-        },
-
-        orderByFirstCall: function (spies) {
-            return spies.sort(function (a, b) {
-                // uuid, won't ever be equal
-                var aCall = a.getCall(0);
-                var bCall = b.getCall(0);
-                var aId = aCall && aCall.callId || -1;
-                var bId = bCall && bCall.callId || -1;
-
-                return aId < bId ? -1 : 1;
-            });
-        },
-
-        log: function () {},
-
-        logError: function (label, err) {
-            var msg = label + " threw exception: "
-            sinon.log(msg + "[" + err.name + "] " + err.message);
-            if (err.stack) { sinon.log(err.stack); }
-
-            setTimeout(function () {
-                err.message = msg + err.message;
-                throw err;
-            }, 0);
-        },
-
-        typeOf: function (value) {
-            if (value === null) {
-                return "null";
-            }
-            else if (value === undefined) {
-                return "undefined";
-            }
-            var string = Object.prototype.toString.call(value);
-            return string.substring(8, string.length - 1).toLowerCase();
-        },
-
-        createStubInstance: function (constructor) {
-            if (typeof constructor !== "function") {
-                throw new TypeError("The constructor should be a function.");
-            }
-            return sinon.stub(sinon.create(constructor.prototype));
-        },
-
-        restore: function (object) {
-            if (object !== null && typeof object === "object") {
-                for (var prop in object) {
-                    if (isRestorable(object[prop])) {
-                        object[prop].restore();
-                    }
-                }
-            }
-            else if (isRestorable(object)) {
-                object.restore();
-            }
-        }
-    };
-
-    var isNode = typeof module == "object" && typeof require == "function";
-
-    if (isNode) {
-        try {
-            buster = { format: require("buster-format") };
-        } catch (e) {}
-        module.exports = sinon;
-        module.exports.spy = require("./sinon/spy");
-        module.exports.stub = require("./sinon/stub");
-        module.exports.mock = require("./sinon/mock");
-        module.exports.collection = require("./sinon/collection");
-        module.exports.assert = require("./sinon/assert");
-        module.exports.sandbox = require("./sinon/sandbox");
-        module.exports.test = require("./sinon/test");
-        module.exports.testCase = require("./sinon/test_case");
-        module.exports.assert = require("./sinon/assert");
-        module.exports.match = require("./sinon/match");
-    }
-
-    if (buster) {
-        var formatter = sinon.create(buster.format);
-        formatter.quoteStrings = false;
-        sinon.format = function () {
-            return formatter.ascii.apply(formatter, arguments);
-        };
-    } else if (isNode) {
-        try {
-            var util = require("util");
-            sinon.format = function (value) {
-                return typeof value == "object" && value.toString === Object.prototype.toString ? util.inspect(value) : value;
-            };
-        } catch (e) {
-            /* Node, but no util module - would be very old, but better safe than
-             sorry */
-        }
-    }
-
-    return sinon;
-}(typeof buster == "object" && buster));
-
-/* @depend ../sinon.js */
-/*jslint eqeqeq: false, onevar: false, plusplus: false*/
-/*global module, require, sinon*/
-/**
- * Match functions
- *
- * @author Maximilian Antoni (mail@maxantoni.de)
- * @license BSD
- *
- * Copyright (c) 2012 Maximilian Antoni
- */
-
-(function (sinon) {
-    var commonJSModule = typeof module == "object" && typeof require == "function";
-
-    if (!sinon && commonJSModule) {
-        sinon = require("../sinon");
-    }
-
-    if (!sinon) {
-        return;
-    }
-
-    function assertType(value, type, name) {
-        var actual = sinon.typeOf(value);
-        if (actual !== type) {
-            throw new TypeError("Expected type of " + name + " to be " +
-                type + ", but was " + actual);
-        }
-    }
-
-    var matcher = {
-        toString: function () {
-            return this.message;
-        }
-    };
-
-    function isMatcher(object) {
-        return matcher.isPrototypeOf(object);
-    }
-
-    function matchObject(expectation, actual) {
-        if (actual === null || actual === undefined) {
-            return false;
-        }
-        for (var key in expectation) {
-            if (expectation.hasOwnProperty(key)) {
-                var exp = expectation[key];
-                var act = actual[key];
-                if (match.isMatcher(exp)) {
-                    if (!exp.test(act)) {
-                        return false;
-                    }
-                } else if (sinon.typeOf(exp) === "object") {
-                    if (!matchObject(exp, act)) {
-                        return false;
-                    }
-                } else if (!sinon.deepEqual(exp, act)) {
-                    return false;
-                }
-            }
-        }
-        return true;
-    }
-
-    matcher.or = function (m2) {
-        if (!isMatcher(m2)) {
-            throw new TypeError("Matcher expected");
-        }
-        var m1 = this;
-        var or = sinon.create(matcher);
-        or.test = function (actual) {
-            return m1.test(actual) || m2.test(actual);
-        };
-        or.message = m1.message + ".or(" + m2.message + ")";
-        return or;
-    };
-
-    matcher.and = function (m2) {
-        if (!isMatcher(m2)) {
-            throw new TypeError("Matcher expected");
-        }
-        var m1 = this;
-        var and = sinon.create(matcher);
-        and.test = function (actual) {
-            return m1.test(actual) && m2.test(actual);
-        };
-        and.message = m1.message + ".and(" + m2.message + ")";
-        return and;
-    };
-
-    var match = function (expectation, message) {
-        var m = sinon.create(matcher);
-        var type = sinon.typeOf(expectation);
-        switch (type) {
-        case "object":
-            if (typeof expectation.test === "function") {
-                m.test = function (actual) {
-                    return expectation.test(actual) === true;
-                };
-                m.message = "match(" + sinon.functionName(expectation.test) + ")";
-                return m;
-            }
-            var str = [];
-            for (var key in expectation) {
-                if (expectation.hasOwnProperty(key)) {
-                    str.push(key + ": " + expectation[key]);
-                }
-            }
-            m.test = function (actual) {
-                return matchObject(expectation, actual);
-            };
-            m.message = "match(" + str.join(", ") + ")";
-            break;
-        case "number":
-            m.test = function (actual) {
-                return expectation == actual;
-            };
-            break;
-        case "string":
-            m.test = function (actual) {
-                if (typeof actual !== "string") {
-                    return false;
-                }
-                return actual.indexOf(expectation) !== -1;
-            };
-            m.message = "match(\"" + expectation + "\")";
-            break;
-        case "regexp":
-            m.test = function (actual) {
-                if (typeof actual !== "string") {
-                    return false;
-                }
-                return expectation.test(actual);
-            };
-            break;
-        case "function":
-            m.test = expectation;
-            if (message) {
-                m.message = message;
-            } else {
-                m.message = "match(" + sinon.functionName(expectation) + ")";
-            }
-            break;
-        default:
-            m.test = function (actual) {
-              return sinon.deepEqual(expectation, actual);
-            };
-        }
-        if (!m.message) {
-            m.message = "match(" + expectation + ")";
-        }
-        return m;
-    };
-
-    match.isMatcher = isMatcher;
-
-    match.any = match(function () {
-        return true;
-    }, "any");
-
-    match.defined = match(function (actual) {
-        return actual !== null && actual !== undefined;
-    }, "defined");
-
-    match.truthy = match(function (actual) {
-        return !!actual;
-    }, "truthy");
-
-    match.falsy = match(function (actual) {
-        return !actual;
-    }, "falsy");
-
-    match.same = function (expectation) {
-        return match(function (actual) {
-            return expectation === actual;
-        }, "same(" + expectation + ")");
-    };
-
-    match.typeOf = function (type) {
-        assertType(type, "string", "type");
-        return match(function (actual) {
-            return sinon.typeOf(actual) === type;
-        }, "typeOf(\"" + type + "\")");
-    };
-
-    match.instanceOf = function (type) {
-        assertType(type, "function", "type");
-        return match(function (actual) {
-            return actual instanceof type;
-        }, "instanceOf(" + sinon.functionName(type) + ")");
-    };
-
-    function createPropertyMatcher(propertyTest, messagePrefix) {
-        return function (property, value) {
-            assertType(property, "string", "property");
-            var onlyProperty = arguments.length === 1;
-            var message = messagePrefix + "(\"" + property + "\"";
-            if (!onlyProperty) {
-                message += ", " + value;
-            }
-            message += ")";
-            return match(function (actual) {
-                if (actual === undefined || actual === null ||
-                        !propertyTest(actual, property)) {
-                    return false;
-                }
-                return onlyProperty || sinon.deepEqual(value, actual[property]);
-            }, message);
-        };
-    }
-
-    match.has = createPropertyMatcher(function (actual, property) {
-        if (typeof actual === "object") {
-            return property in actual;
-        }
-        return actual[property] !== undefined;
-    }, "has");
-
-    match.hasOwn = createPropertyMatcher(function (actual, property) {
-        return actual.hasOwnProperty(property);
-    }, "hasOwn");
-
-    match.bool = match.typeOf("boolean");
-    match.number = match.typeOf("number");
-    match.string = match.typeOf("string");
-    match.object = match.typeOf("object");
-    match.func = match.typeOf("function");
-    match.array = match.typeOf("array");
-    match.regexp = match.typeOf("regexp");
-    match.date = match.typeOf("date");
-
-    if (commonJSModule) {
-        module.exports = match;
-    } else {
-        sinon.match = match;
-    }
-}(typeof sinon == "object" && sinon || null));
-
-/**
-  * @depend ../sinon.js
-  * @depend match.js
-  */
-/*jslint eqeqeq: false, onevar: false, plusplus: false*/
-/*global module, require, sinon*/
-/**
-  * Spy calls
-  *
-  * @author Christian Johansen (christian@cjohansen.no)
-  * @author Maximilian Antoni (mail@maxantoni.de)
-  * @license BSD
-  *
-  * Copyright (c) 2010-2013 Christian Johansen
-  * Copyright (c) 2013 Maximilian Antoni
-  */
-
-var commonJSModule = typeof module == "object" && typeof require == "function";
-
-if (!this.sinon && commonJSModule) {
-    var sinon = require("../sinon");
-}
-
-(function (sinon) {
-    function throwYieldError(proxy, text, args) {
-        var msg = sinon.functionName(proxy) + text;
-        if (args.length) {
-            msg += " Received [" + slice.call(args).join(", ") + "]";
-        }
-        throw new Error(msg);
-    }
-
-    var slice = Array.prototype.slice;
-
-    var callProto = {
-        calledOn: function calledOn(thisValue) {
-            if (sinon.match && sinon.match.isMatcher(thisValue)) {
-                return thisValue.test(this.thisValue);
-            }
-            return this.thisValue === thisValue;
-        },
-
-        calledWith: function calledWith() {
-            for (var i = 0, l = arguments.length; i < l; i += 1) {
-                if (!sinon.deepEqual(arguments[i], this.args[i])) {
-                    return false;
-                }
-            }
-
-            return true;
-        },
-
-        calledWithMatch: function calledWithMatch() {
-            for (var i = 0, l = arguments.length; i < l; i += 1) {
-                var actual = this.args[i];
-                var expectation = arguments[i];
-                if (!sinon.match || !sinon.match(expectation).test(actual)) {
-                    return false;
-                }
-            }
-            return true;
-        },
-
-        calledWithExactly: function calledWithExactly() {
-            return arguments.length == this.args.length &&
-                this.calledWith.apply(this, arguments);
-        },
-
-        notCalledWith: function notCalledWith() {
-            return !this.calledWith.apply(this, arguments);
-        },
-
-        notCalledWithMatch: function notCalledWithMatch() {
-            return !this.calledWithMatch.apply(this, arguments);
-        },
-
-        returned: function returned(value) {
-            return sinon.deepEqual(value, this.returnValue);
-        },
-
-        threw: function threw(error) {
-            if (typeof error === "undefined" || !this.exception) {
-                return !!this.exception;
-            }
-
-            return this.exception === error || this.exception.name === error;
-        },
-
-        calledWithNew: function calledWithNew(thisValue) {
-            return this.thisValue instanceof this.proxy;
-        },
-
-        calledBefore: function (other) {
-            return this.callId < other.callId;
-        },
-
-        calledAfter: function (other) {
-            return this.callId > other.callId;
-        },
-
-        callArg: function (pos) {
-            this.args[pos]();
-        },
-
-        callArgOn: function (pos, thisValue) {
-            this.args[pos].apply(thisValue);
-        },
-
-        callArgWith: function (pos) {
-            this.callArgOnWith.apply(this, [pos, null].concat(slice.call(arguments, 1)));
-        },
-
-        callArgOnWith: function (pos, thisValue) {
-            var args = slice.call(arguments, 2);
-            this.args[pos].apply(thisValue, args);
-        },
-
-        "yield": function () {
-            this.yieldOn.apply(this, [null].concat(slice.call(arguments, 0)));
-        },
-
-        yieldOn: function (thisValue) {
-            var args = this.args;
-            for (var i = 0, l = args.length; i < l; ++i) {
-                if (typeof args[i] === "function") {
-                    args[i].apply(thisValue, slice.call(arguments, 1));
-                    return;
-                }
-            }
-            throwYieldError(this.proxy, " cannot yield since no callback was passed.", args);
-        },
-
-        yieldTo: function (prop) {
-            this.yieldToOn.apply(this, [prop, null].concat(slice.call(arguments, 1)));
-        },
-
-        yieldToOn: function (prop, thisValue) {
-            var args = this.args;
-            for (var i = 0, l = args.length; i < l; ++i) {
-                if (args[i] && typeof args[i][prop] === "function") {
-                    args[i][prop].apply(thisValue, slice.call(arguments, 2));
-                    return;
-                }
-            }
-            throwYieldError(this.proxy, " cannot yield to '" + prop +
-                "' since no callback was passed.", args);
-        },
-
-        toString: function () {
-            var callStr = this.proxy.toString() + "(";
-            var args = [];
-
-            for (var i = 0, l = this.args.length; i < l; ++i) {
-                args.push(sinon.format(this.args[i]));
-            }
-
-            callStr = callStr + args.join(", ") + ")";
-
-            if (typeof this.returnValue != "undefined") {
-                callStr += " => " + sinon.format(this.returnValue);
-            }
-
-            if (this.exception) {
-                callStr += " !" + this.exception.name;
-
-                if (this.exception.message) {
-                    callStr += "(" + this.exception.message + ")";
-                }
-            }
-
-            return callStr;
-        }
-    };
-
-    callProto.invokeCallback = callProto.yield;
-
-    function createSpyCall(spy, thisValue, args, returnValue, exception, id) {
-        if (typeof id !== "number") {
-            throw new TypeError("Call id is not a number");
-        }
-        var proxyCall = sinon.create(callProto);
-        proxyCall.proxy = spy;
-        proxyCall.thisValue = thisValue;
-        proxyCall.args = args;
-        proxyCall.returnValue = returnValue;
-        proxyCall.exception = exception;
-        proxyCall.callId = id;
-
-        return proxyCall;
-    };
-    createSpyCall.toString = callProto.toString; // used by mocks
-
-    sinon.spyCall = createSpyCall;
-}(typeof sinon == "object" && sinon || null));
-
-/**
-  * @depend ../sinon.js
-  */
-/*jslint eqeqeq: false, onevar: false, plusplus: false*/
-/*global module, require, sinon*/
-/**
-  * Spy functions
-  *
-  * @author Christian Johansen (christian@cjohansen.no)
-  * @license BSD
-  *
-  * Copyright (c) 2010-2013 Christian Johansen
-  */
-
-(function (sinon) {
-    var commonJSModule = typeof module == "object" && typeof require == "function";
-    var push = Array.prototype.push;
-    var slice = Array.prototype.slice;
-    var callId = 0;
-
-    function spy(object, property) {
-        if (!property && typeof object == "function") {
-            return spy.create(object);
-        }
-
-        if (!object && !property) {
-            return spy.create(function () { });
-        }
-
-        var method = object[property];
-        return sinon.wrapMethod(object, property, spy.create(method));
-    }
-
-    function matchingFake(fakes, args, strict) {
-        if (!fakes) {
-            return;
-        }
-
-        var alen = args.length;
-
-        for (var i = 0, l = fakes.length; i < l; i++) {
-            if (fakes[i].matches(args, strict)) {
-                return fakes[i];
-            }
-        }
-    }
-
-    function incrementCallCount() {
-        this.called = true;
-        this.callCount += 1;
-        this.notCalled = false;
-        this.calledOnce = this.callCount == 1;
-        this.calledTwice = this.callCount == 2;
-        this.calledThrice = this.callCount == 3;
-    }
-
-    function createCallProperties() {
-        this.firstCall = this.getCall(0);
-        this.secondCall = this.getCall(1);
-        this.thirdCall = this.getCall(2);
-        this.lastCall = this.getCall(this.callCount - 1);
-    }
-
-    var vars = "a,b,c,d,e,f,g,h,i,j,k,l";
-    function createProxy(func) {
-        // Retain the function length:
-        var p;
-        if (func.length) {
-            eval("p = (function proxy(" + vars.substring(0, func.length * 2 - 1) +
-                ") { return p.invoke(func, this, slice.call(arguments)); });");
-        }
-        else {
-            p = function proxy() {
-                return p.invoke(func, this, slice.call(arguments));
-            };
-        }
-        return p;
-    }
-
-    var uuid = 0;
-
-    // Public API
-    var spyApi = {
-        reset: function () {
-            this.called = false;
-            this.notCalled = true;
-            this.calledOnce = false;
-            this.calledTwice = false;
-            this.calledThrice = false;
-            this.callCount = 0;
-            this.firstCall = null;
-            this.secondCall = null;
-            this.thirdCall = null;
-            this.lastCall = null;
-            this.args = [];
-            this.returnValues = [];
-            this.thisValues = [];
-            this.exceptions = [];
-            this.callIds = [];
-            if (this.fakes) {
-                for (var i = 0; i < this.fakes.length; i++) {
-                    this.fakes[i].reset();
-                }
-            }
-        },
-
-        create: function create(func) {
-            var name;
-
-            if (typeof func != "function") {
-                func = function () { };
-            } else {
-                name = sinon.functionName(func);
-            }
-
-            var proxy = createProxy(func);
-
-            sinon.extend(proxy, spy);
-            delete proxy.create;
-            sinon.extend(proxy, func);
-
-            proxy.reset();
-            proxy.prototype = func.prototype;
-            proxy.displayName = name || "spy";
-            proxy.toString = sinon.functionToString;
-            proxy._create = sinon.spy.create;
-            proxy.id = "spy#" + uuid++;
-
-            return proxy;
-        },
-
-        invoke: function invoke(func, thisValue, args) {
-            var matching = matchingFake(this.fakes, args);
-            var exception, returnValue;
-
-            incrementCallCount.call(this);
-            push.call(this.thisValues, thisValue);
-            push.call(this.args, args);
-            push.call(this.callIds, callId++);
-
-            try {
-                if (matching) {
-                    returnValue = matching.invoke(func, thisValue, args);
-                } else {
-                    returnValue = (this.func || func).apply(thisValue, args);
-                }
-            } catch (e) {
-                push.call(this.returnValues, undefined);
-                exception = e;
-                throw e;
-            } finally {
-                push.call(this.exceptions, exception);
-            }
-
-            push.call(this.returnValues, returnValue);
-
-            createCallProperties.call(this);
-
-            return returnValue;
-        },
-
-        getCall: function getCall(i) {
-            if (i < 0 || i >= this.callCount) {
-                return null;
-            }
-
-            return sinon.spyCall(this, this.thisValues[i], this.args[i],
-                                    this.returnValues[i], this.exceptions[i],
-                                    this.callIds[i]);
-        },
-
-        calledBefore: function calledBefore(spyFn) {
-            if (!this.called) {
-                return false;
-            }
-
-            if (!spyFn.called) {
-                return true;
-            }
-
-            return this.callIds[0] < spyFn.callIds[spyFn.callIds.length - 1];
-        },
-
-        calledAfter: function calledAfter(spyFn) {
-            if (!this.called || !spyFn.called) {
-                return false;
-            }
-
-            return this.callIds[this.callCount - 1] > spyFn.callIds[spyFn.callCount - 1];
-        },
-
-        withArgs: function () {
-            var args = slice.call(arguments);
-
-            if (this.fakes) {
-                var match = matchingFake(this.fakes, args, true);
-
-                if (match) {
-                    return match;
-                }
-            } else {
-                this.fakes = [];
-            }
-
-            var original = this;
-            var fake = this._create();
-            fake.matchingAguments = args;
-            push.call(this.fakes, fake);
-
-            fake.withArgs = function () {
-                return original.withArgs.apply(original, arguments);
-            };
-
-            for (var i = 0; i < this.args.length; i++) {
-                if (fake.matches(this.args[i])) {
-                    incrementCallCount.call(fake);
-                    push.call(fake.thisValues, this.thisValues[i]);
-                    push.call(fake.args, this.args[i]);
-                    push.call(fake.returnValues, this.returnValues[i]);
-                    push.call(fake.exceptions, this.exceptions[i]);
-                    push.call(fake.callIds, this.callIds[i]);
-                }
-            }
-            createCallProperties.call(fake);
-
-            return fake;
-        },
-
-        matches: function (args, strict) {
-            var margs = this.matchingAguments;
-
-            if (margs.length <= args.length &&
-                sinon.deepEqual(margs, args.slice(0, margs.length))) {
-                return !strict || margs.length == args.length;
-            }
-        },
-
-        printf: function (format) {
-            var spy = this;
-            var args = slice.call(arguments, 1);
-            var formatter;
-
-            return (format || "").replace(/%(.)/g, function (match, specifyer) {
-                formatter = spyApi.formatters[specifyer];
-
-                if (typeof formatter == "function") {
-                    return formatter.call(null, spy, args);
-                } else if (!isNaN(parseInt(specifyer), 10)) {
-                    return sinon.format(args[specifyer - 1]);
-                }
-
-                return "%" + specifyer;
-            });
-        }
-    };
-
-    function delegateToCalls(method, matchAny, actual, notCalled) {
-        spyApi[method] = function () {
-            if (!this.called) {
-                if (notCalled) {
-                    return notCalled.apply(this, arguments);
-                }
-                return false;
-            }
-
-            var currentCall;
-            var matches = 0;
-
-            for (var i = 0, l = this.callCount; i < l; i += 1) {
-                currentCall = this.getCall(i);
-
-                if (currentCall[actual || method].apply(currentCall, arguments)) {
-                    matches += 1;
-
-                    if (matchAny) {
-                        return true;
-                    }
-                }
-            }
-
-            return matches === this.callCount;
-        };
-    }
-
-    delegateToCalls("calledOn", true);
-    delegateToCalls("alwaysCalledOn", false, "calledOn");
-    delegateToCalls("calledWith", true);
-    delegateToCalls("calledWithMatch", true);
-    delegateToCalls("alwaysCalledWith", false, "calledWith");
-    delegateToCalls("alwaysCalledWithMatch", false, "calledWithMatch");
-    delegateToCalls("calledWithExactly", true);
-    delegateToCalls("alwaysCalledWithExactly", false, "calledWithExactly");
-    delegateToCalls("neverCalledWith", false, "notCalledWith",
-        function () { return true; });
-    delegateToCalls("neverCalledWithMatch", false, "notCalledWithMatch",
-        function () { return true; });
-    delegateToCalls("threw", true);
-    delegateToCalls("alwaysThrew", false, "threw");
-    delegateToCalls("returned", true);
-    delegateToCalls("alwaysReturned", false, "returned");
-    delegateToCalls("calledWithNew", true);
-    delegateToCalls("alwaysCalledWithNew", false, "calledWithNew");
-    delegateToCalls("callArg", false, "callArgWith", function () {
-        throw new Error(this.toString() + " cannot call arg since it was not yet invoked.");
-    });
-    spyApi.callArgWith = spyApi.callArg;
-    delegateToCalls("callArgOn", false, "callArgOnWith", function () {
-        throw new Error(this.toString() + " cannot call arg since it was not yet invoked.");
-    });
-    spyApi.callArgOnWith = spyApi.callArgOn;
-    delegateToCalls("yield", false, "yield", function () {
-        throw new Error(this.toString() + " cannot yield since it was not yet invoked.");
-    });
-    // "invokeCallback" is an alias for "yield" since "yield" is invalid in strict mode.
-    spyApi.invokeCallback = spyApi.yield;
-    delegateToCalls("yieldOn", false, "yieldOn", function () {
-        throw new Error(this.toString() + " cannot yield since it was not yet invoked.");
-    });
-    delegateToCalls("yieldTo", false, "yieldTo", function (property) {
-        throw new Error(this.toString() + " cannot yield to '" + property +
-            "' since it was not yet invoked.");
-    });
-    delegateToCalls("yieldToOn", false, "yieldToOn", function (property) {
-        throw new Error(this.toString() + " cannot yield to '" + property +
-            "' since it was not yet invoked.");
-    });
-
-    spyApi.formatters = {
-        "c": function (spy) {
-            return sinon.timesInWords(spy.callCount);
-        },
-
-        "n": function (spy) {
-            return spy.toString();
-        },
-
-        "C": function (spy) {
-            var calls = [];
-
-            for (var i = 0, l = spy.callCount; i < l; ++i) {
-                var stringifiedCall = "    " + spy.getCall(i).toString();
-                if (/\n/.test(calls[i - 1])) {
-                    stringifiedCall = "\n" + stringifiedCall;
-                }
-                push.call(calls, stringifiedCall);
-            }
-
-            return calls.length > 0 ? "\n" + calls.join("\n") : "";
-        },
-
-        "t": function (spy) {
-            var objects = [];
-
-            for (var i = 0, l = spy.callCount; i < l; ++i) {
-                push.call(objects, sinon.format(spy.thisValues[i]));
-            }
-
-            return objects.join(", ");
-        },
-
-        "*": function (spy, args) {
-            var formatted = [];
-
-            for (var i = 0, l = args.length; i < l; ++i) {
-                push.call(formatted, sinon.format(args[i]));
-            }
-
-            return formatted.join(", ");
-        }
-    };
-
-    sinon.extend(spy, spyApi);
-
-    spy.spyCall = sinon.spyCall;
-
-    if (commonJSModule) {
-        module.exports = spy;
-    } else {
-        sinon.spy = spy;
-    }
-}(typeof sinon == "object" && sinon || null));
-
-/**
- * @depend ../sinon.js
- * @depend spy.js
- */
-/*jslint eqeqeq: false, onevar: false*/
-/*global module, require, sinon*/
-/**
- * Stub functions
- *
- * @author Christian Johansen (christian@cjohansen.no)
- * @license BSD
- *
- * Copyright (c) 2010-2013 Christian Johansen
- */
-
-(function (sinon) {
-    var commonJSModule = typeof module == "object" && typeof require == "function";
-
-    if (!sinon && commonJSModule) {
-        sinon = require("../sinon");
-    }
-
-    if (!sinon) {
-        return;
-    }
-
-    function stub(object, property, func) {
-        if (!!func && typeof func != "function") {
-            throw new TypeError("Custom stub should be function");
-        }
-
-        var wrapper;
-
-        if (func) {
-            wrapper = sinon.spy && sinon.spy.create ? sinon.spy.create(func) : func;
-        } else {
-            wrapper = stub.create();
-        }
-
-        if (!object && !property) {
-            return sinon.stub.create();
-        }
-
-        if (!property && !!object && typeof object == "object") {
-            for (var prop in object) {
-                if (typeof object[prop] === "function") {
-                    stub(object, prop);
-                }
-            }
-
-            return object;
-        }
-
-        return sinon.wrapMethod(object, property, wrapper);
-    }
-
-    function getChangingValue(stub, property) {
-        var index = stub.callCount - 1;
-        var values = stub[property];
-        var prop = index in values ? values[index] : values[values.length - 1];
-        stub[property + "Last"] = prop;
-
-        return prop;
-    }
-
-    function getCallback(stub, args) {
-        var callArgAt = getChangingValue(stub, "callArgAts");
-
-        if (callArgAt < 0) {
-            var callArgProp = getChangingValue(stub, "callArgProps");
-
-            for (var i = 0, l = args.length; i < l; ++i) {
-                if (!callArgProp && typeof args[i] == "function") {
-                    return args[i];
-                }
-
-                if (callArgProp && args[i] &&
-                    typeof args[i][callArgProp] == "function") {
-                    return args[i][callArgProp];
-                }
-            }
-
-            return null;
-        }
-
-        return args[callArgAt];
-    }
-
-    var join = Array.prototype.join;
-
-    function getCallbackError(stub, func, args) {
-        if (stub.callArgAtsLast < 0) {
-            var msg;
-
-            if (stub.callArgPropsLast) {
-                msg = sinon.functionName(stub) +
-                    " expected to yield to '" + stub.callArgPropsLast +
-                    "', but no object with such a property was passed."
-            } else {
-                msg = sinon.functionName(stub) +
-                            " expected to yield, but no callback was passed."
-            }
-
-            if (args.length > 0) {
-                msg += " Received [" + join.call(args, ", ") + "]";
-            }
-
-            return msg;
-        }
-
-        return "argument at index " + stub.callArgAtsLast + " is not a function: " + func;
-    }
-
-    var nextTick = (function () {
-        if (typeof process === "object" && typeof process.nextTick === "function") {
-            return process.nextTick;
-        } else if (typeof setImmediate === "function") {
-            return setImmediate;
-        } else {
-            return function (callback) {
-                setTimeout(callback, 0);
-            };
-        }
-    })();
-
-    function callCallback(stub, args) {
-        if (stub.callArgAts.length > 0) {
-            var func = getCallback(stub, args);
-
-            if (typeof func != "function") {
-                throw new TypeError(getCallbackError(stub, func, args));
-            }
-
-            var callbackArguments = getChangingValue(stub, "callbackArguments");
-            var callbackContext = getChangingValue(stub, "callbackContexts");
-
-            if (stub.callbackAsync) {
-                nextTick(function() {
-                    func.apply(callbackContext, callbackArguments);
-                });
-            } else {
-                func.apply(callbackContext, callbackArguments);
-            }
-        }
-    }
-
-    var uuid = 0;
-
-    sinon.extend(stub, (function () {
-        var slice = Array.prototype.slice, proto;
-
-        function throwsException(error, message) {
-            if (typeof error == "string") {
-                this.exception = new Error(message || "");
-                this.exception.name = error;
-            } else if (!error) {
-                this.exception = new Error("Error");
-            } else {
-                this.exception = error;
-            }
-
-            return this;
-        }
-
-        proto = {
-            create: function create() {
-                var functionStub = function () {
-
-                    callCallback(functionStub, arguments);
-
-                    if (functionStub.exception) {
-                        throw functionStub.exception;
-                    } else if (typeof functionStub.returnArgAt == 'number') {
-                        return arguments[functionStub.returnArgAt];
-                    } else if (functionStub.returnThis) {
-                        return this;
-                    }
-                    return functionStub.returnValue;
-                };
-
-                functionStub.id = "stub#" + uuid++;
-                var orig = functionStub;
-                functionStub = sinon.spy.create(functionStub);
-                functionStub.func = orig;
-
-                functionStub.callArgAts = [];
-                functionStub.callbackArguments = [];
-                functionStub.callbackContexts = [];
-                functionStub.callArgProps = [];
-
-                sinon.extend(functionStub, stub);
-                functionStub._create = sinon.stub.create;
-                functionStub.displayName = "stub";
-                functionStub.toString = sinon.functionToString;
-
-                return functionStub;
-            },
-
-            resetBehavior: function () {
-                var i;
-
-                this.callArgAts = [];
-                this.callbackArguments = [];
-                this.callbackContexts = [];
-                this.callArgProps = [];
-
-                delete this.returnValue;
-                delete this.returnArgAt;
-                this.returnThis = false;
-
-                if (this.fakes) {
-                    for (i = 0; i < this.fakes.length; i++) {
-                        this.fakes[i].resetBehavior();
-                    }
-                }
-            },
-
-            returns: function returns(value) {
-                this.returnValue = value;
-
-                return this;
-            },
-
-            returnsArg: function returnsArg(pos) {
-                if (typeof pos != "number") {
-                    throw new TypeError("argument index is not number");
-                }
-
-                this.returnArgAt = pos;
-
-                return this;
-            },
-
-            returnsThis: function returnsThis() {
-                this.returnThis = true;
-
-                return this;
-            },
-
-            "throws": throwsException,
-            throwsException: throwsException,
-
-            callsArg: function callsArg(pos) {
-                if (typeof pos != "number") {
-                    throw new TypeError("argument index is not number");
-                }
-
-                this.callArgAts.push(pos);
-                this.callbackArguments.push([]);
-                this.callbackContexts.push(undefined);
-                this.callArgProps.push(undefined);
-
-                return this;
-            },
-
-            callsArgOn: function callsArgOn(pos, context) {
-                if (typeof pos != "number") {
-                    throw new TypeError("argument index is not number");
-                }
-                if (typeof context != "object") {
-                    throw new TypeError("argument context is not an object");
-                }
-
-                this.callArgAts.push(pos);
-                this.callbackArguments.push([]);
-                this.callbackContexts.push(context);
-                this.callArgProps.push(undefined);
-
-                return this;
-            },
-
-            callsArgWith: function callsArgWith(pos) {
-                if (typeof pos != "number") {
-                    throw new TypeError("argument index is not number");
-                }
-
-                this.callArgAts.push(pos);
-                this.callbackArguments.push(slice.call(arguments, 1));
-                this.callbackContexts.push(undefined);
-                this.callArgProps.push(undefined);
-
-                return this;
-            },
-
-            callsArgOnWith: function callsArgWith(pos, context) {
-                if (typeof pos != "number") {
-                    throw new TypeError("argument index is not number");
-                }
-                if (typeof context != "object") {
-                    throw new TypeError("argument context is not an object");
-                }
-
-                this.callArgAts.push(pos);
-                this.callbackArguments.push(slice.call(arguments, 2));
-                this.callbackContexts.push(context);
-                this.callArgProps.push(undefined);
-
-                return this;
-            },
-
-            yields: function () {
-                this.callArgAts.push(-1);
-                this.callbackArguments.push(slice.call(arguments, 0));
-                this.callbackContexts.push(undefined);
-                this.callArgProps.push(undefined);
-
-                return this;
-            },
-
-            yieldsOn: function (context) {
-                if (typeof context != "object") {
-                    throw new TypeError("argument context is not an object");
-                }
-
-                this.callArgAts.push(-1);
-                this.callbackArguments.push(slice.call(arguments, 1));
-                this.callbackContexts.push(context);
-                this.callArgProps.push(undefined);
-
-                return this;
-            },
-
-            yieldsTo: function (prop) {
-                this.callArgAts.push(-1);
-                this.callbackArguments.push(slice.call(arguments, 1));
-                this.callbackContexts.push(undefined);
-                this.callArgProps.push(prop);
-
-                return this;
-            },
-
-            yieldsToOn: function (prop, context) {
-                if (typeof context != "object") {
-                    throw new TypeError("argument context is not an object");
-                }
-
-                this.callArgAts.push(-1);
-                this.callbackArguments.push(slice.call(arguments, 2));
-                this.callbackContexts.push(context);
-                this.callArgProps.push(prop);
-
-                return this;
-            }
-        };
-
-        // create asynchronous versions of callsArg* and yields* methods
-        for (var method in proto) {
-            // need to avoid creating anotherasync versions of the newly added async methods
-            if (proto.hasOwnProperty(method) &&
-                method.match(/^(callsArg|yields|thenYields$)/) &&
-                !method.match(/Async/)) {
-                proto[method + 'Async'] = (function (syncFnName) {
-                    return function () {
-                        this.callbackAsync = true;
-                        return this[syncFnName].apply(this, arguments);
-                    };
-                })(method);
-            }
-        }
-
-        return proto;
-
-    }()));
-
-    if (commonJSModule) {
-        module.exports = stub;
-    } else {
-        sinon.stub = stub;
-    }
-}(typeof sinon == "object" && sinon || null));
-
-/**
- * @depend ../sinon.js
- * @depend stub.js
- */
-/*jslint eqeqeq: false, onevar: false, nomen: false*/
-/*global module, require, sinon*/
-/**
- * Mock functions.
- *
- * @author Christian Johansen (christian@cjohansen.no)
- * @license BSD
- *
- * Copyright (c) 2010-2013 Christian Johansen
- */
-
-(function (sinon) {
-    var commonJSModule = typeof module == "object" && typeof require == "function";
-    var push = [].push;
-
-    if (!sinon && commonJSModule) {
-        sinon = require("../sinon");
-    }
-
-    if (!sinon) {
-        return;
-    }
-
-    function mock(object) {
-        if (!object) {
-            return sinon.expectation.create("Anonymous mock");
-        }
-
-        return mock.create(object);
-    }
-
-    sinon.mock = mock;
-
-    sinon.extend(mock, (function () {
-        function each(collection, callback) {
-            if (!collection) {
-                return;
-            }
-
-            for (var i = 0, l = collection.length; i < l; i += 1) {
-                callback(collection[i]);
-            }
-        }
-
-        return {
-            create: function create(object) {
-                if (!object) {
-                    throw new TypeError("object is null");
-                }
-
-                var mockObject = sinon.extend({}, mock);
-                mockObject.object = object;
-                delete mockObject.create;
-
-                return mockObject;
-            },
-
-            expects: function expects(method) {
-                if (!method) {
-                    throw new TypeError("method is falsy");
-                }
-
-                if (!this.expectations) {
-                    this.expectations = {};
-                    this.proxies = [];
-                }
-
-                if (!this.expectations[method]) {
-                    this.expectations[method] = [];
-                    var mockObject = this;
-
-                    sinon.wrapMethod(this.object, method, function () {
-                        return mockObject.invokeMethod(method, this, arguments);
-                    });
-
-                    push.call(this.proxies, method);
-                }
-
-                var expectation = sinon.expectation.create(method);
-                push.call(this.expectations[method], expectation);
-
-                return expectation;
-            },
-
-            restore: function restore() {
-                var object = this.object;
-
-                each(this.proxies, function (proxy) {
-                    if (typeof object[proxy].restore == "function") {
-                        object[proxy].restore();
-                    }
-                });
-            },
-
-            verify: function verify() {
-                var expectations = this.expectations || {};
-                var messages = [], met = [];
-
-                each(this.proxies, function (proxy) {
-                    each(expectations[proxy], function (expectation) {
-                        if (!expectation.met()) {
-                            push.call(messages, expectation.toString());
-                        } else {
-                            push.call(met, expectation.toString());
-                        }
-                    });
-                });
-
-                this.restore();
-
-                if (messages.length > 0) {
-                    sinon.expectation.fail(messages.concat(met).join("\n"));
-                } else {
-                    sinon.expectation.pass(messages.concat(met).join("\n"));
-                }
-
-                return true;
-            },
-
-            invokeMethod: function invokeMethod(method, thisValue, args) {
-                var expectations = this.expectations && this.expectations[method];
-                var length = expectations && expectations.length || 0, i;
-
-                for (i = 0; i < length; i += 1) {
-                    if (!expectations[i].met() &&
-                        expectations[i].allowsCall(thisValue, args)) {
-                        return expectations[i].apply(thisValue, args);
-                    }
-                }
-
-                var messages = [], available, exhausted = 0;
-
-                for (i = 0; i < length; i += 1) {
-                    if (expectations[i].allowsCall(thisValue, args)) {
-                        available = available || expectations[i];
-                    } else {
-                        exhausted += 1;
-                    }
-                    push.call(messages, "    " + expectations[i].toString());
-                }
-
-                if (exhausted === 0) {
-                    return available.apply(thisValue, args);
-                }
-
-                messages.unshift("Unexpected call: " + sinon.spyCall.toString.call({
-                    proxy: method,
-                    args: args
-                }));
-
-                sinon.expectation.fail(messages.join("\n"));
-            }
-        };
-    }()));
-
-    var times = sinon.timesInWords;
-
-    sinon.expectation = (function () {
-        var slice = Array.prototype.slice;
-        var _invoke = sinon.spy.invoke;
-
-        function callCountInWords(callCount) {
-            if (callCount == 0) {
-                return "never called";
-            } else {
-                return "called " + times(callCount);
-            }
-        }
-
-        function expectedCallCountInWords(expectation) {
-            var min = expectation.minCalls;
-            var max = expectation.maxCalls;
-
-            if (typeof min == "number" && typeof max == "number") {
-                var str = times(min);
-
-                if (min != max) {
-                    str = "at least " + str + " and at most " + times(max);
-                }
-
-                return str;
-            }
-
-            if (typeof min == "number") {
-                return "at least " + times(min);
-            }
-
-            return "at most " + times(max);
-        }
-
-        function receivedMinCalls(expectation) {
-            var hasMinLimit = typeof expectation.minCalls == "number";
-            return !hasMinLimit || expectation.callCount >= expectation.minCalls;
-        }
-
-        function receivedMaxCalls(expectation) {
-            if (typeof expectation.maxCalls != "number") {
-                return false;
-            }
-
-            return expectation.callCount == expectation.maxCalls;
-        }
-
-        return {
-            minCalls: 1,
-            maxCalls: 1,
-
-            create: function create(methodName) {
-                var expectation = sinon.extend(sinon.stub.create(), sinon.expectation);
-                delete expectation.create;
-                expectation.method = methodName;
-
-                return expectation;
-            },
-
-            invoke: function invoke(func, thisValue, args) {
-                this.verifyCallAllowed(thisValue, args);
-
-                return _invoke.apply(this, arguments);
-            },
-
-            atLeast: function atLeast(num) {
-                if (typeof num != "number") {
-                    throw new TypeError("'" + num + "' is not number");
-                }
-
-                if (!this.limitsSet) {
-                    this.maxCalls = null;
-                    this.limitsSet = true;
-                }
-
-                this.minCalls = num;
-
-                return this;
-            },
-
-            atMost: function atMost(num) {
-                if (typeof num != "number") {
-                    throw new TypeError("'" + num + "' is not number");
-                }
-
-                if (!this.limitsSet) {
-                    this.minCalls = null;
-                    this.limitsSet = true;
-                }
-
-                this.maxCalls = num;
-
-                return this;
-            },
-
-            never: function never() {
-                return this.exactly(0);
-            },
-
-            once: function once() {
-                return this.exactly(1);
-            },
-
-            twice: function twice() {
-                return this.exactly(2);
-            },
-
-            thrice: function thrice() {
-                return this.exactly(3);
-            },
-
-            exactly: function exactly(num) {
-                if (typeof num != "number") {
-                    throw new TypeError("'" + num + "' is not a number");
-                }
-
-                this.atLeast(num);
-                return this.atMost(num);
-            },
-
-            met: function met() {
-                return !this.failed && receivedMinCalls(this);
-            },
-
-            verifyCallAllowed: function verifyCallAllowed(thisValue, args) {
-                if (receivedMaxCalls(this)) {
-                    this.failed = true;
-                    sinon.expectation.fail(this.method + " already called " + times(this.maxCalls));
-                }
-
-                if ("expectedThis" in this && this.expectedThis !== thisValue) {
-                    sinon.expectation.fail(this.method + " called with " + thisValue + " as thisValue, expected " +
-                        this.expectedThis);
-                }
-
-                if (!("expectedArguments" in this)) {
-                    return;
-                }
-
-                if (!args) {
-                    sinon.expectation.fail(this.method + " received no arguments, expected " +
-                        sinon.format(this.expectedArguments));
-                }
-
-                if (args.length < this.expectedArguments.length) {
-                    sinon.expectation.fail(this.method + " received too few arguments (" + sinon.format(args) +
-                        "), expected " + sinon.format(this.expectedArguments));
-                }
-
-                if (this.expectsExactArgCount &&
-                    args.length != this.expectedArguments.length) {
-                    sinon.expectation.fail(this.method + " received too many arguments (" + sinon.format(args) +
-                        "), expected " + sinon.format(this.expectedArguments));
-                }
-
-                for (var i = 0, l = this.expectedArguments.length; i < l; i += 1) {
-                    if (!sinon.deepEqual(this.expectedArguments[i], args[i])) {
-                        sinon.expectation.fail(this.method + " received wrong arguments " + sinon.format(args) +
-                            ", expected " + sinon.format(this.expectedArguments));
-                    }
-                }
-            },
-
-            allowsCall: function allowsCall(thisValue, args) {
-                if (this.met() && receivedMaxCalls(this)) {
-                    return false;
-                }
-
-                if ("expectedThis" in this && this.expectedThis !== thisValue) {
-                    return false;
-                }
-
-                if (!("expectedArguments" in this)) {
-                    return true;
-                }
-
-                args = args || [];
-
-                if (args.length < this.expectedArguments.length) {
-                    return false;
-                }
-
-                if (this.expectsExactArgCount &&
-                    args.length != this.expectedArguments.length) {
-                    return false;
-                }
-
-                for (var i = 0, l = this.expectedArguments.length; i < l; i += 1) {
-                    if (!sinon.deepEqual(this.expectedArguments[i], args[i])) {
-                        return false;
-                    }
-                }
-
-                return true;
-            },
-
-            withArgs: function withArgs() {
-                this.expectedArguments = slice.call(arguments);
-                return this;
-            },
-
-            withExactArgs: function withExactArgs() {
-                this.withArgs.apply(this, arguments);
-                this.expectsExactArgCount = true;
-                return this;
-            },
-
-            on: function on(thisValue) {
-                this.expectedThis = thisValue;
-                return this;
-            },
-
-            toString: function () {
-                var args = (this.expectedArguments || []).slice();
-
-                if (!this.expectsExactArgCount) {
-                    push.call(args, "[...]");
-                }
-
-                var callStr = sinon.spyCall.toString.call({
-                    proxy: this.method || "anonymous mock expectation",
-                    args: args
-                });
-
-                var message = callStr.replace(", [...", "[, ...") + " " +
-                    expectedCallCountInWords(this);
-
-                if (this.met()) {
-                    return "Expectation met: " + message;
-                }
-
-                return "Expected " + message + " (" +
-                    callCountInWords(this.callCount) + ")";
-            },
-
-            verify: function verify() {
-                if (!this.met()) {
-                    sinon.expectation.fail(this.toString());
-                } else {
-                    sinon.expectation.pass(this.toString());
-                }
-
-                return true;
-            },
-
-            pass: function(message) {
-              sinon.assert.pass(message);
-            },
-            fail: function (message) {
-                var exception = new Error(message);
-                exception.name = "ExpectationError";
-
-                throw exception;
-            }
-        };
-    }());
-
-    if (commonJSModule) {
-        module.exports = mock;
-    } else {
-        sinon.mock = mock;
-    }
-}(typeof sinon == "object" && sinon || null));
-
-/**
- * @depend ../sinon.js
- * @depend stub.js
- * @depend mock.js
- */
-/*jslint eqeqeq: false, onevar: false, forin: true*/
-/*global module, require, sinon*/
-/**
- * Collections of stubs, spies and mocks.
- *
- * @author Christian Johansen (christian@cjohansen.no)
- * @license BSD
- *
- * Copyright (c) 2010-2013 Christian Johansen
- */
-
-(function (sinon) {
-    var commonJSModule = typeof module == "object" && typeof require == "function";
-    var push = [].push;
-    var hasOwnProperty = Object.prototype.hasOwnProperty;
-
-    if (!sinon && commonJSModule) {
-        sinon = require("../sinon");
-    }
-
-    if (!sinon) {
-        return;
-    }
-
-    function getFakes(fakeCollection) {
-        if (!fakeCollection.fakes) {
-            fakeCollection.fakes = [];
-        }
-
-        return fakeCollection.fakes;
-    }
-
-    function each(fakeCollection, method) {
-        var fakes = getFakes(fakeCollection);
-
-        for (var i = 0, l = fakes.length; i < l; i += 1) {
-            if (typeof fakes[i][method] == "function") {
-                fakes[i][method]();
-            }
-        }
-    }
-
-    function compact(fakeCollection) {
-        var fakes = getFakes(fakeCollection);
-        var i = 0;
-        while (i < fakes.length) {
-          fakes.splice(i, 1);
-        }
-    }
-
-    var collection = {
-        verify: function resolve() {
-            each(this, "verify");
-        },
-
-        restore: function restore() {
-            each(this, "restore");
-            compact(this);
-        },
-
-        verifyAndRestore: function verifyAndRestore() {
-            var exception;
-
-            try {
-                this.verify();
-            } catch (e) {
-                exception = e;
-            }
-
-            this.restore();
-
-            if (exception) {
-                throw exception;
-            }
-        },
-
-        add: function add(fake) {
-            push.call(getFakes(this), fake);
-            return fake;
-        },
-
-        spy: function spy() {
-            return this.add(sinon.spy.apply(sinon, arguments));
-        },
-
-        stub: function stub(object, property, value) {
-            if (property) {
-                var original = object[property];
-
-                if (typeof original != "function") {
-                    if (!hasOwnProperty.call(object, property)) {
-                        throw new TypeError("Cannot stub non-existent own property " + property);
-                    }
-
-                    object[property] = value;
-
-                    return this.add({
-                        restore: function () {
-                            object[property] = original;
-                        }
-                    });
-                }
-            }
-            if (!property && !!object && typeof object == "object") {
-                var stubbedObj = sinon.stub.apply(sinon, arguments);
-
-                for (var prop in stubbedObj) {
-                    if (typeof stubbedObj[prop] === "function") {
-                        this.add(stubbedObj[prop]);
-                    }
-                }
-
-                return stubbedObj;
-            }
-
-            return this.add(sinon.stub.apply(sinon, arguments));
-        },
-
-        mock: function mock() {
-            return this.add(sinon.mock.apply(sinon, arguments));
-        },
-
-        inject: function inject(obj) {
-            var col = this;
-
-            obj.spy = function () {
-                return col.spy.apply(col, arguments);
-            };
-
-            obj.stub = function () {
-                return col.stub.apply(col, arguments);
-            };
-
-            obj.mock = function () {
-                return col.mock.apply(col, arguments);
-            };
-
-            return obj;
-        }
-    };
-
-    if (commonJSModule) {
-        module.exports = collection;
-    } else {
-        sinon.collection = collection;
-    }
-}(typeof sinon == "object" && sinon || null));
-
-/*jslint eqeqeq: false, plusplus: false, evil: true, onevar: false, browser: true, forin: false*/
-/*global module, require, window*/
-/**
- * Fake timer API
- * setTimeout
- * setInterval
- * clearTimeout
- * clearInterval
- * tick
- * reset
- * Date
- *
- * Inspired by jsUnitMockTimeOut from JsUnit
- *
- * @author Christian Johansen (christian@cjohansen.no)
- * @license BSD
- *
- * Copyright (c) 2010-2013 Christian Johansen
- */
-
-if (typeof sinon == "undefined") {
-    var sinon = {};
-}
-
-(function (global) {
-    var id = 1;
-
-    function addTimer(args, recurring) {
-        if (args.length === 0) {
-            throw new Error("Function requires at least 1 parameter");
-        }
-
-        var toId = id++;
-        var delay = args[1] || 0;
-
-        if (!this.timeouts) {
-            this.timeouts = {};
-        }
-
-        this.timeouts[toId] = {
-            id: toId,
-            func: args[0],
-            callAt: this.now + delay,
-            invokeArgs: Array.prototype.slice.call(args, 2)
-        };
-
-        if (recurring === true) {
-            this.timeouts[toId].interval = delay;
-        }
-
-        return toId;
-    }
-
-    function parseTime(str) {
-        if (!str) {
-            return 0;
-        }
-
-        var strings = str.split(":");
-        var l = strings.length, i = l;
-        var ms = 0, parsed;
-
-        if (l > 3 || !/^(\d\d:){0,2}\d\d?$/.test(str)) {
-            throw new Error("tick only understands numbers and 'h:m:s'");
-        }
-
-        while (i--) {
-            parsed = parseInt(strings[i], 10);
-
-            if (parsed >= 60) {
-                throw new Error("Invalid time " + str);
-            }
-
-            ms += parsed * Math.pow(60, (l - i - 1));
-        }
-
-        return ms * 1000;
-    }
-
-    function createObject(object) {
-        var newObject;
-
-        if (Object.create) {
-            newObject = Object.create(object);
-        } else {
-            var F = function () {};
-            F.prototype = object;
-            newObject = new F();
-        }
-
-        newObject.Date.clock = newObject;
-        return newObject;
-    }
-
-    sinon.clock = {
-        now: 0,
-
-        create: function create(now) {
-            var clock = createObject(this);
-
-            if (typeof now == "number") {
-                clock.now = now;
-            }
-
-            if (!!now && typeof now == "object") {
-                throw new TypeError("now should be milliseconds since UNIX epoch");
-            }
-
-            return clock;
-        },
-
-        setTimeout: function setTimeout(callback, timeout) {
-            return addTimer.call(this, arguments, false);
-        },
-
-        clearTimeout: function clearTimeout(timerId) {
-            if (!this.timeouts) {
-                this.timeouts = [];
-            }
-
-            if (timerId in this.timeouts) {
-                delete this.timeouts[timerId];
-            }
-        },
-
-        setInterval: function setInterval(callback, timeout) {
-            return addTimer.call(this, arguments, true);
-        },
-
-        clearInterval: function clearInterval(timerId) {
-            this.clearTimeout(timerId);
-        },
-
-        tick: function tick(ms) {
-            ms = typeof ms == "number" ? ms : parseTime(ms);
-            var tickFrom = this.now, tickTo = this.now + ms, previous = this.now;
-            var timer = this.firstTimerInRange(tickFrom, tickTo);
-
-            var firstException;
-            while (timer && tickFrom <= tickTo) {
-                if (this.timeouts[timer.id]) {
-                    tickFrom = this.now = timer.callAt;
-                    try {
-                      this.callTimer(timer);
-                    } catch (e) {
-                      firstException = firstException || e;
-                    }
-                }
-
-                timer = this.firstTimerInRange(previous, tickTo);
-                previous = tickFrom;
-            }
-
-            this.now = tickTo;
-
-            if (firstException) {
-              throw firstException;
-            }
-
-            return this.now;
-        },
-
-        firstTimerInRange: function (from, to) {
-            var timer, smallest, originalTimer;
-
-            for (var id in this.timeouts) {
-                if (this.timeouts.hasOwnProperty(id)) {
-                    if (this.timeouts[id].callAt < from || this.timeouts[id].callAt > to) {
-                        continue;
-                    }
-
-                    if (!smallest || this.timeouts[id].callAt < smallest) {
-                        originalTimer = this.timeouts[id];
-                        smallest = this.timeouts[id].callAt;
-
-                        timer = {
-                            func: this.timeouts[id].func,
-                            callAt: this.timeouts[id].callAt,
-                            interval: this.timeouts[id].interval,
-                            id: this.timeouts[id].id,
-                            invokeArgs: this.timeouts[id].invokeArgs
-                        };
-                    }
-                }
-            }
-
-            return timer || null;
-        },
-
-        callTimer: function (timer) {
-            if (typeof timer.interval == "number") {
-                this.timeouts[timer.id].callAt += timer.interval;
-            } else {
-                delete this.timeouts[timer.id];
-            }
-
-            try {
-                if (typeof timer.func == "function") {
-                    timer.func.apply(null, timer.invokeArgs);
-                } else {
-                    eval(timer.func);
-                }
-            } catch (e) {
-              var exception = e;
-            }
-
-            if (!this.timeouts[timer.id]) {
-                if (exception) {
-                  throw exception;
-                }
-                return;
-            }
-
-            if (exception) {
-              throw exception;
-            }
-        },
-
-        reset: function reset() {
-            this.timeouts = {};
-        },
-
-        Date: (function () {
-            var NativeDate = Date;
-
-            function ClockDate(year, month, date, hour, 

<TRUNCATED>

[61/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/unorm.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/unorm.h b/src/apps/couch_collate/platform/osx/icu/unicode/unorm.h
new file mode 100644
index 0000000..c22b808
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/unorm.h
@@ -0,0 +1,576 @@
+/*
+*******************************************************************************
+* Copyright (c) 1996-2007, International Business Machines Corporation
+*               and others. All Rights Reserved.
+*******************************************************************************
+* File unorm.h
+*
+* Created by: Vladimir Weinstein 12052000
+*
+* Modification history :
+*
+* Date        Name        Description
+* 02/01/01    synwee      Added normalization quickcheck enum and method.
+*/
+#ifndef UNORM_H
+#define UNORM_H
+
+#include "unicode/utypes.h"
+
+#if !UCONFIG_NO_NORMALIZATION
+
+#include "unicode/uiter.h"
+
+/**
+ * \file
+ * \brief C API: Unicode Normalization 
+ *
+ * <h2>Unicode normalization API</h2>
+ *
+ * <code>unorm_normalize</code> transforms Unicode text into an equivalent composed or
+ * decomposed form, allowing for easier sorting and searching of text.
+ * <code>unorm_normalize</code> supports the standard normalization forms described in
+ * <a href="http://www.unicode.org/unicode/reports/tr15/" target="unicode">
+ * Unicode Standard Annex #15: Unicode Normalization Forms</a>.
+ *
+ * Characters with accents or other adornments can be encoded in
+ * several different ways in Unicode.  For example, take the character A-acute.
+ * In Unicode, this can be encoded as a single character (the
+ * "composed" form):
+ *
+ * \code
+ *      00C1    LATIN CAPITAL LETTER A WITH ACUTE
+ * \endcode
+ *
+ * or as two separate characters (the "decomposed" form):
+ *
+ * \code
+ *      0041    LATIN CAPITAL LETTER A
+ *      0301    COMBINING ACUTE ACCENT
+ * \endcode
+ *
+ * To a user of your program, however, both of these sequences should be
+ * treated as the same "user-level" character "A with acute accent".  When you are searching or
+ * comparing text, you must ensure that these two sequences are treated 
+ * equivalently.  In addition, you must handle characters with more than one
+ * accent.  Sometimes the order of a character's combining accents is
+ * significant, while in other cases accent sequences in different orders are
+ * really equivalent.
+ *
+ * Similarly, the string "ffi" can be encoded as three separate letters:
+ *
+ * \code
+ *      0066    LATIN SMALL LETTER F
+ *      0066    LATIN SMALL LETTER F
+ *      0069    LATIN SMALL LETTER I
+ * \endcode
+ *
+ * or as the single character
+ *
+ * \code
+ *      FB03    LATIN SMALL LIGATURE FFI
+ * \endcode
+ *
+ * The ffi ligature is not a distinct semantic character, and strictly speaking
+ * it shouldn't be in Unicode at all, but it was included for compatibility
+ * with existing character sets that already provided it.  The Unicode standard
+ * identifies such characters by giving them "compatibility" decompositions
+ * into the corresponding semantic characters.  When sorting and searching, you
+ * will often want to use these mappings.
+ *
+ * <code>unorm_normalize</code> helps solve these problems by transforming text into the
+ * canonical composed and decomposed forms as shown in the first example above.  
+ * In addition, you can have it perform compatibility decompositions so that 
+ * you can treat compatibility characters the same as their equivalents.
+ * Finally, <code>unorm_normalize</code> rearranges accents into the proper canonical
+ * order, so that you do not have to worry about accent rearrangement on your
+ * own.
+ *
+ * Form FCD, "Fast C or D", is also designed for collation.
+ * It allows to work on strings that are not necessarily normalized
+ * with an algorithm (like in collation) that works under "canonical closure", i.e., it treats precomposed
+ * characters and their decomposed equivalents the same.
+ *
+ * It is not a normalization form because it does not provide for uniqueness of representation. Multiple strings
+ * may be canonically equivalent (their NFDs are identical) and may all conform to FCD without being identical
+ * themselves.
+ *
+ * The form is defined such that the "raw decomposition", the recursive canonical decomposition of each character,
+ * results in a string that is canonically ordered. This means that precomposed characters are allowed for as long
+ * as their decompositions do not need canonical reordering.
+ *
+ * Its advantage for a process like collation is that all NFD and most NFC texts - and many unnormalized texts -
+ * already conform to FCD and do not need to be normalized (NFD) for such a process. The FCD quick check will
+ * return UNORM_YES for most strings in practice.
+ *
+ * unorm_normalize(UNORM_FCD) may be implemented with UNORM_NFD.
+ *
+ * For more details on FCD see the collation design document:
+ * http://source.icu-project.org/repos/icu/icuhtml/trunk/design/collation/ICU_collation_design.htm
+ *
+ * ICU collation performs either NFD or FCD normalization automatically if normalization
+ * is turned on for the collator object.
+ * Beyond collation and string search, normalized strings may be useful for string equivalence comparisons,
+ * transliteration/transcription, unique representations, etc.
+ *
+ * The W3C generally recommends to exchange texts in NFC.
+ * Note also that most legacy character encodings use only precomposed forms and often do not
+ * encode any combining marks by themselves. For conversion to such character encodings the
+ * Unicode text needs to be normalized to NFC.
+ * For more usage examples, see the Unicode Standard Annex.
+ */
+
+/**
+ * Constants for normalization modes.
+ * @stable ICU 2.0
+ */
+typedef enum {
+  /** No decomposition/composition. @stable ICU 2.0 */
+  UNORM_NONE = 1, 
+  /** Canonical decomposition. @stable ICU 2.0 */
+  UNORM_NFD = 2,
+  /** Compatibility decomposition. @stable ICU 2.0 */
+  UNORM_NFKD = 3,
+  /** Canonical decomposition followed by canonical composition. @stable ICU 2.0 */
+  UNORM_NFC = 4,
+  /** Default normalization. @stable ICU 2.0 */
+  UNORM_DEFAULT = UNORM_NFC, 
+  /** Compatibility decomposition followed by canonical composition. @stable ICU 2.0 */
+  UNORM_NFKC =5,
+  /** "Fast C or D" form. @stable ICU 2.0 */
+  UNORM_FCD = 6,
+
+  /** One more than the highest normalization mode constant. @stable ICU 2.0 */
+  UNORM_MODE_COUNT
+} UNormalizationMode;
+
+/**
+ * Constants for options flags for normalization.
+ * Use 0 for default options,
+ * including normalization according to the Unicode version
+ * that is currently supported by ICU (see u_getUnicodeVersion).
+ * @stable ICU 2.6
+ */
+enum {
+    /**
+     * Options bit set value to select Unicode 3.2 normalization
+     * (except NormalizationCorrections).
+     * At most one Unicode version can be selected at a time.
+     * @stable ICU 2.6
+     */
+    UNORM_UNICODE_3_2=0x20
+};
+
+/**
+ * Lowest-order bit number of unorm_compare() options bits corresponding to
+ * normalization options bits.
+ *
+ * The options parameter for unorm_compare() uses most bits for
+ * itself and for various comparison and folding flags.
+ * The most significant bits, however, are shifted down and passed on
+ * to the normalization implementation.
+ * (That is, from unorm_compare(..., options, ...),
+ * options>>UNORM_COMPARE_NORM_OPTIONS_SHIFT will be passed on to the
+ * internal normalization functions.)
+ *
+ * @see unorm_compare
+ * @stable ICU 2.6
+ */
+#define UNORM_COMPARE_NORM_OPTIONS_SHIFT 20
+
+/**
+ * Normalize a string.
+ * The string will be normalized according the specified normalization mode
+ * and options.
+ * The source and result buffers must not be the same, nor overlap.
+ *
+ * @param source The string to normalize.
+ * @param sourceLength The length of source, or -1 if NUL-terminated.
+ * @param mode The normalization mode; one of UNORM_NONE, 
+ *             UNORM_NFD, UNORM_NFC, UNORM_NFKC, UNORM_NFKD, UNORM_DEFAULT.
+ * @param options The normalization options, ORed together (0 for no options).
+ * @param result A pointer to a buffer to receive the result string.
+ *               The result string is NUL-terminated if possible.
+ * @param resultLength The maximum size of result.
+ * @param status A pointer to a UErrorCode to receive any errors.
+ * @return The total buffer size needed; if greater than resultLength,
+ *         the output was truncated, and the error code is set to U_BUFFER_OVERFLOW_ERROR.
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2 
+unorm_normalize(const UChar *source, int32_t sourceLength,
+                UNormalizationMode mode, int32_t options,
+                UChar *result, int32_t resultLength,
+                UErrorCode *status);
+#endif
+/**
+ * Result values for unorm_quickCheck().
+ * For details see Unicode Technical Report 15.
+ * @stable ICU 2.0
+ */
+typedef enum UNormalizationCheckResult {
+  /** 
+   * Indicates that string is not in the normalized format
+   */
+  UNORM_NO,
+  /** 
+   * Indicates that string is in the normalized format
+   */
+  UNORM_YES,
+  /** 
+   * Indicates that string cannot be determined if it is in the normalized 
+   * format without further thorough checks.
+   */
+  UNORM_MAYBE
+} UNormalizationCheckResult;
+#if !UCONFIG_NO_NORMALIZATION
+/**
+ * Performing quick check on a string, to quickly determine if the string is 
+ * in a particular normalization format.
+ * Three types of result can be returned UNORM_YES, UNORM_NO or
+ * UNORM_MAYBE. Result UNORM_YES indicates that the argument
+ * string is in the desired normalized format, UNORM_NO determines that
+ * argument string is not in the desired normalized format. A 
+ * UNORM_MAYBE result indicates that a more thorough check is required, 
+ * the user may have to put the string in its normalized form and compare the 
+ * results.
+ *
+ * @param source       string for determining if it is in a normalized format
+ * @param sourcelength length of source to test, or -1 if NUL-terminated
+ * @param mode         which normalization form to test for
+ * @param status       a pointer to a UErrorCode to receive any errors
+ * @return UNORM_YES, UNORM_NO or UNORM_MAYBE
+ *
+ * @see unorm_isNormalized
+ * @stable ICU 2.0
+ */
+U_STABLE UNormalizationCheckResult U_EXPORT2
+unorm_quickCheck(const UChar *source, int32_t sourcelength,
+                 UNormalizationMode mode,
+                 UErrorCode *status);
+
+/**
+ * Performing quick check on a string; same as unorm_quickCheck but
+ * takes an extra options parameter like most normalization functions.
+ *
+ * @param src        String that is to be tested if it is in a normalization format.
+ * @param srcLength  Length of source to test, or -1 if NUL-terminated.
+ * @param mode       Which normalization form to test for.
+ * @param options    The normalization options, ORed together (0 for no options).
+ * @param pErrorCode ICU error code in/out parameter.
+ *                   Must fulfill U_SUCCESS before the function call.
+ * @return UNORM_YES, UNORM_NO or UNORM_MAYBE
+ *
+ * @see unorm_quickCheck
+ * @see unorm_isNormalized
+ * @stable ICU 2.6
+ */
+U_STABLE UNormalizationCheckResult U_EXPORT2
+unorm_quickCheckWithOptions(const UChar *src, int32_t srcLength, 
+                            UNormalizationMode mode, int32_t options,
+                            UErrorCode *pErrorCode);
+
+/**
+ * Test if a string is in a given normalization form.
+ * This is semantically equivalent to source.equals(normalize(source, mode)) .
+ *
+ * Unlike unorm_quickCheck(), this function returns a definitive result,
+ * never a "maybe".
+ * For NFD, NFKD, and FCD, both functions work exactly the same.
+ * For NFC and NFKC where quickCheck may return "maybe", this function will
+ * perform further tests to arrive at a TRUE/FALSE result.
+ *
+ * @param src        String that is to be tested if it is in a normalization format.
+ * @param srcLength  Length of source to test, or -1 if NUL-terminated.
+ * @param mode       Which normalization form to test for.
+ * @param pErrorCode ICU error code in/out parameter.
+ *                   Must fulfill U_SUCCESS before the function call.
+ * @return Boolean value indicating whether the source string is in the
+ *         "mode" normalization form.
+ *
+ * @see unorm_quickCheck
+ * @stable ICU 2.2
+ */
+U_STABLE UBool U_EXPORT2
+unorm_isNormalized(const UChar *src, int32_t srcLength,
+                   UNormalizationMode mode,
+                   UErrorCode *pErrorCode);
+
+/**
+ * Test if a string is in a given normalization form; same as unorm_isNormalized but
+ * takes an extra options parameter like most normalization functions.
+ *
+ * @param src        String that is to be tested if it is in a normalization format.
+ * @param srcLength  Length of source to test, or -1 if NUL-terminated.
+ * @param mode       Which normalization form to test for.
+ * @param options    The normalization options, ORed together (0 for no options).
+ * @param pErrorCode ICU error code in/out parameter.
+ *                   Must fulfill U_SUCCESS before the function call.
+ * @return Boolean value indicating whether the source string is in the
+ *         "mode/options" normalization form.
+ *
+ * @see unorm_quickCheck
+ * @see unorm_isNormalized
+ * @stable ICU 2.6
+ */
+U_STABLE UBool U_EXPORT2
+unorm_isNormalizedWithOptions(const UChar *src, int32_t srcLength,
+                              UNormalizationMode mode, int32_t options,
+                              UErrorCode *pErrorCode);
+
+/**
+ * Iterative normalization forward.
+ * This function (together with unorm_previous) is somewhat
+ * similar to the C++ Normalizer class (see its non-static functions).
+ *
+ * Iterative normalization is useful when only a small portion of a longer
+ * string/text needs to be processed.
+ *
+ * For example, the likelihood may be high that processing the first 10% of some
+ * text will be sufficient to find certain data.
+ * Another example: When one wants to concatenate two normalized strings and get a
+ * normalized result, it is much more efficient to normalize just a small part of
+ * the result around the concatenation place instead of re-normalizing everything.
+ *
+ * The input text is an instance of the C character iteration API UCharIterator.
+ * It may wrap around a simple string, a CharacterIterator, a Replaceable, or any
+ * other kind of text object.
+ *
+ * If a buffer overflow occurs, then the caller needs to reset the iterator to the
+ * old index and call the function again with a larger buffer - if the caller cares
+ * for the actual output.
+ * Regardless of the output buffer, the iterator will always be moved to the next
+ * normalization boundary.
+ *
+ * This function (like unorm_previous) serves two purposes:
+ *
+ * 1) To find the next boundary so that the normalization of the part of the text
+ * from the current position to that boundary does not affect and is not affected
+ * by the part of the text beyond that boundary.
+ *
+ * 2) To normalize the text up to the boundary.
+ *
+ * The second step is optional, per the doNormalize parameter.
+ * It is omitted for operations like string concatenation, where the two adjacent
+ * string ends need to be normalized together.
+ * In such a case, the output buffer will just contain a copy of the text up to the
+ * boundary.
+ *
+ * pNeededToNormalize is an output-only parameter. Its output value is only defined
+ * if normalization was requested (doNormalize) and successful (especially, no
+ * buffer overflow).
+ * It is useful for operations like a normalizing transliterator, where one would
+ * not want to replace a piece of text if it is not modified.
+ *
+ * If doNormalize==TRUE and pNeededToNormalize!=NULL then *pNeeded... is set TRUE
+ * if the normalization was necessary.
+ *
+ * If doNormalize==FALSE then *pNeededToNormalize will be set to FALSE.
+ *
+ * If the buffer overflows, then *pNeededToNormalize will be undefined;
+ * essentially, whenever U_FAILURE is true (like in buffer overflows), this result
+ * will be undefined.
+ *
+ * @param src The input text in the form of a C character iterator.
+ * @param dest The output buffer; can be NULL if destCapacity==0 for pure preflighting.
+ * @param destCapacity The number of UChars that fit into dest.
+ * @param mode The normalization mode.
+ * @param options The normalization options, ORed together (0 for no options).
+ * @param doNormalize Indicates if the source text up to the next boundary
+ *                    is to be normalized (TRUE) or just copied (FALSE).
+ * @param pNeededToNormalize Output flag indicating if the normalization resulted in
+ *                           different text from the input.
+ *                           Not defined if an error occurs including buffer overflow.
+ *                           Always FALSE if !doNormalize.
+ * @param pErrorCode ICU error code in/out parameter.
+ *                   Must fulfill U_SUCCESS before the function call.
+ * @return Length of output (number of UChars) when successful or buffer overflow.
+ *
+ * @see unorm_previous
+ * @see unorm_normalize
+ *
+ * @stable ICU 2.1
+ */
+U_STABLE int32_t U_EXPORT2
+unorm_next(UCharIterator *src,
+           UChar *dest, int32_t destCapacity,
+           UNormalizationMode mode, int32_t options,
+           UBool doNormalize, UBool *pNeededToNormalize,
+           UErrorCode *pErrorCode);
+
+/**
+ * Iterative normalization backward.
+ * This function (together with unorm_next) is somewhat
+ * similar to the C++ Normalizer class (see its non-static functions).
+ * For all details see unorm_next.
+ *
+ * @param src The input text in the form of a C character iterator.
+ * @param dest The output buffer; can be NULL if destCapacity==0 for pure preflighting.
+ * @param destCapacity The number of UChars that fit into dest.
+ * @param mode The normalization mode.
+ * @param options The normalization options, ORed together (0 for no options).
+ * @param doNormalize Indicates if the source text up to the next boundary
+ *                    is to be normalized (TRUE) or just copied (FALSE).
+ * @param pNeededToNormalize Output flag indicating if the normalization resulted in
+ *                           different text from the input.
+ *                           Not defined if an error occurs including buffer overflow.
+ *                           Always FALSE if !doNormalize.
+ * @param pErrorCode ICU error code in/out parameter.
+ *                   Must fulfill U_SUCCESS before the function call.
+ * @return Length of output (number of UChars) when successful or buffer overflow.
+ *
+ * @see unorm_next
+ * @see unorm_normalize
+ *
+ * @stable ICU 2.1
+ */
+U_STABLE int32_t U_EXPORT2
+unorm_previous(UCharIterator *src,
+               UChar *dest, int32_t destCapacity,
+               UNormalizationMode mode, int32_t options,
+               UBool doNormalize, UBool *pNeededToNormalize,
+               UErrorCode *pErrorCode);
+
+/**
+ * Concatenate normalized strings, making sure that the result is normalized as well.
+ *
+ * If both the left and the right strings are in
+ * the normalization form according to "mode/options",
+ * then the result will be
+ *
+ * \code
+ *     dest=normalize(left+right, mode, options)
+ * \endcode
+ *
+ * With the input strings already being normalized,
+ * this function will use unorm_next() and unorm_previous()
+ * to find the adjacent end pieces of the input strings.
+ * Only the concatenation of these end pieces will be normalized and
+ * then concatenated with the remaining parts of the input strings.
+ *
+ * It is allowed to have dest==left to avoid copying the entire left string.
+ *
+ * @param left Left source string, may be same as dest.
+ * @param leftLength Length of left source string, or -1 if NUL-terminated.
+ * @param right Right source string. Must not be the same as dest, nor overlap.
+ * @param rightLength Length of right source string, or -1 if NUL-terminated.
+ * @param dest The output buffer; can be NULL if destCapacity==0 for pure preflighting.
+ * @param destCapacity The number of UChars that fit into dest.
+ * @param mode The normalization mode.
+ * @param options The normalization options, ORed together (0 for no options).
+ * @param pErrorCode ICU error code in/out parameter.
+ *                   Must fulfill U_SUCCESS before the function call.
+ * @return Length of output (number of UChars) when successful or buffer overflow.
+ *
+ * @see unorm_normalize
+ * @see unorm_next
+ * @see unorm_previous
+ *
+ * @stable ICU 2.1
+ */
+U_STABLE int32_t U_EXPORT2
+unorm_concatenate(const UChar *left, int32_t leftLength,
+                  const UChar *right, int32_t rightLength,
+                  UChar *dest, int32_t destCapacity,
+                  UNormalizationMode mode, int32_t options,
+                  UErrorCode *pErrorCode);
+
+/**
+ * Option bit for unorm_compare:
+ * Both input strings are assumed to fulfill FCD conditions.
+ * @stable ICU 2.2
+ */
+#define UNORM_INPUT_IS_FCD          0x20000
+
+/**
+ * Option bit for unorm_compare:
+ * Perform case-insensitive comparison.
+ * @stable ICU 2.2
+ */
+#define U_COMPARE_IGNORE_CASE       0x10000
+
+#ifndef U_COMPARE_CODE_POINT_ORDER
+/* see also unistr.h and ustring.h */
+/**
+ * Option bit for u_strCaseCompare, u_strcasecmp, unorm_compare, etc:
+ * Compare strings in code point order instead of code unit order.
+ * @stable ICU 2.2
+ */
+#define U_COMPARE_CODE_POINT_ORDER  0x8000
+#endif
+
+/**
+ * Compare two strings for canonical equivalence.
+ * Further options include case-insensitive comparison and
+ * code point order (as opposed to code unit order).
+ *
+ * Canonical equivalence between two strings is defined as their normalized
+ * forms (NFD or NFC) being identical.
+ * This function compares strings incrementally instead of normalizing
+ * (and optionally case-folding) both strings entirely,
+ * improving performance significantly.
+ *
+ * Bulk normalization is only necessary if the strings do not fulfill the FCD
+ * conditions. Only in this case, and only if the strings are relatively long,
+ * is memory allocated temporarily.
+ * For FCD strings and short non-FCD strings there is no memory allocation.
+ *
+ * Semantically, this is equivalent to
+ *   strcmp[CodePointOrder](NFD(foldCase(NFD(s1))), NFD(foldCase(NFD(s2))))
+ * where code point order and foldCase are all optional.
+ *
+ * UAX 21 2.5 Caseless Matching specifies that for a canonical caseless match
+ * the case folding must be performed first, then the normalization.
+ *
+ * @param s1 First source string.
+ * @param length1 Length of first source string, or -1 if NUL-terminated.
+ *
+ * @param s2 Second source string.
+ * @param length2 Length of second source string, or -1 if NUL-terminated.
+ *
+ * @param options A bit set of options:
+ *   - U_FOLD_CASE_DEFAULT or 0 is used for default options:
+ *     Case-sensitive comparison in code unit order, and the input strings
+ *     are quick-checked for FCD.
+ *
+ *   - UNORM_INPUT_IS_FCD
+ *     Set if the caller knows that both s1 and s2 fulfill the FCD conditions.
+ *     If not set, the function will quickCheck for FCD
+ *     and normalize if necessary.
+ *
+ *   - U_COMPARE_CODE_POINT_ORDER
+ *     Set to choose code point order instead of code unit order
+ *     (see u_strCompare for details).
+ *
+ *   - U_COMPARE_IGNORE_CASE
+ *     Set to compare strings case-insensitively using case folding,
+ *     instead of case-sensitively.
+ *     If set, then the following case folding options are used.
+ *
+ *   - Options as used with case-insensitive comparisons, currently:
+ *
+ *   - U_FOLD_CASE_EXCLUDE_SPECIAL_I
+ *    (see u_strCaseCompare for details)
+ *
+ *   - regular normalization options shifted left by UNORM_COMPARE_NORM_OPTIONS_SHIFT
+ *
+ * @param pErrorCode ICU error code in/out parameter.
+ *                   Must fulfill U_SUCCESS before the function call.
+ * @return <0 or 0 or >0 as usual for string comparisons
+ *
+ * @see unorm_normalize
+ * @see UNORM_FCD
+ * @see u_strCompare
+ * @see u_strCaseCompare
+ *
+ * @stable ICU 2.2
+ */
+U_STABLE int32_t U_EXPORT2
+unorm_compare(const UChar *s1, int32_t length1,
+              const UChar *s2, int32_t length2,
+              uint32_t options,
+              UErrorCode *pErrorCode);
+
+#endif /* #if !UCONFIG_NO_NORMALIZATION */
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/unum.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/unum.h b/src/apps/couch_collate/platform/osx/icu/unicode/unum.h
new file mode 100644
index 0000000..c5df2bb
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/unum.h
@@ -0,0 +1,869 @@
+/*
+*******************************************************************************
+* Copyright (C) 1997-2008, International Business Machines Corporation and others.
+* All Rights Reserved.
+* Modification History:
+*
+*   Date        Name        Description
+*   06/24/99    helena      Integrated Alan's NF enhancements and Java2 bug fixes
+*******************************************************************************
+*/
+
+#ifndef _UNUM
+#define _UNUM
+
+#include "unicode/utypes.h"
+
+#if !UCONFIG_NO_FORMATTING
+
+#include "unicode/uloc.h"
+#include "unicode/umisc.h"
+#include "unicode/parseerr.h"
+/**
+ * \file
+ * \brief C API: NumberFormat
+ *
+ * <h2> Number Format C API </h2>
+ *
+ * Number Format C API  Provides functions for
+ * formatting and parsing a number.  Also provides methods for
+ * determining which locales have number formats, and what their names
+ * are.
+ * <P>
+ * UNumberFormat helps you to format and parse numbers for any locale.
+ * Your code can be completely independent of the locale conventions
+ * for decimal points, thousands-separators, or even the particular
+ * decimal digits used, or whether the number format is even decimal.
+ * There are different number format styles like decimal, currency,
+ * percent and spellout.
+ * <P>
+ * To format a number for the current Locale, use one of the static
+ * factory methods:
+ * <pre>
+ * \code
+ *    UChar myString[20];
+ *    double myNumber = 7.0;
+ *    UErrorCode status = U_ZERO_ERROR;
+ *    UNumberFormat* nf = unum_open(UNUM_DEFAULT, NULL, -1, NULL, NULL, &status);
+ *    unum_formatDouble(nf, myNumber, myString, 20, NULL, &status);
+ *    printf(" Example 1: %s\n", austrdup(myString) ); //austrdup( a function used to convert UChar* to char*)
+ * \endcode
+ * </pre>
+ * If you are formatting multiple numbers, it is more efficient to get
+ * the format and use it multiple times so that the system doesn't
+ * have to fetch the information about the local language and country
+ * conventions multiple times.
+ * <pre>
+ * \code
+ * uint32_t i, resultlength, reslenneeded;
+ * UErrorCode status = U_ZERO_ERROR;
+ * UFieldPosition pos;
+ * uint32_t a[] = { 123, 3333, -1234567 };
+ * const uint32_t a_len = sizeof(a) / sizeof(a[0]);
+ * UNumberFormat* nf;
+ * UChar* result = NULL;
+ *
+ * nf = unum_open(UNUM_DEFAULT, NULL, -1, NULL, NULL, &status);
+ * for (i = 0; i < a_len; i++) {
+ *    resultlength=0;
+ *    reslenneeded=unum_format(nf, a[i], NULL, resultlength, &pos, &status);
+ *    result = NULL;
+ *    if(status==U_BUFFER_OVERFLOW_ERROR){
+ *       status=U_ZERO_ERROR;
+ *       resultlength=reslenneeded+1;
+ *       result=(UChar*)malloc(sizeof(UChar) * resultlength);
+ *       unum_format(nf, a[i], result, resultlength, &pos, &status);
+ *    }
+ *    printf( " Example 2: %s\n", austrdup(result));
+ *    free(result);
+ * }
+ * \endcode
+ * </pre>
+ * To format a number for a different Locale, specify it in the
+ * call to unum_open().
+ * <pre>
+ * \code
+ *     UNumberFormat* nf = unum_open(UNUM_DEFAULT, NULL, -1, "fr_FR", NULL, &success)
+ * \endcode
+ * </pre>
+ * You can use a NumberFormat API unum_parse() to parse.
+ * <pre>
+ * \code
+ *    UErrorCode status = U_ZERO_ERROR;
+ *    int32_t pos=0;
+ *    int32_t num;
+ *    num = unum_parse(nf, str, u_strlen(str), &pos, &status);
+ * \endcode
+ * </pre>
+ * Use UNUM_DECIMAL to get the normal number format for that country.
+ * There are other static options available.  Use UNUM_CURRENCY
+ * to get the currency number format for that country.  Use UNUM_PERCENT
+ * to get a format for displaying percentages. With this format, a
+ * fraction from 0.53 is displayed as 53%.
+ * <P>
+ * Use a pattern to create either a DecimalFormat or a RuleBasedNumberFormat
+ * formatter.  The pattern must conform to the syntax defined for those
+ * formatters.
+ * <P>
+ * You can also control the display of numbers with such function as
+ * unum_getAttribues() and unum_setAtributes(), which let you set the
+ * miminum fraction digits, grouping, etc.
+ * @see UNumberFormatAttributes for more details
+ * <P>
+ * You can also use forms of the parse and format methods with
+ * ParsePosition and UFieldPosition to allow you to:
+ * <ul type=round>
+ *   <li>(a) progressively parse through pieces of a string.
+ *   <li>(b) align the decimal point and other areas.
+ * </ul>
+ * <p>
+ * It is also possible to change or set the symbols used for a particular
+ * locale like the currency symbol, the grouping seperator , monetary seperator
+ * etc by making use of functions unum_setSymbols() and unum_getSymbols().
+ */
+
+/** A number formatter.
+ *  For usage in C programs.
+ *  @stable ICU 2.0
+ */
+typedef void* UNumberFormat;
+
+/** The possible number format styles. 
+ *  @stable ICU 2.0
+ */
+typedef enum UNumberFormatStyle {
+    /**
+     * Decimal format defined by pattern 
+     * @stable ICU 3.0
+     */
+    UNUM_PATTERN_DECIMAL=0,
+    /** Decimal format */
+    UNUM_DECIMAL=1,
+    /** Currency format */
+    UNUM_CURRENCY,
+    /** Percent format */
+    UNUM_PERCENT,
+    /** Scientific format */
+    UNUM_SCIENTIFIC,
+    /** Spellout rule-based format */
+    UNUM_SPELLOUT,
+    /** 
+     * Ordinal rule-based format 
+     * @stable ICU 3.0
+     */
+    UNUM_ORDINAL,
+    /** 
+     * Duration rule-based format 
+     * @stable ICU 3.0
+     */
+    UNUM_DURATION,
+    /** 
+     * Rule-based format defined by pattern 
+     * @stable ICU 3.0
+     */
+    UNUM_PATTERN_RULEBASED,
+    /** Default format */
+    UNUM_DEFAULT = UNUM_DECIMAL,
+    /** (Alias for UNUM_PATTERN_DECIMAL) */
+    UNUM_IGNORE = UNUM_PATTERN_DECIMAL
+} UNumberFormatStyle;
+
+/** The possible number format rounding modes. 
+ *  @stable ICU 2.0
+ */
+typedef enum UNumberFormatRoundingMode {
+    UNUM_ROUND_CEILING,
+    UNUM_ROUND_FLOOR,
+    UNUM_ROUND_DOWN,
+    UNUM_ROUND_UP,
+    /**
+     * Half-even rounding, misspelled name
+     * @deprecated, ICU 3.8
+     */
+    UNUM_FOUND_HALFEVEN,
+    UNUM_ROUND_HALFDOWN,
+    UNUM_ROUND_HALFUP,
+    /**
+     * Half-even rounding
+     * @stable, ICU 3.8
+     */
+    UNUM_ROUND_HALFEVEN = UNUM_FOUND_HALFEVEN
+} UNumberFormatRoundingMode;
+
+/** The possible number format pad positions. 
+ *  @stable ICU 2.0
+ */
+typedef enum UNumberFormatPadPosition {
+    UNUM_PAD_BEFORE_PREFIX,
+    UNUM_PAD_AFTER_PREFIX,
+    UNUM_PAD_BEFORE_SUFFIX,
+    UNUM_PAD_AFTER_SUFFIX
+} UNumberFormatPadPosition;
+
+/**
+ * Create and return a new UNumberFormat for formatting and parsing
+ * numbers.  A UNumberFormat may be used to format numbers by calling
+ * {@link #unum_format }, and to parse numbers by calling {@link #unum_parse }.
+ * The caller must call {@link #unum_close } when done to release resources
+ * used by this object.
+ * @param style The type of number format to open: one of
+ * UNUM_DECIMAL, UNUM_CURRENCY, UNUM_PERCENT, UNUM_SCIENTIFIC, UNUM_SPELLOUT,
+ * UNUM_PATTERN_DECIMAL, UNUM_PATTERN_RULEBASED, or UNUM_DEFAULT.
+ * If UNUM_PATTERN_DECIMAL or UNUM_PATTERN_RULEBASED is passed then the
+ * number format is opened using the given pattern, which must conform
+ * to the syntax described in DecimalFormat or RuleBasedNumberFormat,
+ * respectively.
+ * @param pattern A pattern specifying the format to use. 
+ * This parameter is ignored unless the style is
+ * UNUM_PATTERN_DECIMAL or UNUM_PATTERN_RULEBASED.
+ * @param patternLength The number of characters in the pattern, or -1
+ * if null-terminated. This parameter is ignored unless the style is
+ * UNUM_PATTERN.
+ * @param locale A locale identifier to use to determine formatting
+ * and parsing conventions, or NULL to use the default locale.
+ * @param parseErr A pointer to a UParseError struct to receive the
+ * details of any parsing errors, or NULL if no parsing error details
+ * are desired.
+ * @param status A pointer to an input-output UErrorCode.
+ * @return A pointer to a newly created UNumberFormat, or NULL if an
+ * error occurred.
+ * @see unum_close
+ * @see DecimalFormat
+ * @stable ICU 2.0
+ */
+U_STABLE UNumberFormat* U_EXPORT2 
+unum_open(  UNumberFormatStyle    style,
+            const    UChar*    pattern,
+            int32_t            patternLength,
+            const    char*     locale,
+            UParseError*       parseErr,
+            UErrorCode*        status);
+
+
+/**
+* Close a UNumberFormat.
+* Once closed, a UNumberFormat may no longer be used.
+* @param fmt The formatter to close.
+* @stable ICU 2.0
+*/
+U_STABLE void U_EXPORT2 
+unum_close(UNumberFormat* fmt);
+
+/**
+ * Open a copy of a UNumberFormat.
+ * This function performs a deep copy.
+ * @param fmt The format to copy
+ * @param status A pointer to an UErrorCode to receive any errors.
+ * @return A pointer to a UNumberFormat identical to fmt.
+ * @stable ICU 2.0
+ */
+U_STABLE UNumberFormat* U_EXPORT2 
+unum_clone(const UNumberFormat *fmt,
+       UErrorCode *status);
+
+/**
+* Format an integer using a UNumberFormat.
+* The integer will be formatted according to the UNumberFormat's locale.
+* @param fmt The formatter to use.
+* @param number The number to format.
+* @param result A pointer to a buffer to receive the formatted number.
+* @param resultLength The maximum size of result.
+* @param pos    A pointer to a UFieldPosition.  On input, position->field
+* is read.  On output, position->beginIndex and position->endIndex indicate
+* the beginning and ending indices of field number position->field, if such
+* a field exists.  This parameter may be NULL, in which case no field
+* @param status A pointer to an UErrorCode to receive any errors
+* @return The total buffer size needed; if greater than resultLength, the output was truncated.
+* @see unum_formatInt64
+* @see unum_formatDouble
+* @see unum_parse
+* @see unum_parseInt64
+* @see unum_parseDouble
+* @see UFieldPosition
+* @stable ICU 2.0
+*/
+U_STABLE int32_t U_EXPORT2 
+unum_format(    const    UNumberFormat*    fmt,
+        int32_t            number,
+        UChar*            result,
+        int32_t            resultLength,
+        UFieldPosition    *pos,
+        UErrorCode*        status);
+
+/**
+* Format an int64 using a UNumberFormat.
+* The int64 will be formatted according to the UNumberFormat's locale.
+* @param fmt The formatter to use.
+* @param number The number to format.
+* @param result A pointer to a buffer to receive the formatted number.
+* @param resultLength The maximum size of result.
+* @param pos    A pointer to a UFieldPosition.  On input, position->field
+* is read.  On output, position->beginIndex and position->endIndex indicate
+* the beginning and ending indices of field number position->field, if such
+* a field exists.  This parameter may be NULL, in which case no field
+* @param status A pointer to an UErrorCode to receive any errors
+* @return The total buffer size needed; if greater than resultLength, the output was truncated.
+* @see unum_format
+* @see unum_formatDouble
+* @see unum_parse
+* @see unum_parseInt64
+* @see unum_parseDouble
+* @see UFieldPosition
+* @stable ICU 2.0
+*/
+U_STABLE int32_t U_EXPORT2 
+unum_formatInt64(const UNumberFormat *fmt,
+        int64_t         number,
+        UChar*          result,
+        int32_t         resultLength,
+        UFieldPosition *pos,
+        UErrorCode*     status);
+
+/**
+* Format a double using a UNumberFormat.
+* The double will be formatted according to the UNumberFormat's locale.
+* @param fmt The formatter to use.
+* @param number The number to format.
+* @param result A pointer to a buffer to receive the formatted number.
+* @param resultLength The maximum size of result.
+* @param pos    A pointer to a UFieldPosition.  On input, position->field
+* is read.  On output, position->beginIndex and position->endIndex indicate
+* the beginning and ending indices of field number position->field, if such
+* a field exists.  This parameter may be NULL, in which case no field
+* @param status A pointer to an UErrorCode to receive any errors
+* @return The total buffer size needed; if greater than resultLength, the output was truncated.
+* @see unum_format
+* @see unum_formatInt64
+* @see unum_parse
+* @see unum_parseInt64
+* @see unum_parseDouble
+* @see UFieldPosition
+* @stable ICU 2.0
+*/
+U_STABLE int32_t U_EXPORT2 
+unum_formatDouble(    const    UNumberFormat*  fmt,
+            double          number,
+            UChar*          result,
+            int32_t         resultLength,
+            UFieldPosition  *pos, /* 0 if ignore */
+            UErrorCode*     status);
+
+/**
+ * Format a double currency amount using a UNumberFormat.
+ * The double will be formatted according to the UNumberFormat's locale.
+ * @param fmt the formatter to use
+ * @param number the number to format
+ * @param currency the 3-letter null-terminated ISO 4217 currency code
+ * @param result a pointer to the buffer to receive the formatted number
+ * @param resultLength the maximum number of UChars to write to result
+ * @param pos a pointer to a UFieldPosition.  On input,
+ * position->field is read.  On output, position->beginIndex and
+ * position->endIndex indicate the beginning and ending indices of
+ * field number position->field, if such a field exists.  This
+ * parameter may be NULL, in which case it is ignored.
+ * @param status a pointer to an input-output UErrorCode
+ * @return the total buffer size needed; if greater than resultLength,
+ * the output was truncated.
+ * @see unum_formatDouble
+ * @see unum_parseDoubleCurrency
+ * @see UFieldPosition
+ * @stable ICU 3.0
+ */
+U_STABLE int32_t U_EXPORT2 
+unum_formatDoubleCurrency(const UNumberFormat* fmt,
+                          double number,
+                          UChar* currency,
+                          UChar* result,
+                          int32_t resultLength,
+                          UFieldPosition* pos, /* ignored if 0 */
+                          UErrorCode* status);
+
+/**
+* Parse a string into an integer using a UNumberFormat.
+* The string will be parsed according to the UNumberFormat's locale.
+* @param fmt The formatter to use.
+* @param text The text to parse.
+* @param textLength The length of text, or -1 if null-terminated.
+* @param parsePos If not 0, on input a pointer to an integer specifying the offset at which
+* to begin parsing.  If not 0, on output the offset at which parsing ended.
+* @param status A pointer to an UErrorCode to receive any errors
+* @return The value of the parsed integer
+* @see unum_parseInt64
+* @see unum_parseDouble
+* @see unum_format
+* @see unum_formatInt64
+* @see unum_formatDouble
+* @stable ICU 2.0
+*/
+U_STABLE int32_t U_EXPORT2 
+unum_parse(    const   UNumberFormat*  fmt,
+        const   UChar*          text,
+        int32_t         textLength,
+        int32_t         *parsePos /* 0 = start */,
+        UErrorCode      *status);
+
+/**
+* Parse a string into an int64 using a UNumberFormat.
+* The string will be parsed according to the UNumberFormat's locale.
+* @param fmt The formatter to use.
+* @param text The text to parse.
+* @param textLength The length of text, or -1 if null-terminated.
+* @param parsePos If not 0, on input a pointer to an integer specifying the offset at which
+* to begin parsing.  If not 0, on output the offset at which parsing ended.
+* @param status A pointer to an UErrorCode to receive any errors
+* @return The value of the parsed integer
+* @see unum_parse
+* @see unum_parseDouble
+* @see unum_format
+* @see unum_formatInt64
+* @see unum_formatDouble
+* @stable ICU 2.8
+*/
+U_STABLE int64_t U_EXPORT2 
+unum_parseInt64(const UNumberFormat*  fmt,
+        const UChar*  text,
+        int32_t       textLength,
+        int32_t       *parsePos /* 0 = start */,
+        UErrorCode    *status);
+
+/**
+* Parse a string into a double using a UNumberFormat.
+* The string will be parsed according to the UNumberFormat's locale.
+* @param fmt The formatter to use.
+* @param text The text to parse.
+* @param textLength The length of text, or -1 if null-terminated.
+* @param parsePos If not 0, on input a pointer to an integer specifying the offset at which
+* to begin parsing.  If not 0, on output the offset at which parsing ended.
+* @param status A pointer to an UErrorCode to receive any errors
+* @return The value of the parsed double
+* @see unum_parse
+* @see unum_parseInt64
+* @see unum_format
+* @see unum_formatInt64
+* @see unum_formatDouble
+* @stable ICU 2.0
+*/
+U_STABLE double U_EXPORT2 
+unum_parseDouble(    const   UNumberFormat*  fmt,
+            const   UChar*          text,
+            int32_t         textLength,
+            int32_t         *parsePos /* 0 = start */,
+            UErrorCode      *status);
+
+/**
+ * Parse a string into a double and a currency using a UNumberFormat.
+ * The string will be parsed according to the UNumberFormat's locale.
+ * @param fmt the formatter to use
+ * @param text the text to parse
+ * @param textLength the length of text, or -1 if null-terminated
+ * @param parsePos a pointer to an offset index into text at which to
+ * begin parsing. On output, *parsePos will point after the last
+ * parsed character.  This parameter may be 0, in which case parsing
+ * begins at offset 0.
+ * @param currency a pointer to the buffer to receive the parsed null-
+ * terminated currency.  This buffer must have a capacity of at least
+ * 4 UChars.
+ * @param status a pointer to an input-output UErrorCode
+ * @return the parsed double
+ * @see unum_parseDouble
+ * @see unum_formatDoubleCurrency
+ * @stable ICU 3.0
+ */
+U_STABLE double U_EXPORT2
+unum_parseDoubleCurrency(const UNumberFormat* fmt,
+                         const UChar* text,
+                         int32_t textLength,
+                         int32_t* parsePos, /* 0 = start */
+                         UChar* currency,
+                         UErrorCode* status);
+
+/**
+ * Set the pattern used by a UNumberFormat.  This can only be used
+ * on a DecimalFormat, other formats return U_ILLEGAL_ARGUMENT_ERROR
+ * in the status.
+ * @param format The formatter to set.
+ * @param localized TRUE if the pattern is localized, FALSE otherwise.
+ * @param pattern The new pattern
+ * @param patternLength The length of pattern, or -1 if null-terminated.
+ * @param parseError A pointer to UParseError to recieve information
+ * about errors occurred during parsing, or NULL if no parse error
+ * information is desired.
+ * @param status A pointer to an input-output UErrorCode.
+ * @see unum_toPattern
+ * @see DecimalFormat
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+unum_applyPattern(          UNumberFormat  *format,
+                            UBool          localized,
+                    const   UChar          *pattern,
+                            int32_t         patternLength,
+                            UParseError    *parseError,
+                            UErrorCode     *status
+                                    );
+
+/**
+* Get a locale for which decimal formatting patterns are available.
+* A UNumberFormat in a locale returned by this function will perform the correct
+* formatting and parsing for the locale.  The results of this call are not
+* valid for rule-based number formats.
+* @param index The index of the desired locale.
+* @return A locale for which number formatting patterns are available, or 0 if none.
+* @see unum_countAvailable
+* @stable ICU 2.0
+*/
+U_STABLE const char* U_EXPORT2 
+unum_getAvailable(int32_t index);
+
+/**
+* Determine how many locales have decimal formatting patterns available.  The
+* results of this call are not valid for rule-based number formats.
+* This function is useful for determining the loop ending condition for
+* calls to {@link #unum_getAvailable }.
+* @return The number of locales for which decimal formatting patterns are available.
+* @see unum_getAvailable
+* @stable ICU 2.0
+*/
+U_STABLE int32_t U_EXPORT2 
+unum_countAvailable(void);
+
+/** The possible UNumberFormat numeric attributes @stable ICU 2.0 */
+typedef enum UNumberFormatAttribute {
+  /** Parse integers only */
+  UNUM_PARSE_INT_ONLY,
+  /** Use grouping separator */
+  UNUM_GROUPING_USED,
+  /** Always show decimal point */
+  UNUM_DECIMAL_ALWAYS_SHOWN,
+  /** Maximum integer digits */
+  UNUM_MAX_INTEGER_DIGITS,
+  /** Minimum integer digits */
+  UNUM_MIN_INTEGER_DIGITS,
+  /** Integer digits */
+  UNUM_INTEGER_DIGITS,
+  /** Maximum fraction digits */
+  UNUM_MAX_FRACTION_DIGITS,
+  /** Minimum fraction digits */
+  UNUM_MIN_FRACTION_DIGITS,
+  /** Fraction digits */
+  UNUM_FRACTION_DIGITS,
+  /** Multiplier */
+  UNUM_MULTIPLIER,
+  /** Grouping size */
+  UNUM_GROUPING_SIZE,
+  /** Rounding Mode */
+  UNUM_ROUNDING_MODE,
+  /** Rounding increment */
+  UNUM_ROUNDING_INCREMENT,
+  /** The width to which the output of <code>format()</code> is padded. */
+  UNUM_FORMAT_WIDTH,
+  /** The position at which padding will take place. */
+  UNUM_PADDING_POSITION,
+  /** Secondary grouping size */
+  UNUM_SECONDARY_GROUPING_SIZE,
+  /** Use significant digits
+   * @stable ICU 3.0 */
+  UNUM_SIGNIFICANT_DIGITS_USED,
+  /** Minimum significant digits
+   * @stable ICU 3.0 */
+  UNUM_MIN_SIGNIFICANT_DIGITS,
+  /** Maximum significant digits
+   * @stable ICU 3.0 */
+  UNUM_MAX_SIGNIFICANT_DIGITS,
+  /** Lenient parse mode used by rule-based formats.
+   * @stable ICU 3.0
+   */
+  UNUM_LENIENT_PARSE
+} UNumberFormatAttribute;
+
+/**
+* Get a numeric attribute associated with a UNumberFormat.
+* An example of a numeric attribute is the number of integer digits a formatter will produce.
+* @param fmt The formatter to query.
+* @param attr The attribute to query; one of UNUM_PARSE_INT_ONLY, UNUM_GROUPING_USED,
+* UNUM_DECIMAL_ALWAYS_SHOWN, UNUM_MAX_INTEGER_DIGITS, UNUM_MIN_INTEGER_DIGITS, UNUM_INTEGER_DIGITS,
+* UNUM_MAX_FRACTION_DIGITS, UNUM_MIN_FRACTION_DIGITS, UNUM_FRACTION_DIGITS, UNUM_MULTIPLIER,
+* UNUM_GROUPING_SIZE, UNUM_ROUNDING_MODE, UNUM_FORMAT_WIDTH, UNUM_PADDING_POSITION, UNUM_SECONDARY_GROUPING_SIZE.
+* @return The value of attr.
+* @see unum_setAttribute
+* @see unum_getDoubleAttribute
+* @see unum_setDoubleAttribute
+* @see unum_getTextAttribute
+* @see unum_setTextAttribute
+* @stable ICU 2.0
+*/
+U_STABLE int32_t U_EXPORT2 
+unum_getAttribute(const UNumberFormat*          fmt,
+          UNumberFormatAttribute  attr);
+
+/**
+* Set a numeric attribute associated with a UNumberFormat.
+* An example of a numeric attribute is the number of integer digits a formatter will produce.  If the
+* formatter does not understand the attribute, the call is ignored.  Rule-based formatters only understand
+* the lenient-parse attribute.
+* @param fmt The formatter to set.
+* @param attr The attribute to set; one of UNUM_PARSE_INT_ONLY, UNUM_GROUPING_USED,
+* UNUM_DECIMAL_ALWAYS_SHOWN, UNUM_MAX_INTEGER_DIGITS, UNUM_MIN_INTEGER_DIGITS, UNUM_INTEGER_DIGITS,
+* UNUM_MAX_FRACTION_DIGITS, UNUM_MIN_FRACTION_DIGITS, UNUM_FRACTION_DIGITS, UNUM_MULTIPLIER,
+* UNUM_GROUPING_SIZE, UNUM_ROUNDING_MODE, UNUM_FORMAT_WIDTH, UNUM_PADDING_POSITION, UNUM_SECONDARY_GROUPING_SIZE,
+* or UNUM_LENIENT_PARSE.
+* @param newValue The new value of attr.
+* @see unum_getAttribute
+* @see unum_getDoubleAttribute
+* @see unum_setDoubleAttribute
+* @see unum_getTextAttribute
+* @see unum_setTextAttribute
+* @stable ICU 2.0
+*/
+U_STABLE void U_EXPORT2 
+unum_setAttribute(    UNumberFormat*          fmt,
+            UNumberFormatAttribute  attr,
+            int32_t                 newValue);
+
+
+/**
+* Get a numeric attribute associated with a UNumberFormat.
+* An example of a numeric attribute is the number of integer digits a formatter will produce.
+* If the formatter does not understand the attribute, -1 is returned.
+* @param fmt The formatter to query.
+* @param attr The attribute to query; e.g. UNUM_ROUNDING_INCREMENT.
+* @return The value of attr.
+* @see unum_getAttribute
+* @see unum_setAttribute
+* @see unum_setDoubleAttribute
+* @see unum_getTextAttribute
+* @see unum_setTextAttribute
+* @stable ICU 2.0
+*/
+U_STABLE double U_EXPORT2 
+unum_getDoubleAttribute(const UNumberFormat*          fmt,
+          UNumberFormatAttribute  attr);
+
+/**
+* Set a numeric attribute associated with a UNumberFormat.
+* An example of a numeric attribute is the number of integer digits a formatter will produce.
+* If the formatter does not understand the attribute, this call is ignored.
+* @param fmt The formatter to set.
+* @param attr The attribute to set; e.g. UNUM_ROUNDING_INCREMENT.
+* @param newValue The new value of attr.
+* @see unum_getAttribute
+* @see unum_setAttribute
+* @see unum_getDoubleAttribute
+* @see unum_getTextAttribute
+* @see unum_setTextAttribute
+* @stable ICU 2.0
+*/
+U_STABLE void U_EXPORT2 
+unum_setDoubleAttribute(    UNumberFormat*          fmt,
+            UNumberFormatAttribute  attr,
+            double                 newValue);
+
+/** The possible UNumberFormat text attributes @stable ICU 2.0*/
+typedef enum UNumberFormatTextAttribute {
+  /** Positive prefix */
+  UNUM_POSITIVE_PREFIX,
+  /** Positive suffix */
+  UNUM_POSITIVE_SUFFIX,
+  /** Negative prefix */
+  UNUM_NEGATIVE_PREFIX,
+  /** Negative suffix */
+  UNUM_NEGATIVE_SUFFIX,
+  /** The character used to pad to the format width. */
+  UNUM_PADDING_CHARACTER,
+  /** The ISO currency code */
+  UNUM_CURRENCY_CODE,
+  /**
+   * The default rule set.  This is only available with rule-based formatters.
+   * @stable ICU 3.0
+   */
+  UNUM_DEFAULT_RULESET,
+  /**
+   * The public rule sets.  This is only available with rule-based formatters.
+   * This is a read-only attribute.  The public rulesets are returned as a
+   * single string, with each ruleset name delimited by ';' (semicolon).
+   * @stable ICU 3.0
+   */
+  UNUM_PUBLIC_RULESETS
+} UNumberFormatTextAttribute;
+
+/**
+* Get a text attribute associated with a UNumberFormat.
+* An example of a text attribute is the suffix for positive numbers.  If the formatter
+* does not understand the attributre, U_UNSUPPORTED_ERROR is returned as the status.
+* Rule-based formatters only understand UNUM_DEFAULT_RULESET and UNUM_PUBLIC_RULESETS.
+* @param fmt The formatter to query.
+* @param tag The attribute to query; one of UNUM_POSITIVE_PREFIX, UNUM_POSITIVE_SUFFIX,
+* UNUM_NEGATIVE_PREFIX, UNUM_NEGATIVE_SUFFIX, UNUM_PADDING_CHARACTER, UNUM_CURRENCY_CODE,
+* UNUM_DEFAULT_RULESET, or UNUM_PUBLIC_RULESETS.
+* @param result A pointer to a buffer to receive the attribute.
+* @param resultLength The maximum size of result.
+* @param status A pointer to an UErrorCode to receive any errors
+* @return The total buffer size needed; if greater than resultLength, the output was truncated.
+* @see unum_setTextAttribute
+* @see unum_getAttribute
+* @see unum_setAttribute
+* @stable ICU 2.0
+*/
+U_STABLE int32_t U_EXPORT2 
+unum_getTextAttribute(    const    UNumberFormat*                    fmt,
+            UNumberFormatTextAttribute      tag,
+            UChar*                            result,
+            int32_t                            resultLength,
+            UErrorCode*                        status);
+
+/**
+* Set a text attribute associated with a UNumberFormat.
+* An example of a text attribute is the suffix for positive numbers.  Rule-based formatters
+* only understand UNUM_DEFAULT_RULESET.
+* @param fmt The formatter to set.
+* @param tag The attribute to set; one of UNUM_POSITIVE_PREFIX, UNUM_POSITIVE_SUFFIX,
+* UNUM_NEGATIVE_PREFIX, UNUM_NEGATIVE_SUFFIX, UNUM_PADDING_CHARACTER, UNUM_CURRENCY_CODE,
+* or UNUM_DEFAULT_RULESET.
+* @param newValue The new value of attr.
+* @param newValueLength The length of newValue, or -1 if null-terminated.
+* @param status A pointer to an UErrorCode to receive any errors
+* @see unum_getTextAttribute
+* @see unum_getAttribute
+* @see unum_setAttribute
+* @stable ICU 2.0
+*/
+U_STABLE void U_EXPORT2 
+unum_setTextAttribute(    UNumberFormat*                    fmt,
+            UNumberFormatTextAttribute      tag,
+            const    UChar*                            newValue,
+            int32_t                            newValueLength,
+            UErrorCode                        *status);
+
+/**
+ * Extract the pattern from a UNumberFormat.  The pattern will follow
+ * the DecimalFormat pattern syntax.
+ * @param fmt The formatter to query.
+ * @param isPatternLocalized TRUE if the pattern should be localized,
+ * FALSE otherwise.  This is ignored if the formatter is a rule-based
+ * formatter.
+ * @param result A pointer to a buffer to receive the pattern.
+ * @param resultLength The maximum size of result.
+ * @param status A pointer to an input-output UErrorCode.
+ * @return The total buffer size needed; if greater than resultLength,
+ * the output was truncated.
+ * @see unum_applyPattern
+ * @see DecimalFormat
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2 
+unum_toPattern(    const    UNumberFormat*          fmt,
+        UBool                  isPatternLocalized,
+        UChar*                  result,
+        int32_t                 resultLength,
+        UErrorCode*             status);
+
+
+/**
+ * Constants for specifying a number format symbol.
+ * @stable ICU 2.0
+ */
+typedef enum UNumberFormatSymbol {
+  /** The decimal separator */
+  UNUM_DECIMAL_SEPARATOR_SYMBOL = 0,
+  /** The grouping separator */
+  UNUM_GROUPING_SEPARATOR_SYMBOL = 1,
+  /** The pattern separator */
+  UNUM_PATTERN_SEPARATOR_SYMBOL = 2,
+  /** The percent sign */
+  UNUM_PERCENT_SYMBOL = 3,
+  /** Zero*/
+  UNUM_ZERO_DIGIT_SYMBOL = 4,
+  /** Character representing a digit in the pattern */
+  UNUM_DIGIT_SYMBOL = 5,
+  /** The minus sign */
+  UNUM_MINUS_SIGN_SYMBOL = 6,
+  /** The plus sign */
+  UNUM_PLUS_SIGN_SYMBOL = 7,
+  /** The currency symbol */
+  UNUM_CURRENCY_SYMBOL = 8,
+  /** The international currency symbol */
+  UNUM_INTL_CURRENCY_SYMBOL = 9,
+  /** The monetary separator */
+  UNUM_MONETARY_SEPARATOR_SYMBOL = 10,
+  /** The exponential symbol */
+  UNUM_EXPONENTIAL_SYMBOL = 11,
+  /** Per mill symbol */
+  UNUM_PERMILL_SYMBOL = 12,
+  /** Escape padding character */
+  UNUM_PAD_ESCAPE_SYMBOL = 13,
+  /** Infinity symbol */
+  UNUM_INFINITY_SYMBOL = 14,
+  /** Nan symbol */
+  UNUM_NAN_SYMBOL = 15,
+  /** Significant digit symbol
+   * @stable ICU 3.0 */
+  UNUM_SIGNIFICANT_DIGIT_SYMBOL = 16,
+  /** The monetary grouping separator 
+   * @stable ICU 3.6
+   */
+  UNUM_MONETARY_GROUPING_SEPARATOR_SYMBOL = 17,  
+  /** count symbol constants */
+  UNUM_FORMAT_SYMBOL_COUNT = 18
+} UNumberFormatSymbol;
+
+/**
+* Get a symbol associated with a UNumberFormat.
+* A UNumberFormat uses symbols to represent the special locale-dependent
+* characters in a number, for example the percent sign. This API is not
+* supported for rule-based formatters.
+* @param fmt The formatter to query.
+* @param symbol The UNumberFormatSymbol constant for the symbol to get
+* @param buffer The string buffer that will receive the symbol string;
+*               if it is NULL, then only the length of the symbol is returned
+* @param size The size of the string buffer
+* @param status A pointer to an UErrorCode to receive any errors
+* @return The length of the symbol; the buffer is not modified if
+*         <code>length&gt;=size</code>
+* @see unum_setSymbol
+* @stable ICU 2.0
+*/
+U_STABLE int32_t U_EXPORT2
+unum_getSymbol(const UNumberFormat *fmt,
+               UNumberFormatSymbol symbol,
+               UChar *buffer,
+               int32_t size,
+               UErrorCode *status);
+
+/**
+* Set a symbol associated with a UNumberFormat.
+* A UNumberFormat uses symbols to represent the special locale-dependent
+* characters in a number, for example the percent sign.  This API is not
+* supported for rule-based formatters.
+* @param fmt The formatter to set.
+* @param symbol The UNumberFormatSymbol constant for the symbol to set
+* @param value The string to set the symbol to
+* @param length The length of the string, or -1 for a zero-terminated string
+* @param status A pointer to an UErrorCode to receive any errors.
+* @see unum_getSymbol
+* @stable ICU 2.0
+*/
+U_STABLE void U_EXPORT2
+unum_setSymbol(UNumberFormat *fmt,
+               UNumberFormatSymbol symbol,
+               const UChar *value,
+               int32_t length,
+               UErrorCode *status);
+
+
+/**
+ * Get the locale for this number format object.
+ * You can choose between valid and actual locale.
+ * @param fmt The formatter to get the locale from
+ * @param type type of the locale we're looking for (valid or actual) 
+ * @param status error code for the operation
+ * @return the locale name
+ * @stable ICU 2.8
+ */
+U_STABLE const char* U_EXPORT2
+unum_getLocaleByType(const UNumberFormat *fmt,
+                     ULocDataLocaleType type,
+                     UErrorCode* status); 
+
+#endif /* #if !UCONFIG_NO_FORMATTING */
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/uobject.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/uobject.h b/src/apps/couch_collate/platform/osx/icu/unicode/uobject.h
new file mode 100644
index 0000000..3d8b96e
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/uobject.h
@@ -0,0 +1,308 @@
+/*
+******************************************************************************
+*
+*   Copyright (C) 2002-2007, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+*
+******************************************************************************
+*   file name:  uobject.h
+*   encoding:   US-ASCII
+*   tab size:   8 (not used)
+*   indentation:4
+*
+*   created on: 2002jun26
+*   created by: Markus W. Scherer
+*/
+
+#ifndef __UOBJECT_H__
+#define __UOBJECT_H__
+
+#include "unicode/utypes.h"
+
+U_NAMESPACE_BEGIN
+
+/**
+ * \file
+ * \brief C++ API: Common ICU base class UObject.
+ */
+
+/**  U_OVERRIDE_CXX_ALLOCATION - Define this to override operator new and
+ *                               delete in UMemory. Enabled by default for ICU.
+ *
+ *         Enabling forces all allocation of ICU object types to use ICU's
+ *         memory allocation. On Windows, this allows the ICU DLL to be used by
+ *         applications that statically link the C Runtime library, meaning that
+ *         the app and ICU will be using different heaps.
+ *
+ * @stable ICU 2.2
+ */                              
+#ifndef U_OVERRIDE_CXX_ALLOCATION
+#define U_OVERRIDE_CXX_ALLOCATION 1
+#endif
+
+/**  U_HAVE_PLACEMENT_NEW - Define this to define the placement new and
+ *                          delete in UMemory for STL.
+ *
+ * @stable ICU 2.6
+ */                              
+#ifndef U_HAVE_PLACEMENT_NEW
+#define U_HAVE_PLACEMENT_NEW 1
+#endif
+
+
+/**  U_HAVE_DEBUG_LOCATION_NEW - Define this to define the MFC debug
+ * version of the operator new.
+ *
+ * @stable ICU 3.4
+ */                              
+#ifndef U_HAVE_DEBUG_LOCATION_NEW
+#define U_HAVE_DEBUG_LOCATION_NEW 0
+#endif
+
+/**
+ * UMemory is the common ICU base class.
+ * All other ICU C++ classes are derived from UMemory (starting with ICU 2.4).
+ *
+ * This is primarily to make it possible and simple to override the
+ * C++ memory management by adding new/delete operators to this base class.
+ *
+ * To override ALL ICU memory management, including that from plain C code,
+ * replace the allocation functions declared in cmemory.h
+ *
+ * UMemory does not contain any virtual functions.
+ * Common "boilerplate" functions are defined in UObject.
+ *
+ * @stable ICU 2.4
+ */
+class U_COMMON_API UMemory {
+public:
+
+#if U_OVERRIDE_CXX_ALLOCATION
+    /**
+     * Override for ICU4C C++ memory management.
+     * simple, non-class types are allocated using the macros in common/cmemory.h
+     * (uprv_malloc(), uprv_free(), uprv_realloc());
+     * they or something else could be used here to implement C++ new/delete
+     * for ICU4C C++ classes
+     * @stable ICU 2.4
+     */
+    static void * U_EXPORT2 operator new(size_t size);
+
+    /**
+     * Override for ICU4C C++ memory management.
+     * See new().
+     * @stable ICU 2.4
+     */
+    static void * U_EXPORT2 operator new[](size_t size);
+
+    /**
+     * Override for ICU4C C++ memory management.
+     * simple, non-class types are allocated using the macros in common/cmemory.h
+     * (uprv_malloc(), uprv_free(), uprv_realloc());
+     * they or something else could be used here to implement C++ new/delete
+     * for ICU4C C++ classes
+     * @stable ICU 2.4
+     */
+    static void U_EXPORT2 operator delete(void *p);
+
+    /**
+     * Override for ICU4C C++ memory management.
+     * See delete().
+     * @stable ICU 2.4
+     */
+    static void U_EXPORT2 operator delete[](void *p);
+
+#if U_HAVE_PLACEMENT_NEW
+    /**
+     * Override for ICU4C C++ memory management for STL.
+     * See new().
+     * @stable ICU 2.6
+     */
+    static inline void * U_EXPORT2 operator new(size_t, void *ptr) { return ptr; }
+
+    /**
+     * Override for ICU4C C++ memory management for STL.
+     * See delete().
+     * @stable ICU 2.6
+     */
+    static inline void U_EXPORT2 operator delete(void *, void *) {}
+#endif /* U_HAVE_PLACEMENT_NEW */
+#if U_HAVE_DEBUG_LOCATION_NEW
+    /**
+      * This method overrides the MFC debug version of the operator new
+      * 
+      * @param size   The requested memory size
+      * @param file   The file where the allocation was requested
+      * @param line   The line where the allocation was requested 
+      */ 
+    static void * U_EXPORT2 operator new(size_t size, const char* file, int line);
+    /**
+      * This method provides a matching delete for the MFC debug new
+      * 
+      * @param p      The pointer to the allocated memory
+      * @param file   The file where the allocation was requested
+      * @param line   The line where the allocation was requested 
+      */ 
+    static void U_EXPORT2 operator delete(void* p, const char* file, int line);
+#endif /* U_HAVE_DEBUG_LOCATION_NEW */
+#endif /* U_OVERRIDE_CXX_ALLOCATION */
+
+    /*
+     * Assignment operator not declared. The compiler will provide one
+     * which does nothing since this class does not contain any data members.
+     * API/code coverage may show the assignment operator as present and
+     * untested - ignore.
+     * Subclasses need this assignment operator if they use compiler-provided
+     * assignment operators of their own. An alternative to not declaring one
+     * here would be to declare and empty-implement a protected or public one.
+    UMemory &UMemory::operator=(const UMemory &);
+     */
+};
+
+/**
+ * UObject is the common ICU "boilerplate" class.
+ * UObject inherits UMemory (starting with ICU 2.4),
+ * and all other public ICU C++ classes
+ * are derived from UObject (starting with ICU 2.2).
+ *
+ * UObject contains common virtual functions like for ICU's "poor man's RTTI".
+ * It does not contain default implementations of virtual methods
+ * like getDynamicClassID to allow derived classes such as Format
+ * to declare these as pure virtual.
+ *
+ * The clone() function is not available in UObject because it is not
+ * implemented by all ICU classes.
+ * Many ICU services provide a clone() function for their class trees,
+ * defined on the service's C++ base class, and all subclasses within that
+ * service class tree return a pointer to the service base class
+ * (which itself is a subclass of UObject).
+ * This is because some compilers do not support covariant (same-as-this)
+ * return types; cast to the appropriate subclass if necessary.
+ *
+ * @stable ICU 2.2
+ */
+class U_COMMON_API UObject : public UMemory {
+public:
+    /**
+     * Destructor.
+     *
+     * @stable ICU 2.2
+     */
+    virtual ~UObject();
+
+    /**
+     * ICU4C "poor man's RTTI", returns a UClassID for the actual ICU class.
+     *
+     * @stable ICU 2.2
+     */
+    virtual UClassID getDynamicClassID() const = 0;
+
+protected:
+    // the following functions are protected to prevent instantiation and
+    // direct use of UObject itself
+
+    // default constructor
+    // commented out because UObject is abstract (see getDynamicClassID)
+    // inline UObject() {}
+
+    // copy constructor
+    // commented out because UObject is abstract (see getDynamicClassID)
+    // inline UObject(const UObject &other) {}
+
+#if 0
+    // TODO Sometime in the future. Implement operator==().
+    // (This comment inserted in 2.2)
+    // some or all of the following "boilerplate" functions may be made public
+    // in a future ICU4C release when all subclasses implement them
+
+    // assignment operator
+    // (not virtual, see "Taligent's Guide to Designing Programs" pp.73..74)
+    // commented out because the implementation is the same as a compiler's default
+    // UObject &operator=(const UObject &other) { return *this; }
+
+    // comparison operators
+    virtual inline UBool operator==(const UObject &other) const { return this==&other; }
+    inline UBool operator!=(const UObject &other) const { return !operator==(other); }
+
+    // clone() commented out from the base class:
+    // some compilers do not support co-variant return types
+    // (i.e., subclasses would have to return UObject * as well, instead of SubClass *)
+    // see also UObject class documentation.
+    // virtual UObject *clone() const;
+#endif
+
+    /*
+     * Assignment operator not declared. The compiler will provide one
+     * which does nothing since this class does not contain any data members.
+     * API/code coverage may show the assignment operator as present and
+     * untested - ignore.
+     * Subclasses need this assignment operator if they use compiler-provided
+     * assignment operators of their own. An alternative to not declaring one
+     * here would be to declare and empty-implement a protected or public one.
+    UObject &UObject::operator=(const UObject &);
+     */
+
+// Future implementation for RTTI that support subtyping. [alan]
+// 
+//  public:
+//     /**
+//      * @internal
+//      */
+//     static UClassID getStaticClassID();
+// 
+//     /**
+//      * @internal
+//      */
+//     UBool instanceOf(UClassID type) const;
+};
+
+/**
+ * This is a simple macro to add ICU RTTI to an ICU object implementation.
+ * This does not go into the header. This should only be used in *.cpp files.
+ *
+ * @param myClass The name of the class that needs RTTI defined.
+ * @internal
+ */
+#define UOBJECT_DEFINE_RTTI_IMPLEMENTATION(myClass) \
+    UClassID U_EXPORT2 myClass::getStaticClassID() { \
+        static char classID = 0; \
+        return (UClassID)&classID; \
+    } \
+    UClassID myClass::getDynamicClassID() const \
+    { return myClass::getStaticClassID(); }
+
+
+/**
+ * This macro adds ICU RTTI to an ICU abstract class implementation.
+ * This macro should be invoked in *.cpp files.  The corresponding
+ * header should declare getStaticClassID.
+ *
+ * @param myClass The name of the class that needs RTTI defined.
+ * @internal
+ */
+#define UOBJECT_DEFINE_ABSTRACT_RTTI_IMPLEMENTATION(myClass) \
+    UClassID U_EXPORT2 myClass::getStaticClassID() { \
+        static char classID = 0; \
+        return (UClassID)&classID; \
+    }
+
+// /**
+//  * This macro adds ICU RTTI to an ICU concrete class implementation.
+//  * This macro should be invoked in *.cpp files.  The corresponding
+//  * header should declare getDynamicClassID and getStaticClassID.
+//  *
+//  * @param myClass The name of the class that needs RTTI defined.
+//  * @param myParent The name of the myClass's parent.
+//  * @internal
+//  */
+/*#define UOBJECT_DEFINE_RTTI_IMPLEMENTATION(myClass, myParent) \
+    UOBJECT_DEFINE_ABSTRACT_RTTI_IMPLEMENTATION(myClass, myParent) \
+    UClassID myClass::getDynamicClassID() const { \
+        return myClass::getStaticClassID(); \
+    }
+*/
+
+
+U_NAMESPACE_END
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/uobslete.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/uobslete.h b/src/apps/couch_collate/platform/osx/icu/unicode/uobslete.h
new file mode 100644
index 0000000..91be243
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/uobslete.h
@@ -0,0 +1,32 @@
+/*
+*******************************************************************************
+*   Copyright (C) 2004-2008, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+*******************************************************************************
+*
+*   file name:  
+*   encoding:   US-ASCII
+*   tab size:   8 (not used)
+*   indentation:4
+*
+*   Created by: genheaders.pl, a perl script written by Ram Viswanadha
+*
+*  Contains data for commenting out APIs.
+*  Gets included by umachine.h
+*
+*  THIS FILE IS MACHINE-GENERATED, DON'T PLAY WITH IT IF YOU DON'T KNOW WHAT
+*  YOU ARE DOING, OTHERWISE VERY BAD THINGS WILL HAPPEN!
+*/
+
+#ifndef UOBSLETE_H
+#define UOBSLETE_H
+
+#ifdef U_HIDE_OBSOLETE_API
+
+#    if U_DISABLE_RENAMING
+#    else
+#    endif /* U_DISABLE_RENAMING */
+
+#endif /* U_HIDE_OBSOLETE_API */
+#endif /* UOBSLETE_H */
+

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/urbtok.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/urbtok.h b/src/apps/couch_collate/platform/osx/icu/unicode/urbtok.h
new file mode 100644
index 0000000..936ddde
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/urbtok.h
@@ -0,0 +1,126 @@
+/*
+******************************************************************************
+* Copyright (C) 2006-2008 Apple Inc. All Rights Reserved.
+******************************************************************************
+*/
+
+#ifndef URBTOK_H
+#define URBTOK_H
+
+#include "unicode/utypes.h"
+
+#if !UCONFIG_NO_BREAK_ITERATION
+
+#include "unicode/utext.h"
+#include "unicode/ubrk.h"
+#include "unicode/parseerr.h"
+
+
+typedef struct RuleBasedTokenRange {
+    signed long location;
+    signed long length;
+} RuleBasedTokenRange;
+
+/**
+ * Open a new UBreakIterator for tokenizing text using specified breaking rules.
+ * The rule syntax is ... (TBD)
+ * @param rules A set of rules specifying the text breaking conventions.
+ * @param rulesLength The number of characters in rules, or -1 if null-terminated.
+ * @param parseErr   Receives position and context information for any syntax errors
+ *                   detected while parsing the rules.
+ * @param status A UErrorCode to receive any errors.
+ * @return A UBreakIterator for the specified rules.
+ * @see ubrk_open
+ * @internal
+ */
+U_INTERNAL UBreakIterator* U_EXPORT2
+urbtok_openRules(const UChar     *rules,
+               int32_t         rulesLength,
+               UParseError     *parseErr,
+               UErrorCode      *status);
+
+/**
+ * Open a new UBreakIterator for tokenizing text using specified breaking rules.
+ * @param rules A set of rules specifying the text breaking conventions. The binary rules
+ *              must be at least 32-bit aligned. Note: This version makes a copy of the
+ *				rules, so after calling this function the caller can close or release
+ *				the rules that were passed to this function. The copy created by this
+ *				call will be freed when ubrk_close() is called on the UBreakIterator*.
+ * @param status A UErrorCode to receive any errors.
+ * @return A UBreakIterator for the specified rules.
+ * @see ubrk_open
+ * @internal
+ */
+U_INTERNAL UBreakIterator* U_EXPORT2
+urbtok_openBinaryRules(const uint8_t *rules,
+               UErrorCode      *status);
+
+/**
+ * Open a new UBreakIterator for tokenizing text using specified breaking rules.
+ * @param rules A set of rules specifying the text breaking conventions. The binary rules
+ *              must be at least 32-bit aligned. Note: This version does NOT make a copy
+ *				of the rules, so after calling this function the caller must not close or
+ *				release the rules passed to this function until after they are finished
+ *				with this UBreakIterator* (and any others created using the same rules)
+  *				and have called ubrk_close() to close the UBreakIterator* (and any others
+ *				using the same rules).
+ * @param status A UErrorCode to receive any errors.
+ * @return A UBreakIterator for the specified rules.
+ * @see ubrk_open
+ * @internal
+ */
+U_INTERNAL UBreakIterator* U_EXPORT2
+urbtok_openBinaryRulesNoCopy(const uint8_t *rules,
+               UErrorCode      *status);
+
+/**
+ * Get the (native-endian) binary break rules for this tokenizer.
+ * @param bi The tokenizer to use.
+ * @param buffer The output buffer for the rules. You can pass 0 to get the required size.
+ * @param buffSize The size of the output buffer.
+ * @param status A UErrorCode to receive any errors.
+ * @return The actual size of the binary rules, whether they fit the buffer or not.
+ * @internal
+ */
+U_INTERNAL uint32_t U_EXPORT2
+urbtok_getBinaryRules(UBreakIterator      *bi,
+                uint8_t             *buffer,
+                uint32_t            buffSize,
+                UErrorCode          *status);
+
+/**
+ * Tokenize text using a rule-based tokenizer.
+ * @param bi The tokenizer to use.
+ * @param maxTokens The maximum number of tokens to return.
+ * @param outTokens An array of RuleBasedTokenRange to fill in with the tokens.
+ * @param outTokenFlags An (optional) array of uint32_t to fill in with token flags.
+ * @return The number of tokens returned, 0 if done.
+ * @internal
+ */
+U_INTERNAL int32_t U_EXPORT2
+urbtok_tokenize(UBreakIterator      *bi,
+               int32_t              maxTokens,
+               RuleBasedTokenRange  *outTokens,
+               unsigned long        *outTokenFlags);
+
+/**
+ * Swap the endianness of a set of binary break rules.
+ * @param rules A set of rules which need swapping.
+ * @param buffer The output buffer for the swapped rules, which must be the same
+ *               size as the input rules buffer.
+ * @param inIsBigEndian UBool indicating whether the input is big-endian
+ * @param outIsBigEndian UBool indicating whether the output should be big-endian
+ * @param status A UErrorCode to receive any errors.
+ * @internal
+ */
+U_INTERNAL void U_EXPORT2
+urbtok_swapBinaryRules(const uint8_t *rules,
+               uint8_t          *buffer,
+               UBool            inIsBigEndian,
+               UBool            outIsBigEndian,
+               UErrorCode       *status);
+
+
+#endif /* #if !UCONFIG_NO_BREAK_ITERATION */
+
+#endif


[36/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_replicator/test/06-doc-missing-stubs.t
----------------------------------------------------------------------
diff --git a/apps/couch_replicator/test/06-doc-missing-stubs.t b/apps/couch_replicator/test/06-doc-missing-stubs.t
deleted file mode 100755
index e17efc9..0000000
--- a/apps/couch_replicator/test/06-doc-missing-stubs.t
+++ /dev/null
@@ -1,304 +0,0 @@
-#!/usr/bin/env escript
-%% -*- erlang -*-
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
-% Test replication of documents with many leaf revisions.
-% Motivated by COUCHDB-1340 and other similar issues where a document
-% GET with a too long ?open_revs revision list doesn't work due to
-% maximum web server limits for the HTTP request path.
-
--record(user_ctx, {
-    name = null,
-    roles = [],
-    handler
-}).
-
--record(doc, {
-    id = <<"">>,
-    revs = {0, []},
-    body = {[]},
-    atts = [],
-    deleted = false,
-    meta = []
-}).
-
--record(att, {
-    name,
-    type,
-    att_len,
-    disk_len,
-    md5= <<>>,
-    revpos=0,
-    data,
-    encoding=identity
-}).
-
--define(b2l(B), binary_to_list(B)).
-
-source_db_name() -> <<"couch_test_rep_db_a">>.
-target_db_name() -> <<"couch_test_rep_db_b">>.
-
-target_revs_limit() -> 3.
-
-
-main(_) ->
-    test_util:init_code_path(),
-
-    etap:plan(128),
-    case (catch test()) of
-        ok ->
-            etap:end_tests();
-        Other ->
-            etap:diag(io_lib:format("Test died abnormally: ~p", [Other])),
-            etap:bail(Other)
-    end,
-    ok.
-
-
-% Test motivated by COUCHDB-1365.
-test() ->
-    couch_server_sup:start_link(test_util:config_files()),
-    ibrowse:start(),
-
-    Pairs = [
-        {source_db_name(), target_db_name()},
-        {{remote, source_db_name()}, target_db_name()},
-        {source_db_name(), {remote, target_db_name()}},
-        {{remote, source_db_name()}, {remote, (target_db_name())}}
-    ],
-
-    lists:foreach(
-        fun({Source, Target}) ->
-            {ok, SourceDb} = create_db(source_db_name()),
-            etap:diag("Populating source database"),
-            populate_db(SourceDb),
-            ok = couch_db:close(SourceDb),
-
-            etap:diag("Creating target database"),
-            {ok, TargetDb} = create_db(target_db_name()),
-            ok = couch_db:set_revs_limit(TargetDb, target_revs_limit()),
-            ok = couch_db:close(TargetDb),
-
-            etap:diag("Triggering replication"),
-            replicate(Source, Target),
-            etap:diag("Replication finished, comparing source and target databases"),
-            compare_dbs(SourceDb, TargetDb),
-
-            etap:diag("Updating source database docs"),
-            update_db_docs(couch_db:name(SourceDb), target_revs_limit() + 2),
-
-            etap:diag("Triggering replication again"),
-            replicate(Source, Target),
-            etap:diag("Replication finished, comparing source and target databases"),
-            compare_dbs(SourceDb, TargetDb),
-
-            etap:diag("Deleting databases"),
-            delete_db(TargetDb),
-            delete_db(SourceDb),
-            ok = timer:sleep(1000)
-        end,
-        Pairs),
-
-    couch_server_sup:stop(),
-    ok.
-
-
-populate_db(Db) ->
-    AttData = crypto:rand_bytes(6000),
-    Doc1 = #doc{
-        id = <<"doc1">>,
-        atts = [
-            #att{
-                name = <<"doc1_att1">>,
-                type = <<"application/foobar">>,
-                att_len = byte_size(AttData),
-                data = AttData
-            }
-        ]
-    },
-    {ok, _} = couch_db:update_doc(Db, Doc1, []).
-
-
-update_db_docs(DbName, Times) ->
-    {ok, Db} = couch_db:open_int(DbName, []),
-    {ok, _, _} = couch_db:enum_docs(
-        Db,
-        fun(FDI, _, Acc) -> db_fold_fun(FDI, Acc) end,
-        {DbName, Times},
-        []),
-    ok = couch_db:close(Db).
-
-
-db_fold_fun(FullDocInfo, {DbName, Times}) ->
-    {ok, Db} = couch_db:open_int(DbName, []),
-    {ok, Doc} = couch_db:open_doc(Db, FullDocInfo),
-    lists:foldl(
-        fun(_, {Pos, RevId}) ->
-            {ok, Db2} = couch_db:reopen(Db),
-            NewDocVersion = Doc#doc{
-                revs = {Pos, [RevId]},
-                body = {[{<<"value">>, base64:encode(crypto:rand_bytes(100))}]}
-            },
-            {ok, NewRev} = couch_db:update_doc(Db2, NewDocVersion, []),
-            NewRev
-        end,
-        {element(1, Doc#doc.revs), hd(element(2, Doc#doc.revs))},
-        lists:seq(1, Times)),
-    ok = couch_db:close(Db),
-    {ok, {DbName, Times}}.
-
-
-compare_dbs(Source, Target) ->
-    {ok, SourceDb} = couch_db:open_int(couch_db:name(Source), []),
-    {ok, TargetDb} = couch_db:open_int(couch_db:name(Target), []),
-
-    Fun = fun(FullDocInfo, _, Acc) ->
-        {ok, DocSource} = couch_db:open_doc(
-            SourceDb, FullDocInfo, [conflicts, deleted_conflicts]),
-        Id = DocSource#doc.id,
-
-        etap:diag("Verifying document " ++ ?b2l(Id)),
-
-        {ok, DocTarget} = couch_db:open_doc(
-            TargetDb, Id, [conflicts, deleted_conflicts]),
-        etap:is(DocTarget#doc.body, DocSource#doc.body,
-            "Same body in source and target databases"),
-
-        etap:is(
-            couch_doc:to_json_obj(DocTarget, []),
-            couch_doc:to_json_obj(DocSource, []),
-            "Same doc body in source and target databases"),
-
-        #doc{atts = SourceAtts} = DocSource,
-        #doc{atts = TargetAtts} = DocTarget,
-        etap:is(
-            lists:sort([N || #att{name = N} <- SourceAtts]),
-            lists:sort([N || #att{name = N} <- TargetAtts]),
-            "Document has same number (and names) of attachments in "
-            "source and target databases"),
-
-        lists:foreach(
-            fun(#att{name = AttName} = Att) ->
-                etap:diag("Verifying attachment " ++ ?b2l(AttName)),
-
-                {ok, AttTarget} = find_att(TargetAtts, AttName),
-                SourceMd5 = att_md5(Att),
-                TargetMd5 = att_md5(AttTarget),
-                case AttName of
-                <<"att1">> ->
-                    etap:is(Att#att.encoding, gzip,
-                        "Attachment is gzip encoded in source database"),
-                    etap:is(AttTarget#att.encoding, gzip,
-                        "Attachment is gzip encoded in target database"),
-                    DecSourceMd5 = att_decoded_md5(Att),
-                    DecTargetMd5 = att_decoded_md5(AttTarget),
-                    etap:is(DecTargetMd5, DecSourceMd5,
-                        "Same identity content in source and target databases");
-                _ ->
-                    etap:is(Att#att.encoding, identity,
-                        "Attachment is not encoded in source database"),
-                    etap:is(AttTarget#att.encoding, identity,
-                        "Attachment is not encoded in target database")
-                end,
-                etap:is(TargetMd5, SourceMd5,
-                    "Same content in source and target databases"),
-                etap:is(is_integer(Att#att.disk_len), true,
-                    "#att.disk_len is an integer in source database"),
-                etap:is(is_integer(Att#att.att_len), true,
-                    "#att.att_len is an integer in source database"),
-                etap:is(is_integer(AttTarget#att.disk_len), true,
-                    "#att.disk_len is an integer in target database"),
-                etap:is(is_integer(AttTarget#att.att_len), true,
-                    "#att.att_len is an integer in target database"),
-                etap:is(Att#att.disk_len, AttTarget#att.disk_len,
-                    "Same identity length in source and target databases"),
-                etap:is(Att#att.att_len, AttTarget#att.att_len,
-                    "Same encoded length in source and target databases"),
-                etap:is(Att#att.type, AttTarget#att.type,
-                    "Same type in source and target databases"),
-                etap:is(Att#att.md5, SourceMd5, "Correct MD5 in source database"),
-                etap:is(AttTarget#att.md5, SourceMd5, "Correct MD5 in target database")
-            end,
-            SourceAtts),
-
-        {ok, Acc}
-    end,
-
-    {ok, _, _} = couch_db:enum_docs(SourceDb, Fun, [], []),
-    ok = couch_db:close(SourceDb),
-    ok = couch_db:close(TargetDb).
-
-
-find_att([], _Name) ->
-    nil;
-find_att([#att{name = Name} = Att | _], Name) ->
-    {ok, Att};
-find_att([_ | Rest], Name) ->
-    find_att(Rest, Name).
-
-
-att_md5(Att) ->
-    Md50 = couch_doc:att_foldl(
-        Att,
-        fun(Chunk, Acc) -> couch_util:md5_update(Acc, Chunk) end,
-        couch_util:md5_init()),
-    couch_util:md5_final(Md50).
-
-att_decoded_md5(Att) ->
-    Md50 = couch_doc:att_foldl_decode(
-        Att,
-        fun(Chunk, Acc) -> couch_util:md5_update(Acc, Chunk) end,
-        couch_util:md5_init()),
-    couch_util:md5_final(Md50).
-
-
-db_url(DbName) ->
-    iolist_to_binary([
-        "http://", couch_config:get("httpd", "bind_address", "127.0.0.1"),
-        ":", integer_to_list(mochiweb_socket_server:get(couch_httpd, port)),
-        "/", DbName
-    ]).
-
-
-create_db(DbName) ->
-    couch_db:create(
-        DbName,
-        [{user_ctx, #user_ctx{roles = [<<"_admin">>]}}, overwrite]).
-
-
-delete_db(Db) ->
-    ok = couch_server:delete(
-        couch_db:name(Db), [{user_ctx, #user_ctx{roles = [<<"_admin">>]}}]).
-
-
-replicate({remote, Db}, Target) ->
-    replicate(db_url(Db), Target);
-
-replicate(Source, {remote, Db}) ->
-    replicate(Source, db_url(Db));
-
-replicate(Source, Target) ->
-    RepObject = {[
-        {<<"source">>, Source},
-        {<<"target">>, Target}
-    ]},
-    {ok, Rep} = couch_replicator_utils:parse_rep_doc(
-        RepObject, #user_ctx{roles = [<<"_admin">>]}),
-    {ok, Pid} = couch_replicator:async_replicate(Rep),
-    MonRef = erlang:monitor(process, Pid),
-    receive
-    {'DOWN', MonRef, process, Pid, Reason} ->
-        etap:is(Reason, normal, "Replication finished successfully")
-    after 300000 ->
-        etap:bail("Timeout waiting for replication to finish")
-    end.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_replicator/test/07-use-checkpoints.t
----------------------------------------------------------------------
diff --git a/apps/couch_replicator/test/07-use-checkpoints.t b/apps/couch_replicator/test/07-use-checkpoints.t
deleted file mode 100755
index cefc1a7..0000000
--- a/apps/couch_replicator/test/07-use-checkpoints.t
+++ /dev/null
@@ -1,256 +0,0 @@
-#!/usr/bin/env escript
-%% -*- erlang -*-
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
-% Verify that compacting databases that are being used as the source or
-% target of a replication doesn't affect the replication and that the
-% replication doesn't hold their reference counters forever.
-
--define(b2l(B), binary_to_list(B)).
-
--record(user_ctx, {
-    name = null,
-    roles = [],
-    handler
-}).
-
--record(doc, {
-    id = <<"">>,
-    revs = {0, []},
-    body = {[]},
-    atts = [],
-    deleted = false,
-    meta = []
-}).
-
--record(db, {
-    main_pid = nil,
-    update_pid = nil,
-    compactor_pid = nil,
-    instance_start_time, % number of microsecs since jan 1 1970 as a binary string
-    fd,
-    updater_fd,
-    fd_ref_counter,
-    header = nil,
-    committed_update_seq,
-    fulldocinfo_by_id_btree,
-    docinfo_by_seq_btree,
-    local_docs_btree,
-    update_seq,
-    name,
-    filepath,
-    validate_doc_funs = [],
-    security = [],
-    security_ptr = nil,
-    user_ctx = #user_ctx{},
-    waiting_delayed_commit = nil,
-    revs_limit = 1000,
-    fsync_options = [],
-    options = [],
-    compression,
-    before_doc_update,
-    after_doc_read
-}).
-
--record(rep, {
-    id,
-    source,
-    target,
-    options,
-    user_ctx,
-    doc_id
-}).
-
-
-source_db_name() -> <<"couch_test_rep_db_a">>.
-target_db_name() -> <<"couch_test_rep_db_b">>.
-
-
-main(_) ->
-    test_util:init_code_path(),
-
-    etap:plan(16),
-    case (catch test()) of
-        ok ->
-            etap:end_tests();
-        Other ->
-            etap:diag(io_lib:format("Test died abnormally: ~p", [Other])),
-            etap:bail(Other)
-    end,
-    ok.
-
-
-test() ->
-    couch_server_sup:start_link(test_util:config_files()),
-    ibrowse:start(),
-
-    test_use_checkpoints(false),
-    test_use_checkpoints(true),
-
-    couch_server_sup:stop(),
-    ok.
-
-
-test_use_checkpoints(UseCheckpoints) ->
-    Pairs = [
-        {source_db_name(), target_db_name()},
-        {{remote, source_db_name()}, target_db_name()},
-        {source_db_name(), {remote, target_db_name()}},
-        {{remote, source_db_name()}, {remote, (target_db_name())}}
-    ],
-
-    ListenerFun = case UseCheckpoints of
-    false ->
-        fun({finished, _, {CheckpointHistory}}) ->
-            etap:is(CheckpointHistory,
-            [{<<"use_checkpoints">>,false}],
-            "No checkpoints found");
-        (_) ->
-            ok
-        end;
-    true ->
-        fun({finished, _, {CheckpointHistory}}) ->
-            SessionId = lists:keyfind(
-                <<"session_id">>, 1, CheckpointHistory),
-            etap:isnt(SessionId, false, "There's a checkpoint");
-        (_) ->
-            ok
-        end
-    end,
-    {ok, Listener} = couch_replicator_notifier:start_link(ListenerFun),
-
-    lists:foreach(
-        fun({Source, Target}) ->
-            {ok, SourceDb} = create_db(source_db_name()),
-            etap:diag("Populating source database"),
-            populate_db(SourceDb, 100),
-            ok = couch_db:close(SourceDb),
-
-            etap:diag("Creating target database"),
-            {ok, TargetDb} = create_db(target_db_name()),
-            ok = couch_db:close(TargetDb),
-
-            etap:diag("Setup replicator notifier listener"),
-
-            etap:diag("Triggering replication"),
-            replicate(Source, Target, UseCheckpoints),
-
-            etap:diag("Replication finished, comparing source and target databases"),
-            compare_dbs(SourceDb, TargetDb),
-
-            etap:diag("Deleting databases"),
-            delete_db(TargetDb),
-            delete_db(SourceDb),
-
-            ok = timer:sleep(1000)
-        end,
-        Pairs),
-
-    couch_replicator_notifier:stop(Listener).
-
-
-populate_db(Db, DocCount) ->
-    Docs = lists:foldl(
-        fun(DocIdCounter, Acc) ->
-            Id = iolist_to_binary(["doc", integer_to_list(DocIdCounter)]),
-            Value = iolist_to_binary(["val", integer_to_list(DocIdCounter)]),
-            Doc = #doc{
-                id = Id,
-                body = {[ {<<"value">>, Value} ]}
-            },
-            [Doc | Acc]
-        end,
-        [], lists:seq(1, DocCount)),
-    {ok, _} = couch_db:update_docs(Db, Docs, []).
-
-
-compare_dbs(#db{name = SourceName}, #db{name = TargetName}) ->
-    {ok, SourceDb} = couch_db:open_int(SourceName, []),
-    {ok, TargetDb} = couch_db:open_int(TargetName, []),
-    Fun = fun(FullDocInfo, _, Acc) ->
-        {ok, Doc} = couch_db:open_doc(SourceDb, FullDocInfo),
-        {Props} = DocJson = couch_doc:to_json_obj(Doc, [attachments]),
-        DocId = couch_util:get_value(<<"_id">>, Props),
-        DocTarget = case couch_db:open_doc(TargetDb, DocId) of
-        {ok, DocT} ->
-            DocT;
-        Error ->
-            etap:bail("Error opening document '" ++ ?b2l(DocId) ++
-                "' from target: " ++ couch_util:to_list(Error))
-        end,
-        DocTargetJson = couch_doc:to_json_obj(DocTarget, [attachments]),
-        case DocTargetJson of
-        DocJson ->
-            ok;
-        _ ->
-            etap:bail("Content from document '" ++ ?b2l(DocId) ++
-                "' differs in target database")
-        end,
-        {ok, Acc}
-    end,
-    {ok, _, _} = couch_db:enum_docs(SourceDb, Fun, [], []),
-    etap:diag("Target database has the same documents as the source database"),
-    ok = couch_db:close(SourceDb),
-    ok = couch_db:close(TargetDb).
-
-
-db_url(DbName) ->
-    iolist_to_binary([
-        "http://", couch_config:get("httpd", "bind_address", "127.0.0.1"),
-        ":", integer_to_list(mochiweb_socket_server:get(couch_httpd, port)),
-        "/", DbName
-    ]).
-
-
-create_db(DbName) ->
-    {ok, Db} = couch_db:create(
-        DbName,
-        [{user_ctx, #user_ctx{roles = [<<"_admin">>]}}, overwrite]),
-    couch_db:close(Db),
-    {ok, Db}.
-
-
-delete_db(#db{name = DbName, main_pid = Pid}) ->
-    ok = couch_server:delete(
-        DbName, [{user_ctx, #user_ctx{roles = [<<"_admin">>]}}]),
-    MonRef = erlang:monitor(process, Pid),
-    receive
-    {'DOWN', MonRef, process, Pid, _Reason} ->
-        ok
-    after 30000 ->
-        etap:bail("Timeout deleting database")
-    end.
-
-
-replicate({remote, Db}, Target, UseCheckpoints) ->
-    replicate(db_url(Db), Target, UseCheckpoints);
-
-replicate(Source, {remote, Db}, UseCheckpoints) ->
-    replicate(Source, db_url(Db), UseCheckpoints);
-
-replicate(Source, Target, UseCheckpoints) ->
-    RepObject = {[
-        {<<"source">>, Source},
-        {<<"target">>, Target},
-        {<<"use_checkpoints">>, UseCheckpoints}
-    ]},
-    {ok, Rep} = couch_replicator_utils:parse_rep_doc(
-        RepObject, #user_ctx{roles = [<<"_admin">>]}),
-    {ok, Pid} = couch_replicator:async_replicate(Rep),
-    MonRef = erlang:monitor(process, Pid),
-    receive
-    {'DOWN', MonRef, process, Pid, Reason} ->
-        etap:is(Reason, normal, "Replication finished successfully")
-    after 300000 ->
-        etap:bail("Timeout waiting for replication to finish")
-    end.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couchjs-node/README.md
----------------------------------------------------------------------
diff --git a/apps/couchjs-node/README.md b/apps/couchjs-node/README.md
deleted file mode 100644
index 551c3df..0000000
--- a/apps/couchjs-node/README.md
+++ /dev/null
@@ -1,32 +0,0 @@
-# CouchJS
-
-## Drop-in replacement JavaScript engine for Apache CouchDB
-
-CouchJS is a command-line Node.js program. It is 100% compatible with Apache CouchDB's built-in JavaScript system.
-
-By using CouchJS, you will get 100% CouchDB compatibility (the test suite completely passes) but your JavaScript environment is V8, or Node.js.
-
-See share/doc/src/experimental.rst for installation instructions.
-
-## Idea
-
-JavaScript is decoupled from the CouchDB core. To do JavaScript stuff, CouchDB runs a normal Unix subprocess, `couchjs`. This subprocess is just a read-eval-print loop on standard i/o. CouchDB passes `couchjs` a file name, and *that file* contains the view server  implementation.
-
-This tool duplicates the "REPL" look and feel of `couchjs` and supports the exact same view server implementation.
-
-## Security
-
-I have no idea. I would not trust it for production use.
-
-## Log
-
-If you create a file, `/tmp/couchjs.log` then *couchjs* will output debugging messages there.
-
-## License
-
-Apache 2.0
-
-See the [Apache 2.0 license](named/blob/master/LICENSE).
-
-[tap]: https://github.com/isaacs/node-tap
-[def]: https://github.com/iriscouch/defaultable

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couchjs-node/cli.js
----------------------------------------------------------------------
diff --git a/apps/couchjs-node/cli.js b/apps/couchjs-node/cli.js
deleted file mode 100755
index 5447dd5..0000000
--- a/apps/couchjs-node/cli.js
+++ /dev/null
@@ -1,89 +0,0 @@
-#!/usr/bin/env node
-
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-var fs = require('fs');
-var Fiber = require('fibers');
-var optimist = require('optimist');
-
-var couchjs = require('./couchjs');
-var package_json = require('./package.json');
-var LineStream = require('./stream');
-var inspector = require('./inspector');
-var log = require('./console').log;
-
-
-var opts = optimist.boolean(['h', 'V', 'H'])
-                   .describe({ 'h': 'display a short help message and exit',
-                             'V': 'display version information and exit',
-                             'H': 'enable couchjs cURL bindings (not implemented)'
-                             })
-                   .usage('$0 <path to main.js>');
-
-
-function main() {
-
-  'use strict';
-
-  var main_js = opts.argv._[0];
-
-  if (!main_js) {
-    return console.error(opts.help());
-  }
-
-  log('couchjs/%s %s: %s', package_json.version, process.pid, main_js);
-
-  if (process.env.COUCHJS_DEBUG_PORT) {
-    inspector(+process.env.COUCHJS_DEBUG_PORT);
-  }
-
-  fs.readFile(main_js, 'utf8', function(er, body) {
-    if (er) {
-      throw er;
-    }
-
-    var stdin = new LineStream.v2();
-
-    stdin.on('readable', function() {
-      var buf = stdin.read();
-
-      if (buf) {
-        couchjs.stdin(buf);
-      }
-    });
-
-    stdin.on('end', function() {
-      log('Terminate; connection to parent closed');
-      process.exit(0);
-    });
-
-    process.stdin.setEncoding('utf8');
-    process.stdin.pipe(stdin);
-
-    var main_func = Function(['print', 'readline', 'evalcx', 'gc', 'quit'], body);
-
-    log('Call main');
-
-    new Fiber(function() {
-      main_func(couchjs.print, couchjs.readline, couchjs.evalcx, couchjs.gc);
-    }).run();
-  });
-
-  process.on('uncaughtException', function(er) {
-    log('Error:\n%s', er.stack);
-  });
-}
-
-if (require.main === module) {
-  main();
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couchjs-node/console.js
----------------------------------------------------------------------
diff --git a/apps/couchjs-node/console.js b/apps/couchjs-node/console.js
deleted file mode 100644
index 18e7241..0000000
--- a/apps/couchjs-node/console.js
+++ /dev/null
@@ -1,66 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-var fs = require('fs');
-var util = require('util');
-
-var noop = function() {};
-
-module.exports = {};
-module.exports.log = noop;
-module.exports.debug = noop;
-module.exports.info = noop;
-module.exports.warn = noop;
-module.exports.error = noop;
-
-var LOG_PATH = '/tmp/couchjs.log';
-var stat = null;
-var LOG = null;
-
-try {
-  stat = fs.statSync(LOG_PATH);
-} catch(er) {}
-
-if (stat) {
-  LOG = fs.createWriteStream(LOG_PATH, {
-    'flags':'a'
-  });
-
-  var log = function () {
-    var str = util.format.apply(this, arguments);
-    LOG.write(str + '\n');
-  };
-
-  var on_err = function (er) {
-    module.exports.error('Uncaught error:\n%s', er.stack || er.message || JSON.stringify(er));
-
-    if (er.stack) {
-      er = ['fatal', 'unknown_error', er.stack];
-    }
-
-    process.stdout.write(JSON.stringify(er) + '\n');
-    process.exit(1);
-  };
-
-  module.exports.log = log;
-  module.exports.debug = log;
-  module.exports.info = log;
-  module.exports.warn = log;
-  module.exports.error = log;
-
-  process.on('exit', function() {
-    module.exports.log('Exit %d', process.pid);
-  });
-
-  process.on('uncaughtException', on_err);
-}
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couchjs-node/couchdb.js
----------------------------------------------------------------------
diff --git a/apps/couchjs-node/couchdb.js b/apps/couchjs-node/couchdb.js
deleted file mode 100755
index d420540..0000000
--- a/apps/couchjs-node/couchdb.js
+++ /dev/null
@@ -1,29 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-
-var http = require('http');
-
-function handler(req, res) {
-  res.writeHead(200);
-  res.end('Hello: ' + req.url + '\n');
-}
-
-if (require.main === module) {
-  var http = require('http');
-  var server = http.createServer(handler);
-
-  server.listen(3000);
-  console.log('Listening on :3000');
-}
-
-module.exports = handler;

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couchjs-node/couchjs.js
----------------------------------------------------------------------
diff --git a/apps/couchjs-node/couchjs.js b/apps/couchjs-node/couchjs.js
deleted file mode 100644
index ccc1aa9..0000000
--- a/apps/couchjs-node/couchjs.js
+++ /dev/null
@@ -1,133 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-
-
-var vm = require('vm');
-var Fiber = require('fibers');
-var util = require('util');
-
-var XML = require('./xml');
-var log = require('./console').log;
-
-var INPUT = {
-  'queue':[],
-  'waiting':null
-};
-
-
-function print(line) {
-  log('STDOUT %s: %s', process.pid, line);
-  process.stdout.write(line + '\n');
-
-  try {
-    line = JSON.parse(line);
-  } catch(er) {
-    return;
-  }
-
-  if (line[0] === 'log') {
-    log('LOG: %s', line[1]);
-  }
-}
-
-function stdin (line) {
-  log('STDIN %s: %s', process.pid, line.trim());
-
-  if (INPUT.waiting) {
-    INPUT.waiting.run(line);
-  } else {
-    INPUT.queue.push(line);
-  }
-}
-
-function readline () {
-  var line = INPUT.queue.shift();
-
-  if (line) {
-    return line;
-  }
-
-  INPUT.waiting = Fiber.current;
-  line = Fiber.yield();
-  INPUT.waiting = null;
-
-  return line;
-}
-
-
-function evalcx (source, sandbox) {
-  sandbox = sandbox || {};
-  var func;
-  //log('evalcx in %j: %j', Object.keys(sandbox), source)
-
-  if (source === '') {
-    return sandbox;
-  }
-
-  // source might be "function(doc) { emit(doc._id, 1) }"
-  source = source.replace(/;+$/, '');
-
-  sandbox.XML = sandbox.XML || XML;
-  source = '(' + source + ')';
-
-  try {
-    var id = Math.floor(Math.random() * 1000*1000);
-    var filename = '_couchdb:' + id + '.js';
-    var script = vm.createScript(source, filename);
-    func = script.runInNewContext(sandbox);
-  } catch (er) {
-    log('Error making code: %s', er.stack);
-    return sandbox;
-  }
-
-  return func;
-}
-
-function quit(code) {
-  code = code || 1;
-  if (code < 0) {
-    code = -code;
-  }
-
-  process.exit(code);
-}
-
-function gc() { }
-
-
-function toSource() {
-  if (typeof this === 'function') {
-    return '' + this;
-  }
-
-  if (this instanceof Error) {
-    return this.stack;
-  }
-
-  return util.inspect(this);
-}
-
-Error.prototype.toSource = Error.prototype.toSource || toSource;
-Error.prototype.toString = Error.prototype.toString || toSource;
-Function.prototype.toSource = Function.prototype.toSource || toSource;
-Function.prototype.toString = Function.prototype.toString || toSource;
-
-module.exports = {
-  'print': print,
-  'readline': readline,
-  'stdin': stdin,
-  'evalcx': evalcx,
-  'quit': quit,
-  'gc': gc
-};
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couchjs-node/inspector.js
----------------------------------------------------------------------
diff --git a/apps/couchjs-node/inspector.js b/apps/couchjs-node/inspector.js
deleted file mode 100755
index 48182e5..0000000
--- a/apps/couchjs-node/inspector.js
+++ /dev/null
@@ -1,101 +0,0 @@
-#!/usr/bin/env node
-
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-
-
-var cp = require('child_process');
-var log = require('./console').log;
-
-function watchInspector(child) {
-
-  child.stderr.on('data', function(body) {
-    log('Inspector STDERR: %s', body);
-  });
-
-  child.stdout.on('data', function(body) {
-    log('Inspector STDOUT: %s', body);
-  });
-
-  child.on('exit', function(code, signal) {
-    log('Inspector exited %d signal=%j', code, signal);
-    process.exit(code);
-  });
-
-  process.on('exit', function() {
-    log('Kill inspector upon exit: %d', child.pid);
-    process.kill(child.pid, 'SIGTERM');
-  });
-
-}
-
-function start (debugPort) {
-
-  if (!debugPort || typeof debugPort !== 'number') {
-    throw new Error('Need a listen debugPort');
-  }
-
-  var webPort = debugPort + 1;
-  var cmd = __filename;
-  var args = [debugPort, webPort];
-  var opts = {
-    'cwd': __dirname,
-    'stdio': 'pipe',
-    'detached': false
-  };
-
-  log('Start inspector: %s %j %j', cmd, args, opts);
-
-  var inspector = cp.spawn(cmd, args, opts);
-
-  watchInspector(inspector);
-
-  log('Enable remote debug pid=%d port=%d', process.pid, debugPort);
-
-  process.debugPort = debugPort;
-  process.kill(process.pid, 'SIGUSR1');
-}
-
-function main() {
-  var debugPort = +process.argv[2];
-  var webPort = +process.argv[3];
-
-  if (!debugPort || !webPort) {
-    throw new Error('Bad arguments: need debugPort and webPort');
-  }
-
-  console.log('Start inspector debugPort=%j webPort=%j', debugPort, webPort);
-
-  var DebugServer = require('node-inspector/lib/debug-server');
-  var server = new DebugServer();
-
-  server.on('close', function() {
-    console.log('Server closed');
-    process.exit(0);
-  });
-
-  server.start({
-    'webPort':webPort,
-    'debugPort':debugPort
-  });
-
-  process.on('uncaughtException', function(er) {
-    console.log('Error:\n%s', er.stack);
-  });
-}
-
-module.exports = start;
-
-if (require.main === module) {
-  main();
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couchjs-node/package.json
----------------------------------------------------------------------
diff --git a/apps/couchjs-node/package.json b/apps/couchjs-node/package.json
deleted file mode 100644
index 445f3b9..0000000
--- a/apps/couchjs-node/package.json
+++ /dev/null
@@ -1,40 +0,0 @@
-{
-  "name": "couchjs",
-  "description": "Drop-in replacement for CouchDB JavaScript view server",
-  "keywords": [ "couchdb", "couchjs" ],
-  "version": "0.3.2",
-  "author": "Jason Smith <jh...@iriscouch.com> (http://www.iriscouch.com)",
-  "repository": {
-    "type":"git",
-    "url":"https://github.com/iriscouch/couchjs"
-  },
-  "engines": {
-    "node": ">= 0.8"
-  },
-  "main": "./couchjs.js",
-  "bin": {
-    "couchjs-node":"./cli.js"
-  },
-  "couchdb": {
-    "main":"./couchdb.js",
-    "vhosts": [
-      "127.0.0.1.xip.io"
-    ]
-  },
-  "bundledDependencies": [
-    "node-inspector"
-  ],
-  "dependencies": {
-    "optimist": "~0.3.4",
-    "async"   : "~0.2.5",
-    "mkdirp"  : "~0.3.4",
-    "fibers"  : "~1.0.0",
-    "request" : "~2.9.203",
-    "pushover": "~1.2.1",
-    "defaultable": "~0.7.2",
-    "node-inspector": "git://github.com/iriscouch/node-inspector#couchjs"
-  },
-  "devDependencies": {
-    "tap": "~0.2.5"
-  }
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couchjs-node/sandbox.js
----------------------------------------------------------------------
diff --git a/apps/couchjs-node/sandbox.js b/apps/couchjs-node/sandbox.js
deleted file mode 100644
index 5c18ef4..0000000
--- a/apps/couchjs-node/sandbox.js
+++ /dev/null
@@ -1,47 +0,0 @@
-// from https://github.com/KlausTrainer/sandbox.js
-exports.runInSandbox = function(src, ctx, whitelist) {
-  var vm = require('vm');
-  var sandbox;
-
-  if (ctx && ctx.require) {
-
-    whitelist = whitelist || [];
-
-    var insecureRequire = ctx.require;
-    var module = require('module');
-    var oldModulePrototype = module.prototype;
-
-    var secureRequire = function(moduleName) {
-
-      if (whitelist.indexOf(moduleName) === -1) {
-        module.prototype = oldModulePrototype;
-
-        throw new Error("'" + moduleName + "' is not whitelisted");
-
-      } else {
-        var requiredModule = insecureRequire(moduleName);
-
-        module.prototype = oldModulePrototype;
-
-        return requiredModule;
-      }
-    };
-
-    module.prototype = {
-      require: secureRequire,
-      load: module.prototype.load,
-      _compile: module.prototype._compile
-    };
-
-    module._cache = {};
-
-    ctx.require = secureRequire;
-    sandbox = Object.freeze(vm.createContext(ctx));
-    ctx.require = insecureRequire;
-
-  } else {
-    sandbox = Object.freeze(vm.createContext(ctx || {}));
-  }
-
-  return vm.createScript('(function() {"use strict"; return (' + src + ')()}())').runInContext(sandbox);
-};

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couchjs-node/stream.js
----------------------------------------------------------------------
diff --git a/apps/couchjs-node/stream.js b/apps/couchjs-node/stream.js
deleted file mode 100644
index ebffc30..0000000
--- a/apps/couchjs-node/stream.js
+++ /dev/null
@@ -1,115 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-// Text line stream
-
-var stream = require('stream');
-var util = require('util');
-
-
-function LineStream() {
-
-  var self = this;
-  stream.call(self);
-
-  self.readable = true;
-  self.writable = true;
-
-  self.buffer = '';
-  self.downstream = null;
-
-  self.on('pipe', function(upstream) {
-    upstream.on('end', function(data, encoding) {
-      self.emit('end', data, encoding);
-    });
-  });
-}
-
-function LineStream2() {
-
-  if (!(this instanceof LineStream2)) {
-    return new LineStream2();
-  }
-
-  stream.Transform.call(this);
-  this.setEncoding('utf8');
-}
-
-util.inherits(LineStream2, stream.Transform);
-
-LineStream2.prototype._transform = function(message, encoding, done) {
-  var self = this;
-
-  message = message.toString(encoding);
-  var lines = message.split(/\n/);
-
-  // If the data ends in "\n" this will be ""; otherwise the final partial line.
-  var remainder = lines.pop();
-  if (remainder) {
-    this.unshift(remainder);
-  }
-
-  lines.forEach(function(line) {
-    self.push(line);
-  });
-
-  done();
-};
-
-util.inherits(LineStream, stream);
-
-
-
-LineStream.prototype.write = function(data) {
-  var self = this;
-
-  data = data || '';
-  if (typeof data !== 'string') {
-    return self.error(new Error('Data was not a string: ' + util.inspect(data)));
-  }
-
-  self.buffer += data;
-  var lines = self.buffer.split(/\n/);
-  self.buffer = lines.pop(); // If the data ended in "\n" this will be ""; otherwise the final partial line.
-
-  lines.forEach(function(line) {
-    self.emit('data', line);
-  });
-};
-
-
-LineStream.prototype.end = function(data) {
-  var self = this;
-
-  self.is_ending = true;
-  self.writable = false;
-
-  // Always call write, even with no data, so it can fire the "end" event.
-  self.write(data);
-};
-
-
-LineStream.prototype.error = function(er) {
-  var self = this;
-
-  self.readable = false;
-  self.writable = false;
-  self.emit('error', er);
-
-  // The write() method sometimes returns this value, so if there was an error, make write() return false.
-  return false;
-};
-
-
-module.exports = LineStream;
-module.exports.v2 = LineStream2;
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couchjs-node/test/experiment.js
----------------------------------------------------------------------
diff --git a/apps/couchjs-node/test/experiment.js b/apps/couchjs-node/test/experiment.js
deleted file mode 100644
index 9197ec6..0000000
--- a/apps/couchjs-node/test/experiment.js
+++ /dev/null
@@ -1,125 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-var vm = require('vm');
-var util = require('util');
-
-var STATE = 'wait';
-
-function main() {
-  process.debugPort = 5859;
-  process.kill(process.pid, 'SIGUSR1');
-
-  setTimeout(function() {
-    stuff(0);
-  }, 1000);
-}
-
-function stuff(count) {
-
-  console.log('Doing stuff: %d', count);
-  STATE = 'vm';
-  console.log('More stuff: %d', count);
-
-  if (STATE === 'done') {
-    console.log('Done');
-  } else if (STATE === 'code') {
-    setTimeout(code, 1000);
-  } else if(STATE === 'eval') {
-    test_eval();
-  } else if(STATE === 'vm') {
-    test_vm();
-  } else if(STATE === 'wait') {
-    setTimeout(function() {
-      stuff(count+1);
-    }, 1000);
-  } else {
-    throw new Error('Unknown state: ' + STATE);
-  }
-}
-
-function code() {
-  var code = [
-    'var foo = "in the code"',
-    'console.log("This is some code")',
-    'debugger',
-    'console.log("foo = " + foo)'
-    ].join('\n');
-
-  var runner = Function([], code);
-
-  console.log('Run runner in 1s');
-
-  setTimeout(run_runner, 1000)
-
-  function run_runner() {
-    console.log('About to run runner');
-    debugger;
-    runner();
-    console.log('Runner done');
-  }
-}
-
-function test_eval() {
-  console.log('Test eval in 1s');
-  setTimeout(run_eval, 1000);
-
-  var code = [
-    'var foo = "in eval"',
-    'console.log("This is eval")',
-    'debugger',
-    'console.log("foo = " + foo)'
-    ].join('\n');
-
-  function run_eval() {
-    console.log('Run eval now');
-    debugger;
-    eval(code);
-  }
-}
-
-function test_vm() {
-  console.log('Test vm');
-
-  var code = [
-    'var i = 10',
-    'setTimeout(hello, 1000)',
-    '',
-    'function hello() {',
-    '  debugger',
-    '  console.log("Hello: " + i)',
-    '  if(--i)',
-    '    setTimeout(hello, 1000)',
-    '}'
-  ].join('\n');
-
-  console.log('Run vm now');
-  var filename = '_couchdb:code.js';
-
-  var sandbox = {};
-  var ok = ['console', 'setTimeout'];
-
-  ok.forEach(function(key) {
-    sandbox[key] = global[key];
-  });
-
-  var ctx = vm.createContext(sandbox);
-  var script = vm.createScript(code, filename);
-
-  var r = script.runInNewContext(sandbox);
-  console.log('Result:\n%s', util.inspect(r, false, 10));
-  return r;
-}
-
-if (require.main === module) {
-  main();
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couchjs-node/xml.js
----------------------------------------------------------------------
diff --git a/apps/couchjs-node/xml.js b/apps/couchjs-node/xml.js
deleted file mode 100644
index b64d221..0000000
--- a/apps/couchjs-node/xml.js
+++ /dev/null
@@ -1,22 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-
-function XML () {
-  this.foo = 'bar';
-}
-
-XML.prototype.toXMLString = function() {
-  return '<xml>\n  <title>test</title>\n</xml>';
-};
-
-module.exports = XML;

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/Gruntfile.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/Gruntfile.js b/apps/fauxton/Gruntfile.js
deleted file mode 100644
index 3afaa1f..0000000
--- a/apps/fauxton/Gruntfile.js
+++ /dev/null
@@ -1,441 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-
-// This is the main application configuration file.  It is a Grunt
-// configuration file, which you can learn more about here:
-// https://github.com/cowboy/grunt/blob/master/docs/configuring.md
-
-module.exports = function(grunt) {
-  var helper = require('./tasks/helper').init(grunt),
-  _ = grunt.util._,
-  path = require('path');
-
-  var couch_config = function () {
-
-    var default_couch_config = {
-      fauxton: {
-        db: 'http://localhost:5984/fauxton',
-        app: './couchapp.js',
-        options: {
-          okay_if_missing: true
-        }
-      }
-    };
-
-    var settings_couch_config = helper.readSettingsFile().couch_config;
-    return settings_couch_config || default_couch_config;
-  }();
-
-  var cleanableAddons =  function () {
-    var theListToClean = [];
-    helper.processAddons(function(addon){
-      // Only clean addons that are included from a local dir
-      if (addon.path){
-        theListToClean.push("app/addons/" + addon.name);
-      }
-    });
-
-    return theListToClean;
-  }();
-
-  var cleanable = function(){
-    // Whitelist files and directories to be cleaned
-    // You'll always want to clean these two directories
-    // Now find the external addons you have and add them for cleaning up
-    return _.union(["dist/", "app/load_addons.js"], cleanableAddons);
-  }();
-
-  var assets = function(){
-    // Base assets
-    var theAssets = {
-      less:{
-        paths: ["assets/less"],
-        files: {
-          "dist/debug/css/fauxton.css": "assets/less/fauxton.less"
-        }
-      },
-      img: ["assets/img/**"]
-    };
-    helper.processAddons(function(addon){
-      // Less files from addons
-      var root = addon.path || "app/addons/" + addon.name;
-      var lessPath = root + "/assets/less";
-      if(path.existsSync(lessPath)){
-        // .less files exist for this addon
-        theAssets.less.paths.push(lessPath);
-        theAssets.less.files["dist/debug/css/" + addon.name + ".css"] =
-          lessPath + "/" + addon.name + ".less";
-      }
-      // Images
-      root = addon.path || "app/addons/" + addon.name;
-      var imgPath = root + "/assets/img";
-      if(path.existsSync(imgPath)){
-        theAssets.img.push(imgPath + "/**");
-      }
-    });
-    return theAssets;
-  }();
-
-  var templateSettings = function(){
-    var defaultSettings = {
-     "development": {
-        "src": "assets/index.underscore",
-        "dest": "dist/debug/index.html",
-        "variables": {
-          "requirejs": "/assets/js/libs/require.js",
-          "css": "./css/index.css",
-          "base": null
-        }
-      },
-      "release": {
-        "src": "assets/index.underscore",
-        "dest": "dist/debug/index.html",
-        "variables": {
-          "requirejs": "./js/require.js",
-          "css": "./css/index.css",
-          "base": null
-        }
-      }
-    };
-
-    var settings = helper.readSettingsFile();
-    return settings.template || defaultSettings;
-  }();
-
-  grunt.initConfig({
-
-    // The clean task ensures all files are removed from the dist/ directory so
-    // that no files linger from previous builds.
-    clean: {
-      release:  cleanable,
-      watch: cleanableAddons
-    },
-
-    // The lint task will run the build configuration and the application
-    // JavaScript through JSHint and report any errors.  You can change the
-    // options for this task, by reading this:
-    // https://github.com/cowboy/grunt/blob/master/docs/task_lint.md
-    lint: {
-      files: [
-        "build/config.js", "app/**/*.js" 
-      ]
-    },
-
-    less: {
-      compile: {
-        options: {
-          paths: assets.less.paths
-        },
-        files: assets.less.files
-      }
-    },
-
-    // The jshint option for scripturl is set to lax, because the anchor
-    // override inside main.js needs to test for them so as to not accidentally
-    // route. Settings expr true so we can do `migtBeNullObject && mightBeNullObject.coolFunction()`
-    jshint: {
-      all: ['app/**/*.js', 'Gruntfile.js', "test/core/*.js"],
-      options: {
-        scripturl: true,
-        evil: true,
-        expr: true
-      }
-    },
-
-    // The jst task compiles all application templates into JavaScript
-    // functions with the underscore.js template function from 1.2.4.  You can
-    // change the namespace and the template options, by reading this:
-    // https://github.com/gruntjs/grunt-contrib/blob/master/docs/jst.md
-    //
-    // The concat task depends on this file to exist, so if you decide to
-    // remove this, ensure concat is updated accordingly.
-    jst: {
-      "dist/debug/templates.js": [
-        "app/templates/**/*.html",
-        "app/addons/**/templates/**/*.html"
-      ]
-    },
-
-    template: templateSettings,
-
-    // The concatenate task is used here to merge the almond require/define
-    // shim and the templates into the application code.  It's named
-    // dist/debug/require.js, because we want to only load one script file in
-    // index.html.
-    concat: {
-      requirejs: {
-        src: [ "assets/js/libs/require.js", "dist/debug/templates.js", "dist/debug/require.js"],
-        dest: "dist/debug/js/require.js"
-      },
-
-      index_css: {
-        src: ["dist/debug/css/*.css", 'assets/css/*.css'],
-        dest: 'dist/debug/css/index.css'
-      },
-
-      test_config_js: {
-        src: ["dist/debug/templates.js", "test/test.config.js"],
-        dest: 'test/test.config.js'
-      },
-    },
-
-    cssmin: {
-      compress: {
-        files: {
-          "dist/release/css/index.css": [
-            "dist/debug/css/index.css", 'assets/css/*.css',
-            "app/addons/**/assets/css/*.css"
-          ]
-        },
-        options: {
-          report: 'min'
-        }
-      }
-    },
-
-    uglify: {
-      release: {
-        files: {
-          "dist/release/js/require.js": [
-            "dist/debug/js/require.js"
-          ]
-        }
-      }
-    },
-
-    // Runs a proxy server for easier development, no need to keep deploying to couchdb
-    couchserver: {
-      dist: './dist/debug/',
-      port: 8000,
-      proxy: {
-        target: {
-          host: 'localhost',
-          port: 5984,
-          https: false
-        },
-        // This sets the Host header in the proxy so that you can use external
-        // CouchDB instances and not have the Host set to 'localhost'
-        changeOrigin: true
-      }
-    },
-
-    watch: {
-      js: { 
-        files: helper.watchFiles(['.js'], ["./app/**/*.js", '!./app/load_addons.js',"./assets/**/*.js", "./test/**/*.js"]),
-        tasks: ['watchRun'],
-      },
-      style: {
-        files: helper.watchFiles(['.less','.css'],["./app/**/*.css","./app/**/*.less","./assets/**/*.css", "./assets/**/*.less"]),
-        tasks: ['clean:watch', 'dependencies','less', 'concat:index_css'],
-      },
-      html: {
-        // the index.html is added in as a dummy file incase there is no
-        // html dependancies this will break. So we need one include pattern
-        files: helper.watchFiles(['.html'], ['./index.html']),
-        tasks: ['clean:watch', 'dependencies']
-      },
-      options: {
-        nospawn: true,
-        debounceDelay: 500
-      }
-    },
-
-    requirejs: {
-      compile: {
-        options: {
-          baseUrl: 'app',
-          // Include the main configuration file.
-          mainConfigFile: "app/config.js",
-
-          // Output file.
-          out: "dist/debug/require.js",
-
-          // Root application module.
-          name: "config",
-
-          // Do not wrap everything in an IIFE.
-          wrap: false,
-          optimize: "none",
-          findNestedDependencies: true
-        }
-      }
-    },
-
-    // Copy build artifacts and library code into the distribution
-    // see - http://gruntjs.com/configuring-tasks#building-the-files-object-dynamically
-    copy: {
-      couchdb: {
-        files: [
-          // this gets built in the template task
-          {src: "dist/release/index.html", dest: "../../share/www/fauxton/index.html"},
-          {src: ["**"], dest: "../../share/www/fauxton/js/", cwd:'dist/release/js/',  expand: true},
-          {src: ["**"], dest: "../../share/www/fauxton/img/", cwd:'dist/release/img/', expand: true},
-          {src: ["**"], dest: "../../share/www/fauxton/css/", cwd:"dist/release/css/", expand: true}
-        ]
-      },
-      couchdebug: {
-        files: [
-          // this gets built in the template task
-          {src: "dist/debug/index.html", dest: "../../share/www/fauxton/index.html"},
-          {src: ["**"], dest: "../../share/www/fauxton/js/", cwd:'dist/debug/js/',  expand: true},
-          {src: ["**"], dest: "../../share/www/fauxton/img/", cwd:'dist/debug/img/', expand: true},
-          {src: ["**"], dest: "../../share/www/fauxton/css/", cwd:"dist/debug/css/", expand: true}
-        ]
-      },
-      ace: {
-        files: [
-          {src: "assets/js/libs/ace/worker-json.js", dest: "dist/release/js/ace/worker-json.js"},
-          {src: "assets/js/libs/ace/mode-json.js", dest: "dist/release/js/ace/mode-json.js"},
-          {src: "assets/js/libs/ace/theme-crimson_editor.js", dest: "dist/release/js/ace/theme-crimson_editor.js"},
-          {src: "assets/js/libs/ace/mode-javascript.js", dest: "dist/release/js/ace/mode-javascript.js"},
-          {src: "assets/js/libs/ace/worker-javascript.js", dest: "dist/release/js/ace/worker-javascript.js"},
-        ]
-      },
-
-      dist:{
-        files:[
-          {src: "dist/debug/index.html", dest: "dist/release/index.html"},
-          {src: assets.img, dest: "dist/release/img/", flatten: true, expand: true}
-        ]
-      },
-      debug:{
-        files:[
-          {src: assets.img, dest: "dist/debug/img/", flatten: true, expand: true}
-        ]
-      }
-    },
-
-    get_deps: {
-      "default": {
-        src: "settings.json"
-      }
-    },
-
-    gen_load_addons: {
-      "default": {
-        src: "settings.json"
-      }
-    },
-    gen_initialize: templateSettings,
-    /*gen_initialize: {
-      "default": {
-        src: "settings.json"
-      }
-    },*/
-
-    mkcouchdb: couch_config,
-    rmcouchdb: couch_config,
-    couchapp: couch_config,
-
-    mochaSetup: {
-      default: {
-        files: { src: helper.watchFiles(['[Ss]pec.js'], ['./test/core/**/*[Ss]pec.js', './app/**/*[Ss]pec.js'])},
-        template: 'test/test.config.underscore',
-        config: './app/config.js'
-      }
-    },
-
-    mocha_phantomjs: {
-      all: ['test/runner.html']
-    }
-
-  });
-
-  // on watch events configure jshint:all to only run on changed file
-  grunt.event.on('watch', function(action, filepath) {
-    if (!!filepath.match(/.js$/) && filepath.indexOf('test.config.js') === -1) {
-      grunt.config(['jshint', 'all'], filepath);
-    }
-
-    if (!!filepath.match(/[Ss]pec.js$/)) {
-      //grunt.task.run(['mochaSetup','jst', 'concat:test_config_js', 'mocha_phantomjs']);
-    }
-  });
-
-  /*
-   * Load Grunt plugins
-   */
-  // Load fauxton specific tasks
-  grunt.loadTasks('tasks');
-  // Load the couchapp task
-  grunt.loadNpmTasks('grunt-couchapp');
-  // Load the copy task
-  grunt.loadNpmTasks('grunt-contrib-watch');
-  // Load the exec task
-  grunt.loadNpmTasks('grunt-exec');
-  // Load Require.js task
-  grunt.loadNpmTasks('grunt-contrib-requirejs');
-  // Load Copy task
-  grunt.loadNpmTasks('grunt-contrib-copy');
-  // Load Clean task
-  grunt.loadNpmTasks('grunt-contrib-clean');
-  // Load jshint task
-  grunt.loadNpmTasks('grunt-contrib-jshint');
-  // Load jst task
-  grunt.loadNpmTasks('grunt-contrib-jst');
-  // Load less task
-  grunt.loadNpmTasks('grunt-contrib-less');
-  // Load concat task
-  grunt.loadNpmTasks('grunt-contrib-concat');
-  // Load UglifyJS task
-  grunt.loadNpmTasks('grunt-contrib-uglify');
-  // Load CSSMin task
-  grunt.loadNpmTasks('grunt-contrib-cssmin');
-  grunt.loadNpmTasks('grunt-mocha-phantomjs');
-
-  /*
-   * Default task
-   */
-  // defult task - install minified app to local CouchDB
-  grunt.registerTask('default', 'couchdb');
-
-  /*
-   * Transformation tasks
-   */
-  // clean out previous build artefactsa and lint
-  grunt.registerTask('lint', ['clean', 'jshint']);
-  grunt.registerTask('test', ['lint', 'mochaSetup','jst', 'concat:test_config_js', 'mocha_phantomjs']);
-  // Fetch dependencies (from git or local dir), lint them and make load_addons
-  grunt.registerTask('dependencies', ['get_deps', 'gen_load_addons:default']);
-  // build templates, js and css
-  grunt.registerTask('build', ['less', 'concat:index_css', 'jst', 'requirejs', 'concat:requirejs', 'template:release']);
-  // minify code and css, ready for release.
-  grunt.registerTask('minify', ['uglify', 'cssmin:compress']);
-
-  /*
-   * Build the app in either dev, debug, or release mode
-   */
-  // dev server
-  grunt.registerTask('dev', ['debugDev', 'couchserver']);
-  // build a debug release
-  grunt.registerTask('debug', ['lint', 'dependencies', "gen_initialize:development", 'concat:requirejs','less', 'concat:index_css', 'template:development', 'copy:debug']);
-  grunt.registerTask('debugDev', ['clean', 'dependencies', "gen_initialize:development",'jshint','less', 'concat:index_css', 'template:development', 'copy:debug']);
-
-  grunt.registerTask('watchRun', ['clean:watch', 'dependencies', 'jshint']);
-  // build a release
-  grunt.registerTask('release', ['clean' ,'dependencies', "gen_initialize:release", 'jshint', 'build', 'minify', 'copy:dist', 'copy:ace']);
-
-  /*
-   * Install into CouchDB in either debug, release, or couchapp mode
-   */
-  // make a development install that is server by mochiweb under _utils
-  grunt.registerTask('couchdebug', ['debug', 'copy:couchdebug']);
-  // make a minimized install that is server by mochiweb under _utils
-  grunt.registerTask('couchdb', ['release', 'copy:couchdb']);
-  // make an install that can be deployed as a couchapp
-  grunt.registerTask('couchapp_setup', ['release']);
-  // install fauxton as couchapp
-  grunt.registerTask('couchapp_install', ['rmcouchdb:fauxton', 'mkcouchdb:fauxton', 'couchapp:fauxton']);
-  // setup and install fauxton as couchapp
-  grunt.registerTask('couchapp_deploy', ['couchapp_setup', 'couchapp_install']);
-};

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/TODO.md
----------------------------------------------------------------------
diff --git a/apps/fauxton/TODO.md b/apps/fauxton/TODO.md
deleted file mode 100644
index b929e05..0000000
--- a/apps/fauxton/TODO.md
+++ /dev/null
@@ -1,26 +0,0 @@
-# Fauxton todo
-In no particular order
-
-- [ ] docco docs
-- [ ] user management
-- [ ] view options
-- [ ] view editor
-- [ ] visual view builder
-- [ ] new db as modal
-- [ ] new view button
-- [ ] show design docs only
-- [ ] fix delete doc button UI bug
-- [ ] delete multiple docs via _bulk_docs
-- [x] show change events in database view
-- [ ] pouchdb addon
-- [ ] bespoke bootstrap style
-- [ ] responsive interface
-- [ ] sticky subnav for some UI components on _all_docs
-- [ ] "show me" button in API bar doesn't
-- [ ] edit index button doesn't
-- [ ] replicate UI
-- [x] delete database
-- [x] format dates better (e.g. in logs plugin)
-- [ ] format log entry better
-- [ ] filter logs by method
-- [ ] restore unfiltered data in logs UI

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/activetasks/assets/less/activetasks.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/activetasks/assets/less/activetasks.less b/apps/fauxton/app/addons/activetasks/assets/less/activetasks.less
deleted file mode 100644
index 743917d..0000000
--- a/apps/fauxton/app/addons/activetasks/assets/less/activetasks.less
+++ /dev/null
@@ -1,18 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-.task-tabs li {
-  cursor: pointer;
-}
-table.active-tasks{
-	font-size: 16px;
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/activetasks/base.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/activetasks/base.js b/apps/fauxton/app/addons/activetasks/base.js
deleted file mode 100644
index 647add0..0000000
--- a/apps/fauxton/app/addons/activetasks/base.js
+++ /dev/null
@@ -1,26 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-  "app",
-  "api",
-  "addons/activetasks/routes"
-],
-
-function (app, FauxtonAPI, Activetasks) {
-
-  Activetasks.initialize = function() {
-    FauxtonAPI.addHeaderLink({title: "Active Tasks", icon: "fonticon-activetasks", href: "#/activetasks"});
-  };
- 
-  return Activetasks;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/activetasks/resources.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/activetasks/resources.js b/apps/fauxton/app/addons/activetasks/resources.js
deleted file mode 100644
index ca732fb..0000000
--- a/apps/fauxton/app/addons/activetasks/resources.js
+++ /dev/null
@@ -1,118 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-  "app",
-  "backbone",
-  "modules/fauxton/base",
-  "d3"
-],
-
-function (app, backbone, Fauxton) {
-  var Active = {},
-      apiv = app.versionAPI;
-      app.taskSortBy = 'type';
-
-  Active.Task = Backbone.Model.extend({
-    initialize: function() { 
-      this.set({"id": this.get('pid')});
-    }
-  });
-
-// ALL THE TASKS
-  Active.Tasks = Backbone.Model.extend({
-    alltypes: {
-      "all": "All tasks",
-      "replication": "Replication",
-      "database_compaction":" Database Compaction",
-      "indexer": "Indexer",
-      "view_compaction": "View Compaction"
-    },
-    documentation: "_active_tasks",
-    url: function (context) {
-      if (context === "apiurl"){
-        return window.location.origin + '/_active_tasks';
-      } else {
-        return app.host + '/_active_tasks';
-      }
-    },
-    fetch: function (options) {
-     var fetchoptions = options || {};
-     fetchoptions.cache = false;
-     return Backbone.Model.prototype.fetch.call(this, fetchoptions);
-    },
-    parse: function(resp){
-      var types = this.getUniqueTypes(resp),
-          that = this;
-
-      var typeCollections = _.reduce(types, function (collection, val, key) {
-          collection[key] = new Active.AllTasks(that.sortThis(resp, key));
-          return collection;
-        }, {});
-
-      typeCollections.all = new Active.AllTasks(resp);
-
-      this.set(typeCollections);  //now set them all to the model
-    },
-    getUniqueTypes: function(resp){
-      var types = this.alltypes;
-
-      _.each(resp, function(type){
-        if( typeof(types[type.type]) === "undefined"){
-          types[type.type] = type.type.replace(/_/g,' ');
-        }
-      },this);
-
-      this.alltypes = types;
-      return types;
-    },
-    sortThis: function(resp, type){
-      return _.filter(resp, function(item) { return item.type === type; });
-    },
-    changeView: function (view){
-      this.set({
-        "currentView": view
-      });
-    },
-    getCurrentViewData: function(){
-      var currentView = this.get('currentView');
-      return this.get(currentView);
-    },
-    getDatabaseCompactions: function(){
-      return this.get('databaseCompactions');
-    },
-    getIndexes: function(){
-      return this.get('indexes');
-    },
-    getViewCompactions: function(){
-      return this.get('viewCompactions');
-    }
-  });
-
-//ALL TASKS
-
-//NEW IDEA. Lets make this extremely generic, so if there are new weird tasks, they get sorted and collected.
-
-  Active.AllTasks = Backbone.Collection.extend({
-    model: Active.Task,
-    sortByColumn: function(colName) {
-      app.taskSortBy = colName;
-      this.sort();
-    },
-    comparator: function(item) {
-      return item.get(app.taskSortBy);
-    }
-  });
-
-
-  return Active;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/activetasks/routes.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/activetasks/routes.js b/apps/fauxton/app/addons/activetasks/routes.js
deleted file mode 100644
index 89bcfcc..0000000
--- a/apps/fauxton/app/addons/activetasks/routes.js
+++ /dev/null
@@ -1,58 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-  "app",
-  "api",
-  "addons/activetasks/resources",
-  "addons/activetasks/views"
-],
-
-function (app, FauxtonAPI, Activetasks, Views) {
-
-  var  ActiveTasksRouteObject = FauxtonAPI.RouteObject.extend({
-    layout: "with_sidebar",
-    routes: {
-      "activetasks/:id": "defaultView",
-      "activetasks": "defaultView"
-    },
-    selectedHeader: 'Active Tasks',
-    crumbs: [
-    {"name": "Active tasks", "link": "activetasks"}
-    ],
-    apiUrl: function(){
-      return [this.newtasks.url("apiurl"), this.newtasks.documentation];
-    }, 
-
-    roles: ["_admin"],
-
-    defaultView: function(id){
-     this.newtasks = new Activetasks.Tasks({
-        currentView: "all", 
-        id:'activeTasks'
-      });
-      this.setView("#sidebar-content", new Views.TabMenu({
-        currentView: "all",
-        model: this.newtasks
-      })); 
-
-      this.setView("#dashboard-content", new Views.DataSection({
-        model: this.newtasks,
-        currentView: "all"
-      })); 
-    }
-  });
-
-  Activetasks.RouteObjects = [ActiveTasksRouteObject];
-
-  return Activetasks;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/activetasks/templates/detail.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/activetasks/templates/detail.html b/apps/fauxton/app/addons/activetasks/templates/detail.html
deleted file mode 100644
index 5e53129..0000000
--- a/apps/fauxton/app/addons/activetasks/templates/detail.html
+++ /dev/null
@@ -1,21 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<div class="progress progress-striped active">
-  <div class="bar" style="width: <%=model.get("progress")%>%;"><%=model.get("progress")%>%</div>
-</div>
-<p>
-	<%= model.get("type").replace('_',' ')%> on
-	<%= model.get("node")%>
-</p>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/activetasks/templates/table.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/activetasks/templates/table.html b/apps/fauxton/app/addons/activetasks/templates/table.html
deleted file mode 100644
index 885cb47..0000000
--- a/apps/fauxton/app/addons/activetasks/templates/table.html
+++ /dev/null
@@ -1,52 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<% if (collection.length === 0){%>
-   <tr> 
-    <td>
-      <p>No tasks.</p>
-    </td>
-  </tr>
-<%}else{%>
-
-  <thead>
-    <tr>
-      <th data-type="type">Type</th>
-      <th data-type="node">Object</th>
-      <th data-type="started_on">Started on</th>
-      <th data-type="updated_on">Last updated on</th>
-      <th data-type="pid">PID</th>
-      <th data-type="progress" width="200">Status</th>
-    </tr>
-  </thead>
-
-  <tbody id="tasks_go_here">
-
-  </tbody>
-
-<% } %>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/activetasks/templates/tabledetail.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/activetasks/templates/tabledetail.html b/apps/fauxton/app/addons/activetasks/templates/tabledetail.html
deleted file mode 100644
index 67c0dc8..0000000
--- a/apps/fauxton/app/addons/activetasks/templates/tabledetail.html
+++ /dev/null
@@ -1,36 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<td>
-  <%= model.get("type")%>
-</td>
-<td>
-  <%= objectField %>
-</td>
-<td>
-  <%= formatDate(model.get("started_on")) %>
-</td>
-<td>
-  <%= formatDate(model.get("updated_on")) %>
-</td>
-<td>
-  <%= model.get("pid")%>
-</td>
-<td>
-	<div class="progress progress-striped active">
-	  <div class="bar" style="width: <%=model.get("progress")%>%;"><%=model.get("progress")%>%</div>
-
-	</div>
-	<p><%=progress%> </p>
-</td>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/activetasks/templates/tabs.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/activetasks/templates/tabs.html b/apps/fauxton/app/addons/activetasks/templates/tabs.html
deleted file mode 100644
index 5869748..0000000
--- a/apps/fauxton/app/addons/activetasks/templates/tabs.html
+++ /dev/null
@@ -1,46 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-
-
-
-
-<div id="sidenav">
-  <header class="row-fluid">
-    <h3>Filter by: </h3>
-  </header>
-
-  <nav>
-		<ul class="task-tabs nav nav-list">
-		  <% for (var filter in filters) { %>
-		      <li data-type="<%=filter%>">
-			      <a>
-			      		<%=filters[filter]%>
-			      </a>
-		    </li>
-		  <% } %>
-		</ul>
-		<ul class="nav nav-list views">
-			<li class="nav-header">Polling interval</li>
-			<li>
-				<input id="pollingRange" type="range"
-				       min="1"
-				       max="30"
-				       step="1"
-				       value="5"/>
-				<label for="pollingRange"><span>5</span> second(s)</label>
-			</li>
-		</ul>
-  </nav>
-</div>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/activetasks/tests/viewsSpec.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/activetasks/tests/viewsSpec.js b/apps/fauxton/app/addons/activetasks/tests/viewsSpec.js
deleted file mode 100644
index 395b60a..0000000
--- a/apps/fauxton/app/addons/activetasks/tests/viewsSpec.js
+++ /dev/null
@@ -1,139 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-define([
-       'api',
-       'addons/activetasks/views',
-       'addons/activetasks/resources',
-      'testUtils'
-], function (FauxtonAPI, Views, Models, testUtils) {
-  var assert = testUtils.assert,
-      ViewSandbox = testUtils.ViewSandbox;
-  
-  describe("TabMenu", function () {
-    var tabMenu;
-
-    beforeEach(function () {
-      var newtasks = new Models.Tasks({
-        currentView: "all", 
-        id:'activeTasks'
-      });
-
-      tabMenu = new Views.TabMenu({
-        currentView: "all",
-        model: newtasks
-      });
-    });
-
-    describe("on change polling rate", function () {
-      var viewSandbox;
-      beforeEach(function () {
-        viewSandbox = new ViewSandbox();
-        viewSandbox.renderView(tabMenu); 
-      });
-
-      afterEach(function () {
-        viewSandbox.remove();
-      });
-
-      it("Should set polling rate", function () {
-        $range = tabMenu.$('#pollingRange');
-        $range.val(15);
-        $range.trigger('change');
-
-        assert.equal(tabMenu.$('span').text(), 15);
-      });
-
-      it("Should clearInterval", function () {
-        $range = tabMenu.$('#pollingRange');
-        clearIntervalMock = sinon.spy(window,'clearInterval');
-        $range.trigger('change');
-
-        assert.ok(clearIntervalMock.calledOnce);
-
-      });
-
-      it("Should trigger update:poll event", function () {
-        var spy = sinon.spy();
-        Views.Events.on('update:poll', spy);
-        $range = tabMenu.$('#pollingRange');
-        $range.trigger('change');
-
-        assert.ok(spy.calledOnce);
-      });
-
-    });
-
-    describe('on request by type', function () {
-      var viewSandbox;
-      beforeEach(function () {
-        viewSandbox = new ViewSandbox();
-        viewSandbox.renderView(tabMenu); 
-      });
-
-      afterEach(function () {
-        viewSandbox.remove();
-      });
-
-      it("should change model view", function () {
-        var spy = sinon.spy(tabMenu.model, 'changeView');
-        var $rep = tabMenu.$('li[data-type="replication"]');
-        $rep.click();
-        assert.ok(spy.calledOnce);
-      });
-
-      it("should set correct active tab", function () {
-        var spy = sinon.spy(tabMenu.model, 'changeView');
-        var $rep = tabMenu.$('li[data-type="replication"]');
-        $rep.click();
-        assert.ok($rep.hasClass('active'));
-      });
-
-    });
-
-  });
-
-  describe('DataSection', function () {
-    var viewSandbox, dataSection;
-    beforeEach(function () {
-      var newtasks = new Models.Tasks({
-        currentView: "all", 
-        id:'activeTasks'
-      });
-      newtasks.parse([]);
-
-      dataSection = new Views.DataSection({
-        currentView: "all",
-        model: newtasks
-      });
-
-      viewSandbox = new ViewSandbox();
-      viewSandbox.renderView(dataSection); 
-    });
-
-    afterEach(function () {
-      viewSandbox.remove();
-    });
-
-    describe('#setPolling', function () {
-
-      it('Should set polling interval', function () {
-        var spy = sinon.spy(window, 'setInterval');
-        dataSection.setPolling();
-        assert.ok(spy.calledOnce);
-      });
-
-    });
-
-
-
-  });
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/activetasks/views.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/activetasks/views.js b/apps/fauxton/app/addons/activetasks/views.js
deleted file mode 100644
index 005d487..0000000
--- a/apps/fauxton/app/addons/activetasks/views.js
+++ /dev/null
@@ -1,181 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-       "app",
-       "api",
-       "addons/activetasks/resources"
-],
-
-function (app, FauxtonAPI, activetasks) {
-
-  var Views = {},
-      Events = {},
-      pollingInfo ={
-        rate: "5",
-        intervalId: null
-      };
-
-
-  Views.Events = _.extend(Events, Backbone.Events);
-
-  Views.TabMenu = FauxtonAPI.View.extend({
-    template: "addons/activetasks/templates/tabs",
-    events: {
-      "click .task-tabs li": "requestByType",
-      "change #pollingRange": "changePollInterval"
-    },
-    establish: function(){
-      return [this.model.fetch({reset: true})];
-    },
-    serialize: function(){
-      return {
-        filters: this.model.alltypes
-      };
-    },
-    afterRender: function(){
-      this.$('.task-tabs').find('li').eq(0).addClass('active');
-    },
-    changePollInterval: function(e){
-      var range = this.$(e.currentTarget).val();
-      this.$('label[for="pollingRange"] span').text(range);
-      pollingInfo.rate = range;
-      clearInterval(pollingInfo.intervalId);
-      Events.trigger('update:poll');
-    },
-
-    cleanup: function () {
-      clearInterval(pollingInfo.intervalId);
-    },
-
-    requestByType: function(e){
-      var currentTarget = e.currentTarget;
-      datatype = this.$(currentTarget).attr("data-type");
-
-      this.$('.task-tabs').find('li').removeClass('active');
-      this.$(currentTarget).addClass('active');
-      this.model.changeView(datatype);
-    }
-  });
-
-  Views.DataSection = FauxtonAPI.View.extend({
-    showData: function(){
-      var currentData = this.model.getCurrentViewData();
-
-      if (this.dataView) {
-       this.dataView.update(currentData, this.model.get('currentView').replace('_',' '));
-      } else {
-        this.dataView = this.insertView( new Views.TableData({ 
-          collection: currentData,
-          currentView: this.model.get('currentView').replace('_',' ')
-        }));
-      }
-    },
-    showDataAndRender: function () {
-      this.showData();
-      this.dataView.render();
-    },
-
-    beforeRender: function () {
-      this.showData();
-    },
-    establish: function(){
-      return [this.model.fetch()];
-    },
-    setPolling: function(){
-      var that = this;
-      clearInterval(pollingInfo.intervalId);
-      pollingInfo.intervalId = setInterval(function() {
-        that.establish();
-      }, pollingInfo.rate*1000);
-    },
-    cleanup: function(){
-      clearInterval(pollingInfo.intervalId);
-    },
-    afterRender: function(){
-      this.listenTo(this.model, "change", this.showDataAndRender);
-      Events.bind('update:poll', this.setPolling, this);
-      this.setPolling();
-    }
-  });
-
-  Views.TableData = FauxtonAPI.View.extend({
-    tagName: "table",
-    className: "table table-bordered table-striped active-tasks",
-    template: "addons/activetasks/templates/table",
-    events: {
-      "click th": "sortByType"
-    },
-    initialize: function(){
-      currentView = this.options.currentView;
-    },
-    sortByType:  function(e){
-      var currentTarget = e.currentTarget;
-      datatype = $(currentTarget).attr("data-type");
-      this.collection.sortByColumn(datatype);
-      this.render();
-    },
-    serialize: function(){
-      return {
-        currentView: currentView,
-        collection: this.collection
-      };
-    },
-
-    update: function (collection, currentView) {
-      this.collection = collection;
-      this.currentView = currentView;
-    },
-
-    beforeRender: function(){
-      //iterate over the collection to add each
-      this.collection.forEach(function(item) {
-        this.insertView("#tasks_go_here", new Views.TableDetail({ 
-          model: item
-        }));
-      }, this);
-    }
-  });
-
-  Views.TableDetail = FauxtonAPI.View.extend({
-    tagName: 'tr',
-    template: "addons/activetasks/templates/tabledetail",
-    initialize: function(){
-      this.type = this.model.get('type');
-    },
-    getObject: function(){
-      var objectField = this.model.get('database');
-      if (this.type === "replication"){
-        objectField = this.model.get('source') + " to " + this.model.get('target');
-      }
-      return objectField;
-    },
-    getProgress:  function(){
-      var progress = "";
-      if (this.type === "indexer"){
-        progress = "Processed " +this.model.get('changes_done')+ " of "+this.model.get('total_changes')+ ' changes';
-      }
-      return progress;
-    },
-    serialize: function(){
-      return {
-        model: this.model,
-        objectField: this.getObject(),
-        progress: this.getProgress()
-      };
-    }
-  });
-
-
-
-  return Views;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/auth/assets/less/auth.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/auth/assets/less/auth.less b/apps/fauxton/app/addons/auth/assets/less/auth.less
deleted file mode 100644
index 598da10..0000000
--- a/apps/fauxton/app/addons/auth/assets/less/auth.less
+++ /dev/null
@@ -1,15 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-.menuDropdown {
-  display: none;
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/auth/base.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/auth/base.js b/apps/fauxton/app/addons/auth/base.js
deleted file mode 100644
index 9f9a332..0000000
--- a/apps/fauxton/app/addons/auth/base.js
+++ /dev/null
@@ -1,69 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-       "app",
-       "api",
-       "addons/auth/routes"
-],
-
-function(app, FauxtonAPI, Auth) {
-
-  Auth.session = new Auth.Session();
-  FauxtonAPI.setSession(Auth.session);
-
-  Auth.initialize = function() {
-    Auth.navLink = new Auth.NavLink({model: Auth.session});
-
-    FauxtonAPI.addHeaderLink({
-      title: "Auth", 
-      href: "#_auth",
-      view: Auth.navLink,
-      icon: "fonticon-user",
-      bottomNav: true,
-      establish: [FauxtonAPI.session.fetchUser()]
-    });
-      
-
-    var auth = function (session, roles) {
-      var deferred = $.Deferred();
-
-      if (session.isAdminParty()) {
-        deferred.resolve();
-      } else if(session.matchesRoles(roles)) {
-        deferred.resolve();
-      } else {
-        deferred.reject();
-      }
-
-      return [deferred];
-    };
-
-    var authDenied = function () {
-      FauxtonAPI.navigate('/noAccess');
-    };
-
-    FauxtonAPI.auth.registerAuth(auth);
-    FauxtonAPI.auth.registerAuthDenied(authDenied);
-
-    FauxtonAPI.session.on('change', function () {
-      if (FauxtonAPI.session.isLoggedIn()) {
-        FauxtonAPI.addHeaderLink({footerNav: true, href:"#logout", title:"Logout", icon: "", className: 'logout'});
-      } else {
-        FauxtonAPI.removeHeaderLink({title: "Logout", footerNav: true});
-      }
-    });
-  };
-
-
-  return Auth;
-});


[31/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/resizeColumns.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/resizeColumns.js b/apps/fauxton/app/resizeColumns.js
deleted file mode 100644
index 9cf7115..0000000
--- a/apps/fauxton/app/resizeColumns.js
+++ /dev/null
@@ -1,87 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-
-// This file creates a set of helper functions that will be loaded for all html
-// templates. These functions should be self contained and not rely on any 
-// external dependencies as they are loaded prior to the application. We may
-// want to change this later, but for now this should be thought of as a
-// "purely functional" helper system.
-
-define([
-  "mixins"
-],
-
-function(mixins) {
-
-  var Resize = function(options){
-    this.options = options;
-    this.options.selectorElements = options.selectorElements || ".window-resizeable";
-  };
-
-  Resize.prototype = {
-    getPrimaryNavWidth: function(){
-      var primaryNavWidth  = $('body').hasClass('closeMenu')? 64:224;
-      return primaryNavWidth;
-    },
-    getPanelWidth: function(){
-      var sidebarWidth = $('#sidebar-content').length > 0 ? $('#sidebar-content').width(): 0;
-      return (this.getPrimaryNavWidth() + sidebarWidth); 
-    },
-    initialize: function(){
-     // $(window).off('resize');
-      var that = this;
-      //add throttler :) 
-      this.lazyLayout = _.debounce(that.onResizeHandler, 300).bind(this);
-      mixins.addWindowResize(this.lazyLayout,"animation");
-      mixins.initWindowResize();
-      this.onResizeHandler();
-    },
-    updateOptions:function(options){
-      this.options = {};
-      this.options = options;
-      this.options.selectorElements = options.selectorElements || ".window-resizeable";
-    },
-    turnOff:function(){
-      mixins.removeWindowResize("animation");
-    },
-    cleanupCallback: function(){
-      this.callback = null;
-    },
-    onResizeHandler: function (){
-      //if there is an override, do that instead
-      if (this.options.onResizeHandler){
-        this.options.onResizeHandler();
-      } else {
-        var combinedWidth = window.innerWidth - this.getPanelWidth(),
-        smallWidthConstraint = ($('#sidebar-content').length > 0)? 470:800,
-        panelWidth; 
-
-        if( combinedWidth > smallWidthConstraint  && combinedWidth < 1400){
-          panelWidth = window.innerWidth - this.getPanelWidth();
-        } else if (combinedWidth < smallWidthConstraint){
-          panelWidth = smallWidthConstraint;
-        } else if(combinedWidth > 1400){
-          panelWidth = 1400;
-        }
-
-        $(this.options.selectorElements).innerWidth(panelWidth);
-      }
-      //if there is a callback, run that
-      if(this.options.callback) {
-        this.options.callback();
-      }
-    } 
-  };
-
-  return Resize;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/router.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/router.js b/apps/fauxton/app/router.js
deleted file mode 100644
index e3a1636..0000000
--- a/apps/fauxton/app/router.js
+++ /dev/null
@@ -1,175 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-       // Load require for use in nested requiring
-       // as per the note in: http://requirejs.org/docs/api.html#multiversion
-       "require",
-
-       // Application.
-       "app",
-
-       // Initialize application
-       "initialize",
-
-       // Load Fauxton API
-       "api",
-
-       // Modules
-       "modules/fauxton/base",
-       // Layout
-       "modules/fauxton/layout",
-
-       // Routes return the module that they define routes for
-       "modules/databases/base",
-       "modules/documents/base",
-       "modules/pouchdb/base",
-
-
-       // this needs to be added as a plugin later
-       // "modules/logs/base",
-       // "modules/config/base",
-
-       "load_addons"
-],
-
-function(req, app, Initialize, FauxtonAPI, Fauxton, Layout, Databases, Documents, Pouch, LoadAddons) {
-
-  // TODO: auto generate this list if possible
-  var modules = [Databases, Documents];
-
-  var beforeUnloads = {};
-
-  var Router = app.router = Backbone.Router.extend({
-    routes: {},
-
-    beforeUnload: function (name, fn) {
-      beforeUnloads[name] = fn;
-    },
-
-    removeBeforeUnload: function (name) {
-      delete beforeUnloads[name];
-    },
-
-    navigate: function (fragment, trigger) {
-      var continueNav  = true,
-          msg = _.find(_.map(beforeUnloads, function (fn) { return fn(); }), function (beforeReturn) {
-            if (beforeReturn) { return true; }
-          });
-
-      if (msg) {
-        continueNav = window.confirm(msg);
-      }
-
-      if (continueNav) {
-        Backbone.Router.prototype.navigate(fragment, trigger);
-      }
-    },
-
-    addModuleRouteObject: function(RouteObject) {
-      var that = this;
-      var masterLayout = this.masterLayout,
-      routeUrls = RouteObject.prototype.getRouteUrls();
-
-      _.each(routeUrls, function(route) {
-        this.route(route, route.toString(), function() {
-          var args = Array.prototype.slice.call(arguments),
-          roles = RouteObject.prototype.getRouteRoles(route),
-          authPromise = app.auth.checkAccess(roles);
-
-          authPromise.then(function () {
-            if (!that.activeRouteObject || !that.activeRouteObject.hasRoute(route)) {
-              if (that.activeRouteObject) {
-                that.activeRouteObject.removeViews();
-              }
-              that.activeRouteObject = new RouteObject(route, masterLayout, args);
-            }
-
-            var routeObject = that.activeRouteObject;
-            routeObject.routeCallback(route, args);
-            routeObject.renderWith(route, masterLayout, args);
-          }, function () {
-            FauxtonAPI.auth.authDeniedCb();
-          });
-
-        }); 
-      }, this);
-    },
-
-    setModuleRoutes: function() {
-      _.each(modules, function(module) {
-        if (module){
-          _.each(module.RouteObjects, this.addModuleRouteObject, this);
-        }
-      }, this);
-      _.each(LoadAddons.addons, function(module) {
-        if (module){
-          module.initialize();
-          // This is pure routes the addon provides
-          if (module.RouteObjects) {
-            _.each(module.RouteObjects, this.addModuleRouteObject, this);
-          }
-        }
-      }, this);
-    },
-
-    /*setAddonHooks: function() {
-      _.each(LoadAddons.addons, function(module) {
-        // This is updates to views by the addon
-        if (module && module.hooks){
-          _.each(module.hooks, function(callback, route){
-            if (this.masterLayout.hooks[route]) {
-              this.masterLayout.hooks[route].push(callback);
-            } else {
-              this.masterLayout.hooks[route] = [callback];
-            }
-          }, this);
-        }
-      }, this);
-    },*/
-
-    initialize: function() {
-      //TODO: It would be nice to handle this with a router
-      this.navBar = app.navBar = new Fauxton.NavBar();
-      this.apiBar = app.apiBar = new Fauxton.ApiBar();
-      this.auth = app.auth = FauxtonAPI.auth;
-      app.session = FauxtonAPI.session;
-
-      app.masterLayout = this.masterLayout = new Layout(this.navBar, this.apiBar);
-      app.footer = new Fauxton.Footer({el: "#footer-content"});
-
-      // NOTE: This must be below creation of the layout
-      // FauxtonAPI header links and others depend on existence of the layout
-      //this.setAddonHooks();
-      this.setModuleRoutes();
-
-      $("#app-container").html(this.masterLayout.el);
-      this.masterLayout.render();
-
-      // TODO: move this to a proper Fauxton.View
-      $.when.apply(null, app.footer.establish()).done(function() {
-        app.footer.render();
-      });
-    },
-
-    triggerRouteEvent: function(event, args) {
-      if (this.activeRouteObject) {
-        var eventArgs = [event].concat(args);
-        this.activeRouteObject.trigger.apply(this.activeRouteObject, eventArgs );
-        this.activeRouteObject.renderWith(eventArgs, this.masterLayout, args);
-      }
-    }
-  });
-
-  return Router;
-
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/templates/databases/item.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/templates/databases/item.html b/apps/fauxton/app/templates/databases/item.html
deleted file mode 100644
index e2f8071..0000000
--- a/apps/fauxton/app/templates/databases/item.html
+++ /dev/null
@@ -1,24 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<td>
-  <a href="#/database/<%=encoded%>/_all_docs?limit=<%=docLimit%>"><%= database.get("name") %></a>
-</td>
-<td><%= database.status.humanSize() %></td>
-<td><%= database.status.numDocs() %></td>
-<td><%= database.status.updateSeq() %></td>
-<td>
-  <a class="db-actions btn fonticon-replicate set-replication-start" title="Replicate <%= database.get("name") %>" href="#/replication/new/<%=encoded%>"></a>
-  <a class="db-actions btn icon-lock set-permissions" title="Set permissions for <%= database.get("name") %>" href="#/database/<%=encoded%>/permissions"></a>
-</td>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/templates/databases/list.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/templates/databases/list.html b/apps/fauxton/app/templates/databases/list.html
deleted file mode 100644
index 31c0977..0000000
--- a/apps/fauxton/app/templates/databases/list.html
+++ /dev/null
@@ -1,35 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<div class="result-tools" style="">
-  <div id="newButton" class="pull-left"></div>
-  <form id="jump-to-db" class="navbar-form pull-right input-append database-search">
-    <input type="text" class="search-autocomplete" name="search-query" placeholder="Database name"></input>
-    <button class="fonticon-search btn button red " type="submit"></button>
-  </form>
-
-
-</div>
-<table class="databases table table-striped">
-  <thead>
-    <th>Name</th>
-    <th>Size</th>
-    <th># of Docs</th>
-    <th>Update Seq</th>
-    <th>Actions</th>
-  </thead>
-  <tbody>
-  </tbody>
-</table>
-<div id="database-pagination"></div>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/templates/databases/newdatabase.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/templates/databases/newdatabase.html b/apps/fauxton/app/templates/databases/newdatabase.html
deleted file mode 100644
index b357e0b..0000000
--- a/apps/fauxton/app/templates/databases/newdatabase.html
+++ /dev/null
@@ -1,17 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<a class="button new" id="new"><i class="icon fonticon-new-database"></i>Add New Database</a>
-
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/templates/databases/sidebar.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/templates/databases/sidebar.html b/apps/fauxton/app/templates/databases/sidebar.html
deleted file mode 100644
index a8bbd89..0000000
--- a/apps/fauxton/app/templates/databases/sidebar.html
+++ /dev/null
@@ -1,31 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<div class="row-fluid">
-  <a href="http://couchdb.org" target="_blank"><img src="img/couchdblogo.png"/></a>
-  <br/>
-</div>
-<hr>
-<ul class="nav nav-list">
-  <!-- <li class="nav-header">Database types</li> -->
-  <li class="active"><a class="toggle-view" id="owned">Your databases</a></li>
-  <li><a class="btn new" id="new"><i class="icon-plus"></i> New database</a></li>
-</ul>
-<hr>
-
-<div>
-  <a class="twitter-timeline" data-dnt="true" href="https://twitter.com/CouchDB" data-widget-id="314360971646869505">Tweets by @CouchDB</a>
-<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
-
-</div>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/templates/documents/advanced_options.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/templates/documents/advanced_options.html b/apps/fauxton/app/templates/documents/advanced_options.html
deleted file mode 100644
index 8e96574..0000000
--- a/apps/fauxton/app/templates/documents/advanced_options.html
+++ /dev/null
@@ -1,97 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-<div class="errors-container"></div>
-<form class="view-query-update custom-inputs">
-  <div class="controls-group">
-    <div class="row-fluid">
-      <div class="controls controls-row">
-        <input name="key" class="span6" type="text" placeholder="Key">
-        <input name="keys" class="span6" type="text" placeholder="Keys">
-      </div>
-    </div>
-    <div class="row-fluid">
-      <div class="controls controls-row">
-        <input name="startkey" class="span6" type="text" placeholder="Start Key">
-        <input name="endkey" class="span6" type="text" placeholder="End Key">
-      </div>
-    </div>
-  </div>
-  <div class="controls-group">
-    <div class="row-fluid">
-      <div class="controls controls-row">
-        <div class="checkbox inline">  
-          <input id="check1" type="checkbox" name="include_docs" value="true">  
-          <label name="include_docs" for="check1">Include Docs</label>  
-          <% if (hasReduce) { %>
-          <input id="check2" name="reduce" type="checkbox" value="true">
-          <label for="check2">Reduce</label>  
-        </div> 
-        <label id="select1" class="drop-down inline">
-          Group Level:
-          <select id="select1" disabled name="group_level" class="input-small">
-            <option value="0">None</option>
-            <option value="1">1</option>
-            <option value="2">2</option>
-            <option value="3">3</option>
-            <option value="4">4</option>
-            <option value="5">5</option>
-            <option value="6">6</option>
-            <option value="7">7</option>
-            <option value="8">8</option>
-            <option value="9">9</option>
-            <option value="999" selected="selected">exact</option>
-          </select>
-        </label>
-        <% } else{ %>
-        </div>
-        <% } %>
-
-        <div class="checkbox inline">  
-          <input id="check3" name="stale" type="checkbox" value="ok">
-          <label for="check3">Stale</label>
-          <input id="check4" name="descending" type="checkbox" value="true">  
-          <label for="check4">Descending</label>  
-        </div> 
-        <label class="drop-down inline">
-          Limit:
-          <select name="limit" class="input-small">
-            <option>5</option>
-            <option selected="selected">10</option>
-            <option>25</option>
-            <option>50</option>
-            <option>100</option>
-          </select>
-        </label>
-        <div class="checkbox inline">  
-          <input id="check5" name="inclusive_end" type="checkbox" value="false">
-          <label for="check5">Disable Inclusive End</label>
-          <input id="check6" name="update_seq" type="checkbox" value="true">  
-          <label for="check6">Update Sequence</label>  
-        </div>
-      </div>
-    </div>
-  </div>
-  <div class="controls-group">
-    <div class="row-fluid">
-      <div id="button-options" class="controls controls-row">
-        <button type="submit" class="button green">Query</button>
-        <% if (showPreview) { %>
-        <button class="button btn-info preview">Browser Preview</button>
-        <% } %>
-      </div>
-    </div>
-  </div>
-</form>
-</div>
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/templates/documents/all_docs_item.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/templates/documents/all_docs_item.html b/apps/fauxton/app/templates/documents/all_docs_item.html
deleted file mode 100644
index bfedaaa..0000000
--- a/apps/fauxton/app/templates/documents/all_docs_item.html
+++ /dev/null
@@ -1,26 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<td class="select"><input type="checkbox" class="row-select"></td>
-<td>
-  <div>
-    <pre class="prettyprint"><%- doc.prettyJSON() %></pre>
-    <% if (doc.isEditable()) { %>
-      <div class="btn-group">
-        <a href="#<%= doc.url('web-index') %>" class="btn btn-small edits">Edit <%= doc.docType() %></a>
-        <button href="#" class="btn btn-small btn-danger delete" title="Delete this document."><i class="icon icon-trash"></i></button>
-      </div>
-    <% } %>
-  </div>
-</td>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/templates/documents/all_docs_layout.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/templates/documents/all_docs_layout.html b/apps/fauxton/app/templates/documents/all_docs_layout.html
deleted file mode 100644
index 526c200..0000000
--- a/apps/fauxton/app/templates/documents/all_docs_layout.html
+++ /dev/null
@@ -1,20 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-<ul class="nav nav-tabs window-resizeable" id="db-views-tabs-nav">
-  <li><a id="toggle-query" class="fonticon-plus fonticon" href="#query" data-toggle="tab">Query Options</a></li>
-</ul>
-<div class="tab-content">
-  <div class="tab-pane" id="query">
-  </div>
-</div>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/templates/documents/all_docs_list.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/templates/documents/all_docs_list.html b/apps/fauxton/app/templates/documents/all_docs_list.html
deleted file mode 100644
index 335b040..0000000
--- a/apps/fauxton/app/templates/documents/all_docs_list.html
+++ /dev/null
@@ -1,43 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<div class="view show">
-  <% if (!viewList) { %>
-    <div class="row">
-      <div class="btn-toolbar span6">
-        <button type="button" class="btn all" data-toggle="button">✓ All</button>
-        <button class="btn btn-small disabled bulk-delete"><i class="icon-trash"></i></button>
-        <% if (expandDocs) { %>
-        <button id="collapse" class="btn"><i class="icon-minus"></i> Collapse</button>
-        <% } else { %>
-        <button id="collapse" class="btn"><i class="icon-plus"></i> Expand</button>
-        <% } %>
-      </div>
-    </div>
-  <% } %>
-  <p>
-
-  <div id="item-numbers"> </div>
-
-  <% if (requestDuration) { %>
-    <span class="view-request-duration">
-    View request duration: <strong> <%= requestDuration %> </strong> 
-    </span>
-  <% } %>
-  </p>
-  <table class="all-docs table table-striped table-condensed">
-    <tbody></tbody>
-  </table>
-  <div id="documents-pagination"></div>
-</div>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/templates/documents/all_docs_number.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/templates/documents/all_docs_number.html b/apps/fauxton/app/templates/documents/all_docs_number.html
deleted file mode 100644
index c4ea8f6..0000000
--- a/apps/fauxton/app/templates/documents/all_docs_number.html
+++ /dev/null
@@ -1,21 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-<% if (totalRows === "unknown"){ %>
-  Showing 0 documents. <a href="#/database/<%=database%>/new"> Create your first document.</a>
-<% } else { %>
-  Showing <%=offset%> - <%= numModels %> of <%= totalRows %> rows
-<%}%>
-<% if (updateSeq) { %>
-  -- Update Sequence: <%= updateSeq %>
-<% } %>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/templates/documents/changes.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/templates/documents/changes.html b/apps/fauxton/app/templates/documents/changes.html
deleted file mode 100644
index 9408979..0000000
--- a/apps/fauxton/app/templates/documents/changes.html
+++ /dev/null
@@ -1,38 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<table id="changes-table" class="table">
-  <thead>
-    <th id="seq"> seq </th>
-    <th> id </th>
-    <th id="changes"> changes </th>
-    <th id="deleted"> deleted? </th>
-  </thead>
-  <tbody>
-  <% _.each(changes, function (change) { %>
-    <tr>
-      <td> <%= change.seq %> </td>
-      <% if (change.deleted) { %>
-        <td> <%= change.id %> </td>
-      <% } else { %>
-        <td> <a href="#<%= database.url('app') %>/<%= change.id %>"><%= change.id %></a> </td>
-      <% } %>
-        <td> 
-          <pre class="prettyprint">  <%- JSON.stringify({changes: change.changes, doc: change.doc}, null, " ") %> </pre>
-      </td>
-      <td><%= change.deleted ? "true" : "false" %></td>
-    </tr>
-  <% }); %>
-  </tbody>
-</table>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/templates/documents/ddoc_info.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/templates/documents/ddoc_info.html b/apps/fauxton/app/templates/documents/ddoc_info.html
deleted file mode 100644
index ed0aed6..0000000
--- a/apps/fauxton/app/templates/documents/ddoc_info.html
+++ /dev/null
@@ -1,28 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-<div>
-  <h2> Design Doc MetaData </h2>
-  <div class="row-fluid">
-	<% i=0; _.map(view_index, function (val, key) { %>
-		<% if(i%2==0){%>
-			<div class="row-fluid">
-		<% }; %>
-	    <div class="span6 well-item"><strong> <%= key %></strong> : <%= val %>  </div>
-	    <% if(i%2==1){%>
-			</div>
-		<% }; %>
-	  	<% ++i;
-	}); %>
-  </div>
-</div>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/templates/documents/design_doc_selector.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/templates/documents/design_doc_selector.html b/apps/fauxton/app/templates/documents/design_doc_selector.html
deleted file mode 100644
index 7bbe310..0000000
--- a/apps/fauxton/app/templates/documents/design_doc_selector.html
+++ /dev/null
@@ -1,35 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-<div class="span3">
-  <label for="ddoc">Save to Design Document <a href="<%=getDocUrl('design_doc')%>" target="_blank"><i class="icon-question-sign"></i></a></label>
-  <select id="ddoc">
-    <optgroup label="Select a document">
-      <option value="new-doc">New document</option>
-      <% ddocs.each(function(ddoc) { %>
-      <% if (ddoc.id === ddocName) { %>
-      <option selected="selected" value="<%= ddoc.id %>"><%= ddoc.id %></option>
-      <% } else { %>
-      <option value="<%= ddoc.id %>"><%= ddoc.id %></option>
-      <% } %>
-      <% }); %>
-    </optgroup>
-  </select>
-</div>
-
-<div id="new-ddoc-section" class="span5" style="display:none">
-  <label class="control-label" for="new-ddoc"> _design/ </label>
-  <div class="controls">
-    <input type="text" id="new-ddoc" placeholder="newDesignDoc">
-  </div>
-</div>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/templates/documents/doc.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/templates/documents/doc.html b/apps/fauxton/app/templates/documents/doc.html
deleted file mode 100644
index 10bbf8b..0000000
--- a/apps/fauxton/app/templates/documents/doc.html
+++ /dev/null
@@ -1,55 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<div id="doc">
-  <div class="errors-container"></div>
-   
-<div class="row doc-editor-buttons"> 
-  <div class="span3">
-    <button class="save-doc button green btn-medium save fonticon-circle-check" type="button">Save</button>
-    <button class="button cancel-button gray btn-medium">Back to _all_docs</button>
-  </div>
-
-  <div class="span7">
-    <% if (attachments) { %>
-    <div class="btn-group">
-      <a class="button gray btn-medium dropdown-toggle btn" data-bypass="true" data-toggle="dropdown" href="#">
-        View Attachments
-        <span class="caret"></span>
-      </a>
-      <ul class="dropdown-menu">
-        <%_.each(attachments, function (att) { %>
-        <li>
-        <a href="<%= att.url %>" target="_blank"> <strong> <%= att.fileName %> </strong> -
-          <span> <%= att.contentType %>, <%= formatSize(att.size)%> </span>
-        </a>
-        </li>
-        <% }) %>
-      </ul>
-    </div>
-    <% } %> 
-    <button class="button gray btn-medium  upload"><i class="icon-circle-arrow-up"></i> Upload Attachment</button>
-    <button class="button gray btn-medium duplicate"><i class="icon-repeat"></i> Duplicate document</button>
-  </div>
-
-  <button class="button red btn-medium delete"><i class="icon-trash"></i></button>
-  </ul>
-
-<div id="upload-modal"> </div>
-<div id="duplicate-modal"> </div> 
-</div>
-
-  <div id="editor-container" class="doc-code"><%- JSON.stringify(doc.attributes, null, "  ") %></div>
-
-</div>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/templates/documents/doc_field_editor.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/templates/documents/doc_field_editor.html b/apps/fauxton/app/templates/documents/doc_field_editor.html
deleted file mode 100644
index 77d9278..0000000
--- a/apps/fauxton/app/templates/documents/doc_field_editor.html
+++ /dev/null
@@ -1,74 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<div id="doc-field-editor">
-  <div class="tools">
-
-    <div class="btn-toolbar pull-left">
-      <button class="btn btn-small all">&#x2713; All</button>
-      <button class="btn btn-small disabled delete"><i class="icon-trash"></i> Delete field</button>
-      <button class="btn btn-small new" style="margin-left: 64px"><i class="icon-plus"></i> New field</button>
-    </div>
-    <div class="btn-toolbar pull-right">
-      <button class="btn btn-small cancel button cancel-button outlineGray fonticon-circle-x">Cancel</button>
-      <button class="btn btn-small save button green fonticon-circle-check">Save</button>
-    </div>
-  </div>
-
-  <div class="clearfix"></div>
-  <!-- <hr style="margin-top: 0"/> -->
-
-  <table class="table table-striped  table-condensed">
-    <thead>
-      <tr>
-        <th class="select">
-        </th>
-        <th>Key</th>
-        <th>Value</th>
-      </tr>
-    </thead>
-    <tbody>
-      <tr style="display:none">
-        <td class="select"><input type="checkbox" /></td>
-        <td class="key"><input type="text" class="input-large" value='' /></td>
-        <td class="value"><input type="text" class="input-xxlarge" value='' /></td>
-      </tr>
-      <% _.each(doc, function(value, key) { %>
-        <tr>
-          <td class="select"><input type="checkbox" /></td>
-          <td class="key">
-            <input type="text" class="input-large" name="doc[<%= key %>]" value="<%= key %>" />
-          </td>
-          <td class="value"><input type="text" class="input-xxlarge" value='<%= JSON.stringify(value) %>' /></td>
-        </tr>
-      <% }); %>
-        <tr>
-          <th colspan="3">
-            Attachments
-          </th>
-        </tr>
-      <%_.each(attachments, function (att) { %>
-        <tr>
-          <td class="select"><input type="checkbox" /></td>
-          <td colspan="2">
-            <a href="<%= att.url %>" target="_blank"> <%= att.fileName %> </a>
-            <span> <%= att.contentType %>, <%= formatSize(att.size)%> </span>
-          </td>
-        </tr>
-      <% }) %>
-    </tbody>
-  </table>
-  <a class="btn btn-small new" style="margin-left: 64px"><i class="icon-plus"></i> New field</a>
-
-</div>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/templates/documents/doc_field_editor_tabs.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/templates/documents/doc_field_editor_tabs.html b/apps/fauxton/app/templates/documents/doc_field_editor_tabs.html
deleted file mode 100644
index 766647c..0000000
--- a/apps/fauxton/app/templates/documents/doc_field_editor_tabs.html
+++ /dev/null
@@ -1,19 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<!--<ul class="nav nav-tabs">
-  <li id="field_editor" class="<%= isSelectedClass('field_editor') %>"><a href="#<%= doc.url('app') %>/field_editor">Doc fields</a></li>
-  <li id="code_editor" class="<%= isSelectedClass('code_editor') %>"><a href="#<%= doc.url('app') %>/code_editor"><i class="icon-pencil"> </i> Code editor</a>
-  </li>
-</ul>-->

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/templates/documents/duplicate_doc_modal.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/templates/documents/duplicate_doc_modal.html b/apps/fauxton/app/templates/documents/duplicate_doc_modal.html
deleted file mode 100644
index 3f374b6..0000000
--- a/apps/fauxton/app/templates/documents/duplicate_doc_modal.html
+++ /dev/null
@@ -1,36 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<div class="modal hide fade">
-  <div class="modal-header">
-    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
-    <h3>Duplicate Document</h3>
-  </div>
-  <div class="modal-body">
-    <div id="modal-error" class="hide alert alert-error"/>
-    <form id="file-upload" class="form" method="post">
-      <p class="help-block">
-      Set new documents ID:
-      </p>
-      <input id="dup-id" type="text" class="input-xlarge">
-    </form>
-
-  </div>
-  <div class="modal-footer">
-    <a href="#" data-dismiss="modal" class="btn button cancel-button outlineGray fonticon-circle-x">Cancel</a>
-    <a href="#" id="duplicate-btn" class="btn btn-primary button green save fonticon-circle-check">Duplicate</a>
-  </div>
-</div>
-
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/templates/documents/edit_tools.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/templates/documents/edit_tools.html b/apps/fauxton/app/templates/documents/edit_tools.html
deleted file mode 100644
index 40c884d..0000000
--- a/apps/fauxton/app/templates/documents/edit_tools.html
+++ /dev/null
@@ -1,44 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<div class="view show">
-  <p>
-    Showing 1-<%= numModels %> of <%= totalRows %> rows
-    <% if (updateSeq) { %>
-      -- Update Sequence: <%= updateSeq %>
-    <% } %>
-    <% if (requestDuration) { %>
-  <span class="view-request-duration">
-    View request duration: <strong> <%= requestDuration %> </strong> 
-   </span>
-   <% } %>
-  </p>
-  <table class="all-docs table table-striped table-condensed">
-    <tbody></tbody>
-  </table>
-  <!--
-  <div class="pagination pagination-centered">
-    <ul>
-      <li class="disabled"><a href="#">&laquo;</a></li>
-      <li class="active"><a href="#">1</a></li>
-      <li><a href="#">2</a></li>
-      <li><a href="#">3</a></li>
-      <li><a href="#">4</a></li>
-      <li><a href="#">5</a></li>
-      <li><a href="#">&raquo;</a></li>
-    </ul>
-  </div>
-  -->
-
-</div>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/templates/documents/index_menu_item.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/templates/documents/index_menu_item.html b/apps/fauxton/app/templates/documents/index_menu_item.html
deleted file mode 100644
index 7ca9012..0000000
--- a/apps/fauxton/app/templates/documents/index_menu_item.html
+++ /dev/null
@@ -1,17 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<a id="<%= ddoc_clean %>_<%= index_clean %>" href="#database/<%= database_encoded %>/_design/<%= ddoc_encoded %>/_view/<%= index_encoded %>" class="toggle-view">
-  <%= ddoc %><span class="divider">/</span><%= index %>
-</a>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/templates/documents/index_row_docular.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/templates/documents/index_row_docular.html b/apps/fauxton/app/templates/documents/index_row_docular.html
deleted file mode 100644
index 3835453..0000000
--- a/apps/fauxton/app/templates/documents/index_row_docular.html
+++ /dev/null
@@ -1,26 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<td class="select"><input type="checkbox"></td>
-<td>
-  <div>
-    <pre class="prettyprint"><%- doc.prettyJSON() %></pre>
-    <% if (doc.isEditable()) { %>
-      <div class="btn-group">
-        <a href="#<%= doc.url('app') %>" class="btn btn-small edits">Edit <%= doc.docType() %></a>
-        <button href="#" class="btn btn-small btn-danger delete" title="Delete this document."><i class="icon icon-trash"></i></button>
-      </div>
-    <% } %>
-  </div>
-</td>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/templates/documents/index_row_tabular.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/templates/documents/index_row_tabular.html b/apps/fauxton/app/templates/documents/index_row_tabular.html
deleted file mode 100644
index f5f68fa..0000000
--- a/apps/fauxton/app/templates/documents/index_row_tabular.html
+++ /dev/null
@@ -1,25 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<td class="select"><input type="checkbox"></td>
-<td>
-  <div>
-    <pre class="prettyprint"><%- JSON.stringify(doc.get("key")) %></pre>
-  </div>
-</td>
-<td>
-  <div>
-    <pre class="prettyprint"><%- JSON.stringify(doc.get("value")) %></pre>
-  </div>
-</td>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/templates/documents/jumpdoc.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/templates/documents/jumpdoc.html b/apps/fauxton/app/templates/documents/jumpdoc.html
deleted file mode 100644
index 43fdb9c..0000000
--- a/apps/fauxton/app/templates/documents/jumpdoc.html
+++ /dev/null
@@ -1,19 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<form id="jump-to-doc" class="form-inline input-append" >
-  <input type="text" id="jump-to-doc-id" class="input-large" placeholder="Document ID"></input>
-
-  <button class="fonticon-search btn button red " type="submit"></button>
-</form>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/templates/documents/search.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/templates/documents/search.html b/apps/fauxton/app/templates/documents/search.html
deleted file mode 100644
index bb84891..0000000
--- a/apps/fauxton/app/templates/documents/search.html
+++ /dev/null
@@ -1,15 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<input id="searchbox" type="text" class="span12" placeholder="Search by doc id, view key or search index">
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/templates/documents/sidebar.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/templates/documents/sidebar.html b/apps/fauxton/app/templates/documents/sidebar.html
deleted file mode 100644
index 8a73ae9..0000000
--- a/apps/fauxton/app/templates/documents/sidebar.html
+++ /dev/null
@@ -1,67 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<div id="sidenav">
-  <header class="row-fluid">
-    <div class="span12">
-      <div class="btn-group">
-        <button class="btn dropdown-toggle dropdown-toggle-btn" data-toggle="dropdown">
-          Docs
-          <span class="caret"></span>
-        </button>
-        <ul class="dropdown-menu">
-          <!-- dropdown menu links -->
-          <li><a class="icon-file" href="<%= db_url %>">Docs</a></li>
-          <li><a class="icon-lock" href="<%= permissions_url %>">Permissions</a></li>
-          <li><a class="icon-forward" href="<%= changes_url %>">Changes</a></li>
-          <% _.each(docLinks, function (link) { %>
-          <li><a class="<%= link.icon %>" href="<%= database_url + '/' + link.url %>"><%= link.title %></a></li>
-          <% }); %>
-        </ul>
-      </div>
-
-      <div class="btn-group">
-        <button class="btn dropdown-toggle dropdown-toggle-btn" data-toggle="dropdown">
-          New
-          <span class="caret"></span>
-        </button>
-        <ul class="dropdown-menu">
-          <!-- dropdown menu links -->
-          <li>
-          <a id="doc" href="#<%= database.url('app') %>/new">Document</a>
-          </li>
-          <li>
-          <a href="#<%= database.url('app') %>/new_view">Secondary Index</a>
-           <% _.each(newLinks, function (item) { %>
-           <a href="#<%= database.url('app') %>/<%=item.url%>"> <%= item.name %></a>
-           <% }); %>
-          </li>
-        </ul>
-      </div>
-        <button id="delete-database" class="btn"><i class="icon-trash"></i> Database</button>
-    </div>
-  </header>
-
-  <nav>
-    <ul class="nav nav-list">
-      <li class="active"><a id="all-docs" href="#<%= database.url('index') %>?limit=<%= docLimit %>" class="toggle-view"> All documents</a></li>
-      <li><a id="design-docs" href='#<%= database.url("index") %>?limit=<%= docLimit %>&startkey="_design"&endkey="_e"'  class="toggle-view"> All design docs</a></li>
-    </ul>
-    <ul class="nav nav-list views">
-      <li class="nav-header">Secondary Indexes</li>
-      <li><a id="new-view" href="#<%= database.url('app') %>/new_view" class="new"><i class="icon-plus"></i> New</a></li>
-    </ul>
-    <div id="extension-navs"></div>
-  </nav>
-</div>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/templates/documents/tabs.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/templates/documents/tabs.html b/apps/fauxton/app/templates/documents/tabs.html
deleted file mode 100644
index f8b0c4b..0000000
--- a/apps/fauxton/app/templates/documents/tabs.html
+++ /dev/null
@@ -1,18 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<ul class="nav nav-tabs">
-  <li class="active"><a href="<%= db_url %>">Docs</a></li>
-  <li id="changes"><a  href="<%= changes_url %>">Changes</a></li>
-</ul>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/templates/documents/upload_modal.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/templates/documents/upload_modal.html b/apps/fauxton/app/templates/documents/upload_modal.html
deleted file mode 100644
index 9a5c5cd..0000000
--- a/apps/fauxton/app/templates/documents/upload_modal.html
+++ /dev/null
@@ -1,42 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<div class="modal hide fade">
-  <div class="modal-header">
-    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
-    <h3>Upload an Attachment</h3>
-  </div>
-  <div class="modal-body">
-    <div id="modal-error" class="alert alert-error hide" style="font-size: 16px;"> </div>
-    <form id="file-upload" class="form" method="post">
-      <p class="help-block">
-      Please select the file you want to upload as an attachment to this document. 
-      Please note that this will result in the immediate creation of a new revision of the document, 
-      so it's not necessary to save the document after the upload.
-      </p>
-      <input id="_attachments" type="file" name="_attachments">
-      <input id="_rev" type="hidden" name="_rev" value="" >
-      <br/>
-    </form>
-
-    <div class="progress progress-info">
-      <div class="bar" style="width: 0%"></div>
-    </div>
-  </div>
-  <div class="modal-footer">
-    <a href="#" data-dismiss="modal" data-bypass="true" class="btn button cancel-button outlineGray fonticon-circle-x">Cancel</a>
-    <a href="#" id="upload-btn" data-bypass="true" class="btn btn-primary button green save fonticon-circle-check">Upload</a>
-  </div>
-</div>
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/templates/documents/view_editor.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/templates/documents/view_editor.html b/apps/fauxton/app/templates/documents/view_editor.html
deleted file mode 100644
index ddb5a0c..0000000
--- a/apps/fauxton/app/templates/documents/view_editor.html
+++ /dev/null
@@ -1,87 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-<div class="row">
-  <ul class="nav nav-tabs" id="db-views-tabs-nav">
-    <li class="active"> <a data-bypass="true" id="index-nav" class="fonticon-wrench fonticon" data-toggle="tab" href="#index"><% if (newView) { %>Create Index <% } else { %>Edit Index <% } %></a></li>
-    <% if (!newView) { %>
-    <li><a data-bypass="true" id="query-nav" class="fonticon-plus fonticon" href="#query" data-toggle="tab">Query Options</a></li>
-    <li><a data-bypass="true" id="meta-nav" href="#metadata" data-toggle="tab">Design Doc Metadata</a></li>
-    <% } %>
-  </ul>
-  <div class="all-docs-list errors-container"></div>
-  <div class="tab-content">
-    <div class="tab-pane active" id="index">
-      <div id="define-view" class="ddoc-alert well">
-        <div class="errors-container"></div>
-        <form class="form-horizontal view-query-save">
-
-          <div class="control-group design-doc-group">
-          </div>
-
-          <div class="control-group">
-            <label for="index-name">Index name <a href="<%=getDocUrl('view_functions')%>" target="_blank"><i class="icon-question-sign"></i></a></label>
-            <input type="text" id="index-name" value="<%= viewName %>" placeholder="Index name" />
-          </div>
-
-
-          <div class="control-group">
-            <label for="map-function">Map function <a href="<%=getDocUrl('map_functions')%>" target="_blank"><i class="icon-question-sign"></i></a></label>
-            <% if (newView) { %>
-            <div class="js-editor" id="map-function"><%= langTemplates.map %></div>
-            <% } else { %>
-            <div class="js-editor" id="map-function"><%- ddoc.get('views')[viewName].map %></div>
-            <% } %>
-          </div>
-
-
-          <div class="control-group">
-            <label for="reduce-function-selector">Reduce (optional) <a href="<%=getDocUrl('reduce_functions')%>" target="_blank"><i class="icon-question-sign"></i></a></label>
-
-            <select id="reduce-function-selector">
-              <option value="" <%= !reduceFunStr ? 'selected="selected"' : '' %>>None</option>
-              <% _.each(["_sum", "_count", "_stats"], function(reduce) { %>
-              <option value="<%= reduce %>" <% if (reduce == reduceFunStr) { %>selected<% } %>><%= reduce %></option>
-              <% }) %>
-              <option value="CUSTOM" <% if (isCustomReduce) { %>selected<% } %>>Custom Reduce function</option>
-            </select>
-          </div>
-
-          <div class="control-group reduce-function">
-            <label for="reduce-function">Custom Reduce function</label>
-            <% if (newView) { %>
-            <div class="js-editor" id="reduce-function"><%= langTemplates.reduce %></div>
-            <% } else { %>
-            <div class="js-editor" id="reduce-function"><%- ddoc.get('views')[viewName].reduce %></div>
-            <% } %>
-          </div>
-
-          <div class="control-group">
-            <button class="button green save fonticon-circle-check">Save &amp; Build Index</button>
-            <button class="button btn-info preview">Preview</button>
-            <% if (!newView) { %>
-            <button class="button delete outlineGray fonticon-circle-x">Delete</button>
-            <% } %>
-          </div>
-          <div class="clearfix"></div>
-        </form>
-      </div>
-    </div>
-    <div class="tab-pane" id="metadata">
-      <div id="ddoc-info" class="well"> </div>
-    </div>
-    <div class="tab-pane" id="query">
-    </div>
-  </div>
-</div>
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/templates/fauxton/api_bar.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/templates/fauxton/api_bar.html b/apps/fauxton/app/templates/fauxton/api_bar.html
deleted file mode 100644
index 1f03a2c..0000000
--- a/apps/fauxton/app/templates/fauxton/api_bar.html
+++ /dev/null
@@ -1,30 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<button class="button api-url-btn">
-  API URL 
-  <span class="fonticon-plus icon"></span>
-</button>
-<div class="api-navbar" style="display: none">
-    <div class="input-prepend input-append">
-      <span class="add-on">
-        API reference
-        <a href="<%=getDocUrl(documentation)%>" target="_blank">
-          <i class="icon-question-sign"></i>
-        </a>
-      </span>
-      <input type="text" class="input-xxlarge" value="<%= endpoint %>">
-      <a href="<%= endpoint %>" target="_blank" class="btn">Show me</a>
-    </div>
-</div>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/templates/fauxton/breadcrumbs.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/templates/fauxton/breadcrumbs.html b/apps/fauxton/app/templates/fauxton/breadcrumbs.html
deleted file mode 100644
index 026db89..0000000
--- a/apps/fauxton/app/templates/fauxton/breadcrumbs.html
+++ /dev/null
@@ -1,24 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<ul class="breadcrumb">
-  <% _.each(_.initial(crumbs), function(crumb) { %>
-    <li>
-      <a href="#<%= crumb.link %>"><%= crumb.name %></a>
-      <span class="divider fonticon fonticon-carrot"> </span>
-    </li>
-  <% }); %>
-  <% var last = _.last(crumbs) || {name: ''} %>
-  <li class="active"><%= last.name %></li>
-</ul>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/templates/fauxton/footer.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/templates/fauxton/footer.html b/apps/fauxton/app/templates/fauxton/footer.html
deleted file mode 100644
index 593c11f..0000000
--- a/apps/fauxton/app/templates/fauxton/footer.html
+++ /dev/null
@@ -1,15 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<p>Fauxton on <a href="http://couchdb.apache.org/">Apache CouchDB</a> <%=version%></p>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/templates/fauxton/index_pagination.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/templates/fauxton/index_pagination.html b/apps/fauxton/app/templates/fauxton/index_pagination.html
deleted file mode 100644
index f445377..0000000
--- a/apps/fauxton/app/templates/fauxton/index_pagination.html
+++ /dev/null
@@ -1,24 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<div class="pagination pagination-centered">
-  <ul>
-    <li <% if (!canShowPreviousfn()) {%> class="disabled" <% } %>>
-       <a id="previous" href="#"> Previous </a>
-     </li>
-     <li <% if (!canShowNextfn()) {%> class="disabled" <% } %>>
-       <a id="next" href="#"> Next </a></li>
-  </ul>
-</div>
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/templates/fauxton/nav_bar.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/templates/fauxton/nav_bar.html b/apps/fauxton/app/templates/fauxton/nav_bar.html
deleted file mode 100644
index da030d6..0000000
--- a/apps/fauxton/app/templates/fauxton/nav_bar.html
+++ /dev/null
@@ -1,75 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<div class="brand">
-  <div class="burger">
-    <div><!-- * --></div>
-    <div><!-- * --></div>
-    <div><!-- * --></div>
-  </div>
-  <div class="icon">Apache Fauxton</div>
-</div>
-
-<nav id="main_navigation">
-  <ul id="nav-links" class="nav pull-right">
-    <% _.each(navLinks, function(link) { %>
-    <% if (link.view) {return;}  %>
-        <li data-nav-name= "<%= link.title %>" >
-          <a href="<%= link.href %>">
-            <span class="<%= link.icon %> fonticon"></span>
-            <%= link.title %>
-          </a>
-        </li>
-    <% }); %>
-  </ul>
-
-  <div id="footer-links">
-
-    <ul id="bottom-nav-links" class="nav">
-        <li data-nav-name= "Documentation">
-            <a href="<%=getDocUrl('docs')%>" target="_blank">
-              <span class="fonticon-bookmark fonticon"></span>
-                Documentation
-            </a>
-        </li>
-
-
-      <% _.each(bottomNavLinks, function(link) { %>
-      <% if (link.view) {return;}  %>
-        <li data-nav-name= "<%= link.title %>">
-            <a href="<%= link.href %>">
-              <span class="<%= link.icon %> fonticon"></span>
-              <%= link.title %>
-            </a>
-        </li>
-      <% }); %>
-    </ul>
-
-    <ul id="footer-nav-links" class="nav">
-      <% _.each(footerNavLinks, function(link) { %>
-      <% if (link.view) {return;}  %>
-        <li data-nav-name= "<%= link.title %>">
-            <a href="<%= link.href %>">
-              <span class="<%= link.icon %> fonticon"></span>
-              <%= link.title %>
-            </a>
-        </li>
-      <% }); %>
-    </ul>
-
-  </div>
-</nav>
-
-
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/templates/fauxton/notification.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/templates/fauxton/notification.html b/apps/fauxton/app/templates/fauxton/notification.html
deleted file mode 100644
index ca8a903..0000000
--- a/apps/fauxton/app/templates/fauxton/notification.html
+++ /dev/null
@@ -1,18 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<div class="alert alert-<%= type %>">
-  <button type="button" class="close" data-dismiss="alert">×</button>
-  <%= msg %>
-</div>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/templates/fauxton/pagination.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/templates/fauxton/pagination.html b/apps/fauxton/app/templates/fauxton/pagination.html
deleted file mode 100644
index 19dfc8c..0000000
--- a/apps/fauxton/app/templates/fauxton/pagination.html
+++ /dev/null
@@ -1,31 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<div class="pagination pagination-centered">
-  <ul>
-    <% if (page > 1) { %>
-    <li> <a href="<%= urlFun(page-1) %>">&laquo;</a></li>
-    <% } else { %>
-      <li class="disabled"> <a href="<%= urlFun(page) %>">&laquo;</a></li>
-    <% } %>
-    <% _.each(_.range(1, totalPages+1), function(i) { %>
-      <li <% if (page == i) { %>class="active"<% } %>> <a href="<%= urlFun(i) %>"><%= i %></a></li>
-    <% }) %>
-    <% if (page < totalPages) { %>
-      <li><a href="<%= urlFun(page+1) %>">&raquo;</a></li>
-    <% } else { %>
-      <li class="disabled"> <a href="<%= urlFun(page) %>">&raquo;</a></li>
-    <% } %>
-  </ul>
-</div>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/templates/layouts/one_pane.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/templates/layouts/one_pane.html b/apps/fauxton/app/templates/layouts/one_pane.html
deleted file mode 100644
index c7adf1f..0000000
--- a/apps/fauxton/app/templates/layouts/one_pane.html
+++ /dev/null
@@ -1,28 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<div id="primary-navbar"></div>
-<div id="dashboard" class="container-fluid one-pane">
-  <div class="fixed-header">
-    <div id="breadcrumbs"></div>
-    <div id="api-navbar"></div>
-  </div>
-
-
-  <div class="row-fluid content-area">
-  	<div id="tabs" class="row"></div>
-    <div id="dashboard-content" class="window-resizeable"></div>
-  </div>
-</div>
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/templates/layouts/one_pane_notabs.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/templates/layouts/one_pane_notabs.html b/apps/fauxton/app/templates/layouts/one_pane_notabs.html
deleted file mode 100644
index f58661f..0000000
--- a/apps/fauxton/app/templates/layouts/one_pane_notabs.html
+++ /dev/null
@@ -1,27 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<div id="primary-navbar"></div>
-<div id="dashboard" class="container-fluid one-pane">
-  <div class="fixed-header">
-    <div id="breadcrumbs"></div>
-    <div id="api-navbar"></div>
-  </div>
-
-
-  <div class="row-fluid content-area">
-    <div id="dashboard-content" class="window-resizeable"></div>
-  </div>
-</div>
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/templates/layouts/two_pane.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/templates/layouts/two_pane.html b/apps/fauxton/app/templates/layouts/two_pane.html
deleted file mode 100644
index 0c3165e..0000000
--- a/apps/fauxton/app/templates/layouts/two_pane.html
+++ /dev/null
@@ -1,30 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-
-<div id="primary-navbar"></div>
-<div id="dashboard" class="container-fluid">
-  <div class="fixed-header">
-    <div id="breadcrumbs"></div>
-    <div id="api-navbar"></div>
-  </div>
-
-
-  <div class="row-fluid content-area">
-  	<div id="tabs" class="row"></div>
-    <div id="left-content" class="span6"></div>
-    <div id="right-content" class="span6"></div>
-  </div>
-</div>
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/templates/layouts/with_right_sidebar.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/templates/layouts/with_right_sidebar.html b/apps/fauxton/app/templates/layouts/with_right_sidebar.html
deleted file mode 100644
index ade5b82..0000000
--- a/apps/fauxton/app/templates/layouts/with_right_sidebar.html
+++ /dev/null
@@ -1,26 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<div id="primary-navbar"></div>
-<div id="dashboard" class="container-fluid">
-  <div class="fixed-header">
-    <div id="breadcrumbs"></div>
-    <div id="api-navbar"></div>
-  </div>
-  <div class="with-sidebar-right content-area">
-    <div id="dashboard-content" class="list"></div>
-    <div id="sidebar-content" class="sidebar pull-right window-resizeable"></div>
-  </div>
-</div>
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/templates/layouts/with_sidebar.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/templates/layouts/with_sidebar.html b/apps/fauxton/app/templates/layouts/with_sidebar.html
deleted file mode 100644
index 0bba4a1..0000000
--- a/apps/fauxton/app/templates/layouts/with_sidebar.html
+++ /dev/null
@@ -1,27 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-
-<div id="primary-navbar"></div>
-<div id="dashboard" class="container-fluid">
-<header class="fixed-header">
-  <div id="breadcrumbs"></div>
-  <div id="api-navbar"></div>
-</header>
-  <div class="with-sidebar content-area">
-    <div id="sidebar-content" class="sidebar"></div>
-    <div id="dashboard-content" class="list window-resizeable"></div>
-  </div>
-</div>
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/templates/layouts/with_tabs.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/templates/layouts/with_tabs.html b/apps/fauxton/app/templates/layouts/with_tabs.html
deleted file mode 100644
index 8bfc7e0..0000000
--- a/apps/fauxton/app/templates/layouts/with_tabs.html
+++ /dev/null
@@ -1,28 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<div id="primary-navbar"></div>
-<div id="dashboard" class="container-fluid">
-
-<div class="fixed-header">
-  <div id="breadcrumbs"></div>
-  <div id="api-navbar"></div>
-</div>
-
-  <div class="row-fluid content-area">
-  	<div id="tabs" class="row-fluid"></div>
-    <div id="dashboard-content" class="list span12 window-resizeable"></div>
-  </div>
-
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/templates/layouts/with_tabs_sidebar.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/templates/layouts/with_tabs_sidebar.html b/apps/fauxton/app/templates/layouts/with_tabs_sidebar.html
deleted file mode 100644
index d4efc8d..0000000
--- a/apps/fauxton/app/templates/layouts/with_tabs_sidebar.html
+++ /dev/null
@@ -1,41 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<div id="primary-navbar"></div>
-<div id="dashboard" class="container-fluid">
-
-<header class="fixed-header">
-  <div id="breadcrumbs"></div>
-  <div id="api-navbar"></div>
-</header>
-
-
-  <div class="with-sidebar content-area">
-
-    <div id="tabs" class="row-fluid"></div>
-
-    <aside id="sidebar-content" class="sidebar"></aside>
-
-    <section id="dashboard-content" class="list pull-right window-resizeable">
-      <div class="inner">
-        <div id="dashboard-upper-menu" class="window-resizeable"></div>
-        <div id="dashboard-upper-content"></div>
-
-        <div id="dashboard-lower-content"></div>
-      </div>
-    </section>
-
-  </div>
-
-


[02/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/test/mocha/sinon-chai.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/test/mocha/sinon-chai.js b/apps/fauxton/test/mocha/sinon-chai.js
deleted file mode 100644
index 26cee36..0000000
--- a/apps/fauxton/test/mocha/sinon-chai.js
+++ /dev/null
@@ -1,109 +0,0 @@
-(function (sinonChai) {
-    "use strict";
-
-    // Module systems magic dance.
-
-    if (typeof require === "function" && typeof exports === "object" && typeof module === "object") {
-        // NodeJS
-        module.exports = sinonChai;
-    } else if (typeof define === "function" && define.amd) {
-        // AMD
-        define(function () {
-            return sinonChai;
-        });
-    } else {
-        // Other environment (usually <script> tag): plug in to global chai instance directly.
-        chai.use(sinonChai);
-    }
-}(function sinonChai(chai, utils) {
-    "use strict";
-
-    var slice = Array.prototype.slice;
-
-    function isSpy(putativeSpy) {
-        return typeof putativeSpy === "function" &&
-               typeof putativeSpy.getCall === "function" &&
-               typeof putativeSpy.calledWithExactly === "function";
-    }
-
-    function isCall(putativeCall) {
-        return putativeCall && isSpy(putativeCall.proxy);
-    }
-
-    function assertCanWorkWith(assertion) {
-        if (!isSpy(assertion._obj) && !isCall(assertion._obj)) {
-            throw new TypeError(utils.inspect(assertion._obj) + " is not a spy or a call to a spy!");
-        }
-    }
-
-    function getMessages(spy, action, nonNegatedSuffix, always, args) {
-        var verbPhrase = always ? "always have " : "have ";
-        nonNegatedSuffix = nonNegatedSuffix || "";
-        if (isSpy(spy.proxy)) {
-            spy = spy.proxy;
-        }
-
-        function printfArray(array) {
-            return spy.printf.apply(spy, array);
-        }
-
-        return {
-            affirmative: printfArray(["expected %n to " + verbPhrase + action + nonNegatedSuffix].concat(args)),
-            negative: printfArray(["expected %n to not " + verbPhrase + action].concat(args))
-        };
-    }
-
-    function sinonProperty(name, action, nonNegatedSuffix) {
-        utils.addProperty(chai.Assertion.prototype, name, function () {
-            assertCanWorkWith(this);
-
-            var messages = getMessages(this._obj, action, nonNegatedSuffix, false);
-            this.assert(this._obj[name], messages.affirmative, messages.negative);
-        });
-    }
-
-    function createSinonMethodHandler(sinonName, action, nonNegatedSuffix) {
-        return function () {
-            assertCanWorkWith(this);
-
-            var alwaysSinonMethod = "always" + sinonName[0].toUpperCase() + sinonName.substring(1);
-            var shouldBeAlways = utils.flag(this, "always") && typeof this._obj[alwaysSinonMethod] === "function";
-            var sinonMethod = shouldBeAlways ? alwaysSinonMethod : sinonName;
-
-            var messages = getMessages(this._obj, action, nonNegatedSuffix, shouldBeAlways, slice.call(arguments));
-            this.assert(this._obj[sinonMethod].apply(this._obj, arguments), messages.affirmative, messages.negative);
-        };
-    }
-
-    function sinonMethodAsProperty(name, action, nonNegatedSuffix) {
-        var handler = createSinonMethodHandler(name, action, nonNegatedSuffix);
-        utils.addProperty(chai.Assertion.prototype, name, handler);
-    }
-
-    function exceptionalSinonMethod(chaiName, sinonName, action, nonNegatedSuffix) {
-        var handler = createSinonMethodHandler(sinonName, action, nonNegatedSuffix);
-        utils.addMethod(chai.Assertion.prototype, chaiName, handler);
-    }
-
-    function sinonMethod(name, action, nonNegatedSuffix) {
-        exceptionalSinonMethod(name, name, action, nonNegatedSuffix);
-    }
-
-    utils.addProperty(chai.Assertion.prototype, "always", function () {
-        utils.flag(this, "always", true);
-    });
-
-    sinonProperty("called", "been called", " at least once, but it was never called");
-    sinonProperty("calledOnce", "been called exactly once", ", but it was called %c%C");
-    sinonProperty("calledTwice", "been called exactly twice", ", but it was called %c%C");
-    sinonProperty("calledThrice", "been called exactly thrice", ", but it was called %c%C");
-    sinonMethodAsProperty("calledWithNew", "been called with new");
-    sinonMethod("calledBefore", "been called before %1");
-    sinonMethod("calledAfter", "been called after %1");
-    sinonMethod("calledOn", "been called with %1 as this", ", but it was called with %t instead");
-    sinonMethod("calledWith", "been called with arguments %*", "%C");
-    sinonMethod("calledWithExactly", "been called with exact arguments %*", "%C");
-    sinonMethod("calledWithMatch", "been called with arguments matching %*", "%C");
-    sinonMethod("returned", "returned %1");
-    exceptionalSinonMethod("thrown", "threw", "thrown %1");
-}));


[13/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/js/libs/nv.d3.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/js/libs/nv.d3.js b/apps/fauxton/assets/js/libs/nv.d3.js
deleted file mode 100755
index 936b406..0000000
--- a/apps/fauxton/assets/js/libs/nv.d3.js
+++ /dev/null
@@ -1,13119 +0,0 @@
-(function(){
-
-var nv = window.nv || {};
-
-nv.version = '0.0.1a';
-nv.dev = true //set false when in production
-
-window.nv = nv;
-
-nv.tooltip = {}; // For the tooltip system
-nv.utils = {}; // Utility subsystem
-nv.models = {}; //stores all the possible models/components
-nv.charts = {}; //stores all the ready to use charts
-nv.graphs = []; //stores all the graphs currently on the page
-nv.logs = {}; //stores some statistics and potential error messages
-
-nv.dispatch = d3.dispatch('render_start', 'render_end');
-
-// *************************************************************************
-//  Development render timers - disabled if dev = false
-
-if (nv.dev) {
-  nv.dispatch.on('render_start', function(e) {
-    nv.logs.startTime = +new Date();
-  });
-
-  nv.dispatch.on('render_end', function(e) {
-    nv.logs.endTime = +new Date();
-    nv.logs.totalTime = nv.logs.endTime - nv.logs.startTime;
-    nv.log('total', nv.logs.totalTime); // used for development, to keep track of graph generation times
-  });
-}
-
-// ********************************************
-//  Public Core NV functions
-
-// Logs all arguments, and returns the last so you can test things in place
-nv.log = function() {
-  if (nv.dev && console.log && console.log.apply)
-    console.log.apply(console, arguments)
-  else if (nv.dev && console.log && Function.prototype.bind) {
-    var log = Function.prototype.bind.call(console.log, console);
-    log.apply(console, arguments);
-  }
-  return arguments[arguments.length - 1];
-};
-
-
-nv.render = function render(step) {
-  step = step || 1; // number of graphs to generate in each timeout loop
-
-  nv.render.active = true;
-  nv.dispatch.render_start();
-
-  setTimeout(function() {
-    var chart, graph;
-
-    for (var i = 0; i < step && (graph = nv.render.queue[i]); i++) {
-      chart = graph.generate();
-      if (typeof graph.callback == typeof(Function)) graph.callback(chart);
-      nv.graphs.push(chart);
-    }
-
-    nv.render.queue.splice(0, i);
-
-    if (nv.render.queue.length) setTimeout(arguments.callee, 0);
-    else { nv.render.active = false; nv.dispatch.render_end(); }
-  }, 0);
-};
-
-nv.render.active = false;
-nv.render.queue = [];
-
-nv.addGraph = function(obj) {
-  if (typeof arguments[0] === typeof(Function))
-    obj = {generate: arguments[0], callback: arguments[1]};
-
-  nv.render.queue.push(obj);
-
-  if (!nv.render.active) nv.render();
-};
-
-nv.identity = function(d) { return d; };
-
-nv.strip = function(s) { return s.replace(/(\s|&)/g,''); };
-
-function daysInMonth(month,year) {
-  return (new Date(year, month+1, 0)).getDate();
-}
-
-function d3_time_range(floor, step, number) {
-  return function(t0, t1, dt) {
-    var time = floor(t0), times = [];
-    if (time < t0) step(time);
-    if (dt > 1) {
-      while (time < t1) {
-        var date = new Date(+time);
-        if ((number(date) % dt === 0)) times.push(date);
-        step(time);
-      }
-    } else {
-      while (time < t1) { times.push(new Date(+time)); step(time); }
-    }
-    return times;
-  };
-}
-
-d3.time.monthEnd = function(date) {
-  return new Date(date.getFullYear(), date.getMonth(), 0);
-};
-
-d3.time.monthEnds = d3_time_range(d3.time.monthEnd, function(date) {
-    date.setUTCDate(date.getUTCDate() + 1);
-    date.setDate(daysInMonth(date.getMonth() + 1, date.getFullYear()));
-  }, function(date) {
-    return date.getMonth();
-  }
-);
-
-
-/*****
- * A no-frills tooltip implementation.
- *****/
-
-
-(function() {
-
-  var nvtooltip = window.nv.tooltip = {};
-
-  nvtooltip.show = function(pos, content, gravity, dist, parentContainer, classes) {
-
-    var container = document.createElement('div');
-        container.className = 'nvtooltip ' + (classes ? classes : 'xy-tooltip');
-
-    gravity = gravity || 's';
-    dist = dist || 20;
-
-    var body = parentContainer;
-    if ( !parentContainer || parentContainer.tagName.match(/g|svg/i)) {
-        //If the parent element is an SVG element, place tooltip in the <body> element.
-        body = document.getElementsByTagName('body')[0];
-    }
-
-    container.innerHTML = content;
-    container.style.left = 0;
-    container.style.top = 0;
-    container.style.opacity = 0;
-
-    body.appendChild(container);
-
-    var height = parseInt(container.offsetHeight),
-        width = parseInt(container.offsetWidth),
-        windowWidth = nv.utils.windowSize().width,
-        windowHeight = nv.utils.windowSize().height,
-        scrollTop = window.scrollY,
-        scrollLeft = window.scrollX,
-        left, top;
-
-    windowHeight = window.innerWidth >= document.body.scrollWidth ? windowHeight : windowHeight - 16;
-    windowWidth = window.innerHeight >= document.body.scrollHeight ? windowWidth : windowWidth - 16;
-
-    var tooltipTop = function ( Elem ) {
-        var offsetTop = top;
-        do {
-            if( !isNaN( Elem.offsetTop ) ) {
-                offsetTop += (Elem.offsetTop);
-            }
-        } while( Elem = Elem.offsetParent );
-        return offsetTop;
-    }
-
-    var tooltipLeft = function ( Elem ) {
-        var offsetLeft = left;
-        do {
-            if( !isNaN( Elem.offsetLeft ) ) {
-                offsetLeft += (Elem.offsetLeft);
-            }
-        } while( Elem = Elem.offsetParent );
-        return offsetLeft;
-    }
-
-    switch (gravity) {
-      case 'e':
-        left = pos[0] - width - dist;
-        top = pos[1] - (height / 2);
-        var tLeft = tooltipLeft(container);
-        var tTop = tooltipTop(container);
-        if (tLeft < scrollLeft) left = pos[0] + dist > scrollLeft ? pos[0] + dist : scrollLeft - tLeft + left;
-        if (tTop < scrollTop) top = scrollTop - tTop + top;
-        if (tTop + height > scrollTop + windowHeight) top = scrollTop + windowHeight - tTop + top - height;
-        break;
-      case 'w':
-        left = pos[0] + dist;
-        top = pos[1] - (height / 2);
-        if (tLeft + width > windowWidth) left = pos[0] - width - dist;
-        if (tTop < scrollTop) top = scrollTop + 5;
-        if (tTop + height > scrollTop + windowHeight) top = scrollTop - height - 5;
-        break;
-      case 'n':
-        left = pos[0] - (width / 2) - 5;
-        top = pos[1] + dist;
-        var tLeft = tooltipLeft(container);
-        var tTop = tooltipTop(container);
-        if (tLeft < scrollLeft) left = scrollLeft + 5;
-        if (tLeft + width > windowWidth) left = left - width/2 + 5;
-        if (tTop + height > scrollTop + windowHeight) top = scrollTop + windowHeight - tTop + top - height;
-        break;
-      case 's':
-        left = pos[0] - (width / 2);
-        top = pos[1] - height - dist;
-        var tLeft = tooltipLeft(container);
-        var tTop = tooltipTop(container);
-        if (tLeft < scrollLeft) left = scrollLeft + 5;
-        if (tLeft + width > windowWidth) left = left - width/2 + 5;
-        if (scrollTop > tTop) top = scrollTop;
-        break;
-    }
-
-
-    container.style.left = left+'px';
-    container.style.top = top+'px';
-    container.style.opacity = 1;
-    container.style.position = 'absolute'; //fix scroll bar issue
-    container.style.pointerEvents = 'none'; //fix scroll bar issue
-
-    return container;
-  };
-
-  nvtooltip.cleanup = function() {
-
-      // Find the tooltips, mark them for removal by this class (so others cleanups won't find it)
-      var tooltips = document.getElementsByClassName('nvtooltip');
-      var purging = [];
-      while(tooltips.length) {
-        purging.push(tooltips[0]);
-        tooltips[0].style.transitionDelay = '0 !important';
-        tooltips[0].style.opacity = 0;
-        tooltips[0].className = 'nvtooltip-pending-removal';
-      }
-
-
-      setTimeout(function() {
-
-          while (purging.length) {
-             var removeMe = purging.pop();
-              removeMe.parentNode.removeChild(removeMe);
-          }
-    }, 500);
-  };
-
-
-})();
-
-nv.utils.windowSize = function() {
-    // Sane defaults
-    var size = {width: 640, height: 480};
-
-    // Earlier IE uses Doc.body
-    if (document.body && document.body.offsetWidth) {
-        size.width = document.body.offsetWidth;
-        size.height = document.body.offsetHeight;
-    }
-
-    // IE can use depending on mode it is in
-    if (document.compatMode=='CSS1Compat' &&
-        document.documentElement &&
-        document.documentElement.offsetWidth ) {
-        size.width = document.documentElement.offsetWidth;
-        size.height = document.documentElement.offsetHeight;
-    }
-
-    // Most recent browsers use
-    if (window.innerWidth && window.innerHeight) {
-        size.width = window.innerWidth;
-        size.height = window.innerHeight;
-    }
-    return (size);
-};
-
-
-
-// Easy way to bind multiple functions to window.onresize
-// TODO: give a way to remove a function after its bound, other than removing all of them
-nv.utils.windowResize = function(fun){
-  var oldresize = window.onresize;
-
-  window.onresize = function(e) {
-    if (typeof oldresize == 'function') oldresize(e);
-    fun(e);
-  }
-}
-
-// Backwards compatible way to implement more d3-like coloring of graphs.
-// If passed an array, wrap it in a function which implements the old default
-// behavior
-nv.utils.getColor = function(color) {
-    if (!arguments.length) return nv.utils.defaultColor(); //if you pass in nothing, get default colors back
-
-    if( Object.prototype.toString.call( color ) === '[object Array]' )
-        return function(d, i) { return d.color || color[i % color.length]; };
-    else
-        return color;
-        //can't really help it if someone passes rubbish as color
-}
-
-// Default color chooser uses the index of an object as before.
-nv.utils.defaultColor = function() {
-    var colors = d3.scale.category20().range();
-    return function(d, i) { return d.color || colors[i % colors.length] };
-}
-
-
-// Returns a color function that takes the result of 'getKey' for each series and
-// looks for a corresponding color from the dictionary,
-nv.utils.customTheme = function(dictionary, getKey, defaultColors) {
-  getKey = getKey || function(series) { return series.key }; // use default series.key if getKey is undefined
-  defaultColors = defaultColors || d3.scale.category20().range(); //default color function
-
-  var defIndex = defaultColors.length; //current default color (going in reverse)
-
-  return function(series, index) {
-    var key = getKey(series);
-
-    if (!defIndex) defIndex = defaultColors.length; //used all the default colors, start over
-
-    if (typeof dictionary[key] !== "undefined")
-      return (typeof dictionary[key] === "function") ? dictionary[key]() : dictionary[key];
-    else
-      return defaultColors[--defIndex]; // no match in dictionary, use default color
-  }
-}
-
-
-
-// From the PJAX example on d3js.org, while this is not really directly needed
-// it's a very cool method for doing pjax, I may expand upon it a little bit,
-// open to suggestions on anything that may be useful
-nv.utils.pjax = function(links, content) {
-  d3.selectAll(links).on("click", function() {
-    history.pushState(this.href, this.textContent, this.href);
-    load(this.href);
-    d3.event.preventDefault();
-  });
-
-  function load(href) {
-    d3.html(href, function(fragment) {
-      var target = d3.select(content).node();
-      target.parentNode.replaceChild(d3.select(fragment).select(content).node(), target);
-      nv.utils.pjax(links, content);
-    });
-  }
-
-  d3.select(window).on("popstate", function() {
-    if (d3.event.state) load(d3.event.state);
-  });
-}
-
-/* For situations where we want to approximate the width in pixels for an SVG:text element.
-Most common instance is when the element is in a display:none; container. 
-Forumla is : text.length * font-size * constant_factor
-*/
-nv.utils.calcApproxTextWidth = function (svgTextElem) {
-    if (svgTextElem instanceof d3.selection) {
-        var fontSize = parseInt(svgTextElem.style("font-size").replace("px",""));
-        var textLength = svgTextElem.text().length;
-
-        return textLength * fontSize * 0.5; 
-    }
-    return 0;
-};
-nv.models.axis = function() {
-
-  //============================================================
-  // Public Variables with Default Settings
-  //------------------------------------------------------------
-
-  var axis = d3.svg.axis()
-    ;
-
-  var margin = {top: 0, right: 0, bottom: 0, left: 0}
-    , width = 75 //only used for tickLabel currently
-    , height = 60 //only used for tickLabel currently
-    , scale = d3.scale.linear()
-    , axisLabelText = null
-    , showMaxMin = true //TODO: showMaxMin should be disabled on all ordinal scaled axes
-    , highlightZero = true
-    , rotateLabels = 0
-    , rotateYLabel = true
-    , staggerLabels = false
-    , isOrdinal = false
-    , ticks = null
-    ;
-
-  axis
-    .scale(scale)
-    .orient('bottom')
-    .tickFormat(function(d) { return d })
-    ;
-
-  //============================================================
-
-
-  //============================================================
-  // Private Variables
-  //------------------------------------------------------------
-
-  var scale0;
-
-  //============================================================
-
-
-  function chart(selection) {
-    selection.each(function(data) {
-      var container = d3.select(this);
-
-
-      //------------------------------------------------------------
-      // Setup containers and skeleton of chart
-
-      var wrap = container.selectAll('g.nv-wrap.nv-axis').data([data]);
-      var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-axis');
-      var gEnter = wrapEnter.append('g');
-      var g = wrap.select('g')
-
-      //------------------------------------------------------------
-
-
-      if (ticks !== null)
-        axis.ticks(ticks);
-      else if (axis.orient() == 'top' || axis.orient() == 'bottom')
-        axis.ticks(Math.abs(scale.range()[1] - scale.range()[0]) / 100);
-
-
-      //TODO: consider calculating width/height based on whether or not label is added, for reference in charts using this component
-
-
-      d3.transition(g)
-          .call(axis);
-
-      scale0 = scale0 || axis.scale();
-
-      var fmt = axis.tickFormat();
-      if (fmt == null) {
-        fmt = scale0.tickFormat();
-      }
-
-      var axisLabel = g.selectAll('text.nv-axislabel')
-          .data([axisLabelText || null]);
-      axisLabel.exit().remove();
-      switch (axis.orient()) {
-        case 'top':
-          axisLabel.enter().append('text').attr('class', 'nv-axislabel');
-          var w = (scale.range().length==2) ? scale.range()[1] : (scale.range()[scale.range().length-1]+(scale.range()[1]-scale.range()[0]));
-          axisLabel
-              .attr('text-anchor', 'middle')
-              .attr('y', 0)
-              .attr('x', w/2);
-          if (showMaxMin) {
-            var axisMaxMin = wrap.selectAll('g.nv-axisMaxMin')
-                           .data(scale.domain());
-            axisMaxMin.enter().append('g').attr('class', 'nv-axisMaxMin').append('text');
-            axisMaxMin.exit().remove();
-            axisMaxMin
-                .attr('transform', function(d,i) {
-                  return 'translate(' + scale(d) + ',0)'
-                })
-              .select('text')
-                .attr('dy', '0em')
-                .attr('y', -axis.tickPadding())
-                .attr('text-anchor', 'middle')
-                .text(function(d,i) {
-                  var v = fmt(d);
-                  return ('' + v).match('NaN') ? '' : v;
-                });
-            d3.transition(axisMaxMin)
-                .attr('transform', function(d,i) {
-                  return 'translate(' + scale.range()[i] + ',0)'
-                });
-          }
-          break;
-        case 'bottom':
-          var xLabelMargin = 36;
-          var maxTextWidth = 30;
-          var xTicks = g.selectAll('g').select("text");
-          if (rotateLabels%360) {
-            //Calculate the longest xTick width
-            xTicks.each(function(d,i){
-              var width = this.getBBox().width;
-              if(width > maxTextWidth) maxTextWidth = width;
-            });
-            //Convert to radians before calculating sin. Add 30 to margin for healthy padding.
-            var sin = Math.abs(Math.sin(rotateLabels*Math.PI/180));
-            var xLabelMargin = (sin ? sin*maxTextWidth : maxTextWidth)+30;
-            //Rotate all xTicks
-            xTicks
-              .attr('transform', function(d,i,j) { return 'rotate(' + rotateLabels + ' 0,0)' })
-              .attr('text-anchor', rotateLabels%360 > 0 ? 'start' : 'end');
-          }
-          axisLabel.enter().append('text').attr('class', 'nv-axislabel');
-          var w = (scale.range().length==2) ? scale.range()[1] : (scale.range()[scale.range().length-1]+(scale.range()[1]-scale.range()[0]));
-          axisLabel
-              .attr('text-anchor', 'middle')
-              .attr('y', xLabelMargin)
-              .attr('x', w/2);
-          if (showMaxMin) {
-          //if (showMaxMin && !isOrdinal) {
-            var axisMaxMin = wrap.selectAll('g.nv-axisMaxMin')
-                           //.data(scale.domain())
-                           .data([scale.domain()[0], scale.domain()[scale.domain().length - 1]]);
-            axisMaxMin.enter().append('g').attr('class', 'nv-axisMaxMin').append('text');
-            axisMaxMin.exit().remove();
-            axisMaxMin
-                .attr('transform', function(d,i) {
-                  return 'translate(' + (scale(d) + (isOrdinal ? scale.rangeBand() / 2 : 0)) + ',0)'
-                })
-              .select('text')
-                .attr('dy', '.71em')
-                .attr('y', axis.tickPadding())
-                .attr('transform', function(d,i,j) { return 'rotate(' + rotateLabels + ' 0,0)' })
-                .attr('text-anchor', rotateLabels ? (rotateLabels%360 > 0 ? 'start' : 'end') : 'middle')
-                .text(function(d,i) {
-                  var v = fmt(d);
-                  return ('' + v).match('NaN') ? '' : v;
-                });
-            d3.transition(axisMaxMin)
-                .attr('transform', function(d,i) {
-                  //return 'translate(' + scale.range()[i] + ',0)'
-                  //return 'translate(' + scale(d) + ',0)'
-                  return 'translate(' + (scale(d) + (isOrdinal ? scale.rangeBand() / 2 : 0)) + ',0)'
-                });
-          }
-          if (staggerLabels)
-            xTicks
-                .attr('transform', function(d,i) { return 'translate(0,' + (i % 2 == 0 ? '0' : '12') + ')' });
-
-          break;
-        case 'right':
-          axisLabel.enter().append('text').attr('class', 'nv-axislabel');
-          axisLabel
-              .attr('text-anchor', rotateYLabel ? 'middle' : 'begin')
-              .attr('transform', rotateYLabel ? 'rotate(90)' : '')
-              .attr('y', rotateYLabel ? (-Math.max(margin.right,width) + 12) : -10) //TODO: consider calculating this based on largest tick width... OR at least expose this on chart
-              .attr('x', rotateYLabel ? (scale.range()[0] / 2) : axis.tickPadding());
-          if (showMaxMin) {
-            var axisMaxMin = wrap.selectAll('g.nv-axisMaxMin')
-                           .data(scale.domain());
-            axisMaxMin.enter().append('g').attr('class', 'nv-axisMaxMin').append('text')
-                .style('opacity', 0);
-            axisMaxMin.exit().remove();
-            axisMaxMin
-                .attr('transform', function(d,i) {
-                  return 'translate(0,' + scale(d) + ')'
-                })
-              .select('text')
-                .attr('dy', '.32em')
-                .attr('y', 0)
-                .attr('x', axis.tickPadding())
-                .attr('text-anchor', 'start')
-                .text(function(d,i) {
-                  var v = fmt(d);
-                  return ('' + v).match('NaN') ? '' : v;
-                });
-            d3.transition(axisMaxMin)
-                .attr('transform', function(d,i) {
-                  return 'translate(0,' + scale.range()[i] + ')'
-                })
-              .select('text')
-                .style('opacity', 1);
-          }
-          break;
-        case 'left':
-          /*
-          //For dynamically placing the label. Can be used with dynamically-sized chart axis margins
-          var yTicks = g.selectAll('g').select("text");
-          yTicks.each(function(d,i){
-            var labelPadding = this.getBBox().width + axis.tickPadding() + 16;
-            if(labelPadding > width) width = labelPadding;
-          });
-          */
-          axisLabel.enter().append('text').attr('class', 'nv-axislabel');
-          axisLabel
-              .attr('text-anchor', rotateYLabel ? 'middle' : 'end')
-              .attr('transform', rotateYLabel ? 'rotate(-90)' : '')
-              .attr('y', rotateYLabel ? (-Math.max(margin.left,width) + 12) : -10) //TODO: consider calculating this based on largest tick width... OR at least expose this on chart
-              .attr('x', rotateYLabel ? (-scale.range()[0] / 2) : -axis.tickPadding());
-          if (showMaxMin) {
-            var axisMaxMin = wrap.selectAll('g.nv-axisMaxMin')
-                           .data(scale.domain());
-            axisMaxMin.enter().append('g').attr('class', 'nv-axisMaxMin').append('text')
-                .style('opacity', 0);
-            axisMaxMin.exit().remove();
-            axisMaxMin
-                .attr('transform', function(d,i) {
-                  return 'translate(0,' + scale0(d) + ')'
-                })
-              .select('text')
-                .attr('dy', '.32em')
-                .attr('y', 0)
-                .attr('x', -axis.tickPadding())
-                .attr('text-anchor', 'end')
-                .text(function(d,i) {
-                  var v = fmt(d);
-                  return ('' + v).match('NaN') ? '' : v;
-                });
-            d3.transition(axisMaxMin)
-                .attr('transform', function(d,i) {
-                  return 'translate(0,' + scale.range()[i] + ')'
-                })
-              .select('text')
-                .style('opacity', 1);
-          }
-          break;
-      }
-      axisLabel
-          .text(function(d) { return d });
-
-
-      if (showMaxMin && (axis.orient() === 'left' || axis.orient() === 'right')) {
-        //check if max and min overlap other values, if so, hide the values that overlap
-        g.selectAll('g') // the g's wrapping each tick
-            .each(function(d,i) {
-              d3.select(this).select('text').attr('opacity', 1);
-              if (scale(d) < scale.range()[1] + 10 || scale(d) > scale.range()[0] - 10) { // 10 is assuming text height is 16... if d is 0, leave it!
-                if (d > 1e-10 || d < -1e-10) // accounts for minor floating point errors... though could be problematic if the scale is EXTREMELY SMALL
-                  d3.select(this).attr('opacity', 0);
-                
-                d3.select(this).select('text').attr('opacity', 0); // Don't remove the ZERO line!!
-              }
-            });
-
-        //if Max and Min = 0 only show min, Issue #281
-        if (scale.domain()[0] == scale.domain()[1] && scale.domain()[0] == 0)
-          wrap.selectAll('g.nv-axisMaxMin')
-            .style('opacity', function(d,i) { return !i ? 1 : 0 });
-
-      }
-
-      if (showMaxMin && (axis.orient() === 'top' || axis.orient() === 'bottom')) {
-        var maxMinRange = [];
-        wrap.selectAll('g.nv-axisMaxMin')
-            .each(function(d,i) {
-              try {
-                  if (i) // i== 1, max position
-                      maxMinRange.push(scale(d) - this.getBBox().width - 4)  //assuming the max and min labels are as wide as the next tick (with an extra 4 pixels just in case)
-                  else // i==0, min position
-                      maxMinRange.push(scale(d) + this.getBBox().width + 4)
-              }catch (err) {
-                  if (i) // i== 1, max position
-                      maxMinRange.push(scale(d) - 4)  //assuming the max and min labels are as wide as the next tick (with an extra 4 pixels just in case)
-                  else // i==0, min position
-                      maxMinRange.push(scale(d) + 4)
-              }
-            });
-        g.selectAll('g') // the g's wrapping each tick
-            .each(function(d,i) {
-              if (scale(d) < maxMinRange[0] || scale(d) > maxMinRange[1]) {
-                if (d > 1e-10 || d < -1e-10) // accounts for minor floating point errors... though could be problematic if the scale is EXTREMELY SMALL
-                  d3.select(this).remove();
-                else
-                  d3.select(this).select('text').remove(); // Don't remove the ZERO line!!
-              }
-            });
-      }
-
-
-      //highlight zero line ... Maybe should not be an option and should just be in CSS?
-      if (highlightZero)
-        g.selectAll('.tick')
-          .filter(function(d) { return !parseFloat(Math.round(d.__data__*100000)/1000000) && (d.__data__ !== undefined) }) //this is because sometimes the 0 tick is a very small fraction, TODO: think of cleaner technique
-            .classed('zero', true);
-
-      //store old scales for use in transitions on update
-      scale0 = scale.copy();
-
-    });
-
-    return chart;
-  }
-
-
-  //============================================================
-  // Expose Public Variables
-  //------------------------------------------------------------
-
-  // expose chart's sub-components
-  chart.axis = axis;
-
-  d3.rebind(chart, axis, 'orient', 'tickValues', 'tickSubdivide', 'tickSize', 'tickPadding', 'tickFormat');
-  d3.rebind(chart, scale, 'domain', 'range', 'rangeBand', 'rangeBands'); //these are also accessible by chart.scale(), but added common ones directly for ease of use
-
-  chart.margin = function(_) {
-    if(!arguments.length) return margin;
-    margin.top    = typeof _.top    != 'undefined' ? _.top    : margin.top;
-    margin.right  = typeof _.right  != 'undefined' ? _.right  : margin.right;
-    margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
-    margin.left   = typeof _.left   != 'undefined' ? _.left   : margin.left;
-    return chart;
-  }
-
-  chart.width = function(_) {
-    if (!arguments.length) return width;
-    width = _;
-    return chart;
-  };
-
-  chart.ticks = function(_) {
-    if (!arguments.length) return ticks;
-    ticks = _;
-    return chart;
-  };
-
-  chart.height = function(_) {
-    if (!arguments.length) return height;
-    height = _;
-    return chart;
-  };
-
-  chart.axisLabel = function(_) {
-    if (!arguments.length) return axisLabelText;
-    axisLabelText = _;
-    return chart;
-  }
-
-  chart.showMaxMin = function(_) {
-    if (!arguments.length) return showMaxMin;
-    showMaxMin = _;
-    return chart;
-  }
-
-  chart.highlightZero = function(_) {
-    if (!arguments.length) return highlightZero;
-    highlightZero = _;
-    return chart;
-  }
-
-  chart.scale = function(_) {
-    if (!arguments.length) return scale;
-    scale = _;
-    axis.scale(scale);
-    isOrdinal = typeof scale.rangeBands === 'function';
-    d3.rebind(chart, scale, 'domain', 'range', 'rangeBand', 'rangeBands');
-    return chart;
-  }
-
-  chart.rotateYLabel = function(_) {
-    if(!arguments.length) return rotateYLabel;
-    rotateYLabel = _;
-    return chart;
-  }
-
-  chart.rotateLabels = function(_) {
-    if(!arguments.length) return rotateLabels;
-    rotateLabels = _;
-    return chart;
-  }
-
-  chart.staggerLabels = function(_) {
-    if (!arguments.length) return staggerLabels;
-    staggerLabels = _;
-    return chart;
-  };
-
-
-  //============================================================
-
-
-  return chart;
-}
-
-// Chart design based on the recommendations of Stephen Few. Implementation
-// based on the work of Clint Ivy, Jamie Love, and Jason Davies.
-// http://projects.instantcognition.com/protovis/bulletchart/
-
-nv.models.bullet = function() {
-
-  //============================================================
-  // Public Variables with Default Settings
-  //------------------------------------------------------------
-
-  var margin = {top: 0, right: 0, bottom: 0, left: 0}
-    , orient = 'left' // TODO top & bottom
-    , reverse = false
-    , ranges = function(d) { return d.ranges }
-    , markers = function(d) { return d.markers }
-    , measures = function(d) { return d.measures }
-    , forceX = [0] // List of numbers to Force into the X scale (ie. 0, or a max / min, etc.)
-    , width = 380
-    , height = 30
-    , tickFormat = null
-    , color = nv.utils.getColor(['#1f77b4'])
-    , dispatch = d3.dispatch('elementMouseover', 'elementMouseout')
-    ;
-
-  //============================================================
-
-
-  function chart(selection) {
-    selection.each(function(d, i) {
-      var availableWidth = width - margin.left - margin.right,
-          availableHeight = height - margin.top - margin.bottom,
-          container = d3.select(this);
-
-      var rangez = ranges.call(this, d, i).slice().sort(d3.descending),
-          markerz = markers.call(this, d, i).slice().sort(d3.descending),
-          measurez = measures.call(this, d, i).slice().sort(d3.descending);
-
-
-      //------------------------------------------------------------
-      // Setup Scales
-
-      // Compute the new x-scale.
-      var x1 = d3.scale.linear()
-          .domain( d3.extent(d3.merge([forceX, rangez])) )
-          .range(reverse ? [availableWidth, 0] : [0, availableWidth]);
-
-      // Retrieve the old x-scale, if this is an update.
-      var x0 = this.__chart__ || d3.scale.linear()
-          .domain([0, Infinity])
-          .range(x1.range());
-
-      // Stash the new scale.
-      this.__chart__ = x1;
-
-
-      var rangeMin = d3.min(rangez), //rangez[2]
-          rangeMax = d3.max(rangez), //rangez[0]
-          rangeAvg = rangez[1];
-
-      //------------------------------------------------------------
-
-
-      //------------------------------------------------------------
-      // Setup containers and skeleton of chart
-
-      var wrap = container.selectAll('g.nv-wrap.nv-bullet').data([d]);
-      var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-bullet');
-      var gEnter = wrapEnter.append('g');
-      var g = wrap.select('g');
-
-      gEnter.append('rect').attr('class', 'nv-range nv-rangeMax');
-      gEnter.append('rect').attr('class', 'nv-range nv-rangeAvg');
-      gEnter.append('rect').attr('class', 'nv-range nv-rangeMin');
-      gEnter.append('rect').attr('class', 'nv-measure');
-      gEnter.append('path').attr('class', 'nv-markerTriangle');
-
-      wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
-
-      //------------------------------------------------------------
-
-
-
-      var w0 = function(d) { return Math.abs(x0(d) - x0(0)) }, // TODO: could optimize by precalculating x0(0) and x1(0)
-          w1 = function(d) { return Math.abs(x1(d) - x1(0)) };
-      var xp0 = function(d) { return d < 0 ? x0(d) : x0(0) },
-          xp1 = function(d) { return d < 0 ? x1(d) : x1(0) };
-
-
-      g.select('rect.nv-rangeMax')
-          .attr('height', availableHeight)
-          .attr('width', w1(rangeMax > 0 ? rangeMax : rangeMin))
-          .attr('x', xp1(rangeMax > 0 ? rangeMax : rangeMin))
-          .datum(rangeMax > 0 ? rangeMax : rangeMin)
-          /*
-          .attr('x', rangeMin < 0 ?
-                         rangeMax > 0 ?
-                             x1(rangeMin)
-                           : x1(rangeMax)
-                       : x1(0))
-                      */
-
-      g.select('rect.nv-rangeAvg')
-          .attr('height', availableHeight)
-          .attr('width', w1(rangeAvg))
-          .attr('x', xp1(rangeAvg))
-          .datum(rangeAvg)
-          /*
-          .attr('width', rangeMax <= 0 ?
-                             x1(rangeMax) - x1(rangeAvg)
-                           : x1(rangeAvg) - x1(rangeMin))
-          .attr('x', rangeMax <= 0 ?
-                         x1(rangeAvg)
-                       : x1(rangeMin))
-                      */
-
-      g.select('rect.nv-rangeMin')
-          .attr('height', availableHeight)
-          .attr('width', w1(rangeMax))
-          .attr('x', xp1(rangeMax))
-          .attr('width', w1(rangeMax > 0 ? rangeMin : rangeMax))
-          .attr('x', xp1(rangeMax > 0 ? rangeMin : rangeMax))
-          .datum(rangeMax > 0 ? rangeMin : rangeMax)
-          /*
-          .attr('width', rangeMax <= 0 ?
-                             x1(rangeAvg) - x1(rangeMin)
-                           : x1(rangeMax) - x1(rangeAvg))
-          .attr('x', rangeMax <= 0 ?
-                         x1(rangeMin)
-                       : x1(rangeAvg))
-                      */
-
-      g.select('rect.nv-measure')
-          .style('fill', color)
-          .attr('height', availableHeight / 3)
-          .attr('y', availableHeight / 3)
-          .attr('width', measurez < 0 ?
-                             x1(0) - x1(measurez[0])
-                           : x1(measurez[0]) - x1(0))
-          .attr('x', xp1(measurez))
-          .on('mouseover', function() {
-              dispatch.elementMouseover({
-                value: measurez[0],
-                label: 'Current',
-                pos: [x1(measurez[0]), availableHeight/2]
-              })
-          })
-          .on('mouseout', function() {
-              dispatch.elementMouseout({
-                value: measurez[0],
-                label: 'Current'
-              })
-          })
-
-      var h3 =  availableHeight / 6;
-      if (markerz[0]) {
-        g.selectAll('path.nv-markerTriangle')
-            .attr('transform', function(d) { return 'translate(' + x1(markerz[0]) + ',' + (availableHeight / 2) + ')' })
-            .attr('d', 'M0,' + h3 + 'L' + h3 + ',' + (-h3) + ' ' + (-h3) + ',' + (-h3) + 'Z')
-            .on('mouseover', function() {
-              dispatch.elementMouseover({
-                value: markerz[0],
-                label: 'Previous',
-                pos: [x1(markerz[0]), availableHeight/2]
-              })
-            })
-            .on('mouseout', function() {
-              dispatch.elementMouseout({
-                value: markerz[0],
-                label: 'Previous'
-              })
-            });
-      } else {
-        g.selectAll('path.nv-markerTriangle').remove();
-      }
-
-
-      wrap.selectAll('.nv-range')
-          .on('mouseover', function(d,i) {
-            var label = !i ? "Maximum" : i == 1 ? "Mean" : "Minimum";
-
-            dispatch.elementMouseover({
-              value: d,
-              label: label,
-              pos: [x1(d), availableHeight/2]
-            })
-          })
-          .on('mouseout', function(d,i) {
-            var label = !i ? "Maximum" : i == 1 ? "Mean" : "Minimum";
-
-            dispatch.elementMouseout({
-              value: d,
-              label: label
-            })
-          })
-
-/* // THIS IS THE PREVIOUS BULLET IMPLEMENTATION, WILL REMOVE SHORTLY
-      // Update the range rects.
-      var range = g.selectAll('rect.nv-range')
-          .data(rangez);
-
-      range.enter().append('rect')
-          .attr('class', function(d, i) { return 'nv-range nv-s' + i; })
-          .attr('width', w0)
-          .attr('height', availableHeight)
-          .attr('x', reverse ? x0 : 0)
-          .on('mouseover', function(d,i) { 
-              dispatch.elementMouseover({
-                value: d,
-                label: (i <= 0) ? 'Maximum' : (i > 1) ? 'Minimum' : 'Mean', //TODO: make these labels a variable
-                pos: [x1(d), availableHeight/2]
-              })
-          })
-          .on('mouseout', function(d,i) { 
-              dispatch.elementMouseout({
-                value: d,
-                label: (i <= 0) ? 'Minimum' : (i >=1) ? 'Maximum' : 'Mean' //TODO: make these labels a variable
-              })
-          })
-
-      d3.transition(range)
-          .attr('x', reverse ? x1 : 0)
-          .attr('width', w1)
-          .attr('height', availableHeight);
-
-
-      // Update the measure rects.
-      var measure = g.selectAll('rect.nv-measure')
-          .data(measurez);
-
-      measure.enter().append('rect')
-          .attr('class', function(d, i) { return 'nv-measure nv-s' + i; })
-          .style('fill', function(d,i) { return color(d,i ) })
-          .attr('width', w0)
-          .attr('height', availableHeight / 3)
-          .attr('x', reverse ? x0 : 0)
-          .attr('y', availableHeight / 3)
-          .on('mouseover', function(d) { 
-              dispatch.elementMouseover({
-                value: d,
-                label: 'Current', //TODO: make these labels a variable
-                pos: [x1(d), availableHeight/2]
-              })
-          })
-          .on('mouseout', function(d) { 
-              dispatch.elementMouseout({
-                value: d,
-                label: 'Current' //TODO: make these labels a variable
-              })
-          })
-
-      d3.transition(measure)
-          .attr('width', w1)
-          .attr('height', availableHeight / 3)
-          .attr('x', reverse ? x1 : 0)
-          .attr('y', availableHeight / 3);
-
-
-
-      // Update the marker lines.
-      var marker = g.selectAll('path.nv-markerTriangle')
-          .data(markerz);
-
-      var h3 =  availableHeight / 6;
-      marker.enter().append('path')
-          .attr('class', 'nv-markerTriangle')
-          .attr('transform', function(d) { return 'translate(' + x0(d) + ',' + (availableHeight / 2) + ')' })
-          .attr('d', 'M0,' + h3 + 'L' + h3 + ',' + (-h3) + ' ' + (-h3) + ',' + (-h3) + 'Z')
-          .on('mouseover', function(d,i) {
-              dispatch.elementMouseover({
-                value: d,
-                label: 'Previous',
-                pos: [x1(d), availableHeight/2]
-              })
-          })
-          .on('mouseout', function(d,i) {
-              dispatch.elementMouseout({
-                value: d,
-                label: 'Previous'
-              })
-          });
-
-      d3.transition(marker)
-          .attr('transform', function(d) { return 'translate(' + (x1(d) - x1(0)) + ',' + (availableHeight / 2) + ')' });
-
-      marker.exit().remove();
-*/
-
-    });
-
-    // d3.timer.flush();  // Not needed?
-
-    return chart;
-  }
-
-
-  //============================================================
-  // Expose Public Variables
-  //------------------------------------------------------------
-
-  chart.dispatch = dispatch;
-
-  // left, right, top, bottom
-  chart.orient = function(_) {
-    if (!arguments.length) return orient;
-    orient = _;
-    reverse = orient == 'right' || orient == 'bottom';
-    return chart;
-  };
-
-  // ranges (bad, satisfactory, good)
-  chart.ranges = function(_) {
-    if (!arguments.length) return ranges;
-    ranges = _;
-    return chart;
-  };
-
-  // markers (previous, goal)
-  chart.markers = function(_) {
-    if (!arguments.length) return markers;
-    markers = _;
-    return chart;
-  };
-
-  // measures (actual, forecast)
-  chart.measures = function(_) {
-    if (!arguments.length) return measures;
-    measures = _;
-    return chart;
-  };
-
-  chart.forceX = function(_) {
-    if (!arguments.length) return forceX;
-    forceX = _;
-    return chart;
-  };
-
-  chart.width = function(_) {
-    if (!arguments.length) return width;
-    width = _;
-    return chart;
-  };
-
-  chart.height = function(_) {
-    if (!arguments.length) return height;
-    height = _;
-    return chart;
-  };
-
-  chart.margin = function(_) {
-    if (!arguments.length) return margin;
-    margin.top    = typeof _.top    != 'undefined' ? _.top    : margin.top;
-    margin.right  = typeof _.right  != 'undefined' ? _.right  : margin.right;
-    margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
-    margin.left   = typeof _.left   != 'undefined' ? _.left   : margin.left;
-    return chart;
-  };
-
-  chart.tickFormat = function(_) {
-    if (!arguments.length) return tickFormat;
-    tickFormat = _;
-    return chart;
-  };
-
-  chart.color = function(_) {
-    if (!arguments.length) return color;
-    color = nv.utils.getColor(_);
-    return chart;
-  };
-
-  //============================================================
-
-
-  return chart;
-};
-
-
-
-// Chart design based on the recommendations of Stephen Few. Implementation
-// based on the work of Clint Ivy, Jamie Love, and Jason Davies.
-// http://projects.instantcognition.com/protovis/bulletchart/
-nv.models.bulletChart = function() {
-
-  //============================================================
-  // Public Variables with Default Settings
-  //------------------------------------------------------------
-
-  var bullet = nv.models.bullet()
-    ;
-
-  var orient = 'left' // TODO top & bottom
-    , reverse = false
-    , margin = {top: 5, right: 40, bottom: 20, left: 120}
-    , ranges = function(d) { return d.ranges }
-    , markers = function(d) { return d.markers }
-    , measures = function(d) { return d.measures }
-    , width = null
-    , height = 55
-    , tickFormat = null
-    , tooltips = true
-    , tooltip = function(key, x, y, e, graph) {
-        return '<h3>' + x + '</h3>' +
-               '<p>' + y + '</p>'
-      }
-    , noData = 'No Data Available.'
-    , dispatch = d3.dispatch('tooltipShow', 'tooltipHide')
-    ;
-
-  //============================================================
-
-
-  //============================================================
-  // Private Variables
-  //------------------------------------------------------------
-
-  var showTooltip = function(e, offsetElement) {
-    var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ) + margin.left,
-        top = e.pos[1] + ( offsetElement.offsetTop || 0) + margin.top,
-        content = tooltip(e.key, e.label, e.value, e, chart);
-
-    nv.tooltip.show([left, top], content, e.value < 0 ? 'e' : 'w', null, offsetElement);
-  };
-
-  //============================================================
-
-
-  function chart(selection) {
-    selection.each(function(d, i) {
-      var container = d3.select(this);
-
-      var availableWidth = (width  || parseInt(container.style('width')) || 960)
-                             - margin.left - margin.right,
-          availableHeight = height - margin.top - margin.bottom,
-          that = this;
-
-
-      chart.update = function() { chart(selection) };
-      chart.container = this;
-
-      //------------------------------------------------------------
-      // Display No Data message if there's nothing to show.
-
-      if (!d || !ranges.call(this, d, i)) {
-        var noDataText = container.selectAll('.nv-noData').data([noData]);
-
-        noDataText.enter().append('text')
-          .attr('class', 'nvd3 nv-noData')
-          .attr('dy', '-.7em')
-          .style('text-anchor', 'middle');
-
-        noDataText
-          .attr('x', margin.left + availableWidth / 2)
-          .attr('y', 18 + margin.top + availableHeight / 2)
-          .text(function(d) { return d });
-
-        return chart;
-      } else {
-        container.selectAll('.nv-noData').remove();
-      }
-
-      //------------------------------------------------------------
-
-
-
-      var rangez = ranges.call(this, d, i).slice().sort(d3.descending),
-          markerz = markers.call(this, d, i).slice().sort(d3.descending),
-          measurez = measures.call(this, d, i).slice().sort(d3.descending);
-
-
-      //------------------------------------------------------------
-      // Setup containers and skeleton of chart
-
-      var wrap = container.selectAll('g.nv-wrap.nv-bulletChart').data([d]);
-      var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-bulletChart');
-      var gEnter = wrapEnter.append('g');
-      var g = wrap.select('g');
-
-      gEnter.append('g').attr('class', 'nv-bulletWrap');
-      gEnter.append('g').attr('class', 'nv-titles');
-
-      wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
-
-      //------------------------------------------------------------
-
-
-      // Compute the new x-scale.
-      var x1 = d3.scale.linear()
-          .domain([0, Math.max(rangez[0], markerz[0], measurez[0])])  // TODO: need to allow forceX and forceY, and xDomain, yDomain
-          .range(reverse ? [availableWidth, 0] : [0, availableWidth]);
-
-      // Retrieve the old x-scale, if this is an update.
-      var x0 = this.__chart__ || d3.scale.linear()
-          .domain([0, Infinity])
-          .range(x1.range());
-
-      // Stash the new scale.
-      this.__chart__ = x1;
-
-      /*
-      // Derive width-scales from the x-scales.
-      var w0 = bulletWidth(x0),
-          w1 = bulletWidth(x1);
-
-      function bulletWidth(x) {
-        var x0 = x(0);
-        return function(d) {
-          return Math.abs(x(d) - x(0));
-        };
-      }
-
-      function bulletTranslate(x) {
-        return function(d) {
-          return 'translate(' + x(d) + ',0)';
-        };
-      }
-      */
-
-      var w0 = function(d) { return Math.abs(x0(d) - x0(0)) }, // TODO: could optimize by precalculating x0(0) and x1(0)
-          w1 = function(d) { return Math.abs(x1(d) - x1(0)) };
-
-
-      var title = gEnter.select('.nv-titles').append('g')
-          .attr('text-anchor', 'end')
-          .attr('transform', 'translate(-6,' + (height - margin.top - margin.bottom) / 2 + ')');
-      title.append('text')
-          .attr('class', 'nv-title')
-          .text(function(d) { return d.title; });
-
-      title.append('text')
-          .attr('class', 'nv-subtitle')
-          .attr('dy', '1em')
-          .text(function(d) { return d.subtitle; });
-
-
-
-      bullet
-        .width(availableWidth)
-        .height(availableHeight)
-
-      var bulletWrap = g.select('.nv-bulletWrap');
-
-      d3.transition(bulletWrap).call(bullet);
-
-
-
-      // Compute the tick format.
-      var format = tickFormat || x1.tickFormat( availableWidth / 100 );
-
-      // Update the tick groups.
-      var tick = g.selectAll('g.nv-tick')
-          .data(x1.ticks( availableWidth / 50 ), function(d) {
-            return this.textContent || format(d);
-          });
-
-      // Initialize the ticks with the old scale, x0.
-      var tickEnter = tick.enter().append('g')
-          .attr('class', 'nv-tick')
-          .attr('transform', function(d) { return 'translate(' + x0(d) + ',0)' })
-          .style('opacity', 1e-6);
-
-      tickEnter.append('line')
-          .attr('y1', availableHeight)
-          .attr('y2', availableHeight * 7 / 6);
-
-      tickEnter.append('text')
-          .attr('text-anchor', 'middle')
-          .attr('dy', '1em')
-          .attr('y', availableHeight * 7 / 6)
-          .text(format);
-
-
-      // Transition the updating ticks to the new scale, x1.
-      var tickUpdate = d3.transition(tick)
-          .attr('transform', function(d) { return 'translate(' + x1(d) + ',0)' })
-          .style('opacity', 1);
-
-      tickUpdate.select('line')
-          .attr('y1', availableHeight)
-          .attr('y2', availableHeight * 7 / 6);
-
-      tickUpdate.select('text')
-          .attr('y', availableHeight * 7 / 6);
-
-      // Transition the exiting ticks to the new scale, x1.
-      d3.transition(tick.exit())
-          .attr('transform', function(d) { return 'translate(' + x1(d) + ',0)' })
-          .style('opacity', 1e-6)
-          .remove();
-
-
-      //============================================================
-      // Event Handling/Dispatching (in chart's scope)
-      //------------------------------------------------------------
-
-      dispatch.on('tooltipShow', function(e) {
-        e.key = d.title;
-        if (tooltips) showTooltip(e, that.parentNode);
-      });
-
-      //============================================================
-
-    });
-
-    d3.timer.flush();
-
-    return chart;
-  }
-
-
-  //============================================================
-  // Event Handling/Dispatching (out of chart's scope)
-  //------------------------------------------------------------
-
-  bullet.dispatch.on('elementMouseover.tooltip', function(e) {
-    dispatch.tooltipShow(e);
-  });
-
-  bullet.dispatch.on('elementMouseout.tooltip', function(e) {
-    dispatch.tooltipHide(e);
-  });
-
-  dispatch.on('tooltipHide', function() {
-    if (tooltips) nv.tooltip.cleanup();
-  });
-
-  //============================================================
-
-
-  //============================================================
-  // Expose Public Variables
-  //------------------------------------------------------------
-
-  chart.dispatch = dispatch;
-  chart.bullet = bullet;
-
-  d3.rebind(chart, bullet, 'color');
-
-  // left, right, top, bottom
-  chart.orient = function(x) {
-    if (!arguments.length) return orient;
-    orient = x;
-    reverse = orient == 'right' || orient == 'bottom';
-    return chart;
-  };
-
-  // ranges (bad, satisfactory, good)
-  chart.ranges = function(x) {
-    if (!arguments.length) return ranges;
-    ranges = x;
-    return chart;
-  };
-
-  // markers (previous, goal)
-  chart.markers = function(x) {
-    if (!arguments.length) return markers;
-    markers = x;
-    return chart;
-  };
-
-  // measures (actual, forecast)
-  chart.measures = function(x) {
-    if (!arguments.length) return measures;
-    measures = x;
-    return chart;
-  };
-
-  chart.width = function(x) {
-    if (!arguments.length) return width;
-    width = x;
-    return chart;
-  };
-
-  chart.height = function(x) {
-    if (!arguments.length) return height;
-    height = x;
-    return chart;
-  };
-
-  chart.margin = function(_) {
-    if (!arguments.length) return margin;
-    margin.top    = typeof _.top    != 'undefined' ? _.top    : margin.top;
-    margin.right  = typeof _.right  != 'undefined' ? _.right  : margin.right;
-    margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
-    margin.left   = typeof _.left   != 'undefined' ? _.left   : margin.left;
-    return chart;
-  };
-
-  chart.tickFormat = function(x) {
-    if (!arguments.length) return tickFormat;
-    tickFormat = x;
-    return chart;
-  };
-
-  chart.tooltips = function(_) {
-    if (!arguments.length) return tooltips;
-    tooltips = _;
-    return chart;
-  };
-
-  chart.tooltipContent = function(_) {
-    if (!arguments.length) return tooltip;
-    tooltip = _;
-    return chart;
-  };
-
-  chart.noData = function(_) {
-    if (!arguments.length) return noData;
-    noData = _;
-    return chart;
-  };
-
-  //============================================================
-
-
-  return chart;
-};
-
-
-
-nv.models.cumulativeLineChart = function() {
-
-  //============================================================
-  // Public Variables with Default Settings
-  //------------------------------------------------------------
-
-  var lines = nv.models.line()
-    , xAxis = nv.models.axis()
-    , yAxis = nv.models.axis()
-    , legend = nv.models.legend()
-    , controls = nv.models.legend()
-    ;
-
-  var margin = {top: 30, right: 30, bottom: 50, left: 60}
-    , color = nv.utils.defaultColor()
-    , width = null
-    , height = null
-    , showLegend = true
-    , tooltips = true
-    , showControls = true
-    , rescaleY = true
-    , tooltip = function(key, x, y, e, graph) {
-        return '<h3>' + key + '</h3>' +
-               '<p>' +  y + ' at ' + x + '</p>'
-      }
-    , x //can be accessed via chart.xScale()
-    , y //can be accessed via chart.yScale()
-    , id = lines.id()
-    , state = { index: 0, rescaleY: rescaleY }
-    , defaultState = null
-    , noData = 'No Data Available.'
-    , average = function(d) { return d.average }
-    , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState')
-    ;
-
-  xAxis
-    .orient('bottom')
-    .tickPadding(7)
-    ;
-  yAxis
-    .orient('left')
-    ;
-
-  //============================================================
-
-
-  //============================================================
-  // Private Variables
-  //------------------------------------------------------------
-
-   var dx = d3.scale.linear()
-     , index = {i: 0, x: 0}
-     ;
-
-  var showTooltip = function(e, offsetElement) {
-    var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ),
-        top = e.pos[1] + ( offsetElement.offsetTop || 0),
-        x = xAxis.tickFormat()(lines.x()(e.point, e.pointIndex)),
-        y = yAxis.tickFormat()(lines.y()(e.point, e.pointIndex)),
-        content = tooltip(e.series.key, x, y, e, chart);
-
-    nv.tooltip.show([left, top], content, null, null, offsetElement);
-  };
-
-/*
-  //Moved to see if we can get better behavior to fix issue #315
-  var indexDrag = d3.behavior.drag()
-                    .on('dragstart', dragStart)
-                    .on('drag', dragMove)
-                    .on('dragend', dragEnd);
-
-  function dragStart(d,i) {
-    d3.select(chart.container)
-        .style('cursor', 'ew-resize');
-  }
-
-  function dragMove(d,i) {
-    d.x += d3.event.dx;
-    d.i = Math.round(dx.invert(d.x));
-
-    d3.select(this).attr('transform', 'translate(' + dx(d.i) + ',0)');
-    chart.update();
-  }
-
-  function dragEnd(d,i) {
-    d3.select(chart.container)
-        .style('cursor', 'auto');
-    chart.update();
-  }
-*/
-
-  //============================================================
-
-
-  function chart(selection) {
-    selection.each(function(data) {
-      var container = d3.select(this).classed('nv-chart-' + id, true),
-          that = this;
-
-      var availableWidth = (width  || parseInt(container.style('width')) || 960)
-                             - margin.left - margin.right,
-          availableHeight = (height || parseInt(container.style('height')) || 400)
-                             - margin.top - margin.bottom;
-
-
-      chart.update = function() { container.transition().call(chart) };
-      chart.container = this;
-
-      //set state.disabled
-      state.disabled = data.map(function(d) { return !!d.disabled });
-
-      if (!defaultState) {
-        var key;
-        defaultState = {};
-        for (key in state) {
-          if (state[key] instanceof Array)
-            defaultState[key] = state[key].slice(0);
-          else
-            defaultState[key] = state[key];
-        }
-      }
-
-      var indexDrag = d3.behavior.drag()
-                        .on('dragstart', dragStart)
-                        .on('drag', dragMove)
-                        .on('dragend', dragEnd);
-
-
-      function dragStart(d,i) {
-        d3.select(chart.container)
-            .style('cursor', 'ew-resize');
-      }
-
-      function dragMove(d,i) {
-        index.x = d3.event.x;
-        index.i = Math.round(dx.invert(index.x));
-        updateZero();
-      }
-
-      function dragEnd(d,i) {
-        d3.select(chart.container)
-            .style('cursor', 'auto');
-
-        // update state and send stateChange with new index
-        state.index = index.i;
-        dispatch.stateChange(state);
-      }
-
-
-
-
-      //------------------------------------------------------------
-      // Display No Data message if there's nothing to show.
-
-      if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) {
-        var noDataText = container.selectAll('.nv-noData').data([noData]);
-
-        noDataText.enter().append('text')
-          .attr('class', 'nvd3 nv-noData')
-          .attr('dy', '-.7em')
-          .style('text-anchor', 'middle');
-
-        noDataText
-          .attr('x', margin.left + availableWidth / 2)
-          .attr('y', margin.top + availableHeight / 2)
-          .text(function(d) { return d });
-
-        return chart;
-      } else {
-        container.selectAll('.nv-noData').remove();
-      }
-
-      //------------------------------------------------------------
-
-
-      //------------------------------------------------------------
-      // Setup Scales
-
-      x = lines.xScale();
-      y = lines.yScale();
-
-
-      if (!rescaleY) {
-        var seriesDomains = data
-          .filter(function(series) { return !series.disabled })
-          .map(function(series,i) {
-            var initialDomain = d3.extent(series.values, lines.y());
-
-            //account for series being disabled when losing 95% or more
-            if (initialDomain[0] < -.95) initialDomain[0] = -.95;
-
-            return [
-              (initialDomain[0] - initialDomain[1]) / (1 + initialDomain[1]),
-              (initialDomain[1] - initialDomain[0]) / (1 + initialDomain[0])
-            ];
-          });
-
-        var completeDomain = [
-          d3.min(seriesDomains, function(d) { return d[0] }),
-          d3.max(seriesDomains, function(d) { return d[1] })
-        ]
-
-        lines.yDomain(completeDomain);
-      } else {
-        lines.yDomain(null);
-      }
-
-
-      dx  .domain([0, data[0].values.length - 1]) //Assumes all series have same length
-          .range([0, availableWidth])
-          .clamp(true);
-
-      //------------------------------------------------------------
-
-
-      var data = indexify(index.i, data);
-
-
-      //------------------------------------------------------------
-      // Setup containers and skeleton of chart
-
-      var wrap = container.selectAll('g.nv-wrap.nv-cumulativeLine').data([data]);
-      var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-cumulativeLine').append('g');
-      var g = wrap.select('g');
-
-      gEnter.append('g').attr('class', 'nv-x nv-axis');
-      gEnter.append('g').attr('class', 'nv-y nv-axis');
-      gEnter.append('g').attr('class', 'nv-background');
-      gEnter.append('g').attr('class', 'nv-linesWrap');
-      gEnter.append('g').attr('class', 'nv-avgLinesWrap');
-      gEnter.append('g').attr('class', 'nv-legendWrap');
-      gEnter.append('g').attr('class', 'nv-controlsWrap');
-
-      //------------------------------------------------------------
-
-
-      //------------------------------------------------------------
-      // Legend
-
-      if (showLegend) {
-        legend.width(availableWidth);
-
-        g.select('.nv-legendWrap')
-            .datum(data)
-            .call(legend);
-
-        if ( margin.top != legend.height()) {
-          margin.top = legend.height() + legend.legendBelowPadding();// added legend.legendBelowPadding to allow for more spacing
-          availableHeight = (height || parseInt(container.style('height')) || 400)
-                             - margin.top - margin.bottom;
-        }
-
-        g.select('.nv-legendWrap')
-            .attr('transform', 'translate(0,' + (-margin.top) +')')
-      }
-
-      //------------------------------------------------------------
-
-
-      //------------------------------------------------------------
-      // Controls
-
-      if (showControls) {
-        var controlsData = [
-          { key: 'Re-scale y-axis', disabled: !rescaleY }
-        ];
-
-        controls.width(140).color(['#444', '#444', '#444']);
-        g.select('.nv-controlsWrap')
-            .datum(controlsData)
-            .attr('transform', 'translate(0,' + (-margin.top) +')')
-            .call(controls);
-      }
-
-      //------------------------------------------------------------
-
-
-      wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
-
-
-      // Show error if series goes below 100%
-      var tempDisabled = data.filter(function(d) { return d.tempDisabled });
-
-      wrap.select('.tempDisabled').remove(); //clean-up and prevent duplicates
-      if (tempDisabled.length) {
-        wrap.append('text').attr('class', 'tempDisabled')
-            .attr('x', availableWidth / 2)
-            .attr('y', '-.71em')
-            .style('text-anchor', 'end')
-            .text(tempDisabled.map(function(d) { return d.key }).join(', ') + ' values cannot be calculated for this time period.');
-      }
-
-      //------------------------------------------------------------
-      // Main Chart Component(s)
-
-      gEnter.select('.nv-background')
-        .append('rect');
-
-      g.select('.nv-background rect')
-          .attr('width', availableWidth)
-          .attr('height', availableHeight);
-
-      lines
-        //.x(function(d) { return d.x })
-        .y(function(d) { return d.display.y })
-        .width(availableWidth)
-        .height(availableHeight)
-        .color(data.map(function(d,i) {
-          return d.color || color(d, i);
-        }).filter(function(d,i) { return !data[i].disabled && !data[i].tempDisabled; }));
-
-
-
-      var linesWrap = g.select('.nv-linesWrap')
-          .datum(data.filter(function(d) { return  !d.disabled && !d.tempDisabled }));
-
-      //d3.transition(linesWrap).call(lines);
-      linesWrap.call(lines);
-
-      /*Handle average lines [AN-612] ----------------------------*/
-
-      //Store a series index number in the data array.
-      data.forEach(function(d,i) {
-            d.seriesIndex = i;
-      });
-
-      var avgLineData = data.filter(function(d) {
-          return !d.disabled && !!average(d);
-      });
-
-      var avgLines = g.select(".nv-avgLinesWrap").selectAll("line")
-              .data(avgLineData, function(d) { return d.key; });
-
-      avgLines.enter()
-              .append('line')
-              .style('stroke-width',2)
-              .style('stroke-dasharray','10,10')
-              .style('stroke',function (d,i) {
-                  return lines.color()(d,d.seriesIndex);
-              })
-              .attr('x1',0)
-              .attr('x2',availableWidth)
-              .attr('y1', function(d) { return y(average(d)); })
-              .attr('y2', function(d) { return y(average(d)); });
-
-      avgLines
-              .attr('x1',0)
-              .attr('x2',availableWidth)
-              .attr('y1', function(d) { return y(average(d)); })
-              .attr('y2', function(d) { return y(average(d)); });
-
-      avgLines.exit().remove();
-
-      //Create index line -----------------------------------------
-
-      var indexLine = linesWrap.selectAll('.nv-indexLine')
-          .data([index]);
-      indexLine.enter().append('rect').attr('class', 'nv-indexLine')
-          .attr('width', 3)
-          .attr('x', -2)
-          .attr('fill', 'red')
-          .attr('fill-opacity', .5)
-          .call(indexDrag)
-
-      indexLine
-          .attr('transform', function(d) { return 'translate(' + dx(d.i) + ',0)' })
-          .attr('height', availableHeight)
-
-      //------------------------------------------------------------
-
-
-      //------------------------------------------------------------
-      // Setup Axes
-
-      xAxis
-        .scale(x)
-        //Suggest how many ticks based on the chart width and D3 should listen (70 is the optimal number for MM/DD/YY dates)
-        .ticks( Math.min(data[0].values.length,availableWidth/70) )
-        .tickSize(-availableHeight, 0);
-
-      g.select('.nv-x.nv-axis')
-          .attr('transform', 'translate(0,' + y.range()[0] + ')');
-      d3.transition(g.select('.nv-x.nv-axis'))
-          .call(xAxis);
-
-
-      yAxis
-        .scale(y)
-        .ticks( availableHeight / 36 )
-        .tickSize( -availableWidth, 0);
-
-      d3.transition(g.select('.nv-y.nv-axis'))
-          .call(yAxis);
-
-      //------------------------------------------------------------
-
-
-      //============================================================
-      // Event Handling/Dispatching (in chart's scope)
-      //------------------------------------------------------------
-
-
-      function updateZero() {
-        indexLine
-          .data([index]);
-
-        container.call(chart);
-      }
-
-      g.select('.nv-background rect')
-          .on('click', function() {
-            index.x = d3.mouse(this)[0];
-            index.i = Math.round(dx.invert(index.x));
-
-            // update state and send stateChange with new index
-            state.index = index.i;
-            dispatch.stateChange(state);
-
-            updateZero();
-          });
-
-      lines.dispatch.on('elementClick', function(e) {
-        index.i = e.pointIndex;
-        index.x = dx(index.i);
-
-        // update state and send stateChange with new index
-        state.index = index.i;
-        dispatch.stateChange(state);
-
-        updateZero();
-      });
-
-      controls.dispatch.on('legendClick', function(d,i) { 
-        d.disabled = !d.disabled;
-        rescaleY = !d.disabled;
-
-        state.rescaleY = rescaleY;
-        dispatch.stateChange(state);
-
-        //selection.transition().call(chart);
-        chart.update();
-      });
-
-
-      legend.dispatch.on('legendClick', function(d,i) { 
-        d.disabled = !d.disabled;
-
-        if (!data.filter(function(d) { return !d.disabled }).length) {
-          data.map(function(d) {
-            d.disabled = false;
-            wrap.selectAll('.nv-series').classed('disabled', false);
-            return d;
-          });
-        }
-
-        state.disabled = data.map(function(d) { return !!d.disabled });
-        dispatch.stateChange(state);
-
-        //selection.transition().call(chart);
-        chart.update();
-      });
-
-      legend.dispatch.on('legendDblclick', function(d) {
-          //Double clicking should always enable current series, and disabled all others.
-          data.forEach(function(d) {
-             d.disabled = true;
-          });
-          d.disabled = false;  
-
-          state.disabled = data.map(function(d) { return !!d.disabled });
-          dispatch.stateChange(state);
-          chart.update();
-      });
-
-
-/*
-      //
-      legend.dispatch.on('legendMouseover', function(d, i) {
-        d.hover = true;
-        selection.transition().call(chart)
-      });
-
-      legend.dispatch.on('legendMouseout', function(d, i) {
-        d.hover = false;
-        selection.transition().call(chart)
-      });
-*/
-
-      dispatch.on('tooltipShow', function(e) {
-        if (tooltips) showTooltip(e, that.parentNode);
-      });
-
-
-      // Update chart from a state object passed to event handler
-      dispatch.on('changeState', function(e) {
-
-        if (typeof e.disabled !== 'undefined') {
-          data.forEach(function(series,i) {
-            series.disabled = e.disabled[i];
-          });
-
-          state.disabled = e.disabled;
-        }
-
-
-        if (typeof e.index !== 'undefined') {
-          index.i = e.index;
-          index.x = dx(index.i);
-
-          state.index = e.index;
-
-          indexLine
-            .data([index]);
-        }
-
-
-        if (typeof e.rescaleY !== 'undefined') {
-          rescaleY = e.rescaleY;
-        }
-
-        chart.update();
-      });
-
-      //============================================================
-
-    });
-
-    return chart;
-  }
-
-
-  //============================================================
-  // Event Handling/Dispatching (out of chart's scope)
-  //------------------------------------------------------------
-
-  lines.dispatch.on('elementMouseover.tooltip', function(e) {
-    e.pos = [e.pos[0] +  margin.left, e.pos[1] + margin.top];
-    dispatch.tooltipShow(e);
-  });
-
-  lines.dispatch.on('elementMouseout.tooltip', function(e) {
-    dispatch.tooltipHide(e);
-  });
-
-  dispatch.on('tooltipHide', function() {
-    if (tooltips) nv.tooltip.cleanup();
-  });
-
-  //============================================================
-
-
-  //============================================================
-  // Expose Public Variables
-  //------------------------------------------------------------
-
-  // expose chart's sub-components
-  chart.dispatch = dispatch;
-  chart.lines = lines;
-  chart.legend = legend;
-  chart.xAxis = xAxis;
-  chart.yAxis = yAxis;
-
-  d3.rebind(chart, lines, 'defined', 'isArea', 'x', 'y', 'size', 'xDomain', 'yDomain', 'forceX', 'forceY', 'interactive', 'clipEdge', 'clipVoronoi', 'id');
-
-  chart.margin = function(_) {
-    if (!arguments.length) return margin;
-    margin.top    = typeof _.top    != 'undefined' ? _.top    : margin.top;
-    margin.right  = typeof _.right  != 'undefined' ? _.right  : margin.right;
-    margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
-    margin.left   = typeof _.left   != 'undefined' ? _.left   : margin.left;
-    return chart;
-  };
-
-  chart.width = function(_) {
-    if (!arguments.length) return width;
-    width = _;
-    return chart;
-  };
-
-  chart.height = function(_) {
-    if (!arguments.length) return height;
-    height = _;
-    return chart;
-  };
-
-  chart.color = function(_) {
-    if (!arguments.length) return color;
-    color = nv.utils.getColor(_);
-    legend.color(color);
-    return chart;
-  };
-
-  chart.rescaleY = function(_) {
-    if (!arguments.length) return rescaleY;
-    rescaleY = _
-    return rescaleY;
-  };
-
-  chart.showControls = function(_) {
-    if (!arguments.length) return showControls;
-    showControls = _;
-    return chart;
-  };
-
-  chart.showLegend = function(_) {
-    if (!arguments.length) return showLegend;
-    showLegend = _;
-    return chart;
-  };
-
-  chart.tooltips = function(_) {
-    if (!arguments.length) return tooltips;
-    tooltips = _;
-    return chart;
-  };
-
-  chart.tooltipContent = function(_) {
-    if (!arguments.length) return tooltip;
-    tooltip = _;
-    return chart;
-  };
-
-  chart.state = function(_) {
-    if (!arguments.length) return state;
-    state = _;
-    return chart;
-  };
-
-  chart.defaultState = function(_) {
-    if (!arguments.length) return defaultState;
-    defaultState = _;
-    return chart;
-  };
-
-  chart.noData = function(_) {
-    if (!arguments.length) return noData;
-    noData = _;
-    return chart;
-  };
-
-  chart.average = function(_) {
-     if(!arguments.length) return average;
-     average = _;
-     return chart;
-  };
-
-  //============================================================
-
-
-  //============================================================
-  // Functions
-  //------------------------------------------------------------
-
-  /* Normalize the data according to an index point. */
-  function indexify(idx, data) {
-    return data.map(function(line, i) {
-      if (!line.values) {
-         return line;
-      }
-      var v = lines.y()(line.values[idx], idx);
-
-      //TODO: implement check below, and disable series if series loses 100% or more cause divide by 0 issue
-      if (v < -.95) {
-        //if a series loses more than 100%, calculations fail.. anything close can cause major distortion (but is mathematically correct till it hits 100)
-        line.tempDisabled = true;
-        return line;
-      }
-
-      line.tempDisabled = false;
-
-      line.values = line.values.map(function(point, pointIndex) {
-        point.display = {'y': (lines.y()(point, pointIndex) - v) / (1 + v) };
-        return point;
-      })
-
-      return line;
-    })
-  }
-
-  //============================================================
-
-
-  return chart;
-}
-//TODO: consider deprecating by adding necessary features to multiBar model
-nv.models.discreteBar = function() {
-
-  //============================================================
-  // Public Variables with Default Settings
-  //------------------------------------------------------------
-
-  var margin = {top: 0, right: 0, bottom: 0, left: 0}
-    , width = 960
-    , height = 500
-    , id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one
-    , x = d3.scale.ordinal()
-    , y = d3.scale.linear()
-    , getX = function(d) { return d.x }
-    , getY = function(d) { return d.y }
-    , forceY = [0] // 0 is forced by default.. this makes sense for the majority of bar graphs... user can always do chart.forceY([]) to remove
-    , color = nv.utils.defaultColor()
-    , showValues = false
-    , valueFormat = d3.format(',.2f')
-    , xDomain
-    , yDomain
-    , dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout')
-    , rectClass = 'discreteBar'
-    ;
-
-  //============================================================
-
-
-  //============================================================
-  // Private Variables
-  //------------------------------------------------------------
-
-  var x0, y0;
-
-  //============================================================
-
-
-  function chart(selection) {
-    selection.each(function(data) {
-      var availableWidth = width - margin.left - margin.right,
-          availableHeight = height - margin.top - margin.bottom,
-          container = d3.select(this);
-
-
-      //add series index to each data point for reference
-      data = data.map(function(series, i) {
-        series.values = series.values.map(function(point) {
-          point.series = i;
-          return point;
-        });
-        return series;
-      });
-
-
-      //------------------------------------------------------------
-      // Setup Scales
-
-      // remap and flatten the data for use in calculating the scales' domains
-      var seriesData = (xDomain && yDomain) ? [] : // if we know xDomain and yDomain, no need to calculate
-            data.map(function(d) {
-              return d.values.map(function(d,i) {
-                return { x: getX(d,i), y: getY(d,i), y0: d.y0 }
-              })
-            });
-
-      x   .domain(xDomain || d3.merge(seriesData).map(function(d) { return d.x }))
-          .rangeBands([0, availableWidth], .1);
-
-      y   .domain(yDomain || d3.extent(d3.merge(seriesData).map(function(d) { return d.y }).concat(forceY)));
-
-
-      // If showValues, pad the Y axis range to account for label height
-      if (showValues) y.range([availableHeight - (y.domain()[0] < 0 ? 12 : 0), y.domain()[1] > 0 ? 12 : 0]);
-      else y.range([availableHeight, 0]);
-
-      //store old scales if they exist
-      x0 = x0 || x;
-      y0 = y0 || y.copy().range([y(0),y(0)]);
-
-      //------------------------------------------------------------
-
-
-      //------------------------------------------------------------
-      // Setup containers and skeleton of chart
-
-      var wrap = container.selectAll('g.nv-wrap.nv-discretebar').data([data]);
-      var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-discretebar');
-      var gEnter = wrapEnter.append('g');
-      var g = wrap.select('g');
-
-      gEnter.append('g').attr('class', 'nv-groups');
-
-      wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
-
-      //------------------------------------------------------------
-
-
-
-      //TODO: by definition, the discrete bar should not have multiple groups, will modify/remove later
-      var groups = wrap.select('.nv-groups').selectAll('.nv-group')
-          .data(function(d) { return d }, function(d) { return d.key });
-      groups.enter().append('g')
-          .style('stroke-opacity', 1e-6)
-          .style('fill-opacity', 1e-6);
-      d3.transition(groups.exit())
-          .style('stroke-opacity', 1e-6)
-          .style('fill-opacity', 1e-6)
-          .remove();
-      groups
-          .attr('class', function(d,i) { return 'nv-group nv-series-' + i })
-          .classed('hover', function(d) { return d.hover });
-      d3.transition(groups)
-          .style('stroke-opacity', 1)
-          .style('fill-opacity', .75);
-
-
-      var bars = groups.selectAll('g.nv-bar')
-          .data(function(d) { return d.values });
-
-      bars.exit().remove();
-
-
-      var barsEnter = bars.enter().append('g')
-          .attr('transform', function(d,i,j) {
-              return 'translate(' + (x(getX(d,i)) + x.rangeBand() * .05 ) + ', ' + y(0) + ')' 
-          })
-          .on('mouseover', function(d,i) { //TODO: figure out why j works above, but not here
-            d3.select(this).classed('hover', true);
-            dispatch.elementMouseover({
-              value: getY(d,i),
-              point: d,
-              series: data[d.series],
-              pos: [x(getX(d,i)) + (x.rangeBand() * (d.series + .5) / data.length), y(getY(d,i))],  // TODO: Figure out why the value appears to be shifted
-              pointIndex: i,
-              seriesIndex: d.series,
-              e: d3.event
-            });
-          })
-          .on('mouseout', function(d,i) {
-            d3.select(this).classed('hover', false);
-            dispatch.elementMouseout({
-              value: getY(d,i),
-              point: d,
-              series: data[d.series],
-              pointIndex: i,
-              seriesIndex: d.series,
-              e: d3.event
-            });
-          })
-          .on('click', function(d,i) {
-            dispatch.elementClick({
-              value: getY(d,i),
-              point: d,
-              series: data[d.series],
-              pos: [x(getX(d,i)) + (x.rangeBand() * (d.series + .5) / data.length), y(getY(d,i))],  // TODO: Figure out why the value appears to be shifted
-              pointIndex: i,
-              seriesIndex: d.series,
-              e: d3.event
-            });
-            d3.event.stopPropagation();
-          })
-          .on('dblclick', function(d,i) {
-            dispatch.elementDblClick({
-              value: getY(d,i),
-              point: d,
-              series: data[d.series],
-              pos: [x(getX(d,i)) + (x.rangeBand() * (d.series + .5) / data.length), y(getY(d,i))],  // TODO: Figure out why the value appears to be shifted
-              pointIndex: i,
-              seriesIndex: d.series,
-              e: d3.event
-            });
-            d3.event.stopPropagation();
-          });
-
-      barsEnter.append('rect')
-          .attr('height', 0)
-          .attr('width', x.rangeBand() * .9 / data.length )
-
-      if (showValues) {
-        barsEnter.append('text')
-          .attr('text-anchor', 'middle')
-        bars.select('text')
-          .attr('x', x.rangeBand() * .9 / 2)
-          .attr('y', function(d,i) { return getY(d,i) < 0 ? y(getY(d,i)) - y(0) + 12 : -4 })
-          .text(function(d,i) { return valueFormat(getY(d,i)) });
-      } else {
-        bars.selectAll('text').remove();
-      }
-
-      bars
-          .attr('class', function(d,i) { return getY(d,i) < 0 ? 'nv-bar negative' : 'nv-bar positive' })
-          .style('fill', function(d,i) { return d.color || color(d,i) })
-          .style('stroke', function(d,i) { return d.color || color(d,i) })
-        .select('rect')
-          .attr('class', rectClass)
-          .attr('width', x.rangeBand() * .9 / data.length);
-      d3.transition(bars)
-        //.delay(function(d,i) { return i * 1200 / data[0].values.length })
-          .attr('transform', function(d,i) {
-            var left = x(getX(d,i)) + x.rangeBand() * .05,
-                top = getY(d,i) < 0 ?
-                        y(0) :
-                        y(0) - y(getY(d,i)) < 1 ?
-                          y(0) - 1 : //make 1 px positive bars show up above y=0
-                          y(getY(d,i));
-
-              return 'translate(' + left + ', ' + top + ')'
-          })
-        .select('rect')
-          .attr('height', function(d,i) {
-            return  Math.max(Math.abs(y(getY(d,i)) - y(0)) || 1)
-          });
-
-
-      //store old scales for use in transitions on update
-      x0 = x.copy();
-      y0 = y.copy();
-
-    });
-
-    return chart;
-  }
-
-
-  //============================================================
-  // Expose Public Variables
-  //------------------------------------------------------------
-
-  chart.dispatch = dispatch;
-
-  chart.x = function(_) {
-    if (!arguments.length) return getX;
-    getX = _;
-    return chart;
-  };
-
-  chart.y = function(_) {
-    if (!arguments.length) return getY;
-    getY = _;
-    return chart;
-  };
-
-  chart.margin = function(_) {
-    if (!arguments.length) return margin;
-    margin.top    = typeof _.top    != 'undefined' ? _.top    : margin.top;
-    margin.right  = typeof _.right  != 'undefined' ? _.right  : margin.right;
-    margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
-    margin.left   = typeof _.left   != 'undefined' ? _.left   : margin.left;
-    return chart;
-  };
-
-  chart.width = function(_) {
-    if (!arguments.length) return width;
-    width = _;
-    return chart;
-  };
-
-  chart.height = function(_) {
-    if (!arguments.length) return height;
-    height = _;
-    return chart;
-  };
-
-  chart.xScale = function(_) {
-    if (!arguments.length) return x;
-    x = _;
-    return chart;
-  };
-
-  chart.yScale = function(_) {
-    if (!arguments.length) return y;
-    y = _;
-    return chart;
-  };
-
-  chart.xDomain = function(_) {
-    if (!arguments.length) return xDomain;
-    xDomain = _;
-    return chart;
-  };
-
-  chart.yDomain = function(_) {
-    if (!arguments.length) return yDomain;
-    yDomain = _;
-    return chart;
-  };
-
-  chart.forceY = function(_) {
-    if (!arguments.length) return forceY;
-    forceY = _;
-    return chart;
-  };
-
-  chart.color = function(_) {
-    if (!arguments.length) return color;
-    color = nv.utils.getColor(_);
-    return chart;
-  };
-
-  chart.id = function(_) {
-    if (!arguments.length) return id;
-    id = _;
-    return chart;
-  };
-
-  chart.showValues = function(_) {
-    if (!arguments.length) return showValues;
-    showValues = _;
-    return chart;
-  };
-
-  chart.valueFormat= function(_) {
-    if (!arguments.length) return valueFormat;
-    valueFormat = _;
-    return chart;
-  };
-
-  chart.rectClass= function(_) {
-    if (!arguments.length) return rectClass;
-    rectClass = _;
-    return chart;
-  }
-  //============================================================
-
-
-  return chart;
-}
-
-nv.models.discreteBarChart = function() {
-
-  //============================================================
-  // Public Variables with Default Settings
-  //------------------------------------------------------------
-
-  var discretebar = nv.models.discreteBar()
-    , xAxis = nv.models.axis()
-    , yAxis = nv.models.axis()
-    ;
-
-  var margin = {top: 15, right: 10, bottom: 50, left: 60}
-    , width = null
-    , height = null
-    , color = nv.utils.getColor()
-    , staggerLabels = false
-    , tooltips = true
-    , tooltip = function(key, x, y, e, graph) {
-        return '<h3>' + x + '</h3>' +
-               '<p>' +  y + '</p>'
-      }
-    , x
-    , y
-    , noData = "No Data Available."
-    , dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'beforeUpdate')
-    ;
-
-  xAxis
-    .orient('bottom')
-    .highlightZero(false)
-    .showMaxMin(false)
-    .tickFormat(function(d) { return d })
-    ;
-  yAxis
-    .orient('left')
-    .tickFormat(d3.format(',.1f'))
-    ;
-
-  //============================================================
-
-
-  //============================================================
-  // Private Variables
-  //------------------------------------------------------------
-
-  var showTooltip = function(e, offsetElement) {
-    var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ),
-        top = e.pos[1] + ( offsetElement.offsetTop || 0),
-        x = xAxis.tickFormat()(discretebar.x()(e.point, e.pointIndex)),
-        y = yAxis.tickFormat()(discretebar.y()(e.point, e.pointIndex)),
-        content = tooltip(e.series.key, x, y, e, chart);
-
-    nv.tooltip.show([left, top], content, e.value < 0 ? 'n' : 's', null, offsetElement);
-  };
-
-  //============================================================
-
-
-  function chart(selection) {
-    selection.each(function(data) {
-      var container = d3.select(this),
-          that = this;
-
-      var availableWidth = (width  || parseInt(container.style('width')) || 960)
-                             - margin.left - margin.right,
-          availableHeight = (height || parseInt(container.style('height')) || 400)
-                             - margin.top - margin.bottom;
-
-
-      chart.update = function() { dispatch.beforeUpdate(); container.transition().call(chart); };
-      chart.container = this;
-
-
-      //------------------------------------------------------------
-      // Display No Data message if there's nothing to show.
-
-      if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) {
-        var noDataText = container.selectAll('.nv-noData').data([noData]);
-
-        noDataText.enter().append('text')
-          .attr('class', 'nvd3 nv-noData')
-          .attr('dy', '-.7em')
-          .style('text-anchor', 'middle');
-
-        noDataText
-          .attr('x', margin.left + availableWidth / 2)
-          .attr('y', margin.top + availableHeight / 2)
-          .text(function(d) { return d });
-
-        return chart;
-      } else {
-        container.selectAll('.nv-noData').remove();
-      }
-
-      //------------------------------------------------------------
-
-
-      //------------------------------------------------------------
-      // Setup Scales
-
-      x = discretebar.xScale();
-      y = discretebar.yScale();
-
-      //------------------------------------------------------------
-
-
-      //------------------------------------------------------------
-      // Setup containers and skeleton of chart
-
-      var wrap = container.selectAll('g.nv-wrap.nv-discreteBarWithAxes').data([data]);
-      var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-discreteBarWithAxes').append('g');
-      var defsEnter = gEnter.append('defs');
-      var g = wrap.select('g');
-
-      gEnter.append('g').attr('class', 'nv-x nv-axis');
-      gEnter.append('g').attr('class', 'nv-y nv-axis');
-      gEnter.append('g').attr('class', 'nv-barsWrap');
-
-      g.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
-
-      //------------------------------------------------------------
-
-
-      //------------------------------------------------------------
-      // Main Chart Component(s)
-
-      discretebar
-        .width(availableWidth)
-        .height(availableHeight);
-
-
-      var barsWrap = g.select('.nv-barsWrap')
-          .datum(data.filter(function(d) { return !d.disabled }))
-
-      d3.transition(barsWrap).call(discretebar);
-
-      //------------------------------------------------------------
-
-
-
-      defsEnter.append('clipPath')
-          .attr('id', 'nv-x-label-clip-' + discretebar.id())
-        .append('rect');
-
-      g.select('#nv-x-label-clip-' + discretebar.id() + ' rect')
-          .attr('width', x.rangeBand() * (staggerLabels ? 2 : 1))
-          .attr('height', 16)
-          .attr('x', -x.rangeBand() / (staggerLabels ? 1 : 2 ));
-
-
-      //------------------------------------------------------------
-      // Setup Axes
-
-      xAxis
-        .scale(x)
-        .ticks( availableWidth / 100 )
-        .tickSize(-availableHeight, 0);
-
-      g.select('.nv-x.nv-axis')
-          .attr('transform', 'translate(0,' + (y.range()[0] + ((discretebar.showValues() && y.domain()[0] < 0) ? 16 : 0)) + ')');
-      //d3.transition(g.select('.nv-x.nv-axis'))
-      g.select('.nv-x.nv-axis').transition().duration(0)
-          .call(xAxis);
-
-
-      var xTicks = g.select('.nv-x.nv-axis').selectAll('g');
-
-      if (staggerLabels) {
-        xTicks
-            .selectAll('text')
-            .attr('transform', function(d,i,j) { return 'translate(0,' + (j % 2 == 0 ? '5' : '17') + ')' })
-      }
-
-      yAxis
-        .scale(y)
-        .ticks( availableHeight / 36 )
-        .tickSize( -availableWidth, 0);
-
-      d3.transition(g.select('.nv-y.nv-axis'))
-          .call(yAxis);
-
-      //------------------------------------------------------------
-
-
-      //============================================================
-      // Event Handling/Dispatching (in chart's scope)
-      //------------------------------------------------------------
-
-      dispatch.on('tooltipShow', function(e) {
-        if (tooltips) showTooltip(e, that.parentNode);
-      });
-
-      //============================================================
-
-
-    });
-
-    return chart;
-  }
-
-  //============================================================
-  // Event Handling/Dispatching (out of chart's scope)
-  //------------------------------------------------------------
-
-  discretebar.dispatch.on('elementMouseover.tooltip', function(e) {
-    e.pos = [e.pos[0] +  margin.left, e.pos[1] + margin.top];
-    dispatch.tooltipShow(e);
- 

<TRUNCATED>

[27/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/js/libs/ace/ace.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/js/libs/ace/ace.js b/apps/fauxton/assets/js/libs/ace/ace.js
deleted file mode 100644
index eda1067..0000000
--- a/apps/fauxton/assets/js/libs/ace/ace.js
+++ /dev/null
@@ -1,16541 +0,0 @@
-/* ***** BEGIN LICENSE BLOCK *****
- * Distributed under the BSD license:
- *
- * Copyright (c) 2010, Ajax.org B.V.
- * All rights reserved.
- * 
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above copyright
- *       notice, this list of conditions and the following disclaimer in the
- *       documentation and/or other materials provided with the distribution.
- *     * Neither the name of Ajax.org B.V. nor the
- *       names of its contributors may be used to endorse or promote products
- *       derived from this software without specific prior written permission.
- * 
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * ***** END LICENSE BLOCK ***** */
-
-(function() {
-
-var ACE_NAMESPACE = "";
-
-var global = (function() {
-    return this;
-})();
-
-
-if (!ACE_NAMESPACE && typeof requirejs !== "undefined")
-    return;
-
-
-var _define = function(module, deps, payload) {
-    if (typeof module !== 'string') {
-        if (_define.original)
-            _define.original.apply(window, arguments);
-        else {
-            console.error('dropping module because define wasn\'t a string.');
-            console.trace();
-        }
-        return;
-    }
-
-    if (arguments.length == 2)
-        payload = deps;
-
-    if (!_define.modules) {
-        _define.modules = {};
-        _define.payloads = {};
-    }
-    
-    _define.payloads[module] = payload;
-    _define.modules[module] = null;
-};
-var _require = function(parentId, module, callback) {
-    if (Object.prototype.toString.call(module) === "[object Array]") {
-        var params = [];
-        for (var i = 0, l = module.length; i < l; ++i) {
-            var dep = lookup(parentId, module[i]);
-            if (!dep && _require.original)
-                return _require.original.apply(window, arguments);
-            params.push(dep);
-        }
-        if (callback) {
-            callback.apply(null, params);
-        }
-    }
-    else if (typeof module === 'string') {
-        var payload = lookup(parentId, module);
-        if (!payload && _require.original)
-            return _require.original.apply(window, arguments);
-
-        if (callback) {
-            callback();
-        }
-
-        return payload;
-    }
-    else {
-        if (_require.original)
-            return _require.original.apply(window, arguments);
-    }
-};
-
-var normalizeModule = function(parentId, moduleName) {
-    if (moduleName.indexOf("!") !== -1) {
-        var chunks = moduleName.split("!");
-        return normalizeModule(parentId, chunks[0]) + "!" + normalizeModule(parentId, chunks[1]);
-    }
-    if (moduleName.charAt(0) == ".") {
-        var base = parentId.split("/").slice(0, -1).join("/");
-        moduleName = base + "/" + moduleName;
-
-        while(moduleName.indexOf(".") !== -1 && previous != moduleName) {
-            var previous = moduleName;
-            moduleName = moduleName.replace(/\/\.\//, "/").replace(/[^\/]+\/\.\.\//, "");
-        }
-    }
-
-    return moduleName;
-};
-var lookup = function(parentId, moduleName) {
-
-    moduleName = normalizeModule(parentId, moduleName);
-
-    var module = _define.modules[moduleName];
-    if (!module) {
-        module = _define.payloads[moduleName];
-        if (typeof module === 'function') {
-            var exports = {};
-            var mod = {
-                id: moduleName,
-                uri: '',
-                exports: exports,
-                packaged: true
-            };
-
-            var req = function(module, callback) {
-                return _require(moduleName, module, callback);
-            };
-
-            var returnValue = module(req, exports, mod);
-            exports = returnValue || mod.exports;
-            _define.modules[moduleName] = exports;
-            delete _define.payloads[moduleName];
-        }
-        module = _define.modules[moduleName] = exports || module;
-    }
-    return module;
-};
-
-function exportAce(ns) {
-    var require = function(module, callback) {
-        return _require("", module, callback);
-    };    
-
-    var root = global;
-    if (ns) {
-        if (!global[ns])
-            global[ns] = {};
-        root = global[ns];
-    }
-
-    if (!root.define || !root.define.packaged) {
-        _define.original = root.define;
-        root.define = _define;
-        root.define.packaged = true;
-    }
-
-    if (!root.require || !root.require.packaged) {
-        _require.original = root.require;
-        root.require = require;
-        root.require.packaged = true;
-    }
-}
-
-exportAce(ACE_NAMESPACE);
-
-})();
-
-
-define('ace/lib/fixoldbrowsers', ['require', 'exports', 'module' , 'ace/lib/regexp', 'ace/lib/es5-shim'], function(require, exports, module) {
-
-
-require("./regexp");
-require("./es5-shim");
-
-});
- 
-define('ace/lib/regexp', ['require', 'exports', 'module' ], function(require, exports, module) {
-
-    var real = {
-            exec: RegExp.prototype.exec,
-            test: RegExp.prototype.test,
-            match: String.prototype.match,
-            replace: String.prototype.replace,
-            split: String.prototype.split
-        },
-        compliantExecNpcg = real.exec.call(/()??/, "")[1] === undefined, // check `exec` handling of nonparticipating capturing groups
-        compliantLastIndexIncrement = function () {
-            var x = /^/g;
-            real.test.call(x, "");
-            return !x.lastIndex;
-        }();
-
-    if (compliantLastIndexIncrement && compliantExecNpcg)
-        return;
-    RegExp.prototype.exec = function (str) {
-        var match = real.exec.apply(this, arguments),
-            name, r2;
-        if ( typeof(str) == 'string' && match) {
-            if (!compliantExecNpcg && match.length > 1 && indexOf(match, "") > -1) {
-                r2 = RegExp(this.source, real.replace.call(getNativeFlags(this), "g", ""));
-                real.replace.call(str.slice(match.index), r2, function () {
-                    for (var i = 1; i < arguments.length - 2; i++) {
-                        if (arguments[i] === undefined)
-                            match[i] = undefined;
-                    }
-                });
-            }
-            if (this._xregexp && this._xregexp.captureNames) {
-                for (var i = 1; i < match.length; i++) {
-                    name = this._xregexp.captureNames[i - 1];
-                    if (name)
-                       match[name] = match[i];
-                }
-            }
-            if (!compliantLastIndexIncrement && this.global && !match[0].length && (this.lastIndex > match.index))
-                this.lastIndex--;
-        }
-        return match;
-    };
-    if (!compliantLastIndexIncrement) {
-        RegExp.prototype.test = function (str) {
-            var match = real.exec.call(this, str);
-            if (match && this.global && !match[0].length && (this.lastIndex > match.index))
-                this.lastIndex--;
-            return !!match;
-        };
-    }
-
-    function getNativeFlags (regex) {
-        return (regex.global     ? "g" : "") +
-               (regex.ignoreCase ? "i" : "") +
-               (regex.multiline  ? "m" : "") +
-               (regex.extended   ? "x" : "") + // Proposed for ES4; included in AS3
-               (regex.sticky     ? "y" : "");
-    }
-
-    function indexOf (array, item, from) {
-        if (Array.prototype.indexOf) // Use the native array method if available
-            return array.indexOf(item, from);
-        for (var i = from || 0; i < array.length; i++) {
-            if (array[i] === item)
-                return i;
-        }
-        return -1;
-    }
-
-});
-
-define('ace/lib/es5-shim', ['require', 'exports', 'module' ], function(require, exports, module) {
-
-function Empty() {}
-
-if (!Function.prototype.bind) {
-    Function.prototype.bind = function bind(that) { // .length is 1
-        var target = this;
-        if (typeof target != "function") {
-            throw new TypeError("Function.prototype.bind called on incompatible " + target);
-        }
-        var args = slice.call(arguments, 1); // for normal call
-        var bound = function () {
-
-            if (this instanceof bound) {
-
-                var result = target.apply(
-                    this,
-                    args.concat(slice.call(arguments))
-                );
-                if (Object(result) === result) {
-                    return result;
-                }
-                return this;
-
-            } else {
-                return target.apply(
-                    that,
-                    args.concat(slice.call(arguments))
-                );
-
-            }
-
-        };
-        if(target.prototype) {
-            Empty.prototype = target.prototype;
-            bound.prototype = new Empty();
-            Empty.prototype = null;
-        }
-        return bound;
-    };
-}
-var call = Function.prototype.call;
-var prototypeOfArray = Array.prototype;
-var prototypeOfObject = Object.prototype;
-var slice = prototypeOfArray.slice;
-var _toString = call.bind(prototypeOfObject.toString);
-var owns = call.bind(prototypeOfObject.hasOwnProperty);
-var defineGetter;
-var defineSetter;
-var lookupGetter;
-var lookupSetter;
-var supportsAccessors;
-if ((supportsAccessors = owns(prototypeOfObject, "__defineGetter__"))) {
-    defineGetter = call.bind(prototypeOfObject.__defineGetter__);
-    defineSetter = call.bind(prototypeOfObject.__defineSetter__);
-    lookupGetter = call.bind(prototypeOfObject.__lookupGetter__);
-    lookupSetter = call.bind(prototypeOfObject.__lookupSetter__);
-}
-if ([1,2].splice(0).length != 2) {
-    if(function() { // test IE < 9 to splice bug - see issue #138
-        function makeArray(l) {
-            var a = new Array(l+2);
-            a[0] = a[1] = 0;
-            return a;
-        }
-        var array = [], lengthBefore;
-        
-        array.splice.apply(array, makeArray(20));
-        array.splice.apply(array, makeArray(26));
-
-        lengthBefore = array.length; //46
-        array.splice(5, 0, "XXX"); // add one element
-
-        lengthBefore + 1 == array.length
-
-        if (lengthBefore + 1 == array.length) {
-            return true;// has right splice implementation without bugs
-        }
-    }()) {//IE 6/7
-        var array_splice = Array.prototype.splice;
-        Array.prototype.splice = function(start, deleteCount) {
-            if (!arguments.length) {
-                return [];
-            } else {
-                return array_splice.apply(this, [
-                    start === void 0 ? 0 : start,
-                    deleteCount === void 0 ? (this.length - start) : deleteCount
-                ].concat(slice.call(arguments, 2)))
-            }
-        };
-    } else {//IE8
-        Array.prototype.splice = function(pos, removeCount){
-            var length = this.length;
-            if (pos > 0) {
-                if (pos > length)
-                    pos = length;
-            } else if (pos == void 0) {
-                pos = 0;
-            } else if (pos < 0) {
-                pos = Math.max(length + pos, 0);
-            }
-
-            if (!(pos+removeCount < length))
-                removeCount = length - pos;
-
-            var removed = this.slice(pos, pos+removeCount);
-            var insert = slice.call(arguments, 2);
-            var add = insert.length;            
-            if (pos === length) {
-                if (add) {
-                    this.push.apply(this, insert);
-                }
-            } else {
-                var remove = Math.min(removeCount, length - pos);
-                var tailOldPos = pos + remove;
-                var tailNewPos = tailOldPos + add - remove;
-                var tailCount = length - tailOldPos;
-                var lengthAfterRemove = length - remove;
-
-                if (tailNewPos < tailOldPos) { // case A
-                    for (var i = 0; i < tailCount; ++i) {
-                        this[tailNewPos+i] = this[tailOldPos+i];
-                    }
-                } else if (tailNewPos > tailOldPos) { // case B
-                    for (i = tailCount; i--; ) {
-                        this[tailNewPos+i] = this[tailOldPos+i];
-                    }
-                } // else, add == remove (nothing to do)
-
-                if (add && pos === lengthAfterRemove) {
-                    this.length = lengthAfterRemove; // truncate array
-                    this.push.apply(this, insert);
-                } else {
-                    this.length = lengthAfterRemove + add; // reserves space
-                    for (i = 0; i < add; ++i) {
-                        this[pos+i] = insert[i];
-                    }
-                }
-            }
-            return removed;
-        };
-    }
-}
-if (!Array.isArray) {
-    Array.isArray = function isArray(obj) {
-        return _toString(obj) == "[object Array]";
-    };
-}
-var boxedString = Object("a"),
-    splitString = boxedString[0] != "a" || !(0 in boxedString);
-
-if (!Array.prototype.forEach) {
-    Array.prototype.forEach = function forEach(fun /*, thisp*/) {
-        var object = toObject(this),
-            self = splitString && _toString(this) == "[object String]" ?
-                this.split("") :
-                object,
-            thisp = arguments[1],
-            i = -1,
-            length = self.length >>> 0;
-        if (_toString(fun) != "[object Function]") {
-            throw new TypeError(); // TODO message
-        }
-
-        while (++i < length) {
-            if (i in self) {
-                fun.call(thisp, self[i], i, object);
-            }
-        }
-    };
-}
-if (!Array.prototype.map) {
-    Array.prototype.map = function map(fun /*, thisp*/) {
-        var object = toObject(this),
-            self = splitString && _toString(this) == "[object String]" ?
-                this.split("") :
-                object,
-            length = self.length >>> 0,
-            result = Array(length),
-            thisp = arguments[1];
-        if (_toString(fun) != "[object Function]") {
-            throw new TypeError(fun + " is not a function");
-        }
-
-        for (var i = 0; i < length; i++) {
-            if (i in self)
-                result[i] = fun.call(thisp, self[i], i, object);
-        }
-        return result;
-    };
-}
-if (!Array.prototype.filter) {
-    Array.prototype.filter = function filter(fun /*, thisp */) {
-        var object = toObject(this),
-            self = splitString && _toString(this) == "[object String]" ?
-                this.split("") :
-                    object,
-            length = self.length >>> 0,
-            result = [],
-            value,
-            thisp = arguments[1];
-        if (_toString(fun) != "[object Function]") {
-            throw new TypeError(fun + " is not a function");
-        }
-
-        for (var i = 0; i < length; i++) {
-            if (i in self) {
-                value = self[i];
-                if (fun.call(thisp, value, i, object)) {
-                    result.push(value);
-                }
-            }
-        }
-        return result;
-    };
-}
-if (!Array.prototype.every) {
-    Array.prototype.every = function every(fun /*, thisp */) {
-        var object = toObject(this),
-            self = splitString && _toString(this) == "[object String]" ?
-                this.split("") :
-                object,
-            length = self.length >>> 0,
-            thisp = arguments[1];
-        if (_toString(fun) != "[object Function]") {
-            throw new TypeError(fun + " is not a function");
-        }
-
-        for (var i = 0; i < length; i++) {
-            if (i in self && !fun.call(thisp, self[i], i, object)) {
-                return false;
-            }
-        }
-        return true;
-    };
-}
-if (!Array.prototype.some) {
-    Array.prototype.some = function some(fun /*, thisp */) {
-        var object = toObject(this),
-            self = splitString && _toString(this) == "[object String]" ?
-                this.split("") :
-                object,
-            length = self.length >>> 0,
-            thisp = arguments[1];
-        if (_toString(fun) != "[object Function]") {
-            throw new TypeError(fun + " is not a function");
-        }
-
-        for (var i = 0; i < length; i++) {
-            if (i in self && fun.call(thisp, self[i], i, object)) {
-                return true;
-            }
-        }
-        return false;
-    };
-}
-if (!Array.prototype.reduce) {
-    Array.prototype.reduce = function reduce(fun /*, initial*/) {
-        var object = toObject(this),
-            self = splitString && _toString(this) == "[object String]" ?
-                this.split("") :
-                object,
-            length = self.length >>> 0;
-        if (_toString(fun) != "[object Function]") {
-            throw new TypeError(fun + " is not a function");
-        }
-        if (!length && arguments.length == 1) {
-            throw new TypeError("reduce of empty array with no initial value");
-        }
-
-        var i = 0;
-        var result;
-        if (arguments.length >= 2) {
-            result = arguments[1];
-        } else {
-            do {
-                if (i in self) {
-                    result = self[i++];
-                    break;
-                }
-                if (++i >= length) {
-                    throw new TypeError("reduce of empty array with no initial value");
-                }
-            } while (true);
-        }
-
-        for (; i < length; i++) {
-            if (i in self) {
-                result = fun.call(void 0, result, self[i], i, object);
-            }
-        }
-
-        return result;
-    };
-}
-if (!Array.prototype.reduceRight) {
-    Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) {
-        var object = toObject(this),
-            self = splitString && _toString(this) == "[object String]" ?
-                this.split("") :
-                object,
-            length = self.length >>> 0;
-        if (_toString(fun) != "[object Function]") {
-            throw new TypeError(fun + " is not a function");
-        }
-        if (!length && arguments.length == 1) {
-            throw new TypeError("reduceRight of empty array with no initial value");
-        }
-
-        var result, i = length - 1;
-        if (arguments.length >= 2) {
-            result = arguments[1];
-        } else {
-            do {
-                if (i in self) {
-                    result = self[i--];
-                    break;
-                }
-                if (--i < 0) {
-                    throw new TypeError("reduceRight of empty array with no initial value");
-                }
-            } while (true);
-        }
-
-        do {
-            if (i in this) {
-                result = fun.call(void 0, result, self[i], i, object);
-            }
-        } while (i--);
-
-        return result;
-    };
-}
-if (!Array.prototype.indexOf || ([0, 1].indexOf(1, 2) != -1)) {
-    Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) {
-        var self = splitString && _toString(this) == "[object String]" ?
-                this.split("") :
-                toObject(this),
-            length = self.length >>> 0;
-
-        if (!length) {
-            return -1;
-        }
-
-        var i = 0;
-        if (arguments.length > 1) {
-            i = toInteger(arguments[1]);
-        }
-        i = i >= 0 ? i : Math.max(0, length + i);
-        for (; i < length; i++) {
-            if (i in self && self[i] === sought) {
-                return i;
-            }
-        }
-        return -1;
-    };
-}
-if (!Array.prototype.lastIndexOf || ([0, 1].lastIndexOf(0, -3) != -1)) {
-    Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) {
-        var self = splitString && _toString(this) == "[object String]" ?
-                this.split("") :
-                toObject(this),
-            length = self.length >>> 0;
-
-        if (!length) {
-            return -1;
-        }
-        var i = length - 1;
-        if (arguments.length > 1) {
-            i = Math.min(i, toInteger(arguments[1]));
-        }
-        i = i >= 0 ? i : length - Math.abs(i);
-        for (; i >= 0; i--) {
-            if (i in self && sought === self[i]) {
-                return i;
-            }
-        }
-        return -1;
-    };
-}
-if (!Object.getPrototypeOf) {
-    Object.getPrototypeOf = function getPrototypeOf(object) {
-        return object.__proto__ || (
-            object.constructor ?
-            object.constructor.prototype :
-            prototypeOfObject
-        );
-    };
-}
-if (!Object.getOwnPropertyDescriptor) {
-    var ERR_NON_OBJECT = "Object.getOwnPropertyDescriptor called on a " +
-                         "non-object: ";
-    Object.getOwnPropertyDescriptor = function getOwnPropertyDescriptor(object, property) {
-        if ((typeof object != "object" && typeof object != "function") || object === null)
-            throw new TypeError(ERR_NON_OBJECT + object);
-        if (!owns(object, property))
-            return;
-
-        var descriptor, getter, setter;
-        descriptor =  { enumerable: true, configurable: true };
-        if (supportsAccessors) {
-            var prototype = object.__proto__;
-            object.__proto__ = prototypeOfObject;
-
-            var getter = lookupGetter(object, property);
-            var setter = lookupSetter(object, property);
-            object.__proto__ = prototype;
-
-            if (getter || setter) {
-                if (getter) descriptor.get = getter;
-                if (setter) descriptor.set = setter;
-                return descriptor;
-            }
-        }
-        descriptor.value = object[property];
-        return descriptor;
-    };
-}
-if (!Object.getOwnPropertyNames) {
-    Object.getOwnPropertyNames = function getOwnPropertyNames(object) {
-        return Object.keys(object);
-    };
-}
-if (!Object.create) {
-    var createEmpty;
-    if (Object.prototype.__proto__ === null) {
-        createEmpty = function () {
-            return { "__proto__": null };
-        };
-    } else {
-        createEmpty = function () {
-            var empty = {};
-            for (var i in empty)
-                empty[i] = null;
-            empty.constructor =
-            empty.hasOwnProperty =
-            empty.propertyIsEnumerable =
-            empty.isPrototypeOf =
-            empty.toLocaleString =
-            empty.toString =
-            empty.valueOf =
-            empty.__proto__ = null;
-            return empty;
-        }
-    }
-
-    Object.create = function create(prototype, properties) {
-        var object;
-        if (prototype === null) {
-            object = createEmpty();
-        } else {
-            if (typeof prototype != "object")
-                throw new TypeError("typeof prototype["+(typeof prototype)+"] != 'object'");
-            var Type = function () {};
-            Type.prototype = prototype;
-            object = new Type();
-            object.__proto__ = prototype;
-        }
-        if (properties !== void 0)
-            Object.defineProperties(object, properties);
-        return object;
-    };
-}
-
-function doesDefinePropertyWork(object) {
-    try {
-        Object.defineProperty(object, "sentinel", {});
-        return "sentinel" in object;
-    } catch (exception) {
-    }
-}
-if (Object.defineProperty) {
-    var definePropertyWorksOnObject = doesDefinePropertyWork({});
-    var definePropertyWorksOnDom = typeof document == "undefined" ||
-        doesDefinePropertyWork(document.createElement("div"));
-    if (!definePropertyWorksOnObject || !definePropertyWorksOnDom) {
-        var definePropertyFallback = Object.defineProperty;
-    }
-}
-
-if (!Object.defineProperty || definePropertyFallback) {
-    var ERR_NON_OBJECT_DESCRIPTOR = "Property description must be an object: ";
-    var ERR_NON_OBJECT_TARGET = "Object.defineProperty called on non-object: "
-    var ERR_ACCESSORS_NOT_SUPPORTED = "getters & setters can not be defined " +
-                                      "on this javascript engine";
-
-    Object.defineProperty = function defineProperty(object, property, descriptor) {
-        if ((typeof object != "object" && typeof object != "function") || object === null)
-            throw new TypeError(ERR_NON_OBJECT_TARGET + object);
-        if ((typeof descriptor != "object" && typeof descriptor != "function") || descriptor === null)
-            throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR + descriptor);
-        if (definePropertyFallback) {
-            try {
-                return definePropertyFallback.call(Object, object, property, descriptor);
-            } catch (exception) {
-            }
-        }
-        if (owns(descriptor, "value")) {
-
-            if (supportsAccessors && (lookupGetter(object, property) ||
-                                      lookupSetter(object, property)))
-            {
-                var prototype = object.__proto__;
-                object.__proto__ = prototypeOfObject;
-                delete object[property];
-                object[property] = descriptor.value;
-                object.__proto__ = prototype;
-            } else {
-                object[property] = descriptor.value;
-            }
-        } else {
-            if (!supportsAccessors)
-                throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED);
-            if (owns(descriptor, "get"))
-                defineGetter(object, property, descriptor.get);
-            if (owns(descriptor, "set"))
-                defineSetter(object, property, descriptor.set);
-        }
-
-        return object;
-    };
-}
-if (!Object.defineProperties) {
-    Object.defineProperties = function defineProperties(object, properties) {
-        for (var property in properties) {
-            if (owns(properties, property))
-                Object.defineProperty(object, property, properties[property]);
-        }
-        return object;
-    };
-}
-if (!Object.seal) {
-    Object.seal = function seal(object) {
-        return object;
-    };
-}
-if (!Object.freeze) {
-    Object.freeze = function freeze(object) {
-        return object;
-    };
-}
-try {
-    Object.freeze(function () {});
-} catch (exception) {
-    Object.freeze = (function freeze(freezeObject) {
-        return function freeze(object) {
-            if (typeof object == "function") {
-                return object;
-            } else {
-                return freezeObject(object);
-            }
-        };
-    })(Object.freeze);
-}
-if (!Object.preventExtensions) {
-    Object.preventExtensions = function preventExtensions(object) {
-        return object;
-    };
-}
-if (!Object.isSealed) {
-    Object.isSealed = function isSealed(object) {
-        return false;
-    };
-}
-if (!Object.isFrozen) {
-    Object.isFrozen = function isFrozen(object) {
-        return false;
-    };
-}
-if (!Object.isExtensible) {
-    Object.isExtensible = function isExtensible(object) {
-        if (Object(object) === object) {
-            throw new TypeError(); // TODO message
-        }
-        var name = '';
-        while (owns(object, name)) {
-            name += '?';
-        }
-        object[name] = true;
-        var returnValue = owns(object, name);
-        delete object[name];
-        return returnValue;
-    };
-}
-if (!Object.keys) {
-    var hasDontEnumBug = true,
-        dontEnums = [
-            "toString",
-            "toLocaleString",
-            "valueOf",
-            "hasOwnProperty",
-            "isPrototypeOf",
-            "propertyIsEnumerable",
-            "constructor"
-        ],
-        dontEnumsLength = dontEnums.length;
-
-    for (var key in {"toString": null}) {
-        hasDontEnumBug = false;
-    }
-
-    Object.keys = function keys(object) {
-
-        if (
-            (typeof object != "object" && typeof object != "function") ||
-            object === null
-        ) {
-            throw new TypeError("Object.keys called on a non-object");
-        }
-
-        var keys = [];
-        for (var name in object) {
-            if (owns(object, name)) {
-                keys.push(name);
-            }
-        }
-
-        if (hasDontEnumBug) {
-            for (var i = 0, ii = dontEnumsLength; i < ii; i++) {
-                var dontEnum = dontEnums[i];
-                if (owns(object, dontEnum)) {
-                    keys.push(dontEnum);
-                }
-            }
-        }
-        return keys;
-    };
-
-}
-if (!Date.now) {
-    Date.now = function now() {
-        return new Date().getTime();
-    };
-}
-var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" +
-    "\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" +
-    "\u2029\uFEFF";
-if (!String.prototype.trim || ws.trim()) {
-    ws = "[" + ws + "]";
-    var trimBeginRegexp = new RegExp("^" + ws + ws + "*"),
-        trimEndRegexp = new RegExp(ws + ws + "*$");
-    String.prototype.trim = function trim() {
-        return String(this).replace(trimBeginRegexp, "").replace(trimEndRegexp, "");
-    };
-}
-
-function toInteger(n) {
-    n = +n;
-    if (n !== n) { // isNaN
-        n = 0;
-    } else if (n !== 0 && n !== (1/0) && n !== -(1/0)) {
-        n = (n > 0 || -1) * Math.floor(Math.abs(n));
-    }
-    return n;
-}
-
-function isPrimitive(input) {
-    var type = typeof input;
-    return (
-        input === null ||
-        type === "undefined" ||
-        type === "boolean" ||
-        type === "number" ||
-        type === "string"
-    );
-}
-
-function toPrimitive(input) {
-    var val, valueOf, toString;
-    if (isPrimitive(input)) {
-        return input;
-    }
-    valueOf = input.valueOf;
-    if (typeof valueOf === "function") {
-        val = valueOf.call(input);
-        if (isPrimitive(val)) {
-            return val;
-        }
-    }
-    toString = input.toString;
-    if (typeof toString === "function") {
-        val = toString.call(input);
-        if (isPrimitive(val)) {
-            return val;
-        }
-    }
-    throw new TypeError();
-}
-var toObject = function (o) {
-    if (o == null) { // this matches both null and undefined
-        throw new TypeError("can't convert "+o+" to object");
-    }
-    return Object(o);
-};
-
-});
-
-define('ace/lib/dom', ['require', 'exports', 'module' ], function(require, exports, module) {
-
-
-if (typeof document == "undefined")
-    return;
-
-var XHTML_NS = "http://www.w3.org/1999/xhtml";
-
-exports.getDocumentHead = function(doc) {
-    if (!doc)
-        doc = document;
-    return doc.head || doc.getElementsByTagName("head")[0] || doc.documentElement;
-}
-
-exports.createElement = function(tag, ns) {
-    return document.createElementNS ?
-           document.createElementNS(ns || XHTML_NS, tag) :
-           document.createElement(tag);
-};
-
-exports.hasCssClass = function(el, name) {
-    var classes = el.className.split(/\s+/g);
-    return classes.indexOf(name) !== -1;
-};
-exports.addCssClass = function(el, name) {
-    if (!exports.hasCssClass(el, name)) {
-        el.className += " " + name;
-    }
-};
-exports.removeCssClass = function(el, name) {
-    var classes = el.className.split(/\s+/g);
-    while (true) {
-        var index = classes.indexOf(name);
-        if (index == -1) {
-            break;
-        }
-        classes.splice(index, 1);
-    }
-    el.className = classes.join(" ");
-};
-
-exports.toggleCssClass = function(el, name) {
-    var classes = el.className.split(/\s+/g), add = true;
-    while (true) {
-        var index = classes.indexOf(name);
-        if (index == -1) {
-            break;
-        }
-        add = false;
-        classes.splice(index, 1);
-    }
-    if(add)
-        classes.push(name);
-
-    el.className = classes.join(" ");
-    return add;
-};
-exports.setCssClass = function(node, className, include) {
-    if (include) {
-        exports.addCssClass(node, className);
-    } else {
-        exports.removeCssClass(node, className);
-    }
-};
-
-exports.hasCssString = function(id, doc) {
-    var index = 0, sheets;
-    doc = doc || document;
-
-    if (doc.createStyleSheet && (sheets = doc.styleSheets)) {
-        while (index < sheets.length)
-            if (sheets[index++].owningElement.id === id) return true;
-    } else if ((sheets = doc.getElementsByTagName("style"))) {
-        while (index < sheets.length)
-            if (sheets[index++].id === id) return true;
-    }
-
-    return false;
-};
-
-exports.importCssString = function importCssString(cssText, id, doc) {
-    doc = doc || document;
-    if (id && exports.hasCssString(id, doc))
-        return null;
-    
-    var style;
-    
-    if (doc.createStyleSheet) {
-        style = doc.createStyleSheet();
-        style.cssText = cssText;
-        if (id)
-            style.owningElement.id = id;
-    } else {
-        style = doc.createElementNS
-            ? doc.createElementNS(XHTML_NS, "style")
-            : doc.createElement("style");
-
-        style.appendChild(doc.createTextNode(cssText));
-        if (id)
-            style.id = id;
-
-        exports.getDocumentHead(doc).appendChild(style);
-    }
-};
-
-exports.importCssStylsheet = function(uri, doc) {
-    if (doc.createStyleSheet) {
-        doc.createStyleSheet(uri);
-    } else {
-        var link = exports.createElement('link');
-        link.rel = 'stylesheet';
-        link.href = uri;
-
-        exports.getDocumentHead(doc).appendChild(link);
-    }
-};
-
-exports.getInnerWidth = function(element) {
-    return (
-        parseInt(exports.computedStyle(element, "paddingLeft"), 10) +
-        parseInt(exports.computedStyle(element, "paddingRight"), 10) + 
-        element.clientWidth
-    );
-};
-
-exports.getInnerHeight = function(element) {
-    return (
-        parseInt(exports.computedStyle(element, "paddingTop"), 10) +
-        parseInt(exports.computedStyle(element, "paddingBottom"), 10) +
-        element.clientHeight
-    );
-};
-
-if (window.pageYOffset !== undefined) {
-    exports.getPageScrollTop = function() {
-        return window.pageYOffset;
-    };
-
-    exports.getPageScrollLeft = function() {
-        return window.pageXOffset;
-    };
-}
-else {
-    exports.getPageScrollTop = function() {
-        return document.body.scrollTop;
-    };
-
-    exports.getPageScrollLeft = function() {
-        return document.body.scrollLeft;
-    };
-}
-
-if (window.getComputedStyle)
-    exports.computedStyle = function(element, style) {
-        if (style)
-            return (window.getComputedStyle(element, "") || {})[style] || "";
-        return window.getComputedStyle(element, "") || {};
-    };
-else
-    exports.computedStyle = function(element, style) {
-        if (style)
-            return element.currentStyle[style];
-        return element.currentStyle;
-    };
-
-exports.scrollbarWidth = function(document) {
-    var inner = exports.createElement("ace_inner");
-    inner.style.width = "100%";
-    inner.style.minWidth = "0px";
-    inner.style.height = "200px";
-    inner.style.display = "block";
-
-    var outer = exports.createElement("ace_outer");
-    var style = outer.style;
-
-    style.position = "absolute";
-    style.left = "-10000px";
-    style.overflow = "hidden";
-    style.width = "200px";
-    style.minWidth = "0px";
-    style.height = "150px";
-    style.display = "block";
-
-    outer.appendChild(inner);
-
-    var body = document.documentElement;
-    body.appendChild(outer);
-
-    var noScrollbar = inner.offsetWidth;
-
-    style.overflow = "scroll";
-    var withScrollbar = inner.offsetWidth;
-
-    if (noScrollbar == withScrollbar) {
-        withScrollbar = outer.clientWidth;
-    }
-
-    body.removeChild(outer);
-
-    return noScrollbar-withScrollbar;
-};
-exports.setInnerHtml = function(el, innerHtml) {
-    var element = el.cloneNode(false);//document.createElement("div");
-    element.innerHTML = innerHtml;
-    el.parentNode.replaceChild(element, el);
-    return element;
-};
-
-if ("textContent" in document.documentElement) {
-    exports.setInnerText = function(el, innerText) {
-        el.textContent = innerText;
-    };
-
-    exports.getInnerText = function(el) {
-        return el.textContent;
-    };
-}
-else {
-    exports.setInnerText = function(el, innerText) {
-        el.innerText = innerText;
-    };
-
-    exports.getInnerText = function(el) {
-        return el.innerText;
-    };
-}
-
-exports.getParentWindow = function(document) {
-    return document.defaultView || document.parentWindow;
-};
-
-});
-
-define('ace/lib/event', ['require', 'exports', 'module' , 'ace/lib/keys', 'ace/lib/useragent', 'ace/lib/dom'], function(require, exports, module) {
-
-
-var keys = require("./keys");
-var useragent = require("./useragent");
-var dom = require("./dom");
-
-exports.addListener = function(elem, type, callback) {
-    if (elem.addEventListener) {
-        return elem.addEventListener(type, callback, false);
-    }
-    if (elem.attachEvent) {
-        var wrapper = function() {
-            callback.call(elem, window.event);
-        };
-        callback._wrapper = wrapper;
-        elem.attachEvent("on" + type, wrapper);
-    }
-};
-
-exports.removeListener = function(elem, type, callback) {
-    if (elem.removeEventListener) {
-        return elem.removeEventListener(type, callback, false);
-    }
-    if (elem.detachEvent) {
-        elem.detachEvent("on" + type, callback._wrapper || callback);
-    }
-};
-exports.stopEvent = function(e) {
-    exports.stopPropagation(e);
-    exports.preventDefault(e);
-    return false;
-};
-
-exports.stopPropagation = function(e) {
-    if (e.stopPropagation)
-        e.stopPropagation();
-    else
-        e.cancelBubble = true;
-};
-
-exports.preventDefault = function(e) {
-    if (e.preventDefault)
-        e.preventDefault();
-    else
-        e.returnValue = false;
-};
-exports.getButton = function(e) {
-    if (e.type == "dblclick")
-        return 0;
-    if (e.type == "contextmenu" || (e.ctrlKey && useragent.isMac))
-        return 2;
-    if (e.preventDefault) {
-        return e.button;
-    }
-    else {
-        return {1:0, 2:2, 4:1}[e.button];
-    }
-};
-
-exports.capture = function(el, eventHandler, releaseCaptureHandler) {
-    function onMouseUp(e) {
-        eventHandler && eventHandler(e);
-        releaseCaptureHandler && releaseCaptureHandler(e);
-
-        exports.removeListener(document, "mousemove", eventHandler, true);
-        exports.removeListener(document, "mouseup", onMouseUp, true);
-        exports.removeListener(document, "dragstart", onMouseUp, true);
-    }
-
-    exports.addListener(document, "mousemove", eventHandler, true);
-    exports.addListener(document, "mouseup", onMouseUp, true);
-    exports.addListener(document, "dragstart", onMouseUp, true);
-};
-
-exports.addMouseWheelListener = function(el, callback) {
-    if ("onmousewheel" in el) {
-        var factor = 8;
-        exports.addListener(el, "mousewheel", function(e) {
-            if (e.wheelDeltaX !== undefined) {
-                e.wheelX = -e.wheelDeltaX / factor;
-                e.wheelY = -e.wheelDeltaY / factor;
-            } else {
-                e.wheelX = 0;
-                e.wheelY = -e.wheelDelta / factor;
-            }
-            callback(e);
-        });
-    } else if ("onwheel" in el) {
-        exports.addListener(el, "wheel",  function(e) {
-            e.wheelX = (e.deltaX || 0) * 5;
-            e.wheelY = (e.deltaY || 0) * 5;
-            callback(e);
-        });
-    } else {
-        exports.addListener(el, "DOMMouseScroll", function(e) {
-            if (e.axis && e.axis == e.HORIZONTAL_AXIS) {
-                e.wheelX = (e.detail || 0) * 5;
-                e.wheelY = 0;
-            } else {
-                e.wheelX = 0;
-                e.wheelY = (e.detail || 0) * 5;
-            }
-            callback(e);
-        });
-    }
-};
-
-exports.addMultiMouseDownListener = function(el, timeouts, eventHandler, callbackName) {
-    var clicks = 0;
-    var startX, startY, timer;
-    var eventNames = {
-        2: "dblclick",
-        3: "tripleclick",
-        4: "quadclick"
-    };
-
-    exports.addListener(el, "mousedown", function(e) {
-        if (exports.getButton(e) != 0) {
-            clicks = 0;
-        } else if (e.detail > 1) {
-            clicks++;
-            if (clicks > 4)
-                clicks = 1;
-        } else {
-            clicks = 1;
-        }
-        if (useragent.isIE) {
-            var isNewClick = Math.abs(e.clientX - startX) > 5 || Math.abs(e.clientY - startY) > 5;
-            if (isNewClick) {
-                clicks = 1;
-            }
-            if (clicks == 1) {
-                startX = e.clientX;
-                startY = e.clientY;
-            }
-        }
-
-        eventHandler[callbackName]("mousedown", e);
-
-        if (clicks > 4)
-            clicks = 0;
-        else if (clicks > 1)
-            return eventHandler[callbackName](eventNames[clicks], e);
-    });
-
-    if (useragent.isOldIE) {
-        exports.addListener(el, "dblclick", function(e) {
-            clicks = 2;
-            if (timer)
-                clearTimeout(timer);
-            timer = setTimeout(function() {timer = null}, timeouts[clicks - 1] || 600);
-            eventHandler[callbackName]("mousedown", e);
-            eventHandler[callbackName](eventNames[clicks], e);
-        });
-    }
-};
-
-function normalizeCommandKeys(callback, e, keyCode) {
-    var hashId = 0;
-    if ((useragent.isOpera && !("KeyboardEvent" in window)) && useragent.isMac) {
-        hashId = 0 | (e.metaKey ? 1 : 0) | (e.altKey ? 2 : 0)
-            | (e.shiftKey ? 4 : 0) | (e.ctrlKey ? 8 : 0);
-    } else {
-        hashId = 0 | (e.ctrlKey ? 1 : 0) | (e.altKey ? 2 : 0)
-            | (e.shiftKey ? 4 : 0) | (e.metaKey ? 8 : 0);
-    }
-
-    if (!useragent.isMac && pressedKeys) {
-        if (pressedKeys[91] || pressedKeys[92])
-            hashId |= 8;
-        if (pressedKeys.altGr) {
-            if ((3 & hashId) != 3)
-                pressedKeys.altGr = 0
-            else
-                return;
-        }
-        if (keyCode === 18 || keyCode === 17) {
-            var location = e.location || e.keyLocation;
-            if (keyCode === 17 && location === 1) {
-                ts = e.timeStamp;
-            } else if (keyCode === 18 && hashId === 3 && location === 2) {
-                var dt = -ts;
-                ts = e.timeStamp;
-                dt += ts;
-                if (dt < 3)
-                    pressedKeys.altGr = true;
-            }
-        }
-    }
-    
-    if (keyCode in keys.MODIFIER_KEYS) {
-        switch (keys.MODIFIER_KEYS[keyCode]) {
-            case "Alt":
-                hashId = 2;
-                break;
-            case "Shift":
-                hashId = 4;
-                break;
-            case "Ctrl":
-                hashId = 1;
-                break;
-            default:
-                hashId = 8;
-                break;
-        }
-        keyCode = 0;
-    }
-
-    if (hashId & 8 && (keyCode === 91 || keyCode === 93)) {
-        keyCode = 0;
-    }
-    
-    if (!hashId && keyCode === 13) {
-        if (e.location || e.keyLocation === 3) {
-            callback(e, hashId, -keyCode)
-            if (e.defaultPrevented)
-                return;
-        }
-    }
-    if (!hashId && !(keyCode in keys.FUNCTION_KEYS) && !(keyCode in keys.PRINTABLE_KEYS)) {
-        return false;
-    }
-    
-    
-    
-    return callback(e, hashId, keyCode);
-}
-
-var pressedKeys = null;
-var ts = 0;
-exports.addCommandKeyListener = function(el, callback) {
-    var addListener = exports.addListener;
-    if (useragent.isOldGecko || (useragent.isOpera && !("KeyboardEvent" in window))) {
-        var lastKeyDownKeyCode = null;
-        addListener(el, "keydown", function(e) {
-            lastKeyDownKeyCode = e.keyCode;
-        });
-        addListener(el, "keypress", function(e) {
-            return normalizeCommandKeys(callback, e, lastKeyDownKeyCode);
-        });
-    } else {
-        var lastDefaultPrevented = null;
-
-        addListener(el, "keydown", function(e) {
-            pressedKeys[e.keyCode] = true;
-            var result = normalizeCommandKeys(callback, e, e.keyCode);
-            lastDefaultPrevented = e.defaultPrevented;
-            return result;
-        });
-
-        addListener(el, "keypress", function(e) {
-            if (lastDefaultPrevented && (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey)) {
-                exports.stopEvent(e);
-                lastDefaultPrevented = null;
-            }
-        });
-
-        addListener(el, "keyup", function(e) {
-            pressedKeys[e.keyCode] = null;
-        });
-
-        if (!pressedKeys) {
-            pressedKeys = Object.create(null);
-            addListener(window, "focus", function(e) {
-                pressedKeys = Object.create(null);
-            });
-        }
-    }
-};
-
-if (window.postMessage && !useragent.isOldIE) {
-    var postMessageId = 1;
-    exports.nextTick = function(callback, win) {
-        win = win || window;
-        var messageName = "zero-timeout-message-" + postMessageId;
-        exports.addListener(win, "message", function listener(e) {
-            if (e.data == messageName) {
-                exports.stopPropagation(e);
-                exports.removeListener(win, "message", listener);
-                callback();
-            }
-        });
-        win.postMessage(messageName, "*");
-    };
-}
-
-
-exports.nextFrame = window.requestAnimationFrame ||
-    window.mozRequestAnimationFrame ||
-    window.webkitRequestAnimationFrame ||
-    window.msRequestAnimationFrame ||
-    window.oRequestAnimationFrame;
-
-if (exports.nextFrame)
-    exports.nextFrame = exports.nextFrame.bind(window);
-else
-    exports.nextFrame = function(callback) {
-        setTimeout(callback, 17);
-    };
-});
-
-define('ace/lib/keys', ['require', 'exports', 'module' , 'ace/lib/oop'], function(require, exports, module) {
-
-
-var oop = require("./oop");
-var Keys = (function() {
-    var ret = {
-        MODIFIER_KEYS: {
-            16: 'Shift', 17: 'Ctrl', 18: 'Alt', 224: 'Meta'
-        },
-
-        KEY_MODS: {
-            "ctrl": 1, "alt": 2, "option" : 2,
-            "shift": 4, "meta": 8, "command": 8, "cmd": 8
-        },
-
-        FUNCTION_KEYS : {
-            8  : "Backspace",
-            9  : "Tab",
-            13 : "Return",
-            19 : "Pause",
-            27 : "Esc",
-            32 : "Space",
-            33 : "PageUp",
-            34 : "PageDown",
-            35 : "End",
-            36 : "Home",
-            37 : "Left",
-            38 : "Up",
-            39 : "Right",
-            40 : "Down",
-            44 : "Print",
-            45 : "Insert",
-            46 : "Delete",
-            96 : "Numpad0",
-            97 : "Numpad1",
-            98 : "Numpad2",
-            99 : "Numpad3",
-            100: "Numpad4",
-            101: "Numpad5",
-            102: "Numpad6",
-            103: "Numpad7",
-            104: "Numpad8",
-            105: "Numpad9",
-            '-13': "NumpadEnter",
-            112: "F1",
-            113: "F2",
-            114: "F3",
-            115: "F4",
-            116: "F5",
-            117: "F6",
-            118: "F7",
-            119: "F8",
-            120: "F9",
-            121: "F10",
-            122: "F11",
-            123: "F12",
-            144: "Numlock",
-            145: "Scrolllock"
-        },
-
-        PRINTABLE_KEYS: {
-           32: ' ',  48: '0',  49: '1',  50: '2',  51: '3',  52: '4', 53:  '5',
-           54: '6',  55: '7',  56: '8',  57: '9',  59: ';',  61: '=', 65:  'a',
-           66: 'b',  67: 'c',  68: 'd',  69: 'e',  70: 'f',  71: 'g', 72:  'h',
-           73: 'i',  74: 'j',  75: 'k',  76: 'l',  77: 'm',  78: 'n', 79:  'o',
-           80: 'p',  81: 'q',  82: 'r',  83: 's',  84: 't',  85: 'u', 86:  'v',
-           87: 'w',  88: 'x',  89: 'y',  90: 'z', 107: '+', 109: '-', 110: '.',
-          188: ',', 190: '.', 191: '/', 192: '`', 219: '[', 220: '\\',
-          221: ']', 222: '\''
-        }
-    };
-    for (var i in ret.FUNCTION_KEYS) {
-        var name = ret.FUNCTION_KEYS[i].toLowerCase();
-        ret[name] = parseInt(i, 10);
-    }
-    oop.mixin(ret, ret.MODIFIER_KEYS);
-    oop.mixin(ret, ret.PRINTABLE_KEYS);
-    oop.mixin(ret, ret.FUNCTION_KEYS);
-    ret.enter = ret["return"];
-    ret.escape = ret.esc;
-    ret.del = ret["delete"];
-    ret[173] = '-';
-
-    return ret;
-})();
-oop.mixin(exports, Keys);
-
-exports.keyCodeToString = function(keyCode) {
-    return (Keys[keyCode] || String.fromCharCode(keyCode)).toLowerCase();
-}
-
-});
-
-define('ace/lib/oop', ['require', 'exports', 'module' ], function(require, exports, module) {
-
-
-exports.inherits = (function() {
-    var tempCtor = function() {};
-    return function(ctor, superCtor) {
-        tempCtor.prototype = superCtor.prototype;
-        ctor.super_ = superCtor.prototype;
-        ctor.prototype = new tempCtor();
-        ctor.prototype.constructor = ctor;
-    };
-}());
-
-exports.mixin = function(obj, mixin) {
-    for (var key in mixin) {
-        obj[key] = mixin[key];
-    }
-    return obj;
-};
-
-exports.implement = function(proto, mixin) {
-    exports.mixin(proto, mixin);
-};
-
-});
-
-define('ace/lib/useragent', ['require', 'exports', 'module' ], function(require, exports, module) {
-exports.OS = {
-    LINUX: "LINUX",
-    MAC: "MAC",
-    WINDOWS: "WINDOWS"
-};
-exports.getOS = function() {
-    if (exports.isMac) {
-        return exports.OS.MAC;
-    } else if (exports.isLinux) {
-        return exports.OS.LINUX;
-    } else {
-        return exports.OS.WINDOWS;
-    }
-};
-if (typeof navigator != "object")
-    return;
-
-var os = (navigator.platform.match(/mac|win|linux/i) || ["other"])[0].toLowerCase();
-var ua = navigator.userAgent;
-exports.isWin = (os == "win");
-exports.isMac = (os == "mac");
-exports.isLinux = (os == "linux");
-exports.isIE = 
-    (navigator.appName == "Microsoft Internet Explorer" || navigator.appName.indexOf("MSAppHost") >= 0)
-    && parseFloat(navigator.userAgent.match(/MSIE ([0-9]+[\.0-9]+)/)[1]);
-    
-exports.isOldIE = exports.isIE && exports.isIE < 9;
-exports.isGecko = exports.isMozilla = window.controllers && window.navigator.product === "Gecko";
-exports.isOldGecko = exports.isGecko && parseInt((navigator.userAgent.match(/rv\:(\d+)/)||[])[1], 10) < 4;
-exports.isOpera = window.opera && Object.prototype.toString.call(window.opera) == "[object Opera]";
-exports.isWebKit = parseFloat(ua.split("WebKit/")[1]) || undefined;
-
-exports.isChrome = parseFloat(ua.split(" Chrome/")[1]) || undefined;
-
-exports.isAIR = ua.indexOf("AdobeAIR") >= 0;
-
-exports.isIPad = ua.indexOf("iPad") >= 0;
-
-exports.isTouchPad = ua.indexOf("TouchPad") >= 0;
-
-});
-
-define('ace/editor', ['require', 'exports', 'module' , 'ace/lib/fixoldbrowsers', 'ace/lib/oop', 'ace/lib/dom', 'ace/lib/lang', 'ace/lib/useragent', 'ace/keyboard/textinput', 'ace/mouse/mouse_handler', 'ace/mouse/fold_handler', 'ace/keyboard/keybinding', 'ace/edit_session', 'ace/search', 'ace/range', 'ace/lib/event_emitter', 'ace/commands/command_manager', 'ace/commands/default_commands', 'ace/config'], function(require, exports, module) {
-
-
-require("./lib/fixoldbrowsers");
-
-var oop = require("./lib/oop");
-var dom = require("./lib/dom");
-var lang = require("./lib/lang");
-var useragent = require("./lib/useragent");
-var TextInput = require("./keyboard/textinput").TextInput;
-var MouseHandler = require("./mouse/mouse_handler").MouseHandler;
-var FoldHandler = require("./mouse/fold_handler").FoldHandler;
-var KeyBinding = require("./keyboard/keybinding").KeyBinding;
-var EditSession = require("./edit_session").EditSession;
-var Search = require("./search").Search;
-var Range = require("./range").Range;
-var EventEmitter = require("./lib/event_emitter").EventEmitter;
-var CommandManager = require("./commands/command_manager").CommandManager;
-var defaultCommands = require("./commands/default_commands").commands;
-var config = require("./config");
-var Editor = function(renderer, session) {
-    var container = renderer.getContainerElement();
-    this.container = container;
-    this.renderer = renderer;
-
-    this.commands = new CommandManager(useragent.isMac ? "mac" : "win", defaultCommands);
-    this.textInput  = new TextInput(renderer.getTextAreaContainer(), this);
-    this.renderer.textarea = this.textInput.getElement();
-    this.keyBinding = new KeyBinding(this);
-    this.$mouseHandler = new MouseHandler(this);
-    new FoldHandler(this);
-
-    this.$blockScrolling = 0;
-    this.$search = new Search().set({
-        wrap: true
-    });
-
-    this.$historyTracker = this.$historyTracker.bind(this);
-    this.commands.on("exec", this.$historyTracker);
-
-    this.$initOperationListeners();
-    
-    this._$emitInputEvent = lang.delayedCall(function() {
-        this._signal("input", {});
-        this.session.bgTokenizer && this.session.bgTokenizer.scheduleStart();
-    }.bind(this));
-    
-    this.on("change", function(_, _self) {
-        _self._$emitInputEvent.schedule(31);
-    });
-
-    this.setSession(session || new EditSession(""));
-    config.resetOptions(this);
-    config._emit("editor", this);
-};
-
-(function(){
-
-    oop.implement(this, EventEmitter);
-
-    this.$initOperationListeners = function() {
-        function last(a) {return a[a.length - 1]};
-
-        this.selections = [];
-        this.commands.on("exec", function(e) {
-            this.startOperation(e);
-
-            var command = e.command;
-            if (command.group == "fileJump") {
-                var prev = this.prevOp;
-                if (!prev || prev.command.group != "fileJump") {
-                    this.lastFileJumpPos = last(this.selections)
-                }
-            } else {
-                this.lastFileJumpPos = null;
-            }
-        }.bind(this), true);
-
-        this.commands.on("afterExec", function(e) {
-            var command = e.command;
-
-            if (command.group == "fileJump") {
-                if (this.lastFileJumpPos && !this.curOp.selectionChanged) {
-                    this.selection.fromJSON(this.lastFileJumpPos);
-                    return
-                }
-            }
-            this.endOperation(e);
-        }.bind(this), true);
-
-        this.$opResetTimer = lang.delayedCall(this.endOperation.bind(this));
-
-        this.on("change", function() {
-            this.curOp || this.startOperation();
-            this.curOp.docChanged = true;
-        }.bind(this), true);
-
-        this.on("changeSelection", function() {
-            this.curOp || this.startOperation();
-            this.curOp.selectionChanged = true;
-        }.bind(this), true);
-    }
-
-    this.curOp = null;
-    this.prevOp = {};
-    this.startOperation = function(commadEvent) {
-        if (this.curOp) {
-            if (!commadEvent || this.curOp.command)
-                return;
-            this.prevOp = this.curOp;
-        }
-        if (!commadEvent) {
-            this.previousCommand = null;
-            commadEvent = {};
-        }
-
-        this.$opResetTimer.schedule();
-        this.curOp = {
-            command: commadEvent.command || {},
-            args: commadEvent.args
-        };
-
-        this.selections.push(this.selection.toJSON());
-    };
-
-    this.endOperation = function() {
-        if (this.curOp) {
-            this.prevOp = this.curOp;
-            this.curOp = null;
-        }
-    };
-
-    this.$historyTracker = function(e) {
-        if (!this.$mergeUndoDeltas)
-            return;
-
-
-        var prev = this.prevOp;
-        var mergeableCommands = ["backspace", "del", "insertstring"];
-        var shouldMerge = prev.command && (e.command.name == prev.command.name);
-        if (e.command.name == "insertstring") {
-            var text = e.args;
-            if (this.mergeNextCommand === undefined)
-                this.mergeNextCommand = true;
-
-            shouldMerge = shouldMerge
-                && this.mergeNextCommand // previous command allows to coalesce with
-                && (!/\s/.test(text) || /\s/.test(prev.args)) // previous insertion was of same type
-
-            this.mergeNextCommand = true;
-        } else {
-            shouldMerge = shouldMerge
-                && mergeableCommands.indexOf(e.command.name) !== -1// the command is mergeable
-        }
-
-        if (
-            this.$mergeUndoDeltas != "always"
-            && Date.now() - this.sequenceStartTime > 2000
-        ) {
-            shouldMerge = false; // the sequence is too long
-        }
-
-        if (shouldMerge)
-            this.session.mergeUndoDeltas = true;
-        else if (mergeableCommands.indexOf(e.command.name) !== -1)
-            this.sequenceStartTime = Date.now();
-    };
-    this.setKeyboardHandler = function(keyboardHandler) {
-        if (!keyboardHandler) {
-            this.keyBinding.setKeyboardHandler(null);
-        } else if (typeof keyboardHandler == "string") {
-            this.$keybindingId = keyboardHandler;
-            var _self = this;
-            config.loadModule(["keybinding", keyboardHandler], function(module) {
-                if (_self.$keybindingId == keyboardHandler)
-                    _self.keyBinding.setKeyboardHandler(module && module.handler);
-            });
-        } else {
-            this.$keybindingId = null;
-            this.keyBinding.setKeyboardHandler(keyboardHandler);
-        }
-    };
-    this.getKeyboardHandler = function() {
-        return this.keyBinding.getKeyboardHandler();
-    };
-    this.setSession = function(session) {
-        if (this.session == session)
-            return;
-
-        if (this.session) {
-            var oldSession = this.session;
-            this.session.removeEventListener("change", this.$onDocumentChange);
-            this.session.removeEventListener("changeMode", this.$onChangeMode);
-            this.session.removeEventListener("tokenizerUpdate", this.$onTokenizerUpdate);
-            this.session.removeEventListener("changeTabSize", this.$onChangeTabSize);
-            this.session.removeEventListener("changeWrapLimit", this.$onChangeWrapLimit);
-            this.session.removeEventListener("changeWrapMode", this.$onChangeWrapMode);
-            this.session.removeEventListener("onChangeFold", this.$onChangeFold);
-            this.session.removeEventListener("changeFrontMarker", this.$onChangeFrontMarker);
-            this.session.removeEventListener("changeBackMarker", this.$onChangeBackMarker);
-            this.session.removeEventListener("changeBreakpoint", this.$onChangeBreakpoint);
-            this.session.removeEventListener("changeAnnotation", this.$onChangeAnnotation);
-            this.session.removeEventListener("changeOverwrite", this.$onCursorChange);
-            this.session.removeEventListener("changeScrollTop", this.$onScrollTopChange);
-            this.session.removeEventListener("changeScrollLeft", this.$onScrollLeftChange);
-
-            var selection = this.session.getSelection();
-            selection.removeEventListener("changeCursor", this.$onCursorChange);
-            selection.removeEventListener("changeSelection", this.$onSelectionChange);
-        }
-
-        this.session = session;
-
-        this.$onDocumentChange = this.onDocumentChange.bind(this);
-        session.addEventListener("change", this.$onDocumentChange);
-        this.renderer.setSession(session);
-
-        this.$onChangeMode = this.onChangeMode.bind(this);
-        session.addEventListener("changeMode", this.$onChangeMode);
-
-        this.$onTokenizerUpdate = this.onTokenizerUpdate.bind(this);
-        session.addEventListener("tokenizerUpdate", this.$onTokenizerUpdate);
-
-        this.$onChangeTabSize = this.renderer.onChangeTabSize.bind(this.renderer);
-        session.addEventListener("changeTabSize", this.$onChangeTabSize);
-
-        this.$onChangeWrapLimit = this.onChangeWrapLimit.bind(this);
-        session.addEventListener("changeWrapLimit", this.$onChangeWrapLimit);
-
-        this.$onChangeWrapMode = this.onChangeWrapMode.bind(this);
-        session.addEventListener("changeWrapMode", this.$onChangeWrapMode);
-
-        this.$onChangeFold = this.onChangeFold.bind(this);
-        session.addEventListener("changeFold", this.$onChangeFold);
-
-        this.$onChangeFrontMarker = this.onChangeFrontMarker.bind(this);
-        this.session.addEventListener("changeFrontMarker", this.$onChangeFrontMarker);
-
-        this.$onChangeBackMarker = this.onChangeBackMarker.bind(this);
-        this.session.addEventListener("changeBackMarker", this.$onChangeBackMarker);
-
-        this.$onChangeBreakpoint = this.onChangeBreakpoint.bind(this);
-        this.session.addEventListener("changeBreakpoint", this.$onChangeBreakpoint);
-
-        this.$onChangeAnnotation = this.onChangeAnnotation.bind(this);
-        this.session.addEventListener("changeAnnotation", this.$onChangeAnnotation);
-
-        this.$onCursorChange = this.onCursorChange.bind(this);
-        this.session.addEventListener("changeOverwrite", this.$onCursorChange);
-
-        this.$onScrollTopChange = this.onScrollTopChange.bind(this);
-        this.session.addEventListener("changeScrollTop", this.$onScrollTopChange);
-
-        this.$onScrollLeftChange = this.onScrollLeftChange.bind(this);
-        this.session.addEventListener("changeScrollLeft", this.$onScrollLeftChange);
-
-        this.selection = session.getSelection();
-        this.selection.addEventListener("changeCursor", this.$onCursorChange);
-
-        this.$onSelectionChange = this.onSelectionChange.bind(this);
-        this.selection.addEventListener("changeSelection", this.$onSelectionChange);
-
-        this.onChangeMode();
-
-        this.$blockScrolling += 1;
-        this.onCursorChange();
-        this.$blockScrolling -= 1;
-
-        this.onScrollTopChange();
-        this.onScrollLeftChange();
-        this.onSelectionChange();
-        this.onChangeFrontMarker();
-        this.onChangeBackMarker();
-        this.onChangeBreakpoint();
-        this.onChangeAnnotation();
-        this.session.getUseWrapMode() && this.renderer.adjustWrapLimit();
-        this.renderer.updateFull();
-
-        this._emit("changeSession", {
-            session: session,
-            oldSession: oldSession
-        });
-    };
-    this.getSession = function() {
-        return this.session;
-    };
-    this.setValue = function(val, cursorPos) {
-        this.session.doc.setValue(val);
-
-        if (!cursorPos)
-            this.selectAll();
-        else if (cursorPos == 1)
-            this.navigateFileEnd();
-        else if (cursorPos == -1)
-            this.navigateFileStart();
-
-        return val;
-    };
-    this.getValue = function() {
-        return this.session.getValue();
-    };
-    this.getSelection = function() {
-        return this.selection;
-    };
-    this.resize = function(force) {
-        this.renderer.onResize(force);
-    };
-    this.setTheme = function(theme) {
-        this.renderer.setTheme(theme);
-    };
-    this.getTheme = function() {
-        return this.renderer.getTheme();
-    };
-    this.setStyle = function(style) {
-        this.renderer.setStyle(style);
-    };
-    this.unsetStyle = function(style) {
-        this.renderer.unsetStyle(style);
-    };
-    this.getFontSize = function () {
-        return this.getOption("fontSize") ||
-           dom.computedStyle(this.container, "fontSize");
-    };
-    this.setFontSize = function(size) {
-        this.setOption("fontSize", size);
-    };
-
-    this.$highlightBrackets = function() {
-        if (this.session.$bracketHighlight) {
-            this.session.removeMarker(this.session.$bracketHighlight);
-            this.session.$bracketHighlight = null;
-        }
-
-        if (this.$highlightPending) {
-            return;
-        }
-        var self = this;
-        this.$highlightPending = true;
-        setTimeout(function() {
-            self.$highlightPending = false;
-
-            var pos = self.session.findMatchingBracket(self.getCursorPosition());
-            if (pos) {
-                var range = new Range(pos.row, pos.column, pos.row, pos.column+1);
-            } else if (self.session.$mode.getMatching) {
-                var range = self.session.$mode.getMatching(self.session);
-            }
-            if (range)
-                self.session.$bracketHighlight = self.session.addMarker(range, "ace_bracket", "text");
-        }, 50);
-    };
-    this.focus = function() {
-        var _self = this;
-        setTimeout(function() {
-            _self.textInput.focus();
-        });
-        this.textInput.focus();
-    };
-    this.isFocused = function() {
-        return this.textInput.isFocused();
-    };
-    this.blur = function() {
-        this.textInput.blur();
-    };
-    this.onFocus = function() {
-        if (this.$isFocused)
-            return;
-        this.$isFocused = true;
-        this.renderer.showCursor();
-        this.renderer.visualizeFocus();
-        this._emit("focus");
-    };
-    this.onBlur = function() {
-        if (!this.$isFocused)
-            return;
-        this.$isFocused = false;
-        this.renderer.hideCursor();
-        this.renderer.visualizeBlur();
-        this._emit("blur");
-    };
-
-    this.$cursorChange = function() {
-        this.renderer.updateCursor();
-    };
-    this.onDocumentChange = function(e) {
-        var delta = e.data;
-        var range = delta.range;
-        var lastRow;
-
-        if (range.start.row == range.end.row && delta.action != "insertLines" && delta.action != "removeLines")
-            lastRow = range.end.row;
-        else
-            lastRow = Infinity;
-        this.renderer.updateLines(range.start.row, lastRow);
-
-        this._emit("change", e);
-        this.$cursorChange();
-    };
-
-    this.onTokenizerUpdate = function(e) {
-        var rows = e.data;
-        this.renderer.updateLines(rows.first, rows.last);
-    };
-
-
-    this.onScrollTopChange = function() {
-        this.renderer.scrollToY(this.session.getScrollTop());
-    };
-
-    this.onScrollLeftChange = function() {
-        this.renderer.scrollToX(this.session.getScrollLeft());
-    };
-    this.onCursorChange = function() {
-        this.$cursorChange();
-
-        if (!this.$blockScrolling) {
-            this.renderer.scrollCursorIntoView();
-        }
-
-        this.$highlightBrackets();
-        this.$updateHighlightActiveLine();
-        this._emit("changeSelection");
-    };
-
-    this.$updateHighlightActiveLine = function() {
-        var session = this.getSession();
-
-        var highlight;
-        if (this.$highlightActiveLine) {
-            if ((this.$selectionStyle != "line" || !this.selection.isMultiLine()))
-                highlight = this.getCursorPosition();
-            if (this.renderer.$maxLines && this.session.getLength() === 1)
-                highlight = false;
-        }
-
-        if (session.$highlightLineMarker && !highlight) {
-            session.removeMarker(session.$highlightLineMarker.id);
-            session.$highlightLineMarker = null;
-        } else if (!session.$highlightLineMarker && highlight) {
-            var range = new Range(highlight.row, highlight.column, highlight.row, Infinity);
-            range.id = session.addMarker(range, "ace_active-line", "screenLine");
-            session.$highlightLineMarker = range;
-        } else if (highlight) {
-            session.$highlightLineMarker.start.row = highlight.row;
-            session.$highlightLineMarker.end.row = highlight.row;
-            session.$highlightLineMarker.start.column = highlight.column;
-            session._emit("changeBackMarker");
-        }
-    };
-
-    this.onSelectionChange = function(e) {
-        var session = this.session;
-
-        if (session.$selectionMarker) {
-            session.removeMarker(session.$selectionMarker);
-        }
-        session.$selectionMarker = null;
-
-        if (!this.selection.isEmpty()) {
-            var range = this.selection.getRange();
-            var style = this.getSelectionStyle();
-            session.$selectionMarker = session.addMarker(range, "ace_selection", style);
-        } else {
-            this.$updateHighlightActiveLine();
-        }
-
-        var re = this.$highlightSelectedWord && this.$getSelectionHighLightRegexp()
-        this.session.highlight(re);
-
-        this._emit("changeSelection");
-    };
-
-    this.$getSelectionHighLightRegexp = function() {
-        var session = this.session;
-
-        var selection = this.getSelectionRange();
-        if (selection.isEmpty() || selection.isMultiLine())
-            return;
-
-        var startOuter = selection.start.column - 1;
-        var endOuter = selection.end.column + 1;
-        var line = session.getLine(selection.start.row);
-        var lineCols = line.length;
-        var needle = line.substring(Math.max(startOuter, 0),
-                                    Math.min(endOuter, lineCols));
-        if ((startOuter >= 0 && /^[\w\d]/.test(needle)) ||
-            (endOuter <= lineCols && /[\w\d]$/.test(needle)))
-            return;
-
-        needle = line.substring(selection.start.column, selection.end.column);
-        if (!/^[\w\d]+$/.test(needle))
-            return;
-
-        var re = this.$search.$assembleRegExp({
-            wholeWord: true,
-            caseSensitive: true,
-            needle: needle
-        });
-
-        return re;
-    };
-
-
-    this.onChangeFrontMarker = function() {
-        this.renderer.updateFrontMarkers();
-    };
-
-    this.onChangeBackMarker = function() {
-        this.renderer.updateBackMarkers();
-    };
-
-
-    this.onChangeBreakpoint = function() {
-        this.renderer.updateBreakpoints();
-    };
-
-    this.onChangeAnnotation = function() {
-        this.renderer.setAnnotations(this.session.getAnnotations());
-    };
-
-
-    this.onChangeMode = function(e) {
-        this.renderer.updateText();
-        this._emit("changeMode", e);
-    };
-
-
-    this.onChangeWrapLimit = function() {
-        this.renderer.updateFull();
-    };
-
-    this.onChangeWrapMode = function() {
-        this.renderer.onResize(true);
-    };
-
-
-    this.onChangeFold = function() {
-        this.$updateHighlightActiveLine();
-        this.renderer.updateFull();
-    };
-    this.getSelectedText = function() {
-        return this.session.getTextRange(this.getSelectionRange());
-    };
-    this.getCopyText = function() {
-        var text = this.getSelectedText();
-        this._signal("copy", text);
-        return text;
-    };
-    this.onCopy = function() {
-        this.commands.exec("copy", this);
-    };
-    this.onCut = function() {
-        this.commands.exec("cut", this);
-    };
-    this.onPaste = function(text) {
-        if (this.$readOnly)
-            return;
-        this._emit("paste", text);
-        this.insert(text);
-    };
-
-
-    this.execCommand = function(command, args) {
-        this.commands.exec(command, this, args);
-    };
-    this.insert = function(text) {
-        var session = this.session;
-        var mode = session.getMode();
-        var cursor = this.getCursorPosition();
-
-        if (this.getBehavioursEnabled()) {
-            var transform = mode.transformAction(session.getState(cursor.row), 'insertion', this, session, text);
-            if (transform) {
-                if (text !== transform.text) {
-                    this.session.mergeUndoDeltas = false;
-                    this.$mergeNextCommand = false;
-                }
-                text = transform.text;
-
-            }
-        }
-        
-        if (text == "\t")
-            text = this.session.getTabString();
-        if (!this.selection.isEmpty()) {
-            var range = this.getSelectionRange();
-            cursor = this.session.remove(range);
-            this.clearSelection();
-        }
-        else if (this.session.getOverwrite()) {
-            var range = new Range.fromPoints(cursor, cursor);
-            range.end.column += text.length;
-            this.session.remove(range);
-        }
-
-        if (text == "\n" || text == "\r\n") {
-            var line = session.getLine(cursor.row)
-            if (cursor.column > line.search(/\S|$/)) {
-                var d = line.substr(cursor.column).search(/\S|$/);
-                session.doc.removeInLine(cursor.row, cursor.column, cursor.column + d);
-            }
-        }
-        this.clearSelection();
-
-        var start = cursor.column;
-        var lineState = session.getState(cursor.row);
-        var line = session.getLine(cursor.row);
-        var shouldOutdent = mode.checkOutdent(lineState, line, text);
-        var end = session.insert(cursor, text);
-
-        if (transform && transform.selection) {
-            if (transform.selection.length == 2) { // Transform relative to the current column
-                this.selection.setSelectionRange(
-                    new Range(cursor.row, start + transform.selection[0],
-                              cursor.row, start + transform.selection[1]));
-            } else { // Transform relative to the current row.
-                this.selection.setSelectionRange(
-                    new Range(cursor.row + transform.selection[0],
-                              transform.selection[1],
-                              cursor.row + transform.selection[2],
-                              transform.selection[3]));
-            }
-        }
-
-        if (session.getDocument().isNewLine(text)) {
-            var lineIndent = mode.getNextLineIndent(lineState, line.slice(0, cursor.column), session.getTabString());
-
-            session.insert({row: cursor.row+1, column: 0}, lineIndent);
-        }
-        if (shouldOutdent)
-            mode.autoOutdent(lineState, session, cursor.row);
-    };
-
-    this.onTextInput = function(text) {
-        this.keyBinding.onTextInput(text);
-    };
-
-    this.onCommandKey = function(e, hashId, keyCode) {
-        this.keyBinding.onCommandKey(e, hashId, keyCode);
-    };
-    this.setOverwrite = function(overwrite) {
-        this.session.setOverwrite(overwrite);
-    };
-    this.getOverwrite = function() {
-        return this.session.getOverwrite();
-    };
-    this.toggleOverwrite = function() {
-        this.session.toggleOverwrite();
-    };
-    this.setScrollSpeed = function(speed) {
-        this.setOption("scrollSpeed", speed);
-    };
-    this.getScrollSpeed = function() {
-        return this.getOption("scrollSpeed");
-    };
-    this.setDragDelay = function(dragDelay) {
-        this.setOption("dragDelay", dragDelay);
-    };
-    this.getDragDelay = function() {
-        return this.getOption("dragDelay");
-    };
-    this.setSelectionStyle = function(val) {
-        this.setOption("selectionStyle", val);
-    };
-    this.getSelectionStyle = function() {
-        return this.getOption("selectionStyle");
-    };
-    this.setHighlightActiveLine = function(shouldHighlight) {
-        this.setOption("highlightActiveLine", shouldHighlight);
-    };
-    this.getHighlightActiveLine = function() {
-        return this.getOption("highlightActiveLine");
-    };
-    this.setHighlightGutterLine = function(shouldHighlight) {
-        this.setOption("highlightGutterLine", shouldHighlight);
-    };
-
-    this.getHighlightGutterLine = function() {
-        return this.getOption("highlightGutterLine");
-    };
-    this.setHighlightSelectedWord = function(shouldHighlight) {
-        this.setOption("highlightSelectedWord", shouldHighlight);
-    };
-    this.getHighlightSelectedWord = function() {
-        return this.$highlightSelectedWord;
-    };
-
-    this.setAnimatedScroll = function(shouldAnimate){
-        this.renderer.setAnimatedScroll(shouldAnimate);
-    };
-
-    this.getAnimatedScroll = function(){
-        return this.renderer.getAnimatedScroll();
-    };
-    this.setShowInvisibles = function(showInvisibles) {
-        this.renderer.setShowInvisibles(showInvisibles);
-    };
-    this.getShowInvisibles = function() {
-        return this.renderer.getShowInvisibles();
-    };
-
-    this.setDisplayIndentGuides = function(display) {
-        this.renderer.setDisplayIndentGuides(display);
-    };
-
-    this.getDisplayIndentGuides = function() {
-        return this.renderer.getDisplayIndentGuides();
-    };
-    this.setShowPrintMargin = function(showPrintMargin) {
-        this.renderer.setShowPrintMargin(showPrintMargin);
-    };
-    this.getShowPrintMargin = function() {
-        return this.renderer.getShowPrintMargin();
-    };
-    this.setPrintMarginColumn = function(showPrintMargin) {
-        this.renderer.setPrintMarginColumn(showPrintMargin);
-    };
-    this.getPrintMarginColumn = function() {
-        return this.renderer.getPrintMarginColumn();
-    };
-    this.setReadOnly = function(readOnly) {
-        this.setOption("readOnly", readOnly);
-    };
-    this.getReadOnly = function() {
-        return this.getOption("readOnly");
-    };
-    this.setBehavioursEnabled = function (enabled) {
-        this.setOption("behavioursEnabled", enabled);
-    };
-    this.getBehavioursEnabled = function () {
-        return this.getOption("behavioursEnabled");
-    };
-    this.setWrapBehavioursEnabled = function (enabled) {
-        this.setOption("wrapBehavioursEnabled", enabled);
-    };
-    this.getWrapBehavioursEnabled = function () {
-        return this.getOption("wrapBehavioursEnabled");
-    };
-    this.setShowFoldWidgets = function(show) {
-        this.setOption("showFoldWidgets", show);
-
-    };
-    this.getShowFoldWidgets = function() {
-        return this.getOption("showFoldWidgets");
-    };
-
-    this.setFadeFoldWidgets = function(fade) {
-        this.setOption("fadeFoldWidgets", fade);
-    };
-
-    this.getFadeFoldWidgets = function() {
-        return this.getOption("fadeFoldWidgets");
-    };
-    this.remove = function(dir) {
-        if (this.selection.isEmpty()){
-            if (dir == "left")
-                this.selection.selectLeft();
-            else
-                this.selection.selectRight();
-        }
-
-        var range = this.getSelectionRange();
-        if (this.getBehavioursEnabled()) {
-            var session = this.session;
-            var state = session.getState(range.start.row);
-            var new_range = session.getMode().transformAction(state, 'deletion', this, session, range);
-
-            if (range.end.column == 0) {
-                var text = session.getTextRange(range);
-                if (text[text.length - 1] == "\n") {
-                    var line = session.getLine(range.end.row)
-                    if (/^\s+$/.test(line)) {
-                        range.end.column = line.length
-                    }
-                }
-            }
-            if (new_range)
-                range = new_range;
-        }
-
-        this.session.remove(range);
-        this.clearSelection();
-    };
-    this.removeWordRight = function() {
-        if (this.selection.isEmpty())
-            this.selection.selectWordRight();
-
-        this.session.remove(this.getSelectionRange());
-        this.clearSelection();
-    };
-    this.removeWordLeft = function() {
-        if (this.selection.isEmpty())
-            this.selection.selectWordLeft();
-
-        this.session.remove(this.getSelectionRange());
-        this.clearSelection();
-    };
-    this.removeToLineStart = function() {
-        if (this.selection.isEmpty())
-            this.selection.selectLineStart();
-
-        this.session.remove(this.getSelectionRange());
-        this.clearSelection();
-    };
-    this.removeToLineEnd = function() {
-        if (this.selection.isEmpty())
-            this.selection.selectLineEnd();
-
-        var range = this.getSelectionRange();
-        if (range.start.column == range.end.column && range.start.row == range.end.row) {
-            range.end.column = 0;
-            range.end.row++;
-        }
-
-        this.session.remove(range);
-        this.clearSelection();
-    };
-    this.splitLine = function() {
-        if (!this.selection.isEmpty()) {
-            this.session.remove(this.getSelectionRange());
-            this.clearSelection();
-        }
-
-        var cursor = this.getCursorPosition();
-        this.insert("\n");
-        this.moveCursorToPosition(cursor);
-    };
-    this.transposeLetters = function() {
-        if (!this.selection.isEmpty()) {
-            return;
-        }
-
-        var cursor = this.getCursorPosition();
-        var column = cursor.column;
-        if (column === 0)
-            return;
-
-        var line = this.session.getLine(cursor.row);
-        var swap, range;
-        if (column < line.length) {
-            swap = line.charAt(column) + line.charAt(column-1);
-            range = new Range(cursor.row, column-1, cursor.row, column+1);
-        }
-        else {
-            swap = line.charAt(column-1) + line.charAt(column-2);
-            range = new Range(cursor.row, column-2, cursor.row, column);
-        }
-        this.session.replace(range, swap);
-    };
-    this.toLowerCase = function() {
-        var originalRange = this.getSelectionRange();
-        if (this.selection.isEmpty()) {
-            this.selection.selectWord();
-        }
-
-        var range = this.getSelectionRange();
-        var text = this.session.getTextRange(range);
-        this.session.replace(range, text.toLowerCase());
-        this.selection.setSelectionRange(originalRange);
-    };
-    this.toUpperCase = function() {
-        var originalRange = this.getSelectionRange();
-        if (this.selection.isEmpty()) {
-            this.selection.selectWord();
-        }
-
-        var range = this.getSelectionRange();
-        var text = this.session.getTextRange(range);
-        this.session.replace(range, text.toUpperCase());
-        this.selection.setSelectionRange(originalRange);
-    };
-    this.indent = function() {
-        var session = this.session;
-        var range = this.getSelectionRange();
-
-        if (range.start.row < range.end.row) {
-            var rows = this.$getSelectedRows();
-            session.indentRows(rows.first, rows.last, "\t");
-            return;
-        } else if (range.start.column < range.end.column) {
-            var text = session.getTextRange(range)
-            if (!/^\s+$/.test(text)) {
-                var rows = this.$getSelectedRows();
-                session.indentRows(rows.first, rows.last, "\t");
-                return;
-            }
-        }
-        
-        var line = session.getLine(range.start.row)
-        var position = range.start;
-        var size = session.getTabSize();
-        var column = session.documentToScreenColumn(position.row, position.column);
-
-        if (this.session.getUseSoftTabs()) {
-            var count = (size - column % size);
-            var indentString = lang.stringRepeat(" ", count);
-        } else {
-            var count = column % size;
-            while (line[range.start.column] == " " && count) {
-                range.start.column--;
-                count--;
-            }
-            this.selection.setSelectionRange(range);
-            indentString = "\t";
-        }
-        return this.insert(indentString);
-    };
-    this.blockIndent = function() {
-        var rows = this.$getSelectedRows();
-        this.session.indentRows(rows.first, rows.last, "\t");
-    };
-    this.blockOutdent = function() {
-        var selection = this.session.getSelection();
-        this.session.outdentRows(selection.getRange());
-    };
-    this.sortLines = function() {
-        var rows = this.$getSelectedRows();
-        var session = this.session;
-
-        var lines = [];
-        for (i = rows.first; i <= rows.last; i++)
-            lines.push(session.getLine(i));
-
-        lines.sort(function(a, b) {
-            if (a.toLowerCase() < b.toLowerCase()) return -1;
-            if (a.toLowerCase() > b.toLowerCase()) return 1;
-            return 0;
-        });
-
-        var deleteRange = new Range(0, 0, 0, 0);
-        for (var i = rows.first; i <= rows.last; i++) {
-            var line = session.getLine(i);
-            deleteRange.start.row = i;
-            deleteRange.end.row = i;
-            deleteRange.end.column = line.length;
-            session.replace(deleteRange, lines[i-rows.first]);
-        }
-    };
-    this.toggleCommentLines = function() {
-        var state = this.session.getState(this.getCursorPosition().row);
-        var rows = this.$getSelectedRows();
-        this.session.getMode().toggleCommentLines(state, this.session, rows.first, rows.last);
-    };
-
-    this.toggleBlockComment = function() {
-        var cursor = this.getCursorPosition();
-        var state = this.session.getState(cursor.row);
-        var range = this.getSelectionRange();
-        this.session.getMode().toggleBlockComment(state, this.session, range, cursor);
-    };
-    this.getNumberAt = function( row, column ) {
-        var _numberRx = /[\-]?[0-9]+(?:\.[0-9]+)?/g
-        _numberRx.lastIndex = 0
-
-        var s = this.session.getLine(row)
-        while (_numberRx.lastIndex < column) {
-            var m = _numberRx.exec(s)
-            if(m.index <= column && m.index+m[0].length >= column){
-                var number = {
-                    value: m[0],
-                    start: m.index,
-                    end: m.index+m[0].length
-                }
-                return number;
-            }
-        }
-        return null;
-    };
-    this.modifyNumber = function(amount) {
-        var row = this.selection.getCursor().row;
-        var column = this.selection.getCursor().column;
-        var charRange = new Range(row, column-1, row, column);
-
-        var c = this.session.getTextRange(charRange);
-        if (!isNaN(parseFloat(c)) && isFinite(c)) {
-            var nr = this.getNumberAt(row, column);
-            if (nr) {
-                var fp = nr.value.indexOf(".") >= 0 ? nr.start + nr.value.indexOf(".") + 1 : nr.end;
-                var decimals = nr.start + nr.value.length - fp;
-
-                var t = parseFloat(nr.value);
-                t *= Math.pow(10, decimals);
-
-
-                if(fp !== nr.end && column < fp){
-                    amount *= Math.pow(10, nr.end - column - 1);
-                } else {
-                    amount *= Math.pow(10, nr.end - column);
-                }
-
-                t += amount;
-                t /= Math.pow(10, decimals);
-                var nnr = t.toFixed(decimals);
-                var replaceRange = new Range(row, nr.start, row, nr.end);
-                this.session.replace(replaceRange, nnr);
-                this.moveCursorTo(row, Math.max(nr.start +1, column + nnr.length - nr.value.length));
-
-            }
-        }
-    };
-    this.removeLines = function() {
-        var rows = this.$getSelectedRows();
-        var range;
-        if (rows.first === 0 || rows.last+1 < this.session.getLength())
-            range = new Range(rows.first, 0, rows.last+1, 0);
-        else
-            range = new Range(
-                rows.first-1, this.session.getLine(rows.first-1).length,
-                rows.last, this.session.getLine(rows.last).length
-            );
-        this.session.remove(range);
-        this.clearSelection();
-    };
-
-    this.duplicateSelection = function() {
-        var sel = this.selection;
-        var doc = this.session;
-        var range = sel.getRange();
-        var reverse = sel.isBackwards();
-      

<TRUNCATED>

[73/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/ubidi.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/ubidi.h b/src/apps/couch_collate/platform/osx/icu/unicode/ubidi.h
new file mode 100644
index 0000000..25f22b9
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/ubidi.h
@@ -0,0 +1,2013 @@
+/*
+******************************************************************************
+*
+*   Copyright (C) 1999-2008, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+*
+******************************************************************************
+*   file name:  ubidi.h
+*   encoding:   US-ASCII
+*   tab size:   8 (not used)
+*   indentation:4
+*
+*   created on: 1999jul27
+*   created by: Markus W. Scherer, updated by Matitiahu Allouche
+*/
+
+#ifndef UBIDI_H
+#define UBIDI_H
+
+#include "unicode/utypes.h"
+#include "unicode/uchar.h"
+
+/**
+ *\file
+ * \brief C API: Bidi algorithm
+ *
+ * <h2>Bidi algorithm for ICU</h2>
+ *
+ * This is an implementation of the Unicode Bidirectional algorithm.
+ * The algorithm is defined in the
+ * <a href="http://www.unicode.org/unicode/reports/tr9/">Unicode Standard Annex #9</a>,
+ * version 13, also described in The Unicode Standard, Version 4.0 .<p>
+ *
+ * Note: Libraries that perform a bidirectional algorithm and
+ * reorder strings accordingly are sometimes called "Storage Layout Engines".
+ * ICU's Bidi and shaping (u_shapeArabic()) APIs can be used at the core of such
+ * "Storage Layout Engines".
+ *
+ * <h3>General remarks about the API:</h3>
+ *
+ * In functions with an error code parameter,
+ * the <code>pErrorCode</code> pointer must be valid
+ * and the value that it points to must not indicate a failure before
+ * the function call. Otherwise, the function returns immediately.
+ * After the function call, the value indicates success or failure.<p>
+ *
+ * The &quot;limit&quot; of a sequence of characters is the position just after their
+ * last character, i.e., one more than that position.<p>
+ *
+ * Some of the API functions provide access to &quot;runs&quot;.
+ * Such a &quot;run&quot; is defined as a sequence of characters
+ * that are at the same embedding level
+ * after performing the Bidi algorithm.<p>
+ *
+ * @author Markus W. Scherer
+ * @version 1.0
+ *
+ *
+ * <h4> Sample code for the ICU Bidi API </h4>
+ *
+ * <h5>Rendering a paragraph with the ICU Bidi API</h5>
+ *
+ * This is (hypothetical) sample code that illustrates
+ * how the ICU Bidi API could be used to render a paragraph of text.
+ * Rendering code depends highly on the graphics system,
+ * therefore this sample code must make a lot of assumptions,
+ * which may or may not match any existing graphics system's properties.
+ *
+ * <p>The basic assumptions are:</p>
+ * <ul>
+ * <li>Rendering is done from left to right on a horizontal line.</li>
+ * <li>A run of single-style, unidirectional text can be rendered at once.</li>
+ * <li>Such a run of text is passed to the graphics system with
+ *     characters (code units) in logical order.</li>
+ * <li>The line-breaking algorithm is very complicated
+ *     and Locale-dependent -
+ *     and therefore its implementation omitted from this sample code.</li>
+ * </ul>
+ *
+ * <pre>
+ * \code
+ *#include "unicode/ubidi.h"
+ *
+ *typedef enum {
+ *     styleNormal=0, styleSelected=1,
+ *     styleBold=2, styleItalics=4,
+ *     styleSuper=8, styleSub=16
+ *} Style;
+ *
+ *typedef struct { int32_t limit; Style style; } StyleRun;
+ *
+ *int getTextWidth(const UChar *text, int32_t start, int32_t limit,
+ *                  const StyleRun *styleRuns, int styleRunCount);
+ *
+ * // set *pLimit and *pStyleRunLimit for a line
+ * // from text[start] and from styleRuns[styleRunStart]
+ * // using ubidi_getLogicalRun(para, ...)
+ *void getLineBreak(const UChar *text, int32_t start, int32_t *pLimit,
+ *                  UBiDi *para,
+ *                  const StyleRun *styleRuns, int styleRunStart, int *pStyleRunLimit,
+ *                  int *pLineWidth);
+ *
+ * // render runs on a line sequentially, always from left to right
+ *
+ * // prepare rendering a new line
+ * void startLine(UBiDiDirection textDirection, int lineWidth);
+ *
+ * // render a run of text and advance to the right by the run width
+ * // the text[start..limit-1] is always in logical order
+ * void renderRun(const UChar *text, int32_t start, int32_t limit,
+ *               UBiDiDirection textDirection, Style style);
+ *
+ * // We could compute a cross-product
+ * // from the style runs with the directional runs
+ * // and then reorder it.
+ * // Instead, here we iterate over each run type
+ * // and render the intersections -
+ * // with shortcuts in simple (and common) cases.
+ * // renderParagraph() is the main function.
+ *
+ * // render a directional run with
+ * // (possibly) multiple style runs intersecting with it
+ * void renderDirectionalRun(const UChar *text,
+ *                           int32_t start, int32_t limit,
+ *                           UBiDiDirection direction,
+ *                           const StyleRun *styleRuns, int styleRunCount) {
+ *     int i;
+ *
+ *     // iterate over style runs
+ *     if(direction==UBIDI_LTR) {
+ *         int styleLimit;
+ *
+ *         for(i=0; i<styleRunCount; ++i) {
+ *             styleLimit=styleRun[i].limit;
+ *             if(start<styleLimit) {
+ *                 if(styleLimit>limit) { styleLimit=limit; }
+ *                 renderRun(text, start, styleLimit,
+ *                           direction, styleRun[i].style);
+ *                 if(styleLimit==limit) { break; }
+ *                 start=styleLimit;
+ *             }
+ *         }
+ *     } else {
+ *         int styleStart;
+ *
+ *         for(i=styleRunCount-1; i>=0; --i) {
+ *             if(i>0) {
+ *                 styleStart=styleRun[i-1].limit;
+ *             } else {
+ *                 styleStart=0;
+ *             }
+ *             if(limit>=styleStart) {
+ *                 if(styleStart<start) { styleStart=start; }
+ *                 renderRun(text, styleStart, limit,
+ *                           direction, styleRun[i].style);
+ *                 if(styleStart==start) { break; }
+ *                 limit=styleStart;
+ *             }
+ *         }
+ *     }
+ * }
+ *
+ * // the line object represents text[start..limit-1]
+ * void renderLine(UBiDi *line, const UChar *text,
+ *                 int32_t start, int32_t limit,
+ *                 const StyleRun *styleRuns, int styleRunCount) {
+ *     UBiDiDirection direction=ubidi_getDirection(line);
+ *     if(direction!=UBIDI_MIXED) {
+ *         // unidirectional
+ *         if(styleRunCount<=1) {
+ *             renderRun(text, start, limit, direction, styleRuns[0].style);
+ *         } else {
+ *             renderDirectionalRun(text, start, limit,
+ *                                  direction, styleRuns, styleRunCount);
+ *         }
+ *     } else {
+ *         // mixed-directional
+ *         int32_t count, i, length;
+ *         UBiDiLevel level;
+ *
+ *         count=ubidi_countRuns(para, pErrorCode);
+ *         if(U_SUCCESS(*pErrorCode)) {
+ *             if(styleRunCount<=1) {
+ *                 Style style=styleRuns[0].style;
+ *
+ *                 // iterate over directional runs
+ *                for(i=0; i<count; ++i) {
+ *                    direction=ubidi_getVisualRun(para, i, &start, &length);
+ *                     renderRun(text, start, start+length, direction, style);
+ *                }
+ *             } else {
+ *                 int32_t j;
+ *
+ *                 // iterate over both directional and style runs
+ *                 for(i=0; i<count; ++i) {
+ *                     direction=ubidi_getVisualRun(line, i, &start, &length);
+ *                     renderDirectionalRun(text, start, start+length,
+ *                                          direction, styleRuns, styleRunCount);
+ *                 }
+ *             }
+ *         }
+ *     }
+ * }
+ *
+ *void renderParagraph(const UChar *text, int32_t length,
+ *                     UBiDiDirection textDirection,
+ *                      const StyleRun *styleRuns, int styleRunCount,
+ *                      int lineWidth,
+ *                      UErrorCode *pErrorCode) {
+ *     UBiDi *para;
+ *
+ *     if(pErrorCode==NULL || U_FAILURE(*pErrorCode) || length<=0) {
+ *         return;
+ *     }
+ *
+ *     para=ubidi_openSized(length, 0, pErrorCode);
+ *     if(para==NULL) { return; }
+ *
+ *     ubidi_setPara(para, text, length,
+ *                   textDirection ? UBIDI_DEFAULT_RTL : UBIDI_DEFAULT_LTR,
+ *                   NULL, pErrorCode);
+ *     if(U_SUCCESS(*pErrorCode)) {
+ *         UBiDiLevel paraLevel=1&ubidi_getParaLevel(para);
+ *         StyleRun styleRun={ length, styleNormal };
+ *         int width;
+ *
+ *         if(styleRuns==NULL || styleRunCount<=0) {
+ *            styleRunCount=1;
+ *             styleRuns=&styleRun;
+ *         }
+ *
+ *        // assume styleRuns[styleRunCount-1].limit>=length
+ *
+ *         width=getTextWidth(text, 0, length, styleRuns, styleRunCount);
+ *         if(width<=lineWidth) {
+ *             // everything fits onto one line
+ *
+ *            // prepare rendering a new line from either left or right
+ *             startLine(paraLevel, width);
+ *
+ *             renderLine(para, text, 0, length,
+ *                        styleRuns, styleRunCount);
+ *         } else {
+ *             UBiDi *line;
+ *
+ *             // we need to render several lines
+ *             line=ubidi_openSized(length, 0, pErrorCode);
+ *             if(line!=NULL) {
+ *                 int32_t start=0, limit;
+ *                 int styleRunStart=0, styleRunLimit;
+ *
+ *                 for(;;) {
+ *                     limit=length;
+ *                     styleRunLimit=styleRunCount;
+ *                     getLineBreak(text, start, &limit, para,
+ *                                  styleRuns, styleRunStart, &styleRunLimit,
+ *                                 &width);
+ *                     ubidi_setLine(para, start, limit, line, pErrorCode);
+ *                     if(U_SUCCESS(*pErrorCode)) {
+ *                         // prepare rendering a new line
+ *                         // from either left or right
+ *                         startLine(paraLevel, width);
+ *
+ *                         renderLine(line, text, start, limit,
+ *                                    styleRuns+styleRunStart,
+ *                                    styleRunLimit-styleRunStart);
+ *                     }
+ *                     if(limit==length) { break; }
+ *                     start=limit;
+ *                     styleRunStart=styleRunLimit-1;
+ *                     if(start>=styleRuns[styleRunStart].limit) {
+ *                         ++styleRunStart;
+ *                     }
+ *                 }
+ *
+ *                 ubidi_close(line);
+ *             }
+ *        }
+ *    }
+ *
+ *     ubidi_close(para);
+ *}
+ *\endcode
+ * </pre>
+ */
+
+/*DOCXX_TAG*/
+/*@{*/
+
+/**
+ * UBiDiLevel is the type of the level values in this
+ * Bidi implementation.
+ * It holds an embedding level and indicates the visual direction
+ * by its bit&nbsp;0 (even/odd value).<p>
+ *
+ * It can also hold non-level values for the
+ * <code>paraLevel</code> and <code>embeddingLevels</code>
+ * arguments of <code>ubidi_setPara()</code>; there:
+ * <ul>
+ * <li>bit&nbsp;7 of an <code>embeddingLevels[]</code>
+ * value indicates whether the using application is
+ * specifying the level of a character to <i>override</i> whatever the
+ * Bidi implementation would resolve it to.</li>
+ * <li><code>paraLevel</code> can be set to the
+ * pseudo-level values <code>UBIDI_DEFAULT_LTR</code>
+ * and <code>UBIDI_DEFAULT_RTL</code>.</li>
+ * </ul>
+ *
+ * @see ubidi_setPara
+ *
+ * <p>The related constants are not real, valid level values.
+ * <code>UBIDI_DEFAULT_XXX</code> can be used to specify
+ * a default for the paragraph level for
+ * when the <code>ubidi_setPara()</code> function
+ * shall determine it but there is no
+ * strongly typed character in the input.<p>
+ *
+ * Note that the value for <code>UBIDI_DEFAULT_LTR</code> is even
+ * and the one for <code>UBIDI_DEFAULT_RTL</code> is odd,
+ * just like with normal LTR and RTL level values -
+ * these special values are designed that way. Also, the implementation
+ * assumes that UBIDI_MAX_EXPLICIT_LEVEL is odd.
+ *
+ * @see UBIDI_DEFAULT_LTR
+ * @see UBIDI_DEFAULT_RTL
+ * @see UBIDI_LEVEL_OVERRIDE
+ * @see UBIDI_MAX_EXPLICIT_LEVEL
+ * @stable ICU 2.0
+ */
+typedef uint8_t UBiDiLevel;
+
+/** Paragraph level setting.<p>
+ *
+ * Constant indicating that the base direction depends on the first strong
+ * directional character in the text according to the Unicode Bidirectional
+ * Algorithm. If no strong directional character is present,
+ * then set the paragraph level to 0 (left-to-right).<p>
+ *
+ * If this value is used in conjunction with reordering modes
+ * <code>UBIDI_REORDER_INVERSE_LIKE_DIRECT</code> or
+ * <code>UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL</code>, the text to reorder
+ * is assumed to be visual LTR, and the text after reordering is required
+ * to be the corresponding logical string with appropriate contextual
+ * direction. The direction of the result string will be RTL if either
+ * the righmost or leftmost strong character of the source text is RTL
+ * or Arabic Letter, the direction will be LTR otherwise.<p>
+ *
+ * If reordering option <code>UBIDI_OPTION_INSERT_MARKS</code> is set, an RLM may
+ * be added at the beginning of the result string to ensure round trip
+ * (that the result string, when reordered back to visual, will produce
+ * the original source text).
+ * @see UBIDI_REORDER_INVERSE_LIKE_DIRECT
+ * @see UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL
+ * @stable ICU 2.0
+ */
+#define UBIDI_DEFAULT_LTR 0xfe
+
+/** Paragraph level setting.<p>
+ *
+ * Constant indicating that the base direction depends on the first strong
+ * directional character in the text according to the Unicode Bidirectional
+ * Algorithm. If no strong directional character is present,
+ * then set the paragraph level to 1 (right-to-left).<p>
+ *
+ * If this value is used in conjunction with reordering modes
+ * <code>UBIDI_REORDER_INVERSE_LIKE_DIRECT</code> or
+ * <code>UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL</code>, the text to reorder
+ * is assumed to be visual LTR, and the text after reordering is required
+ * to be the corresponding logical string with appropriate contextual
+ * direction. The direction of the result string will be RTL if either
+ * the righmost or leftmost strong character of the source text is RTL
+ * or Arabic Letter, or if the text contains no strong character;
+ * the direction will be LTR otherwise.<p>
+ *
+ * If reordering option <code>UBIDI_OPTION_INSERT_MARKS</code> is set, an RLM may
+ * be added at the beginning of the result string to ensure round trip
+ * (that the result string, when reordered back to visual, will produce
+ * the original source text).
+ * @see UBIDI_REORDER_INVERSE_LIKE_DIRECT
+ * @see UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL
+ * @stable ICU 2.0
+ */
+#define UBIDI_DEFAULT_RTL 0xff
+
+/**
+ * Maximum explicit embedding level.
+ * (The maximum resolved level can be up to <code>UBIDI_MAX_EXPLICIT_LEVEL+1</code>).
+ * @stable ICU 2.0
+ */
+#define UBIDI_MAX_EXPLICIT_LEVEL 61
+
+/** Bit flag for level input.
+ *  Overrides directional properties.
+ * @stable ICU 2.0
+ */
+#define UBIDI_LEVEL_OVERRIDE 0x80
+
+/**
+ * Special value which can be returned by the mapping functions when a logical
+ * index has no corresponding visual index or vice-versa. This may happen
+ * for the logical-to-visual mapping of a Bidi control when option
+ * <code>#UBIDI_OPTION_REMOVE_CONTROLS</code> is specified. This can also happen
+ * for the visual-to-logical mapping of a Bidi mark (LRM or RLM) inserted
+ * by option <code>#UBIDI_OPTION_INSERT_MARKS</code>.
+ * @see ubidi_getVisualIndex
+ * @see ubidi_getVisualMap
+ * @see ubidi_getLogicalIndex
+ * @see ubidi_getLogicalMap
+ * @stable ICU 3.6
+ */
+#define UBIDI_MAP_NOWHERE   (-1)
+
+/**
+ * <code>UBiDiDirection</code> values indicate the text direction.
+ * @stable ICU 2.0
+ */
+enum UBiDiDirection {
+    /** All left-to-right text. This is a 0 value. @stable ICU 2.0 */
+    UBIDI_LTR,
+    /** All right-to-left text. This is a 1 value. @stable ICU 2.0 */
+    UBIDI_RTL,
+    /** Mixed-directional text. @stable ICU 2.0 */
+    UBIDI_MIXED
+};
+
+/** @stable ICU 2.0 */
+typedef enum UBiDiDirection UBiDiDirection;
+
+/**
+ * Forward declaration of the <code>UBiDi</code> structure for the declaration of
+ * the API functions. Its fields are implementation-specific.<p>
+ * This structure holds information about a paragraph (or multiple paragraphs)
+ * of text with Bidi-algorithm-related details, or about one line of
+ * such a paragraph.<p>
+ * Reordering can be done on a line, or on one or more paragraphs which are
+ * then interpreted each as one single line.
+ * @stable ICU 2.0
+ */
+struct UBiDi;
+
+/** @stable ICU 2.0 */
+typedef struct UBiDi UBiDi;
+
+/**
+ * Allocate a <code>UBiDi</code> structure.
+ * Such an object is initially empty. It is assigned
+ * the Bidi properties of a piece of text containing one or more paragraphs
+ * by <code>ubidi_setPara()</code>
+ * or the Bidi properties of a line within a paragraph by
+ * <code>ubidi_setLine()</code>.<p>
+ * This object can be reused for as long as it is not deallocated
+ * by calling <code>ubidi_close()</code>.<p>
+ * <code>ubidi_setPara()</code> and <code>ubidi_setLine()</code> will allocate
+ * additional memory for internal structures as necessary.
+ *
+ * @return An empty <code>UBiDi</code> object.
+ * @stable ICU 2.0
+ */
+U_STABLE UBiDi * U_EXPORT2
+ubidi_open(void);
+
+/**
+ * Allocate a <code>UBiDi</code> structure with preallocated memory
+ * for internal structures.
+ * This function provides a <code>UBiDi</code> object like <code>ubidi_open()</code>
+ * with no arguments, but it also preallocates memory for internal structures
+ * according to the sizings supplied by the caller.<p>
+ * Subsequent functions will not allocate any more memory, and are thus
+ * guaranteed not to fail because of lack of memory.<p>
+ * The preallocation can be limited to some of the internal memory
+ * by setting some values to 0 here. That means that if, e.g.,
+ * <code>maxRunCount</code> cannot be reasonably predetermined and should not
+ * be set to <code>maxLength</code> (the only failproof value) to avoid
+ * wasting memory, then <code>maxRunCount</code> could be set to 0 here
+ * and the internal structures that are associated with it will be allocated
+ * on demand, just like with <code>ubidi_open()</code>.
+ *
+ * @param maxLength is the maximum text or line length that internal memory
+ *        will be preallocated for. An attempt to associate this object with a
+ *        longer text will fail, unless this value is 0, which leaves the allocation
+ *        up to the implementation.
+ *
+ * @param maxRunCount is the maximum anticipated number of same-level runs
+ *        that internal memory will be preallocated for. An attempt to access
+ *        visual runs on an object that was not preallocated for as many runs
+ *        as the text was actually resolved to will fail,
+ *        unless this value is 0, which leaves the allocation up to the implementation.<br><br>
+ *        The number of runs depends on the actual text and maybe anywhere between
+ *        1 and <code>maxLength</code>. It is typically small.
+ *
+ * @param pErrorCode must be a valid pointer to an error code value.
+ *
+ * @return An empty <code>UBiDi</code> object with preallocated memory.
+ * @stable ICU 2.0
+ */
+U_STABLE UBiDi * U_EXPORT2
+ubidi_openSized(int32_t maxLength, int32_t maxRunCount, UErrorCode *pErrorCode);
+
+/**
+ * <code>ubidi_close()</code> must be called to free the memory
+ * associated with a UBiDi object.<p>
+ *
+ * <strong>Important: </strong>
+ * A parent <code>UBiDi</code> object must not be destroyed or reused if
+ * it still has children.
+ * If a <code>UBiDi</code> object has become the <i>child</i>
+ * of another one (its <i>parent</i>) by calling
+ * <code>ubidi_setLine()</code>, then the child object must
+ * be destroyed (closed) or reused (by calling
+ * <code>ubidi_setPara()</code> or <code>ubidi_setLine()</code>)
+ * before the parent object.
+ *
+ * @param pBiDi is a <code>UBiDi</code> object.
+ *
+ * @see ubidi_setPara
+ * @see ubidi_setLine
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2
+ubidi_close(UBiDi *pBiDi);
+
+/**
+ * Modify the operation of the Bidi algorithm such that it
+ * approximates an "inverse Bidi" algorithm. This function
+ * must be called before <code>ubidi_setPara()</code>.
+ *
+ * <p>The normal operation of the Bidi algorithm as described
+ * in the Unicode Technical Report is to take text stored in logical
+ * (keyboard, typing) order and to determine the reordering of it for visual
+ * rendering.
+ * Some legacy systems store text in visual order, and for operations
+ * with standard, Unicode-based algorithms, the text needs to be transformed
+ * to logical order. This is effectively the inverse algorithm of the
+ * described Bidi algorithm. Note that there is no standard algorithm for
+ * this "inverse Bidi" and that the current implementation provides only an
+ * approximation of "inverse Bidi".</p>
+ *
+ * <p>With <code>isInverse</code> set to <code>TRUE</code>,
+ * this function changes the behavior of some of the subsequent functions
+ * in a way that they can be used for the inverse Bidi algorithm.
+ * Specifically, runs of text with numeric characters will be treated in a
+ * special way and may need to be surrounded with LRM characters when they are
+ * written in reordered sequence.</p>
+ *
+ * <p>Output runs should be retrieved using <code>ubidi_getVisualRun()</code>.
+ * Since the actual input for "inverse Bidi" is visually ordered text and
+ * <code>ubidi_getVisualRun()</code> gets the reordered runs, these are actually
+ * the runs of the logically ordered output.</p>
+ *
+ * <p>Calling this function with argument <code>isInverse</code> set to
+ * <code>TRUE</code> is equivalent to calling
+ * <code>ubidi_setReorderingMode</code> with argument
+ * <code>reorderingMode</code>
+ * set to <code>#UBIDI_REORDER_INVERSE_NUMBERS_AS_L</code>.<br>
+ * Calling this function with argument <code>isInverse</code> set to
+ * <code>FALSE</code> is equivalent to calling
+ * <code>ubidi_setReorderingMode</code> with argument
+ * <code>reorderingMode</code>
+ * set to <code>#UBIDI_REORDER_DEFAULT</code>.
+ *
+ * @param pBiDi is a <code>UBiDi</code> object.
+ *
+ * @param isInverse specifies "forward" or "inverse" Bidi operation.
+ *
+ * @see ubidi_setPara
+ * @see ubidi_writeReordered
+ * @see ubidi_setReorderingMode
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2
+ubidi_setInverse(UBiDi *pBiDi, UBool isInverse);
+
+/**
+ * Is this Bidi object set to perform the inverse Bidi algorithm?
+ * <p>Note: calling this function after setting the reordering mode with
+ * <code>ubidi_setReorderingMode</code> will return <code>TRUE</code> if the
+ * reordering mode was set to <code>#UBIDI_REORDER_INVERSE_NUMBERS_AS_L</code>,
+ * <code>FALSE</code> for all other values.</p>
+ *
+ * @param pBiDi is a <code>UBiDi</code> object.
+ * @return TRUE if the Bidi object is set to perform the inverse Bidi algorithm
+ * by handling numbers as L.
+ *
+ * @see ubidi_setInverse
+ * @see ubidi_setReorderingMode
+ * @stable ICU 2.0
+ */
+
+U_STABLE UBool U_EXPORT2
+ubidi_isInverse(UBiDi *pBiDi);
+
+/**
+ * Specify whether block separators must be allocated level zero,
+ * so that successive paragraphs will progress from left to right.
+ * This function must be called before <code>ubidi_setPara()</code>.
+ * Paragraph separators (B) may appear in the text.  Setting them to level zero
+ * means that all paragraph separators (including one possibly appearing
+ * in the last text position) are kept in the reordered text after the text
+ * that they follow in the source text.
+ * When this feature is not enabled, a paragraph separator at the last
+ * position of the text before reordering will go to the first position
+ * of the reordered text when the paragraph level is odd.
+ *
+ * @param pBiDi is a <code>UBiDi</code> object.
+ *
+ * @param orderParagraphsLTR specifies whether paragraph separators (B) must
+ * receive level 0, so that successive paragraphs progress from left to right.
+ *
+ * @see ubidi_setPara
+ * @stable ICU 3.4
+ */
+U_STABLE void U_EXPORT2
+ubidi_orderParagraphsLTR(UBiDi *pBiDi, UBool orderParagraphsLTR);
+
+/**
+ * Is this Bidi object set to allocate level 0 to block separators so that
+ * successive paragraphs progress from left to right?
+ *
+ * @param pBiDi is a <code>UBiDi</code> object.
+ * @return TRUE if the Bidi object is set to allocate level 0 to block
+ *         separators.
+ *
+ * @see ubidi_orderParagraphsLTR
+ * @stable ICU 3.4
+ */
+U_STABLE UBool U_EXPORT2
+ubidi_isOrderParagraphsLTR(UBiDi *pBiDi);
+
+/**
+ * <code>UBiDiReorderingMode</code> values indicate which variant of the Bidi
+ * algorithm to use.
+ *
+ * @see ubidi_setReorderingMode
+ * @stable ICU 3.6
+ */
+typedef enum UBiDiReorderingMode {
+    /** Regular Logical to Visual Bidi algorithm according to Unicode.
+      * This is a 0 value.
+      * @stable ICU 3.6 */
+    UBIDI_REORDER_DEFAULT = 0,
+    /** Logical to Visual algorithm which handles numbers in a way which
+      * mimicks the behavior of Windows XP.
+      * @stable ICU 3.6 */
+    UBIDI_REORDER_NUMBERS_SPECIAL,
+    /** Logical to Visual algorithm grouping numbers with adjacent R characters
+      * (reversible algorithm).
+      * @stable ICU 3.6 */
+    UBIDI_REORDER_GROUP_NUMBERS_WITH_R,
+    /** Reorder runs only to transform a Logical LTR string to the Logical RTL
+      * string with the same display, or vice-versa.<br>
+      * If this mode is set together with option
+      * <code>#UBIDI_OPTION_INSERT_MARKS</code>, some Bidi controls in the source
+      * text may be removed and other controls may be added to produce the
+      * minimum combination which has the required display.
+      * @stable ICU 3.6 */
+    UBIDI_REORDER_RUNS_ONLY,
+    /** Visual to Logical algorithm which handles numbers like L
+      * (same algorithm as selected by <code>ubidi_setInverse(TRUE)</code>.
+      * @see ubidi_setInverse
+      * @stable ICU 3.6 */
+    UBIDI_REORDER_INVERSE_NUMBERS_AS_L,
+    /** Visual to Logical algorithm equivalent to the regular Logical to Visual
+      * algorithm.
+      * @stable ICU 3.6 */
+    UBIDI_REORDER_INVERSE_LIKE_DIRECT,
+    /** Inverse Bidi (Visual to Logical) algorithm for the
+      * <code>UBIDI_REORDER_NUMBERS_SPECIAL</code> Bidi algorithm.
+      * @stable ICU 3.6 */
+    UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL,
+    /** Number of values for reordering mode.
+      * @stable ICU 3.6 */
+    UBIDI_REORDER_COUNT
+} UBiDiReorderingMode;
+
+/**
+ * Modify the operation of the Bidi algorithm such that it implements some
+ * variant to the basic Bidi algorithm or approximates an "inverse Bidi"
+ * algorithm, depending on different values of the "reordering mode".
+ * This function must be called before <code>ubidi_setPara()</code>, and stays
+ * in effect until called again with a different argument.
+ *
+ * <p>The normal operation of the Bidi algorithm as described
+ * in the Unicode Standard Annex #9 is to take text stored in logical
+ * (keyboard, typing) order and to determine how to reorder it for visual
+ * rendering.</p>
+ *
+ * <p>With the reordering mode set to a value other than
+ * <code>#UBIDI_REORDER_DEFAULT</code>, this function changes the behavior of
+ * some of the subsequent functions in a way such that they implement an
+ * inverse Bidi algorithm or some other algorithm variants.</p>
+ *
+ * <p>Some legacy systems store text in visual order, and for operations
+ * with standard, Unicode-based algorithms, the text needs to be transformed
+ * into logical order. This is effectively the inverse algorithm of the
+ * described Bidi algorithm. Note that there is no standard algorithm for
+ * this "inverse Bidi", so a number of variants are implemented here.</p>
+ *
+ * <p>In other cases, it may be desirable to emulate some variant of the
+ * Logical to Visual algorithm (e.g. one used in MS Windows), or perform a
+ * Logical to Logical transformation.</p>
+ *
+ * <ul>
+ * <li>When the reordering mode is set to <code>#UBIDI_REORDER_DEFAULT</code>,
+ * the standard Bidi Logical to Visual algorithm is applied.</li>
+ *
+ * <li>When the reordering mode is set to
+ * <code>#UBIDI_REORDER_NUMBERS_SPECIAL</code>,
+ * the algorithm used to perform Bidi transformations when calling
+ * <code>ubidi_setPara</code> should approximate the algorithm used in
+ * Microsoft Windows XP rather than strictly conform to the Unicode Bidi
+ * algorithm.
+ * <br>
+ * The differences between the basic algorithm and the algorithm addressed
+ * by this option are as follows:
+ * <ul>
+ *   <li>Within text at an even embedding level, the sequence "123AB"
+ *   (where AB represent R or AL letters) is transformed to "123BA" by the
+ *   Unicode algorithm and to "BA123" by the Windows algorithm.</li>
+ *   <li>Arabic-Indic numbers (AN) are handled by the Windows algorithm just
+ *   like regular numbers (EN).</li>
+ * </ul></li>
+ *
+ * <li>When the reordering mode is set to
+ * <code>#UBIDI_REORDER_GROUP_NUMBERS_WITH_R</code>,
+ * numbers located between LTR text and RTL text are associated with the RTL
+ * text. For instance, an LTR paragraph with content "abc 123 DEF" (where
+ * upper case letters represent RTL characters) will be transformed to
+ * "abc FED 123" (and not "abc 123 FED"), "DEF 123 abc" will be transformed
+ * to "123 FED abc" and "123 FED abc" will be transformed to "DEF 123 abc".
+ * This makes the algorithm reversible and makes it useful when round trip
+ * (from visual to logical and back to visual) must be achieved without
+ * adding LRM characters. However, this is a variation from the standard
+ * Unicode Bidi algorithm.<br>
+ * The source text should not contain Bidi control characters other than LRM
+ * or RLM.</li>
+ *
+ * <li>When the reordering mode is set to
+ * <code>#UBIDI_REORDER_RUNS_ONLY</code>,
+ * a "Logical to Logical" transformation must be performed:
+ * <ul>
+ * <li>If the default text level of the source text (argument <code>paraLevel</code>
+ * in <code>ubidi_setPara</code>) is even, the source text will be handled as
+ * LTR logical text and will be transformed to the RTL logical text which has
+ * the same LTR visual display.</li>
+ * <li>If the default level of the source text is odd, the source text
+ * will be handled as RTL logical text and will be transformed to the
+ * LTR logical text which has the same LTR visual display.</li>
+ * </ul>
+ * This mode may be needed when logical text which is basically Arabic or
+ * Hebrew, with possible included numbers or phrases in English, has to be
+ * displayed as if it had an even embedding level (this can happen if the
+ * displaying application treats all text as if it was basically LTR).
+ * <br>
+ * This mode may also be needed in the reverse case, when logical text which is
+ * basically English, with possible included phrases in Arabic or Hebrew, has to
+ * be displayed as if it had an odd embedding level.
+ * <br>
+ * Both cases could be handled by adding LRE or RLE at the head of the text,
+ * if the display subsystem supports these formatting controls. If it does not,
+ * the problem may be handled by transforming the source text in this mode
+ * before displaying it, so that it will be displayed properly.<br>
+ * The source text should not contain Bidi control characters other than LRM
+ * or RLM.</li>
+ *
+ * <li>When the reordering mode is set to
+ * <code>#UBIDI_REORDER_INVERSE_NUMBERS_AS_L</code>, an "inverse Bidi" algorithm
+ * is applied.
+ * Runs of text with numeric characters will be treated like LTR letters and
+ * may need to be surrounded with LRM characters when they are written in
+ * reordered sequence (the option <code>#UBIDI_INSERT_LRM_FOR_NUMERIC</code> can
+ * be used with function <code>ubidi_writeReordered</code> to this end. This
+ * mode is equivalent to calling <code>ubidi_setInverse()</code> with
+ * argument <code>isInverse</code> set to <code>TRUE</code>.</li>
+ *
+ * <li>When the reordering mode is set to
+ * <code>#UBIDI_REORDER_INVERSE_LIKE_DIRECT</code>, the "direct" Logical to Visual
+ * Bidi algorithm is used as an approximation of an "inverse Bidi" algorithm.
+ * This mode is similar to mode <code>#UBIDI_REORDER_INVERSE_NUMBERS_AS_L</code>
+ * but is closer to the regular Bidi algorithm.
+ * <br>
+ * For example, an LTR paragraph with the content "FED 123 456 CBA" (where
+ * upper case represents RTL characters) will be transformed to
+ * "ABC 456 123 DEF", as opposed to "DEF 123 456 ABC"
+ * with mode <code>UBIDI_REORDER_INVERSE_NUMBERS_AS_L</code>.<br>
+ * When used in conjunction with option
+ * <code>#UBIDI_OPTION_INSERT_MARKS</code>, this mode generally
+ * adds Bidi marks to the output significantly more sparingly than mode
+ * <code>#UBIDI_REORDER_INVERSE_NUMBERS_AS_L</code> with option
+ * <code>#UBIDI_INSERT_LRM_FOR_NUMERIC</code> in calls to
+ * <code>ubidi_writeReordered</code>.</li>
+ *
+ * <li>When the reordering mode is set to
+ * <code>#UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL</code>, the Logical to Visual
+ * Bidi algorithm used in Windows XP is used as an approximation of an
+ * "inverse Bidi" algorithm.
+ * <br>
+ * For example, an LTR paragraph with the content "abc FED123" (where
+ * upper case represents RTL characters) will be transformed to
+ * "abc 123DEF.</li>
+ * </ul>
+ *
+ * <p>In all the reordering modes specifying an "inverse Bidi" algorithm
+ * (i.e. those with a name starting with <code>UBIDI_REORDER_INVERSE</code>),
+ * output runs should be retrieved using
+ * <code>ubidi_getVisualRun()</code>, and the output text with
+ * <code>ubidi_writeReordered()</code>. The caller should keep in mind that in
+ * "inverse Bidi" modes the input is actually visually ordered text and
+ * reordered output returned by <code>ubidi_getVisualRun()</code> or
+ * <code>ubidi_writeReordered()</code> are actually runs or character string
+ * of logically ordered output.<br>
+ * For all the "inverse Bidi" modes, the source text should not contain
+ * Bidi control characters other than LRM or RLM.</p>
+ *
+ * <p>Note that option <code>#UBIDI_OUTPUT_REVERSE</code> of
+ * <code>ubidi_writeReordered</code> has no useful meaning and should not be
+ * used in conjunction with any value of the reordering mode specifying
+ * "inverse Bidi" or with value <code>UBIDI_REORDER_RUNS_ONLY</code>.
+ *
+ * @param pBiDi is a <code>UBiDi</code> object.
+ * @param reorderingMode specifies the required variant of the Bidi algorithm.
+ *
+ * @see UBiDiReorderingMode
+ * @see ubidi_setInverse
+ * @see ubidi_setPara
+ * @see ubidi_writeReordered
+ * @stable ICU 3.6
+ */
+U_STABLE void U_EXPORT2
+ubidi_setReorderingMode(UBiDi *pBiDi, UBiDiReorderingMode reorderingMode);
+
+/**
+ * What is the requested reordering mode for a given Bidi object?
+ *
+ * @param pBiDi is a <code>UBiDi</code> object.
+ * @return the current reordering mode of the Bidi object
+ * @see ubidi_setReorderingMode
+ * @stable ICU 3.6
+ */
+U_STABLE UBiDiReorderingMode U_EXPORT2
+ubidi_getReorderingMode(UBiDi *pBiDi);
+
+/**
+ * <code>UBiDiReorderingOption</code> values indicate which options are
+ * specified to affect the Bidi algorithm.
+ *
+ * @see ubidi_setReorderingOptions
+ * @stable ICU 3.6
+ */
+typedef enum UBiDiReorderingOption {
+    /**
+     * option value for <code>ubidi_setReorderingOptions</code>:
+     * disable all the options which can be set with this function
+     * @see ubidi_setReorderingOptions
+     * @stable ICU 3.6
+     */
+    UBIDI_OPTION_DEFAULT = 0,
+
+    /**
+     * option bit for <code>ubidi_setReorderingOptions</code>:
+     * insert Bidi marks (LRM or RLM) when needed to ensure correct result of
+     * a reordering to a Logical order
+     *
+     * <p>This option must be set or reset before calling
+     * <code>ubidi_setPara</code>.</p>
+     *
+     * <p>This option is significant only with reordering modes which generate
+     * a result with Logical order, specifically:</p>
+     * <ul>
+     *   <li><code>#UBIDI_REORDER_RUNS_ONLY</code></li>
+     *   <li><code>#UBIDI_REORDER_INVERSE_NUMBERS_AS_L</code></li>
+     *   <li><code>#UBIDI_REORDER_INVERSE_LIKE_DIRECT</code></li>
+     *   <li><code>#UBIDI_REORDER_INVERSE_FOR_NUMBERS_SPECIAL</code></li>
+     * </ul>
+     *
+     * <p>If this option is set in conjunction with reordering mode
+     * <code>#UBIDI_REORDER_INVERSE_NUMBERS_AS_L</code> or with calling
+     * <code>ubidi_setInverse(TRUE)</code>, it implies
+     * option <code>#UBIDI_INSERT_LRM_FOR_NUMERIC</code>
+     * in calls to function <code>ubidi_writeReordered()</code>.</p>
+     *
+     * <p>For other reordering modes, a minimum number of LRM or RLM characters
+     * will be added to the source text after reordering it so as to ensure
+     * round trip, i.e. when applying the inverse reordering mode on the
+     * resulting logical text with removal of Bidi marks
+     * (option <code>#UBIDI_OPTION_REMOVE_CONTROLS</code> set before calling
+     * <code>ubidi_setPara()</code> or option <code>#UBIDI_REMOVE_BIDI_CONTROLS</code>
+     * in <code>ubidi_writeReordered</code>), the result will be identical to the
+     * source text in the first transformation.
+     *
+     * <p>This option will be ignored if specified together with option
+     * <code>#UBIDI_OPTION_REMOVE_CONTROLS</code>. It inhibits option
+     * <code>UBIDI_REMOVE_BIDI_CONTROLS</code> in calls to function
+     * <code>ubidi_writeReordered()</code> and it implies option
+     * <code>#UBIDI_INSERT_LRM_FOR_NUMERIC</code> in calls to function
+     * <code>ubidi_writeReordered()</code> if the reordering mode is
+     * <code>#UBIDI_REORDER_INVERSE_NUMBERS_AS_L</code>.</p>
+     *
+     * @see ubidi_setReorderingMode
+     * @see ubidi_setReorderingOptions
+     * @stable ICU 3.6
+     */
+    UBIDI_OPTION_INSERT_MARKS = 1,
+
+    /**
+     * option bit for <code>ubidi_setReorderingOptions</code>:
+     * remove Bidi control characters
+     *
+     * <p>This option must be set or reset before calling
+     * <code>ubidi_setPara</code>.</p>
+     *
+     * <p>This option nullifies option <code>#UBIDI_OPTION_INSERT_MARKS</code>.
+     * It inhibits option <code>#UBIDI_INSERT_LRM_FOR_NUMERIC</code> in calls
+     * to function <code>ubidi_writeReordered()</code> and it implies option
+     * <code>#UBIDI_REMOVE_BIDI_CONTROLS</code> in calls to that function.</p>
+     *
+     * @see ubidi_setReorderingMode
+     * @see ubidi_setReorderingOptions
+     * @stable ICU 3.6
+     */
+    UBIDI_OPTION_REMOVE_CONTROLS = 2,
+
+    /**
+     * option bit for <code>ubidi_setReorderingOptions</code>:
+     * process the output as part of a stream to be continued
+     *
+     * <p>This option must be set or reset before calling
+     * <code>ubidi_setPara</code>.</p>
+     *
+     * <p>This option specifies that the caller is interested in processing large
+     * text object in parts.
+     * The results of the successive calls are expected to be concatenated by the
+     * caller. Only the call for the last part will have this option bit off.</p>
+     *
+     * <p>When this option bit is on, <code>ubidi_setPara()</code> may process
+     * less than the full source text in order to truncate the text at a meaningful
+     * boundary. The caller should call <code>ubidi_getProcessedLength()</code>
+     * immediately after calling <code>ubidi_setPara()</code> in order to
+     * determine how much of the source text has been processed.
+     * Source text beyond that length should be resubmitted in following calls to
+     * <code>ubidi_setPara</code>. The processed length may be less than
+     * the length of the source text if a character preceding the last character of
+     * the source text constitutes a reasonable boundary (like a block separator)
+     * for text to be continued.<br>
+     * If the last character of the source text constitutes a reasonable
+     * boundary, the whole text will be processed at once.<br>
+     * If nowhere in the source text there exists
+     * such a reasonable boundary, the processed length will be zero.<br>
+     * The caller should check for such an occurrence and do one of the following:
+     * <ul><li>submit a larger amount of text with a better chance to include
+     *         a reasonable boundary.</li>
+     *     <li>resubmit the same text after turning off option
+     *         <code>UBIDI_OPTION_STREAMING</code>.</li></ul>
+     * In all cases, this option should be turned off before processing the last
+     * part of the text.</p>
+     *
+     * <p>When the <code>UBIDI_OPTION_STREAMING</code> option is used,
+     * it is recommended to call <code>ubidi_orderParagraphsLTR()</code> with
+     * argument <code>orderParagraphsLTR</code> set to <code>TRUE</code> before
+     * calling <code>ubidi_setPara</code> so that later paragraphs may be
+     * concatenated to previous paragraphs on the right.</p>
+     *
+     * @see ubidi_setReorderingMode
+     * @see ubidi_setReorderingOptions
+     * @see ubidi_getProcessedLength
+     * @see ubidi_orderParagraphsLTR
+     * @stable ICU 3.6
+     */
+    UBIDI_OPTION_STREAMING = 4
+} UBiDiReorderingOption;
+
+/**
+ * Specify which of the reordering options
+ * should be applied during Bidi transformations.
+ *
+ * @param pBiDi is a <code>UBiDi</code> object.
+ * @param reorderingOptions is a combination of zero or more of the following
+ * options:
+ * <code>#UBIDI_OPTION_DEFAULT</code>, <code>#UBIDI_OPTION_INSERT_MARKS</code>,
+ * <code>#UBIDI_OPTION_REMOVE_CONTROLS</code>, <code>#UBIDI_OPTION_STREAMING</code>.
+ *
+ * @see ubidi_getReorderingOptions
+ * @stable ICU 3.6
+ */
+U_STABLE void U_EXPORT2
+ubidi_setReorderingOptions(UBiDi *pBiDi, uint32_t reorderingOptions);
+
+/**
+ * What are the reordering options applied to a given Bidi object?
+ *
+ * @param pBiDi is a <code>UBiDi</code> object.
+ * @return the current reordering options of the Bidi object
+ * @see ubidi_setReorderingOptions
+ * @stable ICU 3.6
+ */
+U_STABLE uint32_t U_EXPORT2
+ubidi_getReorderingOptions(UBiDi *pBiDi);
+
+/**
+ * Perform the Unicode Bidi algorithm. It is defined in the
+ * <a href="http://www.unicode.org/unicode/reports/tr9/">Unicode Standard Anned #9</a>,
+ * version 13,
+ * also described in The Unicode Standard, Version 4.0 .<p>
+ *
+ * This function takes a piece of plain text containing one or more paragraphs,
+ * with or without externally specified embedding levels from <i>styled</i>
+ * text and computes the left-right-directionality of each character.<p>
+ *
+ * If the entire text is all of the same directionality, then
+ * the function may not perform all the steps described by the algorithm,
+ * i.e., some levels may not be the same as if all steps were performed.
+ * This is not relevant for unidirectional text.<br>
+ * For example, in pure LTR text with numbers the numbers would get
+ * a resolved level of 2 higher than the surrounding text according to
+ * the algorithm. This implementation may set all resolved levels to
+ * the same value in such a case.<p>
+ *
+ * The text can be composed of multiple paragraphs. Occurrence of a block
+ * separator in the text terminates a paragraph, and whatever comes next starts
+ * a new paragraph. The exception to this rule is when a Carriage Return (CR)
+ * is followed by a Line Feed (LF). Both CR and LF are block separators, but
+ * in that case, the pair of characters is considered as terminating the
+ * preceding paragraph, and a new paragraph will be started by a character
+ * coming after the LF.
+ *
+ * @param pBiDi A <code>UBiDi</code> object allocated with <code>ubidi_open()</code>
+ *        which will be set to contain the reordering information,
+ *        especially the resolved levels for all the characters in <code>text</code>.
+ *
+ * @param text is a pointer to the text that the Bidi algorithm will be performed on.
+ *        This pointer is stored in the UBiDi object and can be retrieved
+ *        with <code>ubidi_getText()</code>.<br>
+ *        <strong>Note:</strong> the text must be (at least) <code>length</code> long.
+ *
+ * @param length is the length of the text; if <code>length==-1</code> then
+ *        the text must be zero-terminated.
+ *
+ * @param paraLevel specifies the default level for the text;
+ *        it is typically 0 (LTR) or 1 (RTL).
+ *        If the function shall determine the paragraph level from the text,
+ *        then <code>paraLevel</code> can be set to
+ *        either <code>#UBIDI_DEFAULT_LTR</code>
+ *        or <code>#UBIDI_DEFAULT_RTL</code>; if the text contains multiple
+ *        paragraphs, the paragraph level shall be determined separately for
+ *        each paragraph; if a paragraph does not include any strongly typed
+ *        character, then the desired default is used (0 for LTR or 1 for RTL).
+ *        Any other value between 0 and <code>#UBIDI_MAX_EXPLICIT_LEVEL</code>
+ *        is also valid, with odd levels indicating RTL.
+ *
+ * @param embeddingLevels (in) may be used to preset the embedding and override levels,
+ *        ignoring characters like LRE and PDF in the text.
+ *        A level overrides the directional property of its corresponding
+ *        (same index) character if the level has the
+ *        <code>#UBIDI_LEVEL_OVERRIDE</code> bit set.<br><br>
+ *        Except for that bit, it must be
+ *        <code>paraLevel<=embeddingLevels[]<=UBIDI_MAX_EXPLICIT_LEVEL</code>,
+ *        with one exception: a level of zero may be specified for a paragraph
+ *        separator even if <code>paraLevel>0</code> when multiple paragraphs
+ *        are submitted in the same call to <code>ubidi_setPara()</code>.<br><br>
+ *        <strong>Caution: </strong>A copy of this pointer, not of the levels,
+ *        will be stored in the <code>UBiDi</code> object;
+ *        the <code>embeddingLevels</code> array must not be
+ *        deallocated before the <code>UBiDi</code> structure is destroyed or reused,
+ *        and the <code>embeddingLevels</code>
+ *        should not be modified to avoid unexpected results on subsequent Bidi operations.
+ *        However, the <code>ubidi_setPara()</code> and
+ *        <code>ubidi_setLine()</code> functions may modify some or all of the levels.<br><br>
+ *        After the <code>UBiDi</code> object is reused or destroyed, the caller
+ *        must take care of the deallocation of the <code>embeddingLevels</code> array.<br><br>
+ *        <strong>Note:</strong> the <code>embeddingLevels</code> array must be
+ *        at least <code>length</code> long.
+ *
+ * @param pErrorCode must be a valid pointer to an error code value.
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2
+ubidi_setPara(UBiDi *pBiDi, const UChar *text, int32_t length,
+              UBiDiLevel paraLevel, UBiDiLevel *embeddingLevels,
+              UErrorCode *pErrorCode);
+
+/**
+ * <code>ubidi_setLine()</code> sets a <code>UBiDi</code> to
+ * contain the reordering information, especially the resolved levels,
+ * for all the characters in a line of text. This line of text is
+ * specified by referring to a <code>UBiDi</code> object representing
+ * this information for a piece of text containing one or more paragraphs,
+ * and by specifying a range of indexes in this text.<p>
+ * In the new line object, the indexes will range from 0 to <code>limit-start-1</code>.<p>
+ *
+ * This is used after calling <code>ubidi_setPara()</code>
+ * for a piece of text, and after line-breaking on that text.
+ * It is not necessary if each paragraph is treated as a single line.<p>
+ *
+ * After line-breaking, rules (L1) and (L2) for the treatment of
+ * trailing WS and for reordering are performed on
+ * a <code>UBiDi</code> object that represents a line.<p>
+ *
+ * <strong>Important: </strong><code>pLineBiDi</code> shares data with
+ * <code>pParaBiDi</code>.
+ * You must destroy or reuse <code>pLineBiDi</code> before <code>pParaBiDi</code>.
+ * In other words, you must destroy or reuse the <code>UBiDi</code> object for a line
+ * before the object for its parent paragraph.<p>
+ *
+ * The text pointer that was stored in <code>pParaBiDi</code> is also copied,
+ * and <code>start</code> is added to it so that it points to the beginning of the
+ * line for this object.
+ *
+ * @param pParaBiDi is the parent paragraph object. It must have been set
+ * by a successful call to ubidi_setPara.
+ *
+ * @param start is the line's first index into the text.
+ *
+ * @param limit is just behind the line's last index into the text
+ *        (its last index +1).<br>
+ *        It must be <code>0<=start<limit<=</code>containing paragraph limit.
+ *        If the specified line crosses a paragraph boundary, the function
+ *        will terminate with error code U_ILLEGAL_ARGUMENT_ERROR.
+ *
+ * @param pLineBiDi is the object that will now represent a line of the text.
+ *
+ * @param pErrorCode must be a valid pointer to an error code value.
+ *
+ * @see ubidi_setPara
+ * @see ubidi_getProcessedLength
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2
+ubidi_setLine(const UBiDi *pParaBiDi,
+              int32_t start, int32_t limit,
+              UBiDi *pLineBiDi,
+              UErrorCode *pErrorCode);
+
+/**
+ * Get the directionality of the text.
+ *
+ * @param pBiDi is the paragraph or line <code>UBiDi</code> object.
+ *
+ * @return a value of <code>UBIDI_LTR</code>, <code>UBIDI_RTL</code>
+ *         or <code>UBIDI_MIXED</code>
+ *         that indicates if the entire text
+ *         represented by this object is unidirectional,
+ *         and which direction, or if it is mixed-directional.
+ *
+ * @see UBiDiDirection
+ * @stable ICU 2.0
+ */
+U_STABLE UBiDiDirection U_EXPORT2
+ubidi_getDirection(const UBiDi *pBiDi);
+
+/**
+ * Get the pointer to the text.
+ *
+ * @param pBiDi is the paragraph or line <code>UBiDi</code> object.
+ *
+ * @return The pointer to the text that the UBiDi object was created for.
+ *
+ * @see ubidi_setPara
+ * @see ubidi_setLine
+ * @stable ICU 2.0
+ */
+U_STABLE const UChar * U_EXPORT2
+ubidi_getText(const UBiDi *pBiDi);
+
+/**
+ * Get the length of the text.
+ *
+ * @param pBiDi is the paragraph or line <code>UBiDi</code> object.
+ *
+ * @return The length of the text that the UBiDi object was created for.
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+ubidi_getLength(const UBiDi *pBiDi);
+
+/**
+ * Get the paragraph level of the text.
+ *
+ * @param pBiDi is the paragraph or line <code>UBiDi</code> object.
+ *
+ * @return The paragraph level. If there are multiple paragraphs, their
+ *         level may vary if the required paraLevel is UBIDI_DEFAULT_LTR or
+ *         UBIDI_DEFAULT_RTL.  In that case, the level of the first paragraph
+ *         is returned.
+ *
+ * @see UBiDiLevel
+ * @see ubidi_getParagraph
+ * @see ubidi_getParagraphByIndex
+ * @stable ICU 2.0
+ */
+U_STABLE UBiDiLevel U_EXPORT2
+ubidi_getParaLevel(const UBiDi *pBiDi);
+
+/**
+ * Get the number of paragraphs.
+ *
+ * @param pBiDi is the paragraph or line <code>UBiDi</code> object.
+ *
+ * @return The number of paragraphs.
+ * @stable ICU 3.4
+ */
+U_STABLE int32_t U_EXPORT2
+ubidi_countParagraphs(UBiDi *pBiDi);
+
+/**
+ * Get a paragraph, given a position within the text.
+ * This function returns information about a paragraph.<br>
+ * Note: if the paragraph index is known, it is more efficient to
+ * retrieve the paragraph information using ubidi_getParagraphByIndex().<p>
+ *
+ * @param pBiDi is the paragraph or line <code>UBiDi</code> object.
+ *
+ * @param charIndex is the index of a character within the text, in the
+ *        range <code>[0..ubidi_getProcessedLength(pBiDi)-1]</code>.
+ *
+ * @param pParaStart will receive the index of the first character of the
+ *        paragraph in the text.
+ *        This pointer can be <code>NULL</code> if this
+ *        value is not necessary.
+ *
+ * @param pParaLimit will receive the limit of the paragraph.
+ *        The l-value that you point to here may be the
+ *        same expression (variable) as the one for
+ *        <code>charIndex</code>.
+ *        This pointer can be <code>NULL</code> if this
+ *        value is not necessary.
+ *
+ * @param pParaLevel will receive the level of the paragraph.
+ *        This pointer can be <code>NULL</code> if this
+ *        value is not necessary.
+ *
+ * @param pErrorCode must be a valid pointer to an error code value.
+ *
+ * @return The index of the paragraph containing the specified position.
+ *
+ * @see ubidi_getProcessedLength
+ * @stable ICU 3.4
+ */
+U_STABLE int32_t U_EXPORT2
+ubidi_getParagraph(const UBiDi *pBiDi, int32_t charIndex, int32_t *pParaStart,
+                   int32_t *pParaLimit, UBiDiLevel *pParaLevel,
+                   UErrorCode *pErrorCode);
+
+/**
+ * Get a paragraph, given the index of this paragraph.
+ *
+ * This function returns information about a paragraph.<p>
+ *
+ * @param pBiDi is the paragraph <code>UBiDi</code> object.
+ *
+ * @param paraIndex is the number of the paragraph, in the
+ *        range <code>[0..ubidi_countParagraphs(pBiDi)-1]</code>.
+ *
+ * @param pParaStart will receive the index of the first character of the
+ *        paragraph in the text.
+ *        This pointer can be <code>NULL</code> if this
+ *        value is not necessary.
+ *
+ * @param pParaLimit will receive the limit of the paragraph.
+ *        This pointer can be <code>NULL</code> if this
+ *        value is not necessary.
+ *
+ * @param pParaLevel will receive the level of the paragraph.
+ *        This pointer can be <code>NULL</code> if this
+ *        value is not necessary.
+ *
+ * @param pErrorCode must be a valid pointer to an error code value.
+ *
+ * @stable ICU 3.4
+ */
+U_STABLE void U_EXPORT2
+ubidi_getParagraphByIndex(const UBiDi *pBiDi, int32_t paraIndex,
+                          int32_t *pParaStart, int32_t *pParaLimit,
+                          UBiDiLevel *pParaLevel, UErrorCode *pErrorCode);
+
+/**
+ * Get the level for one character.
+ *
+ * @param pBiDi is the paragraph or line <code>UBiDi</code> object.
+ *
+ * @param charIndex the index of a character. It must be in the range
+ *         [0..ubidi_getProcessedLength(pBiDi)].
+ *
+ * @return The level for the character at charIndex (0 if charIndex is not
+ *         in the valid range).
+ *
+ * @see UBiDiLevel
+ * @see ubidi_getProcessedLength
+ * @stable ICU 2.0
+ */
+U_STABLE UBiDiLevel U_EXPORT2
+ubidi_getLevelAt(const UBiDi *pBiDi, int32_t charIndex);
+
+/**
+ * Get an array of levels for each character.<p>
+ *
+ * Note that this function may allocate memory under some
+ * circumstances, unlike <code>ubidi_getLevelAt()</code>.
+ *
+ * @param pBiDi is the paragraph or line <code>UBiDi</code> object, whose
+ *        text length must be strictly positive.
+ *
+ * @param pErrorCode must be a valid pointer to an error code value.
+ *
+ * @return The levels array for the text,
+ *         or <code>NULL</code> if an error occurs.
+ *
+ * @see UBiDiLevel
+ * @see ubidi_getProcessedLength
+ * @stable ICU 2.0
+ */
+U_STABLE const UBiDiLevel * U_EXPORT2
+ubidi_getLevels(UBiDi *pBiDi, UErrorCode *pErrorCode);
+
+/**
+ * Get a logical run.
+ * This function returns information about a run and is used
+ * to retrieve runs in logical order.<p>
+ * This is especially useful for line-breaking on a paragraph.
+ *
+ * @param pBiDi is the paragraph or line <code>UBiDi</code> object.
+ *
+ * @param logicalPosition is a logical position within the source text.
+ *
+ * @param pLogicalLimit will receive the limit of the corresponding run.
+ *        The l-value that you point to here may be the
+ *        same expression (variable) as the one for
+ *        <code>logicalPosition</code>.
+ *        This pointer can be <code>NULL</code> if this
+ *        value is not necessary.
+ *
+ * @param pLevel will receive the level of the corresponding run.
+ *        This pointer can be <code>NULL</code> if this
+ *        value is not necessary.
+ *
+ * @see ubidi_getProcessedLength
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2
+ubidi_getLogicalRun(const UBiDi *pBiDi, int32_t logicalPosition,
+                    int32_t *pLogicalLimit, UBiDiLevel *pLevel);
+
+/**
+ * Get the number of runs.
+ * This function may invoke the actual reordering on the
+ * <code>UBiDi</code> object, after <code>ubidi_setPara()</code>
+ * may have resolved only the levels of the text. Therefore,
+ * <code>ubidi_countRuns()</code> may have to allocate memory,
+ * and may fail doing so.
+ *
+ * @param pBiDi is the paragraph or line <code>UBiDi</code> object.
+ *
+ * @param pErrorCode must be a valid pointer to an error code value.
+ *
+ * @return The number of runs.
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+ubidi_countRuns(UBiDi *pBiDi, UErrorCode *pErrorCode);
+
+/**
+ * Get one run's logical start, length, and directionality,
+ * which can be 0 for LTR or 1 for RTL.
+ * In an RTL run, the character at the logical start is
+ * visually on the right of the displayed run.
+ * The length is the number of characters in the run.<p>
+ * <code>ubidi_countRuns()</code> should be called
+ * before the runs are retrieved.
+ *
+ * @param pBiDi is the paragraph or line <code>UBiDi</code> object.
+ *
+ * @param runIndex is the number of the run in visual order, in the
+ *        range <code>[0..ubidi_countRuns(pBiDi)-1]</code>.
+ *
+ * @param pLogicalStart is the first logical character index in the text.
+ *        The pointer may be <code>NULL</code> if this index is not needed.
+ *
+ * @param pLength is the number of characters (at least one) in the run.
+ *        The pointer may be <code>NULL</code> if this is not needed.
+ *
+ * @return the directionality of the run,
+ *         <code>UBIDI_LTR==0</code> or <code>UBIDI_RTL==1</code>,
+ *         never <code>UBIDI_MIXED</code>.
+ *
+ * @see ubidi_countRuns
+ *
+ * Example:
+ * <pre>
+ * \code
+ * int32_t i, count=ubidi_countRuns(pBiDi),
+ *         logicalStart, visualIndex=0, length;
+ * for(i=0; i<count; ++i) {
+ *    if(UBIDI_LTR==ubidi_getVisualRun(pBiDi, i, &logicalStart, &length)) {
+ *         do { // LTR
+ *             show_char(text[logicalStart++], visualIndex++);
+ *         } while(--length>0);
+ *     } else {
+ *         logicalStart+=length;  // logicalLimit
+ *         do { // RTL
+ *             show_char(text[--logicalStart], visualIndex++);
+ *         } while(--length>0);
+ *     }
+ * }
+ *\endcode
+ * </pre>
+ *
+ * Note that in right-to-left runs, code like this places
+ * second surrogates before first ones (which is generally a bad idea)
+ * and combining characters before base characters.
+ * <p>
+ * Use of <code>ubidi_writeReordered()</code>, optionally with the
+ * <code>#UBIDI_KEEP_BASE_COMBINING</code> option, can be considered in order
+ * to avoid these issues.
+ * @stable ICU 2.0
+ */
+U_STABLE UBiDiDirection U_EXPORT2
+ubidi_getVisualRun(UBiDi *pBiDi, int32_t runIndex,
+                   int32_t *pLogicalStart, int32_t *pLength);
+
+/**
+ * Get the visual position from a logical text position.
+ * If such a mapping is used many times on the same
+ * <code>UBiDi</code> object, then calling
+ * <code>ubidi_getLogicalMap()</code> is more efficient.<p>
+ *
+ * The value returned may be <code>#UBIDI_MAP_NOWHERE</code> if there is no
+ * visual position because the corresponding text character is a Bidi control
+ * removed from output by the option <code>#UBIDI_OPTION_REMOVE_CONTROLS</code>.
+ * <p>
+ * When the visual output is altered by using options of
+ * <code>ubidi_writeReordered()</code> such as <code>UBIDI_INSERT_LRM_FOR_NUMERIC</code>,
+ * <code>UBIDI_KEEP_BASE_COMBINING</code>, <code>UBIDI_OUTPUT_REVERSE</code>,
+ * <code>UBIDI_REMOVE_BIDI_CONTROLS</code>, the visual position returned may not
+ * be correct. It is advised to use, when possible, reordering options
+ * such as <code>UBIDI_OPTION_INSERT_MARKS</code> and <code>UBIDI_OPTION_REMOVE_CONTROLS</code>.
+ * <p>
+ * Note that in right-to-left runs, this mapping places
+ * second surrogates before first ones (which is generally a bad idea)
+ * and combining characters before base characters.
+ * Use of <code>ubidi_writeReordered()</code>, optionally with the
+ * <code>#UBIDI_KEEP_BASE_COMBINING</code> option can be considered instead
+ * of using the mapping, in order to avoid these issues.
+ *
+ * @param pBiDi is the paragraph or line <code>UBiDi</code> object.
+ *
+ * @param logicalIndex is the index of a character in the text.
+ *
+ * @param pErrorCode must be a valid pointer to an error code value.
+ *
+ * @return The visual position of this character.
+ *
+ * @see ubidi_getLogicalMap
+ * @see ubidi_getLogicalIndex
+ * @see ubidi_getProcessedLength
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+ubidi_getVisualIndex(UBiDi *pBiDi, int32_t logicalIndex, UErrorCode *pErrorCode);
+
+/**
+ * Get the logical text position from a visual position.
+ * If such a mapping is used many times on the same
+ * <code>UBiDi</code> object, then calling
+ * <code>ubidi_getVisualMap()</code> is more efficient.<p>
+ *
+ * The value returned may be <code>#UBIDI_MAP_NOWHERE</code> if there is no
+ * logical position because the corresponding text character is a Bidi mark
+ * inserted in the output by option <code>#UBIDI_OPTION_INSERT_MARKS</code>.
+ * <p>
+ * This is the inverse function to <code>ubidi_getVisualIndex()</code>.
+ * <p>
+ * When the visual output is altered by using options of
+ * <code>ubidi_writeReordered()</code> such as <code>UBIDI_INSERT_LRM_FOR_NUMERIC</code>,
+ * <code>UBIDI_KEEP_BASE_COMBINING</code>, <code>UBIDI_OUTPUT_REVERSE</code>,
+ * <code>UBIDI_REMOVE_BIDI_CONTROLS</code>, the logical position returned may not
+ * be correct. It is advised to use, when possible, reordering options
+ * such as <code>UBIDI_OPTION_INSERT_MARKS</code> and <code>UBIDI_OPTION_REMOVE_CONTROLS</code>.
+ *
+ * @param pBiDi is the paragraph or line <code>UBiDi</code> object.
+ *
+ * @param visualIndex is the visual position of a character.
+ *
+ * @param pErrorCode must be a valid pointer to an error code value.
+ *
+ * @return The index of this character in the text.
+ *
+ * @see ubidi_getVisualMap
+ * @see ubidi_getVisualIndex
+ * @see ubidi_getResultLength
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+ubidi_getLogicalIndex(UBiDi *pBiDi, int32_t visualIndex, UErrorCode *pErrorCode);
+
+/**
+ * Get a logical-to-visual index map (array) for the characters in the UBiDi
+ * (paragraph or line) object.
+ * <p>
+ * Some values in the map may be <code>#UBIDI_MAP_NOWHERE</code> if the
+ * corresponding text characters are Bidi controls removed from the visual
+ * output by the option <code>#UBIDI_OPTION_REMOVE_CONTROLS</code>.
+ * <p>
+ * When the visual output is altered by using options of
+ * <code>ubidi_writeReordered()</code> such as <code>UBIDI_INSERT_LRM_FOR_NUMERIC</code>,
+ * <code>UBIDI_KEEP_BASE_COMBINING</code>, <code>UBIDI_OUTPUT_REVERSE</code>,
+ * <code>UBIDI_REMOVE_BIDI_CONTROLS</code>, the visual positions returned may not
+ * be correct. It is advised to use, when possible, reordering options
+ * such as <code>UBIDI_OPTION_INSERT_MARKS</code> and <code>UBIDI_OPTION_REMOVE_CONTROLS</code>.
+ * <p>
+ * Note that in right-to-left runs, this mapping places
+ * second surrogates before first ones (which is generally a bad idea)
+ * and combining characters before base characters.
+ * Use of <code>ubidi_writeReordered()</code>, optionally with the
+ * <code>#UBIDI_KEEP_BASE_COMBINING</code> option can be considered instead
+ * of using the mapping, in order to avoid these issues.
+ *
+ * @param pBiDi is the paragraph or line <code>UBiDi</code> object.
+ *
+ * @param indexMap is a pointer to an array of <code>ubidi_getProcessedLength()</code>
+ *        indexes which will reflect the reordering of the characters.
+ *        If option <code>#UBIDI_OPTION_INSERT_MARKS</code> is set, the number
+ *        of elements allocated in <code>indexMap</code> must be no less than
+ *        <code>ubidi_getResultLength()</code>.
+ *        The array does not need to be initialized.<br><br>
+ *        The index map will result in <code>indexMap[logicalIndex]==visualIndex</code>.
+ *
+ * @param pErrorCode must be a valid pointer to an error code value.
+ *
+ * @see ubidi_getVisualMap
+ * @see ubidi_getVisualIndex
+ * @see ubidi_getProcessedLength
+ * @see ubidi_getResultLength
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2
+ubidi_getLogicalMap(UBiDi *pBiDi, int32_t *indexMap, UErrorCode *pErrorCode);
+
+/**
+ * Get a visual-to-logical index map (array) for the characters in the UBiDi
+ * (paragraph or line) object.
+ * <p>
+ * Some values in the map may be <code>#UBIDI_MAP_NOWHERE</code> if the
+ * corresponding text characters are Bidi marks inserted in the visual output
+ * by the option <code>#UBIDI_OPTION_INSERT_MARKS</code>.
+ * <p>
+ * When the visual output is altered by using options of
+ * <code>ubidi_writeReordered()</code> such as <code>UBIDI_INSERT_LRM_FOR_NUMERIC</code>,
+ * <code>UBIDI_KEEP_BASE_COMBINING</code>, <code>UBIDI_OUTPUT_REVERSE</code>,
+ * <code>UBIDI_REMOVE_BIDI_CONTROLS</code>, the logical positions returned may not
+ * be correct. It is advised to use, when possible, reordering options
+ * such as <code>UBIDI_OPTION_INSERT_MARKS</code> and <code>UBIDI_OPTION_REMOVE_CONTROLS</code>.
+ *
+ * @param pBiDi is the paragraph or line <code>UBiDi</code> object.
+ *
+ * @param indexMap is a pointer to an array of <code>ubidi_getResultLength()</code>
+ *        indexes which will reflect the reordering of the characters.
+ *        If option <code>#UBIDI_OPTION_REMOVE_CONTROLS</code> is set, the number
+ *        of elements allocated in <code>indexMap</code> must be no less than
+ *        <code>ubidi_getProcessedLength()</code>.
+ *        The array does not need to be initialized.<br><br>
+ *        The index map will result in <code>indexMap[visualIndex]==logicalIndex</code>.
+ *
+ * @param pErrorCode must be a valid pointer to an error code value.
+ *
+ * @see ubidi_getLogicalMap
+ * @see ubidi_getLogicalIndex
+ * @see ubidi_getProcessedLength
+ * @see ubidi_getResultLength
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2
+ubidi_getVisualMap(UBiDi *pBiDi, int32_t *indexMap, UErrorCode *pErrorCode);
+
+/**
+ * This is a convenience function that does not use a UBiDi object.
+ * It is intended to be used for when an application has determined the levels
+ * of objects (character sequences) and just needs to have them reordered (L2).
+ * This is equivalent to using <code>ubidi_getLogicalMap()</code> on a
+ * <code>UBiDi</code> object.
+ *
+ * @param levels is an array with <code>length</code> levels that have been determined by
+ *        the application.
+ *
+ * @param length is the number of levels in the array, or, semantically,
+ *        the number of objects to be reordered.
+ *        It must be <code>length>0</code>.
+ *
+ * @param indexMap is a pointer to an array of <code>length</code>
+ *        indexes which will reflect the reordering of the characters.
+ *        The array does not need to be initialized.<p>
+ *        The index map will result in <code>indexMap[logicalIndex]==visualIndex</code>.
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2
+ubidi_reorderLogical(const UBiDiLevel *levels, int32_t length, int32_t *indexMap);
+
+/**
+ * This is a convenience function that does not use a UBiDi object.
+ * It is intended to be used for when an application has determined the levels
+ * of objects (character sequences) and just needs to have them reordered (L2).
+ * This is equivalent to using <code>ubidi_getVisualMap()</code> on a
+ * <code>UBiDi</code> object.
+ *
+ * @param levels is an array with <code>length</code> levels that have been determined by
+ *        the application.
+ *
+ * @param length is the number of levels in the array, or, semantically,
+ *        the number of objects to be reordered.
+ *        It must be <code>length>0</code>.
+ *
+ * @param indexMap is a pointer to an array of <code>length</code>
+ *        indexes which will reflect the reordering of the characters.
+ *        The array does not need to be initialized.<p>
+ *        The index map will result in <code>indexMap[visualIndex]==logicalIndex</code>.
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2
+ubidi_reorderVisual(const UBiDiLevel *levels, int32_t length, int32_t *indexMap);
+
+/**
+ * Invert an index map.
+ * The index mapping of the first map is inverted and written to
+ * the second one.
+ *
+ * @param srcMap is an array with <code>length</code> elements
+ *        which defines the original mapping from a source array containing
+ *        <code>length</code> elements to a destination array.
+ *        Some elements of the source array may have no mapping in the
+ *        destination array. In that case, their value will be
+ *        the special value <code>UBIDI_MAP_NOWHERE</code>.
+ *        All elements must be >=0 or equal to <code>UBIDI_MAP_NOWHERE</code>.
+ *        Some elements may have a value >= <code>length</code>, if the
+ *        destination array has more elements than the source array.
+ *        There must be no duplicate indexes (two or more elements with the
+ *        same value except <code>UBIDI_MAP_NOWHERE</code>).
+ *
+ * @param destMap is an array with a number of elements equal to 1 + the highest
+ *        value in <code>srcMap</code>.
+ *        <code>destMap</code> will be filled with the inverse mapping.
+ *        If element with index i in <code>srcMap</code> has a value k different
+ *        from <code>UBIDI_MAP_NOWHERE</code>, this means that element i of
+ *        the source array maps to element k in the destination array.
+ *        The inverse map will have value i in its k-th element.
+ *        For all elements of the destination array which do not map to
+ *        an element in the source array, the corresponding element in the
+ *        inverse map will have a value equal to <code>UBIDI_MAP_NOWHERE</code>.
+ *
+ * @param length is the length of each array.
+ * @see UBIDI_MAP_NOWHERE
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2
+ubidi_invertMap(const int32_t *srcMap, int32_t *destMap, int32_t length);
+
+/** option flags for ubidi_writeReordered() */
+
+/**
+ * option bit for ubidi_writeReordered():
+ * keep combining characters after their base characters in RTL runs
+ *
+ * @see ubidi_writeReordered
+ * @stable ICU 2.0
+ */
+#define UBIDI_KEEP_BASE_COMBINING       1
+
+/**
+ * option bit for ubidi_writeReordered():
+ * replace characters with the "mirrored" property in RTL runs
+ * by their mirror-image mappings
+ *
+ * @see ubidi_writeReordered
+ * @stable ICU 2.0
+ */
+#define UBIDI_DO_MIRRORING              2
+
+/**
+ * option bit for ubidi_writeReordered():
+ * surround the run with LRMs if necessary;
+ * this is part of the approximate "inverse Bidi" algorithm
+ *
+ * <p>This option does not imply corresponding adjustment of the index
+ * mappings.</p>
+ *
+ * @see ubidi_setInverse
+ * @see ubidi_writeReordered
+ * @stable ICU 2.0
+ */
+#define UBIDI_INSERT_LRM_FOR_NUMERIC    4
+
+/**
+ * option bit for ubidi_writeReordered():
+ * remove Bidi control characters
+ * (this does not affect #UBIDI_INSERT_LRM_FOR_NUMERIC)
+ *
+ * <p>This option does not imply corresponding adjustment of the index
+ * mappings.</p>
+ *
+ * @see ubidi_writeReordered
+ * @stable ICU 2.0
+ */
+#define UBIDI_REMOVE_BIDI_CONTROLS      8
+
+/**
+ * option bit for ubidi_writeReordered():
+ * write the output in reverse order
+ *
+ * <p>This has the same effect as calling <code>ubidi_writeReordered()</code>
+ * first without this option, and then calling
+ * <code>ubidi_writeReverse()</code> without mirroring.
+ * Doing this in the same step is faster and avoids a temporary buffer.
+ * An example for using this option is output to a character terminal that
+ * is designed for RTL scripts and stores text in reverse order.</p>
+ *
+ * @see ubidi_writeReordered
+ * @stable ICU 2.0
+ */
+#define UBIDI_OUTPUT_REVERSE            16
+
+/**
+ * Get the length of the source text processed by the last call to
+ * <code>ubidi_setPara()</code>. This length may be different from the length
+ * of the source text if option <code>#UBIDI_OPTION_STREAMING</code>
+ * has been set.
+ * <br>
+ * Note that whenever the length of the text affects the execution or the
+ * result of a function, it is the processed length which must be considered,
+ * except for <code>ubidi_setPara</code> (which receives unprocessed source
+ * text) and <code>ubidi_getLength</code> (which returns the original length
+ * of the source text).<br>
+ * In particular, the processed length is the one to consider in the following
+ * cases:
+ * <ul>
+ * <li>maximum value of the <code>limit</code> argument of
+ * <code>ubidi_setLine</code></li>
+ * <li>maximum value of the <code>charIndex</code> argument of
+ * <code>ubidi_getParagraph</code></li>
+ * <li>maximum value of the <code>charIndex</code> argument of
+ * <code>ubidi_getLevelAt</code></li>
+ * <li>number of elements in the array returned by <code>ubidi_getLevels</code></li>
+ * <li>maximum value of the <code>logicalStart</code> argument of
+ * <code>ubidi_getLogicalRun</code></li>
+ * <li>maximum value of the <code>logicalIndex</code> argument of
+ * <code>ubidi_getVisualIndex</code></li>
+ * <li>number of elements filled in the <code>*indexMap</code> argument of
+ * <code>ubidi_getLogicalMap</code></li>
+ * <li>length of text processed by <code>ubidi_writeReordered</code></li>
+ * </ul>
+ *
+ * @param pBiDi is the paragraph <code>UBiDi</code> object.
+ *
+ * @return The length of the part of the source text processed by
+ *         the last call to <code>ubidi_setPara</code>.
+ * @see ubidi_setPara
+ * @see UBIDI_OPTION_STREAMING
+ * @stable ICU 3.6
+ */
+U_STABLE int32_t U_EXPORT2
+ubidi_getProcessedLength(const UBiDi *pBiDi);
+
+/**
+ * Get the length of the reordered text resulting from the last call to
+ * <code>ubidi_setPara()</code>. This length may be different from the length
+ * of the source text if option <code>#UBIDI_OPTION_INSERT_MARKS</code>
+ * or option <code>#UBIDI_OPTION_REMOVE_CONTROLS</code> has been set.
+ * <br>
+ * This resulting length is the one to consider in the following cases:
+ * <ul>
+ * <li>maximum value of the <code>visualIndex</code> argument of
+ * <code>ubidi_getLogicalIndex</code></li>
+ * <li>number of elements of the <code>*indexMap</code> argument of
+ * <code>ubidi_getVisualMap</code></li>
+ * </ul>
+ * Note that this length stays identical to the source text length if
+ * Bidi marks are inserted or removed using option bits of
+ * <code>ubidi_writeReordered</code>, or if option
+ * <code>#UBIDI_REORDER_INVERSE_NUMBERS_AS_L</code> has been set.
+ *
+ * @param pBiDi is the paragraph <code>UBiDi</code> object.
+ *
+ * @return The length of the reordered text resulting from
+ *         the last call to <code>ubidi_setPara</code>.
+ * @see ubidi_setPara
+ * @see UBIDI_OPTION_INSERT_MARKS
+ * @see UBIDI_OPTION_REMOVE_CONTROLS
+ * @stable ICU 3.6
+ */
+U_STABLE int32_t U_EXPORT2
+ubidi_getResultLength(const UBiDi *pBiDi);
+
+U_CDECL_BEGIN
+/**
+ * value returned by <code>UBiDiClassCallback</code> callbacks when
+ * there is no need to override the standard Bidi class for a given code point.
+ * @see UBiDiClassCallback
+ * @stable ICU 3.6
+ */
+#define U_BIDI_CLASS_DEFAULT  U_CHAR_DIRECTION_COUNT
+
+/**
+ * Callback type declaration for overriding default Bidi class values with
+ * custom ones.
+ * <p>Usually, the function pointer will be propagated to a <code>UBiDi</code>
+ * object by calling the <code>ubidi_setClassCallback()</code> function;
+ * then the callback will be invoked by the UBA implementation any time the
+ * class of a character is to be determined.</p>
+ *
+ * @param context is a pointer to the callback private data.
+ *
+ * @param c       is the code point to get a Bidi class for.
+ *
+ * @return The directional property / Bidi class for the given code point
+ *         <code>c</code> if the default class has been overridden, or
+ *         <code>#U_BIDI_CLASS_DEFAULT</code> if the standard Bidi class value
+ *         for <code>c</code> is to be used.
+ * @see ubidi_setClassCallback
+ * @see ubidi_getClassCallback
+ * @stable ICU 3.6
+ */
+typedef UCharDirection U_CALLCONV
+UBiDiClassCallback(const void *context, UChar32 c);
+
+U_CDECL_END
+
+/**
+ * Retrieve the Bidi class for a given code point.
+ * <p>If a <code>#UBiDiClassCallback</code> callback is defined and returns a
+ * value other than <code>#U_BIDI_CLASS_DEFAULT</code>, that value is used;
+ * otherwise the default class determination mechanism is invoked.</p>
+ *
+ * @param pBiDi is the paragraph <code>UBiDi</code> object.
+ *
+ * @param c     is the code point whose Bidi class must be retrieved.
+ *
+ * @return The Bidi class for character <code>c</code> based
+ *         on the given <code>pBiDi</code> instance.
+ * @see UBiDiClassCallback
+ * @stable ICU 3.6
+ */
+U_STABLE UCharDirection U_EXPORT2
+ubidi_getCustomizedClass(UBiDi *pBiDi, UChar32 c);
+
+/**
+ * Set the callback function and callback data used by the UBA
+ * implementation for Bidi class determination.
+ * <p>This may be useful for assigning Bidi classes to PUA characters, or
+ * for special application needs. For instance, an application may want to
+ * handle all spaces like L or R characters (according to the base direction)
+ * when creating the visual ordering of logical lines which are part of a report
+ * organized in columns: there should not be interaction between adjacent
+ * cells.<p>
+ *
+ * @param pBiDi is the paragraph <code>UBiDi</code> object.
+ *
+ * @param newFn is the new callback function pointer.
+ *
+ * @param newContext is the new callback context pointer. This can be NULL.
+ *
+ * @param oldFn fillin: Returns the old callback function pointer. This can be
+ *                      NULL.
+ *
+ * @param oldContext fillin: Returns the old callback's context. This can be
+ *                           NULL.
+ *
+ * @param pErrorCode must be a valid pointer to an error code value.
+ *
+ * @see ubidi_getClassCallback
+ * @stable ICU 3.6
+ */
+U_STABLE void U_EXPORT2
+ubidi_setClassCallback(UBiDi *pBiDi, UBiDiClassCallback *newFn,
+                       const void *newContext, UBiDiClassCallback **oldFn,
+                       const void **oldContext, UErrorCode *pErrorCode);
+
+/**
+ * Get the current callback function used for Bidi class determination.
+ *
+ * @param pBiDi is the paragraph <code>UBiDi</code> object.
+ *
+ * @param fn fillin: Returns the callback function pointer.
+ *
+ * @param context fillin: Returns the callback's private context.
+ *
+ * @see ubidi_setClassCallback
+ * @stable ICU 3.6
+ */
+U_STABLE void U_EXPORT2
+ubidi_getClassCallback(UBiDi *pBiDi, UBiDiClassCallback **fn, const void **context);
+
+/**
+ * Take a <code>UBiDi</code> object containing the reordering
+ * information for a piece of text (one or more paragraphs) set by
+ * <code>ubidi_setPara()</code> or for a line of text set by
+ * <code>ubidi_setLine()</code> and write a reordered string to the
+ * destination buffer.
+ *
+ * This function preserves the integrity of characters with multiple
+ * code units and (optionally) combining characters.
+ * Characters in RTL runs can be replaced by mirror-image characters
+ * in the destination buffer. Note that "real" mirroring has
+ * to be done in a rendering engine by glyph selection
+ * and that for many "mirrored" characters there are no
+ * Unicode characters as mirror-image equivalents.
+ * There are also options to insert or remove Bidi control
+ * characters; see the description of the <code>destSize</code>
+ * and <code>options</code> parameters and of the option bit flags.
+ *
+ * @param pBiDi A pointer to a <code>UBiDi</code> object that
+ *              is set by <code>ubidi_setPara()</code> or
+ *              <code>ubidi_setLine()</code> and contains the reordering
+ *              information for the text that it was defined for,
+ *              as well as a pointer to that text.<br><br>
+ *              The text was aliased (only the pointer was stored
+ *              without copying the contents) and must not have been modified
+ *              since the <code>ubidi_setPara()</code> call.
+ *
+ * @param dest A pointer to where the reordered text is to be copied.
+ *             The source text and <code>dest[destSize]</code>
+ *             must not overlap.
+ *
+ * @param destSize The size of the <code>dest</code> buffer,
+ *                 in number of UChars.
+ *                 If the <code>UBIDI_INSERT_LRM_FOR_NUMERIC</code>
+ *                 option is set, then the destination length could be
+ *                 as large as
+ *                 <code>ubidi_getLength(pBiDi)+2*ubidi_countRuns(pBiDi)</code>.
+ *                 If the <code>UBIDI_REMOVE_BIDI_CONTROLS</code> option
+ *                 is set, then the destination length may be less than
+ *                 <code>ubidi_getLength(pBiDi)</code>.
+ *                 If none of these options is set, then the destination length
+ *                 will be exactly <code>ubidi_getProcessedLength(pBiDi)</code>.
+ *
+ * @param options A bit set of options for the reordering that control
+ *                how the reordered text is written.
+ *                The options include mirroring the characters on a code
+ *                point basis and inserting LRM characters, which is used
+ *                especially for transforming visually stored text
+ *                to logically stored text (although this is still an
+ *                imperfect implementation of an "inverse Bidi" algorithm
+ *                because it uses the "forward Bidi" algorithm at its core).
+ *                The available options are:
+ *                <code>#UBIDI_DO_MIRRORING</code>,
+ *                <code>#UBIDI_INSERT_LRM_FOR_NUMERIC</code>,
+ *                <code>#UBIDI_KEEP_BASE_COMBINING</code>,
+ *                <code>#UBIDI_OUTPUT_REVERSE</code>,
+ *                <code>#UBIDI_REMOVE_BIDI_CONTROLS</code>
+ *
+ * @param pErrorCode must be a valid pointer to an error code value.
+ *
+ * @return The length of the output string.
+ *
+ * @see ubidi_getProcessedLength
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+ubidi_writeReordered(UBiDi *pBiDi,
+                     UChar *dest, int32_t destSize,
+                     uint16_t options,
+                     UErrorCode *pErrorCode);
+
+/**
+ * Reverse a Right-To-Left run of Unicode text.
+ *
+ * This function preserves the integrity of characters with multiple
+ * code units and (optionally) combining characters.
+ * Characters can be replaced by mirror-image characters
+ * in the destination buffer. Note that "real" mirroring has
+ * to be done in a rendering engine by glyph selection
+ * and that for many "mirrored" characters there are no
+ * Unicode characters as mirror-image equivalents.
+ * There are also options to insert or remove Bidi control
+ * characters.
+ *
+ * This function is the implementation for reversing RTL runs as part
+ * of <code>ubidi_writeReordered()</code>. For detailed descriptions
+ * of the parameters, see there.
+ * Since no Bidi controls are inserted here, the output string length
+ * will never exceed <code>srcLength</code>.
+ *
+ * @see ubidi_writeReordered
+ *
+ * @param src A pointer to the RTL run text.
+ *
+ * @param srcLength The length of the RTL run.
+ *
+ * @param dest A pointer to where the reordered text is to be copied.
+ *             <code>src[srcLength]</code> and <code>dest[destSize]</code>
+ *             must not overlap.
+ *
+ * @param destSize The size of the <code>dest</code> buffer,
+ *                 in number of UChars.
+ *                 If the <code>UBIDI_REMOVE_BIDI_CONTROLS</code> option
+ *                 is set, then the destination length may be less than
+ *                 <code>srcLength</code>.
+ *                 If this option is not set, then the destination length
+ *                 will be exactly <code>srcLength</code>.
+ *
+ * @param options A bit set of options for the reordering that control
+ *                how the reordered text is written.
+ *                See the <code>options</code> parameter in <code>ubidi_writeReordered()</code>.
+ *
+ * @param pErrorCode must be a valid pointer to an error code value.
+ *
+ * @return The length of the output string.
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+ubidi_writeReverse(const UChar *src, int32_t srcLength,
+                   UChar *dest, int32_t destSize,
+                   uint16_t options,
+                   UErrorCode *pErrorCode);
+
+/*#define BIDI_SAMPLE_CODE*/
+/*@}*/
+
+#endif


[08/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/navbar.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/navbar.less b/apps/fauxton/assets/less/bootstrap/navbar.less
deleted file mode 100644
index 93d09bc..0000000
--- a/apps/fauxton/assets/less/bootstrap/navbar.less
+++ /dev/null
@@ -1,497 +0,0 @@
-//
-// Navbars (Redux)
-// --------------------------------------------------
-
-
-// COMMON STYLES
-// -------------
-
-// Base class and wrapper
-.navbar {
-  overflow: visible;
-  margin-bottom: @baseLineHeight;
-
-  // Fix for IE7's bad z-indexing so dropdowns don't appear below content that follows the navbar
-  *position: relative;
-  *z-index: 2;
-}
-
-// Inner for background effects
-// Gradient is applied to its own element because overflow visible is not honored by IE when filter is present
-.navbar-inner {
-  min-height: @navbarHeight;
-  padding-left:  20px;
-  padding-right: 20px;
-  #gradient > .vertical(@navbarBackgroundHighlight, @navbarBackground);
-  border: 1px solid @navbarBorder;
-  .border-radius(@baseBorderRadius);
-  .box-shadow(0 1px 4px rgba(0,0,0,.065));
-
-  // Prevent floats from breaking the navbar
-  .clearfix();
-}
-
-// Set width to auto for default container
-// We then reset it for fixed navbars in the #gridSystem mixin
-.navbar .container {
-  width: auto;
-}
-
-// Override the default collapsed state
-.nav-collapse.collapse {
-  height: auto;
-  overflow: visible;
-}
-
-
-// Brand: website or project name
-// -------------------------
-.navbar .brand {
-  float: left;
-  display: block;
-  // Vertically center the text given @navbarHeight
-  padding: ((@navbarHeight - @baseLineHeight) / 2) 20px ((@navbarHeight - @baseLineHeight) / 2);
-  margin-left: -20px; // negative indent to left-align the text down the page
-  font-size: 20px;
-  font-weight: 200;
-  color: @navbarBrandColor;
-  text-shadow: 0 1px 0 @navbarBackgroundHighlight;
-  &:hover,
-  &:focus {
-    text-decoration: none;
-  }
-}
-
-// Plain text in topbar
-// -------------------------
-.navbar-text {
-  margin-bottom: 0;
-  line-height: @navbarHeight;
-  color: @navbarText;
-}
-
-// Janky solution for now to account for links outside the .nav
-// -------------------------
-.navbar-link {
-  color: @navbarLinkColor;
-  &:hover,
-  &:focus {
-    color: @navbarLinkColorHover;
-  }
-}
-
-// Dividers in navbar
-// -------------------------
-.navbar .divider-vertical {
-  height: @navbarHeight;
-  margin: 0 9px;
-  border-left: 1px solid @navbarBackground;
-  border-right: 1px solid @navbarBackgroundHighlight;
-}
-
-// Buttons in navbar
-// -------------------------
-.navbar .btn,
-.navbar .btn-group {
-  .navbarVerticalAlign(30px); // Vertically center in navbar
-}
-.navbar .btn-group .btn,
-.navbar .input-prepend .btn,
-.navbar .input-append .btn,
-.navbar .input-prepend .btn-group,
-.navbar .input-append .btn-group {
-  margin-top: 0; // then undo the margin here so we don't accidentally double it
-}
-
-// Navbar forms
-// -------------------------
-.navbar-form {
-  margin-bottom: 0; // remove default bottom margin
-  .clearfix();
-  input,
-  select,
-  .radio,
-  .checkbox {
-    .navbarVerticalAlign(30px); // Vertically center in navbar
-  }
-  input,
-  select,
-  .btn {
-    display: inline-block;
-    margin-bottom: 0;
-  }
-  input[type="image"],
-  input[type="checkbox"],
-  input[type="radio"] {
-    margin-top: 3px;
-  }
-  .input-append,
-  .input-prepend {
-    margin-top: 5px;
-    white-space: nowrap; // preven two  items from separating within a .navbar-form that has .pull-left
-    input {
-      margin-top: 0; // remove the margin on top since it's on the parent
-    }
-  }
-}
-
-// Navbar search
-// -------------------------
-.navbar-search {
-  position: relative;
-  float: left;
-  .navbarVerticalAlign(30px); // Vertically center in navbar
-  margin-bottom: 0;
-  .search-query {
-    margin-bottom: 0;
-    padding: 4px 14px;
-    #font > .sans-serif(13px, normal, 1);
-    .border-radius(15px); // redeclare because of specificity of the type attribute
-  }
-}
-
-
-
-// Static navbar
-// -------------------------
-
-.navbar-static-top {
-  position: static;
-  margin-bottom: 0; // remove 18px margin for default navbar
-  .navbar-inner {
-    .border-radius(0);
-  }
-}
-
-
-
-// Fixed navbar
-// -------------------------
-
-// Shared (top/bottom) styles
-.navbar-fixed-top,
-.navbar-fixed-bottom {
-  position: fixed;
-  right: 0;
-  left: 0;
-  z-index: @zindexFixedNavbar;
-  margin-bottom: 0; // remove 18px margin for default navbar
-}
-.navbar-fixed-top .navbar-inner,
-.navbar-static-top .navbar-inner {
-  border-width: 0 0 1px;
-}
-.navbar-fixed-bottom .navbar-inner {
-  border-width: 1px 0 0;
-}
-.navbar-fixed-top .navbar-inner,
-.navbar-fixed-bottom .navbar-inner {
-  padding-left:  0;
-  padding-right: 0;
-  .border-radius(0);
-}
-
-// Reset container width
-// Required here as we reset the width earlier on and the grid mixins don't override early enough
-.navbar-static-top .container,
-.navbar-fixed-top .container,
-.navbar-fixed-bottom .container {
-  #grid > .core > .span(@gridColumns);
-}
-
-// Fixed to top
-.navbar-fixed-top {
-  top: 0;
-}
-.navbar-fixed-top,
-.navbar-static-top {
-  .navbar-inner {
-    .box-shadow(~"0 1px 10px rgba(0,0,0,.1)");
-  }
-}
-
-// Fixed to bottom
-.navbar-fixed-bottom {
-  bottom: 0;
-  .navbar-inner {
-    .box-shadow(~"0 -1px 10px rgba(0,0,0,.1)");
-  }
-}
-
-
-
-// NAVIGATION
-// ----------
-
-.navbar .nav {
-  position: relative;
-  left: 0;
-  display: block;
-  float: left;
-  margin: 0 10px 0 0;
-}
-.navbar .nav.pull-right {
-  float: right; // redeclare due to specificity
-  margin-right: 0; // remove margin on float right nav
-}
-.navbar .nav > li {
-  float: left;
-}
-
-// Links
-.navbar .nav > li > a {
-  float: none;
-  // Vertically center the text given @navbarHeight
-  padding: ((@navbarHeight - @baseLineHeight) / 2) 15px ((@navbarHeight - @baseLineHeight) / 2);
-  color: @navbarLinkColor;
-  text-decoration: none;
-  text-shadow: 0 1px 0 @navbarBackgroundHighlight;
-}
-.navbar .nav .dropdown-toggle .caret {
-  margin-top: 8px;
-}
-
-// Hover/focus
-.navbar .nav > li > a:focus,
-.navbar .nav > li > a:hover {
-  background-color: @navbarLinkBackgroundHover; // "transparent" is default to differentiate :hover/:focus from .active
-  color: @navbarLinkColorHover;
-  text-decoration: none;
-}
-
-// Active nav items
-.navbar .nav > .active > a,
-.navbar .nav > .active > a:hover,
-.navbar .nav > .active > a:focus {
-  color: @navbarLinkColorActive;
-  text-decoration: none;
-  background-color: @navbarLinkBackgroundActive;
-  .box-shadow(inset 0 3px 8px rgba(0,0,0,.125));
-}
-
-// Navbar button for toggling navbar items in responsive layouts
-// These definitions need to come after '.navbar .btn'
-.navbar .btn-navbar {
-  display: none;
-  float: right;
-  padding: 7px 10px;
-  margin-left: 5px;
-  margin-right: 5px;
-  .buttonBackground(darken(@navbarBackgroundHighlight, 5%), darken(@navbarBackground, 5%));
-  .box-shadow(~"inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.075)");
-}
-.navbar .btn-navbar .icon-bar {
-  display: block;
-  width: 18px;
-  height: 2px;
-  background-color: #f5f5f5;
-  .border-radius(1px);
-  .box-shadow(0 1px 0 rgba(0,0,0,.25));
-}
-.btn-navbar .icon-bar + .icon-bar {
-  margin-top: 3px;
-}
-
-
-
-// Dropdown menus
-// --------------
-
-// Menu position and menu carets
-.navbar .nav > li > .dropdown-menu {
-  &:before {
-    content: '';
-    display: inline-block;
-    border-left:   7px solid transparent;
-    border-right:  7px solid transparent;
-    border-bottom: 7px solid #ccc;
-    border-bottom-color: @dropdownBorder;
-    position: absolute;
-    top: -7px;
-    left: 9px;
-  }
-  &:after {
-    content: '';
-    display: inline-block;
-    border-left:   6px solid transparent;
-    border-right:  6px solid transparent;
-    border-bottom: 6px solid @dropdownBackground;
-    position: absolute;
-    top: -6px;
-    left: 10px;
-  }
-}
-// Menu position and menu caret support for dropups via extra dropup class
-.navbar-fixed-bottom .nav > li > .dropdown-menu {
-  &:before {
-    border-top: 7px solid #ccc;
-    border-top-color: @dropdownBorder;
-    border-bottom: 0;
-    bottom: -7px;
-    top: auto;
-  }
-  &:after {
-    border-top: 6px solid @dropdownBackground;
-    border-bottom: 0;
-    bottom: -6px;
-    top: auto;
-  }
-}
-
-// Caret should match text color on hover/focus
-.navbar .nav li.dropdown > a:hover .caret,
-.navbar .nav li.dropdown > a:focus .caret {
-  border-top-color: @navbarLinkColorHover;
-  border-bottom-color: @navbarLinkColorHover;
-}
-
-// Remove background color from open dropdown
-.navbar .nav li.dropdown.open > .dropdown-toggle,
-.navbar .nav li.dropdown.active > .dropdown-toggle,
-.navbar .nav li.dropdown.open.active > .dropdown-toggle {
-  background-color: @navbarLinkBackgroundActive;
-  color: @navbarLinkColorActive;
-}
-.navbar .nav li.dropdown > .dropdown-toggle .caret {
-  border-top-color: @navbarLinkColor;
-  border-bottom-color: @navbarLinkColor;
-}
-.navbar .nav li.dropdown.open > .dropdown-toggle .caret,
-.navbar .nav li.dropdown.active > .dropdown-toggle .caret,
-.navbar .nav li.dropdown.open.active > .dropdown-toggle .caret {
-  border-top-color: @navbarLinkColorActive;
-  border-bottom-color: @navbarLinkColorActive;
-}
-
-// Right aligned menus need alt position
-.navbar .pull-right > li > .dropdown-menu,
-.navbar .nav > li > .dropdown-menu.pull-right {
-  left: auto;
-  right: 0;
-  &:before {
-    left: auto;
-    right: 12px;
-  }
-  &:after {
-    left: auto;
-    right: 13px;
-  }
-  .dropdown-menu {
-    left: auto;
-    right: 100%;
-    margin-left: 0;
-    margin-right: -1px;
-    .border-radius(6px 0 6px 6px);
-  }
-}
-
-
-// Inverted navbar
-// -------------------------
-
-.navbar-inverse {
-
-  .navbar-inner {
-    #gradient > .vertical(@navbarInverseBackgroundHighlight, @navbarInverseBackground);
-    border-color: @navbarInverseBorder;
-  }
-
-  .brand,
-  .nav > li > a {
-    color: @navbarInverseLinkColor;
-    text-shadow: 0 -1px 0 rgba(0,0,0,.25);
-    &:hover,
-    &:focus {
-      color: @navbarInverseLinkColorHover;
-    }
-  }
-
-  .brand {
-    color: @navbarInverseBrandColor;
-  }
-
-  .navbar-text {
-    color: @navbarInverseText;
-  }
-
-  .nav > li > a:focus,
-  .nav > li > a:hover {
-    background-color: @navbarInverseLinkBackgroundHover;
-    color: @navbarInverseLinkColorHover;
-  }
-
-  .nav .active > a,
-  .nav .active > a:hover,
-  .nav .active > a:focus {
-    color: @navbarInverseLinkColorActive;
-    background-color: @navbarInverseLinkBackgroundActive;
-  }
-
-  // Inline text links
-  .navbar-link {
-    color: @navbarInverseLinkColor;
-    &:hover,
-    &:focus {
-      color: @navbarInverseLinkColorHover;
-    }
-  }
-
-  // Dividers in navbar
-  .divider-vertical {
-    border-left-color: @navbarInverseBackground;
-    border-right-color: @navbarInverseBackgroundHighlight;
-  }
-
-  // Dropdowns
-  .nav li.dropdown.open > .dropdown-toggle,
-  .nav li.dropdown.active > .dropdown-toggle,
-  .nav li.dropdown.open.active > .dropdown-toggle {
-    background-color: @navbarInverseLinkBackgroundActive;
-    color: @navbarInverseLinkColorActive;
-  }
-  .nav li.dropdown > a:hover .caret,
-  .nav li.dropdown > a:focus .caret {
-    border-top-color: @navbarInverseLinkColorActive;
-    border-bottom-color: @navbarInverseLinkColorActive;
-  }
-  .nav li.dropdown > .dropdown-toggle .caret {
-    border-top-color: @navbarInverseLinkColor;
-    border-bottom-color: @navbarInverseLinkColor;
-  }
-  .nav li.dropdown.open > .dropdown-toggle .caret,
-  .nav li.dropdown.active > .dropdown-toggle .caret,
-  .nav li.dropdown.open.active > .dropdown-toggle .caret {
-    border-top-color: @navbarInverseLinkColorActive;
-    border-bottom-color: @navbarInverseLinkColorActive;
-  }
-
-  // Navbar search
-  .navbar-search {
-    .search-query {
-      color: @white;
-      background-color: @navbarInverseSearchBackground;
-      border-color: @navbarInverseSearchBorder;
-      .box-shadow(~"inset 0 1px 2px rgba(0,0,0,.1), 0 1px 0 rgba(255,255,255,.15)");
-      .transition(none);
-      .placeholder(@navbarInverseSearchPlaceholderColor);
-
-      // Focus states (we use .focused since IE7-8 and down doesn't support :focus)
-      &:focus,
-      &.focused {
-        padding: 5px 15px;
-        color: @grayDark;
-        text-shadow: 0 1px 0 @white;
-        background-color: @navbarInverseSearchBackgroundFocus;
-        border: 0;
-        .box-shadow(0 0 3px rgba(0,0,0,.15));
-        outline: 0;
-      }
-    }
-  }
-
-  // Navbar collapse button
-  .btn-navbar {
-    .buttonBackground(darken(@navbarInverseBackgroundHighlight, 5%), darken(@navbarInverseBackground, 5%));
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/navs.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/navs.less b/apps/fauxton/assets/less/bootstrap/navs.less
deleted file mode 100644
index 01cd805..0000000
--- a/apps/fauxton/assets/less/bootstrap/navs.less
+++ /dev/null
@@ -1,409 +0,0 @@
-//
-// Navs
-// --------------------------------------------------
-
-
-// BASE CLASS
-// ----------
-
-.nav {
-  margin-left: 0;
-  margin-bottom: @baseLineHeight;
-  list-style: none;
-}
-
-// Make links block level
-.nav > li > a {
-  display: block;
-}
-.nav > li > a:hover,
-.nav > li > a:focus {
-  text-decoration: none;
-  background-color: @grayLighter;
-}
-
-// Prevent IE8 from misplacing imgs
-// See https://github.com/h5bp/html5-boilerplate/issues/984#issuecomment-3985989
-.nav > li > a > img {
-  max-width: none;
-}
-
-// Redeclare pull classes because of specifity
-.nav > .pull-right {
-  float: right;
-}
-
-// Nav headers (for dropdowns and lists)
-.nav-header {
-  display: block;
-  padding: 3px 15px;
-  font-size: 11px;
-  font-weight: bold;
-  line-height: @baseLineHeight;
-  color: @grayLight;
-  text-shadow: 0 1px 0 rgba(255,255,255,.5);
-  text-transform: uppercase;
-}
-// Space them out when they follow another list item (link)
-.nav li + .nav-header {
-  margin-top: 9px;
-}
-
-
-
-// NAV LIST
-// --------
-
-.nav-list {
-  padding-left: 15px;
-  padding-right: 15px;
-  margin-bottom: 0;
-}
-.nav-list > li > a,
-.nav-list .nav-header {
-  margin-left:  -15px;
-  margin-right: -15px;
-  text-shadow: 0 1px 0 rgba(255,255,255,.5);
-}
-.nav-list > li > a {
-  padding: 3px 15px;
-}
-.nav-list > .active > a,
-.nav-list > .active > a:hover,
-.nav-list > .active > a:focus {
-  color: @white;
-  text-shadow: 0 -1px 0 rgba(0,0,0,.2);
-  background-color: @linkColor;
-}
-.nav-list [class^="icon-"],
-.nav-list [class*=" icon-"] {
-  margin-right: 2px;
-}
-// Dividers (basically an hr) within the dropdown
-.nav-list .divider {
-  .nav-divider();
-}
-
-
-
-// TABS AND PILLS
-// -------------
-
-// Common styles
-.nav-tabs,
-.nav-pills {
-  .clearfix();
-}
-.nav-tabs > li,
-.nav-pills > li {
-  float: left;
-}
-.nav-tabs > li > a,
-.nav-pills > li > a {
-  padding-right: 12px;
-  padding-left: 12px;
-  margin-right: 2px;
-  line-height: 14px; // keeps the overall height an even number
-}
-
-// TABS
-// ----
-
-// Give the tabs something to sit on
-.nav-tabs {
-  border-bottom: 1px solid #ddd;
-}
-// Make the list-items overlay the bottom border
-.nav-tabs > li {
-  margin-bottom: -1px;
-}
-// Actual tabs (as links)
-.nav-tabs > li > a {
-  padding-top: 8px;
-  padding-bottom: 8px;
-  line-height: @baseLineHeight;
-  border: 1px solid transparent;
-  .border-radius(4px 4px 0 0);
-  &:hover,
-  &:focus {
-    border-color: @grayLighter @grayLighter #ddd;
-  }
-}
-// Active state, and it's :hover/:focus to override normal :hover/:focus
-.nav-tabs > .active > a,
-.nav-tabs > .active > a:hover,
-.nav-tabs > .active > a:focus {
-  color: @gray;
-  background-color: @bodyBackground;
-  border: 1px solid #ddd;
-  border-bottom-color: transparent;
-  cursor: default;
-}
-
-
-// PILLS
-// -----
-
-// Links rendered as pills
-.nav-pills > li > a {
-  padding-top: 8px;
-  padding-bottom: 8px;
-  margin-top: 2px;
-  margin-bottom: 2px;
-  .border-radius(5px);
-}
-
-// Active state
-.nav-pills > .active > a,
-.nav-pills > .active > a:hover,
-.nav-pills > .active > a:focus {
-  color: @white;
-  background-color: @linkColor;
-}
-
-
-
-// STACKED NAV
-// -----------
-
-// Stacked tabs and pills
-.nav-stacked > li {
-  float: none;
-}
-.nav-stacked > li > a {
-  margin-right: 0; // no need for the gap between nav items
-}
-
-// Tabs
-.nav-tabs.nav-stacked {
-  border-bottom: 0;
-}
-.nav-tabs.nav-stacked > li > a {
-  border: 1px solid #ddd;
-  .border-radius(0);
-}
-.nav-tabs.nav-stacked > li:first-child > a {
-  .border-top-radius(4px);
-}
-.nav-tabs.nav-stacked > li:last-child > a {
-  .border-bottom-radius(4px);
-}
-.nav-tabs.nav-stacked > li > a:hover,
-.nav-tabs.nav-stacked > li > a:focus {
-  border-color: #ddd;
-  z-index: 2;
-}
-
-// Pills
-.nav-pills.nav-stacked > li > a {
-  margin-bottom: 3px;
-}
-.nav-pills.nav-stacked > li:last-child > a {
-  margin-bottom: 1px; // decrease margin to match sizing of stacked tabs
-}
-
-
-
-// DROPDOWNS
-// ---------
-
-.nav-tabs .dropdown-menu {
-  .border-radius(0 0 6px 6px); // remove the top rounded corners here since there is a hard edge above the menu
-}
-.nav-pills .dropdown-menu {
-  .border-radius(6px); // make rounded corners match the pills
-}
-
-// Default dropdown links
-// -------------------------
-// Make carets use linkColor to start
-.nav .dropdown-toggle .caret {
-  border-top-color: @linkColor;
-  border-bottom-color: @linkColor;
-  margin-top: 6px;
-}
-.nav .dropdown-toggle:hover .caret,
-.nav .dropdown-toggle:focus .caret {
-  border-top-color: @linkColorHover;
-  border-bottom-color: @linkColorHover;
-}
-/* move down carets for tabs */
-.nav-tabs .dropdown-toggle .caret {
-  margin-top: 8px;
-}
-
-// Active dropdown links
-// -------------------------
-.nav .active .dropdown-toggle .caret {
-  border-top-color: #fff;
-  border-bottom-color: #fff;
-}
-.nav-tabs .active .dropdown-toggle .caret {
-  border-top-color: @gray;
-  border-bottom-color: @gray;
-}
-
-// Active:hover/:focus dropdown links
-// -------------------------
-.nav > .dropdown.active > a:hover,
-.nav > .dropdown.active > a:focus {
-  cursor: pointer;
-}
-
-// Open dropdowns
-// -------------------------
-.nav-tabs .open .dropdown-toggle,
-.nav-pills .open .dropdown-toggle,
-.nav > li.dropdown.open.active > a:hover,
-.nav > li.dropdown.open.active > a:focus {
-  color: @white;
-  background-color: @grayLight;
-  border-color: @grayLight;
-}
-.nav li.dropdown.open .caret,
-.nav li.dropdown.open.active .caret,
-.nav li.dropdown.open a:hover .caret,
-.nav li.dropdown.open a:focus .caret {
-  border-top-color: @white;
-  border-bottom-color: @white;
-  .opacity(100);
-}
-
-// Dropdowns in stacked tabs
-.tabs-stacked .open > a:hover,
-.tabs-stacked .open > a:focus {
-  border-color: @grayLight;
-}
-
-
-
-// TABBABLE
-// --------
-
-
-// COMMON STYLES
-// -------------
-
-// Clear any floats
-.tabbable {
-  .clearfix();
-}
-.tab-content {
-  overflow: auto; // prevent content from running below tabs
-}
-
-// Remove border on bottom, left, right
-.tabs-below > .nav-tabs,
-.tabs-right > .nav-tabs,
-.tabs-left > .nav-tabs {
-  border-bottom: 0;
-}
-
-// Show/hide tabbable areas
-.tab-content > .tab-pane,
-.pill-content > .pill-pane {
-  display: none;
-}
-.tab-content > .active,
-.pill-content > .active {
-  display: block;
-}
-
-
-// BOTTOM
-// ------
-
-.tabs-below > .nav-tabs {
-  border-top: 1px solid #ddd;
-}
-.tabs-below > .nav-tabs > li {
-  margin-top: -1px;
-  margin-bottom: 0;
-}
-.tabs-below > .nav-tabs > li > a {
-  .border-radius(0 0 4px 4px);
-  &:hover,
-  &:focus {
-    border-bottom-color: transparent;
-    border-top-color: #ddd;
-  }
-}
-.tabs-below > .nav-tabs > .active > a,
-.tabs-below > .nav-tabs > .active > a:hover,
-.tabs-below > .nav-tabs > .active > a:focus {
-  border-color: transparent #ddd #ddd #ddd;
-}
-
-// LEFT & RIGHT
-// ------------
-
-// Common styles
-.tabs-left > .nav-tabs > li,
-.tabs-right > .nav-tabs > li {
-  float: none;
-}
-.tabs-left > .nav-tabs > li > a,
-.tabs-right > .nav-tabs > li > a {
-  min-width: 74px;
-  margin-right: 0;
-  margin-bottom: 3px;
-}
-
-// Tabs on the left
-.tabs-left > .nav-tabs {
-  float: left;
-  margin-right: 19px;
-  border-right: 1px solid #ddd;
-}
-.tabs-left > .nav-tabs > li > a {
-  margin-right: -1px;
-  .border-radius(4px 0 0 4px);
-}
-.tabs-left > .nav-tabs > li > a:hover,
-.tabs-left > .nav-tabs > li > a:focus {
-  border-color: @grayLighter #ddd @grayLighter @grayLighter;
-}
-.tabs-left > .nav-tabs .active > a,
-.tabs-left > .nav-tabs .active > a:hover,
-.tabs-left > .nav-tabs .active > a:focus {
-  border-color: #ddd transparent #ddd #ddd;
-  *border-right-color: @white;
-}
-
-// Tabs on the right
-.tabs-right > .nav-tabs {
-  float: right;
-  margin-left: 19px;
-  border-left: 1px solid #ddd;
-}
-.tabs-right > .nav-tabs > li > a {
-  margin-left: -1px;
-  .border-radius(0 4px 4px 0);
-}
-.tabs-right > .nav-tabs > li > a:hover,
-.tabs-right > .nav-tabs > li > a:focus {
-  border-color: @grayLighter @grayLighter @grayLighter #ddd;
-}
-.tabs-right > .nav-tabs .active > a,
-.tabs-right > .nav-tabs .active > a:hover,
-.tabs-right > .nav-tabs .active > a:focus {
-  border-color: #ddd #ddd #ddd transparent;
-  *border-left-color: @white;
-}
-
-
-
-// DISABLED STATES
-// ---------------
-
-// Gray out text
-.nav > .disabled > a {
-  color: @grayLight;
-}
-// Nuke hover/focus effects
-.nav > .disabled > a:hover,
-.nav > .disabled > a:focus {
-  text-decoration: none;
-  background-color: transparent;
-  cursor: default;
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/pager.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/pager.less b/apps/fauxton/assets/less/bootstrap/pager.less
deleted file mode 100644
index 1476188..0000000
--- a/apps/fauxton/assets/less/bootstrap/pager.less
+++ /dev/null
@@ -1,43 +0,0 @@
-//
-// Pager pagination
-// --------------------------------------------------
-
-
-.pager {
-  margin: @baseLineHeight 0;
-  list-style: none;
-  text-align: center;
-  .clearfix();
-}
-.pager li {
-  display: inline;
-}
-.pager li > a,
-.pager li > span {
-  display: inline-block;
-  padding: 5px 14px;
-  background-color: #fff;
-  border: 1px solid #ddd;
-  .border-radius(15px);
-}
-.pager li > a:hover,
-.pager li > a:focus {
-  text-decoration: none;
-  background-color: #f5f5f5;
-}
-.pager .next > a,
-.pager .next > span {
-  float: right;
-}
-.pager .previous > a,
-.pager .previous > span {
-  float: left;
-}
-.pager .disabled > a,
-.pager .disabled > a:hover,
-.pager .disabled > a:focus,
-.pager .disabled > span {
-  color: @grayLight;
-  background-color: #fff;
-  cursor: default;
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/pagination.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/pagination.less b/apps/fauxton/assets/less/bootstrap/pagination.less
deleted file mode 100644
index a789db2..0000000
--- a/apps/fauxton/assets/less/bootstrap/pagination.less
+++ /dev/null
@@ -1,123 +0,0 @@
-//
-// Pagination (multiple pages)
-// --------------------------------------------------
-
-// Space out pagination from surrounding content
-.pagination {
-  margin: @baseLineHeight 0;
-}
-
-.pagination ul {
-  // Allow for text-based alignment
-  display: inline-block;
-  .ie7-inline-block();
-  // Reset default ul styles
-  margin-left: 0;
-  margin-bottom: 0;
-  // Visuals
-  .border-radius(@baseBorderRadius);
-  .box-shadow(0 1px 2px rgba(0,0,0,.05));
-}
-.pagination ul > li {
-  display: inline; // Remove list-style and block-level defaults
-}
-.pagination ul > li > a,
-.pagination ul > li > span {
-  float: left; // Collapse white-space
-  padding: 4px 12px;
-  line-height: @baseLineHeight;
-  text-decoration: none;
-  background-color: @paginationBackground;
-  border: 1px solid @paginationBorder;
-  border-left-width: 0;
-}
-.pagination ul > li > a:hover,
-.pagination ul > li > a:focus,
-.pagination ul > .active > a,
-.pagination ul > .active > span {
-  background-color: @paginationActiveBackground;
-}
-.pagination ul > .active > a,
-.pagination ul > .active > span {
-  color: @grayLight;
-  cursor: default;
-}
-.pagination ul > .disabled > span,
-.pagination ul > .disabled > a,
-.pagination ul > .disabled > a:hover,
-.pagination ul > .disabled > a:focus {
-  color: @grayLight;
-  background-color: transparent;
-  cursor: default;
-}
-.pagination ul > li:first-child > a,
-.pagination ul > li:first-child > span {
-  border-left-width: 1px;
-  .border-left-radius(@baseBorderRadius);
-}
-.pagination ul > li:last-child > a,
-.pagination ul > li:last-child > span {
-  .border-right-radius(@baseBorderRadius);
-}
-
-
-// Alignment
-// --------------------------------------------------
-
-.pagination-centered {
-  text-align: center;
-}
-.pagination-right {
-  text-align: right;
-}
-
-
-// Sizing
-// --------------------------------------------------
-
-// Large
-.pagination-large {
-  ul > li > a,
-  ul > li > span {
-    padding: @paddingLarge;
-    font-size: @fontSizeLarge;
-  }
-  ul > li:first-child > a,
-  ul > li:first-child > span {
-    .border-left-radius(@borderRadiusLarge);
-  }
-  ul > li:last-child > a,
-  ul > li:last-child > span {
-    .border-right-radius(@borderRadiusLarge);
-  }
-}
-
-// Small and mini
-.pagination-mini,
-.pagination-small {
-  ul > li:first-child > a,
-  ul > li:first-child > span {
-    .border-left-radius(@borderRadiusSmall);
-  }
-  ul > li:last-child > a,
-  ul > li:last-child > span {
-    .border-right-radius(@borderRadiusSmall);
-  }
-}
-
-// Small
-.pagination-small {
-  ul > li > a,
-  ul > li > span {
-    padding: @paddingSmall;
-    font-size: @fontSizeSmall;
-  }
-}
-// Mini
-.pagination-mini {
-  ul > li > a,
-  ul > li > span {
-    padding: @paddingMini;
-    font-size: @fontSizeMini;
-  }
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/popovers.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/popovers.less b/apps/fauxton/assets/less/bootstrap/popovers.less
deleted file mode 100644
index aae35c8..0000000
--- a/apps/fauxton/assets/less/bootstrap/popovers.less
+++ /dev/null
@@ -1,133 +0,0 @@
-//
-// Popovers
-// --------------------------------------------------
-
-
-.popover {
-  position: absolute;
-  top: 0;
-  left: 0;
-  z-index: @zindexPopover;
-  display: none;
-  max-width: 276px;
-  padding: 1px;
-  text-align: left; // Reset given new insertion method
-  background-color: @popoverBackground;
-  -webkit-background-clip: padding-box;
-     -moz-background-clip: padding;
-          background-clip: padding-box;
-  border: 1px solid #ccc;
-  border: 1px solid rgba(0,0,0,.2);
-  .border-radius(6px);
-  .box-shadow(0 5px 10px rgba(0,0,0,.2));
-
-  // Overrides for proper insertion
-  white-space: normal;
-
-  // Offset the popover to account for the popover arrow
-  &.top     { margin-top: -10px; }
-  &.right   { margin-left: 10px; }
-  &.bottom  { margin-top: 10px; }
-  &.left    { margin-left: -10px; }
-}
-
-.popover-title {
-  margin: 0; // reset heading margin
-  padding: 8px 14px;
-  font-size: 14px;
-  font-weight: normal;
-  line-height: 18px;
-  background-color: @popoverTitleBackground;
-  border-bottom: 1px solid darken(@popoverTitleBackground, 5%);
-  .border-radius(5px 5px 0 0);
-
-  &:empty {
-    display: none;
-  }
-}
-
-.popover-content {
-  padding: 9px 14px;
-}
-
-// Arrows
-//
-// .arrow is outer, .arrow:after is inner
-
-.popover .arrow,
-.popover .arrow:after {
-  position: absolute;
-  display: block;
-  width: 0;
-  height: 0;
-  border-color: transparent;
-  border-style: solid;
-}
-.popover .arrow {
-  border-width: @popoverArrowOuterWidth;
-}
-.popover .arrow:after {
-  border-width: @popoverArrowWidth;
-  content: "";
-}
-
-.popover {
-  &.top .arrow {
-    left: 50%;
-    margin-left: -@popoverArrowOuterWidth;
-    border-bottom-width: 0;
-    border-top-color: #999; // IE8 fallback
-    border-top-color: @popoverArrowOuterColor;
-    bottom: -@popoverArrowOuterWidth;
-    &:after {
-      bottom: 1px;
-      margin-left: -@popoverArrowWidth;
-      border-bottom-width: 0;
-      border-top-color: @popoverArrowColor;
-    }
-  }
-  &.right .arrow {
-    top: 50%;
-    left: -@popoverArrowOuterWidth;
-    margin-top: -@popoverArrowOuterWidth;
-    border-left-width: 0;
-    border-right-color: #999; // IE8 fallback
-    border-right-color: @popoverArrowOuterColor;
-    &:after {
-      left: 1px;
-      bottom: -@popoverArrowWidth;
-      border-left-width: 0;
-      border-right-color: @popoverArrowColor;
-    }
-  }
-  &.bottom .arrow {
-    left: 50%;
-    margin-left: -@popoverArrowOuterWidth;
-    border-top-width: 0;
-    border-bottom-color: #999; // IE8 fallback
-    border-bottom-color: @popoverArrowOuterColor;
-    top: -@popoverArrowOuterWidth;
-    &:after {
-      top: 1px;
-      margin-left: -@popoverArrowWidth;
-      border-top-width: 0;
-      border-bottom-color: @popoverArrowColor;
-    }
-  }
-
-  &.left .arrow {
-    top: 50%;
-    right: -@popoverArrowOuterWidth;
-    margin-top: -@popoverArrowOuterWidth;
-    border-right-width: 0;
-    border-left-color: #999; // IE8 fallback
-    border-left-color: @popoverArrowOuterColor;
-    &:after {
-      right: 1px;
-      border-right-width: 0;
-      border-left-color: @popoverArrowColor;
-      bottom: -@popoverArrowWidth;
-    }
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/progress-bars.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/progress-bars.less b/apps/fauxton/assets/less/bootstrap/progress-bars.less
deleted file mode 100644
index 5e0c3dd..0000000
--- a/apps/fauxton/assets/less/bootstrap/progress-bars.less
+++ /dev/null
@@ -1,122 +0,0 @@
-//
-// Progress bars
-// --------------------------------------------------
-
-
-// ANIMATIONS
-// ----------
-
-// Webkit
-@-webkit-keyframes progress-bar-stripes {
-  from  { background-position: 40px 0; }
-  to    { background-position: 0 0; }
-}
-
-// Firefox
-@-moz-keyframes progress-bar-stripes {
-  from  { background-position: 40px 0; }
-  to    { background-position: 0 0; }
-}
-
-// IE9
-@-ms-keyframes progress-bar-stripes {
-  from  { background-position: 40px 0; }
-  to    { background-position: 0 0; }
-}
-
-// Opera
-@-o-keyframes progress-bar-stripes {
-  from  { background-position: 0 0; }
-  to    { background-position: 40px 0; }
-}
-
-// Spec
-@keyframes progress-bar-stripes {
-  from  { background-position: 40px 0; }
-  to    { background-position: 0 0; }
-}
-
-
-
-// THE BARS
-// --------
-
-// Outer container
-.progress {
-  overflow: hidden;
-  height: @baseLineHeight;
-  margin-bottom: @baseLineHeight;
-  #gradient > .vertical(#f5f5f5, #f9f9f9);
-  .box-shadow(inset 0 1px 2px rgba(0,0,0,.1));
-  .border-radius(@baseBorderRadius);
-}
-
-// Bar of progress
-.progress .bar {
-  width: 0%;
-  height: 100%;
-  color: @white;
-  float: left;
-  font-size: 12px;
-  text-align: center;
-  text-shadow: 0 -1px 0 rgba(0,0,0,.25);
-  #gradient > .vertical(#149bdf, #0480be);
-  .box-shadow(inset 0 -1px 0 rgba(0,0,0,.15));
-  .box-sizing(border-box);
-  .transition(width .6s ease);
-}
-.progress .bar + .bar {
-  .box-shadow(~"inset 1px 0 0 rgba(0,0,0,.15), inset 0 -1px 0 rgba(0,0,0,.15)");
-}
-
-// Striped bars
-.progress-striped .bar {
-  #gradient > .striped(#149bdf);
-  .background-size(40px 40px);
-}
-
-// Call animation for the active one
-.progress.active .bar {
-  -webkit-animation: progress-bar-stripes 2s linear infinite;
-     -moz-animation: progress-bar-stripes 2s linear infinite;
-      -ms-animation: progress-bar-stripes 2s linear infinite;
-       -o-animation: progress-bar-stripes 2s linear infinite;
-          animation: progress-bar-stripes 2s linear infinite;
-}
-
-
-
-// COLORS
-// ------
-
-// Danger (red)
-.progress-danger .bar, .progress .bar-danger {
-  #gradient > .vertical(#ee5f5b, #c43c35);
-}
-.progress-danger.progress-striped .bar, .progress-striped .bar-danger {
-  #gradient > .striped(#ee5f5b);
-}
-
-// Success (green)
-.progress-success .bar, .progress .bar-success {
-  #gradient > .vertical(#62c462, #57a957);
-}
-.progress-success.progress-striped .bar, .progress-striped .bar-success {
-  #gradient > .striped(#62c462);
-}
-
-// Info (teal)
-.progress-info .bar, .progress .bar-info {
-  #gradient > .vertical(#5bc0de, #339bb9);
-}
-.progress-info.progress-striped .bar, .progress-striped .bar-info {
-  #gradient > .striped(#5bc0de);
-}
-
-// Warning (orange)
-.progress-warning .bar, .progress .bar-warning {
-  #gradient > .vertical(lighten(@orange, 15%), @orange);
-}
-.progress-warning.progress-striped .bar, .progress-striped .bar-warning {
-  #gradient > .striped(lighten(@orange, 15%));
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/reset.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/reset.less b/apps/fauxton/assets/less/bootstrap/reset.less
deleted file mode 100644
index 4806bd5..0000000
--- a/apps/fauxton/assets/less/bootstrap/reset.less
+++ /dev/null
@@ -1,216 +0,0 @@
-//
-// Reset CSS
-// Adapted from http://github.com/necolas/normalize.css
-// --------------------------------------------------
-
-
-// Display in IE6-9 and FF3
-// -------------------------
-
-article,
-aside,
-details,
-figcaption,
-figure,
-footer,
-header,
-hgroup,
-nav,
-section {
-  display: block;
-}
-
-// Display block in IE6-9 and FF3
-// -------------------------
-
-audio,
-canvas,
-video {
-  display: inline-block;
-  *display: inline;
-  *zoom: 1;
-}
-
-// Prevents modern browsers from displaying 'audio' without controls
-// -------------------------
-
-audio:not([controls]) {
-    display: none;
-}
-
-// Base settings
-// -------------------------
-
-html {
-  font-size: 100%;
-  -webkit-text-size-adjust: 100%;
-      -ms-text-size-adjust: 100%;
-}
-// Focus states
-a:focus {
-  .tab-focus();
-}
-// Hover & Active
-a:hover,
-a:active {
-  outline: 0;
-}
-
-// Prevents sub and sup affecting line-height in all browsers
-// -------------------------
-
-sub,
-sup {
-  position: relative;
-  font-size: 75%;
-  line-height: 0;
-  vertical-align: baseline;
-}
-sup {
-  top: -0.5em;
-}
-sub {
-  bottom: -0.25em;
-}
-
-// Img border in a's and image quality
-// -------------------------
-
-img {
-  /* Responsive images (ensure images don't scale beyond their parents) */
-  max-width: 100%; /* Part 1: Set a maxium relative to the parent */
-  width: auto\9; /* IE7-8 need help adjusting responsive images */
-  height: auto; /* Part 2: Scale the height according to the width, otherwise you get stretching */
-
-  vertical-align: middle;
-  border: 0;
-  -ms-interpolation-mode: bicubic;
-}
-
-// Prevent max-width from affecting Google Maps
-#map_canvas img,
-.google-maps img {
-  max-width: none;
-}
-
-// Forms
-// -------------------------
-
-// Font size in all browsers, margin changes, misc consistency
-button,
-input,
-select,
-textarea {
-  margin: 0;
-  font-size: 100%;
-  vertical-align: middle;
-}
-button,
-input {
-  *overflow: visible; // Inner spacing ie IE6/7
-  line-height: normal; // FF3/4 have !important on line-height in UA stylesheet
-}
-button::-moz-focus-inner,
-input::-moz-focus-inner { // Inner padding and border oddities in FF3/4
-  padding: 0;
-  border: 0;
-}
-button,
-html input[type="button"], // Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio` and `video` controls.
-input[type="reset"],
-input[type="submit"] {
-    -webkit-appearance: button; // Corrects inability to style clickable `input` types in iOS.
-    cursor: pointer; // Improves usability and consistency of cursor style between image-type `input` and others.
-}
-label,
-select,
-button,
-input[type="button"],
-input[type="reset"],
-input[type="submit"],
-input[type="radio"],
-input[type="checkbox"] {
-    cursor: pointer; // Improves usability and consistency of cursor style between image-type `input` and others.
-}
-input[type="search"] { // Appearance in Safari/Chrome
-  .box-sizing(content-box);
-  -webkit-appearance: textfield;
-}
-input[type="search"]::-webkit-search-decoration,
-input[type="search"]::-webkit-search-cancel-button {
-  -webkit-appearance: none; // Inner-padding issues in Chrome OSX, Safari 5
-}
-textarea {
-  overflow: auto; // Remove vertical scrollbar in IE6-9
-  vertical-align: top; // Readability and alignment cross-browser
-}
-
-
-// Printing
-// -------------------------
-// Source: https://github.com/h5bp/html5-boilerplate/blob/master/css/main.css
-
-@media print {
-
-  * {
-    text-shadow: none !important;
-    color: #000 !important; // Black prints faster: h5bp.com/s
-    background: transparent !important;
-    box-shadow: none !important;
-  }
-
-  a,
-  a:visited {
-    text-decoration: underline;
-  }
-
-  a[href]:after {
-    content: " (" attr(href) ")";
-  }
-
-  abbr[title]:after {
-    content: " (" attr(title) ")";
-  }
-
-  // Don't show links for images, or javascript/internal links
-  .ir a:after,
-  a[href^="javascript:"]:after,
-  a[href^="#"]:after {
-    content: "";
-  }
-
-  pre,
-  blockquote {
-    border: 1px solid #999;
-    page-break-inside: avoid;
-  }
-
-  thead {
-    display: table-header-group; // h5bp.com/t
-  }
-
-  tr,
-  img {
-    page-break-inside: avoid;
-  }
-
-  img {
-    max-width: 100% !important;
-  }
-
-  @page {
-    margin: 0.5cm;
-  }
-
-  p,
-  h2,
-  h3 {
-    orphans: 3;
-    widows: 3;
-  }
-
-  h2,
-  h3 {
-    page-break-after: avoid;
-  }
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/responsive-1200px-min.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/responsive-1200px-min.less b/apps/fauxton/assets/less/bootstrap/responsive-1200px-min.less
deleted file mode 100644
index 4f35ba6..0000000
--- a/apps/fauxton/assets/less/bootstrap/responsive-1200px-min.less
+++ /dev/null
@@ -1,28 +0,0 @@
-//
-// Responsive: Large desktop and up
-// --------------------------------------------------
-
-
-@media (min-width: 1200px) {
-
-  // Fixed grid
-  #grid > .core(@gridColumnWidth1200, @gridGutterWidth1200);
-
-  // Fluid grid
-  #grid > .fluid(@fluidGridColumnWidth1200, @fluidGridGutterWidth1200);
-
-  // Input grid
-  #grid > .input(@gridColumnWidth1200, @gridGutterWidth1200);
-
-  // Thumbnails
-  .thumbnails {
-    margin-left: -@gridGutterWidth1200;
-  }
-  .thumbnails > li {
-    margin-left: @gridGutterWidth1200;
-  }
-  .row-fluid .thumbnails {
-    margin-left: 0;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/responsive-767px-max.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/responsive-767px-max.less b/apps/fauxton/assets/less/bootstrap/responsive-767px-max.less
deleted file mode 100644
index 128f4ce..0000000
--- a/apps/fauxton/assets/less/bootstrap/responsive-767px-max.less
+++ /dev/null
@@ -1,193 +0,0 @@
-//
-// Responsive: Landscape phone to desktop/tablet
-// --------------------------------------------------
-
-
-@media (max-width: 767px) {
-
-  // Padding to set content in a bit
-  body {
-    padding-left: 20px;
-    padding-right: 20px;
-  }
-  // Negative indent the now static "fixed" navbar
-  .navbar-fixed-top,
-  .navbar-fixed-bottom,
-  .navbar-static-top {
-    margin-left: -20px;
-    margin-right: -20px;
-  }
-  // Remove padding on container given explicit padding set on body
-  .container-fluid {
-    padding: 0;
-  }
-
-  // TYPOGRAPHY
-  // ----------
-  // Reset horizontal dl
-  .dl-horizontal {
-    dt {
-      float: none;
-      clear: none;
-      width: auto;
-      text-align: left;
-    }
-    dd {
-      margin-left: 0;
-    }
-  }
-
-  // GRID & CONTAINERS
-  // -----------------
-  // Remove width from containers
-  .container {
-    width: auto;
-  }
-  // Fluid rows
-  .row-fluid {
-    width: 100%;
-  }
-  // Undo negative margin on rows and thumbnails
-  .row,
-  .thumbnails {
-    margin-left: 0;
-  }
-  .thumbnails > li {
-    float: none;
-    margin-left: 0; // Reset the default margin for all li elements when no .span* classes are present
-  }
-  // Make all grid-sized elements block level again
-  [class*="span"],
-  .uneditable-input[class*="span"], // Makes uneditable inputs full-width when using grid sizing
-  .row-fluid [class*="span"] {
-    float: none;
-    display: block;
-    width: 100%;
-    margin-left: 0;
-    .box-sizing(border-box);
-  }
-  .span12,
-  .row-fluid .span12 {
-    width: 100%;
-    .box-sizing(border-box);
-  }
-  .row-fluid [class*="offset"]:first-child {
-    margin-left: 0;
-  }
-
-  // FORM FIELDS
-  // -----------
-  // Make span* classes full width
-  .input-large,
-  .input-xlarge,
-  .input-xxlarge,
-  input[class*="span"],
-  select[class*="span"],
-  textarea[class*="span"],
-  .uneditable-input {
-    .input-block-level();
-  }
-  // But don't let it screw up prepend/append inputs
-  .input-prepend input,
-  .input-append input,
-  .input-prepend input[class*="span"],
-  .input-append input[class*="span"] {
-    display: inline-block; // redeclare so they don't wrap to new lines
-    width: auto;
-  }
-  .controls-row [class*="span"] + [class*="span"] {
-    margin-left: 0;
-  }
-
-  // Modals
-  .modal {
-    position: fixed;
-    top:   20px;
-    left:  20px;
-    right: 20px;
-    width: auto;
-    margin: 0;
-    &.fade  { top: -100px; }
-    &.fade.in { top: 20px; }
-  }
-
-}
-
-
-
-// UP TO LANDSCAPE PHONE
-// ---------------------
-
-@media (max-width: 480px) {
-
-  // Smooth out the collapsing/expanding nav
-  .nav-collapse {
-    -webkit-transform: translate3d(0, 0, 0); // activate the GPU
-  }
-
-  // Block level the page header small tag for readability
-  .page-header h1 small {
-    display: block;
-    line-height: @baseLineHeight;
-  }
-
-  // Update checkboxes for iOS
-  input[type="checkbox"],
-  input[type="radio"] {
-    border: 1px solid #ccc;
-  }
-
-  // Remove the horizontal form styles
-  .form-horizontal {
-    .control-label {
-      float: none;
-      width: auto;
-      padding-top: 0;
-      text-align: left;
-    }
-    // Move over all input controls and content
-    .controls {
-      margin-left: 0;
-    }
-    // Move the options list down to align with labels
-    .control-list {
-      padding-top: 0; // has to be padding because margin collaspes
-    }
-    // Move over buttons in .form-actions to align with .controls
-    .form-actions {
-      padding-left: 10px;
-      padding-right: 10px;
-    }
-  }
-
-  // Medias
-  // Reset float and spacing to stack
-  .media .pull-left,
-  .media .pull-right  {
-    float: none;
-    display: block;
-    margin-bottom: 10px;
-  }
-  // Remove side margins since we stack instead of indent
-  .media-object {
-    margin-right: 0;
-    margin-left: 0;
-  }
-
-  // Modals
-  .modal {
-    top:   10px;
-    left:  10px;
-    right: 10px;
-  }
-  .modal-header .close {
-    padding: 10px;
-    margin: -10px;
-  }
-
-  // Carousel
-  .carousel-caption {
-    position: static;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/responsive-768px-979px.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/responsive-768px-979px.less b/apps/fauxton/assets/less/bootstrap/responsive-768px-979px.less
deleted file mode 100644
index 8e8c486..0000000
--- a/apps/fauxton/assets/less/bootstrap/responsive-768px-979px.less
+++ /dev/null
@@ -1,19 +0,0 @@
-//
-// Responsive: Tablet to desktop
-// --------------------------------------------------
-
-
-@media (min-width: 768px) and (max-width: 979px) {
-
-  // Fixed grid
-  #grid > .core(@gridColumnWidth768, @gridGutterWidth768);
-
-  // Fluid grid
-  #grid > .fluid(@fluidGridColumnWidth768, @fluidGridGutterWidth768);
-
-  // Input grid
-  #grid > .input(@gridColumnWidth768, @gridGutterWidth768);
-
-  // No need to reset .thumbnails here since it's the same @gridGutterWidth
-
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/responsive-navbar.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/responsive-navbar.less b/apps/fauxton/assets/less/bootstrap/responsive-navbar.less
deleted file mode 100644
index 21cd3ba..0000000
--- a/apps/fauxton/assets/less/bootstrap/responsive-navbar.less
+++ /dev/null
@@ -1,189 +0,0 @@
-//
-// Responsive: Navbar
-// --------------------------------------------------
-
-
-// TABLETS AND BELOW
-// -----------------
-@media (max-width: @navbarCollapseWidth) {
-
-  // UNFIX THE TOPBAR
-  // ----------------
-  // Remove any padding from the body
-  body {
-    padding-top: 0;
-  }
-  // Unfix the navbars
-  .navbar-fixed-top,
-  .navbar-fixed-bottom {
-    position: static;
-  }
-  .navbar-fixed-top {
-    margin-bottom: @baseLineHeight;
-  }
-  .navbar-fixed-bottom {
-    margin-top: @baseLineHeight;
-  }
-  .navbar-fixed-top .navbar-inner,
-  .navbar-fixed-bottom .navbar-inner {
-    padding: 5px;
-  }
-  .navbar .container {
-    width: auto;
-    padding: 0;
-  }
-  // Account for brand name
-  .navbar .brand {
-    padding-left: 10px;
-    padding-right: 10px;
-    margin: 0 0 0 -5px;
-  }
-
-  // COLLAPSIBLE NAVBAR
-  // ------------------
-  // Nav collapse clears brand
-  .nav-collapse {
-    clear: both;
-  }
-  // Block-level the nav
-  .nav-collapse .nav {
-    float: none;
-    margin: 0 0 (@baseLineHeight / 2);
-  }
-  .nav-collapse .nav > li {
-    float: none;
-  }
-  .nav-collapse .nav > li > a {
-    margin-bottom: 2px;
-  }
-  .nav-collapse .nav > .divider-vertical {
-    display: none;
-  }
-  .nav-collapse .nav .nav-header {
-    color: @navbarText;
-    text-shadow: none;
-  }
-  // Nav and dropdown links in navbar
-  .nav-collapse .nav > li > a,
-  .nav-collapse .dropdown-menu a {
-    padding: 9px 15px;
-    font-weight: bold;
-    color: @navbarLinkColor;
-    .border-radius(3px);
-  }
-  // Buttons
-  .nav-collapse .btn {
-    padding: 4px 10px 4px;
-    font-weight: normal;
-    .border-radius(@baseBorderRadius);
-  }
-  .nav-collapse .dropdown-menu li + li a {
-    margin-bottom: 2px;
-  }
-  .nav-collapse .nav > li > a:hover,
-  .nav-collapse .nav > li > a:focus,
-  .nav-collapse .dropdown-menu a:hover,
-  .nav-collapse .dropdown-menu a:focus {
-    background-color: @navbarBackground;
-  }
-  .navbar-inverse .nav-collapse .nav > li > a,
-  .navbar-inverse .nav-collapse .dropdown-menu a {
-    color: @navbarInverseLinkColor;
-  }
-  .navbar-inverse .nav-collapse .nav > li > a:hover,
-  .navbar-inverse .nav-collapse .nav > li > a:focus,
-  .navbar-inverse .nav-collapse .dropdown-menu a:hover,
-  .navbar-inverse .nav-collapse .dropdown-menu a:focus {
-    background-color: @navbarInverseBackground;
-  }
-  // Buttons in the navbar
-  .nav-collapse.in .btn-group {
-    margin-top: 5px;
-    padding: 0;
-  }
-  // Dropdowns in the navbar
-  .nav-collapse .dropdown-menu {
-    position: static;
-    top: auto;
-    left: auto;
-    float: none;
-    display: none;
-    max-width: none;
-    margin: 0 15px;
-    padding: 0;
-    background-color: transparent;
-    border: none;
-    .border-radius(0);
-    .box-shadow(none);
-  }
-  .nav-collapse .open > .dropdown-menu { 
-    display: block; 
-  }
-
-  .nav-collapse .dropdown-menu:before,
-  .nav-collapse .dropdown-menu:after {
-    display: none;
-  }
-  .nav-collapse .dropdown-menu .divider {
-    display: none;
-  }
-  .nav-collapse .nav > li > .dropdown-menu {
-    &:before,
-    &:after {
-      display: none;
-    }
-  }
-  // Forms in navbar
-  .nav-collapse .navbar-form,
-  .nav-collapse .navbar-search {
-    float: none;
-    padding: (@baseLineHeight / 2) 15px;
-    margin: (@baseLineHeight / 2) 0;
-    border-top: 1px solid @navbarBackground;
-    border-bottom: 1px solid @navbarBackground;
-    .box-shadow(~"inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.1)");
-  }
-  .navbar-inverse .nav-collapse .navbar-form,
-  .navbar-inverse .nav-collapse .navbar-search {
-    border-top-color: @navbarInverseBackground;
-    border-bottom-color: @navbarInverseBackground;
-  }
-  // Pull right (secondary) nav content
-  .navbar .nav-collapse .nav.pull-right {
-    float: none;
-    margin-left: 0;
-  }
-  // Hide everything in the navbar save .brand and toggle button */
-  .nav-collapse,
-  .nav-collapse.collapse {
-    overflow: hidden;
-    height: 0;
-  }
-  // Navbar button
-  .navbar .btn-navbar {
-    display: block;
-  }
-
-  // STATIC NAVBAR
-  // -------------
-  .navbar-static .navbar-inner {
-    padding-left:  10px;
-    padding-right: 10px;
-  }
-
-
-}
-
-
-// DEFAULT DESKTOP
-// ---------------
-
-@media (min-width: @navbarCollapseDesktopWidth) {
-
-  // Required to make the collapsing navbar work on regular desktops
-  .nav-collapse.collapse {
-    height: auto !important;
-    overflow: visible !important;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/responsive-utilities.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/responsive-utilities.less b/apps/fauxton/assets/less/bootstrap/responsive-utilities.less
deleted file mode 100644
index bf43e8e..0000000
--- a/apps/fauxton/assets/less/bootstrap/responsive-utilities.less
+++ /dev/null
@@ -1,59 +0,0 @@
-//
-// Responsive: Utility classes
-// --------------------------------------------------
-
-
-// IE10 Metro responsive
-// Required for Windows 8 Metro split-screen snapping with IE10
-// Source: http://timkadlec.com/2012/10/ie10-snap-mode-and-responsive-design/
-@-ms-viewport{
-  width: device-width;
-}
-
-// Hide from screenreaders and browsers
-// Credit: HTML5 Boilerplate
-.hidden {
-  display: none;
-  visibility: hidden;
-}
-
-// Visibility utilities
-
-// For desktops
-.visible-phone     { display: none !important; }
-.visible-tablet    { display: none !important; }
-.hidden-phone      { }
-.hidden-tablet     { }
-.hidden-desktop    { display: none !important; }
-.visible-desktop   { display: inherit !important; }
-
-// Tablets & small desktops only
-@media (min-width: 768px) and (max-width: 979px) {
-  // Hide everything else
-  .hidden-desktop    { display: inherit !important; }
-  .visible-desktop   { display: none !important ; }
-  // Show
-  .visible-tablet    { display: inherit !important; }
-  // Hide
-  .hidden-tablet     { display: none !important; }
-}
-
-// Phones only
-@media (max-width: 767px) {
-  // Hide everything else
-  .hidden-desktop    { display: inherit !important; }
-  .visible-desktop   { display: none !important; }
-  // Show
-  .visible-phone     { display: inherit !important; } // Use inherit to restore previous behavior
-  // Hide
-  .hidden-phone      { display: none !important; }
-}
-
-// Print utilities
-.visible-print    { display: none !important; }
-.hidden-print     { }
-
-@media print {
-  .visible-print  { display: inherit !important; }
-  .hidden-print   { display: none !important; }
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/responsive.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/responsive.less b/apps/fauxton/assets/less/bootstrap/responsive.less
deleted file mode 100644
index 9e5f9b1..0000000
--- a/apps/fauxton/assets/less/bootstrap/responsive.less
+++ /dev/null
@@ -1,48 +0,0 @@
-/*!
- * Bootstrap Responsive v2.3.2
- *
- * Copyright 2012 Twitter, Inc
- * Licensed under the Apache License v2.0
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Designed and built with all the love in the world @twitter by @mdo and @fat.
- */
-
-
-// Responsive.less
-// For phone and tablet devices
-// -------------------------------------------------------------
-
-
-// REPEAT VARIABLES & MIXINS
-// -------------------------
-// Required since we compile the responsive stuff separately
-
-@import "variables.less"; // Modify this for custom colors, font-sizes, etc
-@import "mixins.less";
-
-
-// RESPONSIVE CLASSES
-// ------------------
-
-@import "responsive-utilities.less";
-
-
-// MEDIA QUERIES
-// ------------------
-
-// Large desktops
-@import "responsive-1200px-min.less";
-
-// Tablets to regular desktops
-@import "responsive-768px-979px.less";
-
-// Phones to portrait tablets and narrow desktops
-@import "responsive-767px-max.less";
-
-
-// RESPONSIVE NAVBAR
-// ------------------
-
-// From 979px and below, show a button to toggle navbar contents
-@import "responsive-navbar.less";

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/scaffolding.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/scaffolding.less b/apps/fauxton/assets/less/bootstrap/scaffolding.less
deleted file mode 100644
index f17e8ca..0000000
--- a/apps/fauxton/assets/less/bootstrap/scaffolding.less
+++ /dev/null
@@ -1,53 +0,0 @@
-//
-// Scaffolding
-// --------------------------------------------------
-
-
-// Body reset
-// -------------------------
-
-body {
-  margin: 0;
-  font-family: @baseFontFamily;
-  font-size: @baseFontSize;
-  line-height: @baseLineHeight;
-  color: @textColor;
-  background-color: @bodyBackground;
-}
-
-
-// Links
-// -------------------------
-
-a {
-  color: @linkColor;
-  text-decoration: none;
-}
-a:hover,
-a:focus {
-  color: @linkColorHover;
-  text-decoration: underline;
-}
-
-
-// Images
-// -------------------------
-
-// Rounded corners
-.img-rounded {
-  .border-radius(6px);
-}
-
-// Add polaroid-esque trim
-.img-polaroid {
-  padding: 4px;
-  background-color: #fff;
-  border: 1px solid #ccc;
-  border: 1px solid rgba(0,0,0,.2);
-  .box-shadow(0 1px 3px rgba(0,0,0,.1));
-}
-
-// Perfect circle
-.img-circle {
-  .border-radius(500px); // crank the border-radius so it works with most reasonably sized images
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/sprites.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/sprites.less b/apps/fauxton/assets/less/bootstrap/sprites.less
deleted file mode 100644
index 1812bf7..0000000
--- a/apps/fauxton/assets/less/bootstrap/sprites.less
+++ /dev/null
@@ -1,197 +0,0 @@
-//
-// Sprites
-// --------------------------------------------------
-
-
-// ICONS
-// -----
-
-// All icons receive the styles of the <i> tag with a base class
-// of .i and are then given a unique class to add width, height,
-// and background-position. Your resulting HTML will look like
-// <i class="icon-inbox"></i>.
-
-// For the white version of the icons, just add the .icon-white class:
-// <i class="icon-inbox icon-white"></i>
-
-[class^="icon-"],
-[class*=" icon-"] {
-  display: inline-block;
-  width: 14px;
-  height: 14px;
-  .ie7-restore-right-whitespace();
-  line-height: 14px;
-  vertical-align: text-top;
-  background-image: url("@{iconSpritePath}");
-  background-position: 14px 14px;
-  background-repeat: no-repeat;
-  margin-top: 1px;
-}
-
-/* White icons with optional class, or on hover/focus/active states of certain elements */
-.icon-white,
-.nav-pills > .active > a > [class^="icon-"],
-.nav-pills > .active > a > [class*=" icon-"],
-.nav-list > .active > a > [class^="icon-"],
-.nav-list > .active > a > [class*=" icon-"],
-.navbar-inverse .nav > .active > a > [class^="icon-"],
-.navbar-inverse .nav > .active > a > [class*=" icon-"],
-.dropdown-menu > li > a:hover > [class^="icon-"],
-.dropdown-menu > li > a:focus > [class^="icon-"],
-.dropdown-menu > li > a:hover > [class*=" icon-"],
-.dropdown-menu > li > a:focus > [class*=" icon-"],
-.dropdown-menu > .active > a > [class^="icon-"],
-.dropdown-menu > .active > a > [class*=" icon-"],
-.dropdown-submenu:hover > a > [class^="icon-"],
-.dropdown-submenu:focus > a > [class^="icon-"],
-.dropdown-submenu:hover > a > [class*=" icon-"],
-.dropdown-submenu:focus > a > [class*=" icon-"] {
-  background-image: url("@{iconWhiteSpritePath}");
-}
-
-.icon-glass              { background-position: 0      0; }
-.icon-music              { background-position: -24px  0; }
-.icon-search             { background-position: -48px  0; }
-.icon-envelope           { background-position: -72px  0; }
-.icon-heart              { background-position: -96px  0; }
-.icon-star               { background-position: -120px 0; }
-.icon-star-empty         { background-position: -144px 0; }
-.icon-user               { background-position: -168px 0; }
-.icon-film               { background-position: -192px 0; }
-.icon-th-large           { background-position: -216px 0; }
-.icon-th                 { background-position: -240px 0; }
-.icon-th-list            { background-position: -264px 0; }
-.icon-ok                 { background-position: -288px 0; }
-.icon-remove             { background-position: -312px 0; }
-.icon-zoom-in            { background-position: -336px 0; }
-.icon-zoom-out           { background-position: -360px 0; }
-.icon-off                { background-position: -384px 0; }
-.icon-signal             { background-position: -408px 0; }
-.icon-cog                { background-position: -432px 0; }
-.icon-trash              { background-position: -456px 0; }
-
-.icon-home               { background-position: 0      -24px; }
-.icon-file               { background-position: -24px  -24px; }
-.icon-time               { background-position: -48px  -24px; }
-.icon-road               { background-position: -72px  -24px; }
-.icon-download-alt       { background-position: -96px  -24px; }
-.icon-download           { background-position: -120px -24px; }
-.icon-upload             { background-position: -144px -24px; }
-.icon-inbox              { background-position: -168px -24px; }
-.icon-play-circle        { background-position: -192px -24px; }
-.icon-repeat             { background-position: -216px -24px; }
-.icon-refresh            { background-position: -240px -24px; }
-.icon-list-alt           { background-position: -264px -24px; }
-.icon-lock               { background-position: -287px -24px; } // 1px off
-.icon-flag               { background-position: -312px -24px; }
-.icon-headphones         { background-position: -336px -24px; }
-.icon-volume-off         { background-position: -360px -24px; }
-.icon-volume-down        { background-position: -384px -24px; }
-.icon-volume-up          { background-position: -408px -24px; }
-.icon-qrcode             { background-position: -432px -24px; }
-.icon-barcode            { background-position: -456px -24px; }
-
-.icon-tag                { background-position: 0      -48px; }
-.icon-tags               { background-position: -25px  -48px; } // 1px off
-.icon-book               { background-position: -48px  -48px; }
-.icon-bookmark           { background-position: -72px  -48px; }
-.icon-print              { background-position: -96px  -48px; }
-.icon-camera             { background-position: -120px -48px; }
-.icon-font               { background-position: -144px -48px; }
-.icon-bold               { background-position: -167px -48px; } // 1px off
-.icon-italic             { background-position: -192px -48px; }
-.icon-text-height        { background-position: -216px -48px; }
-.icon-text-width         { background-position: -240px -48px; }
-.icon-align-left         { background-position: -264px -48px; }
-.icon-align-center       { background-position: -288px -48px; }
-.icon-align-right        { background-position: -312px -48px; }
-.icon-align-justify      { background-position: -336px -48px; }
-.icon-list               { background-position: -360px -48px; }
-.icon-indent-left        { background-position: -384px -48px; }
-.icon-indent-right       { background-position: -408px -48px; }
-.icon-facetime-video     { background-position: -432px -48px; }
-.icon-picture            { background-position: -456px -48px; }
-
-.icon-pencil             { background-position: 0      -72px; }
-.icon-map-marker         { background-position: -24px  -72px; }
-.icon-adjust             { background-position: -48px  -72px; }
-.icon-tint               { background-position: -72px  -72px; }
-.icon-edit               { background-position: -96px  -72px; }
-.icon-share              { background-position: -120px -72px; }
-.icon-check              { background-position: -144px -72px; }
-.icon-move               { background-position: -168px -72px; }
-.icon-step-backward      { background-position: -192px -72px; }
-.icon-fast-backward      { background-position: -216px -72px; }
-.icon-backward           { background-position: -240px -72px; }
-.icon-play               { background-position: -264px -72px; }
-.icon-pause              { background-position: -288px -72px; }
-.icon-stop               { background-position: -312px -72px; }
-.icon-forward            { background-position: -336px -72px; }
-.icon-fast-forward       { background-position: -360px -72px; }
-.icon-step-forward       { background-position: -384px -72px; }
-.icon-eject              { background-position: -408px -72px; }
-.icon-chevron-left       { background-position: -432px -72px; }
-.icon-chevron-right      { background-position: -456px -72px; }
-
-.icon-plus-sign          { background-position: 0      -96px; }
-.icon-minus-sign         { background-position: -24px  -96px; }
-.icon-remove-sign        { background-position: -48px  -96px; }
-.icon-ok-sign            { background-position: -72px  -96px; }
-.icon-question-sign      { background-position: -96px  -96px; }
-.icon-info-sign          { background-position: -120px -96px; }
-.icon-screenshot         { background-position: -144px -96px; }
-.icon-remove-circle      { background-position: -168px -96px; }
-.icon-ok-circle          { background-position: -192px -96px; }
-.icon-ban-circle         { background-position: -216px -96px; }
-.icon-arrow-left         { background-position: -240px -96px; }
-.icon-arrow-right        { background-position: -264px -96px; }
-.icon-arrow-up           { background-position: -289px -96px; } // 1px off
-.icon-arrow-down         { background-position: -312px -96px; }
-.icon-share-alt          { background-position: -336px -96px; }
-.icon-resize-full        { background-position: -360px -96px; }
-.icon-resize-small       { background-position: -384px -96px; }
-.icon-plus               { background-position: -408px -96px; }
-.icon-minus              { background-position: -433px -96px; }
-.icon-asterisk           { background-position: -456px -96px; }
-
-.icon-exclamation-sign   { background-position: 0      -120px; }
-.icon-gift               { background-position: -24px  -120px; }
-.icon-leaf               { background-position: -48px  -120px; }
-.icon-fire               { background-position: -72px  -120px; }
-.icon-eye-open           { background-position: -96px  -120px; }
-.icon-eye-close          { background-position: -120px -120px; }
-.icon-warning-sign       { background-position: -144px -120px; }
-.icon-plane              { background-position: -168px -120px; }
-.icon-calendar           { background-position: -192px -120px; }
-.icon-random             { background-position: -216px -120px; width: 16px; }
-.icon-comment            { background-position: -240px -120px; }
-.icon-magnet             { background-position: -264px -120px; }
-.icon-chevron-up         { background-position: -288px -120px; }
-.icon-chevron-down       { background-position: -313px -119px; } // 1px, 1px off
-.icon-retweet            { background-position: -336px -120px; }
-.icon-shopping-cart      { background-position: -360px -120px; }
-.icon-folder-close       { background-position: -384px -120px; width: 16px; }
-.icon-folder-open        { background-position: -408px -120px; width: 16px; }
-.icon-resize-vertical    { background-position: -432px -119px; } // 1px, 1px off
-.icon-resize-horizontal  { background-position: -456px -118px; } // 1px, 2px off
-
-.icon-hdd                     { background-position: 0      -144px; }
-.icon-bullhorn                { background-position: -24px  -144px; }
-.icon-bell                    { background-position: -48px  -144px; }
-.icon-certificate             { background-position: -72px  -144px; }
-.icon-thumbs-up               { background-position: -96px  -144px; }
-.icon-thumbs-down             { background-position: -120px -144px; }
-.icon-hand-right              { background-position: -144px -144px; }
-.icon-hand-left               { background-position: -168px -144px; }
-.icon-hand-up                 { background-position: -192px -144px; }
-.icon-hand-down               { background-position: -216px -144px; }
-.icon-circle-arrow-right      { background-position: -240px -144px; }
-.icon-circle-arrow-left       { background-position: -264px -144px; }
-.icon-circle-arrow-up         { background-position: -288px -144px; }
-.icon-circle-arrow-down       { background-position: -312px -144px; }
-.icon-globe                   { background-position: -336px -144px; }
-.icon-wrench                  { background-position: -360px -144px; }
-.icon-tasks                   { background-position: -384px -144px; }
-.icon-filter                  { background-position: -408px -144px; }
-.icon-briefcase               { background-position: -432px -144px; }
-.icon-fullscreen              { background-position: -456px -144px; }

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/tables.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/tables.less b/apps/fauxton/assets/less/bootstrap/tables.less
deleted file mode 100644
index 0e35271..0000000
--- a/apps/fauxton/assets/less/bootstrap/tables.less
+++ /dev/null
@@ -1,244 +0,0 @@
-//
-// Tables
-// --------------------------------------------------
-
-
-// BASE TABLES
-// -----------------
-
-table {
-  max-width: 100%;
-  background-color: @tableBackground;
-  border-collapse: collapse;
-  border-spacing: 0;
-}
-
-// BASELINE STYLES
-// ---------------
-
-.table {
-  width: 100%;
-  margin-bottom: @baseLineHeight;
-  // Cells
-  th,
-  td {
-    padding: 8px;
-    line-height: @baseLineHeight;
-    text-align: left;
-    vertical-align: top;
-    border-top: 1px solid @tableBorder;
-  }
-  th {
-    font-weight: bold;
-  }
-  // Bottom align for column headings
-  thead th {
-    vertical-align: bottom;
-  }
-  // Remove top border from thead by default
-  caption + thead tr:first-child th,
-  caption + thead tr:first-child td,
-  colgroup + thead tr:first-child th,
-  colgroup + thead tr:first-child td,
-  thead:first-child tr:first-child th,
-  thead:first-child tr:first-child td {
-    border-top: 0;
-  }
-  // Account for multiple tbody instances
-  tbody + tbody {
-    border-top: 2px solid @tableBorder;
-  }
-
-  // Nesting
-  .table {
-    background-color: @bodyBackground;
-  }
-}
-
-
-
-// CONDENSED TABLE W/ HALF PADDING
-// -------------------------------
-
-.table-condensed {
-  th,
-  td {
-    padding: 4px 5px;
-  }
-}
-
-
-// BORDERED VERSION
-// ----------------
-
-.table-bordered {
-  border: 1px solid @tableBorder;
-  border-collapse: separate; // Done so we can round those corners!
-  *border-collapse: collapse; // IE7 can't round corners anyway
-  border-left: 0;
-  .border-radius(@baseBorderRadius);
-  th,
-  td {
-    border-left: 1px solid @tableBorder;
-  }
-  // Prevent a double border
-  caption + thead tr:first-child th,
-  caption + tbody tr:first-child th,
-  caption + tbody tr:first-child td,
-  colgroup + thead tr:first-child th,
-  colgroup + tbody tr:first-child th,
-  colgroup + tbody tr:first-child td,
-  thead:first-child tr:first-child th,
-  tbody:first-child tr:first-child th,
-  tbody:first-child tr:first-child td {
-    border-top: 0;
-  }
-  // For first th/td in the first row in the first thead or tbody
-  thead:first-child tr:first-child > th:first-child,
-  tbody:first-child tr:first-child > td:first-child,
-  tbody:first-child tr:first-child > th:first-child {
-    .border-top-left-radius(@baseBorderRadius);
-  }
-  // For last th/td in the first row in the first thead or tbody
-  thead:first-child tr:first-child > th:last-child,
-  tbody:first-child tr:first-child > td:last-child,
-  tbody:first-child tr:first-child > th:last-child {
-    .border-top-right-radius(@baseBorderRadius);
-  }
-  // For first th/td (can be either) in the last row in the last thead, tbody, and tfoot
-  thead:last-child tr:last-child > th:first-child,
-  tbody:last-child tr:last-child > td:first-child,
-  tbody:last-child tr:last-child > th:first-child,
-  tfoot:last-child tr:last-child > td:first-child,
-  tfoot:last-child tr:last-child > th:first-child {
-    .border-bottom-left-radius(@baseBorderRadius);
-  }
-  // For last th/td (can be either) in the last row in the last thead, tbody, and tfoot
-  thead:last-child tr:last-child > th:last-child,
-  tbody:last-child tr:last-child > td:last-child,
-  tbody:last-child tr:last-child > th:last-child,
-  tfoot:last-child tr:last-child > td:last-child,
-  tfoot:last-child tr:last-child > th:last-child {
-    .border-bottom-right-radius(@baseBorderRadius);
-  }
-
-  // Clear border-radius for first and last td in the last row in the last tbody for table with tfoot
-  tfoot + tbody:last-child tr:last-child td:first-child {
-    .border-bottom-left-radius(0);
-  }
-  tfoot + tbody:last-child tr:last-child td:last-child {
-    .border-bottom-right-radius(0);
-  }
-
-  // Special fixes to round the left border on the first td/th
-  caption + thead tr:first-child th:first-child,
-  caption + tbody tr:first-child td:first-child,
-  colgroup + thead tr:first-child th:first-child,
-  colgroup + tbody tr:first-child td:first-child {
-    .border-top-left-radius(@baseBorderRadius);
-  }
-  caption + thead tr:first-child th:last-child,
-  caption + tbody tr:first-child td:last-child,
-  colgroup + thead tr:first-child th:last-child,
-  colgroup + tbody tr:first-child td:last-child {
-    .border-top-right-radius(@baseBorderRadius);
-  }
-
-}
-
-
-
-
-// ZEBRA-STRIPING
-// --------------
-
-// Default zebra-stripe styles (alternating gray and transparent backgrounds)
-.table-striped {
-  tbody {
-    > tr:nth-child(odd) > td,
-    > tr:nth-child(odd) > th {
-      background-color: @tableBackgroundAccent;
-    }
-  }
-}
-
-
-// HOVER EFFECT
-// ------------
-// Placed here since it has to come after the potential zebra striping
-.table-hover {
-  tbody {
-    tr:hover > td,
-    tr:hover > th {
-      background-color: @tableBackgroundHover;
-    }
-  }
-}
-
-
-// TABLE CELL SIZING
-// -----------------
-
-// Reset default grid behavior
-table td[class*="span"],
-table th[class*="span"],
-.row-fluid table td[class*="span"],
-.row-fluid table th[class*="span"] {
-  display: table-cell;
-  float: none; // undo default grid column styles
-  margin-left: 0; // undo default grid column styles
-}
-
-// Change the column widths to account for td/th padding
-.table td,
-.table th {
-  &.span1     { .tableColumns(1); }
-  &.span2     { .tableColumns(2); }
-  &.span3     { .tableColumns(3); }
-  &.span4     { .tableColumns(4); }
-  &.span5     { .tableColumns(5); }
-  &.span6     { .tableColumns(6); }
-  &.span7     { .tableColumns(7); }
-  &.span8     { .tableColumns(8); }
-  &.span9     { .tableColumns(9); }
-  &.span10    { .tableColumns(10); }
-  &.span11    { .tableColumns(11); }
-  &.span12    { .tableColumns(12); }
-}
-
-
-
-// TABLE BACKGROUNDS
-// -----------------
-// Exact selectors below required to override .table-striped
-
-.table tbody tr {
-  &.success > td {
-    background-color: @successBackground;
-  }
-  &.error > td {
-    background-color: @errorBackground;
-  }
-  &.warning > td {
-    background-color: @warningBackground;
-  }
-  &.info > td {
-    background-color: @infoBackground;
-  }
-}
-
-// Hover states for .table-hover
-.table-hover tbody tr {
-  &.success:hover > td {
-    background-color: darken(@successBackground, 5%);
-  }
-  &.error:hover > td {
-    background-color: darken(@errorBackground, 5%);
-  }
-  &.warning:hover > td {
-    background-color: darken(@warningBackground, 5%);
-  }
-  &.info:hover > td {
-    background-color: darken(@infoBackground, 5%);
-  }
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/tests/buttons.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/tests/buttons.html b/apps/fauxton/assets/less/bootstrap/tests/buttons.html
deleted file mode 100644
index 9b3c2c5..0000000
--- a/apps/fauxton/assets/less/bootstrap/tests/buttons.html
+++ /dev/null
@@ -1,139 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-  <head>
-    <meta charset="utf-8">
-    <title>Buttons &middot; Bootstrap</title>
-    <meta name="viewport" content="width=device-width, initial-scale=1.0">
-    <meta name="description" content="">
-    <meta name="author" content="">
-
-    <!-- Le styles -->
-    <link href="../../docs/assets/css/bootstrap.css" rel="stylesheet">
-    <style>
-      body {
-        padding-top: 30px;
-        padding-bottom: 30px;
-      }
-    </style>
-    <link href="../../docs/assets/css/bootstrap-responsive.css" rel="stylesheet">
-
-    <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
-    <!--[if lt IE 9]>
-      <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
-    <![endif]-->
-
-    <!-- Le fav and touch icons -->
-    <link rel="apple-touch-icon-precomposed" sizes="144x144" href="../../docs/assets/ico/apple-touch-icon-144-precomposed.png">
-    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="../../docs/assets/ico/apple-touch-icon-114-precomposed.png">
-      <link rel="apple-touch-icon-precomposed" sizes="72x72" href="../../docs/assets/ico/apple-touch-icon-72-precomposed.png">
-                    <link rel="apple-touch-icon-precomposed" href="../../docs/assets/ico/apple-touch-icon-57-precomposed.png">
-                                   <link rel="shortcut icon" href="../../docs/assets/ico/favicon.png">
-  </head>
-
-  <body>
-
-    <div class="container">
-
-      <h2>Dropups</h2>
-      <div class="btn-toolbar">
-        <div class="btn-group dropup">
-          <button class="btn">Dropup</button>
-          <button class="btn dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button>
-          <ul class="dropdown-menu">
-            <li><a href="#">Action</a></li>
-            <li><a href="#">Another action</a></li>
-            <li><a href="#">Something else here</a></li>
-            <li class="divider"></li>
-            <li><a href="#">Separated link</a></li>
-          </ul>
-        </div><!-- /btn-group -->
-        <div class="btn-group dropup">
-          <button class="btn btn-primary">Dropup</button>
-          <button class="btn btn-primary dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button>
-          <ul class="dropdown-menu">
-            <li><a href="#">Action</a></li>
-            <li><a href="#">Another action</a></li>
-            <li><a href="#">Something else here</a></li>
-            <li class="divider"></li>
-            <li><a href="#">Separated link</a></li>
-          </ul>
-        </div><!-- /btn-group -->
-        <div class="btn-group dropup">
-          <button class="btn btn-danger">Dropup</button>
-          <button class="btn btn-danger dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button>
-          <ul class="dropdown-menu">
-            <li><a href="#">Action</a></li>
-            <li><a href="#">Another action</a></li>
-            <li><a href="#">Something else here</a></li>
-            <li class="divider"></li>
-            <li><a href="#">Separated link</a></li>
-          </ul>
-        </div><!-- /btn-group -->
-        <div class="btn-group dropup">
-          <button class="btn btn-warning">Dropup</button>
-          <button class="btn btn-warning dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button>
-          <ul class="dropdown-menu">
-            <li><a href="#">Action</a></li>
-            <li><a href="#">Another action</a></li>
-            <li><a href="#">Something else here</a></li>
-            <li class="divider"></li>
-            <li><a href="#">Separated link</a></li>
-          </ul>
-        </div><!-- /btn-group -->
-        <div class="btn-group dropup">
-          <button class="btn btn-success">Dropup</button>
-          <button class="btn btn-success dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button>
-          <ul class="dropdown-menu">
-            <li><a href="#">Action</a></li>
-            <li><a href="#">Another action</a></li>
-            <li><a href="#">Something else here</a></li>
-            <li class="divider"></li>
-            <li><a href="#">Separated link</a></li>
-          </ul>
-        </div><!-- /btn-group -->
-        <div class="btn-group dropup">
-          <button class="btn btn-info">Dropup</button>
-          <button class="btn btn-info dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button>
-          <ul class="dropdown-menu">
-            <li><a href="#">Action</a></li>
-            <li><a href="#">Another action</a></li>
-            <li><a href="#">Something else here</a></li>
-            <li class="divider"></li>
-            <li><a href="#">Separated link</a></li>
-          </ul>
-        </div><!-- /btn-group -->
-        <div class="btn-group dropup">
-          <button class="btn btn-inverse">Dropup</button>
-          <button class="btn btn-inverse dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button>
-          <ul class="dropdown-menu">
-            <li><a href="#">Action</a></li>
-            <li><a href="#">Another action</a></li>
-            <li><a href="#">Something else here</a></li>
-            <li class="divider"></li>
-            <li><a href="#">Separated link</a></li>
-          </ul>
-        </div><!-- /btn-group -->
-      </div><!-- /btn-toolbar -->
-
-
-    </div> <!-- /container -->
-
-    <!-- Le javascript
-    ================================================== -->
-    <!-- Placed at the end of the document so the pages load faster -->
-    <script src="../../docs/assets/js/jquery.js"></script>
-    <script src="../../docs/assets/js/bootstrap-transition.js"></script>
-    <script src="../../docs/assets/js/bootstrap-alert.js"></script>
-    <script src="../../docs/assets/js/bootstrap-modal.js"></script>
-    <script src="../../docs/assets/js/bootstrap-dropdown.js"></script>
-    <script src="../../docs/assets/js/bootstrap-scrollspy.js"></script>
-    <script src="../../docs/assets/js/bootstrap-tab.js"></script>
-    <script src="../../docs/assets/js/bootstrap-tooltip.js"></script>
-    <script src="../../docs/assets/js/bootstrap-popover.js"></script>
-    <script src="../../docs/assets/js/bootstrap-button.js"></script>
-    <script src="../../docs/assets/js/bootstrap-collapse.js"></script>
-    <script src="../../docs/assets/js/bootstrap-carousel.js"></script>
-    <script src="../../docs/assets/js/bootstrap-typeahead.js"></script>
-
-  </body>
-</html>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/tests/css-tests.css
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/tests/css-tests.css b/apps/fauxton/assets/less/bootstrap/tests/css-tests.css
deleted file mode 100644
index 0f5604e..0000000
--- a/apps/fauxton/assets/less/bootstrap/tests/css-tests.css
+++ /dev/null
@@ -1,150 +0,0 @@
-/*!
- * Bootstrap CSS Tests
- */
-
-
-/* Remove background image */
-body {
-  background-image: none;
-}
-
-/* Space out subhead */
-.subhead {
-  margin-bottom: 36px;
-}
-/*h4 {
-  margin-bottom: 5px;
-}
-*/
-
-.type-test {
-  margin-bottom: 20px;
-  padding: 0 20px 20px;
-  background: url(../../docs/assets/img/grid-baseline-20px.png);
-}
-.type-test h1,
-.type-test h2,
-.type-test h3,
-.type-test h4,
-.type-test h5,
-.type-test h6 {
-  background-color: rgba(255,0,0,.2);
-}
-
-
-/* colgroup tests */
-.col1 {
-  background-color: rgba(255,0,0,.1);
-}
-.col2 {
-  background-color: rgba(0,255,0,.1);
-}
-.col3 {
-  background-color: rgba(0,0,255,.1);
-}
-
-
-/* Fluid row inputs */
-#rowInputs .row > [class*=span],
-#fluidRowInputs .row-fluid > [class*=span] {
-  background-color: rgba(255,0,0,.1);
-}
-
-
-/* Fluid grid */
-.fluid-grid {
-  margin-bottom: 45px;
-}
-.fluid-grid .row {
-  height: 40px;
-  padding-top: 10px;
-  margin-top: 10px;
-  color: #ddd;
-  text-align: center;
-}
-.fluid-grid .span1 {
-  background-color: #999;
-}
-
-
-/* Gradients */
-
-[class^="gradient-"] {
-  width: 100%;
-  height: 400px;
-  margin: 20px 0;
-  -webkit-border-radius: 5px;
-     -moz-border-radius: 5px;
-          border-radius: 5px;
-}
-
-.gradient-horizontal {
-  background-color: #333333;
-  background-image: -moz-linear-gradient(left, #555555, #333333);
-  background-image: -webkit-gradient(linear, 0 0, 100% 0, from(#555555), to(#333333));
-  background-image: -webkit-linear-gradient(left, #555555, #333333);
-  background-image: -o-linear-gradient(left, #555555, #333333);
-  background-image: linear-gradient(to right, #555555, #333333);
-  background-repeat: repeat-x;
-  filter: progid:dximagetransform.microsoft.gradient(startColorstr='#ff555555', endColorstr='#ff333333', GradientType=1);
-}
-
-.gradient-vertical {
-  background-color: #474747;
-  background-image: -moz-linear-gradient(top, #555555, #333333);
-  background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#555555), to(#333333));
-  background-image: -webkit-linear-gradient(top, #555555, #333333);
-  background-image: -o-linear-gradient(top, #555555, #333333);
-  background-image: linear-gradient(to bottom, #555555, #333333);
-  background-repeat: repeat-x;
-  filter: progid:dximagetransform.microsoft.gradient(startColorstr='#ff555555', endColorstr='#ff333333', GradientType=0);
-}
-
-.gradient-directional {
-  background-color: #333333;
-  background-image: -moz-linear-gradient(45deg, #555555, #333333);
-  background-image: -webkit-linear-gradient(45deg, #555555, #333333);
-  background-image: -o-linear-gradient(45deg, #555555, #333333);
-  background-image: linear-gradient(45deg, #555555, #333333);
-  background-repeat: repeat-x;
-}
-
-.gradient-vertical-three {
-  background-color: #8940a5;
-  background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#00b3ee), color-stop(50%, #7a43b6), to(#c3325f));
-  background-image: -webkit-linear-gradient(#00b3ee, #7a43b6 50%, #c3325f);
-  background-image: -moz-linear-gradient(top, #00b3ee, #7a43b6 50%, #c3325f);
-  background-image: -o-linear-gradient(#00b3ee, #7a43b6 50%, #c3325f);
-  background-image: linear-gradient(#00b3ee, #7a43b6 50%, #c3325f);
-  background-repeat: no-repeat;
-  filter: progid:dximagetransform.microsoft.gradient(startColorstr='#ff00b3ee', endColorstr='#ffc3325f', GradientType=0);
-}
-
-.gradient-radial {
-  background-color: #333333;
-  background-image: -webkit-gradient(radial, center center, 0, center center, 460, from(#555555), to(#333333));
-  background-image: -webkit-radial-gradient(circle, #555555, #333333);
-  background-image: -moz-radial-gradient(circle, #555555, #333333);
-  background-image: -o-radial-gradient(circle, #555555, #333333);
-  background-repeat: no-repeat;
-}
-
-.gradient-striped {
-  background-color: #555555;
-  background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent));
-  background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
-  background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
-  background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
-  background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
-}
-
-.gradient-horizontal-three {
-  background-color: #00b3ee;
-  background-image: -webkit-gradient(left, linear, 0 0, 0 100%, from(#00b3ee), color-stop(50%, #7a43b6), to(#c3325f));
-  background-image: -webkit-linear-gradient(left, #00b3ee, #7a43b6 50%, #c3325f);
-  background-image: -moz-linear-gradient(left, #00b3ee, #7a43b6 50%, #c3325f);
-  background-image: -o-linear-gradient(left, #00b3ee, #7a43b6 50%, #c3325f);
-  background-image: linear-gradient(to right, #00b3ee, #7a43b6 50%, #c3325f);
-  background-repeat: no-repeat;
-  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#00b3ee', endColorstr='#c3325f', GradientType=0);
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/thumbnails.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/thumbnails.less b/apps/fauxton/assets/less/bootstrap/thumbnails.less
deleted file mode 100644
index 4fd07d2..0000000
--- a/apps/fauxton/assets/less/bootstrap/thumbnails.less
+++ /dev/null
@@ -1,53 +0,0 @@
-//
-// Thumbnails
-// --------------------------------------------------
-
-
-// Note: `.thumbnails` and `.thumbnails > li` are overriden in responsive files
-
-// Make wrapper ul behave like the grid
-.thumbnails {
-  margin-left: -@gridGutterWidth;
-  list-style: none;
-  .clearfix();
-}
-// Fluid rows have no left margin
-.row-fluid .thumbnails {
-  margin-left: 0;
-}
-
-// Float li to make thumbnails appear in a row
-.thumbnails > li {
-  float: left; // Explicity set the float since we don't require .span* classes
-  margin-bottom: @baseLineHeight;
-  margin-left: @gridGutterWidth;
-}
-
-// The actual thumbnail (can be `a` or `div`)
-.thumbnail {
-  display: block;
-  padding: 4px;
-  line-height: @baseLineHeight;
-  border: 1px solid #ddd;
-  .border-radius(@baseBorderRadius);
-  .box-shadow(0 1px 3px rgba(0,0,0,.055));
-  .transition(all .2s ease-in-out);
-}
-// Add a hover/focus state for linked versions only
-a.thumbnail:hover,
-a.thumbnail:focus {
-  border-color: @linkColor;
-  .box-shadow(0 1px 4px rgba(0,105,214,.25));
-}
-
-// Images and captions
-.thumbnail > img {
-  display: block;
-  max-width: 100%;
-  margin-left: auto;
-  margin-right: auto;
-}
-.thumbnail .caption {
-  padding: 9px;
-  color: @gray;
-}


[56/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/ushape.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/ushape.h b/src/apps/couch_collate/platform/osx/icu/unicode/ushape.h
new file mode 100644
index 0000000..f165e14
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/ushape.h
@@ -0,0 +1,263 @@
+/*
+******************************************************************************
+*
+*   Copyright (C) 2000-2007, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+*
+******************************************************************************
+*   file name:  ushape.h
+*   encoding:   US-ASCII
+*   tab size:   8 (not used)
+*   indentation:4
+*
+*   created on: 2000jun29
+*   created by: Markus W. Scherer
+*/
+
+#ifndef __USHAPE_H__
+#define __USHAPE_H__
+
+#include "unicode/utypes.h"
+
+/**
+ * \file
+ * \brief C API:  Arabic shaping
+ * 
+ */
+
+/**
+ * Shape Arabic text on a character basis.
+ *
+ * <p>This function performs basic operations for "shaping" Arabic text. It is most
+ * useful for use with legacy data formats and legacy display technology
+ * (simple terminals). All operations are performed on Unicode characters.</p>
+ *
+ * <p>Text-based shaping means that some character code points in the text are
+ * replaced by others depending on the context. It transforms one kind of text
+ * into another. In comparison, modern displays for Arabic text select
+ * appropriate, context-dependent font glyphs for each text element, which means
+ * that they transform text into a glyph vector.</p>
+ *
+ * <p>Text transformations are necessary when modern display technology is not
+ * available or when text needs to be transformed to or from legacy formats that
+ * use "shaped" characters. Since the Arabic script is cursive, connecting
+ * adjacent letters to each other, computers select images for each letter based
+ * on the surrounding letters. This usually results in four images per Arabic
+ * letter: initial, middle, final, and isolated forms. In Unicode, on the other
+ * hand, letters are normally stored abstract, and a display system is expected
+ * to select the necessary glyphs. (This makes searching and other text
+ * processing easier because the same letter has only one code.) It is possible
+ * to mimic this with text transformations because there are characters in
+ * Unicode that are rendered as letters with a specific shape
+ * (or cursive connectivity). They were included for interoperability with
+ * legacy systems and codepages, and for unsophisticated display systems.</p>
+ *
+ * <p>A second kind of text transformations is supported for Arabic digits:
+ * For compatibility with legacy codepages that only include European digits,
+ * it is possible to replace one set of digits by another, changing the
+ * character code points. These operations can be performed for either
+ * Arabic-Indic Digits (U+0660...U+0669) or Eastern (Extended) Arabic-Indic
+ * digits (U+06f0...U+06f9).</p>
+ *
+ * <p>Some replacements may result in more or fewer characters (code points).
+ * By default, this means that the destination buffer may receive text with a
+ * length different from the source length. Some legacy systems rely on the
+ * length of the text to be constant. They expect extra spaces to be added
+ * or consumed either next to the affected character or at the end of the
+ * text.</p>
+ *
+ * <p>For details about the available operations, see the description of the
+ * <code>U_SHAPE_...</code> options.</p>
+ *
+ * @param source The input text.
+ *
+ * @param sourceLength The number of UChars in <code>source</code>.
+ *
+ * @param dest The destination buffer that will receive the results of the
+ *             requested operations. It may be <code>NULL</code> only if
+ *             <code>destSize</code> is 0. The source and destination must not
+ *             overlap.
+ *
+ * @param destSize The size (capacity) of the destination buffer in UChars.
+ *                 If <code>destSize</code> is 0, then no output is produced,
+ *                 but the necessary buffer size is returned ("preflighting").
+ *
+ * @param options This is a 32-bit set of flags that specify the operations
+ *                that are performed on the input text. If no error occurs,
+ *                then the result will always be written to the destination
+ *                buffer.
+ *
+ * @param pErrorCode must be a valid pointer to an error code value,
+ *        which must not indicate a failure before the function call.
+ *
+ * @return The number of UChars written to the destination buffer.
+ *         If an error occured, then no output was written, or it may be
+ *         incomplete. If <code>U_BUFFER_OVERFLOW_ERROR</code> is set, then
+ *         the return value indicates the necessary destination buffer size.
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+u_shapeArabic(const UChar *source, int32_t sourceLength,
+              UChar *dest, int32_t destSize,
+              uint32_t options,
+              UErrorCode *pErrorCode);
+
+/**
+ * Memory option: allow the result to have a different length than the source.
+ * @stable ICU 2.0
+ */
+#define U_SHAPE_LENGTH_GROW_SHRINK              0
+
+/**
+ * Memory option: the result must have the same length as the source.
+ * If more room is necessary, then try to consume spaces next to modified characters.
+ * @stable ICU 2.0
+ */
+#define U_SHAPE_LENGTH_FIXED_SPACES_NEAR        1
+
+/**
+ * Memory option: the result must have the same length as the source.
+ * If more room is necessary, then try to consume spaces at the end of the text.
+ * @stable ICU 2.0
+ */
+#define U_SHAPE_LENGTH_FIXED_SPACES_AT_END      2
+
+/**
+ * Memory option: the result must have the same length as the source.
+ * If more room is necessary, then try to consume spaces at the beginning of the text.
+ * @stable ICU 2.0
+ */
+#define U_SHAPE_LENGTH_FIXED_SPACES_AT_BEGINNING 3
+
+/** Bit mask for memory options. @stable ICU 2.0 */
+#define U_SHAPE_LENGTH_MASK                     3
+
+
+/** Direction indicator: the source is in logical (keyboard) order. @stable ICU 2.0 */
+#define U_SHAPE_TEXT_DIRECTION_LOGICAL          0
+
+/**
+ * Direction indicator:
+ * the source is in visual LTR order,
+ * the leftmost displayed character stored first.
+ * @stable ICU 2.0
+ */
+#define U_SHAPE_TEXT_DIRECTION_VISUAL_LTR       4
+
+/** Bit mask for direction indicators. @stable ICU 2.0 */
+#define U_SHAPE_TEXT_DIRECTION_MASK             4
+
+
+/** Letter shaping option: do not perform letter shaping. @stable ICU 2.0 */
+#define U_SHAPE_LETTERS_NOOP                    0
+
+/** Letter shaping option: replace abstract letter characters by "shaped" ones. @stable ICU 2.0 */
+#define U_SHAPE_LETTERS_SHAPE                   8
+
+/** Letter shaping option: replace "shaped" letter characters by abstract ones. @stable ICU 2.0 */
+#define U_SHAPE_LETTERS_UNSHAPE                 0x10
+
+/**
+ * Letter shaping option: replace abstract letter characters by "shaped" ones.
+ * The only difference with U_SHAPE_LETTERS_SHAPE is that Tashkeel letters
+ * are always "shaped" into the isolated form instead of the medial form
+ * (selecting code points from the Arabic Presentation Forms-B block).
+ * @stable ICU 2.0
+ */
+#define U_SHAPE_LETTERS_SHAPE_TASHKEEL_ISOLATED 0x18
+
+/** Bit mask for letter shaping options. @stable ICU 2.0 */
+#define U_SHAPE_LETTERS_MASK                    0x18
+
+
+/** Digit shaping option: do not perform digit shaping. @stable ICU 2.0 */
+#define U_SHAPE_DIGITS_NOOP                     0
+
+/**
+ * Digit shaping option:
+ * Replace European digits (U+0030...) by Arabic-Indic digits.
+ * @stable ICU 2.0
+ */
+#define U_SHAPE_DIGITS_EN2AN                    0x20
+
+/**
+ * Digit shaping option:
+ * Replace Arabic-Indic digits by European digits (U+0030...).
+ * @stable ICU 2.0
+ */
+#define U_SHAPE_DIGITS_AN2EN                    0x40
+
+/**
+ * Digit shaping option:
+ * Replace European digits (U+0030...) by Arabic-Indic digits if the most recent
+ * strongly directional character is an Arabic letter
+ * (<code>u_charDirection()</code> result <code>U_RIGHT_TO_LEFT_ARABIC</code> [AL]).<br>
+ * The direction of "preceding" depends on the direction indicator option.
+ * For the first characters, the preceding strongly directional character
+ * (initial state) is assumed to be not an Arabic letter
+ * (it is <code>U_LEFT_TO_RIGHT</code> [L] or <code>U_RIGHT_TO_LEFT</code> [R]).
+ * @stable ICU 2.0
+ */
+#define U_SHAPE_DIGITS_ALEN2AN_INIT_LR          0x60
+
+/**
+ * Digit shaping option:
+ * Replace European digits (U+0030...) by Arabic-Indic digits if the most recent
+ * strongly directional character is an Arabic letter
+ * (<code>u_charDirection()</code> result <code>U_RIGHT_TO_LEFT_ARABIC</code> [AL]).<br>
+ * The direction of "preceding" depends on the direction indicator option.
+ * For the first characters, the preceding strongly directional character
+ * (initial state) is assumed to be an Arabic letter.
+ * @stable ICU 2.0
+ */
+#define U_SHAPE_DIGITS_ALEN2AN_INIT_AL          0x80
+
+/** Not a valid option value. May be replaced by a new option. @stable ICU 2.0 */
+#define U_SHAPE_DIGITS_RESERVED                 0xa0
+
+/** Bit mask for digit shaping options. @stable ICU 2.0 */
+#define U_SHAPE_DIGITS_MASK                     0xe0
+
+
+/** Digit type option: Use Arabic-Indic digits (U+0660...U+0669). @stable ICU 2.0 */
+#define U_SHAPE_DIGIT_TYPE_AN                   0
+
+/** Digit type option: Use Eastern (Extended) Arabic-Indic digits (U+06f0...U+06f9). @stable ICU 2.0 */
+#define U_SHAPE_DIGIT_TYPE_AN_EXTENDED          0x100
+
+/** Not a valid option value. May be replaced by a new option. @stable ICU 2.0 */
+#define U_SHAPE_DIGIT_TYPE_RESERVED             0x200
+
+/** Bit mask for digit type options. @stable ICU 2.0 */
+#define U_SHAPE_DIGIT_TYPE_MASK                 0x3f00
+
+/** 
+ * Tashkeel aggregation option:
+ * Replaces any combination of U+0651 with one of
+ * U+064C, U+064D, U+064E, U+064F, U+0650 with
+ * U+FC5E, U+FC5F, U+FC60, U+FC61, U+FC62 consecutively.
+ * @stable ICU 3.6
+ */
+#define U_SHAPE_AGGREGATE_TASHKEEL              0x4000
+/** Tashkeel aggregation option: do not aggregate tashkeels. @stable ICU 3.6 */
+#define U_SHAPE_AGGREGATE_TASHKEEL_NOOP         0
+/** Bit mask for tashkeel aggregation. @stable ICU 3.6 */
+#define U_SHAPE_AGGREGATE_TASHKEEL_MASK         0x4000
+
+/** 
+ * Presentation form option:
+ * Don't replace Arabic Presentation Forms-A and Arabic Presentation Forms-B
+ * characters with 0+06xx characters, before shaping.
+ * @stable ICU 3.6
+ */
+#define U_SHAPE_PRESERVE_PRESENTATION           0x8000
+/** Presentation form option: 
+ * Replace Arabic Presentation Forms-A and Arabic Presentationo Forms-B with 
+ * their unshaped correspondants in range 0+06xx, before shaping.
+ * @stable ICU 3.6 
+ */
+#define U_SHAPE_PRESERVE_PRESENTATION_NOOP      0
+/** Bit mask for preserve presentation form. @stable ICU 3.6 */
+#define U_SHAPE_PRESERVE_PRESENTATION_MASK      0x8000
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/usprep.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/usprep.h b/src/apps/couch_collate/platform/osx/icu/unicode/usprep.h
new file mode 100644
index 0000000..c7e75a5
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/usprep.h
@@ -0,0 +1,156 @@
+/*
+ *******************************************************************************
+ *
+ *   Copyright (C) 2003-2006, International Business Machines
+ *   Corporation and others.  All Rights Reserved.
+ *
+ *******************************************************************************
+ *   file name:  usprep.h
+ *   encoding:   US-ASCII
+ *   tab size:   8 (not used)
+ *   indentation:4
+ *
+ *   created on: 2003jul2
+ *   created by: Ram Viswanadha
+ */
+
+#ifndef __USPREP_H__
+#define __USPREP_H__
+
+/**
+ * \file 
+ * \brief C API: Implements the StringPrep algorithm.
+ */
+
+#include "unicode/utypes.h"
+/**
+ *
+ * StringPrep API implements the StingPrep framework as described by RFC 3454.
+ * StringPrep prepares Unicode strings for use in network protocols.
+ * Profiles of StingPrep are set of rules and data according to with the
+ * Unicode Strings are prepared. Each profiles contains tables which describe
+ * how a code point should be treated. The tables are broadly classied into
+ * <ul>
+ *     <li> Unassinged Table: Contains code points that are unassigned 
+ *          in the Unicode Version supported by StringPrep. Currently 
+ *          RFC 3454 supports Unicode 3.2. </li>
+ *     <li> Prohibited Table: Contains code points that are prohibted from
+ *          the output of the StringPrep processing function. </li>
+ *     <li> Mapping Table: Contains code ponts that are deleted from the output or case mapped. </li>
+ * </ul>
+ * 
+ * The procedure for preparing Unicode strings:
+ * <ol>
+ *      <li> Map: For each character in the input, check if it has a mapping
+ *           and, if so, replace it with its mapping. </li>
+ *      <li> Normalize: Possibly normalize the result of step 1 using Unicode
+ *           normalization. </li>
+ *      <li> Prohibit: Check for any characters that are not allowed in the
+ *        output.  If any are found, return an error.</li>
+ *      <li> Check bidi: Possibly check for right-to-left characters, and if
+ *           any are found, make sure that the whole string satisfies the
+ *           requirements for bidirectional strings.  If the string does not
+ *           satisfy the requirements for bidirectional strings, return an
+ *           error.  </li>
+ * </ol>
+ * @author Ram Viswanadha
+ */
+#if !UCONFIG_NO_IDNA
+
+#include "unicode/parseerr.h"
+
+/**
+ * The StringPrep profile
+ * @stable ICU 2.8
+ */
+typedef struct UStringPrepProfile UStringPrepProfile;
+
+
+/** 
+ * Option to prohibit processing of unassigned code points in the input
+ * 
+ * @see  usprep_prepare
+ * @stable ICU 2.8
+ */
+#define USPREP_DEFAULT 0x0000
+
+/** 
+ * Option to allow processing of unassigned code points in the input
+ * 
+ * @see  usprep_prepare
+ * @stable ICU 2.8
+ */
+#define USPREP_ALLOW_UNASSIGNED 0x0001
+
+
+/**
+ * Creates a StringPrep profile from the data file.
+ *
+ * @param path      string containing the full path pointing to the directory
+ *                  where the profile reside followed by the package name
+ *                  e.g. "/usr/resource/my_app/profiles/mydata" on a Unix system.
+ *                  if NULL, ICU default data files will be used.
+ * @param fileName  name of the profile file to be opened
+ * @param status    ICU error code in/out parameter. Must not be NULL.
+ *                  Must fulfill U_SUCCESS before the function call.
+ * @return Pointer to UStringPrepProfile that is opened. Should be closed by
+ * calling usprep_close()
+ * @see usprep_close()
+ * @stable ICU 2.8
+ */
+U_STABLE UStringPrepProfile* U_EXPORT2
+usprep_open(const char* path, 
+            const char* fileName,
+            UErrorCode* status);
+
+
+/**
+ * Closes the profile
+ * @param profile The profile to close
+ * @stable ICU 2.8
+ */
+U_STABLE void U_EXPORT2
+usprep_close(UStringPrepProfile* profile);
+
+
+/**
+ * Prepare the input buffer for use in applications with the given profile. This operation maps, normalizes(NFKC),
+ * checks for prohited and BiDi characters in the order defined by RFC 3454
+ * depending on the options specified in the profile.
+ *
+ * @param prep          The profile to use 
+ * @param src           Pointer to UChar buffer containing the string to prepare
+ * @param srcLength     Number of characters in the source string
+ * @param dest          Pointer to the destination buffer to receive the output
+ * @param destCapacity  The capacity of destination array
+ * @param options       A bit set of options:
+ *
+ *  - USPREP_NONE               Prohibit processing of unassigned code points in the input
+ *
+ *  - USPREP_ALLOW_UNASSIGNED   Treat the unassigned code points are in the input 
+ *                              as normal Unicode code points.
+ *
+ * @param parseError        Pointer to UParseError struct to receive information on position 
+ *                          of error if an error is encountered. Can be NULL.
+ * @param status            ICU in/out error code parameter.
+ *                          U_INVALID_CHAR_FOUND if src contains
+ *                          unmatched single surrogates.
+ *                          U_INDEX_OUTOFBOUNDS_ERROR if src contains
+ *                          too many code points.
+ *                          U_BUFFER_OVERFLOW_ERROR if destCapacity is not enough
+ * @return The number of UChars in the destination buffer
+ * @stable ICU 2.8
+ */
+
+U_STABLE int32_t U_EXPORT2
+usprep_prepare(   const UStringPrepProfile* prep,
+                  const UChar* src, int32_t srcLength, 
+                  UChar* dest, int32_t destCapacity,
+                  int32_t options,
+                  UParseError* parseError,
+                  UErrorCode* status );
+
+
+#endif /* #if !UCONFIG_NO_IDNA */
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/ustring.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/ustring.h b/src/apps/couch_collate/platform/osx/icu/unicode/ustring.h
new file mode 100644
index 0000000..12411ef
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/ustring.h
@@ -0,0 +1,1479 @@
+/*
+**********************************************************************
+*   Copyright (C) 1998-2008, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+**********************************************************************
+*
+* File ustring.h
+*
+* Modification History:
+*
+*   Date        Name        Description
+*   12/07/98    bertrand    Creation.
+******************************************************************************
+*/
+
+#ifndef USTRING_H
+#define USTRING_H
+
+#include "unicode/utypes.h"
+#include "unicode/putil.h"
+#include "unicode/uiter.h"
+
+/** Simple declaration for u_strToTitle() to avoid including unicode/ubrk.h. @stable ICU 2.1*/
+#ifndef UBRK_TYPEDEF_UBREAK_ITERATOR
+#   define UBRK_TYPEDEF_UBREAK_ITERATOR
+    typedef void UBreakIterator;
+#endif
+
+/**
+ * \file
+ * \brief C API: Unicode string handling functions
+ *
+ * These C API functions provide general Unicode string handling.
+ *
+ * Some functions are equivalent in name, signature, and behavior to the ANSI C <string.h>
+ * functions. (For example, they do not check for bad arguments like NULL string pointers.)
+ * In some cases, only the thread-safe variant of such a function is implemented here
+ * (see u_strtok_r()).
+ *
+ * Other functions provide more Unicode-specific functionality like locale-specific
+ * upper/lower-casing and string comparison in code point order.
+ *
+ * ICU uses 16-bit Unicode (UTF-16) in the form of arrays of UChar code units.
+ * UTF-16 encodes each Unicode code point with either one or two UChar code units.
+ * (This is the default form of Unicode, and a forward-compatible extension of the original,
+ * fixed-width form that was known as UCS-2. UTF-16 superseded UCS-2 with Unicode 2.0
+ * in 1996.)
+ *
+ * Some APIs accept a 32-bit UChar32 value for a single code point.
+ *
+ * ICU also handles 16-bit Unicode text with unpaired surrogates.
+ * Such text is not well-formed UTF-16.
+ * Code-point-related functions treat unpaired surrogates as surrogate code points,
+ * i.e., as separate units.
+ *
+ * Although UTF-16 is a variable-width encoding form (like some legacy multi-byte encodings),
+ * it is much more efficient even for random access because the code unit values
+ * for single-unit characters vs. lead units vs. trail units are completely disjoint.
+ * This means that it is easy to determine character (code point) boundaries from
+ * random offsets in the string.
+ *
+ * Unicode (UTF-16) string processing is optimized for the single-unit case.
+ * Although it is important to support supplementary characters
+ * (which use pairs of lead/trail code units called "surrogates"),
+ * their occurrence is rare. Almost all characters in modern use require only
+ * a single UChar code unit (i.e., their code point values are <=0xffff).
+ *
+ * For more details see the User Guide Strings chapter (http://icu-project.org/userguide/strings.html).
+ * For a discussion of the handling of unpaired surrogates see also
+ * Jitterbug 2145 and its icu mailing list proposal on 2002-sep-18.
+ */
+
+/**
+ * \defgroup ustring_ustrlen String Length
+ * \ingroup ustring_strlen
+ */
+/*@{*/
+/**
+ * Determine the length of an array of UChar.
+ *
+ * @param s The array of UChars, NULL (U+0000) terminated.
+ * @return The number of UChars in <code>chars</code>, minus the terminator.
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+u_strlen(const UChar *s);
+/*@}*/
+
+/**
+ * Count Unicode code points in the length UChar code units of the string.
+ * A code point may occupy either one or two UChar code units.
+ * Counting code points involves reading all code units.
+ *
+ * This functions is basically the inverse of the U16_FWD_N() macro (see utf.h).
+ *
+ * @param s The input string.
+ * @param length The number of UChar code units to be checked, or -1 to count all
+ *               code points before the first NUL (U+0000).
+ * @return The number of code points in the specified code units.
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+u_countChar32(const UChar *s, int32_t length);
+
+/**
+ * Check if the string contains more Unicode code points than a certain number.
+ * This is more efficient than counting all code points in the entire string
+ * and comparing that number with a threshold.
+ * This function may not need to scan the string at all if the length is known
+ * (not -1 for NUL-termination) and falls within a certain range, and
+ * never needs to count more than 'number+1' code points.
+ * Logically equivalent to (u_countChar32(s, length)>number).
+ * A Unicode code point may occupy either one or two UChar code units.
+ *
+ * @param s The input string.
+ * @param length The length of the string, or -1 if it is NUL-terminated.
+ * @param number The number of code points in the string is compared against
+ *               the 'number' parameter.
+ * @return Boolean value for whether the string contains more Unicode code points
+ *         than 'number'. Same as (u_countChar32(s, length)>number).
+ * @stable ICU 2.4
+ */
+U_STABLE UBool U_EXPORT2
+u_strHasMoreChar32Than(const UChar *s, int32_t length, int32_t number);
+
+/**
+ * Concatenate two ustrings.  Appends a copy of <code>src</code>,
+ * including the null terminator, to <code>dst</code>. The initial copied
+ * character from <code>src</code> overwrites the null terminator in <code>dst</code>.
+ *
+ * @param dst The destination string.
+ * @param src The source string.
+ * @return A pointer to <code>dst</code>.
+ * @stable ICU 2.0
+ */
+U_STABLE UChar* U_EXPORT2
+u_strcat(UChar     *dst, 
+    const UChar     *src);
+
+/**
+ * Concatenate two ustrings.  
+ * Appends at most <code>n</code> characters from <code>src</code> to <code>dst</code>.
+ * Adds a terminating NUL.
+ * If src is too long, then only <code>n-1</code> characters will be copied
+ * before the terminating NUL.
+ * If <code>n&lt;=0</code> then dst is not modified.
+ *
+ * @param dst The destination string.
+ * @param src The source string.
+ * @param n The maximum number of characters to compare.
+ * @return A pointer to <code>dst</code>.
+ * @stable ICU 2.0
+ */
+U_STABLE UChar* U_EXPORT2
+u_strncat(UChar     *dst, 
+     const UChar     *src, 
+     int32_t     n);
+
+/**
+ * Find the first occurrence of a substring in a string.
+ * The substring is found at code point boundaries.
+ * That means that if the substring begins with
+ * a trail surrogate or ends with a lead surrogate,
+ * then it is found only if these surrogates stand alone in the text.
+ * Otherwise, the substring edge units would be matched against
+ * halves of surrogate pairs.
+ *
+ * @param s The string to search (NUL-terminated).
+ * @param substring The substring to find (NUL-terminated).
+ * @return A pointer to the first occurrence of <code>substring</code> in <code>s</code>,
+ *         or <code>s</code> itself if the <code>substring</code> is empty,
+ *         or <code>NULL</code> if <code>substring</code> is not in <code>s</code>.
+ * @stable ICU 2.0
+ *
+ * @see u_strrstr
+ * @see u_strFindFirst
+ * @see u_strFindLast
+ */
+U_STABLE UChar * U_EXPORT2
+u_strstr(const UChar *s, const UChar *substring);
+
+/**
+ * Find the first occurrence of a substring in a string.
+ * The substring is found at code point boundaries.
+ * That means that if the substring begins with
+ * a trail surrogate or ends with a lead surrogate,
+ * then it is found only if these surrogates stand alone in the text.
+ * Otherwise, the substring edge units would be matched against
+ * halves of surrogate pairs.
+ *
+ * @param s The string to search.
+ * @param length The length of s (number of UChars), or -1 if it is NUL-terminated.
+ * @param substring The substring to find (NUL-terminated).
+ * @param subLength The length of substring (number of UChars), or -1 if it is NUL-terminated.
+ * @return A pointer to the first occurrence of <code>substring</code> in <code>s</code>,
+ *         or <code>s</code> itself if the <code>substring</code> is empty,
+ *         or <code>NULL</code> if <code>substring</code> is not in <code>s</code>.
+ * @stable ICU 2.4
+ *
+ * @see u_strstr
+ * @see u_strFindLast
+ */
+U_STABLE UChar * U_EXPORT2
+u_strFindFirst(const UChar *s, int32_t length, const UChar *substring, int32_t subLength);
+
+/**
+ * Find the first occurrence of a BMP code point in a string.
+ * A surrogate code point is found only if its match in the text is not
+ * part of a surrogate pair.
+ * A NUL character is found at the string terminator.
+ *
+ * @param s The string to search (NUL-terminated).
+ * @param c The BMP code point to find.
+ * @return A pointer to the first occurrence of <code>c</code> in <code>s</code>
+ *         or <code>NULL</code> if <code>c</code> is not in <code>s</code>.
+ * @stable ICU 2.0
+ *
+ * @see u_strchr32
+ * @see u_memchr
+ * @see u_strstr
+ * @see u_strFindFirst
+ */
+U_STABLE UChar * U_EXPORT2
+u_strchr(const UChar *s, UChar c);
+
+/**
+ * Find the first occurrence of a code point in a string.
+ * A surrogate code point is found only if its match in the text is not
+ * part of a surrogate pair.
+ * A NUL character is found at the string terminator.
+ *
+ * @param s The string to search (NUL-terminated).
+ * @param c The code point to find.
+ * @return A pointer to the first occurrence of <code>c</code> in <code>s</code>
+ *         or <code>NULL</code> if <code>c</code> is not in <code>s</code>.
+ * @stable ICU 2.0
+ *
+ * @see u_strchr
+ * @see u_memchr32
+ * @see u_strstr
+ * @see u_strFindFirst
+ */
+U_STABLE UChar * U_EXPORT2
+u_strchr32(const UChar *s, UChar32 c);
+
+/**
+ * Find the last occurrence of a substring in a string.
+ * The substring is found at code point boundaries.
+ * That means that if the substring begins with
+ * a trail surrogate or ends with a lead surrogate,
+ * then it is found only if these surrogates stand alone in the text.
+ * Otherwise, the substring edge units would be matched against
+ * halves of surrogate pairs.
+ *
+ * @param s The string to search (NUL-terminated).
+ * @param substring The substring to find (NUL-terminated).
+ * @return A pointer to the last occurrence of <code>substring</code> in <code>s</code>,
+ *         or <code>s</code> itself if the <code>substring</code> is empty,
+ *         or <code>NULL</code> if <code>substring</code> is not in <code>s</code>.
+ * @stable ICU 2.4
+ *
+ * @see u_strstr
+ * @see u_strFindFirst
+ * @see u_strFindLast
+ */
+U_STABLE UChar * U_EXPORT2
+u_strrstr(const UChar *s, const UChar *substring);
+
+/**
+ * Find the last occurrence of a substring in a string.
+ * The substring is found at code point boundaries.
+ * That means that if the substring begins with
+ * a trail surrogate or ends with a lead surrogate,
+ * then it is found only if these surrogates stand alone in the text.
+ * Otherwise, the substring edge units would be matched against
+ * halves of surrogate pairs.
+ *
+ * @param s The string to search.
+ * @param length The length of s (number of UChars), or -1 if it is NUL-terminated.
+ * @param substring The substring to find (NUL-terminated).
+ * @param subLength The length of substring (number of UChars), or -1 if it is NUL-terminated.
+ * @return A pointer to the last occurrence of <code>substring</code> in <code>s</code>,
+ *         or <code>s</code> itself if the <code>substring</code> is empty,
+ *         or <code>NULL</code> if <code>substring</code> is not in <code>s</code>.
+ * @stable ICU 2.4
+ *
+ * @see u_strstr
+ * @see u_strFindLast
+ */
+U_STABLE UChar * U_EXPORT2
+u_strFindLast(const UChar *s, int32_t length, const UChar *substring, int32_t subLength);
+
+/**
+ * Find the last occurrence of a BMP code point in a string.
+ * A surrogate code point is found only if its match in the text is not
+ * part of a surrogate pair.
+ * A NUL character is found at the string terminator.
+ *
+ * @param s The string to search (NUL-terminated).
+ * @param c The BMP code point to find.
+ * @return A pointer to the last occurrence of <code>c</code> in <code>s</code>
+ *         or <code>NULL</code> if <code>c</code> is not in <code>s</code>.
+ * @stable ICU 2.4
+ *
+ * @see u_strrchr32
+ * @see u_memrchr
+ * @see u_strrstr
+ * @see u_strFindLast
+ */
+U_STABLE UChar * U_EXPORT2
+u_strrchr(const UChar *s, UChar c);
+
+/**
+ * Find the last occurrence of a code point in a string.
+ * A surrogate code point is found only if its match in the text is not
+ * part of a surrogate pair.
+ * A NUL character is found at the string terminator.
+ *
+ * @param s The string to search (NUL-terminated).
+ * @param c The code point to find.
+ * @return A pointer to the last occurrence of <code>c</code> in <code>s</code>
+ *         or <code>NULL</code> if <code>c</code> is not in <code>s</code>.
+ * @stable ICU 2.4
+ *
+ * @see u_strrchr
+ * @see u_memchr32
+ * @see u_strrstr
+ * @see u_strFindLast
+ */
+U_STABLE UChar * U_EXPORT2
+u_strrchr32(const UChar *s, UChar32 c);
+
+/**
+ * Locates the first occurrence in the string <code>string</code> of any of the characters
+ * in the string <code>matchSet</code>.
+ * Works just like C's strpbrk but with Unicode.
+ *
+ * @param string The string in which to search, NUL-terminated.
+ * @param matchSet A NUL-terminated string defining a set of code points
+ *                 for which to search in the text string.
+ * @return A pointer to the  character in <code>string</code> that matches one of the
+ *         characters in <code>matchSet</code>, or NULL if no such character is found.
+ * @stable ICU 2.0
+ */
+U_STABLE UChar * U_EXPORT2
+u_strpbrk(const UChar *string, const UChar *matchSet);
+
+/**
+ * Returns the number of consecutive characters in <code>string</code>,
+ * beginning with the first, that do not occur somewhere in <code>matchSet</code>.
+ * Works just like C's strcspn but with Unicode.
+ *
+ * @param string The string in which to search, NUL-terminated.
+ * @param matchSet A NUL-terminated string defining a set of code points
+ *                 for which to search in the text string.
+ * @return The number of initial characters in <code>string</code> that do not
+ *         occur in <code>matchSet</code>.
+ * @see u_strspn
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+u_strcspn(const UChar *string, const UChar *matchSet);
+
+/**
+ * Returns the number of consecutive characters in <code>string</code>,
+ * beginning with the first, that occur somewhere in <code>matchSet</code>.
+ * Works just like C's strspn but with Unicode.
+ *
+ * @param string The string in which to search, NUL-terminated.
+ * @param matchSet A NUL-terminated string defining a set of code points
+ *                 for which to search in the text string.
+ * @return The number of initial characters in <code>string</code> that do
+ *         occur in <code>matchSet</code>.
+ * @see u_strcspn
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+u_strspn(const UChar *string, const UChar *matchSet);
+
+/**
+ * The string tokenizer API allows an application to break a string into
+ * tokens. Unlike strtok(), the saveState (the current pointer within the
+ * original string) is maintained in saveState. In the first call, the
+ * argument src is a pointer to the string. In subsequent calls to
+ * return successive tokens of that string, src must be specified as
+ * NULL. The value saveState is set by this function to maintain the
+ * function's position within the string, and on each subsequent call
+ * you must give this argument the same variable. This function does
+ * handle surrogate pairs. This function is similar to the strtok_r()
+ * the POSIX Threads Extension (1003.1c-1995) version.
+ *
+ * @param src String containing token(s). This string will be modified.
+ *            After the first call to u_strtok_r(), this argument must
+ *            be NULL to get to the next token.
+ * @param delim Set of delimiter characters (Unicode code points).
+ * @param saveState The current pointer within the original string,
+ *              which is set by this function. The saveState
+ *              parameter should the address of a local variable of type
+ *              UChar *. (i.e. defined "Uhar *myLocalSaveState" and use
+ *              &myLocalSaveState for this parameter).
+ * @return A pointer to the next token found in src, or NULL
+ *         when there are no more tokens.
+ * @stable ICU 2.0
+ */
+U_STABLE UChar * U_EXPORT2
+u_strtok_r(UChar    *src, 
+     const UChar    *delim,
+           UChar   **saveState);
+
+/**
+ * Compare two Unicode strings for bitwise equality (code unit order).
+ *
+ * @param s1 A string to compare.
+ * @param s2 A string to compare.
+ * @return 0 if <code>s1</code> and <code>s2</code> are bitwise equal; a negative
+ * value if <code>s1</code> is bitwise less than <code>s2,</code>; a positive
+ * value if <code>s1</code> is bitwise greater than <code>s2</code>.
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t  U_EXPORT2
+u_strcmp(const UChar     *s1, 
+         const UChar     *s2);
+
+/**
+ * Compare two Unicode strings in code point order.
+ * See u_strCompare for details.
+ *
+ * @param s1 A string to compare.
+ * @param s2 A string to compare.
+ * @return a negative/zero/positive integer corresponding to whether
+ * the first string is less than/equal to/greater than the second one
+ * in code point order
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+u_strcmpCodePointOrder(const UChar *s1, const UChar *s2);
+
+/**
+ * Compare two Unicode strings (binary order).
+ *
+ * The comparison can be done in code unit order or in code point order.
+ * They differ only in UTF-16 when
+ * comparing supplementary code points (U+10000..U+10ffff)
+ * to BMP code points near the end of the BMP (i.e., U+e000..U+ffff).
+ * In code unit order, high BMP code points sort after supplementary code points
+ * because they are stored as pairs of surrogates which are at U+d800..U+dfff.
+ *
+ * This functions works with strings of different explicitly specified lengths
+ * unlike the ANSI C-like u_strcmp() and u_memcmp() etc.
+ * NUL-terminated strings are possible with length arguments of -1.
+ *
+ * @param s1 First source string.
+ * @param length1 Length of first source string, or -1 if NUL-terminated.
+ *
+ * @param s2 Second source string.
+ * @param length2 Length of second source string, or -1 if NUL-terminated.
+ *
+ * @param codePointOrder Choose between code unit order (FALSE)
+ *                       and code point order (TRUE).
+ *
+ * @return <0 or 0 or >0 as usual for string comparisons
+ *
+ * @stable ICU 2.2
+ */
+U_STABLE int32_t U_EXPORT2
+u_strCompare(const UChar *s1, int32_t length1,
+             const UChar *s2, int32_t length2,
+             UBool codePointOrder);
+
+/**
+ * Compare two Unicode strings (binary order)
+ * as presented by UCharIterator objects.
+ * Works otherwise just like u_strCompare().
+ *
+ * Both iterators are reset to their start positions.
+ * When the function returns, it is undefined where the iterators
+ * have stopped.
+ *
+ * @param iter1 First source string iterator.
+ * @param iter2 Second source string iterator.
+ * @param codePointOrder Choose between code unit order (FALSE)
+ *                       and code point order (TRUE).
+ *
+ * @return <0 or 0 or >0 as usual for string comparisons
+ *
+ * @see u_strCompare
+ *
+ * @stable ICU 2.6
+ */
+U_STABLE int32_t U_EXPORT2
+u_strCompareIter(UCharIterator *iter1, UCharIterator *iter2, UBool codePointOrder);
+
+#ifndef U_COMPARE_CODE_POINT_ORDER
+/* see also unistr.h and unorm.h */
+/**
+ * Option bit for u_strCaseCompare, u_strcasecmp, unorm_compare, etc:
+ * Compare strings in code point order instead of code unit order.
+ * @stable ICU 2.2
+ */
+#define U_COMPARE_CODE_POINT_ORDER  0x8000
+#endif
+
+/**
+ * Compare two strings case-insensitively using full case folding.
+ * This is equivalent to
+ *   u_strCompare(u_strFoldCase(s1, options),
+ *                u_strFoldCase(s2, options),
+ *                (options&U_COMPARE_CODE_POINT_ORDER)!=0).
+ *
+ * The comparison can be done in UTF-16 code unit order or in code point order.
+ * They differ only when comparing supplementary code points (U+10000..U+10ffff)
+ * to BMP code points near the end of the BMP (i.e., U+e000..U+ffff).
+ * In code unit order, high BMP code points sort after supplementary code points
+ * because they are stored as pairs of surrogates which are at U+d800..U+dfff.
+ *
+ * This functions works with strings of different explicitly specified lengths
+ * unlike the ANSI C-like u_strcmp() and u_memcmp() etc.
+ * NUL-terminated strings are possible with length arguments of -1.
+ *
+ * @param s1 First source string.
+ * @param length1 Length of first source string, or -1 if NUL-terminated.
+ *
+ * @param s2 Second source string.
+ * @param length2 Length of second source string, or -1 if NUL-terminated.
+ *
+ * @param options A bit set of options:
+ *   - U_FOLD_CASE_DEFAULT or 0 is used for default options:
+ *     Comparison in code unit order with default case folding.
+ *
+ *   - U_COMPARE_CODE_POINT_ORDER
+ *     Set to choose code point order instead of code unit order
+ *     (see u_strCompare for details).
+ *
+ *   - U_FOLD_CASE_EXCLUDE_SPECIAL_I
+ *
+ * @param pErrorCode Must be a valid pointer to an error code value,
+ *                  which must not indicate a failure before the function call.
+ *
+ * @return <0 or 0 or >0 as usual for string comparisons
+ *
+ * @stable ICU 2.2
+ */
+U_STABLE int32_t U_EXPORT2
+u_strCaseCompare(const UChar *s1, int32_t length1,
+                 const UChar *s2, int32_t length2,
+                 uint32_t options,
+                 UErrorCode *pErrorCode);
+
+/**
+ * Compare two ustrings for bitwise equality. 
+ * Compares at most <code>n</code> characters.
+ *
+ * @param ucs1 A string to compare.
+ * @param ucs2 A string to compare.
+ * @param n The maximum number of characters to compare.
+ * @return 0 if <code>s1</code> and <code>s2</code> are bitwise equal; a negative
+ * value if <code>s1</code> is bitwise less than <code>s2</code>; a positive
+ * value if <code>s1</code> is bitwise greater than <code>s2</code>.
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+u_strncmp(const UChar     *ucs1, 
+     const UChar     *ucs2, 
+     int32_t     n);
+
+/**
+ * Compare two Unicode strings in code point order.
+ * This is different in UTF-16 from u_strncmp() if supplementary characters are present.
+ * For details, see u_strCompare().
+ *
+ * @param s1 A string to compare.
+ * @param s2 A string to compare.
+ * @param n The maximum number of characters to compare.
+ * @return a negative/zero/positive integer corresponding to whether
+ * the first string is less than/equal to/greater than the second one
+ * in code point order
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+u_strncmpCodePointOrder(const UChar *s1, const UChar *s2, int32_t n);
+
+/**
+ * Compare two strings case-insensitively using full case folding.
+ * This is equivalent to u_strcmp(u_strFoldCase(s1, options), u_strFoldCase(s2, options)).
+ *
+ * @param s1 A string to compare.
+ * @param s2 A string to compare.
+ * @param options A bit set of options:
+ *   - U_FOLD_CASE_DEFAULT or 0 is used for default options:
+ *     Comparison in code unit order with default case folding.
+ *
+ *   - U_COMPARE_CODE_POINT_ORDER
+ *     Set to choose code point order instead of code unit order
+ *     (see u_strCompare for details).
+ *
+ *   - U_FOLD_CASE_EXCLUDE_SPECIAL_I
+ *
+ * @return A negative, zero, or positive integer indicating the comparison result.
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+u_strcasecmp(const UChar *s1, const UChar *s2, uint32_t options);
+
+/**
+ * Compare two strings case-insensitively using full case folding.
+ * This is equivalent to u_strcmp(u_strFoldCase(s1, at most n, options),
+ * u_strFoldCase(s2, at most n, options)).
+ *
+ * @param s1 A string to compare.
+ * @param s2 A string to compare.
+ * @param n The maximum number of characters each string to case-fold and then compare.
+ * @param options A bit set of options:
+ *   - U_FOLD_CASE_DEFAULT or 0 is used for default options:
+ *     Comparison in code unit order with default case folding.
+ *
+ *   - U_COMPARE_CODE_POINT_ORDER
+ *     Set to choose code point order instead of code unit order
+ *     (see u_strCompare for details).
+ *
+ *   - U_FOLD_CASE_EXCLUDE_SPECIAL_I
+ *
+ * @return A negative, zero, or positive integer indicating the comparison result.
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+u_strncasecmp(const UChar *s1, const UChar *s2, int32_t n, uint32_t options);
+
+/**
+ * Compare two strings case-insensitively using full case folding.
+ * This is equivalent to u_strcmp(u_strFoldCase(s1, n, options),
+ * u_strFoldCase(s2, n, options)).
+ *
+ * @param s1 A string to compare.
+ * @param s2 A string to compare.
+ * @param length The number of characters in each string to case-fold and then compare.
+ * @param options A bit set of options:
+ *   - U_FOLD_CASE_DEFAULT or 0 is used for default options:
+ *     Comparison in code unit order with default case folding.
+ *
+ *   - U_COMPARE_CODE_POINT_ORDER
+ *     Set to choose code point order instead of code unit order
+ *     (see u_strCompare for details).
+ *
+ *   - U_FOLD_CASE_EXCLUDE_SPECIAL_I
+ *
+ * @return A negative, zero, or positive integer indicating the comparison result.
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+u_memcasecmp(const UChar *s1, const UChar *s2, int32_t length, uint32_t options);
+
+/**
+ * Copy a ustring. Adds a null terminator.
+ *
+ * @param dst The destination string.
+ * @param src The source string.
+ * @return A pointer to <code>dst</code>.
+ * @stable ICU 2.0
+ */
+U_STABLE UChar* U_EXPORT2
+u_strcpy(UChar     *dst, 
+    const UChar     *src);
+
+/**
+ * Copy a ustring.
+ * Copies at most <code>n</code> characters.  The result will be null terminated
+ * if the length of <code>src</code> is less than <code>n</code>.
+ *
+ * @param dst The destination string.
+ * @param src The source string.
+ * @param n The maximum number of characters to copy.
+ * @return A pointer to <code>dst</code>.
+ * @stable ICU 2.0
+ */
+U_STABLE UChar* U_EXPORT2
+u_strncpy(UChar     *dst, 
+     const UChar     *src, 
+     int32_t     n);
+
+#if !UCONFIG_NO_CONVERSION
+
+/**
+ * Copy a byte string encoded in the default codepage to a ustring.
+ * Adds a null terminator.
+ * Performs a host byte to UChar conversion
+ *
+ * @param dst The destination string.
+ * @param src The source string.
+ * @return A pointer to <code>dst</code>.
+ * @stable ICU 2.0
+ */
+U_STABLE UChar* U_EXPORT2 u_uastrcpy(UChar *dst,
+               const char *src );
+
+/**
+ * Copy a byte string encoded in the default codepage to a ustring.
+ * Copies at most <code>n</code> characters.  The result will be null terminated
+ * if the length of <code>src</code> is less than <code>n</code>.
+ * Performs a host byte to UChar conversion
+ *
+ * @param dst The destination string.
+ * @param src The source string.
+ * @param n The maximum number of characters to copy.
+ * @return A pointer to <code>dst</code>.
+ * @stable ICU 2.0
+ */
+U_STABLE UChar* U_EXPORT2 u_uastrncpy(UChar *dst,
+            const char *src,
+            int32_t n);
+
+/**
+ * Copy ustring to a byte string encoded in the default codepage.
+ * Adds a null terminator.
+ * Performs a UChar to host byte conversion
+ *
+ * @param dst The destination string.
+ * @param src The source string.
+ * @return A pointer to <code>dst</code>.
+ * @stable ICU 2.0
+ */
+U_STABLE char* U_EXPORT2 u_austrcpy(char *dst,
+            const UChar *src );
+
+/**
+ * Copy ustring to a byte string encoded in the default codepage.
+ * Copies at most <code>n</code> characters.  The result will be null terminated
+ * if the length of <code>src</code> is less than <code>n</code>.
+ * Performs a UChar to host byte conversion
+ *
+ * @param dst The destination string.
+ * @param src The source string.
+ * @param n The maximum number of characters to copy.
+ * @return A pointer to <code>dst</code>.
+ * @stable ICU 2.0
+ */
+U_STABLE char* U_EXPORT2 u_austrncpy(char *dst,
+            const UChar *src,
+            int32_t n );
+
+#endif
+
+/**
+ * Synonym for memcpy(), but with UChars only.
+ * @param dest The destination string
+ * @param src The source string
+ * @param count The number of characters to copy
+ * @return A pointer to <code>dest</code>
+ * @stable ICU 2.0
+ */
+U_STABLE UChar* U_EXPORT2
+u_memcpy(UChar *dest, const UChar *src, int32_t count);
+
+/**
+ * Synonym for memmove(), but with UChars only.
+ * @param dest The destination string
+ * @param src The source string
+ * @param count The number of characters to move
+ * @return A pointer to <code>dest</code>
+ * @stable ICU 2.0
+ */
+U_STABLE UChar* U_EXPORT2
+u_memmove(UChar *dest, const UChar *src, int32_t count);
+
+/**
+ * Initialize <code>count</code> characters of <code>dest</code> to <code>c</code>.
+ *
+ * @param dest The destination string.
+ * @param c The character to initialize the string.
+ * @param count The maximum number of characters to set.
+ * @return A pointer to <code>dest</code>.
+ * @stable ICU 2.0
+ */
+U_STABLE UChar* U_EXPORT2
+u_memset(UChar *dest, UChar c, int32_t count);
+
+/**
+ * Compare the first <code>count</code> UChars of each buffer.
+ *
+ * @param buf1 The first string to compare.
+ * @param buf2 The second string to compare.
+ * @param count The maximum number of UChars to compare.
+ * @return When buf1 < buf2, a negative number is returned.
+ *      When buf1 == buf2, 0 is returned.
+ *      When buf1 > buf2, a positive number is returned.
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+u_memcmp(const UChar *buf1, const UChar *buf2, int32_t count);
+
+/**
+ * Compare two Unicode strings in code point order.
+ * This is different in UTF-16 from u_memcmp() if supplementary characters are present.
+ * For details, see u_strCompare().
+ *
+ * @param s1 A string to compare.
+ * @param s2 A string to compare.
+ * @param count The maximum number of characters to compare.
+ * @return a negative/zero/positive integer corresponding to whether
+ * the first string is less than/equal to/greater than the second one
+ * in code point order
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+u_memcmpCodePointOrder(const UChar *s1, const UChar *s2, int32_t count);
+
+/**
+ * Find the first occurrence of a BMP code point in a string.
+ * A surrogate code point is found only if its match in the text is not
+ * part of a surrogate pair.
+ * A NUL character is found at the string terminator.
+ *
+ * @param s The string to search (contains <code>count</code> UChars).
+ * @param c The BMP code point to find.
+ * @param count The length of the string.
+ * @return A pointer to the first occurrence of <code>c</code> in <code>s</code>
+ *         or <code>NULL</code> if <code>c</code> is not in <code>s</code>.
+ * @stable ICU 2.0
+ *
+ * @see u_strchr
+ * @see u_memchr32
+ * @see u_strFindFirst
+ */
+U_STABLE UChar* U_EXPORT2
+u_memchr(const UChar *s, UChar c, int32_t count);
+
+/**
+ * Find the first occurrence of a code point in a string.
+ * A surrogate code point is found only if its match in the text is not
+ * part of a surrogate pair.
+ * A NUL character is found at the string terminator.
+ *
+ * @param s The string to search (contains <code>count</code> UChars).
+ * @param c The code point to find.
+ * @param count The length of the string.
+ * @return A pointer to the first occurrence of <code>c</code> in <code>s</code>
+ *         or <code>NULL</code> if <code>c</code> is not in <code>s</code>.
+ * @stable ICU 2.0
+ *
+ * @see u_strchr32
+ * @see u_memchr
+ * @see u_strFindFirst
+ */
+U_STABLE UChar* U_EXPORT2
+u_memchr32(const UChar *s, UChar32 c, int32_t count);
+
+/**
+ * Find the last occurrence of a BMP code point in a string.
+ * A surrogate code point is found only if its match in the text is not
+ * part of a surrogate pair.
+ * A NUL character is found at the string terminator.
+ *
+ * @param s The string to search (contains <code>count</code> UChars).
+ * @param c The BMP code point to find.
+ * @param count The length of the string.
+ * @return A pointer to the last occurrence of <code>c</code> in <code>s</code>
+ *         or <code>NULL</code> if <code>c</code> is not in <code>s</code>.
+ * @stable ICU 2.4
+ *
+ * @see u_strrchr
+ * @see u_memrchr32
+ * @see u_strFindLast
+ */
+U_STABLE UChar* U_EXPORT2
+u_memrchr(const UChar *s, UChar c, int32_t count);
+
+/**
+ * Find the last occurrence of a code point in a string.
+ * A surrogate code point is found only if its match in the text is not
+ * part of a surrogate pair.
+ * A NUL character is found at the string terminator.
+ *
+ * @param s The string to search (contains <code>count</code> UChars).
+ * @param c The code point to find.
+ * @param count The length of the string.
+ * @return A pointer to the last occurrence of <code>c</code> in <code>s</code>
+ *         or <code>NULL</code> if <code>c</code> is not in <code>s</code>.
+ * @stable ICU 2.4
+ *
+ * @see u_strrchr32
+ * @see u_memrchr
+ * @see u_strFindLast
+ */
+U_STABLE UChar* U_EXPORT2
+u_memrchr32(const UChar *s, UChar32 c, int32_t count);
+
+/**
+ * Unicode String literals in C.
+ * We need one macro to declare a variable for the string
+ * and to statically preinitialize it if possible,
+ * and a second macro to dynamically intialize such a string variable if necessary.
+ *
+ * The macros are defined for maximum performance.
+ * They work only for strings that contain "invariant characters", i.e.,
+ * only latin letters, digits, and some punctuation.
+ * See utypes.h for details.
+ *
+ * A pair of macros for a single string must be used with the same
+ * parameters.
+ * The string parameter must be a C string literal.
+ * The length of the string, not including the terminating
+ * <code>NUL</code>, must be specified as a constant.
+ * The U_STRING_DECL macro should be invoked exactly once for one
+ * such string variable before it is used.
+ *
+ * Usage:
+ * <pre>
+ *    U_STRING_DECL(ustringVar1, "Quick-Fox 2", 11);
+ *    U_STRING_DECL(ustringVar2, "jumps 5%", 8);
+ *    static UBool didInit=FALSE;
+ * 
+ *    int32_t function() {
+ *        if(!didInit) {
+ *            U_STRING_INIT(ustringVar1, "Quick-Fox 2", 11);
+ *            U_STRING_INIT(ustringVar2, "jumps 5%", 8);
+ *            didInit=TRUE;
+ *        }
+ *        return u_strcmp(ustringVar1, ustringVar2);
+ *    }
+ * </pre>
+ * @stable ICU 2.0
+ */
+#if defined(U_DECLARE_UTF16)
+#   define U_STRING_DECL(var, cs, length) static const UChar var[(length)+1]=U_DECLARE_UTF16(cs)
+    /**@stable ICU 2.0 */
+#   define U_STRING_INIT(var, cs, length)
+#elif U_SIZEOF_WCHAR_T==U_SIZEOF_UCHAR && (U_CHARSET_FAMILY==U_ASCII_FAMILY || (U_SIZEOF_UCHAR == 2 && defined(U_WCHAR_IS_UTF16)))
+#   define U_STRING_DECL(var, cs, length) static const UChar var[(length)+1]=L ## cs
+    /**@stable ICU 2.0 */
+#   define U_STRING_INIT(var, cs, length)
+#elif U_SIZEOF_UCHAR==1 && U_CHARSET_FAMILY==U_ASCII_FAMILY
+#   define U_STRING_DECL(var, cs, length) static const UChar var[(length)+1]=cs
+    /**@stable ICU 2.0 */
+#   define U_STRING_INIT(var, cs, length)
+#else
+#   define U_STRING_DECL(var, cs, length) static UChar var[(length)+1]
+    /**@stable ICU 2.0 */
+#   define U_STRING_INIT(var, cs, length) u_charsToUChars(cs, var, length+1)
+#endif
+
+/**
+ * Unescape a string of characters and write the resulting
+ * Unicode characters to the destination buffer.  The following escape
+ * sequences are recognized:
+ *
+ * \\uhhhh       4 hex digits; h in [0-9A-Fa-f]
+ * \\Uhhhhhhhh   8 hex digits
+ * \\xhh         1-2 hex digits
+ * \\x{h...}     1-8 hex digits
+ * \\ooo         1-3 octal digits; o in [0-7]
+ * \\cX          control-X; X is masked with 0x1F
+ *
+ * as well as the standard ANSI C escapes:
+ *
+ * \\a => U+0007, \\b => U+0008, \\t => U+0009, \\n => U+000A,
+ * \\v => U+000B, \\f => U+000C, \\r => U+000D, \\e => U+001B,
+ * \\" => U+0022, \\' => U+0027, \\? => U+003F, \\\\ => U+005C
+ *
+ * Anything else following a backslash is generically escaped.  For
+ * example, "[a\\-z]" returns "[a-z]".
+ *
+ * If an escape sequence is ill-formed, this method returns an empty
+ * string.  An example of an ill-formed sequence is "\\u" followed by
+ * fewer than 4 hex digits.
+ *
+ * The above characters are recognized in the compiler's codepage,
+ * that is, they are coded as 'u', '\\', etc.  Characters that are
+ * not parts of escape sequences are converted using u_charsToUChars().
+ *
+ * This function is similar to UnicodeString::unescape() but not
+ * identical to it.  The latter takes a source UnicodeString, so it
+ * does escape recognition but no conversion.
+ *
+ * @param src a zero-terminated string of invariant characters
+ * @param dest pointer to buffer to receive converted and unescaped
+ * text and, if there is room, a zero terminator.  May be NULL for
+ * preflighting, in which case no UChars will be written, but the
+ * return value will still be valid.  On error, an empty string is
+ * stored here (if possible).
+ * @param destCapacity the number of UChars that may be written at
+ * dest.  Ignored if dest == NULL.
+ * @return the length of unescaped string.
+ * @see u_unescapeAt
+ * @see UnicodeString#unescape()
+ * @see UnicodeString#unescapeAt()
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+u_unescape(const char *src,
+           UChar *dest, int32_t destCapacity);
+
+U_CDECL_BEGIN
+/**
+ * Callback function for u_unescapeAt() that returns a character of
+ * the source text given an offset and a context pointer.  The context
+ * pointer will be whatever is passed into u_unescapeAt().
+ *
+ * @param offset pointer to the offset that will be passed to u_unescapeAt().
+ * @param context an opaque pointer passed directly into u_unescapeAt()
+ * @return the character represented by the escape sequence at
+ * offset
+ * @see u_unescapeAt
+ * @stable ICU 2.0
+ */
+typedef UChar (U_CALLCONV *UNESCAPE_CHAR_AT)(int32_t offset, void *context);
+U_CDECL_END
+
+/**
+ * Unescape a single sequence. The character at offset-1 is assumed
+ * (without checking) to be a backslash.  This method takes a callback
+ * pointer to a function that returns the UChar at a given offset.  By
+ * varying this callback, ICU functions are able to unescape char*
+ * strings, UnicodeString objects, and UFILE pointers.
+ *
+ * If offset is out of range, or if the escape sequence is ill-formed,
+ * (UChar32)0xFFFFFFFF is returned.  See documentation of u_unescape()
+ * for a list of recognized sequences.
+ *
+ * @param charAt callback function that returns a UChar of the source
+ * text given an offset and a context pointer.
+ * @param offset pointer to the offset that will be passed to charAt.
+ * The offset value will be updated upon return to point after the
+ * last parsed character of the escape sequence.  On error the offset
+ * is unchanged.
+ * @param length the number of characters in the source text.  The
+ * last character of the source text is considered to be at offset
+ * length-1.
+ * @param context an opaque pointer passed directly into charAt.
+ * @return the character represented by the escape sequence at
+ * offset, or (UChar32)0xFFFFFFFF on error.
+ * @see u_unescape()
+ * @see UnicodeString#unescape()
+ * @see UnicodeString#unescapeAt()
+ * @stable ICU 2.0
+ */
+U_STABLE UChar32 U_EXPORT2
+u_unescapeAt(UNESCAPE_CHAR_AT charAt,
+             int32_t *offset,
+             int32_t length,
+             void *context);
+
+/**
+ * Uppercase the characters in a string.
+ * Casing is locale-dependent and context-sensitive.
+ * The result may be longer or shorter than the original.
+ * The source string and the destination buffer are allowed to overlap.
+ *
+ * @param dest      A buffer for the result string. The result will be zero-terminated if
+ *                  the buffer is large enough.
+ * @param destCapacity The size of the buffer (number of UChars). If it is 0, then
+ *                  dest may be NULL and the function will only return the length of the result
+ *                  without writing any of the result string.
+ * @param src       The original string
+ * @param srcLength The length of the original string. If -1, then src must be zero-terminated.
+ * @param locale    The locale to consider, or "" for the root locale or NULL for the default locale.
+ * @param pErrorCode Must be a valid pointer to an error code value,
+ *                  which must not indicate a failure before the function call.
+ * @return The length of the result string. It may be greater than destCapacity. In that case,
+ *         only some of the result was written to the destination buffer.
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+u_strToUpper(UChar *dest, int32_t destCapacity,
+             const UChar *src, int32_t srcLength,
+             const char *locale,
+             UErrorCode *pErrorCode);
+
+/**
+ * Lowercase the characters in a string.
+ * Casing is locale-dependent and context-sensitive.
+ * The result may be longer or shorter than the original.
+ * The source string and the destination buffer are allowed to overlap.
+ *
+ * @param dest      A buffer for the result string. The result will be zero-terminated if
+ *                  the buffer is large enough.
+ * @param destCapacity The size of the buffer (number of UChars). If it is 0, then
+ *                  dest may be NULL and the function will only return the length of the result
+ *                  without writing any of the result string.
+ * @param src       The original string
+ * @param srcLength The length of the original string. If -1, then src must be zero-terminated.
+ * @param locale    The locale to consider, or "" for the root locale or NULL for the default locale.
+ * @param pErrorCode Must be a valid pointer to an error code value,
+ *                  which must not indicate a failure before the function call.
+ * @return The length of the result string. It may be greater than destCapacity. In that case,
+ *         only some of the result was written to the destination buffer.
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+u_strToLower(UChar *dest, int32_t destCapacity,
+             const UChar *src, int32_t srcLength,
+             const char *locale,
+             UErrorCode *pErrorCode);
+
+#if !UCONFIG_NO_BREAK_ITERATION
+
+/**
+ * Titlecase a string.
+ * Casing is locale-dependent and context-sensitive.
+ * Titlecasing uses a break iterator to find the first characters of words
+ * that are to be titlecased. It titlecases those characters and lowercases
+ * all others.
+ *
+ * The titlecase break iterator can be provided to customize for arbitrary
+ * styles, using rules and dictionaries beyond the standard iterators.
+ * It may be more efficient to always provide an iterator to avoid
+ * opening and closing one for each string.
+ * The standard titlecase iterator for the root locale implements the
+ * algorithm of Unicode TR 21.
+ *
+ * This function uses only the setText(), first() and next() methods of the
+ * provided break iterator.
+ *
+ * The result may be longer or shorter than the original.
+ * The source string and the destination buffer are allowed to overlap.
+ *
+ * @param dest      A buffer for the result string. The result will be zero-terminated if
+ *                  the buffer is large enough.
+ * @param destCapacity The size of the buffer (number of UChars). If it is 0, then
+ *                  dest may be NULL and the function will only return the length of the result
+ *                  without writing any of the result string.
+ * @param src       The original string
+ * @param srcLength The length of the original string. If -1, then src must be zero-terminated.
+ * @param titleIter A break iterator to find the first characters of words
+ *                  that are to be titlecased.
+ *                  If none is provided (NULL), then a standard titlecase
+ *                  break iterator is opened.
+ * @param locale    The locale to consider, or "" for the root locale or NULL for the default locale.
+ * @param pErrorCode Must be a valid pointer to an error code value,
+ *                  which must not indicate a failure before the function call.
+ * @return The length of the result string. It may be greater than destCapacity. In that case,
+ *         only some of the result was written to the destination buffer.
+ * @stable ICU 2.1
+ */
+U_STABLE int32_t U_EXPORT2
+u_strToTitle(UChar *dest, int32_t destCapacity,
+             const UChar *src, int32_t srcLength,
+             UBreakIterator *titleIter,
+             const char *locale,
+             UErrorCode *pErrorCode);
+
+#endif
+
+/**
+ * Case-fold the characters in a string.
+ * Case-folding is locale-independent and not context-sensitive,
+ * but there is an option for whether to include or exclude mappings for dotted I
+ * and dotless i that are marked with 'I' in CaseFolding.txt.
+ * The result may be longer or shorter than the original.
+ * The source string and the destination buffer are allowed to overlap.
+ *
+ * @param dest      A buffer for the result string. The result will be zero-terminated if
+ *                  the buffer is large enough.
+ * @param destCapacity The size of the buffer (number of UChars). If it is 0, then
+ *                  dest may be NULL and the function will only return the length of the result
+ *                  without writing any of the result string.
+ * @param src       The original string
+ * @param srcLength The length of the original string. If -1, then src must be zero-terminated.
+ * @param options   Either U_FOLD_CASE_DEFAULT or U_FOLD_CASE_EXCLUDE_SPECIAL_I
+ * @param pErrorCode Must be a valid pointer to an error code value,
+ *                  which must not indicate a failure before the function call.
+ * @return The length of the result string. It may be greater than destCapacity. In that case,
+ *         only some of the result was written to the destination buffer.
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+u_strFoldCase(UChar *dest, int32_t destCapacity,
+              const UChar *src, int32_t srcLength,
+              uint32_t options,
+              UErrorCode *pErrorCode);
+
+#if defined(U_WCHAR_IS_UTF16) || defined(U_WCHAR_IS_UTF32) || !UCONFIG_NO_CONVERSION
+/**
+ * Converts a sequence of UChars to wchar_t units.
+ *
+ * @param dest          A buffer for the result string. The result will be zero-terminated if
+ *                      the buffer is large enough.
+ * @param destCapacity  The size of the buffer (number of wchar_t's). If it is 0, then
+ *                      dest may be NULL and the function will only return the length of the 
+ *                      result without writing any of the result string (pre-flighting).
+ * @param pDestLength   A pointer to receive the number of units written to the destination. If 
+ *                      pDestLength!=NULL then *pDestLength is always set to the 
+ *                      number of output units corresponding to the transformation of 
+ *                      all the input units, even in case of a buffer overflow.
+ * @param src           The original source string
+ * @param srcLength     The length of the original string. If -1, then src must be zero-terminated.
+ * @param pErrorCode    Must be a valid pointer to an error code value,
+ *                      which must not indicate a failure before the function call.
+ * @return The pointer to destination buffer.
+ * @stable ICU 2.0
+ */
+U_STABLE wchar_t* U_EXPORT2
+u_strToWCS(wchar_t *dest, 
+           int32_t destCapacity,
+           int32_t *pDestLength,
+           const UChar *src, 
+           int32_t srcLength,
+           UErrorCode *pErrorCode);
+/**
+ * Converts a sequence of wchar_t units to UChars
+ *
+ * @param dest          A buffer for the result string. The result will be zero-terminated if
+ *                      the buffer is large enough.
+ * @param destCapacity  The size of the buffer (number of UChars). If it is 0, then
+ *                      dest may be NULL and the function will only return the length of the 
+ *                      result without writing any of the result string (pre-flighting).
+ * @param pDestLength   A pointer to receive the number of units written to the destination. If 
+ *                      pDestLength!=NULL then *pDestLength is always set to the 
+ *                      number of output units corresponding to the transformation of 
+ *                      all the input units, even in case of a buffer overflow.
+ * @param src           The original source string
+ * @param srcLength     The length of the original string. If -1, then src must be zero-terminated.
+ * @param pErrorCode    Must be a valid pointer to an error code value,
+ *                      which must not indicate a failure before the function call.
+ * @return The pointer to destination buffer.
+ * @stable ICU 2.0
+ */
+U_STABLE UChar* U_EXPORT2
+u_strFromWCS(UChar   *dest,
+             int32_t destCapacity, 
+             int32_t *pDestLength,
+             const wchar_t *src,
+             int32_t srcLength,
+             UErrorCode *pErrorCode);
+#endif /* defined(U_WCHAR_IS_UTF16) || defined(U_WCHAR_IS_UTF32) || !UCONFIG_NO_CONVERSION */
+
+/**
+ * Converts a sequence of UChars (UTF-16) to UTF-8 bytes
+ *
+ * @param dest          A buffer for the result string. The result will be zero-terminated if
+ *                      the buffer is large enough.
+ * @param destCapacity  The size of the buffer (number of chars). If it is 0, then
+ *                      dest may be NULL and the function will only return the length of the 
+ *                      result without writing any of the result string (pre-flighting).
+ * @param pDestLength   A pointer to receive the number of units written to the destination. If 
+ *                      pDestLength!=NULL then *pDestLength is always set to the 
+ *                      number of output units corresponding to the transformation of 
+ *                      all the input units, even in case of a buffer overflow.
+ * @param src           The original source string
+ * @param srcLength     The length of the original string. If -1, then src must be zero-terminated.
+ * @param pErrorCode    Must be a valid pointer to an error code value,
+ *                      which must not indicate a failure before the function call.
+ * @return The pointer to destination buffer.
+ * @stable ICU 2.0
+ * @see u_strToUTF8WithSub
+ * @see u_strFromUTF8
+ */
+U_STABLE char* U_EXPORT2 
+u_strToUTF8(char *dest,           
+            int32_t destCapacity,
+            int32_t *pDestLength,
+            const UChar *src, 
+            int32_t srcLength,
+            UErrorCode *pErrorCode);
+
+/**
+ * Converts a sequence of UTF-8 bytes to UChars (UTF-16).
+ *
+ * @param dest          A buffer for the result string. The result will be zero-terminated if
+ *                      the buffer is large enough.
+ * @param destCapacity  The size of the buffer (number of UChars). If it is 0, then
+ *                      dest may be NULL and the function will only return the length of the 
+ *                      result without writing any of the result string (pre-flighting).
+ * @param pDestLength   A pointer to receive the number of units written to the destination. If 
+ *                      pDestLength!=NULL then *pDestLength is always set to the 
+ *                      number of output units corresponding to the transformation of 
+ *                      all the input units, even in case of a buffer overflow.
+ * @param src           The original source string
+ * @param srcLength     The length of the original string. If -1, then src must be zero-terminated.
+ * @param pErrorCode    Must be a valid pointer to an error code value,
+ *                      which must not indicate a failure before the function call.
+ * @return The pointer to destination buffer.
+ * @stable ICU 2.0
+ * @see u_strFromUTF8WithSub
+ * @see u_strFromUTF8Lenient
+ */
+U_STABLE UChar* U_EXPORT2
+u_strFromUTF8(UChar *dest,             
+              int32_t destCapacity,
+              int32_t *pDestLength,
+              const char *src, 
+              int32_t srcLength,
+              UErrorCode *pErrorCode);
+
+/**
+ * Converts a sequence of UChars (UTF-16) to UTF-8 bytes.
+ * Same as u_strToUTF8() except for the additional subchar which is output for
+ * illegal input sequences, instead of stopping with the U_INVALID_CHAR_FOUND error code.
+ * With subchar==U_SENTINEL, this function behaves exactly like u_strToUTF8().
+ *
+ * @param dest          A buffer for the result string. The result will be zero-terminated if
+ *                      the buffer is large enough.
+ * @param destCapacity  The size of the buffer (number of chars). If it is 0, then
+ *                      dest may be NULL and the function will only return the length of the 
+ *                      result without writing any of the result string (pre-flighting).
+ * @param pDestLength   A pointer to receive the number of units written to the destination. If 
+ *                      pDestLength!=NULL then *pDestLength is always set to the 
+ *                      number of output units corresponding to the transformation of 
+ *                      all the input units, even in case of a buffer overflow.
+ * @param src           The original source string
+ * @param srcLength     The length of the original string. If -1, then src must be zero-terminated.
+ * @param subchar       The substitution character to use in place of an illegal input sequence,
+ *                      or U_SENTINEL if the function is to return with U_INVALID_CHAR_FOUND instead.
+ *                      A substitution character can be any valid Unicode code point (up to U+10FFFF)
+ *                      except for surrogate code points (U+D800..U+DFFF).
+ *                      The recommended value is U+FFFD "REPLACEMENT CHARACTER".
+ * @param pNumSubstitutions Output parameter receiving the number of substitutions if subchar>=0.
+ *                      Set to 0 if no substitutions occur or subchar<0.
+ *                      pNumSubstitutions can be NULL.
+ * @param pErrorCode    Pointer to a standard ICU error code. Its input value must
+ *                      pass the U_SUCCESS() test, or else the function returns
+ *                      immediately. Check for U_FAILURE() on output or use with
+ *                      function chaining. (See User Guide for details.)
+ * @return The pointer to destination buffer.
+ * @see u_strToUTF8
+ * @see u_strFromUTF8WithSub
+ * @stable ICU 3.6
+ */
+U_STABLE char* U_EXPORT2
+u_strToUTF8WithSub(char *dest,
+            int32_t destCapacity,
+            int32_t *pDestLength,
+            const UChar *src,
+            int32_t srcLength,
+            UChar32 subchar, int32_t *pNumSubstitutions,
+            UErrorCode *pErrorCode);
+
+/**
+ * Converts a sequence of UTF-8 bytes to UChars (UTF-16).
+ * Same as u_strFromUTF8() except for the additional subchar which is output for
+ * illegal input sequences, instead of stopping with the U_INVALID_CHAR_FOUND error code.
+ * With subchar==U_SENTINEL, this function behaves exactly like u_strFromUTF8().
+ *
+ * @param dest          A buffer for the result string. The result will be zero-terminated if
+ *                      the buffer is large enough.
+ * @param destCapacity  The size of the buffer (number of UChars). If it is 0, then
+ *                      dest may be NULL and the function will only return the length of the 
+ *                      result without writing any of the result string (pre-flighting).
+ * @param pDestLength   A pointer to receive the number of units written to the destination. If 
+ *                      pDestLength!=NULL then *pDestLength is always set to the 
+ *                      number of output units corresponding to the transformation of 
+ *                      all the input units, even in case of a buffer overflow.
+ * @param src           The original source string
+ * @param srcLength     The length of the original string. If -1, then src must be zero-terminated.
+ * @param subchar       The substitution character to use in place of an illegal input sequence,
+ *                      or U_SENTINEL if the function is to return with U_INVALID_CHAR_FOUND instead.
+ *                      A substitution character can be any valid Unicode code point (up to U+10FFFF)
+ *                      except for surrogate code points (U+D800..U+DFFF).
+ *                      The recommended value is U+FFFD "REPLACEMENT CHARACTER".
+ * @param pNumSubstitutions Output parameter receiving the number of substitutions if subchar>=0.
+ *                      Set to 0 if no substitutions occur or subchar<0.
+ *                      pNumSubstitutions can be NULL.
+ * @param pErrorCode    Pointer to a standard ICU error code. Its input value must
+ *                      pass the U_SUCCESS() test, or else the function returns
+ *                      immediately. Check for U_FAILURE() on output or use with
+ *                      function chaining. (See User Guide for details.)
+ * @return The pointer to destination buffer.
+ * @see u_strFromUTF8
+ * @see u_strFromUTF8Lenient
+ * @see u_strToUTF8WithSub
+ * @stable ICU 3.6
+ */
+U_STABLE UChar* U_EXPORT2
+u_strFromUTF8WithSub(UChar *dest,
+              int32_t destCapacity,
+              int32_t *pDestLength,
+              const char *src,
+              int32_t srcLength,
+              UChar32 subchar, int32_t *pNumSubstitutions,
+              UErrorCode *pErrorCode);
+
+/**
+ * Converts a sequence of UTF-8 bytes to UChars (UTF-16).
+ * Same as u_strFromUTF8() except that this function is designed to be very fast,
+ * which it achieves by being lenient about malformed UTF-8 sequences.
+ * This function is intended for use in environments where UTF-8 text is
+ * expected to be well-formed.
+ *
+ * Its semantics are:
+ * - Well-formed UTF-8 text is correctly converted to well-formed UTF-16 text.
+ * - The function will not read beyond the input string, nor write beyond
+ *   the destCapacity.
+ * - Malformed UTF-8 results in "garbage" 16-bit Unicode strings which may not
+ *   be well-formed UTF-16.
+ *   The function will resynchronize to valid code point boundaries
+ *   within a small number of code points after an illegal sequence.
+ * - Non-shortest forms are not detected and will result in "spoofing" output.
+ *
+ * For further performance improvement, if srcLength is given (>=0),
+ * then it must be destCapacity>=srcLength.
+ *
+ * @param dest          A buffer for the result string. The result will be zero-terminated if
+ *                      the buffer is large enough.
+ * @param destCapacity  The size of the buffer (number of UChars). If it is 0, then
+ *                      dest may be NULL and the function will only return the length of the 
+ *                      result without writing any of the result string (pre-flighting).
+ *                      Unlike for other ICU functions, if srcLength>=0 then it
+ *                      must be destCapacity>=srcLength.
+ * @param pDestLength   A pointer to receive the number of units written to the destination. If 
+ *                      pDestLength!=NULL then *pDestLength is always set to the 
+ *                      number of output units corresponding to the transformation of 
+ *                      all the input units, even in case of a buffer overflow.
+ *                      Unlike for other ICU functions, if srcLength>=0 but
+ *                      destCapacity<srcLength, then *pDestLength will be set to srcLength
+ *                      (and U_BUFFER_OVERFLOW_ERROR will be set)
+ *                      regardless of the actual result length.
+ * @param src           The original source string
+ * @param srcLength     The length of the original string. If -1, then src must be zero-terminated.
+ * @param pErrorCode    Pointer to a standard ICU error code. Its input value must
+ *                      pass the U_SUCCESS() test, or else the function returns
+ *                      immediately. Check for U_FAILURE() on output or use with
+ *                      function chaining. (See User Guide for details.)
+ * @return The pointer to destination buffer.
+ * @see u_strFromUTF8
+ * @see u_strFromUTF8WithSub
+ * @see u_strToUTF8WithSub
+ * @stable ICU 3.6
+ */
+U_STABLE UChar * U_EXPORT2
+u_strFromUTF8Lenient(UChar *dest,
+                     int32_t destCapacity,
+                     int32_t *pDestLength,
+                     const char *src,
+                     int32_t srcLength,
+                     UErrorCode *pErrorCode);
+
+/**
+ * Converts a sequence of UChars (UTF-16) to UTF32 units.
+ *
+ * @param dest          A buffer for the result string. The result will be zero-terminated if
+ *                      the buffer is large enough.
+ * @param destCapacity  The size of the buffer (number of UChar32s). If it is 0, then
+ *                      dest may be NULL and the function will only return the length of the 
+ *                      result without writing any of the result string (pre-flighting).
+ * @param pDestLength   A pointer to receive the number of units written to the destination. If 
+ *                      pDestLength!=NULL then *pDestLength is always set to the 
+ *                      number of output units corresponding to the transformation of 
+ *                      all the input units, even in case of a buffer overflow.
+ * @param src           The original source string
+ * @param srcLength     The length of the original string. If -1, then src must be zero-terminated.
+ * @param pErrorCode    Must be a valid pointer to an error code value,
+ *                      which must not indicate a failure before the function call.
+ * @return The pointer to destination buffer.
+ * @stable ICU 2.0
+ */
+U_STABLE UChar32* U_EXPORT2 
+u_strToUTF32(UChar32 *dest, 
+             int32_t  destCapacity,
+             int32_t  *pDestLength,
+             const UChar *src, 
+             int32_t  srcLength,
+             UErrorCode *pErrorCode);
+
+/**
+ * Converts a sequence of UTF32 units to UChars (UTF-16)
+ *
+ * @param dest          A buffer for the result string. The result will be zero-terminated if
+ *                      the buffer is large enough.
+ * @param destCapacity  The size of the buffer (number of UChars). If it is 0, then
+ *                      dest may be NULL and the function will only return the length of the 
+ *                      result without writing any of the result string (pre-flighting).
+ * @param pDestLength   A pointer to receive the number of units written to the destination. If 
+ *                      pDestLength!=NULL then *pDestLength is always set to the 
+ *                      number of output units corresponding to the transformation of 
+ *                      all the input units, even in case of a buffer overflow.
+ * @param src           The original source string
+ * @param srcLength     The length of the original string. If -1, then src must be zero-terminated.
+ * @param pErrorCode    Must be a valid pointer to an error code value,
+ *                      which must not indicate a failure before the function call.
+ * @return The pointer to destination buffer.
+ * @stable ICU 2.0
+ */
+U_STABLE UChar* U_EXPORT2 
+u_strFromUTF32(UChar   *dest,
+               int32_t destCapacity, 
+               int32_t *pDestLength,
+               const UChar32 *src,
+               int32_t srcLength,
+               UErrorCode *pErrorCode);
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/usystem.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/usystem.h b/src/apps/couch_collate/platform/osx/icu/unicode/usystem.h
new file mode 100644
index 0000000..752e2f1
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/usystem.h
@@ -0,0 +1,46 @@
+/*
+*******************************************************************************
+*   Copyright (C) 2004-2008, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+*******************************************************************************
+*
+*   file name:  
+*   encoding:   US-ASCII
+*   tab size:   8 (not used)
+*   indentation:4
+*
+*   Created by: genheaders.pl, a perl script written by Ram Viswanadha
+*
+*  Contains data for commenting out APIs.
+*  Gets included by umachine.h
+*
+*  THIS FILE IS MACHINE-GENERATED, DON'T PLAY WITH IT IF YOU DON'T KNOW WHAT
+*  YOU ARE DOING, OTHERWISE VERY BAD THINGS WILL HAPPEN!
+*/
+
+#ifndef USYSTEM_H
+#define USYSTEM_H
+
+#ifdef U_HIDE_SYSTEM_API
+
+#    if U_DISABLE_RENAMING
+#        define u_cleanup u_cleanup_SYSTEM_API_DO_NOT_USE
+#        define u_setAtomicIncDecFunctions u_setAtomicIncDecFunctions_SYSTEM_API_DO_NOT_USE
+#        define u_setMemoryFunctions u_setMemoryFunctions_SYSTEM_API_DO_NOT_USE
+#        define u_setMutexFunctions u_setMutexFunctions_SYSTEM_API_DO_NOT_USE
+#        define ucnv_setDefaultName ucnv_setDefaultName_SYSTEM_API_DO_NOT_USE
+#        define uloc_getDefault uloc_getDefault_SYSTEM_API_DO_NOT_USE
+#        define uloc_setDefault uloc_setDefault_SYSTEM_API_DO_NOT_USE
+#    else
+#        define u_cleanup_4_0 u_cleanup_SYSTEM_API_DO_NOT_USE
+#        define u_setAtomicIncDecFunctions_4_0 u_setAtomicIncDecFunctions_SYSTEM_API_DO_NOT_USE
+#        define u_setMemoryFunctions_4_0 u_setMemoryFunctions_SYSTEM_API_DO_NOT_USE
+#        define u_setMutexFunctions_4_0 u_setMutexFunctions_SYSTEM_API_DO_NOT_USE
+#        define ucnv_setDefaultName_4_0 ucnv_setDefaultName_SYSTEM_API_DO_NOT_USE
+#        define uloc_getDefault_4_0 uloc_getDefault_SYSTEM_API_DO_NOT_USE
+#        define uloc_setDefault_4_0 uloc_setDefault_SYSTEM_API_DO_NOT_USE
+#    endif /* U_DISABLE_RENAMING */
+
+#endif /* U_HIDE_SYSTEM_API */
+#endif /* USYSTEM_H */
+


[82/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/ppalmos.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/ppalmos.h b/src/apps/couch_collate/platform/osx/icu/unicode/ppalmos.h
new file mode 100644
index 0000000..c15b2ce
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/ppalmos.h
@@ -0,0 +1,273 @@
+/*
+******************************************************************************
+*
+*   Copyright (C) 1997-2006, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+*
+******************************************************************************
+*
+*  FILE NAME : ppalmos.h
+*
+*   Date        Name        Description
+*   05/10/04    Ken Krugler Creation (copied from pwin32.h & modified).
+******************************************************************************
+*/
+
+#ifndef U_PPALMOS_H
+#define U_PPALMOS_H
+
+ /**
+  * \file
+  * \brief Configuration constants for the Palm OS platform
+  */
+  
+/* Define the platform we're on. */
+#ifndef U_PALMOS
+#define U_PALMOS
+#endif
+
+/* _MSC_VER is used to detect the Microsoft compiler. */
+#if defined(_MSC_VER)
+#define U_INT64_IS_LONG_LONG 0
+#else
+#define U_INT64_IS_LONG_LONG 1
+#endif
+
+/* Define whether inttypes.h is available */
+#ifndef U_HAVE_INTTYPES_H
+#define U_HAVE_INTTYPES_H 1
+#endif
+
+/*
+ * Define what support for C++ streams is available.
+ *     If U_IOSTREAM_SOURCE is set to 199711, then <iostream> is available
+ * (1997711 is the date the ISO/IEC C++ FDIS was published), and then
+ * one should qualify streams using the std namespace in ICU header
+ * files.
+ *     If U_IOSTREAM_SOURCE is set to 198506, then <iostream.h> is
+ * available instead (198506 is the date when Stroustrup published
+ * "An Extensible I/O Facility for C++" at the summer USENIX conference).
+ *     If U_IOSTREAM_SOURCE is 0, then C++ streams are not available and
+ * support for them will be silently suppressed in ICU.
+ *
+ */
+
+#ifndef U_IOSTREAM_SOURCE
+#define U_IOSTREAM_SOURCE 199711
+#endif
+
+/* Determines whether specific types are available */
+#ifndef U_HAVE_INT8_T
+#define U_HAVE_INT8_T U_HAVE_INTTYPES_H
+#endif
+
+#ifndef U_HAVE_UINT8_T
+#define U_HAVE_UINT8_T U_HAVE_INTTYPES_H
+#endif
+
+#ifndef U_HAVE_INT16_T
+#define U_HAVE_INT16_T U_HAVE_INTTYPES_H
+#endif
+
+#ifndef U_HAVE_UINT16_T
+#define U_HAVE_UINT16_T U_HAVE_INTTYPES_H
+#endif
+
+#ifndef U_HAVE_INT32_T
+#define U_HAVE_INT32_T U_HAVE_INTTYPES_H
+#endif
+
+#ifndef U_HAVE_UINT32_T
+#define U_HAVE_UINT32_T U_HAVE_INTTYPES_H
+#endif
+
+#ifndef U_HAVE_INT64_T
+#define U_HAVE_INT64_T U_HAVE_INTTYPES_H
+#endif
+
+#ifndef U_HAVE_UINT64_T
+#define U_HAVE_UINT64_T U_HAVE_INTTYPES_H
+#endif
+
+
+/*===========================================================================*/
+/* Generic data types                                                        */
+/*===========================================================================*/
+
+/* If your platform does not have the <inttypes.h> header, you may
+   need to edit the typedefs below. */
+#if U_HAVE_INTTYPES_H
+#include <inttypes.h>
+#else /* U_HAVE_INTTYPES_H */
+
+#if ! U_HAVE_INT8_T
+typedef signed char int8_t;
+#endif
+
+#if ! U_HAVE_UINT8_T
+typedef unsigned char uint8_t;
+#endif
+
+#if ! U_HAVE_INT16_T
+typedef signed short int16_t;
+#endif
+
+#if ! U_HAVE_UINT16_T
+typedef unsigned short uint16_t;
+#endif
+
+#if ! U_HAVE_INT32_T
+typedef signed int int32_t;
+#endif
+
+#if ! U_HAVE_UINT32_T
+typedef unsigned int uint32_t;
+#endif
+
+#if ! U_HAVE_INT64_T
+#if U_INT64_IS_LONG_LONG
+    typedef signed long long int64_t;
+#else
+    typedef signed __int64 int64_t;
+#endif
+#endif
+
+#if ! U_HAVE_UINT64_T
+#if U_INT64_IS_LONG_LONG
+    typedef unsigned long long uint64_t;
+#else
+    typedef unsigned __int64 uint64_t;
+#endif
+#endif
+#endif
+
+/*===========================================================================*/
+/* Compiler and environment features                                         */
+/*===========================================================================*/
+
+/* Define whether namespace is supported */
+#ifndef U_HAVE_NAMESPACE
+#define U_HAVE_NAMESPACE 1
+#endif
+
+/* Determines the endianness of the platform */
+#define U_IS_BIG_ENDIAN 0
+
+/* 1 or 0 to enable or disable threads.  If undefined, default is: enable threads. */
+#define ICU_USE_THREADS 1
+
+#ifndef U_DEBUG
+#ifdef _DEBUG
+#define U_DEBUG 1
+#else
+#define U_DEBUG 0
+#endif
+#endif
+
+#ifndef U_RELEASE
+#ifdef NDEBUG
+#define U_RELEASE 1
+#else
+#define U_RELEASE 0
+#endif
+#endif
+
+/* Determine whether to disable renaming or not. This overrides the
+   setting in umachine.h which is for all platforms. */
+#ifndef U_DISABLE_RENAMING
+#define U_DISABLE_RENAMING 0
+#endif
+
+/* Determine whether to override new and delete. */
+#ifndef U_OVERRIDE_CXX_ALLOCATION
+#define U_OVERRIDE_CXX_ALLOCATION 1
+#endif
+/* Determine whether to override placement new and delete for STL. */
+#ifndef U_HAVE_PLACEMENT_NEW
+#define U_HAVE_PLACEMENT_NEW 0
+#endif
+/* Determine whether to override new and delete for MFC. */
+#if !defined(U_HAVE_DEBUG_LOCATION_NEW) && defined(_MSC_VER)
+#define U_HAVE_DEBUG_LOCATION_NEW 0
+#endif
+
+/* Determine whether to enable tracing. */
+#ifndef U_ENABLE_TRACING
+#define U_ENABLE_TRACING 1
+#endif
+
+/* Do we allow ICU users to use the draft APIs by default? */
+#ifndef U_DEFAULT_SHOW_DRAFT
+#define U_DEFAULT_SHOW_DRAFT 1
+#endif
+
+/* Define the library suffix in a C syntax. */
+#define U_HAVE_LIB_SUFFIX 0
+#define U_LIB_SUFFIX_C_NAME 
+#define U_LIB_SUFFIX_C_NAME_STRING ""
+
+/*===========================================================================*/
+/* Information about wchar support                                           */
+/*===========================================================================*/
+
+#define U_HAVE_WCHAR_H 1
+#define U_SIZEOF_WCHAR_T 2
+
+#define U_HAVE_WCSCPY    0
+
+/*===========================================================================*/
+/* Information about POSIX support                                           */
+/*===========================================================================*/
+
+
+/* TODO: Fix Palm OS's determination of a timezone */
+#if 0
+#define U_TZSET         _tzset
+#endif
+#if 0
+#define U_TIMEZONE      _timezone
+#endif
+#if 0
+#define U_TZNAME        _tzname
+#endif
+
+#define U_HAVE_MMAP 0
+#define U_HAVE_POPEN 0
+
+/*===========================================================================*/
+/* Symbol import-export control                                              */
+/*===========================================================================*/
+
+#define U_EXPORT
+#define U_EXPORT2
+#define U_IMPORT
+
+/*===========================================================================*/
+/* Code alignment and C function inlining                                    */
+/*===========================================================================*/
+
+#ifndef U_INLINE
+#   ifdef __cplusplus
+#       define U_INLINE inline
+#   else
+#       define U_INLINE __inline
+#   endif
+#endif
+
+#if defined(_MSC_VER) && defined(_M_IX86)
+#define U_ALIGN_CODE(val)    __asm      align val
+#else
+#define U_ALIGN_CODE(val)
+#endif
+
+
+/*===========================================================================*/
+/* Programs used by ICU code                                                 */
+/*===========================================================================*/
+
+#ifndef U_MAKE
+#define U_MAKE  "nmake"
+#define U_MAKE_IS_NMAKE 1
+#endif
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/putil.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/putil.h b/src/apps/couch_collate/platform/osx/icu/unicode/putil.h
new file mode 100644
index 0000000..3304877
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/putil.h
@@ -0,0 +1,184 @@
+/*
+******************************************************************************
+*
+*   Copyright (C) 1997-2008, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+*
+******************************************************************************
+*
+*  FILE NAME : putil.h
+*
+*   Date        Name        Description
+*   05/14/98    nos         Creation (content moved here from utypes.h).
+*   06/17/99    erm         Added IEEE_754
+*   07/22/98    stephen     Added IEEEremainder, max, min, trunc
+*   08/13/98    stephen     Added isNegativeInfinity, isPositiveInfinity
+*   08/24/98    stephen     Added longBitsFromDouble
+*   03/02/99    stephen     Removed openFile().  Added AS400 support.
+*   04/15/99    stephen     Converted to C
+*   11/15/99    helena      Integrated S/390 changes for IEEE support.
+*   01/11/00    helena      Added u_getVersion.
+******************************************************************************
+*/
+
+#ifndef PUTIL_H
+#define PUTIL_H
+
+#include "unicode/utypes.h"
+ /**
+  * \file
+  * \brief C API: Platform Utilities
+  */
+  
+/* Define this to 1 if your platform supports IEEE 754 floating point,
+   to 0 if it does not. */
+#ifndef IEEE_754
+#   define IEEE_754 1
+#endif
+
+/*==========================================================================*/
+/* Platform utilities                                                       */
+/*==========================================================================*/
+
+/**
+ * Platform utilities isolates the platform dependencies of the
+ * libarary.  For each platform which this code is ported to, these
+ * functions may have to be re-implemented.
+ */
+
+/**
+ * Return the ICU data directory. 
+ * The data directory is where common format ICU data files (.dat files)
+ *   are loaded from.  Note that normal use of the built-in ICU
+ *   facilities does not require loading of an external data file;
+ *   unless you are adding custom data to ICU, the data directory
+ *   does not need to be set.
+ *
+ * The data directory is determined as follows:
+ *    If u_setDataDirectory() has been called, that is it, otherwise
+ *    if the ICU_DATA environment variable is set, use that, otherwise
+ *    If a data directory was specifed at ICU build time
+ *      <code>( #define ICU_DATA_DIR "path" )</code>, use that,
+ *    otherwise no data directory is available.
+ *
+ * @return the data directory, or an empty string ("") if no data directory has
+ *         been specified.
+ *   
+ * @stable ICU 2.0
+ */
+U_STABLE const char* U_EXPORT2 u_getDataDirectory(void);
+
+/** 
+ * Set the ICU data directory. 
+ * The data directory is where common format ICU data files (.dat files)
+ *   are loaded from.  Note that normal use of the built-in ICU
+ *   facilities does not require loading of an external data file;
+ *   unless you are adding custom data to ICU, the data directory
+ *   does not need to be set.
+ *
+ * This function should be called at most once in a process, before the
+ * first ICU operation (e.g., u_init()) that will require the loading of an
+ * ICU data file.
+ * This function is not thread-safe. Use it before calling ICU APIs from
+ * multiple threads.
+ *
+ * @param directory The directory to be set.
+ *
+ * @see u_init
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 u_setDataDirectory(const char *directory);
+
+/**
+ * Please use ucnv_getDefaultName() instead.
+ * Return the default codepage for this platform and locale.
+ * This function can call setlocale() on Unix platforms. Please read the
+ * platform documentation on setlocale() before calling this function.
+ * @return the default codepage for this platform 
+ * @internal
+ */
+U_INTERNAL const char*  U_EXPORT2 uprv_getDefaultCodepage(void);
+
+/**
+ * Please use uloc_getDefault() instead.
+ * Return the default locale ID string by querying ths system, or
+ *     zero if one cannot be found. 
+ * This function can call setlocale() on Unix platforms. Please read the
+ * platform documentation on setlocale() before calling this function.
+ * @return the default locale ID string
+ * @internal
+ */
+U_INTERNAL const char*  U_EXPORT2 uprv_getDefaultLocaleID(void);
+
+/**
+ * Filesystem file and path separator characters.
+ * Example: '/' and ':' on Unix, '\\' and ';' on Windows.
+ * @stable ICU 2.0
+ */
+#ifdef XP_MAC
+#   define U_FILE_SEP_CHAR ':'
+#   define U_FILE_ALT_SEP_CHAR ':'
+#   define U_PATH_SEP_CHAR ';'
+#   define U_FILE_SEP_STRING ":"
+#   define U_FILE_ALT_SEP_STRING ":"
+#   define U_PATH_SEP_STRING ";"
+#elif defined(U_WINDOWS)
+#   define U_FILE_SEP_CHAR '\\'
+#   define U_FILE_ALT_SEP_CHAR '/'
+#   define U_PATH_SEP_CHAR ';'
+#   define U_FILE_SEP_STRING "\\"
+#   define U_FILE_ALT_SEP_STRING "/"
+#   define U_PATH_SEP_STRING ";"
+#else
+#   define U_FILE_SEP_CHAR '/'
+#   define U_FILE_ALT_SEP_CHAR '/'
+#   define U_PATH_SEP_CHAR ':'
+#   define U_FILE_SEP_STRING "/"
+#   define U_FILE_ALT_SEP_STRING "/"
+#   define U_PATH_SEP_STRING ":"
+#endif
+
+/**
+ * Convert char characters to UChar characters.
+ * This utility function is useful only for "invariant characters"
+ * that are encoded in the platform default encoding.
+ * They are a small, constant subset of the encoding and include
+ * just the latin letters, digits, and some punctuation.
+ * For details, see U_CHARSET_FAMILY.
+ *
+ * @param cs Input string, points to <code>length</code>
+ *           character bytes from a subset of the platform encoding.
+ * @param us Output string, points to memory for <code>length</code>
+ *           Unicode characters.
+ * @param length The number of characters to convert; this may
+ *               include the terminating <code>NUL</code>.
+ *
+ * @see U_CHARSET_FAMILY
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2
+u_charsToUChars(const char *cs, UChar *us, int32_t length);
+
+/**
+ * Convert UChar characters to char characters.
+ * This utility function is useful only for "invariant characters"
+ * that can be encoded in the platform default encoding.
+ * They are a small, constant subset of the encoding and include
+ * just the latin letters, digits, and some punctuation.
+ * For details, see U_CHARSET_FAMILY.
+ *
+ * @param us Input string, points to <code>length</code>
+ *           Unicode characters that can be encoded with the
+ *           codepage-invariant subset of the platform encoding.
+ * @param cs Output string, points to memory for <code>length</code>
+ *           character bytes.
+ * @param length The number of characters to convert; this may
+ *               include the terminating <code>NUL</code>.
+ *
+ * @see U_CHARSET_FAMILY
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2
+u_UCharsToChars(const UChar *us, char *cs, int32_t length);
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/pwin32.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/pwin32.h b/src/apps/couch_collate/platform/osx/icu/unicode/pwin32.h
new file mode 100644
index 0000000..9aad353
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/pwin32.h
@@ -0,0 +1,311 @@
+/*
+ ******************************************************************************
+ *
+ *   Copyright (C) 1997-2007, International Business Machines
+ *   Corporation and others.  All Rights Reserved.
+ *
+ ******************************************************************************
+ *
+ *  FILE NAME : platform.h
+ *
+ *   Date        Name        Description
+ *   05/13/98    nos         Creation (content moved here from ptypes.h).
+ *   03/02/99    stephen     Added AS400 support.
+ *   03/30/99    stephen     Added Linux support.
+ *   04/13/99    stephen     Reworked for autoconf.
+ ******************************************************************************
+ */
+
+ /**
+  * \file
+  * \brief Configuration constants for the Windows platform
+  */
+  
+/* Define the platform we're on. */
+#ifndef U_WINDOWS
+#define U_WINDOWS
+#endif
+
+#if defined(__BORLANDC__)
+#define U_HAVE_PLACEMENT_NEW 0
+#define U_HAVE_INTTYPES_H 1
+#define __STDC_CONSTANT_MACROS
+#endif
+
+/* _MSC_VER is used to detect the Microsoft compiler. */
+#if defined(_MSC_VER)
+#define U_INT64_IS_LONG_LONG 0
+#else
+#define U_INT64_IS_LONG_LONG 1
+#endif
+
+/* Define whether inttypes.h is available */
+#ifndef U_HAVE_INTTYPES_H
+#define U_HAVE_INTTYPES_H 0
+#endif
+
+/*
+ * Define what support for C++ streams is available.
+ *     If U_IOSTREAM_SOURCE is set to 199711, then <iostream> is available
+ * (1997711 is the date the ISO/IEC C++ FDIS was published), and then
+ * one should qualify streams using the std namespace in ICU header
+ * files.
+ *     If U_IOSTREAM_SOURCE is set to 198506, then <iostream.h> is
+ * available instead (198506 is the date when Stroustrup published
+ * "An Extensible I/O Facility for C++" at the summer USENIX conference).
+ *     If U_IOSTREAM_SOURCE is 0, then C++ streams are not available and
+ * support for them will be silently suppressed in ICU.
+ *
+ */
+
+#ifndef U_IOSTREAM_SOURCE
+#define U_IOSTREAM_SOURCE 199711
+#endif
+
+/* Determines whether specific types are available */
+#ifndef U_HAVE_INT8_T
+#define U_HAVE_INT8_T U_HAVE_INTTYPES_H
+#endif
+
+#ifndef U_HAVE_UINT8_T
+#define U_HAVE_UINT8_T U_HAVE_INTTYPES_H
+#endif
+
+#ifndef U_HAVE_INT16_T
+#define U_HAVE_INT16_T U_HAVE_INTTYPES_H
+#endif
+
+#ifndef U_HAVE_UINT16_T
+#define U_HAVE_UINT16_T U_HAVE_INTTYPES_H
+#endif
+
+#ifndef U_HAVE_INT32_T
+#define U_HAVE_INT32_T U_HAVE_INTTYPES_H
+#endif
+
+#ifndef U_HAVE_UINT32_T
+#define U_HAVE_UINT32_T U_HAVE_INTTYPES_H
+#endif
+
+#ifndef U_HAVE_INT64_T
+#define U_HAVE_INT64_T U_HAVE_INTTYPES_H
+#endif
+
+#ifndef U_HAVE_UINT64_T
+#define U_HAVE_UINT64_T U_HAVE_INTTYPES_H
+#endif
+
+/* Define 64 bit limits */
+#if !U_INT64_IS_LONG_LONG
+# ifndef INT64_C
+#  define INT64_C(x) ((int64_t)x)
+# endif
+# ifndef UINT64_C
+#  define UINT64_C(x) ((uint64_t)x)
+# endif
+/* else use the umachine.h definition */
+#endif
+
+/*===========================================================================*/
+/* Generic data types                                                        */
+/*===========================================================================*/
+
+/* If your platform does not have the <inttypes.h> header, you may
+   need to edit the typedefs below. */
+#if U_HAVE_INTTYPES_H
+#include <inttypes.h>
+#else /* U_HAVE_INTTYPES_H */
+
+#if ! U_HAVE_INT8_T
+typedef signed char int8_t;
+#endif
+
+#if ! U_HAVE_UINT8_T
+typedef unsigned char uint8_t;
+#endif
+
+#if ! U_HAVE_INT16_T
+typedef signed short int16_t;
+#endif
+
+#if ! U_HAVE_UINT16_T
+typedef unsigned short uint16_t;
+#endif
+
+#if ! U_HAVE_INT32_T
+typedef signed int int32_t;
+#endif
+
+#if ! U_HAVE_UINT32_T
+typedef unsigned int uint32_t;
+#endif
+
+#if ! U_HAVE_INT64_T
+#if U_INT64_IS_LONG_LONG
+    typedef signed long long int64_t;
+#else
+    typedef signed __int64 int64_t;
+#endif
+#endif
+
+#if ! U_HAVE_UINT64_T
+#if U_INT64_IS_LONG_LONG
+    typedef unsigned long long uint64_t;
+#else
+    typedef unsigned __int64 uint64_t;
+#endif
+#endif
+#endif
+
+/*===========================================================================*/
+/* Compiler and environment features                                         */
+/*===========================================================================*/
+
+/* Define whether namespace is supported */
+#ifndef U_HAVE_NAMESPACE
+#define U_HAVE_NAMESPACE 1
+#endif
+
+/* Determines the endianness of the platform */
+#define U_IS_BIG_ENDIAN 0
+
+/* 1 or 0 to enable or disable threads.  If undefined, default is: enable threads. */
+#define ICU_USE_THREADS 1
+
+/* On strong memory model CPUs (e.g. x86 CPUs), we use a safe & quick double check mutex lock. */
+/*
+Microsoft can define _M_IX86, _M_AMD64 (before Visual Studio 8) or _M_X64 (starting in Visual Studio 8). 
+Intel can define _M_IX86 or _M_X64
+*/
+#if defined(_M_IX86) || defined(_M_AMD64) || defined(_M_X64) || (defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)))
+#define UMTX_STRONG_MEMORY_MODEL 1
+#endif
+
+#ifndef U_DEBUG
+#ifdef _DEBUG
+#define U_DEBUG 1
+#else
+#define U_DEBUG 0
+#endif
+#endif
+
+#ifndef U_RELEASE
+#ifdef NDEBUG
+#define U_RELEASE 1
+#else
+#define U_RELEASE 0
+#endif
+#endif
+
+/* Determine whether to disable renaming or not. This overrides the
+   setting in umachine.h which is for all platforms. */
+#ifndef U_DISABLE_RENAMING
+#define U_DISABLE_RENAMING 0
+#endif
+
+/* Determine whether to override new and delete. */
+#ifndef U_OVERRIDE_CXX_ALLOCATION
+#define U_OVERRIDE_CXX_ALLOCATION 1
+#endif
+/* Determine whether to override placement new and delete for STL. */
+#ifndef U_HAVE_PLACEMENT_NEW
+#define U_HAVE_PLACEMENT_NEW 1
+#endif
+/* Determine whether to override new and delete for MFC. */
+#if !defined(U_HAVE_DEBUG_LOCATION_NEW) && defined(_MSC_VER)
+#define U_HAVE_DEBUG_LOCATION_NEW 1
+#endif
+
+/* Determine whether to enable tracing. */
+#ifndef U_ENABLE_TRACING
+#define U_ENABLE_TRACING 0
+#endif
+
+/* Do we allow ICU users to use the draft APIs by default? */
+#ifndef U_DEFAULT_SHOW_DRAFT
+#define U_DEFAULT_SHOW_DRAFT 1
+#endif
+
+/* Define the library suffix in a C syntax. */
+#define U_HAVE_LIB_SUFFIX 0
+#define U_LIB_SUFFIX_C_NAME 
+#define U_LIB_SUFFIX_C_NAME_STRING ""
+
+/*===========================================================================*/
+/* Information about wchar support                                           */
+/*===========================================================================*/
+
+#define U_HAVE_WCHAR_H 1
+#define U_SIZEOF_WCHAR_T 2
+
+#define U_HAVE_WCSCPY 1
+
+/**
+ * \def U_DECLARE_UTF16
+ * Do not use this macro. Use the UNICODE_STRING or U_STRING_DECL macros
+ * instead.
+ * @internal
+ */
+#if 1
+#define U_DECLARE_UTF16(string) L ## string
+#endif
+
+/*===========================================================================*/
+/* Information about POSIX support                                           */
+/*===========================================================================*/
+
+#if 1
+#define U_TZSET         _tzset
+#endif
+#if 1
+#define U_TIMEZONE      _timezone
+#endif
+#if 1
+#define U_TZNAME        _tzname
+#endif
+#if 1
+#define U_DAYLIGHT      _daylight
+#endif
+
+#define U_HAVE_MMAP 0
+#define U_HAVE_POPEN 0
+
+/*===========================================================================*/
+/* Symbol import-export control                                              */
+/*===========================================================================*/
+
+#ifdef U_STATIC_IMPLEMENTATION
+#define U_EXPORT
+#else
+#define U_EXPORT __declspec(dllexport)
+#endif
+#define U_EXPORT2 __cdecl
+#define U_IMPORT __declspec(dllimport)
+
+/*===========================================================================*/
+/* Code alignment and C function inlining                                    */
+/*===========================================================================*/
+
+#ifndef U_INLINE
+#   ifdef __cplusplus
+#       define U_INLINE inline
+#   else
+#       define U_INLINE __inline
+#   endif
+#endif
+
+#if defined(_MSC_VER) && defined(_M_IX86) && !defined(_MANAGED)
+#define U_ALIGN_CODE(val)    __asm      align val
+#else
+#define U_ALIGN_CODE(val)
+#endif
+
+
+/*===========================================================================*/
+/* Programs used by ICU code                                                 */
+/*===========================================================================*/
+
+#ifndef U_MAKE
+#define U_MAKE  "nmake"
+#define U_MAKE_IS_NMAKE 1
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/rbbi.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/rbbi.h b/src/apps/couch_collate/platform/osx/icu/unicode/rbbi.h
new file mode 100644
index 0000000..90ec6e6
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/rbbi.h
@@ -0,0 +1,722 @@
+/*
+***************************************************************************
+*   Copyright (C) 1999-2008 International Business Machines Corporation   *
+*   and others. All rights reserved.                                      *
+***************************************************************************
+
+**********************************************************************
+*   Date        Name        Description
+*   10/22/99    alan        Creation.
+*   11/11/99    rgillam     Complete port from Java.
+**********************************************************************
+*/
+
+#ifndef RBBI_H
+#define RBBI_H
+
+#include "unicode/utypes.h"
+
+/**
+ * \file
+ * \brief C++ API: Rule Based Break Iterator
+ */
+
+#if !UCONFIG_NO_BREAK_ITERATION
+
+#include "unicode/brkiter.h"
+#include "unicode/udata.h"
+#include "unicode/parseerr.h"
+#include "unicode/schriter.h"
+#include "unicode/uchriter.h"
+
+
+struct UTrie;
+
+U_NAMESPACE_BEGIN
+
+/** @internal */
+struct RBBIDataHeader;
+class  RuleBasedBreakIteratorTables;
+class  BreakIterator;
+class  RBBIDataWrapper;
+class  UStack;
+class  LanguageBreakEngine;
+class  UnhandledEngine;
+struct RBBIStateTable;
+
+
+
+
+/**
+ *
+ * A subclass of BreakIterator whose behavior is specified using a list of rules.
+ * <p>Instances of this class are most commonly created by the factory methods of
+ *  BreakIterator::createWordInstance(), BreakIterator::createLineInstance(), etc.,
+ *  and then used via the abstract API in class BreakIterator</p>
+ *
+ * <p>See the ICU User Guide for information on Break Iterator Rules.</p>
+ *
+ * <p>This class is not intended to be subclassed.  (Class DictionaryBasedBreakIterator
+ *    is a subclass, but that relationship is effectively internal to the ICU
+ *    implementation.  The subclassing interface to RulesBasedBreakIterator is
+ *    not part of the ICU API, and may not remain stable.</p>
+ *
+ */
+class U_COMMON_API RuleBasedBreakIterator : public BreakIterator {
+
+protected:
+    /**
+     * The UText through which this BreakIterator accesses the text
+     * @internal
+     */
+    UText  *fText;
+
+    /**
+     *   A character iterator that refers to the same text as the UText, above.
+     *   Only included for compatibility with old API, which was based on CharacterIterators.
+     *   Value may be adopted from outside, or one of fSCharIter or fDCharIter, below.
+     */
+    CharacterIterator  *fCharIter;
+
+    /**
+     *   When the input text is provided by a UnicodeString, this will point to
+     *    a characterIterator that wraps that data.  Needed only for the
+     *    implementation of getText(), a backwards compatibility issue.
+     */
+    StringCharacterIterator *fSCharIter;
+
+    /**
+     *  When the input text is provided by a UText, this
+     *    dummy CharacterIterator over an empty string will
+     *    be returned from getText()
+     */
+    UCharCharacterIterator *fDCharIter;
+
+    /**
+     * The rule data for this BreakIterator instance
+     * @internal
+     */
+    RBBIDataWrapper    *fData;
+
+    /** Index of the Rule {tag} values for the most recent match.
+     *  @internal
+    */
+    int32_t             fLastRuleStatusIndex;
+
+    /**
+     * Rule tag value valid flag.
+     * Some iterator operations don't intrinsically set the correct tag value.
+     * This flag lets us lazily compute the value if we are ever asked for it.
+     * @internal
+     */
+    UBool               fLastStatusIndexValid;
+
+    /**
+     * Counter for the number of characters encountered with the "dictionary"
+     *   flag set.
+     * @internal
+     */
+    uint32_t            fDictionaryCharCount;
+
+    /**
+     * When a range of characters is divided up using the dictionary, the break
+     * positions that are discovered are stored here, preventing us from having
+     * to use either the dictionary or the state table again until the iterator
+     * leaves this range of text. Has the most impact for line breaking.
+     * @internal
+     */
+    int32_t*            fCachedBreakPositions;
+
+    /**
+     * The number of elements in fCachedBreakPositions
+     * @internal
+     */
+    int32_t             fNumCachedBreakPositions;
+
+    /**
+     * if fCachedBreakPositions is not null, this indicates which item in the
+     * cache the current iteration position refers to
+     * @internal
+     */
+    int32_t             fPositionInCache;
+    
+    /**
+     *
+     * If present, UStack of LanguageBreakEngine objects that might handle
+     * dictionary characters. Searched from top to bottom to find an object to
+     * handle a given character.
+     * @internal
+     */
+    UStack              *fLanguageBreakEngines;
+    
+    /**
+     *
+     * If present, the special LanguageBreakEngine used for handling
+     * characters that are in the dictionary set, but not handled by any
+     * LangugageBreakEngine.
+     * @internal
+     */
+    UnhandledEngine     *fUnhandledBreakEngine;
+    
+    /**
+     *
+     * The type of the break iterator, or -1 if it has not been set.
+     * @internal
+     */
+    int32_t             fBreakType;
+    
+protected:
+    //=======================================================================
+    // constructors
+    //=======================================================================
+
+    /**
+     * Constant to be used in the constructor
+     * RuleBasedBreakIterator(RBBIDataHeader*, EDontAdopt, UErrorCode &);
+     * which does not adopt the memory indicated by the RBBIDataHeader*
+     * parameter.
+     *
+     * @internal
+     */
+    enum EDontAdopt {
+        kDontAdopt
+    };
+
+    /**
+     * Constructor from a flattened set of RBBI data in malloced memory.
+     *             RulesBasedBreakIterators built from a custom set of rules
+     *             are created via this constructor; the rules are compiled
+     *             into memory, then the break iterator is constructed here.
+     *
+     *             The break iterator adopts the memory, and will
+     *             free it when done.
+     * @internal
+     */
+    RuleBasedBreakIterator(RBBIDataHeader* data, UErrorCode &status);
+
+    /**
+     * Constructor from a flattened set of RBBI data in memory which need not
+     *             be malloced (e.g. it may be a memory-mapped file, etc.).
+     *
+     *             This version does not adopt the memory, and does not
+     *             free it when done.
+     * @internal
+     */
+    RuleBasedBreakIterator(const RBBIDataHeader* data, enum EDontAdopt dontAdopt, UErrorCode &status);
+
+
+    friend class RBBIRuleBuilder;
+    /** @internal */
+    friend class BreakIterator;
+
+
+
+public:
+
+    /** Default constructor.  Creates an empty shell of an iterator, with no
+     *  rules or text to iterate over.   Object can subsequently be assigned to.
+     *  @stable ICU 2.2
+     */
+    RuleBasedBreakIterator();
+
+    /**
+     * Copy constructor.  Will produce a break iterator with the same behavior,
+     * and which iterates over the same text, as the one passed in.
+     * @param that The RuleBasedBreakIterator passed to be copied
+     * @stable ICU 2.0
+     */
+    RuleBasedBreakIterator(const RuleBasedBreakIterator& that);
+
+    /**
+     * Construct a RuleBasedBreakIterator from a set of rules supplied as a string.
+     * @param rules The break rules to be used.
+     * @param parseError  In the event of a syntax error in the rules, provides the location
+     *                    within the rules of the problem.
+     * @param status Information on any errors encountered.
+     * @stable ICU 2.2
+     */
+    RuleBasedBreakIterator( const UnicodeString    &rules,
+                             UParseError           &parseError,
+                             UErrorCode            &status);
+
+
+    /**
+     * This constructor uses the udata interface to create a BreakIterator
+     * whose internal tables live in a memory-mapped file.  "image" is an
+     * ICU UDataMemory handle for the pre-compiled break iterator tables.
+     * @param image handle to the memory image for the break iterator data.
+     *        Ownership of the UDataMemory handle passes to the Break Iterator,
+     *        which will be responsible for closing it when it is no longer needed.
+     * @param status Information on any errors encountered.
+     * @see udata_open
+     * @see #getBinaryRules
+     * @stable ICU 2.8
+     */
+    RuleBasedBreakIterator(UDataMemory* image, UErrorCode &status);
+
+    /**
+     * Destructor
+     *  @stable ICU 2.0
+     */
+    virtual ~RuleBasedBreakIterator();
+
+    /**
+     * Assignment operator.  Sets this iterator to have the same behavior,
+     * and iterate over the same text, as the one passed in.
+     * @param that The RuleBasedBreakItertor passed in
+     * @return the newly created RuleBasedBreakIterator
+     *  @stable ICU 2.0
+     */
+    RuleBasedBreakIterator& operator=(const RuleBasedBreakIterator& that);
+
+    /**
+     * Equality operator.  Returns TRUE if both BreakIterators are of the
+     * same class, have the same behavior, and iterate over the same text.
+     * @param that The BreakIterator to be compared for equality
+     * @return TRUE if both BreakIterators are of the
+     * same class, have the same behavior, and iterate over the same text.
+     *  @stable ICU 2.0
+     */
+    virtual UBool operator==(const BreakIterator& that) const;
+
+    /**
+     * Not-equal operator.  If operator== returns TRUE, this returns FALSE,
+     * and vice versa.
+     * @param that The BreakIterator to be compared for inequality
+     * @return TRUE if both BreakIterators are not same.
+     *  @stable ICU 2.0
+     */
+    UBool operator!=(const BreakIterator& that) const;
+
+    /**
+     * Returns a newly-constructed RuleBasedBreakIterator with the same
+     * behavior, and iterating over the same text, as this one.
+     * Differs from the copy constructor in that it is polymorphic, and
+     * will correctly clone (copy) a derived class.
+     * clone() is thread safe.  Multiple threads may simultaeneously
+     * clone the same source break iterator.
+     * @return a newly-constructed RuleBasedBreakIterator
+     * @stable ICU 2.0
+     */
+    virtual BreakIterator* clone() const;
+
+    /**
+     * Compute a hash code for this BreakIterator
+     * @return A hash code
+     *  @stable ICU 2.0
+     */
+    virtual int32_t hashCode(void) const;
+
+    /**
+     * Returns the description used to create this iterator
+     * @return the description used to create this iterator
+     *  @stable ICU 2.0
+     */
+    virtual const UnicodeString& getRules(void) const;
+
+    //=======================================================================
+    // BreakIterator overrides
+    //=======================================================================
+
+    /**
+     * <p>
+     * Return a CharacterIterator over the text being analyzed.
+     * The returned character iterator is owned by the break iterator, and must
+     * not be deleted by the caller.  Repeated calls to this function may
+     * return the same CharacterIterator.
+     * </p>
+     * <p>
+     * The returned character iterator must not be used concurrently with
+     * the break iterator.  If concurrent operation is needed, clone the
+     * returned character iterator first and operate on the clone.
+     * </p>
+     * <p>
+     * When the break iterator is operating on text supplied via a UText,
+     * this function will fail.  Lacking any way to signal failures, it
+     * returns an CharacterIterator containing no text.
+     * The function getUText() provides similar functionality,
+     * is reliable, and is more efficient.
+     * </p>
+     *
+     * TODO:  deprecate this function?
+     *
+     * @return An iterator over the text being analyzed.
+     * @stable ICU 2.0
+     */
+    virtual  CharacterIterator& getText(void) const;
+
+
+    /**
+      *  Get a UText for the text being analyzed.
+      *  The returned UText is a shallow clone of the UText used internally
+      *  by the break iterator implementation.  It can safely be used to
+      *  access the text without impacting any break iterator operations,
+      *  but the underlying text itself must not be altered.
+      *
+      * @param fillIn A UText to be filled in.  If NULL, a new UText will be
+      *           allocated to hold the result.
+      * @param status receives any error codes.
+      * @return   The current UText for this break iterator.  If an input
+      *           UText was provided, it will always be returned.
+      * @stable ICU 3.4
+      */
+     virtual UText *getUText(UText *fillIn, UErrorCode &status) const;
+
+    /**
+     * Set the iterator to analyze a new piece of text.  This function resets
+     * the current iteration position to the beginning of the text.
+     * @param newText An iterator over the text to analyze.  The BreakIterator
+     * takes ownership of the character iterator.  The caller MUST NOT delete it!
+     *  @stable ICU 2.0
+     */
+    virtual void adoptText(CharacterIterator* newText);
+
+    /**
+     * Set the iterator to analyze a new piece of text.  This function resets
+     * the current iteration position to the beginning of the text.
+     * @param newText The text to analyze.
+     *  @stable ICU 2.0
+     */
+    virtual void setText(const UnicodeString& newText);
+
+    /**
+     * Reset the break iterator to operate over the text represented by
+     * the UText.  The iterator position is reset to the start.
+     *
+     * This function makes a shallow clone of the supplied UText.  This means
+     * that the caller is free to immediately close or otherwise reuse the
+     * Utext that was passed as a parameter, but that the underlying text itself
+     * must not be altered while being referenced by the break iterator.
+     *
+     * @param text    The UText used to change the text.
+     * @param status  Receives any error codes.
+     * @stable ICU 3.4
+     */
+    virtual void  setText(UText *text, UErrorCode &status);
+
+    /**
+     * Sets the current iteration position to the beginning of the text.
+     * @return The offset of the beginning of the text.
+     *  @stable ICU 2.0
+     */
+    virtual int32_t first(void);
+
+    /**
+     * Sets the current iteration position to the end of the text.
+     * @return The text's past-the-end offset.
+     *  @stable ICU 2.0
+     */
+    virtual int32_t last(void);
+
+    /**
+     * Advances the iterator either forward or backward the specified number of steps.
+     * Negative values move backward, and positive values move forward.  This is
+     * equivalent to repeatedly calling next() or previous().
+     * @param n The number of steps to move.  The sign indicates the direction
+     * (negative is backwards, and positive is forwards).
+     * @return The character offset of the boundary position n boundaries away from
+     * the current one.
+     *  @stable ICU 2.0
+     */
+    virtual int32_t next(int32_t n);
+
+    /**
+     * Advances the iterator to the next boundary position.
+     * @return The position of the first boundary after this one.
+     *  @stable ICU 2.0
+     */
+    virtual int32_t next(void);
+
+    /**
+     * Moves the iterator backwards, to the last boundary preceding this one.
+     * @return The position of the last boundary position preceding this one.
+     *  @stable ICU 2.0
+     */
+    virtual int32_t previous(void);
+
+    /**
+     * Sets the iterator to refer to the first boundary position following
+     * the specified position.
+     * @param offset The position from which to begin searching for a break position.
+     * @return The position of the first break after the current position.
+     *  @stable ICU 2.0
+     */
+    virtual int32_t following(int32_t offset);
+
+    /**
+     * Sets the iterator to refer to the last boundary position before the
+     * specified position.
+     * @param offset The position to begin searching for a break from.
+     * @return The position of the last boundary before the starting position.
+     *  @stable ICU 2.0
+     */
+    virtual int32_t preceding(int32_t offset);
+
+    /**
+     * Returns true if the specfied position is a boundary position.  As a side
+     * effect, leaves the iterator pointing to the first boundary position at
+     * or after "offset".
+     * @param offset the offset to check.
+     * @return True if "offset" is a boundary position.
+     *  @stable ICU 2.0
+     */
+    virtual UBool isBoundary(int32_t offset);
+
+    /**
+     * Returns the current iteration position.
+     * @return The current iteration position.
+     * @stable ICU 2.0
+     */
+    virtual int32_t current(void) const;
+
+
+    /**
+     * Return the status tag from the break rule that determined the most recently
+     * returned break position.  For break rules that do not specify a
+     * status, a default value of 0 is returned.  If more than one break rule
+     * would cause a boundary to be located at some position in the text,
+     * the numerically largest of the applicable status values is returned.
+     * <p>
+     * Of the standard types of ICU break iterators, only word break and
+     * line break provide status values.  The values are defined in
+     * the header file ubrk.h.  For Word breaks, the status allows distinguishing between words
+     * that contain alphabetic letters, "words" that appear to be numbers,
+     * punctuation and spaces, words containing ideographic characters, and
+     * more.  For Line Break, the status distinguishes between hard (mandatory) breaks
+     * and soft (potential) break positions.
+     * <p>
+     * <code>getRuleStatus()</code> can be called after obtaining a boundary
+     * position from <code>next()</code>, <code>previous()</code>, or
+     * any other break iterator functions that returns a boundary position.
+     * <p>
+     * When creating custom break rules, one is free to define whatever
+     * status values may be convenient for the application.
+     * <p>
+     * Note: this function is not thread safe.  It should not have been
+     *       declared const, and the const remains only for compatibility
+     *       reasons.  (The function is logically const, but not bit-wise const).
+     * <p>
+     * @return the status from the break rule that determined the most recently
+     * returned break position.
+     *
+     * @see UWordBreak
+     * @stable ICU 2.2
+     */
+    virtual int32_t getRuleStatus() const;
+
+   /**
+    * Get the status (tag) values from the break rule(s) that determined the most
+    * recently returned break position.
+    * <p>
+    * The returned status value(s) are stored into an array provided by the caller.
+    * The values are stored in sorted (ascending) order.
+    * If the capacity of the output array is insufficient to hold the data,
+    *  the output will be truncated to the available length, and a
+    *  U_BUFFER_OVERFLOW_ERROR will be signaled.
+    *
+    * @param fillInVec an array to be filled in with the status values.
+    * @param capacity  the length of the supplied vector.  A length of zero causes
+    *                  the function to return the number of status values, in the
+    *                  normal way, without attemtping to store any values.
+    * @param status    receives error codes.
+    * @return          The number of rule status values from rules that determined
+    *                  the most recent boundary returned by the break iterator.
+    *                  In the event of a U_BUFFER_OVERFLOW_ERROR, the return value
+    *                  is the total number of status values that were available,
+    *                  not the reduced number that were actually returned.
+    * @see getRuleStatus
+    * @stable ICU 3.0
+    */
+    virtual int32_t getRuleStatusVec(int32_t *fillInVec, int32_t capacity, UErrorCode &status);
+
+    /**
+     * Returns a unique class ID POLYMORPHICALLY.  Pure virtual override.
+     * This method is to implement a simple version of RTTI, since not all
+     * C++ compilers support genuine RTTI.  Polymorphic operator==() and
+     * clone() methods call this method.
+     *
+     * @return          The class ID for this object. All objects of a
+     *                  given class have the same class ID.  Objects of
+     *                  other classes have different class IDs.
+     * @stable ICU 2.0
+     */
+    virtual UClassID getDynamicClassID(void) const;
+
+    /**
+     * Returns the class ID for this class.  This is useful only for
+     * comparing to a return value from getDynamicClassID().  For example:
+     *
+     *      Base* polymorphic_pointer = createPolymorphicObject();
+     *      if (polymorphic_pointer->getDynamicClassID() ==
+     *          Derived::getStaticClassID()) ...
+     *
+     * @return          The class ID for all objects of this class.
+     * @stable ICU 2.0
+     */
+    static UClassID U_EXPORT2 getStaticClassID(void);
+
+    /*
+     * Create a clone (copy) of this break iterator in memory provided
+     *  by the caller.  The idea is to increase performance by avoiding
+     *  a storage allocation.  Use of this functoin is NOT RECOMMENDED.
+     *  Performance gains are minimal, and correct buffer management is
+     *  tricky.  Use clone() instead.
+     *
+     * @param stackBuffer  The pointer to the memory into which the cloned object
+     *                     should be placed.  If NULL,  allocate heap memory
+     *                     for the cloned object.
+     * @param BufferSize   The size of the buffer.  If zero, return the required
+     *                     buffer size, but do not clone the object.  If the
+     *                     size was too small (but not zero), allocate heap
+     *                     storage for the cloned object.
+     *
+     * @param status       Error status.  U_SAFECLONE_ALLOCATED_WARNING will be
+     *                     returned if the the provided buffer was too small, and
+     *                     the clone was therefore put on the heap.
+     *
+     * @return  Pointer to the clone object.  This may differ from the stackBuffer
+     *          address if the byte alignment of the stack buffer was not suitable
+     *          or if the stackBuffer was too small to hold the clone.
+     * @stable ICU 2.0
+     */
+    virtual BreakIterator *  createBufferClone(void *stackBuffer,
+                                               int32_t &BufferSize,
+                                               UErrorCode &status);
+
+
+    /**
+     * Return the binary form of compiled break rules,
+     * which can then be used to create a new break iterator at some
+     * time in the future.  Creating a break iterator from pre-compiled rules
+     * is much faster than building one from the source form of the
+     * break rules.
+     *
+     * The binary data can only be used with the same version of ICU
+     *  and on the same platform type (processor endian-ness)
+     *
+     * @param length Returns the length of the binary data.  (Out paramter.)
+     *
+     * @return   A pointer to the binary (compiled) rule data.  The storage
+     *           belongs to the RulesBasedBreakIterator object, not the
+     *           caller, and must not be modified or deleted.
+     * @internal
+     */
+    virtual const uint8_t *getBinaryRules(uint32_t &length);
+
+
+protected:
+    //=======================================================================
+    // implementation
+    //=======================================================================
+    /**
+     * Dumps caches and performs other actions associated with a complete change
+     * in text or iteration position.
+     * @internal
+     */
+    virtual void reset(void);
+
+#if 0
+    /**
+      * Return true if the category lookup for this char
+      * indicates that it is in the set of dictionary lookup chars.
+      * This function is intended for use by dictionary based break iterators.
+      * @return true if the category lookup for this char
+      * indicates that it is in the set of dictionary lookup chars.
+      * @internal
+      */
+    virtual UBool isDictionaryChar(UChar32);
+
+    /**
+      * Get the type of the break iterator.
+      * @internal
+      */
+    virtual int32_t getBreakType() const;
+#endif
+
+    /**
+      * Set the type of the break iterator.
+      * @internal
+      */
+    virtual void setBreakType(int32_t type);
+
+    /**
+      * Common initialization function, used by constructors and bufferClone.
+      *   (Also used by DictionaryBasedBreakIterator::createBufferClone().)
+      * @internal
+      */
+    void init();
+
+private:
+
+    /**
+     * This method backs the iterator back up to a "safe position" in the text.
+     * This is a position that we know, without any context, must be a break position.
+     * The various calling methods then iterate forward from this safe position to
+     * the appropriate position to return.  (For more information, see the description
+     * of buildBackwardsStateTable() in RuleBasedBreakIterator.Builder.)
+     * @param statetable state table used of moving backwards
+     * @internal
+     */
+    int32_t handlePrevious(const RBBIStateTable *statetable);
+
+    /**
+     * This method is the actual implementation of the next() method.  All iteration
+     * vectors through here.  This method initializes the state machine to state 1
+     * and advances through the text character by character until we reach the end
+     * of the text or the state machine transitions to state 0.  We update our return
+     * value every time the state machine passes through a possible end state.
+     * @param statetable state table used of moving forwards
+     * @internal
+     */
+    int32_t handleNext(const RBBIStateTable *statetable);
+
+protected:
+
+    /**
+     * This is the function that actually implements dictionary-based
+     * breaking.  Covering at least the range from startPos to endPos,
+     * it checks for dictionary characters, and if it finds them determines
+     * the appropriate object to deal with them. It may cache found breaks in
+     * fCachedBreakPositions as it goes. It may well also look at text outside
+     * the range startPos to endPos.
+     * If going forward, endPos is the normal Unicode break result, and
+     * if goind in reverse, startPos is the normal Unicode break result
+     * @param startPos  The start position of a range of text
+     * @param endPos    The end position of a range of text
+     * @param reverse   The call is for the reverse direction
+     * @internal
+     */
+    int32_t checkDictionary(int32_t startPos, int32_t endPos, UBool reverse);
+
+private:
+
+    /**
+     * This function returns the appropriate LanguageBreakEngine for a
+     * given character c.
+     * @param c         A character in the dictionary set
+     * @internal
+     */
+    const LanguageBreakEngine *getLanguageBreakEngine(UChar32 c);
+
+    /**
+     *  @internal
+     */
+    void makeRuleStatusValid();
+
+};
+
+//------------------------------------------------------------------------------
+//
+//   Inline Functions Definitions ...
+//
+//------------------------------------------------------------------------------
+
+inline UBool RuleBasedBreakIterator::operator!=(const BreakIterator& that) const {
+    return !operator==(that);
+}
+
+U_NAMESPACE_END
+
+#endif /* #if !UCONFIG_NO_BREAK_ITERATION */
+
+#endif


[86/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/dtitvinf.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/dtitvinf.h b/src/apps/couch_collate/platform/osx/icu/unicode/dtitvinf.h
new file mode 100644
index 0000000..07a8dbd
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/dtitvinf.h
@@ -0,0 +1,528 @@
+/*
+ *******************************************************************************
+ * Copyright (C) 2008, International Business Machines Corporation and
+ * others. All Rights Reserved.
+ *******************************************************************************
+ *
+ * File DTITVINF.H
+ *
+ *******************************************************************************
+ */
+
+#ifndef __DTITVINF_H__
+#define __DTITVINF_H__
+
+#include "unicode/utypes.h"
+
+/**
+ * \file
+ * \brief C++ API: Date/Time interval patterns for formatting date/time interval
+ */
+
+#if !UCONFIG_NO_FORMATTING
+
+#include "unicode/udat.h"
+#include "unicode/locid.h"
+#include "unicode/ucal.h"
+#include "unicode/dtptngen.h"
+//#include "dtitv_impl.h"
+
+/**
+ * @internal ICU 4.0
+ */
+ 
+union UHashTok;
+
+
+U_NAMESPACE_BEGIN
+
+U_CDECL_BEGIN 
+
+/**
+ * @internal ICU 4.0
+ */
+static UBool U_CALLCONV hashTableValueComparator(UHashTok val1, UHashTok val2) ;
+
+U_CDECL_END 
+
+
+/**
+ * DateIntervalInfo is a public class for encapsulating localizable
+ * date time interval patterns. It is used by DateIntervalFormat.
+ *
+ * <P>
+ * For most users, ordinary use of DateIntervalFormat does not need to create
+ * DateIntervalInfo object directly.
+ * DateIntervalFormat will take care of it when creating a date interval
+ * formatter when user pass in skeleton and locale.
+ *
+ * <P>
+ * For power users, who want to create their own date interval patterns,
+ * or want to re-set date interval patterns, they could do so by
+ * directly creating DateIntervalInfo and manupulating it.
+ *
+ * <P>
+ * Logically, the interval patterns are mappings
+ * from (skeleton, the_largest_different_calendar_field)
+ * to (date_interval_pattern).
+ *
+ * <P>
+ * A skeleton 
+ * <ol>
+ * <li>
+ * only keeps the field pattern letter and ignores all other parts 
+ * in a pattern, such as space, punctuations, and string literals.
+ * <li>
+ * hides the order of fields. 
+ * <li>
+ * might hide a field's pattern letter length.
+ *
+ * For those non-digit calendar fields, the pattern letter length is 
+ * important, such as MMM, MMMM, and MMMMM; EEE and EEEE, 
+ * and the field's pattern letter length is honored.
+ *    
+ * For the digit calendar fields,  such as M or MM, d or dd, yy or yyyy, 
+ * the field pattern length is ignored and the best match, which is defined 
+ * in date time patterns, will be returned without honor the field pattern
+ * letter length in skeleton.
+ * </ol>
+ *
+ * <P>
+ * The calendar fields we support for interval formatting are:
+ * year, month, date, day-of-week, am-pm, hour, hour-of-day, and minute.
+ * Those calendar fields can be defined in the following order:
+ * year >  month > date > am-pm > hour >  minute 
+ *  
+ * The largest different calendar fields between 2 calendars is the
+ * first different calendar field in above order.
+ *
+ * For example: the largest different calendar fields between "Jan 10, 2007" 
+ * and "Feb 20, 2008" is year.
+ *   
+ * <P>
+ * There is a set of pre-defined static skeleton strings.
+ * There are pre-defined interval patterns for those pre-defined skeletons
+ * in locales' resource files.
+ * For example, for a skeleton UDAT_YEAR_ABBR_MONTH_DAY, which is  "yMMMd",
+ * in  en_US, if the largest different calendar field between date1 and date2 
+ * is "year", the date interval pattern  is "MMM d, yyyy - MMM d, yyyy", 
+ * such as "Jan 10, 2007 - Jan 10, 2008".
+ * If the largest different calendar field between date1 and date2 is "month",
+ * the date interval pattern is "MMM d - MMM d, yyyy",
+ * such as "Jan 10 - Feb 10, 2007".
+ * If the largest different calendar field between date1 and date2 is "day",
+ * the date interval pattern is ""MMM d-d, yyyy", such as "Jan 10-20, 2007".
+ *
+ * For date skeleton, the interval patterns when year, or month, or date is 
+ * different are defined in resource files.
+ * For time skeleton, the interval patterns when am/pm, or hour, or minute is
+ * different are defined in resource files.
+ *
+ *
+ * <P>
+ * There are 2 dates in interval pattern. For most locales, the first date
+ * in an interval pattern is the earlier date. There might be a locale in which
+ * the first date in an interval pattern is the later date.
+ * We use fallback format for the default order for the locale.
+ * For example, if the fallback format is "{0} - {1}", it means
+ * the first date in the interval pattern for this locale is earlier date.
+ * If the fallback format is "{1} - {0}", it means the first date is the 
+ * later date.
+ * For a particular interval pattern, the default order can be overriden
+ * by prefixing "latestFirst:" or "earliestFirst:" to the interval pattern.
+ * For example, if the fallback format is "{0}-{1}",
+ * but for skeleton "yMMMd", the interval pattern when day is different is 
+ * "latestFirst:d-d MMM yy", it means by default, the first date in interval
+ * pattern is the earlier date. But for skeleton "yMMMd", when day is different,
+ * the first date in "d-d MMM yy" is the later date.
+ * 
+ * <P>
+ * The recommended way to create a DateIntervalFormat object is to pass in 
+ * the locale. 
+ * By using a Locale parameter, the DateIntervalFormat object is 
+ * initialized with the pre-defined interval patterns for a given or 
+ * default locale.
+ * <P>
+ * Users can also create DateIntervalFormat object 
+ * by supplying their own interval patterns.
+ * It provides flexibility for power users.
+ *
+ * <P>
+ * After a DateIntervalInfo object is created, clients may modify
+ * the interval patterns using setIntervalPattern function as so desired.
+ * Currently, users can only set interval patterns when the following 
+ * calendar fields are different: ERA, YEAR, MONTH, DATE,  DAY_OF_MONTH, 
+ * DAY_OF_WEEK, AM_PM,  HOUR, HOUR_OF_DAY, and MINUTE.
+ * Interval patterns when other calendar fields are different is not supported.
+ * <P>
+ * DateIntervalInfo objects are cloneable. 
+ * When clients obtain a DateIntervalInfo object, 
+ * they can feel free to modify it as necessary.
+ * <P>
+ * DateIntervalInfo are not expected to be subclassed. 
+ * Data for a calendar is loaded out of resource bundles. 
+ * To ICU 4.0, date interval patterns are only supported in Gregorian calendar. 
+ * @draft ICU 4.0
+**/
+
+class U_I18N_API DateIntervalInfo : public UObject {
+public:
+    /**
+     * Default constructor.
+     * It does not initialize any interval patterns except
+     * that it initialize default fall-back pattern as "{0} - {1}",
+     * which can be reset by setFallbackIntervalPattern().
+     * It should be followed by setFallbackIntervalPattern() and 
+     * setIntervalPattern(), 
+     * and is recommended to be used only for power users who
+     * wants to create their own interval patterns and use them to create
+     * date interval formatter.
+     * @param status   output param set to success/failure code on exit
+     * @internal ICU 4.0
+     */
+    DateIntervalInfo(UErrorCode& status);
+
+
+    /** 
+     * Construct DateIntervalInfo for the given locale,
+     * @param locale  the interval patterns are loaded from the Gregorian 
+     *                calendar data in this locale.
+     * @param status  output param set to success/failure code on exit
+     * @draft ICU 4.0
+     */
+    DateIntervalInfo(const Locale& locale, UErrorCode& status);
+
+
+    /**
+     * Copy constructor.
+     * @draft ICU 4.0
+     */
+    DateIntervalInfo(const DateIntervalInfo&);
+
+    /**
+     * Assignment operator
+     * @draft ICU 4.0
+     */
+    DateIntervalInfo& operator=(const DateIntervalInfo&);
+
+    /**
+     * Clone this object polymorphically.
+     * The caller owns the result and should delete it when done.
+     * @return   a copy of the object
+     * @draft    ICU4.0
+     */
+    virtual DateIntervalInfo* clone(void) const;
+
+    /**
+     * Destructor.
+     * It is virtual to be safe, but it is not designed to be subclassed.
+     * @draft ICU 4.0
+     */
+    virtual ~DateIntervalInfo();
+
+
+    /**
+     * Return true if another object is semantically equal to this one.
+     *
+     * @param other    the DateIntervalInfo object to be compared with.
+     * @return         true if other is semantically equal to this.
+     * @stable ICU 4.0
+     */
+    virtual UBool operator==(const DateIntervalInfo& other) const;
+
+    /**
+     * Return true if another object is semantically unequal to this one.
+     *
+     * @param other    the DateIntervalInfo object to be compared with.
+     * @return         true if other is semantically unequal to this.
+     * @stable ICU 4.0
+     */
+    UBool operator!=(const DateIntervalInfo& other) const;
+
+
+
+    /** 
+     * Provides a way for client to build interval patterns.
+     * User could construct DateIntervalInfo by providing a list of skeletons
+     * and their patterns.
+     * <P>
+     * For example:
+     * <pre>
+     * UErrorCode status = U_ZERO_ERROR;
+     * DateIntervalInfo dIntervalInfo = new DateIntervalInfo();
+     * dIntervalInfo->setFallbackIntervalPattern("{0} ~ {1}");
+     * dIntervalInfo->setIntervalPattern("yMd", UCAL_YEAR, "'from' yyyy-M-d 'to' yyyy-M-d", status); 
+     * dIntervalInfo->setIntervalPattern("yMMMd", UCAL_MONTH, "'from' yyyy MMM d 'to' MMM d", status);
+     * dIntervalInfo->setIntervalPattern("yMMMd", UCAL_DAY, "yyyy MMM d-d", status, status);
+     * </pre>
+     *
+     * Restriction: 
+     * Currently, users can only set interval patterns when the following 
+     * calendar fields are different: ERA, YEAR, MONTH, DATE,  DAY_OF_MONTH, 
+     * DAY_OF_WEEK, AM_PM,  HOUR, HOUR_OF_DAY, and MINUTE.
+     * Interval patterns when other calendar fields are different are 
+     * not supported.
+     *
+     * @param skeleton         the skeleton on which interval pattern based
+     * @param lrgDiffCalUnit   the largest different calendar unit.
+     * @param intervalPattern  the interval pattern on the largest different
+     *                         calendar unit.
+     *                         For example, if lrgDiffCalUnit is 
+     *                         "year", the interval pattern for en_US when year
+     *                         is different could be "'from' yyyy 'to' yyyy".
+     * @param status           output param set to success/failure code on exit
+     * @draft ICU 4.0
+     */
+    void setIntervalPattern(const UnicodeString& skeleton, 
+                            UCalendarDateFields lrgDiffCalUnit, 
+                            const UnicodeString& intervalPattern,
+                            UErrorCode& status);
+
+    /**
+     * Get the interval pattern given skeleton and 
+     * the largest different calendar field.
+     * @param skeleton   the skeleton
+     * @param field      the largest different calendar field
+     * @param result     output param to receive the pattern
+     * @param status     output param set to success/failure code on exit
+     * @return a reference to 'result'
+     * @draft ICU 4.0 
+     */
+    UnicodeString& getIntervalPattern(const UnicodeString& skeleton,
+                                      UCalendarDateFields field,
+                                      UnicodeString& result,
+                                      UErrorCode& status) const; 
+
+    /**
+     * Get the fallback interval pattern.
+     * @param  result   output param to receive the pattern
+     * @return a reference to 'result'
+     * @draft ICU 4.0 
+     */
+    UnicodeString& getFallbackIntervalPattern(UnicodeString& result) const;
+
+
+    /**
+     * Re-set the fallback interval pattern.
+     *
+     * In construction, default fallback pattern is set as "{0} - {1}".
+     * And constructor taking locale as parameter will set the
+     * fallback pattern as what defined in the locale resource file.
+     *
+     * This method provides a way for user to replace the fallback pattern.
+     *
+     * @param fallbackPattern  fall-back interval pattern.
+     * @param status           output param set to success/failure code on exit
+     * @draft ICU 4.0 
+     */
+    void setFallbackIntervalPattern(const UnicodeString& fallbackPattern,
+                                    UErrorCode& status);
+
+
+    /** Get default order -- whether the first date in pattern is later date
+                             or not.
+     * return default date ordering in interval pattern. TRUE if the first date
+     *        in pattern is later date, FALSE otherwise.
+     * @draft ICU 4.0 
+     */
+    UBool getDefaultOrder() const;
+
+
+    /**
+     * ICU "poor man's RTTI", returns a UClassID for the actual class.
+     *
+     * @stable ICU 4.0
+     */
+    virtual UClassID getDynamicClassID() const;
+
+    /**
+     * ICU "poor man's RTTI", returns a UClassID for this class.
+     *
+     * @stable ICU 4.0
+     */
+    static UClassID U_EXPORT2 getStaticClassID();
+
+
+private:
+    /**
+     * DateIntervalFormat will need access to
+     * getBestSkeleton(), parseSkeleton(), enum IntervalPatternIndex,
+     * and calendarFieldToPatternIndex().
+     *
+     * Instead of making above public,
+     * make DateIntervalFormat a friend of DateIntervalInfo.
+     */
+    friend class DateIntervalFormat;
+
+    friend UBool U_CALLCONV hashTableValueComparator(UHashTok val1, UHashTok val2) ;
+
+    /**
+     * Following is for saving the interval patterns.
+     * We only support interval patterns on
+     * ERA, YEAR, MONTH, DAY, AM_PM, HOUR, and MINUTE
+     */
+    enum IntervalPatternIndex
+    {
+        kIPI_ERA,
+        kIPI_YEAR,
+        kIPI_MONTH,
+        kIPI_DATE,
+        kIPI_AM_PM,
+        kIPI_HOUR,
+        kIPI_MINUTE,
+        kIPI_MAX_INDEX
+    };
+
+    /** 
+     * Initialize the DateIntervalInfo from locale
+     * @param locale   the given locale.
+     * @param status   output param set to success/failure code on exit
+     * @internal ICU 4.0 
+     */
+    void initializeData(const Locale& locale, UErrorCode& status);
+
+
+    /* Set Interval pattern.
+     *
+     * It sets interval pattern into the hash map.
+     *
+     * @param skeleton         skeleton on which the interval pattern based
+     * @param lrgDiffCalUnit   the largest different calendar unit.
+     * @param intervalPattern  the interval pattern on the largest different
+     *                         calendar unit.
+     * @param status           output param set to success/failure code on exit
+     * @internal ICU 4.0
+     */
+    void setIntervalPatternInternally(const UnicodeString& skeleton,
+                                      UCalendarDateFields lrgDiffCalUnit,
+                                      const UnicodeString& intervalPattern,
+                                      UErrorCode& status); 
+
+
+    /**given an input skeleton, get the best match skeleton 
+     * which has pre-defined interval pattern in resource file.
+     * Also return the difference between the input skeleton
+     * and the best match skeleton.
+     *
+     * TODO (xji): set field weight or
+     *             isolate the funtionality in DateTimePatternGenerator
+     * @param  skeleton               input skeleton
+     * @param  bestMatchDistanceInfo  the difference between input skeleton
+     *                                and best match skeleton.
+     *         0, if there is exact match for input skeleton
+     *         1, if there is only field width difference between 
+     *            the best match and the input skeleton
+     *         2, the only field difference is 'v' and 'z'
+     *        -1, if there is calendar field difference between
+     *            the best match and the input skeleton
+     * @return                        best match skeleton
+     * @internal ICU 4.0
+     */
+    const UnicodeString* getBestSkeleton(const UnicodeString& skeleton,
+                                         int8_t& bestMatchDistanceInfo) const;
+
+
+    /**
+     * Parse skeleton, save each field's width.
+     * It is used for looking for best match skeleton,
+     * and adjust pattern field width.
+     * @param skeleton            skeleton to be parsed
+     * @param skeletonFieldWidth  parsed skeleton field width
+     * @internal ICU 4.0
+     */
+    static void U_EXPORT2 parseSkeleton(const UnicodeString& skeleton, 
+                                        int32_t* skeletonFieldWidth);
+
+
+    /**
+     * Check whether one field width is numeric while the other is string.
+     *
+     * TODO (xji): make it general
+     *
+     * @param fieldWidth          one field width
+     * @param anotherFieldWidth   another field width
+     * @param patternLetter       pattern letter char
+     * @return true if one field width is numeric and the other is string,
+     *         false otherwise.
+     * @internal ICU 4.0
+     */
+    static UBool U_EXPORT2 stringNumeric(int32_t fieldWidth,
+                                         int32_t anotherFieldWidth,
+                                         char patternLetter);
+
+
+    /** 
+     * Convert calendar field to the interval pattern index in 
+     * hash table.
+     *
+     * Since we only support the following calendar fields: 
+     * ERA, YEAR, MONTH, DATE,  DAY_OF_MONTH, DAY_OF_WEEK, 
+     * AM_PM,  HOUR, HOUR_OF_DAY, and MINUTE,
+     * We reserve only 4 interval patterns for a skeleton.
+     *
+     * @param field    calendar field
+     * @param status   output param set to success/failure code on exit
+     * @return  interval pattern index in hash table
+     * @internal ICU 4.0
+     */
+    static IntervalPatternIndex U_EXPORT2 calendarFieldToIntervalIndex(
+                                                      UCalendarDateFields field,
+                                                      UErrorCode& status);
+
+
+    /**
+     * delete hash table (of type fIntervalPatterns).
+     *
+     * @param hTable  hash table to be deleted
+     * @internal ICU 4.0
+     */
+    void deleteHash(Hashtable* hTable);
+
+
+    /**
+     * initialize hash table (of type fIntervalPatterns).
+     *
+     * @param status   output param set to success/failure code on exit
+     * @return         hash table initialized
+     * @internal ICU 4.0
+     */
+    Hashtable* initHash(UErrorCode& status);
+
+
+
+    /**
+     * copy hash table (of type fIntervalPatterns).
+     *
+     * @param source   the source to copy from
+     * @param target   the target to copy to
+     * @param status   output param set to success/failure code on exit
+     * @internal ICU 4.0
+     */
+    void copyHash(const Hashtable* source, Hashtable* target, UErrorCode& status);
+
+
+    // data members
+    // fallback interval pattern 
+    UnicodeString fFallbackIntervalPattern;
+    // default order
+    UBool fFirstDateInPtnIsLaterDate;
+
+    // HashMap<UnicodeString, UnicodeString[kIPI_MAX_INDEX]>
+    // HashMap( skeleton, pattern[largest_different_field] )
+    Hashtable* fIntervalPatterns;
+
+};// end class DateIntervalInfo
+
+
+inline UBool
+DateIntervalInfo::operator!=(const DateIntervalInfo& other) const {
+    return !operator==(other);
+}
+
+
+U_NAMESPACE_END
+
+#endif
+
+#endif
+

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/dtptngen.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/dtptngen.h b/src/apps/couch_collate/platform/osx/icu/unicode/dtptngen.h
new file mode 100644
index 0000000..eeea626
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/dtptngen.h
@@ -0,0 +1,423 @@
+/*
+*******************************************************************************
+* Copyright (C) 2007-2009, International Business Machines Corporation and
+* others. All Rights Reserved.
+*******************************************************************************
+*
+* File DTPTNGEN.H
+*
+*******************************************************************************
+*/
+
+#ifndef __DTPTNGEN_H__
+#define __DTPTNGEN_H__
+
+#include "unicode/datefmt.h"
+#include "unicode/locid.h"
+#include "unicode/udat.h"
+#include "unicode/udatpg.h"
+
+U_NAMESPACE_BEGIN
+
+/**
+ * \file
+ * \brief C++ API: Date/Time Pattern Generator
+ */
+
+
+class Hashtable;
+class FormatParser;
+class DateTimeMatcher;
+class DistanceInfo;
+class PatternMap;
+class PtnSkeleton;
+
+/**
+ * This class provides flexible generation of date format patterns, like "yy-MM-dd". 
+ * The user can build up the generator by adding successive patterns. Once that 
+ * is done, a query can be made using a "skeleton", which is a pattern which just
+ * includes the desired fields and lengths. The generator will return the "best fit" 
+ * pattern corresponding to that skeleton.
+ * <p>The main method people will use is getBestPattern(String skeleton),
+ * since normally this class is pre-built with data from a particular locale. 
+ * However, generators can be built directly from other data as well.
+ * <p><i>Issue: may be useful to also have a function that returns the list of 
+ * fields in a pattern, in order, since we have that internally.
+ * That would be useful for getting the UI order of field elements.</i>
+ * @stable ICU 3.8
+**/
+class U_I18N_API DateTimePatternGenerator : public UObject {
+public:
+    /**
+     * Construct a flexible generator according to default locale.
+     * @param status  Output param set to success/failure code on exit,
+     *               which must not indicate a failure before the function call.
+     * @stable ICU 3.8
+     */
+    static DateTimePatternGenerator* U_EXPORT2 createInstance(UErrorCode& status);
+
+    /**
+     * Construct a flexible generator according to data for a given locale.
+     * @param uLocale
+     * @param status  Output param set to success/failure code on exit,
+     *               which must not indicate a failure before the function call.
+     * @stable ICU 3.8
+     */
+    static DateTimePatternGenerator* U_EXPORT2 createInstance(const Locale& uLocale, UErrorCode& status);
+
+    /**
+     * Create an empty generator, to be constructed with addPattern(...) etc.
+     * @param status  Output param set to success/failure code on exit,
+     *               which must not indicate a failure before the function call.
+     * @stable ICU 3.8
+     */
+     static DateTimePatternGenerator* U_EXPORT2 createEmptyInstance(UErrorCode& status);
+     
+    /**
+     * Destructor.
+     * @stable ICU 3.8
+     */
+    virtual ~DateTimePatternGenerator();
+
+    /**
+     * Clone DateTimePatternGenerator object. Clients are responsible for 
+     * deleting the DateTimePatternGenerator object cloned.
+     * @stable ICU 3.8
+     */
+    DateTimePatternGenerator* clone() const;
+
+     /**
+      * Return true if another object is semantically equal to this one.
+      *
+      * @param other    the DateTimePatternGenerator object to be compared with.
+      * @return         true if other is semantically equal to this.
+      * @stable ICU 3.8
+      */
+    UBool operator==(const DateTimePatternGenerator& other) const;
+    
+    /**
+     * Return true if another object is semantically unequal to this one.
+     *
+     * @param other    the DateTimePatternGenerator object to be compared with.
+     * @return         true if other is semantically unequal to this.
+     * @stable ICU 3.8
+     */
+    UBool operator!=(const DateTimePatternGenerator& other) const;
+
+    /**
+     * Utility to return a unique skeleton from a given pattern. For example,
+     * both "MMM-dd" and "dd/MMM" produce the skeleton "MMMdd".
+     *
+     * @param pattern   Input pattern, such as "dd/MMM"
+     * @param status  Output param set to success/failure code on exit,
+     *                  which must not indicate a failure before the function call.
+     * @return skeleton such as "MMMdd"
+     * @stable ICU 3.8
+     */
+    UnicodeString getSkeleton(const UnicodeString& pattern, UErrorCode& status);
+
+    /**
+     * Utility to return a unique base skeleton from a given pattern. This is
+     * the same as the skeleton, except that differences in length are minimized
+     * so as to only preserve the difference between string and numeric form. So
+     * for example, both "MMM-dd" and "d/MMM" produce the skeleton "MMMd"
+     * (notice the single d).
+     *
+     * @param pattern  Input pattern, such as "dd/MMM"
+     * @param status  Output param set to success/failure code on exit,
+     *               which must not indicate a failure before the function call.
+     * @return base skeleton, such as "Md"
+     * @stable ICU 3.8
+     */
+    UnicodeString getBaseSkeleton(const UnicodeString& pattern, UErrorCode& status);
+
+    /**
+     * Adds a pattern to the generator. If the pattern has the same skeleton as
+     * an existing pattern, and the override parameter is set, then the previous
+     * value is overriden. Otherwise, the previous value is retained. In either
+     * case, the conflicting status is set and previous vale is stored in 
+     * conflicting pattern.
+     * <p>
+     * Note that single-field patterns (like "MMM") are automatically added, and
+     * don't need to be added explicitly!
+     *
+     * @param pattern   Input pattern, such as "dd/MMM"
+     * @param override  When existing values are to be overridden use true, 
+     *                   otherwise use false.
+     * @param conflictingPattern  Previous pattern with the same skeleton.
+     * @param status  Output param set to success/failure code on exit,
+     *               which must not indicate a failure before the function call.
+     * @return conflicting status.  The value could be UDATPG_NO_CONFLICT, 
+     *                             UDATPG_BASE_CONFLICT or UDATPG_CONFLICT.
+     * @stable ICU 3.8
+     */
+    UDateTimePatternConflict addPattern(const UnicodeString& pattern, 
+                                        UBool override, 
+                                        UnicodeString& conflictingPattern,
+                                        UErrorCode& status);
+
+    /**
+     * An AppendItem format is a pattern used to append a field if there is no
+     * good match. For example, suppose that the input skeleton is "GyyyyMMMd",
+     * and there is no matching pattern internally, but there is a pattern
+     * matching "yyyyMMMd", say "d-MM-yyyy". Then that pattern is used, plus the
+     * G. The way these two are conjoined is by using the AppendItemFormat for G
+     * (era). So if that value is, say "{0}, {1}" then the final resulting
+     * pattern is "d-MM-yyyy, G".
+     * <p>
+     * There are actually three available variables: {0} is the pattern so far,
+     * {1} is the element we are adding, and {2} is the name of the element.
+     * <p>
+     * This reflects the way that the CLDR data is organized.
+     *
+     * @param field  such as UDATPG_ERA_FIELD.
+     * @param value  pattern, such as "{0}, {1}"
+     * @stable ICU 3.8
+     */
+    void setAppendItemFormat(UDateTimePatternField field, const UnicodeString& value);
+
+    /**
+     * Getter corresponding to setAppendItemFormat. Values below 0 or at or
+     * above UDATPG_FIELD_COUNT are illegal arguments.
+     *
+     * @param  field  such as UDATPG_ERA_FIELD.
+     * @return append pattern for field
+     * @stable ICU 3.8
+     */
+    const UnicodeString& getAppendItemFormat(UDateTimePatternField field) const;
+
+    /**
+     * Sets the names of field, eg "era" in English for ERA. These are only
+     * used if the corresponding AppendItemFormat is used, and if it contains a
+     * {2} variable.
+     * <p>
+     * This reflects the way that the CLDR data is organized.
+     *
+     * @param field   such as UDATPG_ERA_FIELD.
+     * @param value   name of the field
+     * @stable ICU 3.8
+     */
+    void setAppendItemName(UDateTimePatternField field, const UnicodeString& value);
+
+    /**
+     * Getter corresponding to setAppendItemNames. Values below 0 or at or above
+     * UDATPG_FIELD_COUNT are illegal arguments.
+     *
+     * @param field  such as UDATPG_ERA_FIELD.
+     * @return name for field
+     * @stable ICU 3.8
+     */
+    const UnicodeString& getAppendItemName(UDateTimePatternField field) const;
+
+    /**
+     * The date time format is a message format pattern used to compose date and
+     * time patterns. The default value is "{0} {1}", where {0} will be replaced
+     * by the date pattern and {1} will be replaced by the time pattern.
+     * <p>
+     * This is used when the input skeleton contains both date and time fields,
+     * but there is not a close match among the added patterns. For example,
+     * suppose that this object was created by adding "dd-MMM" and "hh:mm", and
+     * its datetimeFormat is the default "{0} {1}". Then if the input skeleton
+     * is "MMMdhmm", there is not an exact match, so the input skeleton is
+     * broken up into two components "MMMd" and "hmm". There are close matches
+     * for those two skeletons, so the result is put together with this pattern,
+     * resulting in "d-MMM h:mm".
+     *
+     * @param dateTimeFormat
+     *            message format pattern, here {0} will be replaced by the date
+     *            pattern and {1} will be replaced by the time pattern.
+     * @stable ICU 3.8
+     */
+    void setDateTimeFormat(const UnicodeString& dateTimeFormat);
+
+    /**
+     * Getter corresponding to setDateTimeFormat.
+     * @return DateTimeFormat.
+     * @stable ICU 3.8
+     */
+    const UnicodeString& getDateTimeFormat() const;
+
+    /**
+     * Return the best pattern matching the input skeleton. It is guaranteed to
+     * have all of the fields in the skeleton.
+     *
+     * @param skeleton
+     *            The skeleton is a pattern containing only the variable fields.
+     *            For example, "MMMdd" and "mmhh" are skeletons.
+     * @param status  Output param set to success/failure code on exit,
+     *               which must not indicate a failure before the function call.
+     * @return bestPattern
+     *            The best pattern found from the given skeleton.
+     * @stable ICU 3.8
+     */
+     UnicodeString getBestPattern(const UnicodeString& skeleton, UErrorCode& status);
+
+
+    /**
+     * Adjusts the field types (width and subtype) of a pattern to match what is
+     * in a skeleton. That is, if you supply a pattern like "d-M H:m", and a
+     * skeleton of "MMMMddhhmm", then the input pattern is adjusted to be
+     * "dd-MMMM hh:mm". This is used internally to get the best match for the
+     * input skeleton, but can also be used externally.
+     *
+     * @param pattern Input pattern
+     * @param skeleton
+     *            The skeleton is a pattern containing only the variable fields.
+     *            For example, "MMMdd" and "mmhh" are skeletons.
+     * @param status  Output param set to success/failure code on exit,
+     *               which must not indicate a failure before the function call.
+     * @return pattern adjusted to match the skeleton fields widths and subtypes.
+     * @stable ICU 3.8
+     */
+     UnicodeString replaceFieldTypes(const UnicodeString& pattern, 
+                                     const UnicodeString& skeleton, 
+                                     UErrorCode& status);
+
+    /**
+     * Return a list of all the skeletons (in canonical form) from this class.
+     *
+     * Call getPatternForSkeleton() to get the corresponding pattern.
+     *
+     * @param status  Output param set to success/failure code on exit,
+     *               which must not indicate a failure before the function call.
+     * @return StringEnumeration with the skeletons.
+     *         The caller must delete the object.
+     * @stable ICU 3.8
+     */
+     StringEnumeration* getSkeletons(UErrorCode& status) const;
+
+     /**
+      * Get the pattern corresponding to a given skeleton.
+      * @param skeleton 
+      * @return pattern corresponding to a given skeleton.
+      * @stable ICU 3.8
+      */
+     const UnicodeString& getPatternForSkeleton(const UnicodeString& skeleton) const;
+     
+    /**
+     * Return a list of all the base skeletons (in canonical form) from this class.
+     *
+     * @param status  Output param set to success/failure code on exit,
+     *               which must not indicate a failure before the function call.
+     * @return a StringEnumeration with the base skeletons.
+     *         The caller must delete the object.
+     * @stable ICU 3.8
+     */
+     StringEnumeration* getBaseSkeletons(UErrorCode& status) const;
+     
+     /**
+      * Return a list of redundant patterns are those which if removed, make no 
+      * difference in the resulting getBestPattern values. This method returns a 
+      * list of them, to help check the consistency of the patterns used to build 
+      * this generator.
+      * 
+      * @param status  Output param set to success/failure code on exit,
+      *               which must not indicate a failure before the function call.
+      * @return a StringEnumeration with the redundant pattern.
+      *         The caller must delete the object.
+      * @internal ICU 3.8
+      */
+     StringEnumeration* getRedundants(UErrorCode& status);
+      
+    /**
+     * The decimal value is used in formatting fractions of seconds. If the
+     * skeleton contains fractional seconds, then this is used with the
+     * fractional seconds. For example, suppose that the input pattern is
+     * "hhmmssSSSS", and the best matching pattern internally is "H:mm:ss", and
+     * the decimal string is ",". Then the resulting pattern is modified to be
+     * "H:mm:ss,SSSS"
+     *
+     * @param decimal 
+     * @stable ICU 3.8
+     */
+    void setDecimal(const UnicodeString& decimal);
+
+    /**
+     * Getter corresponding to setDecimal.
+     * @return UnicodeString corresponding to the decimal point
+     * @stable ICU 3.8
+     */
+    const UnicodeString& getDecimal() const;
+
+    /**
+     * ICU "poor man's RTTI", returns a UClassID for the actual class.
+     *
+     * @stable ICU 3.8
+     */
+    virtual UClassID getDynamicClassID() const;
+
+    /**
+     * ICU "poor man's RTTI", returns a UClassID for this class.
+     *
+     * @stable ICU 3.8
+     */
+    static UClassID U_EXPORT2 getStaticClassID(void);
+
+private:
+    /**
+     * Constructor.
+     * @stable ICU 3.8
+     */
+    DateTimePatternGenerator(UErrorCode & status);
+
+    /**
+     * Constructor.
+     * @stable ICU 3.8
+     */
+    DateTimePatternGenerator(const Locale& locale, UErrorCode & status);
+
+    /**
+     * Copy constructor.
+     * @param other DateTimePatternGenerator to copy
+     * @stable ICU 3.8
+     */
+    DateTimePatternGenerator(const DateTimePatternGenerator& other);
+
+    /**
+     * Default assignment operator.
+     * @param other DateTimePatternGenerator to copy
+     * @stable ICU 3.8
+     */
+    DateTimePatternGenerator& operator=(const DateTimePatternGenerator& other);
+
+    Locale pLocale;  // pattern locale
+    FormatParser *fp;
+    DateTimeMatcher* dtMatcher;
+    DistanceInfo *distanceInfo;
+    PatternMap *patternMap;
+    UnicodeString appendItemFormats[UDATPG_FIELD_COUNT];
+    UnicodeString appendItemNames[UDATPG_FIELD_COUNT];
+    UnicodeString dateTimeFormat;
+    UnicodeString decimal;
+    DateTimeMatcher *skipMatcher;
+    Hashtable *fAvailableFormatKeyHash;
+    UnicodeString hackPattern;
+    UnicodeString emptyString;
+    UChar fDefaultHourFormatChar;
+
+    void initData(const Locale &locale, UErrorCode &status);
+    void addCanonicalItems();
+    void addICUPatterns(const Locale& locale, UErrorCode& status);
+    void hackTimes(const UnicodeString& hackPattern, UErrorCode& status);
+    void addCLDRData(const Locale& locale);
+    UDateTimePatternConflict addPatternWithSkeleton(const UnicodeString& pattern, const UnicodeString * skeletonToUse, UBool override, UnicodeString& conflictingPattern, UErrorCode& status);
+    void initHashtable(UErrorCode& status);
+    void setDateTimeFromCalendar(const Locale& locale, UErrorCode& status);
+    void setDecimalSymbols(const Locale& locale, UErrorCode& status);
+    UDateTimePatternField getAppendFormatNumber(const char* field) const;
+    UDateTimePatternField getAppendNameNumber(const char* field) const;
+    void getAppendName(UDateTimePatternField field, UnicodeString& value);
+    int32_t getCanonicalIndex(const UnicodeString& field);
+    const UnicodeString* getBestRaw(DateTimeMatcher& source, int32_t includeMask, DistanceInfo* missingFields, const PtnSkeleton** specifiedSkeletonPtr = 0);
+    UnicodeString adjustFieldTypes(const UnicodeString& pattern, const PtnSkeleton* specifiedSkeleton, UBool fixFractionalSeconds);
+    UnicodeString getBestAppending(int32_t missingFields);
+    int32_t getTopBitNumber(int32_t foundMask);
+    void setAvailableFormat(const UnicodeString &key, UErrorCode& status);
+    UBool isAvailableFormatSet(const UnicodeString &key) const;
+    void copyHashtable(Hashtable *other, UErrorCode &status);
+    UBool isCanonicalItem(const UnicodeString& item) const;
+} ;// end class DateTimePatternGenerator
+
+U_NAMESPACE_END
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/dtrule.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/dtrule.h b/src/apps/couch_collate/platform/osx/icu/unicode/dtrule.h
new file mode 100644
index 0000000..c46e618
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/dtrule.h
@@ -0,0 +1,250 @@
+/*
+*******************************************************************************
+* Copyright (C) 2007-2008, International Business Machines Corporation and         *
+* others. All Rights Reserved.                                                *
+*******************************************************************************
+*/
+#ifndef DTRULE_H
+#define DTRULE_H
+
+#include "unicode/utypes.h"
+
+/**
+ * \file 
+ * \brief C++ API: Rule for specifying date and time in an year
+ */
+
+#if !UCONFIG_NO_FORMATTING
+
+#include "unicode/uobject.h"
+
+U_NAMESPACE_BEGIN
+/**
+ * <code>DateTimeRule</code> is a class representing a time in a year by
+ * a rule specified by month, day of month, day of week and
+ * time in the day.
+ * 
+ * @stable ICU 4.0
+ */
+class U_I18N_API DateTimeRule : public UObject {
+public:
+
+    /**
+     * Date rule type constants.
+     * @stable ICU 4.0
+     */
+    enum DateRuleType {
+        DOM = 0,        /**< The exact day of month,
+                             for example, March 11. */
+        DOW,            /**< The Nth occurence of the day of week,
+                             for example, 2nd Sunday in March. */
+        DOW_GEQ_DOM,    /**< The first occurence of the day of week on or after the day of monnth,
+                             for example, first Sunday on or after March 8. */
+        DOW_LEQ_DOM     /**< The last occurence of the day of week on or before the day of month,
+                             for example, first Sunday on or before March 14. */
+    };
+
+    /**
+     * Time rule type constants.
+     * @stable ICU 4.0
+     */
+    enum TimeRuleType {
+        WALL_TIME = 0,  /**< The local wall clock time */
+        STANDARD_TIME,  /**< The local standard time */
+        UTC_TIME        /**< The UTC time */
+    };
+
+    /**
+     * Constructs a <code>DateTimeRule</code> by the day of month and
+     * the time rule.  The date rule type for an instance created by
+     * this constructor is <code>DOM</code>.
+     * 
+     * @param month         The rule month, for example, <code>Calendar::JANUARY</code>
+     * @param dayOfMonth    The day of month, 1-based.
+     * @param millisInDay   The milliseconds in the rule date.
+     * @param timeType      The time type, <code>WALL_TIME</code> or <code>STANDARD_TIME</code>
+     *                      or <code>UTC_TIME</code>.
+     * @stable ICU 4.0
+     */
+    DateTimeRule(int32_t month, int32_t dayOfMonth,
+        int32_t millisInDay, TimeRuleType timeType);
+
+    /**
+     * Constructs a <code>DateTimeRule</code> by the day of week and its oridinal
+     * number and the time rule.  The date rule type for an instance created
+     * by this constructor is <code>DOW</code>.
+     * 
+     * @param month         The rule month, for example, <code>Calendar::JANUARY</code>.
+     * @param weekInMonth   The ordinal number of the day of week.  Negative number
+     *                      may be used for specifying a rule date counted from the
+     *                      end of the rule month.
+     * @param dayOfWeek     The day of week, for example, <code>Calendar::SUNDAY</code>.
+     * @param millisInDay   The milliseconds in the rule date.
+     * @param timeType      The time type, <code>WALL_TIME</code> or <code>STANDARD_TIME</code>
+     *                      or <code>UTC_TIME</code>.
+     * @stable ICU 4.0
+     */
+    DateTimeRule(int32_t month, int32_t weekInMonth, int32_t dayOfWeek,
+        int32_t millisInDay, TimeRuleType timeType);
+
+    /**
+     * Constructs a <code>DateTimeRule</code> by the first/last day of week
+     * on or after/before the day of month and the time rule.  The date rule
+     * type for an instance created by this constructor is either
+     * <code>DOM_GEQ_DOM</code> or <code>DOM_LEQ_DOM</code>.
+     * 
+     * @param month         The rule month, for example, <code>Calendar::JANUARY</code>
+     * @param dayOfMonth    The day of month, 1-based.
+     * @param dayOfWeek     The day of week, for example, <code>Calendar::SUNDAY</code>.
+     * @param after         true if the rule date is on or after the day of month.
+     * @param millisInDay   The milliseconds in the rule date.
+     * @param timeType      The time type, <code>WALL_TIME</code> or <code>STANDARD_TIME</code>
+     *                      or <code>UTC_TIME</code>.
+     * @stable ICU 4.0
+     */
+    DateTimeRule(int32_t month, int32_t dayOfMonth, int32_t dayOfWeek, UBool after,
+        int32_t millisInDay, TimeRuleType timeType);
+
+    /**
+     * Copy constructor.
+     * @param source    The DateTimeRule object to be copied.
+     * @stable ICU 4.0
+     */
+    DateTimeRule(const DateTimeRule& source);
+
+    /**
+     * Destructor.
+     * @stable ICU 4.0
+     */
+    ~DateTimeRule();
+
+    /**
+     * Clone this DateTimeRule object polymorphically. The caller owns the result and
+     * should delete it when done.
+     * @return    A copy of the object.
+     * @stable ICU 4.0
+     */
+    DateTimeRule* clone(void) const;
+
+    /**
+     * Assignment operator.
+     * @param right The object to be copied.
+     * @stable ICU 4.0
+     */
+    DateTimeRule& operator=(const DateTimeRule& right);
+
+    /**
+     * Return true if the given DateTimeRule objects are semantically equal. Objects
+     * of different subclasses are considered unequal.
+     * @param that  The object to be compared with.
+     * @return  true if the given DateTimeRule objects are semantically equal.
+     * @stable ICU 4.0
+     */
+    UBool operator==(const DateTimeRule& that) const;
+
+    /**
+     * Return true if the given DateTimeRule objects are semantically unequal. Objects
+     * of different subclasses are considered unequal.
+     * @param that  The object to be compared with.
+     * @return  true if the given DateTimeRule objects are semantically unequal.
+     * @stable ICU 4.0
+     */
+    UBool operator!=(const DateTimeRule& that) const;
+
+    /**
+     * Gets the date rule type, such as <code>DOM</code>
+     * @return The date rule type.
+     * @stable ICU 4.0
+     */
+    DateRuleType getDateRuleType(void) const;
+
+    /**
+     * Gets the time rule type
+     * @return The time rule type, either <code>WALL_TIME</code> or <code>STANDARD_TIME</code>
+     *         or <code>UTC_TIME</code>.
+     * @stable ICU 4.0
+     */
+    TimeRuleType getTimeRuleType(void) const;
+
+    /**
+     * Gets the rule month.
+     * @return The rule month.
+     * @stable ICU 4.0
+     */
+    int32_t getRuleMonth(void) const;
+
+    /**
+     * Gets the rule day of month.  When the date rule type
+     * is <code>DOW</code>, the value is always 0.
+     * @return The rule day of month
+     * @stable ICU 4.0
+     */
+    int32_t getRuleDayOfMonth(void) const;
+
+    /**
+     * Gets the rule day of week.  When the date rule type
+     * is <code>DOM</code>, the value is always 0.
+     * @return The rule day of week.
+     * @stable ICU 4.0
+     */
+    int32_t getRuleDayOfWeek(void) const;
+
+    /**
+     * Gets the ordinal number of the occurence of the day of week
+     * in the month.  When the date rule type is not <code>DOW</code>,
+     * the value is always 0.
+     * @return The rule day of week ordinal number in the month.
+     * @stable ICU 4.0
+     */
+    int32_t getRuleWeekInMonth(void) const;
+
+    /**
+     * Gets the rule time in the rule day.
+     * @return The time in the rule day in milliseconds.
+     * @stable ICU 4.0
+     */
+    int32_t getRuleMillisInDay(void) const;
+
+private:
+    int32_t fMonth;
+    int32_t fDayOfMonth;
+    int32_t fDayOfWeek;
+    int32_t fWeekInMonth;
+    int32_t fMillisInDay;
+    DateRuleType fDateRuleType;
+    TimeRuleType fTimeRuleType;
+
+public:
+    /**
+     * Return the class ID for this class. This is useful only for comparing to
+     * a return value from getDynamicClassID(). For example:
+     * <pre>
+     * .   Base* polymorphic_pointer = createPolymorphicObject();
+     * .   if (polymorphic_pointer->getDynamicClassID() ==
+     * .       erived::getStaticClassID()) ...
+     * </pre>
+     * @return          The class ID for all objects of this class.
+     * @stable ICU 4.0
+     */
+    static UClassID U_EXPORT2 getStaticClassID(void);
+
+    /**
+     * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This
+     * method is to implement a simple version of RTTI, since not all C++
+     * compilers support genuine RTTI. Polymorphic operator==() and clone()
+     * methods call this method.
+     *
+     * @return          The class ID for this object. All objects of a
+     *                  given class have the same class ID.  Objects of
+     *                  other classes have different class IDs.
+     * @stable ICU 4.0
+     */
+    virtual UClassID getDynamicClassID(void) const;
+};
+
+U_NAMESPACE_END
+
+#endif /* #if !UCONFIG_NO_FORMATTING */
+
+#endif // DTRULE_H
+//eof

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/fieldpos.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/fieldpos.h b/src/apps/couch_collate/platform/osx/icu/unicode/fieldpos.h
new file mode 100644
index 0000000..38a9576
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/fieldpos.h
@@ -0,0 +1,291 @@
+/*
+ ********************************************************************************
+ *   Copyright (C) 1997-2006, International Business Machines
+ *   Corporation and others.  All Rights Reserved.
+ ********************************************************************************
+ *
+ * File FIELDPOS.H
+ *
+ * Modification History:
+ *
+ *   Date        Name        Description
+ *   02/25/97    aliu        Converted from java.
+ *   03/17/97    clhuang     Updated per Format implementation.
+ *    07/17/98    stephen        Added default/copy ctors, and operators =, ==, !=
+ ********************************************************************************
+ */
+
+// *****************************************************************************
+// This file was generated from the java source file FieldPosition.java
+// *****************************************************************************
+ 
+#ifndef FIELDPOS_H
+#define FIELDPOS_H
+
+#include "unicode/utypes.h"
+
+/**
+ * \file 
+ * \brief C++ API: FieldPosition identifies the fields in a formatted output.
+ */
+
+#if !UCONFIG_NO_FORMATTING
+
+#include "unicode/uobject.h"
+
+U_NAMESPACE_BEGIN
+
+/**
+ * <code>FieldPosition</code> is a simple class used by <code>Format</code>
+ * and its subclasses to identify fields in formatted output. Fields are
+ * identified by constants, whose names typically end with <code>_FIELD</code>,
+ * defined in the various subclasses of <code>Format</code>. See
+ * <code>ERA_FIELD</code> and its friends in <code>DateFormat</code> for
+ * an example.
+ *
+ * <p>
+ * <code>FieldPosition</code> keeps track of the position of the
+ * field within the formatted output with two indices: the index
+ * of the first character of the field and the index of the last
+ * character of the field.
+ *
+ * <p>
+ * One version of the <code>format</code> method in the various
+ * <code>Format</code> classes requires a <code>FieldPosition</code>
+ * object as an argument. You use this <code>format</code> method
+ * to perform partial formatting or to get information about the
+ * formatted output (such as the position of a field).
+ *
+ * The FieldPosition class is not suitable for subclassing.
+ *
+ * <p>
+ * Below is an example of using <code>FieldPosition</code> to aid
+ * alignment of an array of formatted floating-point numbers on
+ * their decimal points:
+ * <pre>
+ * \code
+ *       double doubleNum[] = {123456789.0, -12345678.9, 1234567.89, -123456.789,
+ *                  12345.6789, -1234.56789, 123.456789, -12.3456789, 1.23456789};
+ *       int dNumSize = (int)(sizeof(doubleNum)/sizeof(double));
+ *       
+ *       UErrorCode status = U_ZERO_ERROR;
+ *       DecimalFormat* fmt = (DecimalFormat*) NumberFormat::createInstance(status);
+ *       fmt->setDecimalSeparatorAlwaysShown(true);
+ *       
+ *       const int tempLen = 20;
+ *       char temp[tempLen];
+ *       
+ *       for (int i=0; i<dNumSize; i++) {
+ *           FieldPosition pos(NumberFormat::INTEGER_FIELD);
+ *           UnicodeString buf;
+ *           char fmtText[tempLen];
+ *           ToCharString(fmt->format(doubleNum[i], buf, pos), fmtText);
+ *           for (int j=0; j<tempLen; j++) temp[j] = ' '; // clear with spaces
+ *           temp[__min(tempLen, tempLen-pos.getEndIndex())] = '\0';
+ *           cout << temp << fmtText   << endl;
+ *       }
+ *       delete fmt;
+ * \endcode
+ * </pre>
+ * <p>
+ * The code will generate the following output:
+ * <pre>
+ * \code
+ *           123,456,789.000
+ *           -12,345,678.900
+ *             1,234,567.880
+ *              -123,456.789
+ *                12,345.678
+ *                -1,234.567
+ *                   123.456
+ *                   -12.345
+ *                     1.234
+ *  \endcode
+ * </pre>
+ */
+class U_I18N_API FieldPosition : public UObject {
+public:
+    /**
+     * DONT_CARE may be specified as the field to indicate that the
+     * caller doesn't need to specify a field.  Do not subclass.
+     */
+    enum { DONT_CARE = -1 };
+
+    /**
+     * Creates a FieldPosition object with a non-specified field.
+     * @stable ICU 2.0
+     */
+    FieldPosition() 
+        : UObject(), fField(DONT_CARE), fBeginIndex(0), fEndIndex(0) {}
+
+    /**
+     * Creates a FieldPosition object for the given field.  Fields are
+     * identified by constants, whose names typically end with _FIELD,
+     * in the various subclasses of Format.
+     *
+     * @see NumberFormat#INTEGER_FIELD
+     * @see NumberFormat#FRACTION_FIELD
+     * @see DateFormat#YEAR_FIELD
+     * @see DateFormat#MONTH_FIELD
+     * @stable ICU 2.0
+     */
+    FieldPosition(int32_t field) 
+        : UObject(), fField(field), fBeginIndex(0), fEndIndex(0) {}
+
+    /**
+     * Copy constructor
+     * @param copy the object to be copied from.
+     * @stable ICU 2.0
+     */
+    FieldPosition(const FieldPosition& copy) 
+        : UObject(copy), fField(copy.fField), fBeginIndex(copy.fBeginIndex), fEndIndex(copy.fEndIndex) {}
+
+    /**
+     * Destructor
+     * @stable ICU 2.0
+     */
+    virtual ~FieldPosition();
+
+    /**
+     * Assignment operator
+     * @param copy the object to be copied from.
+     * @stable ICU 2.0
+     */
+    FieldPosition&      operator=(const FieldPosition& copy);
+
+    /** 
+     * Equality operator.
+     * @param that    the object to be compared with.
+     * @return        TRUE if the two field positions are equal, FALSE otherwise.
+     * @stable ICU 2.0
+     */
+    UBool              operator==(const FieldPosition& that) const;
+
+    /** 
+     * Equality operator.
+     * @param that    the object to be compared with.
+     * @return        TRUE if the two field positions are not equal, FALSE otherwise.
+     * @stable ICU 2.0
+     */
+    UBool              operator!=(const FieldPosition& that) const;
+
+    /**
+     * Clone this object.
+     * Clones can be used concurrently in multiple threads.
+     * If an error occurs, then NULL is returned.
+     * The caller must delete the clone.
+     *
+     * @return a clone of this object
+     *
+     * @see getDynamicClassID
+     * @stable ICU 2.8
+     */
+    FieldPosition *clone() const;
+
+    /**
+     * Retrieve the field identifier.
+     * @return    the field identifier.
+     * @stable ICU 2.0
+     */
+    int32_t getField(void) const { return fField; }
+
+    /**
+     * Retrieve the index of the first character in the requested field.
+     * @return    the index of the first character in the requested field.
+     * @stable ICU 2.0
+     */
+    int32_t getBeginIndex(void) const { return fBeginIndex; }
+
+    /**
+     * Retrieve the index of the character following the last character in the
+     * requested field.
+     * @return    the index of the character following the last character in the
+     *            requested field.
+     * @stable ICU 2.0
+     */
+    int32_t getEndIndex(void) const { return fEndIndex; }
+ 
+    /**
+     * Set the field.
+     * @param f    the new value of the field.
+     * @stable ICU 2.0
+     */
+    void setField(int32_t f) { fField = f; }
+
+    /**
+     * Set the begin index.  For use by subclasses of Format.
+     * @param bi    the new value of the begin index
+     * @stable ICU 2.0
+     */
+    void setBeginIndex(int32_t bi) { fBeginIndex = bi; }
+
+    /**
+     * Set the end index.  For use by subclasses of Format.
+     * @param ei    the new value of the end index
+     * @stable ICU 2.0
+     */
+    void setEndIndex(int32_t ei) { fEndIndex = ei; }
+    
+    /**
+     * ICU "poor man's RTTI", returns a UClassID for the actual class.
+     *
+     * @stable ICU 2.2
+     */
+    virtual UClassID getDynamicClassID() const;
+
+    /**
+     * ICU "poor man's RTTI", returns a UClassID for this class.
+     *
+     * @stable ICU 2.2
+     */
+    static UClassID U_EXPORT2 getStaticClassID();
+
+private:
+    /**
+     * Input: Desired field to determine start and end offsets for.
+     * The meaning depends on the subclass of Format.
+     */
+    int32_t fField;
+
+    /**
+     * Output: Start offset of field in text.
+     * If the field does not occur in the text, 0 is returned.
+     */
+    int32_t fBeginIndex;
+
+    /**
+     * Output: End offset of field in text.
+     * If the field does not occur in the text, 0 is returned.
+     */
+    int32_t fEndIndex;
+};
+
+inline FieldPosition&
+FieldPosition::operator=(const FieldPosition& copy)
+{
+    fField         = copy.fField;
+    fEndIndex     = copy.fEndIndex;
+    fBeginIndex = copy.fBeginIndex;
+    return *this;
+}
+
+inline UBool
+FieldPosition::operator==(const FieldPosition& copy) const
+{
+    return (fField == copy.fField &&
+        fEndIndex == copy.fEndIndex &&
+        fBeginIndex == copy.fBeginIndex);
+}
+
+inline UBool
+FieldPosition::operator!=(const FieldPosition& copy) const
+{
+    return !operator==(copy);
+}
+
+U_NAMESPACE_END
+
+#endif /* #if !UCONFIG_NO_FORMATTING */
+
+#endif // _FIELDPOS
+//eof

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/fmtable.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/fmtable.h b/src/apps/couch_collate/platform/osx/icu/unicode/fmtable.h
new file mode 100644
index 0000000..94ee328
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/fmtable.h
@@ -0,0 +1,591 @@
+/*
+********************************************************************************
+*   Copyright (C) 1997-2006, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+********************************************************************************
+*
+* File FMTABLE.H
+*
+* Modification History:
+*
+*   Date        Name        Description
+*   02/29/97    aliu        Creation.
+********************************************************************************
+*/
+#ifndef FMTABLE_H
+#define FMTABLE_H
+
+#include "unicode/utypes.h"
+#include "unicode/unistr.h"
+/**
+ * \file 
+ * \brief C++ API: Formattable is a thin wrapper for primitive numeric types.
+ */
+
+#if !UCONFIG_NO_FORMATTING
+
+U_NAMESPACE_BEGIN
+
+/**
+ * Formattable objects can be passed to the Format class or
+ * its subclasses for formatting.  Formattable is a thin wrapper
+ * class which interconverts between the primitive numeric types
+ * (double, long, etc.) as well as UDate and UnicodeString.
+ *
+ * <p>Internally, a Formattable object is a union of primitive types.
+ * As such, it can only store one flavor of data at a time.  To
+ * determine what flavor of data it contains, use the getType method.
+ *
+ * <p>As of ICU 3.0, Formattable may also wrap a UObject pointer,
+ * which it owns.  This allows an instance of any ICU class to be
+ * encapsulated in a Formattable.  For legacy reasons and for
+ * efficiency, primitive numeric types are still stored directly
+ * within a Formattable.
+ *
+ * <p>The Formattable class is not suitable for subclassing.
+ */
+class U_I18N_API Formattable : public UObject {
+public:
+    /**
+     * This enum is only used to let callers distinguish between
+     * the Formattable(UDate) constructor and the Formattable(double)
+     * constructor; the compiler cannot distinguish the signatures,
+     * since UDate is currently typedefed to be either double or long.
+     * If UDate is changed later to be a bonafide class
+     * or struct, then we no longer need this enum.
+     * @stable ICU 2.4
+     */
+    enum ISDATE { kIsDate };
+
+    /**
+     * Default constructor
+     * @stable ICU 2.4
+     */
+    Formattable(); // Type kLong, value 0
+
+    /**
+     * Creates a Formattable object with a UDate instance.
+     * @param d the UDate instance.
+     * @param flag the flag to indicate this is a date. Always set it to kIsDate
+     * @stable ICU 2.0  
+     */
+    Formattable(UDate d, ISDATE flag);
+
+    /**
+     * Creates a Formattable object with a double number.
+     * @param d the double number.
+     * @stable ICU 2.0
+     */
+    Formattable(double d);
+
+    /**
+     * Creates a Formattable object with a long number.
+     * @param l the long number.
+     * @stable ICU 2.0
+     */
+    Formattable(int32_t l);
+
+    /**
+     * Creates a Formattable object with an int64_t number
+     * @param ll the int64_t number.
+     * @stable ICU 2.8
+     */
+    Formattable(int64_t ll);
+
+#if !UCONFIG_NO_CONVERSION
+    /**
+     * Creates a Formattable object with a char string pointer.
+     * Assumes that the char string is null terminated.
+     * @param strToCopy the char string.
+     * @stable ICU 2.0
+     */
+    Formattable(const char* strToCopy);
+#endif
+
+    /**
+     * Creates a Formattable object with a UnicodeString object to copy from.
+     * @param strToCopy the UnicodeString string.
+     * @stable ICU 2.0
+     */
+    Formattable(const UnicodeString& strToCopy);
+
+    /**
+     * Creates a Formattable object with a UnicodeString object to adopt from.
+     * @param strToAdopt the UnicodeString string.
+     * @stable ICU 2.0
+     */
+    Formattable(UnicodeString* strToAdopt);
+
+    /**
+     * Creates a Formattable object with an array of Formattable objects.
+     * @param arrayToCopy the Formattable object array.
+     * @param count the array count.
+     * @stable ICU 2.0
+     */
+    Formattable(const Formattable* arrayToCopy, int32_t count);
+
+    /**
+     * Creates a Formattable object that adopts the given UObject.
+     * @param objectToAdopt the UObject to set this object to
+     * @stable ICU 3.0
+     */
+    Formattable(UObject* objectToAdopt);
+
+    /**
+     * Copy constructor.
+     * @stable ICU 2.0
+     */
+    Formattable(const Formattable&);
+
+    /**
+     * Assignment operator.
+     * @param rhs   The Formattable object to copy into this object.
+     * @stable ICU 2.0
+     */
+    Formattable&    operator=(const Formattable &rhs);
+
+    /**
+     * Equality comparison.
+     * @param other    the object to be compared with.
+     * @return        TRUE if other are equal to this, FALSE otherwise.
+     * @stable ICU 2.0
+     */
+    UBool          operator==(const Formattable &other) const;
+    
+    /** 
+     * Equality operator.
+     * @param other    the object to be compared with.
+     * @return        TRUE if other are unequal to this, FALSE otherwise.
+     * @stable ICU 2.0
+     */
+    UBool          operator!=(const Formattable& other) const
+      { return !operator==(other); }
+
+    /** 
+     * Destructor.
+     * @stable ICU 2.0
+     */
+    virtual         ~Formattable();
+
+    /**
+     * Clone this object.
+     * Clones can be used concurrently in multiple threads.
+     * If an error occurs, then NULL is returned.
+     * The caller must delete the clone.
+     *
+     * @return a clone of this object
+     *
+     * @see getDynamicClassID
+     * @stable ICU 2.8
+     */
+    Formattable *clone() const;
+
+    /** 
+     * Selector for flavor of data type contained within a
+     * Formattable object.  Formattable is a union of several
+     * different types, and at any time contains exactly one type.
+     * @stable ICU 2.4
+     */
+    enum Type {
+        /**
+         * Selector indicating a UDate value.  Use getDate to retrieve
+         * the value.
+         * @stable ICU 2.4
+         */
+        kDate,
+
+        /**
+         * Selector indicating a double value.  Use getDouble to
+         * retrieve the value.
+         * @stable ICU 2.4
+         */
+        kDouble,
+
+        /**
+         * Selector indicating a 32-bit integer value.  Use getLong to
+         * retrieve the value.
+         * @stable ICU 2.4
+         */
+        kLong,
+
+        /**
+         * Selector indicating a UnicodeString value.  Use getString
+         * to retrieve the value.
+         * @stable ICU 2.4
+         */
+        kString,
+
+        /**
+         * Selector indicating an array of Formattables.  Use getArray
+         * to retrieve the value.
+         * @stable ICU 2.4
+         */
+        kArray,
+
+        /**
+         * Selector indicating a 64-bit integer value.  Use getInt64
+         * to retrieve the value.
+         * @stable ICU 2.8
+         */
+        kInt64,
+
+        /**
+         * Selector indicating a UObject value.  Use getObject to
+         * retrieve the value.
+         * @stable ICU 3.0
+         */
+        kObject
+   };
+
+    /**
+     * Gets the data type of this Formattable object.
+     * @return    the data type of this Formattable object.
+     * @stable ICU 2.0
+     */
+    Type            getType(void) const;
+    
+    /**
+     * Returns TRUE if the data type of this Formattable object
+     * is kDouble, kLong, or kInt64.
+     * @return TRUE if this is a pure numeric object
+     * @stable ICU 3.0
+     */
+    UBool           isNumeric() const;
+    
+    /**
+     * Gets the double value of this object. If this object is not of type
+     * kDouble then the result is undefined.
+     * @return    the double value of this object.
+     * @stable ICU 2.0
+     */ 
+    double          getDouble(void) const { return fValue.fDouble; }
+
+    /**
+     * Gets the double value of this object. If this object is of type
+     * long or int64 then a casting conversion is peformed, with
+     * possible loss of precision.  If the type is kObject and the
+     * object is a Measure, then the result of
+     * getNumber().getDouble(status) is returned.  If this object is
+     * neither a numeric type nor a Measure, then 0 is returned and
+     * the status is set to U_INVALID_FORMAT_ERROR.
+     * @param status the error code
+     * @return the double value of this object.
+     * @stable ICU 3.0
+     */ 
+    double          getDouble(UErrorCode& status) const;
+
+    /**
+     * Gets the long value of this object. If this object is not of type
+     * kLong then the result is undefined.
+     * @return    the long value of this object.
+     * @stable ICU 2.0
+     */ 
+    int32_t         getLong(void) const { return (int32_t)fValue.fInt64; }
+
+    /**
+     * Gets the long value of this object. If the magnitude is too
+     * large to fit in a long, then the maximum or minimum long value,
+     * as appropriate, is returned and the status is set to
+     * U_INVALID_FORMAT_ERROR.  If this object is of type kInt64 and
+     * it fits within a long, then no precision is lost.  If it is of
+     * type kDouble, then a casting conversion is peformed, with
+     * truncation of any fractional part.  If the type is kObject and
+     * the object is a Measure, then the result of
+     * getNumber().getLong(status) is returned.  If this object is
+     * neither a numeric type nor a Measure, then 0 is returned and
+     * the status is set to U_INVALID_FORMAT_ERROR.
+     * @param status the error code
+     * @return    the long value of this object.
+     * @stable ICU 3.0
+     */ 
+    int32_t         getLong(UErrorCode& status) const;
+
+    /**
+     * Gets the int64 value of this object. If this object is not of type
+     * kInt64 then the result is undefined.
+     * @return    the int64 value of this object.
+     * @stable ICU 2.8
+     */ 
+    int64_t         getInt64(void) const { return fValue.fInt64; }
+
+    /**
+     * Gets the int64 value of this object. If this object is of type
+     * kDouble and the magnitude is too large to fit in an int64, then
+     * the maximum or minimum int64 value, as appropriate, is returned
+     * and the status is set to U_INVALID_FORMAT_ERROR.  If the
+     * magnitude fits in an int64, then a casting conversion is
+     * peformed, with truncation of any fractional part.  If the type
+     * is kObject and the object is a Measure, then the result of
+     * getNumber().getDouble(status) is returned.  If this object is
+     * neither a numeric type nor a Measure, then 0 is returned and
+     * the status is set to U_INVALID_FORMAT_ERROR.
+     * @param status the error code
+     * @return    the int64 value of this object.
+     * @stable ICU 3.0
+     */ 
+    int64_t         getInt64(UErrorCode& status) const;
+
+    /**
+     * Gets the Date value of this object. If this object is not of type
+     * kDate then the result is undefined.
+     * @return    the Date value of this object.
+     * @stable ICU 2.0
+     */ 
+    UDate           getDate() const { return fValue.fDate; }
+
+    /**
+     * Gets the Date value of this object.  If the type is not a date,
+     * status is set to U_INVALID_FORMAT_ERROR and the return value is
+     * undefined.
+     * @param status the error code.
+     * @return    the Date value of this object.
+     * @stable ICU 3.0
+     */ 
+     UDate          getDate(UErrorCode& status) const;
+
+    /**
+     * Gets the string value of this object. If this object is not of type
+     * kString then the result is undefined.
+     * @param result    Output param to receive the Date value of this object.
+     * @return          A reference to 'result'.
+     * @stable ICU 2.0
+     */ 
+    UnicodeString&  getString(UnicodeString& result) const
+      { result=*fValue.fString; return result; }
+
+    /**
+     * Gets the string value of this object. If the type is not a
+     * string, status is set to U_INVALID_FORMAT_ERROR and a bogus
+     * string is returned.
+     * @param result    Output param to receive the Date value of this object.
+     * @param status    the error code. 
+     * @return          A reference to 'result'.
+     * @stable ICU 3.0
+     */ 
+    UnicodeString&  getString(UnicodeString& result, UErrorCode& status) const;
+
+    /**
+     * Gets a const reference to the string value of this object. If
+     * this object is not of type kString then the result is
+     * undefined.
+     * @return   a const reference to the string value of this object.
+     * @stable ICU 2.0
+     */
+    inline const UnicodeString& getString(void) const;
+
+    /**
+     * Gets a const reference to the string value of this object.  If
+     * the type is not a string, status is set to
+     * U_INVALID_FORMAT_ERROR and the result is a bogus string.
+     * @param status    the error code.
+     * @return   a const reference to the string value of this object.
+     * @stable ICU 3.0
+     */
+    const UnicodeString& getString(UErrorCode& status) const;
+
+    /**
+     * Gets a reference to the string value of this object. If this
+     * object is not of type kString then the result is undefined.
+     * @return   a reference to the string value of this object.
+     * @stable ICU 2.0
+     */
+    inline UnicodeString& getString(void);
+
+    /**
+     * Gets a reference to the string value of this object. If the
+     * type is not a string, status is set to U_INVALID_FORMAT_ERROR
+     * and the result is a bogus string.
+     * @param status    the error code. 
+     * @return   a reference to the string value of this object.
+     * @stable ICU 3.0
+     */
+    UnicodeString& getString(UErrorCode& status);
+
+    /**
+     * Gets the array value and count of this object. If this object
+     * is not of type kArray then the result is undefined.
+     * @param count    fill-in with the count of this object.
+     * @return         the array value of this object.
+     * @stable ICU 2.0
+     */ 
+    const Formattable* getArray(int32_t& count) const
+      { count=fValue.fArrayAndCount.fCount; return fValue.fArrayAndCount.fArray; }
+
+    /**
+     * Gets the array value and count of this object. If the type is
+     * not an array, status is set to U_INVALID_FORMAT_ERROR, count is
+     * set to 0, and the result is NULL.
+     * @param count    fill-in with the count of this object.
+     * @param status the error code. 
+     * @return         the array value of this object.
+     * @stable ICU 3.0
+     */ 
+    const Formattable* getArray(int32_t& count, UErrorCode& status) const;
+
+    /**
+     * Accesses the specified element in the array value of this
+     * Formattable object. If this object is not of type kArray then
+     * the result is undefined.
+     * @param index the specified index.
+     * @return the accessed element in the array.
+     * @stable ICU 2.0
+     */
+    Formattable&    operator[](int32_t index) { return fValue.fArrayAndCount.fArray[index]; }
+       
+    /**
+     * Returns a pointer to the UObject contained within this
+     * formattable, or NULL if this object does not contain a UObject.
+     * @return a UObject pointer, or NULL
+     * @stable ICU 3.0
+     */
+    const UObject*  getObject() const;
+
+    /**
+     * Sets the double value of this object and changes the type to
+     * kDouble.
+     * @param d    the new double value to be set.
+     * @stable ICU 2.0
+     */ 
+    void            setDouble(double d);
+
+    /**
+     * Sets the long value of this object and changes the type to
+     * kLong.
+     * @param l    the new long value to be set.
+     * @stable ICU 2.0
+     */ 
+    void            setLong(int32_t l);
+
+    /**
+     * Sets the int64 value of this object and changes the type to
+     * kInt64.
+     * @param ll    the new int64 value to be set.
+     * @stable ICU 2.8
+     */ 
+    void            setInt64(int64_t ll);
+
+    /**
+     * Sets the Date value of this object and changes the type to
+     * kDate.
+     * @param d    the new Date value to be set.
+     * @stable ICU 2.0
+     */ 
+    void            setDate(UDate d);
+
+    /**
+     * Sets the string value of this object and changes the type to
+     * kString.
+     * @param stringToCopy    the new string value to be set.
+     * @stable ICU 2.0
+     */ 
+    void            setString(const UnicodeString& stringToCopy);
+
+    /**
+     * Sets the array value and count of this object and changes the
+     * type to kArray.
+     * @param array    the array value.
+     * @param count    the number of array elements to be copied.
+     * @stable ICU 2.0
+     */ 
+    void            setArray(const Formattable* array, int32_t count);
+
+    /**
+     * Sets and adopts the string value and count of this object and
+     * changes the type to kArray.
+     * @param stringToAdopt    the new string value to be adopted.
+     * @stable ICU 2.0
+     */ 
+    void            adoptString(UnicodeString* stringToAdopt);
+
+    /**
+     * Sets and adopts the array value and count of this object and
+     * changes the type to kArray.
+     * @stable ICU 2.0
+     */ 
+    void            adoptArray(Formattable* array, int32_t count);
+       
+    /**
+     * Sets and adopts the UObject value of this object and changes
+     * the type to kObject.  After this call, the caller must not
+     * delete the given object.
+     * @param objectToAdopt the UObject value to be adopted
+     * @stable ICU 3.0
+     */
+    void            adoptObject(UObject* objectToAdopt);
+
+    /**
+     * ICU "poor man's RTTI", returns a UClassID for the actual class.
+     *
+     * @stable ICU 2.2
+     */
+    virtual UClassID getDynamicClassID() const;
+
+    /**
+     * ICU "poor man's RTTI", returns a UClassID for this class.
+     *
+     * @stable ICU 2.2
+     */
+    static UClassID U_EXPORT2 getStaticClassID();
+
+    /**
+     * Deprecated variant of getLong(UErrorCode&).
+     * @param status the error code
+     * @return the long value of this object.
+     * @deprecated ICU 3.0 use getLong(UErrorCode&) instead
+     */ 
+    inline int32_t getLong(UErrorCode* status) const;
+
+private:
+    /**
+     * Cleans up the memory for unwanted values.  For example, the adopted
+     * string or array objects.
+     */
+    void            dispose(void);
+
+    UnicodeString* getBogus() const;
+
+    union {
+        UObject*        fObject;
+        UnicodeString*  fString;
+        double          fDouble;
+        int64_t         fInt64;
+        UDate           fDate;
+        struct {
+          Formattable*  fArray;
+          int32_t       fCount;
+        }               fArrayAndCount;
+    } fValue;
+
+    Type                fType;
+    UnicodeString       fBogus; // Bogus string when it's needed.
+};
+
+inline UDate Formattable::getDate(UErrorCode& status) const {
+    if (fType != kDate) {
+        if (U_SUCCESS(status)) {
+            status = U_INVALID_FORMAT_ERROR;
+        }
+        return 0;
+    }
+    return fValue.fDate;
+}
+
+inline const UnicodeString& Formattable::getString(void) const {
+    return *fValue.fString;
+}
+
+inline UnicodeString& Formattable::getString(void) {
+    return *fValue.fString;
+}
+
+inline int32_t Formattable::getLong(UErrorCode* status) const {
+    return getLong(*status);
+}
+
+U_NAMESPACE_END
+
+#endif /* #if !UCONFIG_NO_FORMATTING */
+
+#endif //_FMTABLE
+//eof
+

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/format.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/format.h b/src/apps/couch_collate/platform/osx/icu/unicode/format.h
new file mode 100644
index 0000000..7f17b52
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/format.h
@@ -0,0 +1,296 @@
+/*
+********************************************************************************
+* Copyright (C) 1997-2006, International Business Machines Corporation and others.
+* All Rights Reserved.
+********************************************************************************
+*
+* File FORMAT.H
+*
+* Modification History:
+*
+*   Date        Name        Description
+*   02/19/97    aliu        Converted from java.
+*   03/17/97    clhuang     Updated per C++ implementation.
+*   03/27/97    helena      Updated to pass the simple test after code review.
+********************************************************************************
+*/
+// *****************************************************************************
+// This file was generated from the java source file Format.java
+// *****************************************************************************
+
+#ifndef FORMAT_H
+#define FORMAT_H
+
+
+#include "unicode/utypes.h"
+
+/**
+ * \file 
+ * \brief C++ API: Base class for all formats. 
+ */
+
+#if !UCONFIG_NO_FORMATTING
+
+#include "unicode/unistr.h"
+#include "unicode/fmtable.h"
+#include "unicode/fieldpos.h"
+#include "unicode/parsepos.h"
+#include "unicode/parseerr.h" 
+#include "unicode/locid.h"
+
+U_NAMESPACE_BEGIN
+
+/**
+ * Base class for all formats.  This is an abstract base class which
+ * specifies the protocol for classes which convert other objects or
+ * values, such as numeric values and dates, and their string
+ * representations.  In some cases these representations may be
+ * localized or contain localized characters or strings.  For example,
+ * a numeric formatter such as DecimalFormat may convert a numeric
+ * value such as 12345 to the string "$12,345".  It may also parse
+ * the string back into a numeric value.  A date and time formatter
+ * like SimpleDateFormat may represent a specific date, encoded
+ * numerically, as a string such as "Wednesday, February 26, 1997 AD".
+ * <P>
+ * Many of the concrete subclasses of Format employ the notion of
+ * a pattern.  A pattern is a string representation of the rules which
+ * govern the interconversion between values and strings.  For example,
+ * a DecimalFormat object may be associated with the pattern
+ * "$#,##0.00;($#,##0.00)", which is a common US English format for
+ * currency values, yielding strings such as "$1,234.45" for 1234.45,
+ * and "($987.65)" for 987.6543.  The specific syntax of a pattern
+ * is defined by each subclass.
+ * <P>
+ * Even though many subclasses use patterns, the notion of a pattern
+ * is not inherent to Format classes in general, and is not part of
+ * the explicit base class protocol.
+ * <P>
+ * Two complex formatting classes bear mentioning.  These are
+ * MessageFormat and ChoiceFormat.  ChoiceFormat is a subclass of
+ * NumberFormat which allows the user to format different number ranges
+ * as strings.  For instance, 0 may be represented as "no files", 1 as
+ * "one file", and any number greater than 1 as "many files".
+ * MessageFormat is a formatter which utilizes other Format objects to
+ * format a string containing with multiple values.  For instance,
+ * A MessageFormat object might produce the string "There are no files
+ * on the disk MyDisk on February 27, 1997." given the arguments 0,
+ * "MyDisk", and the date value of 2/27/97.  See the ChoiceFormat
+ * and MessageFormat headers for further information.
+ * <P>
+ * If formatting is unsuccessful, a failing UErrorCode is returned when
+ * the Format cannot format the type of object, otherwise if there is
+ * something illformed about the the Unicode replacement character
+ * 0xFFFD is returned.
+ * <P>
+ * If there is no match when parsing, a parse failure UErrorCode is
+ * retured for methods which take no ParsePosition.  For the method
+ * that takes a ParsePosition, the index parameter is left unchanged.
+ * <P>
+ * <em>User subclasses are not supported.</em> While clients may write
+ * subclasses, such code will not necessarily work and will not be
+ * guaranteed to work stably from release to release.
+ */
+class U_I18N_API Format : public UObject {
+public:
+
+    /** Destructor
+     * @stable ICU 2.4
+     */
+    virtual ~Format();
+
+    /**
+     * Return true if the given Format objects are semantically equal.
+     * Objects of different subclasses are considered unequal.
+     * @param other    the object to be compared with.
+     * @return         Return true if the given Format objects are semantically equal.
+     *                 Objects of different subclasses are considered unequal.
+     * @stable ICU 2.0
+     */
+    virtual UBool operator==(const Format& other) const = 0;
+
+    /**
+     * Return true if the given Format objects are not semantically
+     * equal.
+     * @param other    the object to be compared with.
+     * @return         Return true if the given Format objects are not semantically.
+     * @stable ICU 2.0
+     */
+    UBool operator!=(const Format& other) const { return !operator==(other); }
+
+    /**
+     * Clone this object polymorphically.  The caller is responsible
+     * for deleting the result when done.
+     * @return    A copy of the object
+     * @stable ICU 2.0
+     */
+    virtual Format* clone() const = 0;
+
+    /**
+     * Formats an object to produce a string.
+     *
+     * @param obj       The object to format.
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     * @param status    Output parameter filled in with success or failure status.
+     * @return          Reference to 'appendTo' parameter.
+     * @stable ICU 2.0
+     */
+    UnicodeString& format(const Formattable& obj,
+                          UnicodeString& appendTo,
+                          UErrorCode& status) const;
+
+    /**
+     * Format an object to produce a string.  This is a pure virtual method which
+     * subclasses must implement. This method allows polymorphic formatting
+     * of Formattable objects. If a subclass of Format receives a Formattable
+     * object type it doesn't handle (e.g., if a numeric Formattable is passed
+     * to a DateFormat object) then it returns a failing UErrorCode.
+     *
+     * @param obj       The object to format.
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     * @param pos       On input: an alignment field, if desired.
+     *                  On output: the offsets of the alignment field.
+     * @param status    Output param filled with success/failure status.
+     * @return          Reference to 'appendTo' parameter.
+     * @stable ICU 2.0
+     */
+    virtual UnicodeString& format(const Formattable& obj,
+                                  UnicodeString& appendTo,
+                                  FieldPosition& pos,
+                                  UErrorCode& status) const = 0;
+
+    /**
+     * Parse a string to produce an object.  This is a pure virtual
+     * method which subclasses must implement.  This method allows
+     * polymorphic parsing of strings into Formattable objects.
+     * <P>
+     * Before calling, set parse_pos.index to the offset you want to
+     * start parsing at in the source.  After calling, parse_pos.index
+     * is the end of the text you parsed.  If error occurs, index is
+     * unchanged.
+     * <P>
+     * When parsing, leading whitespace is discarded (with successful
+     * parse), while trailing whitespace is left as is.
+     * <P>
+     * Example:
+     * <P>
+     * Parsing "_12_xy" (where _ represents a space) for a number,
+     * with index == 0 will result in the number 12, with
+     * parse_pos.index updated to 3 (just before the second space).
+     * Parsing a second time will result in a failing UErrorCode since
+     * "xy" is not a number, and leave index at 3.
+     * <P>
+     * Subclasses will typically supply specific parse methods that
+     * return different types of values. Since methods can't overload
+     * on return types, these will typically be named "parse", while
+     * this polymorphic method will always be called parseObject.  Any
+     * parse method that does not take a parse_pos should set status
+     * to an error value when no text in the required format is at the
+     * start position.
+     *
+     * @param source    The string to be parsed into an object.
+     * @param result    Formattable to be set to the parse result.
+     *                  If parse fails, return contents are undefined.
+     * @param parse_pos The position to start parsing at. Upon return
+     *                  this param is set to the position after the
+     *                  last character successfully parsed. If the
+     *                  source is not parsed successfully, this param
+     *                  will remain unchanged.
+     * @stable ICU 2.0
+     */
+    virtual void parseObject(const UnicodeString& source,
+                             Formattable& result,
+                             ParsePosition& parse_pos) const = 0;
+
+    /**
+     * Parses a string to produce an object. This is a convenience method
+     * which calls the pure virtual parseObject() method, and returns a
+     * failure UErrorCode if the ParsePosition indicates failure.
+     *
+     * @param source    The string to be parsed into an object.
+     * @param result    Formattable to be set to the parse result.
+     *                  If parse fails, return contents are undefined.
+     * @param status    Output param to be filled with success/failure
+     *                  result code.
+     * @stable ICU 2.0
+     */
+    void parseObject(const UnicodeString& source,
+                     Formattable& result,
+                     UErrorCode& status) const;
+
+    /**
+     * Returns a unique class ID POLYMORPHICALLY.  Pure virtual method.
+     * This method is to implement a simple version of RTTI, since not all
+     * C++ compilers support genuine RTTI.  Polymorphic operator==() and
+     * clone() methods call this method.
+     * Concrete subclasses of Format must implement getDynamicClassID()
+     *
+     * @return          The class ID for this object. All objects of a
+     *                  given class have the same class ID.  Objects of
+     *                  other classes have different class IDs.
+     * @stable ICU 2.0
+     */
+    virtual UClassID getDynamicClassID() const = 0;
+
+    /** Get the locale for this format object. You can choose between valid and actual locale.
+     *  @param type type of the locale we're looking for (valid or actual) 
+     *  @param status error code for the operation
+     *  @return the locale
+     *  @stable ICU 2.8
+     */
+    Locale getLocale(ULocDataLocaleType type, UErrorCode& status) const;
+
+    /** Get the locale for this format object. You can choose between valid and actual locale.
+     *  @param type type of the locale we're looking for (valid or actual) 
+     *  @param status error code for the operation
+     *  @return the locale
+     *  @internal
+     */
+    const char* getLocaleID(ULocDataLocaleType type, UErrorCode &status) const;
+
+ protected:
+    /** @stable ICU 2.8 */
+    void setLocaleIDs(const char* valid, const char* actual);
+
+protected:
+    /**
+     * Default constructor for subclass use only.  Does nothing.
+     * @stable ICU 2.0
+     */
+    Format();
+
+    /**
+     * @stable ICU 2.0
+     */
+    Format(const Format&); // Does nothing; for subclasses only
+
+    /**
+     * @stable ICU 2.0
+     */
+    Format& operator=(const Format&); // Does nothing; for subclasses
+
+       
+    /**
+     * Simple function for initializing a UParseError from a UnicodeString.
+     *
+     * @param pattern The pattern to copy into the parseError
+     * @param pos The position in pattern where the error occured
+     * @param parseError The UParseError object to fill in
+     * @stable ICU 2.4
+     */
+    static void syntaxError(const UnicodeString& pattern,
+                            int32_t pos,
+                            UParseError& parseError);
+
+ private:
+    char actualLocale[ULOC_FULLNAME_CAPACITY];
+    char validLocale[ULOC_FULLNAME_CAPACITY];
+};
+
+U_NAMESPACE_END
+
+#endif /* #if !UCONFIG_NO_FORMATTING */
+
+#endif // _FORMAT
+//eof


[20/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/js/libs/ace/worker-javascript.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/js/libs/ace/worker-javascript.js b/apps/fauxton/assets/js/libs/ace/worker-javascript.js
deleted file mode 100644
index 5481bed..0000000
--- a/apps/fauxton/assets/js/libs/ace/worker-javascript.js
+++ /dev/null
@@ -1,10088 +0,0 @@
-"no use strict";
-;(function(window) {
-if (typeof window.window != "undefined" && window.document) {
-    return;
-}
-
-window.console = function() {
-    var msgs = Array.prototype.slice.call(arguments, 0);
-    postMessage({type: "log", data: msgs});
-};
-window.console.error =
-window.console.warn = 
-window.console.log =
-window.console.trace = window.console;
-
-window.window = window;
-window.ace = window;
-
-window.normalizeModule = function(parentId, moduleName) {
-    if (moduleName.indexOf("!") !== -1) {
-        var chunks = moduleName.split("!");
-        return window.normalizeModule(parentId, chunks[0]) + "!" + window.normalizeModule(parentId, chunks[1]);
-    }
-    if (moduleName.charAt(0) == ".") {
-        var base = parentId.split("/").slice(0, -1).join("/");
-        moduleName = (base ? base + "/" : "") + moduleName;
-        
-        while(moduleName.indexOf(".") !== -1 && previous != moduleName) {
-            var previous = moduleName;
-            moduleName = moduleName.replace(/^\.\//, "").replace(/\/\.\//, "/").replace(/[^\/]+\/\.\.\//, "");
-        }
-    }
-    
-    return moduleName;
-};
-
-window.require = function(parentId, id) {
-    if (!id) {
-        id = parentId
-        parentId = null;
-    }
-    if (!id.charAt)
-        throw new Error("worker.js require() accepts only (parentId, id) as arguments");
-
-    id = window.normalizeModule(parentId, id);
-
-    var module = window.require.modules[id];
-    if (module) {
-        if (!module.initialized) {
-            module.initialized = true;
-            module.exports = module.factory().exports;
-        }
-        return module.exports;
-    }
-    
-    var chunks = id.split("/");
-    if (!window.require.tlns)
-        return console.log("unable to load " + id);
-    chunks[0] = window.require.tlns[chunks[0]] || chunks[0];
-    var path = chunks.join("/") + ".js";
-    
-    window.require.id = id;
-    importScripts(path);
-    return window.require(parentId, id);
-};
-window.require.modules = {};
-window.require.tlns = {};
-
-window.define = function(id, deps, factory) {
-    if (arguments.length == 2) {
-        factory = deps;
-        if (typeof id != "string") {
-            deps = id;
-            id = window.require.id;
-        }
-    } else if (arguments.length == 1) {
-        factory = id;
-        deps = []
-        id = window.require.id;
-    }
-
-    if (!deps.length)
-        deps = ['require', 'exports', 'module']
-
-    if (id.indexOf("text!") === 0) 
-        return;
-    
-    var req = function(childId) {
-        return window.require(id, childId);
-    };
-
-    window.require.modules[id] = {
-        exports: {},
-        factory: function() {
-            var module = this;
-            var returnExports = factory.apply(this, deps.map(function(dep) {
-              switch(dep) {
-                  case 'require': return req
-                  case 'exports': return module.exports
-                  case 'module':  return module
-                  default:        return req(dep)
-              }
-            }));
-            if (returnExports)
-                module.exports = returnExports;
-            return module;
-        }
-    };
-};
-window.define.amd = {}
-
-window.initBaseUrls  = function initBaseUrls(topLevelNamespaces) {
-    require.tlns = topLevelNamespaces;
-}
-
-window.initSender = function initSender() {
-
-    var EventEmitter = window.require("ace/lib/event_emitter").EventEmitter;
-    var oop = window.require("ace/lib/oop");
-    
-    var Sender = function() {};
-    
-    (function() {
-        
-        oop.implement(this, EventEmitter);
-                
-        this.callback = function(data, callbackId) {
-            postMessage({
-                type: "call",
-                id: callbackId,
-                data: data
-            });
-        };
-    
-        this.emit = function(name, data) {
-            postMessage({
-                type: "event",
-                name: name,
-                data: data
-            });
-        };
-        
-    }).call(Sender.prototype);
-    
-    return new Sender();
-}
-
-window.main = null;
-window.sender = null;
-
-window.onmessage = function(e) {
-    var msg = e.data;
-    if (msg.command) {
-        if (main[msg.command])
-            main[msg.command].apply(main, msg.args);
-        else
-            throw new Error("Unknown command:" + msg.command);
-    }
-    else if (msg.init) {        
-        initBaseUrls(msg.tlns);
-        require("ace/lib/es5-shim");
-        sender = initSender();
-        var clazz = require(msg.module)[msg.classname];
-        main = new clazz(sender);
-    } 
-    else if (msg.event && sender) {
-        sender._emit(msg.event, msg.data);
-    }
-};
-})(this);// https://github.com/kriskowal/es5-shim
-
-define('ace/lib/es5-shim', ['require', 'exports', 'module' ], function(require, exports, module) {
-
-function Empty() {}
-
-if (!Function.prototype.bind) {
-    Function.prototype.bind = function bind(that) { // .length is 1
-        var target = this;
-        if (typeof target != "function") {
-            throw new TypeError("Function.prototype.bind called on incompatible " + target);
-        }
-        var args = slice.call(arguments, 1); // for normal call
-        var bound = function () {
-
-            if (this instanceof bound) {
-
-                var result = target.apply(
-                    this,
-                    args.concat(slice.call(arguments))
-                );
-                if (Object(result) === result) {
-                    return result;
-                }
-                return this;
-
-            } else {
-                return target.apply(
-                    that,
-                    args.concat(slice.call(arguments))
-                );
-
-            }
-
-        };
-        if(target.prototype) {
-            Empty.prototype = target.prototype;
-            bound.prototype = new Empty();
-            Empty.prototype = null;
-        }
-        return bound;
-    };
-}
-var call = Function.prototype.call;
-var prototypeOfArray = Array.prototype;
-var prototypeOfObject = Object.prototype;
-var slice = prototypeOfArray.slice;
-var _toString = call.bind(prototypeOfObject.toString);
-var owns = call.bind(prototypeOfObject.hasOwnProperty);
-var defineGetter;
-var defineSetter;
-var lookupGetter;
-var lookupSetter;
-var supportsAccessors;
-if ((supportsAccessors = owns(prototypeOfObject, "__defineGetter__"))) {
-    defineGetter = call.bind(prototypeOfObject.__defineGetter__);
-    defineSetter = call.bind(prototypeOfObject.__defineSetter__);
-    lookupGetter = call.bind(prototypeOfObject.__lookupGetter__);
-    lookupSetter = call.bind(prototypeOfObject.__lookupSetter__);
-}
-if ([1,2].splice(0).length != 2) {
-    if(function() { // test IE < 9 to splice bug - see issue #138
-        function makeArray(l) {
-            var a = new Array(l+2);
-            a[0] = a[1] = 0;
-            return a;
-        }
-        var array = [], lengthBefore;
-        
-        array.splice.apply(array, makeArray(20));
-        array.splice.apply(array, makeArray(26));
-
-        lengthBefore = array.length; //46
-        array.splice(5, 0, "XXX"); // add one element
-
-        lengthBefore + 1 == array.length
-
-        if (lengthBefore + 1 == array.length) {
-            return true;// has right splice implementation without bugs
-        }
-    }()) {//IE 6/7
-        var array_splice = Array.prototype.splice;
-        Array.prototype.splice = function(start, deleteCount) {
-            if (!arguments.length) {
-                return [];
-            } else {
-                return array_splice.apply(this, [
-                    start === void 0 ? 0 : start,
-                    deleteCount === void 0 ? (this.length - start) : deleteCount
-                ].concat(slice.call(arguments, 2)))
-            }
-        };
-    } else {//IE8
-        Array.prototype.splice = function(pos, removeCount){
-            var length = this.length;
-            if (pos > 0) {
-                if (pos > length)
-                    pos = length;
-            } else if (pos == void 0) {
-                pos = 0;
-            } else if (pos < 0) {
-                pos = Math.max(length + pos, 0);
-            }
-
-            if (!(pos+removeCount < length))
-                removeCount = length - pos;
-
-            var removed = this.slice(pos, pos+removeCount);
-            var insert = slice.call(arguments, 2);
-            var add = insert.length;            
-            if (pos === length) {
-                if (add) {
-                    this.push.apply(this, insert);
-                }
-            } else {
-                var remove = Math.min(removeCount, length - pos);
-                var tailOldPos = pos + remove;
-                var tailNewPos = tailOldPos + add - remove;
-                var tailCount = length - tailOldPos;
-                var lengthAfterRemove = length - remove;
-
-                if (tailNewPos < tailOldPos) { // case A
-                    for (var i = 0; i < tailCount; ++i) {
-                        this[tailNewPos+i] = this[tailOldPos+i];
-                    }
-                } else if (tailNewPos > tailOldPos) { // case B
-                    for (i = tailCount; i--; ) {
-                        this[tailNewPos+i] = this[tailOldPos+i];
-                    }
-                } // else, add == remove (nothing to do)
-
-                if (add && pos === lengthAfterRemove) {
-                    this.length = lengthAfterRemove; // truncate array
-                    this.push.apply(this, insert);
-                } else {
-                    this.length = lengthAfterRemove + add; // reserves space
-                    for (i = 0; i < add; ++i) {
-                        this[pos+i] = insert[i];
-                    }
-                }
-            }
-            return removed;
-        };
-    }
-}
-if (!Array.isArray) {
-    Array.isArray = function isArray(obj) {
-        return _toString(obj) == "[object Array]";
-    };
-}
-var boxedString = Object("a"),
-    splitString = boxedString[0] != "a" || !(0 in boxedString);
-
-if (!Array.prototype.forEach) {
-    Array.prototype.forEach = function forEach(fun /*, thisp*/) {
-        var object = toObject(this),
-            self = splitString && _toString(this) == "[object String]" ?
-                this.split("") :
-                object,
-            thisp = arguments[1],
-            i = -1,
-            length = self.length >>> 0;
-        if (_toString(fun) != "[object Function]") {
-            throw new TypeError(); // TODO message
-        }
-
-        while (++i < length) {
-            if (i in self) {
-                fun.call(thisp, self[i], i, object);
-            }
-        }
-    };
-}
-if (!Array.prototype.map) {
-    Array.prototype.map = function map(fun /*, thisp*/) {
-        var object = toObject(this),
-            self = splitString && _toString(this) == "[object String]" ?
-                this.split("") :
-                object,
-            length = self.length >>> 0,
-            result = Array(length),
-            thisp = arguments[1];
-        if (_toString(fun) != "[object Function]") {
-            throw new TypeError(fun + " is not a function");
-        }
-
-        for (var i = 0; i < length; i++) {
-            if (i in self)
-                result[i] = fun.call(thisp, self[i], i, object);
-        }
-        return result;
-    };
-}
-if (!Array.prototype.filter) {
-    Array.prototype.filter = function filter(fun /*, thisp */) {
-        var object = toObject(this),
-            self = splitString && _toString(this) == "[object String]" ?
-                this.split("") :
-                    object,
-            length = self.length >>> 0,
-            result = [],
-            value,
-            thisp = arguments[1];
-        if (_toString(fun) != "[object Function]") {
-            throw new TypeError(fun + " is not a function");
-        }
-
-        for (var i = 0; i < length; i++) {
-            if (i in self) {
-                value = self[i];
-                if (fun.call(thisp, value, i, object)) {
-                    result.push(value);
-                }
-            }
-        }
-        return result;
-    };
-}
-if (!Array.prototype.every) {
-    Array.prototype.every = function every(fun /*, thisp */) {
-        var object = toObject(this),
-            self = splitString && _toString(this) == "[object String]" ?
-                this.split("") :
-                object,
-            length = self.length >>> 0,
-            thisp = arguments[1];
-        if (_toString(fun) != "[object Function]") {
-            throw new TypeError(fun + " is not a function");
-        }
-
-        for (var i = 0; i < length; i++) {
-            if (i in self && !fun.call(thisp, self[i], i, object)) {
-                return false;
-            }
-        }
-        return true;
-    };
-}
-if (!Array.prototype.some) {
-    Array.prototype.some = function some(fun /*, thisp */) {
-        var object = toObject(this),
-            self = splitString && _toString(this) == "[object String]" ?
-                this.split("") :
-                object,
-            length = self.length >>> 0,
-            thisp = arguments[1];
-        if (_toString(fun) != "[object Function]") {
-            throw new TypeError(fun + " is not a function");
-        }
-
-        for (var i = 0; i < length; i++) {
-            if (i in self && fun.call(thisp, self[i], i, object)) {
-                return true;
-            }
-        }
-        return false;
-    };
-}
-if (!Array.prototype.reduce) {
-    Array.prototype.reduce = function reduce(fun /*, initial*/) {
-        var object = toObject(this),
-            self = splitString && _toString(this) == "[object String]" ?
-                this.split("") :
-                object,
-            length = self.length >>> 0;
-        if (_toString(fun) != "[object Function]") {
-            throw new TypeError(fun + " is not a function");
-        }
-        if (!length && arguments.length == 1) {
-            throw new TypeError("reduce of empty array with no initial value");
-        }
-
-        var i = 0;
-        var result;
-        if (arguments.length >= 2) {
-            result = arguments[1];
-        } else {
-            do {
-                if (i in self) {
-                    result = self[i++];
-                    break;
-                }
-                if (++i >= length) {
-                    throw new TypeError("reduce of empty array with no initial value");
-                }
-            } while (true);
-        }
-
-        for (; i < length; i++) {
-            if (i in self) {
-                result = fun.call(void 0, result, self[i], i, object);
-            }
-        }
-
-        return result;
-    };
-}
-if (!Array.prototype.reduceRight) {
-    Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) {
-        var object = toObject(this),
-            self = splitString && _toString(this) == "[object String]" ?
-                this.split("") :
-                object,
-            length = self.length >>> 0;
-        if (_toString(fun) != "[object Function]") {
-            throw new TypeError(fun + " is not a function");
-        }
-        if (!length && arguments.length == 1) {
-            throw new TypeError("reduceRight of empty array with no initial value");
-        }
-
-        var result, i = length - 1;
-        if (arguments.length >= 2) {
-            result = arguments[1];
-        } else {
-            do {
-                if (i in self) {
-                    result = self[i--];
-                    break;
-                }
-                if (--i < 0) {
-                    throw new TypeError("reduceRight of empty array with no initial value");
-                }
-            } while (true);
-        }
-
-        do {
-            if (i in this) {
-                result = fun.call(void 0, result, self[i], i, object);
-            }
-        } while (i--);
-
-        return result;
-    };
-}
-if (!Array.prototype.indexOf || ([0, 1].indexOf(1, 2) != -1)) {
-    Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) {
-        var self = splitString && _toString(this) == "[object String]" ?
-                this.split("") :
-                toObject(this),
-            length = self.length >>> 0;
-
-        if (!length) {
-            return -1;
-        }
-
-        var i = 0;
-        if (arguments.length > 1) {
-            i = toInteger(arguments[1]);
-        }
-        i = i >= 0 ? i : Math.max(0, length + i);
-        for (; i < length; i++) {
-            if (i in self && self[i] === sought) {
-                return i;
-            }
-        }
-        return -1;
-    };
-}
-if (!Array.prototype.lastIndexOf || ([0, 1].lastIndexOf(0, -3) != -1)) {
-    Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) {
-        var self = splitString && _toString(this) == "[object String]" ?
-                this.split("") :
-                toObject(this),
-            length = self.length >>> 0;
-
-        if (!length) {
-            return -1;
-        }
-        var i = length - 1;
-        if (arguments.length > 1) {
-            i = Math.min(i, toInteger(arguments[1]));
-        }
-        i = i >= 0 ? i : length - Math.abs(i);
-        for (; i >= 0; i--) {
-            if (i in self && sought === self[i]) {
-                return i;
-            }
-        }
-        return -1;
-    };
-}
-if (!Object.getPrototypeOf) {
-    Object.getPrototypeOf = function getPrototypeOf(object) {
-        return object.__proto__ || (
-            object.constructor ?
-            object.constructor.prototype :
-            prototypeOfObject
-        );
-    };
-}
-if (!Object.getOwnPropertyDescriptor) {
-    var ERR_NON_OBJECT = "Object.getOwnPropertyDescriptor called on a " +
-                         "non-object: ";
-    Object.getOwnPropertyDescriptor = function getOwnPropertyDescriptor(object, property) {
-        if ((typeof object != "object" && typeof object != "function") || object === null)
-            throw new TypeError(ERR_NON_OBJECT + object);
-        if (!owns(object, property))
-            return;
-
-        var descriptor, getter, setter;
-        descriptor =  { enumerable: true, configurable: true };
-        if (supportsAccessors) {
-            var prototype = object.__proto__;
-            object.__proto__ = prototypeOfObject;
-
-            var getter = lookupGetter(object, property);
-            var setter = lookupSetter(object, property);
-            object.__proto__ = prototype;
-
-            if (getter || setter) {
-                if (getter) descriptor.get = getter;
-                if (setter) descriptor.set = setter;
-                return descriptor;
-            }
-        }
-        descriptor.value = object[property];
-        return descriptor;
-    };
-}
-if (!Object.getOwnPropertyNames) {
-    Object.getOwnPropertyNames = function getOwnPropertyNames(object) {
-        return Object.keys(object);
-    };
-}
-if (!Object.create) {
-    var createEmpty;
-    if (Object.prototype.__proto__ === null) {
-        createEmpty = function () {
-            return { "__proto__": null };
-        };
-    } else {
-        createEmpty = function () {
-            var empty = {};
-            for (var i in empty)
-                empty[i] = null;
-            empty.constructor =
-            empty.hasOwnProperty =
-            empty.propertyIsEnumerable =
-            empty.isPrototypeOf =
-            empty.toLocaleString =
-            empty.toString =
-            empty.valueOf =
-            empty.__proto__ = null;
-            return empty;
-        }
-    }
-
-    Object.create = function create(prototype, properties) {
-        var object;
-        if (prototype === null) {
-            object = createEmpty();
-        } else {
-            if (typeof prototype != "object")
-                throw new TypeError("typeof prototype["+(typeof prototype)+"] != 'object'");
-            var Type = function () {};
-            Type.prototype = prototype;
-            object = new Type();
-            object.__proto__ = prototype;
-        }
-        if (properties !== void 0)
-            Object.defineProperties(object, properties);
-        return object;
-    };
-}
-
-function doesDefinePropertyWork(object) {
-    try {
-        Object.defineProperty(object, "sentinel", {});
-        return "sentinel" in object;
-    } catch (exception) {
-    }
-}
-if (Object.defineProperty) {
-    var definePropertyWorksOnObject = doesDefinePropertyWork({});
-    var definePropertyWorksOnDom = typeof document == "undefined" ||
-        doesDefinePropertyWork(document.createElement("div"));
-    if (!definePropertyWorksOnObject || !definePropertyWorksOnDom) {
-        var definePropertyFallback = Object.defineProperty;
-    }
-}
-
-if (!Object.defineProperty || definePropertyFallback) {
-    var ERR_NON_OBJECT_DESCRIPTOR = "Property description must be an object: ";
-    var ERR_NON_OBJECT_TARGET = "Object.defineProperty called on non-object: "
-    var ERR_ACCESSORS_NOT_SUPPORTED = "getters & setters can not be defined " +
-                                      "on this javascript engine";
-
-    Object.defineProperty = function defineProperty(object, property, descriptor) {
-        if ((typeof object != "object" && typeof object != "function") || object === null)
-            throw new TypeError(ERR_NON_OBJECT_TARGET + object);
-        if ((typeof descriptor != "object" && typeof descriptor != "function") || descriptor === null)
-            throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR + descriptor);
-        if (definePropertyFallback) {
-            try {
-                return definePropertyFallback.call(Object, object, property, descriptor);
-            } catch (exception) {
-            }
-        }
-        if (owns(descriptor, "value")) {
-
-            if (supportsAccessors && (lookupGetter(object, property) ||
-                                      lookupSetter(object, property)))
-            {
-                var prototype = object.__proto__;
-                object.__proto__ = prototypeOfObject;
-                delete object[property];
-                object[property] = descriptor.value;
-                object.__proto__ = prototype;
-            } else {
-                object[property] = descriptor.value;
-            }
-        } else {
-            if (!supportsAccessors)
-                throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED);
-            if (owns(descriptor, "get"))
-                defineGetter(object, property, descriptor.get);
-            if (owns(descriptor, "set"))
-                defineSetter(object, property, descriptor.set);
-        }
-
-        return object;
-    };
-}
-if (!Object.defineProperties) {
-    Object.defineProperties = function defineProperties(object, properties) {
-        for (var property in properties) {
-            if (owns(properties, property))
-                Object.defineProperty(object, property, properties[property]);
-        }
-        return object;
-    };
-}
-if (!Object.seal) {
-    Object.seal = function seal(object) {
-        return object;
-    };
-}
-if (!Object.freeze) {
-    Object.freeze = function freeze(object) {
-        return object;
-    };
-}
-try {
-    Object.freeze(function () {});
-} catch (exception) {
-    Object.freeze = (function freeze(freezeObject) {
-        return function freeze(object) {
-            if (typeof object == "function") {
-                return object;
-            } else {
-                return freezeObject(object);
-            }
-        };
-    })(Object.freeze);
-}
-if (!Object.preventExtensions) {
-    Object.preventExtensions = function preventExtensions(object) {
-        return object;
-    };
-}
-if (!Object.isSealed) {
-    Object.isSealed = function isSealed(object) {
-        return false;
-    };
-}
-if (!Object.isFrozen) {
-    Object.isFrozen = function isFrozen(object) {
-        return false;
-    };
-}
-if (!Object.isExtensible) {
-    Object.isExtensible = function isExtensible(object) {
-        if (Object(object) === object) {
-            throw new TypeError(); // TODO message
-        }
-        var name = '';
-        while (owns(object, name)) {
-            name += '?';
-        }
-        object[name] = true;
-        var returnValue = owns(object, name);
-        delete object[name];
-        return returnValue;
-    };
-}
-if (!Object.keys) {
-    var hasDontEnumBug = true,
-        dontEnums = [
-            "toString",
-            "toLocaleString",
-            "valueOf",
-            "hasOwnProperty",
-            "isPrototypeOf",
-            "propertyIsEnumerable",
-            "constructor"
-        ],
-        dontEnumsLength = dontEnums.length;
-
-    for (var key in {"toString": null}) {
-        hasDontEnumBug = false;
-    }
-
-    Object.keys = function keys(object) {
-
-        if (
-            (typeof object != "object" && typeof object != "function") ||
-            object === null
-        ) {
-            throw new TypeError("Object.keys called on a non-object");
-        }
-
-        var keys = [];
-        for (var name in object) {
-            if (owns(object, name)) {
-                keys.push(name);
-            }
-        }
-
-        if (hasDontEnumBug) {
-            for (var i = 0, ii = dontEnumsLength; i < ii; i++) {
-                var dontEnum = dontEnums[i];
-                if (owns(object, dontEnum)) {
-                    keys.push(dontEnum);
-                }
-            }
-        }
-        return keys;
-    };
-
-}
-if (!Date.now) {
-    Date.now = function now() {
-        return new Date().getTime();
-    };
-}
-var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" +
-    "\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" +
-    "\u2029\uFEFF";
-if (!String.prototype.trim || ws.trim()) {
-    ws = "[" + ws + "]";
-    var trimBeginRegexp = new RegExp("^" + ws + ws + "*"),
-        trimEndRegexp = new RegExp(ws + ws + "*$");
-    String.prototype.trim = function trim() {
-        return String(this).replace(trimBeginRegexp, "").replace(trimEndRegexp, "");
-    };
-}
-
-function toInteger(n) {
-    n = +n;
-    if (n !== n) { // isNaN
-        n = 0;
-    } else if (n !== 0 && n !== (1/0) && n !== -(1/0)) {
-        n = (n > 0 || -1) * Math.floor(Math.abs(n));
-    }
-    return n;
-}
-
-function isPrimitive(input) {
-    var type = typeof input;
-    return (
-        input === null ||
-        type === "undefined" ||
-        type === "boolean" ||
-        type === "number" ||
-        type === "string"
-    );
-}
-
-function toPrimitive(input) {
-    var val, valueOf, toString;
-    if (isPrimitive(input)) {
-        return input;
-    }
-    valueOf = input.valueOf;
-    if (typeof valueOf === "function") {
-        val = valueOf.call(input);
-        if (isPrimitive(val)) {
-            return val;
-        }
-    }
-    toString = input.toString;
-    if (typeof toString === "function") {
-        val = toString.call(input);
-        if (isPrimitive(val)) {
-            return val;
-        }
-    }
-    throw new TypeError();
-}
-var toObject = function (o) {
-    if (o == null) { // this matches both null and undefined
-        throw new TypeError("can't convert "+o+" to object");
-    }
-    return Object(o);
-};
-
-});
-
-define('ace/mode/javascript_worker', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/worker/mirror', 'ace/mode/javascript/jshint'], function(require, exports, module) {
-
-
-var oop = require("../lib/oop");
-var Mirror = require("../worker/mirror").Mirror;
-var lint = require("./javascript/jshint").JSHINT;
-
-function startRegex(arr) {
-    return RegExp("^(" + arr.join("|") + ")");
-}
-
-var disabledWarningsRe = startRegex([
-    "Bad for in variable '(.+)'.",
-    'Missing "use strict"'
-]);
-var errorsRe = startRegex([
-    "Unexpected",
-    "Expected ",
-    "Confusing (plus|minus)",
-    "\\{a\\} unterminated regular expression",
-    "Unclosed ",
-    "Unmatched ",
-    "Unbegun comment",
-    "Bad invocation",
-    "Missing space after",
-    "Missing operator at"
-]);
-var infoRe = startRegex([
-    "Expected an assignment",
-    "Bad escapement of EOL",
-    "Unexpected comma",
-    "Unexpected space",
-    "Missing radix parameter.",
-    "A leading decimal point can",
-    "\\['{a}'\\] is better written in dot notation.",
-    "'{a}' used out of scope"
-]);
-
-var JavaScriptWorker = exports.JavaScriptWorker = function(sender) {
-    Mirror.call(this, sender);
-    this.setTimeout(500);
-    this.setOptions();
-};
-
-oop.inherits(JavaScriptWorker, Mirror);
-
-(function() {
-    this.setOptions = function(options) {
-        this.options = options || {
-            esnext: true,
-            moz: true,
-            devel: true,
-            browser: true,
-            node: true,
-            laxcomma: true,
-            laxbreak: true,
-            lastsemic: true,
-            onevar: false,
-            passfail: false,
-            maxerr: 100,
-            expr: true,
-            multistr: true,
-            globalstrict: true
-        };
-        this.doc.getValue() && this.deferredUpdate.schedule(100);
-    };
-
-    this.changeOptions = function(newOptions) {
-        oop.mixin(this.options, newOptions);
-        this.doc.getValue() && this.deferredUpdate.schedule(100);
-    };
-
-    this.isValidJS = function(str) {
-        try {
-            eval("throw 0;" + str);
-        } catch(e) {
-            if (e === 0)
-                return true;
-        }
-        return false
-    };
-
-    this.onUpdate = function() {
-        var value = this.doc.getValue();
-        value = value.replace(/^#!.*\n/, "\n");
-        if (!value) {
-            this.sender.emit("jslint", []);
-            return;
-        }
-        var errors = [];
-        var maxErrorLevel = this.isValidJS(value) ? "warning" : "error";
-        lint(value, this.options);
-        var results = lint.errors;
-
-        var errorAdded = false
-        for (var i = 0; i < results.length; i++) {
-            var error = results[i];
-            if (!error)
-                continue;
-            var raw = error.raw;
-            var type = "warning";
-
-            if (raw == "Missing semicolon.") {
-                var str = error.evidence.substr(error.character);
-                str = str.charAt(str.search(/\S/));
-                if (maxErrorLevel == "error" && str && /[\w\d{(['"]/.test(str)) {
-                    error.reason = 'Missing ";" before statement';
-                    type = "error";
-                } else {
-                    type = "info";
-                }
-            }
-            else if (disabledWarningsRe.test(raw)) {
-                continue;
-            }
-            else if (infoRe.test(raw)) {
-                type = "info"
-            }
-            else if (errorsRe.test(raw)) {
-                errorAdded  = true;
-                type = maxErrorLevel;
-            }
-            else if (raw == "'{a}' is not defined.") {
-                type = "warning";
-            }
-            else if (raw == "'{a}' is defined but never used.") {
-                type = "info";
-            }
-
-            errors.push({
-                row: error.line-1,
-                column: error.character-1,
-                text: error.reason,
-                type: type,
-                raw: raw
-            });
-
-            if (errorAdded) {
-            }
-        }
-
-        this.sender.emit("jslint", errors);
-    };
-
-}).call(JavaScriptWorker.prototype);
-
-});
-
-define('ace/lib/oop', ['require', 'exports', 'module' ], function(require, exports, module) {
-
-
-exports.inherits = (function() {
-    var tempCtor = function() {};
-    return function(ctor, superCtor) {
-        tempCtor.prototype = superCtor.prototype;
-        ctor.super_ = superCtor.prototype;
-        ctor.prototype = new tempCtor();
-        ctor.prototype.constructor = ctor;
-    };
-}());
-
-exports.mixin = function(obj, mixin) {
-    for (var key in mixin) {
-        obj[key] = mixin[key];
-    }
-    return obj;
-};
-
-exports.implement = function(proto, mixin) {
-    exports.mixin(proto, mixin);
-};
-
-});
-define('ace/worker/mirror', ['require', 'exports', 'module' , 'ace/document', 'ace/lib/lang'], function(require, exports, module) {
-
-
-var Document = require("../document").Document;
-var lang = require("../lib/lang");
-    
-var Mirror = exports.Mirror = function(sender) {
-    this.sender = sender;
-    var doc = this.doc = new Document("");
-    
-    var deferredUpdate = this.deferredUpdate = lang.delayedCall(this.onUpdate.bind(this));
-    
-    var _self = this;
-    sender.on("change", function(e) {
-        doc.applyDeltas(e.data);
-        deferredUpdate.schedule(_self.$timeout);
-    });
-};
-
-(function() {
-    
-    this.$timeout = 500;
-    
-    this.setTimeout = function(timeout) {
-        this.$timeout = timeout;
-    };
-    
-    this.setValue = function(value) {
-        this.doc.setValue(value);
-        this.deferredUpdate.schedule(this.$timeout);
-    };
-    
-    this.getValue = function(callbackId) {
-        this.sender.callback(this.doc.getValue(), callbackId);
-    };
-    
-    this.onUpdate = function() {
-    };
-    
-}).call(Mirror.prototype);
-
-});
-
-define('ace/document', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter', 'ace/range', 'ace/anchor'], function(require, exports, module) {
-
-
-var oop = require("./lib/oop");
-var EventEmitter = require("./lib/event_emitter").EventEmitter;
-var Range = require("./range").Range;
-var Anchor = require("./anchor").Anchor;
-
-var Document = function(text) {
-    this.$lines = [];
-    if (text.length == 0) {
-        this.$lines = [""];
-    } else if (Array.isArray(text)) {
-        this._insertLines(0, text);
-    } else {
-        this.insert({row: 0, column:0}, text);
-    }
-};
-
-(function() {
-
-    oop.implement(this, EventEmitter);
-    this.setValue = function(text) {
-        var len = this.getLength();
-        this.remove(new Range(0, 0, len, this.getLine(len-1).length));
-        this.insert({row: 0, column:0}, text);
-    };
-    this.getValue = function() {
-        return this.getAllLines().join(this.getNewLineCharacter());
-    };
-    this.createAnchor = function(row, column) {
-        return new Anchor(this, row, column);
-    };
-    if ("aaa".split(/a/).length == 0)
-        this.$split = function(text) {
-            return text.replace(/\r\n|\r/g, "\n").split("\n");
-        }
-    else
-        this.$split = function(text) {
-            return text.split(/\r\n|\r|\n/);
-        };
-
-
-    this.$detectNewLine = function(text) {
-        var match = text.match(/^.*?(\r\n|\r|\n)/m);
-        this.$autoNewLine = match ? match[1] : "\n";
-    };
-    this.getNewLineCharacter = function() {
-        switch (this.$newLineMode) {
-          case "windows":
-            return "\r\n";
-          case "unix":
-            return "\n";
-          default:
-            return this.$autoNewLine;
-        }
-    };
-
-    this.$autoNewLine = "\n";
-    this.$newLineMode = "auto";
-    this.setNewLineMode = function(newLineMode) {
-        if (this.$newLineMode === newLineMode)
-            return;
-
-        this.$newLineMode = newLineMode;
-    };
-    this.getNewLineMode = function() {
-        return this.$newLineMode;
-    };
-    this.isNewLine = function(text) {
-        return (text == "\r\n" || text == "\r" || text == "\n");
-    };
-    this.getLine = function(row) {
-        return this.$lines[row] || "";
-    };
-    this.getLines = function(firstRow, lastRow) {
-        return this.$lines.slice(firstRow, lastRow + 1);
-    };
-    this.getAllLines = function() {
-        return this.getLines(0, this.getLength());
-    };
-    this.getLength = function() {
-        return this.$lines.length;
-    };
-    this.getTextRange = function(range) {
-        if (range.start.row == range.end.row) {
-            return this.getLine(range.start.row)
-                .substring(range.start.column, range.end.column);
-        }
-        var lines = this.getLines(range.start.row, range.end.row);
-        lines[0] = (lines[0] || "").substring(range.start.column);
-        var l = lines.length - 1;
-        if (range.end.row - range.start.row == l)
-            lines[l] = lines[l].substring(0, range.end.column);
-        return lines.join(this.getNewLineCharacter());
-    };
-
-    this.$clipPosition = function(position) {
-        var length = this.getLength();
-        if (position.row >= length) {
-            position.row = Math.max(0, length - 1);
-            position.column = this.getLine(length-1).length;
-        } else if (position.row < 0)
-            position.row = 0;
-        return position;
-    };
-    this.insert = function(position, text) {
-        if (!text || text.length === 0)
-            return position;
-
-        position = this.$clipPosition(position);
-        if (this.getLength() <= 1)
-            this.$detectNewLine(text);
-
-        var lines = this.$split(text);
-        var firstLine = lines.splice(0, 1)[0];
-        var lastLine = lines.length == 0 ? null : lines.splice(lines.length - 1, 1)[0];
-
-        position = this.insertInLine(position, firstLine);
-        if (lastLine !== null) {
-            position = this.insertNewLine(position); // terminate first line
-            position = this._insertLines(position.row, lines);
-            position = this.insertInLine(position, lastLine || "");
-        }
-        return position;
-    };
-    this.insertLines = function(row, lines) {
-        if (row >= this.getLength())
-            return this.insert({row: row, column: 0}, "\n" + lines.join("\n"));
-        return this._insertLines(Math.max(row, 0), lines);
-    };
-    this._insertLines = function(row, lines) {
-        if (lines.length == 0)
-            return {row: row, column: 0};
-        if (lines.length > 0xFFFF) {
-            var end = this._insertLines(row, lines.slice(0xFFFF));
-            lines = lines.slice(0, 0xFFFF);
-        }
-
-        var args = [row, 0];
-        args.push.apply(args, lines);
-        this.$lines.splice.apply(this.$lines, args);
-
-        var range = new Range(row, 0, row + lines.length, 0);
-        var delta = {
-            action: "insertLines",
-            range: range,
-            lines: lines
-        };
-        this._emit("change", { data: delta });
-        return end || range.end;
-    };
-    this.insertNewLine = function(position) {
-        position = this.$clipPosition(position);
-        var line = this.$lines[position.row] || "";
-
-        this.$lines[position.row] = line.substring(0, position.column);
-        this.$lines.splice(position.row + 1, 0, line.substring(position.column, line.length));
-
-        var end = {
-            row : position.row + 1,
-            column : 0
-        };
-
-        var delta = {
-            action: "insertText",
-            range: Range.fromPoints(position, end),
-            text: this.getNewLineCharacter()
-        };
-        this._emit("change", { data: delta });
-
-        return end;
-    };
-    this.insertInLine = function(position, text) {
-        if (text.length == 0)
-            return position;
-
-        var line = this.$lines[position.row] || "";
-
-        this.$lines[position.row] = line.substring(0, position.column) + text
-                + line.substring(position.column);
-
-        var end = {
-            row : position.row,
-            column : position.column + text.length
-        };
-
-        var delta = {
-            action: "insertText",
-            range: Range.fromPoints(position, end),
-            text: text
-        };
-        this._emit("change", { data: delta });
-
-        return end;
-    };
-    this.remove = function(range) {
-        if (!range instanceof Range)
-            range = Range.fromPoints(range.start, range.end);
-        range.start = this.$clipPosition(range.start);
-        range.end = this.$clipPosition(range.end);
-
-        if (range.isEmpty())
-            return range.start;
-
-        var firstRow = range.start.row;
-        var lastRow = range.end.row;
-
-        if (range.isMultiLine()) {
-            var firstFullRow = range.start.column == 0 ? firstRow : firstRow + 1;
-            var lastFullRow = lastRow - 1;
-
-            if (range.end.column > 0)
-                this.removeInLine(lastRow, 0, range.end.column);
-
-            if (lastFullRow >= firstFullRow)
-                this._removeLines(firstFullRow, lastFullRow);
-
-            if (firstFullRow != firstRow) {
-                this.removeInLine(firstRow, range.start.column, this.getLine(firstRow).length);
-                this.removeNewLine(range.start.row);
-            }
-        }
-        else {
-            this.removeInLine(firstRow, range.start.column, range.end.column);
-        }
-        return range.start;
-    };
-    this.removeInLine = function(row, startColumn, endColumn) {
-        if (startColumn == endColumn)
-            return;
-
-        var range = new Range(row, startColumn, row, endColumn);
-        var line = this.getLine(row);
-        var removed = line.substring(startColumn, endColumn);
-        var newLine = line.substring(0, startColumn) + line.substring(endColumn, line.length);
-        this.$lines.splice(row, 1, newLine);
-
-        var delta = {
-            action: "removeText",
-            range: range,
-            text: removed
-        };
-        this._emit("change", { data: delta });
-        return range.start;
-    };
-    this.removeLines = function(firstRow, lastRow) {
-        if (firstRow < 0 || lastRow >= this.getLength())
-            return this.remove(new Range(firstRow, 0, lastRow + 1, 0));
-        return this._removeLines(firstRow, lastRow);
-    };
-
-    this._removeLines = function(firstRow, lastRow) {
-        var range = new Range(firstRow, 0, lastRow + 1, 0);
-        var removed = this.$lines.splice(firstRow, lastRow - firstRow + 1);
-
-        var delta = {
-            action: "removeLines",
-            range: range,
-            nl: this.getNewLineCharacter(),
-            lines: removed
-        };
-        this._emit("change", { data: delta });
-        return removed;
-    };
-    this.removeNewLine = function(row) {
-        var firstLine = this.getLine(row);
-        var secondLine = this.getLine(row+1);
-
-        var range = new Range(row, firstLine.length, row+1, 0);
-        var line = firstLine + secondLine;
-
-        this.$lines.splice(row, 2, line);
-
-        var delta = {
-            action: "removeText",
-            range: range,
-            text: this.getNewLineCharacter()
-        };
-        this._emit("change", { data: delta });
-    };
-    this.replace = function(range, text) {
-        if (!range instanceof Range)
-            range = Range.fromPoints(range.start, range.end);
-        if (text.length == 0 && range.isEmpty())
-            return range.start;
-        if (text == this.getTextRange(range))
-            return range.end;
-
-        this.remove(range);
-        if (text) {
-            var end = this.insert(range.start, text);
-        }
-        else {
-            end = range.start;
-        }
-
-        return end;
-    };
-    this.applyDeltas = function(deltas) {
-        for (var i=0; i<deltas.length; i++) {
-            var delta = deltas[i];
-            var range = Range.fromPoints(delta.range.start, delta.range.end);
-
-            if (delta.action == "insertLines")
-                this.insertLines(range.start.row, delta.lines);
-            else if (delta.action == "insertText")
-                this.insert(range.start, delta.text);
-            else if (delta.action == "removeLines")
-                this._removeLines(range.start.row, range.end.row - 1);
-            else if (delta.action == "removeText")
-                this.remove(range);
-        }
-    };
-    this.revertDeltas = function(deltas) {
-        for (var i=deltas.length-1; i>=0; i--) {
-            var delta = deltas[i];
-
-            var range = Range.fromPoints(delta.range.start, delta.range.end);
-
-            if (delta.action == "insertLines")
-                this._removeLines(range.start.row, range.end.row - 1);
-            else if (delta.action == "insertText")
-                this.remove(range);
-            else if (delta.action == "removeLines")
-                this._insertLines(range.start.row, delta.lines);
-            else if (delta.action == "removeText")
-                this.insert(range.start, delta.text);
-        }
-    };
-    this.indexToPosition = function(index, startRow) {
-        var lines = this.$lines || this.getAllLines();
-        var newlineLength = this.getNewLineCharacter().length;
-        for (var i = startRow || 0, l = lines.length; i < l; i++) {
-            index -= lines[i].length + newlineLength;
-            if (index < 0)
-                return {row: i, column: index + lines[i].length + newlineLength};
-        }
-        return {row: l-1, column: lines[l-1].length};
-    };
-    this.positionToIndex = function(pos, startRow) {
-        var lines = this.$lines || this.getAllLines();
-        var newlineLength = this.getNewLineCharacter().length;
-        var index = 0;
-        var row = Math.min(pos.row, lines.length);
-        for (var i = startRow || 0; i < row; ++i)
-            index += lines[i].length + newlineLength;
-
-        return index + pos.column;
-    };
-
-}).call(Document.prototype);
-
-exports.Document = Document;
-});
-
-define('ace/lib/event_emitter', ['require', 'exports', 'module' ], function(require, exports, module) {
-
-
-var EventEmitter = {};
-var stopPropagation = function() { this.propagationStopped = true; };
-var preventDefault = function() { this.defaultPrevented = true; };
-
-EventEmitter._emit =
-EventEmitter._dispatchEvent = function(eventName, e) {
-    this._eventRegistry || (this._eventRegistry = {});
-    this._defaultHandlers || (this._defaultHandlers = {});
-
-    var listeners = this._eventRegistry[eventName] || [];
-    var defaultHandler = this._defaultHandlers[eventName];
-    if (!listeners.length && !defaultHandler)
-        return;
-
-    if (typeof e != "object" || !e)
-        e = {};
-
-    if (!e.type)
-        e.type = eventName;
-    if (!e.stopPropagation)
-        e.stopPropagation = stopPropagation;
-    if (!e.preventDefault)
-        e.preventDefault = preventDefault;
-
-    listeners = listeners.slice();
-    for (var i=0; i<listeners.length; i++) {
-        listeners[i](e, this);
-        if (e.propagationStopped)
-            break;
-    }
-    
-    if (defaultHandler && !e.defaultPrevented)
-        return defaultHandler(e, this);
-};
-
-
-EventEmitter._signal = function(eventName, e) {
-    var listeners = (this._eventRegistry || {})[eventName];
-    if (!listeners)
-        return;
-    listeners = listeners.slice();
-    for (var i=0; i<listeners.length; i++)
-        listeners[i](e, this);
-};
-
-EventEmitter.once = function(eventName, callback) {
-    var _self = this;
-    callback && this.addEventListener(eventName, function newCallback() {
-        _self.removeEventListener(eventName, newCallback);
-        callback.apply(null, arguments);
-    });
-};
-
-
-EventEmitter.setDefaultHandler = function(eventName, callback) {
-    var handlers = this._defaultHandlers
-    if (!handlers)
-        handlers = this._defaultHandlers = {_disabled_: {}};
-    
-    if (handlers[eventName]) {
-        var old = handlers[eventName];
-        var disabled = handlers._disabled_[eventName];
-        if (!disabled)
-            handlers._disabled_[eventName] = disabled = [];
-        disabled.push(old);
-        var i = disabled.indexOf(callback);
-        if (i != -1) 
-            disabled.splice(i, 1);
-    }
-    handlers[eventName] = callback;
-};
-EventEmitter.removeDefaultHandler = function(eventName, callback) {
-    var handlers = this._defaultHandlers
-    if (!handlers)
-        return;
-    var disabled = handlers._disabled_[eventName];
-    
-    if (handlers[eventName] == callback) {
-        var old = handlers[eventName];
-        if (disabled)
-            this.setDefaultHandler(eventName, disabled.pop());
-    } else if (disabled) {
-        var i = disabled.indexOf(callback);
-        if (i != -1)
-            disabled.splice(i, 1);
-    }
-};
-
-EventEmitter.on =
-EventEmitter.addEventListener = function(eventName, callback, capturing) {
-    this._eventRegistry = this._eventRegistry || {};
-
-    var listeners = this._eventRegistry[eventName];
-    if (!listeners)
-        listeners = this._eventRegistry[eventName] = [];
-
-    if (listeners.indexOf(callback) == -1)
-        listeners[capturing ? "unshift" : "push"](callback);
-    return callback;
-};
-
-EventEmitter.off =
-EventEmitter.removeListener =
-EventEmitter.removeEventListener = function(eventName, callback) {
-    this._eventRegistry = this._eventRegistry || {};
-
-    var listeners = this._eventRegistry[eventName];
-    if (!listeners)
-        return;
-
-    var index = listeners.indexOf(callback);
-    if (index !== -1)
-        listeners.splice(index, 1);
-};
-
-EventEmitter.removeAllListeners = function(eventName) {
-    if (this._eventRegistry) this._eventRegistry[eventName] = [];
-};
-
-exports.EventEmitter = EventEmitter;
-
-});
-
-define('ace/range', ['require', 'exports', 'module' ], function(require, exports, module) {
-
-var comparePoints = function(p1, p2) {
-    return p1.row - p2.row || p1.column - p2.column;
-};
-var Range = function(startRow, startColumn, endRow, endColumn) {
-    this.start = {
-        row: startRow,
-        column: startColumn
-    };
-
-    this.end = {
-        row: endRow,
-        column: endColumn
-    };
-};
-
-(function() {
-    this.isEqual = function(range) {
-        return this.start.row === range.start.row &&
-            this.end.row === range.end.row &&
-            this.start.column === range.start.column &&
-            this.end.column === range.end.column;
-    };
-    this.toString = function() {
-        return ("Range: [" + this.start.row + "/" + this.start.column +
-            "] -> [" + this.end.row + "/" + this.end.column + "]");
-    };
-
-    this.contains = function(row, column) {
-        return this.compare(row, column) == 0;
-    };
-    this.compareRange = function(range) {
-        var cmp,
-            end = range.end,
-            start = range.start;
-
-        cmp = this.compare(end.row, end.column);
-        if (cmp == 1) {
-            cmp = this.compare(start.row, start.column);
-            if (cmp == 1) {
-                return 2;
-            } else if (cmp == 0) {
-                return 1;
-            } else {
-                return 0;
-            }
-        } else if (cmp == -1) {
-            return -2;
-        } else {
-            cmp = this.compare(start.row, start.column);
-            if (cmp == -1) {
-                return -1;
-            } else if (cmp == 1) {
-                return 42;
-            } else {
-                return 0;
-            }
-        }
-    };
-    this.comparePoint = function(p) {
-        return this.compare(p.row, p.column);
-    };
-    this.containsRange = function(range) {
-        return this.comparePoint(range.start) == 0 && this.comparePoint(range.end) == 0;
-    };
-    this.intersects = function(range) {
-        var cmp = this.compareRange(range);
-        return (cmp == -1 || cmp == 0 || cmp == 1);
-    };
-    this.isEnd = function(row, column) {
-        return this.end.row == row && this.end.column == column;
-    };
-    this.isStart = function(row, column) {
-        return this.start.row == row && this.start.column == column;
-    };
-    this.setStart = function(row, column) {
-        if (typeof row == "object") {
-            this.start.column = row.column;
-            this.start.row = row.row;
-        } else {
-            this.start.row = row;
-            this.start.column = column;
-        }
-    };
-    this.setEnd = function(row, column) {
-        if (typeof row == "object") {
-            this.end.column = row.column;
-            this.end.row = row.row;
-        } else {
-            this.end.row = row;
-            this.end.column = column;
-        }
-    };
-    this.inside = function(row, column) {
-        if (this.compare(row, column) == 0) {
-            if (this.isEnd(row, column) || this.isStart(row, column)) {
-                return false;
-            } else {
-                return true;
-            }
-        }
-        return false;
-    };
-    this.insideStart = function(row, column) {
-        if (this.compare(row, column) == 0) {
-            if (this.isEnd(row, column)) {
-                return false;
-            } else {
-                return true;
-            }
-        }
-        return false;
-    };
-    this.insideEnd = function(row, column) {
-        if (this.compare(row, column) == 0) {
-            if (this.isStart(row, column)) {
-                return false;
-            } else {
-                return true;
-            }
-        }
-        return false;
-    };
-    this.compare = function(row, column) {
-        if (!this.isMultiLine()) {
-            if (row === this.start.row) {
-                return column < this.start.column ? -1 : (column > this.end.column ? 1 : 0);
-            };
-        }
-
-        if (row < this.start.row)
-            return -1;
-
-        if (row > this.end.row)
-            return 1;
-
-        if (this.start.row === row)
-            return column >= this.start.column ? 0 : -1;
-
-        if (this.end.row === row)
-            return column <= this.end.column ? 0 : 1;
-
-        return 0;
-    };
-    this.compareStart = function(row, column) {
-        if (this.start.row == row && this.start.column == column) {
-            return -1;
-        } else {
-            return this.compare(row, column);
-        }
-    };
-    this.compareEnd = function(row, column) {
-        if (this.end.row == row && this.end.column == column) {
-            return 1;
-        } else {
-            return this.compare(row, column);
-        }
-    };
-    this.compareInside = function(row, column) {
-        if (this.end.row == row && this.end.column == column) {
-            return 1;
-        } else if (this.start.row == row && this.start.column == column) {
-            return -1;
-        } else {
-            return this.compare(row, column);
-        }
-    };
-    this.clipRows = function(firstRow, lastRow) {
-        if (this.end.row > lastRow)
-            var end = {row: lastRow + 1, column: 0};
-        else if (this.end.row < firstRow)
-            var end = {row: firstRow, column: 0};
-
-        if (this.start.row > lastRow)
-            var start = {row: lastRow + 1, column: 0};
-        else if (this.start.row < firstRow)
-            var start = {row: firstRow, column: 0};
-
-        return Range.fromPoints(start || this.start, end || this.end);
-    };
-    this.extend = function(row, column) {
-        var cmp = this.compare(row, column);
-
-        if (cmp == 0)
-            return this;
-        else if (cmp == -1)
-            var start = {row: row, column: column};
-        else
-            var end = {row: row, column: column};
-
-        return Range.fromPoints(start || this.start, end || this.end);
-    };
-
-    this.isEmpty = function() {
-        return (this.start.row === this.end.row && this.start.column === this.end.column);
-    };
-    this.isMultiLine = function() {
-        return (this.start.row !== this.end.row);
-    };
-    this.clone = function() {
-        return Range.fromPoints(this.start, this.end);
-    };
-    this.collapseRows = function() {
-        if (this.end.column == 0)
-            return new Range(this.start.row, 0, Math.max(this.start.row, this.end.row-1), 0)
-        else
-            return new Range(this.start.row, 0, this.end.row, 0)
-    };
-    this.toScreenRange = function(session) {
-        var screenPosStart = session.documentToScreenPosition(this.start);
-        var screenPosEnd = session.documentToScreenPosition(this.end);
-
-        return new Range(
-            screenPosStart.row, screenPosStart.column,
-            screenPosEnd.row, screenPosEnd.column
-        );
-    };
-    this.moveBy = function(row, column) {
-        this.start.row += row;
-        this.start.column += column;
-        this.end.row += row;
-        this.end.column += column;
-    };
-
-}).call(Range.prototype);
-Range.fromPoints = function(start, end) {
-    return new Range(start.row, start.column, end.row, end.column);
-};
-Range.comparePoints = comparePoints;
-
-Range.comparePoints = function(p1, p2) {
-    return p1.row - p2.row || p1.column - p2.column;
-};
-
-
-exports.Range = Range;
-});
-
-define('ace/anchor', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter'], function(require, exports, module) {
-
-
-var oop = require("./lib/oop");
-var EventEmitter = require("./lib/event_emitter").EventEmitter;
-
-var Anchor = exports.Anchor = function(doc, row, column) {
-    this.$onChange = this.onChange.bind(this);
-    this.attach(doc);
-    
-    if (typeof column == "undefined")
-        this.setPosition(row.row, row.column);
-    else
-        this.setPosition(row, column);
-};
-
-(function() {
-
-    oop.implement(this, EventEmitter);
-    this.getPosition = function() {
-        return this.$clipPositionToDocument(this.row, this.column);
-    };
-    this.getDocument = function() {
-        return this.document;
-    };
-    this.$insertRight = false;
-    this.onChange = function(e) {
-        var delta = e.data;
-        var range = delta.range;
-
-        if (range.start.row == range.end.row && range.start.row != this.row)
-            return;
-
-        if (range.start.row > this.row)
-            return;
-
-        if (range.start.row == this.row && range.start.column > this.column)
-            return;
-
-        var row = this.row;
-        var column = this.column;
-        var start = range.start;
-        var end = range.end;
-
-        if (delta.action === "insertText") {
-            if (start.row === row && start.column <= column) {
-                if (start.column === column && this.$insertRight) {
-                } else if (start.row === end.row) {
-                    column += end.column - start.column;
-                } else {
-                    column -= start.column;
-                    row += end.row - start.row;
-                }
-            } else if (start.row !== end.row && start.row < row) {
-                row += end.row - start.row;
-            }
-        } else if (delta.action === "insertLines") {
-            if (start.row <= row) {
-                row += end.row - start.row;
-            }
-        } else if (delta.action === "removeText") {
-            if (start.row === row && start.column < column) {
-                if (end.column >= column)
-                    column = start.column;
-                else
-                    column = Math.max(0, column - (end.column - start.column));
-
-            } else if (start.row !== end.row && start.row < row) {
-                if (end.row === row)
-                    column = Math.max(0, column - end.column) + start.column;
-                row -= (end.row - start.row);
-            } else if (end.row === row) {
-                row -= end.row - start.row;
-                column = Math.max(0, column - end.column) + start.column;
-            }
-        } else if (delta.action == "removeLines") {
-            if (start.row <= row) {
-                if (end.row <= row)
-                    row -= end.row - start.row;
-                else {
-                    row = start.row;
-                    column = 0;
-                }
-            }
-        }
-
-        this.setPosition(row, column, true);
-    };
-    this.setPosition = function(row, column, noClip) {
-        var pos;
-        if (noClip) {
-            pos = {
-                row: row,
-                column: column
-            };
-        } else {
-            pos = this.$clipPositionToDocument(row, column);
-        }
-
-        if (this.row == pos.row && this.column == pos.column)
-            return;
-
-        var old = {
-            row: this.row,
-            column: this.column
-        };
-
-        this.row = pos.row;
-        this.column = pos.column;
-        this._emit("change", {
-            old: old,
-            value: pos
-        });
-    };
-    this.detach = function() {
-        this.document.removeEventListener("change", this.$onChange);
-    };
-    this.attach = function(doc) {
-        this.document = doc || this.document;
-        this.document.on("change", this.$onChange);
-    };
-    this.$clipPositionToDocument = function(row, column) {
-        var pos = {};
-
-        if (row >= this.document.getLength()) {
-            pos.row = Math.max(0, this.document.getLength() - 1);
-            pos.column = this.document.getLine(pos.row).length;
-        }
-        else if (row < 0) {
-            pos.row = 0;
-            pos.column = 0;
-        }
-        else {
-            pos.row = row;
-            pos.column = Math.min(this.document.getLine(pos.row).length, Math.max(0, column));
-        }
-
-        if (column < 0)
-            pos.column = 0;
-
-        return pos;
-    };
-
-}).call(Anchor.prototype);
-
-});
-
-define('ace/lib/lang', ['require', 'exports', 'module' ], function(require, exports, module) {
-
-
-exports.stringReverse = function(string) {
-    return string.split("").reverse().join("");
-};
-
-exports.stringRepeat = function (string, count) {
-    var result = '';
-    while (count > 0) {
-        if (count & 1)
-            result += string;
-
-        if (count >>= 1)
-            string += string;
-    }
-    return result;
-};
-
-var trimBeginRegexp = /^\s\s*/;
-var trimEndRegexp = /\s\s*$/;
-
-exports.stringTrimLeft = function (string) {
-    return string.replace(trimBeginRegexp, '');
-};
-
-exports.stringTrimRight = function (string) {
-    return string.replace(trimEndRegexp, '');
-};
-
-exports.copyObject = function(obj) {
-    var copy = {};
-    for (var key in obj) {
-        copy[key] = obj[key];
-    }
-    return copy;
-};
-
-exports.copyArray = function(array){
-    var copy = [];
-    for (var i=0, l=array.length; i<l; i++) {
-        if (array[i] && typeof array[i] == "object")
-            copy[i] = this.copyObject( array[i] );
-        else 
-            copy[i] = array[i];
-    }
-    return copy;
-};
-
-exports.deepCopy = function (obj) {
-    if (typeof obj != "object") {
-        return obj;
-    }
-    
-    var copy = obj.constructor();
-    for (var key in obj) {
-        if (typeof obj[key] == "object") {
-            copy[key] = this.deepCopy(obj[key]);
-        } else {
-            copy[key] = obj[key];
-        }
-    }
-    return copy;
-};
-
-exports.arrayToMap = function(arr) {
-    var map = {};
-    for (var i=0; i<arr.length; i++) {
-        map[arr[i]] = 1;
-    }
-    return map;
-
-};
-
-exports.createMap = function(props) {
-    var map = Object.create(null);
-    for (var i in props) {
-        map[i] = props[i];
-    }
-    return map;
-};
-exports.arrayRemove = function(array, value) {
-  for (var i = 0; i <= array.length; i++) {
-    if (value === array[i]) {
-      array.splice(i, 1);
-    }
-  }
-};
-
-exports.escapeRegExp = function(str) {
-    return str.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1');
-};
-
-exports.escapeHTML = function(str) {
-    return str.replace(/&/g, "&#38;").replace(/"/g, "&#34;").replace(/'/g, "&#39;").replace(/</g, "&#60;");
-};
-
-exports.getMatchOffsets = function(string, regExp) {
-    var matches = [];
-
-    string.replace(regExp, function(str) {
-        matches.push({
-            offset: arguments[arguments.length-2],
-            length: str.length
-        });
-    });
-
-    return matches;
-};
-exports.deferredCall = function(fcn) {
-
-    var timer = null;
-    var callback = function() {
-        timer = null;
-        fcn();
-    };
-
-    var deferred = function(timeout) {
-        deferred.cancel();
-        timer = setTimeout(callback, timeout || 0);
-        return deferred;
-    };
-
-    deferred.schedule = deferred;
-
-    deferred.call = function() {
-        this.cancel();
-        fcn();
-        return deferred;
-    };
-
-    deferred.cancel = function() {
-        clearTimeout(timer);
-        timer = null;
-        return deferred;
-    };
-
-    return deferred;
-};
-
-
-exports.delayedCall = function(fcn, defaultTimeout) {
-    var timer = null;
-    var callback = function() {
-        timer = null;
-        fcn();
-    };
-
-    var _self = function(timeout) {
-        timer && clearTimeout(timer);
-        timer = setTimeout(callback, timeout || defaultTimeout);
-    };
-
-    _self.delay = _self;
-    _self.schedule = function(timeout) {
-        if (timer == null)
-            timer = setTimeout(callback, timeout || 0);
-    };
-
-    _self.call = function() {
-        this.cancel();
-        fcn();
-    };
-
-    _self.cancel = function() {
-        timer && clearTimeout(timer);
-        timer = null;
-    };
-
-    _self.isPending = function() {
-        return timer;
-    };
-
-    return _self;
-};
-});
-define('ace/mode/javascript/jshint', ['require', 'exports', 'module' ], function(require, exports, module) {
-require = null;
-require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({
-9:[function (req,module,exports){
-        ["log", "info", "warn", "error", 
-        "time","timeEnd", "trace", "dir", "assert"
-        ].forEach(function(x) {exports[x] = nop;});
-        function nop() {}
-    },{}],
-1:[function(req,module,exports){
-
-(function() {
-  var root = this;
-  var previousUnderscore = root._;
-  var breaker = {};
-  var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
-  var push             = ArrayProto.push,
-      slice            = ArrayProto.slice,
-      concat           = ArrayProto.concat,
-      toString         = ObjProto.toString,
-      hasOwnProperty   = ObjProto.hasOwnProperty;
-  var
-    nativeForEach      = ArrayProto.forEach,
-    nativeMap          = ArrayProto.map,
-    nativeReduce       = ArrayProto.reduce,
-    nativeReduceRight  = ArrayProto.reduceRight,
-    nativeFilter       = ArrayProto.filter,
-    nativeEvery        = ArrayProto.every,
-    nativeSome         = ArrayProto.some,
-    nativeIndexOf      = ArrayProto.indexOf,
-    nativeLastIndexOf  = ArrayProto.lastIndexOf,
-    nativeIsArray      = Array.isArray,
-    nativeKeys         = Object.keys,
-    nativeBind         = FuncProto.bind;
-  var _ = function(obj) {
-    if (obj instanceof _) return obj;
-    if (!(this instanceof _)) return new _(obj);
-    this._wrapped = obj;
-  };
-  if (typeof exports !== 'undefined') {
-    if (typeof module !== 'undefined' && module.exports) {
-      exports = module.exports = _;
-    }
-    exports._ = _;
-  } else {
-    root._ = _;
-  }
-  _.VERSION = '1.4.4';
-  var each = _.each = _.forEach = function(obj, iterator, context) {
-    if (obj == null) return;
-    if (nativeForEach && obj.forEach === nativeForEach) {
-      obj.forEach(iterator, context);
-    } else if (obj.length === +obj.length) {
-      for (var i = 0, l = obj.length; i < l; i++) {
-        if (iterator.call(context, obj[i], i, obj) === breaker) return;
-      }
-    } else {
-      for (var key in obj) {
-        if (_.has(obj, key)) {
-          if (iterator.call(context, obj[key], key, obj) === breaker) return;
-        }
-      }
-    }
-  };
-  _.map = _.collect = function(obj, iterator, context) {
-    var results = [];
-    if (obj == null) return results;
-    if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
-    each(obj, function(value, index, list) {
-      results[results.length] = iterator.call(context, value, index, list);
-    });
-    return results;
-  };
-
-  var reduceError = 'Reduce of empty array with no initial value';
-  _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
-    var initial = arguments.length > 2;
-    if (obj == null) obj = [];
-    if (nativeReduce && obj.reduce === nativeReduce) {
-      if (context) iterator = _.bind(iterator, context);
-      return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
-    }
-    each(obj, function(value, index, list) {
-      if (!initial) {
-        memo = value;
-        initial = true;
-      } else {
-        memo = iterator.call(context, memo, value, index, list);
-      }
-    });
-    if (!initial) throw new TypeError(reduceError);
-    return memo;
-  };
-  _.reduceRight = _.foldr = function(obj, iterator, memo, context) {
-    var initial = arguments.length > 2;
-    if (obj == null) obj = [];
-    if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
-      if (context) iterator = _.bind(iterator, context);
-      return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
-    }
-    var length = obj.length;
-    if (length !== +length) {
-      var keys = _.keys(obj);
-      length = keys.length;
-    }
-    each(obj, function(value, index, list) {
-      index = keys ? keys[--length] : --length;
-      if (!initial) {
-        memo = obj[index];
-        initial = true;
-      } else {
-        memo = iterator.call(context, memo, obj[index], index, list);
-      }
-    });
-    if (!initial) throw new TypeError(reduceError);
-    return memo;
-  };
-  _.find = _.detect = function(obj, iterator, context) {
-    var result;
-    any(obj, function(value, index, list) {
-      if (iterator.call(context, value, index, list)) {
-        result = value;
-        return true;
-      }
-    });
-    return result;
-  };
-  _.filter = _.select = function(obj, iterator, context) {
-    var results = [];
-    if (obj == null) return results;
-    if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
-    each(obj, function(value, index, list) {
-      if (iterator.call(context, value, index, list)) results[results.length] = value;
-    });
-    return results;
-  };
-  _.reject = function(obj, iterator, context) {
-    return _.filter(obj, function(value, index, list) {
-      return !iterator.call(context, value, index, list);
-    }, context);
-  };
-  _.every = _.all = function(obj, iterator, context) {
-    iterator || (iterator = _.identity);
-    var result = true;
-    if (obj == null) return result;
-    if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
-    each(obj, function(value, index, list) {
-      if (!(result = result && iterator.call(context, value, index, list))) return breaker;
-    });
-    return !!result;
-  };
-  var any = _.some = _.any = function(obj, iterator, context) {
-    iterator || (iterator = _.identity);
-    var result = false;
-    if (obj == null) return result;
-    if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
-    each(obj, function(value, index, list) {
-      if (result || (result = iterator.call(context, value, index, list))) return breaker;
-    });
-    return !!result;
-  };
-  _.contains = _.include = function(obj, target) {
-    if (obj == null) return false;
-    if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
-    return any(obj, function(value) {
-      return value === target;
-    });
-  };
-  _.invoke = function(obj, method) {
-    var args = slice.call(arguments, 2);
-    var isFunc = _.isFunction(method);
-    return _.map(obj, function(value) {
-      return (isFunc ? method : value[method]).apply(value, args);
-    });
-  };
-  _.pluck = function(obj, key) {
-    return _.map(obj, function(value){ return value[key]; });
-  };
-  _.where = function(obj, attrs, first) {
-    if (_.isEmpty(attrs)) return first ? null : [];
-    return _[first ? 'find' : 'filter'](obj, function(value) {
-      for (var key in attrs) {
-        if (attrs[key] !== value[key]) return false;
-      }
-      return true;
-    });
-  };
-  _.findWhere = function(obj, attrs) {
-    return _.where(obj, attrs, true);
-  };
-  _.max = function(obj, iterator, context) {
-    if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
-      return Math.max.apply(Math, obj);
-    }
-    if (!iterator && _.isEmpty(obj)) return -Infinity;
-    var result = {computed : -Infinity, value: -Infinity};
-    each(obj, function(value, index, list) {
-      var computed = iterator ? iterator.call(context, value, index, list) : value;
-      computed >= result.computed && (result = {value : value, computed : computed});
-    });
-    return result.value;
-  };
-  _.min = function(obj, iterator, context) {
-    if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
-      return Math.min.apply(Math, obj);
-    }
-    if (!iterator && _.isEmpty(obj)) return Infinity;
-    var result = {computed : Infinity, value: Infinity};
-    each(obj, function(value, index, list) {
-      var computed = iterator ? iterator.call(context, value, index, list) : value;
-      computed < result.computed && (result = {value : value, computed : computed});
-    });
-    return result.value;
-  };
-  _.shuffle = function(obj) {
-    var rand;
-    var index = 0;
-    var shuffled = [];
-    each(obj, function(value) {
-      rand = _.random(index++);
-      shuffled[index - 1] = shuffled[rand];
-      shuffled[rand] = value;
-    });
-    return shuffled;
-  };
-  var lookupIterator = function(value) {
-    return _.isFunction(value) ? value : function(obj){ return obj[value]; };
-  };
-  _.sortBy = function(obj, value, context) {
-    var iterator = lookupIterator(value);
-    return _.pluck(_.map(obj, function(value, index, list) {
-      return {
-        value : value,
-        index : index,
-        criteria : iterator.call(context, value, index, list)
-      };
-    }).sort(function(left, right) {
-      var a = left.criteria;
-      var b = right.criteria;
-      if (a !== b) {
-        if (a > b || a === void 0) return 1;
-        if (a < b || b === void 0) return -1;
-      }
-      return left.index < right.index ? -1 : 1;
-    }), 'value');
-  };
-  var group = function(obj, value, context, behavior) {
-    var result = {};
-    var iterator = lookupIterator(value || _.identity);
-    each(obj, function(value, index) {
-      var key = iterator.call(context, value, index, obj);
-      behavior(result, key, value);
-    });
-    return result;
-  };
-  _.groupBy = function(obj, value, context) {
-    return group(obj, value, context, function(result, key, value) {
-      (_.has(result, key) ? result[key] : (result[key] = [])).push(value);
-    });
-  };
-  _.countBy = function(obj, value, context) {
-    return group(obj, value, context, function(result, key) {
-      if (!_.has(result, key)) result[key] = 0;
-      result[key]++;
-    });
-  };
-  _.sortedIndex = function(array, obj, iterator, context) {
-    iterator = iterator == null ? _.identity : lookupIterator(iterator);
-    var value = iterator.call(context, obj);
-    var low = 0, high = array.length;
-    while (low < high) {
-      var mid = (low + high) >>> 1;
-      iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid;
-    }
-    return low;
-  };
-  _.toArray = function(obj) {
-    if (!obj) return [];
-    if (_.isArray(obj)) return slice.call(obj);
-    if (obj.length === +obj.length) return _.map(obj, _.identity);
-    return _.values(obj);
-  };
-  _.size = function(obj) {
-    if (obj == null) return 0;
-    return (obj.length === +obj.length) ? obj.length : _.keys(obj).length;
-  };
-  _.first = _.head = _.take = function(array, n, guard) {
-    if (array == null) return void 0;
-    return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
-  };
-  _.initial = function(array, n, guard) {
-    return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
-  };
-  _.last = function(array, n, guard) {
-    if (array == null) return void 0;
-    if ((n != null) && !guard) {
-      return slice.call(array, Math.max(array.length - n, 0));
-    } else {
-      return array[array.length - 1];
-    }
-  };
-  _.rest = _.tail = _.drop = function(array, n, guard) {
-    return slice.call(array, (n == null) || guard ? 1 : n);
-  };
-  _.compact = function(array) {
-    return _.filter(array, _.identity);
-  };
-  var flatten = function(input, shallow, output) {
-    each(input, function(value) {
-      if (_.isArray(value)) {
-        shallow ? push.apply(output, value) : flatten(value, shallow, output);
-      } else {
-        output.push(value);
-      }
-    });
-    return output;
-  };
-  _.flatten = function(array, shallow) {
-    return flatten(array, shallow, []);
-  };
-  _.without = function(array) {
-    return _.difference(array, slice.call(arguments, 1));
-  };
-  _.uniq = _.unique = function(array, isSorted, iterator, context) {
-    if (_.isFunction(isSorted)) {
-      context = iterator;
-      iterator = isSorted;
-      isSorted = false;
-    }
-    var initial = iterator ? _.map(array, iterator, context) : array;
-    var results = [];
-    var seen = [];
-    each(initial, function(value, index) {
-      if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) {
-        seen.push(value);
-        results.push(array[index]);
-      }
-    });
-    return results;
-  };
-  _.union = function() {
-    return _.uniq(concat.apply(ArrayProto, arguments));
-  };
-  _.intersection = function(array) {
-    var rest = slice.call(arguments, 1);
-    return _.filter(_.uniq(array), function(item) {
-      return _.every(rest, function(other) {
-        return _.indexOf(other, item) >= 0;
-      });
-    });
-  };
-  _.difference = function(array) {
-    var rest = concat.apply(ArrayProto, slice.call(arguments, 1));
-    return _.filter(array, function(value){ return !_.contains(rest, value); });
-  };
-  _.zip = function() {
-    var args = slice.call(arguments);
-    var length = _.max(_.pluck(args, 'length'));
-    var results = new Array(length);
-    for (var i = 0; i < length; i++) {
-      results[i] = _.pluck(args, "" + i);
-    }
-    return results;
-  };
-  _.object = function(list, values) {
-    if (list == null) return {};
-    var result = {};
-    for (var i = 0, l = list.length; i < l; i++) {
-      if (values) {
-        result[list[i]] = values[i];
-      } else {
-        result[list[i][0]] = list[i][1];
-      }
-    }
-    return result;
-  };
-  _.indexOf = function(array, item, isSorted) {
-    if (array == null) return -1;
-    var i = 0, l = array.length;
-    if (isSorted) {
-      if (typeof isSorted == 'number') {
-        i = (isSorted < 0 ? Math.max(0, l + isSorted) : isSorted);
-      } else {
-        i = _.sortedIndex(array, item);
-        return array[i] === item ? i : -1;
-      }
-    }
-    if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);
-    for (; i < l; i++) if (array[i] === item) return i;
-    return -1;
-  };
-  _.lastIndexOf = function(array, item, from) {
-    if (array == null) return -1;
-    var hasIndex = from != null;
-    if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) {
-      return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item);
-    }
-    var i = (hasIndex ? from : array.length);
-    while (i--) if (array[i] === item) return i;
-    return -1;
-  };
-  _.range = function(start, stop, step) {
-    if (arguments.length <= 1) {
-      stop = start || 0;
-      start = 0;
-    }
-    step = arguments[2] || 1;
-
-    var len = Math.max(Math.ceil((stop - start) / step), 0);
-    var idx = 0;
-    var range = new Array(len);
-
-    while(idx < len) {
-      range[idx++] = start;
-      start += step;
-    }
-
-    return range;
-  };
-  _.bind = function(func, context) {
-    if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
-    var args = slice.call(arguments, 2);
-    return function() {
-      return func.apply(context, args.concat(slice.call(arguments)));
-    };
-  };
-  _.partial = function(func) {
-    var args = slice.call(arguments, 1);
-    return function() {
-      return func.apply(this, args.concat(slice.call(arguments)));
-    };
-  };
-  _.bindAll = function(obj) {
-    var funcs = slice.call(arguments, 1);
-    if (funcs.length === 0) funcs = _.functions(obj);
-    each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
-    return obj;
-  };
-  _.memoize = function(func, hasher) {
-    var memo = {};
-    hasher || (hasher = _.identity);
-    return function() {
-      var key = hasher.apply(this, arguments);
-      return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
-    };
-  };
-  _.delay = function(func, wait) {
-    var args = slice.call(arguments, 2);
-    return setTimeout(function(){ return func.apply(null, args); }, wait);
-  };
-  _.defer = function(func) {
-    return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
-  };
-  _.throttle = function(func, wait) {
-    var context, args, timeout, result;
-    var previous = 0;
-    var later = function() {
-      previous = new Date;
-      timeout = null;
-      result = func.apply(context, args);
-    };
-    return function() {
-      var now = new Date;
-      var remaining = wait - (now - previous);
-      context = this;
-      args = arguments;
-      if (remaining <= 0) {
-        clearTimeout(timeout);
-        timeout = null;
-        previous = now;
-        result = func.apply(context, args);
-      } else if (!timeout) {
-        timeout = setTimeout(later, remaining);
-      }
-      return result;
-    };
-  };
-  _.debounce = function(func, wait, immediate) {
-    var timeout, result;
-    return function() {
-      var context = this, args = arguments;
-      var later = function() {
-        timeout = null;
-        if (!immediate) result = func.apply(context, args);
-      };
-      var callNow = immediate && !timeout;
-      clearTimeout(timeout);
-      timeout = setTimeout(later, wait);
-      if (callNow) result = func.apply(context, args);
-      return result;
-    };
-  };
-  _.once = function(func) {
-    var ran = false, memo;
-    return function() {
-      if (ran) return memo;
-      ran = true;
-      memo = func.apply(this, arguments);
-      func = null;
-      return memo;
-    };
-  };
-  _.wrap = function(func, wrapper) {
-    return function() {
-      var args = [func];
-      push.apply(args, arguments);
-      return wrapper.apply(this, args);
-    };
-  };
-  _.compose = function() {
-    var funcs = arguments;
-    return function() {
-      var args = arguments;
-      for (var i = funcs.length - 1; i >= 0; i--) {
-        args = [funcs[i].apply(this, args)];
-      }
-      return args[0];
-    };
-  };
-  _.after = function(times, func) {
-    if (times <= 0) return func();
-    return function() {
-      if (--times < 1) {
-        return func.apply(this, arguments);
-      }
-    };
-  };
-  _.keys = nativeKeys || function(obj) {
-    if (obj !== Object(obj)) throw new TypeError('Invalid object');
-    var keys = [];
-    for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key;
-    return keys;
-  };
-  _.values = function(obj) {
-    var values = [];
-    for (var key in obj) if (_.has(obj, key)) values.push(obj[key]);
-    return values;
-  };
-  _.pairs = function(obj) {
-    var pairs = [];
-    for (var key in obj) if (_.has(obj, key)) pairs.push([key, obj[key]]);
-    return pairs;
-  };
-  _.invert = function(obj) {
-    var result = {};
-    for (var key in obj) if (_.has(obj, key)) result[obj[key]] = key;
-    return result;
-  };
-  _.functions = _.methods = function(obj) {
-    var names = [];
-    for (var key in obj) {
-      if (_.isFunction(obj[key])) names.push(key);
-    }
-    return names.sort();
-  };
-  _.extend = function(obj) {
-    each(slice.call(arguments, 1), function(source) {
-      if (source) {
-        for (var prop in source) {
-          obj[prop] = source[prop];
-        }
-      }
-    });
-    return obj;
-  };
-  _.pick = function(obj) {
-    var copy = {};
-    var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
-    each(keys, function(key) {
-      if (key in obj) copy[key] = obj[key];
-    });
-    return copy;
-  };
-  _.omit = function(obj) {
-    var copy = {};
-    var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
-    for (var key in obj) {
-      if (!_.contains(keys, key)) copy[key] = obj[key];
-    }
-    return copy;
-  };
-  _.defaults = function(obj) {
-    each(slice.call(arguments, 1), function(source) {
-      if (source) {
-        for (var prop in source) {
-          if (obj[prop] == null) obj[prop] = source[prop];
-        }
-      }
-    });
-    return obj;
-  };
-  _.clone = function(obj) {
-    if (!_.isObject(obj)) return obj;
-    return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
-  };
-  _.tap = function(obj, interceptor) {
-    interceptor(obj);
-    return obj;
-  };
-  var eq = function(a, b, aStack, bStack) {
-    if (a === b) return a !== 0 || 1 / a == 1 / b;
-    if (a == null || b == null) return a === b;
-    if (a instanceof _) a = a._wrapped;
-    if (b instanceof _) b = b._wrapped;
-    var className = toString.call(a);
-    if (className != toString.call(b)) return false;
-    switch (className) {
-      case '[object String]':
-        return a == String(b);
-      case '[object Number]':
-        return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
-      case '[object Date]':
-      case '[object Boolean]':
-        return +a == +b;
-      case '[object RegExp]':
-        return a.source == b.source &&
-               a.global == b.global &&
-               a.multiline == b.multiline &&
-               a.ignoreCase == b.ignoreCase;
-    }
-    if (typeof a != 'object' || typeof b != 'object') return false;
-    var length = aStack.length;
-    while (length--) {
-      if (aStack[length] == a) return bStack[length] == b;
-    }
-    aStack.push(a);
-    bStack.push(b);
-    var size = 0, result = true;
-    if (className == '[object Array]') {
-      size = a.length;
-      result = size == b.length;
-      if (result) {
-        while (size--) {
-          if (!(result = eq(a[size], b[size], aStack, bStack))) break;
-        }
-      }
-    } else {
-      var aCtor = a.constructor, bCtor = b.constructor;
-      if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) &&
-                               _.isFunction(bCtor) && (bCtor instanceof bCtor))) {
-        return false;
-      }
-      for (var key in a) {
-        if (_.has(a, key)) {
-          size++;
-          if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;
-        }
-      }
-      if (result) {
-        for (key in b) {
-          if (_.has(b, key) && !(size--)) break;
-        }
-        result = !size;
-      }
-    }
-    aStack.pop();
-    bStack.pop();
-    return result;
-  };
-  _.isEqual = function(a, b) {
-    return eq(a, b, [], []);
-  };
-  _.isEmpty = function(obj) {
-    if (obj == null) return true;
-    if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
-    for (var key in obj) if (_.has(obj, key)) return false;
-    return true;
-  };
-  _.isElement = function(obj) {
-    return !!(obj && obj.nodeType === 1);
-  };
-  _.isArray = nativeIsArray || function(obj) {
-    return toString.call(obj) == '[object Array]';
-  };
-  _.isObject = function(obj) {
-    return obj === Object(obj);
-  };
-  each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {
-    _['is' + name] = function(obj) {
-      return toString.call(obj) == '[object ' + name + ']';
-    };
-  });
-  if (!_.isArguments(arguments)) {
-    _.isArguments = function(obj) {
-      return !!(obj && _.has(obj, 'callee'));
-    };
-  }
-  if (typeof (/./) !== 'function') {
-    _.isFunction = function(obj) {
-      return typeof obj === 'function';
-    };
-  }
-  _.isFinite = fu

<TRUNCATED>

[42/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_server.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_server.erl b/apps/couch/src/couch_server.erl
deleted file mode 100644
index 4b80dfb..0000000
--- a/apps/couch/src/couch_server.erl
+++ /dev/null
@@ -1,493 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_server).
--behaviour(gen_server).
-
--export([open/2,create/2,delete/2,get_version/0,get_version/1,get_uuid/0]).
--export([all_databases/0, all_databases/2]).
--export([init/1, handle_call/3,sup_start_link/0]).
--export([handle_cast/2,code_change/3,handle_info/2,terminate/2]).
--export([dev_start/0,is_admin/2,has_admins/0,get_stats/0]).
-
--include("couch_db.hrl").
-
--record(server,{
-    root_dir = [],
-    dbname_regexp,
-    max_dbs_open=100,
-    dbs_open=0,
-    start_time=""
-    }).
-
-dev_start() ->
-    couch:stop(),
-    up_to_date = make:all([load, debug_info]),
-    couch:start().
-
-get_version() ->
-    couch:release_version().
-get_version(short) ->
-  %% strip git hash from version string
-  [Version|_Rest] = string:tokens(get_version(), "+"),
-  Version.
-
-
-get_uuid() ->
-    case couch_config:get("couchdb", "uuid", nil) of
-        nil ->
-            UUID = couch_uuids:random(),
-            couch_config:set("couchdb", "uuid", ?b2l(UUID)),
-            UUID;
-        UUID -> ?l2b(UUID)
-    end.
-
-get_stats() ->
-    {ok, #server{start_time=Time,dbs_open=Open}} =
-            gen_server:call(couch_server, get_server),
-    [{start_time, ?l2b(Time)}, {dbs_open, Open}].
-
-sup_start_link() ->
-    gen_server:start_link({local, couch_server}, couch_server, [], []).
-
-open(DbName, Options0) ->
-    Options = maybe_add_sys_db_callbacks(DbName, Options0),
-    case gen_server:call(couch_server, {open, DbName, Options}, infinity) of
-    {ok, Db} ->
-        Ctx = couch_util:get_value(user_ctx, Options, #user_ctx{}),
-        {ok, Db#db{user_ctx=Ctx}};
-    Error ->
-        Error
-    end.
-
-create(DbName, Options0) ->
-    Options = maybe_add_sys_db_callbacks(DbName, Options0),
-    case gen_server:call(couch_server, {create, DbName, Options}, infinity) of
-    {ok, Db} ->
-        Ctx = couch_util:get_value(user_ctx, Options, #user_ctx{}),
-        {ok, Db#db{user_ctx=Ctx}};
-    Error ->
-        Error
-    end.
-
-delete(DbName, Options) ->
-    gen_server:call(couch_server, {delete, DbName, Options}, infinity).
-
-maybe_add_sys_db_callbacks(DbName, Options) when is_binary(DbName) ->
-    maybe_add_sys_db_callbacks(?b2l(DbName), Options);
-maybe_add_sys_db_callbacks(DbName, Options) ->
-    case couch_config:get("replicator", "db", "_replicator") of
-    DbName ->
-        [
-            {before_doc_update, fun couch_replicator_manager:before_doc_update/2},
-            {after_doc_read, fun couch_replicator_manager:after_doc_read/2},
-            sys_db | Options
-        ];
-    _ ->
-        case couch_config:get("couch_httpd_auth", "authentication_db", "_users") of
-        DbName ->
-        [
-            {before_doc_update, fun couch_users_db:before_doc_update/2},
-            {after_doc_read, fun couch_users_db:after_doc_read/2},
-            sys_db | Options
-        ];
-        _ ->
-            Options
-        end
-    end.
-
-check_dbname(#server{dbname_regexp=RegExp}, DbName) ->
-    case re:run(DbName, RegExp, [{capture, none}]) of
-    nomatch ->
-        case DbName of
-            "_users" -> ok;
-            "_replicator" -> ok;
-            _Else ->
-                {error, illegal_database_name, DbName}
-            end;
-    match ->
-        ok
-    end.
-
-is_admin(User, ClearPwd) ->
-    case couch_config:get("admins", User) of
-    "-hashed-" ++ HashedPwdAndSalt ->
-        [HashedPwd, Salt] = string:tokens(HashedPwdAndSalt, ","),
-        couch_util:to_hex(crypto:sha(ClearPwd ++ Salt)) == HashedPwd;
-    _Else ->
-        false
-    end.
-
-has_admins() ->
-    couch_config:get("admins") /= [].
-
-get_full_filename(Server, DbName) ->
-    filename:join([Server#server.root_dir, "./" ++ DbName ++ ".couch"]).
-
-hash_admin_passwords() ->
-    hash_admin_passwords(true).
-
-hash_admin_passwords(Persist) ->
-    lists:foreach(
-        fun({User, ClearPassword}) ->
-            HashedPassword = couch_passwords:hash_admin_password(ClearPassword),
-            couch_config:set("admins", User, ?b2l(HashedPassword), Persist)
-        end, couch_passwords:get_unhashed_admins()).
-
-init([]) ->
-    % read config and register for configuration changes
-
-    % just stop if one of the config settings change. couch_server_sup
-    % will restart us and then we will pick up the new settings.
-
-    RootDir = couch_config:get("couchdb", "database_dir", "."),
-    MaxDbsOpen = list_to_integer(
-            couch_config:get("couchdb", "max_dbs_open")),
-    Self = self(),
-    ok = couch_config:register(
-        fun("couchdb", "database_dir") ->
-            exit(Self, config_change)
-        end),
-    ok = couch_config:register(
-        fun("couchdb", "max_dbs_open", Max) ->
-            gen_server:call(couch_server,
-                    {set_max_dbs_open, list_to_integer(Max)})
-        end),
-    ok = couch_file:init_delete_dir(RootDir),
-    hash_admin_passwords(),
-    ok = couch_config:register(
-        fun("admins", _Key, _Value, Persist) ->
-            % spawn here so couch_config doesn't try to call itself
-            spawn(fun() -> hash_admin_passwords(Persist) end)
-        end, false),
-    {ok, RegExp} = re:compile("^[a-z][a-z0-9\\_\\$()\\+\\-\\/]*$"),
-    ets:new(couch_dbs_by_name, [set, private, named_table]),
-    ets:new(couch_dbs_by_pid, [set, private, named_table]),
-    ets:new(couch_dbs_by_lru, [ordered_set, private, named_table]),
-    ets:new(couch_sys_dbs, [set, private, named_table]),
-    process_flag(trap_exit, true),
-    {ok, #server{root_dir=RootDir,
-                dbname_regexp=RegExp,
-                max_dbs_open=MaxDbsOpen,
-                start_time=couch_util:rfc1123_date()}}.
-
-terminate(_Reason, _Srv) ->
-    lists:foreach(
-        fun({_, {_, Pid, _}}) ->
-                couch_util:shutdown_sync(Pid)
-        end,
-        ets:tab2list(couch_dbs_by_name)).
-
-all_databases() ->
-    {ok, DbList} = all_databases(
-        fun(DbName, Acc) -> {ok, [DbName | Acc]} end, []),
-    {ok, lists:usort(DbList)}.
-
-all_databases(Fun, Acc0) ->
-    {ok, #server{root_dir=Root}} = gen_server:call(couch_server, get_server),
-    NormRoot = couch_util:normpath(Root),
-    FinalAcc = try
-        filelib:fold_files(Root, "^[a-z0-9\\_\\$()\\+\\-]*[\\.]couch$", true,
-            fun(Filename, AccIn) ->
-                NormFilename = couch_util:normpath(Filename),
-                case NormFilename -- NormRoot of
-                [$/ | RelativeFilename] -> ok;
-                RelativeFilename -> ok
-                end,
-                case Fun(?l2b(filename:rootname(RelativeFilename, ".couch")), AccIn) of
-                {ok, NewAcc} -> NewAcc;
-                {stop, NewAcc} -> throw({stop, Fun, NewAcc})
-                end
-            end, Acc0)
-    catch throw:{stop, Fun, Acc1} ->
-         Acc1
-    end,
-    {ok, FinalAcc}.
-
-
-maybe_close_lru_db(#server{dbs_open=NumOpen, max_dbs_open=MaxOpen}=Server)
-        when NumOpen < MaxOpen ->
-    {ok, Server};
-maybe_close_lru_db(#server{dbs_open=NumOpen}=Server) ->
-    % must free up the lru db.
-    case try_close_lru(now()) of
-    ok ->
-        {ok, Server#server{dbs_open=NumOpen - 1}};
-    Error -> Error
-    end.
-
-try_close_lru(StartTime) ->
-    LruTime = get_lru(),
-    if LruTime > StartTime ->
-        % this means we've looped through all our opened dbs and found them
-        % all in use.
-        {error, all_dbs_active};
-    true ->
-        [{_, DbName}] = ets:lookup(couch_dbs_by_lru, LruTime),
-        [{_, {opened, MainPid, LruTime}}] = ets:lookup(couch_dbs_by_name, DbName),
-        case couch_db:is_idle(MainPid) of
-        true ->
-            ok = shutdown_idle_db(DbName, MainPid, LruTime);
-        false ->
-            % this still has referrers. Go ahead and give it a current lru time
-            % and try the next one in the table.
-            NewLruTime = now(),
-            true = ets:insert(couch_dbs_by_name, {DbName, {opened, MainPid, NewLruTime}}),
-            true = ets:insert(couch_dbs_by_pid, {MainPid, DbName}),
-            true = ets:delete(couch_dbs_by_lru, LruTime),
-            true = ets:insert(couch_dbs_by_lru, {NewLruTime, DbName}),
-            try_close_lru(StartTime)
-        end
-    end.
-
-get_lru() ->
-    get_lru(ets:first(couch_dbs_by_lru)).
-
-get_lru(LruTime) ->
-    [{LruTime, DbName}] = ets:lookup(couch_dbs_by_lru, LruTime),
-    case ets:member(couch_sys_dbs, DbName) of
-    false ->
-        LruTime;
-    true ->
-        [{_, {opened, MainPid, _}}] = ets:lookup(couch_dbs_by_name, DbName),
-        case couch_db:is_idle(MainPid) of
-        true ->
-            NextLru = ets:next(couch_dbs_by_lru, LruTime),
-            ok = shutdown_idle_db(DbName, MainPid, LruTime),
-            get_lru(NextLru);
-        false ->
-            get_lru(ets:next(couch_dbs_by_lru, LruTime))
-        end
-    end.
-
-shutdown_idle_db(DbName, MainPid, LruTime) ->
-    couch_util:shutdown_sync(MainPid),
-    true = ets:delete(couch_dbs_by_lru, LruTime),
-    true = ets:delete(couch_dbs_by_name, DbName),
-    true = ets:delete(couch_dbs_by_pid, MainPid),
-    true = ets:delete(couch_sys_dbs, DbName),
-    ok.
-
-open_async(Server, From, DbName, Filepath, Options) ->
-    Parent = self(),
-    Opener = spawn_link(fun() ->
-            Res = couch_db:start_link(DbName, Filepath, Options),
-            gen_server:call(
-                Parent, {open_result, DbName, Res, Options}, infinity
-            ),
-            unlink(Parent),
-            case Res of
-            {ok, DbReader} ->
-                unlink(DbReader);
-            _ ->
-                ok
-            end
-        end),
-    true = ets:insert(couch_dbs_by_name, {DbName, {opening, Opener, [From]}}),
-    true = ets:insert(couch_dbs_by_pid, {Opener, DbName}),
-    DbsOpen = case lists:member(sys_db, Options) of
-    true ->
-        true = ets:insert(couch_sys_dbs, {DbName, true}),
-        Server#server.dbs_open;
-    false ->
-        Server#server.dbs_open + 1
-    end,
-    Server#server{dbs_open = DbsOpen}.
-
-handle_call({set_max_dbs_open, Max}, _From, Server) ->
-    {reply, ok, Server#server{max_dbs_open=Max}};
-handle_call(get_server, _From, Server) ->
-    {reply, {ok, Server}, Server};
-handle_call({open_result, DbName, {ok, OpenedDbPid}, Options}, _From, Server) ->
-    link(OpenedDbPid),
-    [{DbName, {opening,Opener,Froms}}] = ets:lookup(couch_dbs_by_name, DbName),
-    lists:foreach(fun({FromPid,_}=From) ->
-        gen_server:reply(From,
-                catch couch_db:open_ref_counted(OpenedDbPid, FromPid))
-    end, Froms),
-    LruTime = now(),
-    true = ets:insert(couch_dbs_by_name,
-            {DbName, {opened, OpenedDbPid, LruTime}}),
-    true = ets:delete(couch_dbs_by_pid, Opener),
-    true = ets:insert(couch_dbs_by_pid, {OpenedDbPid, DbName}),
-    true = ets:insert(couch_dbs_by_lru, {LruTime, DbName}),
-    case lists:member(create, Options) of
-    true ->
-        couch_db_update_notifier:notify({created, DbName});
-    false ->
-        ok
-    end,
-    {reply, ok, Server};
-handle_call({open_result, DbName, {error, eexist}, Options}, From, Server) ->
-    handle_call({open_result, DbName, file_exists, Options}, From, Server);
-handle_call({open_result, DbName, Error, Options}, _From, Server) ->
-    [{DbName, {opening,Opener,Froms}}] = ets:lookup(couch_dbs_by_name, DbName),
-    lists:foreach(fun(From) ->
-        gen_server:reply(From, Error)
-    end, Froms),
-    true = ets:delete(couch_dbs_by_name, DbName),
-    true = ets:delete(couch_dbs_by_pid, Opener),
-    DbsOpen = case lists:member(sys_db, Options) of
-    true ->
-        true = ets:delete(couch_sys_dbs, DbName),
-        Server#server.dbs_open;
-    false ->
-        Server#server.dbs_open - 1
-    end,
-    {reply, ok, Server#server{dbs_open = DbsOpen}};
-handle_call({open, DbName, Options}, {FromPid,_}=From, Server) ->
-    LruTime = now(),
-    case ets:lookup(couch_dbs_by_name, DbName) of
-    [] ->
-        open_db(DbName, Server, Options, From);
-    [{_, {opening, Opener, Froms}}] ->
-        true = ets:insert(couch_dbs_by_name, {DbName, {opening, Opener, [From|Froms]}}),
-        {noreply, Server};
-    [{_, {opened, MainPid, PrevLruTime}}] ->
-        true = ets:insert(couch_dbs_by_name, {DbName, {opened, MainPid, LruTime}}),
-        true = ets:delete(couch_dbs_by_lru, PrevLruTime),
-        true = ets:insert(couch_dbs_by_lru, {LruTime, DbName}),
-        {reply, couch_db:open_ref_counted(MainPid, FromPid), Server}
-    end;
-handle_call({create, DbName, Options}, From, Server) ->
-    case ets:lookup(couch_dbs_by_name, DbName) of
-    [] ->
-        open_db(DbName, Server, [create | Options], From);
-    [_AlreadyRunningDb] ->
-        {reply, file_exists, Server}
-    end;
-handle_call({delete, DbName, _Options}, _From, Server) ->
-    DbNameList = binary_to_list(DbName),
-    case check_dbname(Server, DbNameList) of
-    ok ->
-        FullFilepath = get_full_filename(Server, DbNameList),
-        UpdateState =
-        case ets:lookup(couch_dbs_by_name, DbName) of
-        [] -> false;
-        [{_, {opening, Pid, Froms}}] ->
-            couch_util:shutdown_sync(Pid),
-            true = ets:delete(couch_dbs_by_name, DbName),
-            true = ets:delete(couch_dbs_by_pid, Pid),
-            [gen_server:reply(F, not_found) || F <- Froms],
-            true;
-        [{_, {opened, Pid, LruTime}}] ->
-            couch_util:shutdown_sync(Pid),
-            true = ets:delete(couch_dbs_by_name, DbName),
-            true = ets:delete(couch_dbs_by_pid, Pid),
-            true = ets:delete(couch_dbs_by_lru, LruTime),
-            true
-        end,
-        Server2 = case UpdateState of
-        true ->
-            DbsOpen = case ets:member(couch_sys_dbs, DbName) of
-            true ->
-                true = ets:delete(couch_sys_dbs, DbName),
-                Server#server.dbs_open;
-            false ->
-                Server#server.dbs_open - 1
-            end,
-            Server#server{dbs_open = DbsOpen};
-        false ->
-            Server
-        end,
-
-        %% Delete any leftover .compact files.  If we don't do this a subsequent
-        %% request for this DB will try to open the .compact file and use it.
-        couch_file:delete(Server#server.root_dir, FullFilepath ++ ".compact"),
-
-        case couch_file:delete(Server#server.root_dir, FullFilepath) of
-        ok ->
-            couch_db_update_notifier:notify({deleted, DbName}),
-            {reply, ok, Server2};
-        {error, enoent} ->
-            {reply, not_found, Server2};
-        Else ->
-            {reply, Else, Server2}
-        end;
-    Error ->
-        {reply, Error, Server}
-    end.
-
-handle_cast(Msg, _Server) ->
-    exit({unknown_cast_message, Msg}).
-
-code_change(_OldVsn, State, _Extra) ->
-    {ok, State}.
-
-handle_info({'EXIT', _Pid, config_change}, Server) ->
-    {noreply, shutdown, Server};
-handle_info({'EXIT', Pid, Reason}, Server) ->
-    Server2 = case ets:lookup(couch_dbs_by_pid, Pid) of
-    [{Pid, DbName}] ->
-
-        % If the Pid is known, the name should be as well.
-        % If not, that's an error, which is why there is no [] clause.
-        case ets:lookup(couch_dbs_by_name, DbName) of
-        [{_, {opening, Pid, Froms}}] ->
-            Msg = case Reason of
-            snappy_nif_not_loaded ->
-                io_lib:format(
-                    "To open the database `~s`, Apache CouchDB "
-                    "must be built with Erlang OTP R13B04 or higher.",
-                    [DbName]
-                );
-            true ->
-                io_lib:format("Error opening database ~p: ~p", [DbName, Reason])
-            end,
-            ?LOG_ERROR(Msg, []),
-            lists:foreach(
-              fun(F) -> gen_server:reply(F, {bad_otp_release, Msg}) end,
-              Froms
-            );
-        [{_, {opened, Pid, LruTime}}] ->
-            ?LOG_ERROR(
-                "Unexpected exit of database process ~p [~p]: ~p",
-                [Pid, DbName, Reason]
-            ),
-            true = ets:delete(couch_dbs_by_lru, LruTime)
-        end,
-
-        true = ets:delete(couch_dbs_by_pid, DbName),
-        true = ets:delete(couch_dbs_by_name, DbName),
-
-        case ets:lookup(couch_sys_dbs, DbName) of
-        [{DbName, _}] ->
-            true = ets:delete(couch_sys_dbs, DbName),
-            Server;
-        [] ->
-            Server#server{dbs_open = Server#server.dbs_open - 1}
-        end
-    end,
-    {noreply, Server2};
-handle_info(Error, _Server) ->
-    ?LOG_ERROR("Unexpected message, restarting couch_server: ~p", [Error]),
-    exit(kill).
-
-open_db(DbName, Server, Options, From) ->
-    DbNameList = binary_to_list(DbName),
-    case check_dbname(Server, DbNameList) of
-    ok ->
-        Filepath = get_full_filename(Server, DbNameList),
-        case lists:member(sys_db, Options) of
-        true ->
-            {noreply, open_async(Server, From, DbName, Filepath, Options)};
-        false ->
-            case maybe_close_lru_db(Server) of
-            {ok, Server2} ->
-                {noreply, open_async(Server2, From, DbName, Filepath, Options)};
-            CloseError ->
-                {reply, CloseError, Server}
-            end
-        end;
-     Error ->
-        {reply, Error, Server}
-     end.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_server_sup.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_server_sup.erl b/apps/couch/src/couch_server_sup.erl
deleted file mode 100644
index be3c3a3..0000000
--- a/apps/couch/src/couch_server_sup.erl
+++ /dev/null
@@ -1,164 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_server_sup).
--behaviour(supervisor).
-
-
--export([start_link/1,stop/0, couch_config_start_link_wrapper/2,
-        restart_core_server/0, config_change/2]).
-
--include("couch_db.hrl").
-
-%% supervisor callbacks
--export([init/1]).
-
-start_link(IniFiles) ->
-    case whereis(couch_server_sup) of
-    undefined ->
-        start_server(IniFiles);
-    _Else ->
-        {error, already_started}
-    end.
-
-restart_core_server() ->
-    init:restart().
-
-couch_config_start_link_wrapper(IniFiles, FirstConfigPid) ->
-    case is_process_alive(FirstConfigPid) of
-        true ->
-            link(FirstConfigPid),
-            {ok, FirstConfigPid};
-        false -> couch_config:start_link(IniFiles)
-    end.
-
-start_server(IniFiles) ->
-    case init:get_argument(pidfile) of
-    {ok, [PidFile]} ->
-        case file:write_file(PidFile, os:getpid()) of
-        ok -> ok;
-        {error, Reason} ->
-            io:format("Failed to write PID file ~s: ~s",
-                [PidFile, file:format_error(Reason)])
-        end;
-    _ -> ok
-    end,
-
-    {ok, ConfigPid} = couch_config:start_link(IniFiles),
-
-    LogLevel = couch_config:get("log", "level", "info"),
-    % announce startup
-    io:format("Apache CouchDB ~s (LogLevel=~s) is starting.~n", [
-        couch_server:get_version(),
-        LogLevel
-    ]),
-    case LogLevel of
-    "debug" ->
-        io:format("Configuration Settings ~p:~n", [IniFiles]),
-        [io:format("  [~s] ~s=~p~n", [Module, Variable, Value])
-            || {{Module, Variable}, Value} <- couch_config:all()];
-    _ -> ok
-    end,
-
-    BaseChildSpecs =
-    {{one_for_all, 10, 3600},
-        [{couch_config,
-            {couch_server_sup, couch_config_start_link_wrapper, [IniFiles, ConfigPid]},
-            permanent,
-            brutal_kill,
-            worker,
-            [couch_config]},
-        {couch_primary_services,
-            {couch_primary_sup, start_link, []},
-            permanent,
-            infinity,
-            supervisor,
-            [couch_primary_sup]},
-        {couch_secondary_services,
-            {couch_secondary_sup, start_link, []},
-            permanent,
-            infinity,
-            supervisor,
-            [couch_secondary_sup]}
-        ]},
-
-    % ensure these applications are running
-    application:start(ibrowse),
-    application:start(crypto),
-
-    {ok, Pid} = supervisor:start_link(
-        {local, couch_server_sup}, couch_server_sup, BaseChildSpecs),
-
-    % launch the icu bridge
-    % just restart if one of the config settings change.
-    couch_config:register(fun ?MODULE:config_change/2, Pid),
-
-    unlink(ConfigPid),
-
-    Ip = couch_config:get("httpd", "bind_address"),
-    io:format("Apache CouchDB has started. Time to relax.~n"),
-    Uris = [get_uri(Name, Ip) || Name <- [couch_httpd, https]],
-    [begin
-        case Uri of
-            undefined -> ok;
-            Uri -> ?LOG_INFO("Apache CouchDB has started on ~s", [Uri])
-        end
-    end
-    || Uri <- Uris],
-    case couch_config:get("couchdb", "uri_file", null) of 
-    null -> ok;
-    UriFile ->
-        Lines = [begin case Uri of
-            undefined -> [];
-            Uri -> io_lib:format("~s~n", [Uri])
-            end end || Uri <- Uris],
-        case file:write_file(UriFile, Lines) of
-        ok -> ok;
-        {error, Reason2} = Error ->
-            ?LOG_ERROR("Failed to write to URI file ~s: ~s",
-                [UriFile, file:format_error(Reason2)]),
-            throw(Error)
-        end
-    end,
-
-    {ok, Pid}.
-
-stop() ->
-    catch exit(whereis(couch_server_sup), normal).
-
-config_change("daemons", _) ->
-    supervisor:terminate_child(couch_server_sup, couch_secondary_services),
-    supervisor:restart_child(couch_server_sup, couch_secondary_services);
-config_change("couchdb", "util_driver_dir") ->
-    init:restart().
-
-init(ChildSpecs) ->
-    {ok, ChildSpecs}.
-
-get_uri(Name, Ip) ->
-    case get_port(Name) of
-        undefined ->
-            undefined;
-        Port ->
-            io_lib:format("~s://~s:~w/", [get_scheme(Name), Ip, Port])
-    end.
-
-get_scheme(couch_httpd) -> "http";
-get_scheme(https) -> "https".
-
-get_port(Name) ->
-    try
-        mochiweb_socket_server:get(Name, port)
-    catch
-        exit:{noproc, _}->
-            undefined
-    end.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_stats_aggregator.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_stats_aggregator.erl b/apps/couch/src/couch_stats_aggregator.erl
deleted file mode 100644
index 6090355..0000000
--- a/apps/couch/src/couch_stats_aggregator.erl
+++ /dev/null
@@ -1,297 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_stats_aggregator).
--behaviour(gen_server).
-
--export([start/0, start/1, stop/0]).
--export([all/0, all/1, get/1, get/2, get_json/1, get_json/2, collect_sample/0]).
-
--export([init/1, terminate/2, code_change/3]).
--export([handle_call/3, handle_cast/2, handle_info/2]).
-
--record(aggregate, {
-    description = <<"">>,
-    seconds = 0,
-    count = 0,
-    current = null,
-    sum = null,
-    mean = null,
-    variance = null,
-    stddev = null,
-    min = null,
-    max = null,
-    samples = []
-}).
-
-
-start() ->
-    PrivDir = couch_util:priv_dir(),
-    start(filename:join(PrivDir, "stat_descriptions.cfg")).
-    
-start(FileName) ->
-    gen_server:start_link({local, ?MODULE}, ?MODULE, [FileName], []).
-
-stop() ->
-    gen_server:cast(?MODULE, stop).
-
-all() ->
-    ?MODULE:all(0).
-all(Time) when is_binary(Time) ->
-    ?MODULE:all(list_to_integer(binary_to_list(Time)));
-all(Time) when is_atom(Time) ->
-    ?MODULE:all(list_to_integer(atom_to_list(Time)));
-all(Time) when is_integer(Time) ->
-    Aggs = ets:match(?MODULE, {{'$1', Time}, '$2'}),
-    Stats = lists:map(fun([Key, Agg]) -> {Key, Agg} end, Aggs),
-    case Stats of
-        [] ->
-            {[]};
-        _ ->
-            Ret = lists:foldl(fun({{Mod, Key}, Agg}, Acc) ->
-                CurrKeys = case proplists:lookup(Mod, Acc) of
-                    none -> [];
-                    {Mod, {Keys}} -> Keys
-                end,
-                NewMod = {[{Key, to_json_term(Agg)} | CurrKeys]},
-                [{Mod, NewMod} | proplists:delete(Mod, Acc)]
-            end, [], Stats),
-            {Ret}
-    end.
-
-get(Key) ->
-    ?MODULE:get(Key, 0).
-get(Key, Time) when is_binary(Time) ->
-    ?MODULE:get(Key, list_to_integer(binary_to_list(Time)));
-get(Key, Time) when is_atom(Time) ->
-    ?MODULE:get(Key, list_to_integer(atom_to_list(Time)));
-get(Key, Time) when is_integer(Time) ->
-    case ets:lookup(?MODULE, {make_key(Key), Time}) of
-        [] -> #aggregate{seconds=Time};
-        [{_, Agg}] -> Agg
-    end.
-
-get_json(Key) ->
-    get_json(Key, 0).
-get_json(Key, Time) ->
-    to_json_term(?MODULE:get(Key, Time)).
-
-collect_sample() ->
-    gen_server:call(?MODULE, collect_sample, infinity).
-
-
-init(StatDescsFileName) ->
-    % Create an aggregate entry for each {description, rate} pair.
-    ets:new(?MODULE, [named_table, set, protected]),
-    SampleStr = couch_config:get("stats", "samples", "[0]"),
-    {ok, Samples} = couch_util:parse_term(SampleStr),
-    {ok, Descs} = file:consult(StatDescsFileName),
-    lists:foreach(fun({Sect, Key, Value}) ->
-        lists:foreach(fun(Secs) ->
-            Agg = #aggregate{
-                description=list_to_binary(Value),
-                seconds=Secs
-            },
-            ets:insert(?MODULE, {{{Sect, Key}, Secs}, Agg})
-        end, Samples)
-    end, Descs),
-    
-    Self = self(),
-    ok = couch_config:register(
-        fun("stats", _) -> exit(Self, config_change) end
-    ),
-    
-    Rate = list_to_integer(couch_config:get("stats", "rate", "1000")),
-    % TODO: Add timer_start to kernel start options.
-    {ok, TRef} = timer:apply_after(Rate, ?MODULE, collect_sample, []),
-    {ok, {TRef, Rate}}.
-    
-terminate(_Reason, {TRef, _Rate}) ->
-    timer:cancel(TRef),
-    ok.
-
-handle_call(collect_sample, _, {OldTRef, SampleInterval}) ->
-    timer:cancel(OldTRef),
-    {ok, TRef} = timer:apply_after(SampleInterval, ?MODULE, collect_sample, []),
-    % Gather new stats values to add.
-    Incs = lists:map(fun({Key, Value}) ->
-        {Key, {incremental, Value}}
-    end, couch_stats_collector:all(incremental)),
-    Abs = lists:map(fun({Key, Values}) ->
-        couch_stats_collector:clear(Key),
-        Values2 = case Values of
-            X when is_list(X) -> X;
-            Else -> [Else]
-        end,
-        {_, Mean} = lists:foldl(fun(Val, {Count, Curr}) ->
-            {Count+1, Curr + (Val - Curr) / (Count+1)}
-        end, {0, 0}, Values2),
-        {Key, {absolute, Mean}}
-    end, couch_stats_collector:all(absolute)),
-    
-    Values = Incs ++ Abs,
-    Now = erlang:now(),
-    lists:foreach(fun({{Key, Rate}, Agg}) ->
-        NewAgg = case proplists:lookup(Key, Values) of
-            none ->
-                rem_values(Now, Agg);
-            {Key, {Type, Value}} ->
-                NewValue = new_value(Type, Value, Agg#aggregate.current),
-                Agg2 = add_value(Now, NewValue, Agg),
-                rem_values(Now, Agg2)
-        end,
-        ets:insert(?MODULE, {{Key, Rate}, NewAgg})
-    end, ets:tab2list(?MODULE)),
-    {reply, ok, {TRef, SampleInterval}}.
-
-handle_cast(stop, State) ->
-    {stop, normal, State}.
-
-handle_info(_Info, State) ->
-    {noreply, State}.
-
-code_change(_OldVersion, State, _Extra) ->
-    {ok, State}.
-
-
-new_value(incremental, Value, null) ->
-    Value;
-new_value(incremental, Value, Current) ->
-    Value - Current;
-new_value(absolute, Value, _Current) ->
-    Value.
-
-add_value(Time, Value, #aggregate{count=Count, seconds=Secs}=Agg) when Count < 1 ->
-    Samples = case Secs of
-        0 -> [];
-        _ -> [{Time, Value}]
-    end,
-    Agg#aggregate{
-        count=1,
-        current=Value,
-        sum=Value,
-        mean=Value,
-        variance=0.0,
-        stddev=null,
-        min=Value,
-        max=Value,
-        samples=Samples
-    };
-add_value(Time, Value, Agg) ->
-    #aggregate{
-        count=Count,
-        current=Current,
-        sum=Sum,
-        mean=Mean,
-        variance=Variance,
-        samples=Samples
-    } = Agg,
-    
-    NewCount = Count + 1,
-    NewMean = Mean + (Value - Mean) / NewCount,
-    NewVariance = Variance + (Value - Mean) * (Value - NewMean),
-    StdDev = case NewCount > 1 of
-        false -> null;
-        _ -> math:sqrt(NewVariance / (NewCount - 1))
-    end,
-    Agg2 = Agg#aggregate{
-        count=NewCount,
-        current=Current + Value,
-        sum=Sum + Value,
-        mean=NewMean,
-        variance=NewVariance,
-        stddev=StdDev,
-        min=lists:min([Agg#aggregate.min, Value]),
-        max=lists:max([Agg#aggregate.max, Value])
-    },
-    case Agg2#aggregate.seconds of
-        0 -> Agg2;
-        _ -> Agg2#aggregate{samples=[{Time, Value} | Samples]}
-    end.
-
-rem_values(Time, Agg) ->
-    Seconds = Agg#aggregate.seconds,
-    Samples = Agg#aggregate.samples,
-    Pred = fun({When, _Value}) ->
-        timer:now_diff(Time, When) =< (Seconds * 1000000)
-    end,
-    {Keep, Remove} = lists:splitwith(Pred, Samples),
-    Agg2 = lists:foldl(fun({_, Value}, Acc) ->
-        rem_value(Value, Acc)
-    end, Agg, Remove),
-    Agg2#aggregate{samples=Keep}.
-
-rem_value(_Value, #aggregate{count=Count, seconds=Secs}) when Count =< 1 ->
-    #aggregate{seconds=Secs};
-rem_value(Value, Agg) ->
-    #aggregate{
-        count=Count,
-        sum=Sum,
-        mean=Mean,
-        variance=Variance
-    } = Agg,
-
-    OldMean = (Mean * Count - Value) / (Count - 1),
-    OldVariance = Variance - (Value - OldMean) * (Value - Mean),
-    OldCount = Count - 1,
-    StdDev = case OldCount > 1 of
-        false -> null;
-        _ -> math:sqrt(clamp_value(OldVariance / (OldCount - 1)))
-    end,
-    Agg#aggregate{
-        count=OldCount,
-        sum=Sum-Value,
-        mean=clamp_value(OldMean),
-        variance=clamp_value(OldVariance),
-        stddev=StdDev
-    }.
-
-to_json_term(Agg) ->
-    {Min, Max} = case Agg#aggregate.seconds > 0 of
-        false ->
-            {Agg#aggregate.min, Agg#aggregate.max};
-        _ ->
-            case length(Agg#aggregate.samples) > 0 of
-                true ->
-                    Extract = fun({_Time, Value}) -> Value end,
-                    Samples = lists:map(Extract, Agg#aggregate.samples),
-                    {lists:min(Samples), lists:max(Samples)};
-                _ ->
-                    {null, null}
-            end
-    end,
-    {[
-        {description, Agg#aggregate.description},
-        {current, round_value(Agg#aggregate.sum)},
-        {sum, round_value(Agg#aggregate.sum)},
-        {mean, round_value(Agg#aggregate.mean)},
-        {stddev, round_value(Agg#aggregate.stddev)},
-        {min, Min},
-        {max, Max}
-    ]}.
-
-make_key({Mod, Val}) when is_integer(Val) ->
-    {Mod, list_to_atom(integer_to_list(Val))};
-make_key(Key) ->
-    Key.
-
-round_value(Val) when not is_number(Val) ->
-    Val;
-round_value(Val) when Val == 0 ->
-    Val;
-round_value(Val) ->
-    erlang:round(Val * 1000.0) / 1000.0.
-
-clamp_value(Val) when Val > 0.00000000000001 ->
-    Val;
-clamp_value(_) ->
-    0.0.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_stats_collector.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_stats_collector.erl b/apps/couch/src/couch_stats_collector.erl
deleted file mode 100644
index f7b9bb4..0000000
--- a/apps/couch/src/couch_stats_collector.erl
+++ /dev/null
@@ -1,136 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
-% todo
-% - remove existance check on increment(), decrement() and record(). have
-%   modules initialize counters on startup.
-
--module(couch_stats_collector).
-
--behaviour(gen_server).
-
--export([start/0, stop/0]).
--export([all/0, all/1, get/1, increment/1, decrement/1, record/2, clear/1]).
--export([track_process_count/1, track_process_count/2]).
-
--export([init/1, terminate/2, code_change/3]).
--export([handle_call/3, handle_cast/2, handle_info/2]).
-
--define(HIT_TABLE, stats_hit_table).
--define(ABS_TABLE, stats_abs_table).
-
-start() ->
-    gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
-
-stop() ->
-    gen_server:call(?MODULE, stop).
-
-all() ->
-    ets:tab2list(?HIT_TABLE) ++ abs_to_list().
-
-all(Type) ->
-    case Type of
-        incremental -> ets:tab2list(?HIT_TABLE);
-        absolute -> abs_to_list()
-    end.
-
-get(Key) ->
-    case ets:lookup(?HIT_TABLE, Key) of
-        [] ->
-            case ets:lookup(?ABS_TABLE, Key) of
-                [] ->
-                    nil;
-                AbsVals ->
-                    lists:map(fun({_, Value}) -> Value end, AbsVals)
-            end;
-        [{_, Counter}] ->
-            Counter
-    end.
-
-increment(Key) ->
-    Key2 = make_key(Key),
-    case catch ets:update_counter(?HIT_TABLE, Key2, 1) of
-        {'EXIT', {badarg, _}} ->
-            catch ets:insert(?HIT_TABLE, {Key2, 1}),
-            ok;
-        _ ->
-            ok
-    end.
-
-decrement(Key) ->
-    Key2 = make_key(Key),
-    case catch ets:update_counter(?HIT_TABLE, Key2, -1) of
-        {'EXIT', {badarg, _}} ->
-            catch ets:insert(?HIT_TABLE, {Key2, -1}),
-            ok;
-        _ -> ok
-    end.
-
-record(Key, Value) ->
-    catch ets:insert(?ABS_TABLE, {make_key(Key), Value}).
-
-clear(Key) ->
-    catch ets:delete(?ABS_TABLE, make_key(Key)).
-
-track_process_count(Stat) ->
-    track_process_count(self(), Stat).
-
-track_process_count(Pid, Stat) ->
-    MonitorFun = fun() ->
-        Ref = erlang:monitor(process, Pid),
-        receive {'DOWN', Ref, _, _, _} -> ok end,
-        couch_stats_collector:decrement(Stat)
-    end,
-    case (catch couch_stats_collector:increment(Stat)) of
-        ok -> spawn(MonitorFun);
-        _ -> ok
-    end.
-
-
-init(_) ->
-    ets:new(?HIT_TABLE, [named_table, set, public]),
-    ets:new(?ABS_TABLE, [named_table, duplicate_bag, public]),
-    {ok, nil}.
-
-terminate(_Reason, _State) ->
-    ok.
-
-handle_call(stop, _, State) ->
-    {stop, normal, stopped, State}.
-
-handle_cast(foo, State) ->
-    {noreply, State}.
-
-handle_info(_Info, State) ->
-    {noreply, State}.
-
-code_change(_OldVersion, State, _Extra) ->
-    {ok, State}.
-
-
-make_key({Module, Key}) when is_integer(Key) ->
-    {Module, list_to_atom(integer_to_list(Key))};
-make_key(Key) ->
-    Key.
-
-abs_to_list() ->
-    SortedKVs = lists:sort(ets:tab2list(?ABS_TABLE)),
-    lists:foldl(fun({Key, Val}, Acc) ->
-        case Acc of
-            [] ->
-                [{Key, [Val]}];
-            [{Key, Prev} | Rest] ->
-                [{Key, [Val | Prev]} | Rest];
-            Others ->
-                [{Key, [Val]} | Others]
-        end
-    end, [], SortedKVs).
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_stream.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_stream.erl b/apps/couch/src/couch_stream.erl
deleted file mode 100644
index 959feef..0000000
--- a/apps/couch/src/couch_stream.erl
+++ /dev/null
@@ -1,299 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_stream).
--behaviour(gen_server).
-
-% public API
--export([open/1, open/2, close/1]).
--export([foldl/4, foldl/5, foldl_decode/6, range_foldl/6]).
--export([copy_to_new_stream/3, write/2]).
-
-% gen_server callbacks
--export([init/1, terminate/2, code_change/3]).
--export([handle_cast/2, handle_call/3, handle_info/2]).
-
--include("couch_db.hrl").
-
--define(DEFAULT_BUFFER_SIZE, 4096).
-
--record(stream,
-    {fd = 0,
-    written_pointers=[],
-    buffer_list = [],
-    buffer_len = 0,
-    max_buffer,
-    written_len = 0,
-    md5,
-    % md5 of the content without any transformation applied (e.g. compression)
-    % needed for the attachment upload integrity check (ticket 558)
-    identity_md5,
-    identity_len = 0,
-    encoding_fun,
-    end_encoding_fun
-    }).
-
-
-%%% Interface functions %%%
-
-open(Fd) ->
-    open(Fd, []).
-
-open(Fd, Options) ->
-    gen_server:start_link(couch_stream, {Fd, Options}, []).
-
-close(Pid) ->
-    gen_server:call(Pid, close, infinity).
-
-copy_to_new_stream(Fd, PosList, DestFd) ->
-    {ok, Dest} = open(DestFd),
-    foldl(Fd, PosList,
-        fun(Bin, _) ->
-            ok = write(Dest, Bin)
-        end, ok),
-    close(Dest).
-
-foldl(_Fd, [], _Fun, Acc) ->
-    Acc;
-foldl(Fd, [Pos|Rest], Fun, Acc) ->
-    {ok, Bin} = couch_file:pread_iolist(Fd, Pos),
-    foldl(Fd, Rest, Fun, Fun(Bin, Acc)).
-
-foldl(Fd, PosList, <<>>, Fun, Acc) ->
-    foldl(Fd, PosList, Fun, Acc);
-foldl(Fd, PosList, Md5, Fun, Acc) ->
-    foldl(Fd, PosList, Md5, couch_util:md5_init(), Fun, Acc).
-
-foldl_decode(Fd, PosList, Md5, Enc, Fun, Acc) ->
-    {DecDataFun, DecEndFun} = case Enc of
-    gzip ->
-        ungzip_init();
-    identity ->
-        identity_enc_dec_funs()
-    end,
-    Result = foldl_decode(
-        DecDataFun, Fd, PosList, Md5, couch_util:md5_init(), Fun, Acc
-    ),
-    DecEndFun(),
-    Result.
-
-foldl(_Fd, [], Md5, Md5Acc, _Fun, Acc) ->
-    Md5 = couch_util:md5_final(Md5Acc),
-    Acc;
-foldl(Fd, [{Pos, _Size}], Md5, Md5Acc, Fun, Acc) -> % 0110 UPGRADE CODE
-    foldl(Fd, [Pos], Md5, Md5Acc, Fun, Acc);
-foldl(Fd, [Pos], Md5, Md5Acc, Fun, Acc) ->
-    {ok, Bin} = couch_file:pread_iolist(Fd, Pos),
-    Md5 = couch_util:md5_final(couch_util:md5_update(Md5Acc, Bin)),
-    Fun(Bin, Acc);
-foldl(Fd, [{Pos, _Size}|Rest], Md5, Md5Acc, Fun, Acc) ->
-    foldl(Fd, [Pos|Rest], Md5, Md5Acc, Fun, Acc);
-foldl(Fd, [Pos|Rest], Md5, Md5Acc, Fun, Acc) ->
-    {ok, Bin} = couch_file:pread_iolist(Fd, Pos),
-    foldl(Fd, Rest, Md5, couch_util:md5_update(Md5Acc, Bin), Fun, Fun(Bin, Acc)).
-
-range_foldl(Fd, PosList, From, To, Fun, Acc) ->
-    range_foldl(Fd, PosList, From, To, 0, Fun, Acc).
-
-range_foldl(_Fd, _PosList, _From, To, Off, _Fun, Acc) when Off >= To ->
-    Acc;
-range_foldl(Fd, [Pos|Rest], From, To, Off, Fun, Acc) when is_integer(Pos) -> % old-style attachment
-    {ok, Bin} = couch_file:pread_iolist(Fd, Pos),
-    range_foldl(Fd, [{Pos, iolist_size(Bin)}] ++ Rest, From, To, Off, Fun, Acc);
-range_foldl(Fd, [{_Pos, Size}|Rest], From, To, Off, Fun, Acc) when From > Off + Size ->
-    range_foldl(Fd, Rest, From, To, Off + Size, Fun, Acc);
-range_foldl(Fd, [{Pos, Size}|Rest], From, To, Off, Fun, Acc) ->
-    {ok, Bin} = couch_file:pread_iolist(Fd, Pos),
-    Bin1 = if
-        From =< Off andalso To >= Off + Size -> Bin; %% the whole block is covered
-        true ->
-            PrefixLen = clip(From - Off, 0, Size),
-            PostfixLen = clip(Off + Size - To, 0, Size),
-            MatchLen = Size - PrefixLen - PostfixLen,
-            <<_Prefix:PrefixLen/binary,Match:MatchLen/binary,_Postfix:PostfixLen/binary>> = iolist_to_binary(Bin),
-            Match
-    end,
-    range_foldl(Fd, Rest, From, To, Off + Size, Fun, Fun(Bin1, Acc)).
-
-clip(Value, Lo, Hi) ->
-    if
-        Value < Lo -> Lo;
-        Value > Hi -> Hi;
-        true -> Value
-    end.
-
-foldl_decode(_DecFun, _Fd, [], Md5, Md5Acc, _Fun, Acc) ->
-    Md5 = couch_util:md5_final(Md5Acc),
-    Acc;
-foldl_decode(DecFun, Fd, [{Pos, _Size}], Md5, Md5Acc, Fun, Acc) ->
-    foldl_decode(DecFun, Fd, [Pos], Md5, Md5Acc, Fun, Acc);
-foldl_decode(DecFun, Fd, [Pos], Md5, Md5Acc, Fun, Acc) ->
-    {ok, EncBin} = couch_file:pread_iolist(Fd, Pos),
-    Md5 = couch_util:md5_final(couch_util:md5_update(Md5Acc, EncBin)),
-    Bin = DecFun(EncBin),
-    Fun(Bin, Acc);
-foldl_decode(DecFun, Fd, [{Pos, _Size}|Rest], Md5, Md5Acc, Fun, Acc) ->
-    foldl_decode(DecFun, Fd, [Pos|Rest], Md5, Md5Acc, Fun, Acc);
-foldl_decode(DecFun, Fd, [Pos|Rest], Md5, Md5Acc, Fun, Acc) ->
-    {ok, EncBin} = couch_file:pread_iolist(Fd, Pos),
-    Bin = DecFun(EncBin),
-    Md5Acc2 = couch_util:md5_update(Md5Acc, EncBin),
-    foldl_decode(DecFun, Fd, Rest, Md5, Md5Acc2, Fun, Fun(Bin, Acc)).
-
-gzip_init(Options) ->
-    case couch_util:get_value(compression_level, Options, 0) of
-    Lvl when Lvl >= 1 andalso Lvl =< 9 ->
-        Z = zlib:open(),
-        % 15 = ?MAX_WBITS (defined in the zlib module)
-        % the 16 + ?MAX_WBITS formula was obtained by inspecting zlib:gzip/1
-        ok = zlib:deflateInit(Z, Lvl, deflated, 16 + 15, 8, default),
-        {
-            fun(Data) ->
-                zlib:deflate(Z, Data)
-            end,
-            fun() ->
-                Last = zlib:deflate(Z, [], finish),
-                ok = zlib:deflateEnd(Z),
-                ok = zlib:close(Z),
-                Last
-            end
-        };
-    _ ->
-        identity_enc_dec_funs()
-    end.
-
-ungzip_init() ->
-    Z = zlib:open(),
-    zlib:inflateInit(Z, 16 + 15),
-    {
-        fun(Data) ->
-            zlib:inflate(Z, Data)
-        end,
-        fun() ->
-            ok = zlib:inflateEnd(Z),
-            ok = zlib:close(Z)
-        end
-    }.
-
-identity_enc_dec_funs() ->
-    {
-        fun(Data) -> Data end,
-        fun() -> [] end
-    }.
-
-write(_Pid, <<>>) ->
-    ok;
-write(Pid, Bin) ->
-    gen_server:call(Pid, {write, Bin}, infinity).
-
-
-init({Fd, Options}) ->
-    {EncodingFun, EndEncodingFun} =
-    case couch_util:get_value(encoding, Options, identity) of
-    identity ->
-        identity_enc_dec_funs();
-    gzip ->
-        gzip_init(Options)
-    end,
-    {ok, #stream{
-            fd=Fd,
-            md5=couch_util:md5_init(),
-            identity_md5=couch_util:md5_init(),
-            encoding_fun=EncodingFun,
-            end_encoding_fun=EndEncodingFun,
-            max_buffer=couch_util:get_value(
-                buffer_size, Options, ?DEFAULT_BUFFER_SIZE)
-        }
-    }.
-
-terminate(_Reason, _Stream) ->
-    ok.
-
-handle_call({write, Bin}, _From, Stream) ->
-    BinSize = iolist_size(Bin),
-    #stream{
-        fd = Fd,
-        written_len = WrittenLen,
-        written_pointers = Written,
-        buffer_len = BufferLen,
-        buffer_list = Buffer,
-        max_buffer = Max,
-        md5 = Md5,
-        identity_md5 = IdenMd5,
-        identity_len = IdenLen,
-        encoding_fun = EncodingFun} = Stream,
-    if BinSize + BufferLen > Max ->
-        WriteBin = lists:reverse(Buffer, [Bin]),
-        IdenMd5_2 = couch_util:md5_update(IdenMd5, WriteBin),
-        case EncodingFun(WriteBin) of
-        [] ->
-            % case where the encoder did some internal buffering
-            % (zlib does it for example)
-            WrittenLen2 = WrittenLen,
-            Md5_2 = Md5,
-            Written2 = Written;
-        WriteBin2 ->
-            {ok, Pos, _} = couch_file:append_binary(Fd, WriteBin2),
-            WrittenLen2 = WrittenLen + iolist_size(WriteBin2),
-            Md5_2 = couch_util:md5_update(Md5, WriteBin2),
-            Written2 = [{Pos, iolist_size(WriteBin2)}|Written]
-        end,
-
-        {reply, ok, Stream#stream{
-                        written_len=WrittenLen2,
-                        written_pointers=Written2,
-                        buffer_list=[],
-                        buffer_len=0,
-                        md5=Md5_2,
-                        identity_md5=IdenMd5_2,
-                        identity_len=IdenLen + BinSize}};
-    true ->
-        {reply, ok, Stream#stream{
-                        buffer_list=[Bin|Buffer],
-                        buffer_len=BufferLen + BinSize,
-                        identity_len=IdenLen + BinSize}}
-    end;
-handle_call(close, _From, Stream) ->
-    #stream{
-        fd = Fd,
-        written_len = WrittenLen,
-        written_pointers = Written,
-        buffer_list = Buffer,
-        md5 = Md5,
-        identity_md5 = IdenMd5,
-        identity_len = IdenLen,
-        encoding_fun = EncodingFun,
-        end_encoding_fun = EndEncodingFun} = Stream,
-
-    WriteBin = lists:reverse(Buffer),
-    IdenMd5Final = couch_util:md5_final(couch_util:md5_update(IdenMd5, WriteBin)),
-    WriteBin2 = EncodingFun(WriteBin) ++ EndEncodingFun(),
-    Md5Final = couch_util:md5_final(couch_util:md5_update(Md5, WriteBin2)),
-    Result = case WriteBin2 of
-    [] ->
-        {lists:reverse(Written), WrittenLen, IdenLen, Md5Final, IdenMd5Final};
-    _ ->
-        {ok, Pos, _} = couch_file:append_binary(Fd, WriteBin2),
-        StreamInfo = lists:reverse(Written, [{Pos, iolist_size(WriteBin2)}]),
-        StreamLen = WrittenLen + iolist_size(WriteBin2),
-        {StreamInfo, StreamLen, IdenLen, Md5Final, IdenMd5Final}
-    end,
-    {stop, normal, Result, Stream}.
-
-handle_cast(_Msg, State) ->
-    {noreply,State}.
-
-code_change(_OldVsn, State, _Extra) ->
-    {ok, State}.
-
-handle_info(_Info, State) ->
-    {noreply, State}.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_task_status.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_task_status.erl b/apps/couch/src/couch_task_status.erl
deleted file mode 100644
index e23b560..0000000
--- a/apps/couch/src/couch_task_status.erl
+++ /dev/null
@@ -1,151 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_task_status).
--behaviour(gen_server).
-
-% This module is used to track the status of long running tasks.
-% Long running tasks register themselves, via a call to add_task/1, and then
-% update their status properties via update/1. The status of a task is a
-% list of properties. Each property is a tuple, with the first element being
-% either an atom or a binary and the second element must be an EJSON value. When
-% a task updates its status, it can override some or all of its properties.
-% The properties {started_on, UnitTimestamp}, {updated_on, UnixTimestamp} and
-% {pid, ErlangPid} are automatically added by this module.
-% When a tracked task dies, its status will be automatically removed from
-% memory. To get the tasks list, call the all/0 function.
-
--export([start_link/0, stop/0]).
--export([all/0, add_task/1, update/1, get/1, set_update_frequency/1]).
--export([is_task_added/0]).
-
--export([init/1, terminate/2, code_change/3]).
--export([handle_call/3, handle_cast/2, handle_info/2]).
-
--include("couch_db.hrl").
-
--define(set(L, K, V), lists:keystore(K, 1, L, {K, V})).
-
-
-start_link() ->
-    gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
-
-
-stop() ->
-    gen_server:cast(?MODULE, stop).
-
-
-all() ->
-    gen_server:call(?MODULE, all).
-
-
-add_task(Props) ->
-    put(task_status_update, {{0, 0, 0}, 0}),
-    Ts = timestamp(),
-    TaskProps = lists:ukeysort(
-        1, [{started_on, Ts}, {updated_on, Ts} | Props]),
-    put(task_status_props, TaskProps),
-    gen_server:call(?MODULE, {add_task, TaskProps}).
-
-
-is_task_added() ->
-    is_list(erlang:get(task_status_props)).
-
-
-set_update_frequency(Msecs) ->
-    put(task_status_update, {{0, 0, 0}, Msecs * 1000}).
-
-
-update(Props) ->
-    MergeProps = lists:ukeysort(1, Props),
-    TaskProps = lists:ukeymerge(1, MergeProps, erlang:get(task_status_props)),
-    put(task_status_props, TaskProps),
-    maybe_persist(TaskProps).
-
-
-get(Props) when is_list(Props) ->
-    TaskProps = erlang:get(task_status_props),
-    [couch_util:get_value(P, TaskProps) || P <- Props];
-get(Prop) ->
-    TaskProps = erlang:get(task_status_props),
-    couch_util:get_value(Prop, TaskProps).
-
-
-maybe_persist(TaskProps0) ->
-    {LastUpdateTime, Frequency} = erlang:get(task_status_update),
-    case timer:now_diff(Now = now(), LastUpdateTime) >= Frequency of
-    true ->
-        put(task_status_update, {Now, Frequency}),
-        TaskProps = ?set(TaskProps0, updated_on, timestamp(Now)),
-        gen_server:cast(?MODULE, {update_status, self(), TaskProps});
-    false ->
-        ok
-    end.
-
-
-init([]) ->
-    % read configuration settings and register for configuration changes
-    ets:new(?MODULE, [ordered_set, protected, named_table]),
-    {ok, nil}.
-
-
-terminate(_Reason,_State) ->
-    ok.
-
-
-handle_call({add_task, TaskProps}, {From, _}, Server) ->
-    case ets:lookup(?MODULE, From) of
-    [] ->
-        true = ets:insert(?MODULE, {From, TaskProps}),
-        erlang:monitor(process, From),
-        {reply, ok, Server};
-    [_] ->
-        {reply, {add_task_error, already_registered}, Server}
-    end;
-handle_call(all, _, Server) ->
-    All = [
-        [{pid, ?l2b(pid_to_list(Pid))} | TaskProps]
-        ||
-        {Pid, TaskProps} <- ets:tab2list(?MODULE)
-    ],
-    {reply, All, Server}.
-
-
-handle_cast({update_status, Pid, NewProps}, Server) ->
-    case ets:lookup(?MODULE, Pid) of
-    [{Pid, _CurProps}] ->
-        ?LOG_DEBUG("New task status for ~p: ~p", [Pid, NewProps]),
-        true = ets:insert(?MODULE, {Pid, NewProps});
-    _ ->
-        % Task finished/died in the meanwhile and we must have received
-        % a monitor message before this call - ignore.
-        ok
-    end,
-    {noreply, Server};
-handle_cast(stop, State) ->
-    {stop, normal, State}.
-
-handle_info({'DOWN', _MonitorRef, _Type, Pid, _Info}, Server) ->
-    %% should we also erlang:demonitor(_MonitorRef), ?
-    ets:delete(?MODULE, Pid),
-    {noreply, Server}.
-
-
-code_change(_OldVsn, State, _Extra) ->
-    {ok, State}.
-
-
-timestamp() ->
-    timestamp(now()).
-
-timestamp({Mega, Secs, _}) ->
-    Mega * 1000000 + Secs.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_users_db.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_users_db.erl b/apps/couch/src/couch_users_db.erl
deleted file mode 100644
index 9b875ba..0000000
--- a/apps/couch/src/couch_users_db.erl
+++ /dev/null
@@ -1,121 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_users_db).
-
--export([before_doc_update/2, after_doc_read/2, strip_non_public_fields/1]).
-
--include("couch_db.hrl").
-
--define(NAME, <<"name">>).
--define(PASSWORD, <<"password">>).
--define(DERIVED_KEY, <<"derived_key">>).
--define(PASSWORD_SCHEME, <<"password_scheme">>).
--define(PBKDF2, <<"pbkdf2">>).
--define(ITERATIONS, <<"iterations">>).
--define(SALT, <<"salt">>).
--define(replace(L, K, V), lists:keystore(K, 1, L, {K, V})).
-
-% If the request's userCtx identifies an admin
-%   -> save_doc (see below)
-%
-% If the request's userCtx.name is null:
-%   -> save_doc
-%   // this is an anonymous user registering a new document
-%   // in case a user doc with the same id already exists, the anonymous
-%   // user will get a regular doc update conflict.
-% If the request's userCtx.name doesn't match the doc's name
-%   -> 404 // Not Found
-% Else
-%   -> save_doc
-before_doc_update(Doc, #db{user_ctx = UserCtx} = Db) ->
-    #user_ctx{name=Name} = UserCtx,
-    DocName = get_doc_name(Doc),
-    case (catch couch_db:check_is_admin(Db)) of
-    ok ->
-        save_doc(Doc);
-    _ when Name =:= DocName orelse Name =:= null ->
-        save_doc(Doc);
-    _ ->
-        throw(not_found)
-    end.
-
-% If newDoc.password == null || newDoc.password == undefined:
-%   ->
-%   noop
-% Else -> // calculate password hash server side
-%    newDoc.password_sha = hash_pw(newDoc.password + salt)
-%    newDoc.salt = salt
-%    newDoc.password = null
-save_doc(#doc{body={Body}} = Doc) ->
-    case couch_util:get_value(?PASSWORD, Body) of
-    null -> % server admins don't have a user-db password entry
-        Doc;
-    undefined ->
-        Doc;
-    ClearPassword ->
-        Iterations = list_to_integer(couch_config:get("couch_httpd_auth", "iterations", "1000")),
-        Salt = couch_uuids:random(),
-        DerivedKey = couch_passwords:pbkdf2(ClearPassword, Salt, Iterations),
-        Body0 = [{?PASSWORD_SCHEME, ?PBKDF2}, {?ITERATIONS, Iterations}|Body],
-        Body1 = ?replace(Body0, ?DERIVED_KEY, DerivedKey),
-        Body2 = ?replace(Body1, ?SALT, Salt),
-        Body3 = proplists:delete(?PASSWORD, Body2),
-        Doc#doc{body={Body3}}
-    end.
-
-% If the doc is a design doc
-%   If the request's userCtx identifies an admin
-%     -> return doc
-%   Else
-%     -> 403 // Forbidden
-% If the request's userCtx identifies an admin
-%   -> return doc
-% If the request's userCtx.name doesn't match the doc's name
-%   -> 404 // Not Found
-% Else
-%   -> return doc
-after_doc_read(#doc{id = <<?DESIGN_DOC_PREFIX, _/binary>>} = Doc, Db) ->
-    case (catch couch_db:check_is_admin(Db)) of
-    ok ->
-        Doc;
-    _ ->
-        throw({forbidden,
-        <<"Only administrators can view design docs in the users database.">>})
-    end;
-after_doc_read(Doc, #db{user_ctx = UserCtx} = Db) ->
-    #user_ctx{name=Name} = UserCtx,
-    DocName = get_doc_name(Doc),
-    case (catch couch_db:check_is_admin(Db)) of
-    ok ->
-        Doc;
-    _ when Name =:= DocName ->
-        Doc;
-    _ ->
-        Doc1 = strip_non_public_fields(Doc),
-        case Doc1 of
-          #doc{body={[]}} ->
-              throw(not_found);
-          _ ->
-              Doc1
-        end
-    end.
-
-get_doc_name(#doc{id= <<"org.couchdb.user:", Name/binary>>}) ->
-    Name;
-get_doc_name(_) ->
-    undefined.
-
-strip_non_public_fields(#doc{body={Props}}=Doc) ->
-    Public = re:split(couch_config:get("couch_httpd_auth", "public_fields", ""),
-                      "\\s*,\\s*", [{return, binary}]),
-    Doc#doc{body={[{K, V} || {K, V} <- Props, lists:member(K, Public)]}}.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_util.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_util.erl b/apps/couch/src/couch_util.erl
deleted file mode 100644
index 76a9293..0000000
--- a/apps/couch/src/couch_util.erl
+++ /dev/null
@@ -1,487 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_util).
-
--export([start_app_deps/1, ensure_started/1]).
--export([priv_dir/0, normpath/1]).
--export([should_flush/0, should_flush/1, to_existing_atom/1]).
--export([rand32/0, implode/2]).
--export([abs_pathname/1,abs_pathname/2, trim/1]).
--export([encodeBase64Url/1, decodeBase64Url/1]).
--export([validate_utf8/1, to_hex/1, parse_term/1, dict_find/3]).
--export([get_nested_json_value/2, json_user_ctx/1]).
--export([proplist_apply_field/2, json_apply_field/2]).
--export([json_decode/1]).
--export([to_binary/1, to_integer/1, to_list/1, url_encode/1]).
--export([verify/2,simple_call/2,shutdown_sync/1]).
--export([get_value/2, get_value/3]).
--export([md5/1, md5_init/0, md5_update/2, md5_final/1]).
--export([reorder_results/2]).
--export([url_strip_password/1]).
--export([encode_doc_id/1]).
--export([with_db/2]).
--export([rfc1123_date/0, rfc1123_date/1]).
-
--include("couch_db.hrl").
-
-% arbitrarily chosen amount of memory to use before flushing to disk
--define(FLUSH_MAX_MEM, 10000000).
-
-%% @spec start_app_deps(App :: atom()) -> ok
-%% @doc Start depedent applications of App.
-start_app_deps(App) ->
-    {ok, DepApps} = application:get_key(App, applications),
-    [ensure_started(A) || A <- DepApps],
-    ok.
-
-%% @spec ensure_started(Application :: atom()) -> ok
-%% @doc Start the named application if not already started.
-ensure_started(App) ->
-    case application:start(App) of
-	ok ->
-	    ok;
-	{error, {already_started, App}} ->
-	    ok
-    end.
-
-priv_dir() ->
-    case code:priv_dir(couch) of
-        {error, _} ->
-            %% try to get relative priv dir. useful for tests.
-            EbinDir = filename:dirname(code:which(?MODULE)),
-            AppPath = filename:dirname(EbinDir),
-            filename:join(AppPath, "priv");
-        Dir -> Dir
-    end.
-
-% Normalize a pathname by removing .. and . components.
-normpath(Path) ->
-    normparts(filename:split(Path), []).
-
-normparts([], Acc) ->
-    filename:join(lists:reverse(Acc));
-normparts([".." | RestParts], [_Drop | RestAcc]) ->
-    normparts(RestParts, RestAcc);
-normparts(["." | RestParts], Acc) ->
-    normparts(RestParts, Acc);
-normparts([Part | RestParts], Acc) ->
-    normparts(RestParts, [Part | Acc]).
-
-% works like list_to_existing_atom, except can be list or binary and it
-% gives you the original value instead of an error if no existing atom.
-to_existing_atom(V) when is_list(V) ->
-    try list_to_existing_atom(V) catch _:_ -> V end;
-to_existing_atom(V) when is_binary(V) ->
-    try list_to_existing_atom(?b2l(V)) catch _:_ -> V end;
-to_existing_atom(V) when is_atom(V) ->
-    V.
-
-shutdown_sync(Pid) when not is_pid(Pid)->
-    ok;
-shutdown_sync(Pid) ->
-    MRef = erlang:monitor(process, Pid),
-    try
-        catch unlink(Pid),
-        catch exit(Pid, shutdown),
-        receive
-        {'DOWN', MRef, _, _, _} ->
-            ok
-        end
-    after
-        erlang:demonitor(MRef, [flush])
-    end.
-
-
-simple_call(Pid, Message) ->
-    MRef = erlang:monitor(process, Pid),
-    try
-        Pid ! {self(), Message},
-        receive
-        {Pid, Result} ->
-            Result;
-        {'DOWN', MRef, _, _, Reason} ->
-            exit(Reason)
-        end
-    after
-        erlang:demonitor(MRef, [flush])
-    end.
-
-validate_utf8(Data) when is_list(Data) ->
-    validate_utf8(?l2b(Data));
-validate_utf8(Bin) when is_binary(Bin) ->
-    validate_utf8_fast(Bin, 0).
-
-validate_utf8_fast(B, O) ->
-    case B of
-        <<_:O/binary>> ->
-            true;
-        <<_:O/binary, C1, _/binary>> when
-                C1 < 128 ->
-            validate_utf8_fast(B, 1 + O);
-        <<_:O/binary, C1, C2, _/binary>> when
-                C1 >= 194, C1 =< 223,
-                C2 >= 128, C2 =< 191 ->
-            validate_utf8_fast(B, 2 + O);
-        <<_:O/binary, C1, C2, C3, _/binary>> when
-                C1 >= 224, C1 =< 239,
-                C2 >= 128, C2 =< 191,
-                C3 >= 128, C3 =< 191 ->
-            validate_utf8_fast(B, 3 + O);
-        <<_:O/binary, C1, C2, C3, C4, _/binary>> when
-                C1 >= 240, C1 =< 244,
-                C2 >= 128, C2 =< 191,
-                C3 >= 128, C3 =< 191,
-                C4 >= 128, C4 =< 191 ->
-            validate_utf8_fast(B, 4 + O);
-        _ ->
-            false
-    end.
-
-to_hex([]) ->
-    [];
-to_hex(Bin) when is_binary(Bin) ->
-    to_hex(binary_to_list(Bin));
-to_hex([H|T]) ->
-    [to_digit(H div 16), to_digit(H rem 16) | to_hex(T)].
-
-to_digit(N) when N < 10 -> $0 + N;
-to_digit(N)             -> $a + N-10.
-
-
-parse_term(Bin) when is_binary(Bin) ->
-    parse_term(binary_to_list(Bin));
-parse_term(List) ->
-    {ok, Tokens, _} = erl_scan:string(List ++ "."),
-    erl_parse:parse_term(Tokens).
-
-get_value(Key, List) ->
-    get_value(Key, List, undefined).
-
-get_value(Key, List, Default) ->
-    case lists:keysearch(Key, 1, List) of
-    {value, {Key,Value}} ->
-        Value;
-    false ->
-        Default
-    end.
-
-get_nested_json_value({Props}, [Key|Keys]) ->
-    case couch_util:get_value(Key, Props, nil) of
-    nil -> throw({not_found, <<"missing json key: ", Key/binary>>});
-    Value -> get_nested_json_value(Value, Keys)
-    end;
-get_nested_json_value(Value, []) ->
-    Value;
-get_nested_json_value(_NotJSONObj, _) ->
-    throw({not_found, json_mismatch}).
-
-proplist_apply_field(H, L) ->
-    {R} = json_apply_field(H, {L}),
-    R.
-
-json_apply_field(H, {L}) ->
-    json_apply_field(H, L, []).
-json_apply_field({Key, NewValue}, [{Key, _OldVal} | Headers], Acc) ->
-    json_apply_field({Key, NewValue}, Headers, Acc);
-json_apply_field({Key, NewValue}, [{OtherKey, OtherVal} | Headers], Acc) ->
-    json_apply_field({Key, NewValue}, Headers, [{OtherKey, OtherVal} | Acc]);
-json_apply_field({Key, NewValue}, [], Acc) ->
-    {[{Key, NewValue}|Acc]}.
-
-json_user_ctx(#db{name=DbName, user_ctx=Ctx}) ->
-    {[{<<"db">>, DbName},
-            {<<"name">>,Ctx#user_ctx.name},
-            {<<"roles">>,Ctx#user_ctx.roles}]}.
-
-json_decode(D) ->
-    try
-        jiffy:decode(D)
-    catch
-        throw:Error ->
-            throw({invalid_json, Error})
-    end.
-
-% returns a random integer
-rand32() ->
-    crypto:rand_uniform(0, 16#100000000).
-
-% given a pathname "../foo/bar/" it gives back the fully qualified
-% absolute pathname.
-abs_pathname(" " ++ Filename) ->
-    % strip leading whitspace
-    abs_pathname(Filename);
-abs_pathname([$/ |_]=Filename) ->
-    Filename;
-abs_pathname(Filename) ->
-    {ok, Cwd} = file:get_cwd(),
-    {Filename2, Args} = separate_cmd_args(Filename, ""),
-    abs_pathname(Filename2, Cwd) ++ Args.
-
-abs_pathname(Filename, Dir) ->
-    Name = filename:absname(Filename, Dir ++ "/"),
-    OutFilename = filename:join(fix_path_list(filename:split(Name), [])),
-    % If the filename is a dir (last char slash, put back end slash
-    case string:right(Filename,1) of
-    "/" ->
-        OutFilename ++ "/";
-    "\\" ->
-        OutFilename ++ "/";
-    _Else->
-        OutFilename
-    end.
-
-% if this as an executable with arguments, seperate out the arguments
-% ""./foo\ bar.sh -baz=blah" -> {"./foo\ bar.sh", " -baz=blah"}
-separate_cmd_args("", CmdAcc) ->
-    {lists:reverse(CmdAcc), ""};
-separate_cmd_args("\\ " ++ Rest, CmdAcc) -> % handle skipped value
-    separate_cmd_args(Rest, " \\" ++ CmdAcc);
-separate_cmd_args(" " ++ Rest, CmdAcc) ->
-    {lists:reverse(CmdAcc), " " ++ Rest};
-separate_cmd_args([Char|Rest], CmdAcc) ->
-    separate_cmd_args(Rest, [Char | CmdAcc]).
-
-% Is a character whitespace?
-is_whitespace($\s) -> true;
-is_whitespace($\t) -> true;
-is_whitespace($\n) -> true;
-is_whitespace($\r) -> true;
-is_whitespace(_Else) -> false.
-
-
-% removes leading and trailing whitespace from a string
-trim(String) ->
-    String2 = lists:dropwhile(fun is_whitespace/1, String),
-    lists:reverse(lists:dropwhile(fun is_whitespace/1, lists:reverse(String2))).
-
-% takes a heirarchical list of dirs and removes the dots ".", double dots
-% ".." and the corresponding parent dirs.
-fix_path_list([], Acc) ->
-    lists:reverse(Acc);
-fix_path_list([".."|Rest], [_PrevAcc|RestAcc]) ->
-    fix_path_list(Rest, RestAcc);
-fix_path_list(["."|Rest], Acc) ->
-    fix_path_list(Rest, Acc);
-fix_path_list([Dir | Rest], Acc) ->
-    fix_path_list(Rest, [Dir | Acc]).
-
-
-implode(List, Sep) ->
-    implode(List, Sep, []).
-
-implode([], _Sep, Acc) ->
-    lists:flatten(lists:reverse(Acc));
-implode([H], Sep, Acc) ->
-    implode([], Sep, [H|Acc]);
-implode([H|T], Sep, Acc) ->
-    implode(T, Sep, [Sep,H|Acc]).
-
-should_flush() ->
-    should_flush(?FLUSH_MAX_MEM).
-
-should_flush(MemThreshHold) ->
-    {memory, ProcMem} = process_info(self(), memory),
-    BinMem = lists:foldl(fun({_Id, Size, _NRefs}, Acc) -> Size+Acc end,
-        0, element(2,process_info(self(), binary))),
-    if ProcMem+BinMem > 2*MemThreshHold ->
-        garbage_collect(),
-        {memory, ProcMem2} = process_info(self(), memory),
-        BinMem2 = lists:foldl(fun({_Id, Size, _NRefs}, Acc) -> Size+Acc end,
-            0, element(2,process_info(self(), binary))),
-        ProcMem2+BinMem2 > MemThreshHold;
-    true -> false end.
-
-encodeBase64Url(Url) ->
-    Url1 = re:replace(base64:encode(Url), ["=+", $$], ""),
-    Url2 = re:replace(Url1, "/", "_", [global]),
-    re:replace(Url2, "\\+", "-", [global, {return, binary}]).
-
-decodeBase64Url(Url64) ->
-    Url1 = re:replace(Url64, "-", "+", [global]),
-    Url2 = re:replace(Url1, "_", "/", [global]),
-    Padding = lists:duplicate((4 - iolist_size(Url2) rem 4) rem 4, $=),
-    base64:decode(iolist_to_binary([Url2, Padding])).
-
-dict_find(Key, Dict, DefaultValue) ->
-    case dict:find(Key, Dict) of
-    {ok, Value} ->
-        Value;
-    error ->
-        DefaultValue
-    end.
-
-to_binary(V) when is_binary(V) ->
-    V;
-to_binary(V) when is_list(V) ->
-    try
-        list_to_binary(V)
-    catch
-        _:_ ->
-            list_to_binary(io_lib:format("~p", [V]))
-    end;
-to_binary(V) when is_atom(V) ->
-    list_to_binary(atom_to_list(V));
-to_binary(V) ->
-    list_to_binary(io_lib:format("~p", [V])).
-
-to_integer(V) when is_integer(V) ->
-    V;
-to_integer(V) when is_list(V) ->
-    erlang:list_to_integer(V);
-to_integer(V) when is_binary(V) ->
-    erlang:list_to_integer(binary_to_list(V)).
-
-to_list(V) when is_list(V) ->
-    V;
-to_list(V) when is_binary(V) ->
-    binary_to_list(V);
-to_list(V) when is_atom(V) ->
-    atom_to_list(V);
-to_list(V) ->
-    lists:flatten(io_lib:format("~p", [V])).
-
-url_encode(Bin) when is_binary(Bin) ->
-    url_encode(binary_to_list(Bin));
-url_encode([H|T]) ->
-    if
-    H >= $a, $z >= H ->
-        [H|url_encode(T)];
-    H >= $A, $Z >= H ->
-        [H|url_encode(T)];
-    H >= $0, $9 >= H ->
-        [H|url_encode(T)];
-    H == $_; H == $.; H == $-; H == $: ->
-        [H|url_encode(T)];
-    true ->
-        case lists:flatten(io_lib:format("~.16.0B", [H])) of
-        [X, Y] ->
-            [$%, X, Y | url_encode(T)];
-        [X] ->
-            [$%, $0, X | url_encode(T)]
-        end
-    end;
-url_encode([]) ->
-    [].
-
-verify([X|RestX], [Y|RestY], Result) ->
-    verify(RestX, RestY, (X bxor Y) bor Result);
-verify([], [], Result) ->
-    Result == 0.
-
-verify(<<X/binary>>, <<Y/binary>>) ->
-    verify(?b2l(X), ?b2l(Y));
-verify(X, Y) when is_list(X) and is_list(Y) ->
-    case length(X) == length(Y) of
-        true ->
-            verify(X, Y, 0);
-        false ->
-            false
-    end;
-verify(_X, _Y) -> false.
-
--spec md5(Data::(iolist() | binary())) -> Digest::binary().
-md5(Data) ->
-    try crypto:md5(Data) catch error:_ -> erlang:md5(Data) end.
-
--spec md5_init() -> Context::binary().
-md5_init() ->
-    try crypto:md5_init() catch error:_ -> erlang:md5_init() end.
-
--spec md5_update(Context::binary(), Data::(iolist() | binary())) ->
-    NewContext::binary().
-md5_update(Ctx, D) ->
-    try crypto:md5_update(Ctx,D) catch error:_ -> erlang:md5_update(Ctx,D) end.
-
--spec md5_final(Context::binary()) -> Digest::binary().
-md5_final(Ctx) ->
-    try crypto:md5_final(Ctx) catch error:_ -> erlang:md5_final(Ctx) end.
-
-% linear search is faster for small lists, length() is 0.5 ms for 100k list
-reorder_results(Keys, SortedResults) when length(Keys) < 100 ->
-    [couch_util:get_value(Key, SortedResults) || Key <- Keys];
-reorder_results(Keys, SortedResults) ->
-    KeyDict = dict:from_list(SortedResults),
-    [dict:fetch(Key, KeyDict) || Key <- Keys].
-
-url_strip_password(Url) ->
-    re:replace(Url,
-        "http(s)?://([^:]+):[^@]+@(.*)$",
-        "http\\1://\\2:*****@\\3",
-        [{return, list}]).
-
-encode_doc_id(#doc{id = Id}) ->
-    encode_doc_id(Id);
-encode_doc_id(Id) when is_list(Id) ->
-    encode_doc_id(?l2b(Id));
-encode_doc_id(<<"_design/", Rest/binary>>) ->
-    "_design/" ++ url_encode(Rest);
-encode_doc_id(<<"_local/", Rest/binary>>) ->
-    "_local/" ++ url_encode(Rest);
-encode_doc_id(Id) ->
-    url_encode(Id).
-
-
-with_db(Db, Fun) when is_record(Db, db) ->
-    Fun(Db);
-with_db(DbName, Fun) ->
-    case couch_db:open_int(DbName, [{user_ctx, #user_ctx{roles=[<<"_admin">>]}}]) of
-        {ok, Db} ->
-            try
-                Fun(Db)
-            after
-                catch couch_db:close(Db)
-            end;
-        Else ->
-            throw(Else)
-    end.
-
-rfc1123_date() ->
-    {{YYYY,MM,DD},{Hour,Min,Sec}} = calendar:universal_time(),
-    DayNumber = calendar:day_of_the_week({YYYY,MM,DD}),
-    lists:flatten(
-      io_lib:format("~s, ~2.2.0w ~3.s ~4.4.0w ~2.2.0w:~2.2.0w:~2.2.0w GMT",
-            [day(DayNumber),DD,month(MM),YYYY,Hour,Min,Sec])).
-
-rfc1123_date(undefined) ->
-    undefined;
-rfc1123_date(UniversalTime) ->
-    {{YYYY,MM,DD},{Hour,Min,Sec}} = UniversalTime,
-    DayNumber = calendar:day_of_the_week({YYYY,MM,DD}),
-    lists:flatten(
-      io_lib:format("~s, ~2.2.0w ~3.s ~4.4.0w ~2.2.0w:~2.2.0w:~2.2.0w GMT",
-            [day(DayNumber),DD,month(MM),YYYY,Hour,Min,Sec])).
-
-%% day
-
-day(1) -> "Mon";
-day(2) -> "Tue";
-day(3) -> "Wed";
-day(4) -> "Thu";
-day(5) -> "Fri";
-day(6) -> "Sat";
-day(7) -> "Sun".
-
-%% month
-
-month(1) -> "Jan";
-month(2) -> "Feb";
-month(3) -> "Mar";
-month(4) -> "Apr";
-month(5) -> "May";
-month(6) -> "Jun";
-month(7) -> "Jul";
-month(8) -> "Aug";
-month(9) -> "Sep";
-month(10) -> "Oct";
-month(11) -> "Nov";
-month(12) -> "Dec".

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_uuids.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_uuids.erl b/apps/couch/src/couch_uuids.erl
deleted file mode 100644
index 6ed75a1..0000000
--- a/apps/couch/src/couch_uuids.erl
+++ /dev/null
@@ -1,103 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
--module(couch_uuids).
--include("couch_db.hrl").
-
--behaviour(gen_server).
-
--export([start/0, stop/0]).
--export([new/0, random/0, utc_random/0]).
-
--export([init/1, terminate/2, code_change/3]).
--export([handle_call/3, handle_cast/2, handle_info/2]).
-
-start() ->
-    gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
-
-stop() ->
-    gen_server:cast(?MODULE, stop).
-
-new() ->
-    gen_server:call(?MODULE, create).
-
-random() ->
-    list_to_binary(couch_util:to_hex(crypto:rand_bytes(16))).
-
-utc_random() ->
-    utc_suffix(couch_util:to_hex(crypto:rand_bytes(9))).
-
-utc_suffix(Suffix) ->
-    Now = {_, _, Micro} = now(),
-    Nowish = calendar:now_to_universal_time(Now),
-    Nowsecs = calendar:datetime_to_gregorian_seconds(Nowish),
-    Then = calendar:datetime_to_gregorian_seconds({{1970, 1, 1}, {0, 0, 0}}),
-    Prefix = io_lib:format("~14.16.0b", [(Nowsecs - Then) * 1000000 + Micro]),
-    list_to_binary(Prefix ++ Suffix).
-
-init([]) ->
-    ok = couch_config:register(
-        fun("uuids", _) -> gen_server:cast(?MODULE, change) end
-    ),
-    {ok, state()}.
-
-terminate(_Reason, _State) ->
-    ok.
-
-handle_call(create, _From, random) ->
-    {reply, random(), random};
-handle_call(create, _From, utc_random) ->
-    {reply, utc_random(), utc_random};
-handle_call(create, _From, {utc_id, UtcIdSuffix}) ->
-    {reply, utc_suffix(UtcIdSuffix), {utc_id, UtcIdSuffix}};
-handle_call(create, _From, {sequential, Pref, Seq}) ->
-    Result = ?l2b(Pref ++ io_lib:format("~6.16.0b", [Seq])),
-    case Seq >= 16#fff000 of
-        true ->
-            {reply, Result, {sequential, new_prefix(), inc()}};
-        _ ->
-            {reply, Result, {sequential, Pref, Seq + inc()}}
-    end.
-
-handle_cast(change, _State) ->
-    {noreply, state()};
-handle_cast(stop, State) ->
-    {stop, normal, State};
-handle_cast(_Msg, State) ->
-    {noreply, State}.
-
-handle_info(_Info, State) ->
-    {noreply, State}.
-
-code_change(_OldVsn, State, _Extra) ->
-    {ok, State}.
-
-new_prefix() ->
-    couch_util:to_hex((crypto:rand_bytes(13))).
-
-inc() ->
-    crypto:rand_uniform(1, 16#ffe).
-
-state() ->
-    AlgoStr = couch_config:get("uuids", "algorithm", "random"),
-    case couch_util:to_existing_atom(AlgoStr) of
-        random ->
-            random;
-        utc_random ->
-            utc_random;
-        utc_id ->
-            UtcIdSuffix = couch_config:get("uuids", "utc_id_suffix", ""),
-            {utc_id, UtcIdSuffix};
-        sequential ->
-            {sequential, new_prefix(), inc()};
-        Unknown ->
-            throw({unknown_uuid_algorithm, Unknown})
-    end.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_work_queue.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_work_queue.erl b/apps/couch/src/couch_work_queue.erl
deleted file mode 100644
index 22968d7..0000000
--- a/apps/couch/src/couch_work_queue.erl
+++ /dev/null
@@ -1,187 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_work_queue).
--behaviour(gen_server).
-
--include("couch_db.hrl").
-
-% public API
--export([new/1, queue/2, dequeue/1, dequeue/2, close/1, item_count/1, size/1]).
-
-% gen_server callbacks
--export([init/1, terminate/2]).
--export([handle_call/3, handle_cast/2, code_change/3, handle_info/2]).
-
--record(q, {
-    queue = queue:new(),
-    blocked = [],
-    max_size,
-    max_items,
-    items = 0,
-    size = 0,
-    work_waiters = [],
-    close_on_dequeue = false,
-    multi_workers = false
-}).
-
-
-new(Options) ->
-    gen_server:start_link(couch_work_queue, Options, []).
-
-
-queue(Wq, Item) when is_binary(Item) ->
-    gen_server:call(Wq, {queue, Item, byte_size(Item)}, infinity);
-queue(Wq, Item) ->
-    gen_server:call(Wq, {queue, Item, ?term_size(Item)}, infinity).
-
-
-dequeue(Wq) ->
-    dequeue(Wq, all).
-
-    
-dequeue(Wq, MaxItems) ->
-    try
-        gen_server:call(Wq, {dequeue, MaxItems}, infinity)
-    catch
-        _:_ -> closed
-    end.
-
-
-item_count(Wq) ->
-    try
-        gen_server:call(Wq, item_count, infinity)
-    catch
-        _:_ -> closed
-    end.
-
-
-size(Wq) ->
-    try
-        gen_server:call(Wq, size, infinity)
-    catch
-        _:_ -> closed
-    end.
-
-
-close(Wq) ->
-    gen_server:cast(Wq, close).
-    
-
-init(Options) ->
-    Q = #q{
-        max_size = couch_util:get_value(max_size, Options, nil),
-        max_items = couch_util:get_value(max_items, Options, nil),
-        multi_workers = couch_util:get_value(multi_workers, Options, false)
-    },
-    {ok, Q}.
-
-
-terminate(_Reason, #q{work_waiters=Workers}) ->
-    lists:foreach(fun({W, _}) -> gen_server:reply(W, closed) end, Workers).
-
-    
-handle_call({queue, Item, Size}, From, #q{work_waiters = []} = Q0) ->
-    Q = Q0#q{size = Q0#q.size + Size,
-                items = Q0#q.items + 1,
-                queue = queue:in({Item, Size}, Q0#q.queue)},
-    case (Q#q.size >= Q#q.max_size) orelse
-            (Q#q.items >= Q#q.max_items) of
-    true ->
-        {noreply, Q#q{blocked = [From | Q#q.blocked]}};
-    false ->
-        {reply, ok, Q}
-    end;
-
-handle_call({queue, Item, _}, _From, #q{work_waiters = [{W, _Max} | Rest]} = Q) ->
-    gen_server:reply(W, {ok, [Item]}),
-    {reply, ok, Q#q{work_waiters = Rest}};
-
-handle_call({dequeue, Max}, From, Q) ->
-    #q{work_waiters = Workers, multi_workers = Multi, items = Count} = Q,
-    case {Workers, Multi} of
-    {[_ | _], false} ->
-        exit("Only one caller allowed to wait for this work at a time");
-    {[_ | _], true} ->
-        {noreply, Q#q{work_waiters=Workers ++ [{From, Max}]}};
-    _ ->
-        case Count of
-        0 ->
-            {noreply, Q#q{work_waiters=Workers ++ [{From, Max}]}};
-        C when C > 0 ->
-            deliver_queue_items(Max, Q)
-        end
-    end;
-
-handle_call(item_count, _From, Q) ->
-    {reply, Q#q.items, Q};
-
-handle_call(size, _From, Q) ->
-    {reply, Q#q.size, Q}.
-
-
-deliver_queue_items(Max, Q) ->
-    #q{
-        queue = Queue,
-        items = Count,
-        size = Size,
-        close_on_dequeue = Close,
-        blocked = Blocked
-    } = Q,
-    case (Max =:= all) orelse (Max >= Count) of
-    false ->
-        {Items, Size2, Queue2, Blocked2} = dequeue_items(
-            Max, Size, Queue, Blocked, []),
-        Q2 = Q#q{
-            items = Count - Max, size = Size2, blocked = Blocked2, queue = Queue2
-        },
-        {reply, {ok, Items}, Q2};
-    true ->
-        lists:foreach(fun(F) -> gen_server:reply(F, ok) end, Blocked),
-        Q2 = Q#q{items = 0, size = 0, blocked = [], queue = queue:new()},
-        Items = [Item || {Item, _} <- queue:to_list(Queue)],
-        case Close of
-        false ->
-            {reply, {ok, Items}, Q2};
-        true ->
-            {stop, normal, {ok, Items}, Q2}
-        end
-    end.
-
-
-dequeue_items(0, Size, Queue, Blocked, DequeuedAcc) ->
-    {lists:reverse(DequeuedAcc), Size, Queue, Blocked};
-
-dequeue_items(NumItems, Size, Queue, Blocked, DequeuedAcc) ->
-    {{value, {Item, ItemSize}}, Queue2} = queue:out(Queue),
-    case Blocked of
-    [] ->
-        Blocked2 = Blocked;
-    [From | Blocked2] ->
-        gen_server:reply(From, ok)
-    end,
-    dequeue_items(
-        NumItems - 1, Size - ItemSize, Queue2, Blocked2, [Item | DequeuedAcc]).
-    
-
-handle_cast(close, #q{items = 0} = Q) ->
-    {stop, normal, Q};
-
-handle_cast(close, Q) ->
-    {noreply, Q#q{close_on_dequeue = true}}.
-
-
-code_change(_OldVsn, State, _Extra) ->
-    {ok, State}.
-
-handle_info(X, Q) ->
-    {stop, X, Q}.


[59/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/urename.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/urename.h b/src/apps/couch_collate/platform/osx/icu/unicode/urename.h
new file mode 100644
index 0000000..5282958
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/urename.h
@@ -0,0 +1,1775 @@
+/*
+*******************************************************************************
+*   Copyright (C) 2002-2008, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+*******************************************************************************
+*
+*   file name:  urename.h
+*   encoding:   US-ASCII
+*   tab size:   8 (not used)
+*   indentation:4
+*
+*   Created by: Perl script written by Vladimir Weinstein
+*
+*  Contains data for renaming ICU exports.
+*  Gets included by umachine.h
+*
+*  THIS FILE IS MACHINE-GENERATED, DON'T PLAY WITH IT IF YOU DON'T KNOW WHAT
+*  YOU ARE DOING, OTHERWISE VERY BAD THINGS WILL HAPPEN!
+*/
+
+#ifndef URENAME_H
+#define URENAME_H
+
+/* Uncomment the following line to disable renaming on platforms
+   that do not use Autoconf. */
+/* #define U_DISABLE_RENAMING 1 */
+
+#if !U_DISABLE_RENAMING
+
+/* C exports renaming data */
+
+#define T_CString_int64ToString T_CString_int64ToString_4_0
+#define T_CString_integerToString T_CString_integerToString_4_0
+#define T_CString_stricmp T_CString_stricmp_4_0
+#define T_CString_stringToInteger T_CString_stringToInteger_4_0
+#define T_CString_strnicmp T_CString_strnicmp_4_0
+#define T_CString_toLowerCase T_CString_toLowerCase_4_0
+#define T_CString_toUpperCase T_CString_toUpperCase_4_0
+#define UCNV_FROM_U_CALLBACK_ESCAPE UCNV_FROM_U_CALLBACK_ESCAPE_4_0
+#define UCNV_FROM_U_CALLBACK_SKIP UCNV_FROM_U_CALLBACK_SKIP_4_0
+#define UCNV_FROM_U_CALLBACK_STOP UCNV_FROM_U_CALLBACK_STOP_4_0
+#define UCNV_FROM_U_CALLBACK_SUBSTITUTE UCNV_FROM_U_CALLBACK_SUBSTITUTE_4_0
+#define UCNV_TO_U_CALLBACK_ESCAPE UCNV_TO_U_CALLBACK_ESCAPE_4_0
+#define UCNV_TO_U_CALLBACK_SKIP UCNV_TO_U_CALLBACK_SKIP_4_0
+#define UCNV_TO_U_CALLBACK_STOP UCNV_TO_U_CALLBACK_STOP_4_0
+#define UCNV_TO_U_CALLBACK_SUBSTITUTE UCNV_TO_U_CALLBACK_SUBSTITUTE_4_0
+#define UDataMemory_createNewInstance UDataMemory_createNewInstance_4_0
+#define UDataMemory_init UDataMemory_init_4_0
+#define UDataMemory_isLoaded UDataMemory_isLoaded_4_0
+#define UDataMemory_normalizeDataPointer UDataMemory_normalizeDataPointer_4_0
+#define UDataMemory_setData UDataMemory_setData_4_0
+#define UDatamemory_assign UDatamemory_assign_4_0
+#define _ASCIIData _ASCIIData_4_0
+#define _Bocu1Data _Bocu1Data_4_0
+#define _CESU8Data _CESU8Data_4_0
+#define _HZData _HZData_4_0
+#define _IMAPData _IMAPData_4_0
+#define _ISCIIData _ISCIIData_4_0
+#define _ISO2022Data _ISO2022Data_4_0
+#define _LMBCSData1 _LMBCSData1_4_0
+#define _LMBCSData11 _LMBCSData11_4_0
+#define _LMBCSData16 _LMBCSData16_4_0
+#define _LMBCSData17 _LMBCSData17_4_0
+#define _LMBCSData18 _LMBCSData18_4_0
+#define _LMBCSData19 _LMBCSData19_4_0
+#define _LMBCSData2 _LMBCSData2_4_0
+#define _LMBCSData3 _LMBCSData3_4_0
+#define _LMBCSData4 _LMBCSData4_4_0
+#define _LMBCSData5 _LMBCSData5_4_0
+#define _LMBCSData6 _LMBCSData6_4_0
+#define _LMBCSData8 _LMBCSData8_4_0
+#define _Latin1Data _Latin1Data_4_0
+#define _MBCSData _MBCSData_4_0
+#define _SCSUData _SCSUData_4_0
+#define _UTF16BEData _UTF16BEData_4_0
+#define _UTF16Data _UTF16Data_4_0
+#define _UTF16LEData _UTF16LEData_4_0
+#define _UTF32BEData _UTF32BEData_4_0
+#define _UTF32Data _UTF32Data_4_0
+#define _UTF32LEData _UTF32LEData_4_0
+#define _UTF7Data _UTF7Data_4_0
+#define _UTF8Data _UTF8Data_4_0
+#define cmemory_cleanup cmemory_cleanup_4_0
+#define cmemory_inUse cmemory_inUse_4_0
+#define le_close le_close_4_0
+#define le_create le_create_4_0
+#define le_getCharIndices le_getCharIndices_4_0
+#define le_getCharIndicesWithBase le_getCharIndicesWithBase_4_0
+#define le_getGlyphCount le_getGlyphCount_4_0
+#define le_getGlyphPosition le_getGlyphPosition_4_0
+#define le_getGlyphPositions le_getGlyphPositions_4_0
+#define le_getGlyphs le_getGlyphs_4_0
+#define le_layoutChars le_layoutChars_4_0
+#define le_reset le_reset_4_0
+#define locale_getKeywords locale_getKeywords_4_0
+#define locale_get_default locale_get_default_4_0
+#define locale_set_default locale_set_default_4_0
+#define pl_addFontRun pl_addFontRun_4_0
+#define pl_addLocaleRun pl_addLocaleRun_4_0
+#define pl_addValueRun pl_addValueRun_4_0
+#define pl_close pl_close_4_0
+#define pl_closeFontRuns pl_closeFontRuns_4_0
+#define pl_closeLine pl_closeLine_4_0
+#define pl_closeLocaleRuns pl_closeLocaleRuns_4_0
+#define pl_closeValueRuns pl_closeValueRuns_4_0
+#define pl_countLineRuns pl_countLineRuns_4_0
+#define pl_create pl_create_4_0
+#define pl_getAscent pl_getAscent_4_0
+#define pl_getDescent pl_getDescent_4_0
+#define pl_getFontRunCount pl_getFontRunCount_4_0
+#define pl_getFontRunFont pl_getFontRunFont_4_0
+#define pl_getFontRunLastLimit pl_getFontRunLastLimit_4_0
+#define pl_getFontRunLimit pl_getFontRunLimit_4_0
+#define pl_getLeading pl_getLeading_4_0
+#define pl_getLineAscent pl_getLineAscent_4_0
+#define pl_getLineDescent pl_getLineDescent_4_0
+#define pl_getLineLeading pl_getLineLeading_4_0
+#define pl_getLineVisualRun pl_getLineVisualRun_4_0
+#define pl_getLineWidth pl_getLineWidth_4_0
+#define pl_getLocaleRunCount pl_getLocaleRunCount_4_0
+#define pl_getLocaleRunLastLimit pl_getLocaleRunLastLimit_4_0
+#define pl_getLocaleRunLimit pl_getLocaleRunLimit_4_0
+#define pl_getLocaleRunLocale pl_getLocaleRunLocale_4_0
+#define pl_getParagraphLevel pl_getParagraphLevel_4_0
+#define pl_getTextDirection pl_getTextDirection_4_0
+#define pl_getValueRunCount pl_getValueRunCount_4_0
+#define pl_getValueRunLastLimit pl_getValueRunLastLimit_4_0
+#define pl_getValueRunLimit pl_getValueRunLimit_4_0
+#define pl_getValueRunValue pl_getValueRunValue_4_0
+#define pl_getVisualRunAscent pl_getVisualRunAscent_4_0
+#define pl_getVisualRunDescent pl_getVisualRunDescent_4_0
+#define pl_getVisualRunDirection pl_getVisualRunDirection_4_0
+#define pl_getVisualRunFont pl_getVisualRunFont_4_0
+#define pl_getVisualRunGlyphCount pl_getVisualRunGlyphCount_4_0
+#define pl_getVisualRunGlyphToCharMap pl_getVisualRunGlyphToCharMap_4_0
+#define pl_getVisualRunGlyphs pl_getVisualRunGlyphs_4_0
+#define pl_getVisualRunLeading pl_getVisualRunLeading_4_0
+#define pl_getVisualRunPositions pl_getVisualRunPositions_4_0
+#define pl_isComplex pl_isComplex_4_0
+#define pl_nextLine pl_nextLine_4_0
+#define pl_openEmptyFontRuns pl_openEmptyFontRuns_4_0
+#define pl_openEmptyLocaleRuns pl_openEmptyLocaleRuns_4_0
+#define pl_openEmptyValueRuns pl_openEmptyValueRuns_4_0
+#define pl_openFontRuns pl_openFontRuns_4_0
+#define pl_openLocaleRuns pl_openLocaleRuns_4_0
+#define pl_openValueRuns pl_openValueRuns_4_0
+#define pl_reflow pl_reflow_4_0
+#define pl_resetFontRuns pl_resetFontRuns_4_0
+#define pl_resetLocaleRuns pl_resetLocaleRuns_4_0
+#define pl_resetValueRuns pl_resetValueRuns_4_0
+#define res_countArrayItems res_countArrayItems_4_0
+#define res_findResource res_findResource_4_0
+#define res_getAlias res_getAlias_4_0
+#define res_getArrayItem res_getArrayItem_4_0
+#define res_getBinary res_getBinary_4_0
+#define res_getIntVector res_getIntVector_4_0
+#define res_getResource res_getResource_4_0
+#define res_getString res_getString_4_0
+#define res_getTableItemByIndex res_getTableItemByIndex_4_0
+#define res_getTableItemByKey res_getTableItemByKey_4_0
+#define res_load res_load_4_0
+#define res_unload res_unload_4_0
+#define transliterator_cleanup transliterator_cleanup_4_0
+#define triedict_swap triedict_swap_4_0
+#define u_UCharsToChars u_UCharsToChars_4_0
+#define u_austrcpy u_austrcpy_4_0
+#define u_austrncpy u_austrncpy_4_0
+#define u_catclose u_catclose_4_0
+#define u_catgets u_catgets_4_0
+#define u_catopen u_catopen_4_0
+#define u_charAge u_charAge_4_0
+#define u_charDigitValue u_charDigitValue_4_0
+#define u_charDirection u_charDirection_4_0
+#define u_charFromName u_charFromName_4_0
+#define u_charMirror u_charMirror_4_0
+#define u_charName u_charName_4_0
+#define u_charType u_charType_4_0
+#define u_charsToUChars u_charsToUChars_4_0
+#define u_cleanup u_cleanup_4_0
+#define u_countChar32 u_countChar32_4_0
+#define u_digit u_digit_4_0
+#define u_enumCharNames u_enumCharNames_4_0
+#define u_enumCharTypes u_enumCharTypes_4_0
+#define u_errorName u_errorName_4_0
+#define u_fclose u_fclose_4_0
+#define u_feof u_feof_4_0
+#define u_fflush u_fflush_4_0
+#define u_fgetConverter u_fgetConverter_4_0
+#define u_fgetc u_fgetc_4_0
+#define u_fgetcodepage u_fgetcodepage_4_0
+#define u_fgetcx u_fgetcx_4_0
+#define u_fgetfile u_fgetfile_4_0
+#define u_fgetlocale u_fgetlocale_4_0
+#define u_fgets u_fgets_4_0
+#define u_file_read u_file_read_4_0
+#define u_file_write u_file_write_4_0
+#define u_file_write_flush u_file_write_flush_4_0
+#define u_finit u_finit_4_0
+#define u_foldCase u_foldCase_4_0
+#define u_fopen u_fopen_4_0
+#define u_forDigit u_forDigit_4_0
+#define u_formatMessage u_formatMessage_4_0
+#define u_formatMessageWithError u_formatMessageWithError_4_0
+#define u_fprintf u_fprintf_4_0
+#define u_fprintf_u u_fprintf_u_4_0
+#define u_fputc u_fputc_4_0
+#define u_fputs u_fputs_4_0
+#define u_frewind u_frewind_4_0
+#define u_fscanf u_fscanf_4_0
+#define u_fscanf_u u_fscanf_u_4_0
+#define u_fsetcodepage u_fsetcodepage_4_0
+#define u_fsetlocale u_fsetlocale_4_0
+#define u_fsettransliterator u_fsettransliterator_4_0
+#define u_fstropen u_fstropen_4_0
+#define u_fungetc u_fungetc_4_0
+#define u_getCombiningClass u_getCombiningClass_4_0
+#define u_getDataDirectory u_getDataDirectory_4_0
+#define u_getDefaultConverter u_getDefaultConverter_4_0
+#define u_getFC_NFKC_Closure u_getFC_NFKC_Closure_4_0
+#define u_getISOComment u_getISOComment_4_0
+#define u_getIntPropertyMaxValue u_getIntPropertyMaxValue_4_0
+#define u_getIntPropertyMinValue u_getIntPropertyMinValue_4_0
+#define u_getIntPropertyValue u_getIntPropertyValue_4_0
+#define u_getNumericValue u_getNumericValue_4_0
+#define u_getPropertyEnum u_getPropertyEnum_4_0
+#define u_getPropertyName u_getPropertyName_4_0
+#define u_getPropertyValueEnum u_getPropertyValueEnum_4_0
+#define u_getPropertyValueName u_getPropertyValueName_4_0
+#define u_getUnicodeProperties u_getUnicodeProperties_4_0
+#define u_getUnicodeVersion u_getUnicodeVersion_4_0
+#define u_getVersion u_getVersion_4_0
+#define u_growBufferFromStatic u_growBufferFromStatic_4_0
+#define u_hasBinaryProperty u_hasBinaryProperty_4_0
+#define u_init u_init_4_0
+#define u_isIDIgnorable u_isIDIgnorable_4_0
+#define u_isIDPart u_isIDPart_4_0
+#define u_isIDStart u_isIDStart_4_0
+#define u_isISOControl u_isISOControl_4_0
+#define u_isJavaIDPart u_isJavaIDPart_4_0
+#define u_isJavaIDStart u_isJavaIDStart_4_0
+#define u_isJavaSpaceChar u_isJavaSpaceChar_4_0
+#define u_isMirrored u_isMirrored_4_0
+#define u_isUAlphabetic u_isUAlphabetic_4_0
+#define u_isULowercase u_isULowercase_4_0
+#define u_isUUppercase u_isUUppercase_4_0
+#define u_isUWhiteSpace u_isUWhiteSpace_4_0
+#define u_isWhitespace u_isWhitespace_4_0
+#define u_isalnum u_isalnum_4_0
+#define u_isalnumPOSIX u_isalnumPOSIX_4_0
+#define u_isalpha u_isalpha_4_0
+#define u_isbase u_isbase_4_0
+#define u_isblank u_isblank_4_0
+#define u_iscntrl u_iscntrl_4_0
+#define u_isdefined u_isdefined_4_0
+#define u_isdigit u_isdigit_4_0
+#define u_isgraph u_isgraph_4_0
+#define u_isgraphPOSIX u_isgraphPOSIX_4_0
+#define u_islower u_islower_4_0
+#define u_isprint u_isprint_4_0
+#define u_isprintPOSIX u_isprintPOSIX_4_0
+#define u_ispunct u_ispunct_4_0
+#define u_isspace u_isspace_4_0
+#define u_istitle u_istitle_4_0
+#define u_isupper u_isupper_4_0
+#define u_isxdigit u_isxdigit_4_0
+#define u_lengthOfIdenticalLevelRun u_lengthOfIdenticalLevelRun_4_0
+#define u_locbund_close u_locbund_close_4_0
+#define u_locbund_getNumberFormat u_locbund_getNumberFormat_4_0
+#define u_locbund_init u_locbund_init_4_0
+#define u_memcasecmp u_memcasecmp_4_0
+#define u_memchr u_memchr_4_0
+#define u_memchr32 u_memchr32_4_0
+#define u_memcmp u_memcmp_4_0
+#define u_memcmpCodePointOrder u_memcmpCodePointOrder_4_0
+#define u_memcpy u_memcpy_4_0
+#define u_memmove u_memmove_4_0
+#define u_memrchr u_memrchr_4_0
+#define u_memrchr32 u_memrchr32_4_0
+#define u_memset u_memset_4_0
+#define u_parseMessage u_parseMessage_4_0
+#define u_parseMessageWithError u_parseMessageWithError_4_0
+#define u_printf_parse u_printf_parse_4_0
+#define u_releaseDefaultConverter u_releaseDefaultConverter_4_0
+#define u_scanf_parse u_scanf_parse_4_0
+#define u_setAtomicIncDecFunctions u_setAtomicIncDecFunctions_4_0
+#define u_setDataDirectory u_setDataDirectory_4_0
+#define u_setMemoryFunctions u_setMemoryFunctions_4_0
+#define u_setMutexFunctions u_setMutexFunctions_4_0
+#define u_shapeArabic u_shapeArabic_4_0
+#define u_snprintf u_snprintf_4_0
+#define u_snprintf_u u_snprintf_u_4_0
+#define u_sprintf u_sprintf_4_0
+#define u_sprintf_u u_sprintf_u_4_0
+#define u_sscanf u_sscanf_4_0
+#define u_sscanf_u u_sscanf_u_4_0
+#define u_strCaseCompare u_strCaseCompare_4_0
+#define u_strCompare u_strCompare_4_0
+#define u_strCompareIter u_strCompareIter_4_0
+#define u_strFindFirst u_strFindFirst_4_0
+#define u_strFindLast u_strFindLast_4_0
+#define u_strFoldCase u_strFoldCase_4_0
+#define u_strFromPunycode u_strFromPunycode_4_0
+#define u_strFromUTF32 u_strFromUTF32_4_0
+#define u_strFromUTF8 u_strFromUTF8_4_0
+#define u_strFromUTF8Lenient u_strFromUTF8Lenient_4_0
+#define u_strFromUTF8WithSub u_strFromUTF8WithSub_4_0
+#define u_strFromWCS u_strFromWCS_4_0
+#define u_strHasMoreChar32Than u_strHasMoreChar32Than_4_0
+#define u_strToLower u_strToLower_4_0
+#define u_strToPunycode u_strToPunycode_4_0
+#define u_strToTitle u_strToTitle_4_0
+#define u_strToUTF32 u_strToUTF32_4_0
+#define u_strToUTF8 u_strToUTF8_4_0
+#define u_strToUTF8WithSub u_strToUTF8WithSub_4_0
+#define u_strToUpper u_strToUpper_4_0
+#define u_strToWCS u_strToWCS_4_0
+#define u_strcasecmp u_strcasecmp_4_0
+#define u_strcat u_strcat_4_0
+#define u_strchr u_strchr_4_0
+#define u_strchr32 u_strchr32_4_0
+#define u_strcmp u_strcmp_4_0
+#define u_strcmpCodePointOrder u_strcmpCodePointOrder_4_0
+#define u_strcmpFold u_strcmpFold_4_0
+#define u_strcpy u_strcpy_4_0
+#define u_strcspn u_strcspn_4_0
+#define u_strlen u_strlen_4_0
+#define u_strncasecmp u_strncasecmp_4_0
+#define u_strncat u_strncat_4_0
+#define u_strncmp u_strncmp_4_0
+#define u_strncmpCodePointOrder u_strncmpCodePointOrder_4_0
+#define u_strncpy u_strncpy_4_0
+#define u_strpbrk u_strpbrk_4_0
+#define u_strrchr u_strrchr_4_0
+#define u_strrchr32 u_strrchr32_4_0
+#define u_strrstr u_strrstr_4_0
+#define u_strspn u_strspn_4_0
+#define u_strstr u_strstr_4_0
+#define u_strtok_r u_strtok_r_4_0
+#define u_terminateChars u_terminateChars_4_0
+#define u_terminateUChar32s u_terminateUChar32s_4_0
+#define u_terminateUChars u_terminateUChars_4_0
+#define u_terminateWChars u_terminateWChars_4_0
+#define u_tolower u_tolower_4_0
+#define u_totitle u_totitle_4_0
+#define u_toupper u_toupper_4_0
+#define u_uastrcpy u_uastrcpy_4_0
+#define u_uastrncpy u_uastrncpy_4_0
+#define u_unescape u_unescape_4_0
+#define u_unescapeAt u_unescapeAt_4_0
+#define u_versionFromString u_versionFromString_4_0
+#define u_versionToString u_versionToString_4_0
+#define u_vformatMessage u_vformatMessage_4_0
+#define u_vformatMessageWithError u_vformatMessageWithError_4_0
+#define u_vfprintf u_vfprintf_4_0
+#define u_vfprintf_u u_vfprintf_u_4_0
+#define u_vfscanf u_vfscanf_4_0
+#define u_vfscanf_u u_vfscanf_u_4_0
+#define u_vparseMessage u_vparseMessage_4_0
+#define u_vparseMessageWithError u_vparseMessageWithError_4_0
+#define u_vsnprintf u_vsnprintf_4_0
+#define u_vsnprintf_u u_vsnprintf_u_4_0
+#define u_vsprintf u_vsprintf_4_0
+#define u_vsprintf_u u_vsprintf_u_4_0
+#define u_vsscanf u_vsscanf_4_0
+#define u_vsscanf_u u_vsscanf_u_4_0
+#define u_writeDiff u_writeDiff_4_0
+#define u_writeIdenticalLevelRun u_writeIdenticalLevelRun_4_0
+#define u_writeIdenticalLevelRunTwoChars u_writeIdenticalLevelRunTwoChars_4_0
+#define ubidi_addPropertyStarts ubidi_addPropertyStarts_4_0
+#define ubidi_close ubidi_close_4_0
+#define ubidi_closeProps ubidi_closeProps_4_0
+#define ubidi_countParagraphs ubidi_countParagraphs_4_0
+#define ubidi_countRuns ubidi_countRuns_4_0
+#define ubidi_getClass ubidi_getClass_4_0
+#define ubidi_getClassCallback ubidi_getClassCallback_4_0
+#define ubidi_getCustomizedClass ubidi_getCustomizedClass_4_0
+#define ubidi_getDirection ubidi_getDirection_4_0
+#define ubidi_getJoiningGroup ubidi_getJoiningGroup_4_0
+#define ubidi_getJoiningType ubidi_getJoiningType_4_0
+#define ubidi_getLength ubidi_getLength_4_0
+#define ubidi_getLevelAt ubidi_getLevelAt_4_0
+#define ubidi_getLevels ubidi_getLevels_4_0
+#define ubidi_getLogicalIndex ubidi_getLogicalIndex_4_0
+#define ubidi_getLogicalMap ubidi_getLogicalMap_4_0
+#define ubidi_getLogicalRun ubidi_getLogicalRun_4_0
+#define ubidi_getMaxValue ubidi_getMaxValue_4_0
+#define ubidi_getMemory ubidi_getMemory_4_0
+#define ubidi_getMirror ubidi_getMirror_4_0
+#define ubidi_getParaLevel ubidi_getParaLevel_4_0
+#define ubidi_getParagraph ubidi_getParagraph_4_0
+#define ubidi_getParagraphByIndex ubidi_getParagraphByIndex_4_0
+#define ubidi_getProcessedLength ubidi_getProcessedLength_4_0
+#define ubidi_getReorderingMode ubidi_getReorderingMode_4_0
+#define ubidi_getReorderingOptions ubidi_getReorderingOptions_4_0
+#define ubidi_getResultLength ubidi_getResultLength_4_0
+#define ubidi_getRuns ubidi_getRuns_4_0
+#define ubidi_getSingleton ubidi_getSingleton_4_0
+#define ubidi_getText ubidi_getText_4_0
+#define ubidi_getVisualIndex ubidi_getVisualIndex_4_0
+#define ubidi_getVisualMap ubidi_getVisualMap_4_0
+#define ubidi_getVisualRun ubidi_getVisualRun_4_0
+#define ubidi_invertMap ubidi_invertMap_4_0
+#define ubidi_isBidiControl ubidi_isBidiControl_4_0
+#define ubidi_isInverse ubidi_isInverse_4_0
+#define ubidi_isJoinControl ubidi_isJoinControl_4_0
+#define ubidi_isMirrored ubidi_isMirrored_4_0
+#define ubidi_isOrderParagraphsLTR ubidi_isOrderParagraphsLTR_4_0
+#define ubidi_open ubidi_open_4_0
+#define ubidi_openSized ubidi_openSized_4_0
+#define ubidi_orderParagraphsLTR ubidi_orderParagraphsLTR_4_0
+#define ubidi_reorderLogical ubidi_reorderLogical_4_0
+#define ubidi_reorderVisual ubidi_reorderVisual_4_0
+#define ubidi_setClassCallback ubidi_setClassCallback_4_0
+#define ubidi_setInverse ubidi_setInverse_4_0
+#define ubidi_setLine ubidi_setLine_4_0
+#define ubidi_setPara ubidi_setPara_4_0
+#define ubidi_setReorderingMode ubidi_setReorderingMode_4_0
+#define ubidi_setReorderingOptions ubidi_setReorderingOptions_4_0
+#define ubidi_writeReordered ubidi_writeReordered_4_0
+#define ubidi_writeReverse ubidi_writeReverse_4_0
+#define ublock_getCode ublock_getCode_4_0
+#define ubrk_close ubrk_close_4_0
+#define ubrk_countAvailable ubrk_countAvailable_4_0
+#define ubrk_current ubrk_current_4_0
+#define ubrk_first ubrk_first_4_0
+#define ubrk_following ubrk_following_4_0
+#define ubrk_getAvailable ubrk_getAvailable_4_0
+#define ubrk_getLocaleByType ubrk_getLocaleByType_4_0
+#define ubrk_getRuleStatus ubrk_getRuleStatus_4_0
+#define ubrk_getRuleStatusVec ubrk_getRuleStatusVec_4_0
+#define ubrk_isBoundary ubrk_isBoundary_4_0
+#define ubrk_last ubrk_last_4_0
+#define ubrk_next ubrk_next_4_0
+#define ubrk_open ubrk_open_4_0
+#define ubrk_openRules ubrk_openRules_4_0
+#define ubrk_preceding ubrk_preceding_4_0
+#define ubrk_previous ubrk_previous_4_0
+#define ubrk_safeClone ubrk_safeClone_4_0
+#define ubrk_setText ubrk_setText_4_0
+#define ubrk_setUText ubrk_setUText_4_0
+#define ubrk_swap ubrk_swap_4_0
+#define ucal_add ucal_add_4_0
+#define ucal_clear ucal_clear_4_0
+#define ucal_clearField ucal_clearField_4_0
+#define ucal_clone ucal_clone_4_0
+#define ucal_close ucal_close_4_0
+#define ucal_countAvailable ucal_countAvailable_4_0
+#define ucal_equivalentTo ucal_equivalentTo_4_0
+#define ucal_get ucal_get_4_0
+#define ucal_getAttribute ucal_getAttribute_4_0
+#define ucal_getAvailable ucal_getAvailable_4_0
+#define ucal_getCanonicalTimeZoneID ucal_getCanonicalTimeZoneID_4_0
+#define ucal_getDSTSavings ucal_getDSTSavings_4_0
+#define ucal_getDefaultTimeZone ucal_getDefaultTimeZone_4_0
+#define ucal_getGregorianChange ucal_getGregorianChange_4_0
+#define ucal_getLimit ucal_getLimit_4_0
+#define ucal_getLocaleByType ucal_getLocaleByType_4_0
+#define ucal_getMillis ucal_getMillis_4_0
+#define ucal_getNow ucal_getNow_4_0
+#define ucal_getTZDataVersion ucal_getTZDataVersion_4_0
+#define ucal_getTimeZoneDisplayName ucal_getTimeZoneDisplayName_4_0
+#define ucal_inDaylightTime ucal_inDaylightTime_4_0
+#define ucal_isSet ucal_isSet_4_0
+#define ucal_open ucal_open_4_0
+#define ucal_openCountryTimeZones ucal_openCountryTimeZones_4_0
+#define ucal_openTimeZones ucal_openTimeZones_4_0
+#define ucal_roll ucal_roll_4_0
+#define ucal_set ucal_set_4_0
+#define ucal_setAttribute ucal_setAttribute_4_0
+#define ucal_setDate ucal_setDate_4_0
+#define ucal_setDateTime ucal_setDateTime_4_0
+#define ucal_setDefaultTimeZone ucal_setDefaultTimeZone_4_0
+#define ucal_setGregorianChange ucal_setGregorianChange_4_0
+#define ucal_setMillis ucal_setMillis_4_0
+#define ucal_setTimeZone ucal_setTimeZone_4_0
+#define ucase_addCaseClosure ucase_addCaseClosure_4_0
+#define ucase_addPropertyStarts ucase_addPropertyStarts_4_0
+#define ucase_addStringCaseClosure ucase_addStringCaseClosure_4_0
+#define ucase_close ucase_close_4_0
+#define ucase_fold ucase_fold_4_0
+#define ucase_getCaseLocale ucase_getCaseLocale_4_0
+#define ucase_getSingleton ucase_getSingleton_4_0
+#define ucase_getType ucase_getType_4_0
+#define ucase_getTypeOrIgnorable ucase_getTypeOrIgnorable_4_0
+#define ucase_hasBinaryProperty ucase_hasBinaryProperty_4_0
+#define ucase_isCaseSensitive ucase_isCaseSensitive_4_0
+#define ucase_isSoftDotted ucase_isSoftDotted_4_0
+#define ucase_toFullFolding ucase_toFullFolding_4_0
+#define ucase_toFullLower ucase_toFullLower_4_0
+#define ucase_toFullTitle ucase_toFullTitle_4_0
+#define ucase_toFullUpper ucase_toFullUpper_4_0
+#define ucase_tolower ucase_tolower_4_0
+#define ucase_totitle ucase_totitle_4_0
+#define ucase_toupper ucase_toupper_4_0
+#define ucasemap_close ucasemap_close_4_0
+#define ucasemap_getBreakIterator ucasemap_getBreakIterator_4_0
+#define ucasemap_getLocale ucasemap_getLocale_4_0
+#define ucasemap_getOptions ucasemap_getOptions_4_0
+#define ucasemap_open ucasemap_open_4_0
+#define ucasemap_setBreakIterator ucasemap_setBreakIterator_4_0
+#define ucasemap_setLocale ucasemap_setLocale_4_0
+#define ucasemap_setOptions ucasemap_setOptions_4_0
+#define ucasemap_toTitle ucasemap_toTitle_4_0
+#define ucasemap_utf8FoldCase ucasemap_utf8FoldCase_4_0
+#define ucasemap_utf8ToLower ucasemap_utf8ToLower_4_0
+#define ucasemap_utf8ToTitle ucasemap_utf8ToTitle_4_0
+#define ucasemap_utf8ToUpper ucasemap_utf8ToUpper_4_0
+#define uchar_addPropertyStarts uchar_addPropertyStarts_4_0
+#define uchar_getHST uchar_getHST_4_0
+#define uchar_swapNames uchar_swapNames_4_0
+#define ucln_common_registerCleanup ucln_common_registerCleanup_4_0
+#define ucln_i18n_registerCleanup ucln_i18n_registerCleanup_4_0
+#define ucln_io_registerCleanup ucln_io_registerCleanup_4_0
+#define ucln_lib_cleanup ucln_lib_cleanup_4_0
+#define ucln_registerCleanup ucln_registerCleanup_4_0
+#define ucnv_MBCSFromUChar32 ucnv_MBCSFromUChar32_4_0
+#define ucnv_MBCSFromUnicodeWithOffsets ucnv_MBCSFromUnicodeWithOffsets_4_0
+#define ucnv_MBCSGetFilteredUnicodeSetForUnicode ucnv_MBCSGetFilteredUnicodeSetForUnicode_4_0
+#define ucnv_MBCSGetType ucnv_MBCSGetType_4_0
+#define ucnv_MBCSGetUnicodeSetForUnicode ucnv_MBCSGetUnicodeSetForUnicode_4_0
+#define ucnv_MBCSIsLeadByte ucnv_MBCSIsLeadByte_4_0
+#define ucnv_MBCSSimpleGetNextUChar ucnv_MBCSSimpleGetNextUChar_4_0
+#define ucnv_MBCSToUnicodeWithOffsets ucnv_MBCSToUnicodeWithOffsets_4_0
+#define ucnv_bld_countAvailableConverters ucnv_bld_countAvailableConverters_4_0
+#define ucnv_bld_getAvailableConverter ucnv_bld_getAvailableConverter_4_0
+#define ucnv_cbFromUWriteBytes ucnv_cbFromUWriteBytes_4_0
+#define ucnv_cbFromUWriteSub ucnv_cbFromUWriteSub_4_0
+#define ucnv_cbFromUWriteUChars ucnv_cbFromUWriteUChars_4_0
+#define ucnv_cbToUWriteSub ucnv_cbToUWriteSub_4_0
+#define ucnv_cbToUWriteUChars ucnv_cbToUWriteUChars_4_0
+#define ucnv_close ucnv_close_4_0
+#define ucnv_compareNames ucnv_compareNames_4_0
+#define ucnv_convert ucnv_convert_4_0
+#define ucnv_convertEx ucnv_convertEx_4_0
+#define ucnv_countAliases ucnv_countAliases_4_0
+#define ucnv_countAvailable ucnv_countAvailable_4_0
+#define ucnv_countStandards ucnv_countStandards_4_0
+#define ucnv_createAlgorithmicConverter ucnv_createAlgorithmicConverter_4_0
+#define ucnv_createConverter ucnv_createConverter_4_0
+#define ucnv_createConverterFromPackage ucnv_createConverterFromPackage_4_0
+#define ucnv_createConverterFromSharedData ucnv_createConverterFromSharedData_4_0
+#define ucnv_detectUnicodeSignature ucnv_detectUnicodeSignature_4_0
+#define ucnv_extContinueMatchFromU ucnv_extContinueMatchFromU_4_0
+#define ucnv_extContinueMatchToU ucnv_extContinueMatchToU_4_0
+#define ucnv_extGetUnicodeSet ucnv_extGetUnicodeSet_4_0
+#define ucnv_extInitialMatchFromU ucnv_extInitialMatchFromU_4_0
+#define ucnv_extInitialMatchToU ucnv_extInitialMatchToU_4_0
+#define ucnv_extSimpleMatchFromU ucnv_extSimpleMatchFromU_4_0
+#define ucnv_extSimpleMatchToU ucnv_extSimpleMatchToU_4_0
+#define ucnv_fixFileSeparator ucnv_fixFileSeparator_4_0
+#define ucnv_flushCache ucnv_flushCache_4_0
+#define ucnv_fromAlgorithmic ucnv_fromAlgorithmic_4_0
+#define ucnv_fromUChars ucnv_fromUChars_4_0
+#define ucnv_fromUCountPending ucnv_fromUCountPending_4_0
+#define ucnv_fromUWriteBytes ucnv_fromUWriteBytes_4_0
+#define ucnv_fromUnicode ucnv_fromUnicode_4_0
+#define ucnv_fromUnicode_UTF8 ucnv_fromUnicode_UTF8_4_0
+#define ucnv_fromUnicode_UTF8_OFFSETS_LOGIC ucnv_fromUnicode_UTF8_OFFSETS_LOGIC_4_0
+#define ucnv_getAlias ucnv_getAlias_4_0
+#define ucnv_getAliases ucnv_getAliases_4_0
+#define ucnv_getAvailableName ucnv_getAvailableName_4_0
+#define ucnv_getCCSID ucnv_getCCSID_4_0
+#define ucnv_getCanonicalName ucnv_getCanonicalName_4_0
+#define ucnv_getCompleteUnicodeSet ucnv_getCompleteUnicodeSet_4_0
+#define ucnv_getDefaultName ucnv_getDefaultName_4_0
+#define ucnv_getDisplayName ucnv_getDisplayName_4_0
+#define ucnv_getFromUCallBack ucnv_getFromUCallBack_4_0
+#define ucnv_getInvalidChars ucnv_getInvalidChars_4_0
+#define ucnv_getInvalidUChars ucnv_getInvalidUChars_4_0
+#define ucnv_getMaxCharSize ucnv_getMaxCharSize_4_0
+#define ucnv_getMinCharSize ucnv_getMinCharSize_4_0
+#define ucnv_getName ucnv_getName_4_0
+#define ucnv_getNextUChar ucnv_getNextUChar_4_0
+#define ucnv_getNonSurrogateUnicodeSet ucnv_getNonSurrogateUnicodeSet_4_0
+#define ucnv_getPlatform ucnv_getPlatform_4_0
+#define ucnv_getStandard ucnv_getStandard_4_0
+#define ucnv_getStandardName ucnv_getStandardName_4_0
+#define ucnv_getStarters ucnv_getStarters_4_0
+#define ucnv_getSubstChars ucnv_getSubstChars_4_0
+#define ucnv_getToUCallBack ucnv_getToUCallBack_4_0
+#define ucnv_getType ucnv_getType_4_0
+#define ucnv_getUnicodeSet ucnv_getUnicodeSet_4_0
+#define ucnv_incrementRefCount ucnv_incrementRefCount_4_0
+#define ucnv_io_countKnownConverters ucnv_io_countKnownConverters_4_0
+#define ucnv_io_getConverterName ucnv_io_getConverterName_4_0
+#define ucnv_io_stripASCIIForCompare ucnv_io_stripASCIIForCompare_4_0
+#define ucnv_io_stripEBCDICForCompare ucnv_io_stripEBCDICForCompare_4_0
+#define ucnv_isAmbiguous ucnv_isAmbiguous_4_0
+#define ucnv_load ucnv_load_4_0
+#define ucnv_loadSharedData ucnv_loadSharedData_4_0
+#define ucnv_open ucnv_open_4_0
+#define ucnv_openAllNames ucnv_openAllNames_4_0
+#define ucnv_openCCSID ucnv_openCCSID_4_0
+#define ucnv_openPackage ucnv_openPackage_4_0
+#define ucnv_openStandardNames ucnv_openStandardNames_4_0
+#define ucnv_openU ucnv_openU_4_0
+#define ucnv_reset ucnv_reset_4_0
+#define ucnv_resetFromUnicode ucnv_resetFromUnicode_4_0
+#define ucnv_resetToUnicode ucnv_resetToUnicode_4_0
+#define ucnv_safeClone ucnv_safeClone_4_0
+#define ucnv_setDefaultName ucnv_setDefaultName_4_0
+#define ucnv_setFallback ucnv_setFallback_4_0
+#define ucnv_setFromUCallBack ucnv_setFromUCallBack_4_0
+#define ucnv_setSubstChars ucnv_setSubstChars_4_0
+#define ucnv_setSubstString ucnv_setSubstString_4_0
+#define ucnv_setToUCallBack ucnv_setToUCallBack_4_0
+#define ucnv_swap ucnv_swap_4_0
+#define ucnv_swapAliases ucnv_swapAliases_4_0
+#define ucnv_toAlgorithmic ucnv_toAlgorithmic_4_0
+#define ucnv_toUChars ucnv_toUChars_4_0
+#define ucnv_toUCountPending ucnv_toUCountPending_4_0
+#define ucnv_toUWriteCodePoint ucnv_toUWriteCodePoint_4_0
+#define ucnv_toUWriteUChars ucnv_toUWriteUChars_4_0
+#define ucnv_toUnicode ucnv_toUnicode_4_0
+#define ucnv_unload ucnv_unload_4_0
+#define ucnv_unloadSharedDataIfReady ucnv_unloadSharedDataIfReady_4_0
+#define ucnv_usesFallback ucnv_usesFallback_4_0
+#define ucol_allocWeights ucol_allocWeights_4_0
+#define ucol_assembleTailoringTable ucol_assembleTailoringTable_4_0
+#define ucol_calcSortKey ucol_calcSortKey_4_0
+#define ucol_calcSortKeySimpleTertiary ucol_calcSortKeySimpleTertiary_4_0
+#define ucol_cloneBinary ucol_cloneBinary_4_0
+#define ucol_cloneRuleData ucol_cloneRuleData_4_0
+#define ucol_close ucol_close_4_0
+#define ucol_closeElements ucol_closeElements_4_0
+#define ucol_countAvailable ucol_countAvailable_4_0
+#define ucol_createElements ucol_createElements_4_0
+#define ucol_doCE ucol_doCE_4_0
+#define ucol_equal ucol_equal_4_0
+#define ucol_equals ucol_equals_4_0
+#define ucol_forgetUCA ucol_forgetUCA_4_0
+#define ucol_getAttribute ucol_getAttribute_4_0
+#define ucol_getAttributeOrDefault ucol_getAttributeOrDefault_4_0
+#define ucol_getAvailable ucol_getAvailable_4_0
+#define ucol_getBound ucol_getBound_4_0
+#define ucol_getCEStrengthDifference ucol_getCEStrengthDifference_4_0
+#define ucol_getContractions ucol_getContractions_4_0
+#define ucol_getContractionsAndExpansions ucol_getContractionsAndExpansions_4_0
+#define ucol_getDisplayName ucol_getDisplayName_4_0
+#define ucol_getFirstCE ucol_getFirstCE_4_0
+#define ucol_getFunctionalEquivalent ucol_getFunctionalEquivalent_4_0
+#define ucol_getKeywordValues ucol_getKeywordValues_4_0
+#define ucol_getKeywords ucol_getKeywords_4_0
+#define ucol_getLocale ucol_getLocale_4_0
+#define ucol_getLocaleByType ucol_getLocaleByType_4_0
+#define ucol_getMaxExpansion ucol_getMaxExpansion_4_0
+#define ucol_getNextCE ucol_getNextCE_4_0
+#define ucol_getOffset ucol_getOffset_4_0
+#define ucol_getPrevCE ucol_getPrevCE_4_0
+#define ucol_getRules ucol_getRules_4_0
+#define ucol_getRulesEx ucol_getRulesEx_4_0
+#define ucol_getShortDefinitionString ucol_getShortDefinitionString_4_0
+#define ucol_getSortKey ucol_getSortKey_4_0
+#define ucol_getSortKeySize ucol_getSortKeySize_4_0
+#define ucol_getSortKeyWithAllocation ucol_getSortKeyWithAllocation_4_0
+#define ucol_getStrength ucol_getStrength_4_0
+#define ucol_getTailoredSet ucol_getTailoredSet_4_0
+#define ucol_getUCAVersion ucol_getUCAVersion_4_0
+#define ucol_getUnsafeSet ucol_getUnsafeSet_4_0
+#define ucol_getVariableTop ucol_getVariableTop_4_0
+#define ucol_getVersion ucol_getVersion_4_0
+#define ucol_greater ucol_greater_4_0
+#define ucol_greaterOrEqual ucol_greaterOrEqual_4_0
+#define ucol_initBuffers ucol_initBuffers_4_0
+#define ucol_initCollator ucol_initCollator_4_0
+#define ucol_initInverseUCA ucol_initInverseUCA_4_0
+#define ucol_initUCA ucol_initUCA_4_0
+#define ucol_inv_getNextCE ucol_inv_getNextCE_4_0
+#define ucol_inv_getPrevCE ucol_inv_getPrevCE_4_0
+#define ucol_isTailored ucol_isTailored_4_0
+#define ucol_keyHashCode ucol_keyHashCode_4_0
+#define ucol_mergeSortkeys ucol_mergeSortkeys_4_0
+#define ucol_next ucol_next_4_0
+#define ucol_nextProcessed ucol_nextProcessed_4_0
+#define ucol_nextSortKeyPart ucol_nextSortKeyPart_4_0
+#define ucol_nextWeight ucol_nextWeight_4_0
+#define ucol_normalizeShortDefinitionString ucol_normalizeShortDefinitionString_4_0
+#define ucol_open ucol_open_4_0
+#define ucol_openAvailableLocales ucol_openAvailableLocales_4_0
+#define ucol_openBinary ucol_openBinary_4_0
+#define ucol_openElements ucol_openElements_4_0
+#define ucol_openFromShortString ucol_openFromShortString_4_0
+#define ucol_openRules ucol_openRules_4_0
+#define ucol_open_internal ucol_open_internal_4_0
+#define ucol_prepareShortStringOpen ucol_prepareShortStringOpen_4_0
+#define ucol_previous ucol_previous_4_0
+#define ucol_previousProcessed ucol_previousProcessed_4_0
+#define ucol_primaryOrder ucol_primaryOrder_4_0
+#define ucol_prv_getSpecialCE ucol_prv_getSpecialCE_4_0
+#define ucol_prv_getSpecialPrevCE ucol_prv_getSpecialPrevCE_4_0
+#define ucol_reset ucol_reset_4_0
+#define ucol_restoreVariableTop ucol_restoreVariableTop_4_0
+#define ucol_safeClone ucol_safeClone_4_0
+#define ucol_secondaryOrder ucol_secondaryOrder_4_0
+#define ucol_setAttribute ucol_setAttribute_4_0
+#define ucol_setOffset ucol_setOffset_4_0
+#define ucol_setOptionsFromHeader ucol_setOptionsFromHeader_4_0
+#define ucol_setReqValidLocales ucol_setReqValidLocales_4_0
+#define ucol_setStrength ucol_setStrength_4_0
+#define ucol_setText ucol_setText_4_0
+#define ucol_setVariableTop ucol_setVariableTop_4_0
+#define ucol_strcoll ucol_strcoll_4_0
+#define ucol_strcollIter ucol_strcollIter_4_0
+#define ucol_swap ucol_swap_4_0
+#define ucol_swapBinary ucol_swapBinary_4_0
+#define ucol_swapInverseUCA ucol_swapInverseUCA_4_0
+#define ucol_tertiaryOrder ucol_tertiaryOrder_4_0
+#define ucol_tok_assembleTokenList ucol_tok_assembleTokenList_4_0
+#define ucol_tok_closeTokenList ucol_tok_closeTokenList_4_0
+#define ucol_tok_getNextArgument ucol_tok_getNextArgument_4_0
+#define ucol_tok_initTokenList ucol_tok_initTokenList_4_0
+#define ucol_tok_parseNextToken ucol_tok_parseNextToken_4_0
+#define ucol_updateInternalState ucol_updateInternalState_4_0
+#define ucsdet_close ucsdet_close_4_0
+#define ucsdet_detect ucsdet_detect_4_0
+#define ucsdet_detectAll ucsdet_detectAll_4_0
+#define ucsdet_enableInputFilter ucsdet_enableInputFilter_4_0
+#define ucsdet_getAllDetectableCharsets ucsdet_getAllDetectableCharsets_4_0
+#define ucsdet_getConfidence ucsdet_getConfidence_4_0
+#define ucsdet_getLanguage ucsdet_getLanguage_4_0
+#define ucsdet_getName ucsdet_getName_4_0
+#define ucsdet_getUChars ucsdet_getUChars_4_0
+#define ucsdet_isInputFilterEnabled ucsdet_isInputFilterEnabled_4_0
+#define ucsdet_open ucsdet_open_4_0
+#define ucsdet_setDeclaredEncoding ucsdet_setDeclaredEncoding_4_0
+#define ucsdet_setText ucsdet_setText_4_0
+#define ucurr_countCurrencies ucurr_countCurrencies_4_0
+#define ucurr_forLocale ucurr_forLocale_4_0
+#define ucurr_forLocaleAndDate ucurr_forLocaleAndDate_4_0
+#define ucurr_getDefaultFractionDigits ucurr_getDefaultFractionDigits_4_0
+#define ucurr_getName ucurr_getName_4_0
+#define ucurr_getRoundingIncrement ucurr_getRoundingIncrement_4_0
+#define ucurr_openISOCurrencies ucurr_openISOCurrencies_4_0
+#define ucurr_register ucurr_register_4_0
+#define ucurr_unregister ucurr_unregister_4_0
+#define udat_applyPattern udat_applyPattern_4_0
+#define udat_clone udat_clone_4_0
+#define udat_close udat_close_4_0
+#define udat_countAvailable udat_countAvailable_4_0
+#define udat_countSymbols udat_countSymbols_4_0
+#define udat_format udat_format_4_0
+#define udat_get2DigitYearStart udat_get2DigitYearStart_4_0
+#define udat_getAvailable udat_getAvailable_4_0
+#define udat_getCalendar udat_getCalendar_4_0
+#define udat_getLocaleByType udat_getLocaleByType_4_0
+#define udat_getNumberFormat udat_getNumberFormat_4_0
+#define udat_getSymbols udat_getSymbols_4_0
+#define udat_isLenient udat_isLenient_4_0
+#define udat_open udat_open_4_0
+#define udat_parse udat_parse_4_0
+#define udat_parseCalendar udat_parseCalendar_4_0
+#define udat_set2DigitYearStart udat_set2DigitYearStart_4_0
+#define udat_setCalendar udat_setCalendar_4_0
+#define udat_setLenient udat_setLenient_4_0
+#define udat_setNumberFormat udat_setNumberFormat_4_0
+#define udat_setSymbols udat_setSymbols_4_0
+#define udat_toPattern udat_toPattern_4_0
+#define udata_checkCommonData udata_checkCommonData_4_0
+#define udata_close udata_close_4_0
+#define udata_closeSwapper udata_closeSwapper_4_0
+#define udata_getHeaderSize udata_getHeaderSize_4_0
+#define udata_getInfo udata_getInfo_4_0
+#define udata_getInfoSize udata_getInfoSize_4_0
+#define udata_getLength udata_getLength_4_0
+#define udata_getMemory udata_getMemory_4_0
+#define udata_getRawMemory udata_getRawMemory_4_0
+#define udata_open udata_open_4_0
+#define udata_openChoice udata_openChoice_4_0
+#define udata_openSwapper udata_openSwapper_4_0
+#define udata_openSwapperForInputData udata_openSwapperForInputData_4_0
+#define udata_printError udata_printError_4_0
+#define udata_readInt16 udata_readInt16_4_0
+#define udata_readInt32 udata_readInt32_4_0
+#define udata_setAppData udata_setAppData_4_0
+#define udata_setCommonData udata_setCommonData_4_0
+#define udata_setFileAccess udata_setFileAccess_4_0
+#define udata_swapDataHeader udata_swapDataHeader_4_0
+#define udata_swapInvStringBlock udata_swapInvStringBlock_4_0
+#define udatpg_addPattern udatpg_addPattern_4_0
+#define udatpg_clone udatpg_clone_4_0
+#define udatpg_close udatpg_close_4_0
+#define udatpg_getAppendItemFormat udatpg_getAppendItemFormat_4_0
+#define udatpg_getAppendItemName udatpg_getAppendItemName_4_0
+#define udatpg_getBaseSkeleton udatpg_getBaseSkeleton_4_0
+#define udatpg_getBestPattern udatpg_getBestPattern_4_0
+#define udatpg_getDateTimeFormat udatpg_getDateTimeFormat_4_0
+#define udatpg_getDecimal udatpg_getDecimal_4_0
+#define udatpg_getPatternForSkeleton udatpg_getPatternForSkeleton_4_0
+#define udatpg_getSkeleton udatpg_getSkeleton_4_0
+#define udatpg_open udatpg_open_4_0
+#define udatpg_openBaseSkeletons udatpg_openBaseSkeletons_4_0
+#define udatpg_openEmpty udatpg_openEmpty_4_0
+#define udatpg_openSkeletons udatpg_openSkeletons_4_0
+#define udatpg_replaceFieldTypes udatpg_replaceFieldTypes_4_0
+#define udatpg_setAppendItemFormat udatpg_setAppendItemFormat_4_0
+#define udatpg_setAppendItemName udatpg_setAppendItemName_4_0
+#define udatpg_setDateTimeFormat udatpg_setDateTimeFormat_4_0
+#define udatpg_setDecimal udatpg_setDecimal_4_0
+#define uenum_close uenum_close_4_0
+#define uenum_count uenum_count_4_0
+#define uenum_next uenum_next_4_0
+#define uenum_nextDefault uenum_nextDefault_4_0
+#define uenum_openCharStringsEnumeration uenum_openCharStringsEnumeration_4_0
+#define uenum_openStringEnumeration uenum_openStringEnumeration_4_0
+#define uenum_reset uenum_reset_4_0
+#define uenum_unext uenum_unext_4_0
+#define uenum_unextDefault uenum_unextDefault_4_0
+#define ufile_close_translit ufile_close_translit_4_0
+#define ufile_fill_uchar_buffer ufile_fill_uchar_buffer_4_0
+#define ufile_flush_translit ufile_flush_translit_4_0
+#define ufile_getch ufile_getch_4_0
+#define ufile_getch32 ufile_getch32_4_0
+#define ufmt_64tou ufmt_64tou_4_0
+#define ufmt_defaultCPToUnicode ufmt_defaultCPToUnicode_4_0
+#define ufmt_digitvalue ufmt_digitvalue_4_0
+#define ufmt_isdigit ufmt_isdigit_4_0
+#define ufmt_ptou ufmt_ptou_4_0
+#define ufmt_uto64 ufmt_uto64_4_0
+#define ufmt_utop ufmt_utop_4_0
+#define uhash_close uhash_close_4_0
+#define uhash_compareCaselessUnicodeString uhash_compareCaselessUnicodeString_4_0
+#define uhash_compareChars uhash_compareChars_4_0
+#define uhash_compareIChars uhash_compareIChars_4_0
+#define uhash_compareLong uhash_compareLong_4_0
+#define uhash_compareUChars uhash_compareUChars_4_0
+#define uhash_compareUnicodeString uhash_compareUnicodeString_4_0
+#define uhash_count uhash_count_4_0
+#define uhash_deleteHashtable uhash_deleteHashtable_4_0
+#define uhash_deleteUVector uhash_deleteUVector_4_0
+#define uhash_deleteUnicodeString uhash_deleteUnicodeString_4_0
+#define uhash_equals uhash_equals_4_0
+#define uhash_find uhash_find_4_0
+#define uhash_freeBlock uhash_freeBlock_4_0
+#define uhash_get uhash_get_4_0
+#define uhash_geti uhash_geti_4_0
+#define uhash_hashCaselessUnicodeString uhash_hashCaselessUnicodeString_4_0
+#define uhash_hashChars uhash_hashChars_4_0
+#define uhash_hashIChars uhash_hashIChars_4_0
+#define uhash_hashLong uhash_hashLong_4_0
+#define uhash_hashUChars uhash_hashUChars_4_0
+#define uhash_hashUCharsN uhash_hashUCharsN_4_0
+#define uhash_hashUnicodeString uhash_hashUnicodeString_4_0
+#define uhash_iget uhash_iget_4_0
+#define uhash_igeti uhash_igeti_4_0
+#define uhash_init uhash_init_4_0
+#define uhash_iput uhash_iput_4_0
+#define uhash_iputi uhash_iputi_4_0
+#define uhash_iremove uhash_iremove_4_0
+#define uhash_iremovei uhash_iremovei_4_0
+#define uhash_nextElement uhash_nextElement_4_0
+#define uhash_open uhash_open_4_0
+#define uhash_openSize uhash_openSize_4_0
+#define uhash_put uhash_put_4_0
+#define uhash_puti uhash_puti_4_0
+#define uhash_remove uhash_remove_4_0
+#define uhash_removeAll uhash_removeAll_4_0
+#define uhash_removeElement uhash_removeElement_4_0
+#define uhash_removei uhash_removei_4_0
+#define uhash_setKeyComparator uhash_setKeyComparator_4_0
+#define uhash_setKeyDeleter uhash_setKeyDeleter_4_0
+#define uhash_setKeyHasher uhash_setKeyHasher_4_0
+#define uhash_setResizePolicy uhash_setResizePolicy_4_0
+#define uhash_setValueComparator uhash_setValueComparator_4_0
+#define uhash_setValueDeleter uhash_setValueDeleter_4_0
+#define uhst_addPropertyStarts uhst_addPropertyStarts_4_0
+#define uidna_IDNToASCII uidna_IDNToASCII_4_0
+#define uidna_IDNToUnicode uidna_IDNToUnicode_4_0
+#define uidna_compare uidna_compare_4_0
+#define uidna_toASCII uidna_toASCII_4_0
+#define uidna_toUnicode uidna_toUnicode_4_0
+#define uiter_current32 uiter_current32_4_0
+#define uiter_getState uiter_getState_4_0
+#define uiter_next32 uiter_next32_4_0
+#define uiter_previous32 uiter_previous32_4_0
+#define uiter_setCharacterIterator uiter_setCharacterIterator_4_0
+#define uiter_setReplaceable uiter_setReplaceable_4_0
+#define uiter_setState uiter_setState_4_0
+#define uiter_setString uiter_setString_4_0
+#define uiter_setUTF16BE uiter_setUTF16BE_4_0
+#define uiter_setUTF8 uiter_setUTF8_4_0
+#define uloc_acceptLanguage uloc_acceptLanguage_4_0
+#define uloc_acceptLanguageFromHTTP uloc_acceptLanguageFromHTTP_4_0
+#define uloc_addLikelySubtags uloc_addLikelySubtags_4_0
+#define uloc_canonicalize uloc_canonicalize_4_0
+#define uloc_countAvailable uloc_countAvailable_4_0
+#define uloc_getAvailable uloc_getAvailable_4_0
+#define uloc_getBaseName uloc_getBaseName_4_0
+#define uloc_getCharacterOrientation uloc_getCharacterOrientation_4_0
+#define uloc_getCountry uloc_getCountry_4_0
+#define uloc_getDefault uloc_getDefault_4_0
+#define uloc_getDisplayCountry uloc_getDisplayCountry_4_0
+#define uloc_getDisplayKeyword uloc_getDisplayKeyword_4_0
+#define uloc_getDisplayKeywordValue uloc_getDisplayKeywordValue_4_0
+#define uloc_getDisplayLanguage uloc_getDisplayLanguage_4_0
+#define uloc_getDisplayName uloc_getDisplayName_4_0
+#define uloc_getDisplayScript uloc_getDisplayScript_4_0
+#define uloc_getDisplayVariant uloc_getDisplayVariant_4_0
+#define uloc_getISO3Country uloc_getISO3Country_4_0
+#define uloc_getISO3Language uloc_getISO3Language_4_0
+#define uloc_getISOCountries uloc_getISOCountries_4_0
+#define uloc_getISOLanguages uloc_getISOLanguages_4_0
+#define uloc_getKeywordValue uloc_getKeywordValue_4_0
+#define uloc_getLCID uloc_getLCID_4_0
+#define uloc_getLanguage uloc_getLanguage_4_0
+#define uloc_getLineOrientation uloc_getLineOrientation_4_0
+#define uloc_getLocaleForLCID uloc_getLocaleForLCID_4_0
+#define uloc_getName uloc_getName_4_0
+#define uloc_getParent uloc_getParent_4_0
+#define uloc_getScript uloc_getScript_4_0
+#define uloc_getVariant uloc_getVariant_4_0
+#define uloc_minimizeSubtags uloc_minimizeSubtags_4_0
+#define uloc_openKeywordList uloc_openKeywordList_4_0
+#define uloc_openKeywords uloc_openKeywords_4_0
+#define uloc_setDefault uloc_setDefault_4_0
+#define uloc_setKeywordValue uloc_setKeywordValue_4_0
+#define ulocdata_close ulocdata_close_4_0
+#define ulocdata_getDelimiter ulocdata_getDelimiter_4_0
+#define ulocdata_getExemplarSet ulocdata_getExemplarSet_4_0
+#define ulocdata_getMeasurementSystem ulocdata_getMeasurementSystem_4_0
+#define ulocdata_getNoSubstitute ulocdata_getNoSubstitute_4_0
+#define ulocdata_getPaperSize ulocdata_getPaperSize_4_0
+#define ulocdata_open ulocdata_open_4_0
+#define ulocdata_setNoSubstitute ulocdata_setNoSubstitute_4_0
+#define umsg_applyPattern umsg_applyPattern_4_0
+#define umsg_autoQuoteApostrophe umsg_autoQuoteApostrophe_4_0
+#define umsg_clone umsg_clone_4_0
+#define umsg_close umsg_close_4_0
+#define umsg_format umsg_format_4_0
+#define umsg_getLocale umsg_getLocale_4_0
+#define umsg_open umsg_open_4_0
+#define umsg_parse umsg_parse_4_0
+#define umsg_setLocale umsg_setLocale_4_0
+#define umsg_toPattern umsg_toPattern_4_0
+#define umsg_vformat umsg_vformat_4_0
+#define umsg_vparse umsg_vparse_4_0
+#define umtx_atomic_dec umtx_atomic_dec_4_0
+#define umtx_atomic_inc umtx_atomic_inc_4_0
+#define umtx_cleanup umtx_cleanup_4_0
+#define umtx_destroy umtx_destroy_4_0
+#define umtx_init umtx_init_4_0
+#define umtx_lock umtx_lock_4_0
+#define umtx_unlock umtx_unlock_4_0
+#define unorm_addPropertyStarts unorm_addPropertyStarts_4_0
+#define unorm_closeIter unorm_closeIter_4_0
+#define unorm_compare unorm_compare_4_0
+#define unorm_compose unorm_compose_4_0
+#define unorm_concatenate unorm_concatenate_4_0
+#define unorm_decompose unorm_decompose_4_0
+#define unorm_getCanonStartSet unorm_getCanonStartSet_4_0
+#define unorm_getCanonicalDecomposition unorm_getCanonicalDecomposition_4_0
+#define unorm_getDecomposition unorm_getDecomposition_4_0
+#define unorm_getFCD16FromCodePoint unorm_getFCD16FromCodePoint_4_0
+#define unorm_getFCDTrie unorm_getFCDTrie_4_0
+#define unorm_getNX unorm_getNX_4_0
+#define unorm_getQuickCheck unorm_getQuickCheck_4_0
+#define unorm_getUnicodeVersion unorm_getUnicodeVersion_4_0
+#define unorm_haveData unorm_haveData_4_0
+#define unorm_internalIsFullCompositionExclusion unorm_internalIsFullCompositionExclusion_4_0
+#define unorm_internalNormalize unorm_internalNormalize_4_0
+#define unorm_internalNormalizeWithNX unorm_internalNormalizeWithNX_4_0
+#define unorm_internalQuickCheck unorm_internalQuickCheck_4_0
+#define unorm_isCanonSafeStart unorm_isCanonSafeStart_4_0
+#define unorm_isNFSkippable unorm_isNFSkippable_4_0
+#define unorm_isNormalized unorm_isNormalized_4_0
+#define unorm_isNormalizedWithOptions unorm_isNormalizedWithOptions_4_0
+#define unorm_next unorm_next_4_0
+#define unorm_normalize unorm_normalize_4_0
+#define unorm_openIter unorm_openIter_4_0
+#define unorm_previous unorm_previous_4_0
+#define unorm_quickCheck unorm_quickCheck_4_0
+#define unorm_quickCheckWithOptions unorm_quickCheckWithOptions_4_0
+#define unorm_setIter unorm_setIter_4_0
+#define unum_applyPattern unum_applyPattern_4_0
+#define unum_clone unum_clone_4_0
+#define unum_close unum_close_4_0
+#define unum_countAvailable unum_countAvailable_4_0
+#define unum_format unum_format_4_0
+#define unum_formatDouble unum_formatDouble_4_0
+#define unum_formatDoubleCurrency unum_formatDoubleCurrency_4_0
+#define unum_formatInt64 unum_formatInt64_4_0
+#define unum_getAttribute unum_getAttribute_4_0
+#define unum_getAvailable unum_getAvailable_4_0
+#define unum_getDoubleAttribute unum_getDoubleAttribute_4_0
+#define unum_getLocaleByType unum_getLocaleByType_4_0
+#define unum_getSymbol unum_getSymbol_4_0
+#define unum_getTextAttribute unum_getTextAttribute_4_0
+#define unum_open unum_open_4_0
+#define unum_parse unum_parse_4_0
+#define unum_parseDouble unum_parseDouble_4_0
+#define unum_parseDoubleCurrency unum_parseDoubleCurrency_4_0
+#define unum_parseInt64 unum_parseInt64_4_0
+#define unum_setAttribute unum_setAttribute_4_0
+#define unum_setDoubleAttribute unum_setDoubleAttribute_4_0
+#define unum_setSymbol unum_setSymbol_4_0
+#define unum_setTextAttribute unum_setTextAttribute_4_0
+#define unum_toPattern unum_toPattern_4_0
+#define upname_swap upname_swap_4_0
+#define uprops_getSource uprops_getSource_4_0
+#define upropsvec_addPropertyStarts upropsvec_addPropertyStarts_4_0
+#define uprv_asciiFromEbcdic uprv_asciiFromEbcdic_4_0
+#define uprv_asciitolower uprv_asciitolower_4_0
+#define uprv_ceil uprv_ceil_4_0
+#define uprv_cnttab_addContraction uprv_cnttab_addContraction_4_0
+#define uprv_cnttab_changeContraction uprv_cnttab_changeContraction_4_0
+#define uprv_cnttab_changeLastCE uprv_cnttab_changeLastCE_4_0
+#define uprv_cnttab_clone uprv_cnttab_clone_4_0
+#define uprv_cnttab_close uprv_cnttab_close_4_0
+#define uprv_cnttab_constructTable uprv_cnttab_constructTable_4_0
+#define uprv_cnttab_findCE uprv_cnttab_findCE_4_0
+#define uprv_cnttab_findCP uprv_cnttab_findCP_4_0
+#define uprv_cnttab_getCE uprv_cnttab_getCE_4_0
+#define uprv_cnttab_insertContraction uprv_cnttab_insertContraction_4_0
+#define uprv_cnttab_isTailored uprv_cnttab_isTailored_4_0
+#define uprv_cnttab_open uprv_cnttab_open_4_0
+#define uprv_cnttab_setContraction uprv_cnttab_setContraction_4_0
+#define uprv_compareASCIIPropertyNames uprv_compareASCIIPropertyNames_4_0
+#define uprv_compareEBCDICPropertyNames uprv_compareEBCDICPropertyNames_4_0
+#define uprv_compareInvAscii uprv_compareInvAscii_4_0
+#define uprv_compareInvEbcdic uprv_compareInvEbcdic_4_0
+#define uprv_convertToLCID uprv_convertToLCID_4_0
+#define uprv_convertToPosix uprv_convertToPosix_4_0
+#define uprv_copyAscii uprv_copyAscii_4_0
+#define uprv_copyEbcdic uprv_copyEbcdic_4_0
+#define uprv_ebcdicFromAscii uprv_ebcdicFromAscii_4_0
+#define uprv_ebcdictolower uprv_ebcdictolower_4_0
+#define uprv_fabs uprv_fabs_4_0
+#define uprv_floor uprv_floor_4_0
+#define uprv_fmax uprv_fmax_4_0
+#define uprv_fmin uprv_fmin_4_0
+#define uprv_fmod uprv_fmod_4_0
+#define uprv_free uprv_free_4_0
+#define uprv_getCharNameCharacters uprv_getCharNameCharacters_4_0
+#define uprv_getDefaultCodepage uprv_getDefaultCodepage_4_0
+#define uprv_getDefaultLocaleID uprv_getDefaultLocaleID_4_0
+#define uprv_getInfinity uprv_getInfinity_4_0
+#define uprv_getMaxCharNameLength uprv_getMaxCharNameLength_4_0
+#define uprv_getMaxValues uprv_getMaxValues_4_0
+#define uprv_getNaN uprv_getNaN_4_0
+#define uprv_getStaticCurrencyName uprv_getStaticCurrencyName_4_0
+#define uprv_getUTCtime uprv_getUTCtime_4_0
+#define uprv_haveProperties uprv_haveProperties_4_0
+#define uprv_init_collIterate uprv_init_collIterate_4_0
+#define uprv_init_pce uprv_init_pce_4_0
+#define uprv_int32Comparator uprv_int32Comparator_4_0
+#define uprv_isInfinite uprv_isInfinite_4_0
+#define uprv_isInvariantString uprv_isInvariantString_4_0
+#define uprv_isInvariantUString uprv_isInvariantUString_4_0
+#define uprv_isNaN uprv_isNaN_4_0
+#define uprv_isNegativeInfinity uprv_isNegativeInfinity_4_0
+#define uprv_isPositiveInfinity uprv_isPositiveInfinity_4_0
+#define uprv_isRuleWhiteSpace uprv_isRuleWhiteSpace_4_0
+#define uprv_itou uprv_itou_4_0
+#define uprv_log uprv_log_4_0
+#define uprv_malloc uprv_malloc_4_0
+#define uprv_mapFile uprv_mapFile_4_0
+#define uprv_max uprv_max_4_0
+#define uprv_maxMantissa uprv_maxMantissa_4_0
+#define uprv_maximumPtr uprv_maximumPtr_4_0
+#define uprv_min uprv_min_4_0
+#define uprv_modf uprv_modf_4_0
+#define uprv_openRuleWhiteSpaceSet uprv_openRuleWhiteSpaceSet_4_0
+#define uprv_parseCurrency uprv_parseCurrency_4_0
+#define uprv_pathIsAbsolute uprv_pathIsAbsolute_4_0
+#define uprv_pow uprv_pow_4_0
+#define uprv_pow10 uprv_pow10_4_0
+#define uprv_realloc uprv_realloc_4_0
+#define uprv_round uprv_round_4_0
+#define uprv_sortArray uprv_sortArray_4_0
+#define uprv_strCompare uprv_strCompare_4_0
+#define uprv_strdup uprv_strdup_4_0
+#define uprv_strndup uprv_strndup_4_0
+#define uprv_syntaxError uprv_syntaxError_4_0
+#define uprv_timezone uprv_timezone_4_0
+#define uprv_toupper uprv_toupper_4_0
+#define uprv_trunc uprv_trunc_4_0
+#define uprv_tzname uprv_tzname_4_0
+#define uprv_tzset uprv_tzset_4_0
+#define uprv_uca_addAnElement uprv_uca_addAnElement_4_0
+#define uprv_uca_assembleTable uprv_uca_assembleTable_4_0
+#define uprv_uca_canonicalClosure uprv_uca_canonicalClosure_4_0
+#define uprv_uca_closeTempTable uprv_uca_closeTempTable_4_0
+#define uprv_uca_getCodePointFromRaw uprv_uca_getCodePointFromRaw_4_0
+#define uprv_uca_getImplicitFromRaw uprv_uca_getImplicitFromRaw_4_0
+#define uprv_uca_getRawFromCodePoint uprv_uca_getRawFromCodePoint_4_0
+#define uprv_uca_getRawFromImplicit uprv_uca_getRawFromImplicit_4_0
+#define uprv_uca_initImplicitConstants uprv_uca_initImplicitConstants_4_0
+#define uprv_uca_initTempTable uprv_uca_initTempTable_4_0
+#define uprv_uint16Comparator uprv_uint16Comparator_4_0
+#define uprv_uint32Comparator uprv_uint32Comparator_4_0
+#define uprv_unmapFile uprv_unmapFile_4_0
+#define uregex_appendReplacement uregex_appendReplacement_4_0
+#define uregex_appendTail uregex_appendTail_4_0
+#define uregex_clone uregex_clone_4_0
+#define uregex_close uregex_close_4_0
+#define uregex_end uregex_end_4_0
+#define uregex_find uregex_find_4_0
+#define uregex_findNext uregex_findNext_4_0
+#define uregex_flags uregex_flags_4_0
+#define uregex_getMatchCallback uregex_getMatchCallback_4_0
+#define uregex_getStackLimit uregex_getStackLimit_4_0
+#define uregex_getText uregex_getText_4_0
+#define uregex_getTimeLimit uregex_getTimeLimit_4_0
+#define uregex_group uregex_group_4_0
+#define uregex_groupCount uregex_groupCount_4_0
+#define uregex_hasAnchoringBounds uregex_hasAnchoringBounds_4_0
+#define uregex_hasTransparentBounds uregex_hasTransparentBounds_4_0
+#define uregex_hitEnd uregex_hitEnd_4_0
+#define uregex_lookingAt uregex_lookingAt_4_0
+#define uregex_matches uregex_matches_4_0
+#define uregex_open uregex_open_4_0
+#define uregex_openC uregex_openC_4_0
+#define uregex_pattern uregex_pattern_4_0
+#define uregex_regionEnd uregex_regionEnd_4_0
+#define uregex_regionStart uregex_regionStart_4_0
+#define uregex_replaceAll uregex_replaceAll_4_0
+#define uregex_replaceFirst uregex_replaceFirst_4_0
+#define uregex_requireEnd uregex_requireEnd_4_0
+#define uregex_reset uregex_reset_4_0
+#define uregex_setMatchCallback uregex_setMatchCallback_4_0
+#define uregex_setRegion uregex_setRegion_4_0
+#define uregex_setStackLimit uregex_setStackLimit_4_0
+#define uregex_setText uregex_setText_4_0
+#define uregex_setTimeLimit uregex_setTimeLimit_4_0
+#define uregex_split uregex_split_4_0
+#define uregex_start uregex_start_4_0
+#define uregex_useAnchoringBounds uregex_useAnchoringBounds_4_0
+#define uregex_useTransparentBounds uregex_useTransparentBounds_4_0
+#define ures_close ures_close_4_0
+#define ures_copyResb ures_copyResb_4_0
+#define ures_countArrayItems ures_countArrayItems_4_0
+#define ures_findResource ures_findResource_4_0
+#define ures_findSubResource ures_findSubResource_4_0
+#define ures_getBinary ures_getBinary_4_0
+#define ures_getByIndex ures_getByIndex_4_0
+#define ures_getByKey ures_getByKey_4_0
+#define ures_getByKeyWithFallback ures_getByKeyWithFallback_4_0
+#define ures_getFunctionalEquivalent ures_getFunctionalEquivalent_4_0
+#define ures_getInt ures_getInt_4_0
+#define ures_getIntVector ures_getIntVector_4_0
+#define ures_getKey ures_getKey_4_0
+#define ures_getKeywordValues ures_getKeywordValues_4_0
+#define ures_getLocale ures_getLocale_4_0
+#define ures_getLocaleByType ures_getLocaleByType_4_0
+#define ures_getName ures_getName_4_0
+#define ures_getNextResource ures_getNextResource_4_0
+#define ures_getNextString ures_getNextString_4_0
+#define ures_getSize ures_getSize_4_0
+#define ures_getString ures_getString_4_0
+#define ures_getStringByIndex ures_getStringByIndex_4_0
+#define ures_getStringByKey ures_getStringByKey_4_0
+#define ures_getStringByKeyWithFallback ures_getStringByKeyWithFallback_4_0
+#define ures_getType ures_getType_4_0
+#define ures_getUInt ures_getUInt_4_0
+#define ures_getUTF8String ures_getUTF8String_4_0
+#define ures_getUTF8StringByIndex ures_getUTF8StringByIndex_4_0
+#define ures_getUTF8StringByKey ures_getUTF8StringByKey_4_0
+#define ures_getVersion ures_getVersion_4_0
+#define ures_getVersionNumber ures_getVersionNumber_4_0
+#define ures_hasNext ures_hasNext_4_0
+#define ures_initStackObject ures_initStackObject_4_0
+#define ures_open ures_open_4_0
+#define ures_openAvailableLocales ures_openAvailableLocales_4_0
+#define ures_openDirect ures_openDirect_4_0
+#define ures_openFillIn ures_openFillIn_4_0
+#define ures_openU ures_openU_4_0
+#define ures_resetIterator ures_resetIterator_4_0
+#define ures_swap ures_swap_4_0
+#define uscript_closeRun uscript_closeRun_4_0
+#define uscript_getCode uscript_getCode_4_0
+#define uscript_getName uscript_getName_4_0
+#define uscript_getScript uscript_getScript_4_0
+#define uscript_getShortName uscript_getShortName_4_0
+#define uscript_nextRun uscript_nextRun_4_0
+#define uscript_openRun uscript_openRun_4_0
+#define uscript_resetRun uscript_resetRun_4_0
+#define uscript_setRunText uscript_setRunText_4_0
+#define usearch_close usearch_close_4_0
+#define usearch_first usearch_first_4_0
+#define usearch_following usearch_following_4_0
+#define usearch_getAttribute usearch_getAttribute_4_0
+#define usearch_getBreakIterator usearch_getBreakIterator_4_0
+#define usearch_getCollator usearch_getCollator_4_0
+#define usearch_getMatchedLength usearch_getMatchedLength_4_0
+#define usearch_getMatchedStart usearch_getMatchedStart_4_0
+#define usearch_getMatchedText usearch_getMatchedText_4_0
+#define usearch_getOffset usearch_getOffset_4_0
+#define usearch_getPattern usearch_getPattern_4_0
+#define usearch_getText usearch_getText_4_0
+#define usearch_handleNextCanonical usearch_handleNextCanonical_4_0
+#define usearch_handleNextExact usearch_handleNextExact_4_0
+#define usearch_handlePreviousCanonical usearch_handlePreviousCanonical_4_0
+#define usearch_handlePreviousExact usearch_handlePreviousExact_4_0
+#define usearch_last usearch_last_4_0
+#define usearch_next usearch_next_4_0
+#define usearch_open usearch_open_4_0
+#define usearch_openFromCollator usearch_openFromCollator_4_0
+#define usearch_preceding usearch_preceding_4_0
+#define usearch_previous usearch_previous_4_0
+#define usearch_reset usearch_reset_4_0
+#define usearch_search usearch_search_4_0
+#define usearch_searchBackwards usearch_searchBackwards_4_0
+#define usearch_setAttribute usearch_setAttribute_4_0
+#define usearch_setBreakIterator usearch_setBreakIterator_4_0
+#define usearch_setCollator usearch_setCollator_4_0
+#define usearch_setOffset usearch_setOffset_4_0
+#define usearch_setPattern usearch_setPattern_4_0
+#define usearch_setText usearch_setText_4_0
+#define uset_add uset_add_4_0
+#define uset_addAll uset_addAll_4_0
+#define uset_addAllCodePoints uset_addAllCodePoints_4_0
+#define uset_addRange uset_addRange_4_0
+#define uset_addString uset_addString_4_0
+#define uset_applyIntPropertyValue uset_applyIntPropertyValue_4_0
+#define uset_applyPattern uset_applyPattern_4_0
+#define uset_applyPropertyAlias uset_applyPropertyAlias_4_0
+#define uset_charAt uset_charAt_4_0
+#define uset_clear uset_clear_4_0
+#define uset_clone uset_clone_4_0
+#define uset_cloneAsThawed uset_cloneAsThawed_4_0
+#define uset_close uset_close_4_0
+#define uset_compact uset_compact_4_0
+#define uset_complement uset_complement_4_0
+#define uset_complementAll uset_complementAll_4_0
+#define uset_contains uset_contains_4_0
+#define uset_containsAll uset_containsAll_4_0
+#define uset_containsAllCodePoints uset_containsAllCodePoints_4_0
+#define uset_containsNone uset_containsNone_4_0
+#define uset_containsRange uset_containsRange_4_0
+#define uset_containsSome uset_containsSome_4_0
+#define uset_containsString uset_containsString_4_0
+#define uset_equals uset_equals_4_0
+#define uset_freeze uset_freeze_4_0
+#define uset_getItem uset_getItem_4_0
+#define uset_getItemCount uset_getItemCount_4_0
+#define uset_getSerializedRange uset_getSerializedRange_4_0
+#define uset_getSerializedRangeCount uset_getSerializedRangeCount_4_0
+#define uset_getSerializedSet uset_getSerializedSet_4_0
+#define uset_indexOf uset_indexOf_4_0
+#define uset_isEmpty uset_isEmpty_4_0
+#define uset_isFrozen uset_isFrozen_4_0
+#define uset_open uset_open_4_0
+#define uset_openPattern uset_openPattern_4_0
+#define uset_openPatternOptions uset_openPatternOptions_4_0
+#define uset_remove uset_remove_4_0
+#define uset_removeAll uset_removeAll_4_0
+#define uset_removeRange uset_removeRange_4_0
+#define uset_removeString uset_removeString_4_0
+#define uset_resemblesPattern uset_resemblesPattern_4_0
+#define uset_retain uset_retain_4_0
+#define uset_retainAll uset_retainAll_4_0
+#define uset_serialize uset_serialize_4_0
+#define uset_serializedContains uset_serializedContains_4_0
+#define uset_set uset_set_4_0
+#define uset_setSerializedToOne uset_setSerializedToOne_4_0
+#define uset_size uset_size_4_0
+#define uset_span uset_span_4_0
+#define uset_spanBack uset_spanBack_4_0
+#define uset_spanBackUTF8 uset_spanBackUTF8_4_0
+#define uset_spanUTF8 uset_spanUTF8_4_0
+#define uset_toPattern uset_toPattern_4_0
+#define usprep_close usprep_close_4_0
+#define usprep_open usprep_open_4_0
+#define usprep_prepare usprep_prepare_4_0
+#define usprep_swap usprep_swap_4_0
+#define ustr_foldCase ustr_foldCase_4_0
+#define ustr_toLower ustr_toLower_4_0
+#define ustr_toTitle ustr_toTitle_4_0
+#define ustr_toUpper ustr_toUpper_4_0
+#define utext_char32At utext_char32At_4_0
+#define utext_clone utext_clone_4_0
+#define utext_close utext_close_4_0
+#define utext_copy utext_copy_4_0
+#define utext_current32 utext_current32_4_0
+#define utext_equals utext_equals_4_0
+#define utext_extract utext_extract_4_0
+#define utext_freeze utext_freeze_4_0
+#define utext_getNativeIndex utext_getNativeIndex_4_0
+#define utext_getPreviousNativeIndex utext_getPreviousNativeIndex_4_0
+#define utext_hasMetaData utext_hasMetaData_4_0
+#define utext_isLengthExpensive utext_isLengthExpensive_4_0
+#define utext_isWritable utext_isWritable_4_0
+#define utext_moveIndex32 utext_moveIndex32_4_0
+#define utext_nativeLength utext_nativeLength_4_0
+#define utext_next32 utext_next32_4_0
+#define utext_next32From utext_next32From_4_0
+#define utext_openCharacterIterator utext_openCharacterIterator_4_0
+#define utext_openConstUnicodeString utext_openConstUnicodeString_4_0
+#define utext_openReplaceable utext_openReplaceable_4_0
+#define utext_openUChars utext_openUChars_4_0
+#define utext_openUTF8 utext_openUTF8_4_0
+#define utext_openUnicodeString utext_openUnicodeString_4_0
+#define utext_previous32 utext_previous32_4_0
+#define utext_previous32From utext_previous32From_4_0
+#define utext_replace utext_replace_4_0
+#define utext_setNativeIndex utext_setNativeIndex_4_0
+#define utext_setup utext_setup_4_0
+#define utf8_appendCharSafeBody utf8_appendCharSafeBody_4_0
+#define utf8_back1SafeBody utf8_back1SafeBody_4_0
+#define utf8_countTrailBytes utf8_countTrailBytes_4_0
+#define utf8_nextCharSafeBody utf8_nextCharSafeBody_4_0
+#define utf8_prevCharSafeBody utf8_prevCharSafeBody_4_0
+#define utmscale_fromInt64 utmscale_fromInt64_4_0
+#define utmscale_getTimeScaleValue utmscale_getTimeScaleValue_4_0
+#define utmscale_toInt64 utmscale_toInt64_4_0
+#define utrace_cleanup utrace_cleanup_4_0
+#define utrace_data utrace_data_4_0
+#define utrace_entry utrace_entry_4_0
+#define utrace_exit utrace_exit_4_0
+#define utrace_format utrace_format_4_0
+#define utrace_functionName utrace_functionName_4_0
+#define utrace_getFunctions utrace_getFunctions_4_0
+#define utrace_getLevel utrace_getLevel_4_0
+#define utrace_level utrace_level_4_0
+#define utrace_setFunctions utrace_setFunctions_4_0
+#define utrace_setLevel utrace_setLevel_4_0
+#define utrace_vformat utrace_vformat_4_0
+#define utrans_clone utrans_clone_4_0
+#define utrans_close utrans_close_4_0
+#define utrans_countAvailableIDs utrans_countAvailableIDs_4_0
+#define utrans_getAvailableID utrans_getAvailableID_4_0
+#define utrans_getID utrans_getID_4_0
+#define utrans_getUnicodeID utrans_getUnicodeID_4_0
+#define utrans_open utrans_open_4_0
+#define utrans_openIDs utrans_openIDs_4_0
+#define utrans_openInverse utrans_openInverse_4_0
+#define utrans_openU utrans_openU_4_0
+#define utrans_register utrans_register_4_0
+#define utrans_rep_caseContextIterator utrans_rep_caseContextIterator_4_0
+#define utrans_setFilter utrans_setFilter_4_0
+#define utrans_stripRules utrans_stripRules_4_0
+#define utrans_trans utrans_trans_4_0
+#define utrans_transIncremental utrans_transIncremental_4_0
+#define utrans_transIncrementalUChars utrans_transIncrementalUChars_4_0
+#define utrans_transUChars utrans_transUChars_4_0
+#define utrans_unregister utrans_unregister_4_0
+#define utrans_unregisterID utrans_unregisterID_4_0
+#define utrie_clone utrie_clone_4_0
+#define utrie_close utrie_close_4_0
+#define utrie_defaultGetFoldingOffset utrie_defaultGetFoldingOffset_4_0
+#define utrie_enum utrie_enum_4_0
+#define utrie_get32 utrie_get32_4_0
+#define utrie_getData utrie_getData_4_0
+#define utrie_open utrie_open_4_0
+#define utrie_serialize utrie_serialize_4_0
+#define utrie_set32 utrie_set32_4_0
+#define utrie_setRange32 utrie_setRange32_4_0
+#define utrie_swap utrie_swap_4_0
+#define utrie_unserialize utrie_unserialize_4_0
+#define utrie_unserializeDummy utrie_unserializeDummy_4_0
+/* C++ class names renaming defines */
+
+#ifdef XP_CPLUSPLUS
+#if !U_HAVE_NAMESPACE
+
+#define AbsoluteValueSubstitution AbsoluteValueSubstitution_4_0
+#define AlternateSubstitutionSubtable AlternateSubstitutionSubtable_4_0
+#define AnchorTable AnchorTable_4_0
+#define AndConstraint AndConstraint_4_0
+#define AnnualTimeZoneRule AnnualTimeZoneRule_4_0
+#define AnyTransliterator AnyTransliterator_4_0
+#define ArabicOpenTypeLayoutEngine ArabicOpenTypeLayoutEngine_4_0
+#define ArabicShaping ArabicShaping_4_0
+#define BMPSet BMPSet_4_0
+#define BasicCalendarFactory BasicCalendarFactory_4_0
+#define BasicTimeZone BasicTimeZone_4_0
+#define BinarySearchLookupTable BinarySearchLookupTable_4_0
+#define BreakIterator BreakIterator_4_0
+#define BreakTransliterator BreakTransliterator_4_0
+#define BuddhistCalendar BuddhistCalendar_4_0
+#define BuildCompactTrieHorizontalNode BuildCompactTrieHorizontalNode_4_0
+#define BuildCompactTrieNode BuildCompactTrieNode_4_0
+#define BuildCompactTrieVerticalNode BuildCompactTrieVerticalNode_4_0
+#define CEBuffer CEBuffer_4_0
+#define CECalendar CECalendar_4_0
+#define CFactory CFactory_4_0
+#define Calendar Calendar_4_0
+#define CalendarAstronomer CalendarAstronomer_4_0
+#define CalendarCache CalendarCache_4_0
+#define CalendarData CalendarData_4_0
+#define CalendarService CalendarService_4_0
+#define CanonMarkFilter CanonMarkFilter_4_0
+#define CanonShaping CanonShaping_4_0
+#define CanonicalIterator CanonicalIterator_4_0
+#define CaseMapTransliterator CaseMapTransliterator_4_0
+#define ChainingContextualSubstitutionFormat1Subtable ChainingContextualSubstitutionFormat1Subtable_4_0
+#define ChainingContextualSubstitutionFormat2Subtable ChainingContextualSubstitutionFormat2Subtable_4_0
+#define ChainingContextualSubstitutionFormat3Subtable ChainingContextualSubstitutionFormat3Subtable_4_0
+#define ChainingContextualSubstitutionSubtable ChainingContextualSubstitutionSubtable_4_0
+#define CharSubstitutionFilter CharSubstitutionFilter_4_0
+#define CharacterIterator CharacterIterator_4_0
+#define CharacterNode CharacterNode_4_0
+#define CharsetDetector CharsetDetector_4_0
+#define CharsetMatch CharsetMatch_4_0
+#define CharsetRecog_2022 CharsetRecog_2022_4_0
+#define CharsetRecog_2022CN CharsetRecog_2022CN_4_0
+#define CharsetRecog_2022JP CharsetRecog_2022JP_4_0
+#define CharsetRecog_2022KR CharsetRecog_2022KR_4_0
+#define CharsetRecog_8859_1 CharsetRecog_8859_1_4_0
+#define CharsetRecog_8859_1_da CharsetRecog_8859_1_da_4_0
+#define CharsetRecog_8859_1_de CharsetRecog_8859_1_de_4_0
+#define CharsetRecog_8859_1_en CharsetRecog_8859_1_en_4_0
+#define CharsetRecog_8859_1_es CharsetRecog_8859_1_es_4_0
+#define CharsetRecog_8859_1_fr CharsetRecog_8859_1_fr_4_0
+#define CharsetRecog_8859_1_it CharsetRecog_8859_1_it_4_0
+#define CharsetRecog_8859_1_nl CharsetRecog_8859_1_nl_4_0
+#define CharsetRecog_8859_1_no CharsetRecog_8859_1_no_4_0
+#define CharsetRecog_8859_1_pt CharsetRecog_8859_1_pt_4_0
+#define CharsetRecog_8859_1_sv CharsetRecog_8859_1_sv_4_0
+#define CharsetRecog_8859_2 CharsetRecog_8859_2_4_0
+#define CharsetRecog_8859_2_cs CharsetRecog_8859_2_cs_4_0
+#define CharsetRecog_8859_2_hu CharsetRecog_8859_2_hu_4_0
+#define CharsetRecog_8859_2_pl CharsetRecog_8859_2_pl_4_0
+#define CharsetRecog_8859_2_ro CharsetRecog_8859_2_ro_4_0
+#define CharsetRecog_8859_5 CharsetRecog_8859_5_4_0
+#define CharsetRecog_8859_5_ru CharsetRecog_8859_5_ru_4_0
+#define CharsetRecog_8859_6 CharsetRecog_8859_6_4_0
+#define CharsetRecog_8859_6_ar CharsetRecog_8859_6_ar_4_0
+#define CharsetRecog_8859_7 CharsetRecog_8859_7_4_0
+#define CharsetRecog_8859_7_el CharsetRecog_8859_7_el_4_0
+#define CharsetRecog_8859_8 CharsetRecog_8859_8_4_0
+#define CharsetRecog_8859_8_I_he CharsetRecog_8859_8_I_he_4_0
+#define CharsetRecog_8859_8_he CharsetRecog_8859_8_he_4_0
+#define CharsetRecog_8859_9 CharsetRecog_8859_9_4_0
+#define CharsetRecog_8859_9_tr CharsetRecog_8859_9_tr_4_0
+#define CharsetRecog_KOI8_R CharsetRecog_KOI8_R_4_0
+#define CharsetRecog_UTF8 CharsetRecog_UTF8_4_0
+#define CharsetRecog_UTF_16_BE CharsetRecog_UTF_16_BE_4_0
+#define CharsetRecog_UTF_16_LE CharsetRecog_UTF_16_LE_4_0
+#define CharsetRecog_UTF_32 CharsetRecog_UTF_32_4_0
+#define CharsetRecog_UTF_32_BE CharsetRecog_UTF_32_BE_4_0
+#define CharsetRecog_UTF_32_LE CharsetRecog_UTF_32_LE_4_0
+#define CharsetRecog_Unicode CharsetRecog_Unicode_4_0
+#define CharsetRecog_big5 CharsetRecog_big5_4_0
+#define CharsetRecog_euc CharsetRecog_euc_4_0
+#define CharsetRecog_euc_jp CharsetRecog_euc_jp_4_0
+#define CharsetRecog_euc_kr CharsetRecog_euc_kr_4_0
+#define CharsetRecog_gb_18030 CharsetRecog_gb_18030_4_0
+#define CharsetRecog_mbcs CharsetRecog_mbcs_4_0
+#define CharsetRecog_sbcs CharsetRecog_sbcs_4_0
+#define CharsetRecog_sjis CharsetRecog_sjis_4_0
+#define CharsetRecog_windows_1251 CharsetRecog_windows_1251_4_0
+#define CharsetRecog_windows_1256 CharsetRecog_windows_1256_4_0
+#define CharsetRecognizer CharsetRecognizer_4_0
+#define ChineseCalendar ChineseCalendar_4_0
+#define ChoiceFormat ChoiceFormat_4_0
+#define ClassDefFormat1Table ClassDefFormat1Table_4_0
+#define ClassDefFormat2Table ClassDefFormat2Table_4_0
+#define ClassDefinitionTable ClassDefinitionTable_4_0
+#define CollationElementIterator CollationElementIterator_4_0
+#define CollationKey CollationKey_4_0
+#define CollationLocaleListEnumeration CollationLocaleListEnumeration_4_0
+#define Collator Collator_4_0
+#define CollatorFactory CollatorFactory_4_0
+#define CompactTrieDictionary CompactTrieDictionary_4_0
+#define CompactTrieEnumeration CompactTrieEnumeration_4_0
+#define CompoundTransliterator CompoundTransliterator_4_0
+#define ContextualGlyphSubstitutionProcessor ContextualGlyphSubstitutionProcessor_4_0
+#define ContextualSubstitutionBase ContextualSubstitutionBase_4_0
+#define ContextualSubstitutionFormat1Subtable ContextualSubstitutionFormat1Subtable_4_0
+#define ContextualSubstitutionFormat2Subtable ContextualSubstitutionFormat2Subtable_4_0
+#define ContextualSubstitutionFormat3Subtable ContextualSubstitutionFormat3Subtable_4_0
+#define ContextualSubstitutionSubtable ContextualSubstitutionSubtable_4_0
+#define CopticCalendar CopticCalendar_4_0
+#define CoverageFormat1Table CoverageFormat1Table_4_0
+#define CoverageFormat2Table CoverageFormat2Table_4_0
+#define CoverageTable CoverageTable_4_0
+#define CurrencyAmount CurrencyAmount_4_0
+#define CurrencyFormat CurrencyFormat_4_0
+#define CurrencyUnit CurrencyUnit_4_0
+#define CursiveAttachmentSubtable CursiveAttachmentSubtable_4_0
+#define DTRedundantEnumeration DTRedundantEnumeration_4_0
+#define DTSkeletonEnumeration DTSkeletonEnumeration_4_0
+#define DateFormat DateFormat_4_0
+#define DateFormatSymbols DateFormatSymbols_4_0
+#define DateInterval DateInterval_4_0
+#define DateIntervalFormat DateIntervalFormat_4_0
+#define DateIntervalInfo DateIntervalInfo_4_0
+#define DateTimeMatcher DateTimeMatcher_4_0
+#define DateTimePatternGenerator DateTimePatternGenerator_4_0
+#define DateTimeRule DateTimeRule_4_0
+#define DecimalFormat DecimalFormat_4_0
+#define DecimalFormatSymbols DecimalFormatSymbols_4_0
+#define DefaultCalendarFactory DefaultCalendarFactory_4_0
+#define DefaultCharMapper DefaultCharMapper_4_0
+#define DeviceTable DeviceTable_4_0
+#define DictionaryBreakEngine DictionaryBreakEngine_4_0
+#define DigitList DigitList_4_0
+#define DistanceInfo DistanceInfo_4_0
+#define Entry Entry_4_0
+#define EnumToOffset EnumToOffset_4_0
+#define EscapeTransliterator EscapeTransliterator_4_0
+#define EthiopicCalendar EthiopicCalendar_4_0
+#define EventListener EventListener_4_0
+#define ExtensionSubtable ExtensionSubtable_4_0
+#define FeatureListTable FeatureListTable_4_0
+#define FieldPosition FieldPosition_4_0
+#define FontRuns FontRuns_4_0
+#define Format Format_4_0
+#define Format1AnchorTable Format1AnchorTable_4_0
+#define Format2AnchorTable Format2AnchorTable_4_0
+#define Format3AnchorTable Format3AnchorTable_4_0
+#define FormatNameEnumeration FormatNameEnumeration_4_0
+#define FormatParser FormatParser_4_0
+#define Formattable Formattable_4_0
+#define ForwardCharacterIterator ForwardCharacterIterator_4_0
+#define FractionalPartSubstitution FractionalPartSubstitution_4_0
+#define FunctionReplacer FunctionReplacer_4_0
+#define GDEFMarkFilter GDEFMarkFilter_4_0
+#define GXLayoutEngine GXLayoutEngine_4_0
+#define GlyphDefinitionTableHeader GlyphDefinitionTableHeader_4_0
+#define GlyphIterator GlyphIterator_4_0
+#define GlyphLookupTableHeader GlyphLookupTableHeader_4_0
+#define GlyphPositionAdjustments GlyphPositionAdjustments_4_0
+#define GlyphPositioningLookupProcessor GlyphPositioningLookupProcessor_4_0
+#define GlyphPositioningTableHeader GlyphPositioningTableHeader_4_0
+#define GlyphSubstitutionLookupProcessor GlyphSubstitutionLookupProcessor_4_0
+#define GlyphSubstitutionTableHeader GlyphSubstitutionTableHeader_4_0
+#define Grego Grego_4_0
+#define GregorianCalendar GregorianCalendar_4_0
+#define HanOpenTypeLayoutEngine HanOpenTypeLayoutEngine_4_0
+#define HangulOpenTypeLayoutEngine HangulOpenTypeLayoutEngine_4_0
+#define HebrewCalendar HebrewCalendar_4_0
+#define ICUBreakIteratorFactory ICUBreakIteratorFactory_4_0
+#define ICUBreakIteratorService ICUBreakIteratorService_4_0
+#define ICUCollatorFactory ICUCollatorFactory_4_0
+#define ICUCollatorService ICUCollatorService_4_0
+#define ICULanguageBreakFactory ICULanguageBreakFactory_4_0
+#define ICULocaleService ICULocaleService_4_0
+#define ICUNotifier ICUNotifier_4_0
+#define ICUNumberFormatFactory ICUNumberFormatFactory_4_0
+#define ICUNumberFormatService ICUNumberFormatService_4_0
+#define ICUResourceBundleFactory ICUResourceBundleFactory_4_0
+#define ICUService ICUService_4_0
+#define ICUServiceFactory ICUServiceFactory_4_0
+#define ICUServiceKey ICUServiceKey_4_0
+#define ICU_Utility ICU_Utility_4_0
+#define IndianCalendar IndianCalendar_4_0
+#define IndicClassTable IndicClassTable_4_0
+#define IndicOpenTypeLayoutEngine IndicOpenTypeLayoutEngine_4_0
+#define IndicRearrangementProcessor IndicRearrangementProcessor_4_0
+#define IndicReordering IndicReordering_4_0
+#define InitialTimeZoneRule InitialTimeZoneRule_4_0
+#define InputText InputText_4_0
+#define IntegralPartSubstitution IntegralPartSubstitution_4_0
+#define IslamicCalendar IslamicCalendar_4_0
+#define IteratedChar IteratedChar_4_0
+#define JapaneseCalendar JapaneseCalendar_4_0
+#define KernTable KernTable_4_0
+#define KeywordEnumeration KeywordEnumeration_4_0
+#define KhmerClassTable KhmerClassTable_4_0
+#define KhmerOpenTypeLayoutEngine KhmerOpenTypeLayoutEngine_4_0
+#define KhmerReordering KhmerReordering_4_0
+#define LECharMapper LECharMapper_4_0
+#define LEFontInstance LEFontInstance_4_0
+#define LEGlyphFilter LEGlyphFilter_4_0
+#define LEGlyphStorage LEGlyphStorage_4_0
+#define LEInsertionCallback LEInsertionCallback_4_0
+#define LEInsertionList LEInsertionList_4_0
+#define LXUtilities LXUtilities_4_0
+#define LanguageBreakEngine LanguageBreakEngine_4_0
+#define LanguageBreakFactory LanguageBreakFactory_4_0
+#define LayoutEngine LayoutEngine_4_0
+#define LigatureSubstitutionProcessor LigatureSubstitutionProcessor_4_0
+#define LigatureSubstitutionSubtable LigatureSubstitutionSubtable_4_0
+#define LocDataParser LocDataParser_4_0
+#define Locale Locale_4_0
+#define LocaleBased LocaleBased_4_0
+#define LocaleKey LocaleKey_4_0
+#define LocaleKeyFactory LocaleKeyFactory_4_0
+#define LocaleRuns LocaleRuns_4_0
+#define LocaleUtility LocaleUtility_4_0
+#define LocalizationInfo LocalizationInfo_4_0
+#define LookupListTable LookupListTable_4_0
+#define LookupProcessor LookupProcessor_4_0
+#define LookupSubtable LookupSubtable_4_0
+#define LookupTable LookupTable_4_0
+#define LowercaseTransliterator LowercaseTransliterator_4_0
+#define MPreFixups MPreFixups_4_0
+#define MarkArray MarkArray_4_0
+#define MarkToBasePositioningSubtable MarkToBasePositioningSubtable_4_0
+#define MarkToLigaturePositioningSubtable MarkToLigaturePositioningSubtable_4_0
+#define MarkToMarkPositioningSubtable MarkToMarkPositioningSubtable_4_0
+#define Math Math_4_0
+#define Measure Measure_4_0
+#define MeasureFormat MeasureFormat_4_0
+#define MeasureUnit MeasureUnit_4_0
+#define MessageFormat MessageFormat_4_0
+#define MessageFormatAdapter MessageFormatAdapter_4_0
+#define ModulusSubstitution ModulusSubstitution_4_0
+#define MoonRiseSetCoordFunc MoonRiseSetCoordFunc_4_0
+#define MoonTimeAngleFunc MoonTimeAngleFunc_4_0
+#define MorphSubtableHeader MorphSubtableHeader_4_0
+#define MorphTableHeader MorphTableHeader_4_0
+#define MultipleSubstitutionSubtable MultipleSubstitutionSubtable_4_0
+#define MultiplierSubstitution MultiplierSubstitution_4_0
+#define MutableTrieDictionary MutableTrieDictionary_4_0
+#define MutableTrieEnumeration MutableTrieEnumeration_4_0
+#define NFFactory NFFactory_4_0
+#define NFRule NFRule_4_0
+#define NFRuleSet NFRuleSet_4_0
+#define NFSubstitution NFSubstitution_4_0
+#define NGramParser NGramParser_4_0
+#define NameToEnum NameToEnum_4_0
+#define NameUnicodeTransliterator NameUnicodeTransliterator_4_0
+#define NonContextualGlyphSubstitutionProcessor NonContextualGlyphSubstitutionProcessor_4_0
+#define NonContiguousEnumToOffset NonContiguousEnumToOffset_4_0
+#define NormalizationTransliterator NormalizationTransliterator_4_0
+#define Normalizer Normalizer_4_0
+#define NullSubstitution NullSubstitution_4_0
+#define NullTransliterator NullTransliterator_4_0
+#define NumberFormat NumberFormat_4_0
+#define NumberFormatFactory NumberFormatFactory_4_0
+#define NumeratorSubstitution NumeratorSubstitution_4_0
+#define OlsonTimeZone OlsonTimeZone_4_0
+#define OpenTypeLayoutEngine OpenTypeLayoutEngine_4_0
+#define OpenTypeUtilities OpenTypeUtilities_4_0
+#define OrConstraint OrConstraint_4_0
+#define PCEBuffer PCEBuffer_4_0
+#define PairPositioningFormat1Subtable PairPositioningFormat1Subtable_4_0
+#define PairPositioningFormat2Subtable PairPositioningFormat2Subtable_4_0
+#define PairPositioningSubtable PairPositioningSubtable_4_0
+#define ParagraphLayout ParagraphLayout_4_0
+#define ParseData ParseData_4_0
+#define ParsePosition ParsePosition_4_0
+#define PatternMap PatternMap_4_0
+#define PatternMapIterator PatternMapIterator_4_0
+#define PersianCalendar PersianCalendar_4_0
+#define PluralFormat PluralFormat_4_0
+#define PluralKeywordEnumeration PluralKeywordEnumeration_4_0
+#define PluralRules PluralRules_4_0
+#define PropertyAliases PropertyAliases_4_0
+#define PtnElem PtnElem_4_0
+#define PtnSkeleton PtnSkeleton_4_0
+#define Quantifier Quantifier_4_0
+#define RBBIDataWrapper RBBIDataWrapper_4_0
+#define RBBINode RBBINode_4_0
+#define RBBIRuleBuilder RBBIRuleBuilder_4_0
+#define RBBIRuleScanner RBBIRuleScanner_4_0
+#define RBBISetBuilder RBBISetBuilder_4_0
+#define RBBIStateDescriptor RBBIStateDescriptor_4_0
+#define RBBISymbolTable RBBISymbolTable_4_0
+#define RBBISymbolTableEntry RBBISymbolTableEntry_4_0
+#define RBBITableBuilder RBBITableBuilder_4_0
+#define RCEBuffer RCEBuffer_4_0
+#define RangeDescriptor RangeDescriptor_4_0
+#define RegexCImpl RegexCImpl_4_0
+#define RegexCompile RegexCompile_4_0
+#define RegexMatcher RegexMatcher_4_0
+#define RegexPattern RegexPattern_4_0
+#define RegexStaticSets RegexStaticSets_4_0
+#define RelativeDateFormat RelativeDateFormat_4_0
+#define RemoveTransliterator RemoveTransliterator_4_0
+#define Replaceable Replaceable_4_0
+#define ReplaceableGlue ReplaceableGlue_4_0
+#define ResourceBundle ResourceBundle_4_0
+#define RiseSetCoordFunc RiseSetCoordFunc_4_0
+#define RuleBasedBreakIterator RuleBasedBreakIterator_4_0
+#define RuleBasedCollator RuleBasedCollator_4_0
+#define RuleBasedNumberFormat RuleBasedNumberFormat_4_0
+#define RuleBasedTimeZone RuleBasedTimeZone_4_0
+#define RuleBasedTransliterator RuleBasedTransliterator_4_0
+#define RuleChain RuleChain_4_0
+#define RuleCharacterIterator RuleCharacterIterator_4_0
+#define RuleHalf RuleHalf_4_0
+#define RuleParser RuleParser_4_0
+#define RunArray RunArray_4_0
+#define SafeZoneStringFormatPtr SafeZoneStringFormatPtr_4_0
+#define SameValueSubstitution SameValueSubstitution_4_0
+#define ScriptListTable ScriptListTable_4_0
+#define ScriptRunIterator ScriptRunIterator_4_0
+#define ScriptTable ScriptTable_4_0
+#define SearchIterator SearchIterator_4_0
+#define SegmentArrayProcessor SegmentArrayProcessor_4_0
+#define SegmentSingleProcessor SegmentSingleProcessor_4_0
+#define ServiceEnumeration ServiceEnumeration_4_0
+#define ServiceListener ServiceListener_4_0
+#define SimpleArrayProcessor SimpleArrayProcessor_4_0
+#define SimpleDateFormat SimpleDateFormat_4_0
+#define SimpleFactory SimpleFactory_4_0
+#define SimpleLocaleKeyFactory SimpleLocaleKeyFactory_4_0
+#define SimpleNumberFormatFactory SimpleNumberFormatFactory_4_0
+#define SimpleTimeZone SimpleTimeZone_4_0
+#define SinglePositioningFormat1Subtable SinglePositioningFormat1Subtable_4_0
+#define SinglePositioningFormat2Subtable SinglePositioningFormat2Subtable_4_0
+#define SinglePositioningSubtable SinglePositioningSubtable_4_0
+#define SingleSubstitutionFormat1Subtable SingleSubstitutionFormat1Subtable_4_0
+#define SingleSubstitutionFormat2Subtable SingleSubstitutionFormat2Subtable_4_0
+#define SingleSubstitutionSubtable SingleSubstitutionSubtable_4_0
+#define SingleTableProcessor SingleTableProcessor_4_0
+#define Spec Spec_4_0
+#define StateTableProcessor StateTableProcessor_4_0
+#define StringCharacterIterator StringCharacterIterator_4_0
+#define StringEnumeration StringEnumeration_4_0
+#define StringLocalizationInfo StringLocalizationInfo_4_0
+#define StringMatcher StringMatcher_4_0
+#define StringPair StringPair_4_0
+#define StringReplacer StringReplacer_4_0
+#define StringSearch StringSearch_4_0
+#define StyleRuns StyleRuns_4_0
+#define SubstitutionLookup SubstitutionLookup_4_0
+#define SubtableProcessor SubtableProcessor_4_0
+#define SunTimeAngleFunc SunTimeAngleFunc_4_0
+#define SymbolTable SymbolTable_4_0
+#define TZEnumeration TZEnumeration_4_0
+#define TaiwanCalendar TaiwanCalendar_4_0
+#define TernaryNode TernaryNode_4_0
+#define TextTrieMap TextTrieMap_4_0
+#define TextTrieMapSearchResultHandler TextTrieMapSearchResultHandler_4_0
+#define ThaiBreakEngine ThaiBreakEngine_4_0
+#define ThaiLayoutEngine ThaiLayoutEngine_4_0
+#define ThaiShaping ThaiShaping_4_0
+#define TibetanClassTable TibetanClassTable_4_0
+#define TibetanOpenTypeLayoutEngine TibetanOpenTypeLayoutEngine_4_0
+#define TibetanReordering TibetanReordering_4_0
+#define TimeArrayTimeZoneRule TimeArrayTimeZoneRule_4_0
+#define TimeZone TimeZone_4_0
+#define TimeZoneRule TimeZoneRule_4_0
+#define TimeZoneTransition TimeZoneTransition_4_0
+#define TitlecaseTransliterator TitlecaseTransliterator_4_0
+#define TransliterationRule TransliterationRule_4_0
+#define TransliterationRuleData TransliterationRuleData_4_0
+#define TransliterationRuleSet TransliterationRuleSet_4_0
+#define Transliterator Transliterator_4_0
+#define TransliteratorAlias TransliteratorAlias_4_0
+#define TransliteratorIDParser TransliteratorIDParser_4_0
+#define TransliteratorParser TransliteratorParser_4_0
+#define TransliteratorRegistry TransliteratorRegistry_4_0
+#define TrieWordDictionary TrieWordDictionary_4_0
+#define TrimmedArrayProcessor TrimmedArrayProcessor_4_0
+#define UCharCharacterIterator UCharCharacterIterator_4_0
+#define UCollationPCE UCollationPCE_4_0
+#define ULocRuns ULocRuns_4_0
+#define UMemory UMemory_4_0
+#define UObject UObject_4_0
+#define URegularExpression URegularExpression_4_0
+#define UStack UStack_4_0
+#define UStringEnumeration UStringEnumeration_4_0
+#define UVector UVector_4_0
+#define UVector32 UVector32_4_0
+#define UnescapeTransliterator UnescapeTransliterator_4_0
+#define UnhandledEngine UnhandledEngine_4_0
+#define UnicodeArabicOpenTypeLayoutEngine UnicodeArabicOpenTypeLayoutEngine_4_0
+#define UnicodeFilter UnicodeFilter_4_0
+#define UnicodeFunctor UnicodeFunctor_4_0
+#define UnicodeMatcher UnicodeMatcher_4_0
+#define UnicodeNameTransliterator UnicodeNameTransliterator_4_0
+#define UnicodeReplacer UnicodeReplacer_4_0
+#define UnicodeSet UnicodeSet_4_0
+#define UnicodeSetIterator UnicodeSetIterator_4_0
+#define UnicodeSetStringSpan UnicodeSetStringSpan_4_0
+#define UnicodeString UnicodeString_4_0
+#define UppercaseTransliterator UppercaseTransliterator_4_0
+#define VTZReader VTZReader_4_0
+#define VTZWriter VTZWriter_4_0
+#define VTimeZone VTimeZone_4_0
+#define ValueRecord ValueRecord_4_0
+#define ValueRuns ValueRuns_4_0
+#define ZSFCache ZSFCache_4_0
+#define ZSFCacheEntry ZSFCacheEntry_4_0
+#define ZoneMeta ZoneMeta_4_0
+#define ZoneStringFormat ZoneStringFormat_4_0
+#define ZoneStringInfo ZoneStringInfo_4_0
+#define ZoneStringSearchResultHandler ZoneStringSearchResultHandler_4_0
+#define ZoneStrings ZoneStrings_4_0
+#define locale_set_default_internal locale_set_default_internal_4_0
+#define util64_fromDouble util64_fromDouble_4_0
+#define util64_pow util64_pow_4_0
+#define util64_tou util64_tou_4_0
+
+#endif
+#endif
+
+#endif
+
+#endif


[52/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/vtzone.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/vtzone.h b/src/apps/couch_collate/platform/osx/icu/unicode/vtzone.h
new file mode 100644
index 0000000..9463f35
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/vtzone.h
@@ -0,0 +1,443 @@
+/*
+*******************************************************************************
+* Copyright (C) 2007-2008, International Business Machines Corporation and         *
+* others. All Rights Reserved.                                                *
+*******************************************************************************
+*/
+#ifndef VTZONE_H
+#define VTZONE_H
+
+#include "unicode/utypes.h"
+
+/**
+ * \file 
+ * \brief C++ API: RFC2445 VTIMEZONE support
+ */
+
+#if !UCONFIG_NO_FORMATTING
+
+#include "unicode/basictz.h"
+
+U_NAMESPACE_BEGIN
+
+class VTZWriter;
+class VTZReader;
+class UVector;
+
+/**
+ * <code>VTimeZone</code> is a class implementing RFC2445 VTIMEZONE.  You can create a
+ * <code>VTimeZone</code> instance from a time zone ID supported by <code>TimeZone</code>.
+ * With the <code>VTimeZone</code> instance created from the ID, you can write out the rule
+ * in RFC2445 VTIMEZONE format.  Also, you can create a <code>VTimeZone</code> instance
+ * from RFC2445 VTIMEZONE data stream, which allows you to calculate time
+ * zone offset by the rules defined by the data.<br><br>
+ * Note: The consumer of this class reading or writing VTIMEZONE data is responsible to
+ * decode or encode Non-ASCII text.  Methods reading/writing VTIMEZONE data in this class
+ * do nothing with MIME encoding.
+ * @stable ICU 4.0
+ */
+class U_I18N_API VTimeZone : public BasicTimeZone {
+public:
+    /**
+     * Copy constructor.
+     * @param source    The <code>VTimeZone</code> object to be copied.
+     * @stable ICU 4.0
+     */
+    VTimeZone(const VTimeZone& source);
+
+    /**
+     * Destructor.
+     * @stable ICU 4.0
+     */
+    virtual ~VTimeZone();
+
+    /**
+     * Assignment operator.
+     * @param right The object to be copied.
+     * @stable ICU 4.0
+     */
+    VTimeZone& operator=(const VTimeZone& right);
+
+    /**
+     * Return true if the given <code>TimeZone</code> objects are
+     * semantically equal. Objects of different subclasses are considered unequal.
+     * @param that  The object to be compared with.
+     * @return  true if the given <code>TimeZone</code> objects are
+      *semantically equal.
+     * @stable ICU 4.0
+     */
+    virtual UBool operator==(const TimeZone& that) const;
+
+    /**
+     * Return true if the given <code>TimeZone</code> objects are
+     * semantically unequal. Objects of different subclasses are considered unequal.
+     * @param that  The object to be compared with.
+     * @return  true if the given <code>TimeZone</code> objects are
+     * semantically unequal.
+     * @stable ICU 4.0
+     */
+    virtual UBool operator!=(const TimeZone& that) const;
+
+    /**
+     * Create a <code>VTimeZone</code> instance by the time zone ID.
+     * @param ID The time zone ID, such as America/New_York
+     * @return A <code>VTimeZone</code> object initialized by the time zone ID,
+     * or NULL when the ID is unknown.
+     * @stable ICU 4.0
+     */
+    static VTimeZone* createVTimeZoneByID(const UnicodeString& ID);
+
+    /**
+     * Create a <code>VTimeZone</code> instance by RFC2445 VTIMEZONE data
+     * 
+     * @param vtzdata The string including VTIMEZONE data block
+     * @param status Output param to filled in with a success or an error.
+     * @return A <code>VTimeZone</code> initialized by the VTIMEZONE data or
+     * NULL if failed to load the rule from the VTIMEZONE data.
+     * @stable ICU 4.0
+     */
+    static VTimeZone* createVTimeZone(const UnicodeString& vtzdata, UErrorCode& status);
+
+    /**
+     * Gets the RFC2445 TZURL property value.  When a <code>VTimeZone</code> instance was
+     * created from VTIMEZONE data, the initial value is set by the TZURL property value
+     * in the data.  Otherwise, the initial value is not set.
+     * @param url Receives the RFC2445 TZURL property value.
+     * @return TRUE if TZURL attribute is available and value is set.
+     * @stable ICU 4.0
+     */
+    UBool getTZURL(UnicodeString& url) const;
+
+    /**
+     * Sets the RFC2445 TZURL property value.
+     * @param url The TZURL property value.
+     * @stable ICU 4.0
+     */
+    void setTZURL(const UnicodeString& url);
+
+    /**
+     * Gets the RFC2445 LAST-MODIFIED property value.  When a <code>VTimeZone</code> instance
+     * was created from VTIMEZONE data, the initial value is set by the LAST-MODIFIED property
+     * value in the data.  Otherwise, the initial value is not set.
+     * @param lastModified Receives the last modified date.
+     * @return TRUE if lastModified attribute is available and value is set.
+     * @stable ICU 4.0
+     */
+    UBool getLastModified(UDate& lastModified) const;
+
+    /**
+     * Sets the RFC2445 LAST-MODIFIED property value.
+     * @param lastModified The LAST-MODIFIED date.
+     * @stable ICU 4.0
+     */
+    void setLastModified(UDate lastModified);
+
+    /**
+     * Writes RFC2445 VTIMEZONE data for this time zone
+     * @param result Output param to filled in with the VTIMEZONE data.
+     * @param status Output param to filled in with a success or an error.
+     * @stable ICU 4.0
+     */
+    void write(UnicodeString& result, UErrorCode& status) const;
+
+    /**
+     * Writes RFC2445 VTIMEZONE data for this time zone applicalbe
+     * for dates after the specified start time.
+     * @param start The start date.
+     * @param result Output param to filled in with the VTIMEZONE data.
+     * @param status Output param to filled in with a success or an error.
+     * @stable ICU 4.0
+     */
+    void write(UDate start, UnicodeString& result, UErrorCode& status) /*const*/;
+
+    /**
+     * Writes RFC2445 VTIMEZONE data applicalbe for the specified date.
+     * Some common iCalendar implementations can only handle a single time
+     * zone property or a pair of standard and daylight time properties using
+     * BYDAY rule with day of week (such as BYDAY=1SUN).  This method produce
+     * the VTIMEZONE data which can be handled these implementations.  The rules
+     * produced by this method can be used only for calculating time zone offset
+     * around the specified date.
+     * @param time The date used for rule extraction.
+     * @param result Output param to filled in with the VTIMEZONE data.
+     * @param status Output param to filled in with a success or an error.
+     * @stable ICU 4.0
+     */
+    void writeSimple(UDate time, UnicodeString& result, UErrorCode& status) /*const*/;
+
+    /**
+     * Clones TimeZone objects polymorphically. Clients are responsible for deleting
+     * the TimeZone object cloned.
+     * @return   A new copy of this TimeZone object.
+     * @stable ICU 4.0
+     */
+    virtual TimeZone* clone(void) const;
+
+    /**
+     * Returns the TimeZone's adjusted GMT offset (i.e., the number of milliseconds to add
+     * to GMT to get local time in this time zone, taking daylight savings time into
+     * account) as of a particular reference date.  The reference date is used to determine
+     * whether daylight savings time is in effect and needs to be figured into the offset
+     * that is returned (in other words, what is the adjusted GMT offset in this time zone
+     * at this particular date and time?).  For the time zones produced by createTimeZone(),
+     * the reference data is specified according to the Gregorian calendar, and the date
+     * and time fields are local standard time.
+     *
+     * <p>Note: Don't call this method. Instead, call the getOffset(UDate...) overload,
+     * which returns both the raw and the DST offset for a given time. This method
+     * is retained only for backward compatibility.
+     *
+     * @param era        The reference date's era
+     * @param year       The reference date's year
+     * @param month      The reference date's month (0-based; 0 is January)
+     * @param day        The reference date's day-in-month (1-based)
+     * @param dayOfWeek  The reference date's day-of-week (1-based; 1 is Sunday)
+     * @param millis     The reference date's milliseconds in day, local standard time
+     * @param status     Output param to filled in with a success or an error.
+     * @return           The offset in milliseconds to add to GMT to get local time.
+     * @stable ICU 4.0
+     */
+    virtual int32_t getOffset(uint8_t era, int32_t year, int32_t month, int32_t day,
+                              uint8_t dayOfWeek, int32_t millis, UErrorCode& status) const;
+
+    /**
+     * Gets the time zone offset, for current date, modified in case of
+     * daylight savings. This is the offset to add *to* UTC to get local time.
+     *
+     * <p>Note: Don't call this method. Instead, call the getOffset(UDate...) overload,
+     * which returns both the raw and the DST offset for a given time. This method
+     * is retained only for backward compatibility.
+     *
+     * @param era        The reference date's era
+     * @param year       The reference date's year
+     * @param month      The reference date's month (0-based; 0 is January)
+     * @param day        The reference date's day-in-month (1-based)
+     * @param dayOfWeek  The reference date's day-of-week (1-based; 1 is Sunday)
+     * @param millis     The reference date's milliseconds in day, local standard time
+     * @param monthLength The length of the given month in days.
+     * @param status     Output param to filled in with a success or an error.
+     * @return           The offset in milliseconds to add to GMT to get local time.
+     * @stable ICU 4.0
+     */
+    virtual int32_t getOffset(uint8_t era, int32_t year, int32_t month, int32_t day,
+                           uint8_t dayOfWeek, int32_t millis,
+                           int32_t monthLength, UErrorCode& status) const;
+
+    /**
+     * Returns the time zone raw and GMT offset for the given moment
+     * in time.  Upon return, local-millis = GMT-millis + rawOffset +
+     * dstOffset.  All computations are performed in the proleptic
+     * Gregorian calendar.  The default implementation in the TimeZone
+     * class delegates to the 8-argument getOffset().
+     *
+     * @param date moment in time for which to return offsets, in
+     * units of milliseconds from January 1, 1970 0:00 GMT, either GMT
+     * time or local wall time, depending on `local'.
+     * @param local if true, `date' is local wall time; otherwise it
+     * is in GMT time.
+     * @param rawOffset output parameter to receive the raw offset, that
+     * is, the offset not including DST adjustments
+     * @param dstOffset output parameter to receive the DST offset,
+     * that is, the offset to be added to `rawOffset' to obtain the
+     * total offset between local and GMT time. If DST is not in
+     * effect, this value is zero; otherwise it is a positive value,
+     * typically one hour.
+     * @param ec input-output error code
+     * @stable ICU 4.0
+     */
+    virtual void getOffset(UDate date, UBool local, int32_t& rawOffset,
+                           int32_t& dstOffset, UErrorCode& ec) const;
+
+    /**
+     * Sets the TimeZone's raw GMT offset (i.e., the number of milliseconds to add
+     * to GMT to get local time, before taking daylight savings time into account).
+     *
+     * @param offsetMillis  The new raw GMT offset for this time zone.
+     * @stable ICU 4.0
+     */
+    virtual void setRawOffset(int32_t offsetMillis);
+
+    /**
+     * Returns the TimeZone's raw GMT offset (i.e., the number of milliseconds to add
+     * to GMT to get local time, before taking daylight savings time into account).
+     *
+     * @return   The TimeZone's raw GMT offset.
+     * @stable ICU 4.0
+     */
+    virtual int32_t getRawOffset(void) const;
+
+    /**
+     * Queries if this time zone uses daylight savings time.
+     * @return true if this time zone uses daylight savings time,
+     * false, otherwise.
+     * @stable ICU 4.0
+     */
+    virtual UBool useDaylightTime(void) const;
+
+    /**
+     * Queries if the given date is in daylight savings time in
+     * this time zone.
+     * This method is wasteful since it creates a new GregorianCalendar and
+     * deletes it each time it is called. This is a deprecated method
+     * and provided only for Java compatibility.
+     *
+     * @param date the given UDate.
+     * @param status Output param filled in with success/error code.
+     * @return true if the given date is in daylight savings time,
+     * false, otherwise.
+     * @deprecated ICU 2.4. Use Calendar::inDaylightTime() instead.
+     */
+    virtual UBool inDaylightTime(UDate date, UErrorCode& status) const;
+
+    /**
+     * Returns true if this zone has the same rule and offset as another zone.
+     * That is, if this zone differs only in ID, if at all.
+     * @param other the <code>TimeZone</code> object to be compared with
+     * @return true if the given zone is the same as this one,
+     * with the possible exception of the ID
+     * @stable ICU 4.0
+     */
+    virtual UBool hasSameRules(const TimeZone& other) const;
+
+    /**
+     * Gets the first time zone transition after the base time.
+     * @param base      The base time.
+     * @param inclusive Whether the base time is inclusive or not.
+     * @param result    Receives the first transition after the base time.
+     * @return  TRUE if the transition is found.
+     * @stable ICU 4.0
+     */
+    virtual UBool getNextTransition(UDate base, UBool inclusive, TimeZoneTransition& result) /*const*/;
+
+    /**
+     * Gets the most recent time zone transition before the base time.
+     * @param base      The base time.
+     * @param inclusive Whether the base time is inclusive or not.
+     * @param result    Receives the most recent transition before the base time.
+     * @return  TRUE if the transition is found.
+     * @stable ICU 4.0
+     */
+    virtual UBool getPreviousTransition(UDate base, UBool inclusive, TimeZoneTransition& result) /*const*/;
+
+    /**
+     * Returns the number of <code>TimeZoneRule</code>s which represents time transitions,
+     * for this time zone, that is, all <code>TimeZoneRule</code>s for this time zone except
+     * <code>InitialTimeZoneRule</code>.  The return value range is 0 or any positive value.
+     * @param status    Receives error status code.
+     * @return The number of <code>TimeZoneRule</code>s representing time transitions.
+     * @stable ICU 4.0
+     */
+    virtual int32_t countTransitionRules(UErrorCode& status) /*const*/;
+
+    /**
+     * Gets the <code>InitialTimeZoneRule</code> and the set of <code>TimeZoneRule</code>
+     * which represent time transitions for this time zone.  On successful return,
+     * the argument initial points to non-NULL <code>InitialTimeZoneRule</code> and
+     * the array trsrules is filled with 0 or multiple <code>TimeZoneRule</code>
+     * instances up to the size specified by trscount.  The results are referencing the
+     * rule instance held by this time zone instance.  Therefore, after this time zone
+     * is destructed, they are no longer available.
+     * @param initial       Receives the initial timezone rule
+     * @param trsrules      Receives the timezone transition rules
+     * @param trscount      On input, specify the size of the array 'transitions' receiving
+     *                      the timezone transition rules.  On output, actual number of
+     *                      rules filled in the array will be set.
+     * @param status        Receives error status code.
+     * @stable ICU 4.0
+     */
+    virtual void getTimeZoneRules(const InitialTimeZoneRule*& initial,
+        const TimeZoneRule* trsrules[], int32_t& trscount, UErrorCode& status) /*const*/;
+
+private:
+    enum { DEFAULT_VTIMEZONE_LINES = 100 };
+
+    /**
+     * Default constructor.
+     */
+    VTimeZone();
+    static VTimeZone* createVTimeZone(VTZReader* reader);
+    void write(VTZWriter& writer, UErrorCode& status) const;
+    void write(UDate start, VTZWriter& writer, UErrorCode& status) /*const*/;
+    void writeSimple(UDate time, VTZWriter& writer, UErrorCode& status) /*const*/;
+    void load(VTZReader& reader, UErrorCode& status);
+    void parse(UErrorCode& status);
+
+    void writeZone(VTZWriter& w, BasicTimeZone& basictz, UVector* customProps,
+        UErrorCode& status) const;
+
+    void writeHeaders(VTZWriter& w, UErrorCode& status) const;
+    void writeFooter(VTZWriter& writer, UErrorCode& status) const;
+
+    void writeZonePropsByTime(VTZWriter& writer, UBool isDst, const UnicodeString& tzname,
+                              int32_t fromOffset, int32_t toOffset, UDate time, UBool withRDATE,
+                              UErrorCode& status) const;
+    void writeZonePropsByDOM(VTZWriter& writer, UBool isDst, const UnicodeString& tzname,
+                             int32_t fromOffset, int32_t toOffset,
+                             int32_t month, int32_t dayOfMonth, UDate startTime, UDate untilTime,
+                             UErrorCode& status) const;
+    void writeZonePropsByDOW(VTZWriter& writer, UBool isDst, const UnicodeString& tzname,
+                             int32_t fromOffset, int32_t toOffset,
+                             int32_t month, int32_t weekInMonth, int32_t dayOfWeek,
+                             UDate startTime, UDate untilTime, UErrorCode& status) const;
+    void writeZonePropsByDOW_GEQ_DOM(VTZWriter& writer, UBool isDst, const UnicodeString& tzname,
+                                     int32_t fromOffset, int32_t toOffset,
+                                     int32_t month, int32_t dayOfMonth, int32_t dayOfWeek,
+                                     UDate startTime, UDate untilTime, UErrorCode& status) const;
+    void writeZonePropsByDOW_GEQ_DOM_sub(VTZWriter& writer, int32_t month, int32_t dayOfMonth,
+                                         int32_t dayOfWeek, int32_t numDays,
+                                         UDate untilTime, int32_t fromOffset, UErrorCode& status) const;
+    void writeZonePropsByDOW_LEQ_DOM(VTZWriter& writer, UBool isDst, const UnicodeString& tzname,
+                                     int32_t fromOffset, int32_t toOffset,
+                                     int32_t month, int32_t dayOfMonth, int32_t dayOfWeek,
+                                     UDate startTime, UDate untilTime, UErrorCode& status) const;
+    void writeFinalRule(VTZWriter& writer, UBool isDst, const AnnualTimeZoneRule* rule,
+                        int32_t fromRawOffset, int32_t fromDSTSavings,
+                        UDate startTime, UErrorCode& status) const;
+
+    void beginZoneProps(VTZWriter& writer, UBool isDst, const UnicodeString& tzname,
+                        int32_t fromOffset, int32_t toOffset, UDate startTime, UErrorCode& status) const;
+    void endZoneProps(VTZWriter& writer, UBool isDst, UErrorCode& status) const;
+    void beginRRULE(VTZWriter& writer, int32_t month, UErrorCode& status) const;
+    void appendUNTIL(VTZWriter& writer, const UnicodeString& until, UErrorCode& status) const;
+
+    BasicTimeZone   *tz;
+    UVector         *vtzlines;
+    UnicodeString   tzurl;
+    UDate           lastmod;
+    UnicodeString   olsonzid;
+    UnicodeString   icutzver;
+
+public:
+    /**
+     * Return the class ID for this class. This is useful only for comparing to
+     * a return value from getDynamicClassID(). For example:
+     * <pre>
+     * .   Base* polymorphic_pointer = createPolymorphicObject();
+     * .   if (polymorphic_pointer->getDynamicClassID() ==
+     * .       erived::getStaticClassID()) ...
+     * </pre>
+     * @return          The class ID for all objects of this class.
+     * @stable ICU 4.0
+     */
+    static UClassID U_EXPORT2 getStaticClassID(void);
+
+    /**
+     * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This
+     * method is to implement a simple version of RTTI, since not all C++
+     * compilers support genuine RTTI. Polymorphic operator==() and clone()
+     * methods call this method.
+     *
+     * @return          The class ID for this object. All objects of a
+     *                  given class have the same class ID.  Objects of
+     *                  other classes have different class IDs.
+     * @stable ICU 4.0
+     */
+    virtual UClassID getDynamicClassID(void) const;
+};
+
+U_NAMESPACE_END
+
+#endif /* #if !UCONFIG_NO_FORMATTING */
+
+#endif // VTZONE_H
+//eof

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/rebar.config.script
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/rebar.config.script b/src/apps/couch_collate/rebar.config.script
index ff5ef9b..fb72cdd 100644
--- a/src/apps/couch_collate/rebar.config.script
+++ b/src/apps/couch_collate/rebar.config.script
@@ -27,20 +27,64 @@ GetFlag = fun(Name, Args) ->
         end
     end,
 
-ICUCFLAGS = GetFlag("ICU_CFLAGS", "--cflags"),
-ICUCXXFLAGS = GetFlag("ICU_CXXFLAGS", "--cxxflags"),
-ICULDFLAGS = GetFlag("ICU_LDFLAGS", "--ldflags"),
-ICUINCPATH = GetFlag("ICU_INCPATH", "--cppflags-searchpath"),
+GetFlag1 = fun(Name, Default) ->
+        case os:getenv(Name) of
+            false -> Default;
+            Val -> Val
+        end
+    end,
+
+BuildStatic = os:getenv("COUCHDB_STATIC") =:= "1" andalso
+                os:getenv("USE_STATIC_ICU") =:= "1",
 
 
-PortEnv = [{port_env, [
+IsDarwin = case os:type() of
+    {unix, darwin} -> true;
+    _ -> false
+end,
+
+UseSystemIcu = IsDarwin andalso os:getenv("USE_STATIC_ICU") /= "1",
+
+PortEnv = case {UseSystemIcu, BuildStatic} of
+    {true, _} ->
+        CFLAGS = GetFlag1("ICU_CFLAGS",
+                         "-Iplatform/osx/icu -I/usr/include -fPIC"),
+        LDFLAGS = GetFlag1("ICU_LDFLAGS",
+                          "-lpthread -lm  -licucore -lstdc++ -L/usr/lib " ++
+                          "$DRV_LDFLAGS -fPIC"),
+        [
+            {"CFLAGS", "$DRV_CFLAGS " ++ CFLAGS},
+            {"LDFLAGS", LDFLAGS}
+        ];
+
+    {_, true} ->
+        CFLAGS = GetFlag("ICU_CFLAGS", "-I.libs/icu/include"),
+        LDFLAGS = GetFlag("ICU_LDFLAGS", "-lstdc++ -fPIC " ++
+                                         ".libs/icu/lib/libicui18n.a " ++
+                                         ".libs/icu/lib/libicuuc.a " ++
+                                         ".libs/icu/lib/libicudata.a"),
+        [
+            {"DRV_CFLAGS", "$DRV_CFLAGS " ++ CFLAGS ++ " -D BSD_SOURCE"},
+            {"DRV_LDFLAGS", "$DRV_LDFLAGS " ++ LDFLAGS}
+        ];
+    {_, false} ->
+        ICUCFLAGS = GetFlag("ICU_CFLAGS", "--cflags"),
+        ICUCXXFLAGS = GetFlag("ICU_CXXFLAGS", "--cxxflags"),
+        ICULDFLAGS = GetFlag("ICU_LDFLAGS", "--ldflags"),
+        ICUINCPATH = GetFlag("ICU_INCPATH", "--cppflags-searchpath"),
+
+        [
             {"CFLAGS",  ICUCFLAGS ++  " $CFLAGS " ++ ICUINCPATH},
             {"CXXFLAGS", ICUCXXFLAGS ++ " $CXXFLAGS " ++ ICUINCPATH},
-            {"LDFLAGS",  ICULDFLAGS ++ " $LDFLAGS"}]},
+            {"LDFLAGS",  ICULDFLAGS ++ " $LDFLAGS"}
+        ]
+end,
 
-           {port_specs, [
-            {filename:join(["priv", Arch, "couch_collate.so"]),
-            ["c_src/*.c"]}]}
-],
+PortInfo = [{port_env, PortEnv},
+            {port_specs, [
+                {filename:join(["priv", Arch, "couch_collate.so"]),
+                    ["c_src/*.c"]}]},
+            {pre_hooks, [{compile, "./build_icu.sh"}]},
+            {post_hooks, [{clean, "./build_icu.sh clean"}]}],
 
-lists:keymerge(1,lists:keysort(1, PortEnv), lists:keysort(1, CONFIG)).
+lists:keymerge(1,lists:keysort(1, PortInfo), lists:keysort(1, CONFIG)).

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/support/build_js.escript
----------------------------------------------------------------------
diff --git a/src/support/build_js.escript b/src/support/build_js.escript
old mode 100644
new mode 100755


[79/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/schriter.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/schriter.h b/src/apps/couch_collate/platform/osx/icu/unicode/schriter.h
new file mode 100644
index 0000000..d0b5e22
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/schriter.h
@@ -0,0 +1,187 @@
+/*
+******************************************************************************
+*
+*   Copyright (C) 1998-2005, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+*
+******************************************************************************
+*
+* File schriter.h
+*
+* Modification History:
+*
+*   Date        Name        Description
+*  05/05/99     stephen     Cleaned up.
+******************************************************************************
+*/
+
+#ifndef SCHRITER_H
+#define SCHRITER_H
+
+#include "unicode/utypes.h"
+#include "unicode/chariter.h"
+#include "unicode/uchriter.h"
+
+/**
+ * \file 
+ * \brief C++ API: String Character Iterator
+ */
+ 
+U_NAMESPACE_BEGIN
+/**
+ * A concrete subclass of CharacterIterator that iterates over the
+ * characters (code units or code points) in a UnicodeString.
+ * It's possible not only to create an
+ * iterator that iterates over an entire UnicodeString, but also to
+ * create one that iterates over only a subrange of a UnicodeString
+ * (iterators over different subranges of the same UnicodeString don't
+ * compare equal).
+ * @see CharacterIterator
+ * @see ForwardCharacterIterator
+ * @stable ICU 2.0
+ */
+class U_COMMON_API StringCharacterIterator : public UCharCharacterIterator {
+public:
+  /**
+   * Create an iterator over the UnicodeString referred to by "textStr".
+   * The UnicodeString object is copied.
+   * The iteration range is the whole string, and the starting position is 0.
+   * @param textStr The unicode string used to create an iterator
+   * @stable ICU 2.0
+   */
+  StringCharacterIterator(const UnicodeString& textStr);
+
+  /**
+   * Create an iterator over the UnicodeString referred to by "textStr".
+   * The iteration range is the whole string, and the starting
+   * position is specified by "textPos".  If "textPos" is outside the valid
+   * iteration range, the behavior of this object is undefined.
+   * @param textStr The unicode string used to create an iterator
+   * @param textPos The starting position of the iteration
+   * @stable ICU 2.0
+   */
+  StringCharacterIterator(const UnicodeString&    textStr,
+              int32_t              textPos);
+
+  /**
+   * Create an iterator over the UnicodeString referred to by "textStr".
+   * The UnicodeString object is copied.
+   * The iteration range begins with the code unit specified by
+   * "textBegin" and ends with the code unit BEFORE the code unit specfied
+   * by "textEnd".  The starting position is specified by "textPos".  If
+   * "textBegin" and "textEnd" don't form a valid range on "text" (i.e.,
+   * textBegin >= textEnd or either is negative or greater than text.size()),
+   * or "textPos" is outside the range defined by "textBegin" and "textEnd",
+   * the behavior of this iterator is undefined.
+   * @param textStr    The unicode string used to create the StringCharacterIterator
+   * @param textBegin  The begin position of the iteration range
+   * @param textEnd    The end position of the iteration range
+   * @param textPos    The starting position of the iteration
+   * @stable ICU 2.0
+   */
+  StringCharacterIterator(const UnicodeString&    textStr,
+              int32_t              textBegin,
+              int32_t              textEnd,
+              int32_t              textPos);
+
+  /**
+   * Copy constructor.  The new iterator iterates over the same range
+   * of the same string as "that", and its initial position is the
+   * same as "that"'s current position.
+   * The UnicodeString object in "that" is copied.
+   * @param that The StringCharacterIterator to be copied
+   * @stable ICU 2.0
+   */
+  StringCharacterIterator(const StringCharacterIterator&  that);
+
+  /**
+   * Destructor.
+   * @stable ICU 2.0
+   */
+  virtual ~StringCharacterIterator();
+
+  /**
+   * Assignment operator.  *this is altered to iterate over the same
+   * range of the same string as "that", and refers to the same
+   * character within that string as "that" does.
+   * @param that The object to be copied.
+   * @return the newly created object.
+   * @stable ICU 2.0
+   */
+  StringCharacterIterator&
+  operator=(const StringCharacterIterator&    that);
+
+  /**
+   * Returns true if the iterators iterate over the same range of the
+   * same string and are pointing at the same character.
+   * @param that The ForwardCharacterIterator to be compared for equality
+   * @return true if the iterators iterate over the same range of the
+   * same string and are pointing at the same character.
+   * @stable ICU 2.0
+   */
+  virtual UBool          operator==(const ForwardCharacterIterator& that) const;
+
+  /**
+   * Returns a new StringCharacterIterator referring to the same
+   * character in the same range of the same string as this one.  The
+   * caller must delete the new iterator.
+   * @return the newly cloned object.
+   * @stable ICU 2.0
+   */
+  virtual CharacterIterator* clone(void) const;
+
+  /**
+   * Sets the iterator to iterate over the provided string.
+   * @param newText The string to be iterated over
+   * @stable ICU 2.0
+   */
+  void setText(const UnicodeString& newText);
+
+  /**
+   * Copies the UnicodeString under iteration into the UnicodeString
+   * referred to by "result".  Even if this iterator iterates across
+   * only a part of this string, the whole string is copied.
+   * @param result Receives a copy of the text under iteration.
+   * @stable ICU 2.0
+   */
+  virtual void            getText(UnicodeString& result);
+
+  /**
+   * Return a class ID for this object (not really public)
+   * @return a class ID for this object.
+   * @stable ICU 2.0
+   */
+  virtual UClassID         getDynamicClassID(void) const;
+
+  /**
+   * Return a class ID for this class (not really public)
+   * @return a class ID for this class
+   * @stable ICU 2.0
+   */
+  static UClassID   U_EXPORT2 getStaticClassID(void);
+
+protected:
+  /**
+   * Default constructor, iteration over empty string.
+   * @stable ICU 2.0
+   */
+  StringCharacterIterator();
+
+  /**
+   * Sets the iterator to iterate over the provided string.
+   * @param newText The string to be iterated over
+   * @param newTextLength The length of the String
+   * @stable ICU 2.0
+   */
+  void setText(const UChar* newText, int32_t newTextLength);
+
+  /**
+   * Copy of the iterated string object.
+   * @stable ICU 2.0
+   */
+  UnicodeString            text;
+
+};
+
+U_NAMESPACE_END
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/search.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/search.h b/src/apps/couch_collate/platform/osx/icu/unicode/search.h
new file mode 100644
index 0000000..8b82906
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/search.h
@@ -0,0 +1,569 @@
+/*
+**********************************************************************
+*   Copyright (C) 2001-2008 IBM and others. All rights reserved.
+**********************************************************************
+*   Date        Name        Description
+*  03/22/2000   helena      Creation.
+**********************************************************************
+*/
+
+#ifndef SEARCH_H
+#define SEARCH_H
+
+#include "unicode/utypes.h"
+
+/**
+ * \file 
+ * \brief C++ API: SearchIterator object.
+ */
+ 
+#if !UCONFIG_NO_COLLATION && !UCONFIG_NO_BREAK_ITERATION
+
+#include "unicode/uobject.h"
+#include "unicode/unistr.h"
+#include "unicode/chariter.h"
+#include "unicode/brkiter.h"
+#include "unicode/usearch.h"
+
+/**
+* @stable ICU 2.0
+*/
+struct USearch;
+/**
+* @stable ICU 2.0
+*/
+typedef struct USearch USearch;
+
+U_NAMESPACE_BEGIN
+
+/**
+ *
+ * <tt>SearchIterator</tt> is an abstract base class that provides 
+ * methods to search for a pattern within a text string. Instances of
+ * <tt>SearchIterator</tt> maintain a current position and scans over the 
+ * target text, returning the indices the pattern is matched and the length 
+ * of each match.
+ * <p>
+ * <tt>SearchIterator</tt> defines a protocol for text searching. 
+ * Subclasses provide concrete implementations of various search algorithms. 
+ * For example, <tt>StringSearch</tt> implements language-sensitive pattern 
+ * matching based on the comparison rules defined in a 
+ * <tt>RuleBasedCollator</tt> object. 
+ * <p> 
+ * Other options for searching includes using a BreakIterator to restrict 
+ * the points at which matches are detected.
+ * <p>
+ * <tt>SearchIterator</tt> provides an API that is similar to that of
+ * other text iteration classes such as <tt>BreakIterator</tt>. Using 
+ * this class, it is easy to scan through text looking for all occurances of 
+ * a given pattern. The following example uses a <tt>StringSearch</tt> 
+ * object to find all instances of "fox" in the target string. Any other 
+ * subclass of <tt>SearchIterator</tt> can be used in an identical 
+ * manner.
+ * <pre><code>
+ * UnicodeString target("The quick brown fox jumped over the lazy fox");
+ * UnicodeString pattern("fox");
+ *
+ * SearchIterator *iter  = new StringSearch(pattern, target);
+ * UErrorCode      error = U_ZERO_ERROR;
+ * for (int pos = iter->first(error); pos != USEARCH_DONE; 
+ *                               pos = iter->next(error)) {
+ *     printf("Found match at %d pos, length is %d\n", pos, 
+ *                                             iter.getMatchLength());
+ * }
+ * </code></pre>
+ *
+ * @see StringSearch
+ * @see RuleBasedCollator
+ */
+class U_I18N_API SearchIterator : public UObject {
+
+public:
+
+    // public constructors and destructors -------------------------------
+
+    /** 
+    * Copy constructor that creates a SearchIterator instance with the same 
+    * behavior, and iterating over the same text. 
+    * @param other the SearchIterator instance to be copied.
+    * @stable ICU 2.0
+    */
+    SearchIterator(const SearchIterator &other);
+
+    /**
+     * Destructor. Cleans up the search iterator data struct.
+     * @stable ICU 2.0
+     */
+    virtual ~SearchIterator();
+
+    // public get and set methods ----------------------------------------
+
+    /**
+     * Sets the index to point to the given position, and clears any state 
+     * that's affected.
+     * <p>
+     * This method takes the argument index and sets the position in the text 
+     * string accordingly without checking if the index is pointing to a 
+     * valid starting point to begin searching. 
+     * @param position within the text to be set. If position is less
+     *             than or greater than the text range for searching, 
+     *          an U_INDEX_OUTOFBOUNDS_ERROR will be returned
+     * @param status for errors if it occurs
+     * @stable ICU 2.0
+     */
+    virtual void setOffset(int32_t position, UErrorCode &status) = 0;
+
+    /**
+     * Return the current index in the text being searched.
+     * If the iteration has gone past the end of the text
+     * (or past the beginning for a backwards search), USEARCH_DONE
+     * is returned.
+     * @return current index in the text being searched.
+     * @stable ICU 2.0
+     */
+    virtual int32_t getOffset(void) const = 0;
+
+    /**
+    * Sets the text searching attributes located in the enum 
+    * USearchAttribute with values from the enum USearchAttributeValue.
+    * USEARCH_DEFAULT can be used for all attributes for resetting.
+    * @param attribute text attribute (enum USearchAttribute) to be set
+    * @param value text attribute value
+    * @param status for errors if it occurs
+    * @stable ICU 2.0
+    */
+    void setAttribute(USearchAttribute       attribute,
+                      USearchAttributeValue  value,
+                      UErrorCode            &status);
+
+    /**    
+    * Gets the text searching attributes
+    * @param attribute text attribute (enum USearchAttribute) to be retrieve
+    * @return text attribute value
+    * @stable ICU 2.0
+    */
+    USearchAttributeValue getAttribute(USearchAttribute  attribute) const;
+    
+    /**
+    * Returns the index to the match in the text string that was searched.
+    * This call returns a valid result only after a successful call to 
+    * <tt>first</tt>, <tt>next</tt>, <tt>previous</tt>, or <tt>last</tt>.
+    * Just after construction, or after a searching method returns 
+    * <tt>USEARCH_DONE</tt>, this method will return <tt>USEARCH_DONE</tt>.
+    * <p>
+    * Use getMatchedLength to get the matched string length.
+    * @return index of a substring within the text string that is being 
+    *         searched.
+    * @see #first
+    * @see #next
+    * @see #previous
+    * @see #last
+    * @stable ICU 2.0
+    */
+    int32_t getMatchedStart(void) const;
+
+    /**
+     * Returns the length of text in the string which matches the search 
+     * pattern. This call returns a valid result only after a successful call 
+     * to <tt>first</tt>, <tt>next</tt>, <tt>previous</tt>, or <tt>last</tt>.
+     * Just after construction, or after a searching method returns 
+     * <tt>USEARCH_DONE</tt>, this method will return 0.
+     * @return The length of the match in the target text, or 0 if there
+     *         is no match currently.
+     * @see #first
+     * @see #next
+     * @see #previous
+     * @see #last
+     * @stable ICU 2.0
+     */
+    int32_t getMatchedLength(void) const;
+    
+    /**
+     * Returns the text that was matched by the most recent call to 
+     * <tt>first</tt>, <tt>next</tt>, <tt>previous</tt>, or <tt>last</tt>.
+     * If the iterator is not pointing at a valid match (e.g. just after 
+     * construction or after <tt>USEARCH_DONE</tt> has been returned, 
+     * returns an empty string. 
+     * @param result stores the matched string or an empty string if a match
+     *        is not found.
+     * @see #first
+     * @see #next
+     * @see #previous
+     * @see #last
+     * @stable ICU 2.0
+     */
+    void getMatchedText(UnicodeString &result) const;
+    
+    /**
+     * Set the BreakIterator that will be used to restrict the points
+     * at which matches are detected. The user is responsible for deleting 
+     * the breakiterator.
+     * @param breakiter A BreakIterator that will be used to restrict the 
+     *                points at which matches are detected. If a match is 
+     *                found, but the match's start or end index is not a 
+     *                boundary as determined by the <tt>BreakIterator</tt>, 
+     *                the match will be rejected and another will be searched 
+     *                for. If this parameter is <tt>NULL</tt>, no break
+     *                detection is attempted.
+     * @param status for errors if it occurs
+     * @see BreakIterator
+     * @stable ICU 2.0
+     */
+    void setBreakIterator(BreakIterator *breakiter, UErrorCode &status);
+    
+    /**
+     * Returns the BreakIterator that is used to restrict the points at 
+     * which matches are detected.  This will be the same object that was 
+     * passed to the constructor or to <tt>setBreakIterator</tt>.
+     * Note that <tt>NULL</tt> is a legal value; it means that break
+     * detection should not be attempted.
+     * @return BreakIterator used to restrict matchings.
+     * @see #setBreakIterator
+     * @stable ICU 2.0
+     */
+    const BreakIterator * getBreakIterator(void) const;
+
+    /**
+     * Set the string text to be searched. Text iteration will hence begin at 
+     * the start of the text string. This method is useful if you want to 
+     * re-use an iterator to search for the same pattern within a different 
+     * body of text. The user is responsible for deleting the text.
+     * @param text string to be searched.
+     * @param status for errors. If the text length is 0, 
+     *        an U_ILLEGAL_ARGUMENT_ERROR is returned.
+     * @stable ICU 2.0
+     */
+    virtual void setText(const UnicodeString &text, UErrorCode &status);    
+
+    /**
+     * Set the string text to be searched. Text iteration will hence begin at 
+     * the start of the text string. This method is useful if you want to 
+     * re-use an iterator to search for the same pattern within a different 
+     * body of text.
+     * <p>
+     * Note: No parsing of the text within the <tt>CharacterIterator</tt> 
+     * will be done during searching for this version. The block of text 
+     * in <tt>CharacterIterator</tt> will be used as it is.
+     * The user is responsible for deleting the text.
+     * @param text string iterator to be searched.
+     * @param status for errors if any. If the text length is 0 then an 
+     *        U_ILLEGAL_ARGUMENT_ERROR is returned.
+     * @stable ICU 2.0
+     */
+    virtual void setText(CharacterIterator &text, UErrorCode &status);
+    
+    /**
+     * Return the string text to be searched.
+     * @return text string to be searched.
+     * @stable ICU 2.0
+     */
+    const UnicodeString & getText(void) const;
+
+    // operator overloading ----------------------------------------------
+
+    /**
+     * Equality operator. 
+     * @param that SearchIterator instance to be compared.
+     * @return TRUE if both BreakIterators are of the same class, have the 
+     *         same behavior, terates over the same text and have the same
+     *         attributes. FALSE otherwise.
+     * @stable ICU 2.0
+     */
+    virtual UBool operator==(const SearchIterator &that) const;
+
+    /**
+     * Not-equal operator. 
+     * @param that SearchIterator instance to be compared.
+     * @return FALSE if operator== returns TRUE, and vice versa.
+     * @stable ICU 2.0
+     */
+    UBool operator!=(const SearchIterator &that) const;
+
+    // public methods ----------------------------------------------------
+
+    /**
+     * Returns a copy of SearchIterator with the same behavior, and 
+     * iterating over the same text, as this one. Note that all data will be
+     * replicated, except for the text string to be searched.
+     * @return cloned object
+     * @stable ICU 2.0
+     */
+    virtual SearchIterator* safeClone(void) const = 0;
+
+    /**
+     * Returns the first index at which the string text matches the search 
+     * pattern. The iterator is adjusted so that its current index (as 
+     * returned by <tt>getOffset</tt>) is the match position if one 
+     * was found.
+     * If a match is not found, <tt>USEARCH_DONE</tt> will be returned and
+     * the iterator will be adjusted to the index USEARCH_DONE
+     * @param  status for errors if it occurs
+     * @return The character index of the first match, or 
+     *         <tt>USEARCH_DONE</tt> if there are no matches.
+     * @see #getOffset
+     * @stable ICU 2.0
+     */
+    int32_t first(UErrorCode &status);
+
+    /**
+     * Returns the first index greater than <tt>position</tt> at which the 
+     * string text matches the search pattern. The iterator is adjusted so 
+     * that its current index (as returned by <tt>getOffset</tt>) is the 
+     * match position if one was found. If a match is not found, 
+     * <tt>USEARCH_DONE</tt> will be returned and the iterator will be 
+     * adjusted to the index USEARCH_DONE
+     * @param  position where search if to start from. If position is less
+     *             than or greater than the text range for searching, 
+     *          an U_INDEX_OUTOFBOUNDS_ERROR will be returned
+     * @param  status for errors if it occurs
+     * @return The character index of the first match following 
+     *         <tt>position</tt>, or <tt>USEARCH_DONE</tt> if there are no 
+     *         matches.
+     * @see #getOffset
+     * @stable ICU 2.0
+     */
+    int32_t following(int32_t position, UErrorCode &status);
+    
+    /**
+     * Returns the last index in the target text at which it matches the 
+     * search pattern. The iterator is adjusted so that its current index 
+     * (as returned by <tt>getOffset</tt>) is the match position if one was 
+     * found.
+     * If a match is not found, <tt>USEARCH_DONE</tt> will be returned and
+     * the iterator will be adjusted to the index USEARCH_DONE.
+     * @param  status for errors if it occurs
+     * @return The index of the first match, or <tt>USEARCH_DONE</tt> if 
+     *         there are no matches.
+     * @see #getOffset
+     * @stable ICU 2.0
+     */
+    int32_t last(UErrorCode &status);
+
+    /**
+     * Returns the first index less than <tt>position</tt> at which the string 
+     * text matches the search pattern. The iterator is adjusted so that its 
+     * current index (as returned by <tt>getOffset</tt>) is the match 
+     * position if one was found. If a match is not found, 
+     * <tt>USEARCH_DONE</tt> will be returned and the iterator will be 
+     * adjusted to the index USEARCH_DONE
+     * @param  position where search is to start from. If position is less
+     *             than or greater than the text range for searching, 
+     *          an U_INDEX_OUTOFBOUNDS_ERROR will be returned
+     * @param  status for errors if it occurs
+     * @return The character index of the first match preceding 
+     *         <tt>position</tt>, or <tt>USEARCH_DONE</tt> if there are 
+     *         no matches.
+     * @see #getOffset
+     * @stable ICU 2.0
+     */
+    int32_t preceding(int32_t position, UErrorCode &status);
+
+    /**
+     * Returns the index of the next point at which the text matches the
+     * search pattern, starting from the current position
+     * The iterator is adjusted so that its current index (as returned by 
+     * <tt>getOffset</tt>) is the match position if one was found.
+     * If a match is not found, <tt>USEARCH_DONE</tt> will be returned and
+     * the iterator will be adjusted to a position after the end of the text 
+     * string.
+     * @param  status for errors if it occurs
+     * @return The index of the next match after the current position,
+     *          or <tt>USEARCH_DONE</tt> if there are no more matches.
+     * @see #getOffset
+     * @stable ICU 2.0
+     */
+     int32_t next(UErrorCode &status);
+
+    /**
+     * Returns the index of the previous point at which the string text 
+     * matches the search pattern, starting at the current position.
+     * The iterator is adjusted so that its current index (as returned by 
+     * <tt>getOffset</tt>) is the match position if one was found.
+     * If a match is not found, <tt>USEARCH_DONE</tt> will be returned and
+     * the iterator will be adjusted to the index USEARCH_DONE
+     * @param  status for errors if it occurs
+     * @return The index of the previous match before the current position,
+     *          or <tt>USEARCH_DONE</tt> if there are no more matches.
+     * @see #getOffset
+     * @stable ICU 2.0
+     */
+    int32_t previous(UErrorCode &status);
+
+    /** 
+    * Resets the iteration.
+    * Search will begin at the start of the text string if a forward 
+    * iteration is initiated before a backwards iteration. Otherwise if a 
+    * backwards iteration is initiated before a forwards iteration, the 
+    * search will begin at the end of the text string.    
+    * @stable ICU 2.0
+    */
+    virtual void reset();
+
+protected:
+    // protected data members ---------------------------------------------
+
+    /**
+    * C search data struct
+    * @stable ICU 2.0
+    */
+    USearch *m_search_;
+
+    /**
+    * Break iterator.
+    * Currently the C++ breakiterator does not have getRules etc to reproduce
+    * another in C. Hence we keep the original around and do the verification
+    * at the end of the match. The user is responsible for deleting this
+    * break iterator.
+    * @stable ICU 2.0
+    */
+    BreakIterator *m_breakiterator_;
+    
+    /**
+    * Unicode string version of the search text
+    * @stable ICU 2.0
+    */
+    UnicodeString  m_text_;
+
+    // protected constructors and destructors -----------------------------
+
+    /**
+    * Default constructor.
+    * Initializes data to the default values.
+    * @stable ICU 2.0
+    */
+    SearchIterator();
+
+    /**
+     * Constructor for use by subclasses.
+     * @param text The target text to be searched.
+     * @param breakiter A {@link BreakIterator} that is used to restrict the 
+     *                points at which matches are detected. If 
+     *                <tt>handleNext</tt> or <tt>handlePrev</tt> finds a 
+     *                match, but the match's start or end index is not a 
+     *                boundary as determined by the <tt>BreakIterator</tt>, 
+     *                the match is rejected and <tt>handleNext</tt> or 
+     *                <tt>handlePrev</tt> is called again. If this parameter 
+     *                is <tt>NULL</tt>, no break detection is attempted.  
+     * @see #handleNext
+     * @see #handlePrev
+     * @stable ICU 2.0
+     */
+    SearchIterator(const UnicodeString &text, 
+                         BreakIterator *breakiter = NULL);
+
+    /**
+     * Constructor for use by subclasses.
+     * <p>
+     * Note: No parsing of the text within the <tt>CharacterIterator</tt> 
+     * will be done during searching for this version. The block of text 
+     * in <tt>CharacterIterator</tt> will be used as it is.
+     * @param text The target text to be searched.
+     * @param breakiter A {@link BreakIterator} that is used to restrict the 
+     *                points at which matches are detected. If 
+     *                <tt>handleNext</tt> or <tt>handlePrev</tt> finds a 
+     *                match, but the match's start or end index is not a 
+     *                boundary as determined by the <tt>BreakIterator</tt>, 
+     *                the match is rejected and <tt>handleNext</tt> or 
+     *                <tt>handlePrev</tt> is called again. If this parameter 
+     *                is <tt>NULL</tt>, no break detection is attempted.
+     * @see #handleNext
+     * @see #handlePrev
+     * @stable ICU 2.0
+     */
+    SearchIterator(CharacterIterator &text, BreakIterator *breakiter = NULL);
+
+    // protected methods --------------------------------------------------
+
+    /**
+     * Assignment operator. Sets this iterator to have the same behavior,
+     * and iterate over the same text, as the one passed in.
+     * @param that instance to be copied.
+     * @stable ICU 2.0
+     */
+    SearchIterator & operator=(const SearchIterator &that);
+
+    /**
+     * Abstract method which subclasses override to provide the mechanism
+     * for finding the next match in the target text. This allows different
+     * subclasses to provide different search algorithms.
+     * <p>
+     * If a match is found, the implementation should return the index at
+     * which the match starts and should call 
+     * <tt>setMatchLength</tt> with the number of characters 
+     * in the target text that make up the match. If no match is found, the 
+     * method should return USEARCH_DONE.
+     * <p>
+     * @param position The index in the target text at which the search 
+     *                 should start.
+     * @param status for error codes if it occurs.
+     * @return index at which the match starts, else if match is not found 
+     *         USEARCH_DONE is returned
+     * @see #setMatchLength
+     * @stable ICU 2.0
+     */
+    virtual int32_t handleNext(int32_t position, UErrorCode &status) 
+                                                                         = 0;
+
+    /**
+     * Abstract method which subclasses override to provide the mechanism for
+     * finding the previous match in the target text. This allows different
+     * subclasses to provide different search algorithms.
+     * <p>
+     * If a match is found, the implementation should return the index at
+     * which the match starts and should call 
+     * <tt>setMatchLength</tt> with the number of characters 
+     * in the target text that make up the match. If no match is found, the 
+     * method should return USEARCH_DONE.
+     * <p>
+     * @param position The index in the target text at which the search 
+     *                 should start.
+     * @param status for error codes if it occurs.
+     * @return index at which the match starts, else if match is not found 
+     *         USEARCH_DONE is returned
+     * @see #setMatchLength
+     * @stable ICU 2.0
+     */
+     virtual int32_t handlePrev(int32_t position, UErrorCode &status) 
+                                                                         = 0;
+
+    /**
+     * Sets the length of the currently matched string in the text string to
+     * be searched.
+     * Subclasses' <tt>handleNext</tt> and <tt>handlePrev</tt>
+     * methods should call this when they find a match in the target text.
+     * @param length length of the matched text.
+     * @see #handleNext
+     * @see #handlePrev
+     * @stable ICU 2.0
+     */
+    virtual void setMatchLength(int32_t length);
+
+    /**
+     * Sets the offset of the currently matched string in the text string to
+     * be searched.
+     * Subclasses' <tt>handleNext</tt> and <tt>handlePrev</tt>
+     * methods should call this when they find a match in the target text.
+     * @param position start offset of the matched text.
+     * @see #handleNext
+     * @see #handlePrev
+     * @stable ICU 2.0
+     */
+    virtual void setMatchStart(int32_t position);
+
+    /**
+    * sets match not found 
+    * @stable ICU 2.0
+    */
+    void setMatchNotFound();
+};
+
+inline UBool SearchIterator::operator!=(const SearchIterator &that) const
+{
+   return !operator==(that); 
+}
+U_NAMESPACE_END
+
+#endif /* #if !UCONFIG_NO_COLLATION */
+
+#endif
+

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/simpletz.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/simpletz.h b/src/apps/couch_collate/platform/osx/icu/unicode/simpletz.h
new file mode 100644
index 0000000..5b85c8d
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/simpletz.h
@@ -0,0 +1,927 @@
+/*
+ ********************************************************************************
+ * Copyright (C) 1997-2008, International Business Machines                     *
+ * Corporation and others. All Rights Reserved.                                 *
+ ********************************************************************************
+ *
+ * File SIMPLETZ.H
+ *
+ * Modification History:
+ *
+ *   Date        Name        Description
+ *   04/21/97    aliu        Overhauled header.
+ *   08/10/98    stephen     JDK 1.2 sync
+ *                           Added setStartRule() / setEndRule() overloads
+ *                           Added hasSameRules()
+ *   09/02/98    stephen     Added getOffset(monthLen)
+ *                           Changed getOffset() to take UErrorCode
+ *   07/09/99    stephen     Removed millisPerHour (unused, for HP compiler)
+ *   12/02/99    aliu        Added TimeMode and constructor and setStart/EndRule
+ *                           methods that take TimeMode. Added to docs.
+ ********************************************************************************
+ */
+
+#ifndef SIMPLETZ_H
+#define SIMPLETZ_H
+
+#include "unicode/utypes.h"
+
+/**
+ * \file 
+ * \brief C++ API: SimpleTimeZone is a concrete subclass of TimeZone.
+ */
+ 
+#if !UCONFIG_NO_FORMATTING
+
+#include "unicode/basictz.h"
+
+U_NAMESPACE_BEGIN
+
+// forward declaration
+class InitialTimeZoneRule;
+class TimeZoneTransition;
+class AnnualTimeZoneRule;
+
+/**
+ * <code>SimpleTimeZone</code> is a concrete subclass of <code>TimeZone</code>
+ * that represents a time zone for use with a Gregorian calendar. This
+ * class does not handle historical changes.
+ * <P>
+ * When specifying daylight-savings-time begin and end dates, use a negative value for
+ * <code>dayOfWeekInMonth</code> to indicate that <code>SimpleTimeZone</code> should
+ * count from the end of the month backwards. For example, in the U.S., Daylight Savings
+ * Time ends at the last (dayOfWeekInMonth = -1) Sunday in October, at 2 AM in standard
+ * time.
+ *
+ * @see      Calendar
+ * @see      GregorianCalendar
+ * @see      TimeZone
+ * @author   D. Goldsmith, Mark Davis, Chen-Lieh Huang, Alan Liu
+ */
+class U_I18N_API SimpleTimeZone: public BasicTimeZone {
+public:
+
+    /**
+     * TimeMode is used, together with a millisecond offset after
+     * midnight, to specify a rule transition time.  Most rules
+     * transition at a local wall time, that is, according to the
+     * current time in effect, either standard, or DST.  However, some
+     * rules transition at local standard time, and some at a specific
+     * UTC time.  Although it might seem that all times could be
+     * converted to wall time, thus eliminating the need for this
+     * parameter, this is not the case.
+     * @stable ICU 2.0
+     */
+    enum TimeMode {
+        WALL_TIME = 0,
+        STANDARD_TIME,
+        UTC_TIME
+    };
+
+    /**
+     * Copy constructor
+     * @param source the object to be copied.
+     * @stable ICU 2.0
+     */
+    SimpleTimeZone(const SimpleTimeZone& source);
+
+    /**
+     * Default assignment operator
+     * @param right    the object to be copied.
+     * @stable ICU 2.0
+     */
+    SimpleTimeZone& operator=(const SimpleTimeZone& right);
+
+    /**
+     * Destructor
+     * @stable ICU 2.0
+     */
+    virtual ~SimpleTimeZone();
+
+    /**
+     * Returns true if the two TimeZone objects are equal; that is, they have
+     * the same ID, raw GMT offset, and DST rules.
+     *
+     * @param that  The SimpleTimeZone object to be compared with.
+     * @return      True if the given time zone is equal to this time zone; false
+     *              otherwise.
+     * @stable ICU 2.0
+     */
+    virtual UBool operator==(const TimeZone& that) const;
+
+    /**
+     * Constructs a SimpleTimeZone with the given raw GMT offset and time zone ID,
+     * and which doesn't observe daylight savings time.  Normally you should use
+     * TimeZone::createInstance() to create a TimeZone instead of creating a
+     * SimpleTimeZone directly with this constructor.
+     *
+     * @param rawOffsetGMT  The given base time zone offset to GMT.
+     * @param ID         The timezone ID which is obtained from
+     *                   TimeZone.getAvailableIDs.
+     * @stable ICU 2.0
+     */
+    SimpleTimeZone(int32_t rawOffsetGMT, const UnicodeString& ID);
+
+    /**
+     * Construct a SimpleTimeZone with the given raw GMT offset, time zone ID,
+     * and times to start and end daylight savings time. To create a TimeZone that
+     * doesn't observe daylight savings time, don't use this constructor; use
+     * SimpleTimeZone(rawOffset, ID) instead. Normally, you should use
+     * TimeZone.createInstance() to create a TimeZone instead of creating a
+     * SimpleTimeZone directly with this constructor.
+     * <P>
+     * Various types of daylight-savings time rules can be specfied by using different
+     * values for startDay and startDayOfWeek and endDay and endDayOfWeek.  For a
+     * complete explanation of how these parameters work, see the documentation for
+     * setStartRule().
+     *
+     * @param rawOffsetGMT      The new SimpleTimeZone's raw GMT offset
+     * @param ID                The new SimpleTimeZone's time zone ID.
+     * @param savingsStartMonth The daylight savings starting month. Month is
+     *                          0-based. eg, 0 for January.
+     * @param savingsStartDayOfWeekInMonth   The daylight savings starting
+     *                          day-of-week-in-month. See setStartRule() for a
+     *                          complete explanation.
+     * @param savingsStartDayOfWeek The daylight savings starting day-of-week.
+     *                          See setStartRule() for a complete explanation.
+     * @param savingsStartTime  The daylight savings starting time, expressed as the
+     *                          number of milliseconds after midnight.
+     * @param savingsEndMonth   The daylight savings ending month. Month is
+     *                          0-based. eg, 0 for January.
+     * @param savingsEndDayOfWeekInMonth     The daylight savings ending day-of-week-in-month.
+     *                          See setStartRule() for a complete explanation.
+     * @param savingsEndDayOfWeek The daylight savings ending day-of-week.
+     *                          See setStartRule() for a complete explanation.
+     * @param savingsEndTime    The daylight savings ending time, expressed as the
+     *                          number of milliseconds after midnight.
+     * @param status            An UErrorCode to receive the status.
+     * @stable ICU 2.0
+     */
+    SimpleTimeZone(int32_t rawOffsetGMT, const UnicodeString& ID,
+        int8_t savingsStartMonth, int8_t savingsStartDayOfWeekInMonth,
+        int8_t savingsStartDayOfWeek, int32_t savingsStartTime,
+        int8_t savingsEndMonth, int8_t savingsEndDayOfWeekInMonth,
+        int8_t savingsEndDayOfWeek, int32_t savingsEndTime,
+        UErrorCode& status);
+    /**
+     * Construct a SimpleTimeZone with the given raw GMT offset, time zone ID,
+     * and times to start and end daylight savings time. To create a TimeZone that
+     * doesn't observe daylight savings time, don't use this constructor; use
+     * SimpleTimeZone(rawOffset, ID) instead. Normally, you should use
+     * TimeZone.createInstance() to create a TimeZone instead of creating a
+     * SimpleTimeZone directly with this constructor.
+     * <P>
+     * Various types of daylight-savings time rules can be specfied by using different
+     * values for startDay and startDayOfWeek and endDay and endDayOfWeek.  For a
+     * complete explanation of how these parameters work, see the documentation for
+     * setStartRule().
+     *
+     * @param rawOffsetGMT      The new SimpleTimeZone's raw GMT offset
+     * @param ID                The new SimpleTimeZone's time zone ID.
+     * @param savingsStartMonth The daylight savings starting month. Month is
+     *                          0-based. eg, 0 for January.
+     * @param savingsStartDayOfWeekInMonth   The daylight savings starting
+     *                          day-of-week-in-month. See setStartRule() for a
+     *                          complete explanation.
+     * @param savingsStartDayOfWeek The daylight savings starting day-of-week.
+     *                          See setStartRule() for a complete explanation.
+     * @param savingsStartTime  The daylight savings starting time, expressed as the
+     *                          number of milliseconds after midnight.
+     * @param savingsEndMonth   The daylight savings ending month. Month is
+     *                          0-based. eg, 0 for January.
+     * @param savingsEndDayOfWeekInMonth     The daylight savings ending day-of-week-in-month.
+     *                          See setStartRule() for a complete explanation.
+     * @param savingsEndDayOfWeek The daylight savings ending day-of-week.
+     *                          See setStartRule() for a complete explanation.
+     * @param savingsEndTime    The daylight savings ending time, expressed as the
+     *                          number of milliseconds after midnight.
+     * @param savingsDST        The number of milliseconds added to standard time
+     *                          to get DST time. Default is one hour.
+     * @param status            An UErrorCode to receive the status.
+     * @stable ICU 2.0
+     */
+    SimpleTimeZone(int32_t rawOffsetGMT, const UnicodeString& ID,
+        int8_t savingsStartMonth, int8_t savingsStartDayOfWeekInMonth,
+        int8_t savingsStartDayOfWeek, int32_t savingsStartTime,
+        int8_t savingsEndMonth, int8_t savingsEndDayOfWeekInMonth,
+        int8_t savingsEndDayOfWeek, int32_t savingsEndTime,
+        int32_t savingsDST, UErrorCode& status);
+
+    /**
+     * Construct a SimpleTimeZone with the given raw GMT offset, time zone ID,
+     * and times to start and end daylight savings time. To create a TimeZone that
+     * doesn't observe daylight savings time, don't use this constructor; use
+     * SimpleTimeZone(rawOffset, ID) instead. Normally, you should use
+     * TimeZone.createInstance() to create a TimeZone instead of creating a
+     * SimpleTimeZone directly with this constructor.
+     * <P>
+     * Various types of daylight-savings time rules can be specfied by using different
+     * values for startDay and startDayOfWeek and endDay and endDayOfWeek.  For a
+     * complete explanation of how these parameters work, see the documentation for
+     * setStartRule().
+     *
+     * @param rawOffsetGMT      The new SimpleTimeZone's raw GMT offset
+     * @param ID                The new SimpleTimeZone's time zone ID.
+     * @param savingsStartMonth The daylight savings starting month. Month is
+     *                          0-based. eg, 0 for January.
+     * @param savingsStartDayOfWeekInMonth   The daylight savings starting
+     *                          day-of-week-in-month. See setStartRule() for a
+     *                          complete explanation.
+     * @param savingsStartDayOfWeek The daylight savings starting day-of-week.
+     *                          See setStartRule() for a complete explanation.
+     * @param savingsStartTime  The daylight savings starting time, expressed as the
+     *                          number of milliseconds after midnight.
+     * @param savingsStartTimeMode Whether the start time is local wall time, local
+     *                          standard time, or UTC time. Default is local wall time.
+     * @param savingsEndMonth   The daylight savings ending month. Month is
+     *                          0-based. eg, 0 for January.
+     * @param savingsEndDayOfWeekInMonth     The daylight savings ending day-of-week-in-month.
+     *                          See setStartRule() for a complete explanation.
+     * @param savingsEndDayOfWeek The daylight savings ending day-of-week.
+     *                          See setStartRule() for a complete explanation.
+     * @param savingsEndTime    The daylight savings ending time, expressed as the
+     *                          number of milliseconds after midnight.
+     * @param savingsEndTimeMode Whether the end time is local wall time, local
+     *                          standard time, or UTC time. Default is local wall time.
+     * @param savingsDST        The number of milliseconds added to standard time
+     *                          to get DST time. Default is one hour.
+     * @param status            An UErrorCode to receive the status.
+     * @stable ICU 2.0
+     */
+    SimpleTimeZone(int32_t rawOffsetGMT, const UnicodeString& ID,
+        int8_t savingsStartMonth, int8_t savingsStartDayOfWeekInMonth,
+        int8_t savingsStartDayOfWeek, int32_t savingsStartTime,
+        TimeMode savingsStartTimeMode,
+        int8_t savingsEndMonth, int8_t savingsEndDayOfWeekInMonth,
+        int8_t savingsEndDayOfWeek, int32_t savingsEndTime, TimeMode savingsEndTimeMode,
+        int32_t savingsDST, UErrorCode& status);
+
+    /**
+     * Sets the daylight savings starting year, that is, the year this time zone began
+     * observing its specified daylight savings time rules.  The time zone is considered
+     * not to observe daylight savings time prior to that year; SimpleTimeZone doesn't
+     * support historical daylight-savings-time rules.
+     * @param year the daylight savings starting year.
+     * @stable ICU 2.0
+     */
+    void setStartYear(int32_t year);
+
+    /**
+     * Sets the daylight savings starting rule. For example, in the U.S., Daylight Savings
+     * Time starts at the first Sunday in April, at 2 AM in standard time.
+     * Therefore, you can set the start rule by calling:
+     * setStartRule(TimeFields.APRIL, 1, TimeFields.SUNDAY, 2*60*60*1000);
+     * The dayOfWeekInMonth and dayOfWeek parameters together specify how to calculate
+     * the exact starting date.  Their exact meaning depend on their respective signs,
+     * allowing various types of rules to be constructed, as follows:
+     * <ul>
+     *   <li>If both dayOfWeekInMonth and dayOfWeek are positive, they specify the
+     *       day of week in the month (e.g., (2, WEDNESDAY) is the second Wednesday
+     *       of the month).</li>
+     *   <li>If dayOfWeek is positive and dayOfWeekInMonth is negative, they specify
+     *       the day of week in the month counting backward from the end of the month.
+     *       (e.g., (-1, MONDAY) is the last Monday in the month)</li>
+     *   <li>If dayOfWeek is zero and dayOfWeekInMonth is positive, dayOfWeekInMonth
+     *       specifies the day of the month, regardless of what day of the week it is.
+     *       (e.g., (10, 0) is the tenth day of the month)</li>
+     *   <li>If dayOfWeek is zero and dayOfWeekInMonth is negative, dayOfWeekInMonth
+     *       specifies the day of the month counting backward from the end of the
+     *       month, regardless of what day of the week it is (e.g., (-2, 0) is the
+     *       next-to-last day of the month).</li>
+     *   <li>If dayOfWeek is negative and dayOfWeekInMonth is positive, they specify the
+     *       first specified day of the week on or after the specfied day of the month.
+     *       (e.g., (15, -SUNDAY) is the first Sunday after the 15th of the month
+     *       [or the 15th itself if the 15th is a Sunday].)</li>
+     *   <li>If dayOfWeek and DayOfWeekInMonth are both negative, they specify the
+     *       last specified day of the week on or before the specified day of the month.
+     *       (e.g., (-20, -TUESDAY) is the last Tuesday before the 20th of the month
+     *       [or the 20th itself if the 20th is a Tuesday].)</li>
+     * </ul>
+     * @param month the daylight savings starting month. Month is 0-based.
+     * eg, 0 for January.
+     * @param dayOfWeekInMonth the daylight savings starting
+     * day-of-week-in-month. Please see the member description for an example.
+     * @param dayOfWeek the daylight savings starting day-of-week. Please see
+     * the member description for an example.
+     * @param time the daylight savings starting time. Please see the member
+     * description for an example.
+     * @param status An UErrorCode
+     * @stable ICU 2.0
+     */
+    void setStartRule(int32_t month, int32_t dayOfWeekInMonth, int32_t dayOfWeek,
+                      int32_t time, UErrorCode& status);
+    /**
+     * Sets the daylight savings starting rule. For example, in the U.S., Daylight Savings
+     * Time starts at the first Sunday in April, at 2 AM in standard time.
+     * Therefore, you can set the start rule by calling:
+     * setStartRule(TimeFields.APRIL, 1, TimeFields.SUNDAY, 2*60*60*1000);
+     * The dayOfWeekInMonth and dayOfWeek parameters together specify how to calculate
+     * the exact starting date.  Their exact meaning depend on their respective signs,
+     * allowing various types of rules to be constructed, as follows:
+     * <ul>
+     *   <li>If both dayOfWeekInMonth and dayOfWeek are positive, they specify the
+     *       day of week in the month (e.g., (2, WEDNESDAY) is the second Wednesday
+     *       of the month).</li>
+     *   <li>If dayOfWeek is positive and dayOfWeekInMonth is negative, they specify
+     *       the day of week in the month counting backward from the end of the month.
+     *       (e.g., (-1, MONDAY) is the last Monday in the month)</li>
+     *   <li>If dayOfWeek is zero and dayOfWeekInMonth is positive, dayOfWeekInMonth
+     *       specifies the day of the month, regardless of what day of the week it is.
+     *       (e.g., (10, 0) is the tenth day of the month)</li>
+     *   <li>If dayOfWeek is zero and dayOfWeekInMonth is negative, dayOfWeekInMonth
+     *       specifies the day of the month counting backward from the end of the
+     *       month, regardless of what day of the week it is (e.g., (-2, 0) is the
+     *       next-to-last day of the month).</li>
+     *   <li>If dayOfWeek is negative and dayOfWeekInMonth is positive, they specify the
+     *       first specified day of the week on or after the specfied day of the month.
+     *       (e.g., (15, -SUNDAY) is the first Sunday after the 15th of the month
+     *       [or the 15th itself if the 15th is a Sunday].)</li>
+     *   <li>If dayOfWeek and DayOfWeekInMonth are both negative, they specify the
+     *       last specified day of the week on or before the specified day of the month.
+     *       (e.g., (-20, -TUESDAY) is the last Tuesday before the 20th of the month
+     *       [or the 20th itself if the 20th is a Tuesday].)</li>
+     * </ul>
+     * @param month the daylight savings starting month. Month is 0-based.
+     * eg, 0 for January.
+     * @param dayOfWeekInMonth the daylight savings starting
+     * day-of-week-in-month. Please see the member description for an example.
+     * @param dayOfWeek the daylight savings starting day-of-week. Please see
+     * the member description for an example.
+     * @param time the daylight savings starting time. Please see the member
+     * description for an example.
+     * @param mode whether the time is local wall time, local standard time,
+     * or UTC time. Default is local wall time.
+     * @param status An UErrorCode
+     * @stable ICU 2.0
+     */
+    void setStartRule(int32_t month, int32_t dayOfWeekInMonth, int32_t dayOfWeek,
+                      int32_t time, TimeMode mode, UErrorCode& status);
+
+    /**
+     * Sets the DST start rule to a fixed date within a month.
+     *
+     * @param month         The month in which this rule occurs (0-based).
+     * @param dayOfMonth    The date in that month (1-based).
+     * @param time          The time of that day (number of millis after midnight)
+     *                      when DST takes effect in local wall time, which is
+     *                      standard time in this case.
+     * @param status An UErrorCode
+     * @stable ICU 2.0
+     */
+    void setStartRule(int32_t month, int32_t dayOfMonth, int32_t time,
+                      UErrorCode& status);
+    /**
+     * Sets the DST start rule to a fixed date within a month.
+     *
+     * @param month         The month in which this rule occurs (0-based).
+     * @param dayOfMonth    The date in that month (1-based).
+     * @param time          The time of that day (number of millis after midnight)
+     *                      when DST takes effect in local wall time, which is
+     *                      standard time in this case.
+     * @param mode whether the time is local wall time, local standard time,
+     * or UTC time. Default is local wall time.
+     * @param status An UErrorCode
+     * @stable ICU 2.0
+     */
+    void setStartRule(int32_t month, int32_t dayOfMonth, int32_t time,
+                      TimeMode mode, UErrorCode& status);
+
+    /**
+     * Sets the DST start rule to a weekday before or after a give date within
+     * a month, e.g., the first Monday on or after the 8th.
+     *
+     * @param month         The month in which this rule occurs (0-based).
+     * @param dayOfMonth    A date within that month (1-based).
+     * @param dayOfWeek     The day of the week on which this rule occurs.
+     * @param time          The time of that day (number of millis after midnight)
+     *                      when DST takes effect in local wall time, which is
+     *                      standard time in this case.
+     * @param after         If true, this rule selects the first dayOfWeek on
+     *                      or after dayOfMonth.  If false, this rule selects
+     *                      the last dayOfWeek on or before dayOfMonth.
+     * @param status An UErrorCode
+     * @stable ICU 2.0
+     */
+    void setStartRule(int32_t month, int32_t dayOfMonth, int32_t dayOfWeek,
+                      int32_t time, UBool after, UErrorCode& status);
+    /**
+     * Sets the DST start rule to a weekday before or after a give date within
+     * a month, e.g., the first Monday on or after the 8th.
+     *
+     * @param month         The month in which this rule occurs (0-based).
+     * @param dayOfMonth    A date within that month (1-based).
+     * @param dayOfWeek     The day of the week on which this rule occurs.
+     * @param time          The time of that day (number of millis after midnight)
+     *                      when DST takes effect in local wall time, which is
+     *                      standard time in this case.
+     * @param mode whether the time is local wall time, local standard time,
+     * or UTC time. Default is local wall time.
+     * @param after         If true, this rule selects the first dayOfWeek on
+     *                      or after dayOfMonth.  If false, this rule selects
+     *                      the last dayOfWeek on or before dayOfMonth.
+     * @param status An UErrorCode
+     * @stable ICU 2.0
+     */
+    void setStartRule(int32_t month, int32_t dayOfMonth, int32_t dayOfWeek,
+                      int32_t time, TimeMode mode, UBool after, UErrorCode& status);
+
+    /**
+     * Sets the daylight savings ending rule. For example, in the U.S., Daylight
+     * Savings Time ends at the last (-1) Sunday in October, at 2 AM in standard time.
+     * Therefore, you can set the end rule by calling:
+     * <pre>
+     * .   setEndRule(TimeFields.OCTOBER, -1, TimeFields.SUNDAY, 2*60*60*1000);
+     * </pre>
+     * Various other types of rules can be specified by manipulating the dayOfWeek
+     * and dayOfWeekInMonth parameters.  For complete details, see the documentation
+     * for setStartRule().
+     *
+     * @param month the daylight savings ending month. Month is 0-based.
+     * eg, 0 for January.
+     * @param dayOfWeekInMonth the daylight savings ending
+     * day-of-week-in-month. See setStartRule() for a complete explanation.
+     * @param dayOfWeek the daylight savings ending day-of-week. See setStartRule()
+     * for a complete explanation.
+     * @param time the daylight savings ending time. Please see the member
+     * description for an example.
+     * @param status An UErrorCode
+     * @stable ICU 2.0
+     */
+    void setEndRule(int32_t month, int32_t dayOfWeekInMonth, int32_t dayOfWeek,
+                    int32_t time, UErrorCode& status);
+
+    /**
+     * Sets the daylight savings ending rule. For example, in the U.S., Daylight
+     * Savings Time ends at the last (-1) Sunday in October, at 2 AM in standard time.
+     * Therefore, you can set the end rule by calling:
+     * <pre>
+     * .   setEndRule(TimeFields.OCTOBER, -1, TimeFields.SUNDAY, 2*60*60*1000);
+     * </pre>
+     * Various other types of rules can be specified by manipulating the dayOfWeek
+     * and dayOfWeekInMonth parameters.  For complete details, see the documentation
+     * for setStartRule().
+     *
+     * @param month the daylight savings ending month. Month is 0-based.
+     * eg, 0 for January.
+     * @param dayOfWeekInMonth the daylight savings ending
+     * day-of-week-in-month. See setStartRule() for a complete explanation.
+     * @param dayOfWeek the daylight savings ending day-of-week. See setStartRule()
+     * for a complete explanation.
+     * @param time the daylight savings ending time. Please see the member
+     * description for an example.
+     * @param mode whether the time is local wall time, local standard time,
+     * or UTC time. Default is local wall time.
+     * @param status An UErrorCode
+     * @stable ICU 2.0
+     */
+    void setEndRule(int32_t month, int32_t dayOfWeekInMonth, int32_t dayOfWeek,
+                    int32_t time, TimeMode mode, UErrorCode& status);
+
+    /**
+     * Sets the DST end rule to a fixed date within a month.
+     *
+     * @param month         The month in which this rule occurs (0-based).
+     * @param dayOfMonth    The date in that month (1-based).
+     * @param time          The time of that day (number of millis after midnight)
+     *                      when DST ends in local wall time, which is daylight
+     *                      time in this case.
+     * @param status An UErrorCode
+     * @stable ICU 2.0
+     */
+    void setEndRule(int32_t month, int32_t dayOfMonth, int32_t time, UErrorCode& status);
+
+    /**
+     * Sets the DST end rule to a fixed date within a month.
+     *
+     * @param month         The month in which this rule occurs (0-based).
+     * @param dayOfMonth    The date in that month (1-based).
+     * @param time          The time of that day (number of millis after midnight)
+     *                      when DST ends in local wall time, which is daylight
+     *                      time in this case.
+     * @param mode whether the time is local wall time, local standard time,
+     * or UTC time. Default is local wall time.
+     * @param status An UErrorCode
+     * @stable ICU 2.0
+     */
+    void setEndRule(int32_t month, int32_t dayOfMonth, int32_t time,
+                    TimeMode mode, UErrorCode& status);
+
+    /**
+     * Sets the DST end rule to a weekday before or after a give date within
+     * a month, e.g., the first Monday on or after the 8th.
+     *
+     * @param month         The month in which this rule occurs (0-based).
+     * @param dayOfMonth    A date within that month (1-based).
+     * @param dayOfWeek     The day of the week on which this rule occurs.
+     * @param time          The time of that day (number of millis after midnight)
+     *                      when DST ends in local wall time, which is daylight
+     *                      time in this case.
+     * @param after         If true, this rule selects the first dayOfWeek on
+     *                      or after dayOfMonth.  If false, this rule selects
+     *                      the last dayOfWeek on or before dayOfMonth.
+     * @param status An UErrorCode
+     * @stable ICU 2.0
+     */
+    void setEndRule(int32_t month, int32_t dayOfMonth, int32_t dayOfWeek,
+                    int32_t time, UBool after, UErrorCode& status);
+
+    /**
+     * Sets the DST end rule to a weekday before or after a give date within
+     * a month, e.g., the first Monday on or after the 8th.
+     *
+     * @param month         The month in which this rule occurs (0-based).
+     * @param dayOfMonth    A date within that month (1-based).
+     * @param dayOfWeek     The day of the week on which this rule occurs.
+     * @param time          The time of that day (number of millis after midnight)
+     *                      when DST ends in local wall time, which is daylight
+     *                      time in this case.
+     * @param mode whether the time is local wall time, local standard time,
+     * or UTC time. Default is local wall time.
+     * @param after         If true, this rule selects the first dayOfWeek on
+     *                      or after dayOfMonth.  If false, this rule selects
+     *                      the last dayOfWeek on or before dayOfMonth.
+     * @param status An UErrorCode
+     * @stable ICU 2.0
+     */
+    void setEndRule(int32_t month, int32_t dayOfMonth, int32_t dayOfWeek,
+                    int32_t time, TimeMode mode, UBool after, UErrorCode& status);
+
+    /**
+     * Returns the TimeZone's adjusted GMT offset (i.e., the number of milliseconds to add
+     * to GMT to get local time in this time zone, taking daylight savings time into
+     * account) as of a particular reference date.  The reference date is used to determine
+     * whether daylight savings time is in effect and needs to be figured into the offset
+     * that is returned (in other words, what is the adjusted GMT offset in this time zone
+     * at this particular date and time?).  For the time zones produced by createTimeZone(),
+     * the reference data is specified according to the Gregorian calendar, and the date
+     * and time fields are in GMT, NOT local time.
+     *
+     * @param era        The reference date's era
+     * @param year       The reference date's year
+     * @param month      The reference date's month (0-based; 0 is January)
+     * @param day        The reference date's day-in-month (1-based)
+     * @param dayOfWeek  The reference date's day-of-week (1-based; 1 is Sunday)
+     * @param millis     The reference date's milliseconds in day, UTT (NOT local time).
+     * @param status     An UErrorCode to receive the status.
+     * @return           The offset in milliseconds to add to GMT to get local time.
+     * @stable ICU 2.0
+     */
+    virtual int32_t getOffset(uint8_t era, int32_t year, int32_t month, int32_t day,
+                              uint8_t dayOfWeek, int32_t millis, UErrorCode& status) const;
+
+    /**
+     * Gets the time zone offset, for current date, modified in case of
+     * daylight savings. This is the offset to add *to* UTC to get local time.
+     * @param era the era of the given date.
+     * @param year the year in the given date.
+     * @param month the month in the given date.
+     * Month is 0-based. e.g., 0 for January.
+     * @param day the day-in-month of the given date.
+     * @param dayOfWeek the day-of-week of the given date.
+     * @param milliseconds the millis in day in <em>standard</em> local time.
+     * @param monthLength the length of the given month in days.
+     * @param status     An UErrorCode to receive the status.
+     * @return the offset to add *to* GMT to get local time.
+     * @stable ICU 2.0
+     */
+    virtual int32_t getOffset(uint8_t era, int32_t year, int32_t month, int32_t day,
+                           uint8_t dayOfWeek, int32_t milliseconds,
+                           int32_t monthLength, UErrorCode& status) const;
+    /**
+     * Gets the time zone offset, for current date, modified in case of
+     * daylight savings. This is the offset to add *to* UTC to get local time.
+     * @param era the era of the given date.
+     * @param year the year in the given date.
+     * @param month the month in the given date.
+     * Month is 0-based. e.g., 0 for January.
+     * @param day the day-in-month of the given date.
+     * @param dayOfWeek the day-of-week of the given date.
+     * @param milliseconds the millis in day in <em>standard</em> local time.
+     * @param monthLength the length of the given month in days.
+     * @param prevMonthLength length of the previous month in days.
+     * @param status     An UErrorCode to receive the status.
+     * @return the offset to add *to* GMT to get local time.
+     * @stable ICU 2.0
+     */
+    virtual int32_t getOffset(uint8_t era, int32_t year, int32_t month, int32_t day,
+                              uint8_t dayOfWeek, int32_t milliseconds,
+                              int32_t monthLength, int32_t prevMonthLength,
+                              UErrorCode& status) const;
+
+    /**
+     * Redeclared TimeZone method.  This implementation simply calls
+     * the base class method, which otherwise would be hidden.
+     * @stable ICU 2.8
+     */
+    virtual void getOffset(UDate date, UBool local, int32_t& rawOffset,
+                           int32_t& dstOffset, UErrorCode& ec) const;
+
+    /**
+     * Get time zone offsets from local wall time.
+     * @internal
+     */
+    virtual void getOffsetFromLocal(UDate date, int32_t nonExistingTimeOpt, int32_t duplicatedTimeOpt,
+        int32_t& rawOffset, int32_t& dstOffset, UErrorCode& status) /*const*/;
+
+    /**
+     * Returns the TimeZone's raw GMT offset (i.e., the number of milliseconds to add
+     * to GMT to get local time, before taking daylight savings time into account).
+     *
+     * @return   The TimeZone's raw GMT offset.
+     * @stable ICU 2.0
+     */
+    virtual int32_t getRawOffset(void) const;
+
+    /**
+     * Sets the TimeZone's raw GMT offset (i.e., the number of milliseconds to add
+     * to GMT to get local time, before taking daylight savings time into account).
+     *
+     * @param offsetMillis  The new raw GMT offset for this time zone.
+     * @stable ICU 2.0
+     */
+    virtual void setRawOffset(int32_t offsetMillis);
+
+    /**
+     * Sets the amount of time in ms that the clock is advanced during DST.
+     * @param millisSavedDuringDST the number of milliseconds the time is
+     * advanced with respect to standard time when the daylight savings rules
+     * are in effect. A positive number, typically one hour (3600000).
+     * @param status  An UErrorCode to receive the status.
+     * @stable ICU 2.0
+     */
+    void setDSTSavings(int32_t millisSavedDuringDST, UErrorCode& status);
+
+    /**
+     * Returns the amount of time in ms that the clock is advanced during DST.
+     * @return the number of milliseconds the time is
+     * advanced with respect to standard time when the daylight savings rules
+     * are in effect. A positive number, typically one hour (3600000).
+     * @stable ICU 2.0
+     */
+    virtual int32_t getDSTSavings(void) const;
+
+    /**
+     * Queries if this TimeZone uses Daylight Savings Time.
+     *
+     * @return   True if this TimeZone uses Daylight Savings Time; false otherwise.
+     * @stable ICU 2.0
+     */
+    virtual UBool useDaylightTime(void) const;
+
+    /**
+     * Returns true if the given date is within the period when daylight savings time
+     * is in effect; false otherwise.  If the TimeZone doesn't observe daylight savings
+     * time, this functions always returns false.
+     * This method is wasteful since it creates a new GregorianCalendar and
+     * deletes it each time it is called. This is a deprecated method
+     * and provided only for Java compatibility.
+     *
+     * @param date The date to test.
+     * @param status  An UErrorCode to receive the status.
+     * @return true if the given date is in Daylight Savings Time;
+     * false otherwise.
+     * @deprecated ICU 2.4. Use Calendar::inDaylightTime() instead.
+     */
+    virtual UBool inDaylightTime(UDate date, UErrorCode& status) const;
+
+    /**
+     * Return true if this zone has the same rules and offset as another zone.
+     * @param other the TimeZone object to be compared with
+     * @return true if the given zone has the same rules and offset as this one
+     * @stable ICU 2.0
+     */
+    UBool hasSameRules(const TimeZone& other) const;
+
+    /**
+     * Clones TimeZone objects polymorphically. Clients are responsible for deleting
+     * the TimeZone object cloned.
+     *
+     * @return   A new copy of this TimeZone object.
+     * @stable ICU 2.0
+     */
+    virtual TimeZone* clone(void) const;
+
+    /**
+     * Gets the first time zone transition after the base time.
+     * @param base      The base time.
+     * @param inclusive Whether the base time is inclusive or not.
+     * @param result    Receives the first transition after the base time.
+     * @return  TRUE if the transition is found.
+     * @stable ICU 4.0
+     */
+    virtual UBool getNextTransition(UDate base, UBool inclusive, TimeZoneTransition& result) /*const*/;
+
+    /**
+     * Gets the most recent time zone transition before the base time.
+     * @param base      The base time.
+     * @param inclusive Whether the base time is inclusive or not.
+     * @param result    Receives the most recent transition before the base time.
+     * @return  TRUE if the transition is found.
+     * @stable ICU 4.0
+     */
+    virtual UBool getPreviousTransition(UDate base, UBool inclusive, TimeZoneTransition& result) /*const*/;
+
+    /**
+     * Returns the number of <code>TimeZoneRule</code>s which represents time transitions,
+     * for this time zone, that is, all <code>TimeZoneRule</code>s for this time zone except
+     * <code>InitialTimeZoneRule</code>.  The return value range is 0 or any positive value.
+     * @param status    Receives error status code.
+     * @return The number of <code>TimeZoneRule</code>s representing time transitions.
+     * @stable ICU 4.0
+     */
+    virtual int32_t countTransitionRules(UErrorCode& status) /*const*/;
+
+    /**
+     * Gets the <code>InitialTimeZoneRule</code> and the set of <code>TimeZoneRule</code>
+     * which represent time transitions for this time zone.  On successful return,
+     * the argument initial points to non-NULL <code>InitialTimeZoneRule</code> and
+     * the array trsrules is filled with 0 or multiple <code>TimeZoneRule</code>
+     * instances up to the size specified by trscount.  The results are referencing the
+     * rule instance held by this time zone instance.  Therefore, after this time zone
+     * is destructed, they are no longer available.
+     * @param initial       Receives the initial timezone rule
+     * @param trsrules      Receives the timezone transition rules
+     * @param trscount      On input, specify the size of the array 'transitions' receiving
+     *                      the timezone transition rules.  On output, actual number of
+     *                      rules filled in the array will be set.
+     * @param status        Receives error status code.
+     * @stable ICU 4.0
+     */
+    virtual void getTimeZoneRules(const InitialTimeZoneRule*& initial,
+        const TimeZoneRule* trsrules[], int32_t& trscount, UErrorCode& status) /*const*/;
+
+
+public:
+
+    /**
+     * Override TimeZone Returns a unique class ID POLYMORPHICALLY. Pure virtual
+     * override. This method is to implement a simple version of RTTI, since not all C++
+     * compilers support genuine RTTI. Polymorphic operator==() and clone() methods call
+     * this method.
+     *
+     * @return   The class ID for this object. All objects of a given class have the
+     *           same class ID. Objects of other classes have different class IDs.
+     * @stable ICU 2.0
+     */
+    virtual UClassID getDynamicClassID(void) const;
+
+    /**
+     * Return the class ID for this class. This is useful only for comparing to a return
+     * value from getDynamicClassID(). For example:
+     * <pre>
+     * .   Base* polymorphic_pointer = createPolymorphicObject();
+     * .   if (polymorphic_pointer->getDynamicClassID() ==
+     * .       Derived::getStaticClassID()) ...
+     * </pre>
+     * @return   The class ID for all objects of this class.
+     * @stable ICU 2.0
+     */
+    static UClassID U_EXPORT2 getStaticClassID(void);
+
+private:
+    /**
+     * Constants specifying values of startMode and endMode.
+     */
+    enum EMode
+    {
+        DOM_MODE = 1,
+        DOW_IN_MONTH_MODE,
+        DOW_GE_DOM_MODE,
+        DOW_LE_DOM_MODE
+    };
+
+    SimpleTimeZone(); // default constructor not implemented
+
+    /**
+     * Internal construction method.
+     * @param rawOffsetGMT    The new SimpleTimeZone's raw GMT offset
+     * @param startMonth      the month DST starts
+     * @param startDay        the day DST starts
+     * @param startDayOfWeek  the DOW DST starts
+     * @param startTime       the time DST starts
+     * @param startTimeMode   Whether the start time is local wall time, local
+     *                        standard time, or UTC time. Default is local wall time.
+     * @param endMonth        the month DST ends
+     * @param endDay          the day DST ends
+     * @param endDayOfWeek    the DOW DST ends
+     * @param endTime         the time DST ends
+     * @param endTimeMode     Whether the end time is local wall time, local
+     *                        standard time, or UTC time. Default is local wall time.
+     * @param savingsDST      The number of milliseconds added to standard time
+     *                        to get DST time. Default is one hour.
+     * @param status          An UErrorCode to receive the status.
+     */
+    void construct(int32_t rawOffsetGMT,
+                   int8_t startMonth, int8_t startDay, int8_t startDayOfWeek,
+                   int32_t startTime, TimeMode startTimeMode,
+                   int8_t endMonth, int8_t endDay, int8_t endDayOfWeek,
+                   int32_t endTime, TimeMode endTimeMode,
+                   int32_t dstSavings, UErrorCode& status);
+
+    /**
+     * Compare a given date in the year to a rule. Return 1, 0, or -1, depending
+     * on whether the date is after, equal to, or before the rule date. The
+     * millis are compared directly against the ruleMillis, so any
+     * standard-daylight adjustments must be handled by the caller.
+     *
+     * @return  1 if the date is after the rule date, -1 if the date is before
+     *          the rule date, or 0 if the date is equal to the rule date.
+     */
+    static int32_t compareToRule(int8_t month, int8_t monthLen, int8_t prevMonthLen,
+                                 int8_t dayOfMonth,
+                                 int8_t dayOfWeek, int32_t millis, int32_t millisDelta,
+                                 EMode ruleMode, int8_t ruleMonth, int8_t ruleDayOfWeek,
+                                 int8_t ruleDay, int32_t ruleMillis);
+
+    /**
+     * Given a set of encoded rules in startDay and startDayOfMonth, decode
+     * them and set the startMode appropriately.  Do the same for endDay and
+     * endDayOfMonth.
+     * <P>
+     * Upon entry, the day of week variables may be zero or
+     * negative, in order to indicate special modes.  The day of month
+     * variables may also be negative.
+     * <P>
+     * Upon exit, the mode variables will be
+     * set, and the day of week and day of month variables will be positive.
+     * <P>
+     * This method also recognizes a startDay or endDay of zero as indicating
+     * no DST.
+     */
+    void decodeRules(UErrorCode& status);
+    void decodeStartRule(UErrorCode& status);
+    void decodeEndRule(UErrorCode& status);
+
+    int8_t startMonth, startDay, startDayOfWeek;   // the month, day, DOW, and time DST starts
+    int32_t startTime;
+    TimeMode startTimeMode, endTimeMode; // Mode for startTime, endTime; see TimeMode
+    int8_t endMonth, endDay, endDayOfWeek; // the month, day, DOW, and time DST ends
+    int32_t endTime;
+    int32_t startYear;  // the year these DST rules took effect
+    int32_t rawOffset;  // the TimeZone's raw GMT offset
+    UBool useDaylight; // flag indicating whether this TimeZone uses DST
+    static const int8_t STATICMONTHLENGTH[12]; // lengths of the months
+    EMode startMode, endMode;   // flags indicating what kind of rules the DST rules are
+
+    /**
+     * A positive value indicating the amount of time saved during DST in ms.
+     * Typically one hour; sometimes 30 minutes.
+     */
+    int32_t dstSavings;
+
+    /* Private for BasicTimeZone implementation */
+    void initTransitionRules(UErrorCode& status);
+    void clearTransitionRules(void);
+    void deleteTransitionRules(void);
+    UBool   transitionRulesInitialized;
+    InitialTimeZoneRule*    initialRule;
+    TimeZoneTransition*     firstTransition;
+    AnnualTimeZoneRule*     stdRule;
+    AnnualTimeZoneRule*     dstRule;
+};
+
+inline void SimpleTimeZone::setStartRule(int32_t month, int32_t dayOfWeekInMonth,
+                                         int32_t dayOfWeek,
+                                         int32_t time, UErrorCode& status) {
+    setStartRule(month, dayOfWeekInMonth, dayOfWeek, time, WALL_TIME, status);
+}
+
+inline void SimpleTimeZone::setStartRule(int32_t month, int32_t dayOfMonth,
+                                         int32_t time,
+                                         UErrorCode& status) {
+    setStartRule(month, dayOfMonth, time, WALL_TIME, status);
+}
+
+inline void SimpleTimeZone::setStartRule(int32_t month, int32_t dayOfMonth,
+                                         int32_t dayOfWeek,
+                                         int32_t time, UBool after, UErrorCode& status) {
+    setStartRule(month, dayOfMonth, dayOfWeek, time, WALL_TIME, after, status);
+}
+
+inline void SimpleTimeZone::setEndRule(int32_t month, int32_t dayOfWeekInMonth,
+                                       int32_t dayOfWeek,
+                                       int32_t time, UErrorCode& status) {
+    setEndRule(month, dayOfWeekInMonth, dayOfWeek, time, WALL_TIME, status);
+}
+
+inline void SimpleTimeZone::setEndRule(int32_t month, int32_t dayOfMonth,
+                                       int32_t time, UErrorCode& status) {
+    setEndRule(month, dayOfMonth, time, WALL_TIME, status);
+}
+
+inline void SimpleTimeZone::setEndRule(int32_t month, int32_t dayOfMonth, int32_t dayOfWeek,
+                                       int32_t time, UBool after, UErrorCode& status) {
+    setEndRule(month, dayOfMonth, dayOfWeek, time, WALL_TIME, after, status);
+}
+
+inline void
+SimpleTimeZone::getOffset(UDate date, UBool local, int32_t& rawOffsetRef,
+                          int32_t& dstOffsetRef, UErrorCode& ec) const {
+    TimeZone::getOffset(date, local, rawOffsetRef, dstOffsetRef, ec);
+}
+
+U_NAMESPACE_END
+
+#endif /* #if !UCONFIG_NO_FORMATTING */
+
+#endif // _SIMPLETZ


[87/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/dtfmtsym.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/dtfmtsym.h b/src/apps/couch_collate/platform/osx/icu/unicode/dtfmtsym.h
new file mode 100644
index 0000000..a4b08bc
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/dtfmtsym.h
@@ -0,0 +1,721 @@
+/*  
+********************************************************************************
+*   Copyright (C) 1997-2008, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+********************************************************************************
+*
+* File DTFMTSYM.H
+*
+* Modification History:
+*
+*   Date        Name        Description
+*   02/19/97    aliu        Converted from java.
+*    07/21/98    stephen        Added getZoneIndex()
+*                            Changed to match C++ conventions
+********************************************************************************
+*/
+     
+#ifndef DTFMTSYM_H
+#define DTFMTSYM_H
+ 
+#include "unicode/utypes.h"
+
+#if !UCONFIG_NO_FORMATTING
+
+#include "unicode/calendar.h"
+#include "unicode/uobject.h"
+#include "unicode/locid.h"
+#include "unicode/ures.h"
+
+/**
+ * \file 
+ * \brief C++ API: Symbols for formatting dates.
+ */
+
+U_NAMESPACE_BEGIN
+
+/* forward declaration */
+class SimpleDateFormat;
+class Hashtable;
+class ZoneStringFormat;
+class SafeZoneStringFormatPtr;
+
+/**
+ * DateFormatSymbols is a public class for encapsulating localizable date-time
+ * formatting data -- including timezone data. DateFormatSymbols is used by
+ * DateFormat and SimpleDateFormat.
+ * <P>
+ * Rather than first creating a DateFormatSymbols to get a date-time formatter
+ * by using a SimpleDateFormat constructor, clients are encouraged to create a
+ * date-time formatter using the getTimeInstance(), getDateInstance(), or
+ * getDateTimeInstance() method in DateFormat. Each of these methods can return a
+ * date/time formatter initialized with a default format pattern along with the
+ * date-time formatting data for a given or default locale. After a formatter is
+ * created, clients may modify the format pattern using the setPattern function
+ * as so desired. For more information on using these formatter factory
+ * functions, see DateFormat.
+ * <P>
+ * If clients decide to create a date-time formatter with a particular format
+ * pattern and locale, they can do so with new SimpleDateFormat(aPattern,
+ * new DateFormatSymbols(aLocale)).  This will load the appropriate date-time
+ * formatting data from the locale.
+ * <P>
+ * DateFormatSymbols objects are clonable. When clients obtain a
+ * DateFormatSymbols object, they can feel free to modify the date-time
+ * formatting data as necessary. For instance, clients can
+ * replace the localized date-time format pattern characters with the ones that
+ * they feel easy to remember. Or they can change the representative cities
+ * originally picked by default to using their favorite ones.
+ * <P>
+ * DateFormatSymbols are not expected to be subclassed. Data for a calendar is
+ * loaded out of resource bundles.  The 'type' parameter indicates the type of
+ * calendar, for example, "gregorian" or "japanese".  If the type is not gregorian
+ * (or NULL, or an empty string) then the type is appended to the resource name,
+ * for example,  'Eras_japanese' instead of 'Eras'.   If the resource 'Eras_japanese' did
+ * not exist (even in root), then this class will fall back to just 'Eras', that is,
+ * Gregorian data.  Therefore, the calendar implementor MUST ensure that the root
+ * locale at least contains any resources that are to be particularized for the
+ * calendar type.
+ */
+class U_I18N_API DateFormatSymbols : public UObject {
+public:
+    /**
+     * Construct a DateFormatSymbols object by loading format data from
+     * resources for the default locale, in the default calendar (Gregorian).
+     * <P>
+     * NOTE: This constructor will never fail; if it cannot get resource
+     * data for the default locale, it will return a last-resort object
+     * based on hard-coded strings.
+     *
+     * @param status    Status code.  Failure
+     *                  results if the resources for the default cannot be
+     *                  found or cannot be loaded
+     * @stable ICU 2.0
+     */
+    DateFormatSymbols(UErrorCode& status);
+
+    /**
+     * Construct a DateFormatSymbols object by loading format data from
+     * resources for the given locale, in the default calendar (Gregorian).
+     *
+     * @param locale    Locale to load format data from.
+     * @param status    Status code.  Failure
+     *                  results if the resources for the locale cannot be
+     *                  found or cannot be loaded
+     * @stable ICU 2.0
+     */
+    DateFormatSymbols(const Locale& locale,
+                      UErrorCode& status);
+
+    /**
+     * Construct a DateFormatSymbols object by loading format data from
+     * resources for the default locale, in the default calendar (Gregorian).
+     * <P>
+     * NOTE: This constructor will never fail; if it cannot get resource
+     * data for the default locale, it will return a last-resort object
+     * based on hard-coded strings.
+     *
+     * @param type      Type of calendar (as returned by Calendar::getType). 
+     *                  Will be used to access the correct set of strings.
+     *                  (NULL or empty string defaults to "gregorian".)
+     * @param status    Status code.  Failure
+     *                  results if the resources for the default cannot be
+     *                  found or cannot be loaded
+     * @internal
+     */
+    DateFormatSymbols(const char *type, UErrorCode& status);
+
+    /**
+     * Construct a DateFormatSymbols object by loading format data from
+     * resources for the given locale, in the default calendar (Gregorian).
+     *
+     * @param locale    Locale to load format data from.
+     * @param type      Type of calendar (as returned by Calendar::getType). 
+     *                  Will be used to access the correct set of strings.
+     *                  (NULL or empty string defaults to "gregorian".)
+     * @param status    Status code.  Failure
+     *                  results if the resources for the locale cannot be
+     *                  found or cannot be loaded
+     * @internal
+     */
+    DateFormatSymbols(const Locale& locale,
+                      const char *type,
+                      UErrorCode& status);
+
+    /**
+     * Copy constructor.
+     * @stable ICU 2.0
+     */
+    DateFormatSymbols(const DateFormatSymbols&);
+
+    /**
+     * Assignment operator.
+     * @stable ICU 2.0
+     */
+    DateFormatSymbols& operator=(const DateFormatSymbols&);
+
+    /**
+     * Destructor. This is nonvirtual because this class is not designed to be
+     * subclassed.
+     * @stable ICU 2.0
+     */
+    virtual ~DateFormatSymbols();
+
+    /**
+     * Return true if another object is semantically equal to this one.
+     *
+     * @param other    the DateFormatSymbols object to be compared with.
+     * @return         true if other is semantically equal to this.
+     * @stable ICU 2.0
+     */
+    UBool operator==(const DateFormatSymbols& other) const;
+
+    /**
+     * Return true if another object is semantically unequal to this one.
+     *
+     * @param other    the DateFormatSymbols object to be compared with.
+     * @return         true if other is semantically unequal to this.
+     * @stable ICU 2.0
+     */
+    UBool operator!=(const DateFormatSymbols& other) const { return !operator==(other); }
+
+    /**
+     * Gets abbreviated era strings. For example: "AD" and "BC".
+     *
+     * @param count    Filled in with length of the array.
+     * @return         the era strings.
+     * @stable ICU 2.0
+     */
+    const UnicodeString* getEras(int32_t& count) const;
+
+    /**
+     * Sets abbreviated era strings. For example: "AD" and "BC".
+     * @param eras  Array of era strings (DateFormatSymbols retains ownership.)
+     * @param count Filled in with length of the array.
+     * @stable ICU 2.0
+     */
+    void setEras(const UnicodeString* eras, int32_t count);
+
+    /**
+     * Gets era name strings. For example: "Anno Domini" and "Before Christ".
+     *
+     * @param count    Filled in with length of the array.
+     * @return         the era name strings.
+     * @stable ICU 3.4
+     */
+    const UnicodeString* getEraNames(int32_t& count) const;
+
+    /**
+     * Sets era name strings. For example: "Anno Domini" and "Before Christ".
+     * @param eraNames  Array of era name strings (DateFormatSymbols retains ownership.)
+     * @param count Filled in with length of the array.
+     * @stable ICU 3.6
+     */
+    void setEraNames(const UnicodeString* eraNames, int32_t count);
+
+    /**
+     * Gets narrow era strings. For example: A" and "D".
+     *
+     * @param count    Filled in with length of the array.
+     * @return         the narrow era strings.
+     * @draft ICU 4.2
+     */
+    const UnicodeString* getNarrowEras(int32_t& count) const;
+
+    /**
+     * Sets narrow era strings. For example: "A" and "B".
+     * @param narrowEras  Array of narrow era strings (DateFormatSymbols retains ownership.)
+     * @param count Filled in with length of the array.
+     * @draft ICU 4.2
+     */
+    void setNarrowEras(const UnicodeString* narrowEras, int32_t count);
+
+    /**
+     * Gets month strings. For example: "January", "February", etc.
+     * @param count Filled in with length of the array.
+     * @return the month strings. (DateFormatSymbols retains ownership.)
+     * @stable ICU 2.0
+     */
+    const UnicodeString* getMonths(int32_t& count) const;
+
+    /**
+     * Sets month strings. For example: "January", "February", etc.
+     *
+     * @param months    the new month strings. (not adopted; caller retains ownership)
+     * @param count     Filled in with length of the array.
+     * @stable ICU 2.0
+     */
+    void setMonths(const UnicodeString* months, int32_t count);
+
+    /**
+     * Gets short month strings. For example: "Jan", "Feb", etc.
+     *
+     * @param count Filled in with length of the array.
+     * @return the short month strings. (DateFormatSymbols retains ownership.)
+     * @stable ICU 2.0
+     */
+    const UnicodeString* getShortMonths(int32_t& count) const;
+
+    /**
+     * Sets short month strings. For example: "Jan", "Feb", etc.
+     * @param count        Filled in with length of the array.
+     * @param shortMonths  the new short month strings. (not adopted; caller retains ownership)
+     * @stable ICU 2.0
+     */
+    void setShortMonths(const UnicodeString* shortMonths, int32_t count);
+
+    /**
+     * Selector for date formatting context
+     * @stable ICU 3.6
+     */
+    enum DtContextType {
+         FORMAT,
+         STANDALONE,
+         DT_CONTEXT_COUNT
+    };
+
+    /**
+     * Selector for date formatting width
+     * @stable ICU 3.6
+     */
+    enum DtWidthType {
+         ABBREVIATED,
+         WIDE,
+         NARROW,
+         DT_WIDTH_COUNT
+    };
+
+    /**
+     * Gets month strings by width and context. For example: "January", "February", etc.
+     * @param count Filled in with length of the array.
+     * @param context The formatting context, either FORMAT or STANDALONE
+     * @param width   The width of returned strings, either WIDE, ABBREVIATED, or NARROW.
+     * @return the month strings. (DateFormatSymbols retains ownership.)
+     * @stable ICU 3.4
+     */
+    const UnicodeString* getMonths(int32_t& count, DtContextType context, DtWidthType width) const;
+
+    /**
+     * Sets month strings by width and context. For example: "January", "February", etc.
+     *
+     * @param months  The new month strings. (not adopted; caller retains ownership)
+     * @param count   Filled in with length of the array.
+     * @param context The formatting context, either FORMAT or STANDALONE
+     * @param width   The width of returned strings, either WIDE, ABBREVIATED, or NARROW.
+     * @stable ICU 3.6
+     */
+    void setMonths(const UnicodeString* months, int32_t count, DtContextType context, DtWidthType width);
+
+    /**
+     * Gets weekday strings. For example: "Sunday", "Monday", etc.
+     * @param count        Filled in with length of the array.
+     * @return the weekday strings. (DateFormatSymbols retains ownership.)
+     * @stable ICU 2.0
+     */
+    const UnicodeString* getWeekdays(int32_t& count) const;
+
+
+    /**
+     * Sets weekday strings. For example: "Sunday", "Monday", etc.
+     * @param weekdays     the new weekday strings. (not adopted; caller retains ownership)
+     * @param count        Filled in with length of the array.
+     * @stable ICU 2.0
+     */
+    void setWeekdays(const UnicodeString* weekdays, int32_t count);
+
+    /**
+     * Gets short weekday strings. For example: "Sun", "Mon", etc.
+     * @param count        Filled in with length of the array.
+     * @return             the short weekday strings. (DateFormatSymbols retains ownership.)
+     * @stable ICU 2.0
+     */
+    const UnicodeString* getShortWeekdays(int32_t& count) const;
+
+    /**
+     * Sets short weekday strings. For example: "Sun", "Mon", etc.
+     * @param shortWeekdays  the new short weekday strings. (not adopted; caller retains ownership)
+     * @param count          Filled in with length of the array.
+     * @stable ICU 2.0
+     */
+    void setShortWeekdays(const UnicodeString* shortWeekdays, int32_t count);
+
+    /**
+     * Gets weekday strings by width and context. For example: "Sunday", "Monday", etc.
+     * @param count   Filled in with length of the array.
+     * @param context The formatting context, either FORMAT or STANDALONE
+     * @param width   The width of returned strings, either WIDE, ABBREVIATED, or NARROW
+     * @return the month strings. (DateFormatSymbols retains ownership.)
+     * @stable ICU 3.4
+     */
+    const UnicodeString* getWeekdays(int32_t& count, DtContextType context, DtWidthType width) const;
+
+    /**
+     * Sets weekday strings by width and context. For example: "Sunday", "Monday", etc.
+     * @param weekdays  The new weekday strings. (not adopted; caller retains ownership)
+     * @param count     Filled in with length of the array.
+     * @param context   The formatting context, either FORMAT or STANDALONE
+     * @param width     The width of returned strings, either WIDE, ABBREVIATED, or NARROW
+     * @stable ICU 3.6
+     */
+    void setWeekdays(const UnicodeString* weekdays, int32_t count, DtContextType context, DtWidthType width);
+
+    /**
+     * Gets quarter strings by width and context. For example: "1st Quarter", "2nd Quarter", etc.
+     * @param count Filled in with length of the array.
+     * @param context The formatting context, either FORMAT or STANDALONE
+     * @param width   The width of returned strings, either WIDE or ABBREVIATED. There
+     *                are no NARROW quarters.
+     * @return the quarter strings. (DateFormatSymbols retains ownership.)
+     * @stable ICU 3.6
+     */
+    const UnicodeString* getQuarters(int32_t& count, DtContextType context, DtWidthType width) const;
+
+    /**
+     * Sets quarter strings by width and context. For example: "1st Quarter", "2nd Quarter", etc.
+     *
+     * @param quarters  The new quarter strings. (not adopted; caller retains ownership)
+     * @param count   Filled in with length of the array.
+     * @param context The formatting context, either FORMAT or STANDALONE
+     * @param width   The width of returned strings, either WIDE or ABBREVIATED. There
+     *                are no NARROW quarters.
+     * @stable ICU 3.6
+     */
+    void setQuarters(const UnicodeString* quarters, int32_t count, DtContextType context, DtWidthType width);
+
+    /**
+     * Gets AM/PM strings. For example: "AM" and "PM".
+     * @param count        Filled in with length of the array.
+     * @return             the weekday strings. (DateFormatSymbols retains ownership.)
+     * @stable ICU 2.0
+     */
+    const UnicodeString* getAmPmStrings(int32_t& count) const;
+
+    /**
+     * Sets ampm strings. For example: "AM" and "PM".
+     * @param ampms        the new ampm strings. (not adopted; caller retains ownership)
+     * @param count        Filled in with length of the array.
+     * @stable ICU 2.0
+     */
+    void setAmPmStrings(const UnicodeString* ampms, int32_t count);
+
+    /**
+     * Gets timezone strings. These strings are stored in a 2-dimensional array.
+     * @param rowCount      Output param to receive number of rows.
+     * @param columnCount   Output param to receive number of columns.
+     * @return              The timezone strings as a 2-d array. (DateFormatSymbols retains ownership.)
+     * @deprecated ICU 3.6
+     */
+    const UnicodeString** getZoneStrings(int32_t& rowCount, int32_t& columnCount) const;
+
+    /**
+     * Sets timezone strings. These strings are stored in a 2-dimensional array.
+     * @param strings       The timezone strings as a 2-d array to be copied. (not adopted; caller retains ownership)
+     * @param rowCount      The number of rows (count of first index).
+     * @param columnCount   The number of columns (count of second index).
+     * @stable ICU 2.0
+     */
+    void setZoneStrings(const UnicodeString* const* strings, int32_t rowCount, int32_t columnCount);
+
+    /**
+     * Get the non-localized date-time pattern characters.
+     * @return    the non-localized date-time pattern characters
+     * @stable ICU 2.0
+     */
+    static const UChar * U_EXPORT2 getPatternUChars(void);
+
+    /**
+     * Gets localized date-time pattern characters. For example: 'u', 't', etc.
+     * <p>
+     * Note: ICU no longer provides localized date-time pattern characters for a locale
+     * starting ICU 3.8.  This method returns the non-localized date-time pattern
+     * characters unless user defined localized data is set by setLocalPatternChars.
+     * @param result    Output param which will receive the localized date-time pattern characters.
+     * @return          A reference to 'result'.
+     * @stable ICU 2.0
+     */
+    UnicodeString& getLocalPatternChars(UnicodeString& result) const;
+
+    /**
+     * Sets localized date-time pattern characters. For example: 'u', 't', etc.
+     * @param newLocalPatternChars the new localized date-time
+     * pattern characters.
+     * @stable ICU 2.0
+     */
+    void setLocalPatternChars(const UnicodeString& newLocalPatternChars);
+
+    /**
+     * Returns the locale for this object. Two flavors are available:
+     * valid and actual locale.
+     * @stable ICU 2.8
+     */
+    Locale getLocale(ULocDataLocaleType type, UErrorCode& status) const;
+
+    /**
+     * ICU "poor man's RTTI", returns a UClassID for the actual class.
+     *
+     * @stable ICU 2.2
+     */
+    virtual UClassID getDynamicClassID() const;
+
+    /**
+     * ICU "poor man's RTTI", returns a UClassID for this class.
+     *
+     * @stable ICU 2.2
+     */
+    static UClassID U_EXPORT2 getStaticClassID();
+
+private:
+
+    friend class SimpleDateFormat;
+    friend class DateFormatSymbolsSingleSetter; // see udat.cpp
+
+    /**
+     * Abbreviated era strings. For example: "AD" and "BC".
+     */
+    UnicodeString*  fEras;
+    int32_t         fErasCount;
+
+    /**
+     * Era name strings. For example: "Anno Domini" and "Before Christ".
+     */
+    UnicodeString*  fEraNames;
+    int32_t         fEraNamesCount;
+
+    /**
+     * Narrow era strings. For example: "A" and "B".
+     */
+    UnicodeString*  fNarrowEras;
+    int32_t         fNarrowErasCount;
+
+    /**
+     * Month strings. For example: "January", "February", etc.
+     */
+    UnicodeString*  fMonths;
+    int32_t         fMonthsCount;
+
+    /**
+     * Short month strings. For example: "Jan", "Feb", etc.
+     */
+    UnicodeString*  fShortMonths;
+    int32_t         fShortMonthsCount;
+
+    /**
+     * Narrow month strings. For example: "J", "F", etc.
+     */
+    UnicodeString*  fNarrowMonths;
+    int32_t         fNarrowMonthsCount;
+
+    /**
+     * Standalone Month strings. For example: "January", "February", etc.
+     */
+    UnicodeString*  fStandaloneMonths;
+    int32_t         fStandaloneMonthsCount;
+
+    /**
+     * Standalone Short month strings. For example: "Jan", "Feb", etc.
+     */
+    UnicodeString*  fStandaloneShortMonths;
+    int32_t         fStandaloneShortMonthsCount;
+
+    /**
+     * Standalone Narrow month strings. For example: "J", "F", etc.
+     */
+    UnicodeString*  fStandaloneNarrowMonths;
+    int32_t         fStandaloneNarrowMonthsCount;
+
+    /**
+     * Weekday strings. For example: "Sunday", "Monday", etc.
+     */
+    UnicodeString*  fWeekdays;
+    int32_t         fWeekdaysCount;
+
+    /**
+     * Short weekday strings. For example: "Sun", "Mon", etc.
+     */
+    UnicodeString*  fShortWeekdays;
+    int32_t         fShortWeekdaysCount;
+
+    /**
+     * Narrow weekday strings. For example: "Sun", "Mon", etc.
+     */
+    UnicodeString*  fNarrowWeekdays;
+    int32_t         fNarrowWeekdaysCount;
+
+    /**
+     * Standalone Weekday strings. For example: "Sunday", "Monday", etc.
+     */
+    UnicodeString*  fStandaloneWeekdays;
+    int32_t         fStandaloneWeekdaysCount;
+
+    /**
+     * Standalone Short weekday strings. For example: "Sun", "Mon", etc.
+     */
+    UnicodeString*  fStandaloneShortWeekdays;
+    int32_t         fStandaloneShortWeekdaysCount;
+
+    /**
+     * Standalone Narrow weekday strings. For example: "Sun", "Mon", etc.
+     */
+    UnicodeString*  fStandaloneNarrowWeekdays;
+    int32_t         fStandaloneNarrowWeekdaysCount;
+
+    /**
+     * Ampm strings. For example: "AM" and "PM".
+     */
+    UnicodeString*  fAmPms;
+    int32_t         fAmPmsCount;
+
+    /**
+     * Quarter strings. For example: "1st quarter", "2nd quarter", etc.
+     */
+    UnicodeString  *fQuarters;
+    int32_t         fQuartersCount;
+
+    /**
+     * Short quarters. For example: "Q1", "Q2", etc.
+     */
+    UnicodeString  *fShortQuarters;
+    int32_t         fShortQuartersCount;
+
+    /**
+     * Standalone quarter strings. For example: "1st quarter", "2nd quarter", etc.
+     */
+    UnicodeString  *fStandaloneQuarters;
+    int32_t         fStandaloneQuartersCount;
+
+    /**
+     * Standalone short quarter strings. For example: "Q1", "Q2", etc.
+     */
+    UnicodeString  *fStandaloneShortQuarters;
+    int32_t         fStandaloneShortQuartersCount;
+
+    /**
+     * The format data of all the timezones in this locale.
+     */
+    UnicodeString   **fZoneStrings;         // Zone string array set by setZoneStrings
+    UnicodeString   **fLocaleZoneStrings;   // Zone string array created by the locale
+    int32_t         fZoneStringsRowCount;
+    int32_t         fZoneStringsColCount;
+
+    const ZoneStringFormat  *fZoneStringFormat;
+    ZoneStringFormat        *fZSFLocal;         // Local ZoneStringFormat instance
+    SafeZoneStringFormatPtr *fZSFCachePtr;      // Cached ZoneStringFormat
+    Locale                  fZSFLocale;         // Locale used for getting ZoneStringFormat
+
+    /**
+     * Pattern string used for localized time zone GMT format.  For example, "GMT{0}"
+     */
+    UnicodeString   fGmtFormat;
+
+    /**
+     * Pattern strings used for formatting zone offset in a localized time zone GMT string.
+     */
+    UnicodeString  *fGmtHourFormats;
+    int32_t         fGmtHourFormatsCount; 
+
+    enum GMTHourType {
+        GMT_NEGATIVE_HMS = 0,
+        GMT_NEGATIVE_HM,
+        GMT_POSITIVE_HMS,
+        GMT_POSITIVE_HM,
+        GMT_HOUR_COUNT
+    };
+
+    /**
+     * Localized date-time pattern characters. For example: use 'u' as 'y'.
+     */
+    UnicodeString   fLocalPatternChars;
+
+private:
+    /** valid/actual locale information 
+     *  these are always ICU locales, so the length should not be a problem
+     */
+    char validLocale[ULOC_FULLNAME_CAPACITY];
+    char actualLocale[ULOC_FULLNAME_CAPACITY];
+
+    DateFormatSymbols(); // default constructor not implemented
+
+    /**
+     * Called by the constructors to actually load data from the resources
+     *
+     * @param locale               The locale to get symbols for.
+     * @param type                 Calendar Type (as from Calendar::getType())
+     * @param status               Input/output parameter, set to success or
+     *                             failure code upon return.
+     * @param useLastResortData    determine if use last resort data
+     */
+    void initializeData(const Locale&, const char *type, UErrorCode& status, UBool useLastResortData = FALSE);
+
+    /**
+     * Copy or alias an array in another object, as appropriate.
+     *
+     * @param dstArray    the copy destination array.
+     * @param dstCount    fill in with the lenth of 'dstArray'.
+     * @param srcArray    the source array to be copied.
+     * @param srcCount    the length of items to be copied from the 'srcArray'.
+     */
+    static void assignArray(UnicodeString*& dstArray,
+                            int32_t& dstCount,
+                            const UnicodeString* srcArray,
+                            int32_t srcCount);
+
+    /**
+     * Return true if the given arrays' contents are equal, or if the arrays are
+     * identical (pointers are equal).
+     *
+     * @param array1   one array to be compared with.
+     * @param array2   another array to be compared with.
+     * @param count    the length of items to be copied.
+     * @return         true if the given arrays' contents are equal, or if the arrays are
+     *                 identical (pointers are equal).
+     */
+    static UBool arrayCompare(const UnicodeString* array1,
+                             const UnicodeString* array2,
+                             int32_t count);
+
+    /**
+     * Create a copy, in fZoneStrings, of the given zone strings array. The
+     * member variables fZoneStringsRowCount and fZoneStringsColCount should be
+     * set already by the caller.
+     */
+    void createZoneStrings(const UnicodeString *const * otherStrings);
+
+    /**
+     * Delete all the storage owned by this object.
+     */
+    void dispose(void);
+
+    /**
+     * Copy all of the other's data to this.
+     * @param other the object to be copied.
+     */
+    void copyData(const DateFormatSymbols& other);
+
+
+    /**
+     * Returns a ZoneStringFormat, used only by SimpleDateFormat for now.
+     */
+    const ZoneStringFormat* getZoneStringFormat(void) const;
+
+    /**
+     * Create a ZoneStringFormat by locale if not yet availble
+     */
+    void initZoneStringFormat(void);
+
+    /**
+     * Create zone strings array by locale if not yet available
+     */
+    void initZoneStringsArray(void);
+
+    /**
+     * Delete just the zone strings.
+     */
+    void disposeZoneStrings(void);
+};
+
+U_NAMESPACE_END
+
+#endif /* #if !UCONFIG_NO_FORMATTING */
+
+#endif // _DTFMTSYM
+//eof

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/dtintrv.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/dtintrv.h b/src/apps/couch_collate/platform/osx/icu/unicode/dtintrv.h
new file mode 100644
index 0000000..b55dcd4
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/dtintrv.h
@@ -0,0 +1,159 @@
+/*
+*******************************************************************************
+* Copyright (C) 2008, International Business Machines Corporation and
+* others. All Rights Reserved.
+*******************************************************************************
+*
+* File DTINTRV.H 
+*
+*******************************************************************************
+*/
+
+#ifndef __DTINTRV_H__
+#define __DTINTRV_H__
+
+#include "unicode/utypes.h"
+#include "unicode/uobject.h"
+
+/**
+ * \file
+ * \brief C++ API: Date Interval data type
+ */
+
+
+U_NAMESPACE_BEGIN
+
+
+/**
+ * This class represents a date interval.
+ * It is a pair of UDate representing from UDate 1 to UDate 2.
+ * @draft ICU 4.0
+**/
+class U_COMMON_API DateInterval : public UObject {
+public:
+
+    /** 
+     * Construct a DateInterval given a from date and a to date.
+     * @param fromDate  The from date in date interval.
+     * @param toDate    The to date in date interval.
+     * @draft ICU 4.0
+     */
+    DateInterval(UDate fromDate, UDate toDate);
+
+    /**
+     * destructor
+     * @draft ICU 4.0
+     */
+    virtual ~DateInterval();
+ 
+    /** 
+     * Get the from date.
+     * @return  the from date in dateInterval.
+     * @draft ICU 4.0
+     */
+    UDate getFromDate() const;
+
+    /** 
+     * Get the to date.
+     * @return  the to date in dateInterval.
+     * @draft ICU 4.0
+     */
+    UDate getToDate() const;
+
+
+    /**
+     * Return the class ID for this class. This is useful only for comparing to
+     * a return value from getDynamicClassID(). For example:
+     * <pre>
+     * .   Base* polymorphic_pointer = createPolymorphicObject();
+     * .   if (polymorphic_pointer->getDynamicClassID() ==
+     * .       erived::getStaticClassID()) ...
+     * </pre>
+     * @return          The class ID for all objects of this class.
+     * @draft ICU 4.0
+     */
+    static UClassID U_EXPORT2 getStaticClassID(void);
+
+    /**
+     * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This
+     * method is to implement a simple version of RTTI, since not all C++
+     * compilers support genuine RTTI. Polymorphic operator==() and clone()
+     * methods call this method.
+     *
+     * @return          The class ID for this object. All objects of a
+     *                  given class have the same class ID.  Objects of
+     *                  other classes have different class IDs.
+     * @draft ICU 4.0
+     */
+    virtual UClassID getDynamicClassID(void) const;
+
+    
+    /**
+     * Copy constructor.
+     * @draft ICU 4.0
+     */
+    DateInterval(const DateInterval& other);
+
+    /**
+     * Default assignment operator
+     * @draft ICU 4.0
+     */
+    DateInterval& operator=(const DateInterval&);
+
+    /**
+     * Equality operator.
+     * @return TRUE if the two DateIntervals are the same
+     * @draft ICU 4.0
+     */
+    virtual UBool operator==(const DateInterval& other) const;
+
+    /**
+     * Non-equality operator
+     * @return TRUE if the two DateIntervals are not the same
+     * @draft ICU 4.0
+     */
+    UBool operator!=(const DateInterval& other) const;
+
+
+    /**
+     * clone this object. 
+     * The caller owns the result and should delete it when done.
+     * @return a cloned DateInterval
+     * @draft ICU 4.0
+     */
+     virtual DateInterval* clone() const;
+
+private:
+    /** 
+     * Default constructor, not implemented.
+     * @draft ICU 4.0
+     */
+    DateInterval();
+
+    UDate fromDate;
+    UDate toDate;
+
+} ;// end class DateInterval
+
+
+inline UDate 
+DateInterval::getFromDate() const { 
+    return fromDate; 
+}
+
+
+inline UDate 
+DateInterval::getToDate() const { 
+    return toDate; 
+}
+
+
+inline UBool 
+DateInterval::operator!=(const DateInterval& other) const { 
+    return ( !operator==(other) );
+}
+
+
+U_NAMESPACE_END
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/dtitvfmt.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/dtitvfmt.h b/src/apps/couch_collate/platform/osx/icu/unicode/dtitvfmt.h
new file mode 100644
index 0000000..2384437
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/dtitvfmt.h
@@ -0,0 +1,949 @@
+/********************************************************************************
+* Copyright (C) 2008, International Business Machines Corporation and others. All Rights Reserved.
+*******************************************************************************
+*
+* File DTITVFMT.H
+*
+*******************************************************************************
+*/
+
+#ifndef __DTITVFMT_H__
+#define __DTITVFMT_H__
+
+
+#include "unicode/utypes.h"
+
+/**
+ * \file 
+ * \brief C++ API: Format and parse date interval in a language-independent manner.
+ */
+ 
+#if !UCONFIG_NO_FORMATTING
+
+#include "unicode/ucal.h"
+#include "unicode/smpdtfmt.h"
+#include "unicode/dtintrv.h"
+#include "unicode/dtitvinf.h"
+
+U_NAMESPACE_BEGIN
+
+
+
+/**
+ * DateIntervalFormat is a class for formatting and parsing date 
+ * intervals in a language-independent manner. 
+ * Date interval formatting is supported in Gregorian calendar only.
+ * And only formatting is supported. Parsing is not supported.
+ *
+ * <P>
+ * Date interval means from one date to another date,
+ * for example, from "Jan 11, 2008" to "Jan 18, 2008".
+ * We introduced class DateInterval to represent it.
+ * DateInterval is a pair of UDate, which is 
+ * the standard milliseconds since 24:00 GMT, Jan 1, 1970.
+ *
+ * <P>
+ * DateIntervalFormat formats a DateInterval into
+ * text as compactly as possible. 
+ * For example, the date interval format from "Jan 11, 2008" to "Jan 18,. 2008"
+ * is "Jan 11-18, 2008" for English.
+ * And it parses text into DateInterval, 
+ * although initially, parsing is not supported. 
+ *
+ * <P>
+ * There is no structural information in date time patterns. 
+ * For any punctuations and string literals inside a date time pattern, 
+ * we do not know whether it is just a separator, or a prefix, or a suffix. 
+ * Without such information, so, it is difficult to generate a sub-pattern 
+ * (or super-pattern) by algorithm.
+ * So, formatting a DateInterval is pattern-driven. It is very
+ * similar to formatting in SimpleDateFormat.
+ * We introduce class DateIntervalInfo to save date interval 
+ * patterns, similar to date time pattern in SimpleDateFormat.
+ *
+ * <P>
+ * Logically, the interval patterns are mappings
+ * from (skeleton, the_largest_different_calendar_field)
+ * to (date_interval_pattern).
+ *
+ * <P>
+ * A skeleton 
+ * <ol>
+ * <li>
+ * only keeps the field pattern letter and ignores all other parts 
+ * in a pattern, such as space, punctuations, and string literals.
+ * </li>
+ * <li>
+ * hides the order of fields. 
+ * </li>
+ * <li>
+ * might hide a field's pattern letter length.
+ * </li>
+ * </ol>
+ *
+ * For those non-digit calendar fields, the pattern letter length is 
+ * important, such as MMM, MMMM, and MMMMM; EEE and EEEE, 
+ * and the field's pattern letter length is honored.
+ *    
+ * For the digit calendar fields,  such as M or MM, d or dd, yy or yyyy, 
+ * the field pattern length is ignored and the best match, which is defined 
+ * in date time patterns, will be returned without honor the field pattern
+ * letter length in skeleton.
+ *
+ * <P>
+ * The calendar fields we support for interval formatting are:
+ * year, month, date, day-of-week, am-pm, hour, hour-of-day, and minute.
+ * Those calendar fields can be defined in the following order:
+ * year >  month > date > hour (in day) >  minute 
+ *  
+ * The largest different calendar fields between 2 calendars is the
+ * first different calendar field in above order.
+ *
+ * For example: the largest different calendar fields between "Jan 10, 2007" 
+ * and "Feb 20, 2008" is year.
+ *
+ * <P>
+ * For other calendar fields, the compact interval formatting is not
+ * supported. And the interval format will be fall back to fall-back
+ * patterns, which is mostly "{date0} - {date1}".
+ *   
+ * <P>
+ * There is a set of pre-defined static skeleton strings.
+ * There are pre-defined interval patterns for those pre-defined skeletons
+ * in locales' resource files.
+ * For example, for a skeleton UDAT_YEAR_ABBR_MONTH_DAY, which is  "yMMMd",
+ * in  en_US, if the largest different calendar field between date1 and date2 
+ * is "year", the date interval pattern  is "MMM d, yyyy - MMM d, yyyy", 
+ * such as "Jan 10, 2007 - Jan 10, 2008".
+ * If the largest different calendar field between date1 and date2 is "month",
+ * the date interval pattern is "MMM d - MMM d, yyyy",
+ * such as "Jan 10 - Feb 10, 2007".
+ * If the largest different calendar field between date1 and date2 is "day",
+ * the date interval pattern is ""MMM d-d, yyyy", such as "Jan 10-20, 2007".
+ *
+ * For date skeleton, the interval patterns when year, or month, or date is 
+ * different are defined in resource files.
+ * For time skeleton, the interval patterns when am/pm, or hour, or minute is
+ * different are defined in resource files.
+ *
+ * <P>
+ * If a skeleton is not found in a locale's DateIntervalInfo, which means
+ * the interval patterns for the skeleton is not defined in resource file,
+ * the interval pattern will falls back to the interval "fallback" pattern 
+ * defined in resource file.
+ * If the interval "fallback" pattern is not defined, the default fall-back
+ * is "{date0} - {data1}".
+ *
+ * <P>
+ * For the combination of date and time, 
+ * The rule to generate interval patterns are:
+ * <ol>
+ * <li>
+ *    when the year, month, or day differs, falls back to fall-back
+ *    interval pattern, which mostly is the concatenate the two original 
+ *    expressions with a separator between, 
+ *    For example, interval pattern from "Jan 10, 2007 10:10 am" 
+ *    to "Jan 11, 2007 10:10am" is 
+ *    "Jan 10, 2007 10:10 am - Jan 11, 2007 10:10am" 
+ * </li>
+ * <li>
+ *    otherwise, present the date followed by the range expression 
+ *    for the time.
+ *    For example, interval pattern from "Jan 10, 2007 10:10 am" 
+ *    to "Jan 10, 2007 11:10am" is "Jan 10, 2007 10:10 am - 11:10am" 
+ * </li>
+ * </ol>
+ *
+ *
+ * <P>
+ * If two dates are the same, the interval pattern is the single date pattern.
+ * For example, interval pattern from "Jan 10, 2007" to "Jan 10, 2007" is 
+ * "Jan 10, 2007".
+ *
+ * Or if the presenting fields between 2 dates have the exact same values,
+ * the interval pattern is the  single date pattern. 
+ * For example, if user only requests year and month,
+ * the interval pattern from "Jan 10, 2007" to "Jan 20, 2007" is "Jan 2007".
+ *
+ * <P>
+ * DateIntervalFormat needs the following information for correct 
+ * formatting: time zone, calendar type, pattern, date format symbols, 
+ * and date interval patterns.
+ * It can be instantiated in 2 ways:
+ * <ol>
+ * <li>
+ *    create an instance using default or given locale plus given skeleton.
+ *    Users are encouraged to created date interval formatter this way and 
+ *    to use the pre-defined skeleton macros, such as
+ *    UDAT_YEAR_NUM_MONTH, which consists the calendar fields and
+ *    the format style. 
+ * </li>
+ * <li>
+ *    create an instance using default or given locale plus given skeleton
+ *    plus a given DateIntervalInfo.
+ *    This factory method is for powerful users who want to provide their own 
+ *    interval patterns. 
+ *    Locale provides the timezone, calendar, and format symbols information.
+ *    Local plus skeleton provides full pattern information.
+ *    DateIntervalInfo provides the date interval patterns.
+ * </li>
+ * </ol>
+ *
+ * <P>
+ * For the calendar field pattern letter, such as G, y, M, d, a, h, H, m, s etc.
+ * DateIntervalFormat uses the same syntax as that of
+ * DateTime format.
+ * 
+ * <P>
+ * Code Sample: general usage
+ * <pre>
+ * \code
+ *   // the date interval object which the DateIntervalFormat formats on
+ *   // and parses into
+ *   DateInterval*  dtInterval = new DateInterval(1000*3600*24, 1000*3600*24*2);
+ *   UErrorCode status = U_ZERO_ERROR;
+ *   DateIntervalFormat* dtIntervalFmt = DateIntervalFormat::createInstance(
+ *                           UDAT_YEAR_MONTH_DAY, 
+ *                           Locale("en", "GB", ""), status);
+ *   UnicodeUnicodeString dateIntervalString;
+ *   FieldPosition pos = 0;
+ *   // formatting
+ *   dtIntervalFmt->format(dtInterval, dateIntervalUnicodeString, pos, status);
+ *   delete dtIntervalFmt;
+ * \endcode
+ * </pre>
+ */
+
+class U_I18N_API DateIntervalFormat : public Format {
+public:
+
+    /**
+     * Construct a DateIntervalFormat from skeleton and  the default locale.
+     *
+     * This is a convenient override of 
+     * createInstance(const UnicodeString& skeleton, const Locale& locale,
+     *                UErrorCode&)  
+     * with the value of locale as default locale.
+     *
+     * @param skeleton  the skeleton on which interval format based.
+     * @param status    output param set to success/failure code on exit
+     * @return          a date time interval formatter which the caller owns.
+     * @draft ICU 4.0
+     */
+    static DateIntervalFormat* U_EXPORT2 createInstance(
+                                               const UnicodeString& skeleton,
+                                               UErrorCode& status);
+
+    /**
+     * Construct a DateIntervalFormat from skeleton and a given locale.
+     * <P>
+     * In this factory method, 
+     * the date interval pattern information is load from resource files.
+     * Users are encouraged to created date interval formatter this way and 
+     * to use the pre-defined skeleton macros.
+     *
+     * <P>
+     * There are pre-defined skeletons (defined in udate.h) having predefined 
+     * interval patterns in resource files.
+     * Users are encouraged to use those macros.
+     * For example: 
+     * DateIntervalFormat::createInstance(UDAT_MONTH_DAY, status) 
+     *
+     * The given Locale provides the interval patterns.
+     * For example, for en_GB, if skeleton is UDAT_YEAR_ABBR_MONTH_WEEKDAY_DAY,
+     * which is "yMMMEEEd",
+     * the interval patterns defined in resource file to above skeleton are:
+     * "EEE, d MMM, yyyy - EEE, d MMM, yyyy" for year differs,
+     * "EEE, d MMM - EEE, d MMM, yyyy" for month differs,
+     * "EEE, d - EEE, d MMM, yyyy" for day differs,
+     * @param skeleton  the skeleton on which interval format based.
+     * @param locale    the given locale
+     * @param status    output param set to success/failure code on exit
+     * @return          a date time interval formatter which the caller owns.
+     * @draft ICU 4.0
+     */
+
+    static DateIntervalFormat* U_EXPORT2 createInstance(
+                                               const UnicodeString& skeleton,
+                                               const Locale& locale,
+                                               UErrorCode& status);
+
+    /**
+     * Construct a DateIntervalFormat from skeleton
+     *  DateIntervalInfo, and default locale.
+     *
+     * This is a convenient override of
+     * createInstance(const UnicodeString& skeleton, const Locale& locale, 
+     *                const DateIntervalInfo& dtitvinf, UErrorCode&)
+     * with the locale value as default locale.
+     *
+     * @param skeleton  the skeleton on which interval format based.
+     * @param dtitvinf  the DateIntervalInfo object. 
+     * @param status    output param set to success/failure code on exit
+     * @return          a date time interval formatter which the caller owns.
+     * @draft ICU 4.0
+     */
+    static DateIntervalFormat* U_EXPORT2 createInstance(
+                                              const UnicodeString& skeleton,
+                                              const DateIntervalInfo& dtitvinf,
+                                              UErrorCode& status);
+
+    /**
+     * Construct a DateIntervalFormat from skeleton
+     * a DateIntervalInfo, and the given locale.
+     *
+     * <P>
+     * In this factory method, user provides its own date interval pattern
+     * information, instead of using those pre-defined data in resource file. 
+     * This factory method is for powerful users who want to provide their own 
+     * interval patterns. 
+     * <P>
+     * There are pre-defined skeletons (defined in udate.h) having predefined 
+     * interval patterns in resource files.
+     * Users are encouraged to use those macros.
+     * For example: 
+     * DateIntervalFormat::createInstance(UDAT_MONTH_DAY, status) 
+     *
+     * The DateIntervalInfo provides the interval patterns.
+     * and the DateIntervalInfo ownership remains to the caller. 
+     *
+     * User are encouraged to set default interval pattern in DateIntervalInfo
+     * as well, if they want to set other interval patterns ( instead of
+     * reading the interval patterns from resource files).
+     * When the corresponding interval pattern for a largest calendar different
+     * field is not found ( if user not set it ), interval format fallback to
+     * the default interval pattern.
+     * If user does not provide default interval pattern, it fallback to
+     * "{date0} - {date1}" 
+     *
+     * @param skeleton  the skeleton on which interval format based.
+     * @param locale    the given locale
+     * @param dtitvinf  the DateIntervalInfo object.
+     * @param status    output param set to success/failure code on exit
+     * @return          a date time interval formatter which the caller owns.
+     * @draft ICU 4.0
+     */
+    static DateIntervalFormat* U_EXPORT2 createInstance(
+                                              const UnicodeString& skeleton,
+                                              const Locale& locale,
+                                              const DateIntervalInfo& dtitvinf,
+                                              UErrorCode& status);
+
+    /**
+     * Destructor.
+     * @draft ICU 4.0
+     */
+    virtual ~DateIntervalFormat();
+
+    /**
+     * Clone this Format object polymorphically. The caller owns the result and
+     * should delete it when done.
+     * @return    A copy of the object.
+     * @draft ICU 4.0
+     */
+    virtual Format* clone(void) const;
+
+    /**
+     * Return true if the given Format objects are semantically equal. Objects
+     * of different subclasses are considered unequal.
+     * @param other    the object to be compared with.
+     * @return         true if the given Format objects are semantically equal.
+     * @draft ICU 4.0
+     */
+    virtual UBool operator==(const Format& other) const;
+
+    /**
+     * Return true if the given Format objects are not semantically equal. 
+     * Objects of different subclasses are considered unequal.
+     * @param other the object to be compared with.
+     * @return      true if the given Format objects are not semantically equal.
+     * @draft ICU 4.0
+     */
+    UBool operator!=(const Format& other) const;
+
+    /**
+     * Format an object to produce a string. This method handles Formattable
+     * objects with a DateInterval type. 
+     * If a the Formattable object type is not a DateInterval,
+     * then it returns a failing UErrorCode.
+     *
+     * @param obj               The object to format. 
+     *                          Must be a DateInterval.
+     * @param appendTo          Output parameter to receive result.
+     *                          Result is appended to existing contents.
+     * @param fieldPosition     On input: an alignment field, if desired.
+     *                          On output: the offsets of the alignment field.
+     * @param status            Output param filled with success/failure status.
+     * @return                  Reference to 'appendTo' parameter.
+     * @draft ICU 4.0
+     */
+    virtual UnicodeString& format(const Formattable& obj,
+                                  UnicodeString& appendTo,
+                                  FieldPosition& fieldPosition,
+                                  UErrorCode& status) const ;
+                                    
+                                    
+
+    /**
+     * Format a DateInterval to produce a string. 
+     *
+     * @param dtInterval        DateInterval to be formatted.
+     * @param appendTo          Output parameter to receive result.
+     *                          Result is appended to existing contents.
+     * @param fieldPosition     On input: an alignment field, if desired.
+     *                          On output: the offsets of the alignment field.
+     * @param status            Output param filled with success/failure status.
+     * @return                  Reference to 'appendTo' parameter.
+     * @draft ICU 4.0
+     */
+    UnicodeString& format(const DateInterval* dtInterval,
+                          UnicodeString& appendTo,
+                          FieldPosition& fieldPosition,
+                          UErrorCode& status) const ;
+                                    
+                                    
+    /**
+     * Format 2 Calendars to produce a string. 
+     *
+     * Note: "fromCalendar" and "toCalendar" are not const,
+     * since calendar is not const in  SimpleDateFormat::format(Calendar&),
+     *
+     * @param fromCalendar      calendar set to the from date in date interval
+     *                          to be formatted into date interval string
+     * @param toCalendar        calendar set to the to date in date interval
+     *                          to be formatted into date interval string
+     * @param appendTo          Output parameter to receive result.
+     *                          Result is appended to existing contents.
+     * @param fieldPosition     On input: an alignment field, if desired.
+     *                          On output: the offsets of the alignment field.
+     * @param status            Output param filled with success/failure status.
+     *                          Caller needs to make sure it is SUCCESS
+     *                          at the function entrance
+     * @return                  Reference to 'appendTo' parameter.
+     * @draft ICU 4.0
+     */
+    UnicodeString& format(Calendar& fromCalendar,
+                          Calendar& toCalendar,
+                          UnicodeString& appendTo,
+                          FieldPosition& fieldPosition,
+                          UErrorCode& status) const ;
+
+    /**
+     * Date interval parsing is not supported. Please do not use.
+     * <P>
+     * This method should handle parsing of
+     * date time interval strings into Formattable objects with 
+     * DateInterval type, which is a pair of UDate.
+     * <P>
+     * Before calling, set parse_pos.index to the offset you want to start
+     * parsing at in the source. After calling, parse_pos.index is the end of
+     * the text you parsed. If error occurs, index is unchanged.
+     * <P>
+     * When parsing, leading whitespace is discarded (with a successful parse),
+     * while trailing whitespace is left as is.
+     * <P>
+     * See Format::parseObject() for more.
+     *
+     * @param source    The string to be parsed into an object.
+     * @param result    Formattable to be set to the parse result.
+     *                  If parse fails, return contents are undefined.
+     * @param parse_pos The position to start parsing at. Since no parsing
+     *                  is supported, upon return this param is unchanged.
+     * @return          A newly created Formattable* object, or NULL
+     *                  on failure.  The caller owns this and should
+     *                  delete it when done.
+     * @internal ICU 4.0
+     */
+    virtual void parseObject(const UnicodeString& source,
+                             Formattable& result,
+                             ParsePosition& parse_pos) const;
+
+
+    /**
+     * Gets the date time interval patterns.
+     * @return the date time interval patterns associated with
+     * this date interval formatter.
+     * @draft ICU 4.0
+     */
+    const DateIntervalInfo* getDateIntervalInfo(void) const;
+
+
+    /**
+     * Set the date time interval patterns. 
+     * @param newIntervalPatterns   the given interval patterns to copy.
+     * @param status          output param set to success/failure code on exit
+     * @draft ICU 4.0
+     */
+    void setDateIntervalInfo(const DateIntervalInfo& newIntervalPatterns,
+                             UErrorCode& status);
+
+
+    /**
+     * Gets the date formatter
+     * @return the date formatter associated with this date interval formatter.
+     * @draft ICU 4.0
+     */
+    const DateFormat* getDateFormat(void) const;
+
+    /**
+     * Return the class ID for this class. This is useful only for comparing to
+     * a return value from getDynamicClassID(). For example:
+     * <pre>
+     * .   Base* polymorphic_pointer = createPolymorphicObject();
+     * .   if (polymorphic_pointer->getDynamicClassID() ==
+     * .       erived::getStaticClassID()) ...
+     * </pre>
+     * @return          The class ID for all objects of this class.
+     * @draft ICU 4.0
+     */
+    static UClassID U_EXPORT2 getStaticClassID(void);
+
+    /**
+     * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This
+     * method is to implement a simple version of RTTI, since not all C++
+     * compilers support genuine RTTI. Polymorphic operator==() and clone()
+     * methods call this method.
+     *
+     * @return          The class ID for this object. All objects of a
+     *                  given class have the same class ID.  Objects of
+     *                  other classes have different class IDs.
+     * @draft ICU 4.0
+     */
+    virtual UClassID getDynamicClassID(void) const;
+
+protected:
+
+    /**
+     * Copy constructor.
+     * @draft ICU 4.0
+     */
+    DateIntervalFormat(const DateIntervalFormat&);
+
+    /**
+     * Assignment operator.
+     * @draft ICU 4.0
+     */
+    DateIntervalFormat& operator=(const DateIntervalFormat&);
+
+private:
+
+    /*
+     * This is for ICU internal use only. Please do not use.
+     * Save the interval pattern information.
+     * Interval pattern consists of 2 single date patterns and the separator.
+     * For example, interval pattern "MMM d - MMM d, yyyy" consists
+     * a single date pattern "MMM d", another single date pattern "MMM d, yyyy",
+     * and a separator "-".
+     * The pattern is divided into 2 parts. For above example,
+     * the first part is "MMM d - ", and the second part is "MMM d, yyyy".
+     * Also, the first date appears in an interval pattern could be 
+     * the earlier date or the later date.
+     * And such information is saved in the interval pattern as well.
+     * @internal ICU 4.0
+     */
+    struct PatternInfo {
+        UnicodeString firstPart;
+        UnicodeString secondPart;
+        /**
+         * Whether the first date in interval pattern is later date or not.
+         * Fallback format set the default ordering.
+         * And for a particular interval pattern, the order can be 
+         * overriden by prefixing the interval pattern with "latestFirst:" or 
+         * "earliestFirst:"
+         * For example, given 2 date, Jan 10, 2007 to Feb 10, 2007.
+         * if the fallback format is "{0} - {1}", 
+         * and the pattern is "d MMM - d MMM yyyy", the interval format is
+         * "10 Jan - 10 Feb, 2007".
+         * If the pattern is "latestFirst:d MMM - d MMM yyyy", 
+         * the interval format is "10 Feb - 10 Jan, 2007"
+         */
+        UBool         laterDateFirst;
+    };
+
+   
+    /**
+     * default constructor 
+     * @internal ICU 4.0
+     */
+    DateIntervalFormat();
+
+    /**
+     * Construct a DateIntervalFormat from DateFormat,
+     * a DateIntervalInfo, and skeleton.
+     * DateFormat provides the timezone, calendar,
+     * full pattern, and date format symbols information.
+     * It should be a SimpleDateFormat object which 
+     * has a pattern in it.
+     * the DateIntervalInfo provides the interval patterns.
+     *
+     * Note: the DateIntervalFormat takes ownership of both 
+     * DateFormat and DateIntervalInfo objects. 
+     * Caller should not delete them.
+     *
+     * @param dtfmt     the SimpleDateFormat object to be adopted.
+     * @param dtitvinf  the DateIntervalInfo object to be adopted.
+     * @param skeleton  the skeleton of the date formatter
+     * @param status    output param set to success/failure code on exit
+     * @internal ICU 4.0
+     */
+    DateIntervalFormat(DateFormat* dtfmt, DateIntervalInfo* dtItvInfo,
+                       const UnicodeString* skeleton, UErrorCode& status);
+
+    
+    /**
+     * Construct a DateIntervalFormat from DateFormat
+     * and a DateIntervalInfo.
+     *
+     * It is a wrapper of the constructor.
+     *
+     * @param dtfmt     the DateFormat object to be adopted.
+     * @param dtitvinf  the DateIntervalInfo object to be adopted.
+     * @param skeleton  the skeleton of this formatter.
+     * @param status    Output param set to success/failure code.
+     * @return          a date time interval formatter which the caller owns.
+     * @internal ICU 4.0
+     */
+    static DateIntervalFormat* U_EXPORT2 create(DateFormat* dtfmt,
+                                                DateIntervalInfo* dtitvinf,
+                                                const UnicodeString* skeleton,
+                                                UErrorCode& status);
+
+
+    /**
+     *  Below are for generating interval patterns locale to the formatter 
+     */
+
+
+    /**
+     * Format 2 Calendars using fall-back interval pattern
+     *
+     * The full pattern used in this fall-back format is the
+     * full pattern of the date formatter.
+     *
+     * @param fromCalendar      calendar set to the from date in date interval
+     *                          to be formatted into date interval string
+     * @param toCalendar        calendar set to the to date in date interval
+     *                          to be formatted into date interval string
+     * @param appendTo          Output parameter to receive result.
+     *                          Result is appended to existing contents.
+     * @param pos               On input: an alignment field, if desired.
+     *                          On output: the offsets of the alignment field.
+     * @param status            output param set to success/failure code on exit
+     * @return                  Reference to 'appendTo' parameter.
+     * @internal ICU 4.0
+     */
+    UnicodeString& fallbackFormat(Calendar& fromCalendar,
+                                  Calendar& toCalendar,
+                                  UnicodeString& appendTo,
+                                  FieldPosition& pos,
+                                  UErrorCode& status) const;
+
+
+
+    /** 
+     * Initialize interval patterns locale to this formatter
+     * 
+     * This code is a bit complicated since 
+     * 1. the interval patterns saved in resource bundle files are interval
+     *    patterns based on date or time only.
+     *    It does not have interval patterns based on both date and time.
+     *    Interval patterns on both date and time are algorithm generated.
+     *
+     *    For example, it has interval patterns on skeleton "dMy" and "hm",
+     *    but it does not have interval patterns on skeleton "dMyhm".
+     *    
+     *    The rule to generate interval patterns for both date and time skeleton are
+     *    1) when the year, month, or day differs, concatenate the two original 
+     *    expressions with a separator between, 
+     *    For example, interval pattern from "Jan 10, 2007 10:10 am" 
+     *    to "Jan 11, 2007 10:10am" is 
+     *    "Jan 10, 2007 10:10 am - Jan 11, 2007 10:10am" 
+     *
+     *    2) otherwise, present the date followed by the range expression 
+     *    for the time.
+     *    For example, interval pattern from "Jan 10, 2007 10:10 am" 
+     *    to "Jan 10, 2007 11:10am" is 
+     *    "Jan 10, 2007 10:10 am - 11:10am" 
+     *
+     * 2. even a pattern does not request a certain calendar field,
+     *    the interval pattern needs to include such field if such fields are
+     *    different between 2 dates.
+     *    For example, a pattern/skeleton is "hm", but the interval pattern 
+     *    includes year, month, and date when year, month, and date differs.
+     * 
+     *
+     * @param status    output param set to success/failure code on exit
+     * @internal ICU 4.0 
+     */
+    void initializePattern(UErrorCode& status); 
+                              
+
+
+    /**
+     * Set fall back interval pattern given a calendar field,
+     * a skeleton, and a date time pattern generator.
+     * @param field      the largest different calendar field
+     * @param skeleton   a skeleton
+     * @param dtpng      date time pattern generator
+     * @param status     output param set to success/failure code on exit
+     * @internal ICU 4.0 
+     */
+    void setFallbackPattern(UCalendarDateFields field, 
+                            const UnicodeString& skeleton,
+                            DateTimePatternGenerator* dtpng,
+                            UErrorCode& status);
+                            
+
+
+    /** 
+     * get separated date and time skeleton from a combined skeleton.
+     *
+     * The difference between date skeleton and normalizedDateSkeleton are:
+     * 1. both 'y' and 'd' are appeared only once in normalizeDateSkeleton
+     * 2. 'E' and 'EE' are normalized into 'EEE'
+     * 3. 'MM' is normalized into 'M'
+     *
+     ** the difference between time skeleton and normalizedTimeSkeleton are:
+     * 1. both 'H' and 'h' are normalized as 'h' in normalized time skeleton,
+     * 2. 'a' is omitted in normalized time skeleton.
+     * 3. there is only one appearance for 'h', 'm','v', 'z' in normalized time
+     *    skeleton
+     *
+     *
+     *  @param skeleton               given combined skeleton.
+     *  @param date                   Output parameter for date only skeleton.
+     *  @param normalizedDate         Output parameter for normalized date only
+     *
+     *  @param time                   Output parameter for time only skeleton.
+     *  @param normalizedTime         Output parameter for normalized time only
+     *                                skeleton.
+     *
+     * @internal ICU 4.0 
+     */
+    static void  U_EXPORT2 getDateTimeSkeleton(const UnicodeString& skeleton,
+                                    UnicodeString& date,
+                                    UnicodeString& normalizedDate,
+                                    UnicodeString& time,
+                                    UnicodeString& normalizedTime);
+
+
+
+    /**
+     * Generate date or time interval pattern from resource,
+     * and set them into the interval pattern locale to this formatter.
+     *
+     * It needs to handle the following: 
+     * 1. need to adjust field width.
+     *    For example, the interval patterns saved in DateIntervalInfo
+     *    includes "dMMMy", but not "dMMMMy".
+     *    Need to get interval patterns for dMMMMy from dMMMy.
+     *    Another example, the interval patterns saved in DateIntervalInfo
+     *    includes "hmv", but not "hmz".
+     *    Need to get interval patterns for "hmz' from 'hmv'
+     *
+     * 2. there might be no pattern for 'y' differ for skeleton "Md",
+     *    in order to get interval patterns for 'y' differ,
+     *    need to look for it from skeleton 'yMd'
+     *
+     * @param dateSkeleton   normalized date skeleton
+     * @param timeSkeleton   normalized time skeleton
+     * @return               whether the resource is found for the skeleton.
+     *                       TRUE if interval pattern found for the skeleton,
+     *                       FALSE otherwise.
+     * @internal ICU 4.0
+     */
+    UBool setSeparateDateTimePtn(const UnicodeString& dateSkeleton, 
+                                 const UnicodeString& timeSkeleton);
+                                   
+
+
+
+    /**
+     * Generate interval pattern from existing resource
+     *
+     * It not only save the interval patterns,
+     * but also return the extended skeleton and its best match skeleton.
+     *
+     * @param field           largest different calendar field
+     * @param skeleton        skeleton
+     * @param bestSkeleton    the best match skeleton which has interval pattern
+     *                        defined in resource
+     * @param differenceInfo  the difference between skeleton and best skeleton
+     *         0 means the best matched skeleton is the same as input skeleton
+     *         1 means the fields are the same, but field width are different
+     *         2 means the only difference between fields are v/z,
+     *        -1 means there are other fields difference 
+     *
+     * @param extendedSkeleton      extended skeleton
+     * @param extendedBestSkeleton  extended best match skeleton
+     * @return                      whether the interval pattern is found 
+     *                              through extending skeleton or not.
+     *                              TRUE if interval pattern is found by
+     *                              extending skeleton, FALSE otherwise.
+     * @internal ICU 4.0
+     */
+    UBool setIntervalPattern(UCalendarDateFields field, 
+                             const UnicodeString* skeleton, 
+                             const UnicodeString* bestSkeleton, 
+                             int8_t differenceInfo, 
+                             UnicodeString* extendedSkeleton = NULL,
+                             UnicodeString* extendedBestSkeleton = NULL);
+
+    /**
+     * Adjust field width in best match interval pattern to match
+     * the field width in input skeleton.
+     *
+     * TODO (xji) make a general solution
+     * The adjusting rule can be:
+     * 1. always adjust
+     * 2. never adjust
+     * 3. default adjust, which means adjust according to the following rules
+     * 3.1 always adjust string, such as MMM and MMMM
+     * 3.2 never adjust between string and numeric, such as MM and MMM
+     * 3.3 always adjust year
+     * 3.4 do not adjust 'd', 'h', or 'm' if h presents
+     * 3.5 do not adjust 'M' if it is numeric(?)
+     *
+     * Since date interval format is well-formed format,
+     * date and time skeletons are normalized previously,
+     * till this stage, the adjust here is only "adjust strings, such as MMM
+     * and MMMM, EEE and EEEE.
+     *
+     * @param inputSkeleton            the input skeleton
+     * @param bestMatchSkeleton        the best match skeleton
+     * @param bestMatchIntervalpattern the best match interval pattern
+     * @param differenceInfo           the difference between 2 skeletons
+     *                                 1 means only field width differs
+     *                                 2 means v/z exchange
+     * @param adjustedIntervalPattern  adjusted interval pattern
+     * @internal ICU 4.0
+     */
+    static void U_EXPORT2 adjustFieldWidth(
+                            const UnicodeString& inputSkeleton,
+                            const UnicodeString& bestMatchSkeleton,
+                            const UnicodeString& bestMatchIntervalPattern,
+                            int8_t differenceInfo,
+                            UnicodeString& adjustedIntervalPattern);
+
+    /**
+     * Concat a single date pattern with a time interval pattern,
+     * set it into the intervalPatterns, while field is time field.
+     * This is used to handle time interval patterns on skeleton with
+     * both time and date. Present the date followed by 
+     * the range expression for the time.
+     * @param format         date and time format
+     * @param formatLen      format string length
+     * @param datePattern    date pattern
+     * @param field          time calendar field: AM_PM, HOUR, MINUTE
+     * @param status         output param set to success/failure code on exit
+     * @internal ICU 4.0 
+     */
+    void concatSingleDate2TimeInterval(const UChar* format,
+                                       int32_t formatLen,
+                                       const UnicodeString& datePattern,
+                                       UCalendarDateFields field,
+                                       UErrorCode& status); 
+
+    /**
+     * check whether a calendar field present in a skeleton.
+     * @param field      calendar field need to check
+     * @param skeleton   given skeleton on which to check the calendar field
+     * @return           true if field present in a skeleton.
+     * @internal ICU 4.0 
+     */
+    static UBool U_EXPORT2 fieldExistsInSkeleton(UCalendarDateFields field, 
+                                                 const UnicodeString& skeleton);
+
+
+    /**
+     * Split interval patterns into 2 part.
+     * @param intervalPattern  interval pattern
+     * @return the index in interval pattern which split the pattern into 2 part
+     * @internal ICU 4.0
+     */
+    static int32_t  U_EXPORT2 splitPatternInto2Part(const UnicodeString& intervalPattern);
+
+
+    /**
+     * Break interval patterns as 2 part and save them into pattern info.
+     * @param field            calendar field
+     * @param intervalPattern  interval pattern
+     * @internal ICU 4.0
+     */
+    void setIntervalPattern(UCalendarDateFields field,
+                            const UnicodeString& intervalPattern);
+
+
+    /**
+     * Break interval patterns as 2 part and save them into pattern info.
+     * @param field            calendar field
+     * @param intervalPattern  interval pattern
+     * @param laterDateFirst   whether later date appear first in interval pattern
+     * @internal ICU 4.0
+     */
+    void setIntervalPattern(UCalendarDateFields field,
+                            const UnicodeString& intervalPattern,
+                            UBool laterDateFirst);
+
+
+    /**
+     * Set pattern information.
+     *
+     * @param field            calendar field
+     * @param firstPart        the first part in interval pattern
+     * @param secondPart       the second part in interval pattern
+     * @param laterDateFirst   whether the first date in intervalPattern
+     *                         is earlier date or later date
+     * @internal ICU 4.0
+     */
+    void setPatternInfo(UCalendarDateFields field,
+                        const UnicodeString* firstPart,
+                        const UnicodeString* secondpart,
+                        UBool laterDateFirst);
+
+
+    // from calendar field to pattern letter
+    static const UChar fgCalendarFieldToPatternLetter[];
+
+
+    /**
+     * The interval patterns for this locale.
+     */
+    DateIntervalInfo*     fInfo;
+
+    /**
+     * The DateFormat object used to format single pattern
+     */
+    SimpleDateFormat*     fDateFormat;
+
+    /**
+     * The 2 calendars with the from and to date.
+     * could re-use the calendar in fDateFormat,
+     * but keeping 2 calendars make it clear and clean.
+     */
+    Calendar* fFromCalendar;
+    Calendar* fToCalendar;
+
+    /**
+     * Following are interval information relavent (locale) to this formatter.
+     */
+    UnicodeString fSkeleton;
+    PatternInfo fIntervalPatterns[DateIntervalInfo::kIPI_MAX_INDEX];
+};
+ 
+
+
+ 
+
+
+inline UBool 
+DateIntervalFormat::operator!=(const Format& other) const  {
+    return !operator==(other); 
+}
+ 
+U_NAMESPACE_END
+
+#endif /* #if !UCONFIG_NO_FORMATTING */
+
+#endif // _DTITVFMT_H__
+//eof


[57/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/usearch.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/usearch.h b/src/apps/couch_collate/platform/osx/icu/unicode/usearch.h
new file mode 100644
index 0000000..deaa78f
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/usearch.h
@@ -0,0 +1,766 @@
+/*
+**********************************************************************
+*   Copyright (C) 2001-2008 IBM and others. All rights reserved.
+**********************************************************************
+*   Date        Name        Description
+*  06/28/2001   synwee      Creation.
+**********************************************************************
+*/
+#ifndef USEARCH_H
+#define USEARCH_H
+
+#include "unicode/utypes.h"
+
+#if !UCONFIG_NO_COLLATION && !UCONFIG_NO_BREAK_ITERATION
+
+#include "unicode/ucol.h"
+#include "unicode/ucoleitr.h"
+#include "unicode/ubrk.h"
+
+/**
+ * \file
+ * \brief C API: StringSearch
+ *
+ * C Apis for an engine that provides language-sensitive text searching based 
+ * on the comparison rules defined in a <tt>UCollator</tt> data struct,
+ * see <tt>ucol.h</tt>. This ensures that language eccentricity can be 
+ * handled, e.g. for the German collator, characters &szlig; and SS will be matched 
+ * if case is chosen to be ignored. 
+ * See the <a href="http://source.icu-project.org/repos/icu/icuhtml/trunk/design/collation/ICU_collation_design.htm">
+ * "ICU Collation Design Document"</a> for more information.
+ * <p> 
+ * The algorithm implemented is a modified form of the Boyer Moore's search.
+ * For more information  see 
+ * <a href="http://icu-project.org/docs/papers/efficient_text_searching_in_java.html">
+ * "Efficient Text Searching in Java"</a>, published in <i>Java Report</i> 
+ * in February, 1999, for further information on the algorithm.
+ * <p>
+ * There are 2 match options for selection:<br>
+ * Let S' be the sub-string of a text string S between the offsets start and 
+ * end <start, end>.
+ * <br>
+ * A pattern string P matches a text string S at the offsets <start, end> 
+ * if
+ * <pre> 
+ * option 1. Some canonical equivalent of P matches some canonical equivalent 
+ *           of S'
+ * option 2. P matches S' and if P starts or ends with a combining mark, 
+ *           there exists no non-ignorable combining mark before or after S' 
+ *           in S respectively. 
+ * </pre>
+ * Option 2. will be the default.
+ * <p>
+ * This search has APIs similar to that of other text iteration mechanisms 
+ * such as the break iterators in <tt>ubrk.h</tt>. Using these 
+ * APIs, it is easy to scan through text looking for all occurances of 
+ * a given pattern. This search iterator allows changing of direction by 
+ * calling a <tt>reset</tt> followed by a <tt>next</tt> or <tt>previous</tt>. 
+ * Though a direction change can occur without calling <tt>reset</tt> first,  
+ * this operation comes with some speed penalty.
+ * Generally, match results in the forward direction will match the result 
+ * matches in the backwards direction in the reverse order
+ * <p>
+ * <tt>usearch.h</tt> provides APIs to specify the starting position 
+ * within the text string to be searched, e.g. <tt>usearch_setOffset</tt>,
+ * <tt>usearch_preceding</tt> and <tt>usearch_following</tt>. Since the 
+ * starting position will be set as it is specified, please take note that 
+ * there are some dangerous positions which the search may render incorrect 
+ * results:
+ * <ul>
+ * <li> The midst of a substring that requires normalization.
+ * <li> If the following match is to be found, the position should not be the
+ *      second character which requires to be swapped with the preceding 
+ *      character. Vice versa, if the preceding match is to be found, 
+ *      position to search from should not be the first character which 
+ *      requires to be swapped with the next character. E.g certain Thai and
+ *      Lao characters require swapping.
+ * <li> If a following pattern match is to be found, any position within a 
+ *      contracting sequence except the first will fail. Vice versa if a 
+ *      preceding pattern match is to be found, a invalid starting point 
+ *      would be any character within a contracting sequence except the last.
+ * </ul>
+ * <p>
+ * A breakiterator can be used if only matches at logical breaks are desired.
+ * Using a breakiterator will only give you results that exactly matches the
+ * boundaries given by the breakiterator. For instance the pattern "e" will
+ * not be found in the string "\u00e9" if a character break iterator is used.
+ * <p>
+ * Options are provided to handle overlapping matches. 
+ * E.g. In English, overlapping matches produces the result 0 and 2 
+ * for the pattern "abab" in the text "ababab", where else mutually 
+ * exclusive matches only produce the result of 0.
+ * <p>
+ * Though collator attributes will be taken into consideration while 
+ * performing matches, there are no APIs here for setting and getting the 
+ * attributes. These attributes can be set by getting the collator
+ * from <tt>usearch_getCollator</tt> and using the APIs in <tt>ucol.h</tt>.
+ * Lastly to update String Search to the new collator attributes, 
+ * usearch_reset() has to be called.
+ * <p> 
+ * Restriction: <br>
+ * Currently there are no composite characters that consists of a
+ * character with combining class > 0 before a character with combining 
+ * class == 0. However, if such a character exists in the future, the 
+ * search mechanism does not guarantee the results for option 1.
+ * 
+ * <p>
+ * Example of use:<br>
+ * <pre><code>
+ * char *tgtstr = "The quick brown fox jumped over the lazy fox";
+ * char *patstr = "fox";
+ * UChar target[64];
+ * UChar pattern[16];
+ * UErrorCode status = U_ZERO_ERROR;
+ * u_uastrcpy(target, tgtstr);
+ * u_uastrcpy(pattern, patstr);
+ *
+ * UStringSearch *search = usearch_open(pattern, -1, target, -1, "en_US", 
+ *                                  NULL, &status);
+ * if (U_SUCCESS(status)) {
+ *     for (int pos = usearch_first(search, &status); 
+ *          pos != USEARCH_DONE; 
+ *          pos = usearch_next(search, &status))
+ *     {
+ *         printf("Found match at %d pos, length is %d\n", pos, 
+ *                                        usearch_getMatchLength(search));
+ *     }
+ * }
+ *
+ * usearch_close(search);
+ * </code></pre>
+ * @stable ICU 2.4
+ */
+
+/**
+* DONE is returned by previous() and next() after all valid matches have 
+* been returned, and by first() and last() if there are no matches at all.
+* @stable ICU 2.4
+*/
+#define USEARCH_DONE -1
+
+/**
+* Data structure for searching
+* @stable ICU 2.4
+*/
+struct UStringSearch;
+/**
+* Data structure for searching
+* @stable ICU 2.4
+*/
+typedef struct UStringSearch UStringSearch;
+
+/**
+* @stable ICU 2.4
+*/
+typedef enum {
+    /** Option for overlapping matches */
+    USEARCH_OVERLAP,
+    /** 
+    Option for canonical matches. option 1 in header documentation.
+    The default value will be USEARCH_OFF
+    */
+    USEARCH_CANONICAL_MATCH,
+    USEARCH_ATTRIBUTE_COUNT
+} USearchAttribute;
+
+/**
+* @stable ICU 2.4
+*/
+typedef enum {
+    /** default value for any USearchAttribute */
+    USEARCH_DEFAULT = -1,
+    /** value for USEARCH_OVERLAP and USEARCH_CANONICAL_MATCH */
+    USEARCH_OFF, 
+    /** value for USEARCH_OVERLAP and USEARCH_CANONICAL_MATCH */
+    USEARCH_ON,
+    USEARCH_ATTRIBUTE_VALUE_COUNT
+} USearchAttributeValue;
+
+/* open and close ------------------------------------------------------ */
+
+/**
+* Creating a search iterator data struct using the argument locale language
+* rule set. A collator will be created in the process, which will be owned by
+* this search and will be deleted in <tt>usearch_close</tt>.
+* @param pattern for matching
+* @param patternlength length of the pattern, -1 for null-termination
+* @param text text string
+* @param textlength length of the text string, -1 for null-termination
+* @param locale name of locale for the rules to be used
+* @param breakiter A BreakIterator that will be used to restrict the points
+*                  at which matches are detected. If a match is found, but 
+*                  the match's start or end index is not a boundary as 
+*                  determined by the <tt>BreakIterator</tt>, the match will 
+*                  be rejected and another will be searched for. 
+*                  If this parameter is <tt>NULL</tt>, no break detection is 
+*                  attempted.
+* @param status for errors if it occurs. If pattern or text is NULL, or if
+*               patternlength or textlength is 0 then an 
+*               U_ILLEGAL_ARGUMENT_ERROR is returned.
+* @return search iterator data structure, or NULL if there is an error.
+* @stable ICU 2.4
+*/
+U_STABLE UStringSearch * U_EXPORT2 usearch_open(const UChar          *pattern, 
+                                              int32_t         patternlength, 
+                                        const UChar          *text, 
+                                              int32_t         textlength,
+                                        const char           *locale,
+                                              UBreakIterator *breakiter,
+                                              UErrorCode     *status);
+
+/**
+* Creating a search iterator data struct using the argument collator language
+* rule set. Note, user retains the ownership of this collator, thus the 
+* responsibility of deletion lies with the user.
+* NOTE: string search cannot be instantiated from a collator that has 
+* collate digits as numbers (CODAN) turned on.
+* @param pattern for matching
+* @param patternlength length of the pattern, -1 for null-termination
+* @param text text string
+* @param textlength length of the text string, -1 for null-termination
+* @param collator used for the language rules
+* @param breakiter A BreakIterator that will be used to restrict the points
+*                  at which matches are detected. If a match is found, but 
+*                  the match's start or end index is not a boundary as 
+*                  determined by the <tt>BreakIterator</tt>, the match will 
+*                  be rejected and another will be searched for. 
+*                  If this parameter is <tt>NULL</tt>, no break detection is 
+*                  attempted.
+* @param status for errors if it occurs. If collator, pattern or text is NULL, 
+*               or if patternlength or textlength is 0 then an 
+*               U_ILLEGAL_ARGUMENT_ERROR is returned.
+* @return search iterator data structure, or NULL if there is an error.
+* @stable ICU 2.4
+*/
+U_STABLE UStringSearch * U_EXPORT2 usearch_openFromCollator(
+                                         const UChar *pattern, 
+                                               int32_t         patternlength,
+                                         const UChar          *text, 
+                                               int32_t         textlength,
+                                         const UCollator      *collator,
+                                               UBreakIterator *breakiter,
+                                               UErrorCode     *status);
+
+/**
+* Destroying and cleaning up the search iterator data struct.
+* If a collator is created in <tt>usearch_open</tt>, it will be destroyed here.
+* @param searchiter data struct to clean up
+* @stable ICU 2.4
+*/
+U_STABLE void U_EXPORT2 usearch_close(UStringSearch *searchiter);
+
+/* get and set methods -------------------------------------------------- */
+
+/**
+* Sets the current position in the text string which the next search will 
+* start from. Clears previous states. 
+* This method takes the argument index and sets the position in the text 
+* string accordingly without checking if the index is pointing to a 
+* valid starting point to begin searching. 
+* Search positions that may render incorrect results are highlighted in the
+* header comments
+* @param strsrch search iterator data struct
+* @param position position to start next search from. If position is less
+*          than or greater than the text range for searching, 
+*          an U_INDEX_OUTOFBOUNDS_ERROR will be returned
+* @param status error status if any.
+* @stable ICU 2.4
+*/
+U_STABLE void U_EXPORT2 usearch_setOffset(UStringSearch *strsrch, 
+                                        int32_t    position,
+                                        UErrorCode    *status);
+
+/**
+* Return the current index in the string text being searched.
+* If the iteration has gone past the end of the text (or past the beginning 
+* for a backwards search), <tt>USEARCH_DONE</tt> is returned.
+* @param strsrch search iterator data struct
+* @see #USEARCH_DONE
+* @stable ICU 2.4
+*/
+U_STABLE int32_t U_EXPORT2 usearch_getOffset(const UStringSearch *strsrch);
+    
+/**
+* Sets the text searching attributes located in the enum USearchAttribute
+* with values from the enum USearchAttributeValue.
+* <tt>USEARCH_DEFAULT</tt> can be used for all attributes for resetting.
+* @param strsrch search iterator data struct
+* @param attribute text attribute to be set
+* @param value text attribute value
+* @param status for errors if it occurs
+* @see #usearch_getAttribute
+* @stable ICU 2.4
+*/
+U_STABLE void U_EXPORT2 usearch_setAttribute(UStringSearch         *strsrch, 
+                                           USearchAttribute       attribute,
+                                           USearchAttributeValue  value,
+                                           UErrorCode            *status);
+
+/**    
+* Gets the text searching attributes.
+* @param strsrch search iterator data struct
+* @param attribute text attribute to be retrieve
+* @return text attribute value
+* @see #usearch_setAttribute
+* @stable ICU 2.4
+*/
+U_STABLE USearchAttributeValue U_EXPORT2 usearch_getAttribute(
+                                         const UStringSearch    *strsrch,
+                                               USearchAttribute  attribute);
+
+/**
+* Returns the index to the match in the text string that was searched.
+* This call returns a valid result only after a successful call to 
+* <tt>usearch_first</tt>, <tt>usearch_next</tt>, <tt>usearch_previous</tt>, 
+* or <tt>usearch_last</tt>.
+* Just after construction, or after a searching method returns 
+* <tt>USEARCH_DONE</tt>, this method will return <tt>USEARCH_DONE</tt>.
+* <p>
+* Use <tt>usearch_getMatchedLength</tt> to get the matched string length.
+* @param strsrch search iterator data struct
+* @return index to a substring within the text string that is being 
+*         searched.
+* @see #usearch_first
+* @see #usearch_next
+* @see #usearch_previous
+* @see #usearch_last
+* @see #USEARCH_DONE
+* @stable ICU 2.4
+*/
+U_STABLE int32_t U_EXPORT2 usearch_getMatchedStart(
+                                               const UStringSearch *strsrch);
+    
+/**
+* Returns the length of text in the string which matches the search pattern. 
+* This call returns a valid result only after a successful call to 
+* <tt>usearch_first</tt>, <tt>usearch_next</tt>, <tt>usearch_previous</tt>, 
+* or <tt>usearch_last</tt>.
+* Just after construction, or after a searching method returns 
+* <tt>USEARCH_DONE</tt>, this method will return 0.
+* @param strsrch search iterator data struct
+* @return The length of the match in the string text, or 0 if there is no 
+*         match currently.
+* @see #usearch_first
+* @see #usearch_next
+* @see #usearch_previous
+* @see #usearch_last
+* @see #USEARCH_DONE
+* @stable ICU 2.4
+*/
+U_STABLE int32_t U_EXPORT2 usearch_getMatchedLength(
+                                               const UStringSearch *strsrch);
+
+/**
+* Returns the text that was matched by the most recent call to 
+* <tt>usearch_first</tt>, <tt>usearch_next</tt>, <tt>usearch_previous</tt>, 
+* or <tt>usearch_last</tt>.
+* If the iterator is not pointing at a valid match (e.g. just after 
+* construction or after <tt>USEARCH_DONE</tt> has been returned, returns
+* an empty string. If result is not large enough to store the matched text,
+* result will be filled with the partial text and an U_BUFFER_OVERFLOW_ERROR 
+* will be returned in status. result will be null-terminated whenever 
+* possible. If the buffer fits the matched text exactly, a null-termination 
+* is not possible, then a U_STRING_NOT_TERMINATED_ERROR set in status.
+* Pre-flighting can be either done with length = 0 or the API 
+* <tt>usearch_getMatchLength</tt>.
+* @param strsrch search iterator data struct
+* @param result UChar buffer to store the matched string
+* @param resultCapacity length of the result buffer
+* @param status error returned if result is not large enough
+* @return exact length of the matched text, not counting the null-termination
+* @see #usearch_first
+* @see #usearch_next
+* @see #usearch_previous
+* @see #usearch_last
+* @see #USEARCH_DONE
+* @stable ICU 2.4
+*/
+U_STABLE int32_t U_EXPORT2 usearch_getMatchedText(const UStringSearch *strsrch, 
+                                            UChar         *result, 
+                                            int32_t        resultCapacity, 
+                                            UErrorCode    *status);
+
+#if !UCONFIG_NO_BREAK_ITERATION
+
+/**
+* Set the BreakIterator that will be used to restrict the points at which 
+* matches are detected.
+* @param strsrch search iterator data struct
+* @param breakiter A BreakIterator that will be used to restrict the points
+*                  at which matches are detected. If a match is found, but 
+*                  the match's start or end index is not a boundary as 
+*                  determined by the <tt>BreakIterator</tt>, the match will 
+*                  be rejected and another will be searched for. 
+*                  If this parameter is <tt>NULL</tt>, no break detection is 
+*                  attempted.
+* @param status for errors if it occurs
+* @see #usearch_getBreakIterator
+* @stable ICU 2.4
+*/
+U_STABLE void U_EXPORT2 usearch_setBreakIterator(UStringSearch  *strsrch, 
+                                               UBreakIterator *breakiter,
+                                               UErrorCode     *status);
+
+/**
+* Returns the BreakIterator that is used to restrict the points at which 
+* matches are detected. This will be the same object that was passed to the 
+* constructor or to <tt>usearch_setBreakIterator</tt>. Note that 
+* <tt>NULL</tt> 
+* is a legal value; it means that break detection should not be attempted.
+* @param strsrch search iterator data struct
+* @return break iterator used
+* @see #usearch_setBreakIterator
+* @stable ICU 2.4
+*/
+U_STABLE const UBreakIterator * U_EXPORT2 usearch_getBreakIterator(
+                                              const UStringSearch *strsrch);
+    
+#endif
+    
+/**
+* Set the string text to be searched. Text iteration will hence begin at the 
+* start of the text string. This method is useful if you want to re-use an 
+* iterator to search for the same pattern within a different body of text.
+* @param strsrch search iterator data struct
+* @param text new string to look for match
+* @param textlength length of the new string, -1 for null-termination
+* @param status for errors if it occurs. If text is NULL, or textlength is 0 
+*               then an U_ILLEGAL_ARGUMENT_ERROR is returned with no change
+*               done to strsrch.
+* @see #usearch_getText
+* @stable ICU 2.4
+*/
+U_STABLE void U_EXPORT2 usearch_setText(      UStringSearch *strsrch, 
+                                      const UChar         *text,
+                                            int32_t        textlength,
+                                            UErrorCode    *status);
+
+/**
+* Return the string text to be searched.
+* @param strsrch search iterator data struct
+* @param length returned string text length
+* @return string text 
+* @see #usearch_setText
+* @stable ICU 2.4
+*/
+U_STABLE const UChar * U_EXPORT2 usearch_getText(const UStringSearch *strsrch, 
+                                               int32_t       *length);
+
+/**
+* Gets the collator used for the language rules. 
+* <p>
+* Deleting the returned <tt>UCollator</tt> before calling 
+* <tt>usearch_close</tt> would cause the string search to fail.
+* <tt>usearch_close</tt> will delete the collator if this search owns it.
+* @param strsrch search iterator data struct
+* @return collator
+* @stable ICU 2.4
+*/
+U_STABLE UCollator * U_EXPORT2 usearch_getCollator(
+                                               const UStringSearch *strsrch);
+
+/**
+* Sets the collator used for the language rules. User retains the ownership 
+* of this collator, thus the responsibility of deletion lies with the user.
+* This method causes internal data such as Boyer-Moore shift tables to  
+* be recalculated, but the iterator's position is unchanged.
+* @param strsrch search iterator data struct
+* @param collator to be used
+* @param status for errors if it occurs
+* @stable ICU 2.4
+*/
+U_STABLE void U_EXPORT2 usearch_setCollator(      UStringSearch *strsrch, 
+                                          const UCollator     *collator,
+                                                UErrorCode    *status);
+
+/**
+* Sets the pattern used for matching.
+* Internal data like the Boyer Moore table will be recalculated, but the 
+* iterator's position is unchanged.
+* @param strsrch search iterator data struct
+* @param pattern string
+* @param patternlength pattern length, -1 for null-terminated string
+* @param status for errors if it occurs. If text is NULL, or textlength is 0 
+*               then an U_ILLEGAL_ARGUMENT_ERROR is returned with no change
+*               done to strsrch.
+* @stable ICU 2.4
+*/
+U_STABLE void U_EXPORT2 usearch_setPattern(      UStringSearch *strsrch, 
+                                         const UChar         *pattern,
+                                               int32_t        patternlength,
+                                               UErrorCode    *status);
+
+/**
+* Gets the search pattern
+* @param strsrch search iterator data struct
+* @param length return length of the pattern, -1 indicates that the pattern 
+*               is null-terminated
+* @return pattern string
+* @stable ICU 2.4
+*/
+U_STABLE const UChar * U_EXPORT2 usearch_getPattern(
+                                               const UStringSearch *strsrch, 
+                                                     int32_t       *length);
+
+/* methods ------------------------------------------------------------- */
+
+/**
+* Returns the first index at which the string text matches the search 
+* pattern.  
+* The iterator is adjusted so that its current index (as returned by 
+* <tt>usearch_getOffset</tt>) is the match position if one was found.
+* If a match is not found, <tt>USEARCH_DONE</tt> will be returned and
+* the iterator will be adjusted to the index <tt>USEARCH_DONE</tt>.
+* @param strsrch search iterator data struct
+* @param status for errors if it occurs
+* @return The character index of the first match, or 
+* <tt>USEARCH_DONE</tt> if there are no matches.
+* @see #usearch_getOffset
+* @see #USEARCH_DONE
+* @stable ICU 2.4
+*/
+U_STABLE int32_t U_EXPORT2 usearch_first(UStringSearch *strsrch, 
+                                           UErrorCode    *status);
+
+/**
+* Returns the first index greater than <tt>position</tt> at which the string 
+* text 
+* matches the search pattern. The iterator is adjusted so that its current 
+* index (as returned by <tt>usearch_getOffset</tt>) is the match position if 
+* one was found.
+* If a match is not found, <tt>USEARCH_DONE</tt> will be returned and
+* the iterator will be adjusted to the index <tt>USEARCH_DONE</tt>
+* <p>
+* Search positions that may render incorrect results are highlighted in the
+* header comments. If position is less than or greater than the text range 
+* for searching, an U_INDEX_OUTOFBOUNDS_ERROR will be returned
+* @param strsrch search iterator data struct
+* @param position to start the search at
+* @param status for errors if it occurs
+* @return The character index of the first match following <tt>pos</tt>,
+*         or <tt>USEARCH_DONE</tt> if there are no matches.
+* @see #usearch_getOffset
+* @see #USEARCH_DONE
+* @stable ICU 2.4
+*/
+U_STABLE int32_t U_EXPORT2 usearch_following(UStringSearch *strsrch, 
+                                               int32_t    position, 
+                                               UErrorCode    *status);
+    
+/**
+* Returns the last index in the target text at which it matches the search 
+* pattern. The iterator is adjusted so that its current 
+* index (as returned by <tt>usearch_getOffset</tt>) is the match position if 
+* one was found.
+* If a match is not found, <tt>USEARCH_DONE</tt> will be returned and
+* the iterator will be adjusted to the index <tt>USEARCH_DONE</tt>.
+* @param strsrch search iterator data struct
+* @param status for errors if it occurs
+* @return The index of the first match, or <tt>USEARCH_DONE</tt> if there 
+*         are no matches.
+* @see #usearch_getOffset
+* @see #USEARCH_DONE
+* @stable ICU 2.4
+*/
+U_STABLE int32_t U_EXPORT2 usearch_last(UStringSearch *strsrch, 
+                                          UErrorCode    *status);
+
+/**
+* Returns the first index less than <tt>position</tt> at which the string text 
+* matches the search pattern. The iterator is adjusted so that its current 
+* index (as returned by <tt>usearch_getOffset</tt>) is the match position if 
+* one was found.
+* If a match is not found, <tt>USEARCH_DONE</tt> will be returned and
+* the iterator will be adjusted to the index <tt>USEARCH_DONE</tt>
+* <p>
+* Search positions that may render incorrect results are highlighted in the
+* header comments. If position is less than or greater than the text range 
+* for searching, an U_INDEX_OUTOFBOUNDS_ERROR will be returned
+* @param strsrch search iterator data struct
+* @param position index position the search is to begin at
+* @param status for errors if it occurs
+* @return The character index of the first match preceding <tt>pos</tt>,
+*         or <tt>USEARCH_DONE</tt> if there are no matches.
+* @see #usearch_getOffset
+* @see #USEARCH_DONE
+* @stable ICU 2.4
+*/
+U_STABLE int32_t U_EXPORT2 usearch_preceding(UStringSearch *strsrch, 
+                                               int32_t    position, 
+                                               UErrorCode    *status);
+    
+/**
+* Returns the index of the next point at which the string text matches the
+* search pattern, starting from the current position.
+* The iterator is adjusted so that its current 
+* index (as returned by <tt>usearch_getOffset</tt>) is the match position if 
+* one was found.
+* If a match is not found, <tt>USEARCH_DONE</tt> will be returned and
+* the iterator will be adjusted to the index <tt>USEARCH_DONE</tt>
+* @param strsrch search iterator data struct
+* @param status for errors if it occurs
+* @return The index of the next match after the current position, or 
+*         <tt>USEARCH_DONE</tt> if there are no more matches.
+* @see #usearch_first
+* @see #usearch_getOffset
+* @see #USEARCH_DONE
+* @stable ICU 2.4
+*/
+U_STABLE int32_t U_EXPORT2 usearch_next(UStringSearch *strsrch, 
+                                          UErrorCode    *status);
+
+/**
+* Returns the index of the previous point at which the string text matches
+* the search pattern, starting at the current position.
+* The iterator is adjusted so that its current 
+* index (as returned by <tt>usearch_getOffset</tt>) is the match position if 
+* one was found.
+* If a match is not found, <tt>USEARCH_DONE</tt> will be returned and
+* the iterator will be adjusted to the index <tt>USEARCH_DONE</tt>
+* @param strsrch search iterator data struct
+* @param status for errors if it occurs
+* @return The index of the previous match before the current position,
+*         or <tt>USEARCH_DONE</tt> if there are no more matches.
+* @see #usearch_last
+* @see #usearch_getOffset
+* @see #USEARCH_DONE
+* @stable ICU 2.4
+*/
+U_STABLE int32_t U_EXPORT2 usearch_previous(UStringSearch *strsrch, 
+                                              UErrorCode    *status);
+    
+/** 
+* Reset the iteration.
+* Search will begin at the start of the text string if a forward iteration 
+* is initiated before a backwards iteration. Otherwise if a backwards 
+* iteration is initiated before a forwards iteration, the search will begin
+* at the end of the text string.
+* @param strsrch search iterator data struct
+* @see #usearch_first
+* @stable ICU 2.4
+*/
+U_STABLE void U_EXPORT2 usearch_reset(UStringSearch *strsrch);
+
+/**
+  *  Simple forward search for the pattern, starting at a specified index,
+  *     and using using a default set search options.
+  *
+  *  This is an experimental function, and is not an official part of the
+  *      ICU API.
+  *
+  *  The collator options, such as UCOL_STRENGTH and UCOL_NORMALIZTION, are honored.
+  *
+  *  The UStringSearch options USEARCH_CANONICAL_MATCH, USEARCH_OVERLAP and
+  *  any Break Iterator are ignored.
+  *
+  *  Matches obey the following constraints:
+  *
+  *      Characters at the start or end positions of a match that are ignorable
+  *      for collation are not included as part of the match, unless they
+  *      are part of a combining sequence, as described below.
+  *
+  *      A match will not include a partial combining sequence.  Combining
+  *      character sequences  are considered to be  inseperable units,
+  *      and either match the pattern completely, or are considered to not match
+  *      at all.  Thus, for example, an A followed a combining accent mark will 
+  *      not be found when searching for a plain (unaccented) A.   (unless
+  *      the collation strength has been set to ignore all accents).
+  *
+  *      When beginning a search, the initial starting position, startIdx,
+  *      is assumed to be an acceptable match boundary with respect to
+  *      combining characters.  A combining sequence that spans across the
+  *      starting point will not supress a match beginning at startIdx.
+  *
+  *      Characters that expand to multiple collation elements
+  *      (German sharp-S becoming 'ss', or the composed forms of accented
+  *      characters, for example) also must match completely.
+  *      Searching for a single 's' in a string containing only a sharp-s will 
+  *      find no match.
+  *
+  *
+  *  @param strsrch    the UStringSearch struct, which references both
+  *                    the text to be searched  and the pattern being sought.
+  *  @param startIdx   The index into the text to begin the search.
+  *  @param matchStart An out parameter, the starting index of the matched text.
+  *                    This parameter may be NULL.
+  *                    A value of -1 will be returned if no match was found.
+  *  @param matchLimit Out parameter, the index of the first position following the matched text.
+  *                    The matchLimit will be at a suitable position for beginning a subsequent search
+  *                    in the input text.
+  *                    This parameter may be NULL.
+  *                    A value of -1 will be returned if no match was found.
+  *          
+  *  @param status     Report any errors.  Note that no match found is not an error.
+  *  @return           TRUE if a match was found, FALSE otherwise.
+  *
+  *  @internal
+  */
+U_INTERNAL UBool U_EXPORT2 usearch_search(UStringSearch *strsrch,
+                                          int32_t        startIdx,
+                                          int32_t        *matchStart,
+                                          int32_t        *matchLimit,
+                                          UErrorCode     *status);
+
+/**
+  *  Simple backwards search for the pattern, starting at a specified index,
+  *     and using using a default set search options.
+  *
+  *  This is an experimental function, and is not an official part of the
+  *      ICU API.
+  *
+  *  The collator options, such as UCOL_STRENGTH and UCOL_NORMALIZTION, are honored.
+  *
+  *  The UStringSearch options USEARCH_CANONICAL_MATCH, USEARCH_OVERLAP and
+  *  any Break Iterator are ignored.
+  *
+  *  Matches obey the following constraints:
+  *
+  *      Characters at the start or end positions of a match that are ignorable
+  *      for collation are not included as part of the match, unless they
+  *      are part of a combining sequence, as described below.
+  *
+  *      A match will not include a partial combining sequence.  Combining
+  *      character sequences  are considered to be  inseperable units,
+  *      and either match the pattern completely, or are considered to not match
+  *      at all.  Thus, for example, an A followed a combining accent mark will 
+  *      not be found when searching for a plain (unaccented) A.   (unless
+  *      the collation strength has been set to ignore all accents).
+  *
+  *      When beginning a search, the initial starting position, startIdx,
+  *      is assumed to be an acceptable match boundary with respect to
+  *      combining characters.  A combining sequence that spans across the
+  *      starting point will not supress a match beginning at startIdx.
+  *
+  *      Characters that expand to multiple collation elements
+  *      (German sharp-S becoming 'ss', or the composed forms of accented
+  *      characters, for example) also must match completely.
+  *      Searching for a single 's' in a string containing only a sharp-s will 
+  *      find no match.
+  *
+  *
+  *  @param strsrch    the UStringSearch struct, which references both
+  *                    the text to be searched  and the pattern being sought.
+  *  @param startIdx   The index into the text to begin the search.
+  *  @param matchStart An out parameter, the starting index of the matched text.
+  *                    This parameter may be NULL.
+  *                    A value of -1 will be returned if no match was found.
+  *  @param matchLimit Out parameter, the index of the first position following the matched text.
+  *                    The matchLimit will be at a suitable position for beginning a subsequent search
+  *                    in the input text.
+  *                    This parameter may be NULL.
+  *                    A value of -1 will be returned if no match was found.
+  *          
+  *  @param status     Report any errors.  Note that no match found is not an error.
+  *  @return           TRUE if a match was found, FALSE otherwise.
+  *
+  *  @internal
+  */
+U_INTERNAL UBool U_EXPORT2 usearch_searchBackwards(UStringSearch *strsrch,
+                                                   int32_t        startIdx,
+                                                   int32_t        *matchStart,
+                                                   int32_t        *matchLimit,
+                                                   UErrorCode     *status);
+
+#endif /* #if !UCONFIG_NO_COLLATION  && !UCONFIG_NO_BREAK_ITERATION */
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/uset.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/uset.h b/src/apps/couch_collate/platform/osx/icu/unicode/uset.h
new file mode 100644
index 0000000..2bbfd7a
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/uset.h
@@ -0,0 +1,1052 @@
+/*
+*******************************************************************************
+*
+*   Copyright (C) 2002-2008, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+*
+*******************************************************************************
+*   file name:  uset.h
+*   encoding:   US-ASCII
+*   tab size:   8 (not used)
+*   indentation:4
+*
+*   created on: 2002mar07
+*   created by: Markus W. Scherer
+*
+*   C version of UnicodeSet.
+*/
+
+
+/**
+ * \file
+ * \brief C API: Unicode Set
+ *
+ * <p>This is a C wrapper around the C++ UnicodeSet class.</p>
+ */
+
+#ifndef __USET_H__
+#define __USET_H__
+
+#include "unicode/utypes.h"
+#include "unicode/uchar.h"
+
+#ifndef UCNV_H
+struct USet;
+/**
+ * A UnicodeSet.  Use the uset_* API to manipulate.  Create with
+ * uset_open*, and destroy with uset_close.
+ * @stable ICU 2.4
+ */
+typedef struct USet USet;
+#endif
+
+/**
+ * Bitmask values to be passed to uset_openPatternOptions() or
+ * uset_applyPattern() taking an option parameter.
+ * @stable ICU 2.4
+ */
+enum {
+    /**
+     * Ignore white space within patterns unless quoted or escaped.
+     * @stable ICU 2.4
+     */
+    USET_IGNORE_SPACE = 1,  
+
+    /**
+     * Enable case insensitive matching.  E.g., "[ab]" with this flag
+     * will match 'a', 'A', 'b', and 'B'.  "[^ab]" with this flag will
+     * match all except 'a', 'A', 'b', and 'B'. This performs a full
+     * closure over case mappings, e.g. U+017F for s.
+     *
+     * The resulting set is a superset of the input for the code points but
+     * not for the strings.
+     * It performs a case mapping closure of the code points and adds
+     * full case folding strings for the code points, and reduces strings of
+     * the original set to their full case folding equivalents.
+     *
+     * This is designed for case-insensitive matches, for example
+     * in regular expressions. The full code point case closure allows checking of
+     * an input character directly against the closure set.
+     * Strings are matched by comparing the case-folded form from the closure
+     * set with an incremental case folding of the string in question.
+     *
+     * The closure set will also contain single code points if the original
+     * set contained case-equivalent strings (like U+00DF for "ss" or "Ss" etc.).
+     * This is not necessary (that is, redundant) for the above matching method
+     * but results in the same closure sets regardless of whether the original
+     * set contained the code point or a string.
+     *
+     * @stable ICU 2.4
+     */
+    USET_CASE_INSENSITIVE = 2,  
+
+    /**
+     * Enable case insensitive matching.  E.g., "[ab]" with this flag
+     * will match 'a', 'A', 'b', and 'B'.  "[^ab]" with this flag will
+     * match all except 'a', 'A', 'b', and 'B'. This adds the lower-,
+     * title-, and uppercase mappings as well as the case folding
+     * of each existing element in the set.
+     * @stable ICU 3.2
+     */
+    USET_ADD_CASE_MAPPINGS = 4,
+    
+    /**
+     * Enough for any single-code point set
+     * @internal
+     */
+    USET_SERIALIZED_STATIC_ARRAY_CAPACITY=8
+};
+
+/**
+ * Argument values for whether span() and similar functions continue while
+ * the current character is contained vs. not contained in the set.
+ *
+ * The functionality is straightforward for sets with only single code points,
+ * without strings (which is the common case):
+ * - USET_SPAN_CONTAINED and USET_SPAN_SIMPLE
+ *   work the same.
+ * - span() and spanBack() partition any string the same way when
+ *   alternating between span(USET_SPAN_NOT_CONTAINED) and
+ *   span(either "contained" condition).
+ * - Using a complemented (inverted) set and the opposite span conditions
+ *   yields the same results.
+ *
+ * When a set contains multi-code point strings, then these statements may not
+ * be true, depending on the strings in the set (for example, whether they
+ * overlap with each other) and the string that is processed.
+ * For a set with strings:
+ * - The complement of the set contains the opposite set of code points,
+ *   but the same set of strings.
+ *   Therefore, complementing both the set and the span conditions
+ *   may yield different results.
+ * - When starting spans at different positions in a string
+ *   (span(s, ...) vs. span(s+1, ...)) the ends of the spans may be different
+ *   because a set string may start before the later position.
+ * - span(USET_SPAN_SIMPLE) may be shorter than
+ *   span(USET_SPAN_CONTAINED) because it will not recursively try
+ *   all possible paths.
+ *   For example, with a set which contains the three strings "xy", "xya" and "ax",
+ *   span("xyax", USET_SPAN_CONTAINED) will return 4 but
+ *   span("xyax", USET_SPAN_SIMPLE) will return 3.
+ *   span(USET_SPAN_SIMPLE) will never be longer than
+ *   span(USET_SPAN_CONTAINED).
+ * - With either "contained" condition, span() and spanBack() may partition
+ *   a string in different ways.
+ *   For example, with a set which contains the two strings "ab" and "ba",
+ *   and when processing the string "aba",
+ *   span() will yield contained/not-contained boundaries of { 0, 2, 3 }
+ *   while spanBack() will yield boundaries of { 0, 1, 3 }.
+ *
+ * Note: If it is important to get the same boundaries whether iterating forward
+ * or backward through a string, then either only span() should be used and
+ * the boundaries cached for backward operation, or an ICU BreakIterator
+ * could be used.
+ *
+ * Note: Unpaired surrogates are treated like surrogate code points.
+ * Similarly, set strings match only on code point boundaries,
+ * never in the middle of a surrogate pair.
+ * Illegal UTF-8 sequences are treated like U+FFFD.
+ * When processing UTF-8 strings, malformed set strings
+ * (strings with unpaired surrogates which cannot be converted to UTF-8)
+ * are ignored.
+ *
+ * @stable ICU 4.0
+ */
+typedef enum USetSpanCondition {
+    /**
+     * Continue a span() while there is no set element at the current position.
+     * Stops before the first set element (character or string).
+     * (For code points only, this is like while contains(current)==FALSE).
+     *
+     * When span() returns, the substring between where it started and the position
+     * it returned consists only of characters that are not in the set,
+     * and none of its strings overlap with the span.
+     *
+     * @stable ICU 4.0
+     */
+    USET_SPAN_NOT_CONTAINED = 0,
+    /**
+     * Continue a span() while there is a set element at the current position.
+     * (For characters only, this is like while contains(current)==TRUE).
+     *
+     * When span() returns, the substring between where it started and the position
+     * it returned consists only of set elements (characters or strings) that are in the set.
+     *
+     * If a set contains strings, then the span will be the longest substring
+     * matching any of the possible concatenations of set elements (characters or strings).
+     * (There must be a single, non-overlapping concatenation of characters or strings.)
+     * This is equivalent to a POSIX regular expression for (OR of each set element)*.
+     *
+     * @stable ICU 4.0
+     */
+    USET_SPAN_CONTAINED = 1,
+    /**
+     * Continue a span() while there is a set element at the current position.
+     * (For characters only, this is like while contains(current)==TRUE).
+     *
+     * When span() returns, the substring between where it started and the position
+     * it returned consists only of set elements (characters or strings) that are in the set.
+     *
+     * If a set only contains single characters, then this is the same
+     * as USET_SPAN_CONTAINED.
+     *
+     * If a set contains strings, then the span will be the longest substring
+     * with a match at each position with the longest single set element (character or string).
+     *
+     * Use this span condition together with other longest-match algorithms,
+     * such as ICU converters (ucnv_getUnicodeSet()).
+     *
+     * @stable ICU 4.0
+     */
+    USET_SPAN_SIMPLE = 2,
+    /**
+     * One more than the last span condition.
+     * @stable ICU 4.0
+     */
+    USET_SPAN_CONDITION_COUNT
+} USetSpanCondition;
+
+/**
+ * A serialized form of a Unicode set.  Limited manipulations are
+ * possible directly on a serialized set.  See below.
+ * @stable ICU 2.4
+ */
+typedef struct USerializedSet {
+    /**
+     * The serialized Unicode Set.
+     * @stable ICU 2.4
+     */
+    const uint16_t *array;
+    /**
+     * The length of the array that contains BMP characters.
+     * @stable ICU 2.4
+     */
+    int32_t bmpLength;
+    /**
+     * The total length of the array.
+     * @stable ICU 2.4
+     */
+    int32_t length;
+    /**
+     * A small buffer for the array to reduce memory allocations.
+     * @stable ICU 2.4
+     */
+    uint16_t staticArray[USET_SERIALIZED_STATIC_ARRAY_CAPACITY];
+} USerializedSet;
+
+/*********************************************************************
+ * USet API
+ *********************************************************************/
+
+/**
+ * Creates a USet object that contains the range of characters
+ * start..end, inclusive.  If <code>start > end</code> 
+ * then an empty set is created.
+ * @param start first character of the range, inclusive
+ * @param end last character of the range, inclusive
+ * @return a newly created USet.  The caller must call uset_close() on
+ * it when done.
+ * @stable ICU 2.4
+ */
+U_STABLE USet* U_EXPORT2
+uset_open(UChar32 start, UChar32 end);
+
+/**
+ * Creates a set from the given pattern.  See the UnicodeSet class
+ * description for the syntax of the pattern language.
+ * @param pattern a string specifying what characters are in the set
+ * @param patternLength the length of the pattern, or -1 if null
+ * terminated
+ * @param ec the error code
+ * @stable ICU 2.4
+ */
+U_STABLE USet* U_EXPORT2
+uset_openPattern(const UChar* pattern, int32_t patternLength,
+                 UErrorCode* ec);
+
+/**
+ * Creates a set from the given pattern.  See the UnicodeSet class
+ * description for the syntax of the pattern language.
+ * @param pattern a string specifying what characters are in the set
+ * @param patternLength the length of the pattern, or -1 if null
+ * terminated
+ * @param options bitmask for options to apply to the pattern.
+ * Valid options are USET_IGNORE_SPACE and USET_CASE_INSENSITIVE.
+ * @param ec the error code
+ * @stable ICU 2.4
+ */
+U_STABLE USet* U_EXPORT2
+uset_openPatternOptions(const UChar* pattern, int32_t patternLength,
+                 uint32_t options,
+                 UErrorCode* ec);
+
+/**
+ * Disposes of the storage used by a USet object.  This function should
+ * be called exactly once for objects returned by uset_open().
+ * @param set the object to dispose of
+ * @stable ICU 2.4
+ */
+U_STABLE void U_EXPORT2
+uset_close(USet* set);
+
+/**
+ * Returns a copy of this object.
+ * If this set is frozen, then the clone will be frozen as well.
+ * Use uset_cloneAsThawed() for a mutable clone of a frozen set.
+ * @param set the original set
+ * @return the newly allocated copy of the set
+ * @see uset_cloneAsThawed
+ * @stable ICU 4.0
+ */
+U_DRAFT USet * U_EXPORT2
+uset_clone(const USet *set);
+
+/**
+ * Determines whether the set has been frozen (made immutable) or not.
+ * See the ICU4J Freezable interface for details.
+ * @param set the set
+ * @return TRUE/FALSE for whether the set has been frozen
+ * @see uset_freeze
+ * @see uset_cloneAsThawed
+ * @stable ICU 4.0
+ */
+U_DRAFT UBool U_EXPORT2
+uset_isFrozen(const USet *set);
+
+/**
+ * Freeze the set (make it immutable).
+ * Once frozen, it cannot be unfrozen and is therefore thread-safe
+ * until it is deleted.
+ * See the ICU4J Freezable interface for details.
+ * Freezing the set may also make some operations faster, for example
+ * uset_contains() and uset_span().
+ * A frozen set will not be modified. (It remains frozen.)
+ * @param set the set
+ * @return the same set, now frozen
+ * @see uset_isFrozen
+ * @see uset_cloneAsThawed
+ * @stable ICU 4.0
+ */
+U_DRAFT void U_EXPORT2
+uset_freeze(USet *set);
+
+/**
+ * Clone the set and make the clone mutable.
+ * See the ICU4J Freezable interface for details.
+ * @param set the set
+ * @return the mutable clone
+ * @see uset_freeze
+ * @see uset_isFrozen
+ * @see uset_clone
+ * @stable ICU 4.0
+ */
+U_DRAFT USet * U_EXPORT2
+uset_cloneAsThawed(const USet *set);
+
+/**
+ * Causes the USet object to represent the range <code>start - end</code>.
+ * If <code>start > end</code> then this USet is set to an empty range.
+ * A frozen set will not be modified.
+ * @param set the object to set to the given range
+ * @param start first character in the set, inclusive
+ * @param end last character in the set, inclusive
+ * @stable ICU 3.2
+ */
+U_STABLE void U_EXPORT2
+uset_set(USet* set,
+         UChar32 start, UChar32 end);
+
+/**
+ * Modifies the set to represent the set specified by the given
+ * pattern. See the UnicodeSet class description for the syntax of 
+ * the pattern language. See also the User Guide chapter about UnicodeSet.
+ * <em>Empties the set passed before applying the pattern.</em>
+ * A frozen set will not be modified.
+ * @param set               The set to which the pattern is to be applied. 
+ * @param pattern           A pointer to UChar string specifying what characters are in the set.
+ *                          The character at pattern[0] must be a '['.
+ * @param patternLength     The length of the UChar string. -1 if NUL terminated.
+ * @param options           A bitmask for options to apply to the pattern.
+ *                          Valid options are USET_IGNORE_SPACE and USET_CASE_INSENSITIVE.
+ * @param status            Returns an error if the pattern cannot be parsed.
+ * @return                  Upon successful parse, the value is either
+ *                          the index of the character after the closing ']' 
+ *                          of the parsed pattern.
+ *                          If the status code indicates failure, then the return value 
+ *                          is the index of the error in the source.
+ *
+ * @stable ICU 2.8
+ */
+U_STABLE int32_t U_EXPORT2 
+uset_applyPattern(USet *set,
+                  const UChar *pattern, int32_t patternLength,
+                  uint32_t options,
+                  UErrorCode *status);
+
+/**
+ * Modifies the set to contain those code points which have the given value
+ * for the given binary or enumerated property, as returned by
+ * u_getIntPropertyValue.  Prior contents of this set are lost.
+ * A frozen set will not be modified.
+ *
+ * @param set the object to contain the code points defined by the property
+ *
+ * @param prop a property in the range UCHAR_BIN_START..UCHAR_BIN_LIMIT-1
+ * or UCHAR_INT_START..UCHAR_INT_LIMIT-1
+ * or UCHAR_MASK_START..UCHAR_MASK_LIMIT-1.
+ *
+ * @param value a value in the range u_getIntPropertyMinValue(prop)..
+ * u_getIntPropertyMaxValue(prop), with one exception.  If prop is
+ * UCHAR_GENERAL_CATEGORY_MASK, then value should not be a UCharCategory, but
+ * rather a mask value produced by U_GET_GC_MASK().  This allows grouped
+ * categories such as [:L:] to be represented.
+ *
+ * @param ec error code input/output parameter
+ *
+ * @stable ICU 3.2
+ */
+U_STABLE void U_EXPORT2
+uset_applyIntPropertyValue(USet* set,
+                           UProperty prop, int32_t value, UErrorCode* ec);
+
+/**
+ * Modifies the set to contain those code points which have the
+ * given value for the given property.  Prior contents of this
+ * set are lost.
+ * A frozen set will not be modified.
+ *
+ * @param set the object to contain the code points defined by the given
+ * property and value alias
+ *
+ * @param prop a string specifying a property alias, either short or long.
+ * The name is matched loosely.  See PropertyAliases.txt for names and a
+ * description of loose matching.  If the value string is empty, then this
+ * string is interpreted as either a General_Category value alias, a Script
+ * value alias, a binary property alias, or a special ID.  Special IDs are
+ * matched loosely and correspond to the following sets:
+ *
+ * "ANY" = [\\u0000-\\U0010FFFF],
+ * "ASCII" = [\\u0000-\\u007F],
+ * "Assigned" = [:^Cn:].
+ *
+ * @param propLength the length of the prop, or -1 if NULL
+ *
+ * @param value a string specifying a value alias, either short or long.
+ * The name is matched loosely.  See PropertyValueAliases.txt for names
+ * and a description of loose matching.  In addition to aliases listed,
+ * numeric values and canonical combining classes may be expressed
+ * numerically, e.g., ("nv", "0.5") or ("ccc", "220").  The value string
+ * may also be empty.
+ *
+ * @param valueLength the length of the value, or -1 if NULL
+ *
+ * @param ec error code input/output parameter
+ *
+ * @stable ICU 3.2
+ */
+U_STABLE void U_EXPORT2
+uset_applyPropertyAlias(USet* set,
+                        const UChar *prop, int32_t propLength,
+                        const UChar *value, int32_t valueLength,
+                        UErrorCode* ec);
+
+/**
+ * Return true if the given position, in the given pattern, appears
+ * to be the start of a UnicodeSet pattern.
+ *
+ * @param pattern a string specifying the pattern
+ * @param patternLength the length of the pattern, or -1 if NULL
+ * @param pos the given position
+ * @stable ICU 3.2
+ */
+U_STABLE UBool U_EXPORT2
+uset_resemblesPattern(const UChar *pattern, int32_t patternLength,
+                      int32_t pos);
+
+/**
+ * Returns a string representation of this set.  If the result of
+ * calling this function is passed to a uset_openPattern(), it
+ * will produce another set that is equal to this one.
+ * @param set the set
+ * @param result the string to receive the rules, may be NULL
+ * @param resultCapacity the capacity of result, may be 0 if result is NULL
+ * @param escapeUnprintable if TRUE then convert unprintable
+ * character to their hex escape representations, \\uxxxx or
+ * \\Uxxxxxxxx.  Unprintable characters are those other than
+ * U+000A, U+0020..U+007E.
+ * @param ec error code.
+ * @return length of string, possibly larger than resultCapacity
+ * @stable ICU 2.4
+ */
+U_STABLE int32_t U_EXPORT2
+uset_toPattern(const USet* set,
+               UChar* result, int32_t resultCapacity,
+               UBool escapeUnprintable,
+               UErrorCode* ec);
+
+/**
+ * Adds the given character to the given USet.  After this call,
+ * uset_contains(set, c) will return TRUE.
+ * A frozen set will not be modified.
+ * @param set the object to which to add the character
+ * @param c the character to add
+ * @stable ICU 2.4
+ */
+U_STABLE void U_EXPORT2
+uset_add(USet* set, UChar32 c);
+
+/**
+ * Adds all of the elements in the specified set to this set if
+ * they're not already present.  This operation effectively
+ * modifies this set so that its value is the <i>union</i> of the two
+ * sets.  The behavior of this operation is unspecified if the specified
+ * collection is modified while the operation is in progress.
+ * A frozen set will not be modified.
+ *
+ * @param set the object to which to add the set
+ * @param additionalSet the source set whose elements are to be added to this set.
+ * @stable ICU 2.6
+ */
+U_STABLE void U_EXPORT2
+uset_addAll(USet* set, const USet *additionalSet);
+
+/**
+ * Adds the given range of characters to the given USet.  After this call,
+ * uset_contains(set, start, end) will return TRUE.
+ * A frozen set will not be modified.
+ * @param set the object to which to add the character
+ * @param start the first character of the range to add, inclusive
+ * @param end the last character of the range to add, inclusive
+ * @stable ICU 2.2
+ */
+U_STABLE void U_EXPORT2
+uset_addRange(USet* set, UChar32 start, UChar32 end);
+
+/**
+ * Adds the given string to the given USet.  After this call,
+ * uset_containsString(set, str, strLen) will return TRUE.
+ * A frozen set will not be modified.
+ * @param set the object to which to add the character
+ * @param str the string to add
+ * @param strLen the length of the string or -1 if null terminated.
+ * @stable ICU 2.4
+ */
+U_STABLE void U_EXPORT2
+uset_addString(USet* set, const UChar* str, int32_t strLen);
+
+/**
+ * Adds each of the characters in this string to the set. Thus "ch" => {"c", "h"}
+ * If this set already any particular character, it has no effect on that character.
+ * A frozen set will not be modified.
+ * @param set the object to which to add the character
+ * @param str the source string
+ * @param strLen the length of the string or -1 if null terminated.
+ * @stable ICU 3.4
+ */
+U_STABLE void U_EXPORT2
+uset_addAllCodePoints(USet* set, const UChar *str, int32_t strLen);
+
+/**
+ * Removes the given character from the given USet.  After this call,
+ * uset_contains(set, c) will return FALSE.
+ * A frozen set will not be modified.
+ * @param set the object from which to remove the character
+ * @param c the character to remove
+ * @stable ICU 2.4
+ */
+U_STABLE void U_EXPORT2
+uset_remove(USet* set, UChar32 c);
+
+/**
+ * Removes the given range of characters from the given USet.  After this call,
+ * uset_contains(set, start, end) will return FALSE.
+ * A frozen set will not be modified.
+ * @param set the object to which to add the character
+ * @param start the first character of the range to remove, inclusive
+ * @param end the last character of the range to remove, inclusive
+ * @stable ICU 2.2
+ */
+U_STABLE void U_EXPORT2
+uset_removeRange(USet* set, UChar32 start, UChar32 end);
+
+/**
+ * Removes the given string to the given USet.  After this call,
+ * uset_containsString(set, str, strLen) will return FALSE.
+ * A frozen set will not be modified.
+ * @param set the object to which to add the character
+ * @param str the string to remove
+ * @param strLen the length of the string or -1 if null terminated.
+ * @stable ICU 2.4
+ */
+U_STABLE void U_EXPORT2
+uset_removeString(USet* set, const UChar* str, int32_t strLen);
+
+/**
+ * Removes from this set all of its elements that are contained in the
+ * specified set.  This operation effectively modifies this
+ * set so that its value is the <i>asymmetric set difference</i> of
+ * the two sets.
+ * A frozen set will not be modified.
+ * @param set the object from which the elements are to be removed
+ * @param removeSet the object that defines which elements will be
+ * removed from this set
+ * @stable ICU 3.2
+ */
+U_STABLE void U_EXPORT2
+uset_removeAll(USet* set, const USet* removeSet);
+
+/**
+ * Retain only the elements in this set that are contained in the
+ * specified range.  If <code>start > end</code> then an empty range is
+ * retained, leaving the set empty.  This is equivalent to
+ * a boolean logic AND, or a set INTERSECTION.
+ * A frozen set will not be modified.
+ *
+ * @param set the object for which to retain only the specified range
+ * @param start first character, inclusive, of range to be retained
+ * to this set.
+ * @param end last character, inclusive, of range to be retained
+ * to this set.
+ * @stable ICU 3.2
+ */
+U_STABLE void U_EXPORT2
+uset_retain(USet* set, UChar32 start, UChar32 end);
+
+/**
+ * Retains only the elements in this set that are contained in the
+ * specified set.  In other words, removes from this set all of
+ * its elements that are not contained in the specified set.  This
+ * operation effectively modifies this set so that its value is
+ * the <i>intersection</i> of the two sets.
+ * A frozen set will not be modified.
+ *
+ * @param set the object on which to perform the retain
+ * @param retain set that defines which elements this set will retain
+ * @stable ICU 3.2
+ */
+U_STABLE void U_EXPORT2
+uset_retainAll(USet* set, const USet* retain);
+
+/**
+ * Reallocate this objects internal structures to take up the least
+ * possible space, without changing this object's value.
+ * A frozen set will not be modified.
+ *
+ * @param set the object on which to perfrom the compact
+ * @stable ICU 3.2
+ */
+U_STABLE void U_EXPORT2
+uset_compact(USet* set);
+
+/**
+ * Inverts this set.  This operation modifies this set so that
+ * its value is its complement.  This operation does not affect
+ * the multicharacter strings, if any.
+ * A frozen set will not be modified.
+ * @param set the set
+ * @stable ICU 2.4
+ */
+U_STABLE void U_EXPORT2
+uset_complement(USet* set);
+
+/**
+ * Complements in this set all elements contained in the specified
+ * set.  Any character in the other set will be removed if it is
+ * in this set, or will be added if it is not in this set.
+ * A frozen set will not be modified.
+ *
+ * @param set the set with which to complement
+ * @param complement set that defines which elements will be xor'ed
+ * from this set.
+ * @stable ICU 3.2
+ */
+U_STABLE void U_EXPORT2
+uset_complementAll(USet* set, const USet* complement);
+
+/**
+ * Removes all of the elements from this set.  This set will be
+ * empty after this call returns.
+ * A frozen set will not be modified.
+ * @param set the set
+ * @stable ICU 2.4
+ */
+U_STABLE void U_EXPORT2
+uset_clear(USet* set);
+
+/**
+ * Returns TRUE if the given USet contains no characters and no
+ * strings.
+ * @param set the set
+ * @return true if set is empty
+ * @stable ICU 2.4
+ */
+U_STABLE UBool U_EXPORT2
+uset_isEmpty(const USet* set);
+
+/**
+ * Returns TRUE if the given USet contains the given character.
+ * This function works faster with a frozen set.
+ * @param set the set
+ * @param c The codepoint to check for within the set
+ * @return true if set contains c
+ * @stable ICU 2.4
+ */
+U_STABLE UBool U_EXPORT2
+uset_contains(const USet* set, UChar32 c);
+
+/**
+ * Returns TRUE if the given USet contains all characters c
+ * where start <= c && c <= end.
+ * @param set the set
+ * @param start the first character of the range to test, inclusive
+ * @param end the last character of the range to test, inclusive
+ * @return TRUE if set contains the range
+ * @stable ICU 2.2
+ */
+U_STABLE UBool U_EXPORT2
+uset_containsRange(const USet* set, UChar32 start, UChar32 end);
+
+/**
+ * Returns TRUE if the given USet contains the given string.
+ * @param set the set
+ * @param str the string
+ * @param strLen the length of the string or -1 if null terminated.
+ * @return true if set contains str
+ * @stable ICU 2.4
+ */
+U_STABLE UBool U_EXPORT2
+uset_containsString(const USet* set, const UChar* str, int32_t strLen);
+
+/**
+ * Returns the index of the given character within this set, where
+ * the set is ordered by ascending code point.  If the character
+ * is not in this set, return -1.  The inverse of this method is
+ * <code>charAt()</code>.
+ * @param set the set
+ * @param c the character to obtain the index for
+ * @return an index from 0..size()-1, or -1
+ * @stable ICU 3.2
+ */
+U_STABLE int32_t U_EXPORT2
+uset_indexOf(const USet* set, UChar32 c);
+
+/**
+ * Returns the character at the given index within this set, where
+ * the set is ordered by ascending code point.  If the index is
+ * out of range, return (UChar32)-1.  The inverse of this method is
+ * <code>indexOf()</code>.
+ * @param set the set
+ * @param index an index from 0..size()-1 to obtain the char for
+ * @return the character at the given index, or (UChar32)-1.
+ * @stable ICU 3.2
+ */
+U_STABLE UChar32 U_EXPORT2
+uset_charAt(const USet* set, int32_t index);
+
+/**
+ * Returns the number of characters and strings contained in the given
+ * USet.
+ * @param set the set
+ * @return a non-negative integer counting the characters and strings
+ * contained in set
+ * @stable ICU 2.4
+ */
+U_STABLE int32_t U_EXPORT2
+uset_size(const USet* set);
+
+/**
+ * Returns the number of items in this set.  An item is either a range
+ * of characters or a single multicharacter string.
+ * @param set the set
+ * @return a non-negative integer counting the character ranges
+ * and/or strings contained in set
+ * @stable ICU 2.4
+ */
+U_STABLE int32_t U_EXPORT2
+uset_getItemCount(const USet* set);
+
+/**
+ * Returns an item of this set.  An item is either a range of
+ * characters or a single multicharacter string.
+ * @param set the set
+ * @param itemIndex a non-negative integer in the range 0..
+ * uset_getItemCount(set)-1
+ * @param start pointer to variable to receive first character
+ * in range, inclusive
+ * @param end pointer to variable to receive last character in range,
+ * inclusive
+ * @param str buffer to receive the string, may be NULL
+ * @param strCapacity capacity of str, or 0 if str is NULL
+ * @param ec error code
+ * @return the length of the string (>= 2), or 0 if the item is a
+ * range, in which case it is the range *start..*end, or -1 if
+ * itemIndex is out of range
+ * @stable ICU 2.4
+ */
+U_STABLE int32_t U_EXPORT2
+uset_getItem(const USet* set, int32_t itemIndex,
+             UChar32* start, UChar32* end,
+             UChar* str, int32_t strCapacity,
+             UErrorCode* ec);
+
+/**
+ * Returns true if set1 contains all the characters and strings
+ * of set2. It answers the question, 'Is set1 a superset of set2?'
+ * @param set1 set to be checked for containment
+ * @param set2 set to be checked for containment
+ * @return true if the test condition is met
+ * @stable ICU 3.2
+ */
+U_STABLE UBool U_EXPORT2
+uset_containsAll(const USet* set1, const USet* set2);
+
+/**
+ * Returns true if this set contains all the characters
+ * of the given string. This is does not check containment of grapheme
+ * clusters, like uset_containsString.
+ * @param set set of characters to be checked for containment
+ * @param str string containing codepoints to be checked for containment
+ * @param strLen the length of the string or -1 if null terminated.
+ * @return true if the test condition is met
+ * @stable ICU 3.4
+ */
+U_STABLE UBool U_EXPORT2
+uset_containsAllCodePoints(const USet* set, const UChar *str, int32_t strLen);
+
+/**
+ * Returns true if set1 contains none of the characters and strings
+ * of set2. It answers the question, 'Is set1 a disjoint set of set2?'
+ * @param set1 set to be checked for containment
+ * @param set2 set to be checked for containment
+ * @return true if the test condition is met
+ * @stable ICU 3.2
+ */
+U_STABLE UBool U_EXPORT2
+uset_containsNone(const USet* set1, const USet* set2);
+
+/**
+ * Returns true if set1 contains some of the characters and strings
+ * of set2. It answers the question, 'Does set1 and set2 have an intersection?'
+ * @param set1 set to be checked for containment
+ * @param set2 set to be checked for containment
+ * @return true if the test condition is met
+ * @stable ICU 3.2
+ */
+U_STABLE UBool U_EXPORT2
+uset_containsSome(const USet* set1, const USet* set2);
+
+/**
+ * Returns the length of the initial substring of the input string which
+ * consists only of characters and strings that are contained in this set
+ * (USET_SPAN_CONTAINED, USET_SPAN_SIMPLE),
+ * or only of characters and strings that are not contained
+ * in this set (USET_SPAN_NOT_CONTAINED).
+ * See USetSpanCondition for details.
+ * Similar to the strspn() C library function.
+ * Unpaired surrogates are treated according to contains() of their surrogate code points.
+ * This function works faster with a frozen set and with a non-negative string length argument.
+ * @param set the set
+ * @param s start of the string
+ * @param length of the string; can be -1 for NUL-terminated
+ * @param spanCondition specifies the containment condition
+ * @return the length of the initial substring according to the spanCondition;
+ *         0 if the start of the string does not fit the spanCondition
+ * @stable ICU 4.0
+ * @see USetSpanCondition
+ */
+U_DRAFT int32_t U_EXPORT2
+uset_span(const USet *set, const UChar *s, int32_t length, USetSpanCondition spanCondition);
+
+/**
+ * Returns the start of the trailing substring of the input string which
+ * consists only of characters and strings that are contained in this set
+ * (USET_SPAN_CONTAINED, USET_SPAN_SIMPLE),
+ * or only of characters and strings that are not contained
+ * in this set (USET_SPAN_NOT_CONTAINED).
+ * See USetSpanCondition for details.
+ * Unpaired surrogates are treated according to contains() of their surrogate code points.
+ * This function works faster with a frozen set and with a non-negative string length argument.
+ * @param set the set
+ * @param s start of the string
+ * @param length of the string; can be -1 for NUL-terminated
+ * @param spanCondition specifies the containment condition
+ * @return the start of the trailing substring according to the spanCondition;
+ *         the string length if the end of the string does not fit the spanCondition
+ * @stable ICU 4.0
+ * @see USetSpanCondition
+ */
+U_DRAFT int32_t U_EXPORT2
+uset_spanBack(const USet *set, const UChar *s, int32_t length, USetSpanCondition spanCondition);
+
+/**
+ * Returns the length of the initial substring of the input string which
+ * consists only of characters and strings that are contained in this set
+ * (USET_SPAN_CONTAINED, USET_SPAN_SIMPLE),
+ * or only of characters and strings that are not contained
+ * in this set (USET_SPAN_NOT_CONTAINED).
+ * See USetSpanCondition for details.
+ * Similar to the strspn() C library function.
+ * Malformed byte sequences are treated according to contains(0xfffd).
+ * This function works faster with a frozen set and with a non-negative string length argument.
+ * @param set the set
+ * @param s start of the string (UTF-8)
+ * @param length of the string; can be -1 for NUL-terminated
+ * @param spanCondition specifies the containment condition
+ * @return the length of the initial substring according to the spanCondition;
+ *         0 if the start of the string does not fit the spanCondition
+ * @stable ICU 4.0
+ * @see USetSpanCondition
+ */
+U_DRAFT int32_t U_EXPORT2
+uset_spanUTF8(const USet *set, const char *s, int32_t length, USetSpanCondition spanCondition);
+
+/**
+ * Returns the start of the trailing substring of the input string which
+ * consists only of characters and strings that are contained in this set
+ * (USET_SPAN_CONTAINED, USET_SPAN_SIMPLE),
+ * or only of characters and strings that are not contained
+ * in this set (USET_SPAN_NOT_CONTAINED).
+ * See USetSpanCondition for details.
+ * Malformed byte sequences are treated according to contains(0xfffd).
+ * This function works faster with a frozen set and with a non-negative string length argument.
+ * @param set the set
+ * @param s start of the string (UTF-8)
+ * @param length of the string; can be -1 for NUL-terminated
+ * @param spanCondition specifies the containment condition
+ * @return the start of the trailing substring according to the spanCondition;
+ *         the string length if the end of the string does not fit the spanCondition
+ * @stable ICU 4.0
+ * @see USetSpanCondition
+ */
+U_DRAFT int32_t U_EXPORT2
+uset_spanBackUTF8(const USet *set, const char *s, int32_t length, USetSpanCondition spanCondition);
+
+/**
+ * Returns true if set1 contains all of the characters and strings
+ * of set2, and vis versa. It answers the question, 'Is set1 equal to set2?'
+ * @param set1 set to be checked for containment
+ * @param set2 set to be checked for containment
+ * @return true if the test condition is met
+ * @stable ICU 3.2
+ */
+U_STABLE UBool U_EXPORT2
+uset_equals(const USet* set1, const USet* set2);
+
+/*********************************************************************
+ * Serialized set API
+ *********************************************************************/
+
+/**
+ * Serializes this set into an array of 16-bit integers.  Serialization
+ * (currently) only records the characters in the set; multicharacter
+ * strings are ignored.
+ *
+ * The array
+ * has following format (each line is one 16-bit integer):
+ *
+ *  length     = (n+2*m) | (m!=0?0x8000:0)
+ *  bmpLength  = n; present if m!=0
+ *  bmp[0]
+ *  bmp[1]
+ *  ...
+ *  bmp[n-1]
+ *  supp-high[0]
+ *  supp-low[0]
+ *  supp-high[1]
+ *  supp-low[1]
+ *  ...
+ *  supp-high[m-1]
+ *  supp-low[m-1]
+ *
+ * The array starts with a header.  After the header are n bmp
+ * code points, then m supplementary code points.  Either n or m
+ * or both may be zero.  n+2*m is always <= 0x7FFF.
+ *
+ * If there are no supplementary characters (if m==0) then the
+ * header is one 16-bit integer, 'length', with value n.
+ *
+ * If there are supplementary characters (if m!=0) then the header
+ * is two 16-bit integers.  The first, 'length', has value
+ * (n+2*m)|0x8000.  The second, 'bmpLength', has value n.
+ *
+ * After the header the code points are stored in ascending order.
+ * Supplementary code points are stored as most significant 16
+ * bits followed by least significant 16 bits.
+ *
+ * @param set the set
+ * @param dest pointer to buffer of destCapacity 16-bit integers.
+ * May be NULL only if destCapacity is zero.
+ * @param destCapacity size of dest, or zero.  Must not be negative.
+ * @param pErrorCode pointer to the error code.  Will be set to
+ * U_INDEX_OUTOFBOUNDS_ERROR if n+2*m > 0x7FFF.  Will be set to
+ * U_BUFFER_OVERFLOW_ERROR if n+2*m+(m!=0?2:1) > destCapacity.
+ * @return the total length of the serialized format, including
+ * the header, that is, n+2*m+(m!=0?2:1), or 0 on error other
+ * than U_BUFFER_OVERFLOW_ERROR.
+ * @stable ICU 2.4
+ */
+U_STABLE int32_t U_EXPORT2
+uset_serialize(const USet* set, uint16_t* dest, int32_t destCapacity, UErrorCode* pErrorCode);
+
+/**
+ * Given a serialized array, fill in the given serialized set object.
+ * @param fillSet pointer to result
+ * @param src pointer to start of array
+ * @param srcLength length of array
+ * @return true if the given array is valid, otherwise false
+ * @stable ICU 2.4
+ */
+U_STABLE UBool U_EXPORT2
+uset_getSerializedSet(USerializedSet* fillSet, const uint16_t* src, int32_t srcLength);
+
+/**
+ * Set the USerializedSet to contain the given character (and nothing
+ * else).
+ * @param fillSet pointer to result
+ * @param c The codepoint to set
+ * @stable ICU 2.4
+ */
+U_STABLE void U_EXPORT2
+uset_setSerializedToOne(USerializedSet* fillSet, UChar32 c);
+
+/**
+ * Returns TRUE if the given USerializedSet contains the given
+ * character.
+ * @param set the serialized set
+ * @param c The codepoint to check for within the set
+ * @return true if set contains c
+ * @stable ICU 2.4
+ */
+U_STABLE UBool U_EXPORT2
+uset_serializedContains(const USerializedSet* set, UChar32 c);
+
+/**
+ * Returns the number of disjoint ranges of characters contained in
+ * the given serialized set.  Ignores any strings contained in the
+ * set.
+ * @param set the serialized set
+ * @return a non-negative integer counting the character ranges
+ * contained in set
+ * @stable ICU 2.4
+ */
+U_STABLE int32_t U_EXPORT2
+uset_getSerializedRangeCount(const USerializedSet* set);
+
+/**
+ * Returns a range of characters contained in the given serialized
+ * set.
+ * @param set the serialized set
+ * @param rangeIndex a non-negative integer in the range 0..
+ * uset_getSerializedRangeCount(set)-1
+ * @param pStart pointer to variable to receive first character
+ * in range, inclusive
+ * @param pEnd pointer to variable to receive last character in range,
+ * inclusive
+ * @return true if rangeIndex is valid, otherwise false
+ * @stable ICU 2.4
+ */
+U_STABLE UBool U_EXPORT2
+uset_getSerializedRange(const USerializedSet* set, int32_t rangeIndex,
+                        UChar32* pStart, UChar32* pEnd);
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/usetiter.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/usetiter.h b/src/apps/couch_collate/platform/osx/icu/unicode/usetiter.h
new file mode 100644
index 0000000..defa75c
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/usetiter.h
@@ -0,0 +1,318 @@
+/*
+**********************************************************************
+* Copyright (c) 2002-2006, International Business Machines
+* Corporation and others.  All Rights Reserved.
+**********************************************************************
+*/
+#ifndef USETITER_H
+#define USETITER_H
+
+#include "unicode/utypes.h"
+#include "unicode/uobject.h"
+#include "unicode/unistr.h"
+
+/**
+ * \file 
+ * \brief C++ API: UnicodeSetIterator iterates over the contents of a UnicodeSet.
+ */
+
+U_NAMESPACE_BEGIN
+
+class UnicodeSet;
+class UnicodeString;
+
+/**
+ *
+ * UnicodeSetIterator iterates over the contents of a UnicodeSet.  It
+ * iterates over either code points or code point ranges.  After all
+ * code points or ranges have been returned, it returns the
+ * multicharacter strings of the UnicodSet, if any.
+ *
+ * This class is not intended to be subclassed.  Consider any fields
+ *  or methods declared as "protected" to be private.  The use of
+ *  protected in this class is an artifact of history.
+ *
+ * <p>To iterate over code points and strings, use a loop like this:
+ * <pre>
+ * UnicodeSetIterator it(set);
+ * while (set.next()) {
+ *     processItem(set.getString());
+ * }
+ * </pre>
+ * <p>Each item in the set is accessed as a string.  Set elements
+ *    consisting of single code points are returned as strings containing
+ *    just the one code point.
+ *
+ * <p>To iterate over code point ranges, instead of individual code points,
+ *    use a loop like this:
+ * <pre>
+ * UnicodeSetIterator it(set);
+ * while (it.nextRange()) {
+ *   if (it.isString()) {
+ *     processString(it.getString());
+ *   } else {
+ *     processCodepointRange(it.getCodepoint(), it.getCodepointEnd());
+ *   }
+ * }
+ * </pre>
+ * @author M. Davis
+ * @stable ICU 2.4
+ */
+class U_COMMON_API UnicodeSetIterator : public UObject {
+
+ protected:
+
+    /**
+     * Value of <tt>codepoint</tt> if the iterator points to a string.
+     * If <tt>codepoint == IS_STRING</tt>, then examine
+     * <tt>string</tt> for the current iteration result.
+     * @stable ICU 2.4
+     */
+    enum { IS_STRING = -1 };
+
+    /**
+     * Current code point, or the special value <tt>IS_STRING</tt>, if
+     * the iterator points to a string.
+     * @stable ICU 2.4
+     */
+    UChar32 codepoint;
+
+    /**
+     * When iterating over ranges using <tt>nextRange()</tt>,
+     * <tt>codepointEnd</tt> contains the inclusive end of the
+     * iteration range, if <tt>codepoint != IS_STRING</tt>.  If
+     * iterating over code points using <tt>next()</tt>, or if
+     * <tt>codepoint == IS_STRING</tt>, then the value of
+     * <tt>codepointEnd</tt> is undefined.
+     * @stable ICU 2.4
+     */
+    UChar32 codepointEnd;
+
+    /**
+     * If <tt>codepoint == IS_STRING</tt>, then <tt>string</tt> points
+     * to the current string.  If <tt>codepoint != IS_STRING</tt>, the
+     * value of <tt>string</tt> is undefined.
+     * @stable ICU 2.4
+     */
+    const UnicodeString* string;
+
+ public:
+
+    /**
+     * Create an iterator over the given set.  The iterator is valid
+     * only so long as <tt>set</tt> is valid.
+     * @param set set to iterate over
+     * @stable ICU 2.4
+     */
+    UnicodeSetIterator(const UnicodeSet& set);
+
+    /**
+     * Create an iterator over nothing.  <tt>next()</tt> and
+     * <tt>nextRange()</tt> return false. This is a convenience
+     * constructor allowing the target to be set later.
+     * @stable ICU 2.4
+     */
+    UnicodeSetIterator();
+
+    /**
+     * Destructor.
+     * @stable ICU 2.4
+     */
+    virtual ~UnicodeSetIterator();
+
+    /**
+     * Returns true if the current element is a string.  If so, the
+     * caller can retrieve it with <tt>getString()</tt>.  If this
+     * method returns false, the current element is a code point or
+     * code point range, depending on whether <tt>next()</tt> or
+     * <tt>nextRange()</tt> was called.
+     * Elements of types string and codepoint can both be retrieved
+     * with the function <tt>getString()</tt>.
+     * Elements of type codepoint can also be retrieved with
+     * <tt>getCodepoint()</tt>.
+     * For ranges, <tt>getCodepoint()</tt> returns the starting codepoint
+     * of the range, and <tt>getCodepointEnd()</tt> returns the end
+     * of the range.
+     * @stable ICU 2.4
+     */
+    inline UBool isString() const;
+
+    /**
+     * Returns the current code point, if <tt>isString()</tt> returned
+     * false.  Otherwise returns an undefined result.
+     * @stable ICU 2.4
+     */
+    inline UChar32 getCodepoint() const;
+
+    /**
+     * Returns the end of the current code point range, if
+     * <tt>isString()</tt> returned false and <tt>nextRange()</tt> was
+     * called.  Otherwise returns an undefined result.
+     * @stable ICU 2.4
+     */
+    inline UChar32 getCodepointEnd() const;
+
+    /**
+     * Returns the current string, if <tt>isString()</tt> returned
+     * true.  If the current iteration item is a code point, a UnicodeString
+     * containing that single code point is returned.
+     *
+     * Ownership of the returned string remains with the iterator.
+     * The string is guaranteed to remain valid only until the iterator is
+     *   advanced to the next item, or until the iterator is deleted.
+     * 
+     * @stable ICU 2.4
+     */
+    const UnicodeString& getString();
+
+    /**
+     * Advances the iteration position to the next element in the set, 
+     * which can be either a single code point or a string.  
+     * If there are no more elements in the set, return false.
+     *
+     * <p>
+     * If <tt>isString() == TRUE</tt>, the value is a
+     * string, otherwise the value is a
+     * single code point.  Elements of either type can be retrieved
+     * with the function <tt>getString()</tt>, while elements of
+     * consisting of a single code point can be retrieved with
+     * <tt>getCodepoint()</tt>
+     *
+     * <p>The order of iteration is all code points in sorted order,
+     * followed by all strings sorted order.    Do not mix
+     * calls to <tt>next()</tt> and <tt>nextRange()</tt> without
+     * calling <tt>reset()</tt> between them.  The results of doing so
+     * are undefined.
+     *
+     * @return true if there was another element in the set.
+     * @stable ICU 2.4
+     */
+    UBool next();
+
+    /**
+     * Returns the next element in the set, either a code point range
+     * or a string.  If there are no more elements in the set, return
+     * false.  If <tt>isString() == TRUE</tt>, the value is a
+     * string and can be accessed with <tt>getString()</tt>.  Otherwise the value is a
+     * range of one or more code points from <tt>getCodepoint()</tt> to
+     * <tt>getCodepointeEnd()</tt> inclusive.
+     *
+     * <p>The order of iteration is all code points ranges in sorted
+     * order, followed by all strings sorted order.  Ranges are
+     * disjoint and non-contiguous.  The value returned from <tt>getString()</tt>
+     * is undefined unless <tt>isString() == TRUE</tt>.  Do not mix calls to
+     * <tt>next()</tt> and <tt>nextRange()</tt> without calling
+     * <tt>reset()</tt> between them.  The results of doing so are
+     * undefined.
+     *
+     * @return true if there was another element in the set.
+     * @stable ICU 2.4
+     */
+    UBool nextRange();
+
+    /**
+     * Sets this iterator to visit the elements of the given set and
+     * resets it to the start of that set.  The iterator is valid only
+     * so long as <tt>set</tt> is valid.
+     * @param set the set to iterate over.
+     * @stable ICU 2.4
+     */
+    void reset(const UnicodeSet& set);
+
+    /**
+     * Resets this iterator to the start of the set.
+     * @stable ICU 2.4
+     */
+    void reset();
+
+    /**
+     * ICU "poor man's RTTI", returns a UClassID for this class.
+     *
+     * @stable ICU 2.4
+     */
+    static UClassID U_EXPORT2 getStaticClassID();
+
+    /**
+     * ICU "poor man's RTTI", returns a UClassID for the actual class.
+     *
+     * @stable ICU 2.4
+     */
+    virtual UClassID getDynamicClassID() const;
+
+    // ======================= PRIVATES ===========================
+
+ protected:
+
+    // endElement and nextElements are really UChar32's, but we keep
+    // them as signed int32_t's so we can do comparisons with
+    // endElement set to -1.  Leave them as int32_t's.
+    /** The set
+     * @stable ICU 2.4
+     */
+    const UnicodeSet* set;
+    /** End range
+     * @stable ICU 2.4
+     */
+    int32_t endRange;
+    /** Range
+     * @stable ICU 2.4
+     */
+    int32_t range;
+    /** End element
+     * @stable ICU 2.4
+     */
+    int32_t endElement;
+    /** Next element
+     * @stable ICU 2.4
+     */
+    int32_t nextElement;
+    //UBool abbreviated;
+    /** Next string
+     * @stable ICU 2.4
+     */
+    int32_t nextString;
+    /** String count
+     * @stable ICU 2.4
+     */
+    int32_t stringCount;
+
+    /**
+     *  Points to the string to use when the caller asks for a
+     *  string and the current iteration item is a code point, not a string.
+     *  @internal
+     */
+    UnicodeString *cpString;
+
+    /** Copy constructor. Disallowed.
+     * @stable ICU 2.4
+     */
+    UnicodeSetIterator(const UnicodeSetIterator&); // disallow
+
+    /** Assignment operator. Disallowed.
+     * @stable ICU 2.4
+     */
+    UnicodeSetIterator& operator=(const UnicodeSetIterator&); // disallow
+
+    /** Load range
+     * @stable ICU 2.4
+     */
+    virtual void loadRange(int32_t range);
+
+};
+
+inline UBool UnicodeSetIterator::isString() const {
+    return codepoint == (UChar32)IS_STRING;
+}
+
+inline UChar32 UnicodeSetIterator::getCodepoint() const {
+    return codepoint;
+}
+
+inline UChar32 UnicodeSetIterator::getCodepointEnd() const {
+    return codepointEnd;
+}
+
+
+U_NAMESPACE_END
+
+#endif


[93/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch/patches/js/patch-configure_in
----------------------------------------------------------------------
diff --git a/src/apps/couch/patches/js/patch-configure_in b/src/apps/couch/patches/js/patch-configure_in
new file mode 100644
index 0000000..94194d4
--- /dev/null
+++ b/src/apps/couch/patches/js/patch-configure_in
@@ -0,0 +1,56 @@
+--- configure.in.orig	2012-06-13 21:24:15.000000000 +0200
++++ configure.in	2012-06-13 21:29:10.000000000 +0200
+@@ -1038,17 +1038,6 @@
+     dnl /usr/bin/g(cc|++)-$GCC_VERSION.
+     MOZ_PATH_PROGS(PBBUILD, pbbuild xcodebuild pbxbuild)
+ 
+-    case "$PBBUILD" in
+-      *xcodebuild*)
+-        changequote(,)
+-        XCODEBUILD_VERSION=`$PBBUILD -version 2>/dev/null | xargs | sed -e 's/.*DevToolsCore-\([0-9]*\).*/\1/'`
+-        changequote([,])
+-        if test -n "$XCODEBUILD_VERSION" && test "$XCODEBUILD_VERSION" -ge 620 ; then
+-          HAS_XCODE_2_1=1;
+-        fi
+-      ;;
+-    esac
+-
+     dnl sdp was formerly in /Developer/Tools.  As of Mac OS X 10.4 (Darwin 8),
+     dnl it has moved into /usr/bin.
+     MOZ_PATH_PROG(SDP, sdp, :, [$PATH:/usr/bin:/Developer/Tools])
+@@ -1056,8 +1045,6 @@
+ esac
+ 
+ AC_SUBST(GCC_VERSION)
+-AC_SUBST(XCODEBUILD_VERSION)
+-AC_SUBST(HAS_XCODE_2_1)
+ 
+ dnl The universal machinery sets UNIVERSAL_BINARY to inform packager.mk
+ dnl that a universal binary is being produced.
+@@ -4656,6 +4643,12 @@
+ 
+ dnl Setup default CPU arch for arm target
+ case "$target_cpu" in
++  armv5*)
++    MOZ_ARM_ARCH=armv5
++  ;;
++  armv6*)
++    MOZ_ARM_ARCH=armv6
++  ;;
+   arm*)
+     MOZ_ARM_ARCH=armv7
+   ;;
+@@ -4716,6 +4709,13 @@
+   esac
+ else
+   case "$target_cpu" in
++    armv6*)
++      if test "$GNU_CC"; then
++        CFLAGS="$CFLAGS -march=armv6j -mthumb-interwork -msoft-float"
++        CXXFLAGS="$CXXFLAGS -march=armv6j -mthumb-interwork -msoft-float"
++        ASFLAGS="$ASFLAGS -march=armv6j -mthumb-interwork -msoft-float"
++      fi
++      ;;
+     arm*)
+       if test "$GNU_CC"; then
+         CFLAGS="$CFLAGS -march=armv5te -mthumb-interwork -msoft-float"

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch/patches/js/patch-jscntxt_h
----------------------------------------------------------------------
diff --git a/src/apps/couch/patches/js/patch-jscntxt_h b/src/apps/couch/patches/js/patch-jscntxt_h
new file mode 100644
index 0000000..2df18be
--- /dev/null
+++ b/src/apps/couch/patches/js/patch-jscntxt_h
@@ -0,0 +1,10 @@
+--- jscntxt.h.orig	2011-10-08 12:18:14.000000000 +0200
++++ jscntxt.h	2011-10-08 12:18:18.000000000 +0200
+@@ -44,6 +44,7 @@
+  * JS execution context.
+  */
+ #include <string.h>
++#include <sys/types.h>
+ 
+ /* Gross special case for Gecko, which defines malloc/calloc/free. */
+ #ifdef mozilla_mozalloc_macro_wrappers_h

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch/patches/js/patch-jsprf_cpp
----------------------------------------------------------------------
diff --git a/src/apps/couch/patches/js/patch-jsprf_cpp b/src/apps/couch/patches/js/patch-jsprf_cpp
new file mode 100644
index 0000000..29a51e7
--- /dev/null
+++ b/src/apps/couch/patches/js/patch-jsprf_cpp
@@ -0,0 +1,11 @@
+--- jsprf.cpp.orig	2011-03-31 12:11:03.000000000 +0200
++++ jsprf.cpp	2011-03-31 12:11:09.000000000 +0200
+@@ -58,6 +58,8 @@
+ */
+ #ifdef HAVE_VA_COPY
+ #define VARARGS_ASSIGN(foo, bar)        VA_COPY(foo,bar)
++#elif defined(va_copy)
++#define VARARGS_ASSIGN(foo, bar)        va_copy(foo,bar)
+ #elif defined(HAVE_VA_LIST_AS_ARRAY)
+ #define VARARGS_ASSIGN(foo, bar)        foo[0] = bar[0]
+ #else

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch/rebar.config.script
----------------------------------------------------------------------
diff --git a/src/apps/couch/rebar.config.script b/src/apps/couch/rebar.config.script
index 2b187b6..5a75a3d 100644
--- a/src/apps/couch/rebar.config.script
+++ b/src/apps/couch/rebar.config.script
@@ -68,41 +68,86 @@ GetFlag = fun(Name, Default) ->
     end,
 
 
-JSLIBS = GetFlag("JS_LIBS", "-lmozjs185"),
-JSCFLAGS = GetFlag("JS_CFLAGS", "-I/usr/include/js"),
-
-{CFLAGS, LDFLAGS}  = case os:type() of
-    {unix, darwin} ->
-        {"-DXP_UNIX " ++ JSCFLAGS, JSLIBS};
-    {unix, _} ->
-        {"-DXP_UNIX " ++ JSCFLAGS, JSLIBS ++ " -lm"};
+
+PortEnv = case os:getenv("COUCHDB_STATIC") of
+    "1" ->
+        {ok, Cwd} = file:get_cwd(),
+        IncJs = filename:join([Cwd, ".libs", "js", "include"]),
+        IncNspr= filename:join([Cwd, ".libs", "nsprpub", "include"]),
+        StaticJs = filename:join([Cwd, ".libs", "js", "lib",
+                                 "libjs_static.a"]),
+        StaticNspr = filename:join([Cwd, ".libs", "nsprpub", "lib",
+                                    "libnspr4.a"]),
+
+
+        CFLAGS = GetFlag("JS_CFLAGS", "-I" ++ IncJs ++
+                                      " -I" ++ IncNspr ++ " -DXP_UNIX -Wall"),
+        LDFLAGS = GetFlag("JS_LIBS", StaticJs ++ " " ++ StaticNspr),
+
+        {CFLAGS1, LDFLAGS1} = case os:getenv("WITHOUT_CURL") of
+            "1" -> {"-DWITHOUT_CURL " ++ CFLAGS, LDFLAGS};
+            _ -> {CFLAGS, LDFLAGS ++ " -lcurl"}
+        end,
+
+        [
+            {"CFLAGS", "$CFLAGS -Wall -c -g -O2 " ++ CFLAGS1},
+            {"LDFLAGS", "$LDFLAGS " ++ LDFLAGS1 ++ " -lstdc++"},
+            {"linux.*", "LDFLAGS", "$LDFLAGS " ++ LDFLAGS1 ++
+                                   " -lstdc++ -lpthread -lm"},
+
+            %% Prevent the make->gmake transition from infecting
+            %% MAKEFLAGS with bad flags that confuse gmake
+            {"freebsd.*", "MAKEFLAGS", ""},
+            {"freebsd.*","LDFLAGS", "$LDFLAGS " ++ LDFLAGS1 ++
+                                     " -lstdc++ -lpthread"}
+        ];
     _ ->
-        {"-DXP_WIN " ++ JSCFLAGS, JSLIBS}
+        JSLIBS = GetFlag("JS_LIBS", "-lmozjs185"),
+
+        {CFLAGS, LDFLAGS}  = case os:type() of
+            {unix, darwin} ->
+                JSCFLAGS = GetFlag("JS_CFLAGS", "-I/usr/local/include/js"),
+                {"-DXP_UNIX " ++ JSCFLAGS, JSLIBS};
+            {unix, linux} ->
+                %% generally linux install in /usr/include
+                JSCFLAGS = GetFlag("JS_CFLAGS", "-I/usr/include/js"),
+                {"-DXP_UNIX " ++ JSCFLAGS, JSLIBS ++ " -lm"};
+            {unix, _} ->
+                %% most likely a bsd
+                JSCFLAGS = GetFlag("JS_CFLAGS", "-I/usr/local/include/js"),
+                {"-DXP_UNIX " ++ JSCFLAGS, JSLIBS ++ " -lm"};
+            _ ->
+                JSCFLAGS = GetFlag("JS_CFLAGS", "-I/usr/include/js"),
+                {"-DXP_WIN " ++ JSCFLAGS, JSLIBS}
+        end,
+
+        {CFLAGS1, LDFLAGS1} = case os:getenv("WITHOUT_CURL") of
+            "1" -> {"-DWITHOUT_CURL " ++ CFLAGS, LDFLAGS};
+            _ -> {CFLAGS, LDFLAGS ++ " -lcurl"}
+        end,
+
+        [
+            {"CFLAGS",  "$CFLAGS -Wall -c -g -O2 " ++ CFLAGS1},
+            {"LDFLAGS", "$LDFLAGS " ++ LDFLAGS1}
+        ]
 end,
 
-{CFLAGS1, LDFLAGS1} = case os:getenv("WITHOUT_CURL") of
-    "1" -> {"-DWITHOUT_CURL " ++ CFLAGS, LDFLAGS};
-    _ -> {CFLAGS, LDFLAGS ++ " -lcurl"}
-end,
+PortSpecs0 = [{filename:join(["priv", CouchJSName]), ["c_src/couch_js/*.c"]}],
 
-PortSpecs0 = case os:type() of
+PortSpecs = case os:type() of
     {win32, _} ->
-        [{filename:join(["priv", "couchspawnkillable"]),
+        PortSpecs0 ++ [{filename:join(["priv", "couchspawnkillable"]),
             ["c_src/spawnkillable/*.c"]}];
     _ ->
         {ok, _} = file:copy("priv/couchspawnkillable.sh",
                             "priv/couchspawnkillable"),
         os:cmd("chmod +x priv/couchspawnkillable"),
-        []
+        PortSpecs0
     end,
 
-PortEnv = [{port_env, [
-            {"CFLAGS",  "$CFLAGS -Wall -c -g -O2 " ++ CFLAGS1},
-            {"LDFLAGS", "$LDFLAGS " ++ LDFLAGS1}]},
-
-           {port_specs, [
-            {filename:join(["priv", CouchJSName]),
-            ["c_src/couch_js/*.c"]}] ++ PortSpecs0}
-],
+PortInfo = [{port_env, PortEnv},
+            {port_specs, PortSpecs},
+            {pre_hooks, [{compile, "./build_spidermonkey.sh"}]},
+            {post_hooks, [{clean, "./build_spidermonkey.sh clean"}]}],
 
-lists:keymerge(1,lists:keysort(1, PortEnv), lists:keysort(1, CONFIG)).
+lists:keymerge(1,lists:keysort(1, PortInfo), lists:keysort(1, CONFIG)).

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/build_icu.sh
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/build_icu.sh b/src/apps/couch_collate/build_icu.sh
new file mode 100755
index 0000000..e6ba834
--- /dev/null
+++ b/src/apps/couch_collate/build_icu.sh
@@ -0,0 +1,191 @@
+#!/bin/sh
+
+CORE_TOP=`pwd`
+export CORE_TOP
+
+CURLBIN=`which curl`
+if ! test -n "CURLBIN"; then
+    display_error "Error: curl is required. Add it to 'PATH'"
+    exit 1
+fi
+
+GUNZIP=`which gunzip`
+UNZIP=`which unzip`
+TAR=`which tar`
+GNUMAKE=`which gmake 2>/dev/null || which make`
+PATCHES=$CORE_TOP/patches
+STATICLIBS=$CORE_TOP/.libs
+DISTDIR=$CORE_TOP/.dists
+
+# icu sources
+ICU_VER=4.4.2
+ICU_DISTNAME=icu4c-4_4_2-src.tgz
+ICU_SITE=http://dl.refuge.io
+ICUDIR=$STATICLIBS/icu_src/icu
+
+
+[ "$MACHINE" ] || MACHINE=`(uname -m) 2>/dev/null` || MACHINE="unknown"
+[ "$RELEASE" ] || RELEASE=`(uname -r) 2>/dev/null` || RELEASE="unknown"
+[ "$SYSTEM" ] || SYSTEM=`(uname -s) 2>/dev/null`  || SYSTEM="unknown"
+[ "$BUILD" ] || VERSION=`(uname -v) 2>/dev/null` || VERSION="unknown"
+
+
+CFLAGS="-g -O2 -Wall"
+LDFLAGS="-lstdc++"
+ARCH=
+ISA64=
+GNUMAKE=make
+CC=gcc
+CXX=g++
+PATCH=patch
+case "$SYSTEM" in
+    Linux)
+        ARCH=`arch 2>/dev/null`
+        ;;
+    FreeBSD|OpenBSD|NetBSD)
+        ARCH=`(uname -p) 2>/dev/null`
+        GNUMAKE=gmake
+        ;;
+    Darwin)
+        ARCH=`(uname -p) 2>/dev/null`
+        ISA64=`(sysctl -n hw.optional.x86_64) 2>/dev/null`
+        ;;
+    Solaris)
+        ARCH=`(uname -p) 2>/dev/null`
+        GNUMAKE=gmake
+        PATCH=gpatch
+        ;;
+    *)
+        ARCH="unknown"
+        ;;
+esac
+
+
+# TODO: add mirror & signature validation support
+fetch()
+{
+    TARGET=$DISTDIR/$1
+    if ! test -f $TARGET; then
+        echo "==> Fetch $1 to $TARGET"
+        $CURLBIN --progress-bar -L $2/$1 -o $TARGET
+    fi
+}
+
+build_icu()
+{
+    fetch $ICU_DISTNAME $ICU_SITE
+
+    mkdir -p $ICUDIR
+
+    echo "==> icu (compile)"
+
+    rm -rf $STATICLIBS/icu*
+
+    cd $STATICLIBS
+    $GUNZIP -c $DISTDIR/$ICU_DISTNAME | $TAR xf - -C $STATICLIBS/icu_src
+
+    # apply patches
+    cd $STATICLIBS/icu_src
+    for P in $PATCHES/icu/*.patch; do \
+        (patch -p0 -i $P || echo "skipping patch"); \
+    done
+
+    cd $ICUDIR/source
+
+    CFLAGS="-g -Wall -fPIC -Os"
+
+    env CC="gcc" CXX="g++" CPPFLAGS="" LDFLAGS="-fPIC" \
+	CFLAGS="$CFLAGS" CXXFLAGS="$CFLAGS" \
+        ./configure --disable-debug \
+		    --enable-static \
+		    --disable-shared \
+		    --disable-icuio \
+		    --disable-layout \
+		    --disable-extras \
+		    --disable-tests \
+		    --disable-samples \
+		    --prefix=$STATICLIBS/icu && \
+        $GNUMAKE && $GNUMAKE install
+}
+
+do_setup()
+{
+    echo "==> build icu"
+    mkdir -p $DISTDIR
+    mkdir -p $STATICLIBS
+}
+
+do_builddeps()
+{
+    if [ ! -f $STATICLIBS/icu/lib/libicui18n.a ]; then
+        build_icu
+    fi
+}
+
+
+clean()
+{
+    rm -rf $STATICLIBS
+    rm -rf $DISTDIR
+}
+
+
+
+usage()
+{
+    cat << EOF
+Usage: $basename [command] [OPTIONS]
+
+The $basename command compile Mozilla Spidermonkey and ICU statically
+for couch_core.
+
+Commands:
+
+    all:        build couch_core static libs
+    clean:      clean static libs
+    -?:         display usage
+
+Report bugs at <https://github.com/refuge/couch_core>.
+EOF
+}
+
+
+if [ ! "x$COUCHDB_STATIC" = "x1" ]; then
+    exit 0
+fi
+
+if [ ! "x$USE_STATIC_ICU" = "x1" ]; then
+    exit 0
+fi
+
+if [ "x$1" = "x" ]; then
+    do_setup
+    do_builddeps
+	exit 0
+fi
+
+case "$1" in
+    all)
+        shift 1
+        do_setup
+        do_builddeps
+        ;;
+    clean)
+        shift 1
+        clean
+        ;;
+    help|--help|-h|-?)
+        usage
+        exit 0
+        ;;
+    *)
+        echo $basename: ERROR Unknown command $arg 1>&2
+        echo 1>&2
+        usage 1>&2
+        echo "### $basename: Exitting." 1>&2
+        exit 1;
+        ;;
+esac
+
+
+exit 0

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/patches/icu/common-uloc_c.patch
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/patches/icu/common-uloc_c.patch b/src/apps/couch_collate/patches/icu/common-uloc_c.patch
new file mode 100644
index 0000000..fe60732
--- /dev/null
+++ b/src/apps/couch_collate/patches/icu/common-uloc_c.patch
@@ -0,0 +1,26 @@
+$FreeBSD: ports/devel/icu/files/patch-common-uloc.c,v 1.1 2011/12/23 14:54:18 crees Exp $
+
+From http://bugs.icu-project.org/trac/ticket/8984
+
+Submitted by: Andrei Lavreniyuk <an...@gmail.com> (thanks!)
+
+--- icu/source/common/uloc.c
++++ icu/source/common/uloc.c
+@@ -1797,7 +1797,7 @@
+                 int32_t variantLen = _deleteVariant(variant, uprv_min(variantSize, (nameCapacity-len)), variantToCompare, n);
+                 len -= variantLen;
+                 if (variantLen > 0) {
+-                    if (name[len-1] == '_') { /* delete trailing '_' */
++                    if (len > 0 && name[len-1] == '_') { /* delete trailing '_' */
+                         --len;
+                     }
+                     addKeyword = VARIANT_MAP[j].keyword;
+@@ -1805,7 +1805,7 @@
+                     break;
+                 }
+             }
+-            if (name[len-1] == '_') { /* delete trailing '_' */
++            if (len > 0 && len <= nameCapacity && name[len-1] == '_') { /* delete trailing '_' */
+                 --len;
+             }
+         }

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/patches/icu/layout_LookupProcessor_cpp.patch
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/patches/icu/layout_LookupProcessor_cpp.patch b/src/apps/couch_collate/patches/icu/layout_LookupProcessor_cpp.patch
new file mode 100644
index 0000000..304d266
--- /dev/null
+++ b/src/apps/couch_collate/patches/icu/layout_LookupProcessor_cpp.patch
@@ -0,0 +1,13 @@
+--- icu/source/layout/LookupProcessor.cpp
++++ icu/source/layout/LookupProcessor.cpp
+@@ -201,7 +201,9 @@
+ 
+     if (requiredFeatureIndex != 0xFFFF) {
+         requiredFeatureTable = featureListTable->getFeatureTable(requiredFeatureIndex, &requiredFeatureTag);
+-        featureReferences += SWAPW(featureTable->lookupCount);
++	if (requiredFeatureTable) {
++	        featureReferences += SWAPW(requiredFeatureTable->lookupCount);
++	}
+     }
+ 
+     lookupOrderArray = LE_NEW_ARRAY(le_uint16, featureReferences);

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/patches/icu/source_config_Makefile_inc_in.patch
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/patches/icu/source_config_Makefile_inc_in.patch b/src/apps/couch_collate/patches/icu/source_config_Makefile_inc_in.patch
new file mode 100644
index 0000000..89d428e
--- /dev/null
+++ b/src/apps/couch_collate/patches/icu/source_config_Makefile_inc_in.patch
@@ -0,0 +1,12 @@
+--- icu/source/config/Makefile.inc.in.orig	2011-04-07 17:41:15.000000000 +0200
++++ icu/source/config/Makefile.inc.in	2011-04-07 17:41:40.000000000 +0200
+@@ -44,8 +44,7 @@
+ LIBICU = lib$(ICUPREFIX)
+ 
+ # Static library prefix and file extension
+-STATIC_PREFIX = s
+-LIBSICU = lib$(STATIC_PREFIX)$(ICUPREFIX)
++LIBSICU = lib$(ICUPREFIX)
+ A = a
+ 
+ # Suffix at the end of libraries. Usually empty.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/patches/icu/source_icudefs_mk_in.patch
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/patches/icu/source_icudefs_mk_in.patch b/src/apps/couch_collate/patches/icu/source_icudefs_mk_in.patch
new file mode 100644
index 0000000..a1add5e
--- /dev/null
+++ b/src/apps/couch_collate/patches/icu/source_icudefs_mk_in.patch
@@ -0,0 +1,19 @@
+--- icu/source/icudefs.mk.in.orig	2011-04-07 17:15:44.000000000 +0200
++++ icu/source/icudefs.mk.in	2011-04-07 17:15:56.000000000 +0200
+@@ -189,14 +189,13 @@
+ 
+ ## If we can't use the shared libraries, use the static libraries
+ ifneq ($(ENABLE_SHARED),YES)
+-STATIC_PREFIX_WHEN_USED = s
++STATIC_PREFIX_WHEN_USED =
+ else
+ STATIC_PREFIX_WHEN_USED = 
+ endif
+ 
+ # Static library prefix and file extension
+-STATIC_PREFIX = s
+-LIBSICU = $(LIBPREFIX)$(STATIC_PREFIX)$(ICUPREFIX)
++LIBSICU = $(LIBPREFIX)$(ICUPREFIX)
+ A = a
+ SOBJ = $(SO)
+ 

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/basictz.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/basictz.h b/src/apps/couch_collate/platform/osx/icu/unicode/basictz.h
new file mode 100644
index 0000000..c616a3e
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/basictz.h
@@ -0,0 +1,210 @@
+/*
+*******************************************************************************
+* Copyright (C) 2007-2008, International Business Machines Corporation and         *
+* others. All Rights Reserved.                                                *
+*******************************************************************************
+*/
+#ifndef BASICTZ_H
+#define BASICTZ_H
+
+/**
+ * \file 
+ * \brief C++ API: ICU TimeZone base class
+ */
+
+#include "unicode/utypes.h"
+
+#if !UCONFIG_NO_FORMATTING
+
+#include "unicode/timezone.h"
+#include "unicode/tzrule.h"
+#include "unicode/tztrans.h"
+
+U_NAMESPACE_BEGIN
+
+// forward declarations
+class UVector;
+
+/**
+ * <code>BasicTimeZone</code> is an abstract class extending <code>TimeZone</code>.
+ * This class provides some additional methods to access time zone transitions and rules.
+ * All ICU <code>TimeZone</code> concrete subclasses extend this class.
+ * @stable ICU 4.0
+ */
+class U_I18N_API BasicTimeZone: public TimeZone {
+public:
+    /**
+     * Destructor.
+     * @stable ICU 4.0
+     */
+    virtual ~BasicTimeZone();
+
+    /**
+     * Gets the first time zone transition after the base time.
+     * @param base      The base time.
+     * @param inclusive Whether the base time is inclusive or not.
+     * @param result    Receives the first transition after the base time.
+     * @return  TRUE if the transition is found.
+     * @stable ICU 4.0
+     */
+    virtual UBool getNextTransition(UDate base, UBool inclusive, TimeZoneTransition& result) /*const*/ = 0;
+
+    /**
+     * Gets the most recent time zone transition before the base time.
+     * @param base      The base time.
+     * @param inclusive Whether the base time is inclusive or not.
+     * @param result    Receives the most recent transition before the base time.
+     * @return  TRUE if the transition is found.
+     * @stable ICU 4.0
+     */
+    virtual UBool getPreviousTransition(UDate base, UBool inclusive, TimeZoneTransition& result) /*const*/ = 0;
+
+    /**
+     * Checks if the time zone has equivalent transitions in the time range.
+     * This method returns true when all of transition times, from/to standard
+     * offsets and DST savings used by this time zone match the other in the
+     * time range.
+     * @param tz    The <code>BasicTimeZone</code> object to be compared with.
+     * @param start The start time of the evaluated time range (inclusive)
+     * @param end   The end time of the evaluated time range (inclusive)
+     * @param ignoreDstAmount
+     *              When true, any transitions with only daylight saving amount
+     *              changes will be ignored, except either of them is zero.
+     *              For example, a transition from rawoffset 3:00/dstsavings 1:00
+     *              to rawoffset 2:00/dstsavings 2:00 is excluded from the comparison,
+     *              but a transtion from rawoffset 2:00/dstsavings 1:00 to
+     *              rawoffset 3:00/dstsavings 0:00 is included.
+     * @param ec    Output param to filled in with a success or an error.
+     * @return      true if the other time zone has the equivalent transitions in the
+     *              time range.
+     * @stable ICU 4.0
+     */
+    virtual UBool hasEquivalentTransitions(/*const*/ BasicTimeZone& tz, UDate start, UDate end,
+        UBool ignoreDstAmount, UErrorCode& ec) /*const*/;
+
+    /**
+     * Returns the number of <code>TimeZoneRule</code>s which represents time transitions,
+     * for this time zone, that is, all <code>TimeZoneRule</code>s for this time zone except
+     * <code>InitialTimeZoneRule</code>.  The return value range is 0 or any positive value.
+     * @param status    Receives error status code.
+     * @return The number of <code>TimeZoneRule</code>s representing time transitions.
+     * @stable ICU 4.0
+     */
+    virtual int32_t countTransitionRules(UErrorCode& status) /*const*/ = 0;
+
+    /**
+     * Gets the <code>InitialTimeZoneRule</code> and the set of <code>TimeZoneRule</code>
+     * which represent time transitions for this time zone.  On successful return,
+     * the argument initial points to non-NULL <code>InitialTimeZoneRule</code> and
+     * the array trsrules is filled with 0 or multiple <code>TimeZoneRule</code>
+     * instances up to the size specified by trscount.  The results are referencing the
+     * rule instance held by this time zone instance.  Therefore, after this time zone
+     * is destructed, they are no longer available.
+     * @param initial       Receives the initial timezone rule
+     * @param trsrules      Receives the timezone transition rules
+     * @param trscount      On input, specify the size of the array 'transitions' receiving
+     *                      the timezone transition rules.  On output, actual number of
+     *                      rules filled in the array will be set.
+     * @param status        Receives error status code.
+     * @stable ICU 4.0
+     */
+    virtual void getTimeZoneRules(const InitialTimeZoneRule*& initial,
+        const TimeZoneRule* trsrules[], int32_t& trscount, UErrorCode& status) /*const*/ = 0;
+
+    /**
+     * Gets the set of time zone rules valid at the specified time.  Some known external time zone
+     * implementations are not capable to handle historic time zone rule changes.  Also some
+     * implementations can only handle certain type of rule definitions.
+     * If this time zone does not use any daylight saving time within about 1 year from the specified
+     * time, only the <code>InitialTimeZone</code> is returned.  Otherwise, the rule for standard
+     * time and daylight saving time transitions are returned in addition to the
+     * <code>InitialTimeZoneRule</code>.  The standard and daylight saving time transition rules are
+     * represented by <code>AnnualTimeZoneRule</code> with <code>DateTimeRule::DOW</code> for its date
+     * rule and <code>DateTimeRule::WALL_TIME</code> for its time rule.  Because daylight saving time
+     * rule is changing time to time in many time zones and also mapping a transition time rule to
+     * different type is lossy transformation, the set of rules returned by this method may be valid
+     * for short period of time.
+     * The time zone rule objects returned by this method is owned by the caller, so the caller is
+     * responsible for deleting them after use.
+     * @param date      The date used for extracting time zone rules.
+     * @param initial   Receives the <code>InitialTimeZone</code>, always not NULL.
+     * @param std       Receives the <code>AnnualTimeZoneRule</code> for standard time transitions.
+     *                  When this time time zone does not observe daylight saving times around the
+     *                  specified date, NULL is set.
+     * @param dst       Receives the <code>AnnualTimeZoneRule</code> for daylight saving time
+     *                  transitions.  When this time zone does not observer daylight saving times
+     *                  around the specified date, NULL is set.
+     * @param status    Receives error status code.
+     * @stable ICU 4.0
+     */
+    virtual void getSimpleRulesNear(UDate date, InitialTimeZoneRule*& initial,
+        AnnualTimeZoneRule*& std, AnnualTimeZoneRule*& dst, UErrorCode& status) /*const*/;
+
+
+    /**
+     * The time type option bit flags used by getOffsetFromLocal
+     * @internal
+     */
+    enum {
+        kStandard = 0x01,
+        kDaylight = 0x03,
+        kFormer = 0x04,
+        kLatter = 0x0C
+    };
+
+    /**
+     * Get time zone offsets from local wall time.
+     * @internal
+     */
+    virtual void getOffsetFromLocal(UDate date, int32_t nonExistingTimeOpt, int32_t duplicatedTimeOpt,
+        int32_t& rawOffset, int32_t& dstOffset, UErrorCode& status) /*const*/;
+
+protected:
+
+    /**
+     * The time type option bit masks used by getOffsetFromLocal
+     * @internal
+     */
+    enum {
+        kStdDstMask = kDaylight,
+        kFormerLatterMask = kLatter
+    };
+
+    /**
+     * Default constructor.
+     * @stable ICU 4.0
+     */
+    BasicTimeZone();
+
+    /**
+     * Construct a timezone with a given ID.
+     * @param id a system time zone ID
+     * @stable ICU 4.0
+     */
+    BasicTimeZone(const UnicodeString &id);
+
+    /**
+     * Copy constructor.
+     * @param source the object to be copied.
+     * @stable ICU 4.0
+     */
+    BasicTimeZone(const BasicTimeZone& source);
+
+    /**
+     * Gets the set of TimeZoneRule instances applicable to the specified time and after.
+     * @param start     The start date used for extracting time zone rules
+     * @param initial   Receives the InitialTimeZone, always not NULL
+     * @param transitionRules   Receives the transition rules, could be NULL
+     * @param status    Receives error status code
+     */
+    void getTimeZoneRulesAfter(UDate start, InitialTimeZoneRule*& initial, UVector*& transitionRules,
+        UErrorCode& status) /*const*/;
+};
+
+U_NAMESPACE_END
+
+#endif /* #if !UCONFIG_NO_FORMATTING */
+
+#endif // BASICTZ_H
+
+//eof

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/brkiter.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/brkiter.h b/src/apps/couch_collate/platform/osx/icu/unicode/brkiter.h
new file mode 100644
index 0000000..7df5f14
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/brkiter.h
@@ -0,0 +1,557 @@
+/*
+********************************************************************************
+*   Copyright (C) 1997-2007, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+********************************************************************************
+*
+* File brkiter.h
+*
+* Modification History:
+*
+*   Date        Name        Description
+*   02/18/97    aliu        Added typedef for TextCount.  Made DONE const.
+*   05/07/97    aliu        Fixed DLL declaration.
+*   07/09/97    jfitz       Renamed BreakIterator and interface synced with JDK
+*   08/11/98    helena      Sync-up JDK1.2.
+*   01/13/2000  helena      Added UErrorCode parameter to createXXXInstance methods.
+********************************************************************************
+*/
+
+#ifndef BRKITER_H
+#define BRKITER_H
+
+#include "unicode/utypes.h"
+
+/**
+ * \file
+ * \brief C++ API: Break Iterator.
+ */
+
+#if UCONFIG_NO_BREAK_ITERATION
+
+U_NAMESPACE_BEGIN
+
+/*
+ * Allow the declaration of APIs with pointers to BreakIterator
+ * even when break iteration is removed from the build.
+ */
+class BreakIterator;
+
+U_NAMESPACE_END
+
+#else
+
+#include "unicode/uobject.h"
+#include "unicode/unistr.h"
+#include "unicode/chariter.h"
+#include "unicode/locid.h"
+#include "unicode/ubrk.h"
+#include "unicode/strenum.h"
+#include "unicode/utext.h"
+#include "unicode/umisc.h"
+
+U_NAMESPACE_BEGIN
+
+/**
+ * The BreakIterator class implements methods for finding the location
+ * of boundaries in text. BreakIterator is an abstract base class.
+ * Instances of BreakIterator maintain a current position and scan over
+ * text returning the index of characters where boundaries occur.
+ * <p>
+ * Line boundary analysis determines where a text string can be broken
+ * when line-wrapping. The mechanism correctly handles punctuation and
+ * hyphenated words.
+ * <p>
+ * Sentence boundary analysis allows selection with correct
+ * interpretation of periods within numbers and abbreviations, and
+ * trailing punctuation marks such as quotation marks and parentheses.
+ * <p>
+ * Word boundary analysis is used by search and replace functions, as
+ * well as within text editing applications that allow the user to
+ * select words with a double click. Word selection provides correct
+ * interpretation of punctuation marks within and following
+ * words. Characters that are not part of a word, such as symbols or
+ * punctuation marks, have word-breaks on both sides.
+ * <p>
+ * Character boundary analysis allows users to interact with
+ * characters as they expect to, for example, when moving the cursor
+ * through a text string. Character boundary analysis provides correct
+ * navigation of through character strings, regardless of how the
+ * character is stored.  For example, an accented character might be
+ * stored as a base character and a diacritical mark. What users
+ * consider to be a character can differ between languages.
+ * <p>
+ * The text boundary positions are found according to the rules
+ * described in Unicode Standard Annex #29, Text Boundaries, and
+ * Unicode Standard Annex #14, Line Breaking Properties.  These
+ * are available at http://www.unicode.org/reports/tr14/ and
+ * http://www.unicode.org/reports/tr29/.
+ * <p>
+ * In addition to the C++ API defined in this header file, a
+ * plain C API with equivalent functionality is defined in the
+ * file ubrk.h
+ * <p>
+ * Code snippits illustrating the use of the Break Iterator APIs
+ * are available in the ICU User Guide,
+ * http://icu-project.org/userguide/boundaryAnalysis.html
+ * and in the sample program icu/source/samples/break/break.cpp"
+ *
+ */
+class U_COMMON_API BreakIterator : public UObject {
+public:
+    /**
+     *  destructor
+     *  @stable ICU 2.0
+     */
+    virtual ~BreakIterator();
+
+    /**
+     * Return true if another object is semantically equal to this
+     * one. The other object should be an instance of the same subclass of
+     * BreakIterator. Objects of different subclasses are considered
+     * unequal.
+     * <P>
+     * Return true if this BreakIterator is at the same position in the
+     * same text, and is the same class and type (word, line, etc.) of
+     * BreakIterator, as the argument.  Text is considered the same if
+     * it contains the same characters, it need not be the same
+     * object, and styles are not considered.
+     * @stable ICU 2.0
+     */
+    virtual UBool operator==(const BreakIterator&) const = 0;
+
+    /**
+     * Returns the complement of the result of operator==
+     * @param rhs The BreakIterator to be compared for inequality
+     * @return the complement of the result of operator==
+     * @stable ICU 2.0
+     */
+    UBool operator!=(const BreakIterator& rhs) const { return !operator==(rhs); }
+
+    /**
+     * Return a polymorphic copy of this object.  This is an abstract
+     * method which subclasses implement.
+     * @stable ICU 2.0
+     */
+    virtual BreakIterator* clone(void) const = 0;
+
+    /**
+     * Return a polymorphic class ID for this object. Different subclasses
+     * will return distinct unequal values.
+     * @stable ICU 2.0
+     */
+    virtual UClassID getDynamicClassID(void) const = 0;
+
+    /**
+     * Return a CharacterIterator over the text being analyzed.
+     * @stable ICU 2.0
+     */
+    virtual CharacterIterator& getText(void) const = 0;
+
+
+    /**
+      *  Get a UText for the text being analyzed.
+      *  The returned UText is a shallow clone of the UText used internally
+      *  by the break iterator implementation.  It can safely be used to
+      *  access the text without impacting any break iterator operations,
+      *  but the underlying text itself must not be altered.
+      *
+      * @param fillIn A UText to be filled in.  If NULL, a new UText will be
+      *           allocated to hold the result.
+      * @param status receives any error codes.
+      * @return   The current UText for this break iterator.  If an input
+      *           UText was provided, it will always be returned.
+      * @stable ICU 3.4
+      */
+     virtual UText *getUText(UText *fillIn, UErrorCode &status) const = 0;
+
+    /**
+     * Change the text over which this operates. The text boundary is
+     * reset to the start.
+     * @param text The UnicodeString used to change the text.
+     * @stable ICU 2.0
+     */
+    virtual void  setText(const UnicodeString &text) = 0;
+
+    /**
+     * Reset the break iterator to operate over the text represented by
+     * the UText.  The iterator position is reset to the start.
+     *
+     * This function makes a shallow clone of the supplied UText.  This means
+     * that the caller is free to immediately close or otherwise reuse the
+     * Utext that was passed as a parameter, but that the underlying text itself
+     * must not be altered while being referenced by the break iterator.
+     *
+     * @param text The UText used to change the text.
+     * @param status receives any error codes.
+     * @stable ICU 3.4
+     */
+    virtual void  setText(UText *text, UErrorCode &status) = 0;
+
+    /**
+     * Change the text over which this operates. The text boundary is
+     * reset to the start.
+     * Note that setText(UText *) provides similar functionality to this function,
+     * and is more efficient.
+     * @param it The CharacterIterator used to change the text.
+     * @stable ICU 2.0
+     */
+    virtual void  adoptText(CharacterIterator* it) = 0;
+
+    enum {
+        /**
+         * DONE is returned by previous() and next() after all valid
+         * boundaries have been returned.
+         * @stable ICU 2.0
+         */
+        DONE = (int32_t)-1
+    };
+
+    /**
+     * Return the index of the first character in the text being scanned.
+     * @stable ICU 2.0
+     */
+    virtual int32_t first(void) = 0;
+
+    /**
+     * Return the index immediately BEYOND the last character in the text being scanned.
+     * @stable ICU 2.0
+     */
+    virtual int32_t last(void) = 0;
+
+    /**
+     * Return the boundary preceding the current boundary.
+     * @return The character index of the previous text boundary or DONE if all
+     * boundaries have been returned.
+     * @stable ICU 2.0
+     */
+    virtual int32_t previous(void) = 0;
+
+    /**
+     * Return the boundary following the current boundary.
+     * @return The character index of the next text boundary or DONE if all
+     * boundaries have been returned.
+     * @stable ICU 2.0
+     */
+    virtual int32_t next(void) = 0;
+
+    /**
+     * Return character index of the current interator position within the text.
+     * @return The boundary most recently returned.
+     * @stable ICU 2.0
+     */
+    virtual int32_t current(void) const = 0;
+
+    /**
+     * Return the first boundary following the specified offset.
+     * The value returned is always greater than the offset or
+     * the value BreakIterator.DONE
+     * @param offset the offset to begin scanning.
+     * @return The first boundary after the specified offset.
+     * @stable ICU 2.0
+     */
+    virtual int32_t following(int32_t offset) = 0;
+
+    /**
+     * Return the first boundary preceding the specified offset.
+     * The value returned is always smaller than the offset or
+     * the value BreakIterator.DONE
+     * @param offset the offset to begin scanning.
+     * @return The first boundary before the specified offset.
+     * @stable ICU 2.0
+     */
+    virtual int32_t preceding(int32_t offset) = 0;
+
+    /**
+     * Return true if the specfied position is a boundary position.
+     * As a side effect, the current position of the iterator is set
+     * to the first boundary position at or following the specified offset.
+     * @param offset the offset to check.
+     * @return True if "offset" is a boundary position.
+     * @stable ICU 2.0
+     */
+    virtual UBool isBoundary(int32_t offset) = 0;
+
+    /**
+     * Return the nth boundary from the current boundary
+     * @param n which boundary to return.  A value of 0
+     * does nothing.  Negative values move to previous boundaries
+     * and positive values move to later boundaries.
+     * @return The index of the nth boundary from the current position, or
+     * DONE if there are fewer than |n| boundaries in the specfied direction.
+     * @stable ICU 2.0
+     */
+    virtual int32_t next(int32_t n) = 0;
+
+    /**
+     * Create BreakIterator for word-breaks using the given locale.
+     * Returns an instance of a BreakIterator implementing word breaks.
+     * WordBreak is useful for word selection (ex. double click)
+     * @param where the locale.
+     * @param status the error code
+     * @return A BreakIterator for word-breaks.  The UErrorCode& status
+     * parameter is used to return status information to the user.
+     * To check whether the construction succeeded or not, you should check
+     * the value of U_SUCCESS(err).  If you wish more detailed information, you
+     * can check for informational error results which still indicate success.
+     * U_USING_FALLBACK_WARNING indicates that a fall back locale was used.  For
+     * example, 'de_CH' was requested, but nothing was found there, so 'de' was
+     * used.  U_USING_DEFAULT_WARNING indicates that the default locale data was
+     * used; neither the requested locale nor any of its fall back locales
+     * could be found.
+     * The caller owns the returned object and is responsible for deleting it.
+     * @stable ICU 2.0
+     */
+    static BreakIterator* U_EXPORT2
+    createWordInstance(const Locale& where, UErrorCode& status);
+
+    /**
+     * Create BreakIterator for line-breaks using specified locale.
+     * Returns an instance of a BreakIterator implementing line breaks. Line
+     * breaks are logically possible line breaks, actual line breaks are
+     * usually determined based on display width.
+     * LineBreak is useful for word wrapping text.
+     * @param where the locale.
+     * @param status The error code.
+     * @return A BreakIterator for line-breaks.  The UErrorCode& status
+     * parameter is used to return status information to the user.
+     * To check whether the construction succeeded or not, you should check
+     * the value of U_SUCCESS(err).  If you wish more detailed information, you
+     * can check for informational error results which still indicate success.
+     * U_USING_FALLBACK_WARNING indicates that a fall back locale was used.  For
+     * example, 'de_CH' was requested, but nothing was found there, so 'de' was
+     * used.  U_USING_DEFAULT_WARNING indicates that the default locale data was
+     * used; neither the requested locale nor any of its fall back locales
+     * could be found.
+     * The caller owns the returned object and is responsible for deleting it.
+     * @stable ICU 2.0
+     */
+    static BreakIterator* U_EXPORT2
+    createLineInstance(const Locale& where, UErrorCode& status);
+
+    /**
+     * Create BreakIterator for character-breaks using specified locale
+     * Returns an instance of a BreakIterator implementing character breaks.
+     * Character breaks are boundaries of combining character sequences.
+     * @param where the locale.
+     * @param status The error code.
+     * @return A BreakIterator for character-breaks.  The UErrorCode& status
+     * parameter is used to return status information to the user.
+     * To check whether the construction succeeded or not, you should check
+     * the value of U_SUCCESS(err).  If you wish more detailed information, you
+     * can check for informational error results which still indicate success.
+     * U_USING_FALLBACK_WARNING indicates that a fall back locale was used.  For
+     * example, 'de_CH' was requested, but nothing was found there, so 'de' was
+     * used.  U_USING_DEFAULT_WARNING indicates that the default locale data was
+     * used; neither the requested locale nor any of its fall back locales
+     * could be found.
+     * The caller owns the returned object and is responsible for deleting it.
+     * @stable ICU 2.0
+     */
+    static BreakIterator* U_EXPORT2
+    createCharacterInstance(const Locale& where, UErrorCode& status);
+
+    /**
+     * Create BreakIterator for sentence-breaks using specified locale
+     * Returns an instance of a BreakIterator implementing sentence breaks.
+     * @param where the locale.
+     * @param status The error code.
+     * @return A BreakIterator for sentence-breaks.  The UErrorCode& status
+     * parameter is used to return status information to the user.
+     * To check whether the construction succeeded or not, you should check
+     * the value of U_SUCCESS(err).  If you wish more detailed information, you
+     * can check for informational error results which still indicate success.
+     * U_USING_FALLBACK_WARNING indicates that a fall back locale was used.  For
+     * example, 'de_CH' was requested, but nothing was found there, so 'de' was
+     * used.  U_USING_DEFAULT_WARNING indicates that the default locale data was
+     * used; neither the requested locale nor any of its fall back locales
+     * could be found.
+     * The caller owns the returned object and is responsible for deleting it.
+     * @stable ICU 2.0
+     */
+    static BreakIterator* U_EXPORT2
+    createSentenceInstance(const Locale& where, UErrorCode& status);
+
+    /**
+     * Create BreakIterator for title-casing breaks using the specified locale
+     * Returns an instance of a BreakIterator implementing title breaks.
+     * The iterator returned locates title boundaries as described for
+     * Unicode 3.2 only. For Unicode 4.0 and above title boundary iteration,
+     * please use Word Boundary iterator.{@link #createWordInstance }
+     *
+     * @param where the locale.
+     * @param status The error code.
+     * @return A BreakIterator for title-breaks.  The UErrorCode& status
+     * parameter is used to return status information to the user.
+     * To check whether the construction succeeded or not, you should check
+     * the value of U_SUCCESS(err).  If you wish more detailed information, you
+     * can check for informational error results which still indicate success.
+     * U_USING_FALLBACK_WARNING indicates that a fall back locale was used.  For
+     * example, 'de_CH' was requested, but nothing was found there, so 'de' was
+     * used.  U_USING_DEFAULT_WARNING indicates that the default locale data was
+     * used; neither the requested locale nor any of its fall back locales
+     * could be found.
+     * The caller owns the returned object and is responsible for deleting it.
+     * @stable ICU 2.1
+     */
+    static BreakIterator* U_EXPORT2
+    createTitleInstance(const Locale& where, UErrorCode& status);
+
+    /**
+     * Get the set of Locales for which TextBoundaries are installed.
+     * <p><b>Note:</b> this will not return locales added through the register
+     * call. To see the registered locales too, use the getAvailableLocales
+     * function that returns a StringEnumeration object </p>
+     * @param count the output parameter of number of elements in the locale list
+     * @return available locales
+     * @stable ICU 2.0
+     */
+    static const Locale* U_EXPORT2 getAvailableLocales(int32_t& count);
+
+    /**
+     * Get name of the object for the desired Locale, in the desired langauge.
+     * @param objectLocale must be from getAvailableLocales.
+     * @param displayLocale specifies the desired locale for output.
+     * @param name the fill-in parameter of the return value
+     * Uses best match.
+     * @return user-displayable name
+     * @stable ICU 2.0
+     */
+    static UnicodeString& U_EXPORT2 getDisplayName(const Locale& objectLocale,
+                                         const Locale& displayLocale,
+                                         UnicodeString& name);
+
+    /**
+     * Get name of the object for the desired Locale, in the langauge of the
+     * default locale.
+     * @param objectLocale must be from getMatchingLocales
+     * @param name the fill-in parameter of the return value
+     * @return user-displayable name
+     * @stable ICU 2.0
+     */
+    static UnicodeString& U_EXPORT2 getDisplayName(const Locale& objectLocale,
+                                         UnicodeString& name);
+
+    /**
+     * Thread safe client-buffer-based cloning operation
+     *    Do NOT call delete on a safeclone, since 'new' is not used to create it.
+     * @param stackBuffer user allocated space for the new clone. If NULL new memory will be allocated.
+     * If buffer is not large enough, new memory will be allocated.
+     * @param BufferSize reference to size of allocated space.
+     * If BufferSize == 0, a sufficient size for use in cloning will
+     * be returned ('pre-flighting')
+     * If BufferSize is not enough for a stack-based safe clone,
+     * new memory will be allocated.
+     * @param status to indicate whether the operation went on smoothly or there were errors
+     *  An informational status value, U_SAFECLONE_ALLOCATED_ERROR, is used if any allocations were
+     *  necessary.
+     * @return pointer to the new clone
+     *
+     * @stable ICU 2.0
+     */
+    virtual BreakIterator *  createBufferClone(void *stackBuffer,
+                                               int32_t &BufferSize,
+                                               UErrorCode &status) = 0;
+
+    /**
+     *   Determine whether the BreakIterator was created in user memory by
+     *   createBufferClone(), and thus should not be deleted.  Such objects
+     *   must be closed by an explicit call to the destructor (not delete).
+     *  @stable ICU 2.0
+     */
+    inline UBool isBufferClone(void);
+
+#if !UCONFIG_NO_SERVICE
+    /**
+     * Register a new break iterator of the indicated kind, to use in the given locale.
+     * The break iterator will be adopted.  Clones of the iterator will be returned
+     * if a request for a break iterator of the given kind matches or falls back to
+     * this locale.
+     * @param toAdopt the BreakIterator instance to be adopted
+     * @param locale the Locale for which this instance is to be registered
+     * @param kind the type of iterator for which this instance is to be registered
+     * @param status the in/out status code, no special meanings are assigned
+     * @return a registry key that can be used to unregister this instance
+     * @stable ICU 2.4
+     */
+    static URegistryKey U_EXPORT2 registerInstance(BreakIterator* toAdopt,
+                                        const Locale& locale,
+                                        UBreakIteratorType kind,
+                                        UErrorCode& status);
+
+    /**
+     * Unregister a previously-registered BreakIterator using the key returned from the
+     * register call.  Key becomes invalid after a successful call and should not be used again.
+     * The BreakIterator corresponding to the key will be deleted.
+     * @param key the registry key returned by a previous call to registerInstance
+     * @param status the in/out status code, no special meanings are assigned
+     * @return TRUE if the iterator for the key was successfully unregistered
+     * @stable ICU 2.4
+     */
+    static UBool U_EXPORT2 unregister(URegistryKey key, UErrorCode& status);
+
+    /**
+     * Return a StringEnumeration over the locales available at the time of the call,
+     * including registered locales.
+     * @return a StringEnumeration over the locales available at the time of the call
+     * @stable ICU 2.4
+     */
+    static StringEnumeration* U_EXPORT2 getAvailableLocales(void);
+#endif
+
+    /**
+     * Returns the locale for this break iterator. Two flavors are available: valid and
+     * actual locale.
+     * @stable ICU 2.8
+     */
+    Locale getLocale(ULocDataLocaleType type, UErrorCode& status) const;
+
+    /** Get the locale for this break iterator object. You can choose between valid and actual locale.
+     *  @param type type of the locale we're looking for (valid or actual)
+     *  @param status error code for the operation
+     *  @return the locale
+     *  @internal
+     */
+    const char *getLocaleID(ULocDataLocaleType type, UErrorCode& status) const;
+
+ private:
+    static BreakIterator* buildInstance(const Locale& loc, const char *type, int32_t kind, UErrorCode& status);
+    static BreakIterator* createInstance(const Locale& loc, int32_t kind, UErrorCode& status);
+    static BreakIterator* makeInstance(const Locale& loc, int32_t kind, UErrorCode& status);
+
+    friend class ICUBreakIteratorFactory;
+    friend class ICUBreakIteratorService;
+
+protected:
+    /** @internal */
+    BreakIterator();
+    /** @internal */
+    UBool fBufferClone;
+    /** @internal */
+    BreakIterator (const BreakIterator &other) : UObject(other), fBufferClone(FALSE) {}
+
+private:
+
+    /** @internal */
+    char actualLocale[ULOC_FULLNAME_CAPACITY];
+    char validLocale[ULOC_FULLNAME_CAPACITY];
+
+    /**
+     * The assignment operator has no real implementation.
+     * It's provided to make the compiler happy. Do not call.
+     */
+    BreakIterator& operator=(const BreakIterator&);
+};
+
+inline UBool BreakIterator::isBufferClone()
+{
+    return fBufferClone;
+}
+
+U_NAMESPACE_END
+
+#endif /* #if !UCONFIG_NO_BREAK_ITERATION */
+
+#endif // _BRKITER
+//eof
+


[18/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/js/libs/backbone.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/js/libs/backbone.js b/apps/fauxton/assets/js/libs/backbone.js
deleted file mode 100644
index 3512d42..0000000
--- a/apps/fauxton/assets/js/libs/backbone.js
+++ /dev/null
@@ -1,1571 +0,0 @@
-//     Backbone.js 1.0.0
-
-//     (c) 2010-2013 Jeremy Ashkenas, DocumentCloud Inc.
-//     Backbone may be freely distributed under the MIT license.
-//     For all details and documentation:
-//     http://backbonejs.org
-
-(function(){
-
-  // Initial Setup
-  // -------------
-
-  // Save a reference to the global object (`window` in the browser, `exports`
-  // on the server).
-  var root = this;
-
-  // Save the previous value of the `Backbone` variable, so that it can be
-  // restored later on, if `noConflict` is used.
-  var previousBackbone = root.Backbone;
-
-  // Create local references to array methods we'll want to use later.
-  var array = [];
-  var push = array.push;
-  var slice = array.slice;
-  var splice = array.splice;
-
-  // The top-level namespace. All public Backbone classes and modules will
-  // be attached to this. Exported for both the browser and the server.
-  var Backbone;
-  if (typeof exports !== 'undefined') {
-    Backbone = exports;
-  } else {
-    Backbone = root.Backbone = {};
-  }
-
-  // Current version of the library. Keep in sync with `package.json`.
-  Backbone.VERSION = '1.0.0';
-
-  // Require Underscore, if we're on the server, and it's not already present.
-  var _ = root._;
-  if (!_ && (typeof require !== 'undefined')) _ = require('underscore');
-
-  // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns
-  // the `$` variable.
-  Backbone.$ = root.jQuery || root.Zepto || root.ender || root.$;
-
-  // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
-  // to its previous owner. Returns a reference to this Backbone object.
-  Backbone.noConflict = function() {
-    root.Backbone = previousBackbone;
-    return this;
-  };
-
-  // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
-  // will fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and
-  // set a `X-Http-Method-Override` header.
-  Backbone.emulateHTTP = false;
-
-  // Turn on `emulateJSON` to support legacy servers that can't deal with direct
-  // `application/json` requests ... will encode the body as
-  // `application/x-www-form-urlencoded` instead and will send the model in a
-  // form param named `model`.
-  Backbone.emulateJSON = false;
-
-  // Backbone.Events
-  // ---------------
-
-  // A module that can be mixed in to *any object* in order to provide it with
-  // custom events. You may bind with `on` or remove with `off` callback
-  // functions to an event; `trigger`-ing an event fires all callbacks in
-  // succession.
-  //
-  //     var object = {};
-  //     _.extend(object, Backbone.Events);
-  //     object.on('expand', function(){ alert('expanded'); });
-  //     object.trigger('expand');
-  //
-  var Events = Backbone.Events = {
-
-    // Bind an event to a `callback` function. Passing `"all"` will bind
-    // the callback to all events fired.
-    on: function(name, callback, context) {
-      if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this;
-      this._events || (this._events = {});
-      var events = this._events[name] || (this._events[name] = []);
-      events.push({callback: callback, context: context, ctx: context || this});
-      return this;
-    },
-
-    // Bind an event to only be triggered a single time. After the first time
-    // the callback is invoked, it will be removed.
-    once: function(name, callback, context) {
-      if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this;
-      var self = this;
-      var once = _.once(function() {
-        self.off(name, once);
-        callback.apply(this, arguments);
-      });
-      once._callback = callback;
-      return this.on(name, once, context);
-    },
-
-    // Remove one or many callbacks. If `context` is null, removes all
-    // callbacks with that function. If `callback` is null, removes all
-    // callbacks for the event. If `name` is null, removes all bound
-    // callbacks for all events.
-    off: function(name, callback, context) {
-      var retain, ev, events, names, i, l, j, k;
-      if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this;
-      if (!name && !callback && !context) {
-        this._events = {};
-        return this;
-      }
-
-      names = name ? [name] : _.keys(this._events);
-      for (i = 0, l = names.length; i < l; i++) {
-        name = names[i];
-        if (events = this._events[name]) {
-          this._events[name] = retain = [];
-          if (callback || context) {
-            for (j = 0, k = events.length; j < k; j++) {
-              ev = events[j];
-              if ((callback && callback !== ev.callback && callback !== ev.callback._callback) ||
-                  (context && context !== ev.context)) {
-                retain.push(ev);
-              }
-            }
-          }
-          if (!retain.length) delete this._events[name];
-        }
-      }
-
-      return this;
-    },
-
-    // Trigger one or many events, firing all bound callbacks. Callbacks are
-    // passed the same arguments as `trigger` is, apart from the event name
-    // (unless you're listening on `"all"`, which will cause your callback to
-    // receive the true name of the event as the first argument).
-    trigger: function(name) {
-      if (!this._events) return this;
-      var args = slice.call(arguments, 1);
-      if (!eventsApi(this, 'trigger', name, args)) return this;
-      var events = this._events[name];
-      var allEvents = this._events.all;
-      if (events) triggerEvents(events, args);
-      if (allEvents) triggerEvents(allEvents, arguments);
-      return this;
-    },
-
-    // Tell this object to stop listening to either specific events ... or
-    // to every object it's currently listening to.
-    stopListening: function(obj, name, callback) {
-      var listeners = this._listeners;
-      if (!listeners) return this;
-      var deleteListener = !name && !callback;
-      if (typeof name === 'object') callback = this;
-      if (obj) (listeners = {})[obj._listenerId] = obj;
-      for (var id in listeners) {
-        listeners[id].off(name, callback, this);
-        if (deleteListener) delete this._listeners[id];
-      }
-      return this;
-    }
-
-  };
-
-  // Regular expression used to split event strings.
-  var eventSplitter = /\s+/;
-
-  // Implement fancy features of the Events API such as multiple event
-  // names `"change blur"` and jQuery-style event maps `{change: action}`
-  // in terms of the existing API.
-  var eventsApi = function(obj, action, name, rest) {
-    if (!name) return true;
-
-    // Handle event maps.
-    if (typeof name === 'object') {
-      for (var key in name) {
-        obj[action].apply(obj, [key, name[key]].concat(rest));
-      }
-      return false;
-    }
-
-    // Handle space separated event names.
-    if (eventSplitter.test(name)) {
-      var names = name.split(eventSplitter);
-      for (var i = 0, l = names.length; i < l; i++) {
-        obj[action].apply(obj, [names[i]].concat(rest));
-      }
-      return false;
-    }
-
-    return true;
-  };
-
-  // A difficult-to-believe, but optimized internal dispatch function for
-  // triggering events. Tries to keep the usual cases speedy (most internal
-  // Backbone events have 3 arguments).
-  var triggerEvents = function(events, args) {
-    var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2];
-    switch (args.length) {
-      case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return;
-      case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return;
-      case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return;
-      case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return;
-      default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args);
-    }
-  };
-
-  var listenMethods = {listenTo: 'on', listenToOnce: 'once'};
-
-  // Inversion-of-control versions of `on` and `once`. Tell *this* object to
-  // listen to an event in another object ... keeping track of what it's
-  // listening to.
-  _.each(listenMethods, function(implementation, method) {
-    Events[method] = function(obj, name, callback) {
-      var listeners = this._listeners || (this._listeners = {});
-      var id = obj._listenerId || (obj._listenerId = _.uniqueId('l'));
-      listeners[id] = obj;
-      if (typeof name === 'object') callback = this;
-      obj[implementation](name, callback, this);
-      return this;
-    };
-  });
-
-  // Aliases for backwards compatibility.
-  Events.bind   = Events.on;
-  Events.unbind = Events.off;
-
-  // Allow the `Backbone` object to serve as a global event bus, for folks who
-  // want global "pubsub" in a convenient place.
-  _.extend(Backbone, Events);
-
-  // Backbone.Model
-  // --------------
-
-  // Backbone **Models** are the basic data object in the framework --
-  // frequently representing a row in a table in a database on your server.
-  // A discrete chunk of data and a bunch of useful, related methods for
-  // performing computations and transformations on that data.
-
-  // Create a new model with the specified attributes. A client id (`cid`)
-  // is automatically generated and assigned for you.
-  var Model = Backbone.Model = function(attributes, options) {
-    var defaults;
-    var attrs = attributes || {};
-    options || (options = {});
-    this.cid = _.uniqueId('c');
-    this.attributes = {};
-    _.extend(this, _.pick(options, modelOptions));
-    if (options.parse) attrs = this.parse(attrs, options) || {};
-    if (defaults = _.result(this, 'defaults')) {
-      attrs = _.defaults({}, attrs, defaults);
-    }
-    this.set(attrs, options);
-    this.changed = {};
-    this.initialize.apply(this, arguments);
-  };
-
-  // A list of options to be attached directly to the model, if provided.
-  var modelOptions = ['url', 'urlRoot', 'collection'];
-
-  // Attach all inheritable methods to the Model prototype.
-  _.extend(Model.prototype, Events, {
-
-    // A hash of attributes whose current and previous value differ.
-    changed: null,
-
-    // The value returned during the last failed validation.
-    validationError: null,
-
-    // The default name for the JSON `id` attribute is `"id"`. MongoDB and
-    // CouchDB users may want to set this to `"_id"`.
-    idAttribute: 'id',
-
-    // Initialize is an empty function by default. Override it with your own
-    // initialization logic.
-    initialize: function(){},
-
-    // Return a copy of the model's `attributes` object.
-    toJSON: function(options) {
-      return _.clone(this.attributes);
-    },
-
-    // Proxy `Backbone.sync` by default -- but override this if you need
-    // custom syncing semantics for *this* particular model.
-    sync: function() {
-      return Backbone.sync.apply(this, arguments);
-    },
-
-    // Get the value of an attribute.
-    get: function(attr) {
-      return this.attributes[attr];
-    },
-
-    // Get the HTML-escaped value of an attribute.
-    escape: function(attr) {
-      return _.escape(this.get(attr));
-    },
-
-    // Returns `true` if the attribute contains a value that is not null
-    // or undefined.
-    has: function(attr) {
-      return this.get(attr) != null;
-    },
-
-    // Set a hash of model attributes on the object, firing `"change"`. This is
-    // the core primitive operation of a model, updating the data and notifying
-    // anyone who needs to know about the change in state. The heart of the beast.
-    set: function(key, val, options) {
-      var attr, attrs, unset, changes, silent, changing, prev, current;
-      if (key == null) return this;
-
-      // Handle both `"key", value` and `{key: value}` -style arguments.
-      if (typeof key === 'object') {
-        attrs = key;
-        options = val;
-      } else {
-        (attrs = {})[key] = val;
-      }
-
-      options || (options = {});
-
-      // Run validation.
-      if (!this._validate(attrs, options)) return false;
-
-      // Extract attributes and options.
-      unset           = options.unset;
-      silent          = options.silent;
-      changes         = [];
-      changing        = this._changing;
-      this._changing  = true;
-
-      if (!changing) {
-        this._previousAttributes = _.clone(this.attributes);
-        this.changed = {};
-      }
-      current = this.attributes, prev = this._previousAttributes;
-
-      // Check for changes of `id`.
-      if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
-
-      // For each `set` attribute, update or delete the current value.
-      for (attr in attrs) {
-        val = attrs[attr];
-        if (!_.isEqual(current[attr], val)) changes.push(attr);
-        if (!_.isEqual(prev[attr], val)) {
-          this.changed[attr] = val;
-        } else {
-          delete this.changed[attr];
-        }
-        unset ? delete current[attr] : current[attr] = val;
-      }
-
-      // Trigger all relevant attribute changes.
-      if (!silent) {
-        if (changes.length) this._pending = true;
-        for (var i = 0, l = changes.length; i < l; i++) {
-          this.trigger('change:' + changes[i], this, current[changes[i]], options);
-        }
-      }
-
-      // You might be wondering why there's a `while` loop here. Changes can
-      // be recursively nested within `"change"` events.
-      if (changing) return this;
-      if (!silent) {
-        while (this._pending) {
-          this._pending = false;
-          this.trigger('change', this, options);
-        }
-      }
-      this._pending = false;
-      this._changing = false;
-      return this;
-    },
-
-    // Remove an attribute from the model, firing `"change"`. `unset` is a noop
-    // if the attribute doesn't exist.
-    unset: function(attr, options) {
-      return this.set(attr, void 0, _.extend({}, options, {unset: true}));
-    },
-
-    // Clear all attributes on the model, firing `"change"`.
-    clear: function(options) {
-      var attrs = {};
-      for (var key in this.attributes) attrs[key] = void 0;
-      return this.set(attrs, _.extend({}, options, {unset: true}));
-    },
-
-    // Determine if the model has changed since the last `"change"` event.
-    // If you specify an attribute name, determine if that attribute has changed.
-    hasChanged: function(attr) {
-      if (attr == null) return !_.isEmpty(this.changed);
-      return _.has(this.changed, attr);
-    },
-
-    // Return an object containing all the attributes that have changed, or
-    // false if there are no changed attributes. Useful for determining what
-    // parts of a view need to be updated and/or what attributes need to be
-    // persisted to the server. Unset attributes will be set to undefined.
-    // You can also pass an attributes object to diff against the model,
-    // determining if there *would be* a change.
-    changedAttributes: function(diff) {
-      if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
-      var val, changed = false;
-      var old = this._changing ? this._previousAttributes : this.attributes;
-      for (var attr in diff) {
-        if (_.isEqual(old[attr], (val = diff[attr]))) continue;
-        (changed || (changed = {}))[attr] = val;
-      }
-      return changed;
-    },
-
-    // Get the previous value of an attribute, recorded at the time the last
-    // `"change"` event was fired.
-    previous: function(attr) {
-      if (attr == null || !this._previousAttributes) return null;
-      return this._previousAttributes[attr];
-    },
-
-    // Get all of the attributes of the model at the time of the previous
-    // `"change"` event.
-    previousAttributes: function() {
-      return _.clone(this._previousAttributes);
-    },
-
-    // Fetch the model from the server. If the server's representation of the
-    // model differs from its current attributes, they will be overridden,
-    // triggering a `"change"` event.
-    fetch: function(options) {
-      options = options ? _.clone(options) : {};
-      if (options.parse === void 0) options.parse = true;
-      var model = this;
-      var success = options.success;
-      options.success = function(resp) {
-        if (!model.set(model.parse(resp, options), options)) return false;
-        if (success) success(model, resp, options);
-        model.trigger('sync', model, resp, options);
-      };
-      wrapError(this, options);
-      return this.sync('read', this, options);
-    },
-
-    // Set a hash of model attributes, and sync the model to the server.
-    // If the server returns an attributes hash that differs, the model's
-    // state will be `set` again.
-    save: function(key, val, options) {
-      var attrs, method, xhr, attributes = this.attributes;
-
-      // Handle both `"key", value` and `{key: value}` -style arguments.
-      if (key == null || typeof key === 'object') {
-        attrs = key;
-        options = val;
-      } else {
-        (attrs = {})[key] = val;
-      }
-
-      // If we're not waiting and attributes exist, save acts as `set(attr).save(null, opts)`.
-      if (attrs && (!options || !options.wait) && !this.set(attrs, options)) return false;
-
-      options = _.extend({validate: true}, options);
-
-      // Do not persist invalid models.
-      if (!this._validate(attrs, options)) return false;
-
-      // Set temporary attributes if `{wait: true}`.
-      if (attrs && options.wait) {
-        this.attributes = _.extend({}, attributes, attrs);
-      }
-
-      // After a successful server-side save, the client is (optionally)
-      // updated with the server-side state.
-      if (options.parse === void 0) options.parse = true;
-      var model = this;
-      var success = options.success;
-      options.success = function(resp) {
-        // Ensure attributes are restored during synchronous saves.
-        model.attributes = attributes;
-        var serverAttrs = model.parse(resp, options);
-        if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs);
-        if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) {
-          return false;
-        }
-        if (success) success(model, resp, options);
-        model.trigger('sync', model, resp, options);
-      };
-      wrapError(this, options);
-
-      method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');
-      if (method === 'patch') options.attrs = attrs;
-      xhr = this.sync(method, this, options);
-
-      // Restore attributes.
-      if (attrs && options.wait) this.attributes = attributes;
-
-      return xhr;
-    },
-
-    // Destroy this model on the server if it was already persisted.
-    // Optimistically removes the model from its collection, if it has one.
-    // If `wait: true` is passed, waits for the server to respond before removal.
-    destroy: function(options) {
-      options = options ? _.clone(options) : {};
-      var model = this;
-      var success = options.success;
-
-      var destroy = function() {
-        model.trigger('destroy', model, model.collection, options);
-      };
-
-      options.success = function(resp) {
-        if (options.wait || model.isNew()) destroy();
-        if (success) success(model, resp, options);
-        if (!model.isNew()) model.trigger('sync', model, resp, options);
-      };
-
-      if (this.isNew()) {
-        options.success();
-        return false;
-      }
-      wrapError(this, options);
-
-      var xhr = this.sync('delete', this, options);
-      if (!options.wait) destroy();
-      return xhr;
-    },
-
-    // Default URL for the model's representation on the server -- if you're
-    // using Backbone's restful methods, override this to change the endpoint
-    // that will be called.
-    url: function() {
-      var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError();
-      if (this.isNew()) return base;
-      return base + (base.charAt(base.length - 1) === '/' ? '' : '/') + encodeURIComponent(this.id);
-    },
-
-    // **parse** converts a response into the hash of attributes to be `set` on
-    // the model. The default implementation is just to pass the response along.
-    parse: function(resp, options) {
-      return resp;
-    },
-
-    // Create a new model with identical attributes to this one.
-    clone: function() {
-      return new this.constructor(this.attributes);
-    },
-
-    // A model is new if it has never been saved to the server, and lacks an id.
-    isNew: function() {
-      return this.id == null;
-    },
-
-    // Check if the model is currently in a valid state.
-    isValid: function(options) {
-      return this._validate({}, _.extend(options || {}, { validate: true }));
-    },
-
-    // Run validation against the next complete set of model attributes,
-    // returning `true` if all is well. Otherwise, fire an `"invalid"` event.
-    _validate: function(attrs, options) {
-      if (!options.validate || !this.validate) return true;
-      attrs = _.extend({}, this.attributes, attrs);
-      var error = this.validationError = this.validate(attrs, options) || null;
-      if (!error) return true;
-      this.trigger('invalid', this, error, _.extend(options || {}, {validationError: error}));
-      return false;
-    }
-
-  });
-
-  // Underscore methods that we want to implement on the Model.
-  var modelMethods = ['keys', 'values', 'pairs', 'invert', 'pick', 'omit'];
-
-  // Mix in each Underscore method as a proxy to `Model#attributes`.
-  _.each(modelMethods, function(method) {
-    Model.prototype[method] = function() {
-      var args = slice.call(arguments);
-      args.unshift(this.attributes);
-      return _[method].apply(_, args);
-    };
-  });
-
-  // Backbone.Collection
-  // -------------------
-
-  // If models tend to represent a single row of data, a Backbone Collection is
-  // more analagous to a table full of data ... or a small slice or page of that
-  // table, or a collection of rows that belong together for a particular reason
-  // -- all of the messages in this particular folder, all of the documents
-  // belonging to this particular author, and so on. Collections maintain
-  // indexes of their models, both in order, and for lookup by `id`.
-
-  // Create a new **Collection**, perhaps to contain a specific type of `model`.
-  // If a `comparator` is specified, the Collection will maintain
-  // its models in sort order, as they're added and removed.
-  var Collection = Backbone.Collection = function(models, options) {
-    options || (options = {});
-    if (options.url) this.url = options.url;
-    if (options.model) this.model = options.model;
-    if (options.comparator !== void 0) this.comparator = options.comparator;
-    this._reset();
-    this.initialize.apply(this, arguments);
-    if (models) this.reset(models, _.extend({silent: true}, options));
-  };
-
-  // Default options for `Collection#set`.
-  var setOptions = {add: true, remove: true, merge: true};
-  var addOptions = {add: true, merge: false, remove: false};
-
-  // Define the Collection's inheritable methods.
-  _.extend(Collection.prototype, Events, {
-
-    // The default model for a collection is just a **Backbone.Model**.
-    // This should be overridden in most cases.
-    model: Model,
-
-    // Initialize is an empty function by default. Override it with your own
-    // initialization logic.
-    initialize: function(){},
-
-    // The JSON representation of a Collection is an array of the
-    // models' attributes.
-    toJSON: function(options) {
-      return this.map(function(model){ return model.toJSON(options); });
-    },
-
-    // Proxy `Backbone.sync` by default.
-    sync: function() {
-      return Backbone.sync.apply(this, arguments);
-    },
-
-    // Add a model, or list of models to the set.
-    add: function(models, options) {
-      return this.set(models, _.defaults(options || {}, addOptions));
-    },
-
-    // Remove a model, or a list of models from the set.
-    remove: function(models, options) {
-      models = _.isArray(models) ? models.slice() : [models];
-      options || (options = {});
-      var i, l, index, model;
-      for (i = 0, l = models.length; i < l; i++) {
-        model = this.get(models[i]);
-        if (!model) continue;
-        delete this._byId[model.id];
-        delete this._byId[model.cid];
-        index = this.indexOf(model);
-        this.models.splice(index, 1);
-        this.length--;
-        if (!options.silent) {
-          options.index = index;
-          model.trigger('remove', model, this, options);
-        }
-        this._removeReference(model);
-      }
-      return this;
-    },
-
-    // Update a collection by `set`-ing a new list of models, adding new ones,
-    // removing models that are no longer present, and merging models that
-    // already exist in the collection, as necessary. Similar to **Model#set**,
-    // the core operation for updating the data contained by the collection.
-    set: function(models, options) {
-      options = _.defaults(options || {}, setOptions);
-      if (options.parse) models = this.parse(models, options);
-      if (!_.isArray(models)) models = models ? [models] : [];
-      var i, l, model, attrs, existing, sort;
-      var at = options.at;
-      var sortable = this.comparator && (at == null) && options.sort !== false;
-      var sortAttr = _.isString(this.comparator) ? this.comparator : null;
-      var toAdd = [], toRemove = [], modelMap = {};
-
-      // Turn bare objects into model references, and prevent invalid models
-      // from being added.
-      for (i = 0, l = models.length; i < l; i++) {
-        if (!(model = this._prepareModel(models[i], options))) continue;
-
-        // If a duplicate is found, prevent it from being added and
-        // optionally merge it into the existing model.
-        if (existing = this.get(model)) {
-          if (options.remove) modelMap[existing.cid] = true;
-          if (options.merge) {
-            existing.set(model.attributes, options);
-            if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true;
-          }
-
-        // This is a new model, push it to the `toAdd` list.
-        } else if (options.add) {
-          toAdd.push(model);
-
-          // Listen to added models' events, and index models for lookup by
-          // `id` and by `cid`.
-          model.on('all', this._onModelEvent, this);
-          this._byId[model.cid] = model;
-          if (model.id != null) this._byId[model.id] = model;
-        }
-      }
-
-      // Remove nonexistent models if appropriate.
-      if (options.remove) {
-        for (i = 0, l = this.length; i < l; ++i) {
-          if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model);
-        }
-        if (toRemove.length) this.remove(toRemove, options);
-      }
-
-      // See if sorting is needed, update `length` and splice in new models.
-      if (toAdd.length) {
-        if (sortable) sort = true;
-        this.length += toAdd.length;
-        if (at != null) {
-          splice.apply(this.models, [at, 0].concat(toAdd));
-        } else {
-          push.apply(this.models, toAdd);
-        }
-      }
-
-      // Silently sort the collection if appropriate.
-      if (sort) this.sort({silent: true});
-
-      if (options.silent) return this;
-
-      // Trigger `add` events.
-      for (i = 0, l = toAdd.length; i < l; i++) {
-        (model = toAdd[i]).trigger('add', model, this, options);
-      }
-
-      // Trigger `sort` if the collection was sorted.
-      if (sort) this.trigger('sort', this, options);
-      return this;
-    },
-
-    // When you have more items than you want to add or remove individually,
-    // you can reset the entire set with a new list of models, without firing
-    // any granular `add` or `remove` events. Fires `reset` when finished.
-    // Useful for bulk operations and optimizations.
-    reset: function(models, options) {
-      options || (options = {});
-      for (var i = 0, l = this.models.length; i < l; i++) {
-        this._removeReference(this.models[i]);
-      }
-      options.previousModels = this.models;
-      this._reset();
-      this.add(models, _.extend({silent: true}, options));
-      if (!options.silent) this.trigger('reset', this, options);
-      return this;
-    },
-
-    // Add a model to the end of the collection.
-    push: function(model, options) {
-      model = this._prepareModel(model, options);
-      this.add(model, _.extend({at: this.length}, options));
-      return model;
-    },
-
-    // Remove a model from the end of the collection.
-    pop: function(options) {
-      var model = this.at(this.length - 1);
-      this.remove(model, options);
-      return model;
-    },
-
-    // Add a model to the beginning of the collection.
-    unshift: function(model, options) {
-      model = this._prepareModel(model, options);
-      this.add(model, _.extend({at: 0}, options));
-      return model;
-    },
-
-    // Remove a model from the beginning of the collection.
-    shift: function(options) {
-      var model = this.at(0);
-      this.remove(model, options);
-      return model;
-    },
-
-    // Slice out a sub-array of models from the collection.
-    slice: function(begin, end) {
-      return this.models.slice(begin, end);
-    },
-
-    // Get a model from the set by id.
-    get: function(obj) {
-      if (obj == null) return void 0;
-      return this._byId[obj.id != null ? obj.id : obj.cid || obj];
-    },
-
-    // Get the model at the given index.
-    at: function(index) {
-      return this.models[index];
-    },
-
-    // Return models with matching attributes. Useful for simple cases of
-    // `filter`.
-    where: function(attrs, first) {
-      if (_.isEmpty(attrs)) return first ? void 0 : [];
-      return this[first ? 'find' : 'filter'](function(model) {
-        for (var key in attrs) {
-          if (attrs[key] !== model.get(key)) return false;
-        }
-        return true;
-      });
-    },
-
-    // Return the first model with matching attributes. Useful for simple cases
-    // of `find`.
-    findWhere: function(attrs) {
-      return this.where(attrs, true);
-    },
-
-    // Force the collection to re-sort itself. You don't need to call this under
-    // normal circumstances, as the set will maintain sort order as each item
-    // is added.
-    sort: function(options) {
-      if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
-      options || (options = {});
-
-      // Run sort based on type of `comparator`.
-      if (_.isString(this.comparator) || this.comparator.length === 1) {
-        this.models = this.sortBy(this.comparator, this);
-      } else {
-        this.models.sort(_.bind(this.comparator, this));
-      }
-
-      if (!options.silent) this.trigger('sort', this, options);
-      return this;
-    },
-
-    // Figure out the smallest index at which a model should be inserted so as
-    // to maintain order.
-    sortedIndex: function(model, value, context) {
-      value || (value = this.comparator);
-      var iterator = _.isFunction(value) ? value : function(model) {
-        return model.get(value);
-      };
-      return _.sortedIndex(this.models, model, iterator, context);
-    },
-
-    // Pluck an attribute from each model in the collection.
-    pluck: function(attr) {
-      return _.invoke(this.models, 'get', attr);
-    },
-
-    // Fetch the default set of models for this collection, resetting the
-    // collection when they arrive. If `reset: true` is passed, the response
-    // data will be passed through the `reset` method instead of `set`.
-    fetch: function(options) {
-      options = options ? _.clone(options) : {};
-      if (options.parse === void 0) options.parse = true;
-      var success = options.success;
-      var collection = this;
-      options.success = function(resp) {
-        var method = options.reset ? 'reset' : 'set';
-        collection[method](resp, options);
-        if (success) success(collection, resp, options);
-        collection.trigger('sync', collection, resp, options);
-      };
-      wrapError(this, options);
-      return this.sync('read', this, options);
-    },
-
-    // Create a new instance of a model in this collection. Add the model to the
-    // collection immediately, unless `wait: true` is passed, in which case we
-    // wait for the server to agree.
-    create: function(model, options) {
-      options = options ? _.clone(options) : {};
-      if (!(model = this._prepareModel(model, options))) return false;
-      if (!options.wait) this.add(model, options);
-      var collection = this;
-      var success = options.success;
-      options.success = function(resp) {
-        if (options.wait) collection.add(model, options);
-        if (success) success(model, resp, options);
-      };
-      model.save(null, options);
-      return model;
-    },
-
-    // **parse** converts a response into a list of models to be added to the
-    // collection. The default implementation is just to pass it through.
-    parse: function(resp, options) {
-      return resp;
-    },
-
-    // Create a new collection with an identical list of models as this one.
-    clone: function() {
-      return new this.constructor(this.models);
-    },
-
-    // Private method to reset all internal state. Called when the collection
-    // is first initialized or reset.
-    _reset: function() {
-      this.length = 0;
-      this.models = [];
-      this._byId  = {};
-    },
-
-    // Prepare a hash of attributes (or other model) to be added to this
-    // collection.
-    _prepareModel: function(attrs, options) {
-      if (attrs instanceof Model) {
-        if (!attrs.collection) attrs.collection = this;
-        return attrs;
-      }
-      options || (options = {});
-      options.collection = this;
-      var model = new this.model(attrs, options);
-      if (!model._validate(attrs, options)) {
-        this.trigger('invalid', this, attrs, options);
-        return false;
-      }
-      return model;
-    },
-
-    // Internal method to sever a model's ties to a collection.
-    _removeReference: function(model) {
-      if (this === model.collection) delete model.collection;
-      model.off('all', this._onModelEvent, this);
-    },
-
-    // Internal method called every time a model in the set fires an event.
-    // Sets need to update their indexes when models change ids. All other
-    // events simply proxy through. "add" and "remove" events that originate
-    // in other collections are ignored.
-    _onModelEvent: function(event, model, collection, options) {
-      if ((event === 'add' || event === 'remove') && collection !== this) return;
-      if (event === 'destroy') this.remove(model, options);
-      if (model && event === 'change:' + model.idAttribute) {
-        delete this._byId[model.previous(model.idAttribute)];
-        if (model.id != null) this._byId[model.id] = model;
-      }
-      this.trigger.apply(this, arguments);
-    }
-
-  });
-
-  // Underscore methods that we want to implement on the Collection.
-  // 90% of the core usefulness of Backbone Collections is actually implemented
-  // right here:
-  var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl',
-    'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select',
-    'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke',
-    'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest',
-    'tail', 'drop', 'last', 'without', 'indexOf', 'shuffle', 'lastIndexOf',
-    'isEmpty', 'chain'];
-
-  // Mix in each Underscore method as a proxy to `Collection#models`.
-  _.each(methods, function(method) {
-    Collection.prototype[method] = function() {
-      var args = slice.call(arguments);
-      args.unshift(this.models);
-      return _[method].apply(_, args);
-    };
-  });
-
-  // Underscore methods that take a property name as an argument.
-  var attributeMethods = ['groupBy', 'countBy', 'sortBy'];
-
-  // Use attributes instead of properties.
-  _.each(attributeMethods, function(method) {
-    Collection.prototype[method] = function(value, context) {
-      var iterator = _.isFunction(value) ? value : function(model) {
-        return model.get(value);
-      };
-      return _[method](this.models, iterator, context);
-    };
-  });
-
-  // Backbone.View
-  // -------------
-
-  // Backbone Views are almost more convention than they are actual code. A View
-  // is simply a JavaScript object that represents a logical chunk of UI in the
-  // DOM. This might be a single item, an entire list, a sidebar or panel, or
-  // even the surrounding frame which wraps your whole app. Defining a chunk of
-  // UI as a **View** allows you to define your DOM events declaratively, without
-  // having to worry about render order ... and makes it easy for the view to
-  // react to specific changes in the state of your models.
-
-  // Creating a Backbone.View creates its initial element outside of the DOM,
-  // if an existing element is not provided...
-  var View = Backbone.View = function(options) {
-    this.cid = _.uniqueId('view');
-    this._configure(options || {});
-    this._ensureElement();
-    this.initialize.apply(this, arguments);
-    this.delegateEvents();
-  };
-
-  // Cached regex to split keys for `delegate`.
-  var delegateEventSplitter = /^(\S+)\s*(.*)$/;
-
-  // List of view options to be merged as properties.
-  var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];
-
-  // Set up all inheritable **Backbone.View** properties and methods.
-  _.extend(View.prototype, Events, {
-
-    // The default `tagName` of a View's element is `"div"`.
-    tagName: 'div',
-
-    // jQuery delegate for element lookup, scoped to DOM elements within the
-    // current view. This should be prefered to global lookups where possible.
-    $: function(selector) {
-      return this.$el.find(selector);
-    },
-
-    // Initialize is an empty function by default. Override it with your own
-    // initialization logic.
-    initialize: function(){},
-
-    // **render** is the core function that your view should override, in order
-    // to populate its element (`this.el`), with the appropriate HTML. The
-    // convention is for **render** to always return `this`.
-    render: function() {
-      return this;
-    },
-
-    // Remove this view by taking the element out of the DOM, and removing any
-    // applicable Backbone.Events listeners.
-    remove: function() {
-      this.$el.remove();
-      this.stopListening();
-      return this;
-    },
-
-    // Change the view's element (`this.el` property), including event
-    // re-delegation.
-    setElement: function(element, delegate) {
-      if (this.$el) this.undelegateEvents();
-      this.$el = element instanceof Backbone.$ ? element : Backbone.$(element);
-      this.el = this.$el[0];
-      if (delegate !== false) this.delegateEvents();
-      return this;
-    },
-
-    // Set callbacks, where `this.events` is a hash of
-    //
-    // *{"event selector": "callback"}*
-    //
-    //     {
-    //       'mousedown .title':  'edit',
-    //       'click .button':     'save'
-    //       'click .open':       function(e) { ... }
-    //     }
-    //
-    // pairs. Callbacks will be bound to the view, with `this` set properly.
-    // Uses event delegation for efficiency.
-    // Omitting the selector binds the event to `this.el`.
-    // This only works for delegate-able events: not `focus`, `blur`, and
-    // not `change`, `submit`, and `reset` in Internet Explorer.
-    delegateEvents: function(events) {
-      if (!(events || (events = _.result(this, 'events')))) return this;
-      this.undelegateEvents();
-      for (var key in events) {
-        var method = events[key];
-        if (!_.isFunction(method)) method = this[events[key]];
-        if (!method) continue;
-
-        var match = key.match(delegateEventSplitter);
-        var eventName = match[1], selector = match[2];
-        method = _.bind(method, this);
-        eventName += '.delegateEvents' + this.cid;
-        if (selector === '') {
-          this.$el.on(eventName, method);
-        } else {
-          this.$el.on(eventName, selector, method);
-        }
-      }
-      return this;
-    },
-
-    // Clears all callbacks previously bound to the view with `delegateEvents`.
-    // You usually don't need to use this, but may wish to if you have multiple
-    // Backbone views attached to the same DOM element.
-    undelegateEvents: function() {
-      this.$el.off('.delegateEvents' + this.cid);
-      return this;
-    },
-
-    // Performs the initial configuration of a View with a set of options.
-    // Keys with special meaning *(e.g. model, collection, id, className)* are
-    // attached directly to the view.  See `viewOptions` for an exhaustive
-    // list.
-    _configure: function(options) {
-      if (this.options) options = _.extend({}, _.result(this, 'options'), options);
-      _.extend(this, _.pick(options, viewOptions));
-      this.options = options;
-    },
-
-    // Ensure that the View has a DOM element to render into.
-    // If `this.el` is a string, pass it through `$()`, take the first
-    // matching element, and re-assign it to `el`. Otherwise, create
-    // an element from the `id`, `className` and `tagName` properties.
-    _ensureElement: function() {
-      if (!this.el) {
-        var attrs = _.extend({}, _.result(this, 'attributes'));
-        if (this.id) attrs.id = _.result(this, 'id');
-        if (this.className) attrs['class'] = _.result(this, 'className');
-        var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs);
-        this.setElement($el, false);
-      } else {
-        this.setElement(_.result(this, 'el'), false);
-      }
-    }
-
-  });
-
-  // Backbone.sync
-  // -------------
-
-  // Override this function to change the manner in which Backbone persists
-  // models to the server. You will be passed the type of request, and the
-  // model in question. By default, makes a RESTful Ajax request
-  // to the model's `url()`. Some possible customizations could be:
-  //
-  // * Use `setTimeout` to batch rapid-fire updates into a single request.
-  // * Send up the models as XML instead of JSON.
-  // * Persist models via WebSockets instead of Ajax.
-  //
-  // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
-  // as `POST`, with a `_method` parameter containing the true HTTP method,
-  // as well as all requests with the body as `application/x-www-form-urlencoded`
-  // instead of `application/json` with the model in a param named `model`.
-  // Useful when interfacing with server-side languages like **PHP** that make
-  // it difficult to read the body of `PUT` requests.
-  Backbone.sync = function(method, model, options) {
-    var type = methodMap[method];
-
-    // Default options, unless specified.
-    _.defaults(options || (options = {}), {
-      emulateHTTP: Backbone.emulateHTTP,
-      emulateJSON: Backbone.emulateJSON
-    });
-
-    // Default JSON-request options.
-    var params = {type: type, dataType: 'json'};
-
-    // Ensure that we have a URL.
-    if (!options.url) {
-      params.url = _.result(model, 'url') || urlError();
-    }
-
-    // Ensure that we have the appropriate request data.
-    if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
-      params.contentType = 'application/json';
-      params.data = JSON.stringify(options.attrs || model.toJSON(options));
-    }
-
-    // For older servers, emulate JSON by encoding the request into an HTML-form.
-    if (options.emulateJSON) {
-      params.contentType = 'application/x-www-form-urlencoded';
-      params.data = params.data ? {model: params.data} : {};
-    }
-
-    // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
-    // And an `X-HTTP-Method-Override` header.
-    if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {
-      params.type = 'POST';
-      if (options.emulateJSON) params.data._method = type;
-      var beforeSend = options.beforeSend;
-      options.beforeSend = function(xhr) {
-        xhr.setRequestHeader('X-HTTP-Method-Override', type);
-        if (beforeSend) return beforeSend.apply(this, arguments);
-      };
-    }
-
-    // Don't process data on a non-GET request.
-    if (params.type !== 'GET' && !options.emulateJSON) {
-      params.processData = false;
-    }
-
-    // If we're sending a `PATCH` request, and we're in an old Internet Explorer
-    // that still has ActiveX enabled by default, override jQuery to use that
-    // for XHR instead. Remove this line when jQuery supports `PATCH` on IE8.
-    if (params.type === 'PATCH' && window.ActiveXObject &&
-          !(window.external && window.external.msActiveXFilteringEnabled)) {
-      params.xhr = function() {
-        return new ActiveXObject("Microsoft.XMLHTTP");
-      };
-    }
-
-    // Make the request, allowing the user to override any Ajax options.
-    var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
-    model.trigger('request', model, xhr, options);
-    return xhr;
-  };
-
-  // Map from CRUD to HTTP for our default `Backbone.sync` implementation.
-  var methodMap = {
-    'create': 'POST',
-    'update': 'PUT',
-    'patch':  'PATCH',
-    'delete': 'DELETE',
-    'read':   'GET'
-  };
-
-  // Set the default implementation of `Backbone.ajax` to proxy through to `$`.
-  // Override this if you'd like to use a different library.
-  Backbone.ajax = function() {
-    return Backbone.$.ajax.apply(Backbone.$, arguments);
-  };
-
-  // Backbone.Router
-  // ---------------
-
-  // Routers map faux-URLs to actions, and fire events when routes are
-  // matched. Creating a new one sets its `routes` hash, if not set statically.
-  var Router = Backbone.Router = function(options) {
-    options || (options = {});
-    if (options.routes) this.routes = options.routes;
-    this._bindRoutes();
-    this.initialize.apply(this, arguments);
-  };
-
-  // Cached regular expressions for matching named param parts and splatted
-  // parts of route strings.
-  var optionalParam = /\((.*?)\)/g;
-  var namedParam    = /(\(\?)?:\w+/g;
-  var splatParam    = /\*\w+/g;
-  var escapeRegExp  = /[\-{}\[\]+?.,\\\^$|#\s]/g;
-
-  // Set up all inheritable **Backbone.Router** properties and methods.
-  _.extend(Router.prototype, Events, {
-
-    // Initialize is an empty function by default. Override it with your own
-    // initialization logic.
-    initialize: function(){},
-
-    // Manually bind a single named route to a callback. For example:
-    //
-    //     this.route('search/:query/p:num', 'search', function(query, num) {
-    //       ...
-    //     });
-    //
-    route: function(route, name, callback) {
-      if (!_.isRegExp(route)) route = this._routeToRegExp(route);
-      if (_.isFunction(name)) {
-        callback = name;
-        name = '';
-      }
-      if (!callback) callback = this[name];
-      var router = this;
-      Backbone.history.route(route, function(fragment) {
-        var args = router._extractParameters(route, fragment);
-        callback && callback.apply(router, args);
-        router.trigger.apply(router, ['route:' + name].concat(args));
-        router.trigger('route', name, args);
-        Backbone.history.trigger('route', router, name, args);
-      });
-      return this;
-    },
-
-    // Simple proxy to `Backbone.history` to save a fragment into the history.
-    navigate: function(fragment, options) {
-      Backbone.history.navigate(fragment, options);
-      return this;
-    },
-
-    // Bind all defined routes to `Backbone.history`. We have to reverse the
-    // order of the routes here to support behavior where the most general
-    // routes can be defined at the bottom of the route map.
-    _bindRoutes: function() {
-      if (!this.routes) return;
-      this.routes = _.result(this, 'routes');
-      var route, routes = _.keys(this.routes);
-      while ((route = routes.pop()) != null) {
-        this.route(route, this.routes[route]);
-      }
-    },
-
-    // Convert a route string into a regular expression, suitable for matching
-    // against the current location hash.
-    _routeToRegExp: function(route) {
-      route = route.replace(escapeRegExp, '\\$&')
-                   .replace(optionalParam, '(?:$1)?')
-                   .replace(namedParam, function(match, optional){
-                     return optional ? match : '([^\/]+)';
-                   })
-                   .replace(splatParam, '(.*?)');
-      return new RegExp('^' + route + '$');
-    },
-
-    // Given a route, and a URL fragment that it matches, return the array of
-    // extracted decoded parameters. Empty or unmatched parameters will be
-    // treated as `null` to normalize cross-browser behavior.
-    _extractParameters: function(route, fragment) {
-      var params = route.exec(fragment).slice(1);
-      return _.map(params, function(param) {
-        return param ? decodeURIComponent(param) : null;
-      });
-    }
-
-  });
-
-  // Backbone.History
-  // ----------------
-
-  // Handles cross-browser history management, based on either
-  // [pushState](http://diveintohtml5.info/history.html) and real URLs, or
-  // [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange)
-  // and URL fragments. If the browser supports neither (old IE, natch),
-  // falls back to polling.
-  var History = Backbone.History = function() {
-    this.handlers = [];
-    _.bindAll(this, 'checkUrl');
-
-    // Ensure that `History` can be used outside of the browser.
-    if (typeof window !== 'undefined') {
-      this.location = window.location;
-      this.history = window.history;
-    }
-  };
-
-  // Cached regex for stripping a leading hash/slash and trailing space.
-  var routeStripper = /^[#\/]|\s+$/g;
-
-  // Cached regex for stripping leading and trailing slashes.
-  var rootStripper = /^\/+|\/+$/g;
-
-  // Cached regex for detecting MSIE.
-  var isExplorer = /msie [\w.]+/;
-
-  // Cached regex for removing a trailing slash.
-  var trailingSlash = /\/$/;
-
-  // Has the history handling already been started?
-  History.started = false;
-
-  // Set up all inheritable **Backbone.History** properties and methods.
-  _.extend(History.prototype, Events, {
-
-    // The default interval to poll for hash changes, if necessary, is
-    // twenty times a second.
-    interval: 50,
-
-    // Gets the true hash value. Cannot use location.hash directly due to bug
-    // in Firefox where location.hash will always be decoded.
-    getHash: function(window) {
-      var match = (window || this).location.href.match(/#(.*)$/);
-      return match ? match[1] : '';
-    },
-
-    // Get the cross-browser normalized URL fragment, either from the URL,
-    // the hash, or the override.
-    getFragment: function(fragment, forcePushState) {
-      if (fragment == null) {
-        if (this._hasPushState || !this._wantsHashChange || forcePushState) {
-          fragment = this.location.pathname;
-          var root = this.root.replace(trailingSlash, '');
-          if (!fragment.indexOf(root)) fragment = fragment.substr(root.length);
-        } else {
-          fragment = this.getHash();
-        }
-      }
-      return fragment.replace(routeStripper, '');
-    },
-
-    // Start the hash change handling, returning `true` if the current URL matches
-    // an existing route, and `false` otherwise.
-    start: function(options) {
-      if (History.started) throw new Error("Backbone.history has already been started");
-      History.started = true;
-
-      // Figure out the initial configuration. Do we need an iframe?
-      // Is pushState desired ... is it available?
-      this.options          = _.extend({}, {root: '/'}, this.options, options);
-      this.root             = this.options.root;
-      this._wantsHashChange = this.options.hashChange !== false;
-      this._wantsPushState  = !!this.options.pushState;
-      this._hasPushState    = !!(this.options.pushState && this.history && this.history.pushState);
-      var fragment          = this.getFragment();
-      var docMode           = document.documentMode;
-      var oldIE             = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7));
-
-      // Normalize root to always include a leading and trailing slash.
-      this.root = ('/' + this.root + '/').replace(rootStripper, '/');
-
-      if (oldIE && this._wantsHashChange) {
-        this.iframe = Backbone.$('<iframe src="javascript:0" tabindex="-1" />').hide().appendTo('body')[0].contentWindow;
-        this.navigate(fragment);
-      }
-
-      // Depending on whether we're using pushState or hashes, and whether
-      // 'onhashchange' is supported, determine how we check the URL state.
-      if (this._hasPushState) {
-        Backbone.$(window).on('popstate', this.checkUrl);
-      } else if (this._wantsHashChange && ('onhashchange' in window) && !oldIE) {
-        Backbone.$(window).on('hashchange', this.checkUrl);
-      } else if (this._wantsHashChange) {
-        this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
-      }
-
-      // Determine if we need to change the base url, for a pushState link
-      // opened by a non-pushState browser.
-      this.fragment = fragment;
-      var loc = this.location;
-      var atRoot = loc.pathname.replace(/[^\/]$/, '$&/') === this.root;
-
-      // If we've started off with a route from a `pushState`-enabled browser,
-      // but we're currently in a browser that doesn't support it...
-      if (this._wantsHashChange && this._wantsPushState && !this._hasPushState && !atRoot) {
-        this.fragment = this.getFragment(null, true);
-        this.location.replace(this.root + this.location.search + '#' + this.fragment);
-        // Return immediately as browser will do redirect to new url
-        return true;
-
-      // Or if we've started out with a hash-based route, but we're currently
-      // in a browser where it could be `pushState`-based instead...
-      } else if (this._wantsPushState && this._hasPushState && atRoot && loc.hash) {
-        this.fragment = this.getHash().replace(routeStripper, '');
-        this.history.replaceState({}, document.title, this.root + this.fragment + loc.search);
-      }
-
-      if (!this.options.silent) return this.loadUrl();
-    },
-
-    // Disable Backbone.history, perhaps temporarily. Not useful in a real app,
-    // but possibly useful for unit testing Routers.
-    stop: function() {
-      Backbone.$(window).off('popstate', this.checkUrl).off('hashchange', this.checkUrl);
-      clearInterval(this._checkUrlInterval);
-      History.started = false;
-    },
-
-    // Add a route to be tested when the fragment changes. Routes added later
-    // may override previous routes.
-    route: function(route, callback) {
-      this.handlers.unshift({route: route, callback: callback});
-    },
-
-    // Checks the current URL to see if it has changed, and if it has,
-    // calls `loadUrl`, normalizing across the hidden iframe.
-    checkUrl: function(e) {
-      var current = this.getFragment();
-      if (current === this.fragment && this.iframe) {
-        current = this.getFragment(this.getHash(this.iframe));
-      }
-      if (current === this.fragment) return false;
-      if (this.iframe) this.navigate(current);
-      this.loadUrl() || this.loadUrl(this.getHash());
-    },
-
-    // Attempt to load the current URL fragment. If a route succeeds with a
-    // match, returns `true`. If no defined routes matches the fragment,
-    // returns `false`.
-    loadUrl: function(fragmentOverride) {
-      var fragment = this.fragment = this.getFragment(fragmentOverride);
-      var matched = _.any(this.handlers, function(handler) {
-        if (handler.route.test(fragment)) {
-          handler.callback(fragment);
-          return true;
-        }
-      });
-      return matched;
-    },
-
-    // Save a fragment into the hash history, or replace the URL state if the
-    // 'replace' option is passed. You are responsible for properly URL-encoding
-    // the fragment in advance.
-    //
-    // The options object can contain `trigger: true` if you wish to have the
-    // route callback be fired (not usually desirable), or `replace: true`, if
-    // you wish to modify the current URL without adding an entry to the history.
-    navigate: function(fragment, options) {
-      if (!History.started) return false;
-      if (!options || options === true) options = {trigger: options};
-      fragment = this.getFragment(fragment || '');
-      if (this.fragment === fragment) return;
-      this.fragment = fragment;
-      var url = this.root + fragment;
-
-      // If pushState is available, we use it to set the fragment as a real URL.
-      if (this._hasPushState) {
-        this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);
-
-      // If hash changes haven't been explicitly disabled, update the hash
-      // fragment to store history.
-      } else if (this._wantsHashChange) {
-        this._updateHash(this.location, fragment, options.replace);
-        if (this.iframe && (fragment !== this.getFragment(this.getHash(this.iframe)))) {
-          // Opening and closing the iframe tricks IE7 and earlier to push a
-          // history entry on hash-tag change.  When replace is true, we don't
-          // want this.
-          if(!options.replace) this.iframe.document.open().close();
-          this._updateHash(this.iframe.location, fragment, options.replace);
-        }
-
-      // If you've told us that you explicitly don't want fallback hashchange-
-      // based history, then `navigate` becomes a page refresh.
-      } else {
-        return this.location.assign(url);
-      }
-      if (options.trigger) this.loadUrl(fragment);
-    },
-
-    // Update the hash location, either replacing the current entry, or adding
-    // a new one to the browser history.
-    _updateHash: function(location, fragment, replace) {
-      if (replace) {
-        var href = location.href.replace(/(javascript:|#).*$/, '');
-        location.replace(href + '#' + fragment);
-      } else {
-        // Some browsers require that `hash` contains a leading #.
-        location.hash = '#' + fragment;
-      }
-    }
-
-  });
-
-  // Create the default Backbone.history.
-  Backbone.history = new History;
-
-  // Helpers
-  // -------
-
-  // Helper function to correctly set up the prototype chain, for subclasses.
-  // Similar to `goog.inherits`, but uses a hash of prototype properties and
-  // class properties to be extended.
-  var extend = function(protoProps, staticProps) {
-    var parent = this;
-    var child;
-
-    // The constructor function for the new subclass is either defined by you
-    // (the "constructor" property in your `extend` definition), or defaulted
-    // by us to simply call the parent's constructor.
-    if (protoProps && _.has(protoProps, 'constructor')) {
-      child = protoProps.constructor;
-    } else {
-      child = function(){ return parent.apply(this, arguments); };
-    }
-
-    // Add static properties to the constructor function, if supplied.
-    _.extend(child, parent, staticProps);
-
-    // Set the prototype chain to inherit from `parent`, without calling
-    // `parent`'s constructor function.
-    var Surrogate = function(){ this.constructor = child; };
-    Surrogate.prototype = parent.prototype;
-    child.prototype = new Surrogate;
-
-    // Add prototype properties (instance properties) to the subclass,
-    // if supplied.
-    if (protoProps) _.extend(child.prototype, protoProps);
-
-    // Set a convenience property in case the parent's prototype is needed
-    // later.
-    child.__super__ = parent.prototype;
-
-    return child;
-  };
-
-  // Set up inheritance for the model, collection, router, view and history.
-  Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend;
-
-  // Throw an error when a URL is needed, and none is supplied.
-  var urlError = function() {
-    throw new Error('A "url" property or function must be specified');
-  };
-
-  // Wrap an optional error callback with a fallback error event.
-  var wrapError = function (model, options) {
-    var error = options.error;
-    options.error = function(resp) {
-      if (error) error(model, resp, options);
-      model.trigger('error', model, resp, options);
-    };
-  };
-
-}).call(this);


[10/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/js/plugins/prettify.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/js/plugins/prettify.js b/apps/fauxton/assets/js/plugins/prettify.js
deleted file mode 100644
index eef5ad7..0000000
--- a/apps/fauxton/assets/js/plugins/prettify.js
+++ /dev/null
@@ -1,28 +0,0 @@
-var q=null;window.PR_SHOULD_USE_CONTINUATION=!0;
-(function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:"0"<=b&&b<="7"?parseInt(a.substring(1),8):b==="u"||b==="x"?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a<32)return(a<16?"\\x0":"\\x")+a.toString(16);a=String.fromCharCode(a);if(a==="\\"||a==="-"||a==="["||a==="]")a="\\"+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a=
-[],b=[],o=f[0]==="^",c=o?1:0,i=f.length;c<i;++c){var j=f[c];if(/\\[bdsw]/i.test(j))a.push(j);else{var j=m(j),d;c+2<i&&"-"===f[c+1]?(d=m(f[c+2]),c+=2):d=j;b.push([j,d]);d<65||j>122||(d<65||j>90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d<97||j>122||b.push([Math.max(97,j)&-33,Math.min(d,122)&-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;c<b.length;++c)i=b[c],i[0]<=j[1]+1?j[1]=Math.max(j[1],i[1]):f.push(j=i);b=["["];o&&b.push("^");b.push.apply(b,a);for(c=0;c<
-f.length;++c)i=f[c],b.push(e(i[0])),i[1]>i[0]&&(i[1]+1>i[0]&&b.push("-"),b.push(e(i[1])));b.push("]");return b.join("")}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c<b;++c){var j=f[c];j==="("?++i:"\\"===j.charAt(0)&&(j=+j.substring(1))&&j<=i&&(d[j]=-1)}for(c=1;c<d.length;++c)-1===d[c]&&(d[c]=++t);for(i=c=0;c<b;++c)j=f[c],j==="("?(++i,d[i]===void 0&&(f[c]="(?:")):"\\"===j.charAt(0)&&
-(j=+j.substring(1))&&j<=i&&(f[c]="\\"+d[i]);for(i=c=0;c<b;++c)"^"===f[c]&&"^"!==f[c+1]&&(f[c]="");if(a.ignoreCase&&s)for(c=0;c<b;++c)j=f[c],a=j.charAt(0),j.length>=2&&a==="["?f[c]=h(j):a!=="\\"&&(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return"["+String.fromCharCode(a&-33,a|32)+"]"}));return f.join("")}for(var t=0,s=!1,l=!1,p=0,d=a.length;p<d;++p){var g=a[p];if(g.ignoreCase)l=!0;else if(/[a-z]/i.test(g.source.replace(/\\u[\da-f]{4}|\\x[\da-f]{2}|\\[^UXux]/gi,""))){s=!0;l=!1;break}}for(var r=
-{b:8,t:9,n:10,v:11,f:12,r:13},n=[],p=0,d=a.length;p<d;++p){g=a[p];if(g.global||g.multiline)throw Error(""+g);n.push("(?:"+y(g)+")")}return RegExp(n.join("|"),l?"gi":"g")}function M(a){function m(a){switch(a.nodeType){case 1:if(e.test(a.className))break;for(var g=a.firstChild;g;g=g.nextSibling)m(g);g=a.nodeName;if("BR"===g||"LI"===g)h[s]="\n",t[s<<1]=y++,t[s++<<1|1]=a;break;case 3:case 4:g=a.nodeValue,g.length&&(g=p?g.replace(/\r\n?/g,"\n"):g.replace(/[\t\n\r ]+/g," "),h[s]=g,t[s<<1]=y,y+=g.length,
-t[s++<<1|1]=a)}}var e=/(?:^|\s)nocode(?:\s|$)/,h=[],y=0,t=[],s=0,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&&(l=document.defaultView.getComputedStyle(a,q).getPropertyValue("white-space"));var p=l&&"pre"===l.substring(0,3);m(a);return{a:h.join("").replace(/\n$/,""),c:t}}function B(a,m,e,h){m&&(a={a:m,d:a},e(a),h.push.apply(h,a.e))}function x(a,m){function e(a){for(var l=a.d,p=[l,"pln"],d=0,g=a.a.match(y)||[],r={},n=0,z=g.length;n<z;++n){var f=g[n],b=r[f],o=void 0,c;if(typeof b===
-"string")c=!1;else{var i=h[f.charAt(0)];if(i)o=f.match(i[1]),b=i[0];else{for(c=0;c<t;++c)if(i=m[c],o=f.match(i[1])){b=i[0];break}o||(b="pln")}if((c=b.length>=5&&"lang-"===b.substring(0,5))&&!(o&&typeof o[1]==="string"))c=!1,b="src";c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&&(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m),
-l=[],p={},d=0,g=e.length;d<g;++d){var r=e[d],n=r[3];if(n)for(var k=n.length;--k>=0;)h[n.charAt(k)]=r;r=r[1];n=""+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push(["str",/^(?:'''(?:[^'\\]|\\[\S\s]|''?(?=[^']))*(?:'''|$)|"""(?:[^"\\]|\\[\S\s]|""?(?=[^"]))*(?:"""|$)|'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$))/,q,"'\""]):a.multiLineStrings?m.push(["str",/^(?:'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/,
-q,"'\"`"]):m.push(["str",/^(?:'(?:[^\n\r'\\]|\\.)*(?:'|$)|"(?:[^\n\r"\\]|\\.)*(?:"|$))/,q,"\"'"]);a.verbatimStrings&&e.push(["str",/^@"(?:[^"]|"")*(?:"|$)/,q]);var h=a.hashComments;h&&(a.cStyleComments?(h>1?m.push(["com",/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,"#"]):m.push(["com",/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,"#"]),e.push(["str",/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,q])):m.push(["com",/^#[^\n\r]*/,
-q,"#"]));a.cStyleComments&&(e.push(["com",/^\/\/[^\n\r]*/,q]),e.push(["com",/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&&e.push(["lang-regex",/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&|&&|&&=|&=|\(|\*|\*=|\+=|,|-=|->|\/|\/=|:|::|;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&&e.push(["typ",h]);a=(""+a.keywords).replace(/^ | $/g,
-"");a.length&&e.push(["kwd",RegExp("^(?:"+a.replace(/[\s,]+/g,"|")+")\\b"),q]);m.push(["pln",/^\s+/,q," \r\n\t\xa0"]);e.push(["lit",/^@[$_a-z][\w$@]*/i,q],["typ",/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],["pln",/^[$_a-z][\w$@]*/i,q],["lit",/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,"0123456789"],["pln",/^\\[\S\s]?/,q],["pun",/^.[^\s\w"-$'./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if("BR"===a.nodeName)h(a),
-a.parentNode&&a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&&a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e}
-for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&&e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&&(l=s.defaultView.getComputedStyle(a,q).getPropertyValue("white-space"));var p=l&&"pre"===l.substring(0,3);for(l=s.createElement("LI");a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g<d.length;++g)e(d[g]);m===(m|0)&&d[0].setAttribute("value",
-m);var r=s.createElement("OL");r.className="linenums";for(var n=Math.max(0,m-1|0)||0,g=0,z=d.length;g<z;++g)l=d[g],l.className="L"+(g+n)%10,l.firstChild||l.appendChild(s.createTextNode("\xa0")),r.appendChild(l);a.appendChild(r)}function k(a,m){for(var e=m.length;--e>=0;){var h=m[e];A.hasOwnProperty(h)?window.console&&console.warn("cannot override language handler %s",h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*</.test(m)?"default-markup":"default-code";return A[a]}function E(a){var m=
-a.g;try{var e=M(a.h),h=e.a;a.a=h;a.c=e.c;a.d=0;C(m,h)(a);var k=/\bMSIE\b/.test(navigator.userAgent),m=/\n/g,t=a.a,s=t.length,e=0,l=a.c,p=l.length,h=0,d=a.e,g=d.length,a=0;d[g]=s;var r,n;for(n=r=0;n<g;)d[n]!==d[n+2]?(d[r++]=d[n++],d[r++]=d[n++]):n+=2;g=r;for(n=r=0;n<g;){for(var z=d[n],f=d[n+1],b=n+2;b+2<=g&&d[b+1]===f;)b+=2;d[r++]=z;d[r++]=f;n=b}for(d.length=r;h<p;){var o=l[h+2]||s,c=d[a+2]||s,b=Math.min(o,c),i=l[h+1],j;if(i.nodeType!==1&&(j=t.substring(e,b))){k&&(j=j.replace(m,"\r"));i.nodeValue=
-j;var u=i.ownerDocument,v=u.createElement("SPAN");v.className=d[a+1];var x=i.parentNode;x.replaceChild(v,i);v.appendChild(i);e<o&&(l[h+1]=i=u.createTextNode(t.substring(b,o)),x.insertBefore(i,v.nextSibling))}e=b;e>=o&&(h+=2);e>=c&&(a+=2)}}catch(w){"console"in window&&console.log(w&&w.stack?w.stack:w)}}var v=["break,continue,do,else,for,if,return,while"],w=[[v,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"],
-"catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"],F=[w,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"],G=[w,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"],
-H=[G,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"],w=[w,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"],I=[v,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"],
-J=[v,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"],v=[v,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END"+
-I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,["default-code"]);k(x([],[["pln",/^[^<?]+/],["dec",/^<!\w[^>]*(?:>|$)/],["com",/^<\!--[\S\s]*?(?:--\>|$)/],["lang-",/^<\?([\S\s]+?)(?:\?>|$)/],["lang-",/^<%([\S\s]+?)(?:%>|$)/],["pun",/^(?:<[%?]|[%?]>)/],["lang-",/^<xmp\b[^>]*>([\S\s]+?)<\/xmp\b[^>]*>/i],["lang-js",/^<script\b[^>]*>([\S\s]*?)(<\/script\b[^>]*>)/i],["lang-css",/^<style\b[^>]*>([\S\s]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]),
-["default-markup","htm","html","mxml","xhtml","xml","xsl"]);k(x([["pln",/^\s+/,q," \t\r\n"],["atv",/^(?:"[^"]*"?|'[^']*'?)/,q,"\"'"]],[["tag",/^^<\/?[a-z](?:[\w-.:]*\w)?|\/?>$/i],["atn",/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^\s"'>]*(?:[^\s"'/>]|\/(?=\s)))/],["pun",/^[/<->]+/],["lang-js",/^on\w+\s*=\s*"([^"]+)"/i],["lang-js",/^on\w+\s*=\s*'([^']+)'/i],["lang-js",/^on\w+\s*=\s*([^\s"'>]+)/i],["lang-css",/^style\s*=\s*"([^"]+)"/i],["lang-css",/^style\s*=\s*'([^']+)'/i],["lang-css",
-/^style\s*=\s*([^\s"'>]+)/i]]),["in.tag"]);k(x([],[["atv",/^[\S\s]+/]]),["uq.val"]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),["c","cc","cpp","cxx","cyc","m"]);k(u({keywords:"null,true,false"}),["json"]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),["cs"]);k(u({keywords:G,cStyleComments:!0}),["java"]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),["bsh","csh","sh"]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}),
-["cv","py"]);k(u({keywords:"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END",hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["perl","pl","pm"]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["rb"]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),["js"]);k(u({keywords:"all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes",
-hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),["coffee"]);k(x([],[["str",/^[\S\s]+/]]),["regex"]);window.prettyPrintOne=function(a,m,e){var h=document.createElement("PRE");h.innerHTML=a;e&&D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p<h.length&&l.now()<e;p++){var n=h[p],k=n.className;if(k.indexOf("prettyprint")>=0){var k=k.match(g),f,b;if(b=
-!k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&&"CODE"===f.tagName}b&&(k=f.className.match(g));k&&(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName==="pre"||o.tagName==="code"||o.tagName==="xmp")&&o.className&&o.className.indexOf("prettyprint")>=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&&b[1].length?+b[1]:!0:!1)&&D(n,b),d={g:k,h:n,i:b},E(d))}}p<h.length?setTimeout(m,
-250):a&&a()}for(var e=[document.getElementsByTagName("pre"),document.getElementsByTagName("code"),document.getElementsByTagName("xmp")],h=[],k=0;k<e.length;++k)for(var t=0,s=e[k].length;t<s;++t)h.push(e[k][t]);var e=q,l=Date;l.now||(l={now:function(){return+new Date}});var p=0,d,g=/\blang(?:uage)?-([\w.]+)(?!\S)/;m()};window.PR={createSimpleLexer:x,registerLangHandler:k,sourceDecorator:u,PR_ATTRIB_NAME:"atn",PR_ATTRIB_VALUE:"atv",PR_COMMENT:"com",PR_DECLARATION:"dec",PR_KEYWORD:"kwd",PR_LITERAL:"lit",
-PR_NOCODE:"nocode",PR_PLAIN:"pln",PR_PUNCTUATION:"pun",PR_SOURCE:"src",PR_STRING:"str",PR_TAG:"tag",PR_TYPE:"typ"}})();

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/accordion.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/accordion.less b/apps/fauxton/assets/less/bootstrap/accordion.less
deleted file mode 100644
index d63523b..0000000
--- a/apps/fauxton/assets/less/bootstrap/accordion.less
+++ /dev/null
@@ -1,34 +0,0 @@
-//
-// Accordion
-// --------------------------------------------------
-
-
-// Parent container
-.accordion {
-  margin-bottom: @baseLineHeight;
-}
-
-// Group == heading + body
-.accordion-group {
-  margin-bottom: 2px;
-  border: 1px solid #e5e5e5;
-  .border-radius(@baseBorderRadius);
-}
-.accordion-heading {
-  border-bottom: 0;
-}
-.accordion-heading .accordion-toggle {
-  display: block;
-  padding: 8px 15px;
-}
-
-// General toggle styles
-.accordion-toggle {
-  cursor: pointer;
-}
-
-// Inner needs the styles because you can't animate properly with any styles on the element
-.accordion-inner {
-  padding: 9px 15px;
-  border-top: 1px solid #e5e5e5;
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/alerts.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/alerts.less b/apps/fauxton/assets/less/bootstrap/alerts.less
deleted file mode 100644
index 0116b19..0000000
--- a/apps/fauxton/assets/less/bootstrap/alerts.less
+++ /dev/null
@@ -1,79 +0,0 @@
-//
-// Alerts
-// --------------------------------------------------
-
-
-// Base styles
-// -------------------------
-
-.alert {
-  padding: 8px 35px 8px 14px;
-  margin-bottom: @baseLineHeight;
-  text-shadow: 0 1px 0 rgba(255,255,255,.5);
-  background-color: @warningBackground;
-  border: 1px solid @warningBorder;
-  .border-radius(@baseBorderRadius);
-}
-.alert,
-.alert h4 {
-  // Specified for the h4 to prevent conflicts of changing @headingsColor
-  color: @warningText;
-}
-.alert h4 {
-  margin: 0;
-}
-
-// Adjust close link position
-.alert .close {
-  position: relative;
-  top: -2px;
-  right: -21px;
-  line-height: @baseLineHeight;
-}
-
-
-// Alternate styles
-// -------------------------
-
-.alert-success {
-  background-color: @successBackground;
-  border-color: @successBorder;
-  color: @successText;
-}
-.alert-success h4 {
-  color: @successText;
-}
-.alert-danger,
-.alert-error {
-  background-color: @errorBackground;
-  border-color: @errorBorder;
-  color: @errorText;
-}
-.alert-danger h4,
-.alert-error h4 {
-  color: @errorText;
-}
-.alert-info {
-  background-color: @infoBackground;
-  border-color: @infoBorder;
-  color: @infoText;
-}
-.alert-info h4 {
-  color: @infoText;
-}
-
-
-// Block alerts
-// -------------------------
-
-.alert-block {
-  padding-top: 14px;
-  padding-bottom: 14px;
-}
-.alert-block > p,
-.alert-block > ul {
-  margin-bottom: 0;
-}
-.alert-block p + p {
-  margin-top: 5px;
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/bootstrap.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/bootstrap.less b/apps/fauxton/assets/less/bootstrap/bootstrap.less
deleted file mode 100644
index 6f1abd7..0000000
--- a/apps/fauxton/assets/less/bootstrap/bootstrap.less
+++ /dev/null
@@ -1,63 +0,0 @@
-/*!
- * Bootstrap v2.3.2
- *
- * Copyright 2012 Twitter, Inc
- * Licensed under the Apache License v2.0
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Designed and built with all the love in the world @twitter by @mdo and @fat.
- */
-
-// Core variables and mixins
-@import "variables.less"; // Modify this for custom colors, font-sizes, etc
-@import "mixins.less";
-
-// CSS Reset
-@import "reset.less";
-
-// Grid system and page structure
-@import "scaffolding.less";
-@import "grid.less";
-@import "layouts.less";
-
-// Base CSS
-@import "type.less";
-@import "code.less";
-@import "forms.less";
-@import "tables.less";
-
-// Components: common
-@import "/font-awesome/font-awesome.less";
-@import "dropdowns.less";
-@import "wells.less";
-@import "component-animations.less";
-@import "close.less";
-
-// Components: Buttons & Alerts
-@import "buttons.less";
-@import "button-groups.less";
-@import "alerts.less"; // Note: alerts share common CSS with buttons and thus have styles in buttons.less
-
-// Components: Nav
-@import "navs.less";
-@import "navbar.less";
-@import "breadcrumbs.less";
-@import "pagination.less";
-@import "pager.less";
-
-// Components: Popovers
-@import "modals.less";
-@import "tooltip.less";
-@import "popovers.less";
-
-// Components: Misc
-@import "thumbnails.less";
-@import "media.less";
-@import "labels-badges.less";
-@import "progress-bars.less";
-@import "accordion.less";
-@import "carousel.less";
-@import "hero-unit.less";
-
-// Utility classes
-@import "utilities.less"; // Has to be last to override when necessary

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/breadcrumbs.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/breadcrumbs.less b/apps/fauxton/assets/less/bootstrap/breadcrumbs.less
deleted file mode 100644
index f753df6..0000000
--- a/apps/fauxton/assets/less/bootstrap/breadcrumbs.less
+++ /dev/null
@@ -1,24 +0,0 @@
-//
-// Breadcrumbs
-// --------------------------------------------------
-
-
-.breadcrumb {
-  padding: 8px 15px;
-  margin: 0 0 @baseLineHeight;
-  list-style: none;
-  background-color: #f5f5f5;
-  .border-radius(@baseBorderRadius);
-  > li {
-    display: inline-block;
-    .ie7-inline-block();
-    text-shadow: 0 1px 0 @white;
-    > .divider {
-      padding: 0 5px;
-      color: #ccc;
-    }
-  }
-  > .active {
-    color: @grayLight;
-  }
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/button-groups.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/button-groups.less b/apps/fauxton/assets/less/bootstrap/button-groups.less
deleted file mode 100644
index 55cdc60..0000000
--- a/apps/fauxton/assets/less/bootstrap/button-groups.less
+++ /dev/null
@@ -1,229 +0,0 @@
-//
-// Button groups
-// --------------------------------------------------
-
-
-// Make the div behave like a button
-.btn-group {
-  position: relative;
-  display: inline-block;
-  .ie7-inline-block();
-  font-size: 0; // remove as part 1 of font-size inline-block hack
-  vertical-align: middle; // match .btn alignment given font-size hack above
-  white-space: nowrap; // prevent buttons from wrapping when in tight spaces (e.g., the table on the tests page)
-  .ie7-restore-left-whitespace();
-}
-
-// Space out series of button groups
-.btn-group + .btn-group {
-  margin-left: 5px;
-}
-
-// Optional: Group multiple button groups together for a toolbar
-.btn-toolbar {
-  font-size: 0; // Hack to remove whitespace that results from using inline-block
-  margin-top: @baseLineHeight / 2;
-  margin-bottom: @baseLineHeight / 2;
-  > .btn + .btn,
-  > .btn-group + .btn,
-  > .btn + .btn-group {
-    margin-left: 5px;
-  }
-}
-
-// Float them, remove border radius, then re-add to first and last elements
-.btn-group > .btn {
-  position: relative;
-  .border-radius(0);
-}
-.btn-group > .btn + .btn {
-  margin-left: -1px;
-}
-.btn-group > .btn,
-.btn-group > .dropdown-menu,
-.btn-group > .popover {
-  font-size: @baseFontSize; // redeclare as part 2 of font-size inline-block hack
-}
-
-// Reset fonts for other sizes
-.btn-group > .btn-mini {
-  font-size: @fontSizeMini;
-}
-.btn-group > .btn-small {
-  font-size: @fontSizeSmall;
-}
-.btn-group > .btn-large {
-  font-size: @fontSizeLarge;
-}
-
-// Set corners individual because sometimes a single button can be in a .btn-group and we need :first-child and :last-child to both match
-.btn-group > .btn:first-child {
-  margin-left: 0;
-  .border-top-left-radius(@baseBorderRadius);
-  .border-bottom-left-radius(@baseBorderRadius);
-}
-// Need .dropdown-toggle since :last-child doesn't apply given a .dropdown-menu immediately after it
-.btn-group > .btn:last-child,
-.btn-group > .dropdown-toggle {
-  .border-top-right-radius(@baseBorderRadius);
-  .border-bottom-right-radius(@baseBorderRadius);
-}
-// Reset corners for large buttons
-.btn-group > .btn.large:first-child {
-  margin-left: 0;
-  .border-top-left-radius(@borderRadiusLarge);
-  .border-bottom-left-radius(@borderRadiusLarge);
-}
-.btn-group > .btn.large:last-child,
-.btn-group > .large.dropdown-toggle {
-  .border-top-right-radius(@borderRadiusLarge);
-  .border-bottom-right-radius(@borderRadiusLarge);
-}
-
-// On hover/focus/active, bring the proper btn to front
-.btn-group > .btn:hover,
-.btn-group > .btn:focus,
-.btn-group > .btn:active,
-.btn-group > .btn.active {
-  z-index: 2;
-}
-
-// On active and open, don't show outline
-.btn-group .dropdown-toggle:active,
-.btn-group.open .dropdown-toggle {
-  outline: 0;
-}
-
-
-
-// Split button dropdowns
-// ----------------------
-
-// Give the line between buttons some depth
-.btn-group > .btn + .dropdown-toggle {
-  padding-left: 8px;
-  padding-right: 8px;
-  .box-shadow(~"inset 1px 0 0 rgba(255,255,255,.125), inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05)");
-  *padding-top: 5px;
-  *padding-bottom: 5px;
-}
-.btn-group > .btn-mini + .dropdown-toggle {
-  padding-left: 5px;
-  padding-right: 5px;
-  *padding-top: 2px;
-  *padding-bottom: 2px;
-}
-.btn-group > .btn-small + .dropdown-toggle {
-  *padding-top: 5px;
-  *padding-bottom: 4px;
-}
-.btn-group > .btn-large + .dropdown-toggle {
-  padding-left: 12px;
-  padding-right: 12px;
-  *padding-top: 7px;
-  *padding-bottom: 7px;
-}
-
-.btn-group.open {
-
-  // The clickable button for toggling the menu
-  // Remove the gradient and set the same inset shadow as the :active state
-  .dropdown-toggle {
-    background-image: none;
-    .box-shadow(~"inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05)");
-  }
-
-  // Keep the hover's background when dropdown is open
-  .btn.dropdown-toggle {
-    background-color: @btnBackgroundHighlight;
-  }
-  .btn-primary.dropdown-toggle {
-    background-color: @btnPrimaryBackgroundHighlight;
-  }
-  .btn-warning.dropdown-toggle {
-    background-color: @btnWarningBackgroundHighlight;
-  }
-  .btn-danger.dropdown-toggle {
-    background-color: @btnDangerBackgroundHighlight;
-  }
-  .btn-success.dropdown-toggle {
-    background-color: @btnSuccessBackgroundHighlight;
-  }
-  .btn-info.dropdown-toggle {
-    background-color: @btnInfoBackgroundHighlight;
-  }
-  .btn-inverse.dropdown-toggle {
-    background-color: @btnInverseBackgroundHighlight;
-  }
-}
-
-
-// Reposition the caret
-.btn .caret {
-  margin-top: 8px;
-  margin-left: 0;
-}
-// Carets in other button sizes
-.btn-large .caret {
-  margin-top: 6px;
-}
-.btn-large .caret {
-  border-left-width:  5px;
-  border-right-width: 5px;
-  border-top-width:   5px;
-}
-.btn-mini .caret,
-.btn-small .caret {
-  margin-top: 8px;
-}
-// Upside down carets for .dropup
-.dropup .btn-large .caret {
-  border-bottom-width: 5px;
-}
-
-
-
-// Account for other colors
-.btn-primary,
-.btn-warning,
-.btn-danger,
-.btn-info,
-.btn-success,
-.btn-inverse {
-  .caret {
-    border-top-color: @white;
-    border-bottom-color: @white;
-  }
-}
-
-
-
-// Vertical button groups
-// ----------------------
-
-.btn-group-vertical {
-  display: inline-block; // makes buttons only take up the width they need
-  .ie7-inline-block();
-}
-.btn-group-vertical > .btn {
-  display: block;
-  float: none;
-  max-width: 100%;
-  .border-radius(0);
-}
-.btn-group-vertical > .btn + .btn {
-  margin-left: 0;
-  margin-top: -1px;
-}
-.btn-group-vertical > .btn:first-child {
-  .border-radius(@baseBorderRadius @baseBorderRadius 0 0);
-}
-.btn-group-vertical > .btn:last-child {
-  .border-radius(0 0 @baseBorderRadius @baseBorderRadius);
-}
-.btn-group-vertical > .btn-large:first-child {
-  .border-radius(@borderRadiusLarge @borderRadiusLarge 0 0);
-}
-.btn-group-vertical > .btn-large:last-child {
-  .border-radius(0 0 @borderRadiusLarge @borderRadiusLarge);
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/buttons.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/buttons.less b/apps/fauxton/assets/less/bootstrap/buttons.less
deleted file mode 100644
index 4cd4d86..0000000
--- a/apps/fauxton/assets/less/bootstrap/buttons.less
+++ /dev/null
@@ -1,228 +0,0 @@
-//
-// Buttons
-// --------------------------------------------------
-
-
-// Base styles
-// --------------------------------------------------
-
-// Core
-.btn {
-  display: inline-block;
-  .ie7-inline-block();
-  padding: 4px 12px;
-  margin-bottom: 0; // For input.btn
-  font-size: @baseFontSize;
-  line-height: @baseLineHeight;
-  text-align: center;
-  vertical-align: middle;
-  cursor: pointer;
-  .buttonBackground(@btnBackground, @btnBackgroundHighlight, @grayDark, 0 1px 1px rgba(255,255,255,.75));
-  border: 1px solid @btnBorder;
-  *border: 0; // Remove the border to prevent IE7's black border on input:focus
-  border-bottom-color: darken(@btnBorder, 10%);
-  .border-radius(@baseBorderRadius);
-  .ie7-restore-left-whitespace(); // Give IE7 some love
-  .box-shadow(~"inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05)");
-
-  // Hover/focus state
-  &:hover,
-  &:focus {
-    color: @grayDark;
-    text-decoration: none;
-    background-position: 0 -15px;
-
-    // transition is only when going to hover/focus, otherwise the background
-    // behind the gradient (there for IE<=9 fallback) gets mismatched
-    .transition(background-position .1s linear);
-  }
-
-  // Focus state for keyboard and accessibility
-  &:focus {
-    .tab-focus();
-  }
-
-  // Active state
-  &.active,
-  &:active {
-    background-image: none;
-    outline: 0;
-    .box-shadow(~"inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05)");
-  }
-
-  // Disabled state
-  &.disabled,
-  &[disabled] {
-    cursor: default;
-    background-image: none;
-    .opacity(65);
-    .box-shadow(none);
-  }
-
-}
-
-
-
-// Button Sizes
-// --------------------------------------------------
-
-// Large
-.btn-large {
-  padding: @paddingLarge;
-  font-size: @fontSizeLarge;
-  .border-radius(@borderRadiusLarge);
-}
-.btn-large [class^="icon-"],
-.btn-large [class*=" icon-"] {
-  margin-top: 4px;
-}
-
-// Small
-.btn-small {
-  padding: @paddingSmall;
-  font-size: @fontSizeSmall;
-  .border-radius(@borderRadiusSmall);
-}
-.btn-small [class^="icon-"],
-.btn-small [class*=" icon-"] {
-  margin-top: 0;
-}
-.btn-mini [class^="icon-"],
-.btn-mini [class*=" icon-"] {
-  margin-top: -1px;
-}
-
-// Mini
-.btn-mini {
-  padding: @paddingMini;
-  font-size: @fontSizeMini;
-  .border-radius(@borderRadiusSmall);
-}
-
-
-// Block button
-// -------------------------
-
-.btn-block {
-  display: block;
-  width: 100%;
-  padding-left: 0;
-  padding-right: 0;
-  .box-sizing(border-box);
-}
-
-// Vertically space out multiple block buttons
-.btn-block + .btn-block {
-  margin-top: 5px;
-}
-
-// Specificity overrides
-input[type="submit"],
-input[type="reset"],
-input[type="button"] {
-  &.btn-block {
-    width: 100%;
-  }
-}
-
-
-
-// Alternate buttons
-// --------------------------------------------------
-
-// Provide *some* extra contrast for those who can get it
-.btn-primary.active,
-.btn-warning.active,
-.btn-danger.active,
-.btn-success.active,
-.btn-info.active,
-.btn-inverse.active {
-  color: rgba(255,255,255,.75);
-}
-
-// Set the backgrounds
-// -------------------------
-.btn-primary {
-  .buttonBackground(@btnPrimaryBackground, @btnPrimaryBackgroundHighlight);
-}
-// Warning appears are orange
-.btn-warning {
-  .buttonBackground(@btnWarningBackground, @btnWarningBackgroundHighlight);
-}
-// Danger and error appear as red
-.btn-danger {
-  .buttonBackground(@btnDangerBackground, @btnDangerBackgroundHighlight);
-}
-// Success appears as green
-.btn-success {
-  .buttonBackground(@btnSuccessBackground, @btnSuccessBackgroundHighlight);
-}
-// Info appears as a neutral blue
-.btn-info {
-  .buttonBackground(@btnInfoBackground, @btnInfoBackgroundHighlight);
-}
-// Inverse appears as dark gray
-.btn-inverse {
-  .buttonBackground(@btnInverseBackground, @btnInverseBackgroundHighlight);
-}
-
-
-// Cross-browser Jank
-// --------------------------------------------------
-
-button.btn,
-input[type="submit"].btn {
-
-  // Firefox 3.6 only I believe
-  &::-moz-focus-inner {
-    padding: 0;
-    border: 0;
-  }
-
-  // IE7 has some default padding on button controls
-  *padding-top: 3px;
-  *padding-bottom: 3px;
-
-  &.btn-large {
-    *padding-top: 7px;
-    *padding-bottom: 7px;
-  }
-  &.btn-small {
-    *padding-top: 3px;
-    *padding-bottom: 3px;
-  }
-  &.btn-mini {
-    *padding-top: 1px;
-    *padding-bottom: 1px;
-  }
-}
-
-
-// Link buttons
-// --------------------------------------------------
-
-// Make a button look and behave like a link
-.btn-link,
-.btn-link:active,
-.btn-link[disabled] {
-  background-color: transparent;
-  background-image: none;
-  .box-shadow(none);
-}
-.btn-link {
-  border-color: transparent;
-  cursor: pointer;
-  color: @linkColor;
-  .border-radius(0);
-}
-.btn-link:hover,
-.btn-link:focus {
-  color: @linkColorHover;
-  text-decoration: underline;
-  background-color: transparent;
-}
-.btn-link[disabled]:hover,
-.btn-link[disabled]:focus {
-  color: @grayDark;
-  text-decoration: none;
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/carousel.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/carousel.less b/apps/fauxton/assets/less/bootstrap/carousel.less
deleted file mode 100644
index 55bc050..0000000
--- a/apps/fauxton/assets/less/bootstrap/carousel.less
+++ /dev/null
@@ -1,158 +0,0 @@
-//
-// Carousel
-// --------------------------------------------------
-
-
-.carousel {
-  position: relative;
-  margin-bottom: @baseLineHeight;
-  line-height: 1;
-}
-
-.carousel-inner {
-  overflow: hidden;
-  width: 100%;
-  position: relative;
-}
-
-.carousel-inner {
-
-  > .item {
-    display: none;
-    position: relative;
-    .transition(.6s ease-in-out left);
-
-    // Account for jankitude on images
-    > img,
-    > a > img {
-      display: block;
-      line-height: 1;
-    }
-  }
-
-  > .active,
-  > .next,
-  > .prev { display: block; }
-
-  > .active {
-    left: 0;
-  }
-
-  > .next,
-  > .prev {
-    position: absolute;
-    top: 0;
-    width: 100%;
-  }
-
-  > .next {
-    left: 100%;
-  }
-  > .prev {
-    left: -100%;
-  }
-  > .next.left,
-  > .prev.right {
-    left: 0;
-  }
-
-  > .active.left {
-    left: -100%;
-  }
-  > .active.right {
-    left: 100%;
-  }
-
-}
-
-// Left/right controls for nav
-// ---------------------------
-
-.carousel-control {
-  position: absolute;
-  top: 40%;
-  left: 15px;
-  width: 40px;
-  height: 40px;
-  margin-top: -20px;
-  font-size: 60px;
-  font-weight: 100;
-  line-height: 30px;
-  color: @white;
-  text-align: center;
-  background: @grayDarker;
-  border: 3px solid @white;
-  .border-radius(23px);
-  .opacity(50);
-
-  // we can't have this transition here
-  // because webkit cancels the carousel
-  // animation if you trip this while
-  // in the middle of another animation
-  // ;_;
-  // .transition(opacity .2s linear);
-
-  // Reposition the right one
-  &.right {
-    left: auto;
-    right: 15px;
-  }
-
-  // Hover/focus state
-  &:hover,
-  &:focus {
-    color: @white;
-    text-decoration: none;
-    .opacity(90);
-  }
-}
-
-// Carousel indicator pips
-// -----------------------------
-.carousel-indicators {
-  position: absolute;
-  top: 15px;
-  right: 15px;
-  z-index: 5;
-  margin: 0;
-  list-style: none;
-
-  li {
-    display: block;
-    float: left;
-    width: 10px;
-    height: 10px;
-    margin-left: 5px;
-    text-indent: -999px;
-    background-color: #ccc;
-    background-color: rgba(255,255,255,.25);
-    border-radius: 5px;
-  }
-  .active {
-    background-color: #fff;
-  }
-}
-
-// Caption for text below images
-// -----------------------------
-
-.carousel-caption {
-  position: absolute;
-  left: 0;
-  right: 0;
-  bottom: 0;
-  padding: 15px;
-  background: @grayDark;
-  background: rgba(0,0,0,.75);
-}
-.carousel-caption h4,
-.carousel-caption p {
-  color: @white;
-  line-height: @baseLineHeight;
-}
-.carousel-caption h4 {
-  margin: 0 0 5px;
-}
-.carousel-caption p {
-  margin-bottom: 0;
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/close.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/close.less b/apps/fauxton/assets/less/bootstrap/close.less
deleted file mode 100644
index 4c626bd..0000000
--- a/apps/fauxton/assets/less/bootstrap/close.less
+++ /dev/null
@@ -1,32 +0,0 @@
-//
-// Close icons
-// --------------------------------------------------
-
-
-.close {
-  float: right;
-  font-size: 20px;
-  font-weight: bold;
-  line-height: @baseLineHeight;
-  color: @black;
-  text-shadow: 0 1px 0 rgba(255,255,255,1);
-  .opacity(20);
-  &:hover,
-  &:focus {
-    color: @black;
-    text-decoration: none;
-    cursor: pointer;
-    .opacity(40);
-  }
-}
-
-// Additional properties for button version
-// iOS requires the button element instead of an anchor tag.
-// If you want the anchor version, it requires `href="#"`.
-button.close {
-  padding: 0;
-  cursor: pointer;
-  background: transparent;
-  border: 0;
-  -webkit-appearance: none;
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/code.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/code.less b/apps/fauxton/assets/less/bootstrap/code.less
deleted file mode 100644
index 266a926..0000000
--- a/apps/fauxton/assets/less/bootstrap/code.less
+++ /dev/null
@@ -1,61 +0,0 @@
-//
-// Code (inline and blocK)
-// --------------------------------------------------
-
-
-// Inline and block code styles
-code,
-pre {
-  padding: 0 3px 2px;
-  #font > #family > .monospace;
-  font-size: @baseFontSize - 2;
-  color: @grayDark;
-  .border-radius(3px);
-}
-
-// Inline code
-code {
-  padding: 2px 4px;
-  color: #d14;
-  background-color: #f7f7f9;
-  border: 1px solid #e1e1e8;
-  white-space: nowrap;
-}
-
-// Blocks of code
-pre {
-  display: block;
-  padding: (@baseLineHeight - 1) / 2;
-  margin: 0 0 @baseLineHeight / 2;
-  font-size: @baseFontSize - 1; // 14px to 13px
-  line-height: @baseLineHeight;
-  word-break: break-all;
-  word-wrap: break-word;
-  white-space: pre;
-  white-space: pre-wrap;
-  background-color: #f5f5f5;
-  border: 1px solid #ccc; // fallback for IE7-8
-  border: 1px solid rgba(0,0,0,.15);
-  .border-radius(@baseBorderRadius);
-
-  // Make prettyprint styles more spaced out for readability
-  &.prettyprint {
-    margin-bottom: @baseLineHeight;
-  }
-
-  // Account for some code outputs that place code tags in pre tags
-  code {
-    padding: 0;
-    color: inherit;
-    white-space: pre;
-    white-space: pre-wrap;
-    background-color: transparent;
-    border: 0;
-  }
-}
-
-// Enable scrollable blocks of code
-.pre-scrollable {
-  max-height: 340px;
-  overflow-y: scroll;
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/component-animations.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/component-animations.less b/apps/fauxton/assets/less/bootstrap/component-animations.less
deleted file mode 100644
index d614263..0000000
--- a/apps/fauxton/assets/less/bootstrap/component-animations.less
+++ /dev/null
@@ -1,22 +0,0 @@
-//
-// Component animations
-// --------------------------------------------------
-
-
-.fade {
-  opacity: 0;
-  .transition(opacity .15s linear);
-  &.in {
-    opacity: 1;
-  }
-}
-
-.collapse {
-  position: relative;
-  height: 0;
-  overflow: hidden;
-  .transition(height .35s ease);
-  &.in {
-    height: auto;
-  }
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/dropdowns.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/dropdowns.less b/apps/fauxton/assets/less/bootstrap/dropdowns.less
deleted file mode 100644
index 9e47b47..0000000
--- a/apps/fauxton/assets/less/bootstrap/dropdowns.less
+++ /dev/null
@@ -1,248 +0,0 @@
-//
-// Dropdown menus
-// --------------------------------------------------
-
-
-// Use the .menu class on any <li> element within the topbar or ul.tabs and you'll get some superfancy dropdowns
-.dropup,
-.dropdown {
-  position: relative;
-}
-.dropdown-toggle {
-  // The caret makes the toggle a bit too tall in IE7
-  *margin-bottom: -3px;
-}
-.dropdown-toggle:active,
-.open .dropdown-toggle {
-  outline: 0;
-}
-
-// Dropdown arrow/caret
-// --------------------
-.caret {
-  display: inline-block;
-  width: 0;
-  height: 0;
-  vertical-align: top;
-  border-top:   4px solid @black;
-  border-right: 4px solid transparent;
-  border-left:  4px solid transparent;
-  content: "";
-}
-
-// Place the caret
-.dropdown .caret {
-  margin-top: 8px;
-  margin-left: 2px;
-}
-
-// The dropdown menu (ul)
-// ----------------------
-.dropdown-menu {
-  position: absolute;
-  top: 100%;
-  left: 0;
-  z-index: @zindexDropdown;
-  display: none; // none by default, but block on "open" of the menu
-  float: left;
-  min-width: 160px;
-  padding: 5px 0;
-  margin: 2px 0 0; // override default ul
-  list-style: none;
-  background-color: @dropdownBackground;
-  border: 1px solid #ccc; // Fallback for IE7-8
-  border: 1px solid @dropdownBorder;
-  *border-right-width: 2px;
-  *border-bottom-width: 2px;
-  .border-radius(6px);
-  .box-shadow(0 5px 10px rgba(0,0,0,.2));
-  -webkit-background-clip: padding-box;
-     -moz-background-clip: padding;
-          background-clip: padding-box;
-
-  // Aligns the dropdown menu to right
-  &.pull-right {
-    right: 0;
-    left: auto;
-  }
-
-  // Dividers (basically an hr) within the dropdown
-  .divider {
-    .nav-divider(@dropdownDividerTop, @dropdownDividerBottom);
-  }
-
-  // Links within the dropdown menu
-  > li > a {
-    display: block;
-    padding: 3px 20px;
-    clear: both;
-    font-weight: normal;
-    line-height: @baseLineHeight;
-    color: @dropdownLinkColor;
-    white-space: nowrap;
-  }
-}
-
-// Hover/Focus state
-// -----------
-.dropdown-menu > li > a:hover,
-.dropdown-menu > li > a:focus,
-.dropdown-submenu:hover > a,
-.dropdown-submenu:focus > a {
-  text-decoration: none;
-  color: @dropdownLinkColorHover;
-  #gradient > .vertical(@dropdownLinkBackgroundHover, darken(@dropdownLinkBackgroundHover, 5%));
-}
-
-// Active state
-// ------------
-.dropdown-menu > .active > a,
-.dropdown-menu > .active > a:hover,
-.dropdown-menu > .active > a:focus {
-  color: @dropdownLinkColorActive;
-  text-decoration: none;
-  outline: 0;
-  #gradient > .vertical(@dropdownLinkBackgroundActive, darken(@dropdownLinkBackgroundActive, 5%));
-}
-
-// Disabled state
-// --------------
-// Gray out text and ensure the hover/focus state remains gray
-.dropdown-menu > .disabled > a,
-.dropdown-menu > .disabled > a:hover,
-.dropdown-menu > .disabled > a:focus {
-  color: @grayLight;
-}
-// Nuke hover/focus effects
-.dropdown-menu > .disabled > a:hover,
-.dropdown-menu > .disabled > a:focus {
-  text-decoration: none;
-  background-color: transparent;
-  background-image: none; // Remove CSS gradient
-  .reset-filter();
-  cursor: default;
-}
-
-// Open state for the dropdown
-// ---------------------------
-.open {
-  // IE7's z-index only goes to the nearest positioned ancestor, which would
-  // make the menu appear below buttons that appeared later on the page
-  *z-index: @zindexDropdown;
-
-  & > .dropdown-menu {
-    display: block;
-  }
-}
-
-// Backdrop to catch body clicks on mobile, etc.
-// ---------------------------
-.dropdown-backdrop {
-  position: fixed;
-  left: 0;
-  right: 0;
-  bottom: 0;
-  top: 0;
-  z-index: @zindexDropdown - 10;
-}
-
-// Right aligned dropdowns
-// ---------------------------
-.pull-right > .dropdown-menu {
-  right: 0;
-  left: auto;
-}
-
-// Allow for dropdowns to go bottom up (aka, dropup-menu)
-// ------------------------------------------------------
-// Just add .dropup after the standard .dropdown class and you're set, bro.
-// TODO: abstract this so that the navbar fixed styles are not placed here?
-.dropup,
-.navbar-fixed-bottom .dropdown {
-  // Reverse the caret
-  .caret {
-    border-top: 0;
-    border-bottom: 4px solid @black;
-    content: "";
-  }
-  // Different positioning for bottom up menu
-  .dropdown-menu {
-    top: auto;
-    bottom: 100%;
-    margin-bottom: 1px;
-  }
-}
-
-// Sub menus
-// ---------------------------
-.dropdown-submenu {
-  position: relative;
-}
-// Default dropdowns
-.dropdown-submenu > .dropdown-menu {
-  top: 0;
-  left: 100%;
-  margin-top: -6px;
-  margin-left: -1px;
-  .border-radius(0 6px 6px 6px);
-}
-.dropdown-submenu:hover > .dropdown-menu {
-  display: block;
-}
-
-// Dropups
-.dropup .dropdown-submenu > .dropdown-menu {
-  top: auto;
-  bottom: 0;
-  margin-top: 0;
-  margin-bottom: -2px;
-  .border-radius(5px 5px 5px 0);
-}
-
-// Caret to indicate there is a submenu
-.dropdown-submenu > a:after {
-  display: block;
-  content: " ";
-  float: right;
-  width: 0;
-  height: 0;
-  border-color: transparent;
-  border-style: solid;
-  border-width: 5px 0 5px 5px;
-  border-left-color: darken(@dropdownBackground, 20%);
-  margin-top: 5px;
-  margin-right: -10px;
-}
-.dropdown-submenu:hover > a:after {
-  border-left-color: @dropdownLinkColorHover;
-}
-
-// Left aligned submenus
-.dropdown-submenu.pull-left {
-  // Undo the float
-  // Yes, this is awkward since .pull-left adds a float, but it sticks to our conventions elsewhere.
-  float: none;
-
-  // Positioning the submenu
-  > .dropdown-menu {
-    left: -100%;
-    margin-left: 10px;
-    .border-radius(6px 0 6px 6px);
-  }
-}
-
-// Tweak nav headers
-// -----------------
-// Increase padding from 15px to 20px on sides
-.dropdown .dropdown-menu .nav-header {
-  padding-left: 20px;
-  padding-right: 20px;
-}
-
-// Typeahead
-// ---------
-.typeahead {
-  z-index: 1051;
-  margin-top: 2px; // give it some space to breathe
-  .border-radius(@baseBorderRadius);
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/font-awesome/bootstrap.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/font-awesome/bootstrap.less b/apps/fauxton/assets/less/bootstrap/font-awesome/bootstrap.less
deleted file mode 100644
index a2c9604..0000000
--- a/apps/fauxton/assets/less/bootstrap/font-awesome/bootstrap.less
+++ /dev/null
@@ -1,84 +0,0 @@
-/* BOOTSTRAP SPECIFIC CLASSES
- * -------------------------- */
-
-/* Bootstrap 2.0 sprites.less reset */
-[class^="icon-"],
-[class*=" icon-"] {
-  display: inline;
-  width: auto;
-  height: auto;
-  line-height: normal;
-  vertical-align: baseline;
-  background-image: none;
-  background-position: 0% 0%;
-  background-repeat: repeat;
-  margin-top: 0;
-}
-
-/* more sprites.less reset */
-.icon-white,
-.nav-pills > .active > a > [class^="icon-"],
-.nav-pills > .active > a > [class*=" icon-"],
-.nav-list > .active > a > [class^="icon-"],
-.nav-list > .active > a > [class*=" icon-"],
-.navbar-inverse .nav > .active > a > [class^="icon-"],
-.navbar-inverse .nav > .active > a > [class*=" icon-"],
-.dropdown-menu > li > a:hover > [class^="icon-"],
-.dropdown-menu > li > a:hover > [class*=" icon-"],
-.dropdown-menu > .active > a > [class^="icon-"],
-.dropdown-menu > .active > a > [class*=" icon-"],
-.dropdown-submenu:hover > a > [class^="icon-"],
-.dropdown-submenu:hover > a > [class*=" icon-"] {
-  background-image: none;
-}
-
-
-/* keeps Bootstrap styles with and without icons the same */
-.btn, .nav {
-  [class^="icon-"],
-  [class*=" icon-"] {
-//    display: inline;
-    &.icon-large { line-height: .9em; }
-    &.icon-spin { display: inline-block; }
-  }
-}
-.nav-tabs, .nav-pills {
-  [class^="icon-"],
-  [class*=" icon-"] {
-    &, &.icon-large { line-height: .9em; }
-  }
-}
-.btn {
-  [class^="icon-"],
-  [class*=" icon-"] {
-    &.pull-left, &.pull-right {
-      &.icon-2x { margin-top: .18em; }
-    }
-    &.icon-spin.icon-large { line-height: .8em; }
-  }
-}
-.btn.btn-small {
-  [class^="icon-"],
-  [class*=" icon-"] {
-    &.pull-left, &.pull-right {
-      &.icon-2x { margin-top: .25em; }
-    }
-  }
-}
-.btn.btn-large {
-  [class^="icon-"],
-  [class*=" icon-"] {
-    margin-top: 0; // overrides bootstrap default
-    &.pull-left, &.pull-right {
-      &.icon-2x { margin-top: .05em; }
-    }
-    &.pull-left.icon-2x { margin-right: .2em; }
-    &.pull-right.icon-2x { margin-left: .2em; }
-  }
-}
-
-/* Fixes alignment in nav lists */
-.nav-list [class^="icon-"],
-.nav-list [class*=" icon-"] {
-  line-height: inherit;
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/font-awesome/core.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/font-awesome/core.less b/apps/fauxton/assets/less/bootstrap/font-awesome/core.less
deleted file mode 100644
index 1ef7e22..0000000
--- a/apps/fauxton/assets/less/bootstrap/font-awesome/core.less
+++ /dev/null
@@ -1,129 +0,0 @@
-/* FONT AWESOME CORE
- * -------------------------- */
-
-[class^="icon-"],
-[class*=" icon-"] {
-  .icon-FontAwesome();
-}
-
-[class^="icon-"]:before,
-[class*=" icon-"]:before {
-  text-decoration: inherit;
-  display: inline-block;
-  speak: none;
-}
-
-/* makes the font 33% larger relative to the icon container */
-.icon-large:before {
-  vertical-align: -10%;
-  font-size: 4/3em;
-}
-
-/* makes sure icons active on rollover in links */
-a {
-  [class^="icon-"],
-  [class*=" icon-"] {
-    display: inline;
-  }
-}
-
-/* increased font size for icon-large */
-[class^="icon-"],
-[class*=" icon-"] {
-  &.icon-fixed-width {
-    display: inline-block;
-    width: 16/14em;
-    text-align: right;
-    padding-right: 4/14em;
-    &.icon-large {
-      width: 20/14em;
-    }
-  }
-}
-
-.icons-ul {
-  margin-left: @icons-li-width;
-  list-style-type: none;
-
-  > li { position: relative; }
-
-  .icon-li {
-    position: absolute;
-    left: -@icons-li-width;
-    width: @icons-li-width;
-    text-align: center;
-    line-height: inherit;
-  }
-}
-
-// allows usage of the hide class directly on font awesome icons
-[class^="icon-"],
-[class*=" icon-"] {
-  &.hide {
-    display: none;
-  }
-}
-
-.icon-muted { color: @iconMuted; }
-.icon-light { color: @iconLight; }
-.icon-dark { color: @iconDark; }
-
-// Icon Borders
-// -------------------------
-
-.icon-border {
-  border: solid 1px @borderColor;
-  padding: .2em .25em .15em;
-  .border-radius(3px);
-}
-
-// Icon Sizes
-// -------------------------
-
-.icon-2x {
-  font-size: 2em;
-  &.icon-border {
-    border-width: 2px;
-    .border-radius(4px);
-  }
-}
-.icon-3x {
-  font-size: 3em;
-  &.icon-border {
-    border-width: 3px;
-    .border-radius(5px);
-  }
-}
-.icon-4x {
-  font-size: 4em;
-  &.icon-border {
-    border-width: 4px;
-    .border-radius(6px);
-  }
-}
-
-.icon-5x {
-  font-size: 5em;
-  &.icon-border {
-    border-width: 5px;
-    .border-radius(7px);
-  }
-}
-
-
-// Floats & Margins
-// -------------------------
-
-// Quick floats
-.pull-right { float: right; }
-.pull-left { float: left; }
-
-[class^="icon-"],
-[class*=" icon-"] {
-  &.pull-left {
-    margin-right: .3em;
-  }
-  &.pull-right {
-    margin-left: .3em;
-  }
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/font-awesome/extras.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/font-awesome/extras.less b/apps/fauxton/assets/less/bootstrap/font-awesome/extras.less
deleted file mode 100644
index c93c260..0000000
--- a/apps/fauxton/assets/less/bootstrap/font-awesome/extras.less
+++ /dev/null
@@ -1,93 +0,0 @@
-/* EXTRAS
- * -------------------------- */
-
-/* Stacked and layered icon */
-.icon-stack();
-
-/* Animated rotating icon */
-.icon-spin {
-  display: inline-block;
-  -moz-animation: spin 2s infinite linear;
-  -o-animation: spin 2s infinite linear;
-  -webkit-animation: spin 2s infinite linear;
-  animation: spin 2s infinite linear;
-}
-
-/* Prevent stack and spinners from being taken inline when inside a link */
-a .icon-stack,
-a .icon-spin {
-  display: inline-block;
-  text-decoration: none;
-}
-
-@-moz-keyframes spin {
-  0% { -moz-transform: rotate(0deg); }
-  100% { -moz-transform: rotate(359deg); }
-}
-@-webkit-keyframes spin {
-  0% { -webkit-transform: rotate(0deg); }
-  100% { -webkit-transform: rotate(359deg); }
-}
-@-o-keyframes spin {
-  0% { -o-transform: rotate(0deg); }
-  100% { -o-transform: rotate(359deg); }
-}
-@-ms-keyframes spin {
-  0% { -ms-transform: rotate(0deg); }
-  100% { -ms-transform: rotate(359deg); }
-}
-@keyframes spin {
-  0% { transform: rotate(0deg); }
-  100% { transform: rotate(359deg); }
-}
-
-/* Icon rotations and mirroring */
-.icon-rotate-90:before {
-  -webkit-transform: rotate(90deg);
-  -moz-transform: rotate(90deg);
-  -ms-transform: rotate(90deg);
-  -o-transform: rotate(90deg);
-  transform: rotate(90deg);
-  filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=1);
-}
-
-.icon-rotate-180:before {
-  -webkit-transform: rotate(180deg);
-  -moz-transform: rotate(180deg);
-  -ms-transform: rotate(180deg);
-  -o-transform: rotate(180deg);
-  transform: rotate(180deg);
-  filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=2);
-}
-
-.icon-rotate-270:before {
-  -webkit-transform: rotate(270deg);
-  -moz-transform: rotate(270deg);
-  -ms-transform: rotate(270deg);
-  -o-transform: rotate(270deg);
-  transform: rotate(270deg);
-  filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);
-}
-
-.icon-flip-horizontal:before {
-  -webkit-transform: scale(-1, 1);
-  -moz-transform: scale(-1, 1);
-  -ms-transform: scale(-1, 1);
-  -o-transform: scale(-1, 1);
-  transform: scale(-1, 1);
-}
-
-.icon-flip-vertical:before {
-  -webkit-transform: scale(1, -1);
-  -moz-transform: scale(1, -1);
-  -ms-transform: scale(1, -1);
-  -o-transform: scale(1, -1);
-  transform: scale(1, -1);
-}
-
-/* ensure rotation occurs inside anchor tags */
-a {
-  .icon-rotate-90, .icon-rotate-180, .icon-rotate-270, .icon-flip-horizontal, .icon-flip-vertical {
-    &:before { display: inline-block; }
-  }
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/font-awesome/font-awesome-ie7.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/font-awesome/font-awesome-ie7.less b/apps/fauxton/assets/less/bootstrap/font-awesome/font-awesome-ie7.less
deleted file mode 100644
index 6675c49..0000000
--- a/apps/fauxton/assets/less/bootstrap/font-awesome/font-awesome-ie7.less
+++ /dev/null
@@ -1,1953 +0,0 @@
-/*!
- *  Font Awesome 3.2.1
- *  the iconic font designed for Bootstrap
- *  ------------------------------------------------------------------------------
- *  The full suite of pictographic icons, examples, and documentation can be
- *  found at http://fontawesome.io.  Stay up to date on Twitter at
- *  http://twitter.com/fontawesome.
- *
- *  License
- *  ------------------------------------------------------------------------------
- *  - The Font Awesome font is licensed under SIL OFL 1.1 -
- *    http://scripts.sil.org/OFL
- *  - Font Awesome CSS, LESS, and SASS files are licensed under MIT License -
- *    http://opensource.org/licenses/mit-license.html
- *  - Font Awesome documentation licensed under CC BY 3.0 -
- *    http://creativecommons.org/licenses/by/3.0/
- *  - Attribution is no longer required in Font Awesome 3.0, but much appreciated:
- *    "Font Awesome by Dave Gandy - http://fontawesome.io"
- *
- *  Author - Dave Gandy
- *  ------------------------------------------------------------------------------
- *  Email: dave@fontawesome.io
- *  Twitter: http://twitter.com/davegandy
- *  Work: Lead Product Designer @ Kyruus - http://kyruus.com
- */
-
-.icon-large {
-  font-size: 4/3em;
-  margin-top: -4px;
-  padding-top: 3px;
-  margin-bottom: -4px;
-  padding-bottom: 3px;
-  vertical-align: middle;
-}
-
-.nav {
-  [class^="icon-"],
-  [class*=" icon-"] {
-    vertical-align: inherit;
-    margin-top: -4px;
-    padding-top: 3px;
-    margin-bottom: -4px;
-    padding-bottom: 3px;
-    &.icon-large {
-      vertical-align: -25%;
-    }
-  }
-}
-
-.nav-pills, .nav-tabs {
-  [class^="icon-"],
-  [class*=" icon-"] {
-    &.icon-large {
-      line-height: .75em;
-      margin-top: -7px;
-      padding-top: 5px;
-      margin-bottom: -5px;
-      padding-bottom: 4px;
-    }
-  }
-}
-
-.btn {
-  [class^="icon-"],
-  [class*=" icon-"] {
-    &.pull-left, &.pull-right { vertical-align: inherit; }
-    &.icon-large {
-      margin-top: -.5em;
-    }
-  }
-}
-
-a [class^="icon-"],
-a [class*=" icon-"] {
-  cursor: pointer;
-}
-
-.ie7icon(@inner) { *zoom: ~"expression( this.runtimeStyle['zoom'] = '1', this.innerHTML = '@{inner}')"; }
-
-
-.icon-glass {
-  .ie7icon('&#xf000;');
-}
-
-
-.icon-music {
-  .ie7icon('&#xf001;');
-}
-
-
-.icon-search {
-  .ie7icon('&#xf002;');
-}
-
-
-.icon-envelope-alt {
-  .ie7icon('&#xf003;');
-}
-
-
-.icon-heart {
-  .ie7icon('&#xf004;');
-}
-
-
-.icon-star {
-  .ie7icon('&#xf005;');
-}
-
-
-.icon-star-empty {
-  .ie7icon('&#xf006;');
-}
-
-
-.icon-user {
-  .ie7icon('&#xf007;');
-}
-
-
-.icon-film {
-  .ie7icon('&#xf008;');
-}
-
-
-.icon-th-large {
-  .ie7icon('&#xf009;');
-}
-
-
-.icon-th {
-  .ie7icon('&#xf00a;');
-}
-
-
-.icon-th-list {
-  .ie7icon('&#xf00b;');
-}
-
-
-.icon-ok {
-  .ie7icon('&#xf00c;');
-}
-
-
-.icon-remove {
-  .ie7icon('&#xf00d;');
-}
-
-
-.icon-zoom-in {
-  .ie7icon('&#xf00e;');
-}
-
-
-.icon-zoom-out {
-  .ie7icon('&#xf010;');
-}
-
-
-.icon-off {
-  .ie7icon('&#xf011;');
-}
-
-.icon-power-off {
-  .ie7icon('&#xf011;');
-}
-
-
-.icon-signal {
-  .ie7icon('&#xf012;');
-}
-
-
-.icon-cog {
-  .ie7icon('&#xf013;');
-}
-
-.icon-gear {
-  .ie7icon('&#xf013;');
-}
-
-
-.icon-trash {
-  .ie7icon('&#xf014;');
-}
-
-
-.icon-home {
-  .ie7icon('&#xf015;');
-}
-
-
-.icon-file-alt {
-  .ie7icon('&#xf016;');
-}
-
-
-.icon-time {
-  .ie7icon('&#xf017;');
-}
-
-
-.icon-road {
-  .ie7icon('&#xf018;');
-}
-
-
-.icon-download-alt {
-  .ie7icon('&#xf019;');
-}
-
-
-.icon-download {
-  .ie7icon('&#xf01a;');
-}
-
-
-.icon-upload {
-  .ie7icon('&#xf01b;');
-}
-
-
-.icon-inbox {
-  .ie7icon('&#xf01c;');
-}
-
-
-.icon-play-circle {
-  .ie7icon('&#xf01d;');
-}
-
-
-.icon-repeat {
-  .ie7icon('&#xf01e;');
-}
-
-.icon-rotate-right {
-  .ie7icon('&#xf01e;');
-}
-
-
-.icon-refresh {
-  .ie7icon('&#xf021;');
-}
-
-
-.icon-list-alt {
-  .ie7icon('&#xf022;');
-}
-
-
-.icon-lock {
-  .ie7icon('&#xf023;');
-}
-
-
-.icon-flag {
-  .ie7icon('&#xf024;');
-}
-
-
-.icon-headphones {
-  .ie7icon('&#xf025;');
-}
-
-
-.icon-volume-off {
-  .ie7icon('&#xf026;');
-}
-
-
-.icon-volume-down {
-  .ie7icon('&#xf027;');
-}
-
-
-.icon-volume-up {
-  .ie7icon('&#xf028;');
-}
-
-
-.icon-qrcode {
-  .ie7icon('&#xf029;');
-}
-
-
-.icon-barcode {
-  .ie7icon('&#xf02a;');
-}
-
-
-.icon-tag {
-  .ie7icon('&#xf02b;');
-}
-
-
-.icon-tags {
-  .ie7icon('&#xf02c;');
-}
-
-
-.icon-book {
-  .ie7icon('&#xf02d;');
-}
-
-
-.icon-bookmark {
-  .ie7icon('&#xf02e;');
-}
-
-
-.icon-print {
-  .ie7icon('&#xf02f;');
-}
-
-
-.icon-camera {
-  .ie7icon('&#xf030;');
-}
-
-
-.icon-font {
-  .ie7icon('&#xf031;');
-}
-
-
-.icon-bold {
-  .ie7icon('&#xf032;');
-}
-
-
-.icon-italic {
-  .ie7icon('&#xf033;');
-}
-
-
-.icon-text-height {
-  .ie7icon('&#xf034;');
-}
-
-
-.icon-text-width {
-  .ie7icon('&#xf035;');
-}
-
-
-.icon-align-left {
-  .ie7icon('&#xf036;');
-}
-
-
-.icon-align-center {
-  .ie7icon('&#xf037;');
-}
-
-
-.icon-align-right {
-  .ie7icon('&#xf038;');
-}
-
-
-.icon-align-justify {
-  .ie7icon('&#xf039;');
-}
-
-
-.icon-list {
-  .ie7icon('&#xf03a;');
-}
-
-
-.icon-indent-left {
-  .ie7icon('&#xf03b;');
-}
-
-
-.icon-indent-right {
-  .ie7icon('&#xf03c;');
-}
-
-
-.icon-facetime-video {
-  .ie7icon('&#xf03d;');
-}
-
-
-.icon-picture {
-  .ie7icon('&#xf03e;');
-}
-
-
-.icon-pencil {
-  .ie7icon('&#xf040;');
-}
-
-
-.icon-map-marker {
-  .ie7icon('&#xf041;');
-}
-
-
-.icon-adjust {
-  .ie7icon('&#xf042;');
-}
-
-
-.icon-tint {
-  .ie7icon('&#xf043;');
-}
-
-
-.icon-edit {
-  .ie7icon('&#xf044;');
-}
-
-
-.icon-share {
-  .ie7icon('&#xf045;');
-}
-
-
-.icon-check {
-  .ie7icon('&#xf046;');
-}
-
-
-.icon-move {
-  .ie7icon('&#xf047;');
-}
-
-
-.icon-step-backward {
-  .ie7icon('&#xf048;');
-}
-
-
-.icon-fast-backward {
-  .ie7icon('&#xf049;');
-}
-
-
-.icon-backward {
-  .ie7icon('&#xf04a;');
-}
-
-
-.icon-play {
-  .ie7icon('&#xf04b;');
-}
-
-
-.icon-pause {
-  .ie7icon('&#xf04c;');
-}
-
-
-.icon-stop {
-  .ie7icon('&#xf04d;');
-}
-
-
-.icon-forward {
-  .ie7icon('&#xf04e;');
-}
-
-
-.icon-fast-forward {
-  .ie7icon('&#xf050;');
-}
-
-
-.icon-step-forward {
-  .ie7icon('&#xf051;');
-}
-
-
-.icon-eject {
-  .ie7icon('&#xf052;');
-}
-
-
-.icon-chevron-left {
-  .ie7icon('&#xf053;');
-}
-
-
-.icon-chevron-right {
-  .ie7icon('&#xf054;');
-}
-
-
-.icon-plus-sign {
-  .ie7icon('&#xf055;');
-}
-
-
-.icon-minus-sign {
-  .ie7icon('&#xf056;');
-}
-
-
-.icon-remove-sign {
-  .ie7icon('&#xf057;');
-}
-
-
-.icon-ok-sign {
-  .ie7icon('&#xf058;');
-}
-
-
-.icon-question-sign {
-  .ie7icon('&#xf059;');
-}
-
-
-.icon-info-sign {
-  .ie7icon('&#xf05a;');
-}
-
-
-.icon-screenshot {
-  .ie7icon('&#xf05b;');
-}
-
-
-.icon-remove-circle {
-  .ie7icon('&#xf05c;');
-}
-
-
-.icon-ok-circle {
-  .ie7icon('&#xf05d;');
-}
-
-
-.icon-ban-circle {
-  .ie7icon('&#xf05e;');
-}
-
-
-.icon-arrow-left {
-  .ie7icon('&#xf060;');
-}
-
-
-.icon-arrow-right {
-  .ie7icon('&#xf061;');
-}
-
-
-.icon-arrow-up {
-  .ie7icon('&#xf062;');
-}
-
-
-.icon-arrow-down {
-  .ie7icon('&#xf063;');
-}
-
-
-.icon-share-alt {
-  .ie7icon('&#xf064;');
-}
-
-.icon-mail-forward {
-  .ie7icon('&#xf064;');
-}
-
-
-.icon-resize-full {
-  .ie7icon('&#xf065;');
-}
-
-
-.icon-resize-small {
-  .ie7icon('&#xf066;');
-}
-
-
-.icon-plus {
-  .ie7icon('&#xf067;');
-}
-
-
-.icon-minus {
-  .ie7icon('&#xf068;');
-}
-
-
-.icon-asterisk {
-  .ie7icon('&#xf069;');
-}
-
-
-.icon-exclamation-sign {
-  .ie7icon('&#xf06a;');
-}
-
-
-.icon-gift {
-  .ie7icon('&#xf06b;');
-}
-
-
-.icon-leaf {
-  .ie7icon('&#xf06c;');
-}
-
-
-.icon-fire {
-  .ie7icon('&#xf06d;');
-}
-
-
-.icon-eye-open {
-  .ie7icon('&#xf06e;');
-}
-
-
-.icon-eye-close {
-  .ie7icon('&#xf070;');
-}
-
-
-.icon-warning-sign {
-  .ie7icon('&#xf071;');
-}
-
-
-.icon-plane {
-  .ie7icon('&#xf072;');
-}
-
-
-.icon-calendar {
-  .ie7icon('&#xf073;');
-}
-
-
-.icon-random {
-  .ie7icon('&#xf074;');
-}
-
-
-.icon-comment {
-  .ie7icon('&#xf075;');
-}
-
-
-.icon-magnet {
-  .ie7icon('&#xf076;');
-}
-
-
-.icon-chevron-up {
-  .ie7icon('&#xf077;');
-}
-
-
-.icon-chevron-down {
-  .ie7icon('&#xf078;');
-}
-
-
-.icon-retweet {
-  .ie7icon('&#xf079;');
-}
-
-
-.icon-shopping-cart {
-  .ie7icon('&#xf07a;');
-}
-
-
-.icon-folder-close {
-  .ie7icon('&#xf07b;');
-}
-
-
-.icon-folder-open {
-  .ie7icon('&#xf07c;');
-}
-
-
-.icon-resize-vertical {
-  .ie7icon('&#xf07d;');
-}
-
-
-.icon-resize-horizontal {
-  .ie7icon('&#xf07e;');
-}
-
-
-.icon-bar-chart {
-  .ie7icon('&#xf080;');
-}
-
-
-.icon-twitter-sign {
-  .ie7icon('&#xf081;');
-}
-
-
-.icon-facebook-sign {
-  .ie7icon('&#xf082;');
-}
-
-
-.icon-camera-retro {
-  .ie7icon('&#xf083;');
-}
-
-
-.icon-key {
-  .ie7icon('&#xf084;');
-}
-
-
-.icon-cogs {
-  .ie7icon('&#xf085;');
-}
-
-.icon-gears {
-  .ie7icon('&#xf085;');
-}
-
-
-.icon-comments {
-  .ie7icon('&#xf086;');
-}
-
-
-.icon-thumbs-up-alt {
-  .ie7icon('&#xf087;');
-}
-
-
-.icon-thumbs-down-alt {
-  .ie7icon('&#xf088;');
-}
-
-
-.icon-star-half {
-  .ie7icon('&#xf089;');
-}
-
-
-.icon-heart-empty {
-  .ie7icon('&#xf08a;');
-}
-
-
-.icon-signout {
-  .ie7icon('&#xf08b;');
-}
-
-
-.icon-linkedin-sign {
-  .ie7icon('&#xf08c;');
-}
-
-
-.icon-pushpin {
-  .ie7icon('&#xf08d;');
-}
-
-
-.icon-external-link {
-  .ie7icon('&#xf08e;');
-}
-
-
-.icon-signin {
-  .ie7icon('&#xf090;');
-}
-
-
-.icon-trophy {
-  .ie7icon('&#xf091;');
-}
-
-
-.icon-github-sign {
-  .ie7icon('&#xf092;');
-}
-
-
-.icon-upload-alt {
-  .ie7icon('&#xf093;');
-}
-
-
-.icon-lemon {
-  .ie7icon('&#xf094;');
-}
-
-
-.icon-phone {
-  .ie7icon('&#xf095;');
-}
-
-
-.icon-check-empty {
-  .ie7icon('&#xf096;');
-}
-
-.icon-unchecked {
-  .ie7icon('&#xf096;');
-}
-
-
-.icon-bookmark-empty {
-  .ie7icon('&#xf097;');
-}
-
-
-.icon-phone-sign {
-  .ie7icon('&#xf098;');
-}
-
-
-.icon-twitter {
-  .ie7icon('&#xf099;');
-}
-
-
-.icon-facebook {
-  .ie7icon('&#xf09a;');
-}
-
-
-.icon-github {
-  .ie7icon('&#xf09b;');
-}
-
-
-.icon-unlock {
-  .ie7icon('&#xf09c;');
-}
-
-
-.icon-credit-card {
-  .ie7icon('&#xf09d;');
-}
-
-
-.icon-rss {
-  .ie7icon('&#xf09e;');
-}
-
-
-.icon-hdd {
-  .ie7icon('&#xf0a0;');
-}
-
-
-.icon-bullhorn {
-  .ie7icon('&#xf0a1;');
-}
-
-
-.icon-bell {
-  .ie7icon('&#xf0a2;');
-}
-
-
-.icon-certificate {
-  .ie7icon('&#xf0a3;');
-}
-
-
-.icon-hand-right {
-  .ie7icon('&#xf0a4;');
-}
-
-
-.icon-hand-left {
-  .ie7icon('&#xf0a5;');
-}
-
-
-.icon-hand-up {
-  .ie7icon('&#xf0a6;');
-}
-
-
-.icon-hand-down {
-  .ie7icon('&#xf0a7;');
-}
-
-
-.icon-circle-arrow-left {
-  .ie7icon('&#xf0a8;');
-}
-
-
-.icon-circle-arrow-right {
-  .ie7icon('&#xf0a9;');
-}
-
-
-.icon-circle-arrow-up {
-  .ie7icon('&#xf0aa;');
-}
-
-
-.icon-circle-arrow-down {
-  .ie7icon('&#xf0ab;');
-}
-
-
-.icon-globe {
-  .ie7icon('&#xf0ac;');
-}
-
-
-.icon-wrench {
-  .ie7icon('&#xf0ad;');
-}
-
-
-.icon-tasks {
-  .ie7icon('&#xf0ae;');
-}
-
-
-.icon-filter {
-  .ie7icon('&#xf0b0;');
-}
-
-
-.icon-briefcase {
-  .ie7icon('&#xf0b1;');
-}
-
-
-.icon-fullscreen {
-  .ie7icon('&#xf0b2;');
-}
-
-
-.icon-group {
-  .ie7icon('&#xf0c0;');
-}
-
-
-.icon-link {
-  .ie7icon('&#xf0c1;');
-}
-
-
-.icon-cloud {
-  .ie7icon('&#xf0c2;');
-}
-
-
-.icon-beaker {
-  .ie7icon('&#xf0c3;');
-}
-
-
-.icon-cut {
-  .ie7icon('&#xf0c4;');
-}
-
-
-.icon-copy {
-  .ie7icon('&#xf0c5;');
-}
-
-
-.icon-paper-clip {
-  .ie7icon('&#xf0c6;');
-}
-
-.icon-paperclip {
-  .ie7icon('&#xf0c6;');
-}
-
-
-.icon-save {
-  .ie7icon('&#xf0c7;');
-}
-
-
-.icon-sign-blank {
-  .ie7icon('&#xf0c8;');
-}
-
-
-.icon-reorder {
-  .ie7icon('&#xf0c9;');
-}
-
-
-.icon-list-ul {
-  .ie7icon('&#xf0ca;');
-}
-
-
-.icon-list-ol {
-  .ie7icon('&#xf0cb;');
-}
-
-
-.icon-strikethrough {
-  .ie7icon('&#xf0cc;');
-}
-
-
-.icon-underline {
-  .ie7icon('&#xf0cd;');
-}
-
-
-.icon-table {
-  .ie7icon('&#xf0ce;');
-}
-
-
-.icon-magic {
-  .ie7icon('&#xf0d0;');
-}
-
-
-.icon-truck {
-  .ie7icon('&#xf0d1;');
-}
-
-
-.icon-pinterest {
-  .ie7icon('&#xf0d2;');
-}
-
-
-.icon-pinterest-sign {
-  .ie7icon('&#xf0d3;');
-}
-
-
-.icon-google-plus-sign {
-  .ie7icon('&#xf0d4;');
-}
-
-
-.icon-google-plus {
-  .ie7icon('&#xf0d5;');
-}
-
-
-.icon-money {
-  .ie7icon('&#xf0d6;');
-}
-
-
-.icon-caret-down {
-  .ie7icon('&#xf0d7;');
-}
-
-
-.icon-caret-up {
-  .ie7icon('&#xf0d8;');
-}
-
-
-.icon-caret-left {
-  .ie7icon('&#xf0d9;');
-}
-
-
-.icon-caret-right {
-  .ie7icon('&#xf0da;');
-}
-
-
-.icon-columns {
-  .ie7icon('&#xf0db;');
-}
-
-
-.icon-sort {
-  .ie7icon('&#xf0dc;');
-}
-
-
-.icon-sort-down {
-  .ie7icon('&#xf0dd;');
-}
-
-
-.icon-sort-up {
-  .ie7icon('&#xf0de;');
-}
-
-
-.icon-envelope {
-  .ie7icon('&#xf0e0;');
-}
-
-
-.icon-linkedin {
-  .ie7icon('&#xf0e1;');
-}
-
-
-.icon-undo {
-  .ie7icon('&#xf0e2;');
-}
-
-.icon-rotate-left {
-  .ie7icon('&#xf0e2;');
-}
-
-
-.icon-legal {
-  .ie7icon('&#xf0e3;');
-}
-
-
-.icon-dashboard {
-  .ie7icon('&#xf0e4;');
-}
-
-
-.icon-comment-alt {
-  .ie7icon('&#xf0e5;');
-}
-
-
-.icon-comments-alt {
-  .ie7icon('&#xf0e6;');
-}
-
-
-.icon-bolt {
-  .ie7icon('&#xf0e7;');
-}
-
-
-.icon-sitemap {
-  .ie7icon('&#xf0e8;');
-}
-
-
-.icon-umbrella {
-  .ie7icon('&#xf0e9;');
-}
-
-
-.icon-paste {
-  .ie7icon('&#xf0ea;');
-}
-
-
-.icon-lightbulb {
-  .ie7icon('&#xf0eb;');
-}
-
-
-.icon-exchange {
-  .ie7icon('&#xf0ec;');
-}
-
-
-.icon-cloud-download {
-  .ie7icon('&#xf0ed;');
-}
-
-
-.icon-cloud-upload {
-  .ie7icon('&#xf0ee;');
-}
-
-
-.icon-user-md {
-  .ie7icon('&#xf0f0;');
-}
-
-
-.icon-stethoscope {
-  .ie7icon('&#xf0f1;');
-}
-
-
-.icon-suitcase {
-  .ie7icon('&#xf0f2;');
-}
-
-
-.icon-bell-alt {
-  .ie7icon('&#xf0f3;');
-}
-
-
-.icon-coffee {
-  .ie7icon('&#xf0f4;');
-}
-
-
-.icon-food {
-  .ie7icon('&#xf0f5;');
-}
-
-
-.icon-file-text-alt {
-  .ie7icon('&#xf0f6;');
-}
-
-
-.icon-building {
-  .ie7icon('&#xf0f7;');
-}
-
-
-.icon-hospital {
-  .ie7icon('&#xf0f8;');
-}
-
-
-.icon-ambulance {
-  .ie7icon('&#xf0f9;');
-}
-
-
-.icon-medkit {
-  .ie7icon('&#xf0fa;');
-}
-
-
-.icon-fighter-jet {
-  .ie7icon('&#xf0fb;');
-}
-
-
-.icon-beer {
-  .ie7icon('&#xf0fc;');
-}
-
-
-.icon-h-sign {
-  .ie7icon('&#xf0fd;');
-}
-
-
-.icon-plus-sign-alt {
-  .ie7icon('&#xf0fe;');
-}
-
-
-.icon-double-angle-left {
-  .ie7icon('&#xf100;');
-}
-
-
-.icon-double-angle-right {
-  .ie7icon('&#xf101;');
-}
-
-
-.icon-double-angle-up {
-  .ie7icon('&#xf102;');
-}
-
-
-.icon-double-angle-down {
-  .ie7icon('&#xf103;');
-}
-
-
-.icon-angle-left {
-  .ie7icon('&#xf104;');
-}
-
-
-.icon-angle-right {
-  .ie7icon('&#xf105;');
-}
-
-
-.icon-angle-up {
-  .ie7icon('&#xf106;');
-}
-
-
-.icon-angle-down {
-  .ie7icon('&#xf107;');
-}
-
-
-.icon-desktop {
-  .ie7icon('&#xf108;');
-}
-
-
-.icon-laptop {
-  .ie7icon('&#xf109;');
-}
-
-
-.icon-tablet {
-  .ie7icon('&#xf10a;');
-}
-
-
-.icon-mobile-phone {
-  .ie7icon('&#xf10b;');
-}
-
-
-.icon-circle-blank {
-  .ie7icon('&#xf10c;');
-}
-
-
-.icon-quote-left {
-  .ie7icon('&#xf10d;');
-}
-
-
-.icon-quote-right {
-  .ie7icon('&#xf10e;');
-}
-
-
-.icon-spinner {
-  .ie7icon('&#xf110;');
-}
-
-
-.icon-circle {
-  .ie7icon('&#xf111;');
-}
-
-
-.icon-reply {
-  .ie7icon('&#xf112;');
-}
-
-.icon-mail-reply {
-  .ie7icon('&#xf112;');
-}
-
-
-.icon-github-alt {
-  .ie7icon('&#xf113;');
-}
-
-
-.icon-folder-close-alt {
-  .ie7icon('&#xf114;');
-}
-
-
-.icon-folder-open-alt {
-  .ie7icon('&#xf115;');
-}
-
-
-.icon-expand-alt {
-  .ie7icon('&#xf116;');
-}
-
-
-.icon-collapse-alt {
-  .ie7icon('&#xf117;');
-}
-
-
-.icon-smile {
-  .ie7icon('&#xf118;');
-}
-
-
-.icon-frown {
-  .ie7icon('&#xf119;');
-}
-
-
-.icon-meh {
-  .ie7icon('&#xf11a;');
-}
-
-
-.icon-gamepad {
-  .ie7icon('&#xf11b;');
-}
-
-
-.icon-keyboard {
-  .ie7icon('&#xf11c;');
-}
-
-
-.icon-flag-alt {
-  .ie7icon('&#xf11d;');
-}
-
-
-.icon-flag-checkered {
-  .ie7icon('&#xf11e;');
-}
-
-
-.icon-terminal {
-  .ie7icon('&#xf120;');
-}
-
-
-.icon-code {
-  .ie7icon('&#xf121;');
-}
-
-
-.icon-reply-all {
-  .ie7icon('&#xf122;');
-}
-
-
-.icon-mail-reply-all {
-  .ie7icon('&#xf122;');
-}
-
-
-.icon-star-half-empty {
-  .ie7icon('&#xf123;');
-}
-
-.icon-star-half-full {
-  .ie7icon('&#xf123;');
-}
-
-
-.icon-location-arrow {
-  .ie7icon('&#xf124;');
-}
-
-
-.icon-crop {
-  .ie7icon('&#xf125;');
-}
-
-
-.icon-code-fork {
-  .ie7icon('&#xf126;');
-}
-
-
-.icon-unlink {
-  .ie7icon('&#xf127;');
-}
-
-
-.icon-question {
-  .ie7icon('&#xf128;');
-}
-
-
-.icon-info {
-  .ie7icon('&#xf129;');
-}
-
-
-.icon-exclamation {
-  .ie7icon('&#xf12a;');
-}
-
-
-.icon-superscript {
-  .ie7icon('&#xf12b;');
-}
-
-
-.icon-subscript {
-  .ie7icon('&#xf12c;');
-}
-
-
-.icon-eraser {
-  .ie7icon('&#xf12d;');
-}
-
-
-.icon-puzzle-piece {
-  .ie7icon('&#xf12e;');
-}
-
-
-.icon-microphone {
-  .ie7icon('&#xf130;');
-}
-
-
-.icon-microphone-off {
-  .ie7icon('&#xf131;');
-}
-
-
-.icon-shield {
-  .ie7icon('&#xf132;');
-}
-
-
-.icon-calendar-empty {
-  .ie7icon('&#xf133;');
-}
-
-
-.icon-fire-extinguisher {
-  .ie7icon('&#xf134;');
-}
-
-
-.icon-rocket {
-  .ie7icon('&#xf135;');
-}
-
-
-.icon-maxcdn {
-  .ie7icon('&#xf136;');
-}
-
-
-.icon-chevron-sign-left {
-  .ie7icon('&#xf137;');
-}
-
-
-.icon-chevron-sign-right {
-  .ie7icon('&#xf138;');
-}
-
-
-.icon-chevron-sign-up {
-  .ie7icon('&#xf139;');
-}
-
-
-.icon-chevron-sign-down {
-  .ie7icon('&#xf13a;');
-}
-
-
-.icon-html5 {
-  .ie7icon('&#xf13b;');
-}
-
-
-.icon-css3 {
-  .ie7icon('&#xf13c;');
-}
-
-
-.icon-anchor {
-  .ie7icon('&#xf13d;');
-}
-
-
-.icon-unlock-alt {
-  .ie7icon('&#xf13e;');
-}
-
-
-.icon-bullseye {
-  .ie7icon('&#xf140;');
-}
-
-
-.icon-ellipsis-horizontal {
-  .ie7icon('&#xf141;');
-}
-
-
-.icon-ellipsis-vertical {
-  .ie7icon('&#xf142;');
-}
-
-
-.icon-rss-sign {
-  .ie7icon('&#xf143;');
-}
-
-
-.icon-play-sign {
-  .ie7icon('&#xf144;');
-}
-
-
-.icon-ticket {
-  .ie7icon('&#xf145;');
-}
-
-
-.icon-minus-sign-alt {
-  .ie7icon('&#xf146;');
-}
-
-
-.icon-check-minus {
-  .ie7icon('&#xf147;');
-}
-
-
-.icon-level-up {
-  .ie7icon('&#xf148;');
-}
-
-
-.icon-level-down {
-  .ie7icon('&#xf149;');
-}
-
-
-.icon-check-sign {
-  .ie7icon('&#xf14a;');
-}
-
-
-.icon-edit-sign {
-  .ie7icon('&#xf14b;');
-}
-
-
-.icon-external-link-sign {
-  .ie7icon('&#xf14c;');
-}
-
-
-.icon-share-sign {
-  .ie7icon('&#xf14d;');
-}
-
-
-.icon-compass {
-  .ie7icon('&#xf14e;');
-}
-
-
-.icon-collapse {
-  .ie7icon('&#xf150;');
-}
-
-
-.icon-collapse-top {
-  .ie7icon('&#xf151;');
-}
-
-
-.icon-expand {
-  .ie7icon('&#xf152;');
-}
-
-
-.icon-eur {
-  .ie7icon('&#xf153;');
-}
-
-.icon-euro {
-  .ie7icon('&#xf153;');
-}
-
-
-.icon-gbp {
-  .ie7icon('&#xf154;');
-}
-
-
-.icon-usd {
-  .ie7icon('&#xf155;');
-}
-
-.icon-dollar {
-  .ie7icon('&#xf155;');
-}
-
-
-.icon-inr {
-  .ie7icon('&#xf156;');
-}
-
-.icon-rupee {
-  .ie7icon('&#xf156;');
-}
-
-
-.icon-jpy {
-  .ie7icon('&#xf157;');
-}
-
-.icon-yen {
-  .ie7icon('&#xf157;');
-}
-
-
-.icon-cny {
-  .ie7icon('&#xf158;');
-}
-
-.icon-renminbi {
-  .ie7icon('&#xf158;');
-}
-
-
-.icon-krw {
-  .ie7icon('&#xf159;');
-}
-
-.icon-won {
-  .ie7icon('&#xf159;');
-}
-
-
-.icon-btc {
-  .ie7icon('&#xf15a;');
-}
-
-.icon-bitcoin {
-  .ie7icon('&#xf15a;');
-}
-
-
-.icon-file {
-  .ie7icon('&#xf15b;');
-}
-
-
-.icon-file-text {
-  .ie7icon('&#xf15c;');
-}
-
-
-.icon-sort-by-alphabet {
-  .ie7icon('&#xf15d;');
-}
-
-
-.icon-sort-by-alphabet-alt {
-  .ie7icon('&#xf15e;');
-}
-
-
-.icon-sort-by-attributes {
-  .ie7icon('&#xf160;');
-}
-
-
-.icon-sort-by-attributes-alt {
-  .ie7icon('&#xf161;');
-}
-
-
-.icon-sort-by-order {
-  .ie7icon('&#xf162;');
-}
-
-
-.icon-sort-by-order-alt {
-  .ie7icon('&#xf163;');
-}
-
-
-.icon-thumbs-up {
-  .ie7icon('&#xf164;');
-}
-
-
-.icon-thumbs-down {
-  .ie7icon('&#xf165;');
-}
-
-
-.icon-youtube-sign {
-  .ie7icon('&#xf166;');
-}
-
-
-.icon-youtube {
-  .ie7icon('&#xf167;');
-}
-
-
-.icon-xing {
-  .ie7icon('&#xf168;');
-}
-
-
-.icon-xing-sign {
-  .ie7icon('&#xf169;');
-}
-
-
-.icon-youtube-play {
-  .ie7icon('&#xf16a;');
-}
-
-
-.icon-dropbox {
-  .ie7icon('&#xf16b;');
-}
-
-
-.icon-stackexchange {
-  .ie7icon('&#xf16c;');
-}
-
-
-.icon-instagram {
-  .ie7icon('&#xf16d;');
-}
-
-
-.icon-flickr {
-  .ie7icon('&#xf16e;');
-}
-
-
-.icon-adn {
-  .ie7icon('&#xf170;');
-}
-
-
-.icon-bitbucket {
-  .ie7icon('&#xf171;');
-}
-
-
-.icon-bitbucket-sign {
-  .ie7icon('&#xf172;');
-}
-
-
-.icon-tumblr {
-  .ie7icon('&#xf173;');
-}
-
-
-.icon-tumblr-sign {
-  .ie7icon('&#xf174;');
-}
-
-
-.icon-long-arrow-down {
-  .ie7icon('&#xf175;');
-}
-
-
-.icon-long-arrow-up {
-  .ie7icon('&#xf176;');
-}
-
-
-.icon-long-arrow-left {
-  .ie7icon('&#xf177;');
-}
-
-
-.icon-long-arrow-right {
-  .ie7icon('&#xf178;');
-}
-
-
-.icon-apple {
-  .ie7icon('&#xf179;');
-}
-
-
-.icon-windows {
-  .ie7icon('&#xf17a;');
-}
-
-
-.icon-android {
-  .ie7icon('&#xf17b;');
-}
-
-
-.icon-linux {
-  .ie7icon('&#xf17c;');
-}
-
-
-.icon-dribbble {
-  .ie7icon('&#xf17d;');
-}
-
-
-.icon-skype {
-  .ie7icon('&#xf17e;');
-}
-
-
-.icon-foursquare {
-  .ie7icon('&#xf180;');
-}
-
-
-.icon-trello {
-  .ie7icon('&#xf181;');
-}
-
-
-.icon-female {
-  .ie7icon('&#xf182;');
-}
-
-
-.icon-male {
-  .ie7icon('&#xf183;');
-}
-
-
-.icon-gittip {
-  .ie7icon('&#xf184;');
-}
-
-
-.icon-sun {
-  .ie7icon('&#xf185;');
-}
-
-
-.icon-moon {
-  .ie7icon('&#xf186;');
-}
-
-
-.icon-archive {
-  .ie7icon('&#xf187;');
-}
-
-
-.icon-bug {
-  .ie7icon('&#xf188;');
-}
-
-
-.icon-vk {
-  .ie7icon('&#xf189;');
-}
-
-
-.icon-weibo {
-  .ie7icon('&#xf18a;');
-}
-
-
-.icon-renren {
-  .ie7icon('&#xf18b;');
-}
-
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/font-awesome/font-awesome.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/font-awesome/font-awesome.less b/apps/fauxton/assets/less/bootstrap/font-awesome/font-awesome.less
deleted file mode 100644
index 0f45461..0000000
--- a/apps/fauxton/assets/less/bootstrap/font-awesome/font-awesome.less
+++ /dev/null
@@ -1,33 +0,0 @@
-/*!
- *  Font Awesome 3.2.1
- *  the iconic font designed for Bootstrap
- *  ------------------------------------------------------------------------------
- *  The full suite of pictographic icons, examples, and documentation can be
- *  found at http://fontawesome.io.  Stay up to date on Twitter at
- *  http://twitter.com/fontawesome.
- *
- *  License
- *  ------------------------------------------------------------------------------
- *  - The Font Awesome font is licensed under SIL OFL 1.1 -
- *    http://scripts.sil.org/OFL
- *  - Font Awesome CSS, LESS, and SASS files are licensed under MIT License -
- *    http://opensource.org/licenses/mit-license.html
- *  - Font Awesome documentation licensed under CC BY 3.0 -
- *    http://creativecommons.org/licenses/by/3.0/
- *  - Attribution is no longer required in Font Awesome 3.0, but much appreciated:
- *    "Font Awesome by Dave Gandy - http://fontawesome.io"
- *
- *  Author - Dave Gandy
- *  ------------------------------------------------------------------------------
- *  Email: dave@fontawesome.io
- *  Twitter: http://twitter.com/davegandy
- *  Work: Lead Product Designer @ Kyruus - http://kyruus.com
- */
-
-@import "variables.less";
-@import "mixins.less";
-@import "path.less";
-@import "core.less";
-@import "bootstrap.less";
-@import "extras.less";
-@import "icons.less";


[32/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/modules/documents/views.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/modules/documents/views.js b/apps/fauxton/app/modules/documents/views.js
deleted file mode 100644
index e155435..0000000
--- a/apps/fauxton/app/modules/documents/views.js
+++ /dev/null
@@ -1,1805 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-       "app",
-
-       "api",
-       "modules/fauxton/components",
-
-       "modules/documents/resources",
-       "modules/databases/resources",
-       "modules/pouchdb/base",
-
-       // Libs
-       "resizeColumns",
-
-       // Plugins
-       "plugins/prettify"
-
-],
-
-function(app, FauxtonAPI, Components, Documents, Databases, pouchdb, resizeColumns) {
-  var Views = {};
-
-  // Views.Tabs = FauxtonAPI.View.extend({
-  //   template: "templates/documents/tabs",
-  //   initialize: function(options){
-  //     this.collection = options.collection;
-  //     this.database = options.database;
-  //     this.active_id = options.active_id;
-  //   },
-
-  //   events: {
-  //     "click #delete-database": "delete_database"
-  //   },
-
-  //   serialize: function () {
-  //     return {
-  //       // TODO make this not hard coded here
-  //       changes_url: '#' + this.database.url('changes'),
-  //       db_url: '#' + this.database.url('index') + '?limit=' + Databases.DocLimit,
-  //     };
-  //   },
-
-  //   beforeRender: function(manage) {
-  //     this.insertView("#search", new Views.SearchBox({
-  //       collection: this.collection,
-  //       database: this.database.id
-  //     }));
-  //   },
-
-  //   afterRender: function () {
-  //     if (this.active_id) {
-  //       this.$('.active').removeClass('active');
-  //       this.$('#'+this.active_id).addClass('active');
-  //     }
-  //   },
-
-  //   delete_database: function (event) {
-  //     event.preventDefault();
-
-  //     var result = confirm("Are you sure you want to delete this database?");
-
-  //     if (!result) { return; }
-  //     FauxtonAPI.addNotification({
-  //       msg: "Deleting your database...",
-  //       type: "error"
-  //     });
-  //     return this.database.destroy().done(function () {
-  //       app.router.navigate('#/_all_dbs', {trigger: true});
-  //     });
-  //   }
-  // });
-
-  Views.SearchBox = FauxtonAPI.View.extend({
-    template: "templates/documents/search",
-    tagName: "form",
-    initialize: function(options){
-      this.collection = options.collection;
-      this.database = options.database;
-    },
-    afterRender: function(){
-      var collection = this.collection;
-      var form = this.$el;
-      var searchbox = form.find("input#searchbox");
-      var database = this.database;
-
-      form.submit(function(evt){
-        evt.preventDefault();
-        var viewname = form.find("input#view").val().split('/');
-        var url = "#database/" + database + "/_design/";
-        url += viewname[0] + "/_view/" + viewname[1];
-        if (searchbox.val() !== ""){
-          // TODO: this'll need to work when val() is a number etc.
-          url += '?startkey="' + searchbox.val() + '"';
-        }
-        FauxtonAPI.navigate(url);
-      });
-
-      searchbox.typeahead({
-        source: function(query, process) {
-          // TODO: include _all_docs and view keys somehow
-          var views = _.map(collection.pluck('doc'), function(d){
-            return _.map(_.keys(d.views), function(view){
-              return d._id.split('/')[1] + "/" + view;
-            });
-          });
-          return _.flatten(views);
-        },
-        minLength: 3,
-        updater: function(item){
-          // TODO: some way to return the original search box
-          this.$element.removeClass('span12');
-          this.$element.addClass('span6');
-          this.$element.attr('placeholder', 'Search by view key');
-          $('<span class="add-on span6">' + item +'</span>').insertBefore(this.$element);
-          $('<input type="hidden" id="view" value="' + item +'"/>').insertBefore(this.$element);
-          // Remove the type ahead for now
-          $('.typehead').unbind();
-        }
-      });
-    }
-  });
-
-  Views.UploadModal = FauxtonAPI.View.extend({
-    template: "templates/documents/upload_modal",
-
-    disableLoader: true,
-    
-    initialize: function (options) {
-      _.bindAll(this);
-    },
-
-    events: {
-      "click a#upload-btn": "uploadFile"
-    },
-
-    uploadFile: function (event) {
-      event.preventDefault();
-
-      var docRev = this.model.get('_rev'),
-          that = this,
-          $form = this.$('#file-upload');
-
-      if (!docRev) {
-        return this.set_error_msg('The document needs to be saved before adding an attachment.');
-      }
-
-      if ($('input[type="file"]')[0].files.length === 0) {
-        return this.set_error_msg('Selected a file to be uploaded.');
-      }
-
-      this.$('#_rev').val(docRev);
-
-      $form.ajaxSubmit({
-        url: this.model.url(),
-        type: 'POST',
-        beforeSend: this.beforeSend,
-        uploadProgress: this.uploadProgress,
-        success: this.success,
-        error: function (resp) {
-          console.log('ERR on upload', resp);
-          return that.set_error_msg('Could not upload document: ' + JSON.parse(resp.responseText).reason);
-        }
-      });
-    },
-
-    success: function (resp) {
-      var hideModal = this.hideModal,
-          $form = this.$('#file-upload');
-
-      FauxtonAPI.triggerRouteEvent('reRenderDoc');
-      //slight delay to make this transistion a little more fluid and less jumpy
-      setTimeout(function () {
-        $form.clearForm();
-        hideModal();
-        $('.modal-backdrop').remove();
-      }, 1000);
-    },
-
-    uploadProgress: function(event, position, total, percentComplete) {
-      this.$('.bar').css({width: percentComplete + '%'});
-    },
-
-    beforeSend: function () {
-      this.$('.progress').removeClass('hide');
-    },
-
-    showModal: function () {
-      this.$('.bar').css({width: '0%'});
-      this.$('.progress').addClass('hide');
-      this.clear_error_msg();
-      this.$('.modal').modal();
-      // hack to get modal visible 
-      $('.modal-backdrop').css('z-index',1025);
-    },
-
-    hideModal: function () {
-      this.$('.modal').modal('hide');
-    },
-
-    set_error_msg: function (msg) {
-      var text;
-      if (typeof(msg) == 'string') {
-        text = msg;
-      } else {
-        text = JSON.parse(msg.responseText).reason;
-      }
-      this.$('#modal-error').text(text).removeClass('hide');
-    },
-
-    clear_error_msg: function () {
-      this.$('#modal-error').text(' ').addClass('hide');
-    },
-
-    serialize: function () {
-      return this.model.toJSON();
-    }
-  });
-
-  Views.DuplicateDocModal = FauxtonAPI.View.extend({
-    template: "templates/documents/duplicate_doc_modal",
-
-    initialize: function () {
-      _.bindAll(this);
-    },
-
-    events: {
-      "click #duplicate-btn":"duplicate"
-
-    },
-
-    duplicate: function (event) {
-      event.preventDefault();
-      var newId = this.$('#dup-id').val(),
-          encodedID = app.mixins.safeURLName(newId);
-
-      this.hideModal();
-      FauxtonAPI.triggerRouteEvent('duplicateDoc', encodedID);
-    },
-
-    _showModal: function () {
-      this.$('.bar').css({width: '0%'});
-      this.$('.progress').addClass('hide');
-      this.clear_error_msg();
-      this.$('.modal').modal();
-      // hack to get modal visible 
-      $('.modal-backdrop').css('z-index',1025);
-    },
-
-    showModal: function () {
-      var showModal = this._showModal,
-          setDefaultIdValue = this.setDefaultIdValue,
-          uuid = new FauxtonAPI.UUID();
-
-      uuid.fetch().then(function () {
-        setDefaultIdValue(uuid.next());
-        showModal();
-      });
-    },
-
-    setDefaultIdValue: function (id) {
-      this.$('#dup-id').val(id);
-    },
-
-    hideModal: function () {
-      this.$('.modal').modal('hide');
-    },
-
-    set_error_msg: function (msg) {
-      var text;
-      if (typeof(msg) == 'string') {
-        text = msg;
-      } else {
-        text = JSON.parse(msg.responseText).reason;
-      }
-      this.$('#modal-error').text(text).removeClass('hide');
-    },
-
-    clear_error_msg: function () {
-      this.$('#modal-error').text(' ').addClass('hide');
-    },
-
-    serialize: function () {
-      return this.model.toJSON();
-    }
-
-  });
-
-  Views.FieldEditorTabs = FauxtonAPI.View.extend({
-    template: "templates/documents/doc_field_editor_tabs",
-    disableLoader: true,
-    initialize: function(options) {
-      this.selected = options.selected;
-    },
-
-    events: {
-    },
-    updateSelected: function (selected) {
-      this.selected = selected;
-      this.$('.active').removeClass('active');
-      this.$('#'+this.selected).addClass('active');
-    },
-
-    serialize: function() {
-      var selected = this.selected;
-      return {
-        doc: this.model,
-        isNewDoc: this.model.isNewDoc(),
-        isSelectedClass: function(item) {
-          return item && item === selected ? "active" : "";
-        }
-      };
-    },
-
-    establish: function() {
-      return [this.model.fetch()];
-    }
-  });
-
-  Views.Document = FauxtonAPI.View.extend({
-    template: "templates/documents/all_docs_item",
-    tagName: "tr",
-    className: "all-docs-item",
-
-    events: {
-      "click button.delete": "destroy",
-      "dblclick pre.prettyprint": "edit"
-    },
-
-    attributes: function() {
-      return {
-        "data-id": this.model.id
-      };
-    },
-
-    serialize: function() {
-      return {
-        doc: this.model
-      };
-    },
-
-    establish: function() {
-      return [this.model.fetch()];
-    },
-
-    edit: function(event) {
-      event.preventDefault();
-      FauxtonAPI.navigate("#" + this.model.url('app'));
-    },
-
-    destroy: function(event) {
-      event.preventDefault();
-      var that = this;
-
-      if (!window.confirm("Are you sure you want to delete this doc?")) {
-        return false;
-      }
-
-      this.model.destroy().then(function(resp) {
-        FauxtonAPI.addNotification({
-          msg: "Succesfully destroyed your doc"
-        });
-        that.$el.fadeOut(function () {
-          that.remove();
-        });
-
-        that.model.collection.remove(that.model.id);
-        if (!!that.model.id.match('_design')) {
-          FauxtonAPI.triggerRouteEvent('reloadDesignDocs');
-        }
-      }, function(resp) {
-        FauxtonAPI.addNotification({
-          msg: "Failed to destroy your doc!",
-          type: "error"
-        });
-      });
-    }
-  });
-
-  Views.Row = FauxtonAPI.View.extend({
-    template: "templates/documents/index_row_docular",
-    tagName: "tr",
-
-    events: {
-      "click button.delete": "destroy"
-    },
-
-    destroy: function (event) {
-      event.preventDefault(); 
-      
-      window.alert('Cannot delete a document generated from a view.');
-    },
-
-    serialize: function() {
-      return {
-        doc: this.model
-      };
-    }
-  });
-
-  Views.IndexItem = FauxtonAPI.View.extend({
-    template: "templates/documents/index_menu_item",
-    tagName: "li",
-
-    initialize: function(options){
-      this.index = options.index;
-      this.ddoc = options.ddoc;
-      this.database = options.database;
-      this.selected = !! options.selected;
-    },
-
-    serialize: function() {
-      return {
-        index: this.index,
-        ddoc: this.ddoc,
-        database: this.database,
-        index_clean: app.mixins.removeSpecialCharacters(this.index),
-        ddoc_clean: app.mixins.removeSpecialCharacters(this.ddoc), 
-        index_encoded: app.mixins.safeURLName(this.index),
-        ddoc_encoded: app.mixins.safeURLName(this.ddoc),
-        database_encoded: app.mixins.safeURLName(this.database),
-        selected: this.selected
-      };
-    },
-
-    afterRender: function() {
-      if (this.selected) {
-        $("#sidenav ul.nav-list li").removeClass("active");
-        this.$el.addClass("active");
-      }
-    }
-  });
-
-  Views.AllDocsNumber = FauxtonAPI.View.extend({
-    template: "templates/documents/all_docs_number",
-
-    initialize: function (options) {
-      this.newView = options.newView || false;
-      
-      this.listenTo(this.collection, 'totalRows:decrement', this.render);
-    },
-
-    serialize: function () {
-       var totalRows = 0,
-          recordStart = 0,
-          updateSeq = false;
-
-      if (!this.newView) {
-        totalRows = this.collection.totalRows();
-        updateSeq = this.collection.updateSeq();
-      }
-
-      recordStart = this.collection.recordStart();
-
-      return {
-        database: app.mixins.safeURLName(this.collection.database.id),
-        updateSeq: updateSeq,
-        offset: recordStart,
-        totalRows: totalRows,
-        numModels: this.collection.models.length + recordStart - 1,
-      };
-    }
-
-  });
-
-  Views.AllDocsLayout = FauxtonAPI.View.extend({
-    template: "templates/documents/all_docs_layout",
-    className: "row",
-
-    initialize: function (options) {
-      this.database = options.database;
-      this.params = options.params;
-    },
-
-    events: {
-      'click #toggle-query': "toggleQuery"
-    },
-
-    toggleQuery: function (event) {
-      this.$('#query').toggle('fast');
-    },
-
-    beforeRender: function () {
-      this.advancedOptions = this.insertView('#query', new Views.AdvancedOptions({
-        updateViewFn: this.updateView,
-        previewFn: this.previewView,
-        hasReduce: false,
-        showPreview: false,
-        database: this.database
-      }));
-
-      this.$('#query').hide();
-    },
-
-    afterRender: function () {
-      if (this.params) {
-        this.advancedOptions.updateFromParams(this.params);
-      }
-
-    },
-
-    updateView: function (event, paramInfo) {
-      event.preventDefault();
-
-      var errorParams = paramInfo.errorParams,
-          params = paramInfo.params;
-
-      if (_.any(errorParams)) {
-        _.map(errorParams, function(param) {
-
-          // TODO: Where to add this error?
-          // bootstrap wants the error on a control-group div, but we're not using that
-          //$('form.view-query-update input[name='+param+'], form.view-query-update select[name='+param+']').addClass('error');
-          return FauxtonAPI.addNotification({
-            msg: "JSON Parse Error on field: "+param.name,
-            type: "error",
-            selector: ".advanced-options .errors-container"
-          });
-        });
-        FauxtonAPI.addNotification({
-          msg: "Make sure that strings are properly quoted and any other values are valid JSON structures",
-          type: "warning",
-          selector: ".advanced-options .errors-container"
-        });
-
-        return false;
-      }
-
-      var fragment = window.location.hash.replace(/\?.*$/, '');
-      fragment = fragment + '?' + $.param(params);
-      FauxtonAPI.navigate(fragment, {trigger: false});
-
-      FauxtonAPI.triggerRouteEvent('updateAllDocs', {allDocs: true});
-    },
-
-    previewView: function (event) {
-      event.preventDefault();
-    }
-
-  });
-
-  // TODO: Rename to reflect that this is a list of rows or documents
-  Views.AllDocsList = FauxtonAPI.View.extend({
-    template: "templates/documents/all_docs_list",
-    events: {
-      "click button.all": "selectAll",
-      "click button.bulk-delete": "bulkDelete",
-      "click #collapse": "collapse",
-      "change .row-select":"toggleTrash"
-    },
-
-    toggleTrash: function () {
-      if (this.$('.row-select:checked').length > 0) {
-        this.$('.bulk-delete').removeClass('disabled');
-      } else {
-        this.$('.bulk-delete').addClass('disabled');
-      }
-    },
-
-    initialize: function(options){
-      this.nestedView = options.nestedView || Views.Document;
-      this.rows = {};
-      this.viewList = !! options.viewList;
-      this.database = options.database;
-      if (options.ddocInfo) {
-        this.designDocs = options.ddocInfo.designDocs;
-        this.ddocID = options.ddocInfo.id;
-      }
-      this.newView = options.newView || false;
-      this.expandDocs = true;
-      this.addPagination();
-    },
-
-    establish: function() {
-      if (this.newView) { return null; }
-
-      return this.collection.fetch({reset: true}).fail(function() {
-        // TODO: handle error requests that slip through
-        // This should just throw a notification, not break the page
-        console.log("ERROR: ", arguments);
-      });
-    },
-
-    selectAll: function(evt){
-      $("input:checkbox").prop('checked', !$(evt.target).hasClass('active')).trigger('change');
-    },
-
-    serialize: function() {
-      var requestDuration = false;
-
-      if (this.collection.requestDurationInString) {
-        requestDuration = this.collection.requestDurationInString();
-      }
-
-      return {
-        viewList: this.viewList,
-        requestDuration: requestDuration,
-        expandDocs: this.expandDocs
-      };
-    },
-
-    collapse: function (event) {
-      event.preventDefault();
-
-      if (this.expandDocs) {
-        this.expandDocs = false;
-      } else {
-        this.expandDocs = true;
-      }
-
-      this.render();
-    },
-
-    /*
-     * TODO: this should be reconsidered
-     * This currently performs delete operations on the model level,
-     * when we could be using bulk docs with _deleted = true. Using
-     * individual models is cleaner from a backbone standpoint, but
-     * not from the couchdb api.
-     * Also, the delete method is naive and leaves the body intact,
-     * when we should switch the doc to only having id/rev/deleted.
-     */
-    bulkDelete: function() {
-      var that = this;
-      // yuck, data binding ftw?
-      var eles = this.$el.find("input.row-select:checked")
-                         .parents("tr.all-docs-item")
-                         .map(function(e) { return $(this).attr("data-id"); })
-                         .get();
-
-      if (eles.length === 0 || !window.confirm("Are you sure you want to delete these " + eles.length + " docs?")) {
-        return false;
-      }
-
-      _.each(eles, function(ele) {
-        var model = this.collection.get(ele);
-
-        model.destroy().then(function(resp) {
-          that.rows[ele].$el.fadeOut(function () {
-            $(this).remove();
-          });
-
-          model.collection.remove(model.id);
-          console.log(model.id.match('_design'), !!model.id.match('_design'));
-          if (!!model.id.match('_design')) { 
-            FauxtonAPI.triggerRouteEvent('reloadDesignDocs');
-          }
-          that.$('.bulk-delete').addClass('disabled');
-        }, function(resp) {
-          FauxtonAPI.addNotification({
-            msg: "Failed to destroy your doc!",
-            type: "error"
-          });
-        });
-      }, this);
-    },
-
-    addPagination: function () {
-      var collection = this.collection;
-
-      this.pagination = new Components.IndexPagination({
-        collection: this.collection,
-        scrollToSelector: '#dashboard-content',
-        previousUrlfn: function () {
-          return collection.urlPreviousPage(20, this.previousIds.pop());
-        },
-        canShowPreviousfn: function () {
-          if (collection.viewMeta.offset === 0) {
-            return false;
-          }
-
-          return true;
-        },
-        canShowNextfn: function () {
-          if (collection.length === 0 || (collection.viewMeta.offset + collection.length + 2) >= collection.viewMeta.total_rows) {
-            return false;
-          }
-
-          return true;
-        },
-        
-        nextUrlfn: function () {
-          return collection.urlNextPage(20);
-        }
-      });
-    },
-
-    beforeRender: function() {
-      this.allDocsNumber = this.setView('#item-numbers', new Views.AllDocsNumber({
-        collection: this.collection,
-        newView: this.newView
-      }));
-
-      this.insertView('#documents-pagination', this.pagination);
-      var docs = this.expandDocs ? this.collection : this.collection.simple();
-
-      docs.each(function(doc) {
-        this.rows[doc.id] = this.insertView("table.all-docs tbody", new this.nestedView({
-          model: doc
-        }));
-      }, this);
-    },
-
-    afterRender: function(){
-      prettyPrint();
-    }
-  });
-
-  Views.Doc = FauxtonAPI.View.extend({
-    template: "templates/documents/doc",
-    events: {
-      "click button.save-doc": "saveDoc",
-      "click button.delete": "destroy",
-      "click button.duplicate": "duplicate",
-      "click button.upload": "upload",
-      "click button.cancel-button": "goback"
-    },
-    disableLoader: true,
-    initialize: function (options) {
-      this.database = options.database;
-      _.bindAll(this);
-    },
-    goback: function(){
-      FauxtonAPI.navigate(this.database.url("index") + "?limit=100");
-    },
-    destroy: function(event) {
-      if (this.model.isNewDoc()) {
-        FauxtonAPI.addNotification({
-          msg: 'This document has not been saved yet.',
-          type: 'warning'
-        });
-        return;
-      }
-
-      if (!window.confirm("Are you sure you want to delete this doc?")) {
-        return false;
-      }
-
-      var database = this.model.database;
-
-      this.model.destroy().then(function(resp) {
-        FauxtonAPI.addNotification({
-          msg: "Succesfully destroyed your doc"
-        });
-        FauxtonAPI.navigate(database.url("index"));
-      }, function(resp) {
-        FauxtonAPI.addNotification({
-          msg: "Failed to destroy your doc!",
-          type: "error"
-        });
-      });
-    },
-
-    beforeRender: function () {
-      this.uploadModal = this.setView('#upload-modal', new Views.UploadModal({model: this.model}));
-      this.uploadModal.render();
-
-      this.duplicateModal = this.setView('#duplicate-modal', new Views.DuplicateDocModal({model: this.model}));
-      this.duplicateModal.render();
-    },
-
-    upload: function (event) {
-      event.preventDefault();
-      if (this.model.isNewDoc()) {
-        FauxtonAPI.addNotification({
-          msg: 'Please save the document before uploading an attachment.',
-          type: 'warning'
-        });
-        return;
-      }
-      this.uploadModal.showModal();
-    },
-
-    duplicate: function(event) {
-      if (this.model.isNewDoc()) {
-        FauxtonAPI.addNotification({
-          msg: 'Please save the document before duplicating it.',
-          type: 'warning'
-        });
-        return;
-      }
-      event.preventDefault();
-      this.duplicateModal.showModal();
-    },
-
-    updateValues: function() {
-      var notification;
-      if (this.model.changedAttributes()) {
-        notification = FauxtonAPI.addNotification({
-          msg: "Document saved successfully.",
-          type: "success",
-          clear: true
-        });
-        this.editor.setValue(this.model.prettyJSON());
-      }
-    },
-
-    establish: function() {
-      var promise = this.model.fetch(),
-          databaseId = this.database.safeID(),
-          deferred = $.Deferred(),
-          that = this;
-
-      promise.then(function () {
-        deferred.resolve();
-      }, function (xhr, reason, msg) {
-        if (xhr.status === 404) {
-          FauxtonAPI.addNotification({
-            msg: 'The document does not exist',
-            type: 'error',
-            clear: true
-          });
-          that.goback();
-        }
-        deferred.reject();
-     });
-      
-      return deferred;
-    },
-
-    saveDoc: function(event) {
-      var json, notification, 
-      that = this,
-      editor = this.editor,
-      validDoc = this.getDocFromEditor();
-
-      if (validDoc) {
-        this.getDocFromEditor();
-
-        notification = FauxtonAPI.addNotification({msg: "Saving document."});
-
-        this.model.save().then(function () {
-          editor.editSaved();
-          FauxtonAPI.navigate('/database/' + that.database.safeID() + '/' + that.model.id);
-        }).fail(function(xhr) {
-          var responseText = JSON.parse(xhr.responseText).reason;
-          notification = FauxtonAPI.addNotification({
-            msg: "Save failed: " + responseText,
-            type: "error",
-            clear: true,
-            selector: "#doc .errors-container"
-          });
-        });
-      } else if(this.model.validationError && this.model.validationError === 'Cannot change a documents id.') {
-          notification = FauxtonAPI.addNotification({
-            msg: "Cannot save: " + 'Cannot change a documents _id, try Duplicate doc instead!',
-            type: "error",
-            selector: "#doc .errors-container"
-          });
-        delete this.model.validationError;
-      } else {
-        notification = FauxtonAPI.addNotification({
-          msg: "Please fix the JSON errors and try again.",
-          type: "error",
-          selector: "#doc .errors-container"
-        });
-      }
-    },
-
-    getDocFromEditor: function () {
-      if (!this.hasValidCode()) {
-        return false;
-      }
-
-      json = JSON.parse(this.editor.getValue());
-
-      this.model.clear().set(json, {validate: true});
-      if (this.model.validationError) {
-        return false;
-      }
-
-      return this.model;
-    },
-
-    hasValidCode: function() {
-      var errors = this.editor.getAnnotations();
-      return errors.length === 0;
-    },
-
-    serialize: function() {
-      return {
-        doc: this.model,
-        attachments: this.getAttachments()
-      };
-    },
-
-    getAttachments: function () {
-      var attachments = this.model.get('_attachments');
-
-      if (!attachments) { return false; }
-
-      return _.map(attachments, function (att, key) {
-        return {
-          fileName: key,
-          size: att.length,
-          contentType: att.content_type,
-          url: this.model.url() + '/' + key
-        };
-      }, this);
-    },
-
-    afterRender: function() {
-      var saveDoc = this.saveDoc;
-
-      this.editor = new Components.Editor({
-        editorId: "editor-container",
-        commands: [{
-          name: 'save',
-          bindKey: {win: 'Ctrl-S',  mac: 'Ctrl-S'},
-          exec: function(editor) {
-            saveDoc();
-          },
-          readOnly: true // false if this command should not apply in readOnly mode
-        }]
-      });
-      this.editor.render();
-      this.model.on("sync", this.updateValues, this);
-    },
-
-    cleanup: function () {
-      if (this.editor) this.editor.remove();
-    }
-  });
-
-  Views.DocFieldEditor = FauxtonAPI.View.extend({
-    template: "templates/documents/doc_field_editor",
-    disableLoader: true,
-    events: {
-      "click button.save": "saveDoc"
-    },
-
-    saveDoc: function(event) {
-      FauxtonAPI.addNotification({
-        type: "warning",
-        msg: "Save functionality coming soon."
-      });
-    },
-
-    serialize: function() {
-      return {
-        doc: this.getModelWithoutAttachments(),
-        attachments: this.getAttachments()
-      };
-    },
-
-    getModelWithoutAttachments: function() {
-      var model = this.model.toJSON();
-      delete model._attachments;
-      return model;
-    },
-
-    getAttachments: function () {
-      var attachments = this.model.get('_attachments');
-
-      if (!attachments) { return []; }
-
-      return _.map(attachments, function (att, key) {
-        return {
-          fileName: key,
-          size: att.length,
-          contentType: att.content_type,
-          url: this.model.url() + '/' + key
-        };
-      }, this);
-    },
-
-    establish: function() {
-      return [this.model.fetch()];
-    }
-  });
-
-  Views.AdvancedOptions = FauxtonAPI.View.extend({
-    template: "templates/documents/advanced_options",
-    className: "advanced-options well",
-
-    initialize: function (options) {
-      this.database = options.database;
-      this.ddocName = options.ddocName;
-      this.viewName = options.viewName;
-      this.updateViewFn = options.updateViewFn;
-      this.previewFn = options.previewFn;
-      //this.hadReduce = options.hasReduce || true;
-
-      if (typeof(options.hasReduce) === 'undefined') {
-        this.hasReduce = true;
-      } else {
-        this.hasReduce = options.hasReduce;
-      }
-
-      if (typeof(options.showPreview) === 'undefined') {
-        this.showPreview = true;
-      } else {
-        this.showPreview = options.showPreview;
-      }
-    },
-
-    events: {
-      "change form.view-query-update input": "updateFilters",
-      "change form.view-query-update select": "updateFilters",
-      "submit form.view-query-update": "updateView",
-      "click button.preview": "previewView"
-    },
-
-    beforeRender: function () {
-      if (this.viewName && this.ddocName) {
-        var buttonViews = FauxtonAPI.getExtensions('advancedOptions:ViewButton');
-        _.each(buttonViews, function (view) {
-          this.insertView('#button-options', view);
-          view.update(this.database, this.ddocName, this.viewName);
-        }, this);
-      }
-    },
-
-    renderOnUpdatehasReduce: function (hasReduce) {
-      this.hasReduce = hasReduce;
-      this.render();
-    },
-
-    queryParams: function () {
-      var $form = this.$(".view-query-update");
-      // Ignore params without a value
-      var params = _.filter($form.serializeArray(), function(param) {
-        return param.value;
-      });
-
-      // Validate *key* params to ensure they're valid JSON
-      var keyParams = ["key","keys","startkey","endkey"];
-      var errorParams = _.filter(params, function(param) {
-        if (_.contains(keyParams, param.name)) {
-          try {
-            JSON.parse(param.value);
-            return false;
-          } catch(e) {
-            return true;
-          }
-        } else {
-          return false;
-        }
-      });
-
-      return {params: params, errorParams: errorParams};
-    },
-
-    updateFilters: function(event) {
-      event.preventDefault();
-      var $ele = $(event.currentTarget);
-      var name = $ele.attr('name');
-      this.updateFiltersFor(name, $ele);
-    },
-
-    updateFiltersFor: function(name, $ele) {
-      var $form = $ele.parents("form.view-query-update:first");
-      switch (name) {
-        // Reduce constraints
-        //   - Can't include_docs for reduce=true
-        //   - can't include group_level for reduce=false
-        case "reduce":
-          if ($ele.prop('checked') === true) {
-          if ($form.find("input[name=include_docs]").prop("checked") === true) {
-            $form.find("input[name=include_docs]").prop("checked", false);
-            var notification = FauxtonAPI.addNotification({
-              msg: "include_docs has been disabled as you cannot include docs on a reduced view",
-              type: "warn",
-              selector: ".view.show .all-docs-list.errors-container"
-            });
-          }
-          $form.find("input[name=include_docs]").prop("disabled", true);
-          $form.find("select[name=group_level]").prop("disabled", false);
-        } else {
-          $form.find("select[name=group_level]").prop("disabled", true);
-          $form.find("input[name=include_docs]").prop("disabled", false);
-        }
-        break;
-        case "include_docs":
-          break;
-      }
-    },
-
-    updateFromParams: function (params) {
-      var $form = this.$el.find("form.view-query-update");
-      _.each(params, function(val, key) {
-        var $ele;
-        switch (key) {
-          case "limit":
-            case "group_level":
-            $form.find("select[name='"+key+"']").val(val);
-          break;
-          case "include_docs":
-            case "stale":
-            case "descending":
-            case "inclusive_end":
-            $form.find("input[name='"+key+"']").prop('checked', true);
-          break;
-          case "reduce":
-            $ele = $form.find("input[name='"+key+"']");
-          if (val == "true") {
-            $ele.prop('checked', true);
-          }
-          this.updateFiltersFor(key, $ele);
-          break;
-          default:
-            $form.find("input[name='"+key+"']").val(val);
-          break;
-        }
-      }, this);
-    },
-
-    updateView: function (event) {
-      this.updateViewFn(event, this.queryParams());
-    },
-
-    previewView: function (event) {
-      this.previewFn(event, this.queryParams());
-    },
-
-    serialize: function () {
-      return {
-        hasReduce: this.hasReduce,
-        showPreview: this.showPreview
-      };
-    }
-  });
-
-  Views.DesignDocSelector = FauxtonAPI.View.extend({
-    template: "templates/documents/design_doc_selector",
-
-    events: {
-      "change select#ddoc": "updateDesignDoc"
-    },
-
-    initialize: function (options) {
-      this.ddocName = options.ddocName;
-      this.database = options.database;
-      this.listenTo(this.collection, 'add', this.ddocAdded);
-      this.DocModel = options.DocModel || Documents.Doc;
-    },
-
-    ddocAdded: function (ddoc) {
-      this.ddocName = ddoc.id;
-      this.render();
-    },
-
-    serialize: function () {
-      return {
-        ddocName: this.ddocName,
-        ddocs: this.collection
-      };
-    },
-
-    updateDesignDoc: function () {
-      if (this.newDesignDoc()) {
-        this.$('#new-ddoc-section').show();
-      } else {
-        this.$('#new-ddoc-section').hide();
-      }
-    },
-
-    newDesignDoc: function () {
-
-      return this.$('#ddoc').val() === 'new-doc';
-    },
-
-    newDocValidation: function(){
-      return this.newDesignDoc() && this.$('#new-ddoc').val()==="";
-    },
-    getCurrentDesignDoc: function () {
-      if (this.newDesignDoc()) {
-        var doc = {
-          _id: '_design/' + this.$('#new-ddoc').val(),
-          views: {},
-          language: "javascript"
-        };
-        var ddoc = new this.DocModel(doc, {database: this.database});
-        //this.collection.add(ddoc);
-        return ddoc;
-      } else if ( !this.newDesignDoc() ) {
-        var ddocName = this.$('#ddoc').val();
-        return this.collection.find(function (ddoc) {
-          return ddoc.id === ddocName;
-        }).dDocModel();
-      }
-    }
-  });
-
-  Views.ViewEditor = FauxtonAPI.View.extend({
-    template: "templates/documents/view_editor",
-    builtinReduces: ['_sum', '_count', '_stats'],
-
-    events: {
-      "click button.save": "saveView",
-      "click button.delete": "deleteView",
-      "change select#reduce-function-selector": "updateReduce",
-      "click button.preview": "previewView",
-      "click #db-views-tabs-nav": 'toggleIndexNav'
-    },
-
-    langTemplates: {
-      "javascript": {
-        map: "function(doc) {\n  emit(doc._id, 1);\n}",
-        reduce: "function(keys, values, rereduce){\n  if (rereduce){\n    return sum(values);\n  } else {\n    return values.length;\n  }\n}"
-      }
-    },
-
-    defaultLang: "javascript",
-
-    initialize: function(options) {
-      this.newView = options.newView || false;
-      this.ddocs = options.ddocs;
-      this.params = options.params;
-      this.database = options.database;
-      if (this.newView) {
-        this.viewName = 'newView';
-      } else {
-        this.ddocID = options.ddocInfo.id;
-        this.viewName = options.viewName;
-        this.ddocInfo = new Documents.DdocInfo({_id: this.ddocID},{database: this.database});
-      }
-
-      this.showIndex = false;
-      _.bindAll(this);
-    },
-
-    establish: function () {
-      if (this.ddocInfo) {
-        return this.ddocInfo.fetch();
-      }
-    },
-
-    updateValues: function() {
-      var notification;
-      if (this.model.changedAttributes()) {
-        notification = FauxtonAPI.addNotification({
-          msg: "Document saved successfully.",
-          type: "success",
-          clear: true
-        });
-        this.editor.setValue(this.model.prettyJSON());
-      }
-    },
-
-    updateReduce: function(event) {
-      var $ele = $("#reduce-function-selector");
-      var $reduceContainer = $(".control-group.reduce-function");
-      if ($ele.val() == "CUSTOM") {
-        this.createReduceEditor();
-        this.reduceEditor.setValue(this.langTemplates.javascript.reduce);
-        $reduceContainer.show();
-      } else {
-        $reduceContainer.hide();
-      }
-    },
-
-    deleteView: function (event) {
-      event.preventDefault();
-
-      if (this.newView) { return alert('Cannot delete a new view.'); }
-      if (!confirm('Are you sure you want to delete this view?')) {return;}
-
-      var that = this,
-          promise,
-          viewName = this.$('#index-name').val(),
-          ddocName = this.$('#ddoc :selected').val(),
-          ddoc = this.getCurrentDesignDoc();
-
-      ddoc.removeDdocView(viewName);
-
-      if (ddoc.hasViews()) {
-        promise = ddoc.save(); 
-      } else {
-        promise = ddoc.destroy();
-      }
-
-      promise.then(function () {
-        FauxtonAPI.navigate('/database/' + that.database.safeID() + '/_all_docs?limit=' + Databases.DocLimit);
-        FauxtonAPI.triggerRouteEvent('reloadDesignDocs');
-      });
-    },
-
-    saveView: function(event) {
-      var json, notification,
-      that = this;
-
-      if (event) { event.preventDefault();}
-
-      if (this.hasValidCode() && this.$('#new-ddoc:visible').val() !=="") {
-        var mapVal = this.mapEditor.getValue(), 
-        reduceVal = this.reduceVal(),
-        viewName = this.$('#index-name').val(),
-        ddoc = this.getCurrentDesignDoc(),
-        ddocName = ddoc.id;
-
-        this.viewName = viewName;
-
-        notification = FauxtonAPI.addNotification({
-          msg: "Saving document.",
-          selector: "#define-view .errors-container"
-        });
-
-        ddoc.setDdocView(viewName, mapVal, reduceVal);
-
-        ddoc.save().then(function () {
-          that.ddocs.add(ddoc);
-
-          that.mapEditor.editSaved();
-          that.reduceEditor && that.reduceEditor.editSaved();
-
-          FauxtonAPI.addNotification({
-            msg: "View has been saved.",
-            type: "success",
-            selector: "#define-view .errors-container"
-          });
-
-          if (that.newView) {
-            var fragment = '/database/' + that.database.safeID() +'/' + ddoc.safeID() + '/_view/' + app.mixins.safeURLName(viewName); 
-
-            FauxtonAPI.navigate(fragment, {trigger: false});
-            that.newView = false;
-            that.ddocID = ddoc.safeID();
-            that.viewName = viewName;
-            that.ddocInfo = ddoc;
-            that.showIndex = true;
-            that.render();
-            FauxtonAPI.triggerRouteEvent('reloadDesignDocs', {
-              selectedTab: app.mixins.removeSpecialCharacters(ddocName.replace(/_design\//,'')) + '_' + app.mixins.removeSpecialCharacters(viewName)
-            });
-          }
-
-          if (that.reduceFunStr !== reduceVal) {
-            that.reduceFunStr = reduceVal;
-            that.advancedOptions.renderOnUpdatehasReduce(that.hasReduce()); 
-          }
-
-          FauxtonAPI.triggerRouteEvent('updateAllDocs', {ddoc: ddocName, view: viewName});
-
-        }, function(xhr) {
-          var responseText = JSON.parse(xhr.responseText).reason;
-          notification = FauxtonAPI.addNotification({
-            msg: "Save failed: " + responseText,
-            type: "error",
-            clear: true
-          });
-        });
-      } else {
-        var errormessage = (this.$('#new-ddoc:visible').val() ==="")?"Enter a design doc name":"Please fix the Javascript errors and try again.";
-        notification = FauxtonAPI.addNotification({
-          msg: errormessage,
-          type: "error",
-          selector: "#define-view .errors-container"
-        });
-      }
-    },
-
-    updateView: function(event, paramInfo) {
-       event.preventDefault();
- 
-       if (this.newView) { return alert('Please save this new view before querying it.'); }
- 
-       var errorParams = paramInfo.errorParams,
-           params = paramInfo.params;
- 
-       if (_.any(errorParams)) {
-         _.map(errorParams, function(param) {
- 
-           // TODO: Where to add this error?
-           // bootstrap wants the error on a control-group div, but we're not using that
-           //$('form.view-query-update input[name='+param+'], form.view-query-update select[name='+param+']').addClass('error');
-           return FauxtonAPI.addNotification({
-             msg: "JSON Parse Error on field: "+param.name,
-             type: "error",
-             selector: ".advanced-options .errors-container"
-           });
-         });
-         FauxtonAPI.addNotification({
-           msg: "Make sure that strings are properly quoted and any other values are valid JSON structures",
-           type: "warning",
-           selector: ".advanced-options .errors-container"
-         });
- 
-         return false;
-      }
- 
-       var fragment = window.location.hash.replace(/\?.*$/, '');
-       fragment = fragment + '?' + $.param(params);
-       FauxtonAPI.navigate(fragment, {trigger: false});
- 
-       FauxtonAPI.triggerRouteEvent('updateAllDocs', {ddoc: this.ddocID, view: this.viewName});
-    },
-
-
-    previewView: function(event, paramsInfo) {
-      event.preventDefault();
-      var that = this,
-      mapVal = this.mapVal(),
-      reduceVal = this.reduceVal(),
-      paramsArr = [];
-
-      if (paramsInfo && paramsInfo.params) {
-        paramsArr = paramsInfo.params;
-      }
-
-      var params = _.reduce(paramsArr, function (params, param) {
-        params[param.name] = param.value;
-        return params;
-      }, {reduce: false});
-
-      event.preventDefault();
-
-      FauxtonAPI.addNotification({
-        msg: "<strong>Warning!</strong> Preview executes the Map/Reduce functions in your browser, and may behave differently from CouchDB.",
-        type: "warning",
-        selector: ".advanced-options .errors-container",
-        fade: true
-      });
-
-      var promise = FauxtonAPI.Deferred();
-
-      if (!this.database.allDocs) {
-        this.database.buildAllDocs({limit: Databases.DocLimit.toString(), include_docs: true});
-        promise = this.database.allDocs.fetch();
-      } else {
-        promise.resolve();
-      }
-
-      promise.then(function () {
-        params.docs = that.database.allDocs.map(function (model) { return model.get('doc');}); 
-
-        var queryPromise = pouchdb.runViewQuery({map: mapVal, reduce: reduceVal}, params);
-        queryPromise.then(function (results) {
-          FauxtonAPI.triggerRouteEvent('updatePreviewDocs', {rows: results.rows, ddoc: that.getCurrentDesignDoc().id, view: that.viewName});
-        });
-      });
-    },
-
-    getCurrentDesignDoc: function () {
-      return this.designDocSelector.getCurrentDesignDoc();
-    },
-    
-    isCustomReduceEnabled: function() {
-      return $("#reduce-function-selector").val() == "CUSTOM";
-    },
-
-    mapVal: function () {
-      if (this.mapEditor) {
-        return this.mapEditor.getValue();
-      }
-
-      return this.$('#map-function').text();
-    },
-
-    reduceVal: function() {
-      var reduceOption = this.$('#reduce-function-selector :selected').val(),
-      reduceVal = "";
-
-      if (reduceOption === 'CUSTOM') {
-        reduceVal = this.reduceEditor.getValue();
-      } else if ( reduceOption !== 'NONE') {
-        reduceVal = reduceOption;
-      }
-
-      return reduceVal;
-    },
-
-
-    hasValidCode: function() {
-      return _.every(["mapEditor", "reduceEditor"], function(editorName) {
-        var editor = this[editorName];
-        if (editorName === "reduceEditor" && ! this.isCustomReduceEnabled()) {
-          return true;
-        } 
-        return editor.hadValidCode();
-      }, this);
-    },
-
-    toggleIndexNav: function (event) {
-      var $targetId = this.$(event.target).attr('id'),
-          $previousTab = this.$(this.$('li.active a').attr('href')),
-          $targetTab = this.$(this.$(event.target).attr('href'));
-
-      if ($targetTab.attr('id') !== $previousTab.attr('id')) {
-        $previousTab.removeAttr('style');
-      }
-
-      if ($targetId === 'index-nav') {
-        if (this.newView) { return; }
-        var that = this;
-        $targetTab.toggle('slow', function(){
-           that.showEditors();
-        });
-      } else {
-        $targetTab.toggle('slow');
-      }
-    },
-
-    serialize: function() {
-      return {
-        ddocs: this.ddocs,
-        ddoc: this.model,
-        ddocName: this.model.id,
-        viewName: this.viewName,
-        reduceFunStr: this.reduceFunStr,
-        isCustomReduce: this.hasCustomReduce(),
-        newView: this.newView,
-        langTemplates: this.langTemplates.javascript
-      };
-    },
-
-    hasCustomReduce: function() {
-      return this.reduceFunStr && ! _.contains(this.builtinReduces, this.reduceFunStr);
-    },
-
-    hasReduce: function () {
-      return this.reduceFunStr || false;
-    },
-
-    createReduceEditor: function () {
-      if (this.reduceEditor) {
-        this.reduceEditor.remove();
-      }
-
-      this.reduceEditor = new Components.Editor({
-        editorId: "reduce-function",
-        mode: "javascript",
-        couchJSHINT: true
-      });
-      this.reduceEditor.render();
-    },
-
-    beforeRender: function () {
-
-      if (this.newView) {
-        this.reduceFunStr = '_sum';
-        if (this.ddocs.length === 0) {
-          this.model = new Documents.Doc(null, {database: this.database});
-        } else {
-          this.model = this.ddocs.first().dDocModel();
-        }
-        this.ddocID = this.model.id;
-      } else {
-        this.model = this.ddocs.get(this.ddocID).dDocModel();
-        this.reduceFunStr = this.model.viewHasReduce(this.viewName);
-        this.setView('#ddoc-info', new Views.DdocInfo({model: this.ddocInfo }));
-      }
-
-      this.designDocSelector = this.setView('.design-doc-group', new Views.DesignDocSelector({
-        collection: this.ddocs,
-        ddocName: this.model.id,
-        database: this.database
-      }));
-      
-      this.advancedOptions = this.insertView('#query', new Views.AdvancedOptions({
-        updateViewFn: this.updateView,
-        previewFn: this.previewView,
-        database: this.database,
-        viewName: this.viewName,
-        ddocName: this.model.id,
-        hasReduce: this.hasReduce()
-      }));
-    },
-
-    afterRender: function() {
-      if (this.params) {
-        this.advancedOptions.updateFromParams(this.params);
-      }
-
-      this.designDocSelector.updateDesignDoc();
-      if (this.newView || this.showIndex) {
-        this.showEditors();
-        this.showIndex = false;
-      } else {
-        this.$('#index').hide();
-        this.$('#index-nav').parent().removeClass('active');
-      }
-    },
-
-    showEditors: function () {
-      this.mapEditor = new Components.Editor({
-        editorId: "map-function",
-        mode: "javascript",
-        couchJSHINT: true
-      });
-      this.mapEditor.render();
-
-      if (this.hasCustomReduce()) {
-        this.createReduceEditor();
-      } else {
-        $(".control-group.reduce-function").hide();
-      }
-
-      if (this.newView) {
-        this.mapEditor.setValue(this.langTemplates[this.defaultLang].map);
-        //Use a built in view by default
-        //this.reduceEditor.setValue(this.langTemplates[this.defaultLang].reduce);
-      } 
-
-      this.mapEditor.editSaved();
-      this.reduceEditor && this.reduceEditor.editSaved();
-    },
-
-    cleanup: function () {
-      this.mapEditor && this.mapEditor.remove();
-      this.reduceEditor && this.reduceEditor.remove();
-    }
-  });
-
-  Views.JumpToDoc = FauxtonAPI.View.extend({
-    template: "templates/documents/jumpdoc",
-
-    initialize: function (options) {
-      this.database = options.database;
-    },
-
-    events: {
-      "submit #jump-to-doc": "jumpToDoc"
-    },
-
-    jumpToDoc: function (event) {
-      event.preventDefault();
-      var docId = this.$('#jump-to-doc-id').val().trim();
-      FauxtonAPI.navigate('/database/' + app.mixins.safeURLName(this.database.id) +'/' + app.mixins.safeURLName(docId), {trigger: true});
-    },
-
-    afterRender: function () {
-     this.typeAhead = new Components.DocSearchTypeahead({el: '#jump-to-doc-id', database: this.database});
-     this.typeAhead.render();
-    }
-  });
-
-  Views.Sidebar = FauxtonAPI.View.extend({
-    template: "templates/documents/sidebar",
-    events: {
-      "click button#delete-database": "deleteDatabase"
-    },
-
-    initialize: function(options) {
-      this.database = options.database;
-      if (options.ddocInfo) {
-        this.ddocID = options.ddocInfo.id;
-        this.currView = options.ddocInfo.currView;
-      }
-    },
-
-    deleteDatabase: function (event) {
-      event.preventDefault();
-
-      var result = confirm('Are you sure you want to delete this database?');
-
-      if (!result) { return; }
-      var databaseName = this.database.id;
-      FauxtonAPI.addNotification({
-        msg: "Deleting your database...",
-        type: "error",
-        clear: true
-      });
-
-      this.database.destroy().then(function () {
-        FauxtonAPI.navigate('#/_all_dbs');
-        FauxtonAPI.addNotification({
-          msg: 'The database ' + databaseName + ' has been deleted.',
-          clear: true
-        });
-      }).fail(function (rsp, error, msg) {
-        FauxtonAPI.addNotification({
-          msg: 'Could not delete the database, reason ' + msg + '.',
-          type: 'error',
-          clear: true
-        });
-      });
-    },
-
-    serialize: function() {
-      var docLinks = FauxtonAPI.getExtensions('docLinks'),
-          newLinks = FauxtonAPI.getExtensions('sidebar:newLinks'),
-          addLinks = FauxtonAPI.getExtensions('sidebar:links'),
-          extensionList = FauxtonAPI.getExtensions('sidebar:list');
-      return {
-        changes_url: '#' + this.database.url('changes'),
-        permissions_url: '#' + this.database.url('app') + '/permissions',
-        db_url: '#' + this.database.url('index') + '?limit=' + Databases.DocLimit,
-        database: this.collection.database,
-        database_url: '#' + this.database.url('app'), 
-        docLinks: docLinks,
-        docLimit: Databases.DocLimit,
-        addLinks: addLinks,
-        newLinks: newLinks,
-        extensionList: extensionList > 0
-      };
-    },
-
-    buildIndexList: function(collection, selector, design){
-      _.each(_.keys(collection), function(key){
-        var selected = this.ddocID == "_design/"+design;
-        this.insertView("ul.nav." + selector, new Views.IndexItem({
-          ddoc: design,
-          index: key,
-          database: this.collection.database.id,
-          selected: selected && key == this.currView
-        }));
-      }, this);
-    },
-
-    beforeRender: function(manage) {
-
-      var sidebarListViews = FauxtonAPI.getExtensions('sidebar:list');
-      _.each(sidebarListViews, function (view) {
-        var extension = this.insertView('#extension-navs', view);
-        extension.update(this.database, this.collection, this.viewName);
-        extension.render();
-      }, this);
-
-
-      this.collection.each(function(design) {
-        if (design.has('doc')){
-          var ddoc = design.id.replace(/^_design\//,"");
-          if (design.get('doc').views){
-            this.buildIndexList(design.get('doc').views, "views", ddoc);
-          }
-        }
-      }, this);
-    },
-
-    afterRender: function () {
-      if (this.selectedTab) {
-        this.setSelectedTab(this.selectedTab);
-      }
-    },
-
-    setSelectedTab: function (selectedTab) {
-      this.selectedTab = selectedTab;
-      this.$('li').removeClass('active');
-      this.$('#' + selectedTab).parent().addClass('active');
-    }
-  });
-
-  Views.Indexed = FauxtonAPI.View.extend({});
-
-  Views.Changes = FauxtonAPI.View.extend({
-    template: "templates/documents/changes",
-
-    establish: function() {
-      return [ this.model.changes.fetch()];
-    },
-
-    serialize: function () {
-      return {
-        changes: this.model.changes.toJSON(),
-        database: this.model
-      };
-    },
-
-    afterRender: function(){
-      prettyPrint();
-    }
-  });
-
-  Views.DdocInfo = FauxtonAPI.View.extend({
-    template: "templates/documents/ddoc_info",
-
-    initialize: function (options) {
-      this.refreshTime = options.refreshTime || 5000;
-      this.listenTo(this.model, 'change', this.render);
-    },
-
-    serialize: function () {
-      return {
-        view_index: this.model.get('view_index')
-      };
-    },
-
-    afterRender: function () {
-      this.startRefreshInterval();
-    },
-
-    startRefreshInterval: function () {
-      var model = this.model;
-
-      // Interval already set
-      if (this.intervalId) { return ; }
-
-      this.intervalId = setInterval(function () {
-        model.fetch();
-      }, this.refreshTime);
-    },
-
-    stopRefreshInterval: function () {
-      clearInterval(this.intervalId);
-    },
-
-    cleanup: function () {
-      this.stopRefreshInterval();
-    }
-  });
-
-  Documents.Views = Views;
-  return Documents;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/modules/fauxton/base.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/modules/fauxton/base.js b/apps/fauxton/app/modules/fauxton/base.js
deleted file mode 100644
index 01c2928..0000000
--- a/apps/fauxton/app/modules/fauxton/base.js
+++ /dev/null
@@ -1,276 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-       "app",
-       // Libs
-       "backbone",
-       "resizeColumns"
-
-],
-
-function(app, Backbone, resizeColumns) {
-
-
-   //resizeAnimation
-   app.resizeColumns = new resizeColumns({});
-   app.resizeColumns.onResizeHandler();
-
-  var Fauxton = app.module();
-
-  Fauxton.Breadcrumbs = Backbone.View.extend({
-    template: "templates/fauxton/breadcrumbs",
-
-    serialize: function() {
-      var crumbs = _.clone(this.crumbs);
-      return {
-        crumbs: crumbs
-      };
-    },
-
-    initialize: function(options) {
-      this.crumbs = options.crumbs;
-    }
-  });
-
-  Fauxton.VersionInfo = Backbone.Model.extend({
-    url: app.host
-  });
-
-  // TODO: this View should extend from FauxtonApi.View.
-  // Chicken and egg problem, api.js extends fauxton/base.js.
-  // Need to sort the loading order.
-  Fauxton.Footer = Backbone.View.extend({
-    template: "templates/fauxton/footer",
-
-    initialize: function() {
-      this.versionInfo = new Fauxton.VersionInfo();
-    },
-
-    establish: function() {
-      return [this.versionInfo.fetch()];
-    },
-
-    serialize: function() {
-      return {
-        version: this.versionInfo.get("version")
-      };
-    }
-  });
-
-  Fauxton.NavBar = Backbone.View.extend({
-    className:"navbar",
-    template: "templates/fauxton/nav_bar",
-    // TODO: can we generate this list from the router?
-    navLinks: [
-      {href:"#/_all_dbs", title:"Databases", icon: "fonticon-database", className: 'databases'}
-    ],
-
-    bottomNavLinks: [],
-    footerNavLinks: [],
-
-    serialize: function() {
-      return {
-        navLinks: this.navLinks,
-        bottomNavLinks: this.bottomNavLinks,
-        footerNavLinks: this.footerNavLinks
-      };
-    },
-
-    addLink: function(link) {
-      // link.top means it gets pushed to the top of the array,
-      // link.bottomNav means it goes to the additional bottom nav
-      // link.footerNav means goes to the footer nav
-      if (link.top && !link.bottomNav){
-        this.navLinks.unshift(link);
-      } else if (link.top && link.bottomNav){
-        this.bottomNavLinks.unshift(link);
-      } else if (link.bottomNav) {
-        this.bottomNavLinks.push(link);
-      } else if (link.footerNav) {
-        this.footerNavLinks.push(link);
-      } else {
-        this.navLinks.push(link);
-      }
-
-      //this.trigger("link:add");
-
-      //this.render();
-    },
-
-    removeLink: function (removeLink) {
-      var links = this.navlinks;
-
-      if (removeLink.bottomNav) {
-        links = this.bottomNavLinks;
-      } else if (removeLink.footerNav) {
-        links = this.footerNavLinks;
-      }
-
-      var foundIndex = -1;
-
-      _.each(links, function (link, index) {
-        if (link.title === removeLink.title) {
-          foundIndex = index;
-        }
-      });
-
-      if (foundIndex === -1) {return;}
-      links.splice(foundIndex, 1);
-      this.render();
-    },
-
-    afterRender: function(){
-
-      $('#primary-navbar li[data-nav-name="' + app.selectedHeader + '"]').addClass('active');
-
-      var menuOpen = true;
-      var $selectorList = $('body');
-      $('.brand').off();
-      $('.brand').on({
-        click: function(e){
-          if(!$(e.target).is('a')){
-            toggleMenu();
-          }
-         }
-      });
-
-      function toggleMenu(){
-        $selectorList.toggleClass('closeMenu');
-        menuOpen = $selectorList.hasClass('closeMenu');
-        app.resizeColumns.onResizeHandler();
-      }
-
-      $('#primary-navbar').on("click", ".nav a", function(){
-        if (!($selectorList.hasClass('closeMenu'))){
-        setTimeout(
-          function(){
-            $selectorList.addClass('closeMenu');
-            app.resizeColumns.onResizeHandler();
-          },3000);
-
-        }
-      });
-
-      app.resizeColumns.initialize();
-    },
-
-    beforeRender: function () {
-      this.addLinkViews();
-    },
-
-    addLinkViews: function () {
-      var that = this;
-
-      _.each(_.union(this.navLinks, this.bottomNavLinks), function (link) {
-        if (!link.view) { return; }
-
-        //TODO check if establish is a function
-        var establish = link.establish || [];
-        $.when.apply(null, establish).then( function () {
-          var selector =  link.bottomNav ? '#bottom-nav-links' : '#nav-links';
-          that.insertView(selector, link.view).render();
-        });
-      }, this);
-    }
-
-    // TODO: ADD ACTIVE CLASS
-  });
-
-  Fauxton.ApiBar = Backbone.View.extend({
-    template: "templates/fauxton/api_bar",
-    endpoint: '_all_docs',
-
-    documentation: 'docs',
-
-    events:  {
-      "click .api-url-btn" : "toggleAPIbar"
-    },
-
-    toggleAPIbar: function(e){
-      var $currentTarget = $(e.currentTarget).find('span');
-      if ($currentTarget.hasClass("fonticon-plus")){
-        $currentTarget.removeClass("fonticon-plus").addClass("fonticon-minus");
-      }else{
-        $currentTarget.removeClass("fonticon-minus").addClass("fonticon-plus");
-      }
-
-      $('.api-navbar').toggle();
-
-    },
-
-    serialize: function() {
-      return {
-        endpoint: this.endpoint,
-        documentation: this.documentation
-      };
-    },
-
-    hide: function(){
-      this.$el.addClass('hide');
-    },
-    show: function(){
-      this.$el.removeClass('hide');
-    },
-    update: function(endpoint) {
-      this.show();
-      this.endpoint = endpoint[0];
-      this.documentation = endpoint[1];
-      this.render();
-    }
-
-  });
-
-  Fauxton.Notification = Backbone.View.extend({
-    fadeTimer: 5000,
-
-    initialize: function(options) {
-      this.msg = options.msg;
-      this.type = options.type || "info";
-      this.selector = options.selector;
-      this.fade = options.fade === undefined ? true : options.fade;
-      this.clear = options.clear;
-      this.data = options.data || "";
-      this.template = options.template || "templates/fauxton/notification";
-    },
-
-    serialize: function() {
-      return {
-        data: this.data,
-        msg: this.msg,
-        type: this.type
-      };
-    },
-
-    delayedFade: function() {
-      var that = this;
-      if (this.fade) {
-        setTimeout(function() {
-          that.$el.fadeOut();
-        }, this.fadeTimer);
-      }
-    },
-
-    renderNotification: function(selector) {
-      selector = selector || this.selector;
-      if (this.clear) {
-        $(selector).html('');
-      }
-      this.render().$el.appendTo(selector);
-      this.delayedFade();
-      return this;
-    }
-  });
-
-  
-  return Fauxton;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/modules/fauxton/components.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/modules/fauxton/components.js b/apps/fauxton/app/modules/fauxton/components.js
deleted file mode 100644
index 6afe046..0000000
--- a/apps/fauxton/app/modules/fauxton/components.js
+++ /dev/null
@@ -1,316 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define('ace_configuration', ["app", "ace/ace"], function (app, ace) {
-  var path = app.host + app.root + 'js/ace';
-  var config = require("ace/config");
-  config.set("packaged", true);
-  config.set("workerPath",path);
-  config.set("modePath",path);
-  config.set("themePath", path);
-  return ace;
-});
-
-define([
-  "app",
-  // Libs
-  "api",
-  "ace_configuration",
-],
-
-function(app, FauxtonAPI, ace) {
-  var Components = app.module();
-
-  Components.Pagination = FauxtonAPI.View.extend({
-    template: "templates/fauxton/pagination",
-
-    initialize: function(options) {
-      this.page = parseInt(options.page, 10);
-      this.perPage = options.perPage;
-      this.total = options.total;
-      this.totalPages = Math.ceil(this.total / this.perPage);
-      this.urlFun = options.urlFun;
-    },
-
-    serialize: function() {
-      return {
-        page: this.page,
-        perPage: this.perPage,
-        total: this.total,
-        totalPages: this.totalPages,
-        urlFun: this.urlFun
-      };
-    }
-  });
-
-  Components.IndexPagination = FauxtonAPI.View.extend({
-    template: "templates/fauxton/index_pagination",
-    events: {
-      "click a": 'scrollTo',
-      "click a#next": 'nextClicked',
-      "click a#previous": 'previousClicked'
-    },
-
-    previousIds: [],
-
-    scrollTo: function () {
-      if (!this.scrollToSelector) { return; }
-      $(this.scrollToSelector).animate({ scrollTop: 0 }, 'slow');
-    },
-
-    initialize: function (options) {
-      this.previousUrlfn = options.previousUrlfn;
-      this.nextUrlfn = options.nextUrlfn;
-      this.canShowPreviousfn = options.canShowPreviousfn;
-      this.canShowNextfn = options.canShowNextfn;
-      this.scrollToSelector = options.scrollToSelector;
-      _.bindAll(this);
-    },
-
-    previousClicked: function (event) {
-      event.preventDefault();
-      event.stopPropagation();
-      if (!this.canShowPreviousfn()) { return; }
-      FauxtonAPI.navigate(this.previousUrlfn(), {trigger: false});
-      FauxtonAPI.triggerRouteEvent('paginate', 'previous');
-    },
-
-    nextClicked: function (event) {
-      event.preventDefault();
-      event.stopPropagation();
-      if (!this.canShowNextfn()) { return; }
-      var doc = this.collection.first();
-
-      if (doc) {
-        this.previousIds.push(doc.id);
-      }
-
-      FauxtonAPI.navigate(this.nextUrlfn(), {trigger: false});
-      FauxtonAPI.triggerRouteEvent('paginate', 'next');
-    },
-
-    serialize: function () {
-      return {
-        canShowNextfn: this.canShowNextfn,
-        canShowPreviousfn: this.canShowPreviousfn,
-      };
-    }
-
-  });
-
-  //TODO allow more of the typeahead options.
-  //Current this just does what we need but we
-  //need to support the other typeahead options.
-  Components.Typeahead = FauxtonAPI.View.extend({
-
-    initialize: function (options) {
-      this.source = options.source;
-      _.bindAll(this);
-    },
-
-    afterRender: function () {
-      var onUpdate = this.onUpdate;
-
-      this.$el.typeahead({
-        source: this.source,
-        updater: function (item) {
-          if (onUpdate) {
-            onUpdate(item);
-          }
-
-          return item;
-        }
-      });
-    }
-
-  });
-
-
-  Components.DbSearchTypeahead = Components.Typeahead.extend({
-    initialize: function (options) {
-      this.dbLimit = options.dbLimit || 30;
-      this.onUpdate = options.onUpdate;
-      _.bindAll(this);
-    },
-    source: function(query, process) {
-      var url = [
-        app.host,
-        "/_all_dbs?startkey=%22",
-        query,
-        "%22&endkey=%22",
-        query,
-        "\u9999",
-        "%22&limit=",
-        this.dbLimit
-      ].join('');
-
-      if (this.ajaxReq) { this.ajaxReq.abort(); }
-
-      this.ajaxReq = $.ajax({
-        cache: false,
-        url: url,
-        dataType: 'json',
-        success: function(data) {
-          process(data);
-        }
-      });
-    }
-  });
-
-  Components.DocSearchTypeahead = Components.Typeahead.extend({
-    initialize: function (options) {
-      this.docLimit = options.docLimit || 30;
-      this.database = options.database;
-      _.bindAll(this);
-    },
-    source: function(query, process) {
-      var url = [
-        app.host,
-        "/",
-        this.database.id,
-        "/_all_docs?startkey=%22",
-        query,
-        "%22&endkey=%22",
-        query,
-        "\u9999",
-        "%22&limit=",
-        this.docLimit
-      ].join('');
-
-      if (this.ajaxReq) { this.ajaxReq.abort(); }
-
-      this.ajaxReq = $.ajax({
-        cache: false,
-        url: url,
-        dataType: 'json',
-        success: function(data) {
-          var ids = _.map(data.rows, function (row) {
-            return row.id;
-          });
-          process(ids);
-        }
-      });
-    }
-  });
-
-  Components.Editor = FauxtonAPI.View.extend({
-    initialize: function (options) {
-      this.editorId = options.editorId;
-      this.mode = options.mode || "json";
-      this.commands = options.commands;
-      this.theme = options.theme || 'crimson_editor';
-      this.couchJSHINT = options.couchJSHINT;
-      this.edited = false;
-    },
-
-    afterRender: function () {
-      this.editor = ace.edit(this.editorId);
-      this.setHeightToLineCount();
-      this.editor.setTheme("ace/theme/" + this.theme);
-      this.editor.getSession().setMode("ace/mode/" + this.mode);
-      this.editor.getSession().setUseWrapMode(true);
-      this.editor.setShowPrintMargin(false);
-      this.editor.gotoLine(2);
-      this.addCommands();
-
-      if (this.couchJSHINT) {
-        this.removeIncorrectAnnotations();
-      }
-
-      var that = this;
-      this.editor.getSession().on('change', function () {
-        that.setHeightToLineCount();
-        that.edited = true;
-      });
-
-      $(window).on('beforeunload.editor', function() {
-        if (that.edited) {
-          return 'Your changes have not been saved. Click cancel to return to the document.';
-        }
-      });
-
-      FauxtonAPI.beforeUnload("editor", function (deferred) {
-        if (that.edited) {
-          return 'Your changes have not been saved. Click cancel to return to the document.';
-        }
-      });
-    },
-
-    cleanup: function () {
-      $(window).off('beforeunload.editor');
-      FauxtonAPI.removeBeforeUnload("editor");
-    },
-
-    setHeightToLineCount: function () {
-      var lines = this.editor.getSession().getDocument().getLength();
-      this.editor.setOptions({
-        maxLines: lines
-      });
-
-      this.editor.resize();
-    },
-
-    addCommands: function () {
-      _.each(this.commands, function (command) {
-        this.editor.commands.addCommand(command);
-      }, this);
-    },
-
-    removeIncorrectAnnotations: function () {
-      var editor = this.editor;
-
-      this.editor.getSession().on("changeAnnotation", function(){
-        var annotations = editor.getSession().getAnnotations();
-
-        var newAnnotations = _.reduce(annotations, function (annotations, error) {
-          if (!FauxtonAPI.isIgnorableError(error.raw)) {
-            annotations.push(error);
-          }
-          return annotations;
-        }, []);
-
-        if (annotations.length !== newAnnotations.length) {
-          editor.getSession().setAnnotations(newAnnotations);
-        }
-      });
-    },
-
-    editSaved: function () {
-      this.edited = false;
-    },
-
-    setValue: function (data, lineNumber) {
-      lineNumber = lineNumber ? lineNumber : -1;
-      this.editor.setValue(data, lineNumber);
-    },
-
-    getValue: function () {
-      return this.editor.getValue();
-    },
-
-    getAnnotations: function () {
-      return this.editor.getSession().getAnnotations();
-    },
-
-    hadValidCode: function () {
-     var errors = this.getAnnotations();
-     // By default CouchDB view functions don't pass lint
-     return _.every(errors, function(error) {
-      return FauxtonAPI.isIgnorableError(error.raw);
-      },this);
-    }
-
-  });
-
-  return Components;
-});
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/modules/fauxton/layout.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/modules/fauxton/layout.js b/apps/fauxton/app/modules/fauxton/layout.js
deleted file mode 100644
index 1422241..0000000
--- a/apps/fauxton/app/modules/fauxton/layout.js
+++ /dev/null
@@ -1,98 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define(["backbone"],
-
-function(Backbone) {
-
-  // A wrapper of the main Backbone.layoutmanager
-  // Allows the main layout of the page to be changed by any plugin.
-  // Exposes the different views:
-  //    navBar -> the top navigation bar
-  //    dashboardContent -> Main display view
-  //    breadcrumbs -> Breadcrumbs navigation section
-  var Layout = function (navBar, apiBar) {
-    this.navBar = navBar;
-    this.apiBar = apiBar;
-
-    this.layout = new Backbone.Layout({
-      template: "templates/layouts/with_sidebar",
-
-      views: {
-        "#primary-navbar": this.navBar,
-        "#api-navbar": this.apiBar
-      },
-      afterRender: function(){
-
-      }
-    });
-
-    this.layoutViews = {};
-    //this.hooks = {};
-
-    this.el = this.layout.el;
-  };
-
-  // creatings the dashboard object same way backbone does
-  _.extend(Layout.prototype, {
-    render: function () {
-      return this.layout.render();
-    },
-
-    setTemplate: function(template) {
-      if (template.prefix){
-        this.layout.template = template.prefix + template.name;
-      } else{
-        this.layout.template = "templates/layouts/" + template;
-      }
-      // If we're changing layouts all bets are off, so kill off all the
-      // existing views in the layout.
-      _.each(this.layoutViews, function(view){view.remove();});
-      this.layoutViews = {};
-      this.render();
-    },
-
-    setTabs: function(view){
-      // TODO: Not sure I like this - seems fragile/repetitive
-      this.tabs = this.layout.setView("#tabs", view);
-      this.tabs.render();
-    },
-
-    setBreadcrumbs: function(view) {
-      this.breadcrumbs = this.layout.setView("#breadcrumbs", view);
-      this.breadcrumbs.render();
-    },
-
-    clearBreadcrumbs: function () {
-      if (!this.breadcrumbs) {return ;}
-
-      this.breadcrumbs.remove();
-    },
-
-    setView: function(selector, view) {
-      this.layoutViews[selector] = this.layout.setView(selector, view, false);
-    },
-
-    renderView: function(selector) {
-      var view = this.layoutViews[selector];
-      if (!view) {
-        return false;
-      } else {
-        return view.render();
-      }
-    }
-
-  });
-
-  return Layout;
-
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/modules/pouchdb/base.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/modules/pouchdb/base.js b/apps/fauxton/app/modules/pouchdb/base.js
deleted file mode 100644
index ee323a7..0000000
--- a/apps/fauxton/app/modules/pouchdb/base.js
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * NOTE:
- * This temporarily uses the PouchDB map reduce implementation
- * These files are modified locally until we make a more general version and
- * push it back upstream.
- */
-
-define([
-  "app",
-
-  "api",
-
-  // Modules
-  "modules/pouchdb/pouchdb.mapreduce.js"
-],
-
-function(app, FauxtonAPI, MapReduce) {
-  var Pouch = {};
-  Pouch.MapReduce = MapReduce;
-
-  Pouch.runViewQuery = function(fun, opts) {
-    /*docs = [
-      {_id: 'test_doc_1', foo: 'bar-1'},
-      {_id: 'test_doc_2', foo: 'bar-2'},
-      {_id: 'test_doc_3', foo: 'bar-3'},
-      {_id: 'test_doc_4', foo: 'bar-4'},
-      {_id: 'test_doc_5', foo: 'bar-5'},
-      {_id: 'test_doc_6', foo: 'bar-6'},
-      {_id: 'test_doc_7', foo: 'bar-7'},
-      {_id: 'test_doc_8', foo: 'bar-8'},
-      {_id: 'test_doc_9', foo: 'bar-9'},
-      {_id: 'test_doc_10', foo: 'bar-10'}
-    ];*/
-
-    var deferred = FauxtonAPI.Deferred();
-    var complete = function(resp, rows) {
-      deferred.resolve(rows);
-    };
-
-    var options = _.extend(opts, {complete: complete});
-
-    Pouch.MapReduce.query(fun, options);
-    return deferred;
-  };
-  //pdb.runViewQuery({map:function(doc) { emit(doc._id, doc.foo) }})
-  return Pouch;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/modules/pouchdb/pouch.collate.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/modules/pouchdb/pouch.collate.js b/apps/fauxton/app/modules/pouchdb/pouch.collate.js
deleted file mode 100644
index 7cc5f9c..0000000
--- a/apps/fauxton/app/modules/pouchdb/pouch.collate.js
+++ /dev/null
@@ -1,115 +0,0 @@
-/*
- * NOTE:
- * This temporarily uses the PouchDB map reduce implementation
- * These files are modified locally until we make a more general version and
- * push it back upstream.
- * Original file:
- * https://github.com/daleharvey/pouchdb/blob/master/src/pouch.collate.js
- */
-
-/*
-(function() {
-  // a few hacks to get things in the right place for node.js
-  if (typeof module !== 'undefined' && module.exports) {
-    module.exports = Pouch;
-  }
-*/
-
-define([
-  "app",
-
-  "api",
-
-  // Modules
-  "modules/pouchdb/pouch.collate.js"
-],
-
-function(app, FauxtonAPI, Collate) {
-  var Pouch = {};
-
-  Pouch.collate = function(a, b) {
-    var ai = collationIndex(a);
-    var bi = collationIndex(b);
-    if ((ai - bi) !== 0) {
-      return ai - bi;
-    }
-    if (a === null) {
-      return 0;
-    }
-    if (typeof a === 'number') {
-      return a - b;
-    }
-    if (typeof a === 'boolean') {
-      return a < b ? -1 : 1;
-    }
-    if (typeof a === 'string') {
-      return stringCollate(a, b);
-    }
-    if (Array.isArray(a)) {
-      return arrayCollate(a, b);
-    }
-    if (typeof a === 'object') {
-      return objectCollate(a, b);
-    }
-  };
-
-  var stringCollate = function(a, b) {
-    // See: https://github.com/daleharvey/pouchdb/issues/40
-    // This is incompatible with the CouchDB implementation, but its the
-    // best we can do for now
-    return (a === b) ? 0 : ((a > b) ? 1 : -1);
-  };
-
-  var objectCollate = function(a, b) {
-    var ak = Object.keys(a), bk = Object.keys(b);
-    var len = Math.min(ak.length, bk.length);
-    for (var i = 0; i < len; i++) {
-      // First sort the keys
-      var sort = Pouch.collate(ak[i], bk[i]);
-      if (sort !== 0) {
-        return sort;
-      }
-      // if the keys are equal sort the values
-      sort = Pouch.collate(a[ak[i]], b[bk[i]]);
-      if (sort !== 0) {
-        return sort;
-      }
-
-    }
-    return (ak.length === bk.length) ? 0 :
-      (ak.length > bk.length) ? 1 : -1;
-  };
-
-  var arrayCollate = function(a, b) {
-    var len = Math.min(a.length, b.length);
-    for (var i = 0; i < len; i++) {
-      var sort = Pouch.collate(a[i], b[i]);
-      if (sort !== 0) {
-        return sort;
-      }
-    }
-    return (a.length === b.length) ? 0 :
-      (a.length > b.length) ? 1 : -1;
-  };
-
-  // The collation is defined by erlangs ordered terms
-  // the atoms null, true, false come first, then numbers, strings,
-  // arrays, then objects
-  var collationIndex = function(x) {
-    var id = ['boolean', 'number', 'string', 'object'];
-    if (id.indexOf(typeof x) !== -1) {
-      if (x === null) {
-        return 1;
-      }
-      return id.indexOf(typeof x) + 2;
-    }
-    if (Array.isArray(x)) {
-      return 4.5;
-    }
-  };
-
-  return Pouch;
-
-//}).call(this);
-
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/modules/pouchdb/pouchdb.mapreduce.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/modules/pouchdb/pouchdb.mapreduce.js b/apps/fauxton/app/modules/pouchdb/pouchdb.mapreduce.js
deleted file mode 100644
index a2d0b91..0000000
--- a/apps/fauxton/app/modules/pouchdb/pouchdb.mapreduce.js
+++ /dev/null
@@ -1,324 +0,0 @@
-/*
- * NOTE:
- * This temporarily uses the PouchDB map reduce implementation
- * These files are modified locally until we make a more general version and
- * push it back upstream.
- * Original file:
- * https://github.com/daleharvey/pouchdb/blob/master/src/plugins/pouchdb.mapreduce.js
- */
-
-/*global Pouch: true */
-
-//"use strict";
-
-// This is the first implementation of a basic plugin, we register the
-// plugin object with pouch and it is mixin'd to each database created
-// (regardless of adapter), adapters can override plugins by providing
-// their own implementation. functions on the plugin object that start
-// with _ are reserved function that are called by pouchdb for special
-// notifications.
-
-// If we wanted to store incremental views we can do it here by listening
-// to the changes feed (keeping track of our last update_seq between page loads)
-// and storing the result of the map function (possibly using the upcoming
-// extracted adapter functions)
-
-define([
-  "app",
-
-  "api",
-
-  // Modules
-  "modules/pouchdb/pouch.collate.js"
-],
-
-function(app, FauxtonAPI, Collate) {
-  var Pouch = {};
-  Pouch.collate = Collate.collate;
-
-  //var MapReduce = function(db) {
-  var MapReduce = function() {
-
-    var builtInReduce = {
-      "_sum": function(keys, values){
-        return sum(values);
-      },
-
-      "_count": function(keys, values, rereduce){
-        if (rereduce){
-          return sum(values);
-        } else {
-          return values.length;
-        }
-      },
-
-      "_stats": function(keys, values, rereduce){
-        return {
-          'sum': sum(values),
-          'min': Math.min.apply(null, values),
-          'max': Math.max.apply(null, values),
-          'count': values.length,
-          'sumsqr': (function(){
-            _sumsqr = 0;
-            for(var idx in values){
-              _sumsqr += values[idx] * values[idx];
-            }
-            return _sumsqr;
-          })()
-        };
-      }
-    };
-
-    function viewQuery(fun, options) {
-      console.log("IN VIEW QUERY");
-      if (!options.complete) {
-        return;
-      }
-
-      function sum(values) {
-        return values.reduce(function(a, b) { return a + b; }, 0);
-      }
-
-      var results = [];
-      var current = null;
-      var num_started= 0;
-      var completed= false;
-
-      var emit = function(key, val) {
-        //console.log("IN EMIT: ", key, val, current);
-        var viewRow = {
-          id: current.doc._id,
-          key: key,
-          value: val
-        }; 
-        //console.log("VIEW ROW: ", viewRow);
-
-        if (options.startkey && Pouch.collate(key, options.startkey) < 0) return;
-        if (options.endkey && Pouch.collate(key, options.endkey) > 0) return;
-        if (options.key && Pouch.collate(key, options.key) !== 0) return;
-        num_started++;
-        if (options.include_docs) {
-          // TODO:: FIX
-          throw({error: "Include Docs not supported"});
-          /*
-
-          //in this special case, join on _id (issue #106)
-          if (val && typeof val === 'object' && val._id){
-            db.get(val._id,
-                function(_, joined_doc){
-                  if (joined_doc) {
-                    viewRow.doc = joined_doc;
-                  }
-                  results.push(viewRow);
-                  checkComplete();
-                });
-            return;
-          } else {
-            viewRow.doc = current.doc;
-          }
-          */
-        }
-        console.log("EMITTING: ", viewRow);
-        results.push(viewRow);
-      };
-
-      // ugly way to make sure references to 'emit' in map/reduce bind to the
-      // above emit
-      eval('fun.map = ' + fun.map.toString() + ';');
-      if (fun.reduce && options.reduce) {
-        if (builtInReduce[fun.reduce]) {
-          console.log('built in reduce');
-          fun.reduce = builtInReduce[fun.reduce];
-        }
-        eval('fun.reduce = ' + fun.reduce.toString() + ';');
-      }
-
-      // exclude  _conflicts key by default
-      // or to use options.conflicts if it's set when called by db.query
-      var conflicts = ('conflicts' in options ? options.conflicts : false);
-
-      //only proceed once all documents are mapped and joined
-      var checkComplete= function(){
-        console.log('check');
-        if (completed && results.length == num_started){
-          results.sort(function(a, b) {
-            return Pouch.collate(a.key, b.key);
-          });
-          if (options.descending) {
-            results.reverse();
-          }
-          if (options.reduce === false) {
-            return options.complete(null, {rows: results});
-          }
-
-          console.log('reducing', options);
-          var groups = [];
-          results.forEach(function(e) {
-            var last = groups[groups.length-1] || null;
-            if (last && Pouch.collate(last.key[0][0], e.key) === 0) {
-              last.key.push([e.key, e.id]);
-              last.value.push(e.value);
-              return;
-            }
-            groups.push({key: [[e.key, e.id]], value: [e.value]});
-          });
-          groups.forEach(function(e) {
-            e.value = fun.reduce(e.key, e.value) || null;
-            e.key = e.key[0][0];
-          });
-          console.log('GROUPs', groups);
-          options.complete(null, {rows: groups});
-        }
-      };
-
-      if (options.docs) {
-        //console.log("RUNNING MR ON DOCS: ", options.docs);
-        _.each(options.docs, function(doc) {
-          current = {doc: doc};
-          fun.map.call(this, doc);
-        }, this);
-        completed = true;
-        return checkComplete();//options.complete(null, {rows: results});
-      } else {
-        //console.log("COULD NOT FIND DOCS");
-        return false;
-      }
-
-      /*
-      db.changes({
-        conflicts: conflicts,
-        include_docs: true,
-        onChange: function(doc) {
-          if (!('deleted' in doc)) {
-            current = {doc: doc.doc};
-            fun.map.call(this, doc.doc);
-          }
-        },
-        complete: function() {
-          completed= true;
-          checkComplete();
-        }
-      });
-      */
-    }
-
-    /*
-    function httpQuery(fun, opts, callback) {
-
-      // List of parameters to add to the PUT request
-      var params = [];
-      var body = undefined;
-      var method = 'GET';
-
-      // If opts.reduce exists and is defined, then add it to the list
-      // of parameters.
-      // If reduce=false then the results are that of only the map function
-      // not the final result of map and reduce.
-      if (typeof opts.reduce !== 'undefined') {
-        params.push('reduce=' + opts.reduce);
-      }
-      if (typeof opts.include_docs !== 'undefined') {
-        params.push('include_docs=' + opts.include_docs);
-      }
-      if (typeof opts.limit !== 'undefined') {
-        params.push('limit=' + opts.limit);
-      }
-      if (typeof opts.descending !== 'undefined') {
-        params.push('descending=' + opts.descending);
-      }
-      if (typeof opts.startkey !== 'undefined') {
-        params.push('startkey=' + encodeURIComponent(JSON.stringify(opts.startkey)));
-      }
-      if (typeof opts.endkey !== 'undefined') {
-        params.push('endkey=' + encodeURIComponent(JSON.stringify(opts.endkey)));
-      }
-      if (typeof opts.key !== 'undefined') {
-        params.push('key=' + encodeURIComponent(JSON.stringify(opts.key)));
-      }
-
-      // If keys are supplied, issue a POST request to circumvent GET query string limits
-      // see http://wiki.apache.org/couchdb/HTTP_view_API#Querying_Options
-      if (typeof opts.keys !== 'undefined') {
-        method = 'POST';
-        body = JSON.stringify({keys:opts.keys});
-      }
-
-      // Format the list of parameters into a valid URI query string
-      params = params.join('&');
-      params = params === '' ? '' : '?' + params;
-
-      // We are referencing a query defined in the design doc
-      if (typeof fun === 'string') {
-        var parts = fun.split('/');
-        db.request({
-          method: method,
-          url: '_design/' + parts[0] + '/_view/' + parts[1] + params,
-          body: body
-        }, callback);
-        return;
-      }
-
-      // We are using a temporary view, terrible for performance but good for testing
-      var queryObject = JSON.parse(JSON.stringify(fun, function(key, val) {
-        if (typeof val === 'function') {
-          return val + ''; // implicitly `toString` it
-        }
-        return val;
-      }));
-
-      db.request({
-        method:'POST',
-        url: '_temp_view' + params,
-        body: queryObject
-      }, callback);
-    }
-    */
-
-    function query(fun, opts, callback) {
-      if (typeof opts === 'function') {
-        callback = opts;
-        opts = {};
-      }
-
-      if (callback) {
-        opts.complete = callback;
-      }
-
-      /*
-      if (db.type() === 'http') {
-        return httpQuery(fun, opts, callback);
-      }
-      */
-
-      if (typeof fun === 'object') {
-        console.log("RUNNING VIEW QUERY", fun, opts, arguments);
-        return viewQuery(fun, opts);
-      }
-
-      throw({error: "Shouldn't have gotten here"});
-
-      /*
-      var parts = fun.split('/');
-      db.get('_design/' + parts[0], function(err, doc) {
-        if (err) {
-          if (callback) callback(err);
-          return;
-        }
-        viewQuery({
-          map: doc.views[parts[1]].map,
-          reduce: doc.views[parts[1]].reduce
-        }, opts);
-      });
-      */
-    }
-
-    return {'query': query};
-  };
-
-  // Deletion is a noop since we dont store the results of the view
-  MapReduce._delete = function() { };
-
-  //Pouch.plugin('mapreduce', MapReduce);
-
-  return MapReduce();
-});


[11/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/js/plugins/backbone.layoutmanager.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/js/plugins/backbone.layoutmanager.js b/apps/fauxton/assets/js/plugins/backbone.layoutmanager.js
deleted file mode 100644
index b8296b4..0000000
--- a/apps/fauxton/assets/js/plugins/backbone.layoutmanager.js
+++ /dev/null
@@ -1,996 +0,0 @@
-/*!
- * backbone.layoutmanager.js v0.9.1
- * Copyright 2013, Tim Branyen (@tbranyen)
- * backbone.layoutmanager.js may be freely distributed under the MIT license.
- */
-(function(window, factory) {
-  "use strict";
-  var Backbone = window.Backbone;
-
-  // AMD. Register as an anonymous module.  Wrap in function so we have access
-  // to root via `this`.
-  if (typeof define === "function" && define.amd) {
-    return define(["backbone", "underscore", "jquery"], function() {
-      return factory.apply(window, arguments);
-    });
-  }
-
-  // Browser globals.
-  Backbone.Layout = factory.call(window, Backbone, window._, Backbone.$);
-}(typeof global === "object" ? global : this, function (Backbone, _, $) {
-"use strict";
-
-// Create a reference to the global object. In browsers, it will map to the
-// `window` object; in Node, it will be `global`.
-var window = this;
-
-// Hoisted, referenced at the bottom of the source.  This caches a list of all
-// LayoutManager options at definition time.
-var keys;
-
-// Maintain references to the two `Backbone.View` functions that are
-// overwritten so that they can be proxied.
-var _configure = Backbone.View.prototype._configure;
-
-// Cache these methods for performance.
-var aPush = Array.prototype.push;
-var aConcat = Array.prototype.concat;
-var aSplice = Array.prototype.splice;
-
-// LayoutManager is a wrapper around a `Backbone.View`.
-var LayoutManager = Backbone.View.extend({
-  _render: function(manage, options) {
-    // Keep the view consistent between callbacks and deferreds.
-    var view = this;
-    // Shorthand the manager.
-    var manager = view.__manager__;
-    // Cache these properties.
-    var beforeRender = options.beforeRender;
-    // Create a deferred instead of going off
-    var def = options.deferred();
-
-    // Ensure all nested Views are properly scrubbed if re-rendering.
-    if (view.hasRendered) {
-      view._removeViews();
-    }
-
-    // This continues the render flow after `beforeRender` has completed.
-    manager.callback = function() {
-      // Clean up asynchronous manager properties.
-      delete manager.isAsync;
-      delete manager.callback;
-
-      // Always emit a beforeRender event.
-      view.trigger("beforeRender", view);
-
-      // Render!
-      manage(view, options).render().then(function() {
-        // Complete this deferred once resolved.
-        def.resolve();
-      });
-    };
-
-    // If a beforeRender function is defined, call it.
-    if (beforeRender) {
-      beforeRender.call(view, view);
-    }
-
-    if (!manager.isAsync) {
-      manager.callback();
-    }
-
-    // Return this intermediary promise.
-    return def.promise();
-  },
-      
-  // This named function allows for significantly easier debugging.
-  constructor: function Layout(options) {
-    // Options may not always be passed to the constructor, this ensures it is
-    // always an object.
-    options = options || {};
-
-    // Grant this View superpowers.
-    LayoutManager.setupView(this, options);
-
-    // Have Backbone set up the rest of this View.
-    Backbone.View.call(this, options);
-  },
-
-  // This method is used within specific methods to indicate that they should
-  // be treated as asynchronous.  This method should only be used within the
-  // render chain, otherwise unexpected behavior may occur.
-  async: function() {
-    var manager = this.__manager__;
-
-    // Set this View's action to be asynchronous.
-    manager.isAsync = true;
-
-    // Return the callback.
-    return manager.callback;
-  },
-
-  promise: function() {
-    return this.__manager__.renderDeferred.promise();
-  },
-
-  // Sometimes it's desirable to only render the child views under the parent.
-  // This is typical for a layout that does not change.  This method will
-  // iterate over the child Views and aggregate all child render promises and
-  // return the parent View.  The internal `promise()` method will return the
-  // aggregate promise that resolves once all children have completed their
-  // render.
-  renderViews: function() {
-    var root = this;
-    var manager = root.__manager__;
-    var options = root.getAllOptions();
-    var newDeferred = options.deferred();
-
-    // Collect all promises from rendering the child views and wait till they
-    // all complete.
-    var promises = root.getViews().map(function(view) {
-      return view.render().__manager__.renderDeferred;
-    }).value();
-
-    // Simulate a parent render to remain consistent.
-    manager.renderDeferred = newDeferred.promise();
-
-    // Once all child views have completed rendering, resolve parent deferred
-    // with the correct context.
-    options.when(promises).then(function() {
-      newDeferred.resolveWith(root, [root]);
-    });
-
-    // Allow this method to be chained.
-    return root;
-  },
-
-  // Shorthand to `setView` function with the `insert` flag set.
-  insertView: function(selector, view) {
-    // If the `view` argument exists, then a selector was passed in.  This code
-    // path will forward the selector on to `setView`.
-    if (view) {
-      return this.setView(selector, view, true);
-    }
-
-    // If no `view` argument is defined, then assume the first argument is the
-    // View, somewhat now confusingly named `selector`.
-    return this.setView(selector, true);
-  },
-
-  // Iterate over an object and ensure every value is wrapped in an array to
-  // ensure they will be inserted, then pass that object to `setViews`.
-  insertViews: function(views) {
-    // If an array of views was passed it should be inserted into the
-    // root view. Much like calling insertView without a selector.
-    if (_.isArray(views)) {
-      return this.setViews({ "": views });
-    }
-
-    _.each(views, function(view, selector) {
-      views[selector] = _.isArray(view) ? view : [view];
-    });
-
-    return this.setViews(views);
-  },
-
-  // Returns the View that matches the `getViews` filter function.
-  getView: function(fn) {
-    // If `getView` is invoked with undefined as the first argument, then the
-    // second argument will be used instead.  This is to allow
-    // `getViews(undefined, fn)` to work as `getViews(fn)`.  Useful for when
-    // you are allowing an optional selector.
-    if (fn == null) {
-      fn = arguments[1];
-    }
-
-    return this.getViews(fn).first().value();
-  },
-
-  // Provide a filter function to get a flattened array of all the subviews.
-  // If the filter function is omitted it will return all subviews.  If a
-  // String is passed instead, it will return the Views for that selector.
-  getViews: function(fn) {
-    var views;
-
-    // If the filter argument is a String, then return a chained Version of the
-    // elements. The value at the specified filter may be undefined, a single
-    // view, or an array of views; in all cases, chain on a flat array.
-    if (typeof fn === "string") {
-      fn = this.sections[fn] || fn;
-      views = this.views[fn] || [];
-
-      // If Views is undefined you are concatenating an `undefined` to an array
-      // resulting in a value being returned.  Defaulting to an array prevents
-      // this.
-      //return _.chain([].concat(views || []));
-      return _.chain([].concat(views));
-    }
-
-    // Generate an array of all top level (no deeply nested) Views flattened.
-    views = _.chain(this.views).map(function(view) {
-      return _.isArray(view) ? view : [view];
-    }, this).flatten();
-
-    // If the argument passed is an Object, then pass it to `_.where`.
-    if (typeof fn === "object") {
-      return views.where(fn);
-    }
-
-    // If a filter function is provided, run it on all Views and return a
-    // wrapped chain. Otherwise, simply return a wrapped chain of all Views.
-    return typeof fn === "function" ? views.filter(fn) : views;
-  },
-
-  // Use this to remove Views, internally uses `getViews` so you can pass the
-  // same argument here as you would to that method.
-  removeView: function(fn) {
-    // Allow an optional selector or function to find the right model and
-    // remove nested Views based off the results of the selector or filter.
-    return this.getViews(fn).each(function(nestedView) {
-      nestedView.remove();
-    });
-  },
-
-  // This takes in a partial name and view instance and assigns them to
-  // the internal collection of views.  If a view is not a LayoutManager
-  // instance, then mix in the LayoutManager prototype.  This ensures
-  // all Views can be used successfully.
-  //
-  // Must definitely wrap any render method passed in or defaults to a
-  // typical render function `return layout(this).render()`.
-  setView: function(name, view, insert) {
-    var manager, options, selector;
-    // Parent view, the one you are setting a View on.
-    var root = this;
-
-    // If no name was passed, use an empty string and shift all arguments.
-    if (typeof name !== "string") {
-      insert = view;
-      view = name;
-      name = "";
-    }
-
-    // Shorthand the `__manager__` property.
-    manager = view.__manager__;
-
-    // If the View has not been properly set up, throw an Error message
-    // indicating that the View needs `manage: true` set.
-    if (!manager) {
-      throw new Error("The argument associated with selector '" + name +
-        "' is defined and a View.  Set `manage` property to true for " +
-        "Backbone.View instances.");
-    }
-
-    // Assign options.
-    options = view.getAllOptions();
-
-    // Add reference to the parentView.
-    manager.parent = root;
-
-    // Add reference to the placement selector used.
-    selector = manager.selector = root.sections[name] || name;
-
-    // Call the `setup` method, since we now have a relationship created.
-    _.result(view, "setup");
-
-    // Code path is less complex for Views that are not being inserted.  Simply
-    // remove existing Views and bail out with the assignment.
-    if (!insert) {
-      // If the View we are adding has already been rendered, simply inject it
-      // into the parent.
-      if (view.hasRendered) {
-        // Apply the partial.
-        options.partial(root.$el, view.$el, root.__manager__, manager);
-      }
-
-      // Ensure remove is called when swapping View's.
-      root.removeView(name);
-
-      // Assign to main views object and return for chainability.
-      return root.views[selector] = view;
-    }
-
-    // Ensure this.views[selector] is an array and push this View to
-    // the end.
-    root.views[selector] = aConcat.call([], root.views[name] || [], view);
-
-    // Put the parent view into `insert` mode.
-    root.__manager__.insert = true;
-
-    return view;
-  },
-
-  // Allows the setting of multiple views instead of a single view.
-  setViews: function(views) {
-    // Iterate over all the views and use the View's view method to assign.
-    _.each(views, function(view, name) {
-      // If the view is an array put all views into insert mode.
-      if (_.isArray(view)) {
-        return _.each(view, function(view) {
-          this.insertView(name, view);
-        }, this);
-      }
-
-      // Assign each view using the view function.
-      this.setView(name, view);
-    }, this);
-
-    // Allow for chaining
-    return this;
-  },
-
-  // By default this should find all nested views and render them into
-  // the this.el and call done once all of them have successfully been
-  // resolved.
-  //
-  // This function returns a promise that can be chained to determine
-  // once all subviews and main view have been rendered into the view.el.
-  render: function() {
-    var root = this;
-    var options = root.getAllOptions();
-    var manager = root.__manager__;
-    var parent = manager.parent;
-    var rentManager = parent && parent.__manager__;
-    var def = options.deferred();
-
-    // Triggered once the render has succeeded.
-    function resolve() {
-      var next;
-
-      // Insert all subViews into the parent at once.
-      _.each(root.views, function(views, selector) {
-        // Fragments aren't used on arrays of subviews.
-        if (_.isArray(views)) {
-          options.htmlBatch(root, views, selector);
-        }
-      });
-
-      // If there is a parent and we weren't attached to it via the previous
-      // method (single view), attach.
-      if (parent && !manager.insertedViaFragment) {
-        if (!options.contains(parent.el, root.el)) {
-          // Apply the partial using parent's html() method.
-          parent.getAllOptions().partial(parent.$el, root.$el, rentManager,
-            manager);
-        }
-      }
-
-      // Ensure events are always correctly bound after rendering.
-      root.delegateEvents();
-
-      // Set this View as successfully rendered.
-      root.hasRendered = true;
-
-      // Only process the queue if it exists.
-      if (next = manager.queue.shift()) {
-        // Ensure that the next render is only called after all other
-        // `done` handlers have completed.  This will prevent `render`
-        // callbacks from firing out of order.
-        next();
-      } else {
-        // Once the queue is depleted, remove it, the render process has
-        // completed.
-        delete manager.queue;
-      }
-
-      // Reusable function for triggering the afterRender callback and event
-      // and setting the hasRendered flag.
-      function completeRender() {
-        var console = window.console;
-        var afterRender = options.afterRender;
-
-        if (afterRender) {
-          afterRender.call(root, root);
-        }
-
-        // Always emit an afterRender event.
-        root.trigger("afterRender", root);
-
-        // If there are multiple top level elements and `el: false` is used,
-        // display a warning message and a stack trace.
-        if (manager.noel && root.$el.length > 1) {
-          // Do not display a warning while testing or if warning suppression
-          // is enabled.
-          if (_.isFunction(console.warn) && !options.suppressWarnings) {
-            console.warn("`el: false` with multiple top level elements is " +
-              "not supported.");
-
-            // Provide a stack trace if available to aid with debugging.
-            if (_.isFunction(console.trace)) {
-              console.trace();
-            }
-          }
-        }
-      }
-
-      // If the parent is currently rendering, wait until it has completed
-      // until calling the nested View's `afterRender`.
-      if (rentManager && rentManager.queue) {
-        // Wait until the parent View has finished rendering, which could be
-        // asynchronous, and trigger afterRender on this View once it has
-        // compeleted.
-        parent.once("afterRender", completeRender);
-      } else {
-        // This View and its parent have both rendered.
-        completeRender();
-      }
-
-      return def.resolveWith(root, [root]);
-    }
-
-    // Actually facilitate a render.
-    function actuallyRender() {
-      var options = root.getAllOptions();
-
-      // The `_viewRender` method is broken out to abstract away from having
-      // too much code in `actuallyRender`.
-      root._render(LayoutManager._viewRender, options).done(function() {
-        // If there are no children to worry about, complete the render
-        // instantly.
-        if (!_.keys(root.views).length) {
-          return resolve();
-        }
-
-        // Create a list of promises to wait on until rendering is done.
-        // Since this method will run on all children as well, its sufficient
-        // for a full hierarchical.
-        var promises = _.map(root.views, function(view) {
-          var insert = _.isArray(view);
-
-          // If items are being inserted, they will be in a non-zero length
-          // Array.
-          if (insert && view.length) {
-            // Mark each subview's manager so they don't attempt to attach by
-            // themselves.  Return a single promise representing the entire
-            // render.
-            return options.when(_.map(view, function(subView) {
-              subView.__manager__.insertedViaFragment = true;
-              return subView.render().__manager__.renderDeferred;
-            }));
-          }
-
-          // Only return the fetch deferred, resolve the main deferred after
-          // the element has been attached to it's parent.
-          return !insert ? view.render().__manager__.renderDeferred : view;
-        });
-
-        // Once all nested Views have been rendered, resolve this View's
-        // deferred.
-        options.when(promises).done(resolve);
-      });
-    }
-
-    // Another render is currently happening if there is an existing queue, so
-    // push a closure to render later into the queue.
-    if (manager.queue) {
-      aPush.call(manager.queue, actuallyRender);
-    } else {
-      manager.queue = [];
-
-      // This the first `render`, preceeding the `queue` so render
-      // immediately.
-      actuallyRender(root, def);
-    }
-
-    // Put the deferred inside of the `__manager__` object, since we don't want
-    // end users accessing this directly anymore in favor of the `afterRender`
-    // event.  So instead of doing `render().then(...` do
-    // `render().once("afterRender", ...`.
-    root.__manager__.renderDeferred = def;
-
-    // Return the actual View for chainability purposes.
-    return root;
-  },
-
-  // Ensure the cleanup function is called whenever remove is called.
-  remove: function() {
-    // Force remove itself from its parent.
-    LayoutManager._removeView(this, true);
-
-    // Call the original remove function.
-    return this._remove.apply(this, arguments);
-  },
-
-  // Merge instance and global options.
-  getAllOptions: function() {
-    // Instance overrides take precedence, fallback to prototype options.
-    return _.extend({}, this, LayoutManager.prototype.options, this.options);
-  }
-},
-{
-  // Clearable cache.
-  _cache: {},
-
-  // Creates a deferred and returns a function to call when finished.
-  // This gets passed to all _render methods.  The `root` value here is passed
-  // from the `manage(this).render()` line in the `_render` function
-  _viewRender: function(root, options) {
-    var url, contents, def, renderedEl;
-    var manager = root.__manager__;
-
-    // This function is responsible for pairing the rendered template into
-    // the DOM element.
-    function applyTemplate(rendered) {
-      // Actually put the rendered contents into the element.
-      if (_.isString(rendered)) {
-        // If no container is specified, we must replace the content.
-        if (manager.noel) {
-          // Trim off the whitespace, since the contents are passed into `$()`.
-          rendered = $.trim(rendered);
-
-          // Hold a reference to created element as replaceWith doesn't return
-          // new el.
-          renderedEl = $(rendered);
-
-          // Remove extra root elements.
-          root.$el.slice(1).remove();
-
-          // Swap out the View on the first top level element to avoid
-          // duplication.
-          root.$el.replaceWith(renderedEl);
-
-          // Don't delegate events here - we'll do that in resolve()
-          root.setElement(renderedEl, false);
-        } else {
-          options.html(root.$el, rendered);
-        }
-      }
-
-      // Resolve only after fetch and render have succeeded.
-      def.resolveWith(root, [root]);
-    }
-
-    // Once the template is successfully fetched, use its contents to proceed.
-    // Context argument is first, since it is bound for partial application
-    // reasons.
-    function done(context, contents) {
-      // Store the rendered template someplace so it can be re-assignable.
-      var rendered;
-
-      // Trigger this once the render method has completed.
-      manager.callback = function(rendered) {
-        // Clean up asynchronous manager properties.
-        delete manager.isAsync;
-        delete manager.callback;
-
-        applyTemplate(rendered);
-      };
-
-      // Ensure the cache is up-to-date.
-      LayoutManager.cache(url, contents);
-
-      // Render the View into the el property.
-      if (contents) {
-        rendered = options.renderTemplate.call(root, contents, context);
-      }
-
-      // If the function was synchronous, continue execution.
-      if (!manager.isAsync) {
-        applyTemplate(rendered);
-      }
-    }
-
-    return {
-      // This `render` function is what gets called inside of the View render,
-      // when `manage(this).render` is called.  Returns a promise that can be
-      // used to know when the element has been rendered into its parent.
-      render: function() {
-        var context = root.serialize || options.serialize;
-        var template = root.template || options.template;
-
-        // Create a deferred specifically for fetching.
-        def = options.deferred();
-
-        // If data is a function, immediately call it.
-        if (_.isFunction(context)) {
-          context = context.call(root);
-        }
-
-        // Set the internal callback to trigger once the asynchronous or
-        // synchronous behavior has completed.
-        manager.callback = function(contents) {
-          // Clean up asynchronous manager properties.
-          delete manager.isAsync;
-          delete manager.callback;
-
-          done(context, contents);
-        };
-
-        // Set the url to the prefix + the view's template property.
-        if (typeof template === "string") {
-          url = options.prefix + template;
-        }
-
-        // Check if contents are already cached and if they are, simply process
-        // the template with the correct data.
-        if (contents = LayoutManager.cache(url)) {
-          done(context, contents, url);
-
-          return def;
-        }
-
-        // Fetch layout and template contents.
-        if (typeof template === "string") {
-          contents = options.fetchTemplate.call(root, options.prefix +
-            template);
-        // If the template is already a function, simply call it.
-        } else if (typeof template === "function") {
-          contents = template;
-        // If its not a string and not undefined, pass the value to `fetch`.
-        } else if (template != null) {
-          contents = options.fetchTemplate.call(root, template);
-        }
-
-        // If the function was synchronous, continue execution.
-        if (!manager.isAsync) {
-          done(context, contents);
-        }
-
-        return def;
-      }
-    };
-  },
-
-  // Remove all nested Views.
-  _removeViews: function(root, force) {
-    // Shift arguments around.
-    if (typeof root === "boolean") {
-      force = root;
-      root = this;
-    }
-
-    // Allow removeView to be called on instances.
-    root = root || this;
-
-    // Iterate over all of the nested View's and remove.
-    root.getViews().each(function(view) {
-      // Force doesn't care about if a View has rendered or not.
-      if (view.hasRendered || force) {
-        LayoutManager._removeView(view, force);
-      }
-    });
-  },
-
-  // Remove a single nested View.
-  _removeView: function(view, force) {
-    var parentViews;
-    // Shorthand the managers for easier access.
-    var manager = view.__manager__;
-    var rentManager = manager.parent && manager.parent.__manager__;
-    // Test for keep.
-    var keep = typeof view.keep === "boolean" ? view.keep : view.options.keep;
-
-    // In insert mode, remove views that do not have `keep` attribute set,
-    // unless the force flag is set.
-    if ((!keep && rentManager && rentManager.insert === true) || force) {
-      // Clean out the events.
-      LayoutManager.cleanViews(view);
-
-      // Since we are removing this view, force subviews to remove
-      view._removeViews(true);
-
-      // Remove the View completely.
-      view.$el.remove();
-
-      // Bail out early if no parent exists.
-      if (!manager.parent) { return; }
-
-      // Assign (if they exist) the sibling Views to a property.
-      parentViews = manager.parent.views[manager.selector];
-
-      // If this is an array of items remove items that are not marked to
-      // keep.
-      if (_.isArray(parentViews)) {
-        // Remove duplicate Views.
-        return _.each(_.clone(parentViews), function(view, i) {
-          // If the managers match, splice off this View.
-          if (view && view.__manager__ === manager) {
-            aSplice.call(parentViews, i, 1);
-          }
-        });
-      }
-
-      // Otherwise delete the parent selector.
-      delete manager.parent.views[manager.selector];
-    }
-  },
-
-  // Cache templates into LayoutManager._cache.
-  cache: function(path, contents) {
-    // If template path is found in the cache, return the contents.
-    if (path in this._cache && contents == null) {
-      return this._cache[path];
-    // Ensure path and contents aren't undefined.
-    } else if (path != null && contents != null) {
-      return this._cache[path] = contents;
-    }
-
-    // If the template is not in the cache, return undefined.
-  },
-
-  // Accept either a single view or an array of views to clean of all DOM
-  // events internal model and collection references and all Backbone.Events.
-  cleanViews: function(views) {
-    // Clear out all existing views.
-    _.each(aConcat.call([], views), function(view) {
-      var cleanup;
-
-      // Remove all custom events attached to this View.
-      view.unbind();
-
-      // Automatically unbind `model`.
-      if (view.model instanceof Backbone.Model) {
-        view.model.off(null, null, view);
-      }
-
-      // Automatically unbind `collection`.
-      if (view.collection instanceof Backbone.Collection) {
-        view.collection.off(null, null, view);
-      }
-
-      // Automatically unbind events bound to this View.
-      view.stopListening();
-
-      // If a custom cleanup method was provided on the view, call it after
-      // the initial cleanup is done
-      cleanup = view.getAllOptions().cleanup;
-      if (_.isFunction(cleanup)) {
-        cleanup.call(view);
-      }
-    });
-  },
-
-  // This static method allows for global configuration of LayoutManager.
-  configure: function(options) {
-    _.extend(LayoutManager.prototype.options, options);
-
-    // Allow LayoutManager to manage Backbone.View.prototype.
-    if (options.manage) {
-      Backbone.View.prototype.manage = true;
-    }
-
-    // Disable the element globally.
-    if (options.el === false) {
-      Backbone.View.prototype.el = false;
-    }
-
-    // Allow global configuration of `suppressWarnings`.
-    if (options.suppressWarnings === true) {
-      Backbone.View.prototype.suppressWarnings = true;
-    }
-  },
-
-  // Configure a View to work with the LayoutManager plugin.
-  setupView: function(views, options) {
-    // Set up all Views passed.
-    _.each(aConcat.call([], views), function(view) {
-      // If the View has already been setup, no need to do it again.
-      if (view.__manager__) {
-        return;
-      }
-
-      var views, declaredViews, viewOptions;
-      var proto = LayoutManager.prototype;
-      var viewOverrides = _.pick(view, keys);
-
-      // Ensure necessary properties are set.
-      _.defaults(view, {
-        // Ensure a view always has a views object.
-        views: {},
-
-        // Ensure a view always has a sections object.
-        sections: {},
-
-        // Internal state object used to store whether or not a View has been
-        // taken over by layout manager and if it has been rendered into the
-        // DOM.
-        __manager__: {},
-
-        // Add the ability to remove all Views.
-        _removeViews: LayoutManager._removeViews,
-
-        // Add the ability to remove itself.
-        _removeView: LayoutManager._removeView
-
-      // Mix in all LayoutManager prototype properties as well.
-      }, LayoutManager.prototype);
-
-      // Extend the options with the prototype and passed options.
-      options = view.options = _.defaults(options || {}, view.options,
-        proto.options);
-
-      // Ensure view events are properly copied over.
-      viewOptions = _.pick(options, aConcat.call(["events", "sections"],
-        _.values(options.events)));
-
-      // Merge the View options into the View.
-      _.extend(view, viewOptions);
-
-      // Pick out the specific properties that can be dynamically added at
-      // runtime and ensure they are available on the view object.
-      _.extend(options, viewOverrides);
-
-      // By default the original Remove function is the Backbone.View one.
-      view._remove = Backbone.View.prototype.remove;
-
-      // Ensure the render is always set correctly.
-      view.render = LayoutManager.prototype.render;
-
-      // If the user provided their own remove override, use that instead of
-      // the default.
-      if (view.remove !== proto.remove) {
-        view._remove = view.remove;
-        view.remove = proto.remove;
-      }
-
-      // Normalize views to exist on either instance or options, default to
-      // options.
-      views = options.views || view.views;
-
-      // Set the internal views, only if selectors have been provided.
-      if (_.keys(views).length) {
-        // Keep original object declared containing Views.
-        declaredViews = views;
-
-        // Reset the property to avoid duplication or overwritting.
-        view.views = {};
-
-        // Set the declared Views.
-        view.setViews(declaredViews);
-      }
-
-      // If a template is passed use that instead.
-      if (view.options.template) {
-        view.options.template = options.template;
-      // Ensure the template is mapped over.
-      } else if (view.template) {
-        options.template = view.template;
-      }
-    });
-  }
-});
-
-// Tack on the version.
-LayoutManager.VERSION = "0.9.1";
-
-Backbone.Layout = LayoutManager;
-
-// Override _configure to provide extra functionality that is necessary in
-// order for the render function reference to be bound during initialize.
-Backbone.View.prototype._configure = function(options) {
-  var noel, retVal;
-
-  // Remove the container element provided by Backbone.
-  if ("el" in options ? options.el === false : this.el === false) {
-    noel = true;
-  }
-
-  // Run the original _configure.
-  retVal = _configure.apply(this, arguments);
-
-  // If manage is set, do it!
-  if (options.manage || this.manage) {
-    // Set up this View.
-    LayoutManager.setupView(this);
-  }
-
-  // Assign the `noel` property once we're sure the View we're working with is
-  // managed by LayoutManager.
-  if (this.__manager__) {
-    this.__manager__.noel = noel;
-    this.__manager__.suppressWarnings = options.suppressWarnings;
-  }
-
-  // Act like nothing happened.
-  return retVal;
-};
-
-// Default configuration options; designed to be overriden.
-LayoutManager.prototype.options = {
-  // Prefix template/layout paths.
-  prefix: "",
-
-  // Can be used to supply a different deferred implementation.
-  deferred: function() {
-    return $.Deferred();
-  },
-
-  // Fetch is passed a path and is expected to return template contents as a
-  // function or string.
-  fetchTemplate: function(path) {
-    return _.template($(path).html());
-  },
-
-  // By default, render using underscore's templating.
-  renderTemplate: function(template, context) {
-    return template(context);
-  },
-
-  // This is the most common way you will want to partially apply a view into
-  // a layout.
-  partial: function($root, $el, rentManager, manager) {
-    var $filtered;
-
-    // If selector is specified, attempt to find it.
-    if (manager.selector) {
-      if (rentManager.noel) {
-        $filtered = $root.filter(manager.selector);
-        $root = $filtered.length ? $filtered : $root.find(manager.selector);
-      } else {
-        $root = $root.find(manager.selector);
-      }
-    }
-
-    // Use the insert method if the parent's `insert` argument is true.
-    if (rentManager.insert) {
-      this.insert($root, $el);
-    } else {
-      this.html($root, $el);
-    }
-  },
-
-  // Override this with a custom HTML method, passed a root element and content
-  // (a jQuery collection or a string) to replace the innerHTML with.
-  html: function($root, content) {
-    $root.html(content);
-  },
-
-  // Used for inserting subViews in a single batch.  This gives a small
-  // performance boost as we write to a disconnected fragment instead of to the
-  // DOM directly. Smarter browsers like Chrome will batch writes internally
-  // and layout as seldom as possible, but even in that case this provides a
-  // decent boost.  jQuery will use a DocumentFragment for the batch update,
-  // but Cheerio in Node will not.
-  htmlBatch: function(rootView, subViews, selector) {
-    // Shorthand the parent manager object.
-    var rentManager = rootView.__manager__;
-    // Create a simplified manager object that tells partial() where
-    // place the elements.
-    var manager = { selector: selector };
-
-    // Get the elements to be inserted into the root view.
-    var els = _.reduce(subViews, function(memo, sub) {
-      // Check if keep is present - do boolean check in case the user
-      // has created a `keep` function.
-      var keep = typeof sub.keep === "boolean" ? sub.keep : sub.options.keep;
-      // If a subView is present, don't push it.  This can only happen if
-      // `keep: true`.  We do the keep check for speed as $.contains is not
-      // cheap.
-      var exists = keep && $.contains(rootView.el, sub.el);
-
-      // If there is an element and it doesn't already exist in our structure
-      // attach it.
-      if (sub.el && !exists) {
-        memo.push(sub.el);
-      }
-
-      return memo;
-    }, []);
-
-    // Use partial to apply the elements. Wrap els in jQ obj for cheerio.
-    return this.partial(rootView.$el, $(els), rentManager, manager);
-  },
-
-  // Very similar to HTML except this one will appendChild by default.
-  insert: function($root, $el) {
-    $root.append($el);
-  },
-
-  // Return a deferred for when all promises resolve/reject.
-  when: function(promises) {
-    return $.when.apply(null, promises);
-  },
-
-  // A method to determine if a View contains another.
-  contains: function(parent, child) {
-    return $.contains(parent, child);
-  }
-};
-
-// Maintain a list of the keys at define time.
-keys = _.keys(LayoutManager.prototype.options);
-
-// Assign `LayoutManager` object for AMD loaders.
-return LayoutManager;
-
-}));

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/js/plugins/jquery.form.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/js/plugins/jquery.form.js b/apps/fauxton/assets/js/plugins/jquery.form.js
deleted file mode 100644
index e3126ca..0000000
--- a/apps/fauxton/assets/js/plugins/jquery.form.js
+++ /dev/null
@@ -1,1190 +0,0 @@
-/*!
- * jQuery Form Plugin
- * version: 3.35.0-2013.05.23
- * @requires jQuery v1.5 or later
- * Copyright (c) 2013 M. Alsup
- * Examples and documentation at: http://malsup.com/jquery/form/
- * Project repository: https://github.com/malsup/form
- * Dual licensed under the MIT and GPL licenses.
- * https://github.com/malsup/form#copyright-and-license
- */
-/*global ActiveXObject */
-;(function($) {
-"use strict";
-
-/*
-    Usage Note:
-    -----------
-    Do not use both ajaxSubmit and ajaxForm on the same form.  These
-    functions are mutually exclusive.  Use ajaxSubmit if you want
-    to bind your own submit handler to the form.  For example,
-
-    $(document).ready(function() {
-        $('#myForm').on('submit', function(e) {
-            e.preventDefault(); // <-- important
-            $(this).ajaxSubmit({
-                target: '#output'
-            });
-        });
-    });
-
-    Use ajaxForm when you want the plugin to manage all the event binding
-    for you.  For example,
-
-    $(document).ready(function() {
-        $('#myForm').ajaxForm({
-            target: '#output'
-        });
-    });
-
-    You can also use ajaxForm with delegation (requires jQuery v1.7+), so the
-    form does not have to exist when you invoke ajaxForm:
-
-    $('#myForm').ajaxForm({
-        delegation: true,
-        target: '#output'
-    });
-
-    When using ajaxForm, the ajaxSubmit function will be invoked for you
-    at the appropriate time.
-*/
-
-/**
- * Feature detection
- */
-var feature = {};
-feature.fileapi = $("<input type='file'/>").get(0).files !== undefined;
-feature.formdata = window.FormData !== undefined;
-
-var hasProp = !!$.fn.prop;
-
-// attr2 uses prop when it can but checks the return type for
-// an expected string.  this accounts for the case where a form 
-// contains inputs with names like "action" or "method"; in those
-// cases "prop" returns the element
-$.fn.attr2 = function() {
-    if ( ! hasProp )
-        return this.attr.apply(this, arguments);
-    var val = this.prop.apply(this, arguments);
-    if ( ( val && val.jquery ) || typeof val === 'string' )
-        return val;
-    return this.attr.apply(this, arguments);
-};
-
-/**
- * ajaxSubmit() provides a mechanism for immediately submitting
- * an HTML form using AJAX.
- */
-$.fn.ajaxSubmit = function(options) {
-    /*jshint scripturl:true */
-
-    // fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
-    if (!this.length) {
-        log('ajaxSubmit: skipping submit process - no element selected');
-        return this;
-    }
-
-    var method, action, url, $form = this;
-
-    if (typeof options == 'function') {
-        options = { success: options };
-    }
-
-    method = options.type || this.attr2('method');
-    action = options.url  || this.attr2('action');
-
-    url = (typeof action === 'string') ? $.trim(action) : '';
-    url = url || window.location.href || '';
-    if (url) {
-        // clean url (don't include hash vaue)
-        url = (url.match(/^([^#]+)/)||[])[1];
-    }
-
-    options = $.extend(true, {
-        url:  url,
-        success: $.ajaxSettings.success,
-        type: method || 'GET',
-        iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank'
-    }, options);
-
-    // hook for manipulating the form data before it is extracted;
-    // convenient for use with rich editors like tinyMCE or FCKEditor
-    var veto = {};
-    this.trigger('form-pre-serialize', [this, options, veto]);
-    if (veto.veto) {
-        log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
-        return this;
-    }
-
-    // provide opportunity to alter form data before it is serialized
-    if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
-        log('ajaxSubmit: submit aborted via beforeSerialize callback');
-        return this;
-    }
-
-    var traditional = options.traditional;
-    if ( traditional === undefined ) {
-        traditional = $.ajaxSettings.traditional;
-    }
-
-    var elements = [];
-    var qx, a = this.formToArray(options.semantic, elements);
-    if (options.data) {
-        options.extraData = options.data;
-        qx = $.param(options.data, traditional);
-    }
-
-    // give pre-submit callback an opportunity to abort the submit
-    if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
-        log('ajaxSubmit: submit aborted via beforeSubmit callback');
-        return this;
-    }
-
-    // fire vetoable 'validate' event
-    this.trigger('form-submit-validate', [a, this, options, veto]);
-    if (veto.veto) {
-        log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
-        return this;
-    }
-
-    var q = $.param(a, traditional);
-    if (qx) {
-        q = ( q ? (q + '&' + qx) : qx );
-    }
-    if (options.type.toUpperCase() == 'GET') {
-        options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
-        options.data = null;  // data is null for 'get'
-    }
-    else {
-        options.data = q; // data is the query string for 'post'
-    }
-
-    var callbacks = [];
-    if (options.resetForm) {
-        callbacks.push(function() { $form.resetForm(); });
-    }
-    if (options.clearForm) {
-        callbacks.push(function() { $form.clearForm(options.includeHidden); });
-    }
-
-    // perform a load on the target only if dataType is not provided
-    if (!options.dataType && options.target) {
-        var oldSuccess = options.success || function(){};
-        callbacks.push(function(data) {
-            var fn = options.replaceTarget ? 'replaceWith' : 'html';
-            $(options.target)[fn](data).each(oldSuccess, arguments);
-        });
-    }
-    else if (options.success) {
-        callbacks.push(options.success);
-    }
-
-    options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg
-        var context = options.context || this ;    // jQuery 1.4+ supports scope context
-        for (var i=0, max=callbacks.length; i < max; i++) {
-            callbacks[i].apply(context, [data, status, xhr || $form, $form]);
-        }
-    };
-
-    if (options.error) {
-        var oldError = options.error;
-        options.error = function(xhr, status, error) {
-            var context = options.context || this;
-            oldError.apply(context, [xhr, status, error, $form]);
-        };
-    }
-
-     if (options.complete) {
-        var oldComplete = options.complete;
-        options.complete = function(xhr, status) {
-            var context = options.context || this;
-            oldComplete.apply(context, [xhr, status, $form]);
-        };
-    }
-
-    // are there files to upload?
-
-    // [value] (issue #113), also see comment:
-    // https://github.com/malsup/form/commit/588306aedba1de01388032d5f42a60159eea9228#commitcomment-2180219
-    var fileInputs = $('input[type=file]:enabled[value!=""]', this);
-
-    var hasFileInputs = fileInputs.length > 0;
-    var mp = 'multipart/form-data';
-    var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp);
-
-    var fileAPI = feature.fileapi && feature.formdata;
-    log("fileAPI :" + fileAPI);
-    var shouldUseFrame = (hasFileInputs || multipart) && !fileAPI;
-
-    var jqxhr;
-
-    // options.iframe allows user to force iframe mode
-    // 06-NOV-09: now defaulting to iframe mode if file input is detected
-    if (options.iframe !== false && (options.iframe || shouldUseFrame)) {
-        // hack to fix Safari hang (thanks to Tim Molendijk for this)
-        // see:  http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
-        if (options.closeKeepAlive) {
-            $.get(options.closeKeepAlive, function() {
-                jqxhr = fileUploadIframe(a);
-            });
-        }
-        else {
-            jqxhr = fileUploadIframe(a);
-        }
-    }
-    else if ((hasFileInputs || multipart) && fileAPI) {
-        jqxhr = fileUploadXhr(a);
-    }
-    else {
-        jqxhr = $.ajax(options);
-    }
-
-    $form.removeData('jqxhr').data('jqxhr', jqxhr);
-
-    // clear element array
-    for (var k=0; k < elements.length; k++)
-        elements[k] = null;
-
-    // fire 'notify' event
-    this.trigger('form-submit-notify', [this, options]);
-    return this;
-
-    // utility fn for deep serialization
-    function deepSerialize(extraData){
-        var serialized = $.param(extraData, options.traditional).split('&');
-        var len = serialized.length;
-        var result = [];
-        var i, part;
-        for (i=0; i < len; i++) {
-            // #252; undo param space replacement
-            serialized[i] = serialized[i].replace(/\+/g,' ');
-            part = serialized[i].split('=');
-            // #278; use array instead of object storage, favoring array serializations
-            result.push([decodeURIComponent(part[0]), decodeURIComponent(part[1])]);
-        }
-        return result;
-    }
-
-     // XMLHttpRequest Level 2 file uploads (big hat tip to francois2metz)
-    function fileUploadXhr(a) {
-        var formdata = new FormData();
-
-        for (var i=0; i < a.length; i++) {
-            formdata.append(a[i].name, a[i].value);
-        }
-
-        if (options.extraData) {
-            var serializedData = deepSerialize(options.extraData);
-            for (i=0; i < serializedData.length; i++)
-                if (serializedData[i])
-                    formdata.append(serializedData[i][0], serializedData[i][1]);
-        }
-
-        options.data = null;
-
-        var s = $.extend(true, {}, $.ajaxSettings, options, {
-            contentType: false,
-            processData: false,
-            cache: false,
-            type: method || 'POST'
-        });
-
-        if (options.uploadProgress) {
-            // workaround because jqXHR does not expose upload property
-            s.xhr = function() {
-                var xhr = jQuery.ajaxSettings.xhr();
-                if (xhr.upload) {
-                    xhr.upload.addEventListener('progress', function(event) {
-                        var percent = 0;
-                        var position = event.loaded || event.position; /*event.position is deprecated*/
-                        var total = event.total;
-                        if (event.lengthComputable) {
-                            percent = Math.ceil(position / total * 100);
-                        }
-                        options.uploadProgress(event, position, total, percent);
-                    }, false);
-                }
-                return xhr;
-            };
-        }
-
-        s.data = null;
-            var beforeSend = s.beforeSend;
-            s.beforeSend = function(xhr, o) {
-                o.data = formdata;
-                if(beforeSend)
-                    beforeSend.call(this, xhr, o);
-        };
-        return $.ajax(s);
-    }
-
-    // private function for handling file uploads (hat tip to YAHOO!)
-    function fileUploadIframe(a) {
-        var form = $form[0], el, i, s, g, id, $io, io, xhr, sub, n, timedOut, timeoutHandle;
-        var deferred = $.Deferred();
-
-        if (a) {
-            // ensure that every serialized input is still enabled
-            for (i=0; i < elements.length; i++) {
-                el = $(elements[i]);
-                if ( hasProp )
-                    el.prop('disabled', false);
-                else
-                    el.removeAttr('disabled');
-            }
-        }
-
-        s = $.extend(true, {}, $.ajaxSettings, options);
-        s.context = s.context || s;
-        id = 'jqFormIO' + (new Date().getTime());
-        if (s.iframeTarget) {
-            $io = $(s.iframeTarget);
-            n = $io.attr2('name');
-            if (!n)
-                 $io.attr2('name', id);
-            else
-                id = n;
-        }
-        else {
-            $io = $('<iframe name="' + id + '" src="'+ s.iframeSrc +'" />');
-            $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
-        }
-        io = $io[0];
-
-
-        xhr = { // mock object
-            aborted: 0,
-            responseText: null,
-            responseXML: null,
-            status: 0,
-            statusText: 'n/a',
-            getAllResponseHeaders: function() {},
-            getResponseHeader: function() {},
-            setRequestHeader: function() {},
-            abort: function(status) {
-                var e = (status === 'timeout' ? 'timeout' : 'aborted');
-                log('aborting upload... ' + e);
-                this.aborted = 1;
-
-                try { // #214, #257
-                    if (io.contentWindow.document.execCommand) {
-                        io.contentWindow.document.execCommand('Stop');
-                    }
-                }
-                catch(ignore) {}
-
-                $io.attr('src', s.iframeSrc); // abort op in progress
-                xhr.error = e;
-                if (s.error)
-                    s.error.call(s.context, xhr, e, status);
-                if (g)
-                    $.event.trigger("ajaxError", [xhr, s, e]);
-                if (s.complete)
-                    s.complete.call(s.context, xhr, e);
-            }
-        };
-
-        g = s.global;
-        // trigger ajax global events so that activity/block indicators work like normal
-        if (g && 0 === $.active++) {
-            $.event.trigger("ajaxStart");
-        }
-        if (g) {
-            $.event.trigger("ajaxSend", [xhr, s]);
-        }
-
-        if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) {
-            if (s.global) {
-                $.active--;
-            }
-            deferred.reject();
-            return deferred;
-        }
-        if (xhr.aborted) {
-            deferred.reject();
-            return deferred;
-        }
-
-        // add submitting element to data if we know it
-        sub = form.clk;
-        if (sub) {
-            n = sub.name;
-            if (n && !sub.disabled) {
-                s.extraData = s.extraData || {};
-                s.extraData[n] = sub.value;
-                if (sub.type == "image") {
-                    s.extraData[n+'.x'] = form.clk_x;
-                    s.extraData[n+'.y'] = form.clk_y;
-                }
-            }
-        }
-
-        var CLIENT_TIMEOUT_ABORT = 1;
-        var SERVER_ABORT = 2;
-                
-        function getDoc(frame) {
-            /* it looks like contentWindow or contentDocument do not
-             * carry the protocol property in ie8, when running under ssl
-             * frame.document is the only valid response document, since
-             * the protocol is know but not on the other two objects. strange?
-             * "Same origin policy" http://en.wikipedia.org/wiki/Same_origin_policy
-             */
-            
-            var doc = null;
-            
-            // IE8 cascading access check
-            try {
-                if (frame.contentWindow) {
-                    doc = frame.contentWindow.document;
-                }
-            } catch(err) {
-                // IE8 access denied under ssl & missing protocol
-                log('cannot get iframe.contentWindow document: ' + err);
-            }
-
-            if (doc) { // successful getting content
-                return doc;
-            }
-
-            try { // simply checking may throw in ie8 under ssl or mismatched protocol
-                doc = frame.contentDocument ? frame.contentDocument : frame.document;
-            } catch(err) {
-                // last attempt
-                log('cannot get iframe.contentDocument: ' + err);
-                doc = frame.document;
-            }
-            return doc;
-        }
-
-        // Rails CSRF hack (thanks to Yvan Barthelemy)
-        var csrf_token = $('meta[name=csrf-token]').attr('content');
-        var csrf_param = $('meta[name=csrf-param]').attr('content');
-        if (csrf_param && csrf_token) {
-            s.extraData = s.extraData || {};
-            s.extraData[csrf_param] = csrf_token;
-        }
-
-        // take a breath so that pending repaints get some cpu time before the upload starts
-        function doSubmit() {
-            // make sure form attrs are set
-            var t = $form.attr2('target'), a = $form.attr2('action');
-
-            // update form attrs in IE friendly way
-            form.setAttribute('target',id);
-            if (!method) {
-                form.setAttribute('method', 'POST');
-            }
-            if (a != s.url) {
-                form.setAttribute('action', s.url);
-            }
-
-            // ie borks in some cases when setting encoding
-            if (! s.skipEncodingOverride && (!method || /post/i.test(method))) {
-                $form.attr({
-                    encoding: 'multipart/form-data',
-                    enctype:  'multipart/form-data'
-                });
-            }
-
-            // support timout
-            if (s.timeout) {
-                timeoutHandle = setTimeout(function() { timedOut = true; cb(CLIENT_TIMEOUT_ABORT); }, s.timeout);
-            }
-
-            // look for server aborts
-            function checkState() {
-                try {
-                    var state = getDoc(io).readyState;
-                    log('state = ' + state);
-                    if (state && state.toLowerCase() == 'uninitialized')
-                        setTimeout(checkState,50);
-                }
-                catch(e) {
-                    log('Server abort: ' , e, ' (', e.name, ')');
-                    cb(SERVER_ABORT);
-                    if (timeoutHandle)
-                        clearTimeout(timeoutHandle);
-                    timeoutHandle = undefined;
-                }
-            }
-
-            // add "extra" data to form if provided in options
-            var extraInputs = [];
-            try {
-                if (s.extraData) {
-                    for (var n in s.extraData) {
-                        if (s.extraData.hasOwnProperty(n)) {
-                           // if using the $.param format that allows for multiple values with the same name
-                           if($.isPlainObject(s.extraData[n]) && s.extraData[n].hasOwnProperty('name') && s.extraData[n].hasOwnProperty('value')) {
-                               extraInputs.push(
-                               $('<input type="hidden" name="'+s.extraData[n].name+'">').val(s.extraData[n].value)
-                                   .appendTo(form)[0]);
-                           } else {
-                               extraInputs.push(
-                               $('<input type="hidden" name="'+n+'">').val(s.extraData[n])
-                                   .appendTo(form)[0]);
-                           }
-                        }
-                    }
-                }
-
-                if (!s.iframeTarget) {
-                    // add iframe to doc and submit the form
-                    $io.appendTo('body');
-                    if (io.attachEvent)
-                        io.attachEvent('onload', cb);
-                    else
-                        io.addEventListener('load', cb, false);
-                }
-                setTimeout(checkState,15);
-
-                try {
-                    form.submit();
-                } catch(err) {
-                    // just in case form has element with name/id of 'submit'
-                    var submitFn = document.createElement('form').submit;
-                    submitFn.apply(form);
-                }
-            }
-            finally {
-                // reset attrs and remove "extra" input elements
-                form.setAttribute('action',a);
-                if(t) {
-                    form.setAttribute('target', t);
-                } else {
-                    $form.removeAttr('target');
-                }
-                $(extraInputs).remove();
-            }
-        }
-
-        if (s.forceSync) {
-            doSubmit();
-        }
-        else {
-            setTimeout(doSubmit, 10); // this lets dom updates render
-        }
-
-        var data, doc, domCheckCount = 50, callbackProcessed;
-
-        function cb(e) {
-            if (xhr.aborted || callbackProcessed) {
-                return;
-            }
-            
-            doc = getDoc(io);
-            if(!doc) {
-                log('cannot access response document');
-                e = SERVER_ABORT;
-            }
-            if (e === CLIENT_TIMEOUT_ABORT && xhr) {
-                xhr.abort('timeout');
-                deferred.reject(xhr, 'timeout');
-                return;
-            }
-            else if (e == SERVER_ABORT && xhr) {
-                xhr.abort('server abort');
-                deferred.reject(xhr, 'error', 'server abort');
-                return;
-            }
-
-            if (!doc || doc.location.href == s.iframeSrc) {
-                // response not received yet
-                if (!timedOut)
-                    return;
-            }
-            if (io.detachEvent)
-                io.detachEvent('onload', cb);
-            else
-                io.removeEventListener('load', cb, false);
-
-            var status = 'success', errMsg;
-            try {
-                if (timedOut) {
-                    throw 'timeout';
-                }
-
-                var isXml = s.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc);
-                log('isXml='+isXml);
-                if (!isXml && window.opera && (doc.body === null || !doc.body.innerHTML)) {
-                    if (--domCheckCount) {
-                        // in some browsers (Opera) the iframe DOM is not always traversable when
-                        // the onload callback fires, so we loop a bit to accommodate
-                        log('requeing onLoad callback, DOM not available');
-                        setTimeout(cb, 250);
-                        return;
-                    }
-                    // let this fall through because server response could be an empty document
-                    //log('Could not access iframe DOM after mutiple tries.');
-                    //throw 'DOMException: not available';
-                }
-
-                //log('response detected');
-                var docRoot = doc.body ? doc.body : doc.documentElement;
-                xhr.responseText = docRoot ? docRoot.innerHTML : null;
-                xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
-                if (isXml)
-                    s.dataType = 'xml';
-                xhr.getResponseHeader = function(header){
-                    var headers = {'content-type': s.dataType};
-                    return headers[header];
-                };
-                // support for XHR 'status' & 'statusText' emulation :
-                if (docRoot) {
-                    xhr.status = Number( docRoot.getAttribute('status') ) || xhr.status;
-                    xhr.statusText = docRoot.getAttribute('statusText') || xhr.statusText;
-                }
-
-                var dt = (s.dataType || '').toLowerCase();
-                var scr = /(json|script|text)/.test(dt);
-                if (scr || s.textarea) {
-                    // see if user embedded response in textarea
-                    var ta = doc.getElementsByTagName('textarea')[0];
-                    if (ta) {
-                        xhr.responseText = ta.value;
-                        // support for XHR 'status' & 'statusText' emulation :
-                        xhr.status = Number( ta.getAttribute('status') ) || xhr.status;
-                        xhr.statusText = ta.getAttribute('statusText') || xhr.statusText;
-                    }
-                    else if (scr) {
-                        // account for browsers injecting pre around json response
-                        var pre = doc.getElementsByTagName('pre')[0];
-                        var b = doc.getElementsByTagName('body')[0];
-                        if (pre) {
-                            xhr.responseText = pre.textContent ? pre.textContent : pre.innerText;
-                        }
-                        else if (b) {
-                            xhr.responseText = b.textContent ? b.textContent : b.innerText;
-                        }
-                    }
-                }
-                else if (dt == 'xml' && !xhr.responseXML && xhr.responseText) {
-                    xhr.responseXML = toXml(xhr.responseText);
-                }
-
-                try {
-                    data = httpData(xhr, dt, s);
-                }
-                catch (err) {
-                    status = 'parsererror';
-                    xhr.error = errMsg = (err || status);
-                }
-            }
-            catch (err) {
-                log('error caught: ',err);
-                status = 'error';
-                xhr.error = errMsg = (err || status);
-            }
-
-            if (xhr.aborted) {
-                log('upload aborted');
-                status = null;
-            }
-
-            if (xhr.status) { // we've set xhr.status
-                status = (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) ? 'success' : 'error';
-            }
-
-            // ordering of these callbacks/triggers is odd, but that's how $.ajax does it
-            if (status === 'success') {
-                if (s.success)
-                    s.success.call(s.context, data, 'success', xhr);
-                deferred.resolve(xhr.responseText, 'success', xhr);
-                if (g)
-                    $.event.trigger("ajaxSuccess", [xhr, s]);
-            }
-            else if (status) {
-                if (errMsg === undefined)
-                    errMsg = xhr.statusText;
-                if (s.error)
-                    s.error.call(s.context, xhr, status, errMsg);
-                deferred.reject(xhr, 'error', errMsg);
-                if (g)
-                    $.event.trigger("ajaxError", [xhr, s, errMsg]);
-            }
-
-            if (g)
-                $.event.trigger("ajaxComplete", [xhr, s]);
-
-            if (g && ! --$.active) {
-                $.event.trigger("ajaxStop");
-            }
-
-            if (s.complete)
-                s.complete.call(s.context, xhr, status);
-
-            callbackProcessed = true;
-            if (s.timeout)
-                clearTimeout(timeoutHandle);
-
-            // clean up
-            setTimeout(function() {
-                if (!s.iframeTarget)
-                    $io.remove();
-                xhr.responseXML = null;
-            }, 100);
-        }
-
-        var toXml = $.parseXML || function(s, doc) { // use parseXML if available (jQuery 1.5+)
-            if (window.ActiveXObject) {
-                doc = new ActiveXObject('Microsoft.XMLDOM');
-                doc.async = 'false';
-                doc.loadXML(s);
-            }
-            else {
-                doc = (new DOMParser()).parseFromString(s, 'text/xml');
-            }
-            return (doc && doc.documentElement && doc.documentElement.nodeName != 'parsererror') ? doc : null;
-        };
-        var parseJSON = $.parseJSON || function(s) {
-            /*jslint evil:true */
-            return window['eval']('(' + s + ')');
-        };
-
-        var httpData = function( xhr, type, s ) { // mostly lifted from jq1.4.4
-
-            var ct = xhr.getResponseHeader('content-type') || '',
-                xml = type === 'xml' || !type && ct.indexOf('xml') >= 0,
-                data = xml ? xhr.responseXML : xhr.responseText;
-
-            if (xml && data.documentElement.nodeName === 'parsererror') {
-                if ($.error)
-                    $.error('parsererror');
-            }
-            if (s && s.dataFilter) {
-                data = s.dataFilter(data, type);
-            }
-            if (typeof data === 'string') {
-                if (type === 'json' || !type && ct.indexOf('json') >= 0) {
-                    data = parseJSON(data);
-                } else if (type === "script" || !type && ct.indexOf("javascript") >= 0) {
-                    $.globalEval(data);
-                }
-            }
-            return data;
-        };
-
-        return deferred;
-    }
-};
-
-/**
- * ajaxForm() provides a mechanism for fully automating form submission.
- *
- * The advantages of using this method instead of ajaxSubmit() are:
- *
- * 1: This method will include coordinates for <input type="image" /> elements (if the element
- *    is used to submit the form).
- * 2. This method will include the submit element's name/value data (for the element that was
- *    used to submit the form).
- * 3. This method binds the submit() method to the form for you.
- *
- * The options argument for ajaxForm works exactly as it does for ajaxSubmit.  ajaxForm merely
- * passes the options argument along after properly binding events for submit elements and
- * the form itself.
- */
-$.fn.ajaxForm = function(options) {
-    options = options || {};
-    options.delegation = options.delegation && $.isFunction($.fn.on);
-
-    // in jQuery 1.3+ we can fix mistakes with the ready state
-    if (!options.delegation && this.length === 0) {
-        var o = { s: this.selector, c: this.context };
-        if (!$.isReady && o.s) {
-            log('DOM not ready, queuing ajaxForm');
-            $(function() {
-                $(o.s,o.c).ajaxForm(options);
-            });
-            return this;
-        }
-        // is your DOM ready?  http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
-        log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)'));
-        return this;
-    }
-
-    if ( options.delegation ) {
-        $(document)
-            .off('submit.form-plugin', this.selector, doAjaxSubmit)
-            .off('click.form-plugin', this.selector, captureSubmittingElement)
-            .on('submit.form-plugin', this.selector, options, doAjaxSubmit)
-            .on('click.form-plugin', this.selector, options, captureSubmittingElement);
-        return this;
-    }
-
-    return this.ajaxFormUnbind()
-        .bind('submit.form-plugin', options, doAjaxSubmit)
-        .bind('click.form-plugin', options, captureSubmittingElement);
-};
-
-// private event handlers
-function doAjaxSubmit(e) {
-    /*jshint validthis:true */
-    var options = e.data;
-    if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed
-        e.preventDefault();
-        $(this).ajaxSubmit(options);
-    }
-}
-
-function captureSubmittingElement(e) {
-    /*jshint validthis:true */
-    var target = e.target;
-    var $el = $(target);
-    if (!($el.is("[type=submit],[type=image]"))) {
-        // is this a child element of the submit el?  (ex: a span within a button)
-        var t = $el.closest('[type=submit]');
-        if (t.length === 0) {
-            return;
-        }
-        target = t[0];
-    }
-    var form = this;
-    form.clk = target;
-    if (target.type == 'image') {
-        if (e.offsetX !== undefined) {
-            form.clk_x = e.offsetX;
-            form.clk_y = e.offsetY;
-        } else if (typeof $.fn.offset == 'function') {
-            var offset = $el.offset();
-            form.clk_x = e.pageX - offset.left;
-            form.clk_y = e.pageY - offset.top;
-        } else {
-            form.clk_x = e.pageX - target.offsetLeft;
-            form.clk_y = e.pageY - target.offsetTop;
-        }
-    }
-    // clear form vars
-    setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100);
-}
-
-
-// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
-$.fn.ajaxFormUnbind = function() {
-    return this.unbind('submit.form-plugin click.form-plugin');
-};
-
-/**
- * formToArray() gathers form element data into an array of objects that can
- * be passed to any of the following ajax functions: $.get, $.post, or load.
- * Each object in the array has both a 'name' and 'value' property.  An example of
- * an array for a simple login form might be:
- *
- * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
- *
- * It is this array that is passed to pre-submit callback functions provided to the
- * ajaxSubmit() and ajaxForm() methods.
- */
-$.fn.formToArray = function(semantic, elements) {
-    var a = [];
-    if (this.length === 0) {
-        return a;
-    }
-
-    var form = this[0];
-    var els = semantic ? form.getElementsByTagName('*') : form.elements;
-    if (!els) {
-        return a;
-    }
-
-    var i,j,n,v,el,max,jmax;
-    for(i=0, max=els.length; i < max; i++) {
-        el = els[i];
-        n = el.name;
-        if (!n || el.disabled) {
-            continue;
-        }
-
-        if (semantic && form.clk && el.type == "image") {
-            // handle image inputs on the fly when semantic == true
-            if(form.clk == el) {
-                a.push({name: n, value: $(el).val(), type: el.type });
-                a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
-            }
-            continue;
-        }
-
-        v = $.fieldValue(el, true);
-        if (v && v.constructor == Array) {
-            if (elements)
-                elements.push(el);
-            for(j=0, jmax=v.length; j < jmax; j++) {
-                a.push({name: n, value: v[j]});
-            }
-        }
-        else if (feature.fileapi && el.type == 'file') {
-            if (elements)
-                elements.push(el);
-            var files = el.files;
-            if (files.length) {
-                for (j=0; j < files.length; j++) {
-                    a.push({name: n, value: files[j], type: el.type});
-                }
-            }
-            else {
-                // #180
-                a.push({ name: n, value: '', type: el.type });
-            }
-        }
-        else if (v !== null && typeof v != 'undefined') {
-            if (elements)
-                elements.push(el);
-            a.push({name: n, value: v, type: el.type, required: el.required});
-        }
-    }
-
-    if (!semantic && form.clk) {
-        // input type=='image' are not found in elements array! handle it here
-        var $input = $(form.clk), input = $input[0];
-        n = input.name;
-        if (n && !input.disabled && input.type == 'image') {
-            a.push({name: n, value: $input.val()});
-            a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
-        }
-    }
-    return a;
-};
-
-/**
- * Serializes form data into a 'submittable' string. This method will return a string
- * in the format: name1=value1&amp;name2=value2
- */
-$.fn.formSerialize = function(semantic) {
-    //hand off to jQuery.param for proper encoding
-    return $.param(this.formToArray(semantic));
-};
-
-/**
- * Serializes all field elements in the jQuery object into a query string.
- * This method will return a string in the format: name1=value1&amp;name2=value2
- */
-$.fn.fieldSerialize = function(successful) {
-    var a = [];
-    this.each(function() {
-        var n = this.name;
-        if (!n) {
-            return;
-        }
-        var v = $.fieldValue(this, successful);
-        if (v && v.constructor == Array) {
-            for (var i=0,max=v.length; i < max; i++) {
-                a.push({name: n, value: v[i]});
-            }
-        }
-        else if (v !== null && typeof v != 'undefined') {
-            a.push({name: this.name, value: v});
-        }
-    });
-    //hand off to jQuery.param for proper encoding
-    return $.param(a);
-};
-
-/**
- * Returns the value(s) of the element in the matched set.  For example, consider the following form:
- *
- *  <form><fieldset>
- *      <input name="A" type="text" />
- *      <input name="A" type="text" />
- *      <input name="B" type="checkbox" value="B1" />
- *      <input name="B" type="checkbox" value="B2"/>
- *      <input name="C" type="radio" value="C1" />
- *      <input name="C" type="radio" value="C2" />
- *  </fieldset></form>
- *
- *  var v = $('input[type=text]').fieldValue();
- *  // if no values are entered into the text inputs
- *  v == ['','']
- *  // if values entered into the text inputs are 'foo' and 'bar'
- *  v == ['foo','bar']
- *
- *  var v = $('input[type=checkbox]').fieldValue();
- *  // if neither checkbox is checked
- *  v === undefined
- *  // if both checkboxes are checked
- *  v == ['B1', 'B2']
- *
- *  var v = $('input[type=radio]').fieldValue();
- *  // if neither radio is checked
- *  v === undefined
- *  // if first radio is checked
- *  v == ['C1']
- *
- * The successful argument controls whether or not the field element must be 'successful'
- * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
- * The default value of the successful argument is true.  If this value is false the value(s)
- * for each element is returned.
- *
- * Note: This method *always* returns an array.  If no valid value can be determined the
- *    array will be empty, otherwise it will contain one or more values.
- */
-$.fn.fieldValue = function(successful) {
-    for (var val=[], i=0, max=this.length; i < max; i++) {
-        var el = this[i];
-        var v = $.fieldValue(el, successful);
-        if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) {
-            continue;
-        }
-        if (v.constructor == Array)
-            $.merge(val, v);
-        else
-            val.push(v);
-    }
-    return val;
-};
-
-/**
- * Returns the value of the field element.
- */
-$.fieldValue = function(el, successful) {
-    var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
-    if (successful === undefined) {
-        successful = true;
-    }
-
-    if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
-        (t == 'checkbox' || t == 'radio') && !el.checked ||
-        (t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
-        tag == 'select' && el.selectedIndex == -1)) {
-            return null;
-    }
-
-    if (tag == 'select') {
-        var index = el.selectedIndex;
-        if (index < 0) {
-            return null;
-        }
-        var a = [], ops = el.options;
-        var one = (t == 'select-one');
-        var max = (one ? index+1 : ops.length);
-        for(var i=(one ? index : 0); i < max; i++) {
-            var op = ops[i];
-            if (op.selected) {
-                var v = op.value;
-                if (!v) { // extra pain for IE...
-                    v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value;
-                }
-                if (one) {
-                    return v;
-                }
-                a.push(v);
-            }
-        }
-        return a;
-    }
-    return $(el).val();
-};
-
-/**
- * Clears the form data.  Takes the following actions on the form's input fields:
- *  - input text fields will have their 'value' property set to the empty string
- *  - select elements will have their 'selectedIndex' property set to -1
- *  - checkbox and radio inputs will have their 'checked' property set to false
- *  - inputs of type submit, button, reset, and hidden will *not* be effected
- *  - button elements will *not* be effected
- */
-$.fn.clearForm = function(includeHidden) {
-    return this.each(function() {
-        $('input,select,textarea', this).clearFields(includeHidden);
-    });
-};
-
-/**
- * Clears the selected form elements.
- */
-$.fn.clearFields = $.fn.clearInputs = function(includeHidden) {
-    var re = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list
-    return this.each(function() {
-        var t = this.type, tag = this.tagName.toLowerCase();
-        if (re.test(t) || tag == 'textarea') {
-            this.value = '';
-        }
-        else if (t == 'checkbox' || t == 'radio') {
-            this.checked = false;
-        }
-        else if (tag == 'select') {
-            this.selectedIndex = -1;
-        }
-		else if (t == "file") {
-			if (/MSIE/.test(navigator.userAgent)) {
-				$(this).replaceWith($(this).clone(true));
-			} else {
-				$(this).val('');
-			}
-		}
-        else if (includeHidden) {
-            // includeHidden can be the value true, or it can be a selector string
-            // indicating a special test; for example:
-            //  $('#myForm').clearForm('.special:hidden')
-            // the above would clean hidden inputs that have the class of 'special'
-            if ( (includeHidden === true && /hidden/.test(t)) ||
-                 (typeof includeHidden == 'string' && $(this).is(includeHidden)) )
-                this.value = '';
-        }
-    });
-};
-
-/**
- * Resets the form data.  Causes all form elements to be reset to their original value.
- */
-$.fn.resetForm = function() {
-    return this.each(function() {
-        // guard against an input with the name of 'reset'
-        // note that IE reports the reset function as an 'object'
-        if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) {
-            this.reset();
-        }
-    });
-};
-
-/**
- * Enables or disables any matching elements.
- */
-$.fn.enable = function(b) {
-    if (b === undefined) {
-        b = true;
-    }
-    return this.each(function() {
-        this.disabled = !b;
-    });
-};
-
-/**
- * Checks/unchecks any matching checkboxes or radio buttons and
- * selects/deselects and matching option elements.
- */
-$.fn.selected = function(select) {
-    if (select === undefined) {
-        select = true;
-    }
-    return this.each(function() {
-        var t = this.type;
-        if (t == 'checkbox' || t == 'radio') {
-            this.checked = select;
-        }
-        else if (this.tagName.toLowerCase() == 'option') {
-            var $sel = $(this).parent('select');
-            if (select && $sel[0] && $sel[0].type == 'select-one') {
-                // deselect all other options
-                $sel.find('option').selected(false);
-            }
-            this.selected = select;
-        }
-    });
-};
-
-// expose debug var
-$.fn.ajaxSubmit.debug = false;
-
-// helper fn for console logging
-function log() {
-    if (!$.fn.ajaxSubmit.debug)
-        return;
-    var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,'');
-    if (window.console && window.console.log) {
-        window.console.log(msg);
-    }
-    else if (window.opera && window.opera.postError) {
-        window.opera.postError(msg);
-    }
-}
-
-})(jQuery);


[47/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_db_updater.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_db_updater.erl b/apps/couch/src/couch_db_updater.erl
deleted file mode 100644
index af7578e..0000000
--- a/apps/couch/src/couch_db_updater.erl
+++ /dev/null
@@ -1,1035 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_db_updater).
--behaviour(gen_server).
-
--export([btree_by_id_reduce/2,btree_by_seq_reduce/2]).
--export([make_doc_summary/2]).
--export([init/1,terminate/2,handle_call/3,handle_cast/2,code_change/3,handle_info/2]).
-
--include("couch_db.hrl").
-
-
-init({MainPid, DbName, Filepath, Fd, Options}) ->
-    process_flag(trap_exit, true),
-    case lists:member(create, Options) of
-    true ->
-        % create a new header and writes it to the file
-        Header =  #db_header{},
-        ok = couch_file:write_header(Fd, Header),
-        % delete any old compaction files that might be hanging around
-        RootDir = couch_config:get("couchdb", "database_dir", "."),
-        couch_file:delete(RootDir, Filepath ++ ".compact");
-    false ->
-        case couch_file:read_header(Fd) of
-        {ok, Header} ->
-            ok;
-        no_valid_header ->
-            % create a new header and writes it to the file
-            Header =  #db_header{},
-            ok = couch_file:write_header(Fd, Header),
-            % delete any old compaction files that might be hanging around
-            file:delete(Filepath ++ ".compact")
-        end
-    end,
-    ReaderFd = open_reader_fd(Filepath, Options),
-    Db = init_db(DbName, Filepath, Fd, ReaderFd, Header, Options),
-    Db2 = refresh_validate_doc_funs(Db),
-    {ok, Db2#db{main_pid = MainPid}}.
-
-
-terminate(_Reason, Db) ->
-    ok = couch_file:close(Db#db.updater_fd),
-    ok = couch_file:close(Db#db.fd),
-    couch_util:shutdown_sync(Db#db.compactor_pid),
-    couch_util:shutdown_sync(Db#db.fd_ref_counter),
-    ok.
-
-handle_call(get_db, _From, Db) ->
-    {reply, {ok, Db}, Db};
-handle_call(full_commit, _From, #db{waiting_delayed_commit=nil}=Db) ->
-    {reply, ok, Db}; % no data waiting, return ok immediately
-handle_call(full_commit, _From,  Db) ->
-    {reply, ok, commit_data(Db)}; % commit the data and return ok
-handle_call(increment_update_seq, _From, Db) ->
-    Db2 = commit_data(Db#db{update_seq=Db#db.update_seq+1}),
-    ok = gen_server:call(Db2#db.main_pid, {db_updated, Db2}),
-    couch_db_update_notifier:notify({updated, Db#db.name}),
-    {reply, {ok, Db2#db.update_seq}, Db2};
-
-handle_call({set_security, NewSec}, _From, #db{compression = Comp} = Db) ->
-    {ok, Ptr, _} = couch_file:append_term(
-        Db#db.updater_fd, NewSec, [{compression, Comp}]),
-    Db2 = commit_data(Db#db{security=NewSec, security_ptr=Ptr,
-            update_seq=Db#db.update_seq+1}),
-    ok = gen_server:call(Db2#db.main_pid, {db_updated, Db2}),
-    {reply, ok, Db2};
-
-handle_call({set_revs_limit, Limit}, _From, Db) ->
-    Db2 = commit_data(Db#db{revs_limit=Limit,
-            update_seq=Db#db.update_seq+1}),
-    ok = gen_server:call(Db2#db.main_pid, {db_updated, Db2}),
-    {reply, ok, Db2};
-
-handle_call({purge_docs, _IdRevs}, _From,
-        #db{compactor_pid=Pid}=Db) when Pid /= nil ->
-    {reply, {error, purge_during_compaction}, Db};
-handle_call({purge_docs, IdRevs}, _From, Db) ->
-    #db{
-        updater_fd = Fd,
-        fulldocinfo_by_id_btree = DocInfoByIdBTree,
-        docinfo_by_seq_btree = DocInfoBySeqBTree,
-        update_seq = LastSeq,
-        header = Header = #db_header{purge_seq=PurgeSeq},
-        compression = Comp
-        } = Db,
-    DocLookups = couch_btree:lookup(DocInfoByIdBTree,
-            [Id || {Id, _Revs} <- IdRevs]),
-
-    NewDocInfos = lists:zipwith(
-        fun({_Id, Revs}, {ok, #full_doc_info{rev_tree=Tree}=FullDocInfo}) ->
-            case couch_key_tree:remove_leafs(Tree, Revs) of
-            {_, []=_RemovedRevs} -> % no change
-                nil;
-            {NewTree, RemovedRevs} ->
-                {FullDocInfo#full_doc_info{rev_tree=NewTree},RemovedRevs}
-            end;
-        (_, not_found) ->
-            nil
-        end,
-        IdRevs, DocLookups),
-
-    SeqsToRemove = [Seq
-            || {#full_doc_info{update_seq=Seq},_} <- NewDocInfos],
-
-    FullDocInfoToUpdate = [FullInfo
-            || {#full_doc_info{rev_tree=Tree}=FullInfo,_}
-            <- NewDocInfos, Tree /= []],
-
-    IdRevsPurged = [{Id, Revs}
-            || {#full_doc_info{id=Id}, Revs} <- NewDocInfos],
-
-    {DocInfoToUpdate, NewSeq} = lists:mapfoldl(
-        fun(#full_doc_info{rev_tree=Tree}=FullInfo, SeqAcc) ->
-            Tree2 = couch_key_tree:map_leafs(
-                fun(_RevId, LeafVal) ->
-                    IsDeleted = element(1, LeafVal),
-                    BodyPointer = element(2, LeafVal),
-                    {IsDeleted, BodyPointer, SeqAcc + 1}
-                end, Tree),
-            {couch_doc:to_doc_info(FullInfo#full_doc_info{rev_tree=Tree2}),
-                SeqAcc + 1}
-        end, LastSeq, FullDocInfoToUpdate),
-
-    IdsToRemove = [Id || {#full_doc_info{id=Id,rev_tree=[]},_}
-            <- NewDocInfos],
-
-    {ok, DocInfoBySeqBTree2} = couch_btree:add_remove(DocInfoBySeqBTree,
-            DocInfoToUpdate, SeqsToRemove),
-    {ok, DocInfoByIdBTree2} = couch_btree:add_remove(DocInfoByIdBTree,
-            FullDocInfoToUpdate, IdsToRemove),
-    {ok, Pointer, _} = couch_file:append_term(
-            Fd, IdRevsPurged, [{compression, Comp}]),
-
-    Db2 = commit_data(
-        Db#db{
-            fulldocinfo_by_id_btree = DocInfoByIdBTree2,
-            docinfo_by_seq_btree = DocInfoBySeqBTree2,
-            update_seq = NewSeq + 1,
-            header=Header#db_header{purge_seq=PurgeSeq+1, purged_docs=Pointer}}),
-
-    ok = gen_server:call(Db2#db.main_pid, {db_updated, Db2}),
-    couch_db_update_notifier:notify({updated, Db#db.name}),
-    {reply, {ok, (Db2#db.header)#db_header.purge_seq, IdRevsPurged}, Db2};
-handle_call(start_compact, _From, Db) ->
-    case Db#db.compactor_pid of
-    nil ->
-        ?LOG_INFO("Starting compaction for db \"~s\"", [Db#db.name]),
-        Pid = spawn_link(fun() -> start_copy_compact(Db) end),
-        Db2 = Db#db{compactor_pid=Pid},
-        ok = gen_server:call(Db#db.main_pid, {db_updated, Db2}),
-        {reply, {ok, Pid}, Db2};
-    _ ->
-        % compact currently running, this is a no-op
-        {reply, {ok, Db#db.compactor_pid}, Db}
-    end;
-handle_call(cancel_compact, _From, #db{compactor_pid = nil} = Db) ->
-    {reply, ok, Db};
-handle_call(cancel_compact, _From, #db{compactor_pid = Pid} = Db) ->
-    unlink(Pid),
-    exit(Pid, kill),
-    RootDir = couch_config:get("couchdb", "database_dir", "."),
-    ok = couch_file:delete(RootDir, Db#db.filepath ++ ".compact"),
-    {reply, ok, Db#db{compactor_pid = nil}};
-
-
-handle_call({compact_done, CompactFilepath}, _From, #db{filepath=Filepath}=Db) ->
-    {ok, NewFd} = couch_file:open(CompactFilepath),
-    ReaderFd = open_reader_fd(CompactFilepath, Db#db.options),
-    {ok, NewHeader} = couch_file:read_header(NewFd),
-    #db{update_seq=NewSeq} = NewDb =
-        init_db(Db#db.name, Filepath, NewFd, ReaderFd, NewHeader, Db#db.options),
-    unlink(NewFd),
-    case Db#db.update_seq == NewSeq of
-    true ->
-        % suck up all the local docs into memory and write them to the new db
-        {ok, _, LocalDocs} = couch_btree:foldl(Db#db.local_docs_btree,
-                fun(Value, _Offset, Acc) -> {ok, [Value | Acc]} end, []),
-        {ok, NewLocalBtree} = couch_btree:add(NewDb#db.local_docs_btree, LocalDocs),
-
-        NewDb2 = commit_data(NewDb#db{
-            local_docs_btree = NewLocalBtree,
-            main_pid = Db#db.main_pid,
-            filepath = Filepath,
-            instance_start_time = Db#db.instance_start_time,
-            revs_limit = Db#db.revs_limit
-        }),
-
-        ?LOG_DEBUG("CouchDB swapping files ~s and ~s.",
-                [Filepath, CompactFilepath]),
-        RootDir = couch_config:get("couchdb", "database_dir", "."),
-        couch_file:delete(RootDir, Filepath),
-        ok = file:rename(CompactFilepath, Filepath),
-        close_db(Db),
-        NewDb3 = refresh_validate_doc_funs(NewDb2),
-        ok = gen_server:call(Db#db.main_pid, {db_updated, NewDb3}, infinity),
-        couch_db_update_notifier:notify({compacted, NewDb3#db.name}),
-        ?LOG_INFO("Compaction for db \"~s\" completed.", [Db#db.name]),
-        {reply, ok, NewDb3#db{compactor_pid=nil}};
-    false ->
-        ?LOG_INFO("Compaction file still behind main file "
-            "(update seq=~p. compact update seq=~p). Retrying.",
-            [Db#db.update_seq, NewSeq]),
-        close_db(NewDb),
-        {reply, {retry, Db}, Db}
-    end.
-
-
-handle_cast(Msg, #db{name = Name} = Db) ->
-    ?LOG_ERROR("Database `~s` updater received unexpected cast: ~p", [Name, Msg]),
-    {stop, Msg, Db}.
-
-
-handle_info({update_docs, Client, GroupedDocs, NonRepDocs, MergeConflicts,
-        FullCommit}, Db) ->
-    GroupedDocs2 = [[{Client, D} || D <- DocGroup] || DocGroup <- GroupedDocs],
-    if NonRepDocs == [] ->
-        {GroupedDocs3, Clients, FullCommit2} = collect_updates(GroupedDocs2,
-                [Client], MergeConflicts, FullCommit);
-    true ->
-        GroupedDocs3 = GroupedDocs2,
-        FullCommit2 = FullCommit,
-        Clients = [Client]
-    end,
-    NonRepDocs2 = [{Client, NRDoc} || NRDoc <- NonRepDocs],
-    try update_docs_int(Db, GroupedDocs3, NonRepDocs2, MergeConflicts,
-                FullCommit2) of
-    {ok, Db2, UpdatedDDocIds} ->
-        ok = gen_server:call(Db#db.main_pid, {db_updated, Db2}),
-        if Db2#db.update_seq /= Db#db.update_seq ->
-            couch_db_update_notifier:notify({updated, Db2#db.name});
-        true -> ok
-        end,
-        [catch(ClientPid ! {done, self()}) || ClientPid <- Clients],
-        lists:foreach(fun(DDocId) ->
-            couch_db_update_notifier:notify({ddoc_updated, {Db#db.name, DDocId}})
-        end, UpdatedDDocIds),
-        {noreply, Db2}
-    catch
-        throw: retry ->
-            [catch(ClientPid ! {retry, self()}) || ClientPid <- Clients],
-            {noreply, Db}
-    end;
-handle_info(delayed_commit, #db{waiting_delayed_commit=nil}=Db) ->
-    %no outstanding delayed commits, ignore
-    {noreply, Db};
-handle_info(delayed_commit, Db) ->
-    case commit_data(Db) of
-        Db ->
-            {noreply, Db};
-        Db2 ->
-            ok = gen_server:call(Db2#db.main_pid, {db_updated, Db2}),
-            {noreply, Db2}
-    end;
-handle_info({'EXIT', _Pid, normal}, Db) ->
-    {noreply, Db};
-handle_info({'EXIT', _Pid, Reason}, Db) ->
-    {stop, Reason, Db}.
-
-code_change(_OldVsn, State, _Extra) ->
-    {ok, State}.
-
-
-merge_updates([], RestB, AccOutGroups) ->
-    lists:reverse(AccOutGroups, RestB);
-merge_updates(RestA, [], AccOutGroups) ->
-    lists:reverse(AccOutGroups, RestA);
-merge_updates([[{_, {#doc{id=IdA}, _}}|_]=GroupA | RestA],
-        [[{_, {#doc{id=IdB}, _}}|_]=GroupB | RestB], AccOutGroups) ->
-    if IdA == IdB ->
-        merge_updates(RestA, RestB, [GroupA ++ GroupB | AccOutGroups]);
-    IdA < IdB ->
-        merge_updates(RestA, [GroupB | RestB], [GroupA | AccOutGroups]);
-    true ->
-        merge_updates([GroupA | RestA], RestB, [GroupB | AccOutGroups])
-    end.
-
-collect_updates(GroupedDocsAcc, ClientsAcc, MergeConflicts, FullCommit) ->
-    receive
-        % Only collect updates with the same MergeConflicts flag and without
-        % local docs. It's easier to just avoid multiple _local doc
-        % updaters than deal with their possible conflicts, and local docs
-        % writes are relatively rare. Can be optmized later if really needed.
-        {update_docs, Client, GroupedDocs, [], MergeConflicts, FullCommit2} ->
-            GroupedDocs2 = [[{Client, Doc} || Doc <- DocGroup]
-                    || DocGroup <- GroupedDocs],
-            GroupedDocsAcc2 =
-                merge_updates(GroupedDocsAcc, GroupedDocs2, []),
-            collect_updates(GroupedDocsAcc2, [Client | ClientsAcc],
-                    MergeConflicts, (FullCommit or FullCommit2))
-    after 0 ->
-        {GroupedDocsAcc, ClientsAcc, FullCommit}
-    end.
-
-
-btree_by_seq_split(#doc_info{id=Id, high_seq=KeySeq, revs=Revs}) ->
-    {RevInfos, DeletedRevInfos} = lists:foldl(
-        fun(#rev_info{deleted = false, seq = Seq} = Ri, {Acc, AccDel}) ->
-                {[{Ri#rev_info.rev, Seq, Ri#rev_info.body_sp} | Acc], AccDel};
-            (#rev_info{deleted = true, seq = Seq} = Ri, {Acc, AccDel}) ->
-                {Acc, [{Ri#rev_info.rev, Seq, Ri#rev_info.body_sp} | AccDel]}
-        end,
-        {[], []}, Revs),
-    {KeySeq, {Id, lists:reverse(RevInfos), lists:reverse(DeletedRevInfos)}}.
-
-btree_by_seq_join(KeySeq, {Id, RevInfos, DeletedRevInfos}) ->
-    #doc_info{
-        id = Id,
-        high_seq=KeySeq,
-        revs =
-            [#rev_info{rev=Rev,seq=Seq,deleted=false,body_sp = Bp} ||
-                {Rev, Seq, Bp} <- RevInfos] ++
-            [#rev_info{rev=Rev,seq=Seq,deleted=true,body_sp = Bp} ||
-                {Rev, Seq, Bp} <- DeletedRevInfos]}.
-
-btree_by_id_split(#full_doc_info{id=Id, update_seq=Seq,
-        deleted=Deleted, rev_tree=Tree}) ->
-    DiskTree =
-    couch_key_tree:map(
-        fun(_RevId, ?REV_MISSING) ->
-            ?REV_MISSING;
-        (_RevId, RevValue) ->
-            IsDeleted = element(1, RevValue),
-            BodyPointer = element(2, RevValue),
-            UpdateSeq = element(3, RevValue),
-            Size = case tuple_size(RevValue) of
-            4 ->
-                element(4, RevValue);
-            3 ->
-                % pre 1.2 format, will be upgraded on compaction
-                nil
-            end,
-            {if IsDeleted -> 1; true -> 0 end, BodyPointer, UpdateSeq, Size}
-        end, Tree),
-    {Id, {Seq, if Deleted -> 1; true -> 0 end, DiskTree}}.
-
-btree_by_id_join(Id, {HighSeq, Deleted, DiskTree}) ->
-    {Tree, LeafsSize} =
-    couch_key_tree:mapfold(
-        fun(_RevId, {IsDeleted, BodyPointer, UpdateSeq}, leaf, _Acc) ->
-            % pre 1.2 format, will be upgraded on compaction
-            {{IsDeleted == 1, BodyPointer, UpdateSeq, nil}, nil};
-        (_RevId, {IsDeleted, BodyPointer, UpdateSeq}, branch, Acc) ->
-            {{IsDeleted == 1, BodyPointer, UpdateSeq, nil}, Acc};
-        (_RevId, {IsDeleted, BodyPointer, UpdateSeq, Size}, leaf, Acc) ->
-            Acc2 = sum_leaf_sizes(Acc, Size),
-            {{IsDeleted == 1, BodyPointer, UpdateSeq, Size}, Acc2};
-        (_RevId, {IsDeleted, BodyPointer, UpdateSeq, Size}, branch, Acc) ->
-            {{IsDeleted == 1, BodyPointer, UpdateSeq, Size}, Acc};
-        (_RevId, ?REV_MISSING, _Type, Acc) ->
-            {?REV_MISSING, Acc}
-        end, 0, DiskTree),
-    #full_doc_info{
-        id = Id,
-        update_seq = HighSeq,
-        deleted = (Deleted == 1),
-        rev_tree = Tree,
-        leafs_size = LeafsSize
-    }.
-
-btree_by_id_reduce(reduce, FullDocInfos) ->
-    lists:foldl(
-        fun(Info, {NotDeleted, Deleted, Size}) ->
-            Size2 = sum_leaf_sizes(Size, Info#full_doc_info.leafs_size),
-            case Info#full_doc_info.deleted of
-            true ->
-                {NotDeleted, Deleted + 1, Size2};
-            false ->
-                {NotDeleted + 1, Deleted, Size2}
-            end
-        end,
-        {0, 0, 0}, FullDocInfos);
-btree_by_id_reduce(rereduce, Reds) ->
-    lists:foldl(
-        fun({NotDeleted, Deleted}, {AccNotDeleted, AccDeleted, _AccSize}) ->
-            % pre 1.2 format, will be upgraded on compaction
-            {AccNotDeleted + NotDeleted, AccDeleted + Deleted, nil};
-        ({NotDeleted, Deleted, Size}, {AccNotDeleted, AccDeleted, AccSize}) ->
-            AccSize2 = sum_leaf_sizes(AccSize, Size),
-            {AccNotDeleted + NotDeleted, AccDeleted + Deleted, AccSize2}
-        end,
-        {0, 0, 0}, Reds).
-
-sum_leaf_sizes(nil, _) ->
-    nil;
-sum_leaf_sizes(_, nil) ->
-    nil;
-sum_leaf_sizes(Size1, Size2) ->
-    Size1 + Size2.
-
-btree_by_seq_reduce(reduce, DocInfos) ->
-    % count the number of documents
-    length(DocInfos);
-btree_by_seq_reduce(rereduce, Reds) ->
-    lists:sum(Reds).
-
-simple_upgrade_record(Old, New) when tuple_size(Old) < tuple_size(New) ->
-    OldSz = tuple_size(Old),
-    NewValuesTail =
-        lists:sublist(tuple_to_list(New), OldSz + 1, tuple_size(New) - OldSz),
-    list_to_tuple(tuple_to_list(Old) ++ NewValuesTail);
-simple_upgrade_record(Old, _New) ->
-    Old.
-
--define(OLD_DISK_VERSION_ERROR,
-    "Database files from versions smaller than 0.10.0 are no longer supported").
-
-init_db(DbName, Filepath, Fd, ReaderFd, Header0, Options) ->
-    Header1 = simple_upgrade_record(Header0, #db_header{}),
-    Header =
-    case element(2, Header1) of
-    1 -> throw({database_disk_version_error, ?OLD_DISK_VERSION_ERROR});
-    2 -> throw({database_disk_version_error, ?OLD_DISK_VERSION_ERROR});
-    3 -> throw({database_disk_version_error, ?OLD_DISK_VERSION_ERROR});
-    4 -> Header1#db_header{security_ptr = nil}; % 0.10 and pre 0.11
-    5 -> Header1; % pre 1.2
-    ?LATEST_DISK_VERSION -> Header1;
-    _ -> throw({database_disk_version_error, "Incorrect disk header version"})
-    end,
-
-    {ok, FsyncOptions} = couch_util:parse_term(
-            couch_config:get("couchdb", "fsync_options",
-                    "[before_header, after_header, on_file_open]")),
-
-    case lists:member(on_file_open, FsyncOptions) of
-    true -> ok = couch_file:sync(Fd);
-    _ -> ok
-    end,
-
-    Compression = couch_compress:get_compression_method(),
-
-    {ok, IdBtree} = couch_btree:open(Header#db_header.fulldocinfo_by_id_btree_state, Fd,
-        [{split, fun(X) -> btree_by_id_split(X) end},
-        {join, fun(X,Y) -> btree_by_id_join(X,Y) end},
-        {reduce, fun(X,Y) -> btree_by_id_reduce(X,Y) end},
-        {compression, Compression}]),
-    {ok, SeqBtree} = couch_btree:open(Header#db_header.docinfo_by_seq_btree_state, Fd,
-            [{split, fun(X) -> btree_by_seq_split(X) end},
-            {join, fun(X,Y) -> btree_by_seq_join(X,Y) end},
-            {reduce, fun(X,Y) -> btree_by_seq_reduce(X,Y) end},
-            {compression, Compression}]),
-    {ok, LocalDocsBtree} = couch_btree:open(Header#db_header.local_docs_btree_state, Fd,
-        [{compression, Compression}]),
-    case Header#db_header.security_ptr of
-    nil ->
-        Security = [],
-        SecurityPtr = nil;
-    SecurityPtr ->
-        {ok, Security} = couch_file:pread_term(Fd, SecurityPtr)
-    end,
-    % convert start time tuple to microsecs and store as a binary string
-    {MegaSecs, Secs, MicroSecs} = now(),
-    StartTime = ?l2b(io_lib:format("~p",
-            [(MegaSecs*1000000*1000000) + (Secs*1000000) + MicroSecs])),
-    {ok, RefCntr} = couch_ref_counter:start([Fd, ReaderFd]),
-    #db{
-        update_pid=self(),
-        fd = ReaderFd,
-        updater_fd = Fd,
-        fd_ref_counter = RefCntr,
-        header=Header,
-        fulldocinfo_by_id_btree = IdBtree,
-        docinfo_by_seq_btree = SeqBtree,
-        local_docs_btree = LocalDocsBtree,
-        committed_update_seq = Header#db_header.update_seq,
-        update_seq = Header#db_header.update_seq,
-        name = DbName,
-        filepath = Filepath,
-        security = Security,
-        security_ptr = SecurityPtr,
-        instance_start_time = StartTime,
-        revs_limit = Header#db_header.revs_limit,
-        fsync_options = FsyncOptions,
-        options = Options,
-        compression = Compression,
-        before_doc_update = couch_util:get_value(before_doc_update, Options, nil),
-        after_doc_read = couch_util:get_value(after_doc_read, Options, nil)
-        }.
-
-open_reader_fd(Filepath, Options) ->
-    {ok, Fd} = case lists:member(sys_db, Options) of
-    true ->
-        couch_file:open(Filepath, [read_only, sys_db]);
-    false ->
-        couch_file:open(Filepath, [read_only])
-    end,
-    unlink(Fd),
-    Fd.
-
-close_db(#db{fd_ref_counter = RefCntr}) ->
-    couch_ref_counter:drop(RefCntr).
-
-
-refresh_validate_doc_funs(Db0) ->
-    Db = Db0#db{user_ctx = #user_ctx{roles=[<<"_admin">>]}},
-    DesignDocs = couch_db:get_design_docs(Db),
-    ProcessDocFuns = lists:flatmap(
-        fun(DesignDocInfo) ->
-            {ok, DesignDoc} = couch_db:open_doc_int(
-                Db, DesignDocInfo, [ejson_body]),
-            case couch_doc:get_validate_doc_fun(DesignDoc) of
-            nil -> [];
-            Fun -> [Fun]
-            end
-        end, DesignDocs),
-    Db0#db{validate_doc_funs=ProcessDocFuns}.
-
-% rev tree functions
-
-flush_trees(_Db, [], AccFlushedTrees) ->
-    {ok, lists:reverse(AccFlushedTrees)};
-flush_trees(#db{updater_fd = Fd} = Db,
-        [InfoUnflushed | RestUnflushed], AccFlushed) ->
-    #full_doc_info{update_seq=UpdateSeq, rev_tree=Unflushed} = InfoUnflushed,
-    {Flushed, LeafsSize} = couch_key_tree:mapfold(
-        fun(_Rev, Value, Type, Acc) ->
-            case Value of
-            #doc{deleted = IsDeleted, body = {summary, Summary, AttsFd}} ->
-                % this node value is actually an unwritten document summary,
-                % write to disk.
-                % make sure the Fd in the written bins is the same Fd we are
-                % and convert bins, removing the FD.
-                % All bins should have been written to disk already.
-                case {AttsFd, Fd} of
-                {nil, _} ->
-                    ok;
-                {SameFd, SameFd} ->
-                    ok;
-                _ ->
-                    % Fd where the attachments were written to is not the same
-                    % as our Fd. This can happen when a database is being
-                    % switched out during a compaction.
-                    ?LOG_DEBUG("File where the attachments are written has"
-                            " changed. Possibly retrying.", []),
-                    throw(retry)
-                end,
-                {ok, NewSummaryPointer, SummarySize} =
-                    couch_file:append_raw_chunk(Fd, Summary),
-                TotalSize = lists:foldl(
-                    fun(#att{att_len = L}, A) -> A + L end,
-                    SummarySize, Value#doc.atts),
-                NewValue = {IsDeleted, NewSummaryPointer, UpdateSeq, TotalSize},
-                case Type of
-                leaf ->
-                    {NewValue, Acc + TotalSize};
-                branch ->
-                    {NewValue, Acc}
-                end;
-             {_, _, _, LeafSize} when Type =:= leaf, LeafSize =/= nil ->
-                {Value, Acc + LeafSize};
-             _ ->
-                {Value, Acc}
-            end
-        end, 0, Unflushed),
-    InfoFlushed = InfoUnflushed#full_doc_info{
-        rev_tree = Flushed,
-        leafs_size = LeafsSize
-    },
-    flush_trees(Db, RestUnflushed, [InfoFlushed | AccFlushed]).
-
-
-send_result(Client, Ref, NewResult) ->
-    % used to send a result to the client
-    catch(Client ! {result, self(), {Ref, NewResult}}).
-
-merge_rev_trees(_Limit, _Merge, [], [], AccNewInfos, AccRemoveSeqs, AccSeq) ->
-    {ok, lists:reverse(AccNewInfos), AccRemoveSeqs, AccSeq};
-merge_rev_trees(Limit, MergeConflicts, [NewDocs|RestDocsList],
-        [OldDocInfo|RestOldInfo], AccNewInfos, AccRemoveSeqs, AccSeq) ->
-    #full_doc_info{id=Id,rev_tree=OldTree,deleted=OldDeleted0,update_seq=OldSeq}
-            = OldDocInfo,
-    {NewRevTree, _} = lists:foldl(
-        fun({Client, {#doc{revs={Pos,[_Rev|PrevRevs]}}=NewDoc, Ref}}, {AccTree, OldDeleted}) ->
-            if not MergeConflicts ->
-                case couch_key_tree:merge(AccTree, couch_doc:to_path(NewDoc),
-                    Limit) of
-                {_NewTree, conflicts} when (not OldDeleted) ->
-                    send_result(Client, Ref, conflict),
-                    {AccTree, OldDeleted};
-                {NewTree, conflicts} when PrevRevs /= [] ->
-                    % Check to be sure if prev revision was specified, it's
-                    % a leaf node in the tree
-                    Leafs = couch_key_tree:get_all_leafs(AccTree),
-                    IsPrevLeaf = lists:any(fun({_, {LeafPos, [LeafRevId|_]}}) ->
-                            {LeafPos, LeafRevId} == {Pos-1, hd(PrevRevs)}
-                        end, Leafs),
-                    if IsPrevLeaf ->
-                        {NewTree, OldDeleted};
-                    true ->
-                        send_result(Client, Ref, conflict),
-                        {AccTree, OldDeleted}
-                    end;
-                {NewTree, no_conflicts} when  AccTree == NewTree ->
-                    % the tree didn't change at all
-                    % meaning we are saving a rev that's already
-                    % been editted again.
-                    if (Pos == 1) and OldDeleted ->
-                        % this means we are recreating a brand new document
-                        % into a state that already existed before.
-                        % put the rev into a subsequent edit of the deletion
-                        #doc_info{revs=[#rev_info{rev={OldPos,OldRev}}|_]} =
-                                couch_doc:to_doc_info(OldDocInfo),
-                        NewRevId = couch_db:new_revid(
-                                NewDoc#doc{revs={OldPos, [OldRev]}}),
-                        NewDoc2 = NewDoc#doc{revs={OldPos + 1, [NewRevId, OldRev]}},
-                        {NewTree2, _} = couch_key_tree:merge(AccTree,
-                                couch_doc:to_path(NewDoc2), Limit),
-                        % we changed the rev id, this tells the caller we did
-                        send_result(Client, Ref, {ok, {OldPos + 1, NewRevId}}),
-                        {NewTree2, OldDeleted};
-                    true ->
-                        send_result(Client, Ref, conflict),
-                        {AccTree, OldDeleted}
-                    end;
-                {NewTree, _} ->
-                    {NewTree, NewDoc#doc.deleted}
-                end;
-            true ->
-                {NewTree, _} = couch_key_tree:merge(AccTree,
-                            couch_doc:to_path(NewDoc), Limit),
-                {NewTree, OldDeleted}
-            end
-        end,
-        {OldTree, OldDeleted0}, NewDocs),
-    if NewRevTree == OldTree ->
-        % nothing changed
-        merge_rev_trees(Limit, MergeConflicts, RestDocsList, RestOldInfo,
-            AccNewInfos, AccRemoveSeqs, AccSeq);
-    true ->
-        % we have updated the document, give it a new seq #
-        NewInfo = #full_doc_info{id=Id,update_seq=AccSeq+1,rev_tree=NewRevTree},
-        RemoveSeqs = case OldSeq of
-            0 -> AccRemoveSeqs;
-            _ -> [OldSeq | AccRemoveSeqs]
-        end,
-        merge_rev_trees(Limit, MergeConflicts, RestDocsList, RestOldInfo,
-            [NewInfo|AccNewInfos], RemoveSeqs, AccSeq+1)
-    end.
-
-
-
-new_index_entries([], AccById, AccBySeq, AccDDocIds) ->
-    {AccById, AccBySeq, AccDDocIds};
-new_index_entries([FullDocInfo|RestInfos], AccById, AccBySeq, AccDDocIds) ->
-    #doc_info{revs=[#rev_info{deleted=Deleted}|_], id=Id} = DocInfo =
-            couch_doc:to_doc_info(FullDocInfo),
-    AccDDocIds2 = case Id of
-    <<?DESIGN_DOC_PREFIX, _/binary>> ->
-        [Id | AccDDocIds];
-    _ ->
-        AccDDocIds
-    end,
-    new_index_entries(RestInfos,
-        [FullDocInfo#full_doc_info{deleted=Deleted}|AccById],
-        [DocInfo|AccBySeq],
-        AccDDocIds2).
-
-
-stem_full_doc_infos(#db{revs_limit=Limit}, DocInfos) ->
-    [Info#full_doc_info{rev_tree=couch_key_tree:stem(Tree, Limit)} ||
-            #full_doc_info{rev_tree=Tree}=Info <- DocInfos].
-
-update_docs_int(Db, DocsList, NonRepDocs, MergeConflicts, FullCommit) ->
-    #db{
-        fulldocinfo_by_id_btree = DocInfoByIdBTree,
-        docinfo_by_seq_btree = DocInfoBySeqBTree,
-        update_seq = LastSeq,
-        revs_limit = RevsLimit
-        } = Db,
-    Ids = [Id || [{_Client, {#doc{id=Id}, _Ref}}|_] <- DocsList],
-    % lookup up the old documents, if they exist.
-    OldDocLookups = couch_btree:lookup(DocInfoByIdBTree, Ids),
-    OldDocInfos = lists:zipwith(
-        fun(_Id, {ok, FullDocInfo}) ->
-            FullDocInfo;
-        (Id, not_found) ->
-            #full_doc_info{id=Id}
-        end,
-        Ids, OldDocLookups),
-    % Merge the new docs into the revision trees.
-    {ok, NewFullDocInfos, RemoveSeqs, NewSeq} = merge_rev_trees(RevsLimit,
-            MergeConflicts, DocsList, OldDocInfos, [], [], LastSeq),
-
-    % All documents are now ready to write.
-
-    {ok, Db2}  = update_local_docs(Db, NonRepDocs),
-
-    % Write out the document summaries (the bodies are stored in the nodes of
-    % the trees, the attachments are already written to disk)
-    {ok, FlushedFullDocInfos} = flush_trees(Db2, NewFullDocInfos, []),
-
-    {IndexFullDocInfos, IndexDocInfos, UpdatedDDocIds} =
-            new_index_entries(FlushedFullDocInfos, [], [], []),
-
-    % and the indexes
-    {ok, DocInfoByIdBTree2} = couch_btree:add_remove(DocInfoByIdBTree, IndexFullDocInfos, []),
-    {ok, DocInfoBySeqBTree2} = couch_btree:add_remove(DocInfoBySeqBTree, IndexDocInfos, RemoveSeqs),
-
-    Db3 = Db2#db{
-        fulldocinfo_by_id_btree = DocInfoByIdBTree2,
-        docinfo_by_seq_btree = DocInfoBySeqBTree2,
-        update_seq = NewSeq},
-
-    % Check if we just updated any design documents, and update the validation
-    % funs if we did.
-    Db4 = case UpdatedDDocIds of
-    [] ->
-        Db3;
-    _ ->
-        refresh_validate_doc_funs(Db3)
-    end,
-
-    {ok, commit_data(Db4, not FullCommit), UpdatedDDocIds}.
-
-update_local_docs(Db, []) ->
-    {ok, Db};
-update_local_docs(#db{local_docs_btree=Btree}=Db, Docs) ->
-    Ids = [Id || {_Client, {#doc{id=Id}, _Ref}} <- Docs],
-    OldDocLookups = couch_btree:lookup(Btree, Ids),
-    BtreeEntries = lists:zipwith(
-        fun({Client, {#doc{id=Id,deleted=Delete,revs={0,PrevRevs},body=Body}, Ref}}, OldDocLookup) ->
-            case PrevRevs of
-            [RevStr|_] ->
-                PrevRev = list_to_integer(?b2l(RevStr));
-            [] ->
-                PrevRev = 0
-            end,
-            OldRev =
-            case OldDocLookup of
-                {ok, {_, {OldRev0, _}}} -> OldRev0;
-                not_found -> 0
-            end,
-            case OldRev == PrevRev of
-            true ->
-                case Delete of
-                    false ->
-                        send_result(Client, Ref, {ok,
-                                {0, ?l2b(integer_to_list(PrevRev + 1))}}),
-                        {update, {Id, {PrevRev + 1, Body}}};
-                    true  ->
-                        send_result(Client, Ref,
-                                {ok, {0, <<"0">>}}),
-                        {remove, Id}
-                end;
-            false ->
-                send_result(Client, Ref, conflict),
-                ignore
-            end
-        end, Docs, OldDocLookups),
-
-    BtreeIdsRemove = [Id || {remove, Id} <- BtreeEntries],
-    BtreeIdsUpdate = [{Key, Val} || {update, {Key, Val}} <- BtreeEntries],
-
-    {ok, Btree2} =
-        couch_btree:add_remove(Btree, BtreeIdsUpdate, BtreeIdsRemove),
-
-    {ok, Db#db{local_docs_btree = Btree2}}.
-
-
-commit_data(Db) ->
-    commit_data(Db, false).
-
-db_to_header(Db, Header) ->
-    Header#db_header{
-        update_seq = Db#db.update_seq,
-        docinfo_by_seq_btree_state = couch_btree:get_state(Db#db.docinfo_by_seq_btree),
-        fulldocinfo_by_id_btree_state = couch_btree:get_state(Db#db.fulldocinfo_by_id_btree),
-        local_docs_btree_state = couch_btree:get_state(Db#db.local_docs_btree),
-        security_ptr = Db#db.security_ptr,
-        revs_limit = Db#db.revs_limit}.
-
-commit_data(#db{waiting_delayed_commit=nil} = Db, true) ->
-    Db#db{waiting_delayed_commit=erlang:send_after(1000,self(),delayed_commit)};
-commit_data(Db, true) ->
-    Db;
-commit_data(Db, _) ->
-    #db{
-        updater_fd = Fd,
-        filepath = Filepath,
-        header = OldHeader,
-        fsync_options = FsyncOptions,
-        waiting_delayed_commit = Timer
-    } = Db,
-    if is_reference(Timer) -> erlang:cancel_timer(Timer); true -> ok end,
-    case db_to_header(Db, OldHeader) of
-    OldHeader ->
-        Db#db{waiting_delayed_commit=nil};
-    Header ->
-        case lists:member(before_header, FsyncOptions) of
-        true -> ok = couch_file:sync(Filepath);
-        _    -> ok
-        end,
-
-        ok = couch_file:write_header(Fd, Header),
-
-        case lists:member(after_header, FsyncOptions) of
-        true -> ok = couch_file:sync(Filepath);
-        _    -> ok
-        end,
-
-        Db#db{waiting_delayed_commit=nil,
-            header=Header,
-            committed_update_seq=Db#db.update_seq}
-    end.
-
-
-copy_doc_attachments(#db{updater_fd = SrcFd} = SrcDb, SrcSp, DestFd) ->
-    {ok, {BodyData, BinInfos0}} = couch_db:read_doc(SrcDb, SrcSp),
-    BinInfos = case BinInfos0 of
-    _ when is_binary(BinInfos0) ->
-        couch_compress:decompress(BinInfos0);
-    _ when is_list(BinInfos0) ->
-        % pre 1.2 file format
-        BinInfos0
-    end,
-    % copy the bin values
-    NewBinInfos = lists:map(
-        fun({Name, Type, BinSp, AttLen, RevPos, Md5}) ->
-            % 010 UPGRADE CODE
-            {NewBinSp, AttLen, AttLen, Md5, _IdentityMd5} =
-                couch_stream:copy_to_new_stream(SrcFd, BinSp, DestFd),
-            {Name, Type, NewBinSp, AttLen, AttLen, RevPos, Md5, identity};
-        ({Name, Type, BinSp, AttLen, DiskLen, RevPos, Md5, Enc1}) ->
-            {NewBinSp, AttLen, _, Md5, _IdentityMd5} =
-                couch_stream:copy_to_new_stream(SrcFd, BinSp, DestFd),
-            Enc = case Enc1 of
-            true ->
-                % 0110 UPGRADE CODE
-                gzip;
-            false ->
-                % 0110 UPGRADE CODE
-                identity;
-            _ ->
-                Enc1
-            end,
-            {Name, Type, NewBinSp, AttLen, DiskLen, RevPos, Md5, Enc}
-        end, BinInfos),
-    {BodyData, NewBinInfos}.
-
-copy_docs(Db, #db{updater_fd = DestFd} = NewDb, InfoBySeq0, Retry) ->
-    % COUCHDB-968, make sure we prune duplicates during compaction
-    InfoBySeq = lists:usort(fun(#doc_info{id=A}, #doc_info{id=B}) -> A =< B end,
-        InfoBySeq0),
-    Ids = [Id || #doc_info{id=Id} <- InfoBySeq],
-    LookupResults = couch_btree:lookup(Db#db.fulldocinfo_by_id_btree, Ids),
-
-    NewFullDocInfos1 = lists:map(
-        fun({ok, #full_doc_info{rev_tree=RevTree}=Info}) ->
-            Info#full_doc_info{rev_tree=couch_key_tree:map(
-                fun(_, _, branch) ->
-                    ?REV_MISSING;
-                (_Rev, LeafVal, leaf) ->
-                    IsDel = element(1, LeafVal),
-                    Sp = element(2, LeafVal),
-                    Seq = element(3, LeafVal),
-                    {_Body, AttsInfo} = Summary = copy_doc_attachments(
-                        Db, Sp, DestFd),
-                    SummaryChunk = make_doc_summary(NewDb, Summary),
-                    {ok, Pos, SummarySize} = couch_file:append_raw_chunk(
-                        DestFd, SummaryChunk),
-                    TotalLeafSize = lists:foldl(
-                        fun({_, _, _, AttLen, _, _, _, _}, S) -> S + AttLen end,
-                        SummarySize, AttsInfo),
-                    {IsDel, Pos, Seq, TotalLeafSize}
-                end, RevTree)}
-        end, LookupResults),
-
-    NewFullDocInfos = stem_full_doc_infos(Db, NewFullDocInfos1),
-    NewDocInfos = [couch_doc:to_doc_info(Info) || Info <- NewFullDocInfos],
-    RemoveSeqs =
-    case Retry of
-    false ->
-        [];
-    true ->
-        % We are retrying a compaction, meaning the documents we are copying may
-        % already exist in our file and must be removed from the by_seq index.
-        Existing = couch_btree:lookup(NewDb#db.fulldocinfo_by_id_btree, Ids),
-        [Seq || {ok, #full_doc_info{update_seq=Seq}} <- Existing]
-    end,
-
-    {ok, DocInfoBTree} = couch_btree:add_remove(
-            NewDb#db.docinfo_by_seq_btree, NewDocInfos, RemoveSeqs),
-    {ok, FullDocInfoBTree} = couch_btree:add_remove(
-            NewDb#db.fulldocinfo_by_id_btree, NewFullDocInfos, []),
-    update_compact_task(length(NewFullDocInfos)),
-    NewDb#db{ fulldocinfo_by_id_btree=FullDocInfoBTree,
-              docinfo_by_seq_btree=DocInfoBTree}.
-
-
-
-copy_compact(Db, NewDb0, Retry) ->
-    FsyncOptions = [Op || Op <- NewDb0#db.fsync_options, Op == before_header],
-    Compression = couch_compress:get_compression_method(),
-    NewDb = NewDb0#db{fsync_options=FsyncOptions, compression=Compression},
-    TotalChanges = couch_db:count_changes_since(Db, NewDb#db.update_seq),
-    BufferSize = list_to_integer(
-        couch_config:get("database_compaction", "doc_buffer_size", "524288")),
-    CheckpointAfter = couch_util:to_integer(
-        couch_config:get("database_compaction", "checkpoint_after",
-            BufferSize * 10)),
-
-    EnumBySeqFun =
-    fun(#doc_info{high_seq=Seq}=DocInfo, _Offset,
-        {AccNewDb, AccUncopied, AccUncopiedSize, AccCopiedSize}) ->
-
-        AccUncopiedSize2 = AccUncopiedSize + ?term_size(DocInfo),
-        if AccUncopiedSize2 >= BufferSize ->
-            NewDb2 = copy_docs(
-                Db, AccNewDb, lists:reverse([DocInfo | AccUncopied]), Retry),
-            AccCopiedSize2 = AccCopiedSize + AccUncopiedSize2,
-            if AccCopiedSize2 >= CheckpointAfter ->
-                {ok, {commit_data(NewDb2#db{update_seq = Seq}), [], 0, 0}};
-            true ->
-                {ok, {NewDb2#db{update_seq = Seq}, [], 0, AccCopiedSize2}}
-            end;
-        true ->
-            {ok, {AccNewDb, [DocInfo | AccUncopied], AccUncopiedSize2,
-                AccCopiedSize}}
-        end
-    end,
-
-    TaskProps0 = [
-        {type, database_compaction},
-        {database, Db#db.name},
-        {progress, 0},
-        {changes_done, 0},
-        {total_changes, TotalChanges}
-    ],
-    case Retry and couch_task_status:is_task_added() of
-    true ->
-        couch_task_status:update([
-            {retry, true},
-            {progress, 0},
-            {changes_done, 0},
-            {total_changes, TotalChanges}
-        ]);
-    false ->
-        couch_task_status:add_task(TaskProps0),
-        couch_task_status:set_update_frequency(500)
-    end,
-
-    {ok, _, {NewDb2, Uncopied, _, _}} =
-        couch_btree:foldl(Db#db.docinfo_by_seq_btree, EnumBySeqFun,
-            {NewDb, [], 0, 0},
-            [{start_key, NewDb#db.update_seq + 1}]),
-
-    NewDb3 = copy_docs(Db, NewDb2, lists:reverse(Uncopied), Retry),
-
-    % copy misc header values
-    if NewDb3#db.security /= Db#db.security ->
-        {ok, Ptr, _} = couch_file:append_term(
-            NewDb3#db.updater_fd, Db#db.security,
-            [{compression, NewDb3#db.compression}]),
-        NewDb4 = NewDb3#db{security=Db#db.security, security_ptr=Ptr};
-    true ->
-        NewDb4 = NewDb3
-    end,
-
-    commit_data(NewDb4#db{update_seq=Db#db.update_seq}).
-
-start_copy_compact(#db{name=Name,filepath=Filepath,header=#db_header{purge_seq=PurgeSeq}}=Db) ->
-    CompactFile = Filepath ++ ".compact",
-    ?LOG_DEBUG("Compaction process spawned for db \"~s\"", [Name]),
-    case couch_file:open(CompactFile, [nologifmissing]) of
-    {ok, Fd} ->
-        Retry = true,
-        case couch_file:read_header(Fd) of
-        {ok, Header} ->
-            ok;
-        no_valid_header ->
-            ok = couch_file:write_header(Fd, Header=#db_header{})
-        end;
-    {error, enoent} ->
-        {ok, Fd} = couch_file:open(CompactFile, [create]),
-        Retry = false,
-        ok = couch_file:write_header(Fd, Header=#db_header{})
-    end,
-    ReaderFd = open_reader_fd(CompactFile, Db#db.options),
-    NewDb = init_db(Name, CompactFile, Fd, ReaderFd, Header, Db#db.options),
-    NewDb2 = if PurgeSeq > 0 ->
-        {ok, PurgedIdsRevs} = couch_db:get_last_purged(Db),
-        {ok, Pointer, _} = couch_file:append_term(
-            Fd, PurgedIdsRevs, [{compression, NewDb#db.compression}]),
-        NewDb#db{header=Header#db_header{purge_seq=PurgeSeq, purged_docs=Pointer}};
-    true ->
-        NewDb
-    end,
-    unlink(Fd),
-
-    NewDb3 = copy_compact(Db, NewDb2, Retry),
-    close_db(NewDb3),
-    case gen_server:call(
-        Db#db.update_pid, {compact_done, CompactFile}, infinity) of
-    ok ->
-        ok;
-    {retry, CurrentDb} ->
-        start_copy_compact(CurrentDb)
-    end.
-
-update_compact_task(NumChanges) ->
-    [Changes, Total] = couch_task_status:get([changes_done, total_changes]),
-    Changes2 = Changes + NumChanges,
-    Progress = case Total of
-    0 ->
-        0;
-    _ ->
-        (Changes2 * 100) div Total
-    end,
-    couch_task_status:update([{changes_done, Changes2}, {progress, Progress}]).
-
-make_doc_summary(#db{compression = Comp}, {Body0, Atts0}) ->
-    Body = case couch_compress:is_compressed(Body0, Comp) of
-    true ->
-        Body0;
-    false ->
-        % pre 1.2 database file format
-        couch_compress:compress(Body0, Comp)
-    end,
-    Atts = case couch_compress:is_compressed(Atts0, Comp) of
-    true ->
-        Atts0;
-    false ->
-        couch_compress:compress(Atts0, Comp)
-    end,
-    SummaryBin = ?term_to_bin({Body, Atts}),
-    couch_file:assemble_file_chunk(SummaryBin, couch_util:md5(SummaryBin)).

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_doc.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_doc.erl b/apps/couch/src/couch_doc.erl
deleted file mode 100644
index 4047370..0000000
--- a/apps/couch/src/couch_doc.erl
+++ /dev/null
@@ -1,650 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_doc).
-
--export([to_doc_info/1,to_doc_info_path/1,parse_rev/1,parse_revs/1,rev_to_str/1,revs_to_strs/1]).
--export([att_foldl/3,range_att_foldl/5,att_foldl_decode/3,get_validate_doc_fun/1]).
--export([from_json_obj/1,to_json_obj/2,has_stubs/1, merge_stubs/2]).
--export([validate_docid/1]).
--export([doc_from_multi_part_stream/2]).
--export([doc_to_multi_part_stream/5, len_doc_to_multi_part_stream/4]).
--export([abort_multi_part_stream/1]).
--export([to_path/1]).
--export([mp_parse_doc/2]).
--export([with_ejson_body/1]).
-
--include("couch_db.hrl").
-
--spec to_path(#doc{}) -> path().
-to_path(#doc{revs={Start, RevIds}}=Doc) ->
-    [Branch] = to_branch(Doc, lists:reverse(RevIds)),
-    {Start - length(RevIds) + 1, Branch}.
-
--spec to_branch(#doc{}, [RevId::binary()]) -> [branch()].
-to_branch(Doc, [RevId]) ->
-    [{RevId, Doc, []}];
-to_branch(Doc, [RevId | Rest]) ->
-    [{RevId, ?REV_MISSING, to_branch(Doc, Rest)}].
-
-% helpers used by to_json_obj
-to_json_rev(0, []) ->
-    [];
-to_json_rev(Start, [FirstRevId|_]) ->
-    [{<<"_rev">>, ?l2b([integer_to_list(Start),"-",revid_to_str(FirstRevId)])}].
-
-to_json_body(true, {Body}) ->
-    Body ++ [{<<"_deleted">>, true}];
-to_json_body(false, {Body}) ->
-    Body.
-
-to_json_revisions(Options, Start, RevIds) ->
-    case lists:member(revs, Options) of
-    false -> [];
-    true ->
-        [{<<"_revisions">>, {[{<<"start">>, Start},
-                {<<"ids">>, [revid_to_str(R) ||R <- RevIds]}]}}]
-    end.
-
-revid_to_str(RevId) when size(RevId) =:= 16 ->
-    ?l2b(couch_util:to_hex(RevId));
-revid_to_str(RevId) ->
-    RevId.
-
-rev_to_str({Pos, RevId}) ->
-    ?l2b([integer_to_list(Pos),"-",revid_to_str(RevId)]).
-
-
-revs_to_strs([]) ->
-    [];
-revs_to_strs([{Pos, RevId}| Rest]) ->
-    [rev_to_str({Pos, RevId}) | revs_to_strs(Rest)].
-
-to_json_meta(Meta) ->
-    lists:map(
-        fun({revs_info, Start, RevsInfo}) ->
-            {JsonRevsInfo, _Pos}  = lists:mapfoldl(
-                fun({RevId, Status}, PosAcc) ->
-                    JsonObj = {[{<<"rev">>, rev_to_str({PosAcc, RevId})},
-                        {<<"status">>, ?l2b(atom_to_list(Status))}]},
-                    {JsonObj, PosAcc - 1}
-                end, Start, RevsInfo),
-            {<<"_revs_info">>, JsonRevsInfo};
-        ({local_seq, Seq}) ->
-            {<<"_local_seq">>, Seq};
-        ({conflicts, Conflicts}) ->
-            {<<"_conflicts">>, revs_to_strs(Conflicts)};
-        ({deleted_conflicts, DConflicts}) ->
-            {<<"_deleted_conflicts">>, revs_to_strs(DConflicts)}
-        end, Meta).
-
-to_json_attachments(Attachments, Options) ->
-    to_json_attachments(
-        Attachments,
-        lists:member(attachments, Options),
-        lists:member(follows, Options),
-        lists:member(att_encoding_info, Options)
-    ).
-
-to_json_attachments([], _OutputData, _DataToFollow, _ShowEncInfo) ->
-    [];
-to_json_attachments(Atts, OutputData, DataToFollow, ShowEncInfo) ->
-    AttProps = lists:map(
-        fun(#att{disk_len=DiskLen, att_len=AttLen, encoding=Enc}=Att) ->
-            {Att#att.name, {[
-                {<<"content_type">>, Att#att.type},
-                {<<"revpos">>, Att#att.revpos}] ++
-                case Att#att.md5 of
-                    <<>> ->
-                        [];
-                    Md5 ->
-                        EncodedMd5 = base64:encode(Md5),
-                        [{<<"digest">>, <<"md5-",EncodedMd5/binary>>}]
-                end ++
-                if not OutputData orelse Att#att.data == stub ->
-                    [{<<"length">>, DiskLen}, {<<"stub">>, true}];
-                true ->
-                    if DataToFollow ->
-                        [{<<"length">>, DiskLen}, {<<"follows">>, true}];
-                    true ->
-                        AttData = case Enc of
-                        gzip ->
-                            zlib:gunzip(att_to_bin(Att));
-                        identity ->
-                            att_to_bin(Att)
-                        end,
-                        [{<<"data">>, base64:encode(AttData)}]
-                    end
-                end ++
-                    case {ShowEncInfo, Enc} of
-                    {false, _} ->
-                        [];
-                    {true, identity} ->
-                        [];
-                    {true, _} ->
-                        [
-                            {<<"encoding">>, couch_util:to_binary(Enc)},
-                            {<<"encoded_length">>, AttLen}
-                        ]
-                    end
-            }}
-        end, Atts),
-    [{<<"_attachments">>, {AttProps}}].
-
-to_json_obj(Doc, Options) ->
-    doc_to_json_obj(with_ejson_body(Doc), Options).
-
-doc_to_json_obj(#doc{id=Id,deleted=Del,body=Body,revs={Start, RevIds},
-            meta=Meta}=Doc,Options)->
-    {[{<<"_id">>, Id}]
-        ++ to_json_rev(Start, RevIds)
-        ++ to_json_body(Del, Body)
-        ++ to_json_revisions(Options, Start, RevIds)
-        ++ to_json_meta(Meta)
-        ++ to_json_attachments(Doc#doc.atts, Options)
-    }.
-
-from_json_obj({Props}) ->
-    transfer_fields(Props, #doc{body=[]});
-
-from_json_obj(_Other) ->
-    throw({bad_request, "Document must be a JSON object"}).
-
-parse_revid(RevId) when size(RevId) =:= 32 ->
-    RevInt = erlang:list_to_integer(?b2l(RevId), 16),
-     <<RevInt:128>>;
-parse_revid(RevId) when length(RevId) =:= 32 ->
-    RevInt = erlang:list_to_integer(RevId, 16),
-     <<RevInt:128>>;
-parse_revid(RevId) when is_binary(RevId) ->
-    RevId;
-parse_revid(RevId) when is_list(RevId) ->
-    ?l2b(RevId).
-
-
-parse_rev(Rev) when is_binary(Rev) ->
-    parse_rev(?b2l(Rev));
-parse_rev(Rev) when is_list(Rev) ->
-    SplitRev = lists:splitwith(fun($-) -> false; (_) -> true end, Rev),
-    case SplitRev of
-        {Pos, [$- | RevId]} -> {list_to_integer(Pos), parse_revid(RevId)};
-        _Else -> throw({bad_request, <<"Invalid rev format">>})
-    end;
-parse_rev(_BadRev) ->
-    throw({bad_request, <<"Invalid rev format">>}).
-
-parse_revs([]) ->
-    [];
-parse_revs([Rev | Rest]) ->
-    [parse_rev(Rev) | parse_revs(Rest)].
-
-
-validate_docid(<<"">>) ->
-    throw({bad_request, <<"Document id must not be empty">>});
-validate_docid(Id) when is_binary(Id) ->
-    case couch_util:validate_utf8(Id) of
-        false -> throw({bad_request, <<"Document id must be valid UTF-8">>});
-        true -> ok
-    end,
-    case Id of
-    <<"_design/", _/binary>> -> ok;
-    <<"_local/", _/binary>> -> ok;
-    <<"_", _/binary>> ->
-        throw({bad_request, <<"Only reserved document ids may start with underscore.">>});
-    _Else -> ok
-    end;
-validate_docid(Id) ->
-    ?LOG_DEBUG("Document id is not a string: ~p", [Id]),
-    throw({bad_request, <<"Document id must be a string">>}).
-
-transfer_fields([], #doc{body=Fields}=Doc) ->
-    % convert fields back to json object
-    Doc#doc{body={lists:reverse(Fields)}};
-
-transfer_fields([{<<"_id">>, Id} | Rest], Doc) ->
-    validate_docid(Id),
-    transfer_fields(Rest, Doc#doc{id=Id});
-
-transfer_fields([{<<"_rev">>, Rev} | Rest], #doc{revs={0, []}}=Doc) ->
-    {Pos, RevId} = parse_rev(Rev),
-    transfer_fields(Rest,
-            Doc#doc{revs={Pos, [RevId]}});
-
-transfer_fields([{<<"_rev">>, _Rev} | Rest], Doc) ->
-    % we already got the rev from the _revisions
-    transfer_fields(Rest,Doc);
-
-transfer_fields([{<<"_attachments">>, {JsonBins}} | Rest], Doc) ->
-    Atts = lists:map(fun({Name, {BinProps}}) ->
-        Md5 = case couch_util:get_value(<<"digest">>, BinProps) of
-            <<"md5-",EncodedMd5/binary>> ->
-                base64:decode(EncodedMd5);
-            _ ->
-               <<>>
-        end,
-        case couch_util:get_value(<<"stub">>, BinProps) of
-        true ->
-            Type = couch_util:get_value(<<"content_type">>, BinProps),
-            RevPos = couch_util:get_value(<<"revpos">>, BinProps, nil),
-            DiskLen = couch_util:get_value(<<"length">>, BinProps),
-            {Enc, EncLen} = att_encoding_info(BinProps),
-            #att{name=Name, data=stub, type=Type, att_len=EncLen,
-                disk_len=DiskLen, encoding=Enc, revpos=RevPos, md5=Md5};
-        _ ->
-            Type = couch_util:get_value(<<"content_type">>, BinProps,
-                    ?DEFAULT_ATTACHMENT_CONTENT_TYPE),
-            RevPos = couch_util:get_value(<<"revpos">>, BinProps, 0),
-            case couch_util:get_value(<<"follows">>, BinProps) of
-            true ->
-                DiskLen = couch_util:get_value(<<"length">>, BinProps),
-                {Enc, EncLen} = att_encoding_info(BinProps),
-                #att{name=Name, data=follows, type=Type, encoding=Enc,
-                    att_len=EncLen, disk_len=DiskLen, revpos=RevPos, md5=Md5};
-            _ ->
-                Value = couch_util:get_value(<<"data">>, BinProps),
-                Bin = base64:decode(Value),
-                LenBin = size(Bin),
-                #att{name=Name, data=Bin, type=Type, att_len=LenBin,
-                        disk_len=LenBin, revpos=RevPos}
-            end
-        end
-    end, JsonBins),
-    transfer_fields(Rest, Doc#doc{atts=Atts});
-
-transfer_fields([{<<"_revisions">>, {Props}} | Rest], Doc) ->
-    RevIds = couch_util:get_value(<<"ids">>, Props),
-    Start = couch_util:get_value(<<"start">>, Props),
-    if not is_integer(Start) ->
-        throw({doc_validation, "_revisions.start isn't an integer."});
-    not is_list(RevIds) ->
-        throw({doc_validation, "_revisions.ids isn't a array."});
-    true ->
-        ok
-    end,
-    [throw({doc_validation, "RevId isn't a string"}) ||
-            RevId <- RevIds, not is_binary(RevId)],
-    RevIds2 = [parse_revid(RevId) || RevId <- RevIds],
-    transfer_fields(Rest, Doc#doc{revs={Start, RevIds2}});
-
-transfer_fields([{<<"_deleted">>, B} | Rest], Doc) when is_boolean(B) ->
-    transfer_fields(Rest, Doc#doc{deleted=B});
-
-% ignored fields
-transfer_fields([{<<"_revs_info">>, _} | Rest], Doc) ->
-    transfer_fields(Rest, Doc);
-transfer_fields([{<<"_local_seq">>, _} | Rest], Doc) ->
-    transfer_fields(Rest, Doc);
-transfer_fields([{<<"_conflicts">>, _} | Rest], Doc) ->
-    transfer_fields(Rest, Doc);
-transfer_fields([{<<"_deleted_conflicts">>, _} | Rest], Doc) ->
-    transfer_fields(Rest, Doc);
-
-% special fields for replication documents
-transfer_fields([{<<"_replication_state">>, _} = Field | Rest],
-    #doc{body=Fields} = Doc) ->
-    transfer_fields(Rest, Doc#doc{body=[Field|Fields]});
-transfer_fields([{<<"_replication_state_time">>, _} = Field | Rest],
-    #doc{body=Fields} = Doc) ->
-    transfer_fields(Rest, Doc#doc{body=[Field|Fields]});
-transfer_fields([{<<"_replication_state_reason">>, _} = Field | Rest],
-    #doc{body=Fields} = Doc) ->
-    transfer_fields(Rest, Doc#doc{body=[Field|Fields]});
-transfer_fields([{<<"_replication_id">>, _} = Field | Rest],
-    #doc{body=Fields} = Doc) ->
-    transfer_fields(Rest, Doc#doc{body=[Field|Fields]});
-transfer_fields([{<<"_replication_stats">>, _} = Field | Rest],
-    #doc{body=Fields} = Doc) ->
-    transfer_fields(Rest, Doc#doc{body=[Field|Fields]});
-
-% unknown special field
-transfer_fields([{<<"_",Name/binary>>, _} | _], _) ->
-    throw({doc_validation,
-            ?l2b(io_lib:format("Bad special document member: _~s", [Name]))});
-
-transfer_fields([Field | Rest], #doc{body=Fields}=Doc) ->
-    transfer_fields(Rest, Doc#doc{body=[Field|Fields]}).
-
-att_encoding_info(BinProps) ->
-    DiskLen = couch_util:get_value(<<"length">>, BinProps),
-    case couch_util:get_value(<<"encoding">>, BinProps) of
-    undefined ->
-        {identity, DiskLen};
-    Enc ->
-        EncodedLen = couch_util:get_value(<<"encoded_length">>, BinProps, DiskLen),
-        {list_to_existing_atom(?b2l(Enc)), EncodedLen}
-    end.
-
-to_doc_info(FullDocInfo) ->
-    {DocInfo, _Path} = to_doc_info_path(FullDocInfo),
-    DocInfo.
-
-max_seq(Tree, UpdateSeq) ->
-    FoldFun = fun({_Pos, _Key}, Value, _Type, MaxOldSeq) ->
-        case Value of
-            {_Deleted, _DiskPos, OldTreeSeq} ->
-                % Older versions didn't track data sizes.
-                erlang:max(MaxOldSeq, OldTreeSeq);
-            {_Deleted, _DiskPos, OldTreeSeq, _Size} ->
-                erlang:max(MaxOldSeq, OldTreeSeq);
-            _ ->
-                MaxOldSeq
-        end
-    end,
-    couch_key_tree:fold(FoldFun, UpdateSeq, Tree).
-
-to_doc_info_path(#full_doc_info{id=Id,rev_tree=Tree,update_seq=Seq}) ->
-    RevInfosAndPath = [
-        {#rev_info{
-            deleted = element(1, LeafVal),
-            body_sp = element(2, LeafVal),
-            seq = element(3, LeafVal),
-            rev = {Pos, RevId}
-        }, Path} || {LeafVal, {Pos, [RevId | _]} = Path} <-
-            couch_key_tree:get_all_leafs(Tree)
-    ],
-    SortedRevInfosAndPath = lists:sort(
-            fun({#rev_info{deleted=DeletedA,rev=RevA}, _PathA},
-                {#rev_info{deleted=DeletedB,rev=RevB}, _PathB}) ->
-            % sort descending by {not deleted, rev}
-            {not DeletedA, RevA} > {not DeletedB, RevB}
-        end, RevInfosAndPath),
-    [{_RevInfo, WinPath}|_] = SortedRevInfosAndPath,
-    RevInfos = [RevInfo || {RevInfo, _Path} <- SortedRevInfosAndPath],
-    {#doc_info{id=Id, high_seq=max_seq(Tree, Seq), revs=RevInfos}, WinPath}.
-
-
-
-
-att_foldl(#att{data=Bin}, Fun, Acc) when is_binary(Bin) ->
-    Fun(Bin, Acc);
-att_foldl(#att{data={Fd,Sp},md5=Md5}, Fun, Acc) ->
-    couch_stream:foldl(Fd, Sp, Md5, Fun, Acc);
-att_foldl(#att{data=DataFun,att_len=Len}, Fun, Acc) when is_function(DataFun) ->
-   fold_streamed_data(DataFun, Len, Fun, Acc).
-
-range_att_foldl(#att{data={Fd,Sp}}, From, To, Fun, Acc) ->
-   couch_stream:range_foldl(Fd, Sp, From, To, Fun, Acc).
-
-att_foldl_decode(#att{data={Fd,Sp},md5=Md5,encoding=Enc}, Fun, Acc) ->
-    couch_stream:foldl_decode(Fd, Sp, Md5, Enc, Fun, Acc);
-att_foldl_decode(#att{data=Fun2,att_len=Len, encoding=identity}, Fun, Acc) ->
-       fold_streamed_data(Fun2, Len, Fun, Acc).
-
-att_to_bin(#att{data=Bin}) when is_binary(Bin) ->
-    Bin;
-att_to_bin(#att{data=Iolist}) when is_list(Iolist) ->
-    iolist_to_binary(Iolist);
-att_to_bin(#att{data={_Fd,_Sp}}=Att) ->
-    iolist_to_binary(
-        lists:reverse(att_foldl(
-                Att,
-                fun(Bin,Acc) -> [Bin|Acc] end,
-                []
-        ))
-    );
-att_to_bin(#att{data=DataFun, att_len=Len}) when is_function(DataFun)->
-    iolist_to_binary(
-        lists:reverse(fold_streamed_data(
-            DataFun,
-            Len,
-            fun(Data, Acc) -> [Data | Acc] end,
-            []
-        ))
-    ).
-
-get_validate_doc_fun(#doc{body={Props}}=DDoc) ->
-    case couch_util:get_value(<<"validate_doc_update">>, Props) of
-    undefined ->
-        nil;
-    _Else ->
-        fun(EditDoc, DiskDoc, Ctx, SecObj) ->
-            couch_query_servers:validate_doc_update(DDoc, EditDoc, DiskDoc, Ctx, SecObj)
-        end
-    end.
-
-
-has_stubs(#doc{atts=Atts}) ->
-    has_stubs(Atts);
-has_stubs([]) ->
-    false;
-has_stubs([#att{data=stub}|_]) ->
-    true;
-has_stubs([_Att|Rest]) ->
-    has_stubs(Rest).
-
-merge_stubs(#doc{id = Id}, nil) ->
-    throw({missing_stub, <<"Previous revision missing for document ", Id/binary>>});
-merge_stubs(#doc{id=Id,atts=MemBins}=StubsDoc, #doc{atts=DiskBins}) ->
-    BinDict = dict:from_list([{Name, Att} || #att{name=Name}=Att <- DiskBins]),
-    MergedBins = lists:map(
-        fun(#att{name=Name, data=stub, revpos=StubRevPos}) ->
-            case dict:find(Name, BinDict) of
-            {ok, #att{revpos=DiskRevPos}=DiskAtt}
-                    when DiskRevPos == StubRevPos orelse StubRevPos == nil ->
-                DiskAtt;
-            _ ->
-                throw({missing_stub,
-                        <<"id:", Id/binary, ", name:", Name/binary>>})
-            end;
-        (Att) ->
-            Att
-        end, MemBins),
-    StubsDoc#doc{atts= MergedBins}.
-
-fold_streamed_data(_RcvFun, 0, _Fun, Acc) ->
-    Acc;
-fold_streamed_data(RcvFun, LenLeft, Fun, Acc) when LenLeft > 0->
-    Bin = RcvFun(),
-    ResultAcc = Fun(Bin, Acc),
-    fold_streamed_data(RcvFun, LenLeft - size(Bin), Fun, ResultAcc).
-
-len_doc_to_multi_part_stream(Boundary, JsonBytes, Atts, SendEncodedAtts) ->
-    AttsSize = lists:foldl(fun(Att, AccAttsSize) ->
-            #att{
-                data=Data,
-                name=Name,
-                att_len=AttLen,
-                disk_len=DiskLen,
-                type=Type,
-                encoding=Encoding
-            } = Att,
-            case Data of
-            stub ->
-                AccAttsSize;
-            _ ->
-                AccAttsSize +
-                4 + % "\r\n\r\n"
-                case SendEncodedAtts of
-                true ->
-                    % header
-                    length(integer_to_list(AttLen)) +
-                    AttLen;
-                _ ->
-                    % header
-                    length(integer_to_list(DiskLen)) +
-                    DiskLen
-                end +
-                4 + % "\r\n--"
-                size(Boundary) +
-
-                % attachment headers
-                % (the length of the Content-Length has already been set)
-                size(Name) +
-                size(Type) +
-                length("\r\nContent-Disposition: attachment; filename=\"\"") +
-                length("\r\nContent-Type: ") +
-                length("\r\nContent-Length: ") +
-                case Encoding of
-                identity ->
-                    0;
-                 _ ->
-                    length(atom_to_list(Encoding)) +
-                    length("\r\nContent-Encoding: ")
-                end
-            end
-        end, 0, Atts),
-    if AttsSize == 0 ->
-        {<<"application/json">>, iolist_size(JsonBytes)};
-    true ->
-        {<<"multipart/related; boundary=\"", Boundary/binary, "\"">>,
-            2 + % "--"
-            size(Boundary) +
-            36 + % "\r\ncontent-type: application/json\r\n\r\n"
-            iolist_size(JsonBytes) +
-            4 + % "\r\n--"
-            size(Boundary) +
-            + AttsSize +
-            2 % "--"
-            }
-    end.
-
-doc_to_multi_part_stream(Boundary, JsonBytes, Atts, WriteFun,
-    SendEncodedAtts) ->
-    case lists:any(fun(#att{data=Data})-> Data /= stub end, Atts) of
-    true ->
-        WriteFun([<<"--", Boundary/binary,
-                "\r\nContent-Type: application/json\r\n\r\n">>,
-                JsonBytes, <<"\r\n--", Boundary/binary>>]),
-        atts_to_mp(Atts, Boundary, WriteFun, SendEncodedAtts);
-    false ->
-        WriteFun(JsonBytes)
-    end.
-
-atts_to_mp([], _Boundary, WriteFun, _SendEncAtts) ->
-    WriteFun(<<"--">>);
-atts_to_mp([#att{data=stub} | RestAtts], Boundary, WriteFun,
-        SendEncodedAtts) ->
-    atts_to_mp(RestAtts, Boundary, WriteFun, SendEncodedAtts);
-atts_to_mp([Att | RestAtts], Boundary, WriteFun,
-        SendEncodedAtts)  ->
-    #att{
-        name=Name,
-        att_len=AttLen,
-        disk_len=DiskLen,
-        type=Type,
-        encoding=Encoding
-    } = Att,
-
-    % write headers
-    LengthBin = case SendEncodedAtts of
-    true -> list_to_binary(integer_to_list(AttLen));
-    false -> list_to_binary(integer_to_list(DiskLen))
-    end,
-    WriteFun(<<"\r\nContent-Disposition: attachment; filename=\"", Name/binary, "\"">>),
-    WriteFun(<<"\r\nContent-Type: ", Type/binary>>),
-    WriteFun(<<"\r\nContent-Length: ", LengthBin/binary>>),
-    case Encoding of
-    identity ->
-        ok;
-    _ ->
-        EncodingBin = atom_to_binary(Encoding, latin1),
-        WriteFun(<<"\r\nContent-Encoding: ", EncodingBin/binary>>)
-    end,
-
-    % write data
-    WriteFun(<<"\r\n\r\n">>),
-    AttFun = case SendEncodedAtts of
-    false ->
-        fun att_foldl_decode/3;
-    true ->
-        fun att_foldl/3
-    end,
-    AttFun(Att, fun(Data, _) -> WriteFun(Data) end, ok),
-    WriteFun(<<"\r\n--", Boundary/binary>>),
-    atts_to_mp(RestAtts, Boundary, WriteFun, SendEncodedAtts).
-
-
-doc_from_multi_part_stream(ContentType, DataFun) ->
-    Parent = self(),
-    Parser = spawn_link(fun() ->
-        {<<"--",_/binary>>, _, _} = couch_httpd:parse_multipart_request(
-            ContentType, DataFun,
-            fun(Next) -> mp_parse_doc(Next, []) end),
-        unlink(Parent),
-        Parent ! {self(), finished}
-        end),
-    Ref = make_ref(),
-    Parser ! {get_doc_bytes, Ref, self()},
-    receive
-    {doc_bytes, Ref, DocBytes} ->
-        Doc = from_json_obj(?JSON_DECODE(DocBytes)),
-        % go through the attachments looking for 'follows' in the data,
-        % replace with function that reads the data from MIME stream.
-        ReadAttachmentDataFun = fun() ->
-            Parser ! {get_bytes, Ref, self()},
-            receive {bytes, Ref, Bytes} -> Bytes end
-        end,
-        Atts2 = lists:map(
-            fun(#att{data=follows}=A) ->
-                A#att{data=ReadAttachmentDataFun};
-            (A) ->
-                A
-            end, Doc#doc.atts),
-        WaitFun = fun() ->
-            receive {Parser, finished} -> ok end,
-            erlang:put(mochiweb_request_recv, true)
-        end,
-        {ok, Doc#doc{atts=Atts2}, WaitFun, Parser}
-    end.
-
-mp_parse_doc({headers, H}, []) ->
-    case couch_util:get_value("content-type", H) of
-    {"application/json", _} ->
-        fun (Next) ->
-            mp_parse_doc(Next, [])
-        end
-    end;
-mp_parse_doc({body, Bytes}, AccBytes) ->
-    fun (Next) ->
-        mp_parse_doc(Next, [Bytes | AccBytes])
-    end;
-mp_parse_doc(body_end, AccBytes) ->
-    receive {get_doc_bytes, Ref, From} ->
-        From ! {doc_bytes, Ref, lists:reverse(AccBytes)}
-    end,
-    fun mp_parse_atts/1.
-
-mp_parse_atts(eof) ->
-    ok;
-mp_parse_atts({headers, _H}) ->
-    fun mp_parse_atts/1;
-mp_parse_atts({body, Bytes}) ->
-    receive {get_bytes, Ref, From} ->
-        From ! {bytes, Ref, Bytes}
-    end,
-    fun mp_parse_atts/1;
-mp_parse_atts(body_end) ->
-    fun mp_parse_atts/1.
-
-
-abort_multi_part_stream(Parser) ->
-    abort_multi_part_stream(Parser, erlang:monitor(process, Parser)).
-
-abort_multi_part_stream(Parser, MonRef) ->
-    case is_process_alive(Parser) of
-    true ->
-        Parser ! {get_bytes, nil, self()},
-        receive
-        {bytes, nil, _Bytes} ->
-             abort_multi_part_stream(Parser, MonRef);
-        {'DOWN', MonRef, _, _, _} ->
-             ok
-        end;
-    false ->
-        erlang:demonitor(MonRef, [flush])
-    end.
-
-
-with_ejson_body(#doc{body = Body} = Doc) when is_binary(Body) ->
-    Doc#doc{body = couch_compress:decompress(Body)};
-with_ejson_body(#doc{body = {_}} = Doc) ->
-    Doc.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_ejson_compare.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_ejson_compare.erl b/apps/couch/src/couch_ejson_compare.erl
deleted file mode 100644
index f46ec35..0000000
--- a/apps/couch/src/couch_ejson_compare.erl
+++ /dev/null
@@ -1,81 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_ejson_compare).
-
--export([less/2, less_json_ids/2, less_json/2]).
-
-less_json_ids({JsonA, IdA}, {JsonB, IdB}) ->
-    case less(JsonA, JsonB) of
-    0 ->
-        IdA < IdB;
-    Result ->
-        Result < 0
-    end.
-
-less_json(A,B) ->
-    less(A, B) < 0.
-
-less(A,A)                                 -> 0;
-
-less(A,B) when is_atom(A), is_atom(B)     -> atom_sort(A) - atom_sort(B);
-less(A,_) when is_atom(A)                 -> -1;
-less(_,B) when is_atom(B)                 -> 1;
-
-less(A,B) when is_number(A), is_number(B) -> A - B;
-less(A,_) when is_number(A)               -> -1;
-less(_,B) when is_number(B)               -> 1;
-
-less(A,B) when is_binary(A), is_binary(B) -> couch_collate:collate(A,B);
-less(A,_) when is_binary(A)               -> -1;
-less(_,B) when is_binary(B)               -> 1;
-
-less(A,B) when is_list(A), is_list(B)     -> less_list(A,B);
-less(A,_) when is_list(A)                 -> -1;
-less(_,B) when is_list(B)                 -> 1;
-
-less({A},{B}) when is_list(A), is_list(B) -> less_props(A,B);
-less({A},_) when is_list(A)               -> -1;
-less(_,{B}) when is_list(B)               -> 1.
-
-atom_sort(null) -> 1;
-atom_sort(false) -> 2;
-atom_sort(true) -> 3.
-
-less_props([], [_|_]) ->
-    -1;
-less_props(_, []) ->
-    1;
-less_props([{AKey, AValue}|RestA], [{BKey, BValue}|RestB]) ->
-    case couch_collate:collate(AKey, BKey) of
-    0 ->
-        case less(AValue, BValue) of
-        0 ->
-            less_props(RestA, RestB);
-        Result ->
-            Result
-        end;
-    Result ->
-        Result
-    end.
-
-less_list([], [_|_]) ->
-    -1;
-less_list(_, []) ->
-    1;
-less_list([A|RestA], [B|RestB]) ->
-    case less(A,B) of
-    0 ->
-        less_list(RestA, RestB);
-    Result ->
-        Result
-    end.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_event_sup.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_event_sup.erl b/apps/couch/src/couch_event_sup.erl
deleted file mode 100644
index 07c4879..0000000
--- a/apps/couch/src/couch_event_sup.erl
+++ /dev/null
@@ -1,73 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
-%% The purpose of this module is to allow event handlers to particpate in Erlang
-%% supervisor trees. It provide a monitorable process that crashes if the event
-%% handler fails. The process, when shutdown, deregisters the event handler.
-
--module(couch_event_sup).
--behaviour(gen_server).
-
--include("couch_db.hrl").
-
--export([start_link/3,start_link/4, stop/1]).
--export([init/1, terminate/2, handle_call/3, handle_cast/2, handle_info/2,code_change/3]).
-
-%
-% Instead calling the
-% ok = gen_event:add_sup_handler(error_logger, my_log, Args)
-%
-% do this:
-% {ok, LinkedPid} = couch_event_sup:start_link(error_logger, my_log, Args)
-%
-% The benefit is the event is now part of the process tree, and can be
-% started, restarted and shutdown consistently like the rest of the server
-% components.
-%
-% And now if the "event" crashes, the supervisor is notified and can restart
-% the event handler.
-%
-% Use this form to named process:
-% {ok, LinkedPid} = couch_event_sup:start_link({local, my_log}, error_logger, my_log, Args)
-%
-
-start_link(EventMgr, EventHandler, Args) ->
-    gen_server:start_link(couch_event_sup, {EventMgr, EventHandler, Args}, []).
-
-start_link(ServerName, EventMgr, EventHandler, Args) ->
-    gen_server:start_link(ServerName, couch_event_sup, {EventMgr, EventHandler, Args}, []).
-
-stop(Pid) ->
-    gen_server:cast(Pid, stop).
-
-init({EventMgr, EventHandler, Args}) ->
-    case gen_event:add_sup_handler(EventMgr, EventHandler, Args) of
-    ok ->
-        {ok, {EventMgr, EventHandler}};
-    {stop, Error} ->
-        {stop, Error}
-    end.
-
-terminate(_Reason, _State) ->
-    ok.
-
-handle_call(_Whatever, _From, State) ->
-    {ok, State}.
-
-handle_cast(stop, State) ->
-    {stop, normal, State}.
-
-handle_info({gen_event_EXIT, _Handler, Reason}, State) ->
-    {stop, Reason, State}.
-
-code_change(_OldVsn, State, _Extra) ->
-    {ok, State}.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_external_manager.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_external_manager.erl b/apps/couch/src/couch_external_manager.erl
deleted file mode 100644
index 0c66ef8..0000000
--- a/apps/couch/src/couch_external_manager.erl
+++ /dev/null
@@ -1,101 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_external_manager).
--behaviour(gen_server).
-
--export([start_link/0, execute/2, config_change/2]).
--export([init/1, terminate/2, code_change/3, handle_call/3, handle_cast/2, handle_info/2]).
-
--include("couch_db.hrl").
-
-start_link() ->
-    gen_server:start_link({local, couch_external_manager},
-        couch_external_manager, [], []).
-
-execute(UrlName, JsonReq) ->
-    Pid = gen_server:call(couch_external_manager, {get, UrlName}),
-    case Pid of
-    {error, Reason} ->
-        Reason;
-    _ ->
-        couch_external_server:execute(Pid, JsonReq)
-    end.
-
-config_change("external", UrlName) ->
-    gen_server:call(couch_external_manager, {config, UrlName}).
-
-% gen_server API
-
-init([]) ->
-    process_flag(trap_exit, true),
-    Handlers = ets:new(couch_external_manager_handlers, [set, private]),
-    couch_config:register(fun ?MODULE:config_change/2),
-    {ok, Handlers}.
-
-terminate(_Reason, Handlers) ->
-    ets:foldl(fun({_UrlName, Pid}, nil) ->
-        couch_external_server:stop(Pid),
-        nil
-    end, nil, Handlers),
-    ok.
-
-handle_call({get, UrlName}, _From, Handlers) ->
-    case ets:lookup(Handlers, UrlName) of
-    [] ->
-        case couch_config:get("external", UrlName, nil) of
-        nil ->
-            Msg = lists:flatten(
-                io_lib:format("No server configured for ~p.", [UrlName])),
-            {reply, {error, {unknown_external_server, ?l2b(Msg)}}, Handlers};
-        Command ->
-            {ok, NewPid} = couch_external_server:start_link(UrlName, Command),
-            true = ets:insert(Handlers, {UrlName, NewPid}),
-            {reply, NewPid, Handlers}
-        end;
-    [{UrlName, Pid}] ->
-        {reply, Pid, Handlers}
-    end;
-handle_call({config, UrlName}, _From, Handlers) ->
-    % A newly added handler and a handler that had it's command
-    % changed are treated exactly the same.
-
-    % Shutdown the old handler.
-    case ets:lookup(Handlers, UrlName) of
-    [{UrlName, Pid}] ->
-        couch_external_server:stop(Pid);
-    [] ->
-        ok
-    end,
-    % Wait for next request to boot the handler.
-    {reply, ok, Handlers}.
-
-handle_cast(_Whatever, State) ->
-    {noreply, State}.
-
-handle_info({'EXIT', Pid, normal}, Handlers) ->
-    ?LOG_INFO("EXTERNAL: Server ~p terminated normally", [Pid]),
-    % The process terminated normally without us asking - Remove Pid from the
-    % handlers table so we don't attempt to reuse it
-    ets:match_delete(Handlers, {'_', Pid}),
-    {noreply, Handlers};
-
-handle_info({'EXIT', Pid, Reason}, Handlers) ->
-    ?LOG_INFO("EXTERNAL: Server ~p died. (reason: ~p)", [Pid, Reason]),
-    % Remove Pid from the handlers table so we don't try closing
-    % it a second time in terminate/2.
-    ets:match_delete(Handlers, {'_', Pid}),
-    {stop, normal, Handlers}.
-
-code_change(_OldVsn, State, _Extra) ->
-    {ok, State}.
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_external_server.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_external_server.erl b/apps/couch/src/couch_external_server.erl
deleted file mode 100644
index b52c7ff..0000000
--- a/apps/couch/src/couch_external_server.erl
+++ /dev/null
@@ -1,70 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_external_server).
--behaviour(gen_server).
-
--export([start_link/2, stop/1, execute/2]).
--export([init/1, terminate/2, handle_call/3, handle_cast/2, handle_info/2, code_change/3]).
-
--include("couch_db.hrl").
-
-% External API
-
-start_link(Name, Command) ->
-    gen_server:start_link(couch_external_server, [Name, Command], []).
-
-stop(Pid) ->
-    gen_server:cast(Pid, stop).
-
-execute(Pid, JsonReq) ->
-    {json, Json} = gen_server:call(Pid, {execute, JsonReq}, infinity),
-    ?JSON_DECODE(Json).
-
-% Gen Server Handlers
-
-init([Name, Command]) ->
-    ?LOG_INFO("EXTERNAL: Starting process for: ~s", [Name]),
-    ?LOG_INFO("COMMAND: ~s", [Command]),
-    process_flag(trap_exit, true),
-    Timeout = list_to_integer(couch_config:get("couchdb", "os_process_timeout",
-        "5000")),
-    {ok, Pid} = couch_os_process:start_link(Command, [{timeout, Timeout}]),
-    couch_config:register(fun("couchdb", "os_process_timeout", NewTimeout) ->
-        couch_os_process:set_timeout(Pid, list_to_integer(NewTimeout))
-    end),
-    {ok, {Name, Command, Pid}}.
-
-terminate(_Reason, {_Name, _Command, Pid}) ->
-    couch_os_process:stop(Pid),
-    ok.
-
-handle_call({execute, JsonReq}, _From, {Name, Command, Pid}) ->
-    {reply, couch_os_process:prompt(Pid, JsonReq), {Name, Command, Pid}}.
-
-handle_info({'EXIT', _Pid, normal}, State) ->
-    {noreply, State};
-handle_info({'EXIT', Pid, Reason}, {Name, Command, Pid}) ->
-    ?LOG_INFO("EXTERNAL: Process for ~s exiting. (reason: ~w)", [Name, Reason]),
-    {stop, Reason, {Name, Command, Pid}}.
-
-handle_cast(stop, {Name, Command, Pid}) ->
-    ?LOG_INFO("EXTERNAL: Shutting down ~s", [Name]),
-    exit(Pid, normal),
-    {stop, normal, {Name, Command, Pid}};
-handle_cast(_Whatever, State) ->
-    {noreply, State}.
-
-code_change(_OldVsn, State, _Extra) ->
-    {ok, State}.
-
-


[43/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_native_process.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_native_process.erl b/apps/couch/src/couch_native_process.erl
deleted file mode 100644
index 5a32e75..0000000
--- a/apps/couch/src/couch_native_process.erl
+++ /dev/null
@@ -1,409 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License");
-% you may not use this file except in compliance with the License.
-%
-% You may obtain a copy of the License at
-% http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing,
-% software distributed under the License is distributed on an
-% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
-% either express or implied.
-%
-% See the License for the specific language governing permissions
-% and limitations under the License.
-%
-% This file drew much inspiration from erlview, which was written by and
-% copyright Michael McDaniel [http://autosys.us], and is also under APL 2.0
-%
-%
-% This module provides the smallest possible native view-server.
-% With this module in-place, you can add the following to your couch INI files:
-%  [native_query_servers]
-%  erlang={couch_native_process, start_link, []}
-%
-% Which will then allow following example map function to be used:
-%
-%  fun({Doc}) ->
-%    % Below, we emit a single record - the _id as key, null as value
-%    DocId = couch_util:get_value(<<"_id">>, Doc, null),
-%    Emit(DocId, null)
-%  end.
-%
-% which should be roughly the same as the javascript:
-%    emit(doc._id, null);
-%
-% This module exposes enough functions such that a native erlang server can
-% act as a fully-fleged view server, but no 'helper' functions specifically
-% for simplifying your erlang view code.  It is expected other third-party
-% extensions will evolve which offer useful layers on top of this view server
-% to help simplify your view code.
--module(couch_native_process).
--behaviour(gen_server).
-
--export([start_link/0,init/1,terminate/2,handle_call/3,handle_cast/2,code_change/3,
-         handle_info/2]).
--export([set_timeout/2, prompt/2]).
-
--define(STATE, native_proc_state).
--record(evstate, {ddocs, funs=[], query_config=[], list_pid=nil, timeout=5000}).
-
--include("couch_db.hrl").
-
-start_link() ->
-    gen_server:start_link(?MODULE, [], []).
-
-% this is a bit messy, see also couch_query_servers handle_info
-% stop(_Pid) ->
-%     ok.
-
-set_timeout(Pid, TimeOut) ->
-    gen_server:call(Pid, {set_timeout, TimeOut}).
-
-prompt(Pid, Data) when is_list(Data) ->
-    gen_server:call(Pid, {prompt, Data}).
-
-% gen_server callbacks
-init([]) ->
-    {ok, #evstate{ddocs=dict:new()}}.
-
-handle_call({set_timeout, TimeOut}, _From, State) ->
-    {reply, ok, State#evstate{timeout=TimeOut}};
-
-handle_call({prompt, Data}, _From, State) ->
-    ?LOG_DEBUG("Prompt native qs: ~s",[?JSON_ENCODE(Data)]),
-    {NewState, Resp} = try run(State, to_binary(Data)) of
-        {S, R} -> {S, R}
-        catch
-            throw:{error, Why} ->
-                {State, [<<"error">>, Why, Why]}
-        end,
-
-    case Resp of
-        {error, Reason} ->
-            Msg = io_lib:format("couch native server error: ~p", [Reason]),
-            {reply, [<<"error">>, <<"native_query_server">>, list_to_binary(Msg)], NewState};
-        [<<"error">> | Rest] ->
-            % Msg = io_lib:format("couch native server error: ~p", [Rest]),
-            % TODO: markh? (jan)
-            {reply, [<<"error">> | Rest], NewState};
-        [<<"fatal">> | Rest] ->
-            % Msg = io_lib:format("couch native server error: ~p", [Rest]),
-            % TODO: markh? (jan)
-            {stop, fatal, [<<"error">> | Rest], NewState};
-        Resp ->
-            {reply, Resp, NewState}
-    end.
-
-handle_cast(foo, State) -> {noreply, State}.
-handle_info({'EXIT',_,normal}, State) -> {noreply, State};
-handle_info({'EXIT',_,Reason}, State) ->
-    {stop, Reason, State}.
-terminate(_Reason, _State) -> ok.
-code_change(_OldVersion, State, _Extra) -> {ok, State}.
-
-run(#evstate{list_pid=Pid}=State, [<<"list_row">>, Row]) when is_pid(Pid) ->
-    Pid ! {self(), list_row, Row},
-    receive
-        {Pid, chunks, Data} ->
-            {State, [<<"chunks">>, Data]};
-        {Pid, list_end, Data} ->
-            receive
-                {'EXIT', Pid, normal} -> ok
-            after State#evstate.timeout ->
-                throw({timeout, list_cleanup})
-            end,
-            process_flag(trap_exit, erlang:get(do_trap)),
-            {State#evstate{list_pid=nil}, [<<"end">>, Data]}
-    after State#evstate.timeout ->
-        throw({timeout, list_row})
-    end;
-run(#evstate{list_pid=Pid}=State, [<<"list_end">>]) when is_pid(Pid) ->
-    Pid ! {self(), list_end},
-    Resp =
-    receive
-        {Pid, list_end, Data} ->
-            receive
-                {'EXIT', Pid, normal} -> ok
-            after State#evstate.timeout ->
-                throw({timeout, list_cleanup})
-            end,
-            [<<"end">>, Data]
-    after State#evstate.timeout ->
-        throw({timeout, list_end})
-    end,
-    process_flag(trap_exit, erlang:get(do_trap)),
-    {State#evstate{list_pid=nil}, Resp};
-run(#evstate{list_pid=Pid}=State, _Command) when is_pid(Pid) ->
-    {State, [<<"error">>, list_error, list_error]};
-run(#evstate{ddocs=DDocs}, [<<"reset">>]) ->
-    {#evstate{ddocs=DDocs}, true};
-run(#evstate{ddocs=DDocs}, [<<"reset">>, QueryConfig]) ->
-    {#evstate{ddocs=DDocs, query_config=QueryConfig}, true};
-run(#evstate{funs=Funs}=State, [<<"add_fun">> , BinFunc]) ->
-    FunInfo = makefun(State, BinFunc),
-    {State#evstate{funs=Funs ++ [FunInfo]}, true};
-run(State, [<<"map_doc">> , Doc]) ->
-    Resp = lists:map(fun({Sig, Fun}) ->
-        erlang:put(Sig, []),
-        Fun(Doc),
-        lists:reverse(erlang:get(Sig))
-    end, State#evstate.funs),
-    {State, Resp};
-run(State, [<<"reduce">>, Funs, KVs]) ->
-    {Keys, Vals} =
-    lists:foldl(fun([K, V], {KAcc, VAcc}) ->
-        {[K | KAcc], [V | VAcc]}
-    end, {[], []}, KVs),
-    Keys2 = lists:reverse(Keys),
-    Vals2 = lists:reverse(Vals),
-    {State, catch reduce(State, Funs, Keys2, Vals2, false)};
-run(State, [<<"rereduce">>, Funs, Vals]) ->
-    {State, catch reduce(State, Funs, null, Vals, true)};
-run(#evstate{ddocs=DDocs}=State, [<<"ddoc">>, <<"new">>, DDocId, DDoc]) ->
-    DDocs2 = store_ddoc(DDocs, DDocId, DDoc),
-    {State#evstate{ddocs=DDocs2}, true};
-run(#evstate{ddocs=DDocs}=State, [<<"ddoc">>, DDocId | Rest]) ->
-    DDoc = load_ddoc(DDocs, DDocId),
-    ddoc(State, DDoc, Rest);
-run(_, Unknown) ->
-    ?LOG_ERROR("Native Process: Unknown command: ~p~n", [Unknown]),
-    throw({error, unknown_command}).
-    
-ddoc(State, {DDoc}, [FunPath, Args]) ->
-    % load fun from the FunPath
-    BFun = lists:foldl(fun
-        (Key, {Props}) when is_list(Props) ->
-            couch_util:get_value(Key, Props, nil);
-        (_Key, Fun) when is_binary(Fun) ->
-            Fun;
-        (_Key, nil) ->
-            throw({error, not_found});
-        (_Key, _Fun) ->
-            throw({error, malformed_ddoc})
-        end, {DDoc}, FunPath),
-    ddoc(State, makefun(State, BFun, {DDoc}), FunPath, Args).
-
-ddoc(State, {_, Fun}, [<<"validate_doc_update">>], Args) ->
-    {State, (catch apply(Fun, Args))};
-ddoc(State, {_, Fun}, [<<"filters">>|_], [Docs, Req]) ->
-    FilterFunWrapper = fun(Doc) ->
-        case catch Fun(Doc, Req) of
-        true -> true;
-        false -> false;
-        {'EXIT', Error} -> ?LOG_ERROR("~p", [Error])
-        end
-    end,
-    Resp = lists:map(FilterFunWrapper, Docs),
-    {State, [true, Resp]};
-ddoc(State, {_, Fun}, [<<"shows">>|_], Args) ->
-    Resp = case (catch apply(Fun, Args)) of
-        FunResp when is_list(FunResp) ->
-            FunResp;
-        {FunResp} ->
-            [<<"resp">>, {FunResp}];
-        FunResp ->
-            FunResp
-    end,
-    {State, Resp};
-ddoc(State, {_, Fun}, [<<"updates">>|_], Args) ->
-    Resp = case (catch apply(Fun, Args)) of
-        [JsonDoc, JsonResp]  ->
-            [<<"up">>, JsonDoc, JsonResp]
-    end,
-    {State, Resp};
-ddoc(State, {Sig, Fun}, [<<"lists">>|_], Args) ->
-    Self = self(),
-    SpawnFun = fun() ->
-        LastChunk = (catch apply(Fun, Args)),
-        case start_list_resp(Self, Sig) of
-            started ->
-                receive
-                    {Self, list_row, _Row} -> ignore;
-                    {Self, list_end} -> ignore
-                after State#evstate.timeout ->
-                    throw({timeout, list_cleanup_pid})
-                end;
-            _ ->
-                ok
-        end,
-        LastChunks =
-        case erlang:get(Sig) of
-            undefined -> [LastChunk];
-            OtherChunks -> [LastChunk | OtherChunks]
-        end,
-        Self ! {self(), list_end, lists:reverse(LastChunks)}
-    end,
-    erlang:put(do_trap, process_flag(trap_exit, true)),
-    Pid = spawn_link(SpawnFun),
-    Resp =
-    receive
-        {Pid, start, Chunks, JsonResp} ->
-            [<<"start">>, Chunks, JsonResp]
-    after State#evstate.timeout ->
-        throw({timeout, list_start})
-    end,
-    {State#evstate{list_pid=Pid}, Resp}.
-
-store_ddoc(DDocs, DDocId, DDoc) ->
-    dict:store(DDocId, DDoc, DDocs).
-load_ddoc(DDocs, DDocId) ->
-    try dict:fetch(DDocId, DDocs) of
-        {DDoc} -> {DDoc}
-    catch
-        _:_Else -> throw({error, ?l2b(io_lib:format("Native Query Server missing DDoc with Id: ~s",[DDocId]))})
-    end.
-
-bindings(State, Sig) ->
-    bindings(State, Sig, nil).
-bindings(State, Sig, DDoc) ->
-    Self = self(),
-
-    Log = fun(Msg) ->
-        ?LOG_INFO(Msg, [])
-    end,
-
-    Emit = fun(Id, Value) ->
-        Curr = erlang:get(Sig),
-        erlang:put(Sig, [[Id, Value] | Curr])
-    end,
-
-    Start = fun(Headers) ->
-        erlang:put(list_headers, Headers)
-    end,
-
-    Send = fun(Chunk) ->
-        Curr =
-        case erlang:get(Sig) of
-            undefined -> [];
-            Else -> Else
-        end,
-        erlang:put(Sig, [Chunk | Curr])
-    end,
-
-    GetRow = fun() ->
-        case start_list_resp(Self, Sig) of
-            started ->
-                ok;
-            _ ->
-                Chunks =
-                case erlang:get(Sig) of
-                    undefined -> [];
-                    CurrChunks -> CurrChunks
-                end,
-                Self ! {self(), chunks, lists:reverse(Chunks)}
-        end,
-        erlang:put(Sig, []),
-        receive
-            {Self, list_row, Row} -> Row;
-            {Self, list_end} -> nil
-        after State#evstate.timeout ->
-            throw({timeout, list_pid_getrow})
-        end
-    end,
-   
-    FoldRows = fun(Fun, Acc) -> foldrows(GetRow, Fun, Acc) end,
-
-    Bindings = [
-        {'Log', Log},
-        {'Emit', Emit},
-        {'Start', Start},
-        {'Send', Send},
-        {'GetRow', GetRow},
-        {'FoldRows', FoldRows}
-    ],
-    case DDoc of
-        {_Props} ->
-            Bindings ++ [{'DDoc', DDoc}];
-        _Else -> Bindings
-    end.
-
-% thanks to erlview, via:
-% http://erlang.org/pipermail/erlang-questions/2003-November/010544.html
-makefun(State, Source) ->
-    Sig = couch_util:md5(Source),
-    BindFuns = bindings(State, Sig),
-    {Sig, makefun(State, Source, BindFuns)}.
-makefun(State, Source, {DDoc}) ->
-    Sig = couch_util:md5(lists:flatten([Source, term_to_binary(DDoc)])),
-    BindFuns = bindings(State, Sig, {DDoc}),
-    {Sig, makefun(State, Source, BindFuns)};
-makefun(_State, Source, BindFuns) when is_list(BindFuns) ->
-    FunStr = binary_to_list(Source),
-    {ok, Tokens, _} = erl_scan:string(FunStr),
-    Form = case (catch erl_parse:parse_exprs(Tokens)) of
-        {ok, [ParsedForm]} ->
-            ParsedForm;
-        {error, {LineNum, _Mod, [Mesg, Params]}}=Error ->
-            io:format(standard_error, "Syntax error on line: ~p~n", [LineNum]),
-            io:format(standard_error, "~s~p~n", [Mesg, Params]),
-            throw(Error)
-    end,
-    Bindings = lists:foldl(fun({Name, Fun}, Acc) ->
-        erl_eval:add_binding(Name, Fun, Acc)
-    end, erl_eval:new_bindings(), BindFuns),
-    {value, Fun, _} = erl_eval:expr(Form, Bindings),
-    Fun.
-
-reduce(State, BinFuns, Keys, Vals, ReReduce) ->
-    Funs = case is_list(BinFuns) of
-        true ->
-            lists:map(fun(BF) -> makefun(State, BF) end, BinFuns);
-        _ ->
-            [makefun(State, BinFuns)]
-    end,
-    Reds = lists:map(fun({_Sig, Fun}) ->
-        Fun(Keys, Vals, ReReduce)
-    end, Funs),
-    [true, Reds].
-
-foldrows(GetRow, ProcRow, Acc) ->
-    case GetRow() of
-        nil ->
-            {ok, Acc};
-        Row ->
-            case (catch ProcRow(Row, Acc)) of
-                {ok, Acc2} ->
-                    foldrows(GetRow, ProcRow, Acc2);
-                {stop, Acc2} ->
-                    {ok, Acc2}
-            end
-    end.
-
-start_list_resp(Self, Sig) ->
-    case erlang:get(list_started) of
-        undefined ->
-            Headers =
-            case erlang:get(list_headers) of
-                undefined -> {[{<<"headers">>, {[]}}]};
-                CurrHdrs -> CurrHdrs
-            end,
-            Chunks =
-            case erlang:get(Sig) of
-                undefined -> [];
-                CurrChunks -> CurrChunks
-            end,
-            Self ! {self(), start, lists:reverse(Chunks), Headers},
-            erlang:put(list_started, true),
-            erlang:put(Sig, []),
-            started;
-        _ ->
-            ok
-    end.
-
-to_binary({Data}) ->
-    Pred = fun({Key, Value}) ->
-        {to_binary(Key), to_binary(Value)}
-    end,
-    {lists:map(Pred, Data)};
-to_binary(Data) when is_list(Data) ->
-    [to_binary(D) || D <- Data];
-to_binary(null) ->
-    null;
-to_binary(true) ->
-    true;
-to_binary(false) ->
-    false;
-to_binary(Data) when is_atom(Data) ->
-    list_to_binary(atom_to_list(Data));
-to_binary(Data) ->
-    Data.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_os_daemons.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_os_daemons.erl b/apps/couch/src/couch_os_daemons.erl
deleted file mode 100644
index cac031a..0000000
--- a/apps/couch/src/couch_os_daemons.erl
+++ /dev/null
@@ -1,374 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
--module(couch_os_daemons).
--behaviour(gen_server).
-
--export([start_link/0, info/0, info/1, config_change/2]).
-
--export([init/1, terminate/2, code_change/3]).
--export([handle_call/3, handle_cast/2, handle_info/2]).
-
--include("couch_db.hrl").
-
--record(daemon, {
-    port,
-    name,
-    cmd,
-    kill,
-    status=running,
-    cfg_patterns=[],
-    errors=[],
-    buf=[]
-}).
-
--define(PORT_OPTIONS, [stream, {line, 1024}, binary, exit_status, hide]).
--define(TIMEOUT, 5000).
-
-start_link() ->
-    gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
-
-info() ->
-    info([]).
-
-info(Options) ->
-    gen_server:call(?MODULE, {daemon_info, Options}).
-
-config_change(Section, Key) ->
-    gen_server:cast(?MODULE, {config_change, Section, Key}).
-
-init(_) ->
-    process_flag(trap_exit, true),
-    ok = couch_config:register(fun ?MODULE:config_change/2),
-    Table = ets:new(?MODULE, [protected, set, {keypos, #daemon.port}]),
-    reload_daemons(Table),
-    {ok, Table}.
-
-terminate(_Reason, Table) ->
-    [stop_port(D) || D <- ets:tab2list(Table)],
-    ok.
-
-handle_call({daemon_info, Options}, _From, Table) when is_list(Options) ->
-    case lists:member(table, Options) of
-        true ->
-            {reply, {ok, ets:tab2list(Table)}, Table};
-        _ ->
-            {reply, {ok, Table}, Table}
-    end;
-handle_call(Msg, From, Table) ->
-    ?LOG_ERROR("Unknown call message to ~p from ~p: ~p", [?MODULE, From, Msg]),
-    {stop, error, Table}.
-
-handle_cast({config_change, Sect, Key}, Table) ->
-    restart_daemons(Table, Sect, Key),
-    case Sect of
-        "os_daemons" -> reload_daemons(Table);
-        _ -> ok
-    end,
-    {noreply, Table};
-handle_cast(stop, Table) ->
-    {stop, normal, Table};
-handle_cast(Msg, Table) ->
-    ?LOG_ERROR("Unknown cast message to ~p: ~p", [?MODULE, Msg]),
-    {stop, error, Table}.
-
-handle_info({'EXIT', Port, Reason}, Table) ->
-    case ets:lookup(Table, Port) of
-        [] ->
-            ?LOG_INFO("Port ~p exited after stopping: ~p~n", [Port, Reason]);
-        [#daemon{status=stopping}] ->
-            true = ets:delete(Table, Port);
-        [#daemon{name=Name, status=restarting}=D] ->
-            ?LOG_INFO("Daemon ~P restarting after config change.", [Name]),
-            true = ets:delete(Table, Port),
-            {ok, Port2} = start_port(D#daemon.cmd),
-            true = ets:insert(Table, D#daemon{
-                port=Port2, status=running, kill=undefined, buf=[]
-            });
-        [#daemon{name=Name, status=halted}] ->
-            ?LOG_ERROR("Halted daemon process: ~p", [Name]);
-        [D] ->
-            ?LOG_ERROR("Invalid port state at exit: ~p", [D])
-    end,
-    {noreply, Table};
-handle_info({Port, closed}, Table) ->
-    handle_info({Port, {exit_status, closed}}, Table);
-handle_info({Port, {exit_status, Status}}, Table) ->
-    case ets:lookup(Table, Port) of
-        [] ->
-            ?LOG_ERROR("Unknown port ~p exiting ~p", [Port, Status]),
-            {stop, {error, unknown_port_died, Status}, Table};
-        [#daemon{name=Name, status=restarting}=D] ->
-            ?LOG_INFO("Daemon ~P restarting after config change.", [Name]),
-            true = ets:delete(Table, Port),
-            {ok, Port2} = start_port(D#daemon.cmd),
-            true = ets:insert(Table, D#daemon{
-                port=Port2, status=running, kill=undefined, buf=[]
-            }),
-            {noreply, Table};
-        [#daemon{status=stopping}=D] ->
-            % The configuration changed and this daemon is no
-            % longer needed.
-            ?LOG_DEBUG("Port ~p shut down.", [D#daemon.name]),
-            true = ets:delete(Table, Port),
-            {noreply, Table};
-        [D] ->
-            % Port died for unknown reason. Check to see if it's
-            % died too many times or if we should boot it back up.
-            case should_halt([now() | D#daemon.errors]) of
-                {true, _} ->
-                    % Halting the process. We won't try and reboot
-                    % until the configuration changes.
-                    Fmt = "Daemon ~p halted with exit_status ~p",
-                    ?LOG_ERROR(Fmt, [D#daemon.name, Status]),
-                    D2 = D#daemon{status=halted, errors=nil, buf=nil},
-                    true = ets:insert(Table, D2),
-                    {noreply, Table};
-                {false, Errors} ->
-                    % We're guessing it was a random error, this daemon
-                    % has behaved so we'll give it another chance.
-                    Fmt = "Daemon ~p is being rebooted after exit_status ~p",
-                    ?LOG_INFO(Fmt, [D#daemon.name, Status]),
-                    true = ets:delete(Table, Port),
-                    {ok, Port2} = start_port(D#daemon.cmd),
-                    true = ets:insert(Table, D#daemon{
-                        port=Port2, status=running, kill=undefined,
-                                                errors=Errors, buf=[]
-                    }),
-                    {noreply, Table}
-            end;
-        _Else ->
-            throw(error)
-    end;
-handle_info({Port, {data, {noeol, Data}}}, Table) ->
-    [#daemon{buf=Buf}=D] = ets:lookup(Table, Port),
-    true = ets:insert(Table, D#daemon{buf=[Data | Buf]}),
-    {noreply, Table};
-handle_info({Port, {data, {eol, Data}}}, Table) ->
-    [#daemon{buf=Buf}=D] = ets:lookup(Table, Port),
-    Line = lists:reverse(Buf, Data),
-    % The first line echoed back is the kill command
-    % for when we go to get rid of the port. Lines after
-    % that are considered part of the stdio API.
-    case D#daemon.kill of
-        undefined ->
-            true = ets:insert(Table, D#daemon{kill=?b2l(Line), buf=[]});
-        _Else ->
-            D2 = case (catch ?JSON_DECODE(Line)) of
-                {invalid_json, Rejected} ->
-                    ?LOG_ERROR("Ignoring OS daemon request: ~p", [Rejected]),
-                    D;
-                JSON ->
-                    {ok, D3} = handle_port_message(D, JSON),
-                    D3
-            end,
-            true = ets:insert(Table, D2#daemon{buf=[]})
-    end,
-    {noreply, Table};
-handle_info({Port, Error}, Table) ->
-    ?LOG_ERROR("Unexpectd message from port ~p: ~p", [Port, Error]),
-    stop_port(Port),
-    [D] = ets:lookup(Table, Port),
-    true = ets:insert(Table, D#daemon{status=restarting, buf=nil}),
-    {noreply, Table};
-handle_info(Msg, Table) ->
-    ?LOG_ERROR("Unexpected info message to ~p: ~p", [?MODULE, Msg]),
-    {stop, error, Table}.
-
-code_change(_OldVsn, State, _Extra) ->
-    {ok, State}.
-
-% Internal API
-
-%
-% Port management helpers
-%
-
-start_port(Command) ->
-    start_port(Command, []).
-
-start_port(Command, EnvPairs) ->
-    PrivDir = couch_util:priv_dir(),
-    Spawnkiller = filename:join(PrivDir, "couchspawnkillable"),
-    Opts = case lists:keytake(env, 1, ?PORT_OPTIONS) of
-        false ->
-            ?PORT_OPTIONS ++ [ {env,EnvPairs} ];
-        {value, {env,OldPairs}, SubOpts} ->
-            AllPairs = lists:keymerge(1, EnvPairs, OldPairs),
-            SubOpts ++ [ {env,AllPairs} ]
-    end,
-    Port = open_port({spawn, Spawnkiller ++ " " ++ Command}, Opts),
-    {ok, Port}.
-
-
-stop_port(#daemon{port=Port, kill=undefined}=D) ->
-    ?LOG_ERROR("Stopping daemon without a kill command: ~p", [D#daemon.name]),
-    catch port_close(Port);
-stop_port(#daemon{port=Port}=D) ->
-    ?LOG_DEBUG("Stopping daemon: ~p", [D#daemon.name]),
-    os:cmd(D#daemon.kill),
-    catch port_close(Port).
-
-
-handle_port_message(#daemon{port=Port}=Daemon, [<<"get">>, Section]) ->
-    KVs = couch_config:get(Section),
-    Data = lists:map(fun({K, V}) -> {?l2b(K), ?l2b(V)} end, KVs),
-    Json = iolist_to_binary(?JSON_ENCODE({Data})),
-    port_command(Port, <<Json/binary, "\n">>),
-    {ok, Daemon};
-handle_port_message(#daemon{port=Port}=Daemon, [<<"get">>, Section, Key]) ->
-    Value = case couch_config:get(Section, Key, null) of
-        null -> null;
-        String -> ?l2b(String)
-    end,
-    Json = iolist_to_binary(?JSON_ENCODE(Value)),
-    port_command(Port, <<Json/binary, "\n">>),
-    {ok, Daemon};
-handle_port_message(Daemon, [<<"register">>, Sec]) when is_binary(Sec) ->
-    Patterns = lists:usort(Daemon#daemon.cfg_patterns ++ [{?b2l(Sec)}]),
-    {ok, Daemon#daemon{cfg_patterns=Patterns}};
-handle_port_message(Daemon, [<<"register">>, Sec, Key])
-                        when is_binary(Sec) andalso is_binary(Key) ->
-    Pattern = {?b2l(Sec), ?b2l(Key)},
-    Patterns = lists:usort(Daemon#daemon.cfg_patterns ++ [Pattern]),
-    {ok, Daemon#daemon{cfg_patterns=Patterns}};
-handle_port_message(#daemon{name=Name}=Daemon, [<<"log">>, Msg]) ->
-    handle_log_message(Name, Msg, <<"info">>),
-    {ok, Daemon};
-handle_port_message(#daemon{name=Name}=Daemon, [<<"log">>, Msg, {Opts}]) ->
-    Level = couch_util:get_value(<<"level">>, Opts, <<"info">>),
-    handle_log_message(Name, Msg, Level),
-    {ok, Daemon};
-handle_port_message(#daemon{name=Name}=Daemon, Else) ->
-    ?LOG_ERROR("Daemon ~p made invalid request: ~p", [Name, Else]),
-    {ok, Daemon}.
-
-
-handle_log_message(Name, Msg, _Level) when not is_binary(Msg) ->
-    ?LOG_ERROR("Invalid log message from daemon ~p: ~p", [Name, Msg]);
-handle_log_message(Name, Msg, <<"debug">>) ->
-    ?LOG_DEBUG("Daemon ~p :: ~s", [Name, ?b2l(Msg)]);
-handle_log_message(Name, Msg, <<"info">>) ->
-    ?LOG_INFO("Daemon ~p :: ~s", [Name, ?b2l(Msg)]);
-handle_log_message(Name, Msg, <<"error">>) ->
-    ?LOG_ERROR("Daemon: ~p :: ~s", [Name, ?b2l(Msg)]);
-handle_log_message(Name, Msg, Level) ->
-    ?LOG_ERROR("Invalid log level from daemon: ~p", [Level]),
-    ?LOG_INFO("Daemon: ~p :: ~s", [Name, ?b2l(Msg)]).
-
-%
-% Daemon management helpers
-%
-
-reload_daemons(Table) ->
-    % List of daemons we want to have running.
-    Configured = lists:sort(couch_config:get("os_daemons")),
-    
-    % Remove records for daemons that were halted.
-    MSpecHalted = #daemon{name='$1', cmd='$2', status=halted, _='_'},
-    Halted = lists:sort([{N, C} || [N, C] <- ets:match(Table, MSpecHalted)]),
-    ok = stop_os_daemons(Table, find_to_stop(Configured, Halted, [])),
-    
-    % Stop daemons that are running
-    % Start newly configured daemons
-    MSpecRunning = #daemon{name='$1', cmd='$2', status=running, _='_'},
-    Running = lists:sort([{N, C} || [N, C] <- ets:match(Table, MSpecRunning)]),
-    ok = stop_os_daemons(Table, find_to_stop(Configured, Running, [])),
-    ok = boot_os_daemons(Table, find_to_boot(Configured, Running, [])),
-    ok.
-
-
-restart_daemons(Table, Sect, Key) ->
-    restart_daemons(Table, Sect, Key, ets:first(Table)).
-
-restart_daemons(_, _, _, '$end_of_table') ->
-    ok;
-restart_daemons(Table, Sect, Key, Port) ->
-    [D] = ets:lookup(Table, Port),
-    HasSect = lists:member({Sect}, D#daemon.cfg_patterns),
-    HasKey = lists:member({Sect, Key}, D#daemon.cfg_patterns),
-    case HasSect or HasKey of
-        true ->
-            stop_port(D),
-            D2 = D#daemon{status=restarting, buf=nil},
-            true = ets:insert(Table, D2);
-        _ ->
-            ok
-    end,
-    restart_daemons(Table, Sect, Key, ets:next(Table, Port)).
-    
-
-stop_os_daemons(_Table, []) ->
-    ok;
-stop_os_daemons(Table, [{Name, Cmd} | Rest]) ->
-    [[Port]] = ets:match(Table, #daemon{port='$1', name=Name, cmd=Cmd, _='_'}),
-    [D] = ets:lookup(Table, Port),
-    case D#daemon.status of
-        halted ->
-            ets:delete(Table, Port);
-        _ ->
-            stop_port(D),
-            D2 = D#daemon{status=stopping, errors=nil, buf=nil},
-            true = ets:insert(Table, D2)
-    end,
-    stop_os_daemons(Table, Rest).
-    
-boot_os_daemons(_Table, []) ->
-    ok;
-boot_os_daemons(Table, [{Name, Cmd} | Rest]) ->
-    {ok, Port} = start_port(Cmd),
-    true = ets:insert(Table, #daemon{port=Port, name=Name, cmd=Cmd}),
-    boot_os_daemons(Table, Rest).
-    
-% Elements unique to the configured set need to be booted.
-find_to_boot([], _Rest, Acc) ->
-    % Nothing else configured.
-    Acc;
-find_to_boot([D | R1], [D | R2], Acc) ->
-    % Elements are equal, daemon already running.
-    find_to_boot(R1, R2, Acc);
-find_to_boot([D1 | R1], [D2 | _]=A2, Acc) when D1 < D2 ->
-    find_to_boot(R1, A2, [D1 | Acc]);
-find_to_boot(A1, [_ | R2], Acc) ->
-    find_to_boot(A1, R2, Acc);
-find_to_boot(Rest, [], Acc) ->
-    % No more candidates for already running. Boot all.
-    Rest ++ Acc.
-
-% Elements unique to the running set need to be killed.
-find_to_stop([], Rest, Acc) ->
-    % The rest haven't been found, so they must all
-    % be ready to die.
-    Rest ++ Acc;
-find_to_stop([D | R1], [D | R2], Acc) ->
-    % Elements are equal, daemon already running.
-    find_to_stop(R1, R2, Acc);
-find_to_stop([D1 | R1], [D2 | _]=A2, Acc) when D1 < D2 ->
-    find_to_stop(R1, A2, Acc);
-find_to_stop(A1, [D2 | R2], Acc) ->
-    find_to_stop(A1, R2, [D2 | Acc]);
-find_to_stop(_, [], Acc) ->
-    % No more running daemons to worry about.
-    Acc.
-
-should_halt(Errors) ->
-    RetryTimeCfg = couch_config:get("os_daemon_settings", "retry_time", "5"),
-    RetryTime = list_to_integer(RetryTimeCfg),
-
-    Now = now(),
-    RecentErrors = lists:filter(fun(Time) ->
-        timer:now_diff(Now, Time) =< RetryTime * 1000000
-    end, Errors),
-
-    RetryCfg = couch_config:get("os_daemon_settings", "max_retries", "3"),
-    Retries = list_to_integer(RetryCfg),
-
-    {length(RecentErrors) >= Retries, RecentErrors}.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_os_process.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_os_process.erl b/apps/couch/src/couch_os_process.erl
deleted file mode 100644
index db62d49..0000000
--- a/apps/couch/src/couch_os_process.erl
+++ /dev/null
@@ -1,216 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_os_process).
--behaviour(gen_server).
-
--export([start_link/1, start_link/2, start_link/3, stop/1]).
--export([set_timeout/2, prompt/2]).
--export([send/2, writeline/2, readline/1, writejson/2, readjson/1]).
--export([init/1, terminate/2, handle_call/3, handle_cast/2, handle_info/2, code_change/3]).
-
--include("couch_db.hrl").
-
--define(PORT_OPTIONS, [stream, {line, 4096}, binary, exit_status, hide]).
-
--record(os_proc,
-    {command,
-     port,
-     writer,
-     reader,
-     timeout=5000
-    }).
-
-start_link(Command) ->
-    start_link(Command, []).
-start_link(Command, Options) ->
-    start_link(Command, Options, ?PORT_OPTIONS).
-start_link(Command, Options, PortOptions) ->
-    gen_server:start_link(couch_os_process, [Command, Options, PortOptions], []).
-
-stop(Pid) ->
-    gen_server:cast(Pid, stop).
-
-% Read/Write API
-set_timeout(Pid, TimeOut) when is_integer(TimeOut) ->
-    ok = gen_server:call(Pid, {set_timeout, TimeOut}, infinity).
-
-% Used by couch_db_update_notifier.erl
-send(Pid, Data) ->
-    gen_server:cast(Pid, {send, Data}).
-
-prompt(Pid, Data) ->
-    case gen_server:call(Pid, {prompt, Data}, infinity) of
-        {ok, Result} ->
-            Result;
-        Error ->
-            ?LOG_ERROR("OS Process Error ~p :: ~p",[Pid,Error]),
-            throw(Error)
-    end.
-
-% Utility functions for reading and writing
-% in custom functions
-writeline(OsProc, Data) when is_record(OsProc, os_proc) ->
-    port_command(OsProc#os_proc.port, [Data, $\n]).
-
-readline(#os_proc{} = OsProc) ->
-    readline(OsProc, []).
-readline(#os_proc{port = Port} = OsProc, Acc) ->
-    receive
-    {Port, {data, {noeol, Data}}} when is_binary(Acc) ->
-        readline(OsProc, <<Acc/binary,Data/binary>>);
-    {Port, {data, {noeol, Data}}} when is_binary(Data) ->
-        readline(OsProc, Data);
-    {Port, {data, {noeol, Data}}} ->
-        readline(OsProc, [Data|Acc]);
-    {Port, {data, {eol, <<Data/binary>>}}} when is_binary(Acc) ->
-        [<<Acc/binary,Data/binary>>];
-    {Port, {data, {eol, Data}}} when is_binary(Data) ->
-        [Data];
-    {Port, {data, {eol, Data}}} ->
-        lists:reverse(Acc, Data);
-    {Port, Err} ->
-        catch port_close(Port),
-        throw({os_process_error, Err})
-    after OsProc#os_proc.timeout ->
-        catch port_close(Port),
-        throw({os_process_error, "OS process timed out."})
-    end.
-
-% Standard JSON functions
-writejson(OsProc, Data) when is_record(OsProc, os_proc) ->
-    JsonData = ?JSON_ENCODE(Data),
-    ?LOG_DEBUG("OS Process ~p Input  :: ~s", [OsProc#os_proc.port, JsonData]),
-    true = writeline(OsProc, JsonData).
-
-readjson(OsProc) when is_record(OsProc, os_proc) ->
-    Line = iolist_to_binary(readline(OsProc)),
-    ?LOG_DEBUG("OS Process ~p Output :: ~s", [OsProc#os_proc.port, Line]),
-    try
-        % Don't actually parse the whole JSON. Just try to see if it's
-        % a command or a doc map/reduce/filter/show/list/update output.
-        % If it's a command then parse the whole JSON and execute the
-        % command, otherwise return the raw JSON line to the caller.
-        pick_command(Line)
-    catch
-    throw:abort ->
-        {json, Line};
-    throw:{cmd, _Cmd} ->
-        case ?JSON_DECODE(Line) of
-        [<<"log">>, Msg] when is_binary(Msg) ->
-            % we got a message to log. Log it and continue
-            ?LOG_INFO("OS Process ~p Log :: ~s", [OsProc#os_proc.port, Msg]),
-            readjson(OsProc);
-        [<<"error">>, Id, Reason] ->
-            throw({error, {couch_util:to_existing_atom(Id),Reason}});
-        [<<"fatal">>, Id, Reason] ->
-            ?LOG_INFO("OS Process ~p Fatal Error :: ~s ~p",
-                [OsProc#os_proc.port, Id, Reason]),
-            throw({couch_util:to_existing_atom(Id),Reason});
-        _Result ->
-            {json, Line}
-        end
-    end.
-
-pick_command(Line) ->
-    json_stream_parse:events(Line, fun pick_command0/1).
-
-pick_command0(array_start) ->
-    fun pick_command1/1;
-pick_command0(_) ->
-    throw(abort).
-
-pick_command1(<<"log">> = Cmd) ->
-    throw({cmd, Cmd});
-pick_command1(<<"error">> = Cmd) ->
-    throw({cmd, Cmd});
-pick_command1(<<"fatal">> = Cmd) ->
-    throw({cmd, Cmd});
-pick_command1(_) ->
-    throw(abort).
-
-
-% gen_server API
-init([Command, Options, PortOptions]) ->
-    PrivDir = couch_util:priv_dir(),
-    Spawnkiller = filename:join(PrivDir, "couchspawnkillable"),
-    BaseProc = #os_proc{
-        command=Command,
-        port=open_port({spawn, Spawnkiller ++ " " ++ Command}, PortOptions),
-        writer=fun writejson/2,
-        reader=fun readjson/1
-    },
-    KillCmd = iolist_to_binary(readline(BaseProc)),
-    Pid = self(),
-    ?LOG_DEBUG("OS Process Start :: ~p", [BaseProc#os_proc.port]),
-    spawn(fun() ->
-            % this ensure the real os process is killed when this process dies.
-            erlang:monitor(process, Pid),
-            receive _ -> ok end,
-            os:cmd(?b2l(iolist_to_binary(KillCmd)))
-        end),
-    OsProc =
-    lists:foldl(fun(Opt, Proc) ->
-        case Opt of
-        {writer, Writer} when is_function(Writer) ->
-            Proc#os_proc{writer=Writer};
-        {reader, Reader} when is_function(Reader) ->
-            Proc#os_proc{reader=Reader};
-        {timeout, TimeOut} when is_integer(TimeOut) ->
-            Proc#os_proc{timeout=TimeOut}
-        end
-    end, BaseProc, Options),
-    {ok, OsProc}.
-
-terminate(_Reason, #os_proc{port=Port}) ->
-    catch port_close(Port),
-    ok.
-
-handle_call({set_timeout, TimeOut}, _From, OsProc) ->
-    {reply, ok, OsProc#os_proc{timeout=TimeOut}};
-handle_call({prompt, Data}, _From, OsProc) ->
-    #os_proc{writer=Writer, reader=Reader} = OsProc,
-    try
-        Writer(OsProc, Data),
-        {reply, {ok, Reader(OsProc)}, OsProc}
-    catch
-        throw:{error, OsError} ->
-            {reply, OsError, OsProc};
-        throw:OtherError ->
-            {stop, normal, OtherError, OsProc}
-    end.
-
-handle_cast({send, Data}, #os_proc{writer=Writer}=OsProc) ->
-    try
-        Writer(OsProc, Data),
-        {noreply, OsProc}
-    catch
-        throw:OsError ->
-            ?LOG_ERROR("Failed sending data: ~p -> ~p", [Data, OsError]),
-            {stop, normal, OsProc}
-    end;
-handle_cast(stop, OsProc) ->
-    {stop, normal, OsProc};
-handle_cast(Msg, OsProc) ->
-    ?LOG_DEBUG("OS Proc: Unknown cast: ~p", [Msg]),
-    {noreply, OsProc}.
-
-handle_info({Port, {exit_status, 0}}, #os_proc{port=Port}=OsProc) ->
-    ?LOG_INFO("OS Process terminated normally", []),
-    {stop, normal, OsProc};
-handle_info({Port, {exit_status, Status}}, #os_proc{port=Port}=OsProc) ->
-    ?LOG_ERROR("OS Process died with status: ~p", [Status]),
-    {stop, {exit_status, Status}, OsProc}.
-
-code_change(_OldVsn, State, _Extra) ->
-    {ok, State}.
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_passwords.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_passwords.erl b/apps/couch/src/couch_passwords.erl
deleted file mode 100644
index d9e6836..0000000
--- a/apps/couch/src/couch_passwords.erl
+++ /dev/null
@@ -1,119 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_passwords).
-
--export([simple/2, pbkdf2/3, pbkdf2/4, verify/2]).
--export([hash_admin_password/1, get_unhashed_admins/0]).
-
--include("couch_db.hrl").
-
--define(MAX_DERIVED_KEY_LENGTH, (1 bsl 32 - 1)).
--define(SHA1_OUTPUT_LENGTH, 20).
-
-%% legacy scheme, not used for new passwords.
--spec simple(binary(), binary()) -> binary().
-simple(Password, Salt) ->
-    ?l2b(couch_util:to_hex(crypto:sha(<<Password/binary, Salt/binary>>))).
-
-%% CouchDB utility functions
--spec hash_admin_password(binary()) -> binary().
-hash_admin_password(ClearPassword) ->
-    Iterations = couch_config:get("couch_httpd_auth", "iterations", "10000"),
-    Salt = couch_uuids:random(),
-    DerivedKey = couch_passwords:pbkdf2(couch_util:to_binary(ClearPassword),
-                                        Salt ,list_to_integer(Iterations)),
-    ?l2b("-pbkdf2-" ++ ?b2l(DerivedKey) ++ ","
-        ++ ?b2l(Salt) ++ ","
-        ++ Iterations).
-
--spec get_unhashed_admins() -> list().
-get_unhashed_admins() ->
-    lists:filter(
-        fun({_User, "-hashed-" ++ _}) ->
-            false; % already hashed
-        ({_User, "-pbkdf2-" ++ _}) ->
-            false; % already hashed
-        ({_User, _ClearPassword}) ->
-            true
-        end,
-    couch_config:get("admins")).
-
-%% Current scheme, much stronger.
--spec pbkdf2(binary(), binary(), integer()) -> binary().
-pbkdf2(Password, Salt, Iterations) ->
-    {ok, Result} = pbkdf2(Password, Salt, Iterations, ?SHA1_OUTPUT_LENGTH),
-    Result.
-
--spec pbkdf2(binary(), binary(), integer(), integer())
-    -> {ok, binary()} | {error, derived_key_too_long}.
-pbkdf2(_Password, _Salt, _Iterations, DerivedLength)
-    when DerivedLength > ?MAX_DERIVED_KEY_LENGTH ->
-    {error, derived_key_too_long};
-pbkdf2(Password, Salt, Iterations, DerivedLength) ->
-    L = ceiling(DerivedLength / ?SHA1_OUTPUT_LENGTH),
-    <<Bin:DerivedLength/binary,_/binary>> =
-        iolist_to_binary(pbkdf2(Password, Salt, Iterations, L, 1, [])),
-    {ok, ?l2b(couch_util:to_hex(Bin))}.
-
--spec pbkdf2(binary(), binary(), integer(), integer(), integer(), iolist())
-    -> iolist().
-pbkdf2(_Password, _Salt, _Iterations, BlockCount, BlockIndex, Acc)
-    when BlockIndex > BlockCount ->
-    lists:reverse(Acc);
-pbkdf2(Password, Salt, Iterations, BlockCount, BlockIndex, Acc) ->
-    Block = pbkdf2(Password, Salt, Iterations, BlockIndex, 1, <<>>, <<>>),
-    pbkdf2(Password, Salt, Iterations, BlockCount, BlockIndex + 1, [Block|Acc]).
-
--spec pbkdf2(binary(), binary(), integer(), integer(), integer(),
-    binary(), binary()) -> binary().
-pbkdf2(_Password, _Salt, Iterations, _BlockIndex, Iteration, _Prev, Acc)
-    when Iteration > Iterations ->
-    Acc;
-pbkdf2(Password, Salt, Iterations, BlockIndex, 1, _Prev, _Acc) ->
-    InitialBlock = crypto:sha_mac(Password,
-        <<Salt/binary,BlockIndex:32/integer>>),
-    pbkdf2(Password, Salt, Iterations, BlockIndex, 2,
-        InitialBlock, InitialBlock);
-pbkdf2(Password, Salt, Iterations, BlockIndex, Iteration, Prev, Acc) ->
-    Next = crypto:sha_mac(Password, Prev),
-    pbkdf2(Password, Salt, Iterations, BlockIndex, Iteration + 1,
-                   Next, crypto:exor(Next, Acc)).
-
-%% verify two lists for equality without short-circuits to avoid timing attacks.
--spec verify(string(), string(), integer()) -> boolean().
-verify([X|RestX], [Y|RestY], Result) ->
-    verify(RestX, RestY, (X bxor Y) bor Result);
-verify([], [], Result) ->
-    Result == 0.
-
--spec verify(binary(), binary()) -> boolean();
-            (list(), list()) -> boolean().
-verify(<<X/binary>>, <<Y/binary>>) ->
-    verify(?b2l(X), ?b2l(Y));
-verify(X, Y) when is_list(X) and is_list(Y) ->
-    case length(X) == length(Y) of
-        true ->
-            verify(X, Y, 0);
-        false ->
-            false
-    end;
-verify(_X, _Y) -> false.
-
--spec ceiling(number()) -> integer().
-ceiling(X) ->
-    T = erlang:trunc(X),
-    case (X - T) of
-        Neg when Neg < 0 -> T;
-        Pos when Pos > 0 -> T + 1;
-        _ -> T
-    end.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_primary_sup.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_primary_sup.erl b/apps/couch/src/couch_primary_sup.erl
deleted file mode 100644
index 7c4fde2..0000000
--- a/apps/couch/src/couch_primary_sup.erl
+++ /dev/null
@@ -1,48 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_primary_sup).
--behaviour(supervisor).
--export([init/1, start_link/0]).
-
-start_link() ->
-    supervisor:start_link({local,couch_primary_services}, ?MODULE, []).
-
-init([]) ->
-    Children = [
-        {couch_task_status,
-            {couch_task_status, start_link, []},
-            permanent,
-            brutal_kill,
-            worker,
-            [couch_task_status]},
-        {couch_server,
-            {couch_server, sup_start_link, []},
-            permanent,
-            brutal_kill,
-            worker,
-            [couch_server]},
-        {couch_db_update_event,
-            {gen_event, start_link, [{local, couch_db_update}]},
-            permanent,
-            brutal_kill,
-            worker,
-            dynamic},
-        {couch_log,
-            {couch_log, start_link, []},
-            permanent,
-            brutal_kill,
-            worker,
-            [couch_log]}
-    ],
-    {ok, {{one_for_one, 10, 3600}, Children}}.
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_query_servers.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_query_servers.erl b/apps/couch/src/couch_query_servers.erl
deleted file mode 100644
index 3b58cbe..0000000
--- a/apps/couch/src/couch_query_servers.erl
+++ /dev/null
@@ -1,616 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_query_servers).
--behaviour(gen_server).
-
--export([start_link/0, config_change/1]).
-
--export([init/1, terminate/2, handle_call/3, handle_cast/2, handle_info/2,code_change/3]).
--export([start_doc_map/3, map_docs/2, map_doc_raw/2, stop_doc_map/1, raw_to_ejson/1]).
--export([reduce/3, rereduce/3,validate_doc_update/5]).
--export([filter_docs/5]).
--export([filter_view/3]).
-
--export([with_ddoc_proc/2, proc_prompt/2, ddoc_prompt/3, ddoc_proc_prompt/3, json_doc/1]).
-
-% For 210-os-proc-pool.t
--export([get_os_process/1, ret_os_process/1]).
-
--include("couch_db.hrl").
-
--record(proc, {
-    pid,
-    lang,
-    ddoc_keys = [],
-    prompt_fun,
-    set_timeout_fun,
-    stop_fun
-}).
-
--record(qserver, {
-    langs, % Keyed by language name, value is {Mod,Func,Arg}
-    pid_procs, % Keyed by PID, valus is a #proc record.
-    lang_procs, % Keyed by language name, value is a #proc record
-    lang_limits, % Keyed by language name, value is {Lang, Limit, Current}
-    waitlist = [],
-    config
-}).
-
-start_link() ->
-    gen_server:start_link({local, couch_query_servers}, couch_query_servers, [], []).
-
-start_doc_map(Lang, Functions, Lib) ->
-    Proc = get_os_process(Lang),
-    case Lib of
-    {[]} -> ok;
-    Lib ->
-        true = proc_prompt(Proc, [<<"add_lib">>, Lib])
-    end,
-    lists:foreach(fun(FunctionSource) ->
-        true = proc_prompt(Proc, [<<"add_fun">>, FunctionSource])
-    end, Functions),
-    {ok, Proc}.
-
-map_docs(Proc, Docs) ->
-    % send the documents
-    Results = lists:map(
-        fun(Doc) ->
-            Json = couch_doc:to_json_obj(Doc, []),
-
-            FunsResults = proc_prompt(Proc, [<<"map_doc">>, Json]),
-            % the results are a json array of function map yields like this:
-            % [FunResults1, FunResults2 ...]
-            % where funresults is are json arrays of key value pairs:
-            % [[Key1, Value1], [Key2, Value2]]
-            % Convert the key, value pairs to tuples like
-            % [{Key1, Value1}, {Key2, Value2}]
-            lists:map(
-                fun(FunRs) ->
-                    [list_to_tuple(FunResult) || FunResult <- FunRs]
-                end,
-            FunsResults)
-        end,
-        Docs),
-    {ok, Results}.
-
-map_doc_raw(Proc, Doc) ->
-    Json = couch_doc:to_json_obj(Doc, []),
-    {ok, proc_prompt_raw(Proc, [<<"map_doc">>, Json])}.
-
-
-stop_doc_map(nil) ->
-    ok;
-stop_doc_map(Proc) ->
-    ok = ret_os_process(Proc).
-
-group_reductions_results([]) ->
-    [];
-group_reductions_results(List) ->
-    {Heads, Tails} = lists:foldl(
-        fun([H|T], {HAcc,TAcc}) ->
-            {[H|HAcc], [T|TAcc]}
-        end, {[], []}, List),
-    case Tails of
-    [[]|_] -> % no tails left
-        [Heads];
-    _ ->
-     [Heads | group_reductions_results(Tails)]
-    end.
-
-rereduce(_Lang, [], _ReducedValues) ->
-    {ok, []};
-rereduce(Lang, RedSrcs, ReducedValues) ->
-    Grouped = group_reductions_results(ReducedValues),
-    Results = lists:zipwith(
-        fun
-        (<<"_", _/binary>> = FunSrc, Values) ->
-            {ok, [Result]} = builtin_reduce(rereduce, [FunSrc], [[[], V] || V <- Values], []),
-            Result;
-        (FunSrc, Values) ->
-            os_rereduce(Lang, [FunSrc], Values)
-        end, RedSrcs, Grouped),
-    {ok, Results}.
-
-reduce(_Lang, [], _KVs) ->
-    {ok, []};
-reduce(Lang, RedSrcs, KVs) ->
-    {OsRedSrcs, BuiltinReds} = lists:partition(fun
-        (<<"_", _/binary>>) -> false;
-        (_OsFun) -> true
-    end, RedSrcs),
-    {ok, OsResults} = os_reduce(Lang, OsRedSrcs, KVs),
-    {ok, BuiltinResults} = builtin_reduce(reduce, BuiltinReds, KVs, []),
-    recombine_reduce_results(RedSrcs, OsResults, BuiltinResults, []).
-
-recombine_reduce_results([], [], [], Acc) ->
-    {ok, lists:reverse(Acc)};
-recombine_reduce_results([<<"_", _/binary>>|RedSrcs], OsResults, [BRes|BuiltinResults], Acc) ->
-    recombine_reduce_results(RedSrcs, OsResults, BuiltinResults, [BRes|Acc]);
-recombine_reduce_results([_OsFun|RedSrcs], [OsR|OsResults], BuiltinResults, Acc) ->
-    recombine_reduce_results(RedSrcs, OsResults, BuiltinResults, [OsR|Acc]).
-
-os_reduce(_Lang, [], _KVs) ->
-    {ok, []};
-os_reduce(Lang, OsRedSrcs, KVs) ->
-    Proc = get_os_process(Lang),
-    OsResults = try proc_prompt(Proc, [<<"reduce">>, OsRedSrcs, KVs]) of
-        [true, Reductions] -> Reductions
-    after
-        ok = ret_os_process(Proc)
-    end,
-    {ok, OsResults}.
-
-os_rereduce(Lang, OsRedSrcs, KVs) ->
-    Proc = get_os_process(Lang),
-    try proc_prompt(Proc, [<<"rereduce">>, OsRedSrcs, KVs]) of
-        [true, [Reduction]] -> Reduction
-    after
-        ok = ret_os_process(Proc)
-    end.
-
-
-builtin_reduce(_Re, [], _KVs, Acc) ->
-    {ok, lists:reverse(Acc)};
-builtin_reduce(Re, [<<"_sum",_/binary>>|BuiltinReds], KVs, Acc) ->
-    Sum = builtin_sum_rows(KVs),
-    builtin_reduce(Re, BuiltinReds, KVs, [Sum|Acc]);
-builtin_reduce(reduce, [<<"_count",_/binary>>|BuiltinReds], KVs, Acc) ->
-    Count = length(KVs),
-    builtin_reduce(reduce, BuiltinReds, KVs, [Count|Acc]);
-builtin_reduce(rereduce, [<<"_count",_/binary>>|BuiltinReds], KVs, Acc) ->
-    Count = builtin_sum_rows(KVs),
-    builtin_reduce(rereduce, BuiltinReds, KVs, [Count|Acc]);
-builtin_reduce(Re, [<<"_stats",_/binary>>|BuiltinReds], KVs, Acc) ->
-    Stats = builtin_stats(Re, KVs),
-    builtin_reduce(Re, BuiltinReds, KVs, [Stats|Acc]).
-
-builtin_sum_rows(KVs) ->
-    lists:foldl(fun
-        ([_Key, Value], Acc) when is_number(Value), is_number(Acc) ->
-            Acc + Value;
-        ([_Key, Value], Acc) when is_list(Value), is_list(Acc) ->
-            sum_terms(Acc, Value);
-        ([_Key, Value], Acc) when is_number(Value), is_list(Acc) ->
-            sum_terms(Acc, [Value]);
-        ([_Key, Value], Acc) when is_list(Value), is_number(Acc) ->
-            sum_terms([Acc], Value);
-        (_Else, _Acc) ->
-            throw({invalid_value, <<"builtin _sum function requires map values to be numbers or lists of numbers">>})
-    end, 0, KVs).
-
-sum_terms([], []) ->
-    [];
-sum_terms([_|_]=Xs, []) ->
-    Xs;
-sum_terms([], [_|_]=Ys) ->
-    Ys;
-sum_terms([X|Xs], [Y|Ys]) when is_number(X), is_number(Y) ->
-    [X+Y | sum_terms(Xs,Ys)];
-sum_terms(_, _) ->
-    throw({invalid_value, <<"builtin _sum function requires map values to be numbers or lists of numbers">>}).
-
-builtin_stats(reduce, []) ->
-    {[]};
-builtin_stats(reduce, [[_,First]|Rest]) when is_number(First) ->
-    Stats = lists:foldl(fun([_K,V], {S,C,Mi,Ma,Sq}) when is_number(V) ->
-        {S+V, C+1, lists:min([Mi, V]), lists:max([Ma, V]), Sq+(V*V)};
-    (_, _) ->
-        throw({invalid_value,
-            <<"builtin _stats function requires map values to be numbers">>})
-    end, {First,1,First,First,First*First}, Rest),
-    {Sum, Cnt, Min, Max, Sqr} = Stats,
-    {[{sum,Sum}, {count,Cnt}, {min,Min}, {max,Max}, {sumsqr,Sqr}]};
-
-builtin_stats(rereduce, [[_,First]|Rest]) ->
-    {[{sum,Sum0}, {count,Cnt0}, {min,Min0}, {max,Max0}, {sumsqr,Sqr0}]} = First,
-    Stats = lists:foldl(fun([_K,Red], {S,C,Mi,Ma,Sq}) ->
-        {[{sum,Sum}, {count,Cnt}, {min,Min}, {max,Max}, {sumsqr,Sqr}]} = Red,
-        {Sum+S, Cnt+C, lists:min([Min, Mi]), lists:max([Max, Ma]), Sqr+Sq}
-    end, {Sum0,Cnt0,Min0,Max0,Sqr0}, Rest),
-    {Sum, Cnt, Min, Max, Sqr} = Stats,
-    {[{sum,Sum}, {count,Cnt}, {min,Min}, {max,Max}, {sumsqr,Sqr}]}.
-
-% use the function stored in ddoc.validate_doc_update to test an update.
-validate_doc_update(DDoc, EditDoc, DiskDoc, Ctx, SecObj) ->
-    JsonEditDoc = couch_doc:to_json_obj(EditDoc, [revs]),
-    JsonDiskDoc = json_doc(DiskDoc),
-    case ddoc_prompt(DDoc, [<<"validate_doc_update">>], [JsonEditDoc, JsonDiskDoc, Ctx, SecObj]) of
-        1 ->
-            ok;
-        {[{<<"forbidden">>, Message}]} ->
-            throw({forbidden, Message});
-        {[{<<"unauthorized">>, Message}]} ->
-            throw({unauthorized, Message})
-    end.
-
-json_doc(nil) -> null;
-json_doc(Doc) ->
-    couch_doc:to_json_obj(Doc, [revs]).
-
-filter_view(DDoc, VName, Docs) ->
-    JsonDocs = [couch_doc:to_json_obj(Doc, [revs]) || Doc <- Docs],
-    [true, Passes] = ddoc_prompt(DDoc, [<<"views">>, VName, <<"map">>], [JsonDocs]),
-    {ok, Passes}.
-
-filter_docs(Req, Db, DDoc, FName, Docs) ->
-    JsonReq = case Req of
-    {json_req, JsonObj} ->
-        JsonObj;
-    #httpd{} = HttpReq ->
-        couch_httpd_external:json_req_obj(HttpReq, Db)
-    end,
-    JsonDocs = [couch_doc:to_json_obj(Doc, [revs]) || Doc <- Docs],
-    [true, Passes] = ddoc_prompt(DDoc, [<<"filters">>, FName],
-        [JsonDocs, JsonReq]),
-    {ok, Passes}.
-
-ddoc_proc_prompt({Proc, DDocId}, FunPath, Args) ->
-    proc_prompt(Proc, [<<"ddoc">>, DDocId, FunPath, Args]).
-
-ddoc_prompt(DDoc, FunPath, Args) ->
-    with_ddoc_proc(DDoc, fun({Proc, DDocId}) ->
-        proc_prompt(Proc, [<<"ddoc">>, DDocId, FunPath, Args])
-    end).
-
-with_ddoc_proc(#doc{id=DDocId,revs={Start, [DiskRev|_]}}=DDoc, Fun) ->
-    Rev = couch_doc:rev_to_str({Start, DiskRev}),
-    DDocKey = {DDocId, Rev},
-    Proc = get_ddoc_process(DDoc, DDocKey),
-    try Fun({Proc, DDocId})
-    after
-        ok = ret_os_process(Proc)
-    end.
-
-init([]) ->
-    % register async to avoid deadlock on restart_child
-    Self = self(),
-    spawn(couch_config, register, [fun ?MODULE:config_change/1, Self]),
-
-    Langs = ets:new(couch_query_server_langs, [set, private]),
-    LangLimits = ets:new(couch_query_server_lang_limits, [set, private]),
-    PidProcs = ets:new(couch_query_server_pid_langs, [set, private]),
-    LangProcs = ets:new(couch_query_server_procs, [set, private]),
-
-    ProcTimeout = list_to_integer(couch_config:get(
-                        "couchdb", "os_process_timeout", "5000")),
-    ReduceLimit = list_to_atom(
-        couch_config:get("query_server_config","reduce_limit","true")),
-    OsProcLimit = list_to_integer(
-        couch_config:get("query_server_config","os_process_limit","10")),
-
-    % 'query_servers' specifies an OS command-line to execute.
-    lists:foreach(fun({Lang, Command}) ->
-        true = ets:insert(LangLimits, {?l2b(Lang), OsProcLimit, 0}),
-        true = ets:insert(Langs, {?l2b(Lang),
-                          couch_os_process, start_link, [Command]})
-    end, couch_config:get("query_servers")),
-    % 'native_query_servers' specifies a {Module, Func, Arg} tuple.
-    lists:foreach(fun({Lang, SpecStr}) ->
-        {ok, {Mod, Fun, SpecArg}} = couch_util:parse_term(SpecStr),
-        true = ets:insert(LangLimits, {?l2b(Lang), 0, 0}), % 0 means no limit
-        true = ets:insert(Langs, {?l2b(Lang),
-                          Mod, Fun, SpecArg})
-    end, couch_config:get("native_query_servers")),
-
-
-    process_flag(trap_exit, true),
-    {ok, #qserver{
-        langs = Langs, % Keyed by language name, value is {Mod,Func,Arg}
-        pid_procs = PidProcs, % Keyed by PID, valus is a #proc record.
-        lang_procs = LangProcs, % Keyed by language name, value is a #proc record
-        lang_limits = LangLimits, % Keyed by language name, value is {Lang, Limit, Current}
-        config = {[{<<"reduce_limit">>, ReduceLimit},{<<"timeout">>, ProcTimeout}]}
-    }}.
-
-terminate(_Reason, #qserver{pid_procs=PidProcs}) ->
-    [couch_util:shutdown_sync(P) || {P,_} <- ets:tab2list(PidProcs)],
-    ok.
-
-handle_call({get_proc, DDoc1, DDocKey}, From, Server) ->
-    #doc{body = {Props}} = DDoc = couch_doc:with_ejson_body(DDoc1),
-    Lang = couch_util:get_value(<<"language">>, Props, <<"javascript">>),
-    case lang_proc(Lang, Server, fun(Procs) ->
-            % find a proc in the set that has the DDoc
-            proc_with_ddoc(DDoc, DDocKey, Procs)
-        end) of
-    {ok, Proc} ->
-        {reply, {ok, Proc, Server#qserver.config}, Server};
-    wait ->
-        {noreply, add_to_waitlist({DDoc, DDocKey}, From, Server)};
-    Error ->
-        {reply, Error, Server}
-    end;
-handle_call({get_proc, Lang}, From, Server) ->
-    case lang_proc(Lang, Server, fun([P|_Procs]) ->
-            {ok, P}
-        end) of
-    {ok, Proc} ->
-        {reply, {ok, Proc, Server#qserver.config}, Server};
-    wait ->
-        {noreply, add_to_waitlist({Lang}, From, Server)};
-    Error ->
-        {reply, Error, Server}
-    end;
-handle_call({unlink_proc, Pid}, _From, Server) ->
-    unlink(Pid),
-    {reply, ok, Server};
-handle_call({ret_proc, Proc}, _From, #qserver{
-        pid_procs=PidProcs,
-        lang_procs=LangProcs}=Server) ->
-    % Along with max process limit, here we should check
-    % if we're over the limit and discard when we are.
-    case is_process_alive(Proc#proc.pid) of
-        true ->
-            add_value(PidProcs, Proc#proc.pid, Proc),
-            add_to_list(LangProcs, Proc#proc.lang, Proc),
-            link(Proc#proc.pid);
-        false ->
-            ok
-    end,
-    {reply, true, service_waitlist(Server)}.
-
-handle_cast(_Whatever, Server) ->
-    {noreply, Server}.
-
-handle_info({'EXIT', _, _}, Server) ->
-    {noreply, Server};
-handle_info({'DOWN', _, process, Pid, Status}, #qserver{
-        pid_procs=PidProcs,
-        lang_procs=LangProcs,
-        lang_limits=LangLimits}=Server) ->
-    case ets:lookup(PidProcs, Pid) of
-    [{Pid, Proc}] ->
-        case Status of
-        normal -> ok;
-        _ -> ?LOG_DEBUG("Linked process died abnormally: ~p (reason: ~p)", [Pid, Status])
-        end,
-        rem_value(PidProcs, Pid),
-        catch rem_from_list(LangProcs, Proc#proc.lang, Proc),
-        [{Lang, Lim, Current}] = ets:lookup(LangLimits, Proc#proc.lang),
-        true = ets:insert(LangLimits, {Lang, Lim, Current-1}),
-        {noreply, service_waitlist(Server)};
-    [] ->
-        case Status of
-        normal ->
-            {noreply, Server};
-        _ ->
-            {stop, Status, Server}
-        end
-    end.
-
-code_change(_OldVsn, State, _Extra) ->
-    {ok, State}.
-
-config_change("query_servers") ->
-    supervisor:terminate_child(couch_secondary_services, query_servers),
-    supervisor:restart_child(couch_secondary_services, query_servers);
-config_change("native_query_servers") ->
-    supervisor:terminate_child(couch_secondary_services, query_servers),
-    supervisor:restart_child(couch_secondary_services, query_servers);
-config_change("query_server_config") ->
-    supervisor:terminate_child(couch_secondary_services, query_servers),
-    supervisor:restart_child(couch_secondary_services, query_servers).
-
-% Private API
-
-add_to_waitlist(Info, From, #qserver{waitlist=Waitlist}=Server) ->
-    Server#qserver{waitlist=[{Info, From}|Waitlist]}.
-
-service_waitlist(#qserver{waitlist=[]}=Server) ->
-    Server;
-service_waitlist(#qserver{waitlist=Waitlist}=Server) ->
-    [Oldest|RevWList] = lists:reverse(Waitlist),
-    case service_waiting(Oldest, Server) of
-    ok ->
-        Server#qserver{waitlist=lists:reverse(RevWList)};
-    wait ->
-        Server#qserver{waitlist=Waitlist}
-    end.
-
-% todo get rid of duplication
-service_waiting({{#doc{body={Props}}=DDoc, DDocKey}, From}, Server) ->
-    Lang = couch_util:get_value(<<"language">>, Props, <<"javascript">>),
-    case lang_proc(Lang, Server, fun(Procs) ->
-            % find a proc in the set that has the DDoc
-            proc_with_ddoc(DDoc, DDocKey, Procs)
-        end) of
-    {ok, Proc} ->
-        gen_server:reply(From, {ok, Proc, Server#qserver.config}),
-        ok;
-    wait -> % this should never happen
-        wait;
-    Error ->
-        gen_server:reply(From, Error),
-        ok
-    end;
-service_waiting({{Lang}, From}, Server) ->
-    case lang_proc(Lang, Server, fun([P|_Procs]) ->
-            {ok, P}
-        end) of
-    {ok, Proc} ->
-        gen_server:reply(From, {ok, Proc, Server#qserver.config}),
-        ok;
-    wait -> % this should never happen
-        wait;
-    Error ->
-        gen_server:reply(From, Error),
-        ok
-    end.
-
-lang_proc(Lang, #qserver{
-        langs=Langs,
-        pid_procs=PidProcs,
-        lang_procs=LangProcs,
-        lang_limits=LangLimits}, PickFun) ->
-    % Note to future self. Add max process limit.
-    case ets:lookup(LangProcs, Lang) of
-    [{Lang, [P|Procs]}] ->
-        {ok, Proc} = PickFun([P|Procs]),
-        rem_from_list(LangProcs, Lang, Proc),
-        {ok, Proc};
-    _ ->
-        case (catch new_process(Langs, LangLimits, Lang)) of
-        {ok, Proc} ->
-            add_value(PidProcs, Proc#proc.pid, Proc),
-            PickFun([Proc]);
-        ErrorOrWait ->
-            ErrorOrWait
-        end
-    end.
-
-new_process(Langs, LangLimits, Lang) ->
-    [{Lang, Lim, Current}] = ets:lookup(LangLimits, Lang),
-    if (Lim == 0) or (Current < Lim) -> % Lim == 0 means no limit
-        % we are below the limit for our language, make a new one
-        case ets:lookup(Langs, Lang) of
-        [{Lang, Mod, Func, Arg}] ->
-            {ok, Pid} = apply(Mod, Func, Arg),
-            erlang:monitor(process, Pid),
-            true = ets:insert(LangLimits, {Lang, Lim, Current+1}),
-            {ok, #proc{lang=Lang,
-                       pid=Pid,
-                       % Called via proc_prompt, proc_set_timeout, and proc_stop
-                       prompt_fun={Mod, prompt},
-                       set_timeout_fun={Mod, set_timeout},
-                       stop_fun={Mod, stop}}};
-        _ ->
-            {unknown_query_language, Lang}
-        end;
-    true ->
-        wait
-    end.
-
-proc_with_ddoc(DDoc, DDocKey, LangProcs) ->
-    DDocProcs = lists:filter(fun(#proc{ddoc_keys=Keys}) ->
-            lists:any(fun(Key) ->
-                Key == DDocKey
-            end, Keys)
-        end, LangProcs),
-    case DDocProcs of
-        [DDocProc|_] ->
-            ?LOG_DEBUG("DDocProc found for DDocKey: ~p",[DDocKey]),
-            {ok, DDocProc};
-        [] ->
-            [TeachProc|_] = LangProcs,
-            ?LOG_DEBUG("Teach ddoc to new proc ~p with DDocKey: ~p",[TeachProc, DDocKey]),
-            {ok, SmartProc} = teach_ddoc(DDoc, DDocKey, TeachProc),
-            {ok, SmartProc}
-    end.
-
-proc_prompt(Proc, Args) ->
-     case proc_prompt_raw(Proc, Args) of
-     {json, Json} ->
-         ?JSON_DECODE(Json);
-     EJson ->
-         EJson
-     end.
-
-proc_prompt_raw(#proc{prompt_fun = {Mod, Func}} = Proc, Args) ->
-    apply(Mod, Func, [Proc#proc.pid, Args]).
-
-raw_to_ejson({json, Json}) ->
-    ?JSON_DECODE(Json);
-raw_to_ejson(EJson) ->
-    EJson.
-
-proc_stop(Proc) ->
-    {Mod, Func} = Proc#proc.stop_fun,
-    apply(Mod, Func, [Proc#proc.pid]).
-
-proc_set_timeout(Proc, Timeout) ->
-    {Mod, Func} = Proc#proc.set_timeout_fun,
-    apply(Mod, Func, [Proc#proc.pid, Timeout]).
-
-teach_ddoc(DDoc, {DDocId, _Rev}=DDocKey, #proc{ddoc_keys=Keys}=Proc) ->
-    % send ddoc over the wire
-    % we only share the rev with the client we know to update code
-    % but it only keeps the latest copy, per each ddoc, around.
-    true = proc_prompt(Proc, [<<"ddoc">>, <<"new">>, DDocId, couch_doc:to_json_obj(DDoc, [])]),
-    % we should remove any other ddocs keys for this docid
-    % because the query server overwrites without the rev
-    Keys2 = [{D,R} || {D,R} <- Keys, D /= DDocId],
-    % add ddoc to the proc
-    {ok, Proc#proc{ddoc_keys=[DDocKey|Keys2]}}.
-
-get_ddoc_process(#doc{} = DDoc, DDocKey) ->
-    % remove this case statement
-    case gen_server:call(couch_query_servers, {get_proc, DDoc, DDocKey}, infinity) of
-    {ok, Proc, {QueryConfig}} ->
-        % process knows the ddoc
-        case (catch proc_prompt(Proc, [<<"reset">>, {QueryConfig}])) of
-        true ->
-            proc_set_timeout(Proc, couch_util:get_value(<<"timeout">>, QueryConfig)),
-            link(Proc#proc.pid),
-            gen_server:call(couch_query_servers, {unlink_proc, Proc#proc.pid}, infinity),
-            Proc;
-        _ ->
-            catch proc_stop(Proc),
-            get_ddoc_process(DDoc, DDocKey)
-        end;
-    Error ->
-        throw(Error)
-    end.
-
-get_os_process(Lang) ->
-    case gen_server:call(couch_query_servers, {get_proc, Lang}, infinity) of
-    {ok, Proc, {QueryConfig}} ->
-        case (catch proc_prompt(Proc, [<<"reset">>, {QueryConfig}])) of
-        true ->
-            proc_set_timeout(Proc, couch_util:get_value(<<"timeout">>, QueryConfig)),
-            link(Proc#proc.pid),
-            gen_server:call(couch_query_servers, {unlink_proc, Proc#proc.pid}, infinity),
-            Proc;
-        _ ->
-            catch proc_stop(Proc),
-            get_os_process(Lang)
-        end;
-    Error ->
-        throw(Error)
-    end.
-
-ret_os_process(Proc) ->
-    true = gen_server:call(couch_query_servers, {ret_proc, Proc}, infinity),
-    catch unlink(Proc#proc.pid),
-    ok.
-
-add_value(Tid, Key, Value) ->
-    true = ets:insert(Tid, {Key, Value}).
-
-rem_value(Tid, Key) ->
-    true = ets:delete(Tid, Key).
-
-add_to_list(Tid, Key, Value) ->
-    case ets:lookup(Tid, Key) of
-    [{Key, Vals}] ->
-        true = ets:insert(Tid, {Key, [Value|Vals]});
-    [] ->
-        true = ets:insert(Tid, {Key, [Value]})
-    end.
-
-rem_from_list(Tid, Key, Value) when is_record(Value, proc)->
-    Pid = Value#proc.pid,
-    case ets:lookup(Tid, Key) of
-    [{Key, Vals}] ->
-        % make a new values list that doesn't include the Value arg
-        NewValues = [Val || #proc{pid=P}=Val <- Vals, P /= Pid],
-        ets:insert(Tid, {Key, NewValues});
-    [] -> ok
-    end;
-rem_from_list(Tid, Key, Value) ->
-    case ets:lookup(Tid, Key) of
-    [{Key, Vals}] ->
-        % make a new values list that doesn't include the Value arg
-        NewValues = [Val || Val <- Vals, Val /= Value],
-        ets:insert(Tid, {Key, NewValues});
-    [] -> ok
-    end.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_ref_counter.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_ref_counter.erl b/apps/couch/src/couch_ref_counter.erl
deleted file mode 100644
index a774f46..0000000
--- a/apps/couch/src/couch_ref_counter.erl
+++ /dev/null
@@ -1,111 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_ref_counter).
--behaviour(gen_server).
-
--export([start/1, init/1, terminate/2, handle_call/3, handle_cast/2, code_change/3, handle_info/2]).
--export([drop/1,drop/2,add/1,add/2,count/1]).
-
-start(ChildProcs) ->
-    gen_server:start(couch_ref_counter, {self(), ChildProcs}, []).
-
-
-drop(RefCounterPid) ->
-    drop(RefCounterPid, self()).
-
-drop(RefCounterPid, Pid) ->
-    gen_server:call(RefCounterPid, {drop, Pid}, infinity).
-
-
-add(RefCounterPid) ->
-    add(RefCounterPid, self()).
-
-add(RefCounterPid, Pid) ->
-    gen_server:call(RefCounterPid, {add, Pid}, infinity).
-
-count(RefCounterPid) ->
-    gen_server:call(RefCounterPid, count).
-
-% server functions
-
--record(srv,
-    {
-    referrers=dict:new(), % a dict of each ref counting proc.
-    child_procs=[]
-    }).
-
-init({Pid, ChildProcs}) ->
-    [link(ChildProc) || ChildProc <- ChildProcs],
-    Referrers = dict:from_list([{Pid, {erlang:monitor(process, Pid), 1}}]),
-    {ok, #srv{referrers=Referrers, child_procs=ChildProcs}}.
-
-
-terminate(_Reason, #srv{child_procs=ChildProcs}) ->
-    [couch_util:shutdown_sync(Pid) || Pid <- ChildProcs],
-    ok.
-
-
-handle_call({add, Pid},_From, #srv{referrers=Referrers}=Srv) ->
-    Referrers2 =
-    case dict:find(Pid, Referrers) of
-    error ->
-        dict:store(Pid, {erlang:monitor(process, Pid), 1}, Referrers);
-    {ok, {MonRef, RefCnt}} ->
-        dict:store(Pid, {MonRef, RefCnt + 1}, Referrers)
-    end,
-    {reply, ok, Srv#srv{referrers=Referrers2}};
-handle_call(count, _From, Srv) ->
-    {monitors, Monitors} =  process_info(self(), monitors),
-    {reply, length(Monitors), Srv};
-handle_call({drop, Pid}, _From, #srv{referrers=Referrers}=Srv) ->
-    Referrers2 =
-    case dict:find(Pid, Referrers) of
-    {ok, {MonRef, 1}} ->
-        erlang:demonitor(MonRef, [flush]),
-        dict:erase(Pid, Referrers);
-    {ok, {MonRef, Num}} ->
-        dict:store(Pid, {MonRef, Num-1}, Referrers);
-    error ->
-        Referrers
-    end,
-    Srv2 = Srv#srv{referrers=Referrers2},
-    case should_close() of
-    true ->
-        {stop,normal,ok,Srv2};
-    false ->
-        {reply, ok, Srv2}
-    end.
-
-handle_cast(Msg, _Srv)->
-    exit({unknown_msg,Msg}).
-
-
-code_change(_OldVsn, State, _Extra) ->
-    {ok, State}.
-
-handle_info({'DOWN', MonRef, _, Pid, _}, #srv{referrers=Referrers}=Srv) ->
-    {ok, {MonRef, _RefCount}} = dict:find(Pid, Referrers),
-    Srv2 = Srv#srv{referrers=dict:erase(Pid, Referrers)},
-    case should_close() of
-    true ->
-        {stop,normal,Srv2};
-    false ->
-        {noreply,Srv2}
-    end.
-
-
-should_close() ->
-    case process_info(self(), monitors) of
-    {monitors, []} ->   true;
-    _ ->                false
-    end.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_secondary_sup.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_secondary_sup.erl b/apps/couch/src/couch_secondary_sup.erl
deleted file mode 100644
index 6dd5604..0000000
--- a/apps/couch/src/couch_secondary_sup.erl
+++ /dev/null
@@ -1,49 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_secondary_sup).
--behaviour(supervisor).
--export([init/1, start_link/0]).
-
-start_link() ->
-    supervisor:start_link({local,couch_secondary_services}, ?MODULE, []).
-
-init([]) ->
-    SecondarySupervisors = [
-        {couch_db_update_notifier_sup,
-            {couch_db_update_notifier_sup, start_link, []},
-            permanent,
-            infinity,
-            supervisor,
-            [couch_db_update_notifier_sup]},
-
-        {couch_plugin_event,
-            {gen_event, start_link, [{local, couch_plugin}]},
-            permanent,
-            brutal_kill,
-            worker,
-            dynamic}
-    ],
-    Children = SecondarySupervisors ++ [
-        begin
-            {ok, {Module, Fun, Args}} = couch_util:parse_term(SpecStr),
-
-            {list_to_atom(Name),
-                {Module, Fun, Args},
-                permanent,
-                brutal_kill,
-                worker,
-                [Module]}
-        end
-        || {Name, SpecStr}
-        <- couch_config:get("daemons"), SpecStr /= ""],
-    {ok, {{one_for_one, 10, 3600}, Children}}.


[78/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/smpdtfmt.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/smpdtfmt.h b/src/apps/couch_collate/platform/osx/icu/unicode/smpdtfmt.h
new file mode 100644
index 0000000..e7ce15b
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/smpdtfmt.h
@@ -0,0 +1,975 @@
+/*
+* Copyright (C) 1997-2009, International Business Machines Corporation and others. All Rights Reserved.
+*******************************************************************************
+*
+* File SMPDTFMT.H
+*
+* Modification History:
+*
+*   Date        Name        Description
+*   02/19/97    aliu        Converted from java.
+*   07/09/97    helena      Make ParsePosition into a class.
+*   07/21/98    stephen     Added GMT_PLUS, GMT_MINUS
+*                            Changed setTwoDigitStartDate to set2DigitYearStart
+*                            Changed getTwoDigitStartDate to get2DigitYearStart
+*                            Removed subParseLong
+*                            Removed getZoneIndex (added in DateFormatSymbols)
+*   06/14/99    stephen     Removed fgTimeZoneDataSuffix
+*   10/14/99    aliu        Updated class doc to describe 2-digit year parsing
+*                           {j28 4182066}.
+*******************************************************************************
+*/
+
+#ifndef SMPDTFMT_H
+#define SMPDTFMT_H
+
+#include "unicode/utypes.h"
+
+/**
+ * \file 
+ * \brief C++ API: Format and parse dates in a language-independent manner.
+ */
+ 
+#if !UCONFIG_NO_FORMATTING
+
+#include "unicode/datefmt.h"
+
+U_NAMESPACE_BEGIN
+
+class DateFormatSymbols;
+class DateFormat;
+class MessageFormat;
+
+/**
+ *
+ * SimpleDateFormat is a concrete class for formatting and parsing dates in a
+ * language-independent manner. It allows for formatting (millis -> text),
+ * parsing (text -> millis), and normalization. Formats/Parses a date or time,
+ * which is the standard milliseconds since 24:00 GMT, Jan 1, 1970.
+ * <P>
+ * Clients are encouraged to create a date-time formatter using DateFormat::getInstance(),
+ * getDateInstance(), getDateInstance(), or getDateTimeInstance() rather than
+ * explicitly constructing an instance of SimpleDateFormat.  This way, the client
+ * is guaranteed to get an appropriate formatting pattern for whatever locale the
+ * program is running in.  However, if the client needs something more unusual than
+ * the default patterns in the locales, he can construct a SimpleDateFormat directly
+ * and give it an appropriate pattern (or use one of the factory methods on DateFormat
+ * and modify the pattern after the fact with toPattern() and applyPattern().
+ * <P>
+ * Date/Time format syntax:
+ * <P>
+ * The date/time format is specified by means of a string time pattern. In this
+ * pattern, all ASCII letters are reserved as pattern letters, which are defined
+ * as the following:
+ * <pre>
+ * \code
+ * Symbol   Meaning                 Presentation        Example
+ * ------   -------                 ------------        -------
+ * G        era designator          (Text)              AD
+ * y        year                    (Number)            1996
+ * Y        year (week of year)     (Number)            1997
+ * u        extended year           (Number)            4601
+ * Q        Quarter                 (Text & Number)     Q2 & 02
+ * M        month in year           (Text & Number)     July & 07
+ * d        day in month            (Number)            10
+ * h        hour in am/pm (1~12)    (Number)            12
+ * H        hour in day (0~23)      (Number)            0
+ * m        minute in hour          (Number)            30
+ * s        second in minute        (Number)            55
+ * S        fractional second       (Number)            978
+ * E        day of week             (Text)              Tuesday
+ * e        day of week (local 1~7) (Text & Number)     Tues & 2
+ * D        day in year             (Number)            189
+ * F        day of week in month    (Number)            2 (2nd Wed in July)
+ * w        week in year            (Number)            27
+ * W        week in month           (Number)            2
+ * a        am/pm marker            (Text)              PM
+ * k        hour in day (1~24)      (Number)            24
+ * K        hour in am/pm (0~11)    (Number)            0
+ * z        time zone               (Time)              Pacific Standard Time
+ * Z        time zone (RFC 822)     (Number)            -0800
+ * v        time zone (generic)     (Text)              Pacific Time
+ * V        time zone (abreviation) (Text)              PT
+ * VVVV     time zone (location)    (Text)              United States (Los Angeles)
+ * g        Julian day              (Number)            2451334
+ * A        milliseconds in day     (Number)            69540000
+ * q        stand alone quarter     (Text & Number)     Q2 & 02
+ * L        stand alone month       (Text & Number)     July & 07
+ * c        stand alone day of week (Text & Number)     Tuesday & 2
+ * '        escape for text         (Delimiter)         'Date='
+ * ''       single quote            (Literal)           'o''clock'
+ * \endcode
+ * </pre>
+ * The count of pattern letters determine the format.
+ * <P>
+ * (Text): 4 or more, use full form, &lt;4, use short or abbreviated form if it
+ * exists. (e.g., "EEEE" produces "Monday", "EEE" produces "Mon")
+ * <P>
+ * (Number): the minimum number of digits. Shorter numbers are zero-padded to
+ * this amount (e.g. if "m" produces "6", "mm" produces "06"). Year is handled
+ * specially; that is, if the count of 'y' is 2, the Year will be truncated to 2 digits.
+ * (e.g., if "yyyy" produces "1997", "yy" produces "97".)
+ * Unlike other fields, fractional seconds are padded on the right with zero.
+ * <P>
+ * (Text & Number): 3 or over, use text, otherwise use number.  (e.g., "M" produces "1",
+ * "MM" produces "01", "MMM" produces "Jan", and "MMMM" produces "January".)
+ * <P>
+ * Any characters in the pattern that are not in the ranges of ['a'..'z'] and
+ * ['A'..'Z'] will be treated as quoted text. For instance, characters
+ * like ':', '.', ' ', '#' and '@' will appear in the resulting time text
+ * even they are not embraced within single quotes.
+ * <P>
+ * A pattern containing any invalid pattern letter will result in a failing
+ * UErrorCode result during formatting or parsing.
+ * <P>
+ * Examples using the US locale:
+ * <pre>
+ * \code
+ *    Format Pattern                         Result
+ *    --------------                         -------
+ *    "yyyy.MM.dd G 'at' HH:mm:ss vvvv" ->>  1996.07.10 AD at 15:08:56 Pacific Time
+ *    "EEE, MMM d, ''yy"                ->>  Wed, July 10, '96
+ *    "h:mm a"                          ->>  12:08 PM
+ *    "hh 'o''clock' a, zzzz"           ->>  12 o'clock PM, Pacific Daylight Time
+ *    "K:mm a, vvv"                     ->>  0:00 PM, PT
+ *    "yyyyy.MMMMM.dd GGG hh:mm aaa"    ->>  1996.July.10 AD 12:08 PM
+ * \endcode
+ * </pre>
+ * Code Sample:
+ * <pre>
+ * \code
+ *     UErrorCode success = U_ZERO_ERROR;
+ *     SimpleTimeZone* pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, "PST");
+ *     pdt->setStartRule( Calendar::APRIL, 1, Calendar::SUNDAY, 2*60*60*1000);
+ *     pdt->setEndRule( Calendar::OCTOBER, -1, Calendar::SUNDAY, 2*60*60*1000);
+ *
+ *     // Format the current time.
+ *     SimpleDateFormat* formatter
+ *         = new SimpleDateFormat ("yyyy.MM.dd G 'at' hh:mm:ss a zzz", success );
+ *     GregorianCalendar cal(success);
+ *     UDate currentTime_1 = cal.getTime(success);
+ *     FieldPosition fp(0);
+ *     UnicodeString dateString;
+ *     formatter->format( currentTime_1, dateString, fp );
+ *     cout << "result: " << dateString << endl;
+ *
+ *     // Parse the previous string back into a Date.
+ *     ParsePosition pp(0);
+ *     UDate currentTime_2 = formatter->parse(dateString, pp );
+ * \endcode
+ * </pre>
+ * In the above example, the time value "currentTime_2" obtained from parsing
+ * will be equal to currentTime_1. However, they may not be equal if the am/pm
+ * marker 'a' is left out from the format pattern while the "hour in am/pm"
+ * pattern symbol is used. This information loss can happen when formatting the
+ * time in PM.
+ *
+ * <p>
+ * When parsing a date string using the abbreviated year pattern ("y" or "yy"),
+ * SimpleDateFormat must interpret the abbreviated year
+ * relative to some century.  It does this by adjusting dates to be
+ * within 80 years before and 20 years after the time the SimpleDateFormat
+ * instance is created. For example, using a pattern of "MM/dd/yy" and a
+ * SimpleDateFormat instance created on Jan 1, 1997,  the string
+ * "01/11/12" would be interpreted as Jan 11, 2012 while the string "05/04/64"
+ * would be interpreted as May 4, 1964.
+ * During parsing, only strings consisting of exactly two digits, as defined by
+ * <code>Unicode::isDigit()</code>, will be parsed into the default century.
+ * Any other numeric string, such as a one digit string, a three or more digit
+ * string, or a two digit string that isn't all digits (for example, "-1"), is
+ * interpreted literally.  So "01/02/3" or "01/02/003" are parsed, using the
+ * same pattern, as Jan 2, 3 AD.  Likewise, "01/02/-3" is parsed as Jan 2, 4 BC.
+ *
+ * <p>
+ * If the year pattern has more than two 'y' characters, the year is
+ * interpreted literally, regardless of the number of digits.  So using the
+ * pattern "MM/dd/yyyy", "01/11/12" parses to Jan 11, 12 A.D.
+ *
+ * <p>
+ * When numeric fields abut one another directly, with no intervening delimiter
+ * characters, they constitute a run of abutting numeric fields.  Such runs are
+ * parsed specially.  For example, the format "HHmmss" parses the input text
+ * "123456" to 12:34:56, parses the input text "12345" to 1:23:45, and fails to
+ * parse "1234".  In other words, the leftmost field of the run is flexible,
+ * while the others keep a fixed width.  If the parse fails anywhere in the run,
+ * then the leftmost field is shortened by one character, and the entire run is
+ * parsed again. This is repeated until either the parse succeeds or the
+ * leftmost field is one character in length.  If the parse still fails at that
+ * point, the parse of the run fails.
+ *
+ * <P>
+ * For time zones that have no names, SimpleDateFormat uses strings GMT+hours:minutes or
+ * GMT-hours:minutes.
+ * <P>
+ * The calendar defines what is the first day of the week, the first week of the
+ * year, whether hours are zero based or not (0 vs 12 or 24), and the timezone.
+ * There is one common number format to handle all the numbers; the digit count
+ * is handled programmatically according to the pattern.
+ *
+ * <p><em>User subclasses are not supported.</em> While clients may write
+ * subclasses, such code will not necessarily work and will not be
+ * guaranteed to work stably from release to release.
+ */
+class U_I18N_API SimpleDateFormat: public DateFormat {
+public:
+    /**
+     * Construct a SimpleDateFormat using the default pattern for the default
+     * locale.
+     * <P>
+     * [Note:] Not all locales support SimpleDateFormat; for full generality,
+     * use the factory methods in the DateFormat class.
+     * @param status    Output param set to success/failure code.
+     * @stable ICU 2.0
+     */
+    SimpleDateFormat(UErrorCode& status);
+
+    /**
+     * Construct a SimpleDateFormat using the given pattern and the default locale.
+     * The locale is used to obtain the symbols used in formatting (e.g., the
+     * names of the months), but not to provide the pattern.
+     * <P>
+     * [Note:] Not all locales support SimpleDateFormat; for full generality,
+     * use the factory methods in the DateFormat class.
+     * @param pattern    the pattern for the format.
+     * @param status     Output param set to success/failure code.
+     * @stable ICU 2.0
+     */
+    SimpleDateFormat(const UnicodeString& pattern,
+                     UErrorCode& status);
+
+    /**
+     * Construct a SimpleDateFormat using the given pattern and locale.
+     * The locale is used to obtain the symbols used in formatting (e.g., the
+     * names of the months), but not to provide the pattern.
+     * <P>
+     * [Note:] Not all locales support SimpleDateFormat; for full generality,
+     * use the factory methods in the DateFormat class.
+     * @param pattern    the pattern for the format.
+     * @param locale     the given locale.
+     * @param status     Output param set to success/failure code.
+     * @stable ICU 2.0
+     */
+    SimpleDateFormat(const UnicodeString& pattern,
+                     const Locale& locale,
+                     UErrorCode& status);
+
+    /**
+     * Construct a SimpleDateFormat using the given pattern and locale-specific
+     * symbol data.  The formatter takes ownership of the DateFormatSymbols object;
+     * the caller is no longer responsible for deleting it.
+     * @param pattern           the given pattern for the format.
+     * @param formatDataToAdopt the symbols to be adopted.
+     * @param status            Output param set to success/faulure code.
+     * @stable ICU 2.0
+     */
+    SimpleDateFormat(const UnicodeString& pattern,
+                     DateFormatSymbols* formatDataToAdopt,
+                     UErrorCode& status);
+
+    /**
+     * Construct a SimpleDateFormat using the given pattern and locale-specific
+     * symbol data.  The DateFormatSymbols object is NOT adopted; the caller
+     * remains responsible for deleting it.
+     * @param pattern           the given pattern for the format.
+     * @param formatData        the formatting symbols to be use.
+     * @param status            Output param set to success/faulure code.
+     * @stable ICU 2.0
+     */
+    SimpleDateFormat(const UnicodeString& pattern,
+                     const DateFormatSymbols& formatData,
+                     UErrorCode& status);
+
+    /**
+     * Copy constructor.
+     * @stable ICU 2.0
+     */
+    SimpleDateFormat(const SimpleDateFormat&);
+
+    /**
+     * Assignment operator.
+     * @stable ICU 2.0
+     */
+    SimpleDateFormat& operator=(const SimpleDateFormat&);
+
+    /**
+     * Destructor.
+     * @stable ICU 2.0
+     */
+    virtual ~SimpleDateFormat();
+
+    /**
+     * Clone this Format object polymorphically. The caller owns the result and
+     * should delete it when done.
+     * @return    A copy of the object.
+     * @stable ICU 2.0
+     */
+    virtual Format* clone(void) const;
+
+    /**
+     * Return true if the given Format objects are semantically equal. Objects
+     * of different subclasses are considered unequal.
+     * @param other    the object to be compared with.
+     * @return         true if the given Format objects are semantically equal.
+     * @stable ICU 2.0
+     */
+    virtual UBool operator==(const Format& other) const;
+
+    /**
+     * Format a date or time, which is the standard millis since 24:00 GMT, Jan
+     * 1, 1970. Overrides DateFormat pure virtual method.
+     * <P>
+     * Example: using the US locale: "yyyy.MM.dd e 'at' HH:mm:ss zzz" ->>
+     * 1996.07.10 AD at 15:08:56 PDT
+     *
+     * @param cal       Calendar set to the date and time to be formatted
+     *                  into a date/time string.
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     * @param pos       The formatting position. On input: an alignment field,
+     *                  if desired. On output: the offsets of the alignment field.
+     * @return          Reference to 'appendTo' parameter.
+     * @stable ICU 2.1
+     */
+    virtual UnicodeString& format(  Calendar& cal,
+                                    UnicodeString& appendTo,
+                                    FieldPosition& pos) const;
+
+    /**
+     * Format a date or time, which is the standard millis since 24:00 GMT, Jan
+     * 1, 1970. Overrides DateFormat pure virtual method.
+     * <P>
+     * Example: using the US locale: "yyyy.MM.dd e 'at' HH:mm:ss zzz" ->>
+     * 1996.07.10 AD at 15:08:56 PDT
+     *
+     * @param obj       A Formattable containing the date-time value to be formatted
+     *                  into a date-time string.  If the type of the Formattable
+     *                  is a numeric type, it is treated as if it were an
+     *                  instance of Date.
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     * @param pos       The formatting position. On input: an alignment field,
+     *                  if desired. On output: the offsets of the alignment field.
+     * @param status    Output param set to success/faulure code.
+     * @return          Reference to 'appendTo' parameter.
+     * @stable ICU 2.0
+     */
+    virtual UnicodeString& format(  const Formattable& obj,
+                                    UnicodeString& appendTo,
+                                    FieldPosition& pos,
+                                    UErrorCode& status) const;
+
+    /**
+     * Redeclared DateFormat method.
+     * @param date          the Date value to be formatted.
+     * @param appendTo      Output parameter to receive result.
+     *                      Result is appended to existing contents.
+     * @param fieldPosition The formatting position. On input: an alignment field,
+     *                      if desired. On output: the offsets of the alignment field.
+     * @return              Reference to 'appendTo' parameter.
+     * @stable ICU 2.1
+     */
+    UnicodeString& format(UDate date,
+                          UnicodeString& appendTo,
+                          FieldPosition& fieldPosition) const;
+
+    /**
+     * Redeclared DateFormat method.
+     * @param obj       Object to be formatted.
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     * @param status    Input/output success/failure code.
+     * @return          Reference to 'appendTo' parameter.
+     * @stable ICU 2.0
+     */
+    UnicodeString& format(const Formattable& obj,
+                          UnicodeString& appendTo,
+                          UErrorCode& status) const;
+
+    /**
+     * Redeclared DateFormat method.
+     * @param date      Date value to be formatted.
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     * @return          Reference to 'appendTo' parameter.
+     * @stable ICU 2.0
+     */
+    UnicodeString& format(UDate date, UnicodeString& appendTo) const;
+
+    /**
+     * Parse a date/time string beginning at the given parse position. For
+     * example, a time text "07/10/96 4:5 PM, PDT" will be parsed into a Date
+     * that is equivalent to Date(837039928046).
+     * <P>
+     * By default, parsing is lenient: If the input is not in the form used by
+     * this object's format method but can still be parsed as a date, then the
+     * parse succeeds. Clients may insist on strict adherence to the format by
+     * calling setLenient(false).
+     *
+     * @param text  The date/time string to be parsed
+     * @param cal   a Calendar set to the date and time to be formatted
+     *              into a date/time string.
+     * @param pos   On input, the position at which to start parsing; on
+     *              output, the position at which parsing terminated, or the
+     *              start position if the parse failed.
+     * @return      A valid UDate if the input could be parsed.
+     * @stable ICU 2.1
+     */
+    virtual void parse( const UnicodeString& text,
+                        Calendar& cal,
+                        ParsePosition& pos) const;
+
+    /**
+     * Parse a date/time string starting at the given parse position. For
+     * example, a time text "07/10/96 4:5 PM, PDT" will be parsed into a Date
+     * that is equivalent to Date(837039928046).
+     * <P>
+     * By default, parsing is lenient: If the input is not in the form used by
+     * this object's format method but can still be parsed as a date, then the
+     * parse succeeds. Clients may insist on strict adherence to the format by
+     * calling setLenient(false).
+     *
+     * @see DateFormat::setLenient(boolean)
+     *
+     * @param text  The date/time string to be parsed
+     * @param pos   On input, the position at which to start parsing; on
+     *              output, the position at which parsing terminated, or the
+     *              start position if the parse failed.
+     * @return      A valid UDate if the input could be parsed.
+     * @stable ICU 2.0
+     */
+    UDate parse( const UnicodeString& text,
+                 ParsePosition& pos) const;
+
+
+    /**
+     * Parse a date/time string. For example, a time text "07/10/96 4:5 PM, PDT"
+     * will be parsed into a UDate that is equivalent to Date(837039928046).
+     * Parsing begins at the beginning of the string and proceeds as far as
+     * possible.  Assuming no parse errors were encountered, this function
+     * doesn't return any information about how much of the string was consumed
+     * by the parsing.  If you need that information, use the version of
+     * parse() that takes a ParsePosition.
+     *
+     * @param text  The date/time string to be parsed
+     * @param status Filled in with U_ZERO_ERROR if the parse was successful, and with
+     *              an error value if there was a parse error.
+     * @return      A valid UDate if the input could be parsed.
+     * @stable ICU 2.0
+     */
+    virtual UDate parse( const UnicodeString& text,
+                        UErrorCode& status) const;
+
+    /**
+     * Set the start UDate used to interpret two-digit year strings.
+     * When dates are parsed having 2-digit year strings, they are placed within
+     * a assumed range of 100 years starting on the two digit start date.  For
+     * example, the string "24-Jan-17" may be in the year 1817, 1917, 2017, or
+     * some other year.  SimpleDateFormat chooses a year so that the resultant
+     * date is on or after the two digit start date and within 100 years of the
+     * two digit start date.
+     * <P>
+     * By default, the two digit start date is set to 80 years before the current
+     * time at which a SimpleDateFormat object is created.
+     * @param d      start UDate used to interpret two-digit year strings.
+     * @param status Filled in with U_ZERO_ERROR if the parse was successful, and with
+     *               an error value if there was a parse error.
+     * @stable ICU 2.0
+     */
+    virtual void set2DigitYearStart(UDate d, UErrorCode& status);
+
+    /**
+     * Get the start UDate used to interpret two-digit year strings.
+     * When dates are parsed having 2-digit year strings, they are placed within
+     * a assumed range of 100 years starting on the two digit start date.  For
+     * example, the string "24-Jan-17" may be in the year 1817, 1917, 2017, or
+     * some other year.  SimpleDateFormat chooses a year so that the resultant
+     * date is on or after the two digit start date and within 100 years of the
+     * two digit start date.
+     * <P>
+     * By default, the two digit start date is set to 80 years before the current
+     * time at which a SimpleDateFormat object is created.
+     * @param status Filled in with U_ZERO_ERROR if the parse was successful, and with
+     *               an error value if there was a parse error.
+     * @stable ICU 2.0
+     */
+    UDate get2DigitYearStart(UErrorCode& status) const;
+
+    /**
+     * Return a pattern string describing this date format.
+     * @param result Output param to receive the pattern.
+     * @return       A reference to 'result'.
+     * @stable ICU 2.0
+     */
+    virtual UnicodeString& toPattern(UnicodeString& result) const;
+
+    /**
+     * Return a localized pattern string describing this date format.
+     * In most cases, this will return the same thing as toPattern(),
+     * but a locale can specify characters to use in pattern descriptions
+     * in place of the ones described in this class's class documentation.
+     * (Presumably, letters that would be more mnemonic in that locale's
+     * language.)  This function would produce a pattern using those
+     * letters.
+     *
+     * @param result    Receives the localized pattern.
+     * @param status    Output param set to success/failure code on
+     *                  exit. If the pattern is invalid, this will be
+     *                  set to a failure result.
+     * @return          A reference to 'result'.
+     * @stable ICU 2.0
+     */
+    virtual UnicodeString& toLocalizedPattern(UnicodeString& result,
+                                              UErrorCode& status) const;
+
+    /**
+     * Apply the given unlocalized pattern string to this date format.
+     * (i.e., after this call, this formatter will format dates according to
+     * the new pattern)
+     *
+     * @param pattern   The pattern to be applied.
+     * @stable ICU 2.0
+     */
+    virtual void applyPattern(const UnicodeString& pattern);
+
+    /**
+     * Apply the given localized pattern string to this date format.
+     * (see toLocalizedPattern() for more information on localized patterns.)
+     *
+     * @param pattern   The localized pattern to be applied.
+     * @param status    Output param set to success/failure code on
+     *                  exit. If the pattern is invalid, this will be
+     *                  set to a failure result.
+     * @stable ICU 2.0
+     */
+    virtual void applyLocalizedPattern(const UnicodeString& pattern,
+                                       UErrorCode& status);
+
+    /**
+     * Gets the date/time formatting symbols (this is an object carrying
+     * the various strings and other symbols used in formatting: e.g., month
+     * names and abbreviations, time zone names, AM/PM strings, etc.)
+     * @return a copy of the date-time formatting data associated
+     * with this date-time formatter.
+     * @stable ICU 2.0
+     */
+    virtual const DateFormatSymbols* getDateFormatSymbols(void) const;
+
+    /**
+     * Set the date/time formatting symbols.  The caller no longer owns the
+     * DateFormatSymbols object and should not delete it after making this call.
+     * @param newFormatSymbols the given date-time formatting symbols to copy.
+     * @stable ICU 2.0
+     */
+    virtual void adoptDateFormatSymbols(DateFormatSymbols* newFormatSymbols);
+
+    /**
+     * Set the date/time formatting data.
+     * @param newFormatSymbols the given date-time formatting symbols to copy.
+     * @stable ICU 2.0
+     */
+    virtual void setDateFormatSymbols(const DateFormatSymbols& newFormatSymbols);
+
+    /**
+     * Return the class ID for this class. This is useful only for comparing to
+     * a return value from getDynamicClassID(). For example:
+     * <pre>
+     * .   Base* polymorphic_pointer = createPolymorphicObject();
+     * .   if (polymorphic_pointer->getDynamicClassID() ==
+     * .       erived::getStaticClassID()) ...
+     * </pre>
+     * @return          The class ID for all objects of this class.
+     * @stable ICU 2.0
+     */
+    static UClassID U_EXPORT2 getStaticClassID(void);
+
+    /**
+     * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This
+     * method is to implement a simple version of RTTI, since not all C++
+     * compilers support genuine RTTI. Polymorphic operator==() and clone()
+     * methods call this method.
+     *
+     * @return          The class ID for this object. All objects of a
+     *                  given class have the same class ID.  Objects of
+     *                  other classes have different class IDs.
+     * @stable ICU 2.0
+     */
+    virtual UClassID getDynamicClassID(void) const;
+
+    /**
+     * Set the calendar to be used by this date format. Initially, the default
+     * calendar for the specified or default locale is used.  The caller should
+     * not delete the Calendar object after it is adopted by this call.
+     * Adopting a new calendar will change to the default symbols.
+     *
+     * @param calendarToAdopt    Calendar object to be adopted.
+     * @stable ICU 2.0
+     */
+    virtual void adoptCalendar(Calendar* calendarToAdopt);
+
+    /**
+     * This is for ICU internal use only. Please do not use.
+     * Check whether the 'field' is smaller than all the fields covered in
+     * pattern, return TRUE if it is. The sequence of calendar field, 
+     * from large to small is: ERA, YEAR, MONTH, DATE, AM_PM, HOUR, MINUTE,...
+     * @param field    the calendar field need to check against
+     * @return         TRUE if the 'field' is smaller than all the fields 
+     *                 covered in pattern. FALSE otherwise.
+     * @internal ICU 4.0
+     */
+    UBool isFieldUnitIgnored(UCalendarDateFields field) const;
+
+
+    /**
+     * This is for ICU internal use only. Please do not use.
+     * Check whether the 'field' is smaller than all the fields covered in
+     * pattern, return TRUE if it is. The sequence of calendar field, 
+     * from large to small is: ERA, YEAR, MONTH, DATE, AM_PM, HOUR, MINUTE,...
+     * @param pattern  the pattern to check against
+     * @param field    the calendar field need to check against
+     * @return         TRUE if the 'field' is smaller than all the fields 
+     *                 covered in pattern. FALSE otherwise.
+     * @internal ICU 4.0
+     */
+    static UBool isFieldUnitIgnored(const UnicodeString& pattern, 
+                                    UCalendarDateFields field);
+
+
+
+    /**
+     * This is for ICU internal use only. Please do not use.
+     * Get the locale of this simple date formatter.
+     * It is used in DateIntervalFormat.
+     *
+     * @return   locale in this simple date formatter
+     * @internal ICU 4.0
+     */
+    const Locale& getSmpFmtLocale(void) const;
+
+
+private:
+    friend class DateFormat;
+
+    void initializeDefaultCentury(void);
+
+    SimpleDateFormat(); // default constructor not implemented
+
+    /**
+     * Used by the DateFormat factory methods to construct a SimpleDateFormat.
+     * @param timeStyle the time style.
+     * @param dateStyle the date style.
+     * @param locale    the given locale.
+     * @param status    Output param set to success/failure code on
+     *                  exit.
+     */
+    SimpleDateFormat(EStyle timeStyle, EStyle dateStyle, const Locale& locale, UErrorCode& status);
+
+    /**
+     * Construct a SimpleDateFormat for the given locale.  If no resource data
+     * is available, create an object of last resort, using hard-coded strings.
+     * This is an internal method, called by DateFormat.  It should never fail.
+     * @param locale    the given locale.
+     * @param status    Output param set to success/failure code on
+     *                  exit.
+     */
+    SimpleDateFormat(const Locale& locale, UErrorCode& status); // Use default pattern
+
+    /**
+     * Called by format() to format a single field.
+     *
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     * @param ch        The format character we encountered in the pattern.
+     * @param count     Number of characters in the current pattern symbol (e.g.,
+     *                  "yyyy" in the pattern would result in a call to this function
+     *                  with ch equal to 'y' and count equal to 4)
+     * @param pos       The FieldPosition being filled in by the format() call.  If
+     *                  this function is formatting the field specfied by pos, it
+     *                  will fill in pos with the beginning and ending offsets of the
+     *                  field.
+     * @param status    Receives a status code, which will be U_ZERO_ERROR if the operation
+     *                  succeeds.
+     */
+    void subFormat(             UnicodeString &appendTo,
+                                UChar ch,
+                                int32_t count,
+                                FieldPosition& pos,
+                                Calendar& cal,
+                                UErrorCode& status) const; // in case of illegal argument
+
+    /**
+     * Used by subFormat() to format a numeric value.
+     * Appends to toAppendTo a string representation of "value"
+     * having a number of digits between "minDigits" and
+     * "maxDigits".  Uses the DateFormat's NumberFormat.
+     *
+     * @param appendTo  Output parameter to receive result.
+     *                  Formatted number is appended to existing contents.
+     * @param value     Value to format.
+     * @param minDigits Minimum number of digits the result should have
+     * @param maxDigits Maximum number of digits the result should have
+     */
+    void zeroPaddingNumber(          UnicodeString &appendTo,
+                                     int32_t value,
+                                     int32_t minDigits,
+                                     int32_t maxDigits) const;
+
+    /**
+     * Return true if the given format character, occuring count
+     * times, represents a numeric field.
+     */
+    static UBool isNumeric(UChar formatChar, int32_t count);
+
+    /**
+     * initializes fCalendar from parameters.  Returns fCalendar as a convenience.
+     * @param adoptZone  Zone to be adopted, or NULL for TimeZone::createDefault().
+     * @param locale Locale of the calendar
+     * @param status Error code
+     * @return the newly constructed fCalendar
+     */
+    Calendar *initializeCalendar(TimeZone* adoptZone, const Locale& locale, UErrorCode& status);
+
+    /**
+     * initializes fSymbols from parameters.
+     * @param locale Locale of the symbols
+     * @param calendar Alias to Calendar that will be used.
+     * @param status Error code
+     */
+    void initializeSymbols(const Locale& locale, Calendar* calendar, UErrorCode& status);
+
+    /**
+     * Called by several of the constructors to load pattern data and formatting symbols
+     * out of a resource bundle and initialize the locale based on it.
+     * @param timeStyle     The time style, as passed to DateFormat::createDateInstance().
+     * @param dateStyle     The date style, as passed to DateFormat::createTimeInstance().
+     * @param locale        The locale to load the patterns from.
+     * @param status        Filled in with an error code if loading the data from the
+     *                      resources fails.
+     */
+    void construct(EStyle timeStyle, EStyle dateStyle, const Locale& locale, UErrorCode& status);
+
+    /**
+     * Called by construct() and the various constructors to set up the SimpleDateFormat's
+     * Calendar and NumberFormat objects.
+     * @param locale    The locale for which we want a Calendar and a NumberFormat.
+     * @param statuc    Filled in with an error code if creating either subobject fails.
+     */
+    void initialize(const Locale& locale, UErrorCode& status);
+
+    /**
+     * Private code-size reduction function used by subParse.
+     * @param text the time text being parsed.
+     * @param start where to start parsing.
+     * @param field the date field being parsed.
+     * @param stringArray the string array to parsed.
+     * @param stringArrayCount the size of the array.
+     * @param cal a Calendar set to the date and time to be formatted
+     *            into a date/time string.
+     * @return the new start position if matching succeeded; a negative number
+     * indicating matching failure, otherwise.
+     */
+    int32_t matchString(const UnicodeString& text, int32_t start, UCalendarDateFields field,
+                        const UnicodeString* stringArray, int32_t stringArrayCount, Calendar& cal) const;
+
+    /**
+     * Private code-size reduction function used by subParse.
+     * @param text the time text being parsed.
+     * @param start where to start parsing.
+     * @param field the date field being parsed.
+     * @param stringArray the string array to parsed.
+     * @param stringArrayCount the size of the array.
+     * @param cal a Calendar set to the date and time to be formatted
+     *            into a date/time string.
+     * @return the new start position if matching succeeded; a negative number
+     * indicating matching failure, otherwise.
+     */
+    int32_t matchQuarterString(const UnicodeString& text, int32_t start, UCalendarDateFields field,
+                               const UnicodeString* stringArray, int32_t stringArrayCount, Calendar& cal) const;
+    
+    /**
+     * Private function used by subParse to match literal pattern text.
+     *
+     * @param pattern the pattern string
+     * @param patternOffset the starting offset into the pattern text. On
+     *        outupt will be set the offset of the first non-literal character in the pattern
+     * @param text the text being parsed
+     * @param textOffset the starting offset into the text. On output
+     *                   will be set to the offset of the character after the match
+     * @param lenient <code>TRUE</code> if the parse is lenient, <code>FALSE</code> otherwise.
+     *
+     * @return <code>TRUE</code> if the literal text could be matched, <code>FALSE</code> otherwise.
+     */
+    static UBool matchLiterals(const UnicodeString &pattern, int32_t &patternOffset,
+                               const UnicodeString &text, int32_t &textOffset, UBool lenient);
+    
+    /**
+     * Private member function that converts the parsed date strings into
+     * timeFields. Returns -start (for ParsePosition) if failed.
+     * @param text the time text to be parsed.
+     * @param start where to start parsing.
+     * @param ch the pattern character for the date field text to be parsed.
+     * @param count the count of a pattern character.
+     * @param obeyCount if true then the count is strictly obeyed.
+     * @param ambiguousYear If true then the two-digit year == the default start year.
+     * @param cal a Calendar set to the date and time to be formatted
+     *            into a date/time string.
+     * @return the new start position if matching succeeded; a negative number
+     * indicating matching failure, otherwise.
+     */
+    int32_t subParse(const UnicodeString& text, int32_t& start, UChar ch, int32_t count,
+                     UBool obeyCount, UBool allowNegative, UBool ambiguousYear[], Calendar& cal) const;
+
+    void parseInt(const UnicodeString& text,
+                  Formattable& number,
+                  ParsePosition& pos,
+                  UBool allowNegative) const;
+
+    void parseInt(const UnicodeString& text,
+                  Formattable& number,
+                  int32_t maxDigits,
+                  ParsePosition& pos,
+                  UBool allowNegative) const;
+
+    /**
+     * Translate a pattern, mapping each character in the from string to the
+     * corresponding character in the to string. Return an error if the original
+     * pattern contains an unmapped character, or if a quote is unmatched.
+     * Quoted (single quotes only) material is not translated.
+     * @param originalPattern   the original pattern.
+     * @param translatedPattern Output param to receive the translited pattern.
+     * @param from              the characters to be translited from.
+     * @param to                the characters to be translited to.
+     * @param status            Receives a status code, which will be U_ZERO_ERROR
+     *                          if the operation succeeds.
+     */
+    static void translatePattern(const UnicodeString& originalPattern,
+                                UnicodeString& translatedPattern,
+                                const UnicodeString& from,
+                                const UnicodeString& to,
+                                UErrorCode& status);
+
+    /**
+     * Sets the starting date of the 100-year window that dates with 2-digit years
+     * are considered to fall within.
+     * @param startDate the start date
+     * @param status    Receives a status code, which will be U_ZERO_ERROR
+     *                  if the operation succeeds.
+     */
+    void         parseAmbiguousDatesAsAfter(UDate startDate, UErrorCode& status);
+    
+    /**
+     * Private methods for formatting/parsing GMT string
+     */
+    void appendGMT(UnicodeString &appendTo, Calendar& cal, UErrorCode& status) const;
+    void formatGMTDefault(UnicodeString &appendTo, int32_t offset) const;
+    int32_t parseGMT(const UnicodeString &text, ParsePosition &pos) const;
+    int32_t parseGMTDefault(const UnicodeString &text, ParsePosition &pos) const;
+    UBool isDefaultGMTFormat() const;
+
+    void formatRFC822TZ(UnicodeString &appendTo, int32_t offset) const;
+
+    /**
+     * Initialize MessageFormat instances used for GMT formatting/parsing
+     */
+    void initGMTFormatters(UErrorCode &status);
+
+    /**
+     * Used to map pattern characters to Calendar field identifiers.
+     */
+    static const UCalendarDateFields fgPatternIndexToCalendarField[];
+
+    /**
+     * Map index into pattern character string to DateFormat field number
+     */
+    static const UDateFormatField fgPatternIndexToDateFormatField[];
+
+    /**
+     * Used to map Calendar field to field level.
+     * The larger the level, the smaller the field unit.
+     * For example, UCAL_ERA level is 0, UCAL_YEAR level is 10,
+     * UCAL_MONTH level is 20.
+     */
+    static const int32_t fgCalendarFieldToLevel[];
+    static const int32_t fgPatternCharToLevel[];
+
+    /**
+     * The formatting pattern for this formatter.
+     */
+    UnicodeString       fPattern;
+
+    /**
+     * The original locale used (for reloading symbols)
+     */
+    Locale              fLocale;
+
+    /**
+     * A pointer to an object containing the strings to use in formatting (e.g.,
+     * month and day names, AM and PM strings, time zone names, etc.)
+     */
+    DateFormatSymbols*  fSymbols;   // Owned
+
+    /**
+     * If dates have ambiguous years, we map them into the century starting
+     * at defaultCenturyStart, which may be any date.  If defaultCenturyStart is
+     * set to SYSTEM_DEFAULT_CENTURY, which it is by default, then the system
+     * values are used.  The instance values defaultCenturyStart and
+     * defaultCenturyStartYear are only used if explicitly set by the user
+     * through the API method parseAmbiguousDatesAsAfter().
+     */
+    UDate                fDefaultCenturyStart;
+
+    /**
+     * See documentation for defaultCenturyStart.
+     */
+    /*transient*/ int32_t   fDefaultCenturyStartYear;
+
+    enum ParsedTZType {
+        TZTYPE_UNK,
+        TZTYPE_STD,
+        TZTYPE_DST
+    };
+
+    ParsedTZType tztype; // here to avoid api change
+
+    /*
+     * MessageFormat instances used for localized GMT format
+     */
+    MessageFormat   **fGMTFormatters;
+
+    UBool fHaveDefaultCentury;
+};
+
+inline UDate
+SimpleDateFormat::get2DigitYearStart(UErrorCode& /*status*/) const
+{
+    return fDefaultCenturyStart;
+}
+
+inline UnicodeString&
+SimpleDateFormat::format(const Formattable& obj,
+                         UnicodeString& appendTo,
+                         UErrorCode& status) const {
+    // Don't use Format:: - use immediate base class only,
+    // in case immediate base modifies behavior later.
+    return DateFormat::format(obj, appendTo, status);
+}
+
+inline UnicodeString&
+SimpleDateFormat::format(UDate date,
+                         UnicodeString& appendTo,
+                         FieldPosition& fieldPosition) const {
+    // Don't use Format:: - use immediate base class only,
+    // in case immediate base modifies behavior later.
+    return DateFormat::format(date, appendTo, fieldPosition);
+}
+
+inline UnicodeString&
+SimpleDateFormat::format(UDate date, UnicodeString& appendTo) const {
+    return DateFormat::format(date, appendTo);
+}
+
+U_NAMESPACE_END
+
+#endif /* #if !UCONFIG_NO_FORMATTING */
+
+#endif // _SMPDTFMT
+//eof

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/sortkey.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/sortkey.h b/src/apps/couch_collate/platform/osx/icu/unicode/sortkey.h
new file mode 100644
index 0000000..ef202dd
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/sortkey.h
@@ -0,0 +1,324 @@
+/*
+ *****************************************************************************
+ * Copyright (C) 1996-2006, International Business Machines Corporation and others.
+ * All Rights Reserved.
+ *****************************************************************************
+ *
+ * File sortkey.h
+ *
+ * Created by: Helena Shih
+ *
+ * Modification History:
+ *
+ *  Date         Name          Description
+ *
+ *  6/20/97     helena      Java class name change.
+ *  8/18/97     helena      Added internal API documentation.
+ *  6/26/98     erm         Changed to use byte arrays and memcmp.
+ *****************************************************************************
+ */
+
+#ifndef SORTKEY_H
+#define SORTKEY_H
+
+#include "unicode/utypes.h"
+
+/**
+ * \file 
+ * \brief C++ API: Keys for comparing strings multiple times. 
+ */
+ 
+#if !UCONFIG_NO_COLLATION
+
+#include "unicode/uobject.h"
+#include "unicode/unistr.h"
+#include "unicode/coll.h"
+
+U_NAMESPACE_BEGIN
+
+/* forward declaration */
+class RuleBasedCollator;
+
+/**
+ *
+ * Collation keys are generated by the Collator class.  Use the CollationKey objects
+ * instead of Collator to compare strings multiple times.  A CollationKey
+ * preprocesses the comparison information from the Collator object to
+ * make the comparison faster.  If you are not going to comparing strings
+ * multiple times, then using the Collator object is generally faster,
+ * since it only processes as much of the string as needed to make a
+ * comparison.
+ * <p> For example (with strength == tertiary)
+ * <p>When comparing "Abernathy" to "Baggins-Smythworthy", Collator
+ * only needs to process a couple of characters, while a comparison
+ * with CollationKeys will process all of the characters.  On the other hand,
+ * if you are doing a sort of a number of fields, it is much faster to use
+ * CollationKeys, since you will be comparing strings multiple times.
+ * <p>Typical use of CollationKeys are in databases, where you store a CollationKey
+ * in a hidden field, and use it for sorting or indexing.
+ *
+ * <p>Example of use:
+ * <pre>
+ * \code
+ *     UErrorCode success = U_ZERO_ERROR;
+ *     Collator* myCollator = Collator::createInstance(success);
+ *     CollationKey* keys = new CollationKey [3];
+ *     myCollator->getCollationKey("Tom", keys[0], success );
+ *     myCollator->getCollationKey("Dick", keys[1], success );
+ *     myCollator->getCollationKey("Harry", keys[2], success );
+ *
+ *     // Inside body of sort routine, compare keys this way:
+ *     CollationKey tmp;
+ *     if(keys[0].compareTo( keys[1] ) > 0 ) {
+ *         tmp = keys[0]; keys[0] = keys[1]; keys[1] = tmp;
+ *     }
+ *     //...
+ * \endcode
+ * </pre>
+ * <p>Because Collator::compare()'s algorithm is complex, it is faster to sort
+ * long lists of words by retrieving collation keys with Collator::getCollationKey().
+ * You can then cache the collation keys and compare them using CollationKey::compareTo().
+ * <p>
+ * <strong>Note:</strong> <code>Collator</code>s with different Locale,
+ * CollationStrength and DecompositionMode settings will return different
+ * CollationKeys for the same set of strings. Locales have specific
+ * collation rules, and the way in which secondary and tertiary differences
+ * are taken into account, for example, will result in different CollationKeys
+ * for same strings.
+ * <p>
+
+ * @see          Collator
+ * @see          RuleBasedCollator
+ * @version      1.3 12/18/96
+ * @author       Helena Shih
+ * @deprecated ICU 2.8 Use Collator::getSortKey(...) instead
+ */
+class U_I18N_API CollationKey : public UObject {
+public:
+    /**
+    * This creates an empty collation key based on the null string.  An empty
+    * collation key contains no sorting information.  When comparing two empty
+    * collation keys, the result is Collator::EQUAL.  Comparing empty collation key
+    * with non-empty collation key is always Collator::LESS.
+    * @deprecated ICU 2.8 Use Collator::getSortKey(...) instead
+    */
+    CollationKey();
+
+
+    /**
+    * Creates a collation key based on the collation key values.
+    * @param values the collation key values
+    * @param count number of collation key values, including trailing nulls.
+    * @deprecated ICU 2.8 Use Collator::getSortKey(...) instead
+    */
+    CollationKey(const  uint8_t*    values,
+                int32_t     count);
+
+    /**
+    * Copy constructor.
+    * @param other    the object to be copied.
+    * @deprecated ICU 2.8 Use Collator::getSortKey(...) instead
+    */
+    CollationKey(const CollationKey& other);
+
+    /**
+    * Sort key destructor.
+    * @deprecated ICU 2.8 Use Collator::getSortKey(...) instead
+    */
+    virtual ~CollationKey();
+
+    /**
+    * Assignment operator
+    * @param other    the object to be copied.
+    * @deprecated ICU 2.8 Use Collator::getSortKey(...) instead
+    */
+    const   CollationKey&   operator=(const CollationKey& other);
+
+    /**
+    * Compare if two collation keys are the same.
+    * @param source the collation key to compare to.
+    * @return Returns true if two collation keys are equal, false otherwise.
+    * @deprecated ICU 2.8 Use Collator::getSortKey(...) instead
+    */
+    UBool                   operator==(const CollationKey& source) const;
+
+    /**
+    * Compare if two collation keys are not the same.
+    * @param source the collation key to compare to.
+    * @return Returns TRUE if two collation keys are different, FALSE otherwise.
+    * @deprecated ICU 2.8 Use Collator::getSortKey(...) instead
+    */
+    UBool                   operator!=(const CollationKey& source) const;
+
+
+    /**
+    * Test to see if the key is in an invalid state. The key will be in an
+    * invalid state if it couldn't allocate memory for some operation.
+    * @return Returns TRUE if the key is in an invalid, FALSE otherwise.
+    * @deprecated ICU 2.8 Use Collator::getSortKey(...) instead
+    */
+    UBool                   isBogus(void) const;
+
+    /**
+    * Returns a pointer to the collation key values. The storage is owned
+    * by the collation key and the pointer will become invalid if the key
+    * is deleted.
+    * @param count the output parameter of number of collation key values,
+    * including any trailing nulls.
+    * @return a pointer to the collation key values.
+    * @deprecated ICU 2.8 Use Collator::getSortKey(...) instead
+    */
+    const    uint8_t*       getByteArray(int32_t& count) const;
+
+#ifdef U_USE_COLLATION_KEY_DEPRECATES
+    /**
+    * Extracts the collation key values into a new array. The caller owns
+    * this storage and should free it.
+    * @param count the output parameter of number of collation key values,
+    * including any trailing nulls.
+    * @obsolete ICU 2.6. Use getByteArray instead since this API will be removed in that release.
+    */
+    uint8_t*                toByteArray(int32_t& count) const;
+#endif
+
+    /**
+    * Convenience method which does a string(bit-wise) comparison of the
+    * two collation keys.
+    * @param target target collation key to be compared with
+    * @return Returns Collator::LESS if sourceKey &lt; targetKey,
+    * Collator::GREATER if sourceKey > targetKey and Collator::EQUAL
+    * otherwise.
+    * @deprecated ICU 2.6 use the overload with error code
+    */
+    Collator::EComparisonResult compareTo(const CollationKey& target) const;
+
+    /**
+    * Convenience method which does a string(bit-wise) comparison of the
+    * two collation keys.
+    * @param target target collation key to be compared with
+    * @param status error code
+    * @return Returns UCOL_LESS if sourceKey &lt; targetKey,
+    * UCOL_GREATER if sourceKey > targetKey and UCOL_EQUAL
+    * otherwise.
+    * @deprecated ICU 2.8 Use Collator::getSortKey(...) instead
+    */
+    UCollationResult compareTo(const CollationKey& target, UErrorCode &status) const;
+
+    /**
+    * Creates an integer that is unique to the collation key.  NOTE: this
+    * is not the same as String.hashCode.
+    * <p>Example of use:
+    * <pre>
+    * .    UErrorCode status = U_ZERO_ERROR;
+    * .    Collator *myCollation = Collator::createInstance(Locale::US, status);
+    * .    if (U_FAILURE(status)) return;
+    * .    CollationKey key1, key2;
+    * .    UErrorCode status1 = U_ZERO_ERROR, status2 = U_ZERO_ERROR;
+    * .    myCollation->getCollationKey("abc", key1, status1);
+    * .    if (U_FAILURE(status1)) { delete myCollation; return; }
+    * .    myCollation->getCollationKey("ABC", key2, status2);
+    * .    if (U_FAILURE(status2)) { delete myCollation; return; }
+    * .    // key1.hashCode() != key2.hashCode()
+    * </pre>
+    * @return the hash value based on the string's collation order.
+    * @see UnicodeString#hashCode
+    * @deprecated ICU 2.8 Use Collator::getSortKey(...) instead
+    */
+    int32_t                 hashCode(void) const;
+
+    /**
+     * ICU "poor man's RTTI", returns a UClassID for the actual class.
+     * @deprecated ICU 2.8 Use Collator::getSortKey(...) instead
+     */
+    virtual UClassID getDynamicClassID() const;
+
+    /**
+     * ICU "poor man's RTTI", returns a UClassID for this class.
+     * @deprecated ICU 2.8 Use Collator::getSortKey(...) instead
+     */
+    static UClassID U_EXPORT2 getStaticClassID();
+
+private:
+    /**
+    * Returns an array of the collation key values as 16-bit integers.
+    * The caller owns the storage and must delete it.
+    * @param values Output param of the collation key values.
+    * @param count output parameter of the number of collation key values
+    * @return a pointer to an array of 16-bit collation key values.
+    */
+    void adopt(uint8_t *values, int32_t count);
+
+    /*
+    * Creates a collation key with a string.
+    */
+
+    /**
+    * If this CollationKey has capacity less than newSize,
+    * its internal capacity will be increased to newSize.
+    * @param newSize minimum size this CollationKey has to have
+    * @return this CollationKey
+    */
+    CollationKey&           ensureCapacity(int32_t newSize);
+    /**
+    * Set the CollationKey to a "bogus" or invalid state
+    * @return this CollationKey
+    */
+    CollationKey&           setToBogus(void);
+    /**
+    * Resets this CollationKey to an empty state
+    * @return this CollationKey
+    */
+    CollationKey&           reset(void);
+    
+    /**
+    * Allow private access to RuleBasedCollator
+    */
+    friend  class           RuleBasedCollator;
+    /**
+    * Bogus status
+    */
+    UBool                   fBogus;
+    /**
+    * Size of fBytes used to store the sortkey. i.e. up till the 
+    * null-termination.
+    */
+    int32_t                 fCount;
+    /**
+    * Full size of the fBytes
+    */
+    int32_t                 fCapacity;
+    /**
+    * Unique hash value of this CollationKey
+    */
+    int32_t                 fHashCode;
+    /**
+    * Array to store the sortkey
+    */
+    uint8_t*                fBytes;
+
+};
+
+inline UBool
+CollationKey::operator!=(const CollationKey& other) const
+{
+    return !(*this == other);
+}
+
+inline UBool
+CollationKey::isBogus() const
+{
+    return fBogus;
+}
+
+inline const uint8_t*
+CollationKey::getByteArray(int32_t &count) const
+{
+    count = fCount;
+    return fBytes;
+}
+
+U_NAMESPACE_END
+
+#endif /* #if !UCONFIG_NO_COLLATION */
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/strenum.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/strenum.h b/src/apps/couch_collate/platform/osx/icu/unicode/strenum.h
new file mode 100644
index 0000000..ce42195
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/strenum.h
@@ -0,0 +1,271 @@
+/*
+*******************************************************************************
+*
+*   Copyright (C) 2002-2007, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+*
+*******************************************************************************
+*/
+
+#ifndef STRENUM_H
+#define STRENUM_H
+
+#include "unicode/uobject.h"
+#include "unicode/unistr.h"
+
+/**
+ * \file 
+ * \brief C++ API: String Enumeration
+ */
+ 
+U_NAMESPACE_BEGIN
+
+/**
+ * Base class for 'pure' C++ implementations of uenum api.  Adds a
+ * method that returns the next UnicodeString since in C++ this can
+ * be a common storage format for strings.
+ *
+ * <p>The model is that the enumeration is over strings maintained by
+ * a 'service.'  At any point, the service might change, invalidating
+ * the enumerator (though this is expected to be rare).  The iterator
+ * returns an error if this has occurred.  Lack of the error is no
+ * guarantee that the service didn't change immediately after the
+ * call, so the returned string still might not be 'valid' on
+ * subsequent use.</p>
+ *
+ * <p>Strings may take the form of const char*, const UChar*, or const
+ * UnicodeString*.  The type you get is determine by the variant of
+ * 'next' that you call.  In general the StringEnumeration is
+ * optimized for one of these types, but all StringEnumerations can
+ * return all types.  Returned strings are each terminated with a NUL.
+ * Depending on the service data, they might also include embedded NUL
+ * characters, so API is provided to optionally return the true
+ * length, counting the embedded NULs but not counting the terminating
+ * NUL.</p>
+ *
+ * <p>The pointers returned by next, unext, and snext become invalid
+ * upon any subsequent call to the enumeration's destructor, next,
+ * unext, snext, or reset.</p>
+ *
+ * ICU 2.8 adds some default implementations and helper functions
+ * for subclasses.
+ *
+ * @stable ICU 2.4 
+ */
+class U_COMMON_API StringEnumeration : public UObject { 
+public:
+    /**
+     * Destructor.
+     * @stable ICU 2.4
+     */
+    virtual ~StringEnumeration();
+
+    /**
+     * Clone this object, an instance of a subclass of StringEnumeration.
+     * Clones can be used concurrently in multiple threads.
+     * If a subclass does not implement clone(), or if an error occurs,
+     * then NULL is returned.
+     * The clone functions in all subclasses return a base class pointer
+     * because some compilers do not support covariant (same-as-this)
+     * return types; cast to the appropriate subclass if necessary.
+     * The caller must delete the clone.
+     *
+     * @return a clone of this object
+     *
+     * @see getDynamicClassID
+     * @stable ICU 2.8
+     */
+    virtual StringEnumeration *clone() const;
+
+    /**
+     * <p>Return the number of elements that the iterator traverses.  If
+     * the iterator is out of sync with its service, status is set to
+     * U_ENUM_OUT_OF_SYNC_ERROR, and the return value is zero.</p>
+     *
+     * <p>The return value will not change except possibly as a result of
+     * a subsequent call to reset, or if the iterator becomes out of sync.</p>
+     *
+     * <p>This is a convenience function. It can end up being very
+     * expensive as all the items might have to be pre-fetched
+     * (depending on the storage format of the data being
+     * traversed).</p>
+     *
+     * @param status the error code.
+     * @return number of elements in the iterator.
+     *
+     * @stable ICU 2.4 */
+    virtual int32_t count(UErrorCode& status) const = 0;
+
+    /**
+     * <p>Returns the next element as a NUL-terminated char*.  If there
+     * are no more elements, returns NULL.  If the resultLength pointer
+     * is not NULL, the length of the string (not counting the
+     * terminating NUL) is returned at that address.  If an error
+     * status is returned, the value at resultLength is undefined.</p>
+     *
+     * <p>The returned pointer is owned by this iterator and must not be
+     * deleted by the caller.  The pointer is valid until the next call
+     * to next, unext, snext, reset, or the enumerator's destructor.</p>
+     *
+     * <p>If the iterator is out of sync with its service, status is set
+     * to U_ENUM_OUT_OF_SYNC_ERROR and NULL is returned.</p>
+     *
+     * <p>If the native service string is a UChar* string, it is
+     * converted to char* with the invariant converter.  If the
+     * conversion fails (because a character cannot be converted) then
+     * status is set to U_INVARIANT_CONVERSION_ERROR and the return
+     * value is undefined (though not NULL).</p>
+     *
+     * Starting with ICU 2.8, the default implementation calls snext()
+     * and handles the conversion.
+     *
+     * @param status the error code.
+     * @param resultLength a pointer to receive the length, can be NULL.
+     * @return a pointer to the string, or NULL.
+     *
+     * @stable ICU 2.4 
+     */
+    virtual const char* next(int32_t *resultLength, UErrorCode& status);
+
+    /**
+     * <p>Returns the next element as a NUL-terminated UChar*.  If there
+     * are no more elements, returns NULL.  If the resultLength pointer
+     * is not NULL, the length of the string (not counting the
+     * terminating NUL) is returned at that address.  If an error
+     * status is returned, the value at resultLength is undefined.</p>
+     *
+     * <p>The returned pointer is owned by this iterator and must not be
+     * deleted by the caller.  The pointer is valid until the next call
+     * to next, unext, snext, reset, or the enumerator's destructor.</p>
+     *
+     * <p>If the iterator is out of sync with its service, status is set
+     * to U_ENUM_OUT_OF_SYNC_ERROR and NULL is returned.</p>
+     *
+     * Starting with ICU 2.8, the default implementation calls snext()
+     * and handles the conversion.
+     *
+     * @param status the error code.
+     * @param resultLength a ponter to receive the length, can be NULL.
+     * @return a pointer to the string, or NULL.
+     *
+     * @stable ICU 2.4 
+     */
+    virtual const UChar* unext(int32_t *resultLength, UErrorCode& status);
+
+    /**
+     * <p>Returns the next element a UnicodeString*.  If there are no
+     * more elements, returns NULL.</p>
+     *
+     * <p>The returned pointer is owned by this iterator and must not be
+     * deleted by the caller.  The pointer is valid until the next call
+     * to next, unext, snext, reset, or the enumerator's destructor.</p>
+     *
+     * <p>If the iterator is out of sync with its service, status is set
+     * to U_ENUM_OUT_OF_SYNC_ERROR and NULL is returned.</p>
+     *
+     * @param status the error code.
+     * @return a pointer to the string, or NULL.
+     *
+     * @stable ICU 2.4 
+     */
+    virtual const UnicodeString* snext(UErrorCode& status) = 0;
+
+    /**
+     * <p>Resets the iterator.  This re-establishes sync with the
+     * service and rewinds the iterator to start at the first
+     * element.</p>
+     *
+     * <p>Previous pointers returned by next, unext, or snext become
+     * invalid, and the value returned by count might change.</p>
+     *
+     * @param status the error code.
+     *
+     * @stable ICU 2.4 
+     */
+    virtual void reset(UErrorCode& status) = 0;
+
+    /**
+     * Compares this enumeration to other to check if both are equal
+     *
+     * @param that The other string enumeration to compare this object to
+     * @return TRUE if the enumerations are equal. FALSE if not.
+     * @stable ICU 3.6 
+     */
+    virtual UBool operator==(const StringEnumeration& that)const;
+    /**
+     * Compares this enumeration to other to check if both are not equal
+     *
+     * @param that The other string enumeration to compare this object to
+     * @return TRUE if the enumerations are equal. FALSE if not.
+     * @stable ICU 3.6 
+     */
+    virtual UBool operator!=(const StringEnumeration& that)const;
+
+protected:
+    /**
+     * UnicodeString field for use with default implementations and subclasses.
+     * @stable ICU 2.8
+     */
+    UnicodeString unistr;
+    /**
+     * char * default buffer for use with default implementations and subclasses.
+     * @stable ICU 2.8
+     */
+    char charsBuffer[32];
+    /**
+     * char * buffer for use with default implementations and subclasses.
+     * Allocated in constructor and in ensureCharsCapacity().
+     * @stable ICU 2.8
+     */
+    char *chars;
+    /**
+     * Capacity of chars, for use with default implementations and subclasses.
+     * @stable ICU 2.8
+     */
+    int32_t charsCapacity;
+
+    /**
+     * Default constructor for use with default implementations and subclasses.
+     * @stable ICU 2.8
+     */
+    StringEnumeration();
+
+    /**
+     * Ensures that chars is at least as large as the requested capacity.
+     * For use with default implementations and subclasses.
+     *
+     * @param capacity Requested capacity.
+     * @param status ICU in/out error code.
+     * @stable ICU 2.8
+     */
+    void ensureCharsCapacity(int32_t capacity, UErrorCode &status);
+
+    /**
+     * Converts s to Unicode and sets unistr to the result.
+     * For use with default implementations and subclasses,
+     * especially for implementations of snext() in terms of next().
+     * This is provided with a helper function instead of a default implementation
+     * of snext() to avoid potential infinite loops between next() and snext().
+     *
+     * For example:
+     * \code
+     * const UnicodeString* snext(UErrorCode& status) {
+     *   int32_t resultLength=0;
+     *   const char *s=next(&resultLength, status);
+     *   return setChars(s, resultLength, status);
+     * }
+     * \endcode
+     *
+     * @param s String to be converted to Unicode.
+     * @param length Length of the string.
+     * @param status ICU in/out error code.
+     * @return A pointer to unistr.
+     * @stable ICU 2.8
+     */
+    UnicodeString *setChars(const char *s, int32_t length, UErrorCode &status);
+};
+
+U_NAMESPACE_END
+
+/* STRENUM_H */
+#endif


[94/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch/patches/js/patch-configure
----------------------------------------------------------------------
diff --git a/src/apps/couch/patches/js/patch-configure b/src/apps/couch/patches/js/patch-configure
new file mode 100644
index 0000000..5c87deb
--- /dev/null
+++ b/src/apps/couch/patches/js/patch-configure
@@ -0,0 +1,3508 @@
+--- configure.orig	2012-06-13 21:31:31.000000000 +0200
++++ configure	2012-06-13 21:39:23.000000000 +0200
+@@ -4312,21 +4312,10 @@
+   fi
+ 
+ 
+-    case "$PBBUILD" in
+-      *xcodebuild*)
+-        
+-        XCODEBUILD_VERSION=`$PBBUILD -version 2>/dev/null | xargs | sed -e 's/.*DevToolsCore-\([0-9]*\).*/\1/'`
+-        
+-        if test -n "$XCODEBUILD_VERSION" && test "$XCODEBUILD_VERSION" -ge 620 ; then
+-          HAS_XCODE_2_1=1;
+-        fi
+-      ;;
+-    esac
+-
+              # Extract the first word of "sdp", so it can be a program name with args.
+ set dummy sdp; ac_word=$2
+ echo $ac_n "checking for $ac_word""... $ac_c" 1>&6
+-echo "configure:4330: checking for $ac_word" >&5
++echo "configure:4319: checking for $ac_word" >&5
+ if eval "test \"`echo '$''{'ac_cv_path_SDP'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+@@ -4380,8 +4369,6 @@
+ 
+ 
+ 
+-
+-
+ # Check whether --enable-macos-target or --disable-macos-target was given.
+ if test "${enable_macos_target+set}" = set; then
+   enableval="$enable_macos_target"
+@@ -4452,7 +4439,7 @@
+ 
+   
+   echo $ac_n "checking for valid compiler/Mac OS X SDK combination""... $ac_c" 1>&6
+-echo "configure:4456: checking for valid compiler/Mac OS X SDK combination" >&5
++echo "configure:4443: checking for valid compiler/Mac OS X SDK combination" >&5
+   ac_ext=C
+ # CXXFLAGS is not in ac_cpp because -g, -O, etc. are not valid cpp options.
+ ac_cpp='$CXXCPP $CPPFLAGS'
+@@ -4461,7 +4448,7 @@
+ cross_compiling=$ac_cv_prog_cxx_cross
+ 
+   cat > conftest.$ac_ext <<EOF
+-#line 4465 "configure"
++#line 4452 "configure"
+ #include "confdefs.h"
+ #include <new>
+                  int main() { return 0; }
+@@ -4469,7 +4456,7 @@
+ result=yes
+ ; return 0; }
+ EOF
+-if { (eval echo configure:4473: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
++if { (eval echo configure:4460: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+   rm -rf conftest*
+   result=no
+ else
+@@ -4506,7 +4493,7 @@
+ # Extract the first word of "$ac_prog", so it can be a program name with args.
+ set dummy $ac_prog; ac_word=$2
+ echo $ac_n "checking for $ac_word""... $ac_c" 1>&6
+-echo "configure:4510: checking for $ac_word" >&5
++echo "configure:4497: checking for $ac_word" >&5
+ if eval "test \"`echo '$''{'ac_cv_path_GMAKE'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+@@ -4562,7 +4549,7 @@
+ # Extract the first word of "$ac_prog", so it can be a program name with args.
+ set dummy $ac_prog; ac_word=$2
+ echo $ac_n "checking for $ac_word""... $ac_c" 1>&6
+-echo "configure:4566: checking for $ac_word" >&5
++echo "configure:4553: checking for $ac_word" >&5
+ if eval "test \"`echo '$''{'ac_cv_path_GMAKE'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+@@ -4625,7 +4612,7 @@
+ # Uses ac_ vars as temps to allow command line to override cache and checks.
+ # --without-x overrides everything else, but does not touch the cache.
+ echo $ac_n "checking for X""... $ac_c" 1>&6
+-echo "configure:4629: checking for X" >&5
++echo "configure:4616: checking for X" >&5
+ 
+ # Check whether --with-x or --without-x was given.
+ if test "${with_x+set}" = set; then
+@@ -4687,12 +4674,12 @@
+ 
+   # First, try using that file with no special directory specified.
+ cat > conftest.$ac_ext <<EOF
+-#line 4691 "configure"
++#line 4678 "configure"
+ #include "confdefs.h"
+ #include <$x_direct_test_include>
+ EOF
+ ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
+-{ (eval echo configure:4696: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
++{ (eval echo configure:4683: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
+ ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
+ if test -z "$ac_err"; then
+   rm -rf conftest*
+@@ -4761,14 +4748,14 @@
+   ac_save_LIBS="$LIBS"
+   LIBS="-l$x_direct_test_library $LIBS"
+ cat > conftest.$ac_ext <<EOF
+-#line 4765 "configure"
++#line 4752 "configure"
+ #include "confdefs.h"
+ 
+ int main() {
+ ${x_direct_test_function}()
+ ; return 0; }
+ EOF
+-if { (eval echo configure:4772: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
++if { (eval echo configure:4759: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
+   rm -rf conftest*
+   LIBS="$ac_save_LIBS"
+ # We can link X programs with no special library path.
+@@ -4874,17 +4861,17 @@
+     case "`(uname -sr) 2>/dev/null`" in
+     "SunOS 5"*)
+       echo $ac_n "checking whether -R must be followed by a space""... $ac_c" 1>&6
+-echo "configure:4878: checking whether -R must be followed by a space" >&5
++echo "configure:4865: checking whether -R must be followed by a space" >&5
+       ac_xsave_LIBS="$LIBS"; LIBS="$LIBS -R$x_libraries"
+       cat > conftest.$ac_ext <<EOF
+-#line 4881 "configure"
++#line 4868 "configure"
+ #include "confdefs.h"
+ 
+ int main() {
+ 
+ ; return 0; }
+ EOF
+-if { (eval echo configure:4888: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
++if { (eval echo configure:4875: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
+   rm -rf conftest*
+   ac_R_nospace=yes
+ else
+@@ -4900,14 +4887,14 @@
+       else
+ 	LIBS="$ac_xsave_LIBS -R $x_libraries"
+ 	cat > conftest.$ac_ext <<EOF
+-#line 4904 "configure"
++#line 4891 "configure"
+ #include "confdefs.h"
+ 
+ int main() {
+ 
+ ; return 0; }
+ EOF
+-if { (eval echo configure:4911: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
++if { (eval echo configure:4898: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
+   rm -rf conftest*
+   ac_R_space=yes
+ else
+@@ -4939,7 +4926,7 @@
+     # libraries were built with DECnet support.  And karl@cs.umb.edu says
+     # the Alpha needs dnet_stub (dnet does not exist).
+     echo $ac_n "checking for dnet_ntoa in -ldnet""... $ac_c" 1>&6
+-echo "configure:4943: checking for dnet_ntoa in -ldnet" >&5
++echo "configure:4930: checking for dnet_ntoa in -ldnet" >&5
+ ac_lib_var=`echo dnet'_'dnet_ntoa | sed 'y%./+-%__p_%'`
+ if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+@@ -4947,7 +4934,7 @@
+   ac_save_LIBS="$LIBS"
+ LIBS="-ldnet  $LIBS"
+ cat > conftest.$ac_ext <<EOF
+-#line 4951 "configure"
++#line 4938 "configure"
+ #include "confdefs.h"
+ /* Override any gcc2 internal prototype to avoid an error.  */
+ /* We use char because int might match the return type of a gcc2
+@@ -4958,7 +4945,7 @@
+ dnet_ntoa()
+ ; return 0; }
+ EOF
+-if { (eval echo configure:4962: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
++if { (eval echo configure:4949: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
+   rm -rf conftest*
+   eval "ac_cv_lib_$ac_lib_var=yes"
+ else
+@@ -4980,7 +4967,7 @@
+ 
+     if test $ac_cv_lib_dnet_dnet_ntoa = no; then
+       echo $ac_n "checking for dnet_ntoa in -ldnet_stub""... $ac_c" 1>&6
+-echo "configure:4984: checking for dnet_ntoa in -ldnet_stub" >&5
++echo "configure:4971: checking for dnet_ntoa in -ldnet_stub" >&5
+ ac_lib_var=`echo dnet_stub'_'dnet_ntoa | sed 'y%./+-%__p_%'`
+ if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+@@ -4988,7 +4975,7 @@
+   ac_save_LIBS="$LIBS"
+ LIBS="-ldnet_stub  $LIBS"
+ cat > conftest.$ac_ext <<EOF
+-#line 4992 "configure"
++#line 4979 "configure"
+ #include "confdefs.h"
+ /* Override any gcc2 internal prototype to avoid an error.  */
+ /* We use char because int might match the return type of a gcc2
+@@ -4999,7 +4986,7 @@
+ dnet_ntoa()
+ ; return 0; }
+ EOF
+-if { (eval echo configure:5003: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
++if { (eval echo configure:4990: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
+   rm -rf conftest*
+   eval "ac_cv_lib_$ac_lib_var=yes"
+ else
+@@ -5028,12 +5015,12 @@
+     # The nsl library prevents programs from opening the X display
+     # on Irix 5.2, according to dickey@clark.net.
+     echo $ac_n "checking for gethostbyname""... $ac_c" 1>&6
+-echo "configure:5032: checking for gethostbyname" >&5
++echo "configure:5019: checking for gethostbyname" >&5
+ if eval "test \"`echo '$''{'ac_cv_func_gethostbyname'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 5037 "configure"
++#line 5024 "configure"
+ #include "confdefs.h"
+ /* System header to define __stub macros and hopefully few prototypes,
+     which can conflict with char gethostbyname(); below.  */
+@@ -5056,7 +5043,7 @@
+ 
+ ; return 0; }
+ EOF
+-if { (eval echo configure:5060: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
++if { (eval echo configure:5047: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
+   rm -rf conftest*
+   eval "ac_cv_func_gethostbyname=yes"
+ else
+@@ -5077,7 +5064,7 @@
+ 
+     if test $ac_cv_func_gethostbyname = no; then
+       echo $ac_n "checking for gethostbyname in -lnsl""... $ac_c" 1>&6
+-echo "configure:5081: checking for gethostbyname in -lnsl" >&5
++echo "configure:5068: checking for gethostbyname in -lnsl" >&5
+ ac_lib_var=`echo nsl'_'gethostbyname | sed 'y%./+-%__p_%'`
+ if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+@@ -5085,7 +5072,7 @@
+   ac_save_LIBS="$LIBS"
+ LIBS="-lnsl  $LIBS"
+ cat > conftest.$ac_ext <<EOF
+-#line 5089 "configure"
++#line 5076 "configure"
+ #include "confdefs.h"
+ /* Override any gcc2 internal prototype to avoid an error.  */
+ /* We use char because int might match the return type of a gcc2
+@@ -5096,7 +5083,7 @@
+ gethostbyname()
+ ; return 0; }
+ EOF
+-if { (eval echo configure:5100: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
++if { (eval echo configure:5087: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
+   rm -rf conftest*
+   eval "ac_cv_lib_$ac_lib_var=yes"
+ else
+@@ -5126,12 +5113,12 @@
+     # -lsocket must be given before -lnsl if both are needed.
+     # We assume that if connect needs -lnsl, so does gethostbyname.
+     echo $ac_n "checking for connect""... $ac_c" 1>&6
+-echo "configure:5130: checking for connect" >&5
++echo "configure:5117: checking for connect" >&5
+ if eval "test \"`echo '$''{'ac_cv_func_connect'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 5135 "configure"
++#line 5122 "configure"
+ #include "confdefs.h"
+ /* System header to define __stub macros and hopefully few prototypes,
+     which can conflict with char connect(); below.  */
+@@ -5154,7 +5141,7 @@
+ 
+ ; return 0; }
+ EOF
+-if { (eval echo configure:5158: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
++if { (eval echo configure:5145: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
+   rm -rf conftest*
+   eval "ac_cv_func_connect=yes"
+ else
+@@ -5175,7 +5162,7 @@
+ 
+     if test $ac_cv_func_connect = no; then
+       echo $ac_n "checking for connect in -lsocket""... $ac_c" 1>&6
+-echo "configure:5179: checking for connect in -lsocket" >&5
++echo "configure:5166: checking for connect in -lsocket" >&5
+ ac_lib_var=`echo socket'_'connect | sed 'y%./+-%__p_%'`
+ if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+@@ -5183,7 +5170,7 @@
+   ac_save_LIBS="$LIBS"
+ LIBS="-lsocket $X_EXTRA_LIBS $LIBS"
+ cat > conftest.$ac_ext <<EOF
+-#line 5187 "configure"
++#line 5174 "configure"
+ #include "confdefs.h"
+ /* Override any gcc2 internal prototype to avoid an error.  */
+ /* We use char because int might match the return type of a gcc2
+@@ -5194,7 +5181,7 @@
+ connect()
+ ; return 0; }
+ EOF
+-if { (eval echo configure:5198: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
++if { (eval echo configure:5185: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
+   rm -rf conftest*
+   eval "ac_cv_lib_$ac_lib_var=yes"
+ else
+@@ -5218,12 +5205,12 @@
+ 
+     # gomez@mi.uni-erlangen.de says -lposix is necessary on A/UX.
+     echo $ac_n "checking for remove""... $ac_c" 1>&6
+-echo "configure:5222: checking for remove" >&5
++echo "configure:5209: checking for remove" >&5
+ if eval "test \"`echo '$''{'ac_cv_func_remove'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 5227 "configure"
++#line 5214 "configure"
+ #include "confdefs.h"
+ /* System header to define __stub macros and hopefully few prototypes,
+     which can conflict with char remove(); below.  */
+@@ -5246,7 +5233,7 @@
+ 
+ ; return 0; }
+ EOF
+-if { (eval echo configure:5250: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
++if { (eval echo configure:5237: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
+   rm -rf conftest*
+   eval "ac_cv_func_remove=yes"
+ else
+@@ -5267,7 +5254,7 @@
+ 
+     if test $ac_cv_func_remove = no; then
+       echo $ac_n "checking for remove in -lposix""... $ac_c" 1>&6
+-echo "configure:5271: checking for remove in -lposix" >&5
++echo "configure:5258: checking for remove in -lposix" >&5
+ ac_lib_var=`echo posix'_'remove | sed 'y%./+-%__p_%'`
+ if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+@@ -5275,7 +5262,7 @@
+   ac_save_LIBS="$LIBS"
+ LIBS="-lposix  $LIBS"
+ cat > conftest.$ac_ext <<EOF
+-#line 5279 "configure"
++#line 5266 "configure"
+ #include "confdefs.h"
+ /* Override any gcc2 internal prototype to avoid an error.  */
+ /* We use char because int might match the return type of a gcc2
+@@ -5286,7 +5273,7 @@
+ remove()
+ ; return 0; }
+ EOF
+-if { (eval echo configure:5290: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
++if { (eval echo configure:5277: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
+   rm -rf conftest*
+   eval "ac_cv_lib_$ac_lib_var=yes"
+ else
+@@ -5310,12 +5297,12 @@
+ 
+     # BSDI BSD/OS 2.1 needs -lipc for XOpenDisplay.
+     echo $ac_n "checking for shmat""... $ac_c" 1>&6
+-echo "configure:5314: checking for shmat" >&5
++echo "configure:5301: checking for shmat" >&5
+ if eval "test \"`echo '$''{'ac_cv_func_shmat'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 5319 "configure"
++#line 5306 "configure"
+ #include "confdefs.h"
+ /* System header to define __stub macros and hopefully few prototypes,
+     which can conflict with char shmat(); below.  */
+@@ -5338,7 +5325,7 @@
+ 
+ ; return 0; }
+ EOF
+-if { (eval echo configure:5342: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
++if { (eval echo configure:5329: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
+   rm -rf conftest*
+   eval "ac_cv_func_shmat=yes"
+ else
+@@ -5359,7 +5346,7 @@
+ 
+     if test $ac_cv_func_shmat = no; then
+       echo $ac_n "checking for shmat in -lipc""... $ac_c" 1>&6
+-echo "configure:5363: checking for shmat in -lipc" >&5
++echo "configure:5350: checking for shmat in -lipc" >&5
+ ac_lib_var=`echo ipc'_'shmat | sed 'y%./+-%__p_%'`
+ if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+@@ -5367,7 +5354,7 @@
+   ac_save_LIBS="$LIBS"
+ LIBS="-lipc  $LIBS"
+ cat > conftest.$ac_ext <<EOF
+-#line 5371 "configure"
++#line 5358 "configure"
+ #include "confdefs.h"
+ /* Override any gcc2 internal prototype to avoid an error.  */
+ /* We use char because int might match the return type of a gcc2
+@@ -5378,7 +5365,7 @@
+ shmat()
+ ; return 0; }
+ EOF
+-if { (eval echo configure:5382: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
++if { (eval echo configure:5369: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
+   rm -rf conftest*
+   eval "ac_cv_lib_$ac_lib_var=yes"
+ else
+@@ -5411,7 +5398,7 @@
+   # libraries we check for below, so use a different variable.
+   #  --interran@uluru.Stanford.EDU, kb@cs.umb.edu.
+   echo $ac_n "checking for IceConnectionNumber in -lICE""... $ac_c" 1>&6
+-echo "configure:5415: checking for IceConnectionNumber in -lICE" >&5
++echo "configure:5402: checking for IceConnectionNumber in -lICE" >&5
+ ac_lib_var=`echo ICE'_'IceConnectionNumber | sed 'y%./+-%__p_%'`
+ if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+@@ -5419,7 +5406,7 @@
+   ac_save_LIBS="$LIBS"
+ LIBS="-lICE $X_EXTRA_LIBS $LIBS"
+ cat > conftest.$ac_ext <<EOF
+-#line 5423 "configure"
++#line 5410 "configure"
+ #include "confdefs.h"
+ /* Override any gcc2 internal prototype to avoid an error.  */
+ /* We use char because int might match the return type of a gcc2
+@@ -5430,7 +5417,7 @@
+ IceConnectionNumber()
+ ; return 0; }
+ EOF
+-if { (eval echo configure:5434: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
++if { (eval echo configure:5421: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
+   rm -rf conftest*
+   eval "ac_cv_lib_$ac_lib_var=yes"
+ else
+@@ -5913,7 +5900,7 @@
+     _USE_CPP_INCLUDE_FLAG=1
+ 
+     echo $ac_n "checking whether the compiler supports -Wno-invalid-offsetof""... $ac_c" 1>&6
+-echo "configure:5917: checking whether the compiler supports -Wno-invalid-offsetof" >&5
++echo "configure:5904: checking whether the compiler supports -Wno-invalid-offsetof" >&5
+ if eval "test \"`echo '$''{'ac_has_wno_invalid_offsetof'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+@@ -5929,14 +5916,14 @@
+             _SAVE_CXXFLAGS="$CXXFLAGS"
+             CXXFLAGS="$CXXFLAGS ${_COMPILER_PREFIX}-Wno-invalid-offsetof"
+             cat > conftest.$ac_ext <<EOF
+-#line 5933 "configure"
++#line 5920 "configure"
+ #include "confdefs.h"
+ 
+ int main() {
+ return(0);
+ ; return 0; }
+ EOF
+-if { (eval echo configure:5940: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
++if { (eval echo configure:5927: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+   rm -rf conftest*
+   ac_has_wno_invalid_offsetof="yes"
+ else
+@@ -5963,7 +5950,7 @@
+     fi
+ 
+     echo $ac_n "checking whether the compiler supports -Wno-variadic-macros""... $ac_c" 1>&6
+-echo "configure:5967: checking whether the compiler supports -Wno-variadic-macros" >&5
++echo "configure:5954: checking whether the compiler supports -Wno-variadic-macros" >&5
+ if eval "test \"`echo '$''{'ac_has_wno_variadic_macros'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+@@ -5979,14 +5966,14 @@
+             _SAVE_CXXFLAGS="$CXXFLAGS"
+             CXXFLAGS="$CXXFLAGS ${_COMPILER_PREFIX}-Wno-variadic-macros"
+             cat > conftest.$ac_ext <<EOF
+-#line 5983 "configure"
++#line 5970 "configure"
+ #include "confdefs.h"
+ 
+ int main() {
+ return(0);
+ ; return 0; }
+ EOF
+-if { (eval echo configure:5990: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
++if { (eval echo configure:5977: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+   rm -rf conftest*
+   ac_has_wno_variadic_macros="yes"
+ else
+@@ -6013,7 +6000,7 @@
+     fi
+ 
+     echo $ac_n "checking whether the compiler supports -Werror=return-type""... $ac_c" 1>&6
+-echo "configure:6017: checking whether the compiler supports -Werror=return-type" >&5
++echo "configure:6004: checking whether the compiler supports -Werror=return-type" >&5
+ if eval "test \"`echo '$''{'ac_has_werror_return_type'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+@@ -6029,14 +6016,14 @@
+             _SAVE_CXXFLAGS="$CXXFLAGS"
+             CXXFLAGS="$CXXFLAGS -Werror=return-type"
+             cat > conftest.$ac_ext <<EOF
+-#line 6033 "configure"
++#line 6020 "configure"
+ #include "confdefs.h"
+ 
+ int main() {
+ return(0);
+ ; return 0; }
+ EOF
+-if { (eval echo configure:6040: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
++if { (eval echo configure:6027: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+   rm -rf conftest*
+   ac_has_werror_return_type="yes"
+ else
+@@ -6072,7 +6059,7 @@
+ if test "$COMPILE_ENVIRONMENT"; then
+ if test "$GNU_CC"; then
+   echo $ac_n "checking whether ld has archive extraction flags""... $ac_c" 1>&6
+-echo "configure:6076: checking whether ld has archive extraction flags" >&5
++echo "configure:6063: checking whether ld has archive extraction flags" >&5
+   if eval "test \"`echo '$''{'ac_cv_mkshlib_force_and_unforce'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+@@ -6089,14 +6076,14 @@
+       LDFLAGS=$force
+       LIBS=$unforce
+       cat > conftest.$ac_ext <<EOF
+-#line 6093 "configure"
++#line 6080 "configure"
+ #include "confdefs.h"
+ 
+ int main() {
+ 
+ ; return 0; }
+ EOF
+-if { (eval echo configure:6100: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
++if { (eval echo configure:6087: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
+   rm -rf conftest*
+   ac_cv_mkshlib_force_and_unforce=$line; break
+ else
+@@ -6129,7 +6116,7 @@
+ '
+ 
+ echo $ac_n "checking that static assertion macros used in autoconf tests work""... $ac_c" 1>&6
+-echo "configure:6133: checking that static assertion macros used in autoconf tests work" >&5
++echo "configure:6120: checking that static assertion macros used in autoconf tests work" >&5
+ if eval "test \"`echo '$''{'ac_cv_static_assertion_macros_work'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+@@ -6143,14 +6130,14 @@
+ 
+   ac_cv_static_assertion_macros_work="yes"
+   cat > conftest.$ac_ext <<EOF
+-#line 6147 "configure"
++#line 6134 "configure"
+ #include "confdefs.h"
+ $configure_static_assert_macros
+ int main() {
+ CONFIGURE_STATIC_ASSERT(1)
+ ; return 0; }
+ EOF
+-if { (eval echo configure:6154: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
++if { (eval echo configure:6141: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+   :
+ else
+   echo "configure: failed program was:" >&5
+@@ -6160,14 +6147,14 @@
+ fi
+ rm -f conftest*
+   cat > conftest.$ac_ext <<EOF
+-#line 6164 "configure"
++#line 6151 "configure"
+ #include "confdefs.h"
+ $configure_static_assert_macros
+ int main() {
+ CONFIGURE_STATIC_ASSERT(0)
+ ; return 0; }
+ EOF
+-if { (eval echo configure:6171: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
++if { (eval echo configure:6158: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+   rm -rf conftest*
+   ac_cv_static_assertion_macros_work="no"
+ else
+@@ -6183,14 +6170,14 @@
+ cross_compiling=$ac_cv_prog_cxx_cross
+ 
+   cat > conftest.$ac_ext <<EOF
+-#line 6187 "configure"
++#line 6174 "configure"
+ #include "confdefs.h"
+ $configure_static_assert_macros
+ int main() {
+ CONFIGURE_STATIC_ASSERT(1)
+ ; return 0; }
+ EOF
+-if { (eval echo configure:6194: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
++if { (eval echo configure:6181: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+   :
+ else
+   echo "configure: failed program was:" >&5
+@@ -6200,14 +6187,14 @@
+ fi
+ rm -f conftest*
+   cat > conftest.$ac_ext <<EOF
+-#line 6204 "configure"
++#line 6191 "configure"
+ #include "confdefs.h"
+ $configure_static_assert_macros
+ int main() {
+ CONFIGURE_STATIC_ASSERT(0)
+ ; return 0; }
+ EOF
+-if { (eval echo configure:6211: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
++if { (eval echo configure:6198: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+   rm -rf conftest*
+   ac_cv_static_assertion_macros_work="no"
+ else
+@@ -6241,16 +6228,16 @@
+ cross_compiling=$ac_cv_prog_cc_cross
+ 
+ echo $ac_n "checking for 64-bit OS""... $ac_c" 1>&6
+-echo "configure:6245: checking for 64-bit OS" >&5
++echo "configure:6232: checking for 64-bit OS" >&5
+ cat > conftest.$ac_ext <<EOF
+-#line 6247 "configure"
++#line 6234 "configure"
+ #include "confdefs.h"
+ $configure_static_assert_macros
+ int main() {
+ CONFIGURE_STATIC_ASSERT(sizeof(void*) == 8)
+ ; return 0; }
+ EOF
+-if { (eval echo configure:6254: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
++if { (eval echo configure:6241: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+   rm -rf conftest*
+   result="yes"
+ else
+@@ -6389,7 +6376,7 @@
+ esac
+ 
+ echo $ac_n "checking for Python version >= $PYTHON_VERSION but not 3.x""... $ac_c" 1>&6
+-echo "configure:6393: checking for Python version >= $PYTHON_VERSION but not 3.x" >&5
++echo "configure:6380: checking for Python version >= $PYTHON_VERSION but not 3.x" >&5
+ 
+ $PYTHON -c "import sys; sys.exit(sys.version[:3] < sys.argv[1] or sys.version[:2] != '2.')" $PYTHON_VERSION
+ _python_res=$?
+@@ -6437,9 +6424,9 @@
+ cross_compiling=$ac_cv_prog_cxx_cross
+ 
+             echo $ac_n "checking for IBM XLC/C++ compiler version >= 9.0.0.7""... $ac_c" 1>&6
+-echo "configure:6441: checking for IBM XLC/C++ compiler version >= 9.0.0.7" >&5
++echo "configure:6428: checking for IBM XLC/C++ compiler version >= 9.0.0.7" >&5
+             cat > conftest.$ac_ext <<EOF
+-#line 6443 "configure"
++#line 6430 "configure"
+ #include "confdefs.h"
+ 
+ int main() {
+@@ -6448,7 +6435,7 @@
+                  #endif
+ ; return 0; }
+ EOF
+-if { (eval echo configure:6452: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
++if { (eval echo configure:6439: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+   rm -rf conftest*
+   _BAD_COMPILER=
+ else
+@@ -6486,17 +6473,17 @@
+ do
+ ac_safe=`echo "$ac_hdr" | sed 'y%./+-%__p_%'`
+ echo $ac_n "checking for $ac_hdr""... $ac_c" 1>&6
+-echo "configure:6490: checking for $ac_hdr" >&5
++echo "configure:6477: checking for $ac_hdr" >&5
+ if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 6495 "configure"
++#line 6482 "configure"
+ #include "confdefs.h"
+ #include <$ac_hdr>
+ EOF
+ ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
+-{ (eval echo configure:6500: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
++{ (eval echo configure:6487: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
+ ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
+ if test -z "$ac_err"; then
+   rm -rf conftest*
+@@ -6542,7 +6529,7 @@
+     LIBS="$LIBS -lbe"
+     if test "$COMPILE_ENVIRONMENT"; then
+         echo $ac_n "checking for main in -lbind""... $ac_c" 1>&6
+-echo "configure:6546: checking for main in -lbind" >&5
++echo "configure:6533: checking for main in -lbind" >&5
+ ac_lib_var=`echo bind'_'main | sed 'y%./+-%__p_%'`
+ if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+@@ -6550,14 +6537,14 @@
+   ac_save_LIBS="$LIBS"
+ LIBS="-lbind  $LIBS"
+ cat > conftest.$ac_ext <<EOF
+-#line 6554 "configure"
++#line 6541 "configure"
+ #include "confdefs.h"
+ 
+ int main() {
+ main()
+ ; return 0; }
+ EOF
+-if { (eval echo configure:6561: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
++if { (eval echo configure:6548: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
+   rm -rf conftest*
+   eval "ac_cv_lib_$ac_lib_var=yes"
+ else
+@@ -6578,7 +6565,7 @@
+ fi
+ 
+         echo $ac_n "checking for main in -lzeta""... $ac_c" 1>&6
+-echo "configure:6582: checking for main in -lzeta" >&5
++echo "configure:6569: checking for main in -lzeta" >&5
+ ac_lib_var=`echo zeta'_'main | sed 'y%./+-%__p_%'`
+ if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+@@ -6586,14 +6573,14 @@
+   ac_save_LIBS="$LIBS"
+ LIBS="-lzeta  $LIBS"
+ cat > conftest.$ac_ext <<EOF
+-#line 6590 "configure"
++#line 6577 "configure"
+ #include "confdefs.h"
+ 
+ int main() {
+ main()
+ ; return 0; }
+ EOF
+-if { (eval echo configure:6597: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
++if { (eval echo configure:6584: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
+   rm -rf conftest*
+   eval "ac_cv_lib_$ac_lib_var=yes"
+ else
+@@ -6667,18 +6654,18 @@
+         echo "Skipping -dead_strip because DTrace is enabled. See bug 403132."
+     else
+                 echo $ac_n "checking for -dead_strip option to ld""... $ac_c" 1>&6
+-echo "configure:6671: checking for -dead_strip option to ld" >&5
++echo "configure:6658: checking for -dead_strip option to ld" >&5
+         _SAVE_LDFLAGS=$LDFLAGS
+         LDFLAGS="$LDFLAGS -Wl,-dead_strip"
+         cat > conftest.$ac_ext <<EOF
+-#line 6675 "configure"
++#line 6662 "configure"
+ #include "confdefs.h"
+ 
+ int main() {
+ return 0;
+ ; return 0; }
+ EOF
+-if { (eval echo configure:6682: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
++if { (eval echo configure:6669: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
+   rm -rf conftest*
+   _HAVE_DEAD_STRIP=1
+ else
+@@ -7250,17 +7237,17 @@
+ do
+ ac_safe=`echo "$ac_hdr" | sed 'y%./+-%__p_%'`
+ echo $ac_n "checking for $ac_hdr""... $ac_c" 1>&6
+-echo "configure:7254: checking for $ac_hdr" >&5
++echo "configure:7241: checking for $ac_hdr" >&5
+ if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 7259 "configure"
++#line 7246 "configure"
+ #include "confdefs.h"
+ #include <$ac_hdr>
+ EOF
+ ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
+-{ (eval echo configure:7264: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
++{ (eval echo configure:7251: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
+ ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
+ if test -z "$ac_err"; then
+   rm -rf conftest*
+@@ -7492,19 +7479,19 @@
+     _DEFINES_CXXFLAGS="$_DEFINES_CXXFLAGS -Uunix -U__unix -U__unix__"
+ 
+     echo $ac_n "checking for __declspec(dllexport)""... $ac_c" 1>&6
+-echo "configure:7496: checking for __declspec(dllexport)" >&5
++echo "configure:7483: checking for __declspec(dllexport)" >&5
+ if eval "test \"`echo '$''{'ac_os2_declspec'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 7501 "configure"
++#line 7488 "configure"
+ #include "confdefs.h"
+ __declspec(dllexport) void ac_os2_declspec(void) {}
+ int main() {
+ return 0;
+ ; return 0; }
+ EOF
+-if { (eval echo configure:7508: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
++if { (eval echo configure:7495: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+   rm -rf conftest*
+   ac_os2_declspec="yes"
+ else
+@@ -7625,14 +7612,14 @@
+            _SAVE_LDFLAGS=$LDFLAGS
+            LDFLAGS="-M /usr/lib/ld/map.noexstk $LDFLAGS" 
+            cat > conftest.$ac_ext <<EOF
+-#line 7629 "configure"
++#line 7616 "configure"
+ #include "confdefs.h"
+ #include <stdio.h>
+ int main() {
+ printf("Hello World\n");
+ ; return 0; }
+ EOF
+-if { (eval echo configure:7636: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
++if { (eval echo configure:7623: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
+   :
+ else
+   echo "configure: failed program was:" >&5
+@@ -7661,7 +7648,7 @@
+        CC_VERSION=`$CC -V 2>&1 | grep '^cc:' 2>/dev/null | $AWK -F\: '{ print $2 }'`
+        CXX_VERSION=`$CXX -V 2>&1 | grep '^CC:' 2>/dev/null | $AWK -F\: '{ print $2 }'`
+        echo $ac_n "checking for Sun C++ compiler version >= 5.9""... $ac_c" 1>&6
+-echo "configure:7665: checking for Sun C++ compiler version >= 5.9" >&5
++echo "configure:7652: checking for Sun C++ compiler version >= 5.9" >&5
+        
+        ac_ext=C
+ # CXXFLAGS is not in ac_cpp because -g, -O, etc. are not valid cpp options.
+@@ -7671,7 +7658,7 @@
+ cross_compiling=$ac_cv_prog_cxx_cross
+ 
+        cat > conftest.$ac_ext <<EOF
+-#line 7675 "configure"
++#line 7662 "configure"
+ #include "confdefs.h"
+ 
+ int main() {
+@@ -7680,7 +7667,7 @@
+            #endif
+ ; return 0; }
+ EOF
+-if { (eval echo configure:7684: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
++if { (eval echo configure:7671: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+   rm -rf conftest*
+   _BAD_COMPILER=
+ else
+@@ -7697,7 +7684,7 @@
+            _res="yes"
+        fi
+        cat > conftest.$ac_ext <<EOF
+-#line 7701 "configure"
++#line 7688 "configure"
+ #include "confdefs.h"
+ 
+ int main() {
+@@ -7706,7 +7693,7 @@
+            #endif
+ ; return 0; }
+ EOF
+-if { (eval echo configure:7710: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
++if { (eval echo configure:7697: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+   rm -rf conftest*
+   _ABOVE_SS12U1=
+ else
+@@ -8122,12 +8109,12 @@
+ 
+ if test -z "$SKIP_COMPILER_CHECKS"; then
+ echo $ac_n "checking for ANSI C header files""... $ac_c" 1>&6
+-echo "configure:8126: checking for ANSI C header files" >&5
++echo "configure:8113: checking for ANSI C header files" >&5
+ if eval "test \"`echo '$''{'ac_cv_header_stdc'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 8131 "configure"
++#line 8118 "configure"
+ #include "confdefs.h"
+ #include <stdlib.h>
+ #include <stdarg.h>
+@@ -8135,7 +8122,7 @@
+ #include <float.h>
+ EOF
+ ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
+-{ (eval echo configure:8139: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
++{ (eval echo configure:8126: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
+ ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
+ if test -z "$ac_err"; then
+   rm -rf conftest*
+@@ -8152,7 +8139,7 @@
+ if test $ac_cv_header_stdc = yes; then
+   # SunOS 4.x string.h does not declare mem*, contrary to ANSI.
+ cat > conftest.$ac_ext <<EOF
+-#line 8156 "configure"
++#line 8143 "configure"
+ #include "confdefs.h"
+ #include <string.h>
+ EOF
+@@ -8170,7 +8157,7 @@
+ if test $ac_cv_header_stdc = yes; then
+   # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI.
+ cat > conftest.$ac_ext <<EOF
+-#line 8174 "configure"
++#line 8161 "configure"
+ #include "confdefs.h"
+ #include <stdlib.h>
+ EOF
+@@ -8191,7 +8178,7 @@
+   :
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 8195 "configure"
++#line 8182 "configure"
+ #include "confdefs.h"
+ #include <ctype.h>
+ #define ISLOWER(c) ('a' <= (c) && (c) <= 'z')
+@@ -8202,7 +8189,7 @@
+ exit (0); }
+ 
+ EOF
+-if { (eval echo configure:8206: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext} && (./conftest; exit) 2>/dev/null
++if { (eval echo configure:8193: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext} && (./conftest; exit) 2>/dev/null
+ then
+   :
+ else
+@@ -8226,12 +8213,12 @@
+ fi
+ 
+ echo $ac_n "checking for working const""... $ac_c" 1>&6
+-echo "configure:8230: checking for working const" >&5
++echo "configure:8217: checking for working const" >&5
+ if eval "test \"`echo '$''{'ac_cv_c_const'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 8235 "configure"
++#line 8222 "configure"
+ #include "confdefs.h"
+ 
+ int main() {
+@@ -8280,7 +8267,7 @@
+ 
+ ; return 0; }
+ EOF
+-if { (eval echo configure:8284: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
++if { (eval echo configure:8271: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+   rm -rf conftest*
+   ac_cv_c_const=yes
+ else
+@@ -8301,12 +8288,12 @@
+ fi
+ 
+ echo $ac_n "checking for mode_t""... $ac_c" 1>&6
+-echo "configure:8305: checking for mode_t" >&5
++echo "configure:8292: checking for mode_t" >&5
+ if eval "test \"`echo '$''{'ac_cv_type_mode_t'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 8310 "configure"
++#line 8297 "configure"
+ #include "confdefs.h"
+ #include <sys/types.h>
+ #if STDC_HEADERS
+@@ -8334,12 +8321,12 @@
+ fi
+ 
+ echo $ac_n "checking for off_t""... $ac_c" 1>&6
+-echo "configure:8338: checking for off_t" >&5
++echo "configure:8325: checking for off_t" >&5
+ if eval "test \"`echo '$''{'ac_cv_type_off_t'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 8343 "configure"
++#line 8330 "configure"
+ #include "confdefs.h"
+ #include <sys/types.h>
+ #if STDC_HEADERS
+@@ -8367,12 +8354,12 @@
+ fi
+ 
+ echo $ac_n "checking for pid_t""... $ac_c" 1>&6
+-echo "configure:8371: checking for pid_t" >&5
++echo "configure:8358: checking for pid_t" >&5
+ if eval "test \"`echo '$''{'ac_cv_type_pid_t'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 8376 "configure"
++#line 8363 "configure"
+ #include "confdefs.h"
+ #include <sys/types.h>
+ #if STDC_HEADERS
+@@ -8400,12 +8387,12 @@
+ fi
+ 
+ echo $ac_n "checking for size_t""... $ac_c" 1>&6
+-echo "configure:8404: checking for size_t" >&5
++echo "configure:8391: checking for size_t" >&5
+ if eval "test \"`echo '$''{'ac_cv_type_size_t'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 8409 "configure"
++#line 8396 "configure"
+ #include "confdefs.h"
+ #include <sys/types.h>
+ #if STDC_HEADERS
+@@ -8440,12 +8427,12 @@
+ cross_compiling=$ac_cv_prog_cxx_cross
+ 
+ echo $ac_n "checking for __stdcall""... $ac_c" 1>&6
+-echo "configure:8444: checking for __stdcall" >&5
++echo "configure:8431: checking for __stdcall" >&5
+ if eval "test \"`echo '$''{'ac_cv___stdcall'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 8449 "configure"
++#line 8436 "configure"
+ #include "confdefs.h"
+ template <typename Method> struct foo;
+                   template <> struct foo<void (*)()> {};
+@@ -8454,7 +8441,7 @@
+ 
+ ; return 0; }
+ EOF
+-if { (eval echo configure:8458: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
++if { (eval echo configure:8445: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+   rm -rf conftest*
+   ac_cv___stdcall=true
+ else
+@@ -8483,12 +8470,12 @@
+ cross_compiling=$ac_cv_prog_cc_cross
+ 
+ echo $ac_n "checking for ssize_t""... $ac_c" 1>&6
+-echo "configure:8487: checking for ssize_t" >&5
++echo "configure:8474: checking for ssize_t" >&5
+ if eval "test \"`echo '$''{'ac_cv_type_ssize_t'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 8492 "configure"
++#line 8479 "configure"
+ #include "confdefs.h"
+ #include <stdio.h>
+                   #include <sys/types.h>
+@@ -8496,7 +8483,7 @@
+ ssize_t foo = 0;
+ ; return 0; }
+ EOF
+-if { (eval echo configure:8500: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
++if { (eval echo configure:8487: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+   rm -rf conftest*
+   ac_cv_type_ssize_t=true
+ else
+@@ -8518,12 +8505,12 @@
+   echo "$ac_t""no" 1>&6
+ fi
+ echo $ac_n "checking for st_blksize in struct stat""... $ac_c" 1>&6
+-echo "configure:8522: checking for st_blksize in struct stat" >&5
++echo "configure:8509: checking for st_blksize in struct stat" >&5
+ if eval "test \"`echo '$''{'ac_cv_struct_st_blksize'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 8527 "configure"
++#line 8514 "configure"
+ #include "confdefs.h"
+ #include <sys/types.h>
+ #include <sys/stat.h>
+@@ -8531,7 +8518,7 @@
+ struct stat s; s.st_blksize;
+ ; return 0; }
+ EOF
+-if { (eval echo configure:8535: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
++if { (eval echo configure:8522: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+   rm -rf conftest*
+   ac_cv_struct_st_blksize=yes
+ else
+@@ -8552,12 +8539,12 @@
+ fi
+ 
+ echo $ac_n "checking for siginfo_t""... $ac_c" 1>&6
+-echo "configure:8556: checking for siginfo_t" >&5
++echo "configure:8543: checking for siginfo_t" >&5
+ if eval "test \"`echo '$''{'ac_cv_siginfo_t'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 8561 "configure"
++#line 8548 "configure"
+ #include "confdefs.h"
+ #define _POSIX_C_SOURCE 199506L
+                   #include <signal.h>
+@@ -8565,7 +8552,7 @@
+ siginfo_t* info;
+ ; return 0; }
+ EOF
+-if { (eval echo configure:8569: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
++if { (eval echo configure:8556: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+   rm -rf conftest*
+   ac_cv_siginfo_t=true
+ else
+@@ -8590,17 +8577,17 @@
+ 
+ ac_safe=`echo "stdint.h" | sed 'y%./+-%__p_%'`
+ echo $ac_n "checking for stdint.h""... $ac_c" 1>&6
+-echo "configure:8594: checking for stdint.h" >&5
++echo "configure:8581: checking for stdint.h" >&5
+ if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 8599 "configure"
++#line 8586 "configure"
+ #include "confdefs.h"
+ #include <stdint.h>
+ EOF
+ ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
+-{ (eval echo configure:8604: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
++{ (eval echo configure:8591: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
+ ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
+ if test -z "$ac_err"; then
+   rm -rf conftest*
+@@ -8629,7 +8616,7 @@
+ else
+                     
+ echo $ac_n "checking for a 1-byte type""... $ac_c" 1>&6
+-echo "configure:8633: checking for a 1-byte type" >&5
++echo "configure:8620: checking for a 1-byte type" >&5
+ if eval "test \"`echo '$''{'moz_cv_n_byte_type_JS_INT8_TYPE'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+@@ -8637,7 +8624,7 @@
+   moz_cv_n_byte_type_JS_INT8_TYPE=
+   for type in char; do
+     cat > conftest.$ac_ext <<EOF
+-#line 8641 "configure"
++#line 8628 "configure"
+ #include "confdefs.h"
+ 
+ int main() {
+@@ -8647,7 +8634,7 @@
+                    
+ ; return 0; }
+ EOF
+-if { (eval echo configure:8651: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
++if { (eval echo configure:8638: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+   rm -rf conftest*
+   moz_cv_n_byte_type_JS_INT8_TYPE=$type; break
+ else
+@@ -8670,7 +8657,7 @@
+ 
+     
+ echo $ac_n "checking for a 2-byte type""... $ac_c" 1>&6
+-echo "configure:8674: checking for a 2-byte type" >&5
++echo "configure:8661: checking for a 2-byte type" >&5
+ if eval "test \"`echo '$''{'moz_cv_n_byte_type_JS_INT16_TYPE'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+@@ -8678,7 +8665,7 @@
+   moz_cv_n_byte_type_JS_INT16_TYPE=
+   for type in short int long; do
+     cat > conftest.$ac_ext <<EOF
+-#line 8682 "configure"
++#line 8669 "configure"
+ #include "confdefs.h"
+ 
+ int main() {
+@@ -8688,7 +8675,7 @@
+                    
+ ; return 0; }
+ EOF
+-if { (eval echo configure:8692: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
++if { (eval echo configure:8679: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+   rm -rf conftest*
+   moz_cv_n_byte_type_JS_INT16_TYPE=$type; break
+ else
+@@ -8711,7 +8698,7 @@
+ 
+     
+ echo $ac_n "checking for a 4-byte type""... $ac_c" 1>&6
+-echo "configure:8715: checking for a 4-byte type" >&5
++echo "configure:8702: checking for a 4-byte type" >&5
+ if eval "test \"`echo '$''{'moz_cv_n_byte_type_JS_INT32_TYPE'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+@@ -8719,7 +8706,7 @@
+   moz_cv_n_byte_type_JS_INT32_TYPE=
+   for type in int long 'long long' short; do
+     cat > conftest.$ac_ext <<EOF
+-#line 8723 "configure"
++#line 8710 "configure"
+ #include "confdefs.h"
+ 
+ int main() {
+@@ -8729,7 +8716,7 @@
+                    
+ ; return 0; }
+ EOF
+-if { (eval echo configure:8733: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
++if { (eval echo configure:8720: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+   rm -rf conftest*
+   moz_cv_n_byte_type_JS_INT32_TYPE=$type; break
+ else
+@@ -8752,7 +8739,7 @@
+ 
+     
+ echo $ac_n "checking for a 8-byte type""... $ac_c" 1>&6
+-echo "configure:8756: checking for a 8-byte type" >&5
++echo "configure:8743: checking for a 8-byte type" >&5
+ if eval "test \"`echo '$''{'moz_cv_n_byte_type_JS_INT64_TYPE'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+@@ -8760,7 +8747,7 @@
+   moz_cv_n_byte_type_JS_INT64_TYPE=
+   for type in int long 'long long'; do
+     cat > conftest.$ac_ext <<EOF
+-#line 8764 "configure"
++#line 8751 "configure"
+ #include "confdefs.h"
+ 
+ int main() {
+@@ -8770,7 +8757,7 @@
+                    
+ ; return 0; }
+ EOF
+-if { (eval echo configure:8774: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
++if { (eval echo configure:8761: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+   rm -rf conftest*
+   moz_cv_n_byte_type_JS_INT64_TYPE=$type; break
+ else
+@@ -8793,7 +8780,7 @@
+ 
+     
+ echo $ac_n "checking for a sizeof (void *)-byte type""... $ac_c" 1>&6
+-echo "configure:8797: checking for a sizeof (void *)-byte type" >&5
++echo "configure:8784: checking for a sizeof (void *)-byte type" >&5
+ if eval "test \"`echo '$''{'moz_cv_n_byte_type_JS_INTPTR_TYPE'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+@@ -8801,7 +8788,7 @@
+   moz_cv_n_byte_type_JS_INTPTR_TYPE=
+   for type in int long 'long long' short; do
+     cat > conftest.$ac_ext <<EOF
+-#line 8805 "configure"
++#line 8792 "configure"
+ #include "confdefs.h"
+ 
+ int main() {
+@@ -8811,7 +8798,7 @@
+                    
+ ; return 0; }
+ EOF
+-if { (eval echo configure:8815: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
++if { (eval echo configure:8802: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+   rm -rf conftest*
+   moz_cv_n_byte_type_JS_INTPTR_TYPE=$type; break
+ else
+@@ -8836,7 +8823,7 @@
+ 
+ 
+ echo $ac_n "checking for the size of void*""... $ac_c" 1>&6
+-echo "configure:8840: checking for the size of void*" >&5
++echo "configure:8827: checking for the size of void*" >&5
+ if eval "test \"`echo '$''{'moz_cv_size_of_JS_BYTES_PER_WORD'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+@@ -8844,7 +8831,7 @@
+   moz_cv_size_of_JS_BYTES_PER_WORD=
+   for size in 4 8; do
+     cat > conftest.$ac_ext <<EOF
+-#line 8848 "configure"
++#line 8835 "configure"
+ #include "confdefs.h"
+ 
+ int main() {
+@@ -8854,7 +8841,7 @@
+                    
+ ; return 0; }
+ EOF
+-if { (eval echo configure:8858: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
++if { (eval echo configure:8845: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+   rm -rf conftest*
+   moz_cv_size_of_JS_BYTES_PER_WORD=$size; break
+ else
+@@ -8891,7 +8878,7 @@
+ 
+ 
+ echo $ac_n "checking for the alignment of void*""... $ac_c" 1>&6
+-echo "configure:8895: checking for the alignment of void*" >&5
++echo "configure:8882: checking for the alignment of void*" >&5
+ if eval "test \"`echo '$''{'moz_cv_align_of_JS_ALIGN_OF_POINTER'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+@@ -8899,7 +8886,7 @@
+   moz_cv_align_of_JS_ALIGN_OF_POINTER=
+   for align in 2 4 8 16; do
+     cat > conftest.$ac_ext <<EOF
+-#line 8903 "configure"
++#line 8890 "configure"
+ #include "confdefs.h"
+ 
+                      #include <stddef.h>
+@@ -8912,7 +8899,7 @@
+                    
+ ; return 0; }
+ EOF
+-if { (eval echo configure:8916: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
++if { (eval echo configure:8903: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+   rm -rf conftest*
+   moz_cv_align_of_JS_ALIGN_OF_POINTER=$align; break
+ else
+@@ -8935,7 +8922,7 @@
+ 
+ 
+ echo $ac_n "checking for the size of double""... $ac_c" 1>&6
+-echo "configure:8939: checking for the size of double" >&5
++echo "configure:8926: checking for the size of double" >&5
+ if eval "test \"`echo '$''{'moz_cv_size_of_JS_BYTES_PER_DOUBLE'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+@@ -8943,7 +8930,7 @@
+   moz_cv_size_of_JS_BYTES_PER_DOUBLE=
+   for size in 6 8 10 12 14; do
+     cat > conftest.$ac_ext <<EOF
+-#line 8947 "configure"
++#line 8934 "configure"
+ #include "confdefs.h"
+ 
+ int main() {
+@@ -8953,7 +8940,7 @@
+                    
+ ; return 0; }
+ EOF
+-if { (eval echo configure:8957: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
++if { (eval echo configure:8944: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+   rm -rf conftest*
+   moz_cv_size_of_JS_BYTES_PER_DOUBLE=$size; break
+ else
+@@ -8976,12 +8963,12 @@
+ 
+ 
+ echo $ac_n "checking for int16_t""... $ac_c" 1>&6
+-echo "configure:8980: checking for int16_t" >&5
++echo "configure:8967: checking for int16_t" >&5
+ if eval "test \"`echo '$''{'ac_cv_int16_t'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 8985 "configure"
++#line 8972 "configure"
+ #include "confdefs.h"
+ #include <stdio.h>
+                   #include <sys/types.h>
+@@ -8989,7 +8976,7 @@
+ int16_t foo = 0;
+ ; return 0; }
+ EOF
+-if { (eval echo configure:8993: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
++if { (eval echo configure:8980: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+   rm -rf conftest*
+   ac_cv_int16_t=true
+ else
+@@ -9011,12 +8998,12 @@
+   echo "$ac_t""no" 1>&6
+ fi
+ echo $ac_n "checking for int32_t""... $ac_c" 1>&6
+-echo "configure:9015: checking for int32_t" >&5
++echo "configure:9002: checking for int32_t" >&5
+ if eval "test \"`echo '$''{'ac_cv_int32_t'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 9020 "configure"
++#line 9007 "configure"
+ #include "confdefs.h"
+ #include <stdio.h>
+                   #include <sys/types.h>
+@@ -9024,7 +9011,7 @@
+ int32_t foo = 0;
+ ; return 0; }
+ EOF
+-if { (eval echo configure:9028: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
++if { (eval echo configure:9015: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+   rm -rf conftest*
+   ac_cv_int32_t=true
+ else
+@@ -9046,12 +9033,12 @@
+   echo "$ac_t""no" 1>&6
+ fi
+ echo $ac_n "checking for int64_t""... $ac_c" 1>&6
+-echo "configure:9050: checking for int64_t" >&5
++echo "configure:9037: checking for int64_t" >&5
+ if eval "test \"`echo '$''{'ac_cv_int64_t'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 9055 "configure"
++#line 9042 "configure"
+ #include "confdefs.h"
+ #include <stdio.h>
+                   #include <sys/types.h>
+@@ -9059,7 +9046,7 @@
+ int64_t foo = 0;
+ ; return 0; }
+ EOF
+-if { (eval echo configure:9063: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
++if { (eval echo configure:9050: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+   rm -rf conftest*
+   ac_cv_int64_t=true
+ else
+@@ -9081,12 +9068,12 @@
+   echo "$ac_t""no" 1>&6
+ fi
+ echo $ac_n "checking for int64""... $ac_c" 1>&6
+-echo "configure:9085: checking for int64" >&5
++echo "configure:9072: checking for int64" >&5
+ if eval "test \"`echo '$''{'ac_cv_int64'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 9090 "configure"
++#line 9077 "configure"
+ #include "confdefs.h"
+ #include <stdio.h>
+                   #include <sys/types.h>
+@@ -9094,7 +9081,7 @@
+ int64 foo = 0;
+ ; return 0; }
+ EOF
+-if { (eval echo configure:9098: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
++if { (eval echo configure:9085: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+   rm -rf conftest*
+   ac_cv_int64=true
+ else
+@@ -9116,12 +9103,12 @@
+   echo "$ac_t""no" 1>&6
+ fi
+ echo $ac_n "checking for uint""... $ac_c" 1>&6
+-echo "configure:9120: checking for uint" >&5
++echo "configure:9107: checking for uint" >&5
+ if eval "test \"`echo '$''{'ac_cv_uint'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 9125 "configure"
++#line 9112 "configure"
+ #include "confdefs.h"
+ #include <stdio.h>
+                   #include <sys/types.h>
+@@ -9129,7 +9116,7 @@
+ uint foo = 0;
+ ; return 0; }
+ EOF
+-if { (eval echo configure:9133: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
++if { (eval echo configure:9120: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+   rm -rf conftest*
+   ac_cv_uint=true
+ else
+@@ -9151,12 +9138,12 @@
+   echo "$ac_t""no" 1>&6
+ fi
+ echo $ac_n "checking for uint_t""... $ac_c" 1>&6
+-echo "configure:9155: checking for uint_t" >&5
++echo "configure:9142: checking for uint_t" >&5
+ if eval "test \"`echo '$''{'ac_cv_uint_t'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 9160 "configure"
++#line 9147 "configure"
+ #include "confdefs.h"
+ #include <stdio.h>
+                   #include <sys/types.h>
+@@ -9164,7 +9151,7 @@
+ uint_t foo = 0;
+ ; return 0; }
+ EOF
+-if { (eval echo configure:9168: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
++if { (eval echo configure:9155: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+   rm -rf conftest*
+   ac_cv_uint_t=true
+ else
+@@ -9186,12 +9173,12 @@
+   echo "$ac_t""no" 1>&6
+ fi
+ echo $ac_n "checking for uint16_t""... $ac_c" 1>&6
+-echo "configure:9190: checking for uint16_t" >&5
++echo "configure:9177: checking for uint16_t" >&5
+ if eval "test \"`echo '$''{'ac_cv_uint16_t'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 9195 "configure"
++#line 9182 "configure"
+ #include "confdefs.h"
+ #include <stdio.h>
+                   #include <sys/types.h>
+@@ -9199,7 +9186,7 @@
+ uint16_t foo = 0;
+ ; return 0; }
+ EOF
+-if { (eval echo configure:9203: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
++if { (eval echo configure:9190: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+   rm -rf conftest*
+   ac_cv_uint16_t=true
+ else
+@@ -9230,12 +9217,12 @@
+ 
+ 
+ echo $ac_n "checking for uname.domainname""... $ac_c" 1>&6
+-echo "configure:9234: checking for uname.domainname" >&5
++echo "configure:9221: checking for uname.domainname" >&5
+ if eval "test \"`echo '$''{'ac_cv_have_uname_domainname_field'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 9239 "configure"
++#line 9226 "configure"
+ #include "confdefs.h"
+ #include <sys/utsname.h>
+ int main() {
+@@ -9243,7 +9230,7 @@
+             (void)uname(res);  if (res != 0) { domain = res->domainname; } 
+ ; return 0; }
+ EOF
+-if { (eval echo configure:9247: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
++if { (eval echo configure:9234: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+   rm -rf conftest*
+   ac_cv_have_uname_domainname_field=true
+ else
+@@ -9267,12 +9254,12 @@
+ fi
+ 
+ echo $ac_n "checking for uname.__domainname""... $ac_c" 1>&6
+-echo "configure:9271: checking for uname.__domainname" >&5
++echo "configure:9258: checking for uname.__domainname" >&5
+ if eval "test \"`echo '$''{'ac_cv_have_uname_us_domainname_field'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 9276 "configure"
++#line 9263 "configure"
+ #include "confdefs.h"
+ #include <sys/utsname.h>
+ int main() {
+@@ -9280,7 +9267,7 @@
+             (void)uname(res);  if (res != 0) { domain = res->__domainname; } 
+ ; return 0; }
+ EOF
+-if { (eval echo configure:9284: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
++if { (eval echo configure:9271: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+   rm -rf conftest*
+   ac_cv_have_uname_us_domainname_field=true
+ else
+@@ -9313,7 +9300,7 @@
+ 
+ if test "$GNU_CC"; then
+   echo $ac_n "checking for visibility(hidden) attribute""... $ac_c" 1>&6
+-echo "configure:9317: checking for visibility(hidden) attribute" >&5
++echo "configure:9304: checking for visibility(hidden) attribute" >&5
+ if eval "test \"`echo '$''{'ac_cv_visibility_hidden'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+@@ -9338,7 +9325,7 @@
+ 
+ 
+     echo $ac_n "checking for visibility(default) attribute""... $ac_c" 1>&6
+-echo "configure:9342: checking for visibility(default) attribute" >&5
++echo "configure:9329: checking for visibility(default) attribute" >&5
+ if eval "test \"`echo '$''{'ac_cv_visibility_default'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+@@ -9363,7 +9350,7 @@
+ 
+ 
+       echo $ac_n "checking for visibility pragma support""... $ac_c" 1>&6
+-echo "configure:9367: checking for visibility pragma support" >&5
++echo "configure:9354: checking for visibility pragma support" >&5
+ if eval "test \"`echo '$''{'ac_cv_visibility_pragma'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+@@ -9388,7 +9375,7 @@
+ echo "$ac_t""$ac_cv_visibility_pragma" 1>&6
+       if test "$ac_cv_visibility_pragma" = "yes"; then
+         echo $ac_n "checking For gcc visibility bug with class-level attributes (GCC bug 26905)""... $ac_c" 1>&6
+-echo "configure:9392: checking For gcc visibility bug with class-level attributes (GCC bug 26905)" >&5
++echo "configure:9379: checking For gcc visibility bug with class-level attributes (GCC bug 26905)" >&5
+ if eval "test \"`echo '$''{'ac_cv_have_visibility_class_bug'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+@@ -9416,7 +9403,7 @@
+ echo "$ac_t""$ac_cv_have_visibility_class_bug" 1>&6
+ 
+         echo $ac_n "checking For x86_64 gcc visibility bug with builtins (GCC bug 20297)""... $ac_c" 1>&6
+-echo "configure:9420: checking For x86_64 gcc visibility bug with builtins (GCC bug 20297)" >&5
++echo "configure:9407: checking For x86_64 gcc visibility bug with builtins (GCC bug 20297)" >&5
+ if eval "test \"`echo '$''{'ac_cv_have_visibility_builtin_bug'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+@@ -9470,19 +9457,19 @@
+   CFLAGS_save="${CFLAGS}"
+   CFLAGS="${CFLAGS} -Werror"
+   echo $ac_n "checking for __force_align_arg_pointer__ attribute""... $ac_c" 1>&6
+-echo "configure:9474: checking for __force_align_arg_pointer__ attribute" >&5
++echo "configure:9461: checking for __force_align_arg_pointer__ attribute" >&5
+ if eval "test \"`echo '$''{'ac_cv_force_align_arg_pointer'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 9479 "configure"
++#line 9466 "configure"
+ #include "confdefs.h"
+ __attribute__ ((__force_align_arg_pointer__)) void test() {}
+ int main() {
+ 
+ ; return 0; }
+ EOF
+-if { (eval echo configure:9486: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
++if { (eval echo configure:9473: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+   rm -rf conftest*
+   ac_cv_force_align_arg_pointer="yes"
+ else
+@@ -9509,12 +9496,12 @@
+ do
+ ac_safe=`echo "$ac_hdr" | sed 'y%./+-%__p_%'`
+ echo $ac_n "checking for $ac_hdr that defines DIR""... $ac_c" 1>&6
+-echo "configure:9513: checking for $ac_hdr that defines DIR" >&5
++echo "configure:9500: checking for $ac_hdr that defines DIR" >&5
+ if eval "test \"`echo '$''{'ac_cv_header_dirent_$ac_safe'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 9518 "configure"
++#line 9505 "configure"
+ #include "confdefs.h"
+ #include <sys/types.h>
+ #include <$ac_hdr>
+@@ -9522,7 +9509,7 @@
+ DIR *dirp = 0;
+ ; return 0; }
+ EOF
+-if { (eval echo configure:9526: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
++if { (eval echo configure:9513: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+   rm -rf conftest*
+   eval "ac_cv_header_dirent_$ac_safe=yes"
+ else
+@@ -9547,7 +9534,7 @@
+ # Two versions of opendir et al. are in -ldir and -lx on SCO Xenix.
+ if test $ac_header_dirent = dirent.h; then
+ echo $ac_n "checking for opendir in -ldir""... $ac_c" 1>&6
+-echo "configure:9551: checking for opendir in -ldir" >&5
++echo "configure:9538: checking for opendir in -ldir" >&5
+ ac_lib_var=`echo dir'_'opendir | sed 'y%./+-%__p_%'`
+ if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+@@ -9555,7 +9542,7 @@
+   ac_save_LIBS="$LIBS"
+ LIBS="-ldir  $LIBS"
+ cat > conftest.$ac_ext <<EOF
+-#line 9559 "configure"
++#line 9546 "configure"
+ #include "confdefs.h"
+ /* Override any gcc2 internal prototype to avoid an error.  */
+ /* We use char because int might match the return type of a gcc2
+@@ -9566,7 +9553,7 @@
+ opendir()
+ ; return 0; }
+ EOF
+-if { (eval echo configure:9570: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
++if { (eval echo configure:9557: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
+   rm -rf conftest*
+   eval "ac_cv_lib_$ac_lib_var=yes"
+ else
+@@ -9588,7 +9575,7 @@
+ 
+ else
+ echo $ac_n "checking for opendir in -lx""... $ac_c" 1>&6
+-echo "configure:9592: checking for opendir in -lx" >&5
++echo "configure:9579: checking for opendir in -lx" >&5
+ ac_lib_var=`echo x'_'opendir | sed 'y%./+-%__p_%'`
+ if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+@@ -9596,7 +9583,7 @@
+   ac_save_LIBS="$LIBS"
+ LIBS="-lx  $LIBS"
+ cat > conftest.$ac_ext <<EOF
+-#line 9600 "configure"
++#line 9587 "configure"
+ #include "confdefs.h"
+ /* Override any gcc2 internal prototype to avoid an error.  */
+ /* We use char because int might match the return type of a gcc2
+@@ -9607,7 +9594,7 @@
+ opendir()
+ ; return 0; }
+ EOF
+-if { (eval echo configure:9611: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
++if { (eval echo configure:9598: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
+   rm -rf conftest*
+   eval "ac_cv_lib_$ac_lib_var=yes"
+ else
+@@ -9639,17 +9626,17 @@
+ do
+ ac_safe=`echo "$ac_hdr" | sed 'y%./+-%__p_%'`
+ echo $ac_n "checking for $ac_hdr""... $ac_c" 1>&6
+-echo "configure:9643: checking for $ac_hdr" >&5
++echo "configure:9630: checking for $ac_hdr" >&5
+ if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 9648 "configure"
++#line 9635 "configure"
+ #include "confdefs.h"
+ #include <$ac_hdr>
+ EOF
+ ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
+-{ (eval echo configure:9653: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
++{ (eval echo configure:9640: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
+ ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
+ if test -z "$ac_err"; then
+   rm -rf conftest*
+@@ -9679,17 +9666,17 @@
+ do
+ ac_safe=`echo "$ac_hdr" | sed 'y%./+-%__p_%'`
+ echo $ac_n "checking for $ac_hdr""... $ac_c" 1>&6
+-echo "configure:9683: checking for $ac_hdr" >&5
++echo "configure:9670: checking for $ac_hdr" >&5
+ if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 9688 "configure"
++#line 9675 "configure"
+ #include "confdefs.h"
+ #include <$ac_hdr>
+ EOF
+ ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
+-{ (eval echo configure:9693: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
++{ (eval echo configure:9680: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
+ ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
+ if test -z "$ac_err"; then
+   rm -rf conftest*
+@@ -9719,17 +9706,17 @@
+ do
+ ac_safe=`echo "$ac_hdr" | sed 'y%./+-%__p_%'`
+ echo $ac_n "checking for $ac_hdr""... $ac_c" 1>&6
+-echo "configure:9723: checking for $ac_hdr" >&5
++echo "configure:9710: checking for $ac_hdr" >&5
+ if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 9728 "configure"
++#line 9715 "configure"
+ #include "confdefs.h"
+ #include <$ac_hdr>
+ EOF
+ ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
+-{ (eval echo configure:9733: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
++{ (eval echo configure:9720: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
+ ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
+ if test -z "$ac_err"; then
+   rm -rf conftest*
+@@ -9759,17 +9746,17 @@
+ do
+ ac_safe=`echo "$ac_hdr" | sed 'y%./+-%__p_%'`
+ echo $ac_n "checking for $ac_hdr""... $ac_c" 1>&6
+-echo "configure:9763: checking for $ac_hdr" >&5
++echo "configure:9750: checking for $ac_hdr" >&5
+ if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 9768 "configure"
++#line 9755 "configure"
+ #include "confdefs.h"
+ #include <$ac_hdr>
+ EOF
+ ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
+-{ (eval echo configure:9773: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
++{ (eval echo configure:9760: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
+ ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
+ if test -z "$ac_err"; then
+   rm -rf conftest*
+@@ -9799,17 +9786,17 @@
+ do
+ ac_safe=`echo "$ac_hdr" | sed 'y%./+-%__p_%'`
+ echo $ac_n "checking for $ac_hdr""... $ac_c" 1>&6
+-echo "configure:9803: checking for $ac_hdr" >&5
++echo "configure:9790: checking for $ac_hdr" >&5
+ if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 9808 "configure"
++#line 9795 "configure"
+ #include "confdefs.h"
+ #include <$ac_hdr>
+ EOF
+ ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
+-{ (eval echo configure:9813: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
++{ (eval echo configure:9800: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
+ ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
+ if test -z "$ac_err"; then
+   rm -rf conftest*
+@@ -9839,17 +9826,17 @@
+ do
+ ac_safe=`echo "$ac_hdr" | sed 'y%./+-%__p_%'`
+ echo $ac_n "checking for $ac_hdr""... $ac_c" 1>&6
+-echo "configure:9843: checking for $ac_hdr" >&5
++echo "configure:9830: checking for $ac_hdr" >&5
+ if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 9848 "configure"
++#line 9835 "configure"
+ #include "confdefs.h"
+ #include <$ac_hdr>
+ EOF
+ ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
+-{ (eval echo configure:9853: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
++{ (eval echo configure:9840: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
+ ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
+ if test -z "$ac_err"; then
+   rm -rf conftest*
+@@ -9880,17 +9867,17 @@
+ do
+ ac_safe=`echo "$ac_hdr" | sed 'y%./+-%__p_%'`
+ echo $ac_n "checking for $ac_hdr""... $ac_c" 1>&6
+-echo "configure:9884: checking for $ac_hdr" >&5
++echo "configure:9871: checking for $ac_hdr" >&5
+ if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 9889 "configure"
++#line 9876 "configure"
+ #include "confdefs.h"
+ #include <$ac_hdr>
+ EOF
+ ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
+-{ (eval echo configure:9894: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
++{ (eval echo configure:9881: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
+ ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
+ if test -z "$ac_err"; then
+   rm -rf conftest*
+@@ -9921,17 +9908,17 @@
+ do
+ ac_safe=`echo "$ac_hdr" | sed 'y%./+-%__p_%'`
+ echo $ac_n "checking for $ac_hdr""... $ac_c" 1>&6
+-echo "configure:9925: checking for $ac_hdr" >&5
++echo "configure:9912: checking for $ac_hdr" >&5
+ if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 9930 "configure"
++#line 9917 "configure"
+ #include "confdefs.h"
+ #include <$ac_hdr>
+ EOF
+ ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
+-{ (eval echo configure:9935: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
++{ (eval echo configure:9922: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
+ ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
+ if test -z "$ac_err"; then
+   rm -rf conftest*
+@@ -9961,17 +9948,17 @@
+ do
+ ac_safe=`echo "$ac_hdr" | sed 'y%./+-%__p_%'`
+ echo $ac_n "checking for $ac_hdr""... $ac_c" 1>&6
+-echo "configure:9965: checking for $ac_hdr" >&5
++echo "configure:9952: checking for $ac_hdr" >&5
+ if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 9970 "configure"
++#line 9957 "configure"
+ #include "confdefs.h"
+ #include <$ac_hdr>
+ EOF
+ ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
+-{ (eval echo configure:9975: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
++{ (eval echo configure:9962: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
+ ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
+ if test -z "$ac_err"; then
+   rm -rf conftest*
+@@ -10002,17 +9989,17 @@
+ do
+ ac_safe=`echo "$ac_hdr" | sed 'y%./+-%__p_%'`
+ echo $ac_n "checking for $ac_hdr""... $ac_c" 1>&6
+-echo "configure:10006: checking for $ac_hdr" >&5
++echo "configure:9993: checking for $ac_hdr" >&5
+ if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 10011 "configure"
++#line 9998 "configure"
+ #include "confdefs.h"
+ #include <$ac_hdr>
+ EOF
+ ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
+-{ (eval echo configure:10016: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
++{ (eval echo configure:10003: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
+ ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
+ if test -z "$ac_err"; then
+   rm -rf conftest*
+@@ -10049,17 +10036,17 @@
+ NEW_H=new.h
+ ac_safe=`echo "new" | sed 'y%./+-%__p_%'`
+ echo $ac_n "checking for new""... $ac_c" 1>&6
+-echo "configure:10053: checking for new" >&5
++echo "configure:10040: checking for new" >&5
+ if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 10058 "configure"
++#line 10045 "configure"
+ #include "confdefs.h"
+ #include <new>
+ EOF
+ ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
+-{ (eval echo configure:10063: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
++{ (eval echo configure:10050: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
+ ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
+ if test -z "$ac_err"; then
+   rm -rf conftest*
+@@ -10101,17 +10088,17 @@
+ if test "x$enable_dtrace" = "xyes"; then
+   ac_safe=`echo "sys/sdt.h" | sed 'y%./+-%__p_%'`
+ echo $ac_n "checking for sys/sdt.h""... $ac_c" 1>&6
+-echo "configure:10105: checking for sys/sdt.h" >&5
++echo "configure:10092: checking for sys/sdt.h" >&5
+ if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 10110 "configure"
++#line 10097 "configure"
+ #include "confdefs.h"
+ #include <sys/sdt.h>
+ EOF
+ ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
+-{ (eval echo configure:10115: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
++{ (eval echo configure:10102: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
+ ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
+ if test -z "$ac_err"; then
+   rm -rf conftest*
+@@ -10151,17 +10138,17 @@
+ do
+ ac_safe=`echo "$ac_hdr" | sed 'y%./+-%__p_%'`
+ echo $ac_n "checking for $ac_hdr""... $ac_c" 1>&6
+-echo "configure:10155: checking for $ac_hdr" >&5
++echo "configure:10142: checking for $ac_hdr" >&5
+ if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 10160 "configure"
++#line 10147 "configure"
+ #include "confdefs.h"
+ #include <$ac_hdr>
+ EOF
+ ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
+-{ (eval echo configure:10165: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
++{ (eval echo configure:10152: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
+ ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
+ if test -z "$ac_err"; then
+   rm -rf conftest*
+@@ -10192,17 +10179,17 @@
+ 
+ ac_safe=`echo "linux/perf_event.h" | sed 'y%./+-%__p_%'`
+ echo $ac_n "checking for linux/perf_event.h""... $ac_c" 1>&6
+-echo "configure:10196: checking for linux/perf_event.h" >&5
++echo "configure:10183: checking for linux/perf_event.h" >&5
+ if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 10201 "configure"
++#line 10188 "configure"
+ #include "confdefs.h"
+ #include <linux/perf_event.h>
+ EOF
+ ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
+-{ (eval echo configure:10206: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
++{ (eval echo configure:10193: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
+ ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
+ if test -z "$ac_err"; then
+   rm -rf conftest*
+@@ -10230,7 +10217,7 @@
+ 	;;
+ *)
+ 	echo $ac_n "checking for gethostbyname_r in -lc_r""... $ac_c" 1>&6
+-echo "configure:10234: checking for gethostbyname_r in -lc_r" >&5
++echo "configure:10221: checking for gethostbyname_r in -lc_r" >&5
+ ac_lib_var=`echo c_r'_'gethostbyname_r | sed 'y%./+-%__p_%'`
+ if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+@@ -10238,7 +10225,7 @@
+   ac_save_LIBS="$LIBS"
+ LIBS="-lc_r  $LIBS"
+ cat > conftest.$ac_ext <<EOF
+-#line 10242 "configure"
++#line 10229 "configure"
+ #include "confdefs.h"
+ /* Override any gcc2 internal prototype to avoid an error.  */
+ /* We use char because int might match the return type of a gcc2
+@@ -10249,7 +10236,7 @@
+ gethostbyname_r()
+ ; return 0; }
+ EOF
+-if { (eval echo configure:10253: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
++if { (eval echo configure:10240: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
+   rm -rf conftest*
+   eval "ac_cv_lib_$ac_lib_var=yes"
+ else
+@@ -10289,14 +10276,14 @@
+ *)
+     
+ echo $ac_n "checking for library containing dlopen""... $ac_c" 1>&6
+-echo "configure:10293: checking for library containing dlopen" >&5
++echo "configure:10280: checking for library containing dlopen" >&5
+ if eval "test \"`echo '$''{'ac_cv_search_dlopen'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   ac_func_search_save_LIBS="$LIBS"
+ ac_cv_search_dlopen="no"
+ cat > conftest.$ac_ext <<EOF
+-#line 10300 "configure"
++#line 10287 "configure"
+ #include "confdefs.h"
+ /* Override any gcc2 internal prototype to avoid an error.  */
+ /* We use char because int might match the return type of a gcc2
+@@ -10307,7 +10294,7 @@
+ dlopen()
+ ; return 0; }
+ EOF
+-if { (eval echo configure:10311: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
++if { (eval echo configure:10298: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
+   rm -rf conftest*
+   ac_cv_search_dlopen="none required"
+ else
+@@ -10318,7 +10305,7 @@
+ test "$ac_cv_search_dlopen" = "no" && for i in dl; do
+ LIBS="-l$i  $ac_func_search_save_LIBS"
+ cat > conftest.$ac_ext <<EOF
+-#line 10322 "configure"
++#line 10309 "configure"
+ #include "confdefs.h"
+ /* Override any gcc2 internal prototype to avoid an error.  */
+ /* We use char because int might match the return type of a gcc2
+@@ -10329,7 +10316,7 @@
+ dlopen()
+ ; return 0; }
+ EOF
+-if { (eval echo configure:10333: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
++if { (eval echo configure:10320: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
+   rm -rf conftest*
+   ac_cv_search_dlopen="-l$i"
+ break
+@@ -10347,17 +10334,17 @@
+   test "$ac_cv_search_dlopen" = "none required" || LIBS="$ac_cv_search_dlopen $LIBS"
+   ac_safe=`echo "dlfcn.h" | sed 'y%./+-%__p_%'`
+ echo $ac_n "checking for dlfcn.h""... $ac_c" 1>&6
+-echo "configure:10351: checking for dlfcn.h" >&5
++echo "configure:10338: checking for dlfcn.h" >&5
+ if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 10356 "configure"
++#line 10343 "configure"
+ #include "confdefs.h"
+ #include <dlfcn.h>
+ EOF
+ ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
+-{ (eval echo configure:10361: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
++{ (eval echo configure:10348: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
+ ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"`
+ if test -z "$ac_err"; then
+   rm -rf conftest*
+@@ -10392,12 +10379,12 @@
+ for ac_func in dladdr
+ do
+ echo $ac_n "checking for $ac_func""... $ac_c" 1>&6
+-echo "configure:10396: checking for $ac_func" >&5
++echo "configure:10383: checking for $ac_func" >&5
+ if eval "test \"`echo '$''{'ac_cv_func_$ac_func'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 10401 "configure"
++#line 10388 "configure"
+ #include "confdefs.h"
+ /* System header to define __stub macros and hopefully few prototypes,
+     which can conflict with char $ac_func(); below.  */
+@@ -10420,7 +10407,7 @@
+ 
+ ; return 0; }
+ EOF
+-if { (eval echo configure:10424: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
++if { (eval echo configure:10411: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
+   rm -rf conftest*
+   eval "ac_cv_func_$ac_func=yes"
+ else
+@@ -10451,7 +10438,7 @@
+     case $target in
+     *-aix*)
+ 	echo $ac_n "checking for demangle in -lC_r""... $ac_c" 1>&6
+-echo "configure:10455: checking for demangle in -lC_r" >&5
++echo "configure:10442: checking for demangle in -lC_r" >&5
+ ac_lib_var=`echo C_r'_'demangle | sed 'y%./+-%__p_%'`
+ if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+@@ -10459,7 +10446,7 @@
+   ac_save_LIBS="$LIBS"
+ LIBS="-lC_r  $LIBS"
+ cat > conftest.$ac_ext <<EOF
+-#line 10463 "configure"
++#line 10450 "configure"
+ #include "confdefs.h"
+ /* Override any gcc2 internal prototype to avoid an error.  */
+ /* We use char because int might match the return type of a gcc2
+@@ -10470,7 +10457,7 @@
+ demangle()
+ ; return 0; }
+ EOF
+-if { (eval echo configure:10474: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
++if { (eval echo configure:10461: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
+   rm -rf conftest*
+   eval "ac_cv_lib_$ac_lib_var=yes"
+ else
+@@ -10500,7 +10487,7 @@
+ 	;;
+      *)
+ 	echo $ac_n "checking for demangle in -lC""... $ac_c" 1>&6
+-echo "configure:10504: checking for demangle in -lC" >&5
++echo "configure:10491: checking for demangle in -lC" >&5
+ ac_lib_var=`echo C'_'demangle | sed 'y%./+-%__p_%'`
+ if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+@@ -10508,7 +10495,7 @@
+   ac_save_LIBS="$LIBS"
+ LIBS="-lC  $LIBS"
+ cat > conftest.$ac_ext <<EOF
+-#line 10512 "configure"
++#line 10499 "configure"
+ #include "confdefs.h"
+ /* Override any gcc2 internal prototype to avoid an error.  */
+ /* We use char because int might match the return type of a gcc2
+@@ -10519,7 +10506,7 @@
+ demangle()
+ ; return 0; }
+ EOF
+-if { (eval echo configure:10523: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
++if { (eval echo configure:10510: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
+   rm -rf conftest*
+   eval "ac_cv_lib_$ac_lib_var=yes"
+ else
+@@ -10555,7 +10542,7 @@
+     ;;
+ *)
+     echo $ac_n "checking for socket in -lsocket""... $ac_c" 1>&6
+-echo "configure:10559: checking for socket in -lsocket" >&5
++echo "configure:10546: checking for socket in -lsocket" >&5
+ ac_lib_var=`echo socket'_'socket | sed 'y%./+-%__p_%'`
+ if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+@@ -10563,7 +10550,7 @@
+   ac_save_LIBS="$LIBS"
+ LIBS="-lsocket  $LIBS"
+ cat > conftest.$ac_ext <<EOF
+-#line 10567 "configure"
++#line 10554 "configure"
+ #include "confdefs.h"
+ /* Override any gcc2 internal prototype to avoid an error.  */
+ /* We use char because int might match the return type of a gcc2
+@@ -10574,7 +10561,7 @@
+ socket()
+ ; return 0; }
+ EOF
+-if { (eval echo configure:10578: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
++if { (eval echo configure:10565: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
+   rm -rf conftest*
+   eval "ac_cv_lib_$ac_lib_var=yes"
+ else
+@@ -10604,16 +10591,16 @@
+ esac
+ 
+ echo $ac_n "checking for ARM SIMD support in compiler""... $ac_c" 1>&6
+-echo "configure:10608: checking for ARM SIMD support in compiler" >&5
++echo "configure:10595: checking for ARM SIMD support in compiler" >&5
+ cat > conftest.$ac_ext <<EOF
+-#line 10610 "configure"
++#line 10597 "configure"
+ #include "confdefs.h"
+ 
+ int main() {
+ asm("uqadd8 r1, r1, r2");
+ ; return 0; }
+ EOF
+-if { (eval echo configure:10617: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
++if { (eval echo configure:10604: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+   rm -rf conftest*
+   result="yes"
+ else
+@@ -10634,21 +10621,21 @@
+ 
+ 
+ echo $ac_n "checking for ARM NEON support in compiler""... $ac_c" 1>&6
+-echo "configure:10638: checking for ARM NEON support in compiler" >&5
++echo "configure:10625: checking for ARM NEON support in compiler" >&5
+ _SAVE_CFLAGS="$CFLAGS"
+ if test "$GNU_CC"; then
+   # gcc needs -mfpu=neon to recognize NEON instructions
+   CFLAGS="$CFLAGS -mfpu=neon -mfloat-abi=softfp"
+ fi
+ cat > conftest.$ac_ext <<EOF
+-#line 10645 "configure"
++#line 10632 "configure"
+ #include "confdefs.h"
+ 
+ int main() {
+ asm("vadd.i8 d0, d0, d0");
+ ; return 0; }
+ EOF
+-if { (eval echo configure:10652: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
++if { (eval echo configure:10639: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
+   rm -rf conftest*
+   result="yes"
+ else
+@@ -10676,7 +10663,7 @@
+ *)
+     
+ echo $ac_n "checking for pthread_create in -lpthreads""... $ac_c" 1>&6
+-echo "configure:10680: checking for pthread_create in -lpthreads" >&5
++echo "configure:10667: checking for pthread_create in -lpthreads" >&5
+ echo "
+     #include <pthread.h>
+     #include <stdlib.h>
+@@ -10699,7 +10686,7 @@
+         echo "$ac_t""no" 1>&6
+         
+ echo $ac_n "checking for pthread_create in -lpthread""... $ac_c" 1>&6
+-echo "configure:10703: checking for pthread_create in -lpthread" >&5
++echo "configure:10690: checking for pthread_create in -lpthread" >&5
+ echo "
+     #include <pthread.h>
+     #include <stdlib.h>
+@@ -10722,7 +10709,7 @@
+         echo "$ac_t""no" 1>&6
+         
+ echo $ac_n "checking for pthread_create in -lc_r""... $ac_c" 1>&6
+-echo "configure:10726: checking for pthread_create in -lc_r" >&5
++echo "configure:10713: checking for pthread_create in -lc_r" >&5
+ echo "
+     #include <pthread.h>
+     #include <stdlib.h>
+@@ -10745,7 +10732,7 @@
+         echo "$ac_t""no" 1>&6
+         
+ echo $ac_n "checking for pthread_create in -lc""... $ac_c" 1>&6
+-echo "configure:10749: checking for pthread_create in -lc" >&5
++echo "configure:10736: checking for pthread_create in -lc" >&5
+ echo "
+     #include <pthread.h>
+     #include <stdlib.h>
+@@ -10804,7 +10791,7 @@
+ 				rm -f conftest*
+ 	ac_cv_have_dash_pthread=no
+ 	echo $ac_n "checking whether ${CC-cc} accepts -pthread""... $ac_c" 1>&6
+-echo "configure:10808: checking whether ${CC-cc} accepts -pthread" >&5
++echo "configure:10795: checking whether ${CC-cc} accepts -pthread" >&5
+ 	echo 'int main() { return 0; }' | cat > conftest.c
+ 	${CC-cc} -pthread -o conftest conftest.c > conftest.out 2>&1
+ 	if test $? -eq 0; then
+@@ -10827,7 +10814,7 @@
+ 			    ac_cv_have_dash_pthreads=no
+     if test "$ac_cv_have_dash_pthread" = "no"; then
+ 	    echo $ac_n "checking whether ${CC-cc} accepts -pthreads""... $ac_c" 1>&6
+-echo "configure:10831: checking whether ${CC-cc} accepts -pthreads" >&5
++echo "configure:10818: checking whether ${CC-cc} accepts -pthreads" >&5
+     	echo 'int main() { return 0; }' | cat > conftest.c
+ 	    ${CC-cc} -pthreads -o conftest conftest.c > conftest.out 2>&1
+     	if test $? -eq 0; then
+@@ -10922,7 +10909,7 @@
+ fi
+ 
+ echo $ac_n "checking whether mmap() sees write()s""... $ac_c" 1>&6
+-echo "configure:10926: checking whether mmap() sees write()s" >&5
++echo "configure:10913: checking whether mmap() sees write()s" >&5
+ 
+ 
+ mmap_test_prog='
+@@ -10961,11 +10948,11 @@
+   result="yes"
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 10965 "configure"
++#line 10952 "configure"
+ #include "confdefs.h"
+ $mmap_test_prog 
+ EOF
+-if { (eval echo configure:10969: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext} && (./conftest; exit) 2>/dev/null
++if { (eval echo configure:10956: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext} && (./conftest; exit) 2>/dev/null
+ then
+   result="yes"
+ else
+@@ -10990,13 +10977,13 @@
+ 
+ if test $ac_cv_prog_gcc = yes; then
+     echo $ac_n "checking whether ${CC-cc} needs -traditional""... $ac_c" 1>&6
+-echo "configure:10994: checking whether ${CC-cc} needs -traditional" >&5
++echo "configure:10981: checking whether ${CC-cc} needs -traditional" >&5
+ if eval "test \"`echo '$''{'ac_cv_prog_gcc_traditional'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+     ac_pattern="Autoconf.*'x'"
+   cat > conftest.$ac_ext <<EOF
+-#line 11000 "configure"
++#line 10987 "configure"
+ #include "confdefs.h"
+ #include <sgtty.h>
+ Autoconf TIOCGETP
+@@ -11014,7 +11001,7 @@
+ 
+   if test $ac_cv_prog_gcc_traditional = no; then
+     cat > conftest.$ac_ext <<EOF
+-#line 11018 "configure"
++#line 11005 "configure"
+ #include "confdefs.h"
+ #include <termio.h>
+ Autoconf TCGETA
+@@ -11036,7 +11023,7 @@
+ fi
+ 
+ echo $ac_n "checking for 8-bit clean memcmp""... $ac_c" 1>&6
+-echo "configure:11040: checking for 8-bit clean memcmp" >&5
++echo "configure:11027: checking for 8-bit clean memcmp" >&5
+ if eval "test \"`echo '$''{'ac_cv_func_memcmp_clean'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+@@ -11044,7 +11031,7 @@
+   ac_cv_func_memcmp_clean=no
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 11048 "configure"
++#line 11035 "configure"
+ #include "confdefs.h"
+ 
+ main()
+@@ -11054,7 +11041,7 @@
+ }
+ 
+ EOF
+-if { (eval echo configure:11058: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext} && (./conftest; exit) 2>/dev/null
++if { (eval echo configure:11045: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext} && (./conftest; exit) 2>/dev/null
+ then
+   ac_cv_func_memcmp_clean=yes
+ else
+@@ -11076,12 +11063,12 @@
+                 stat64 statvfs statvfs64 strerror strtok_r truncate64
+ do
+ echo $ac_n "checking for $ac_func""... $ac_c" 1>&6
+-echo "configure:11080: checking for $ac_func" >&5
++echo "configure:11067: checking for $ac_func" >&5
+ if eval "test \"`echo '$''{'ac_cv_func_$ac_func'+set}'`\" = set"; then
+   echo $ac_n "(cached) $ac_c" 1>&6
+ else
+   cat > conftest.$ac_ext <<EOF
+-#line 11085 "configure"
++#line 11072 "configure"
+ #include "confdefs.h"
+ /* System header to define __stub macros and hopefully few prototypes,
+     which can conflict with char $ac_func(); below.  */
+@@ -11104,7 +11091,7 @@
+ 
+ ; return 0; }
+ EOF
+-if { (eval echo configure:11108: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
++if { (eval echo configure:11095: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
+   rm -rf conftest*
+   eval "ac_cv_func_$ac_func=yes"
+ else
+@@ -11132,12 +11119,12 @@
+ _SAVE_LDFLAGS=$LDFLAGS
+ LDFLAGS="$LDFLAGS -lrt"
+ echo $ac_n "checking for clock_gettime(CLOCK_MONOTONIC) and -lrt""... $ac_c" 1>&6
+-echo "config

<TRUNCATED>

[35/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/auth/resources.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/auth/resources.js b/apps/fauxton/app/addons/auth/resources.js
deleted file mode 100644
index b1d40cc..0000000
--- a/apps/fauxton/app/addons/auth/resources.js
+++ /dev/null
@@ -1,364 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-       "app",
-       "api"
-],
-
-function (app, FauxtonAPI) {
-
-  var Auth = new FauxtonAPI.addon();
-
-  var Admin = Backbone.Model.extend({
-
-    url: function () {
-      return app.host + '/_config/admins/' + this.get("name");
-    },
-
-    isNew: function () { return false; },
-
-    sync: function (method, model, options) {
-
-      var params = {
-        url: model.url(),
-        contentType: 'application/json',
-        dataType: 'json',
-        data: JSON.stringify(model.get('value'))
-      };
-
-      if (method === 'delete') {
-        params.type = 'DELETE';
-      } else {
-        params.type = 'PUT';
-      }
-
-      return $.ajax(params);
-    }
-  });
-
-  Auth.Session = FauxtonAPI.Session.extend({
-    url: '/_session',
-
-    initialize: function (options) {
-      if (!options) { options = {}; }
-
-      this.messages = _.extend({},  { 
-          missingCredentials: 'Username or password cannot be blank.',
-          passwordsNotMatch:  'Passwords do not match.',
-          incorrectCredentials: 'Incorrect username or password.',
-          loggedIn: 'You have been logged in.',
-          adminCreated: 'Couchdb admin created',
-          changePassword: 'Your password has been updated.'
-        }, options.messages);
-    },
-
-    isAdminParty: function () {
-      var userCtx = this.get('userCtx');
-
-      if (!userCtx.name && userCtx.roles.indexOf("_admin") > -1) {
-        return true;
-      }
-
-      return false;
-    },
-
-    isLoggedIn: function () {
-      var userCtx = this.get('userCtx');
-
-      if (userCtx.name) {
-        return true;
-      }
-
-      return false;
-    },
-
-    userRoles: function () {
-      var user = this.user();
-
-      if (user && user.roles) { 
-        return user.roles;
-      }
-
-      return [];
-    },
-
-    matchesRoles: function (roles) {
-      if (roles.length === 0) {
-        return true;
-      }
-
-      var numberMatchingRoles = _.intersection(this.userRoles(), roles).length;
-
-      if (numberMatchingRoles > 0) {
-        return true;
-      }
-
-      return false;
-    },
-
-    validateUser: function (username, password, msg) {
-      if (_.isEmpty(username) || _.isEmpty(password)) {
-        var deferred = FauxtonAPI.Deferred();
-
-        deferred.rejectWith(this, [msg]);
-        return deferred;
-      }
-    },
-
-    validatePasswords: function (password, password_confirm, msg) {
-      if (_.isEmpty(password) || _.isEmpty(password_confirm) || (password !== password_confirm)) {
-        var deferred = FauxtonAPI.Deferred();
-
-        deferred.rejectWith(this, [msg]);
-        return deferred;
-      }
-
-    },
-
-    createAdmin: function (username, password, login) {
-      var that = this,
-          error_promise =  this.validateUser(username, password, this.messages.missingCredentials);
-
-      if (error_promise) { return error_promise; }
-
-      var admin = new Admin({
-        name: username,
-        value: password
-      });
-
-      return admin.save().then(function () {
-        if (login) {
-          return that.login(username, password);
-        } else {
-         return that.fetchUser({forceFetch: true});
-        }
-      });
-    },
-
-    login: function (username, password) {
-      var error_promise =  this.validateUser(username, password, this.messages.missingCredentials);
-
-      if (error_promise) { return error_promise; }
-
-      var that = this;
-
-      return $.ajax({
-        cache: false,
-        type: "POST", 
-        url: "/_session", 
-        dataType: "json",
-        data: {name: username, password: password}
-      }).then(function () {
-         return that.fetchUser({forceFetch: true});
-      });
-    },
-
-    logout: function () {
-      var that = this;
-
-      return $.ajax({
-        type: "DELETE", 
-        url: "/_session", 
-        dataType: "json",
-        username : "_", 
-        password : "_"
-      }).then(function () {
-       return that.fetchUser({forceFetch: true });
-      });
-    },
-
-    changePassword: function (password, password_confirm) {
-      var error_promise =  this.validatePasswords(password, password_confirm, this.messages.passwordsNotMatch);
-
-      if (error_promise) { return error_promise; }
-
-      var  that = this,
-           info = this.get('info'),
-           userCtx = this.get('userCtx');
-
-       var admin = new Admin({
-        name: userCtx.name,
-        value: password
-      });
-
-      return admin.save().then(function () {
-        return that.login(userCtx.name, password);
-      });
-    }
-  });
-
-  Auth.CreateAdminView = FauxtonAPI.View.extend({
-    template: 'addons/auth/templates/create_admin',
-
-    initialize: function (options) {
-      options = options || {};
-      this.login_after = options.login_after === false ? false : true;
-    },
-
-    events: {
-      "submit #create-admin-form": "createAdmin"
-    },
-
-    createAdmin: function (event) {
-      event.preventDefault();
-
-      var that = this,
-          username = this.$('#username').val(),
-          password = this.$('#password').val();
-
-      var promise = this.model.createAdmin(username, password, this.login_after);
-
-      promise.then(function () {
-        FauxtonAPI.addNotification({
-          msg: FauxtonAPI.session.messages.adminCreated,
-        });
-
-        if (that.login_after) {
-          FauxtonAPI.navigate('/');
-        } else {
-          that.$('#username').val('');
-          that.$('#password').val('');
-        }
-      });
-
-      promise.fail(function (rsp) {
-        FauxtonAPI.addNotification({
-          msg: 'Could not create admin. Reason' + rsp + '.',
-          type: 'error'
-        });
-      });
-    }
-
-  });
-
-  Auth.LoginView = FauxtonAPI.View.extend({
-    template: 'addons/auth/templates/login',
-
-    events: {
-      "submit #login": "login"
-    },
-
-    login: function (event) {
-      event.preventDefault();
-
-      var that = this,
-          username = this.$('#username').val(),
-          password = this.$('#password').val(),
-          promise = this.model.login(username, password);
-
-      promise.then(function () {
-        FauxtonAPI.addNotification({msg:  FauxtonAPI.session.messages.loggedIn });
-        FauxtonAPI.navigate('/');
-      });
-
-      promise.fail(function (xhr, type, msg) {
-        if (arguments.length === 3) {
-          msg = FauxtonAPI.session.messages.incorrectCredentials;
-        } else {
-          msg = xhr;
-        }
-
-        FauxtonAPI.addNotification({
-          msg: msg,
-          type: 'error'
-        });
-      });
-    }
-
-  });
-
-  Auth.ChangePassword = FauxtonAPI.View.extend({
-    template: 'addons/auth/templates/change_password',
-
-    events: {
-      "submit #change-password": "changePassword"
-    },
-
-    changePassword: function () {
-      event.preventDefault();
-
-      var that = this,
-          new_password = this.$('#password').val(),
-          password_confirm = this.$('#password-confirm').val();
-
-      var promise = this.model.changePassword(new_password, password_confirm);
-
-      promise.done(function () {
-        FauxtonAPI.addNotification({msg: FauxtonAPI.session.messages.changePassword});
-        that.$('#password').val('');
-        that.$('#password-confirm').val('');
-      });
-
-      promise.fail(function (xhr, error, msg) {
-        if (arguments.length < 3) {
-          msg = xhr;
-        }
-
-        FauxtonAPI.addNotification({
-          msg: xhr,
-          type: 'error'
-        });
-      });
-    }
-  });
-
-  Auth.NavLink = FauxtonAPI.View.extend({ 
-    template: 'addons/auth/templates/nav_link_title',
-    tagName: 'li',
-
-    beforeRender: function () {
-      this.listenTo(this.model, 'change', this.render);
-    },
-
-    serialize: function () {
-      return {
-        admin_party: this.model.isAdminParty(),
-        user: this.model.user()
-      };
-    }
-  });
-
-  Auth.NavDropDown = FauxtonAPI.View.extend({ 
-    template: 'addons/auth/templates/nav_dropdown',
-
-    beforeRender: function () {
-      this.listenTo(this.model, 'change', this.render);
-    },
-
-    setTab: function (selectedTab) {
-      this.selectedTab = selectedTab;
-      this.$('.active').removeClass('active');
-      var $tab = this.$('a[data-select="' + selectedTab +'"]');
-      $tab.parent().addClass('active');
-    },
-
-    afterRender: function () {
-      if (this.selectedTab) {
-        this.setTab(this.selectedTab);
-      }
-    },
-
-    serialize: function () {
-      return {
-        admin_party: this.model.isAdminParty(),
-        user: this.model.user()
-      };
-    }
-  });
-
-  Auth.NoAccessView = FauxtonAPI.View.extend({
-    template: "addons/auth/templates/noAccess"
-  });
-
-  return Auth;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/auth/routes.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/auth/routes.js b/apps/fauxton/app/addons/auth/routes.js
deleted file mode 100644
index fe40a77..0000000
--- a/apps/fauxton/app/addons/auth/routes.js
+++ /dev/null
@@ -1,93 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-       "app",
-       "api",
-       "addons/auth/resources"
-],
-
-function(app, FauxtonAPI, Auth) {
-  var authRouteObject = FauxtonAPI.RouteObject.extend({
-    layout: 'one_pane',
-
-    routes: {
-      'login': 'login',
-      'logout': 'logout',
-      'createAdmin': 'createAdmin',
-      'noAccess': 'noAccess'
-    },
-
-    login: function () {
-      this.crumbs = [{name: 'Login', link:"#"}];
-      this.setView('#dashboard-content', new Auth.LoginView({model: FauxtonAPI.session}));
-    },
-
-    logout: function () {
-      FauxtonAPI.addNotification({msg: 'You have been logged out.'});
-      FauxtonAPI.session.logout().then(function () {
-        FauxtonAPI.navigate('/');
-      });
-    },
-
-    changePassword: function () {
-      this.crumbs = [{name: 'Change Password', link:"#"}];
-      this.setView('#dashboard-content', new Auth.ChangePassword({model: FauxtonAPI.session}));
-    },
-
-    createAdmin: function () {
-      this.crumbs = [{name: 'Create Admin', link:"#"}];
-      this.setView('#dashboard-content', new Auth.CreateAdminView({model: FauxtonAPI.session}));
-    },
-
-    noAccess: function () {
-      this.crumbs = [{name: 'Access Denied', link:"#"}];
-      this.setView('#dashboard-content', new Auth.NoAccessView());
-      this.apiUrl = 'noAccess';
-    },
-  });
-
-  var userRouteObject = FauxtonAPI.RouteObject.extend({
-    layout: 'with_sidebar',
-
-    routes: {
-      'changePassword': {
-        route: 'changePassword',
-        roles: ['_admin', '_reader', '_replicator']
-      },
-      'addAdmin': {
-        roles: ['_admin'],
-        route: 'addAdmin',
-      },
-    },
-    
-    initialize: function () {
-     this.navDrop = this.setView('#sidebar-content', new Auth.NavDropDown({model: FauxtonAPI.session}));
-    },
-
-    changePassword: function () {
-      this.navDrop.setTab('change-password');
-      this.setView('#dashboard-content', new Auth.ChangePassword({model: FauxtonAPI.session}));
-    },
-
-    addAdmin: function () {
-      this.navDrop.setTab('add-admin');
-      this.setView('#dashboard-content', new Auth.CreateAdminView({login_after: false, model: FauxtonAPI.session}));
-    },
-
-    crumbs: [{name: 'User Management', link: '#'}]
-  });
-
-  Auth.RouteObjects = [authRouteObject, userRouteObject];
-  
-  return Auth;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/auth/templates/change_password.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/auth/templates/change_password.html b/apps/fauxton/app/addons/auth/templates/change_password.html
deleted file mode 100644
index 64b7d1f..0000000
--- a/apps/fauxton/app/addons/auth/templates/change_password.html
+++ /dev/null
@@ -1,26 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<div class="span12">
-  <h2> Change Password </h2>
-  <form id="change-password">
-    <p class="help-block">
-    Enter your new password.
-    </p>
-    <input id="password" type="password" name="password" placeholder= "New Password:" size="24">
-    <br/>
-    <input id="password-confirm" type="password" name="password_confirm" placeholder= "Verify New Password" size="24">
-    <button type="submit" class="btn btn-primary">Change</button>
-  </form>
-</div>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/auth/templates/create_admin.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/auth/templates/create_admin.html b/apps/fauxton/app/addons/auth/templates/create_admin.html
deleted file mode 100644
index 4715be5..0000000
--- a/apps/fauxton/app/addons/auth/templates/create_admin.html
+++ /dev/null
@@ -1,37 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<div class="span12">
-  <h2> Add Admin </h2>
-  <form id="create-admin-form">
-    <input id="username" type="text" name="name" placeholder= "Username:" size="24">
-    <br/>
-    <input id="password" type="password" name="password" placeholder= "Password" size="24">
-    <p class="help-block">
-    Before a server admin is configured, all clients have admin privileges.
-    This is fine when HTTP access is restricted 
-    to trusted users. <strong>If end-users will be accessing this CouchDB, you must
-      create an admin account to prevent accidental (or malicious) data loss.</strong>
-    </p>
-    <p class="help-block">Server admins can create and destroy databases, install 
-    and update _design documents, run the test suite, and edit all aspects of CouchDB 
-    configuration.
-    </p>
-    <p class="help-block">Non-admin users have read and write access to all databases, which
-    are controlled by validation functions. CouchDB can be configured to block all
-    access to anonymous users.
-    </p>
-    <button type="submit" href="#" id="create-admin" class="btn btn-primary">Create Admin</button>
-  </form>
-</div>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/auth/templates/login.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/auth/templates/login.html b/apps/fauxton/app/addons/auth/templates/login.html
deleted file mode 100644
index a57f3f0..0000000
--- a/apps/fauxton/app/addons/auth/templates/login.html
+++ /dev/null
@@ -1,26 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-<div class="span12">
-  <form id="login">
-    <p class="help-block">
-      Login to CouchDB with your name and password.
-    </p>
-    <input id="username" type="text" name="name" placeholder= "Username:" size="24">
-    <br/>
-    <input id="password" type="password" name="password" placeholder= "Password" size="24">
-    <br/>
-    <button id="submit" class="btn" type="submit"> Login </button>
-  </form>
-</div>
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/auth/templates/nav_dropdown.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/auth/templates/nav_dropdown.html b/apps/fauxton/app/addons/auth/templates/nav_dropdown.html
deleted file mode 100644
index d61c24a..0000000
--- a/apps/fauxton/app/addons/auth/templates/nav_dropdown.html
+++ /dev/null
@@ -1,26 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<div id="sidenav">
-<header class="row-fluid">
-  <h3> <%= user.name %> </h3>
-</header>
-<nav>
-<ul class="nav nav-list">
-  <li class="active" ><a data-select="change-password" id="user-change-password" href="#changePassword"> Change Password </a></li>
-  <li ><a data-select="add-admin" href="#addAdmin"> Create Admins </a></li>
-</ul>
-</nav>
-</div>
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/auth/templates/nav_link_title.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/auth/templates/nav_link_title.html b/apps/fauxton/app/addons/auth/templates/nav_link_title.html
deleted file mode 100644
index b23157e..0000000
--- a/apps/fauxton/app/addons/auth/templates/nav_link_title.html
+++ /dev/null
@@ -1,31 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-<% if (admin_party) { %>
-  <a id="user-create-admin" href="#createAdmin"> 
-  	<span class="fonticon-user fonticon"></span>
-  	Admin Party! 
-  </a>
-<% } else if (user) { %>
-  <a  href="#changePassword" >
-  	<span class="fonticon-user fonticon"></span> 
-  	<%= user.name %> 
-	</a>
-<% } else { %>
-  <a  href="#login" >  
-  	<span class="fonticon-user fonticon"></span> 
-  	Login 
-  </a>
-<% } %>
-
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/auth/templates/noAccess.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/auth/templates/noAccess.html b/apps/fauxton/app/addons/auth/templates/noAccess.html
deleted file mode 100644
index ceff992..0000000
--- a/apps/fauxton/app/addons/auth/templates/noAccess.html
+++ /dev/null
@@ -1,20 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-
-<div class="span12">
-  <h2> Access Denied </h2>
-  <p> You do not have permission to view this page. <br/> You might need to <a href="#login"> login </a> to view this page/ </p>
-  
-</div>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/compaction/assets/less/compaction.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/compaction/assets/less/compaction.less b/apps/fauxton/app/addons/compaction/assets/less/compaction.less
deleted file mode 100644
index 70b034b..0000000
--- a/apps/fauxton/app/addons/compaction/assets/less/compaction.less
+++ /dev/null
@@ -1,19 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-.compaction-option {
-  background-color: #F7F7F7;
-  border: 1px solid #DDD;
-  margin-bottom: 30px;
-  padding: 10px;
-
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/compaction/base.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/compaction/base.js b/apps/fauxton/app/addons/compaction/base.js
deleted file mode 100644
index de0f124..0000000
--- a/apps/fauxton/app/addons/compaction/base.js
+++ /dev/null
@@ -1,31 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-  "app",
-  "api",
-  "addons/compaction/routes"
-],
-
-function(app, FauxtonAPI, Compaction) {
-  Compaction.initialize = function() {
-    FauxtonAPI.registerExtension('docLinks', {
-      title: "Compact & Clean", 
-      url: "compact", 
-      icon: "icon-cogs"
-    });
-
-    FauxtonAPI.registerExtension('advancedOptions:ViewButton', new Compaction.CompactView({}));
-  };
-
-  return Compaction;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/compaction/resources.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/compaction/resources.js b/apps/fauxton/app/addons/compaction/resources.js
deleted file mode 100644
index 6633677..0000000
--- a/apps/fauxton/app/addons/compaction/resources.js
+++ /dev/null
@@ -1,48 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-  "app",
-  "api"
-],
-
-function (app, FauxtonAPI) {
-  var Compaction = FauxtonAPI.addon();
-
-  Compaction.compactDB = function (db) {
-    return $.ajax({
-      url: db.url() + '/_compact',
-      contentType: 'application/json',
-      type: 'POST'
-    });
-  };
-
-  Compaction.cleanupViews = function (db) {
-    return $.ajax({
-      url: db.url() + '/_view_cleanup',
-      contentType: 'application/json',
-      type: 'POST'
-    });
-  };
-
-
-  Compaction.compactView = function (db, designDoc) {
-    // /some_database/_compact/designname
-    return $.ajax({
-      url: db.url() + '/_compact/' + designDoc.replace('_design/','') ,
-      contentType: 'application/json',
-      type: 'POST'
-    });
-  };
-
-  return Compaction;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/compaction/routes.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/compaction/routes.js b/apps/fauxton/app/addons/compaction/routes.js
deleted file mode 100644
index 2a33e07..0000000
--- a/apps/fauxton/app/addons/compaction/routes.js
+++ /dev/null
@@ -1,65 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-       "app",
-
-       "api",
-
-       // Modules
-       "addons/compaction/views",
-       "modules/databases/resources"
-],
-
-function(app, FauxtonAPI, Compaction, Databases) {
-
-  var  CompactionRouteObject = FauxtonAPI.RouteObject.extend({
-    layout: "one_pane",
-
-    crumbs: function () {
-      return [
-        {"name": this.database.id, "link": Databases.databaseUrl(this.database)},
-        {"name": "Compact & Clean", "link": "compact"}
-      ];
-    },
-
-    routes: {
-      "database/:database/compact": "compaction"
-    },
-
-    initialize: function(route, masterLayout, options) {
-      var databaseName = options[0];
-
-      this.database = this.database || new Databases.Model({id: databaseName});
-    },
-
-    compaction: function () {
-      this.setView('#dashboard-content', new Compaction.Layout({model: this.database}));
-    },
-
-    establish: function () {
-      return this.database.fetch();
-    }
-
-    /*apiUrl: function() {
-      return [this.compactions.url(), this.compactions.documentation];
-    },*/
-
-  });
-
-  Compaction.RouteObjects = [CompactionRouteObject];
-
-  return Compaction;
-
-});
-
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/compaction/templates/compact_view.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/compaction/templates/compact_view.html b/apps/fauxton/app/addons/compaction/templates/compact_view.html
deleted file mode 100644
index 8a0b7ec..0000000
--- a/apps/fauxton/app/addons/compaction/templates/compact_view.html
+++ /dev/null
@@ -1,14 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-Compact View

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/compaction/templates/layout.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/compaction/templates/layout.html b/apps/fauxton/app/addons/compaction/templates/layout.html
deleted file mode 100644
index 5125892..0000000
--- a/apps/fauxton/app/addons/compaction/templates/layout.html
+++ /dev/null
@@ -1,28 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-<div class="row">
-  <div class="span12 compaction-option">
-    <h3> Compact Database </h3>
-    <p>Compacting a database removes deleted documents and previous revisions. It is an irreversible operation and may take a while to complete for large databases.</p>
-    <button id="compact-db" class="btn btn-large btn-primary"> Run </button>
-  </div>
-</div>
-
-<div class="row">
-  <div class="span12 compaction-option">
-    <h3> Cleanup Views </h3>
-    <p>Cleaning up views in a database removes old view files still stored on the filesystem. It is an irreversible operation.</p>
-    <button id="cleanup-views" class="btn btn-large btn-primary"> Run </button>
-  </div>
-</div>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/compaction/views.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/compaction/views.js b/apps/fauxton/app/addons/compaction/views.js
deleted file mode 100644
index 06a1300..0000000
--- a/apps/fauxton/app/addons/compaction/views.js
+++ /dev/null
@@ -1,140 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-       "app",
-
-       "api",
-       // Modules
-       "addons/compaction/resources"
-],
-function (app, FauxtonAPI, Compaction) {
-
-  Compaction.Layout = FauxtonAPI.View.extend({
-    template: 'addons/compaction/templates/layout',
-
-    initialize: function () {
-      _.bindAll(this);
-    },
-
-    events: {
-      "click #compact-db": "compactDB",
-      "click #compact-view": "compactDB",
-      "click #cleanup-views": "cleanupViews"
-    },
-
-    disableButton: function (selector, text) {
-      this.$(selector).attr('disabled', 'disabled').text(text);
-    },
-
-    enableButton: function (selector, text) {
-      this.$(selector).removeAttr('disabled').text(text);
-    },
-
-    compactDB: function (event) {
-      var enableButton = this.enableButton;
-      event.preventDefault();
-
-      this.disableButton('#compact-db', 'Compacting...');
-
-      Compaction.compactDB(this.model).then(function () {
-        FauxtonAPI.addNotification({
-          type: 'success',
-          msg: 'Database compaction has started. Visit <a href="#activetasks">Active Tasks</a> to view the compaction progress.',
-        });
-      }, function (xhr, error, reason) {
-        console.log(arguments);
-        FauxtonAPI.addNotification({
-          type: 'error',
-          msg: 'Error: ' + JSON.parse(xhr.responseText).reason
-        });
-      }).always(function () {
-        enableButton('#compact-db', 'Run');
-      });
-    },
-
-    cleanupViews: function (event) {
-      var enableButton = this.enableButton;
-      event.preventDefault();
-
-      this.disableButton('#cleanup-view', 'Cleaning...');
-
-      Compaction.cleanupViews(this.model).then(function () {
-        FauxtonAPI.addNotification({
-          type: 'success',
-          msg: 'View cleanup has started. Visit <a href="#activetasks">Active Tasks</a> to view progress.'
-        });
-      }, function (xhr, error, reason) {
-        FauxtonAPI.addNotification({
-          type: 'error',
-          msg: 'Error: ' + JSON.parse(xhr.responseText).reason
-        });
-      }).always(function () {
-        enableButton('#cleanup-views', 'Run');
-      });
-    }
-  });
-
-  Compaction.CompactView = FauxtonAPI.View.extend({
-    template: 'addons/compaction/templates/compact_view',
-    className: 'btn btn-info btn-large pull-right',
-    tagName: 'button',
-
-    initialize: function () {
-      _.bindAll(this);
-    },
-
-    events: {
-      "click": "compact"
-    },
-
-    disableButton: function () {
-      this.$el.attr('disabled', 'disabled').text('Compacting...');
-    },
-
-    enableButton: function () {
-      this.$el.removeAttr('disabled').text('Compact View');
-    },
-
-
-    update: function (database, designDoc, viewName) {
-      this.database = database;
-      this.designDoc = designDoc;
-      this.viewName = viewName;
-    },
-
-    compact: function (event) {
-      event.preventDefault();
-      var enableButton = this.enableButton;
-
-      this.disableButton();
-
-      Compaction.compactView(this.database, this.designDoc).then(function () {
-        FauxtonAPI.addNotification({
-          type: 'success',
-          msg: 'View compaction has started. Visit <a href="#activetasks">Active Tasks</a> to view progress.'
-        });
-      }, function (xhr, error, reason) {
-        FauxtonAPI.addNotification({
-          type: 'error',
-          msg: 'Error: ' + JSON.parse(xhr.responseText).reason
-        });
-      }).always(function () {
-        enableButton();
-      });
-
-    }
-
-  });
-
-  return Compaction;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/config/assets/less/config.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/config/assets/less/config.less b/apps/fauxton/app/addons/config/assets/less/config.less
deleted file mode 100644
index 86d9bf1..0000000
--- a/apps/fauxton/app/addons/config/assets/less/config.less
+++ /dev/null
@@ -1,13 +0,0 @@
-table.config {
-  #config-trash {
-    width: 5%;
-  }
-  
-  #delete-value {
-    text-align: center;
-  } 
-}
-
-button#add-section {
-  float: right;
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/config/base.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/config/base.js b/apps/fauxton/app/addons/config/base.js
deleted file mode 100644
index 8362cb5..0000000
--- a/apps/fauxton/app/addons/config/base.js
+++ /dev/null
@@ -1,28 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-  "app",
-
-  "api",
-
-  // Modules
-  "addons/config/routes"
-],
-
-function(app, FauxtonAPI, Config) {
-  Config.initialize = function() {
-    FauxtonAPI.addHeaderLink({title: "Config", href: "#_config", icon:"fonticon-cog", className: 'config'});
-  };
-
-  return Config;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/config/resources.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/config/resources.js b/apps/fauxton/app/addons/config/resources.js
deleted file mode 100644
index 14d2474..0000000
--- a/apps/fauxton/app/addons/config/resources.js
+++ /dev/null
@@ -1,176 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-  "app",
-  "api"
-],
-
-function (app, FauxtonAPI) {
-
-  var Config = FauxtonAPI.addon();
-
-  Config.Model = Backbone.Model.extend({});
-  Config.OptionModel = Backbone.Model.extend({
-    documentation: "config",
-    
-    url: function () {
-      return app.host + '/_config/' + this.get("section") + '/' + this.get("name");
-    },
-
-    isNew: function () { return false; },
-
-    sync: function (method, model, options) {
-
-      var params = {
-        url: model.url(),
-        contentType: 'application/json',
-        dataType: 'json',
-        data: JSON.stringify(model.get('value'))
-      };
-
-      if (method === 'delete') {
-        params.type = 'DELETE';
-      } else {
-        params.type = 'PUT';
-      }
-
-      return $.ajax(params);
-    }
-  });
-
-  Config.Collection = Backbone.Collection.extend({
-    model: Config.Model,
-    documentation: "config",
-    url: function () {
-      return app.host + '/_config';
-    },
-
-    parse: function (resp) {
-      return _.map(resp, function (section, section_name) {
-        return {
-          section: section_name,
-          options: _.map(section, function (option, option_name) {
-            return {
-              name: option_name,
-              value: option
-            };
-          })
-        };
-      });
-    }
-  });
-
-  Config.ViewItem = FauxtonAPI.View.extend({
-    tagName: "tr",
-    className: "config-item",
-    template: "addons/config/templates/item",
-
-    events: {
-      "click .edit-button": "editValue",
-      "click #delete-value": "deleteValue",
-      "click #cancel-value": "cancelEdit",
-      "click #save-value": "saveValue"
-    },
-
-    deleteValue: function (event) {
-      var result = confirm("Are you sure you want to delete this configuration value?");
-
-      if (!result) { return; }
-
-      this.model.destroy();
-      this.remove();
-    },
-
-    editValue: function (event) {
-      this.$("#show-value").hide();
-      this.$("#edit-value-form").show();
-    },
-
-    saveValue: function (event) {
-      this.model.save({value: this.$(".value-input").val()});
-      this.render();
-    },
-
-    cancelEdit: function (event) {
-      this.$("#edit-value-form").hide();
-      this.$("#show-value").show();
-    },
-
-    serialize: function () {
-      return {option: this.model.toJSON()};
-    }
-
-  });
-
-  Config.View = FauxtonAPI.View.extend({
-    template: "addons/config/templates/dashboard",
-
-    events: {
-      "click #add-section": "addSection",
-      "submit #add-section-form": "submitForm"
-    },
-
-    submitForm: function (event) {
-      event.preventDefault();
-      var option = new Config.OptionModel({
-        section: this.$('input[name="section"]').val(),
-        name: this.$('input[name="name"]').val(),
-        value: this.$('input[name="value"]').val()
-      });
-
-      option.save();
-
-      var section = this.collection.find(function (section) {
-        return section.get("section") === option.get("section");
-      });
-
-      if (section) {
-        section.get("options").push(option.attributes);
-      } else {
-        this.collection.add({
-          section: option.get("section"),
-          options: [option.attributes]
-        });
-      }
-
-      this.$("#add-section-modal").modal('hide');
-      this.render();
-    },
-
-    addSection: function (event) {
-      event.preventDefault();
-      this.$("#add-section-modal").modal({show:true});
-    },
-
-    beforeRender: function() {
-      this.collection.each(function(config) {
-        _.each(config.get("options"), function (option, index) {
-          this.insertView("table.config tbody", new Config.ViewItem({
-            model: new Config.OptionModel({
-              section: config.get("section"),
-              name: option.name,
-              value: option.value,
-              index: index
-            })
-          }));
-        }, this);
-      }, this);
-    },
-
-    establish: function() {
-      return [this.collection.fetch()];
-    }
-  });
-
-  return Config;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/config/routes.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/config/routes.js b/apps/fauxton/app/addons/config/routes.js
deleted file mode 100644
index 6af8157..0000000
--- a/apps/fauxton/app/addons/config/routes.js
+++ /dev/null
@@ -1,59 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-       "app",
-
-       "api",
-
-       // Modules
-       "addons/config/resources"
-],
-
-function(app, FauxtonAPI, Config) {
-
-  var ConfigRouteObject = FauxtonAPI.RouteObject.extend({
-    layout: "one_pane",
-
-    initialize: function () {
-      this.configs = new Config.Collection();
-    },
-
-    roles: ["_admin"],
-
-    selectedHeader: "Config",
-
-    crumbs: [
-      {"name": "Config","link": "_config"}
-    ],
-
-    apiUrl: function () {
-      return [this.configs.url(), this.configs.documentation];
-    },
-
-    routes: {
-      "_config": "config"
-    },
-
-    config: function () {
-      this.setView("#dashboard-content", new Config.View({collection: this.configs}));
-    },
-
-    establish: function () {
-      return [this.configs.fetch()];
-    }
-  });
-
-
-  Config.RouteObjects = [ConfigRouteObject];
-  return Config;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/config/templates/dashboard.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/config/templates/dashboard.html b/apps/fauxton/app/addons/config/templates/dashboard.html
deleted file mode 100644
index ffbeb37..0000000
--- a/apps/fauxton/app/addons/config/templates/dashboard.html
+++ /dev/null
@@ -1,52 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<div class="row">
-  <div class="span2 offset10">
-    <button id="add-section" href="#" class="button button-margin">
-      <i class="icon-plus icon-white"> </i>
-      Add Section
-    </button>
-  </div>
-</div>
-<table class="config table table-striped table-bordered">
-  <thead>
-    <th id="config-section"> Section </th>
-    <th id="config-option"> Option </th>
-    <th id="config-value"> Value </th>
-    <th id="config-trash"></th>
-  </thead>
-  <tbody>
-  </tbody>
-</table>
-<div id="add-section-modal" class="modal hide fade">
-  <div class="modal-header">
-    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
-    <h3>Create Config Option</h3>
-  </div>
-  <div class="modal-body">
-    <form id="add-section-form" class="form well">
-      <label>Section</label>
-      <input type="text" name="section" placeholder="Section">
-      <span class="help-block">Enter an existing section name to add to it.</span>
-      <input type="text" name="name" placeholder="Name">
-      <br/>
-      <input type="text" name="value" placeholder="Value">
-      <div class="modal-footer">
-        <button type="button" class="btn" data-dismiss="modal">Cancel</button>
-        <button type="submit" class="btn btn-primary"> Save </button>
-      </div>
-    </form>
-  </div>
-</div>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/config/templates/item.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/config/templates/item.html b/apps/fauxton/app/addons/config/templates/item.html
deleted file mode 100644
index 3e6e4ee..0000000
--- a/apps/fauxton/app/addons/config/templates/item.html
+++ /dev/null
@@ -1,31 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<% if (option.index === 0) {%>
-<th> <%= option.section %> </th>
-<% } else { %>
-<td></td>
-<% } %>
-<td> <%= option.name %> </td>
-<td>
-  <div id="show-value">
-    <%= option.value %> <button class="edit-button"> Edit </button>
-  </div>
-  <div id="edit-value-form" style="display:none">
-    <input class="value-input" type="text" value="<%= option.value %>" />
-    <button id="save-value" class="btn btn-success btn-small"> Save </button>
-    <button id="cancel-value" class="btn btn-danger btn-small"> Cancel </button>
-  </div>
-</td>
-<td id="delete-value"> <i class="icon-trash"> </i> </td>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/contribute/base.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/contribute/base.js b/apps/fauxton/app/addons/contribute/base.js
deleted file mode 100644
index 8f622fe..0000000
--- a/apps/fauxton/app/addons/contribute/base.js
+++ /dev/null
@@ -1,33 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-  // Libraries.
-  "jquery",
-  "lodash"
-],
-function($, _){
-  $.contribute = function(message, file){
-    /*
-    var JST = window.JST = window.JST || {};
-    var template = JST['app/addons/contribute/templates/modal.html'];
-    console.log(template);
-    var compiled = template({message: message, file: file});
-    */
-    console.log('contribute!contribute!monorail!contribute!');
-    /*
-    console.log(compiled);
-    var elem = $(compiled);
-    elem.modal('show');
-    */
-  };
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/exampleAuth/base.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/exampleAuth/base.js b/apps/fauxton/app/addons/exampleAuth/base.js
deleted file mode 100644
index aa99670..0000000
--- a/apps/fauxton/app/addons/exampleAuth/base.js
+++ /dev/null
@@ -1,59 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-  "app",
-
-  "api"
-],
-
-function(app, FauxtonAPI) {
-  // This is an example module of using the new auth module.
-
-  var noAccessView = FauxtonAPI.View.extend({
-    template: "addons/exampleAuth/templates/noAccess"
-
-  });
-
-  // To utilise the authentication - all that is required, is one callback
-  // that is registered with the auth api. This function can return an array
-  // of deferred objects.
-  // The roles argument that is passed in is the required roles for the current user
-  // to be allowed to access the current page.
-  // The layout is the main layout for use when you want to render a view onto the page
-  var auth = function (roles) {
-    var deferred = $.Deferred();
-
-    if (roles.indexOf('_admin') > -1) {
-      deferred.reject();
-    } else {
-      deferred.resolve();
-    }
-
-    return [deferred];
-  };
-
-  // If you would like to do something with when access is denied you can register this callback.
-  // It will be called is access has been denied on the previous page.
-  var authFail = function () {
-    app.masterLayout.setView('#dashboard', new noAccessView());
-    app.masterLayout.renderView('#dashboard');
-  };
-
-  // Register the auth call back. This will be called before new route rendered
-  FauxtonAPI.auth.registerAuth(auth);
-  // Register a failed route request callback. This is called if access is denied.
-  FauxtonAPI.auth.registerAuthDenied(authFail);
-
-
-
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/exampleAuth/templates/noAccess.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/exampleAuth/templates/noAccess.html b/apps/fauxton/app/addons/exampleAuth/templates/noAccess.html
deleted file mode 100644
index f1a9506..0000000
--- a/apps/fauxton/app/addons/exampleAuth/templates/noAccess.html
+++ /dev/null
@@ -1,19 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<div class="row-fluid" >
-  <div class="span6 offset4">
-  <h3> You do not have permission to view this page </h3>
-</div>
-</div>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/logs/base.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/logs/base.js b/apps/fauxton/app/addons/logs/base.js
deleted file mode 100644
index 1aecbdf..0000000
--- a/apps/fauxton/app/addons/logs/base.js
+++ /dev/null
@@ -1,28 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-  "app",
-
-  "api",
-
-  // Modules
-  "addons/logs/routes"
-],
-
-function(app, FauxtonAPI, Log) {
-  Log.initialize = function() {
-    FauxtonAPI.addHeaderLink({title: "Log", href: "#_log", icon: "fonticon-log", className: 'logs'});
-  };
-
-  return Log;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/logs/resources.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/logs/resources.js b/apps/fauxton/app/addons/logs/resources.js
deleted file mode 100644
index 3a47b92..0000000
--- a/apps/fauxton/app/addons/logs/resources.js
+++ /dev/null
@@ -1,225 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-  "app",
-  "api",
-  "backbone"
-],
-
-function (app, FauxtonAPI, Backbone) {
-
-  var Log = FauxtonAPI.addon();
-
-  Log.Model = Backbone.Model.extend({
-
-    date: function () {
-      var date = new Date(this.get('date'));
-
-      var formatted_time = date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
-      var formatted_date = date.toDateString().slice(4, 10);
-
-      return formatted_date + ' ' + formatted_time;
-    },
-
-    logLevel: function () {
-      return this.get('log_level').replace(/ /g,'');
-    },
-
-    pid: function () {
-      return _.escape(this.get('pid'));
-    },
-
-    args: function () {
-      return _.escape(this.get('args'));
-    }
-
-  });
-
-  Log.Collection = Backbone.Collection.extend({
-    model: Log.Model,
-
-    initialize: function (options) {
-      this.params = {bytes: 5000};
-    },
-    
-    documentation: "log",
-
-    url: function () {
-      query = "?" + $.param(this.params);
-      return app.host + '/_log' + query;
-    },
-
-    // override fetch because backbone expects json and couchdb sends text/html for logs,
-    // I think its more elegant to set the dataType here than where ever fetch is called
-    fetch: function (options) {
-      options = options ? options : {};
-
-      return Backbone.Collection.prototype.fetch.call(this, _.extend(options, {dataType: "html"}));
-    },
-
-    parse: function (resp) {
-      var lines =  resp.split(/\n/);
-      return _.foldr(lines, function (acc, logLine) {
-        var match = logLine.match(/^\[(.*?)\]\s\[(.*?)\]\s\[(.*?)\]\s(.*)/);
-
-        if (!match) { return acc;}
-
-        acc.push({
-                  date: match[1],
-                  log_level: match[2],
-                  pid: match[3],
-                  args: match[4]
-                 });
-
-        return acc;
-      }, []);
-    }
-  });
-
-  Log.events = {};
-  _.extend(Log.events, Backbone.Events);
-
-  Log.Views.View = FauxtonAPI.View.extend({
-    template: "addons/logs/templates/dashboard",
-
-    initialize: function (options) {
-      this.refreshTime = options.refreshTime || 5000;
-
-      Log.events.on("log:filter", this.filterLogs, this);
-      Log.events.on("log:remove", this.removeFilterLogs, this);
-
-      this.filters = [];
-
-      this.collection.on("add", function () {
-        this.render();
-      }, this);
-    },
-
-    establish: function () {
-      return [this.collection.fetch()];
-    },
-
-    serialize: function () {
-      return { logs: new Log.Collection(this.createFilteredCollection())};
-    },
-
-    afterRender: function () {
-      this.startRefreshInterval();
-    },
-
-    cleanup: function () {
-      this.stopRefreshInterval();
-    },
-
-    filterLogs: function (filter) {
-      this.filters.push(filter);
-      this.render();
-    },
-
-    createFilteredCollection: function () {
-      var that = this;
-
-      return _.reduce(this.filters, function (logs, filter) {
-
-        return _.filter(logs, function (log) {
-          var match = false;
-
-          _.each(log, function (value) {
-            if (value.toString().match(new RegExp(filter))) {
-              match = true;
-            }
-          });
-          return match;
-        });
-
-
-      }, this.collection.toJSON(), this);
-
-    },
-
-    removeFilterLogs: function (filter) {
-      this.filters.splice(this.filters.indexOf(filter), 1);
-      this.render();
-    },
-
-    startRefreshInterval: function () {
-      var collection = this.collection;
-
-      // Interval already set
-      if (this.intervalId) { return ; }
-
-      this.intervalId = setInterval(function () {
-        collection.fetch();
-      }, this.refreshTime);
-
-    },
-
-    stopRefreshInterval: function () {
-      clearInterval(this.intervalId);
-    }
-  });
-
-  Log.Views.FilterView = FauxtonAPI.View.extend({
-    template: "addons/logs/templates/sidebar",
-
-    events: {
-      "submit #log-filter-form": "filterLogs"
-    },
-
-    filterLogs: function (event) {
-      event.preventDefault();
-      var $filter = this.$('input[name="filter"]'),
-          filter = $filter.val();
-
-      Log.events.trigger("log:filter", filter);
-
-      this.insertView("#filter-list", new Log.Views.FilterItemView({
-        filter: filter
-      })).render();
-
-      $filter.val('');
-    }
-
-  });
-
-  Log.Views.FilterItemView = FauxtonAPI.View.extend({
-    template: "addons/logs/templates/filterItem",
-    tagName: "li",
-
-    initialize: function (options) {
-      this.filter = options.filter;
-    },
-
-    events: {
-      "click .remove-filter": "removeFilter"
-    },
-
-    serialize: function () {
-      return {
-        filter: this.filter
-      };
-    },
-
-    removeFilter: function (event) {
-      event.preventDefault();
-
-      Log.events.trigger("log:remove", this.filter);
-      this.remove();
-    }
-
-  });
-
-
-  return Log;
-
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/logs/routes.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/logs/routes.js b/apps/fauxton/app/addons/logs/routes.js
deleted file mode 100644
index 5c937af..0000000
--- a/apps/fauxton/app/addons/logs/routes.js
+++ /dev/null
@@ -1,58 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-       "app",
-
-       "api",
-
-       // Modules
-       "addons/logs/resources"
-],
-
-function(app, FauxtonAPI, Log) {
-
-  var  LogRouteObject = FauxtonAPI.RouteObject.extend({
-    layout: "with_sidebar",
-
-    crumbs: [
-      {"name": "Logs", "link": "_log"}
-    ],
-
-    routes: {
-      "_log": "showLog"
-    },
-
-    selectedHeader: "Log",
-
-    roles: ["_admin"],
-
-    apiUrl: function() {
-      return [this.logs.url(), this.logs.documentation];
-    },
-
-    initialize: function () {
-      this.logs = new Log.Collection();
-      this.setView("#sidebar-content", new Log.Views.FilterView({}));
-    },
-
-    showLog: function () {
-      this.setView("#dashboard-content", new Log.Views.View({collection: this.logs}));
-    }
-  });
-
-  Log.RouteObjects = [LogRouteObject];
-
-  return Log;
-
-});
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/logs/templates/dashboard.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/logs/templates/dashboard.html b/apps/fauxton/app/addons/logs/templates/dashboard.html
deleted file mode 100644
index 199794c..0000000
--- a/apps/fauxton/app/addons/logs/templates/dashboard.html
+++ /dev/null
@@ -1,46 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
- <h2> CouchDB Logs </h2>
-  <table class="table table-bordered" >
-  <thead>
-    <tr>
-      <th class="Date">Date</th>
-      <th class="Log Level">Log Value</th>
-      <th class="Pid">Pid</th>
-      <th class="Args">Url</th>
-    </tr>
-  </thead>
-
-  <tbody>
-    <% logs.each(function (log) { %>
-    <tr class="<%= log.logLevel() %>">
-      <td>
-        <!-- TODO: better format the date -->
-        <%= log.date() %>
-      </td>
-      <td>
-        <%= log.logLevel() %>
-      </td>
-      <td>
-        <%= log.pid() %>
-      </td>
-      <td>
-        <!-- TODO: split the line, maybe put method in it's own column -->
-        <%= log.args() %>
-      </td>
-    </tr>
-    <% }); %>
-  </tbody>
-</table>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/logs/templates/filterItem.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/logs/templates/filterItem.html b/apps/fauxton/app/addons/logs/templates/filterItem.html
deleted file mode 100644
index c4e885a..0000000
--- a/apps/fauxton/app/addons/logs/templates/filterItem.html
+++ /dev/null
@@ -1,16 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<span class="label label-info"> <%= filter %>  </span>
-<a class="label label-info remove-filter" href="#">&times;</a>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/logs/templates/sidebar.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/logs/templates/sidebar.html b/apps/fauxton/app/addons/logs/templates/sidebar.html
deleted file mode 100644
index 59b10ac..0000000
--- a/apps/fauxton/app/addons/logs/templates/sidebar.html
+++ /dev/null
@@ -1,27 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<div id="log-sidebar">
-  <header>Log Filter</header>
-  <form class="form-inline" id="log-filter-form">
-    <fieldset>
-      <input type="text" name="filter" placeholder="Type a filter to sort the logs by">
-      <!-- TODO: filter by method -->
-      <!-- TODO: correct removed filter behaviour -->
-      <button type="submit" class="btn">Filter</button>
-      <span class="help-block"> <h6> Eg. debug or <1.4.1> or any regex </h6> </span>
-    </fieldset>
-  </form>
-  <ul id="filter-list"></ul>
-</div>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/logs/tests/logSpec.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/logs/tests/logSpec.js b/apps/fauxton/app/addons/logs/tests/logSpec.js
deleted file mode 100644
index 621cc9b..0000000
--- a/apps/fauxton/app/addons/logs/tests/logSpec.js
+++ /dev/null
@@ -1,38 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-define([
-       'addons/logs/base',
-       'chai'
-], function (Log, chai) {
-  var expect = chai.expect;
-
-  describe('Logs Addon', function(){
-
-    describe('Log Model', function () {
-      var log;
-
-      beforeEach(function () {
-        log = new Log.Model({
-          log_level: 'DEBUG',
-          pid: '1234',
-          args: 'testing 123',
-          date: (new Date()).toString()
-        });
-      });
-
-      it('should have a log level', function () {
-        expect(log.logLevel()).to.equal('DEBUG');
-      });
-
-    });
-  });
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/permissions/assets/less/permissions.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/permissions/assets/less/permissions.less b/apps/fauxton/app/addons/permissions/assets/less/permissions.less
deleted file mode 100644
index 7ce4d10..0000000
--- a/apps/fauxton/app/addons/permissions/assets/less/permissions.less
+++ /dev/null
@@ -1,44 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-.border-hdr {
-  border-bottom: 1px solid #E3E3E3;
-  margin-bottom: 10px;
-  .help{
-
-  }
-  h3{
-    text-transform: capitalize;
-    margin-bottom: 0;
-  }
-}
-
-
-.permission-items.unstyled{
-	margin-left: 0px;
-	li {
-		padding: 5px;
-		border-bottom: 1px solid #E3E3E3;
-		border-right: 1px solid #E3E3E3;
-		border-left: 3px solid #E3E3E3;
-		&:first-child{
-			border-top: 1px solid #E3E3E3;
-		}
-		&:nth-child(odd){
-      border-left: 3px solid red;
-    }
-    button {
-    	float: right;
-    	margin-bottom: 6px;
-    }
-  }
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/permissions/base.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/permissions/base.js b/apps/fauxton/app/addons/permissions/base.js
deleted file mode 100644
index 016ba1c..0000000
--- a/apps/fauxton/app/addons/permissions/base.js
+++ /dev/null
@@ -1,25 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-       "app",
-       "api",
-       "addons/permissions/routes"
-],
-
-function(app, FauxtonAPI, Permissions) {
-
-  Permissions.initialize = function() {};
-
-  return Permissions;
-});
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/permissions/resources.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/permissions/resources.js b/apps/fauxton/app/addons/permissions/resources.js
deleted file mode 100644
index 66eaffd..0000000
--- a/apps/fauxton/app/addons/permissions/resources.js
+++ /dev/null
@@ -1,70 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-       "app",
-       "api"
-],
-function (app, FauxtonAPI ) {
-  var Permissions = FauxtonAPI.addon();
-
-  Permissions.Security = Backbone.Model.extend({
-    defaults: {
-      admins: {
-        names: [],
-        roles: []
-      },
-
-      members: {
-        names: [],
-        roles: []
-      }
-    },
-
-    isNew: function () {
-      return false;
-    },
-
-    initialize: function (attrs, options) {
-      this.database = options.database;
-    },
-
-    url: function () {
-      return this.database.id + '/_security';
-    },
-
-    addItem: function (value, type, section) {
-      var sectionValues = this.get(section);
-
-      if (!sectionValues || !sectionValues[type]) { 
-        return {
-          error: true,
-          msg: 'Section ' + section + 'does not exist'
-        };
-      }
-
-      if (sectionValues[type].indexOf(value) > -1) { 
-        return {
-          error: true,
-          msg: 'Role/Name has already been added'
-        }; 
-      }
-
-      sectionValues[type].push(value);
-      return this.set(section, sectionValues);
-    }
-
-  });
-
-  return Permissions;
-});
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/permissions/routes.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/permissions/routes.js b/apps/fauxton/app/addons/permissions/routes.js
deleted file mode 100644
index 89c2bd7..0000000
--- a/apps/fauxton/app/addons/permissions/routes.js
+++ /dev/null
@@ -1,63 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-       "app",
-       "api",
-       "modules/databases/base",
-       "addons/permissions/views"
-],
-function (app, FauxtonAPI, Databases, Permissions) {
-  
-  var PermissionsRouteObject = FauxtonAPI.RouteObject.extend({
-    layout: 'one_pane',
-    selectedHeader: 'Databases',
-
-    routes: {
-      'database/:database/permissions': 'permissions'
-    },
-
-    initialize: function (route, masterLayout, options) {
-      var docOptions = app.getParams();
-      docOptions.include_docs = true;
-
-      this.databaseName = options[0];
-      this.database = new Databases.Model({id:this.databaseName});
-      this.security = new Permissions.Security(null, {
-        database: this.database
-      });
-    },
-
-    establish: function () {
-      return [this.database.fetch(), this.security.fetch()];
-    },
-
-    permissions: function () {
-      this.setView('#dashboard-content', new Permissions.Permissions({
-        database: this.database,
-        model: this.security
-      }));
-
-    },
-
-    crumbs: function () {
-      return [
-        {"name": this.database.id, "link": Databases.databaseUrl(this.database)},
-        {"name": "Permissions", "link": "/permissions"}
-      ];
-    },
-
-  });
-  
-  Permissions.RouteObjects = [PermissionsRouteObject];
-  return Permissions;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/permissions/templates/item.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/permissions/templates/item.html b/apps/fauxton/app/addons/permissions/templates/item.html
deleted file mode 100644
index 616ffd6..0000000
--- a/apps/fauxton/app/addons/permissions/templates/item.html
+++ /dev/null
@@ -1,17 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<span> <%= item %> </span>
-<button type="button" class="close">&times;</button>
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/permissions/templates/permissions.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/permissions/templates/permissions.html b/apps/fauxton/app/addons/permissions/templates/permissions.html
deleted file mode 100644
index 99c9ff5..0000000
--- a/apps/fauxton/app/addons/permissions/templates/permissions.html
+++ /dev/null
@@ -1,15 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<div id="sections"> </div>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/permissions/templates/section.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/permissions/templates/section.html b/apps/fauxton/app/addons/permissions/templates/section.html
deleted file mode 100644
index 3360308..0000000
--- a/apps/fauxton/app/addons/permissions/templates/section.html
+++ /dev/null
@@ -1,46 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-<header class="border-hdr">
-<h3> <%= (section) %> </h3>
-<p id="help"> <%= help %> <a href="<%=getDocUrl('database_permission')%>" target="_blank"><i class="icon-question-sign"> </i> </a></p>
-</header>
-
-<div class="row">
-  <div class="span6">
-    <header>
-      <h4> Users </h4>
-      <p>Specify users who will have <%= section %> access to this database.</p>
-    </header>
-    <form class="permission-item-form form-inline">
-      <input data-section="<%= section %>" data-type="names" type="text" class="item input-small" placeholder="Add Name">
-      <button type="submit" class="button btn green fonticon-circle-plus">Add Name</button>
-    </form>
-    <ul class="clearfix unstyled permission-items span10" id="<%= (section) %>-items-names">
-    </ul>
-  </div>
-  <div class="span6">
-    <header>
-      <h4> Roles </h4>
-      <p>All users under the following role(s) will have <%= section %> access.</p>
-    </header>
-
-
-    <form class="permission-item-form form-inline">
-      <input data-section="<%= section %>" data-type="roles" type="text" class="item input-small" placeholder="Add Role">
-      <button type="submit" class="button btn green fonticon-circle-plus">Add Role</button>
-    </form>
-    <ul class="unstyled permission-items span10" id="<%= (section) %>-items-roles">
-    </ul>
-  </div>
-</div>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/permissions/tests/resourceSpec.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/permissions/tests/resourceSpec.js b/apps/fauxton/app/addons/permissions/tests/resourceSpec.js
deleted file mode 100644
index f73687a..0000000
--- a/apps/fauxton/app/addons/permissions/tests/resourceSpec.js
+++ /dev/null
@@ -1,51 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-define([
-       'api',
-       'addons/permissions/resources',
-      'testUtils'
-], function (FauxtonAPI, Models, testUtils) {
-  var assert = testUtils.assert;
-
-  describe('Permissions', function () {
-
-    describe('#addItem', function () {
-      var security;
-      
-      beforeEach(function () {
-        security = new Models.Security(null, {database: 'fakedb'});
-      });
-
-      it('Should add value to section', function () {
-
-        security.addItem('_user', 'names', 'admins');
-        assert.equal(security.get('admins').names[0], '_user');
-      });
-
-      it('Should handle incorrect type', function () {
-        security.addItem('_user', 'asdasd', 'admins');
-      });
-
-      it('Should handle incorrect section', function () {
-        security.addItem('_user', 'names', 'Asdasd');
-      });
-
-      it('Should reject duplicates', function () {
-        security.addItem('_user', 'names', 'admins');
-        security.addItem('_user', 'names', 'admins');
-        assert.equal(security.get('admins').names.length, 1);
-      });
-    });
-
-  });
-
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/permissions/tests/viewsSpec.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/permissions/tests/viewsSpec.js b/apps/fauxton/app/addons/permissions/tests/viewsSpec.js
deleted file mode 100644
index e5330c0..0000000
--- a/apps/fauxton/app/addons/permissions/tests/viewsSpec.js
+++ /dev/null
@@ -1,159 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-define([
-       'api',
-       'addons/permissions/views',
-       'addons/permissions/resources',
-       'testUtils'
-], function (FauxtonAPI, Views, Models, testUtils) {
-  var assert = testUtils.assert,
-  ViewSandbox = testUtils.ViewSandbox;
-
-  describe('Permission View', function () {
-
-    beforeEach(function () {
-      security = new Models.Security({'admins': {
-        'names': ['_user'],
-        'roles': []
-      }
-      }, {database: 'fakedb'});
-
-      section = new Views.Permissions({
-        database: 'fakedb',
-        model: security
-      });
-
-      viewSandbox = new ViewSandbox();
-      viewSandbox.renderView(section); 
-    });
-
-    afterEach(function () {
-      viewSandbox.remove();
-    });
-
-    describe('itemRemoved', function () {
-
-      it('Should set model', function () {
-        var saveMock = sinon.spy(security, 'set');
-        Views.events.trigger('itemRemoved');
-
-        assert.ok(saveMock.calledOnce);
-        var args = saveMock.args; 
-        assert.deepEqual(args[0][0], {"admins":{"names":["_user"],"roles":[]},"members":{"names":[],"roles":[]}});
-      });
-
-      it('Should save model', function () {
-        var saveMock = sinon.spy(security, 'save');
-        Views.events.trigger('itemRemoved');
-
-        assert.ok(saveMock.calledOnce);
-      });
-    });
-
-  });
-
-  describe('PermissionsSection', function () {
-    var section, security;
-
-    beforeEach(function () {
-      security = new Models.Security({'admins': {
-        'names': ['_user'],
-        'roles': []
-      }
-      }, {database: 'fakedb'});
-
-      section = new Views.PermissionSection({
-        section: 'admins',
-        model: security
-      });
-
-      viewSandbox = new ViewSandbox();
-      viewSandbox.renderView(section); 
-    });
-
-    afterEach(function () {
-      viewSandbox.remove();
-    });
-
-    describe('#discardRemovedViews', function () {
-      it('Should not filter out active views', function () {
-        section.discardRemovedViews();
-
-        assert.equal(section.nameViews.length, 1);
-
-      });
-
-      it('Should filter out removed views', function () {
-        section.nameViews[0].removed = true;
-        section.discardRemovedViews();
-
-        assert.equal(section.nameViews.length, 0);
-
-      });
-
-    });
-
-    describe('#getItemFromView', function () {
-
-      it('Should return item list', function () {
-        var items = section.getItemFromView(section.nameViews);
-
-        assert.deepEqual(items, ['_user']);
-      });
-
-    });
-
-    describe('#addItems', function () {
-
-      it('Should add item to model', function () {
-        //todo add a test here
-
-      });
-
-    });
-
-  });
-
-  describe('PermissionItem', function () {
-    var item;
-
-    beforeEach(function () {
-      item = new Views.PermissionItem({
-        item: '_user'
-      });
-
-      viewSandbox = new ViewSandbox();
-      viewSandbox.renderView(item); 
-    });
-
-    afterEach(function () {
-      viewSandbox.remove();
-    });
-
-    it('should trigger event on remove item', function () {
-      var eventSpy = sinon.spy();
-
-      Views.events.on('itemRemoved', eventSpy);
-
-      item.$('.close').click();
-      
-      assert.ok(eventSpy.calledOnce); 
-    });
-
-    it('should set removed to true', function () {
-      item.$('.close').click();
-      
-      assert.ok(item.removed); 
-    });
-  });
-
-});


[51/96] [abbrv] [partial] git commit: updated refs/heads/1994-merge-rcouch to 9605700

Posted by be...@apache.org.
move sources to src


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/941a8236
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/941a8236
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/941a8236

Branch: refs/heads/1994-merge-rcouch
Commit: 941a8236c33a248b77abc8fa546a082d08c18bd9
Parents: 79dec6d
Author: Benoit Chesneau <be...@apache.org>
Authored: Wed Jan 8 03:16:05 2014 +0100
Committer: Benoit Chesneau <be...@apache.org>
Committed: Wed Jan 8 03:16:05 2014 +0100

----------------------------------------------------------------------
 .gitignore                                      |    34 +-
 apps/couch/c_src/couch_js/help.h                |    82 -
 apps/couch/c_src/couch_js/http.c                |   696 -
 apps/couch/c_src/couch_js/http.h                |    27 -
 apps/couch/c_src/couch_js/main.c                |   431 -
 apps/couch/c_src/couch_js/utf8.c                |   288 -
 apps/couch/c_src/couch_js/utf8.h                |    19 -
 apps/couch/c_src/couch_js/util.c                |   288 -
 apps/couch/c_src/couch_js/util.h                |    35 -
 .../spawnkillable/couchspawnkillable_win.c      |   145 -
 apps/couch/include/couch_db.hrl                 |   286 -
 apps/couch/priv/couchspawnkillable.sh           |    20 -
 apps/couch/priv/stat_descriptions.cfg           |    50 -
 apps/couch/rebar.config.script                  |   108 -
 apps/couch/src/couch.app.src                    |     0
 apps/couch/src/couch.app.src.script             |    67 -
 apps/couch/src/couch.erl                        |    67 -
 apps/couch/src/couch_app.erl                    |    36 -
 apps/couch/src/couch_auth_cache.erl             |   425 -
 apps/couch/src/couch_btree.erl                  |   714 -
 apps/couch/src/couch_changes.erl                |   577 -
 apps/couch/src/couch_compaction_daemon.erl      |   504 -
 apps/couch/src/couch_compress.erl               |    84 -
 apps/couch/src/couch_config.erl                 |   251 -
 apps/couch/src/couch_config_writer.erl          |    88 -
 apps/couch/src/couch_db.erl                     |  1358 --
 apps/couch/src/couch_db_update_notifier.erl     |    82 -
 apps/couch/src/couch_db_update_notifier_sup.erl |    61 -
 apps/couch/src/couch_db_updater.erl             |  1035 --
 apps/couch/src/couch_doc.erl                    |   650 -
 apps/couch/src/couch_ejson_compare.erl          |    81 -
 apps/couch/src/couch_event_sup.erl              |    73 -
 apps/couch/src/couch_external_manager.erl       |   101 -
 apps/couch/src/couch_external_server.erl        |    70 -
 apps/couch/src/couch_file.erl                   |   532 -
 apps/couch/src/couch_httpd.erl                  |  1114 --
 apps/couch/src/couch_httpd_auth.erl             |   380 -
 apps/couch/src/couch_httpd_cors.erl             |   351 -
 apps/couch/src/couch_httpd_db.erl               |  1226 --
 apps/couch/src/couch_httpd_external.erl         |   177 -
 apps/couch/src/couch_httpd_misc_handlers.erl    |   318 -
 apps/couch/src/couch_httpd_oauth.erl            |   387 -
 apps/couch/src/couch_httpd_proxy.erl            |   426 -
 apps/couch/src/couch_httpd_rewrite.erl          |   484 -
 apps/couch/src/couch_httpd_stats_handlers.erl   |    56 -
 apps/couch/src/couch_httpd_vhost.erl            |   383 -
 apps/couch/src/couch_js_functions.hrl           |   170 -
 apps/couch/src/couch_key_tree.erl               |   422 -
 apps/couch/src/couch_log.erl                    |   254 -
 apps/couch/src/couch_native_process.erl         |   409 -
 apps/couch/src/couch_os_daemons.erl             |   374 -
 apps/couch/src/couch_os_process.erl             |   216 -
 apps/couch/src/couch_passwords.erl              |   119 -
 apps/couch/src/couch_primary_sup.erl            |    48 -
 apps/couch/src/couch_query_servers.erl          |   616 -
 apps/couch/src/couch_ref_counter.erl            |   111 -
 apps/couch/src/couch_secondary_sup.erl          |    49 -
 apps/couch/src/couch_server.erl                 |   493 -
 apps/couch/src/couch_server_sup.erl             |   164 -
 apps/couch/src/couch_stats_aggregator.erl       |   297 -
 apps/couch/src/couch_stats_collector.erl        |   136 -
 apps/couch/src/couch_stream.erl                 |   299 -
 apps/couch/src/couch_task_status.erl            |   151 -
 apps/couch/src/couch_users_db.erl               |   121 -
 apps/couch/src/couch_util.erl                   |   487 -
 apps/couch/src/couch_uuids.erl                  |   103 -
 apps/couch/src/couch_work_queue.erl             |   187 -
 apps/couch/src/json_stream_parse.erl            |   432 -
 apps/couch_collate/c_src/couch_collate.c        |   281 -
 apps/couch_collate/rebar.config                 |     9 -
 apps/couch_collate/rebar.config.script          |    46 -
 apps/couch_collate/src/couch_collate.app.src    |    13 -
 apps/couch_collate/src/couch_collate.erl        |    62 -
 .../couch_dbupdates/src/couch_dbupdates.app.src |    11 -
 apps/couch_dbupdates/src/couch_dbupdates.erl    |    46 -
 .../src/couch_dbupdates_httpd.erl               |    69 -
 apps/couch_index/src/couch_index.app.src        |    20 -
 apps/couch_index/src/couch_index.erl            |   338 -
 apps/couch_index/src/couch_index_api.erl        |    54 -
 apps/couch_index/src/couch_index_app.erl        |    27 -
 apps/couch_index/src/couch_index_compactor.erl  |   113 -
 apps/couch_index/src/couch_index_server.erl     |   201 -
 apps/couch_index/src/couch_index_sup.erl        |    30 -
 apps/couch_index/src/couch_index_updater.erl    |   200 -
 apps/couch_index/src/couch_index_util.erl       |    77 -
 apps/couch_mrview/include/couch_mrview.hrl      |    81 -
 apps/couch_mrview/src/couch_mrview.app.src      |    28 -
 apps/couch_mrview/src/couch_mrview.erl          |   387 -
 apps/couch_mrview/src/couch_mrview_cleanup.erl  |    45 -
 .../couch_mrview/src/couch_mrview_compactor.erl |   178 -
 apps/couch_mrview/src/couch_mrview_http.erl     |   409 -
 apps/couch_mrview/src/couch_mrview_index.erl    |   162 -
 apps/couch_mrview/src/couch_mrview_show.erl     |   368 -
 .../couch_mrview/src/couch_mrview_test_util.erl |    92 -
 apps/couch_mrview/src/couch_mrview_updater.erl  |   282 -
 apps/couch_mrview/src/couch_mrview_util.erl     |   802 -
 apps/couch_mrview/test/01-load.t                |    34 -
 apps/couch_mrview/test/02-map-views.t           |   131 -
 apps/couch_mrview/test/03-red-views.t           |    78 -
 apps/couch_mrview/test/04-index-info.t          |    54 -
 apps/couch_mrview/test/05-collation.t           |   163 -
 apps/couch_mrview/test/06-all-docs.t            |   127 -
 apps/couch_mrview/test/07-compact-swap.t        |    57 -
 apps/couch_plugins/README.md                    |   159 -
 apps/couch_plugins/src/couch_plugins.app.src    |    23 -
 apps/couch_plugins/src/couch_plugins.erl        |   300 -
 apps/couch_plugins/src/couch_plugins_httpd.erl  |    65 -
 apps/couch_rel/ebin/couch_rel.app               |    18 -
 apps/couch_rel/src/etop_txt.erl                 |   134 -
 .../src/couch_replicator.app.src                |    28 -
 apps/couch_replicator/src/couch_replicator.erl  |   965 -
 apps/couch_replicator/src/couch_replicator.hrl  |    30 -
 .../src/couch_replicator_api_wrap.erl           |   877 -
 .../src/couch_replicator_api_wrap.hrl           |    36 -
 .../src/couch_replicator_app.erl                |    29 -
 .../src/couch_replicator_httpc.erl              |   297 -
 .../src/couch_replicator_httpc_pool.erl         |   138 -
 .../src/couch_replicator_httpd.erl              |    66 -
 .../src/couch_replicator_job_sup.erl            |    31 -
 .../src/couch_replicator_js_functions.hrl       |   151 -
 .../src/couch_replicator_manager.erl            |   709 -
 .../src/couch_replicator_manager_sup.erl        |    47 -
 .../src/couch_replicator_notifier.erl           |    57 -
 .../src/couch_replicator_sup.erl                |    59 -
 .../src/couch_replicator_utils.erl              |   396 -
 .../src/couch_replicator_worker.erl             |   515 -
 apps/couch_replicator/test/01-load.t            |    37 -
 apps/couch_replicator/test/02-httpc-pool.t      |   250 -
 .../test/03-replication-compact.t               |   488 -
 .../test/04-replication-large-atts.t            |   267 -
 .../test/05-replication-many-leaves.t           |   294 -
 .../test/06-doc-missing-stubs.t                 |   304 -
 apps/couch_replicator/test/07-use-checkpoints.t |   256 -
 apps/couchjs-node/README.md                     |    32 -
 apps/couchjs-node/cli.js                        |    89 -
 apps/couchjs-node/console.js                    |    66 -
 apps/couchjs-node/couchdb.js                    |    29 -
 apps/couchjs-node/couchjs.js                    |   133 -
 apps/couchjs-node/inspector.js                  |   101 -
 apps/couchjs-node/package.json                  |    40 -
 apps/couchjs-node/sandbox.js                    |    47 -
 apps/couchjs-node/stream.js                     |   115 -
 apps/couchjs-node/test/experiment.js            |   125 -
 apps/couchjs-node/xml.js                        |    22 -
 apps/fauxton/Gruntfile.js                       |   441 -
 apps/fauxton/TODO.md                            |    26 -
 .../activetasks/assets/less/activetasks.less    |    18 -
 apps/fauxton/app/addons/activetasks/base.js     |    26 -
 .../fauxton/app/addons/activetasks/resources.js |   118 -
 apps/fauxton/app/addons/activetasks/routes.js   |    58 -
 .../addons/activetasks/templates/detail.html    |    21 -
 .../app/addons/activetasks/templates/table.html |    52 -
 .../activetasks/templates/tabledetail.html      |    36 -
 .../app/addons/activetasks/templates/tabs.html  |    46 -
 .../app/addons/activetasks/tests/viewsSpec.js   |   139 -
 apps/fauxton/app/addons/activetasks/views.js    |   181 -
 .../app/addons/auth/assets/less/auth.less       |    15 -
 apps/fauxton/app/addons/auth/base.js            |    69 -
 apps/fauxton/app/addons/auth/resources.js       |   364 -
 apps/fauxton/app/addons/auth/routes.js          |    93 -
 .../addons/auth/templates/change_password.html  |    26 -
 .../app/addons/auth/templates/create_admin.html |    37 -
 .../app/addons/auth/templates/login.html        |    26 -
 .../app/addons/auth/templates/nav_dropdown.html |    26 -
 .../addons/auth/templates/nav_link_title.html   |    31 -
 .../app/addons/auth/templates/noAccess.html     |    20 -
 .../compaction/assets/less/compaction.less      |    19 -
 apps/fauxton/app/addons/compaction/base.js      |    31 -
 apps/fauxton/app/addons/compaction/resources.js |    48 -
 apps/fauxton/app/addons/compaction/routes.js    |    65 -
 .../compaction/templates/compact_view.html      |    14 -
 .../app/addons/compaction/templates/layout.html |    28 -
 apps/fauxton/app/addons/compaction/views.js     |   140 -
 .../app/addons/config/assets/less/config.less   |    13 -
 apps/fauxton/app/addons/config/base.js          |    28 -
 apps/fauxton/app/addons/config/resources.js     |   176 -
 apps/fauxton/app/addons/config/routes.js        |    59 -
 .../app/addons/config/templates/dashboard.html  |    52 -
 .../app/addons/config/templates/item.html       |    31 -
 apps/fauxton/app/addons/contribute/base.js      |    33 -
 apps/fauxton/app/addons/exampleAuth/base.js     |    59 -
 .../addons/exampleAuth/templates/noAccess.html  |    19 -
 apps/fauxton/app/addons/logs/base.js            |    28 -
 apps/fauxton/app/addons/logs/resources.js       |   225 -
 apps/fauxton/app/addons/logs/routes.js          |    58 -
 .../app/addons/logs/templates/dashboard.html    |    46 -
 .../app/addons/logs/templates/filterItem.html   |    16 -
 .../app/addons/logs/templates/sidebar.html      |    27 -
 apps/fauxton/app/addons/logs/tests/logSpec.js   |    38 -
 .../permissions/assets/less/permissions.less    |    44 -
 apps/fauxton/app/addons/permissions/base.js     |    25 -
 .../fauxton/app/addons/permissions/resources.js |    70 -
 apps/fauxton/app/addons/permissions/routes.js   |    63 -
 .../app/addons/permissions/templates/item.html  |    17 -
 .../permissions/templates/permissions.html      |    15 -
 .../addons/permissions/templates/section.html   |    46 -
 .../addons/permissions/tests/resourceSpec.js    |    51 -
 .../app/addons/permissions/tests/viewsSpec.js   |   159 -
 apps/fauxton/app/addons/permissions/views.js    |   200 -
 apps/fauxton/app/addons/plugins/base.js         |    24 -
 apps/fauxton/app/addons/plugins/resources.js    |    26 -
 apps/fauxton/app/addons/plugins/routes.js       |    47 -
 .../app/addons/plugins/templates/plugins.html   |   102 -
 .../replication/assets/less/replication.less    |   196 -
 apps/fauxton/app/addons/replication/base.js     |    24 -
 .../fauxton/app/addons/replication/resources.js |    69 -
 apps/fauxton/app/addons/replication/route.js    |    50 -
 .../app/addons/replication/templates/form.html  |    74 -
 .../addons/replication/templates/progress.html  |    22 -
 .../addons/replication/tests/replicationSpec.js |    28 -
 apps/fauxton/app/addons/replication/views.js    |   295 -
 .../app/addons/stats/assets/less/stats.less     |    19 -
 apps/fauxton/app/addons/stats/base.js           |    26 -
 apps/fauxton/app/addons/stats/resources.js      |    38 -
 apps/fauxton/app/addons/stats/routes.js         |    63 -
 .../app/addons/stats/templates/by_method.html   |    16 -
 .../app/addons/stats/templates/pie_table.html   |    54 -
 .../app/addons/stats/templates/stats.html       |    16 -
 .../app/addons/stats/templates/statselect.html  |    22 -
 apps/fauxton/app/addons/stats/views.js          |   171 -
 .../assets/less/verifyinstall.less              |    16 -
 apps/fauxton/app/addons/verifyinstall/base.js   |    31 -
 .../app/addons/verifyinstall/resources.js       |   181 -
 apps/fauxton/app/addons/verifyinstall/routes.js |    37 -
 .../addons/verifyinstall/templates/main.html    |    50 -
 apps/fauxton/app/addons/verifyinstall/views.js  |   127 -
 apps/fauxton/app/api.js                         |   558 -
 apps/fauxton/app/app.js                         |   122 -
 apps/fauxton/app/config.js                      |    60 -
 apps/fauxton/app/helpers.js                     |    78 -
 apps/fauxton/app/initialize.js.underscore       |    33 -
 apps/fauxton/app/load_addons.js.underscore      |    27 -
 apps/fauxton/app/main.js                        |    48 -
 apps/fauxton/app/mixins.js                      |    65 -
 apps/fauxton/app/modules/databases/base.js      |    37 -
 apps/fauxton/app/modules/databases/resources.js |   193 -
 apps/fauxton/app/modules/databases/routes.js    |    69 -
 apps/fauxton/app/modules/databases/views.js     |   255 -
 apps/fauxton/app/modules/documents/base.js      |    24 -
 apps/fauxton/app/modules/documents/resources.js |   638 -
 apps/fauxton/app/modules/documents/routes.js    |   408 -
 .../modules/documents/tests/resourcesSpec.js    |    84 -
 apps/fauxton/app/modules/documents/views.js     |  1805 --
 apps/fauxton/app/modules/fauxton/base.js        |   276 -
 apps/fauxton/app/modules/fauxton/components.js  |   316 -
 apps/fauxton/app/modules/fauxton/layout.js      |    98 -
 apps/fauxton/app/modules/pouchdb/base.js        |    47 -
 .../app/modules/pouchdb/pouch.collate.js        |   115 -
 .../app/modules/pouchdb/pouchdb.mapreduce.js    |   324 -
 apps/fauxton/app/resizeColumns.js               |    87 -
 apps/fauxton/app/router.js                      |   175 -
 apps/fauxton/app/templates/databases/item.html  |    24 -
 apps/fauxton/app/templates/databases/list.html  |    35 -
 .../app/templates/databases/newdatabase.html    |    17 -
 .../app/templates/databases/sidebar.html        |    31 -
 .../templates/documents/advanced_options.html   |    97 -
 .../app/templates/documents/all_docs_item.html  |    26 -
 .../templates/documents/all_docs_layout.html    |    20 -
 .../app/templates/documents/all_docs_list.html  |    43 -
 .../templates/documents/all_docs_number.html    |    21 -
 .../app/templates/documents/changes.html        |    38 -
 .../app/templates/documents/ddoc_info.html      |    28 -
 .../documents/design_doc_selector.html          |    35 -
 apps/fauxton/app/templates/documents/doc.html   |    55 -
 .../templates/documents/doc_field_editor.html   |    74 -
 .../documents/doc_field_editor_tabs.html        |    19 -
 .../documents/duplicate_doc_modal.html          |    36 -
 .../app/templates/documents/edit_tools.html     |    44 -
 .../templates/documents/index_menu_item.html    |    17 -
 .../templates/documents/index_row_docular.html  |    26 -
 .../templates/documents/index_row_tabular.html  |    25 -
 .../app/templates/documents/jumpdoc.html        |    19 -
 .../fauxton/app/templates/documents/search.html |    15 -
 .../app/templates/documents/sidebar.html        |    67 -
 apps/fauxton/app/templates/documents/tabs.html  |    18 -
 .../app/templates/documents/upload_modal.html   |    42 -
 .../app/templates/documents/view_editor.html    |    87 -
 apps/fauxton/app/templates/fauxton/api_bar.html |    30 -
 .../app/templates/fauxton/breadcrumbs.html      |    24 -
 apps/fauxton/app/templates/fauxton/footer.html  |    15 -
 .../app/templates/fauxton/index_pagination.html |    24 -
 apps/fauxton/app/templates/fauxton/nav_bar.html |    75 -
 .../app/templates/fauxton/notification.html     |    18 -
 .../app/templates/fauxton/pagination.html       |    31 -
 .../fauxton/app/templates/layouts/one_pane.html |    28 -
 .../app/templates/layouts/one_pane_notabs.html  |    27 -
 .../fauxton/app/templates/layouts/two_pane.html |    30 -
 .../templates/layouts/with_right_sidebar.html   |    26 -
 .../app/templates/layouts/with_sidebar.html     |    27 -
 .../app/templates/layouts/with_tabs.html        |    28 -
 .../templates/layouts/with_tabs_sidebar.html    |    41 -
 apps/fauxton/assets/css/nv.d3.css               |   656 -
 apps/fauxton/assets/img/FontAwesome.otf         |   Bin 61896 -> 0 bytes
 apps/fauxton/assets/img/couchdb-site.png        |   Bin 4946 -> 0 bytes
 apps/fauxton/assets/img/couchdblogo.png         |   Bin 2738 -> 0 bytes
 apps/fauxton/assets/img/fontawesome-webfont.eot |   Bin 37405 -> 0 bytes
 apps/fauxton/assets/img/fontawesome-webfont.svg |   399 -
 apps/fauxton/assets/img/fontawesome-webfont.ttf |   Bin 79076 -> 0 bytes
 .../fauxton/assets/img/fontawesome-webfont.woff |   Bin 43572 -> 0 bytes
 apps/fauxton/assets/img/fontcustom_fauxton.eot  |   Bin 7364 -> 0 bytes
 apps/fauxton/assets/img/fontcustom_fauxton.svg  |   200 -
 apps/fauxton/assets/img/fontcustom_fauxton.ttf  |   Bin 9636 -> 0 bytes
 apps/fauxton/assets/img/fontcustom_fauxton.woff |   Bin 4816 -> 0 bytes
 .../assets/img/glyphicons-halflings-white.png   |   Bin 8777 -> 0 bytes
 .../fauxton/assets/img/glyphicons-halflings.png |   Bin 13826 -> 0 bytes
 apps/fauxton/assets/img/linen.png               |   Bin 87134 -> 0 bytes
 apps/fauxton/assets/img/loader.gif              |   Bin 5193 -> 0 bytes
 apps/fauxton/assets/img/minilogo.png            |   Bin 2927 -> 0 bytes
 apps/fauxton/assets/index.underscore            |    47 -
 apps/fauxton/assets/js/libs/ace/ace.js          | 16541 -----------------
 .../fauxton/assets/js/libs/ace/ext-chromevox.js |   537 -
 .../js/libs/ace/ext-elastic_tabstops_lite.js    |   301 -
 apps/fauxton/assets/js/libs/ace/ext-emmet.js    |  1096 --
 .../assets/js/libs/ace/ext-keybinding_menu.js   |   207 -
 .../assets/js/libs/ace/ext-language_tools.js    |  1615 --
 apps/fauxton/assets/js/libs/ace/ext-modelist.js |   166 -
 apps/fauxton/assets/js/libs/ace/ext-old_ie.js   |   499 -
 apps/fauxton/assets/js/libs/ace/ext-options.js  |   252 -
 .../fauxton/assets/js/libs/ace/ext-searchbox.js |   420 -
 .../assets/js/libs/ace/ext-settings_menu.js     |   634 -
 .../assets/js/libs/ace/ext-spellcheck.js        |    68 -
 apps/fauxton/assets/js/libs/ace/ext-split.js    |   271 -
 .../assets/js/libs/ace/ext-static_highlight.js  |   165 -
 .../fauxton/assets/js/libs/ace/ext-statusbar.js |    47 -
 apps/fauxton/assets/js/libs/ace/ext-textarea.js |   478 -
 .../fauxton/assets/js/libs/ace/ext-themelist.js |    90 -
 .../assets/js/libs/ace/ext-whitespace.js        |   206 -
 .../assets/js/libs/ace/mode-javascript.js       |   886 -
 apps/fauxton/assets/js/libs/ace/mode-json.js    |   578 -
 apps/fauxton/assets/js/libs/ace/mode-jsoniq.js  |  2714 ---
 .../assets/js/libs/ace/snippets/javascript.js   |   202 -
 .../fauxton/assets/js/libs/ace/snippets/json.js |     7 -
 .../assets/js/libs/ace/snippets/jsoniq.js       |     7 -
 .../assets/js/libs/ace/theme-crimson_editor.js  |   148 -
 .../assets/js/libs/ace/worker-javascript.js     | 10088 ----------
 apps/fauxton/assets/js/libs/ace/worker-json.js  |  2271 ---
 apps/fauxton/assets/js/libs/almond.js           |   314 -
 apps/fauxton/assets/js/libs/backbone.js         |  1571 --
 apps/fauxton/assets/js/libs/bootstrap.js        |  2291 ---
 apps/fauxton/assets/js/libs/d3.js               |  7026 -------
 apps/fauxton/assets/js/libs/jquery.js           |  9789 ----------
 apps/fauxton/assets/js/libs/lodash.js           |  4493 -----
 apps/fauxton/assets/js/libs/nv.d3.js            | 13119 -------------
 apps/fauxton/assets/js/libs/require.js          |  2045 --
 apps/fauxton/assets/js/libs/spin.min.js         |     1 -
 .../assets/js/plugins/backbone.layoutmanager.js |   996 -
 apps/fauxton/assets/js/plugins/jquery.form.js   |  1190 --
 apps/fauxton/assets/js/plugins/prettify.js      |    28 -
 .../assets/less/bootstrap/accordion.less        |    34 -
 apps/fauxton/assets/less/bootstrap/alerts.less  |    79 -
 .../assets/less/bootstrap/bootstrap.less        |    63 -
 .../assets/less/bootstrap/breadcrumbs.less      |    24 -
 .../assets/less/bootstrap/button-groups.less    |   229 -
 apps/fauxton/assets/less/bootstrap/buttons.less |   228 -
 .../fauxton/assets/less/bootstrap/carousel.less |   158 -
 apps/fauxton/assets/less/bootstrap/close.less   |    32 -
 apps/fauxton/assets/less/bootstrap/code.less    |    61 -
 .../less/bootstrap/component-animations.less    |    22 -
 .../assets/less/bootstrap/dropdowns.less        |   248 -
 .../less/bootstrap/font-awesome/bootstrap.less  |    84 -
 .../less/bootstrap/font-awesome/core.less       |   129 -
 .../less/bootstrap/font-awesome/extras.less     |    93 -
 .../font-awesome/font-awesome-ie7.less          |  1953 --
 .../bootstrap/font-awesome/font-awesome.less    |    33 -
 .../less/bootstrap/font-awesome/icons.less      |   381 -
 .../less/bootstrap/font-awesome/mixins.less     |    48 -
 .../less/bootstrap/font-awesome/path.less       |    14 -
 .../less/bootstrap/font-awesome/variables.less  |   735 -
 apps/fauxton/assets/less/bootstrap/forms.less   |   690 -
 apps/fauxton/assets/less/bootstrap/grid.less    |    21 -
 .../assets/less/bootstrap/hero-unit.less        |    25 -
 .../assets/less/bootstrap/labels-badges.less    |    84 -
 apps/fauxton/assets/less/bootstrap/layouts.less |    16 -
 apps/fauxton/assets/less/bootstrap/media.less   |    55 -
 apps/fauxton/assets/less/bootstrap/mixins.less  |   716 -
 apps/fauxton/assets/less/bootstrap/modals.less  |    95 -
 apps/fauxton/assets/less/bootstrap/navbar.less  |   497 -
 apps/fauxton/assets/less/bootstrap/navs.less    |   409 -
 apps/fauxton/assets/less/bootstrap/pager.less   |    43 -
 .../assets/less/bootstrap/pagination.less       |   123 -
 .../fauxton/assets/less/bootstrap/popovers.less |   133 -
 .../assets/less/bootstrap/progress-bars.less    |   122 -
 apps/fauxton/assets/less/bootstrap/reset.less   |   216 -
 .../less/bootstrap/responsive-1200px-min.less   |    28 -
 .../less/bootstrap/responsive-767px-max.less    |   193 -
 .../less/bootstrap/responsive-768px-979px.less  |    19 -
 .../less/bootstrap/responsive-navbar.less       |   189 -
 .../less/bootstrap/responsive-utilities.less    |    59 -
 .../assets/less/bootstrap/responsive.less       |    48 -
 .../assets/less/bootstrap/scaffolding.less      |    53 -
 apps/fauxton/assets/less/bootstrap/sprites.less |   197 -
 apps/fauxton/assets/less/bootstrap/tables.less  |   244 -
 .../assets/less/bootstrap/tests/buttons.html    |   139 -
 .../assets/less/bootstrap/tests/css-tests.css   |   150 -
 .../assets/less/bootstrap/thumbnails.less       |    53 -
 apps/fauxton/assets/less/bootstrap/tooltip.less |    70 -
 apps/fauxton/assets/less/bootstrap/type.less    |   247 -
 .../assets/less/bootstrap/utilities.less        |    30 -
 .../assets/less/bootstrap/variables.less        |   301 -
 apps/fauxton/assets/less/bootstrap/wells.less   |    29 -
 apps/fauxton/assets/less/config.less            |    46 -
 apps/fauxton/assets/less/couchdb.less           |    72 -
 apps/fauxton/assets/less/database.less          |   245 -
 apps/fauxton/assets/less/fauxton.less           |  1009 -
 apps/fauxton/assets/less/icons.less             |   111 -
 apps/fauxton/assets/less/logs.less              |    24 -
 apps/fauxton/assets/less/prettyprint.less       |    46 -
 apps/fauxton/assets/less/variables.less         |    82 -
 apps/fauxton/bin/grunt                          |    18 -
 apps/fauxton/couchapp.js                        |    39 -
 apps/fauxton/extensions.md                      |    17 -
 apps/fauxton/favicon.ico                        |   Bin 1150 -> 0 bytes
 apps/fauxton/index.html                         |    53 -
 apps/fauxton/package.json                       |    48 -
 apps/fauxton/readme.md                          |    79 -
 apps/fauxton/settings.json.default              |    55 -
 apps/fauxton/settings.json.sample_external      |    10 -
 apps/fauxton/tasks/addon/rename.json            |     5 -
 .../fauxton/tasks/addon/root/base.js.underscore |    21 -
 .../tasks/addon/root/resources.js.underscore    |    21 -
 .../tasks/addon/root/routes.js.underscore       |    42 -
 apps/fauxton/tasks/addon/template.js            |    70 -
 apps/fauxton/tasks/couchserver.js               |   104 -
 apps/fauxton/tasks/fauxton.js                   |   137 -
 apps/fauxton/tasks/helper.js                    |    45 -
 apps/fauxton/test/core/layoutSpec.js            |    94 -
 apps/fauxton/test/core/navbarSpec.js            |   107 -
 apps/fauxton/test/core/paginateSpec.js          |   109 -
 apps/fauxton/test/core/routeObjectSpec.js       |   105 -
 apps/fauxton/test/mocha/chai.js                 |  4330 -----
 apps/fauxton/test/mocha/mocha.css               |   251 -
 apps/fauxton/test/mocha/mocha.js                |  5428 ------
 apps/fauxton/test/mocha/sinon-chai.js           |   109 -
 apps/fauxton/test/mocha/sinon.js                |  4290 -----
 apps/fauxton/test/mocha/testUtils.js            |    50 -
 apps/fauxton/test/runner.html                   |    33 -
 apps/fauxton/test/test.config.underscore        |    15 -
 apps/fauxton/writing_addons.md                  |   173 -
 etc/Makefile.am                                 |   117 -
 etc/couchdb/Makefile.am                         |    95 -
 etc/default/Makefile.am                         |    13 -
 etc/default/couchdb                             |     7 -
 etc/init/Makefile.am                            |    13 -
 etc/init/couchdb.tpl.in                         |   159 -
 etc/launchd/Makefile.am                         |    13 -
 etc/launchd/org.apache.couchdb.plist.tpl.in     |    30 -
 etc/logrotate.d/Makefile.am                     |    13 -
 etc/logrotate.d/couchdb.tpl.in                  |     9 -
 etc/windows/Makefile.am                         |    13 -
 etc/windows/README.txt.tpl                      |    29 -
 etc/windows/couchdb.iss.tpl                     |    92 -
 rebar.config                                    |    22 +-
 rel/files/app.config                            |    30 -
 rel/files/couch.ini                             |   350 -
 rel/files/empty                                 |     0
 rel/files/local.ini                             |    97 -
 rel/files/vm.args                               |    24 -
 rel/reltool.config.script                       |    28 +-
 share/Makefile.am                               |   260 -
 share/doc/Makefile.am                           |    14 -
 share/doc/build/Makefile.am                     |   626 -
 share/doc/ext/configdomain.py                   |   127 -
 share/doc/ext/github.py                         |    44 -
 share/doc/ext/httpdomain.py                     |   656 -
 share/doc/images/epub-icon.png                  |   Bin 19185 -> 0 bytes
 share/doc/images/favicon.ico                    |   Bin 9326 -> 0 bytes
 share/doc/images/futon-createdb.png             |   Bin 76194 -> 0 bytes
 share/doc/images/futon-editdoc.png              |   Bin 52733 -> 0 bytes
 share/doc/images/futon-editeddoc.png            |   Bin 56005 -> 0 bytes
 share/doc/images/futon-overview.png             |   Bin 50815 -> 0 bytes
 share/doc/images/futon-replform.png             |   Bin 52223 -> 0 bytes
 share/doc/images/intro-consistency-01.png       |   Bin 35605 -> 0 bytes
 share/doc/images/intro-consistency-02.png       |   Bin 48145 -> 0 bytes
 share/doc/images/intro-consistency-03.png       |   Bin 17333 -> 0 bytes
 share/doc/images/intro-consistency-04.png       |   Bin 13744 -> 0 bytes
 share/doc/images/intro-consistency-05.png       |   Bin 25592 -> 0 bytes
 share/doc/images/intro-consistency-06.png       |   Bin 56651 -> 0 bytes
 share/doc/images/intro-consistency-07.png       |   Bin 53634 -> 0 bytes
 share/doc/images/intro-tour-01.png              |   Bin 50815 -> 0 bytes
 share/doc/images/intro-tour-02.png              |   Bin 83380 -> 0 bytes
 share/doc/images/intro-tour-03.png              |   Bin 53795 -> 0 bytes
 share/doc/images/intro-tour-04.png              |   Bin 56470 -> 0 bytes
 share/doc/images/intro-tour-05.png              |   Bin 53778 -> 0 bytes
 share/doc/images/intro-tour-06.png              |   Bin 61296 -> 0 bytes
 share/doc/images/intro-tour-07.png              |   Bin 67121 -> 0 bytes
 share/doc/images/intro-tour-08.png              |   Bin 83494 -> 0 bytes
 share/doc/images/intro-tour-09.png              |   Bin 84701 -> 0 bytes
 share/doc/images/intro-tour-10.png              |   Bin 61631 -> 0 bytes
 share/doc/images/intro-why-01.png               |   Bin 25755 -> 0 bytes
 share/doc/images/intro-why-02.png               |   Bin 5937 -> 0 bytes
 share/doc/images/intro-why-03.png               |   Bin 5134 -> 0 bytes
 share/doc/images/logo.png                       |   Bin 13195 -> 0 bytes
 share/doc/images/views-intro-01.png             |   Bin 1026767 -> 0 bytes
 share/doc/images/views-intro-02.png             |   Bin 9758 -> 0 bytes
 share/doc/images/views-intro-03.png             |   Bin 12650 -> 0 bytes
 share/doc/images/views-intro-04.png             |   Bin 14537 -> 0 bytes
 share/doc/src/about.rst                         |    25 -
 share/doc/src/api/basics.rst                    |   601 -
 share/doc/src/api/database/bulk-api.rst         |   646 -
 share/doc/src/api/database/changes.rst          |   574 -
 share/doc/src/api/database/common.rst           |   430 -
 share/doc/src/api/database/compact.rst          |   243 -
 share/doc/src/api/database/index.rst            |    47 -
 share/doc/src/api/database/misc.rst             |   351 -
 share/doc/src/api/database/security.rst         |   182 -
 share/doc/src/api/database/temp-views.rst       |    79 -
 share/doc/src/api/ddoc/common.rst               |   226 -
 share/doc/src/api/ddoc/index.rst                |    37 -
 share/doc/src/api/ddoc/render.rst               |   390 -
 share/doc/src/api/ddoc/rewrites.rst             |    90 -
 share/doc/src/api/ddoc/views.rst                |   797 -
 share/doc/src/api/document/attachments.rst      |   318 -
 share/doc/src/api/document/common.rst           |  1201 --
 share/doc/src/api/document/index.rst            |    25 -
 share/doc/src/api/index.rst                     |    42 -
 share/doc/src/api/local.rst                     |    84 -
 share/doc/src/api/server/authn.rst              |   452 -
 share/doc/src/api/server/common.rst             |  1012 -
 share/doc/src/api/server/configuration.rst      |   336 -
 share/doc/src/api/server/index.rst              |    28 -
 share/doc/src/conf.py                           |   158 -
 share/doc/src/config/auth.rst                   |   360 -
 share/doc/src/config/compaction.rst             |   174 -
 share/doc/src/config/couchdb.rst                |   200 -
 share/doc/src/config/externals.rst              |   179 -
 share/doc/src/config/http-handlers.rst          |   291 -
 share/doc/src/config/http.rst                   |   593 -
 share/doc/src/config/index.rst                  |    34 -
 share/doc/src/config/intro.rst                  |   172 -
 share/doc/src/config/logging.rst                |    94 -
 share/doc/src/config/misc.rst                   |   223 -
 share/doc/src/config/proxying.rst               |    98 -
 share/doc/src/config/query-servers.rst          |   161 -
 share/doc/src/config/replicator.rst             |   200 -
 share/doc/src/config/services.rst               |   150 -
 share/doc/src/contents.rst                      |    40 -
 share/doc/src/contributing.rst                  |   167 -
 share/doc/src/couchapp/ddocs.rst                |   768 -
 share/doc/src/couchapp/index.rst                |    31 -
 share/doc/src/couchapp/views/collation.rst      |   256 -
 share/doc/src/couchapp/views/index.rst          |    30 -
 share/doc/src/couchapp/views/intro.rst          |   675 -
 share/doc/src/couchapp/views/joins.rst          |   430 -
 share/doc/src/couchapp/views/nosql.rst          |   530 -
 share/doc/src/couchapp/views/pagination.rst     |   287 -
 share/doc/src/cve/2010-0009.rst                 |    54 -
 share/doc/src/cve/2010-2234.rst                 |    64 -
 share/doc/src/cve/2010-3854.rst                 |    57 -
 share/doc/src/cve/2012-5641.rst                 |    77 -
 share/doc/src/cve/2012-5649.rst                 |    50 -
 share/doc/src/cve/2012-5650.rst                 |    69 -
 share/doc/src/cve/index.rst                     |    73 -
 share/doc/src/experimental.rst                  |    83 -
 share/doc/src/externals.rst                     |   261 -
 share/doc/src/fauxton/addons.rst                |   199 -
 share/doc/src/fauxton/index.rst                 |    23 -
 share/doc/src/fauxton/install.rst               |   109 -
 share/doc/src/install/freebsd.rst               |    80 -
 share/doc/src/install/index.rst                 |    26 -
 share/doc/src/install/mac.rst                   |   194 -
 share/doc/src/install/unix.rst                  |   269 -
 share/doc/src/install/windows.rst               |   275 -
 share/doc/src/intro/api.rst                     |   783 -
 share/doc/src/intro/consistency.rst             |   465 -
 share/doc/src/intro/curl.rst                    |   122 -
 share/doc/src/intro/futon.rst                   |   186 -
 share/doc/src/intro/index.rst                   |    56 -
 share/doc/src/intro/overview.rst                |   387 -
 share/doc/src/intro/security.rst                |   525 -
 share/doc/src/intro/tour.rst                    |   542 -
 share/doc/src/intro/why.rst                     |   315 -
 share/doc/src/json-structure.rst                |   641 -
 share/doc/src/maintenance/compaction.rst        |   193 -
 share/doc/src/maintenance/index.rst             |    21 -
 share/doc/src/maintenance/performance.rst       |   293 -
 share/doc/src/query-server/erlang.rst           |   139 -
 share/doc/src/query-server/index.rst            |    40 -
 share/doc/src/query-server/javascript.rst       |   288 -
 share/doc/src/query-server/protocol.rst         |   967 -
 share/doc/src/replication/conflicts.rst         |   793 -
 share/doc/src/replication/index.rst             |    37 -
 share/doc/src/replication/intro.rst             |    95 -
 share/doc/src/replication/protocol.rst          |   202 -
 share/doc/src/replication/replicator.rst        |   405 -
 share/doc/src/whatsnew/0.10.rst                 |   150 -
 share/doc/src/whatsnew/0.11.rst                 |   357 -
 share/doc/src/whatsnew/0.8.rst                  |   178 -
 share/doc/src/whatsnew/0.9.rst                  |   262 -
 share/doc/src/whatsnew/1.0.rst                  |   277 -
 share/doc/src/whatsnew/1.1.rst                  |   175 -
 share/doc/src/whatsnew/1.2.rst                  |   242 -
 share/doc/src/whatsnew/1.3.rst                  |   256 -
 share/doc/src/whatsnew/1.4.rst                  |    61 -
 share/doc/src/whatsnew/1.5.rst                  |    48 -
 share/doc/src/whatsnew/1.6.rst                  |    53 -
 share/doc/src/whatsnew/index.rst                |    33 -
 share/doc/static/rtd.css                        |   795 -
 share/doc/templates/couchdb/domainindex.html    |    49 -
 share/doc/templates/couchdb/theme.conf          |    13 -
 share/doc/templates/help.html                   |    33 -
 share/doc/templates/layout.html                 |    27 -
 share/doc/templates/pages/download.html         |    48 -
 share/doc/templates/pages/index.html            |   175 -
 share/doc/templates/searchbox.html              |    31 -
 share/doc/templates/utilities.html              |    22 -
 share/server/coffee-script.js                   |     8 -
 share/server/filter.js                          |    45 -
 share/server/json2.js                           |   482 -
 share/server/loop.js                            |   167 -
 share/server/mimeparse.js                       |   158 -
 share/server/render.js                          |   369 -
 share/server/state.js                           |    32 -
 share/server/util.js                            |   166 -
 share/server/validate.js                        |    25 -
 share/server/views.js                           |   127 -
 share/www/_sidebar.html                         |    67 -
 share/www/config.html                           |   135 -
 share/www/couch_tests.html                      |    98 -
 share/www/custom_test.html                      |   112 -
 share/www/database.html                         |   270 -
 share/www/dialog/_admin_party.html              |    33 -
 share/www/dialog/_change_password.html          |    31 -
 share/www/dialog/_compact_cleanup.html          |    51 -
 share/www/dialog/_create_admin.html             |    50 -
 share/www/dialog/_create_config.html            |    42 -
 share/www/dialog/_create_database.html          |    33 -
 share/www/dialog/_database_security.html        |    50 -
 share/www/dialog/_delete_database.html          |    29 -
 share/www/dialog/_delete_document.html          |    26 -
 share/www/dialog/_login.html                    |    34 -
 share/www/dialog/_save_view_as.html             |    35 -
 share/www/dialog/_share_test_reports.html       |    42 -
 share/www/dialog/_signup.html                   |    35 -
 share/www/dialog/_upload_attachment.html        |    36 -
 share/www/document.html                         |   114 -
 share/www/fauxton/css/index.css                 |    37 -
 share/www/fauxton/img/FontAwesome.otf           |   Bin 61896 -> 0 bytes
 share/www/fauxton/img/couchdb-site.png          |   Bin 4946 -> 0 bytes
 share/www/fauxton/img/couchdblogo.png           |   Bin 2738 -> 0 bytes
 share/www/fauxton/img/fontawesome-webfont.eot   |   Bin 37405 -> 0 bytes
 share/www/fauxton/img/fontawesome-webfont.svg   |   399 -
 share/www/fauxton/img/fontawesome-webfont.ttf   |   Bin 79076 -> 0 bytes
 share/www/fauxton/img/fontawesome-webfont.woff  |   Bin 43572 -> 0 bytes
 share/www/fauxton/img/fontcustom_fauxton.eot    |   Bin 7364 -> 0 bytes
 share/www/fauxton/img/fontcustom_fauxton.svg    |   200 -
 share/www/fauxton/img/fontcustom_fauxton.ttf    |   Bin 9636 -> 0 bytes
 share/www/fauxton/img/fontcustom_fauxton.woff   |   Bin 4816 -> 0 bytes
 .../fauxton/img/glyphicons-halflings-white.png  |   Bin 8777 -> 0 bytes
 share/www/fauxton/img/glyphicons-halflings.png  |   Bin 13826 -> 0 bytes
 share/www/fauxton/img/linen.png                 |   Bin 87134 -> 0 bytes
 share/www/fauxton/img/loader.gif                |   Bin 5193 -> 0 bytes
 share/www/fauxton/img/minilogo.png              |   Bin 2927 -> 0 bytes
 share/www/fauxton/index.html                    |    45 -
 share/www/fauxton/js/ace/mode-javascript.js     |   886 -
 share/www/fauxton/js/ace/mode-json.js           |   578 -
 .../www/fauxton/js/ace/theme-crimson_editor.js  |   148 -
 share/www/fauxton/js/ace/worker-javascript.js   | 10088 ----------
 share/www/fauxton/js/ace/worker-json.js         |  2271 ---
 share/www/fauxton/js/require.js                 |    35 -
 share/www/favicon.ico                           |   Bin 9326 -> 0 bytes
 share/www/image/add.png                         |   Bin 709 -> 0 bytes
 share/www/image/apply.gif                       |   Bin 652 -> 0 bytes
 share/www/image/bg.png                          |   Bin 372 -> 0 bytes
 share/www/image/cancel.gif                      |   Bin 659 -> 0 bytes
 share/www/image/compact.png                     |   Bin 28735 -> 0 bytes
 share/www/image/delete-mini.png                 |   Bin 418 -> 0 bytes
 share/www/image/delete.png                      |   Bin 718 -> 0 bytes
 share/www/image/grippie.gif                     |   Bin 75 -> 0 bytes
 share/www/image/hgrad.gif                       |   Bin 118 -> 0 bytes
 share/www/image/key.png                         |   Bin 859 -> 0 bytes
 share/www/image/load.png                        |   Bin 780 -> 0 bytes
 share/www/image/logo.png                        |   Bin 3010 -> 0 bytes
 share/www/image/order-asc.gif                   |   Bin 195 -> 0 bytes
 share/www/image/order-desc.gif                  |   Bin 187 -> 0 bytes
 share/www/image/path.gif                        |   Bin 104 -> 0 bytes
 share/www/image/progress.gif                    |   Bin 10819 -> 0 bytes
 share/www/image/rarrow.png                      |   Bin 27721 -> 0 bytes
 share/www/image/run-mini.png                    |   Bin 478 -> 0 bytes
 share/www/image/run.png                         |   Bin 718 -> 0 bytes
 share/www/image/running.png                     |   Bin 284 -> 0 bytes
 share/www/image/save.png                        |   Bin 843 -> 0 bytes
 share/www/image/sidebar-toggle.png              |   Bin 512 -> 0 bytes
 share/www/image/spinner.gif                     |   Bin 3008 -> 0 bytes
 share/www/image/spinner_33.gif                  |   Bin 2987 -> 0 bytes
 share/www/image/spinner_6b.gif                  |   Bin 2969 -> 0 bytes
 share/www/image/test_failure.gif                |   Bin 114 -> 0 bytes
 share/www/image/test_success.gif                |   Bin 185 -> 0 bytes
 share/www/image/thead-key.gif                   |   Bin 77 -> 0 bytes
 share/www/image/thead.gif                       |   Bin 51 -> 0 bytes
 share/www/image/toggle-collapse.gif             |   Bin 176 -> 0 bytes
 share/www/image/toggle-expand.gif               |   Bin 181 -> 0 bytes
 share/www/image/twisty.gif                      |   Bin 160 -> 0 bytes
 share/www/index.html                            |    94 -
 share/www/plugins.html                          |   121 -
 share/www/replicator.html                       |   184 -
 share/www/script/base64.js                      |   124 -
 share/www/script/couch.js                       |   514 -
 share/www/script/couch_test_runner.js           |   472 -
 share/www/script/couch_tests.js                 |   114 -
 share/www/script/futon.browse.js                |  1344 --
 share/www/script/futon.format.js                |   146 -
 share/www/script/futon.js                       |   597 -
 share/www/script/jquery-ui-1.8.11.custom.min.js |    81 -
 share/www/script/jquery.couch.js                |  1078 --
 share/www/script/jquery.dialog.js               |    96 -
 share/www/script/jquery.editinline.js           |   114 -
 share/www/script/jquery.form.js                 |   803 -
 share/www/script/jquery.js                      |  9472 ----------
 share/www/script/jquery.resizer.js              |    84 -
 share/www/script/jquery.suggest.js              |   161 -
 share/www/script/json2.js                       |   482 -
 share/www/script/jspec/jspec.css                |   149 -
 share/www/script/jspec/jspec.jquery.js          |    72 -
 share/www/script/jspec/jspec.js                 |  1756 --
 share/www/script/jspec/jspec.xhr.js             |   195 -
 share/www/script/oauth.js                       |   511 -
 share/www/script/replicator_db_inc.js           |    96 -
 share/www/script/sha1.js                        |   202 -
 share/www/script/test/all_docs.js               |   142 -
 share/www/script/test/attachment_names.js       |    96 -
 share/www/script/test/attachment_paths.js       |   153 -
 share/www/script/test/attachment_ranges.js      |   160 -
 share/www/script/test/attachment_views.js       |   140 -
 share/www/script/test/attachments.js            |   328 -
 share/www/script/test/attachments_multipart.js  |   416 -
 share/www/script/test/auth_cache.js             |   277 -
 share/www/script/test/basics.js                 |   290 -
 share/www/script/test/batch_save.js             |    48 -
 share/www/script/test/bulk_docs.js              |   124 -
 share/www/script/test/changes.js                |   719 -
 share/www/script/test/coffee.js                 |    67 -
 share/www/script/test/compact.js                |    65 -
 share/www/script/test/config.js                 |   211 -
 share/www/script/test/conflicts.js              |   119 -
 share/www/script/test/content_negotiation.js    |    39 -
 share/www/script/test/cookie_auth.js            |   289 -
 share/www/script/test/copy_doc.js               |    65 -
 share/www/script/test/delayed_commits.js        |   154 -
 share/www/script/test/design_docs.js            |   466 -
 share/www/script/test/design_options.js         |    74 -
 share/www/script/test/design_paths.js           |    72 -
 share/www/script/test/erlang_views.js           |   133 -
 share/www/script/test/etags_head.js             |    78 -
 share/www/script/test/etags_views.js            |   220 -
 share/www/script/test/form_submit.js            |    25 -
 share/www/script/test/http.js                   |    54 -
 share/www/script/test/invalid_docids.js         |    77 -
 share/www/script/test/jsonp.js                  |    84 -
 share/www/script/test/large_docs.js             |    33 -
 share/www/script/test/list_views.js             |   492 -
 share/www/script/test/lorem.txt                 |   103 -
 share/www/script/test/lorem_b64.txt             |     1 -
 share/www/script/test/lots_of_docs.js           |    55 -
 share/www/script/test/method_override.js        |    40 -
 share/www/script/test/multiple_rows.js          |    80 -
 share/www/script/test/oauth.js                  |   293 -
 share/www/script/test/oauth_users_db.js         |   161 -
 share/www/script/test/proxyauth.js              |   129 -
 share/www/script/test/purge.js                  |   145 -
 share/www/script/test/reader_acl.js             |   219 -
 share/www/script/test/recreate_doc.js           |   145 -
 share/www/script/test/reduce.js                 |   414 -
 share/www/script/test/reduce_builtin.js         |   179 -
 share/www/script/test/reduce_false.js           |    44 -
 share/www/script/test/reduce_false_temp.js      |    37 -
 share/www/script/test/replication.js            |  1789 --
 .../www/script/test/replicator_db_bad_rep_id.js |    77 -
 .../www/script/test/replicator_db_by_doc_id.js  |    99 -
 .../script/test/replicator_db_compact_rep_db.js |   119 -
 .../www/script/test/replicator_db_continuous.js |   137 -
 .../test/replicator_db_credential_delegation.js |   149 -
 .../test/replicator_db_field_validation.js      |   178 -
 share/www/script/test/replicator_db_filtered.js |   105 -
 .../www/script/test/replicator_db_identical.js  |    87 -
 .../test/replicator_db_identical_continuous.js  |   132 -
 .../script/test/replicator_db_invalid_filter.js |   119 -
 share/www/script/test/replicator_db_security.js |   399 -
 share/www/script/test/replicator_db_simple.js   |   114 -
 .../www/script/test/replicator_db_successive.js |   127 -
 share/www/script/test/replicator_db_survives.js |   126 -
 .../script/test/replicator_db_swap_rep_db.js    |   170 -
 .../test/replicator_db_update_security.js       |    92 -
 share/www/script/test/replicator_db_user_ctx.js |   272 -
 .../www/script/test/replicator_db_write_auth.js |   102 -
 share/www/script/test/rev_stemming.js           |   110 -
 share/www/script/test/rewrite.js                |   494 -
 share/www/script/test/security_validation.js    |   336 -
 share/www/script/test/show_documents.js         |   420 -
 share/www/script/test/stats.js                  |   330 -
 share/www/script/test/update_documents.js       |   235 -
 share/www/script/test/users_db.js               |   173 -
 share/www/script/test/users_db_security.js      |   367 -
 share/www/script/test/utf8.js                   |    42 -
 share/www/script/test/uuids.js                  |   145 -
 share/www/script/test/view_collation.js         |   116 -
 share/www/script/test/view_collation_raw.js     |   130 -
 share/www/script/test/view_compaction.js        |   110 -
 share/www/script/test/view_conflicts.js         |    49 -
 share/www/script/test/view_errors.js            |   189 -
 share/www/script/test/view_include_docs.js      |   192 -
 .../www/script/test/view_multi_key_all_docs.js  |    95 -
 share/www/script/test/view_multi_key_design.js  |   220 -
 share/www/script/test/view_multi_key_temp.js    |    40 -
 share/www/script/test/view_offsets.js           |   108 -
 share/www/script/test/view_pagination.js        |   147 -
 share/www/script/test/view_sandboxing.js        |   140 -
 share/www/script/test/view_update_seq.js        |   106 -
 share/www/session.html                          |    96 -
 share/www/spec/couch_js_class_methods_spec.js   |   401 -
 .../spec/couch_js_instance_methods_1_spec.js    |   311 -
 .../spec/couch_js_instance_methods_2_spec.js    |   246 -
 .../spec/couch_js_instance_methods_3_spec.js    |   215 -
 share/www/spec/custom_helpers.js                |    51 -
 .../spec/jquery_couch_js_class_methods_spec.js  |   523 -
 .../jquery_couch_js_instance_methods_1_spec.js  |   202 -
 .../jquery_couch_js_instance_methods_2_spec.js  |   433 -
 .../jquery_couch_js_instance_methods_3_spec.js  |   540 -
 share/www/spec/run.html                         |    47 -
 share/www/status.html                           |   152 -
 share/www/style/jquery-ui-1.8.11.custom.css     |   347 -
 share/www/style/layout.css                      |   626 -
 share/www/verify_install.html                   |   119 -
 src/apps/couch/c_src/couch_js/help.h            |    82 +
 src/apps/couch/c_src/couch_js/http.c            |   696 +
 src/apps/couch/c_src/couch_js/http.h            |    27 +
 src/apps/couch/c_src/couch_js/main.c            |   431 +
 src/apps/couch/c_src/couch_js/utf8.c            |   288 +
 src/apps/couch/c_src/couch_js/utf8.h            |    19 +
 src/apps/couch/c_src/couch_js/util.c            |   288 +
 src/apps/couch/c_src/couch_js/util.h            |    35 +
 .../spawnkillable/couchspawnkillable_win.c      |   145 +
 src/apps/couch/include/couch_db.hrl             |   286 +
 src/apps/couch/priv/couchspawnkillable.sh       |    20 +
 src/apps/couch/priv/stat_descriptions.cfg       |    50 +
 src/apps/couch/rebar.config.script              |   108 +
 src/apps/couch/src/couch.app.src                |     0
 src/apps/couch/src/couch.app.src.script         |    67 +
 src/apps/couch/src/couch.erl                    |    67 +
 src/apps/couch/src/couch_app.erl                |    36 +
 src/apps/couch/src/couch_auth_cache.erl         |   425 +
 src/apps/couch/src/couch_btree.erl              |   714 +
 src/apps/couch/src/couch_changes.erl            |   577 +
 src/apps/couch/src/couch_compaction_daemon.erl  |   504 +
 src/apps/couch/src/couch_compress.erl           |    84 +
 src/apps/couch/src/couch_config.erl             |   251 +
 src/apps/couch/src/couch_config_writer.erl      |    88 +
 src/apps/couch/src/couch_db.erl                 |  1358 ++
 src/apps/couch/src/couch_db_update_notifier.erl |    82 +
 .../couch/src/couch_db_update_notifier_sup.erl  |    61 +
 src/apps/couch/src/couch_db_updater.erl         |  1035 ++
 src/apps/couch/src/couch_doc.erl                |   650 +
 src/apps/couch/src/couch_ejson_compare.erl      |    81 +
 src/apps/couch/src/couch_event_sup.erl          |    73 +
 src/apps/couch/src/couch_external_manager.erl   |   101 +
 src/apps/couch/src/couch_external_server.erl    |    70 +
 src/apps/couch/src/couch_file.erl               |   532 +
 src/apps/couch/src/couch_httpd.erl              |  1114 ++
 src/apps/couch/src/couch_httpd_auth.erl         |   380 +
 src/apps/couch/src/couch_httpd_cors.erl         |   351 +
 src/apps/couch/src/couch_httpd_db.erl           |  1226 ++
 src/apps/couch/src/couch_httpd_external.erl     |   177 +
 .../couch/src/couch_httpd_misc_handlers.erl     |   318 +
 src/apps/couch/src/couch_httpd_oauth.erl        |   387 +
 src/apps/couch/src/couch_httpd_proxy.erl        |   426 +
 src/apps/couch/src/couch_httpd_rewrite.erl      |   484 +
 .../couch/src/couch_httpd_stats_handlers.erl    |    56 +
 src/apps/couch/src/couch_httpd_vhost.erl        |   383 +
 src/apps/couch/src/couch_js_functions.hrl       |   170 +
 src/apps/couch/src/couch_key_tree.erl           |   422 +
 src/apps/couch/src/couch_log.erl                |   254 +
 src/apps/couch/src/couch_native_process.erl     |   409 +
 src/apps/couch/src/couch_os_daemons.erl         |   374 +
 src/apps/couch/src/couch_os_process.erl         |   216 +
 src/apps/couch/src/couch_passwords.erl          |   119 +
 src/apps/couch/src/couch_primary_sup.erl        |    48 +
 src/apps/couch/src/couch_query_servers.erl      |   616 +
 src/apps/couch/src/couch_ref_counter.erl        |   111 +
 src/apps/couch/src/couch_secondary_sup.erl      |    49 +
 src/apps/couch/src/couch_server.erl             |   493 +
 src/apps/couch/src/couch_server_sup.erl         |   164 +
 src/apps/couch/src/couch_stats_aggregator.erl   |   297 +
 src/apps/couch/src/couch_stats_collector.erl    |   136 +
 src/apps/couch/src/couch_stream.erl             |   299 +
 src/apps/couch/src/couch_task_status.erl        |   151 +
 src/apps/couch/src/couch_users_db.erl           |   121 +
 src/apps/couch/src/couch_util.erl               |   487 +
 src/apps/couch/src/couch_uuids.erl              |   103 +
 src/apps/couch/src/couch_work_queue.erl         |   187 +
 src/apps/couch/src/json_stream_parse.erl        |   432 +
 src/apps/couch_collate/c_src/couch_collate.c    |   281 +
 src/apps/couch_collate/rebar.config             |     9 +
 src/apps/couch_collate/rebar.config.script      |    46 +
 .../couch_collate/src/couch_collate.app.src     |    13 +
 src/apps/couch_collate/src/couch_collate.erl    |    62 +
 .../couch_dbupdates/src/couch_dbupdates.app.src |    11 +
 .../couch_dbupdates/src/couch_dbupdates.erl     |    46 +
 .../src/couch_dbupdates_httpd.erl               |    69 +
 src/apps/couch_index/src/couch_index.app.src    |    20 +
 src/apps/couch_index/src/couch_index.erl        |   338 +
 src/apps/couch_index/src/couch_index_api.erl    |    54 +
 src/apps/couch_index/src/couch_index_app.erl    |    27 +
 .../couch_index/src/couch_index_compactor.erl   |   113 +
 src/apps/couch_index/src/couch_index_server.erl |   201 +
 src/apps/couch_index/src/couch_index_sup.erl    |    30 +
 .../couch_index/src/couch_index_updater.erl     |   200 +
 src/apps/couch_index/src/couch_index_util.erl   |    77 +
 src/apps/couch_mrview/include/couch_mrview.hrl  |    81 +
 src/apps/couch_mrview/src/couch_mrview.app.src  |    28 +
 src/apps/couch_mrview/src/couch_mrview.erl      |   387 +
 .../couch_mrview/src/couch_mrview_cleanup.erl   |    45 +
 .../couch_mrview/src/couch_mrview_compactor.erl |   178 +
 src/apps/couch_mrview/src/couch_mrview_http.erl |   409 +
 .../couch_mrview/src/couch_mrview_index.erl     |   162 +
 src/apps/couch_mrview/src/couch_mrview_show.erl |   368 +
 .../couch_mrview/src/couch_mrview_test_util.erl |    92 +
 .../couch_mrview/src/couch_mrview_updater.erl   |   282 +
 src/apps/couch_mrview/src/couch_mrview_util.erl |   802 +
 src/apps/couch_mrview/test/01-load.t            |    34 +
 src/apps/couch_mrview/test/02-map-views.t       |   131 +
 src/apps/couch_mrview/test/03-red-views.t       |    78 +
 src/apps/couch_mrview/test/04-index-info.t      |    54 +
 src/apps/couch_mrview/test/05-collation.t       |   163 +
 src/apps/couch_mrview/test/06-all-docs.t        |   127 +
 src/apps/couch_mrview/test/07-compact-swap.t    |    57 +
 src/apps/couch_plugins/README.md                |   159 +
 .../couch_plugins/src/couch_plugins.app.src     |    23 +
 src/apps/couch_plugins/src/couch_plugins.erl    |   300 +
 .../couch_plugins/src/couch_plugins_httpd.erl   |    65 +
 src/apps/couch_rel/ebin/couch_rel.app           |    18 +
 src/apps/couch_rel/src/etop_txt.erl             |   134 +
 .../src/couch_replicator.app.src                |    28 +
 .../couch_replicator/src/couch_replicator.erl   |   965 +
 .../couch_replicator/src/couch_replicator.hrl   |    30 +
 .../src/couch_replicator_api_wrap.erl           |   877 +
 .../src/couch_replicator_api_wrap.hrl           |    36 +
 .../src/couch_replicator_app.erl                |    29 +
 .../src/couch_replicator_httpc.erl              |   297 +
 .../src/couch_replicator_httpc_pool.erl         |   138 +
 .../src/couch_replicator_httpd.erl              |    66 +
 .../src/couch_replicator_job_sup.erl            |    31 +
 .../src/couch_replicator_js_functions.hrl       |   151 +
 .../src/couch_replicator_manager.erl            |   709 +
 .../src/couch_replicator_manager_sup.erl        |    47 +
 .../src/couch_replicator_notifier.erl           |    57 +
 .../src/couch_replicator_sup.erl                |    59 +
 .../src/couch_replicator_utils.erl              |   396 +
 .../src/couch_replicator_worker.erl             |   515 +
 src/apps/couch_replicator/test/01-load.t        |    37 +
 src/apps/couch_replicator/test/02-httpc-pool.t  |   250 +
 .../test/03-replication-compact.t               |   488 +
 .../test/04-replication-large-atts.t            |   267 +
 .../test/05-replication-many-leaves.t           |   294 +
 .../test/06-doc-missing-stubs.t                 |   304 +
 .../couch_replicator/test/07-use-checkpoints.t  |   256 +
 src/apps/couchjs-node/README.md                 |    32 +
 src/apps/couchjs-node/cli.js                    |    89 +
 src/apps/couchjs-node/console.js                |    66 +
 src/apps/couchjs-node/couchdb.js                |    29 +
 src/apps/couchjs-node/couchjs.js                |   133 +
 src/apps/couchjs-node/inspector.js              |   101 +
 src/apps/couchjs-node/package.json              |    40 +
 src/apps/couchjs-node/sandbox.js                |    47 +
 src/apps/couchjs-node/stream.js                 |   115 +
 src/apps/couchjs-node/test/experiment.js        |   125 +
 src/apps/couchjs-node/xml.js                    |    22 +
 src/apps/fauxton/Gruntfile.js                   |   441 +
 src/apps/fauxton/TODO.md                        |    26 +
 .../activetasks/assets/less/activetasks.less    |    18 +
 src/apps/fauxton/app/addons/activetasks/base.js |    26 +
 .../fauxton/app/addons/activetasks/resources.js |   118 +
 .../fauxton/app/addons/activetasks/routes.js    |    58 +
 .../addons/activetasks/templates/detail.html    |    21 +
 .../app/addons/activetasks/templates/table.html |    52 +
 .../activetasks/templates/tabledetail.html      |    36 +
 .../app/addons/activetasks/templates/tabs.html  |    46 +
 .../app/addons/activetasks/tests/viewsSpec.js   |   139 +
 .../fauxton/app/addons/activetasks/views.js     |   181 +
 .../app/addons/auth/assets/less/auth.less       |    15 +
 src/apps/fauxton/app/addons/auth/base.js        |    69 +
 src/apps/fauxton/app/addons/auth/resources.js   |   364 +
 src/apps/fauxton/app/addons/auth/routes.js      |    93 +
 .../addons/auth/templates/change_password.html  |    26 +
 .../app/addons/auth/templates/create_admin.html |    37 +
 .../app/addons/auth/templates/login.html        |    26 +
 .../app/addons/auth/templates/nav_dropdown.html |    26 +
 .../addons/auth/templates/nav_link_title.html   |    31 +
 .../app/addons/auth/templates/noAccess.html     |    20 +
 .../compaction/assets/less/compaction.less      |    19 +
 src/apps/fauxton/app/addons/compaction/base.js  |    31 +
 .../fauxton/app/addons/compaction/resources.js  |    48 +
 .../fauxton/app/addons/compaction/routes.js     |    65 +
 .../compaction/templates/compact_view.html      |    14 +
 .../app/addons/compaction/templates/layout.html |    28 +
 src/apps/fauxton/app/addons/compaction/views.js |   140 +
 .../app/addons/config/assets/less/config.less   |    13 +
 src/apps/fauxton/app/addons/config/base.js      |    28 +
 src/apps/fauxton/app/addons/config/resources.js |   176 +
 src/apps/fauxton/app/addons/config/routes.js    |    59 +
 .../app/addons/config/templates/dashboard.html  |    52 +
 .../app/addons/config/templates/item.html       |    31 +
 src/apps/fauxton/app/addons/contribute/base.js  |    33 +
 src/apps/fauxton/app/addons/exampleAuth/base.js |    59 +
 .../addons/exampleAuth/templates/noAccess.html  |    19 +
 src/apps/fauxton/app/addons/logs/base.js        |    28 +
 src/apps/fauxton/app/addons/logs/resources.js   |   225 +
 src/apps/fauxton/app/addons/logs/routes.js      |    58 +
 .../app/addons/logs/templates/dashboard.html    |    46 +
 .../app/addons/logs/templates/filterItem.html   |    16 +
 .../app/addons/logs/templates/sidebar.html      |    27 +
 .../fauxton/app/addons/logs/tests/logSpec.js    |    38 +
 .../permissions/assets/less/permissions.less    |    44 +
 src/apps/fauxton/app/addons/permissions/base.js |    25 +
 .../fauxton/app/addons/permissions/resources.js |    70 +
 .../fauxton/app/addons/permissions/routes.js    |    63 +
 .../app/addons/permissions/templates/item.html  |    17 +
 .../permissions/templates/permissions.html      |    15 +
 .../addons/permissions/templates/section.html   |    46 +
 .../addons/permissions/tests/resourceSpec.js    |    51 +
 .../app/addons/permissions/tests/viewsSpec.js   |   159 +
 .../fauxton/app/addons/permissions/views.js     |   200 +
 src/apps/fauxton/app/addons/plugins/base.js     |    24 +
 .../fauxton/app/addons/plugins/resources.js     |    26 +
 src/apps/fauxton/app/addons/plugins/routes.js   |    47 +
 .../app/addons/plugins/templates/plugins.html   |   102 +
 .../replication/assets/less/replication.less    |   196 +
 src/apps/fauxton/app/addons/replication/base.js |    24 +
 .../fauxton/app/addons/replication/resources.js |    69 +
 .../fauxton/app/addons/replication/route.js     |    50 +
 .../app/addons/replication/templates/form.html  |    74 +
 .../addons/replication/templates/progress.html  |    22 +
 .../addons/replication/tests/replicationSpec.js |    28 +
 .../fauxton/app/addons/replication/views.js     |   295 +
 .../app/addons/stats/assets/less/stats.less     |    19 +
 src/apps/fauxton/app/addons/stats/base.js       |    26 +
 src/apps/fauxton/app/addons/stats/resources.js  |    38 +
 src/apps/fauxton/app/addons/stats/routes.js     |    63 +
 .../app/addons/stats/templates/by_method.html   |    16 +
 .../app/addons/stats/templates/pie_table.html   |    54 +
 .../app/addons/stats/templates/stats.html       |    16 +
 .../app/addons/stats/templates/statselect.html  |    22 +
 src/apps/fauxton/app/addons/stats/views.js      |   171 +
 .../assets/less/verifyinstall.less              |    16 +
 .../fauxton/app/addons/verifyinstall/base.js    |    31 +
 .../app/addons/verifyinstall/resources.js       |   181 +
 .../fauxton/app/addons/verifyinstall/routes.js  |    37 +
 .../addons/verifyinstall/templates/main.html    |    50 +
 .../fauxton/app/addons/verifyinstall/views.js   |   127 +
 src/apps/fauxton/app/api.js                     |   558 +
 src/apps/fauxton/app/app.js                     |   122 +
 src/apps/fauxton/app/config.js                  |    60 +
 src/apps/fauxton/app/helpers.js                 |    78 +
 src/apps/fauxton/app/initialize.js.underscore   |    33 +
 src/apps/fauxton/app/load_addons.js.underscore  |    27 +
 src/apps/fauxton/app/main.js                    |    48 +
 src/apps/fauxton/app/mixins.js                  |    65 +
 src/apps/fauxton/app/modules/databases/base.js  |    37 +
 .../fauxton/app/modules/databases/resources.js  |   193 +
 .../fauxton/app/modules/databases/routes.js     |    69 +
 src/apps/fauxton/app/modules/databases/views.js |   255 +
 src/apps/fauxton/app/modules/documents/base.js  |    24 +
 .../fauxton/app/modules/documents/resources.js  |   638 +
 .../fauxton/app/modules/documents/routes.js     |   408 +
 .../modules/documents/tests/resourcesSpec.js    |    84 +
 src/apps/fauxton/app/modules/documents/views.js |  1805 ++
 src/apps/fauxton/app/modules/fauxton/base.js    |   276 +
 .../fauxton/app/modules/fauxton/components.js   |   316 +
 src/apps/fauxton/app/modules/fauxton/layout.js  |    98 +
 src/apps/fauxton/app/modules/pouchdb/base.js    |    47 +
 .../app/modules/pouchdb/pouch.collate.js        |   115 +
 .../app/modules/pouchdb/pouchdb.mapreduce.js    |   324 +
 src/apps/fauxton/app/resizeColumns.js           |    87 +
 src/apps/fauxton/app/router.js                  |   175 +
 .../fauxton/app/templates/databases/item.html   |    24 +
 .../fauxton/app/templates/databases/list.html   |    35 +
 .../app/templates/databases/newdatabase.html    |    17 +
 .../app/templates/databases/sidebar.html        |    31 +
 .../templates/documents/advanced_options.html   |    97 +
 .../app/templates/documents/all_docs_item.html  |    26 +
 .../templates/documents/all_docs_layout.html    |    20 +
 .../app/templates/documents/all_docs_list.html  |    43 +
 .../templates/documents/all_docs_number.html    |    21 +
 .../app/templates/documents/changes.html        |    38 +
 .../app/templates/documents/ddoc_info.html      |    28 +
 .../documents/design_doc_selector.html          |    35 +
 .../fauxton/app/templates/documents/doc.html    |    55 +
 .../templates/documents/doc_field_editor.html   |    74 +
 .../documents/doc_field_editor_tabs.html        |    19 +
 .../documents/duplicate_doc_modal.html          |    36 +
 .../app/templates/documents/edit_tools.html     |    44 +
 .../templates/documents/index_menu_item.html    |    17 +
 .../templates/documents/index_row_docular.html  |    26 +
 .../templates/documents/index_row_tabular.html  |    25 +
 .../app/templates/documents/jumpdoc.html        |    19 +
 .../fauxton/app/templates/documents/search.html |    15 +
 .../app/templates/documents/sidebar.html        |    67 +
 .../fauxton/app/templates/documents/tabs.html   |    18 +
 .../app/templates/documents/upload_modal.html   |    42 +
 .../app/templates/documents/view_editor.html    |    87 +
 .../fauxton/app/templates/fauxton/api_bar.html  |    30 +
 .../app/templates/fauxton/breadcrumbs.html      |    24 +
 .../fauxton/app/templates/fauxton/footer.html   |    15 +
 .../app/templates/fauxton/index_pagination.html |    24 +
 .../fauxton/app/templates/fauxton/nav_bar.html  |    75 +
 .../app/templates/fauxton/notification.html     |    18 +
 .../app/templates/fauxton/pagination.html       |    31 +
 .../fauxton/app/templates/layouts/one_pane.html |    28 +
 .../app/templates/layouts/one_pane_notabs.html  |    27 +
 .../fauxton/app/templates/layouts/two_pane.html |    30 +
 .../templates/layouts/with_right_sidebar.html   |    26 +
 .../app/templates/layouts/with_sidebar.html     |    27 +
 .../app/templates/layouts/with_tabs.html        |    28 +
 .../templates/layouts/with_tabs_sidebar.html    |    41 +
 src/apps/fauxton/assets/css/nv.d3.css           |   656 +
 src/apps/fauxton/assets/img/FontAwesome.otf     |   Bin 0 -> 61896 bytes
 src/apps/fauxton/assets/img/couchdb-site.png    |   Bin 0 -> 4946 bytes
 src/apps/fauxton/assets/img/couchdblogo.png     |   Bin 0 -> 2738 bytes
 .../fauxton/assets/img/fontawesome-webfont.eot  |   Bin 0 -> 37405 bytes
 .../fauxton/assets/img/fontawesome-webfont.svg  |   399 +
 .../fauxton/assets/img/fontawesome-webfont.ttf  |   Bin 0 -> 79076 bytes
 .../fauxton/assets/img/fontawesome-webfont.woff |   Bin 0 -> 43572 bytes
 .../fauxton/assets/img/fontcustom_fauxton.eot   |   Bin 0 -> 7364 bytes
 .../fauxton/assets/img/fontcustom_fauxton.svg   |   200 +
 .../fauxton/assets/img/fontcustom_fauxton.ttf   |   Bin 0 -> 9636 bytes
 .../fauxton/assets/img/fontcustom_fauxton.woff  |   Bin 0 -> 4816 bytes
 .../assets/img/glyphicons-halflings-white.png   |   Bin 0 -> 8777 bytes
 .../fauxton/assets/img/glyphicons-halflings.png |   Bin 0 -> 13826 bytes
 src/apps/fauxton/assets/img/linen.png           |   Bin 0 -> 87134 bytes
 src/apps/fauxton/assets/img/loader.gif          |   Bin 0 -> 5193 bytes
 src/apps/fauxton/assets/img/minilogo.png        |   Bin 0 -> 2927 bytes
 src/apps/fauxton/assets/index.underscore        |    47 +
 src/apps/fauxton/assets/js/libs/ace/ace.js      | 16541 +++++++++++++++++
 .../fauxton/assets/js/libs/ace/ext-chromevox.js |   537 +
 .../js/libs/ace/ext-elastic_tabstops_lite.js    |   301 +
 .../fauxton/assets/js/libs/ace/ext-emmet.js     |  1096 ++
 .../assets/js/libs/ace/ext-keybinding_menu.js   |   207 +
 .../assets/js/libs/ace/ext-language_tools.js    |  1615 ++
 .../fauxton/assets/js/libs/ace/ext-modelist.js  |   166 +
 .../fauxton/assets/js/libs/ace/ext-old_ie.js    |   499 +
 .../fauxton/assets/js/libs/ace/ext-options.js   |   252 +
 .../fauxton/assets/js/libs/ace/ext-searchbox.js |   420 +
 .../assets/js/libs/ace/ext-settings_menu.js     |   634 +
 .../assets/js/libs/ace/ext-spellcheck.js        |    68 +
 .../fauxton/assets/js/libs/ace/ext-split.js     |   271 +
 .../assets/js/libs/ace/ext-static_highlight.js  |   165 +
 .../fauxton/assets/js/libs/ace/ext-statusbar.js |    47 +
 .../fauxton/assets/js/libs/ace/ext-textarea.js  |   478 +
 .../fauxton/assets/js/libs/ace/ext-themelist.js |    90 +
 .../assets/js/libs/ace/ext-whitespace.js        |   206 +
 .../assets/js/libs/ace/mode-javascript.js       |   886 +
 .../fauxton/assets/js/libs/ace/mode-json.js     |   578 +
 .../fauxton/assets/js/libs/ace/mode-jsoniq.js   |  2714 +++
 .../assets/js/libs/ace/snippets/javascript.js   |   202 +
 .../fauxton/assets/js/libs/ace/snippets/json.js |     7 +
 .../assets/js/libs/ace/snippets/jsoniq.js       |     7 +
 .../assets/js/libs/ace/theme-crimson_editor.js  |   148 +
 .../assets/js/libs/ace/worker-javascript.js     | 10088 ++++++++++
 .../fauxton/assets/js/libs/ace/worker-json.js   |  2271 +++
 src/apps/fauxton/assets/js/libs/almond.js       |   314 +
 src/apps/fauxton/assets/js/libs/backbone.js     |  1571 ++
 src/apps/fauxton/assets/js/libs/bootstrap.js    |  2291 +++
 src/apps/fauxton/assets/js/libs/d3.js           |  7026 +++++++
 src/apps/fauxton/assets/js/libs/jquery.js       |  9789 ++++++++++
 src/apps/fauxton/assets/js/libs/lodash.js       |  4493 +++++
 src/apps/fauxton/assets/js/libs/nv.d3.js        | 13119 +++++++++++++
 src/apps/fauxton/assets/js/libs/require.js      |  2045 ++
 src/apps/fauxton/assets/js/libs/spin.min.js     |     1 +
 .../assets/js/plugins/backbone.layoutmanager.js |   996 +
 .../fauxton/assets/js/plugins/jquery.form.js    |  1190 ++
 src/apps/fauxton/assets/js/plugins/prettify.js  |    28 +
 .../assets/less/bootstrap/accordion.less        |    34 +
 .../fauxton/assets/less/bootstrap/alerts.less   |    79 +
 .../assets/less/bootstrap/bootstrap.less        |    63 +
 .../assets/less/bootstrap/breadcrumbs.less      |    24 +
 .../assets/less/bootstrap/button-groups.less    |   229 +
 .../fauxton/assets/less/bootstrap/buttons.less  |   228 +
 .../fauxton/assets/less/bootstrap/carousel.less |   158 +
 .../fauxton/assets/less/bootstrap/close.less    |    32 +
 .../fauxton/assets/less/bootstrap/code.less     |    61 +
 .../less/bootstrap/component-animations.less    |    22 +
 .../assets/less/bootstrap/dropdowns.less        |   248 +
 .../less/bootstrap/font-awesome/bootstrap.less  |    84 +
 .../less/bootstrap/font-awesome/core.less       |   129 +
 .../less/bootstrap/font-awesome/extras.less     |    93 +
 .../font-awesome/font-awesome-ie7.less          |  1953 ++
 .../bootstrap/font-awesome/font-awesome.less    |    33 +
 .../less/bootstrap/font-awesome/icons.less      |   381 +
 .../less/bootstrap/font-awesome/mixins.less     |    48 +
 .../less/bootstrap/font-awesome/path.less       |    14 +
 .../less/bootstrap/font-awesome/variables.less  |   735 +
 .../fauxton/assets/less/bootstrap/forms.less    |   690 +
 .../fauxton/assets/less/bootstrap/grid.less     |    21 +
 .../assets/less/bootstrap/hero-unit.less        |    25 +
 .../assets/less/bootstrap/labels-badges.less    |    84 +
 .../fauxton/assets/less/bootstrap/layouts.less  |    16 +
 .../fauxton/assets/less/bootstrap/media.less    |    55 +
 .../fauxton/assets/less/bootstrap/mixins.less   |   716 +
 .../fauxton/assets/less/bootstrap/modals.less   |    95 +
 .../fauxton/assets/less/bootstrap/navbar.less   |   497 +
 .../fauxton/assets/less/bootstrap/navs.less     |   409 +
 .../fauxton/assets/less/bootstrap/pager.less    |    43 +
 .../assets/less/bootstrap/pagination.less       |   123 +
 .../fauxton/assets/less/bootstrap/popovers.less |   133 +
 .../assets/less/bootstrap/progress-bars.less    |   122 +
 .../fauxton/assets/less/bootstrap/reset.less    |   216 +
 .../less/bootstrap/responsive-1200px-min.less   |    28 +
 .../less/bootstrap/responsive-767px-max.less    |   193 +
 .../less/bootstrap/responsive-768px-979px.less  |    19 +
 .../less/bootstrap/responsive-navbar.less       |   189 +
 .../less/bootstrap/responsive-utilities.less    |    59 +
 .../assets/less/bootstrap/responsive.less       |    48 +
 .../assets/less/bootstrap/scaffolding.less      |    53 +
 .../fauxton/assets/less/bootstrap/sprites.less  |   197 +
 .../fauxton/assets/less/bootstrap/tables.less   |   244 +
 .../assets/less/bootstrap/tests/buttons.html    |   139 +
 .../assets/less/bootstrap/tests/css-tests.css   |   150 +
 .../assets/less/bootstrap/thumbnails.less       |    53 +
 .../fauxton/assets/less/bootstrap/tooltip.less  |    70 +
 .../fauxton/assets/less/bootstrap/type.less     |   247 +
 .../assets/less/bootstrap/utilities.less        |    30 +
 .../assets/less/bootstrap/variables.less        |   301 +
 .../fauxton/assets/less/bootstrap/wells.less    |    29 +
 src/apps/fauxton/assets/less/config.less        |    46 +
 src/apps/fauxton/assets/less/couchdb.less       |    72 +
 src/apps/fauxton/assets/less/database.less      |   245 +
 src/apps/fauxton/assets/less/fauxton.less       |  1009 +
 src/apps/fauxton/assets/less/icons.less         |   111 +
 src/apps/fauxton/assets/less/logs.less          |    24 +
 src/apps/fauxton/assets/less/prettyprint.less   |    46 +
 src/apps/fauxton/assets/less/variables.less     |    82 +
 src/apps/fauxton/bin/grunt                      |    18 +
 src/apps/fauxton/couchapp.js                    |    39 +
 src/apps/fauxton/extensions.md                  |    17 +
 src/apps/fauxton/favicon.ico                    |   Bin 0 -> 1150 bytes
 src/apps/fauxton/index.html                     |    53 +
 src/apps/fauxton/package.json                   |    48 +
 src/apps/fauxton/readme.md                      |    79 +
 src/apps/fauxton/settings.json.default          |    55 +
 src/apps/fauxton/settings.json.sample_external  |    10 +
 src/apps/fauxton/tasks/addon/rename.json        |     5 +
 .../fauxton/tasks/addon/root/base.js.underscore |    21 +
 .../tasks/addon/root/resources.js.underscore    |    21 +
 .../tasks/addon/root/routes.js.underscore       |    42 +
 src/apps/fauxton/tasks/addon/template.js        |    70 +
 src/apps/fauxton/tasks/couchserver.js           |   104 +
 src/apps/fauxton/tasks/fauxton.js               |   137 +
 src/apps/fauxton/tasks/helper.js                |    45 +
 src/apps/fauxton/test/core/layoutSpec.js        |    94 +
 src/apps/fauxton/test/core/navbarSpec.js        |   107 +
 src/apps/fauxton/test/core/paginateSpec.js      |   109 +
 src/apps/fauxton/test/core/routeObjectSpec.js   |   105 +
 src/apps/fauxton/test/mocha/chai.js             |  4330 +++++
 src/apps/fauxton/test/mocha/mocha.css           |   251 +
 src/apps/fauxton/test/mocha/mocha.js            |  5428 ++++++
 src/apps/fauxton/test/mocha/sinon-chai.js       |   109 +
 src/apps/fauxton/test/mocha/sinon.js            |  4290 +++++
 src/apps/fauxton/test/mocha/testUtils.js        |    50 +
 src/apps/fauxton/test/runner.html               |    33 +
 src/apps/fauxton/test/test.config.underscore    |    15 +
 src/apps/fauxton/writing_addons.md              |   173 +
 src/etc/couchdb/Makefile.am                     |    95 +
 src/etc/couchdb/app.config                      |    30 +
 src/etc/couchdb/couch.ini                       |   350 +
 src/etc/couchdb/empty                           |     0
 src/etc/couchdb/local.ini                       |    97 +
 src/etc/couchdb/vm.args                         |    24 +
 src/etc/windows/Makefile.am                     |    13 +
 src/etc/windows/README.txt.tpl                  |    29 +
 src/etc/windows/couchdb.iss.tpl                 |    92 +
 src/share/Makefile.am                           |   260 +
 src/share/doc/Makefile.am                       |    14 +
 src/share/doc/build/Makefile.am                 |   626 +
 src/share/doc/ext/configdomain.py               |   127 +
 src/share/doc/ext/github.py                     |    44 +
 src/share/doc/ext/httpdomain.py                 |   656 +
 src/share/doc/images/epub-icon.png              |   Bin 0 -> 19185 bytes
 src/share/doc/images/favicon.ico                |   Bin 0 -> 9326 bytes
 src/share/doc/images/futon-createdb.png         |   Bin 0 -> 76194 bytes
 src/share/doc/images/futon-editdoc.png          |   Bin 0 -> 52733 bytes
 src/share/doc/images/futon-editeddoc.png        |   Bin 0 -> 56005 bytes
 src/share/doc/images/futon-overview.png         |   Bin 0 -> 50815 bytes
 src/share/doc/images/futon-replform.png         |   Bin 0 -> 52223 bytes
 src/share/doc/images/intro-consistency-01.png   |   Bin 0 -> 35605 bytes
 src/share/doc/images/intro-consistency-02.png   |   Bin 0 -> 48145 bytes
 src/share/doc/images/intro-consistency-03.png   |   Bin 0 -> 17333 bytes
 src/share/doc/images/intro-consistency-04.png   |   Bin 0 -> 13744 bytes
 src/share/doc/images/intro-consistency-05.png   |   Bin 0 -> 25592 bytes
 src/share/doc/images/intro-consistency-06.png   |   Bin 0 -> 56651 bytes
 src/share/doc/images/intro-consistency-07.png   |   Bin 0 -> 53634 bytes
 src/share/doc/images/intro-tour-01.png          |   Bin 0 -> 50815 bytes
 src/share/doc/images/intro-tour-02.png          |   Bin 0 -> 83380 bytes
 src/share/doc/images/intro-tour-03.png          |   Bin 0 -> 53795 bytes
 src/share/doc/images/intro-tour-04.png          |   Bin 0 -> 56470 bytes
 src/share/doc/images/intro-tour-05.png          |   Bin 0 -> 53778 bytes
 src/share/doc/images/intro-tour-06.png          |   Bin 0 -> 61296 bytes
 src/share/doc/images/intro-tour-07.png          |   Bin 0 -> 67121 bytes
 src/share/doc/images/intro-tour-08.png          |   Bin 0 -> 83494 bytes
 src/share/doc/images/intro-tour-09.png          |   Bin 0 -> 84701 bytes
 src/share/doc/images/intro-tour-10.png          |   Bin 0 -> 61631 bytes
 src/share/doc/images/intro-why-01.png           |   Bin 0 -> 25755 bytes
 src/share/doc/images/intro-why-02.png           |   Bin 0 -> 5937 bytes
 src/share/doc/images/intro-why-03.png           |   Bin 0 -> 5134 bytes
 src/share/doc/images/logo.png                   |   Bin 0 -> 13195 bytes
 src/share/doc/images/views-intro-01.png         |   Bin 0 -> 1026767 bytes
 src/share/doc/images/views-intro-02.png         |   Bin 0 -> 9758 bytes
 src/share/doc/images/views-intro-03.png         |   Bin 0 -> 12650 bytes
 src/share/doc/images/views-intro-04.png         |   Bin 0 -> 14537 bytes
 src/share/doc/src/about.rst                     |    25 +
 src/share/doc/src/api/basics.rst                |   601 +
 src/share/doc/src/api/database/bulk-api.rst     |   646 +
 src/share/doc/src/api/database/changes.rst      |   574 +
 src/share/doc/src/api/database/common.rst       |   430 +
 src/share/doc/src/api/database/compact.rst      |   243 +
 src/share/doc/src/api/database/index.rst        |    47 +
 src/share/doc/src/api/database/misc.rst         |   351 +
 src/share/doc/src/api/database/security.rst     |   182 +
 src/share/doc/src/api/database/temp-views.rst   |    79 +
 src/share/doc/src/api/ddoc/common.rst           |   226 +
 src/share/doc/src/api/ddoc/index.rst            |    37 +
 src/share/doc/src/api/ddoc/render.rst           |   390 +
 src/share/doc/src/api/ddoc/rewrites.rst         |    90 +
 src/share/doc/src/api/ddoc/views.rst            |   797 +
 src/share/doc/src/api/document/attachments.rst  |   318 +
 src/share/doc/src/api/document/common.rst       |  1201 ++
 src/share/doc/src/api/document/index.rst        |    25 +
 src/share/doc/src/api/index.rst                 |    42 +
 src/share/doc/src/api/local.rst                 |    84 +
 src/share/doc/src/api/server/authn.rst          |   452 +
 src/share/doc/src/api/server/common.rst         |  1012 +
 src/share/doc/src/api/server/configuration.rst  |   336 +
 src/share/doc/src/api/server/index.rst          |    28 +
 src/share/doc/src/conf.py                       |   158 +
 src/share/doc/src/config/auth.rst               |   360 +
 src/share/doc/src/config/compaction.rst         |   174 +
 src/share/doc/src/config/couchdb.rst            |   200 +
 src/share/doc/src/config/externals.rst          |   179 +
 src/share/doc/src/config/http-handlers.rst      |   291 +
 src/share/doc/src/config/http.rst               |   593 +
 src/share/doc/src/config/index.rst              |    34 +
 src/share/doc/src/config/intro.rst              |   172 +
 src/share/doc/src/config/logging.rst            |    94 +
 src/share/doc/src/config/misc.rst               |   223 +
 src/share/doc/src/config/proxying.rst           |    98 +
 src/share/doc/src/config/query-servers.rst      |   161 +
 src/share/doc/src/config/replicator.rst         |   200 +
 src/share/doc/src/config/services.rst           |   150 +
 src/share/doc/src/contents.rst                  |    40 +
 src/share/doc/src/contributing.rst              |   167 +
 src/share/doc/src/couchapp/ddocs.rst            |   768 +
 src/share/doc/src/couchapp/index.rst            |    31 +
 src/share/doc/src/couchapp/views/collation.rst  |   256 +
 src/share/doc/src/couchapp/views/index.rst      |    30 +
 src/share/doc/src/couchapp/views/intro.rst      |   675 +
 src/share/doc/src/couchapp/views/joins.rst      |   430 +
 src/share/doc/src/couchapp/views/nosql.rst      |   530 +
 src/share/doc/src/couchapp/views/pagination.rst |   287 +
 src/share/doc/src/cve/2010-0009.rst             |    54 +
 src/share/doc/src/cve/2010-2234.rst             |    64 +
 src/share/doc/src/cve/2010-3854.rst             |    57 +
 src/share/doc/src/cve/2012-5641.rst             |    77 +
 src/share/doc/src/cve/2012-5649.rst             |    50 +
 src/share/doc/src/cve/2012-5650.rst             |    69 +
 src/share/doc/src/cve/index.rst                 |    73 +
 src/share/doc/src/experimental.rst              |    83 +
 src/share/doc/src/externals.rst                 |   261 +
 src/share/doc/src/fauxton/addons.rst            |   199 +
 src/share/doc/src/fauxton/index.rst             |    23 +
 src/share/doc/src/fauxton/install.rst           |   109 +
 src/share/doc/src/install/freebsd.rst           |    80 +
 src/share/doc/src/install/index.rst             |    26 +
 src/share/doc/src/install/mac.rst               |   194 +
 src/share/doc/src/install/unix.rst              |   269 +
 src/share/doc/src/install/windows.rst           |   275 +
 src/share/doc/src/intro/api.rst                 |   783 +
 src/share/doc/src/intro/consistency.rst         |   465 +
 src/share/doc/src/intro/curl.rst                |   122 +
 src/share/doc/src/intro/futon.rst               |   186 +
 src/share/doc/src/intro/index.rst               |    56 +
 src/share/doc/src/intro/overview.rst            |   387 +
 src/share/doc/src/intro/security.rst            |   525 +
 src/share/doc/src/intro/tour.rst                |   542 +
 src/share/doc/src/intro/why.rst                 |   315 +
 src/share/doc/src/json-structure.rst            |   641 +
 src/share/doc/src/maintenance/compaction.rst    |   193 +
 src/share/doc/src/maintenance/index.rst         |    21 +
 src/share/doc/src/maintenance/performance.rst   |   293 +
 src/share/doc/src/query-server/erlang.rst       |   139 +
 src/share/doc/src/query-server/index.rst        |    40 +
 src/share/doc/src/query-server/javascript.rst   |   288 +
 src/share/doc/src/query-server/protocol.rst     |   967 +
 src/share/doc/src/replication/conflicts.rst     |   793 +
 src/share/doc/src/replication/index.rst         |    37 +
 src/share/doc/src/replication/intro.rst         |    95 +
 src/share/doc/src/replication/protocol.rst      |   202 +
 src/share/doc/src/replication/replicator.rst    |   405 +
 src/share/doc/src/whatsnew/0.10.rst             |   150 +
 src/share/doc/src/whatsnew/0.11.rst             |   357 +
 src/share/doc/src/whatsnew/0.8.rst              |   178 +
 src/share/doc/src/whatsnew/0.9.rst              |   262 +
 src/share/doc/src/whatsnew/1.0.rst              |   277 +
 src/share/doc/src/whatsnew/1.1.rst              |   175 +
 src/share/doc/src/whatsnew/1.2.rst              |   242 +
 src/share/doc/src/whatsnew/1.3.rst              |   256 +
 src/share/doc/src/whatsnew/1.4.rst              |    61 +
 src/share/doc/src/whatsnew/1.5.rst              |    48 +
 src/share/doc/src/whatsnew/1.6.rst              |    53 +
 src/share/doc/src/whatsnew/index.rst            |    33 +
 src/share/doc/static/rtd.css                    |   795 +
 .../doc/templates/couchdb/domainindex.html      |    49 +
 src/share/doc/templates/couchdb/theme.conf      |    13 +
 src/share/doc/templates/help.html               |    33 +
 src/share/doc/templates/layout.html             |    27 +
 src/share/doc/templates/pages/download.html     |    48 +
 src/share/doc/templates/pages/index.html        |   175 +
 src/share/doc/templates/searchbox.html          |    31 +
 src/share/doc/templates/utilities.html          |    22 +
 src/share/server/coffee-script.js               |     8 +
 src/share/server/filter.js                      |    45 +
 src/share/server/json2.js                       |   482 +
 src/share/server/loop.js                        |   167 +
 src/share/server/mimeparse.js                   |   158 +
 src/share/server/render.js                      |   369 +
 src/share/server/state.js                       |    32 +
 src/share/server/util.js                        |   166 +
 src/share/server/validate.js                    |    25 +
 src/share/server/views.js                       |   127 +
 src/share/www/_sidebar.html                     |    67 +
 src/share/www/config.html                       |   135 +
 src/share/www/couch_tests.html                  |    98 +
 src/share/www/custom_test.html                  |   112 +
 src/share/www/database.html                     |   270 +
 src/share/www/dialog/_admin_party.html          |    33 +
 src/share/www/dialog/_change_password.html      |    31 +
 src/share/www/dialog/_compact_cleanup.html      |    51 +
 src/share/www/dialog/_create_admin.html         |    50 +
 src/share/www/dialog/_create_config.html        |    42 +
 src/share/www/dialog/_create_database.html      |    33 +
 src/share/www/dialog/_database_security.html    |    50 +
 src/share/www/dialog/_delete_database.html      |    29 +
 src/share/www/dialog/_delete_document.html      |    26 +
 src/share/www/dialog/_login.html                |    34 +
 src/share/www/dialog/_save_view_as.html         |    35 +
 src/share/www/dialog/_share_test_reports.html   |    42 +
 src/share/www/dialog/_signup.html               |    35 +
 src/share/www/dialog/_upload_attachment.html    |    36 +
 src/share/www/document.html                     |   114 +
 src/share/www/fauxton/css/index.css             |    37 +
 src/share/www/fauxton/img/FontAwesome.otf       |   Bin 0 -> 61896 bytes
 src/share/www/fauxton/img/couchdb-site.png      |   Bin 0 -> 4946 bytes
 src/share/www/fauxton/img/couchdblogo.png       |   Bin 0 -> 2738 bytes
 .../www/fauxton/img/fontawesome-webfont.eot     |   Bin 0 -> 37405 bytes
 .../www/fauxton/img/fontawesome-webfont.svg     |   399 +
 .../www/fauxton/img/fontawesome-webfont.ttf     |   Bin 0 -> 79076 bytes
 .../www/fauxton/img/fontawesome-webfont.woff    |   Bin 0 -> 43572 bytes
 .../www/fauxton/img/fontcustom_fauxton.eot      |   Bin 0 -> 7364 bytes
 .../www/fauxton/img/fontcustom_fauxton.svg      |   200 +
 .../www/fauxton/img/fontcustom_fauxton.ttf      |   Bin 0 -> 9636 bytes
 .../www/fauxton/img/fontcustom_fauxton.woff     |   Bin 0 -> 4816 bytes
 .../fauxton/img/glyphicons-halflings-white.png  |   Bin 0 -> 8777 bytes
 .../www/fauxton/img/glyphicons-halflings.png    |   Bin 0 -> 13826 bytes
 src/share/www/fauxton/img/linen.png             |   Bin 0 -> 87134 bytes
 src/share/www/fauxton/img/loader.gif            |   Bin 0 -> 5193 bytes
 src/share/www/fauxton/img/minilogo.png          |   Bin 0 -> 2927 bytes
 src/share/www/fauxton/index.html                |    45 +
 src/share/www/fauxton/js/ace/mode-javascript.js |   886 +
 src/share/www/fauxton/js/ace/mode-json.js       |   578 +
 .../www/fauxton/js/ace/theme-crimson_editor.js  |   148 +
 .../www/fauxton/js/ace/worker-javascript.js     | 10088 ++++++++++
 src/share/www/fauxton/js/ace/worker-json.js     |  2271 +++
 src/share/www/fauxton/js/require.js             |    35 +
 src/share/www/favicon.ico                       |   Bin 0 -> 9326 bytes
 src/share/www/image/add.png                     |   Bin 0 -> 709 bytes
 src/share/www/image/apply.gif                   |   Bin 0 -> 652 bytes
 src/share/www/image/bg.png                      |   Bin 0 -> 372 bytes
 src/share/www/image/cancel.gif                  |   Bin 0 -> 659 bytes
 src/share/www/image/compact.png                 |   Bin 0 -> 28735 bytes
 src/share/www/image/delete-mini.png             |   Bin 0 -> 418 bytes
 src/share/www/image/delete.png                  |   Bin 0 -> 718 bytes
 src/share/www/image/grippie.gif                 |   Bin 0 -> 75 bytes
 src/share/www/image/hgrad.gif                   |   Bin 0 -> 118 bytes
 src/share/www/image/key.png                     |   Bin 0 -> 859 bytes
 src/share/www/image/load.png                    |   Bin 0 -> 780 bytes
 src/share/www/image/logo.png                    |   Bin 0 -> 3010 bytes
 src/share/www/image/order-asc.gif               |   Bin 0 -> 195 bytes
 src/share/www/image/order-desc.gif              |   Bin 0 -> 187 bytes
 src/share/www/image/path.gif                    |   Bin 0 -> 104 bytes
 src/share/www/image/progress.gif                |   Bin 0 -> 10819 bytes
 src/share/www/image/rarrow.png                  |   Bin 0 -> 27721 bytes
 src/share/www/image/run-mini.png                |   Bin 0 -> 478 bytes
 src/share/www/image/run.png                     |   Bin 0 -> 718 bytes
 src/share/www/image/running.png                 |   Bin 0 -> 284 bytes
 src/share/www/image/save.png                    |   Bin 0 -> 843 bytes
 src/share/www/image/sidebar-toggle.png          |   Bin 0 -> 512 bytes
 src/share/www/image/spinner.gif                 |   Bin 0 -> 3008 bytes
 src/share/www/image/spinner_33.gif              |   Bin 0 -> 2987 bytes
 src/share/www/image/spinner_6b.gif              |   Bin 0 -> 2969 bytes
 src/share/www/image/test_failure.gif            |   Bin 0 -> 114 bytes
 src/share/www/image/test_success.gif            |   Bin 0 -> 185 bytes
 src/share/www/image/thead-key.gif               |   Bin 0 -> 77 bytes
 src/share/www/image/thead.gif                   |   Bin 0 -> 51 bytes
 src/share/www/image/toggle-collapse.gif         |   Bin 0 -> 176 bytes
 src/share/www/image/toggle-expand.gif           |   Bin 0 -> 181 bytes
 src/share/www/image/twisty.gif                  |   Bin 0 -> 160 bytes
 src/share/www/index.html                        |    94 +
 src/share/www/plugins.html                      |   121 +
 src/share/www/replicator.html                   |   184 +
 src/share/www/script/base64.js                  |   124 +
 src/share/www/script/couch.js                   |   514 +
 src/share/www/script/couch_test_runner.js       |   472 +
 src/share/www/script/couch_tests.js             |   114 +
 src/share/www/script/futon.browse.js            |  1344 ++
 src/share/www/script/futon.format.js            |   146 +
 src/share/www/script/futon.js                   |   597 +
 .../www/script/jquery-ui-1.8.11.custom.min.js   |    81 +
 src/share/www/script/jquery.couch.js            |  1078 ++
 src/share/www/script/jquery.dialog.js           |    96 +
 src/share/www/script/jquery.editinline.js       |   114 +
 src/share/www/script/jquery.form.js             |   803 +
 src/share/www/script/jquery.js                  |  9472 ++++++++++
 src/share/www/script/jquery.resizer.js          |    84 +
 src/share/www/script/jquery.suggest.js          |   161 +
 src/share/www/script/json2.js                   |   482 +
 src/share/www/script/jspec/jspec.css            |   149 +
 src/share/www/script/jspec/jspec.jquery.js      |    72 +
 src/share/www/script/jspec/jspec.js             |  1756 ++
 src/share/www/script/jspec/jspec.xhr.js         |   195 +
 src/share/www/script/oauth.js                   |   511 +
 src/share/www/script/replicator_db_inc.js       |    96 +
 src/share/www/script/sha1.js                    |   202 +
 src/share/www/script/test/all_docs.js           |   142 +
 src/share/www/script/test/attachment_names.js   |    96 +
 src/share/www/script/test/attachment_paths.js   |   153 +
 src/share/www/script/test/attachment_ranges.js  |   160 +
 src/share/www/script/test/attachment_views.js   |   140 +
 src/share/www/script/test/attachments.js        |   328 +
 .../www/script/test/attachments_multipart.js    |   416 +
 src/share/www/script/test/auth_cache.js         |   277 +
 src/share/www/script/test/basics.js             |   290 +
 src/share/www/script/test/batch_save.js         |    48 +
 src/share/www/script/test/bulk_docs.js          |   124 +
 src/share/www/script/test/changes.js            |   719 +
 src/share/www/script/test/coffee.js             |    67 +
 src/share/www/script/test/compact.js            |    65 +
 src/share/www/script/test/config.js             |   211 +
 src/share/www/script/test/conflicts.js          |   119 +
 .../www/script/test/content_negotiation.js      |    39 +
 src/share/www/script/test/cookie_auth.js        |   289 +
 src/share/www/script/test/copy_doc.js           |    65 +
 src/share/www/script/test/delayed_commits.js    |   154 +
 src/share/www/script/test/design_docs.js        |   466 +
 src/share/www/script/test/design_options.js     |    74 +
 src/share/www/script/test/design_paths.js       |    72 +
 src/share/www/script/test/erlang_views.js       |   133 +
 src/share/www/script/test/etags_head.js         |    78 +
 src/share/www/script/test/etags_views.js        |   220 +
 src/share/www/script/test/form_submit.js        |    25 +
 src/share/www/script/test/http.js               |    54 +
 src/share/www/script/test/invalid_docids.js     |    77 +
 src/share/www/script/test/jsonp.js              |    84 +
 src/share/www/script/test/large_docs.js         |    33 +
 src/share/www/script/test/list_views.js         |   492 +
 src/share/www/script/test/lorem.txt             |   103 +
 src/share/www/script/test/lorem_b64.txt         |     1 +
 src/share/www/script/test/lots_of_docs.js       |    55 +
 src/share/www/script/test/method_override.js    |    40 +
 src/share/www/script/test/multiple_rows.js      |    80 +
 src/share/www/script/test/oauth.js              |   293 +
 src/share/www/script/test/oauth_users_db.js     |   161 +
 src/share/www/script/test/proxyauth.js          |   129 +
 src/share/www/script/test/purge.js              |   145 +
 src/share/www/script/test/reader_acl.js         |   219 +
 src/share/www/script/test/recreate_doc.js       |   145 +
 src/share/www/script/test/reduce.js             |   414 +
 src/share/www/script/test/reduce_builtin.js     |   179 +
 src/share/www/script/test/reduce_false.js       |    44 +
 src/share/www/script/test/reduce_false_temp.js  |    37 +
 src/share/www/script/test/replication.js        |  1789 ++
 .../www/script/test/replicator_db_bad_rep_id.js |    77 +
 .../www/script/test/replicator_db_by_doc_id.js  |    99 +
 .../script/test/replicator_db_compact_rep_db.js |   119 +
 .../www/script/test/replicator_db_continuous.js |   137 +
 .../test/replicator_db_credential_delegation.js |   149 +
 .../test/replicator_db_field_validation.js      |   178 +
 .../www/script/test/replicator_db_filtered.js   |   105 +
 .../www/script/test/replicator_db_identical.js  |    87 +
 .../test/replicator_db_identical_continuous.js  |   132 +
 .../script/test/replicator_db_invalid_filter.js |   119 +
 .../www/script/test/replicator_db_security.js   |   399 +
 .../www/script/test/replicator_db_simple.js     |   114 +
 .../www/script/test/replicator_db_successive.js |   127 +
 .../www/script/test/replicator_db_survives.js   |   126 +
 .../script/test/replicator_db_swap_rep_db.js    |   170 +
 .../test/replicator_db_update_security.js       |    92 +
 .../www/script/test/replicator_db_user_ctx.js   |   272 +
 .../www/script/test/replicator_db_write_auth.js |   102 +
 src/share/www/script/test/rev_stemming.js       |   110 +
 src/share/www/script/test/rewrite.js            |   494 +
 .../www/script/test/security_validation.js      |   336 +
 src/share/www/script/test/show_documents.js     |   420 +
 src/share/www/script/test/stats.js              |   330 +
 src/share/www/script/test/update_documents.js   |   235 +
 src/share/www/script/test/users_db.js           |   173 +
 src/share/www/script/test/users_db_security.js  |   367 +
 src/share/www/script/test/utf8.js               |    42 +
 src/share/www/script/test/uuids.js              |   145 +
 src/share/www/script/test/view_collation.js     |   116 +
 src/share/www/script/test/view_collation_raw.js |   130 +
 src/share/www/script/test/view_compaction.js    |   110 +
 src/share/www/script/test/view_conflicts.js     |    49 +
 src/share/www/script/test/view_errors.js        |   189 +
 src/share/www/script/test/view_include_docs.js  |   192 +
 .../www/script/test/view_multi_key_all_docs.js  |    95 +
 .../www/script/test/view_multi_key_design.js    |   220 +
 .../www/script/test/view_multi_key_temp.js      |    40 +
 src/share/www/script/test/view_offsets.js       |   108 +
 src/share/www/script/test/view_pagination.js    |   147 +
 src/share/www/script/test/view_sandboxing.js    |   140 +
 src/share/www/script/test/view_update_seq.js    |   106 +
 src/share/www/session.html                      |    96 +
 .../www/spec/couch_js_class_methods_spec.js     |   401 +
 .../spec/couch_js_instance_methods_1_spec.js    |   311 +
 .../spec/couch_js_instance_methods_2_spec.js    |   246 +
 .../spec/couch_js_instance_methods_3_spec.js    |   215 +
 src/share/www/spec/custom_helpers.js            |    51 +
 .../spec/jquery_couch_js_class_methods_spec.js  |   523 +
 .../jquery_couch_js_instance_methods_1_spec.js  |   202 +
 .../jquery_couch_js_instance_methods_2_spec.js  |   433 +
 .../jquery_couch_js_instance_methods_3_spec.js  |   540 +
 src/share/www/spec/run.html                     |    47 +
 src/share/www/status.html                       |   152 +
 src/share/www/style/jquery-ui-1.8.11.custom.css |   347 +
 src/share/www/style/layout.css                  |   626 +
 src/share/www/verify_install.html               |   119 +
 src/support/README.md                           |    12 +
 src/support/build_js.escript                    |    55 +
 src/support/rebar/CONTRIBUTING.md               |    94 +
 src/support/rebar/LICENSE                       |   178 +
 src/support/rebar/NOTES.org                     |    28 +
 src/support/rebar/README.md                     |    79 +
 src/support/rebar/bootstrap                     |   119 +
 src/support/rebar/bootstrap.bat                 |     2 +
 src/support/rebar/dialyzer_reference            |     3 +
 src/support/rebar/ebin/rebar.app                |    93 +
 src/support/rebar/include/rebar.hrl             |    14 +
 src/support/rebar/inttest/bug_5_rt.erl          |    29 +
 src/support/rebar/inttest/ct1/ct1_rt.erl        |    28 +
 src/support/rebar/inttest/ct1/rebar.config      |     1 +
 src/support/rebar/inttest/ct1/test_SUITE.erl    |    11 +
 src/support/rebar/inttest/ct2/ct2_rt.erl        |    26 +
 src/support/rebar/inttest/ct2/foo.test.spec     |     1 +
 src/support/rebar/inttest/ct2/foo_SUITE.erl     |    10 +
 .../rebar/inttest/depplugins/depplugins_rt.erl  |    50 +
 .../rebar/inttest/depplugins/rebar.config       |     1 +
 .../depplugins/rebar_dependsonplugin.config     |     2 +
 .../rebar/inttest/depplugins/testplugin_mod.erl |     6 +
 .../rebar/inttest/logging/logging_rt.erl        |    99 +
 src/support/rebar/inttest/rgen1/reltool.config  |    31 +
 src/support/rebar/inttest/rgen1/retest.config   |     1 +
 src/support/rebar/inttest/rgen1/rgen1_rt.erl    |    18 +
 src/support/rebar/inttest/rgen1/test.config     |     1 +
 src/support/rebar/inttest/rgen1/vars.config     |     1 +
 .../rebar/inttest/t_custom_config/custom.config |     4 +
 .../inttest/t_custom_config/custom_config.erl   |     6 +
 .../t_custom_config/t_custom_config_rt.erl      |    39 +
 src/support/rebar/inttest/tdeps1/a.erl          |     8 +
 src/support/rebar/inttest/tdeps1/a.rebar.config |     1 +
 src/support/rebar/inttest/tdeps1/b.hrl          |     1 +
 src/support/rebar/inttest/tdeps1/b.rebar.config |     1 +
 src/support/rebar/inttest/tdeps1/c.hrl          |     1 +
 src/support/rebar/inttest/tdeps1/tdeps1_rt.erl  |    59 +
 src/support/rebar/inttest/tdeps2/a.erl          |     3 +
 src/support/rebar/inttest/tdeps2/a.rebar.config |     1 +
 src/support/rebar/inttest/tdeps2/b.hrl          |     1 +
 src/support/rebar/inttest/tdeps2/b.rebar.config |     1 +
 src/support/rebar/inttest/tdeps2/c.hrl          |     1 +
 .../rebar/inttest/tdeps2/root.rebar.config      |     2 +
 src/support/rebar/inttest/tdeps2/tdeps2_rt.erl  |    65 +
 src/support/rebar/inttest/tdeps3/a.erl          |     3 +
 src/support/rebar/inttest/tdeps3/a.rebar.config |     4 +
 src/support/rebar/inttest/tdeps3/b.hrl          |     1 +
 src/support/rebar/inttest/tdeps3/b.rebar.config |     5 +
 src/support/rebar/inttest/tdeps3/c.hrl          |     1 +
 src/support/rebar/inttest/tdeps3/c.rebar.config |     1 +
 src/support/rebar/inttest/tdeps3/d.hrl          |     1 +
 src/support/rebar/inttest/tdeps3/d.rebar.config |     1 +
 src/support/rebar/inttest/tdeps3/e.hrl          |     1 +
 src/support/rebar/inttest/tdeps3/f.hrl          |     1 +
 .../rebar/inttest/tdeps3/root.rebar.config      |     1 +
 src/support/rebar/inttest/tdeps3/tdeps3_rt.erl  |    89 +
 src/support/rebar/inttest/tdeps_update/a.erl    |     3 +
 .../rebar/inttest/tdeps_update/a.rebar.config   |     1 +
 .../rebar/inttest/tdeps_update/a2.rebar.config  |     1 +
 .../rebar/inttest/tdeps_update/a3.rebar.config  |     1 +
 .../rebar/inttest/tdeps_update/a4.rebar.config  |     4 +
 src/support/rebar/inttest/tdeps_update/b.hrl    |     1 +
 .../rebar/inttest/tdeps_update/b.rebar.config   |     1 +
 .../rebar/inttest/tdeps_update/b2.rebar.config  |     1 +
 .../rebar/inttest/tdeps_update/b3.rebar.config  |     1 +
 .../rebar/inttest/tdeps_update/b4.rebar.config  |     1 +
 src/support/rebar/inttest/tdeps_update/c.hrl    |     1 +
 .../rebar/inttest/tdeps_update/c.rebar.config   |     1 +
 src/support/rebar/inttest/tdeps_update/c2.hrl   |     1 +
 .../rebar/inttest/tdeps_update/c2.rebar.config  |     4 +
 .../rebar/inttest/tdeps_update/c3.rebar.config  |     4 +
 src/support/rebar/inttest/tdeps_update/d.hrl    |     1 +
 .../inttest/tdeps_update/root.rebar.config      |     1 +
 .../inttest/tdeps_update/tdeps_update_rt.erl    |   147 +
 src/support/rebar/inttest/thooks/fish.erl       |     5 +
 src/support/rebar/inttest/thooks/rebar.config   |     7 +
 src/support/rebar/inttest/thooks/thooks_rt.erl  |    40 +
 src/support/rebar/inttest/tplugins/bad.config   |     2 +
 .../rebar/inttest/tplugins/bad_plugin.erl       |     7 +
 src/support/rebar/inttest/tplugins/fish.erl     |     5 +
 src/support/rebar/inttest/tplugins/rebar.config |     1 +
 .../rebar/inttest/tplugins/test_plugin.erl      |     8 +
 .../rebar/inttest/tplugins/tplugins_rt.erl      |    40 +
 .../rebar/priv/shell-completion/zsh/_rebar      |    84 +
 src/support/rebar/priv/templates/basicnif.c     |    59 +
 src/support/rebar/priv/templates/basicnif.erl   |    42 +
 .../rebar/priv/templates/basicnif.template      |     3 +
 src/support/rebar/priv/templates/ctsuite.erl    |   167 +
 .../rebar/priv/templates/ctsuite.template       |     2 +
 .../rebar/priv/templates/simpleapp.app.src      |    12 +
 .../rebar/priv/templates/simpleapp.template     |     4 +
 .../rebar/priv/templates/simpleapp_app.erl      |    16 +
 .../rebar/priv/templates/simpleapp_sup.erl      |    27 +
 src/support/rebar/priv/templates/simplefsm.erl  |    57 +
 .../rebar/priv/templates/simplefsm.template     |     2 +
 .../rebar/priv/templates/simplelib.app.src      |    14 +
 src/support/rebar/priv/templates/simplelib.erl  |    18 +
 .../rebar/priv/templates/simplelib.template     |     3 +
 src/support/rebar/priv/templates/simplemod.erl  |     6 +
 .../rebar/priv/templates/simplemod.template     |     3 +
 .../rebar/priv/templates/simplemod_tests.erl    |     3 +
 .../rebar/priv/templates/simplenode.erl.script  |    44 +
 .../simplenode.install_upgrade.escript          |    44 +
 .../rebar/priv/templates/simplenode.nodetool    |   182 +
 .../priv/templates/simplenode.reltool.config    |    44 +
 .../rebar/priv/templates/simplenode.runner      |   348 +
 .../rebar/priv/templates/simplenode.sys.config  |    11 +
 .../rebar/priv/templates/simplenode.template    |    13 +
 .../rebar/priv/templates/simplenode.vm.args     |    19 +
 .../templates/simplenode.windows.runner.cmd     |   103 +
 .../templates/simplenode.windows.start_erl.cmd  |    40 +
 src/support/rebar/priv/templates/simplesrv.erl  |    50 +
 .../rebar/priv/templates/simplesrv.template     |     2 +
 src/support/rebar/rebar.config                  |    21 +
 src/support/rebar/rebar.config.sample           |   236 +
 src/support/rebar/rebar.config.script           |    17 +
 src/support/rebar/src/getopt.erl                |   842 +
 src/support/rebar/src/mustache.erl              |   228 +
 src/support/rebar/src/rebar.erl                 |   517 +
 src/support/rebar/src/rebar_abnfc_compiler.erl  |   123 +
 src/support/rebar/src/rebar_app_utils.erl       |   208 +
 src/support/rebar/src/rebar_appups.erl          |   210 +
 src/support/rebar/src/rebar_asn1_compiler.erl   |   100 +
 src/support/rebar/src/rebar_base_compiler.erl   |   260 +
 src/support/rebar/src/rebar_cleaner.erl         |    56 +
 src/support/rebar/src/rebar_config.erl          |   244 +
 src/support/rebar/src/rebar_core.erl            |   608 +
 src/support/rebar/src/rebar_ct.erl              |   350 +
 src/support/rebar/src/rebar_deps.erl            |   774 +
 src/support/rebar/src/rebar_dia_compiler.erl    |   106 +
 src/support/rebar/src/rebar_edoc.erl            |   130 +
 src/support/rebar/src/rebar_erlc_compiler.erl   |   511 +
 .../rebar/src/rebar_erlydtl_compiler.erl        |   265 +
 src/support/rebar/src/rebar_escripter.erl       |   197 +
 src/support/rebar/src/rebar_eunit.erl           |   812 +
 src/support/rebar/src/rebar_file_utils.erl      |   194 +
 src/support/rebar/src/rebar_lfe_compiler.erl    |    84 +
 src/support/rebar/src/rebar_log.erl             |    96 +
 .../rebar/src/rebar_neotoma_compiler.erl        |   163 +
 src/support/rebar/src/rebar_otp_app.erl         |   220 +
 src/support/rebar/src/rebar_port_compiler.erl   |   607 +
 .../rebar/src/rebar_protobuffs_compiler.erl     |   153 +
 src/support/rebar/src/rebar_qc.erl              |   187 +
 src/support/rebar/src/rebar_rel_utils.erl       |   238 +
 src/support/rebar/src/rebar_reltool.erl         |   408 +
 src/support/rebar/src/rebar_require_vsn.erl     |   121 +
 src/support/rebar/src/rebar_shell.erl           |    56 +
 src/support/rebar/src/rebar_subdirs.erl         |    84 +
 src/support/rebar/src/rebar_templater.erl       |   473 +
 src/support/rebar/src/rebar_upgrade.erl         |   268 +
 src/support/rebar/src/rebar_utils.erl           |   510 +
 src/support/rebar/src/rebar_xref.erl            |   287 +
 src/support/rebar/test/rebar_eunit_tests.erl    |   434 +
 .../rebar/test/rebar_file_utils_tests.erl       |   278 +
 src/support/rebar/test/rebar_xref_eunit.erl     |   203 +
 .../rebar/test/upgrade_project/README.md        |    40 +
 .../apps/dummy/src/dummy.app.src                |     9 +
 .../apps/dummy/src/dummy_app.erl                |     9 +
 .../apps/dummy/src/dummy_server.erl             |    56 +
 .../apps/dummy/src/dummy_sup.erl                |    15 +
 .../rebar/test/upgrade_project/rebar.config     |     4 +
 .../rebar/test/upgrade_project/rel/files/dummy  |   347 +
 .../rebar/test/upgrade_project/rel/files/erl    |    44 +
 .../test/upgrade_project/rel/files/nodetool     |   182 +
 .../test/upgrade_project/rel/files/sys.config   |    11 +
 .../test/upgrade_project/rel/files/vm.args      |    19 +
 .../test/upgrade_project/rel/reltool.config     |    27 +
 support/README.md                               |    12 -
 support/build_js.escript                        |    55 -
 support/rebar/CONTRIBUTING.md                   |    94 -
 support/rebar/LICENSE                           |   178 -
 support/rebar/NOTES.org                         |    28 -
 support/rebar/README.md                         |    79 -
 support/rebar/bootstrap                         |   119 -
 support/rebar/bootstrap.bat                     |     2 -
 support/rebar/dialyzer_reference                |     3 -
 support/rebar/ebin/rebar.app                    |    93 -
 support/rebar/include/rebar.hrl                 |    14 -
 support/rebar/inttest/bug_5_rt.erl              |    29 -
 support/rebar/inttest/ct1/ct1_rt.erl            |    28 -
 support/rebar/inttest/ct1/rebar.config          |     1 -
 support/rebar/inttest/ct1/test_SUITE.erl        |    11 -
 support/rebar/inttest/ct2/ct2_rt.erl            |    26 -
 support/rebar/inttest/ct2/foo.test.spec         |     1 -
 support/rebar/inttest/ct2/foo_SUITE.erl         |    10 -
 .../rebar/inttest/depplugins/depplugins_rt.erl  |    50 -
 support/rebar/inttest/depplugins/rebar.config   |     1 -
 .../depplugins/rebar_dependsonplugin.config     |     2 -
 .../rebar/inttest/depplugins/testplugin_mod.erl |     6 -
 support/rebar/inttest/logging/logging_rt.erl    |    99 -
 support/rebar/inttest/rgen1/reltool.config      |    31 -
 support/rebar/inttest/rgen1/retest.config       |     1 -
 support/rebar/inttest/rgen1/rgen1_rt.erl        |    18 -
 support/rebar/inttest/rgen1/test.config         |     1 -
 support/rebar/inttest/rgen1/vars.config         |     1 -
 .../rebar/inttest/t_custom_config/custom.config |     4 -
 .../inttest/t_custom_config/custom_config.erl   |     6 -
 .../t_custom_config/t_custom_config_rt.erl      |    39 -
 support/rebar/inttest/tdeps1/a.erl              |     8 -
 support/rebar/inttest/tdeps1/a.rebar.config     |     1 -
 support/rebar/inttest/tdeps1/b.hrl              |     1 -
 support/rebar/inttest/tdeps1/b.rebar.config     |     1 -
 support/rebar/inttest/tdeps1/c.hrl              |     1 -
 support/rebar/inttest/tdeps1/tdeps1_rt.erl      |    59 -
 support/rebar/inttest/tdeps2/a.erl              |     3 -
 support/rebar/inttest/tdeps2/a.rebar.config     |     1 -
 support/rebar/inttest/tdeps2/b.hrl              |     1 -
 support/rebar/inttest/tdeps2/b.rebar.config     |     1 -
 support/rebar/inttest/tdeps2/c.hrl              |     1 -
 support/rebar/inttest/tdeps2/root.rebar.config  |     2 -
 support/rebar/inttest/tdeps2/tdeps2_rt.erl      |    65 -
 support/rebar/inttest/tdeps3/a.erl              |     3 -
 support/rebar/inttest/tdeps3/a.rebar.config     |     4 -
 support/rebar/inttest/tdeps3/b.hrl              |     1 -
 support/rebar/inttest/tdeps3/b.rebar.config     |     5 -
 support/rebar/inttest/tdeps3/c.hrl              |     1 -
 support/rebar/inttest/tdeps3/c.rebar.config     |     1 -
 support/rebar/inttest/tdeps3/d.hrl              |     1 -
 support/rebar/inttest/tdeps3/d.rebar.config     |     1 -
 support/rebar/inttest/tdeps3/e.hrl              |     1 -
 support/rebar/inttest/tdeps3/f.hrl              |     1 -
 support/rebar/inttest/tdeps3/root.rebar.config  |     1 -
 support/rebar/inttest/tdeps3/tdeps3_rt.erl      |    89 -
 support/rebar/inttest/tdeps_update/a.erl        |     3 -
 .../rebar/inttest/tdeps_update/a.rebar.config   |     1 -
 .../rebar/inttest/tdeps_update/a2.rebar.config  |     1 -
 .../rebar/inttest/tdeps_update/a3.rebar.config  |     1 -
 .../rebar/inttest/tdeps_update/a4.rebar.config  |     4 -
 support/rebar/inttest/tdeps_update/b.hrl        |     1 -
 .../rebar/inttest/tdeps_update/b.rebar.config   |     1 -
 .../rebar/inttest/tdeps_update/b2.rebar.config  |     1 -
 .../rebar/inttest/tdeps_update/b3.rebar.config  |     1 -
 .../rebar/inttest/tdeps_update/b4.rebar.config  |     1 -
 support/rebar/inttest/tdeps_update/c.hrl        |     1 -
 .../rebar/inttest/tdeps_update/c.rebar.config   |     1 -
 support/rebar/inttest/tdeps_update/c2.hrl       |     1 -
 .../rebar/inttest/tdeps_update/c2.rebar.config  |     4 -
 .../rebar/inttest/tdeps_update/c3.rebar.config  |     4 -
 support/rebar/inttest/tdeps_update/d.hrl        |     1 -
 .../inttest/tdeps_update/root.rebar.config      |     1 -
 .../inttest/tdeps_update/tdeps_update_rt.erl    |   147 -
 support/rebar/inttest/thooks/fish.erl           |     5 -
 support/rebar/inttest/thooks/rebar.config       |     7 -
 support/rebar/inttest/thooks/thooks_rt.erl      |    40 -
 support/rebar/inttest/tplugins/bad.config       |     2 -
 support/rebar/inttest/tplugins/bad_plugin.erl   |     7 -
 support/rebar/inttest/tplugins/fish.erl         |     5 -
 support/rebar/inttest/tplugins/rebar.config     |     1 -
 support/rebar/inttest/tplugins/test_plugin.erl  |     8 -
 support/rebar/inttest/tplugins/tplugins_rt.erl  |    40 -
 support/rebar/priv/shell-completion/zsh/_rebar  |    84 -
 support/rebar/priv/templates/basicnif.c         |    59 -
 support/rebar/priv/templates/basicnif.erl       |    42 -
 support/rebar/priv/templates/basicnif.template  |     3 -
 support/rebar/priv/templates/ctsuite.erl        |   167 -
 support/rebar/priv/templates/ctsuite.template   |     2 -
 support/rebar/priv/templates/simpleapp.app.src  |    12 -
 support/rebar/priv/templates/simpleapp.template |     4 -
 support/rebar/priv/templates/simpleapp_app.erl  |    16 -
 support/rebar/priv/templates/simpleapp_sup.erl  |    27 -
 support/rebar/priv/templates/simplefsm.erl      |    57 -
 support/rebar/priv/templates/simplefsm.template |     2 -
 support/rebar/priv/templates/simplelib.app.src  |    14 -
 support/rebar/priv/templates/simplelib.erl      |    18 -
 support/rebar/priv/templates/simplelib.template |     3 -
 support/rebar/priv/templates/simplemod.erl      |     6 -
 support/rebar/priv/templates/simplemod.template |     3 -
 .../rebar/priv/templates/simplemod_tests.erl    |     3 -
 .../rebar/priv/templates/simplenode.erl.script  |    44 -
 .../simplenode.install_upgrade.escript          |    44 -
 .../rebar/priv/templates/simplenode.nodetool    |   182 -
 .../priv/templates/simplenode.reltool.config    |    44 -
 support/rebar/priv/templates/simplenode.runner  |   348 -
 .../rebar/priv/templates/simplenode.sys.config  |    11 -
 .../rebar/priv/templates/simplenode.template    |    13 -
 support/rebar/priv/templates/simplenode.vm.args |    19 -
 .../templates/simplenode.windows.runner.cmd     |   103 -
 .../templates/simplenode.windows.start_erl.cmd  |    40 -
 support/rebar/priv/templates/simplesrv.erl      |    50 -
 support/rebar/priv/templates/simplesrv.template |     2 -
 support/rebar/rebar.config                      |    21 -
 support/rebar/rebar.config.sample               |   236 -
 support/rebar/rebar.config.script               |    17 -
 support/rebar/src/getopt.erl                    |   842 -
 support/rebar/src/mustache.erl                  |   228 -
 support/rebar/src/rebar.erl                     |   517 -
 support/rebar/src/rebar_abnfc_compiler.erl      |   123 -
 support/rebar/src/rebar_app_utils.erl           |   208 -
 support/rebar/src/rebar_appups.erl              |   210 -
 support/rebar/src/rebar_asn1_compiler.erl       |   100 -
 support/rebar/src/rebar_base_compiler.erl       |   260 -
 support/rebar/src/rebar_cleaner.erl             |    56 -
 support/rebar/src/rebar_config.erl              |   244 -
 support/rebar/src/rebar_core.erl                |   608 -
 support/rebar/src/rebar_ct.erl                  |   350 -
 support/rebar/src/rebar_deps.erl                |   774 -
 support/rebar/src/rebar_dia_compiler.erl        |   106 -
 support/rebar/src/rebar_edoc.erl                |   130 -
 support/rebar/src/rebar_erlc_compiler.erl       |   511 -
 support/rebar/src/rebar_erlydtl_compiler.erl    |   265 -
 support/rebar/src/rebar_escripter.erl           |   197 -
 support/rebar/src/rebar_eunit.erl               |   812 -
 support/rebar/src/rebar_file_utils.erl          |   194 -
 support/rebar/src/rebar_lfe_compiler.erl        |    84 -
 support/rebar/src/rebar_log.erl                 |    96 -
 support/rebar/src/rebar_neotoma_compiler.erl    |   163 -
 support/rebar/src/rebar_otp_app.erl             |   220 -
 support/rebar/src/rebar_port_compiler.erl       |   607 -
 support/rebar/src/rebar_protobuffs_compiler.erl |   153 -
 support/rebar/src/rebar_qc.erl                  |   187 -
 support/rebar/src/rebar_rel_utils.erl           |   238 -
 support/rebar/src/rebar_reltool.erl             |   408 -
 support/rebar/src/rebar_require_vsn.erl         |   121 -
 support/rebar/src/rebar_shell.erl               |    56 -
 support/rebar/src/rebar_subdirs.erl             |    84 -
 support/rebar/src/rebar_templater.erl           |   473 -
 support/rebar/src/rebar_upgrade.erl             |   268 -
 support/rebar/src/rebar_utils.erl               |   510 -
 support/rebar/src/rebar_xref.erl                |   287 -
 support/rebar/test/rebar_eunit_tests.erl        |   434 -
 support/rebar/test/rebar_file_utils_tests.erl   |   278 -
 support/rebar/test/rebar_xref_eunit.erl         |   203 -
 support/rebar/test/upgrade_project/README.md    |    40 -
 .../apps/dummy/src/dummy.app.src                |     9 -
 .../apps/dummy/src/dummy_app.erl                |     9 -
 .../apps/dummy/src/dummy_server.erl             |    56 -
 .../apps/dummy/src/dummy_sup.erl                |    15 -
 support/rebar/test/upgrade_project/rebar.config |     4 -
 .../rebar/test/upgrade_project/rel/files/dummy  |   347 -
 .../rebar/test/upgrade_project/rel/files/erl    |    44 -
 .../test/upgrade_project/rel/files/nodetool     |   182 -
 .../test/upgrade_project/rel/files/sys.config   |    11 -
 .../test/upgrade_project/rel/files/vm.args      |    19 -
 .../test/upgrade_project/rel/reltool.config     |    27 -
 1966 files changed, 261058 insertions(+), 261430 deletions(-)
----------------------------------------------------------------------



[58/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/urep.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/urep.h b/src/apps/couch_collate/platform/osx/icu/unicode/urep.h
new file mode 100644
index 0000000..57b547c
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/urep.h
@@ -0,0 +1,155 @@
+/*
+******************************************************************************
+*   Copyright (C) 1997-2005, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+******************************************************************************
+*   Date        Name        Description
+*   06/23/00    aliu        Creation.
+******************************************************************************
+*/
+
+#ifndef __UREP_H
+#define __UREP_H
+
+#include "unicode/utypes.h"
+
+U_CDECL_BEGIN
+
+/********************************************************************
+ * General Notes
+ ********************************************************************
+ * TODO
+ * Add usage scenario
+ * Add test code
+ * Talk about pinning
+ * Talk about "can truncate result if out of memory"
+ */
+
+/********************************************************************
+ * Data Structures
+ ********************************************************************/
+/**
+ * \file
+ * \brief C API: Callbacks for UReplacebale
+ */
+/**
+ * An opaque replaceable text object.  This will be manipulated only
+ * through the caller-supplied UReplaceableFunctor struct.  Related
+ * to the C++ class Replaceable.
+ * This is currently only used in the Transliterator C API, see utrans.h .
+ * @stable ICU 2.0
+ */
+typedef void* UReplaceable;
+
+/**
+ * A set of function pointers that transliterators use to manipulate a
+ * UReplaceable.  The caller should supply the required functions to
+ * manipulate their text appropriately.  Related to the C++ class
+ * Replaceable.
+ * @stable ICU 2.0
+ */
+typedef struct UReplaceableCallbacks {
+
+    /**
+     * Function pointer that returns the number of UChar code units in
+     * this text.
+     *
+     * @param rep A pointer to "this" UReplaceable object.
+     * @return The length of the text.
+     * @stable ICU 2.0
+     */
+    int32_t (*length)(const UReplaceable* rep);
+
+    /**
+     * Function pointer that returns a UChar code units at the given
+     * offset into this text; 0 <= offset < n, where n is the value
+     * returned by (*length)(rep).  See unistr.h for a description of
+     * charAt() vs. char32At().
+     *
+     * @param rep A pointer to "this" UReplaceable object.
+     * @param offset The index at which to fetch the UChar (code unit).
+     * @return The UChar (code unit) at offset, or U+FFFF if the offset is out of bounds.
+     * @stable ICU 2.0
+     */
+    UChar   (*charAt)(const UReplaceable* rep,
+                      int32_t offset);
+
+    /**
+     * Function pointer that returns a UChar32 code point at the given
+     * offset into this text.  See unistr.h for a description of
+     * charAt() vs. char32At().
+     *
+     * @param rep A pointer to "this" UReplaceable object.
+     * @param offset The index at which to fetch the UChar32 (code point).
+     * @return The UChar32 (code point) at offset, or U+FFFF if the offset is out of bounds.
+     * @stable ICU 2.0
+     */
+    UChar32 (*char32At)(const UReplaceable* rep,
+                        int32_t offset);
+    
+    /**
+     * Function pointer that replaces text between start and limit in
+     * this text with the given text.  Attributes (out of band info)
+     * should be retained.
+     *
+     * @param rep A pointer to "this" UReplaceable object.
+     * @param start the starting index of the text to be replaced,
+     * inclusive.
+     * @param limit the ending index of the text to be replaced,
+     * exclusive.
+     * @param text the new text to replace the UChars from
+     * start..limit-1.
+     * @param textLength the number of UChars at text, or -1 if text
+     * is null-terminated.
+     * @stable ICU 2.0
+     */
+    void    (*replace)(UReplaceable* rep,
+                       int32_t start,
+                       int32_t limit,
+                       const UChar* text,
+                       int32_t textLength);
+    
+    /**
+     * Function pointer that copies the characters in the range
+     * [<tt>start</tt>, <tt>limit</tt>) into the array <tt>dst</tt>.
+     *
+     * @param rep A pointer to "this" UReplaceable object.
+     * @param start offset of first character which will be copied
+     * into the array
+     * @param limit offset immediately following the last character to
+     * be copied
+     * @param dst array in which to copy characters.  The length of
+     * <tt>dst</tt> must be at least <tt>(limit - start)</tt>.
+     * @stable ICU 2.1
+     */
+    void    (*extract)(UReplaceable* rep,
+                       int32_t start,
+                       int32_t limit,
+                       UChar* dst);
+
+    /**
+     * Function pointer that copies text between start and limit in
+     * this text to another index in the text.  Attributes (out of
+     * band info) should be retained.  After this call, there will be
+     * (at least) two copies of the characters originally located at
+     * start..limit-1.
+     *
+     * @param rep A pointer to "this" UReplaceable object.
+     * @param start the starting index of the text to be copied,
+     * inclusive.
+     * @param limit the ending index of the text to be copied,
+     * exclusive.
+     * @param dest the index at which the copy of the UChars should be
+     * inserted.
+     * @stable ICU 2.0
+     */
+    void    (*copy)(UReplaceable* rep,
+                    int32_t start,
+                    int32_t limit,
+                    int32_t dest);    
+
+} UReplaceableCallbacks;
+
+U_CDECL_END
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/ures.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/ures.h b/src/apps/couch_collate/platform/osx/icu/unicode/ures.h
new file mode 100644
index 0000000..9cc2e89
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/ures.h
@@ -0,0 +1,871 @@
+/*
+**********************************************************************
+*   Copyright (C) 1997-2007, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+**********************************************************************
+*
+* File URES.H (formerly CRESBUND.H)
+*
+* Modification History:
+*
+*   Date        Name        Description
+*   04/01/97    aliu        Creation.
+*   02/22/99    damiba      overhaul.
+*   04/04/99    helena      Fixed internal header inclusion.
+*   04/15/99    Madhu       Updated Javadoc  
+*   06/14/99    stephen     Removed functions taking a filename suffix.
+*   07/20/99    stephen     Language-independent ypedef to void*
+*   11/09/99    weiv        Added ures_getLocale()
+*   06/24/02    weiv        Added support for resource sharing
+******************************************************************************
+*/
+
+#ifndef URES_H
+#define URES_H
+
+#include "unicode/utypes.h"
+#include "unicode/uloc.h"
+
+/**
+ * \file
+ * \brief C API: Resource Bundle 
+ *
+ * <h2>C API: Resource Bundle</h2>
+ *
+ * C API representing a collection of resource information pertaining to a given
+ * locale. A resource bundle provides a way of accessing locale- specific information in
+ * a data file. You create a resource bundle that manages the resources for a given
+ * locale and then ask it for individual resources.
+ * <P>
+ * Resource bundles in ICU4C are currently defined using text files which conform to the following
+ * <a href="http://source.icu-project.org/repos/icu/icuhtml/trunk/design/bnf_rb.txt">BNF definition</a>.
+ * More on resource bundle concepts and syntax can be found in the 
+ * <a href="http://icu-project.org/userguide/ResourceManagement.html">Users Guide</a>.
+ * <P>
+ */
+
+/**
+ * UResourceBundle is an opaque type for handles for resource bundles in C APIs.
+ * @stable ICU 2.0
+ */
+struct UResourceBundle;
+
+/**
+ * @stable ICU 2.0
+ */
+typedef struct UResourceBundle UResourceBundle;
+
+/**
+ * Numeric constants for types of resource items.
+ * @see ures_getType
+ * @stable ICU 2.0
+ */
+typedef enum {
+    /** Resource type constant for "no resource". @stable ICU 2.6 */
+    URES_NONE=-1,
+
+    /** Resource type constant for 16-bit Unicode strings. @stable ICU 2.6 */
+    URES_STRING=0,
+
+    /** Resource type constant for binary data. @stable ICU 2.6 */
+    URES_BINARY=1,
+
+    /** Resource type constant for tables of key-value pairs. @stable ICU 2.6 */
+    URES_TABLE=2,
+
+    /**
+     * Resource type constant for aliases;
+     * internally stores a string which identifies the actual resource
+     * storing the data (can be in a different resource bundle).
+     * Resolved internally before delivering the actual resource through the API.
+     * @stable ICU 2.6
+     */
+    URES_ALIAS=3,
+
+#ifndef U_HIDE_INTERNAL_API
+
+    /**
+     * Internal use only.
+     * Alternative resource type constant for tables of key-value pairs.
+     * Never returned by ures_getType().
+     * @internal
+     */
+    URES_TABLE32=4,
+
+#endif /* U_HIDE_INTERNAL_API */
+
+    /**
+     * Resource type constant for a single 28-bit integer, interpreted as
+     * signed or unsigned by the ures_getInt() or ures_getUInt() function.
+     * @see ures_getInt
+     * @see ures_getUInt
+     * @stable ICU 2.6
+     */
+    URES_INT=7,
+
+    /** Resource type constant for arrays of resources. @stable ICU 2.6 */
+    URES_ARRAY=8,
+
+    /**
+     * Resource type constant for vectors of 32-bit integers.
+     * @see ures_getIntVector
+     * @stable ICU 2.6
+     */
+    URES_INT_VECTOR = 14,
+#ifndef U_HIDE_DEPRECATED_API
+    /** @deprecated ICU 2.6 Use the URES_ constant instead. */
+    RES_NONE=URES_NONE,
+    /** @deprecated ICU 2.6 Use the URES_ constant instead. */
+    RES_STRING=URES_STRING,
+    /** @deprecated ICU 2.6 Use the URES_ constant instead. */
+    RES_BINARY=URES_BINARY,
+    /** @deprecated ICU 2.6 Use the URES_ constant instead. */
+    RES_TABLE=URES_TABLE,
+    /** @deprecated ICU 2.6 Use the URES_ constant instead. */
+    RES_ALIAS=URES_ALIAS,
+    /** @deprecated ICU 2.6 Use the URES_ constant instead. */
+    RES_INT=URES_INT,
+    /** @deprecated ICU 2.6 Use the URES_ constant instead. */
+    RES_ARRAY=URES_ARRAY,
+    /** @deprecated ICU 2.6 Use the URES_ constant instead. */
+    RES_INT_VECTOR=URES_INT_VECTOR,
+    /** @deprecated ICU 2.6 Not used. */
+    RES_RESERVED=15, 
+#endif /* U_HIDE_DEPRECATED_API */
+
+    URES_LIMIT = 16
+} UResType;
+
+/*
+ * Functions to create and destroy resource bundles.
+ */
+
+/**
+ * Opens a UResourceBundle, from which users can extract strings by using
+ * their corresponding keys.
+ * Note that the caller is responsible of calling <TT>ures_close</TT> on each succesfully
+ * opened resource bundle.
+ * @param packageName   The packageName and locale together point to an ICU udata object, 
+ *                      as defined by <code> udata_open( packageName, "res", locale, err) </code> 
+ *                      or equivalent.  Typically, packageName will refer to a (.dat) file, or to
+ *                      a package registered with udata_setAppData(). Using a full file or directory
+ *                      pathname for packageName is deprecated. If NULL, ICU data will be used.
+ * @param locale  specifies the locale for which we want to open the resource
+ *                if NULL, the default locale will be used. If strlen(locale) == 0
+ *                root locale will be used.
+ *                
+ * @param status  fills in the outgoing error code.
+ * The UErrorCode err parameter is used to return status information to the user. To
+ * check whether the construction succeeded or not, you should check the value of
+ * U_SUCCESS(err). If you wish more detailed information, you can check for
+ * informational status results which still indicate success. U_USING_FALLBACK_WARNING
+ * indicates that a fall back locale was used. For example, 'de_CH' was requested,
+ * but nothing was found there, so 'de' was used. U_USING_DEFAULT_WARNING indicates that
+ * the default locale data or root locale data was used; neither the requested locale 
+ * nor any of its fall back locales could be found. Please see the users guide for more 
+ * information on this topic.
+ * @return      a newly allocated resource bundle.
+ * @see ures_close
+ * @stable ICU 2.0
+ */
+U_STABLE UResourceBundle*  U_EXPORT2 
+ures_open(const char*    packageName,
+          const char*  locale, 
+          UErrorCode*     status);
+
+
+/** This function does not care what kind of localeID is passed in. It simply opens a bundle with 
+ *  that name. Fallback mechanism is disabled for the new bundle. If the requested bundle contains
+ *  an %%ALIAS directive, the results are undefined.
+ * @param packageName   The packageName and locale together point to an ICU udata object, 
+ *                      as defined by <code> udata_open( packageName, "res", locale, err) </code> 
+ *                      or equivalent.  Typically, packageName will refer to a (.dat) file, or to
+ *                      a package registered with udata_setAppData(). Using a full file or directory
+ *                      pathname for packageName is deprecated. If NULL, ICU data will be used.
+ * @param locale  specifies the locale for which we want to open the resource
+ *                if NULL, the default locale will be used. If strlen(locale) == 0
+ *                root locale will be used.
+ *                
+ * @param status fills in the outgoing error code. Either U_ZERO_ERROR or U_MISSING_RESOURCE_ERROR
+ * @return      a newly allocated resource bundle or NULL if it doesn't exist.
+ * @see ures_close
+ * @stable ICU 2.0
+ */
+U_STABLE UResourceBundle* U_EXPORT2 
+ures_openDirect(const char* packageName, 
+                const char* locale, 
+                UErrorCode* status);
+
+/**
+ * Same as ures_open() but takes a const UChar *path.
+ * This path will be converted to char * using the default converter,
+ * then ures_open() is called.
+ *
+ * @param packageName   The packageName and locale together point to an ICU udata object, 
+ *                      as defined by <code> udata_open( packageName, "res", locale, err) </code> 
+ *                      or equivalent.  Typically, packageName will refer to a (.dat) file, or to
+ *                      a package registered with udata_setAppData(). Using a full file or directory
+ *                      pathname for packageName is deprecated. If NULL, ICU data will be used.
+ * @param locale  specifies the locale for which we want to open the resource
+ *                if NULL, the default locale will be used. If strlen(locale) == 0
+ *                root locale will be used.
+ * @param status  fills in the outgoing error code.
+ * @return      a newly allocated resource bundle.
+ * @see ures_open
+ * @stable ICU 2.0
+ */
+U_STABLE UResourceBundle* U_EXPORT2 
+ures_openU(const UChar* packageName, 
+           const char* locale, 
+           UErrorCode* status);
+
+/**
+ * Returns the number of strings/arrays in resource bundles.
+ * Better to use ures_getSize, as this function will be deprecated. 
+ *
+ *@param resourceBundle resource bundle containing the desired strings
+ *@param resourceKey key tagging the resource
+ *@param err fills in the outgoing error code
+ *                could be <TT>U_MISSING_RESOURCE_ERROR</TT> if the key is not found
+ *                could be a non-failing error 
+ *                e.g.: <TT>U_USING_FALLBACK_WARNING</TT>,<TT>U_USING_FALLBACK_WARNING </TT>
+ *@return: for    <STRONG>Arrays</STRONG>: returns the number of resources in the array
+ *                <STRONG>Tables</STRONG>: returns the number of resources in the table
+ *                <STRONG>single string</STRONG>: returns 1
+ *@see ures_getSize
+ * @deprecated ICU 2.8 User ures_getSize instead
+ */
+U_DEPRECATED int32_t U_EXPORT2 
+ures_countArrayItems(const UResourceBundle* resourceBundle,
+                     const char* resourceKey,
+                     UErrorCode* err);
+/**
+ * Close a resource bundle, all pointers returned from the various ures_getXXX calls
+ * on this particular bundle should be considered invalid henceforth.
+ *
+ * @param resourceBundle a pointer to a resourceBundle struct. Can be NULL.
+ * @see ures_open
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+ures_close(UResourceBundle* resourceBundle);
+
+/**
+ * Return the version number associated with this ResourceBundle as a string. Please
+ * use ures_getVersion as this function is going to be deprecated.
+ *
+ * @param resourceBundle The resource bundle for which the version is checked.
+ * @return  A version number string as specified in the resource bundle or its parent.
+ *          The caller does not own this string.
+ * @see ures_getVersion
+ * @deprecated ICU 2.8 Use ures_getVersion instead.
+ */
+U_DEPRECATED const char* U_EXPORT2 
+ures_getVersionNumber(const UResourceBundle*   resourceBundle);
+
+/**
+ * Return the version number associated with this ResourceBundle as an 
+ * UVersionInfo array.
+ *
+ * @param resB The resource bundle for which the version is checked.
+ * @param versionInfo A UVersionInfo array that is filled with the version number
+ *                    as specified in the resource bundle or its parent.
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+ures_getVersion(const UResourceBundle* resB, 
+                UVersionInfo versionInfo);
+
+/**
+ * Return the name of the Locale associated with this ResourceBundle. This API allows
+ * you to query for the real locale of the resource. For example, if you requested 
+ * "en_US_CALIFORNIA" and only "en_US" bundle exists, "en_US" will be returned. 
+ * For subresources, the locale where this resource comes from will be returned.
+ * If fallback has occured, getLocale will reflect this.
+ *
+ * @param resourceBundle resource bundle in question
+ * @param status just for catching illegal arguments
+ * @return  A Locale name
+ * @deprecated ICU 2.8 Use ures_getLocaleByType instead.
+ */
+U_DEPRECATED const char* U_EXPORT2 
+ures_getLocale(const UResourceBundle* resourceBundle, 
+               UErrorCode* status);
+
+
+/**
+ * Return the name of the Locale associated with this ResourceBundle. 
+ * You can choose between requested, valid and real locale.
+ *
+ * @param resourceBundle resource bundle in question
+ * @param type You can choose between requested, valid and actual
+ *             locale. For description see the definition of
+ *             ULocDataLocaleType in uloc.h
+ * @param status just for catching illegal arguments
+ * @return  A Locale name
+ * @stable ICU 2.8
+ */
+U_STABLE const char* U_EXPORT2 
+ures_getLocaleByType(const UResourceBundle* resourceBundle, 
+                     ULocDataLocaleType type, 
+                     UErrorCode* status);
+
+
+/**
+ * Same as ures_open() but uses the fill-in parameter instead of allocating
+ * a bundle, if r!=NULL.
+ * TODO need to revisit usefulness of this function
+ *      and usage model for fillIn parameters without knowing sizeof(UResourceBundle)
+ * @param r The resourcebundle to open
+ * @param packageName   The packageName and locale together point to an ICU udata object, 
+ *                      as defined by <code> udata_open( packageName, "res", locale, err) </code> 
+ *                      or equivalent.  Typically, packageName will refer to a (.dat) file, or to
+ *                      a package registered with udata_setAppData(). Using a full file or directory
+ *                      pathname for packageName is deprecated. If NULL, ICU data will be used.
+ * @param localeID specifies the locale for which we want to open the resource
+ * @param status The error code
+ * @return a newly allocated resource bundle or NULL if it doesn't exist.
+ * @internal
+ */
+U_INTERNAL void U_EXPORT2 
+ures_openFillIn(UResourceBundle *r, 
+                const char* packageName,
+                const char* localeID, 
+                UErrorCode* status);
+
+/**
+ * Returns a string from a string resource type
+ *
+ * @param resourceBundle a string resource
+ * @param len    fills in the length of resulting string
+ * @param status fills in the outgoing error code
+ *                could be <TT>U_MISSING_RESOURCE_ERROR</TT> if the key is not found
+ *                Always check the value of status. Don't count on returning NULL.
+ *                could be a non-failing error 
+ *                e.g.: <TT>U_USING_FALLBACK_WARNING</TT>,<TT>U_USING_DEFAULT_WARNING </TT>
+ * @return a pointer to a zero-terminated UChar array which lives in a memory mapped/DLL file.
+ * @see ures_getBinary
+ * @see ures_getIntVector
+ * @see ures_getInt
+ * @see ures_getUInt
+ * @stable ICU 2.0
+ */
+U_STABLE const UChar* U_EXPORT2 
+ures_getString(const UResourceBundle* resourceBundle, 
+               int32_t* len, 
+               UErrorCode* status);
+
+/**
+ * Returns a UTF-8 string from a string resource.
+ * The UTF-8 string may be returnable directly as a pointer, or
+ * it may need to be copied, or transformed from UTF-16 using u_strToUTF8()
+ * or equivalent.
+ *
+ * If forceCopy==TRUE, then the string is always written to the dest buffer
+ * and dest is returned.
+ *
+ * If forceCopy==FALSE, then the string is returned as a pointer if possible,
+ * without needing a dest buffer (it can be NULL). If the string needs to be
+ * copied or transformed, then it may be placed into dest at an arbitrary offset.
+ *
+ * If the string is to be written to dest, then U_BUFFER_OVERFLOW_ERROR and
+ * U_STRING_NOT_TERMINATED_WARNING are set if appropriate, as usual.
+ *
+ * If the string is transformed from UTF-16, then a conversion error may occur
+ * if an unpaired surrogate is encountered. If the function is successful, then
+ * the output UTF-8 string is always well-formed.
+ *
+ * @param resB Resource bundle.
+ * @param dest Destination buffer. Can be NULL only if capacity=*length==0.
+ * @param length Input: Capacity of destination buffer.
+ *               Output: Actual length of the UTF-8 string, not counting the
+ *               terminating NUL, even in case of U_BUFFER_OVERFLOW_ERROR.
+ *               Can be NULL, meaning capacity=0 and the string length is not
+ *               returned to the caller.
+ * @param forceCopy If TRUE, then the output string will always be written to
+ *                  dest, with U_BUFFER_OVERFLOW_ERROR and
+ *                  U_STRING_NOT_TERMINATED_WARNING set if appropriate.
+ *                  If FALSE, then the dest buffer may or may not contain a
+ *                  copy of the string. dest may or may not be modified.
+ *                  If a copy needs to be written, then the UErrorCode parameter
+ *                  indicates overflow etc. as usual.
+ * @param status Pointer to a standard ICU error code. Its input value must
+ *               pass the U_SUCCESS() test, or else the function returns
+ *               immediately. Check for U_FAILURE() on output or use with
+ *               function chaining. (See User Guide for details.)
+ * @return The pointer to the UTF-8 string. It may be dest, or at some offset
+ *         from dest (only if !forceCopy), or in unrelated memory.
+ *         Always NUL-terminated unless the string was written to dest and
+ *         length==capacity (in which case U_STRING_NOT_TERMINATED_WARNING is set).
+ *
+ * @see ures_getString
+ * @see u_strToUTF8
+ * @stable ICU 3.6
+ */
+U_STABLE const char * U_EXPORT2
+ures_getUTF8String(const UResourceBundle *resB,
+                   char *dest, int32_t *length,
+                   UBool forceCopy,
+                   UErrorCode *status);
+
+/**
+ * Returns a binary data from a binary resource. 
+ *
+ * @param resourceBundle a string resource
+ * @param len    fills in the length of resulting byte chunk
+ * @param status fills in the outgoing error code
+ *                could be <TT>U_MISSING_RESOURCE_ERROR</TT> if the key is not found
+ *                Always check the value of status. Don't count on returning NULL.
+ *                could be a non-failing error 
+ *                e.g.: <TT>U_USING_FALLBACK_WARNING</TT>,<TT>U_USING_DEFAULT_WARNING </TT>
+ * @return a pointer to a chuck of unsigned bytes which live in a memory mapped/DLL file.
+ * @see ures_getString
+ * @see ures_getIntVector
+ * @see ures_getInt
+ * @see ures_getUInt
+ * @stable ICU 2.0
+ */
+U_STABLE const uint8_t* U_EXPORT2 
+ures_getBinary(const UResourceBundle* resourceBundle, 
+               int32_t* len, 
+               UErrorCode* status);
+
+/**
+ * Returns a 32 bit integer array from a resource. 
+ *
+ * @param resourceBundle an int vector resource
+ * @param len    fills in the length of resulting byte chunk
+ * @param status fills in the outgoing error code
+ *                could be <TT>U_MISSING_RESOURCE_ERROR</TT> if the key is not found
+ *                Always check the value of status. Don't count on returning NULL.
+ *                could be a non-failing error 
+ *                e.g.: <TT>U_USING_FALLBACK_WARNING</TT>,<TT>U_USING_DEFAULT_WARNING </TT>
+ * @return a pointer to a chunk of unsigned bytes which live in a memory mapped/DLL file.
+ * @see ures_getBinary
+ * @see ures_getString
+ * @see ures_getInt
+ * @see ures_getUInt
+ * @stable ICU 2.0
+ */
+U_STABLE const int32_t* U_EXPORT2 
+ures_getIntVector(const UResourceBundle* resourceBundle, 
+                  int32_t* len, 
+                  UErrorCode* status);
+
+/**
+ * Returns an unsigned integer from a resource. 
+ * This integer is originally 28 bits.
+ *
+ * @param resourceBundle a string resource
+ * @param status fills in the outgoing error code
+ *                could be <TT>U_MISSING_RESOURCE_ERROR</TT> if the key is not found
+ *                could be a non-failing error 
+ *                e.g.: <TT>U_USING_FALLBACK_WARNING</TT>,<TT>U_USING_DEFAULT_WARNING </TT>
+ * @return an integer value
+ * @see ures_getInt
+ * @see ures_getIntVector
+ * @see ures_getBinary
+ * @see ures_getString
+ * @stable ICU 2.0
+ */
+U_STABLE uint32_t U_EXPORT2 
+ures_getUInt(const UResourceBundle* resourceBundle, 
+             UErrorCode *status);
+
+/**
+ * Returns a signed integer from a resource. 
+ * This integer is originally 28 bit and the sign gets propagated.
+ *
+ * @param resourceBundle a string resource
+ * @param status  fills in the outgoing error code
+ *                could be <TT>U_MISSING_RESOURCE_ERROR</TT> if the key is not found
+ *                could be a non-failing error 
+ *                e.g.: <TT>U_USING_FALLBACK_WARNING</TT>,<TT>U_USING_DEFAULT_WARNING </TT>
+ * @return an integer value
+ * @see ures_getUInt
+ * @see ures_getIntVector
+ * @see ures_getBinary
+ * @see ures_getString
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2 
+ures_getInt(const UResourceBundle* resourceBundle, 
+            UErrorCode *status);
+
+/**
+ * Returns the size of a resource. Size for scalar types is always 1, 
+ * and for vector/table types is the number of child resources.
+ * @warning Integer array is treated as a scalar type. There are no 
+ *          APIs to access individual members of an integer array. It
+ *          is always returned as a whole.
+ * @param resourceBundle a resource
+ * @return number of resources in a given resource.
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2 
+ures_getSize(const UResourceBundle *resourceBundle);
+
+/**
+ * Returns the type of a resource. Available types are defined in enum UResType
+ *
+ * @param resourceBundle a resource
+ * @return type of the given resource.
+ * @see UResType
+ * @stable ICU 2.0
+ */
+U_STABLE UResType U_EXPORT2 
+ures_getType(const UResourceBundle *resourceBundle);
+
+/**
+ * Returns the key associated with a given resource. Not all the resources have a key - only 
+ * those that are members of a table.
+ *
+ * @param resourceBundle a resource
+ * @return a key associated to this resource, or NULL if it doesn't have a key
+ * @stable ICU 2.0
+ */
+U_STABLE const char * U_EXPORT2 
+ures_getKey(const UResourceBundle *resourceBundle);
+
+/* ITERATION API 
+    This API provides means for iterating through a resource
+*/
+
+/**
+ * Resets the internal context of a resource so that iteration starts from the first element.
+ *
+ * @param resourceBundle a resource
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+ures_resetIterator(UResourceBundle *resourceBundle);
+
+/**
+ * Checks whether the given resource has another element to iterate over.
+ *
+ * @param resourceBundle a resource
+ * @return TRUE if there are more elements, FALSE if there is no more elements
+ * @stable ICU 2.0
+ */
+U_STABLE UBool U_EXPORT2 
+ures_hasNext(const UResourceBundle *resourceBundle);
+
+/**
+ * Returns the next resource in a given resource or NULL if there are no more resources 
+ * to iterate over. Features a fill-in parameter. 
+ *
+ * @param resourceBundle    a resource
+ * @param fillIn            if NULL a new UResourceBundle struct is allocated and must be closed by the caller.
+ *                          Alternatively, you can supply a struct to be filled by this function.
+ * @param status            fills in the outgoing error code. You may still get a non NULL result even if an
+ *                          error occured. Check status instead.
+ * @return                  a pointer to a UResourceBundle struct. If fill in param was NULL, caller must close it
+ * @stable ICU 2.0
+ */
+U_STABLE UResourceBundle* U_EXPORT2 
+ures_getNextResource(UResourceBundle *resourceBundle, 
+                     UResourceBundle *fillIn, 
+                     UErrorCode *status);
+
+/**
+ * Returns the next string in a given resource or NULL if there are no more resources 
+ * to iterate over. 
+ *
+ * @param resourceBundle    a resource
+ * @param len               fill in length of the string
+ * @param key               fill in for key associated with this string. NULL if no key
+ * @param status            fills in the outgoing error code. If an error occured, we may return NULL, but don't
+ *                          count on it. Check status instead!
+ * @return a pointer to a zero-terminated UChar array which lives in a memory mapped/DLL file.
+ * @stable ICU 2.0
+ */
+U_STABLE const UChar* U_EXPORT2 
+ures_getNextString(UResourceBundle *resourceBundle, 
+                   int32_t* len, 
+                   const char ** key, 
+                   UErrorCode *status);
+
+/**
+ * Returns the resource in a given resource at the specified index. Features a fill-in parameter. 
+ *
+ * @param resourceBundle    the resource bundle from which to get a sub-resource
+ * @param indexR            an index to the wanted resource.
+ * @param fillIn            if NULL a new UResourceBundle struct is allocated and must be closed by the caller.
+ *                          Alternatively, you can supply a struct to be filled by this function.
+ * @param status            fills in the outgoing error code. Don't count on NULL being returned if an error has
+ *                          occured. Check status instead.
+ * @return                  a pointer to a UResourceBundle struct. If fill in param was NULL, caller must close it
+ * @stable ICU 2.0
+ */
+U_STABLE UResourceBundle* U_EXPORT2 
+ures_getByIndex(const UResourceBundle *resourceBundle, 
+                int32_t indexR, 
+                UResourceBundle *fillIn, 
+                UErrorCode *status);
+
+/**
+ * Returns the string in a given resource at the specified index.
+ *
+ * @param resourceBundle    a resource
+ * @param indexS            an index to the wanted string.
+ * @param len               fill in length of the string
+ * @param status            fills in the outgoing error code. If an error occured, we may return NULL, but don't
+ *                          count on it. Check status instead!
+ * @return                  a pointer to a zero-terminated UChar array which lives in a memory mapped/DLL file.
+ * @stable ICU 2.0
+ */
+U_STABLE const UChar* U_EXPORT2 
+ures_getStringByIndex(const UResourceBundle *resourceBundle, 
+                      int32_t indexS, 
+                      int32_t* len, 
+                      UErrorCode *status);
+
+/**
+ * Returns a UTF-8 string from a resource at the specified index.
+ * The UTF-8 string may be returnable directly as a pointer, or
+ * it may need to be copied, or transformed from UTF-16 using u_strToUTF8()
+ * or equivalent.
+ *
+ * If forceCopy==TRUE, then the string is always written to the dest buffer
+ * and dest is returned.
+ *
+ * If forceCopy==FALSE, then the string is returned as a pointer if possible,
+ * without needing a dest buffer (it can be NULL). If the string needs to be
+ * copied or transformed, then it may be placed into dest at an arbitrary offset.
+ *
+ * If the string is to be written to dest, then U_BUFFER_OVERFLOW_ERROR and
+ * U_STRING_NOT_TERMINATED_WARNING are set if appropriate, as usual.
+ *
+ * If the string is transformed from UTF-16, then a conversion error may occur
+ * if an unpaired surrogate is encountered. If the function is successful, then
+ * the output UTF-8 string is always well-formed.
+ *
+ * @param resB Resource bundle.
+ * @param index An index to the wanted string.
+ * @param dest Destination buffer. Can be NULL only if capacity=*length==0.
+ * @param pLength Input: Capacity of destination buffer.
+ *               Output: Actual length of the UTF-8 string, not counting the
+ *               terminating NUL, even in case of U_BUFFER_OVERFLOW_ERROR.
+ *               Can be NULL, meaning capacity=0 and the string length is not
+ *               returned to the caller.
+ * @param forceCopy If TRUE, then the output string will always be written to
+ *                  dest, with U_BUFFER_OVERFLOW_ERROR and
+ *                  U_STRING_NOT_TERMINATED_WARNING set if appropriate.
+ *                  If FALSE, then the dest buffer may or may not contain a
+ *                  copy of the string. dest may or may not be modified.
+ *                  If a copy needs to be written, then the UErrorCode parameter
+ *                  indicates overflow etc. as usual.
+ * @param status Pointer to a standard ICU error code. Its input value must
+ *               pass the U_SUCCESS() test, or else the function returns
+ *               immediately. Check for U_FAILURE() on output or use with
+ *               function chaining. (See User Guide for details.)
+ * @return The pointer to the UTF-8 string. It may be dest, or at some offset
+ *         from dest (only if !forceCopy), or in unrelated memory.
+ *         Always NUL-terminated unless the string was written to dest and
+ *         length==capacity (in which case U_STRING_NOT_TERMINATED_WARNING is set).
+ *
+ * @see ures_getStringByIndex
+ * @see u_strToUTF8
+ * @stable ICU 3.6
+ */
+U_STABLE const char * U_EXPORT2
+ures_getUTF8StringByIndex(const UResourceBundle *resB,
+                          int32_t index,
+                          char *dest, int32_t *pLength,
+                          UBool forceCopy,
+                          UErrorCode *status);
+
+/**
+ * Returns a resource in a given resource that has a given key. This procedure works only with table
+ * resources. Features a fill-in parameter. 
+ *
+ * @param resourceBundle    a resource
+ * @param key               a key associated with the wanted resource
+ * @param fillIn            if NULL a new UResourceBundle struct is allocated and must be closed by the caller.
+ *                          Alternatively, you can supply a struct to be filled by this function.
+ * @param status            fills in the outgoing error code.
+ * @return                  a pointer to a UResourceBundle struct. If fill in param was NULL, caller must close it
+ * @stable ICU 2.0
+ */
+U_STABLE UResourceBundle* U_EXPORT2 
+ures_getByKey(const UResourceBundle *resourceBundle, 
+              const char* key, 
+              UResourceBundle *fillIn, 
+              UErrorCode *status);
+
+/**
+ * Returns a string in a given resource that has a given key. This procedure works only with table
+ * resources. 
+ *
+ * @param resB              a resource
+ * @param key               a key associated with the wanted string
+ * @param len               fill in length of the string
+ * @param status            fills in the outgoing error code. If an error occured, we may return NULL, but don't
+ *                          count on it. Check status instead!
+ * @return                  a pointer to a zero-terminated UChar array which lives in a memory mapped/DLL file.
+ * @stable ICU 2.0
+ */
+U_STABLE const UChar* U_EXPORT2 
+ures_getStringByKey(const UResourceBundle *resB, 
+                    const char* key, 
+                    int32_t* len, 
+                    UErrorCode *status);
+
+/**
+ * Returns a UTF-8 string from a resource and a key.
+ * This function works only with table resources.
+ *
+ * The UTF-8 string may be returnable directly as a pointer, or
+ * it may need to be copied, or transformed from UTF-16 using u_strToUTF8()
+ * or equivalent.
+ *
+ * If forceCopy==TRUE, then the string is always written to the dest buffer
+ * and dest is returned.
+ *
+ * If forceCopy==FALSE, then the string is returned as a pointer if possible,
+ * without needing a dest buffer (it can be NULL). If the string needs to be
+ * copied or transformed, then it may be placed into dest at an arbitrary offset.
+ *
+ * If the string is to be written to dest, then U_BUFFER_OVERFLOW_ERROR and
+ * U_STRING_NOT_TERMINATED_WARNING are set if appropriate, as usual.
+ *
+ * If the string is transformed from UTF-16, then a conversion error may occur
+ * if an unpaired surrogate is encountered. If the function is successful, then
+ * the output UTF-8 string is always well-formed.
+ *
+ * @param resB Resource bundle.
+ * @param key  A key associated with the wanted resource
+ * @param dest Destination buffer. Can be NULL only if capacity=*length==0.
+ * @param pLength Input: Capacity of destination buffer.
+ *               Output: Actual length of the UTF-8 string, not counting the
+ *               terminating NUL, even in case of U_BUFFER_OVERFLOW_ERROR.
+ *               Can be NULL, meaning capacity=0 and the string length is not
+ *               returned to the caller.
+ * @param forceCopy If TRUE, then the output string will always be written to
+ *                  dest, with U_BUFFER_OVERFLOW_ERROR and
+ *                  U_STRING_NOT_TERMINATED_WARNING set if appropriate.
+ *                  If FALSE, then the dest buffer may or may not contain a
+ *                  copy of the string. dest may or may not be modified.
+ *                  If a copy needs to be written, then the UErrorCode parameter
+ *                  indicates overflow etc. as usual.
+ * @param status Pointer to a standard ICU error code. Its input value must
+ *               pass the U_SUCCESS() test, or else the function returns
+ *               immediately. Check for U_FAILURE() on output or use with
+ *               function chaining. (See User Guide for details.)
+ * @return The pointer to the UTF-8 string. It may be dest, or at some offset
+ *         from dest (only if !forceCopy), or in unrelated memory.
+ *         Always NUL-terminated unless the string was written to dest and
+ *         length==capacity (in which case U_STRING_NOT_TERMINATED_WARNING is set).
+ *
+ * @see ures_getStringByKey
+ * @see u_strToUTF8
+ * @stable ICU 3.6
+ */
+U_STABLE const char * U_EXPORT2
+ures_getUTF8StringByKey(const UResourceBundle *resB,
+                        const char *key,
+                        char *dest, int32_t *pLength,
+                        UBool forceCopy,
+                        UErrorCode *status);
+
+#ifdef XP_CPLUSPLUS
+#include "unicode/unistr.h"
+
+U_NAMESPACE_BEGIN
+/**
+ * returns a string from a string resource type
+ *
+ * @param resB    a resource
+ * @param status: fills in the outgoing error code
+ *                could be <TT>U_MISSING_RESOURCE_ERROR</TT> if the key is not found
+ *                could be a non-failing error 
+ *                e.g.: <TT>U_USING_FALLBACK_WARNING</TT>,<TT>U_USING_DEFAULT_WARNING </TT>
+ * @return        a UnicodeString object. If there is an error, string is bogus
+ * @stable ICU 2.0
+ */
+inline UnicodeString 
+ures_getUnicodeString(const UResourceBundle *resB, 
+                      UErrorCode* status) 
+{
+    int32_t len = 0;
+    const UChar *r = ures_getString(resB, &len, status);
+    return UnicodeString(TRUE, r, len);
+}
+
+/**
+ * Returns the next string in a resource or NULL if there are no more resources 
+ * to iterate over. 
+ *
+ * @param resB              a resource
+ * @param key               fill in for key associated with this string
+ * @param status            fills in the outgoing error code
+ * @return an UnicodeString object.
+ * @stable ICU 2.0
+ */
+inline UnicodeString 
+ures_getNextUnicodeString(UResourceBundle *resB, 
+                          const char ** key, 
+                          UErrorCode* status) 
+{
+    int32_t len = 0;
+    const UChar* r = ures_getNextString(resB, &len, key, status);
+    return UnicodeString(TRUE, r, len);
+}
+
+/**
+ * Returns the string in a given resource at the specified index.
+ *
+ * @param resB              a resource
+ * @param index             an index to the wanted string.
+ * @param status            fills in the outgoing error code
+ * @return                  an UnicodeString object. If there is an error, string is bogus
+ * @stable ICU 2.0
+ */
+inline UnicodeString 
+ures_getUnicodeStringByIndex(const UResourceBundle *resB, 
+                             int32_t indexS, 
+                             UErrorCode* status) 
+{
+    int32_t len = 0;
+    const UChar* r = ures_getStringByIndex(resB, indexS, &len, status);
+    return UnicodeString(TRUE, r, len);
+}
+
+/**
+ * Returns a string in a resource that has a given key. This procedure works only with table
+ * resources. 
+ *
+ * @param resB              a resource
+ * @param key               a key associated with the wanted string
+ * @param status            fills in the outgoing error code
+ * @return                  an UnicodeString object. If there is an error, string is bogus
+ * @stable ICU 2.0
+ */
+inline UnicodeString 
+ures_getUnicodeStringByKey(const UResourceBundle *resB, 
+                           const char* key, 
+                           UErrorCode* status) 
+{
+    int32_t len = 0;
+    const UChar* r = ures_getStringByKey(resB, key, &len, status);
+    return UnicodeString(TRUE, r, len);
+}
+
+U_NAMESPACE_END
+
+#endif
+
+/**
+ * Create a string enumerator, owned by the caller, of all locales located within 
+ * the specified resource tree.
+ * @param packageName name of the tree, such as (NULL) or U_ICUDATA_ALIAS or  or "ICUDATA-coll"
+ * This call is similar to uloc_getAvailable().
+ * @param status error code
+ * @stable ICU 3.2
+ */
+U_STABLE UEnumeration* U_EXPORT2
+ures_openAvailableLocales(const char *packageName, UErrorCode *status);
+
+
+#endif /*_URES*/
+/*eof*/

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/uscript.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/uscript.h b/src/apps/couch_collate/platform/osx/icu/unicode/uscript.h
new file mode 100644
index 0000000..c915d8d
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/uscript.h
@@ -0,0 +1,254 @@
+/*
+ **********************************************************************
+ *   Copyright (C) 1997-2008, International Business Machines
+ *   Corporation and others.  All Rights Reserved.
+ **********************************************************************
+ *
+ * File USCRIPT.H
+ *
+ * Modification History:
+ *
+ *   Date        Name        Description
+ *   07/06/2001    Ram         Creation.
+ ******************************************************************************
+ */
+
+#ifndef USCRIPT_H
+#define USCRIPT_H
+#include "unicode/utypes.h"
+
+/**
+ * \file
+ * \brief C API: Unicode Script Information
+ */
+ 
+/**
+ * Constants for ISO 15924 script codes.
+ *
+ * Many of these script codes - those from Unicode's ScriptNames.txt -
+ * are character property values for Unicode's Script property.
+ * See UAX #24 Script Names (http://www.unicode.org/reports/tr24/).
+ *
+ * Starting with ICU 3.6, constants for most ISO 15924 script codes
+ * are included (currently excluding private-use codes Qaaa..Qabx).
+ * For scripts for which there are codes in ISO 15924 but which are not
+ * used in the Unicode Character Database (UCD), there are no Unicode characters
+ * associated with those scripts.
+ *
+ * For example, there are no characters that have a UCD script code of
+ * Hans or Hant. All Han ideographs have the Hani script code.
+ * The Hans and Hant script codes are used with CLDR data.
+ *
+ * ISO 15924 script codes are included for use with CLDR and similar.
+ *
+ * @stable ICU 2.2
+ */
+typedef enum UScriptCode {
+      USCRIPT_INVALID_CODE = -1,
+      USCRIPT_COMMON       =  0 , /* Zyyy */
+      USCRIPT_INHERITED    =  1,  /* Qaai */
+      USCRIPT_ARABIC       =  2,  /* Arab */
+      USCRIPT_ARMENIAN     =  3,  /* Armn */
+      USCRIPT_BENGALI      =  4,  /* Beng */
+      USCRIPT_BOPOMOFO     =  5,  /* Bopo */
+      USCRIPT_CHEROKEE     =  6,  /* Cher */
+      USCRIPT_COPTIC       =  7,  /* Copt */
+      USCRIPT_CYRILLIC     =  8,  /* Cyrl */
+      USCRIPT_DESERET      =  9,  /* Dsrt */
+      USCRIPT_DEVANAGARI   = 10,  /* Deva */
+      USCRIPT_ETHIOPIC     = 11,  /* Ethi */
+      USCRIPT_GEORGIAN     = 12,  /* Geor */
+      USCRIPT_GOTHIC       = 13,  /* Goth */
+      USCRIPT_GREEK        = 14,  /* Grek */
+      USCRIPT_GUJARATI     = 15,  /* Gujr */
+      USCRIPT_GURMUKHI     = 16,  /* Guru */
+      USCRIPT_HAN          = 17,  /* Hani */
+      USCRIPT_HANGUL       = 18,  /* Hang */
+      USCRIPT_HEBREW       = 19,  /* Hebr */
+      USCRIPT_HIRAGANA     = 20,  /* Hira */
+      USCRIPT_KANNADA      = 21,  /* Knda */
+      USCRIPT_KATAKANA     = 22,  /* Kana */
+      USCRIPT_KHMER        = 23,  /* Khmr */
+      USCRIPT_LAO          = 24,  /* Laoo */
+      USCRIPT_LATIN        = 25,  /* Latn */
+      USCRIPT_MALAYALAM    = 26,  /* Mlym */
+      USCRIPT_MONGOLIAN    = 27,  /* Mong */
+      USCRIPT_MYANMAR      = 28,  /* Mymr */
+      USCRIPT_OGHAM        = 29,  /* Ogam */
+      USCRIPT_OLD_ITALIC   = 30,  /* Ital */
+      USCRIPT_ORIYA        = 31,  /* Orya */
+      USCRIPT_RUNIC        = 32,  /* Runr */
+      USCRIPT_SINHALA      = 33,  /* Sinh */
+      USCRIPT_SYRIAC       = 34,  /* Syrc */
+      USCRIPT_TAMIL        = 35,  /* Taml */
+      USCRIPT_TELUGU       = 36,  /* Telu */
+      USCRIPT_THAANA       = 37,  /* Thaa */
+      USCRIPT_THAI         = 38,  /* Thai */
+      USCRIPT_TIBETAN      = 39,  /* Tibt */
+      /** Canadian_Aboriginal script. @stable ICU 2.6 */
+      USCRIPT_CANADIAN_ABORIGINAL = 40,  /* Cans */
+      /** Canadian_Aboriginal script (alias). @stable ICU 2.2 */
+      USCRIPT_UCAS         = USCRIPT_CANADIAN_ABORIGINAL,
+      USCRIPT_YI           = 41,  /* Yiii */
+      USCRIPT_TAGALOG      = 42,  /* Tglg */
+      USCRIPT_HANUNOO      = 43,  /* Hano */
+      USCRIPT_BUHID        = 44,  /* Buhd */
+      USCRIPT_TAGBANWA     = 45,  /* Tagb */
+
+      /* New scripts in Unicode 4 @stable ICU 2.6 */
+      USCRIPT_BRAILLE      = 46,  /* Brai */
+      USCRIPT_CYPRIOT      = 47,  /* Cprt */
+      USCRIPT_LIMBU        = 48,  /* Limb */
+      USCRIPT_LINEAR_B     = 49,  /* Linb */
+      USCRIPT_OSMANYA      = 50,  /* Osma */
+      USCRIPT_SHAVIAN      = 51,  /* Shaw */
+      USCRIPT_TAI_LE       = 52,  /* Tale */
+      USCRIPT_UGARITIC     = 53,  /* Ugar */
+
+      /** New script code in Unicode 4.0.1 @stable ICU 3.0 */
+      USCRIPT_KATAKANA_OR_HIRAGANA = 54,/*Hrkt */
+      
+      /* New scripts in Unicode 4.1 @stable ICU 3.4 */
+      USCRIPT_BUGINESE      = 55, /* Bugi */
+      USCRIPT_GLAGOLITIC    = 56, /* Glag */
+      USCRIPT_KHAROSHTHI    = 57, /* Khar */
+      USCRIPT_SYLOTI_NAGRI  = 58, /* Sylo */
+      USCRIPT_NEW_TAI_LUE   = 59, /* Talu */
+      USCRIPT_TIFINAGH      = 60, /* Tfng */
+      USCRIPT_OLD_PERSIAN   = 61, /* Xpeo */
+
+      /* New script codes from ISO 15924 @stable ICU 3.6 */
+      USCRIPT_BALINESE                      = 62, /* Bali */
+      USCRIPT_BATAK                         = 63, /* Batk */
+      USCRIPT_BLISSYMBOLS                   = 64, /* Blis */
+      USCRIPT_BRAHMI                        = 65, /* Brah */
+      USCRIPT_CHAM                          = 66, /* Cham */
+      USCRIPT_CIRTH                         = 67, /* Cirt */
+      USCRIPT_OLD_CHURCH_SLAVONIC_CYRILLIC  = 68, /* Cyrs */
+      USCRIPT_DEMOTIC_EGYPTIAN              = 69, /* Egyd */
+      USCRIPT_HIERATIC_EGYPTIAN             = 70, /* Egyh */
+      USCRIPT_EGYPTIAN_HIEROGLYPHS          = 71, /* Egyp */
+      USCRIPT_KHUTSURI                      = 72, /* Geok */
+      USCRIPT_SIMPLIFIED_HAN                = 73, /* Hans */
+      USCRIPT_TRADITIONAL_HAN               = 74, /* Hant */
+      USCRIPT_PAHAWH_HMONG                  = 75, /* Hmng */
+      USCRIPT_OLD_HUNGARIAN                 = 76, /* Hung */
+      USCRIPT_HARAPPAN_INDUS                = 77, /* Inds */
+      USCRIPT_JAVANESE                      = 78, /* Java */
+      USCRIPT_KAYAH_LI                      = 79, /* Kali */
+      USCRIPT_LATIN_FRAKTUR                 = 80, /* Latf */
+      USCRIPT_LATIN_GAELIC                  = 81, /* Latg */
+      USCRIPT_LEPCHA                        = 82, /* Lepc */
+      USCRIPT_LINEAR_A                      = 83, /* Lina */
+      USCRIPT_MANDAEAN                      = 84, /* Mand */
+      USCRIPT_MAYAN_HIEROGLYPHS             = 85, /* Maya */
+      USCRIPT_MEROITIC                      = 86, /* Mero */
+      USCRIPT_NKO                           = 87, /* Nkoo */
+      USCRIPT_ORKHON                        = 88, /* Orkh */
+      USCRIPT_OLD_PERMIC                    = 89, /* Perm */
+      USCRIPT_PHAGS_PA                      = 90, /* Phag */
+      USCRIPT_PHOENICIAN                    = 91, /* Phnx */
+      USCRIPT_PHONETIC_POLLARD              = 92, /* Plrd */
+      USCRIPT_RONGORONGO                    = 93, /* Roro */
+      USCRIPT_SARATI                        = 94, /* Sara */
+      USCRIPT_ESTRANGELO_SYRIAC             = 95, /* Syre */
+      USCRIPT_WESTERN_SYRIAC                = 96, /* Syrj */
+      USCRIPT_EASTERN_SYRIAC                = 97, /* Syrn */
+      USCRIPT_TENGWAR                       = 98, /* Teng */
+      USCRIPT_VAI                           = 99, /* Vaii */
+      USCRIPT_VISIBLE_SPEECH                = 100, /* Visp */
+      USCRIPT_CUNEIFORM                     = 101,/* Xsux */
+      USCRIPT_UNWRITTEN_LANGUAGES           = 102,/* Zxxx */
+      USCRIPT_UNKNOWN                       = 103,/* Zzzz */ /* Unknown="Code for uncoded script", for unassigned code points */
+
+      /* New script codes from ISO 15924 @stable ICU 4.0 */
+      USCRIPT_CARIAN                        = 104,/* Cari */
+      USCRIPT_JAPANESE                      = 105,/* Jpan */
+      USCRIPT_LANNA                         = 106,/* Lana */
+      USCRIPT_LYCIAN                        = 107,/* Lyci */
+      USCRIPT_LYDIAN                        = 108,/* Lydi */
+      USCRIPT_OL_CHIKI                      = 109,/* Olck */
+      USCRIPT_REJANG                        = 110,/* Rjng */
+      USCRIPT_SAURASHTRA                    = 111,/* Saur */
+      USCRIPT_SIGN_WRITING                  = 112,/* Sgnw */
+      USCRIPT_SUNDANESE                     = 113,/* Sund */
+      USCRIPT_MOON                          = 114,/* Moon */
+      USCRIPT_MEITEI_MAYEK                  = 115,/* Mtei */
+
+      /* New script codes from ISO 15924 @draft ICU 4.0 */
+      USCRIPT_IMPERIAL_ARAMAIC              = 116,/* Armi */
+      USCRIPT_AVESTAN                       = 117,/* Avst */
+      USCRIPT_CHAKMA                        = 118,/* Cakm */
+      USCRIPT_KOREAN                        = 119,/* Kore */
+      USCRIPT_KAITHI                        = 120,/* Kthi */
+      USCRIPT_MANICHAEAN                    = 121,/* Mani */
+      USCRIPT_INSCRIPTIONAL_PAHLAVI         = 122,/* Phli */
+      USCRIPT_PSALTER_PAHLAVI               = 123,/* Phlp */
+      USCRIPT_BOOK_PAHLAVI                  = 124,/* Phlv */
+      USCRIPT_INSCRIPTIONAL_PARTHIAN        = 125,/* Prti */
+      USCRIPT_SAMARITAN                     = 126,/* Samr */
+      USCRIPT_TAI_VIET                      = 127,/* Tavt */
+      USCRIPT_MATHEMATICAL_NOTATION         = 128,/* Zmth */
+      USCRIPT_SYMBOLS                       = 129,/* Zsym */
+
+      /* Private use codes from Qaaa - Qabx are not supported*/
+      USCRIPT_CODE_LIMIT    = 130
+} UScriptCode;
+
+/**
+ * Gets script codes associated with the given locale or ISO 15924 abbreviation or name. 
+ * Fills in USCRIPT_MALAYALAM given "Malayam" OR "Mlym".
+ * Fills in USCRIPT_LATIN given "en" OR "en_US" 
+ * If required capacity is greater than capacity of the destination buffer then the error code
+ * is set to U_BUFFER_OVERFLOW_ERROR and the required capacity is returned
+ *
+ * <p>Note: To search by short or long script alias only, use
+ * u_getPropertyValueEnum(UCHAR_SCRIPT, alias) instead.  This does
+ * a fast lookup with no access of the locale data.
+ * @param nameOrAbbrOrLocale name of the script, as given in
+ * PropertyValueAliases.txt, or ISO 15924 code or locale
+ * @param fillIn the UScriptCode buffer to fill in the script code
+ * @param capacity the capacity (size) fo UScriptCode buffer passed in.
+ * @param err the error status code.
+ * @return The number of script codes filled in the buffer passed in 
+ * @stable ICU 2.4
+ */
+U_STABLE int32_t  U_EXPORT2 
+uscript_getCode(const char* nameOrAbbrOrLocale,UScriptCode* fillIn,int32_t capacity,UErrorCode *err);
+
+/**
+ * Gets a script name associated with the given script code. 
+ * Returns  "Malayam" given USCRIPT_MALAYALAM
+ * @param scriptCode UScriptCode enum
+ * @return script long name as given in
+ * PropertyValueAliases.txt, or NULL if scriptCode is invalid
+ * @stable ICU 2.4
+ */
+U_STABLE const char*  U_EXPORT2 
+uscript_getName(UScriptCode scriptCode);
+
+/**
+ * Gets a script name associated with the given script code. 
+ * Returns  "Mlym" given USCRIPT_MALAYALAM
+ * @param scriptCode UScriptCode enum
+ * @return script abbreviated name as given in
+ * PropertyValueAliases.txt, or NULL if scriptCode is invalid
+ * @stable ICU 2.4
+ */
+U_STABLE const char*  U_EXPORT2 
+uscript_getShortName(UScriptCode scriptCode);
+
+/** 
+ * Gets the script code associated with the given codepoint.
+ * Returns USCRIPT_MALAYALAM given 0x0D02 
+ * @param codepoint UChar32 codepoint
+ * @param err the error status code.
+ * @return The UScriptCode, or 0 if codepoint is invalid 
+ * @stable ICU 2.4
+ */
+U_STABLE UScriptCode  U_EXPORT2 
+uscript_getScript(UChar32 codepoint, UErrorCode *err);
+
+#endif
+
+


[12/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/js/libs/require.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/js/libs/require.js b/apps/fauxton/assets/js/libs/require.js
deleted file mode 100644
index 2109a25..0000000
--- a/apps/fauxton/assets/js/libs/require.js
+++ /dev/null
@@ -1,2045 +0,0 @@
-/** vim: et:ts=4:sw=4:sts=4
- * @license RequireJS 2.1.6 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved.
- * Available via the MIT or new BSD license.
- * see: http://github.com/jrburke/requirejs for details
- */
-//Not using strict: uneven strict support in browsers, #392, and causes
-//problems with requirejs.exec()/transpiler plugins that may not be strict.
-/*jslint regexp: true, nomen: true, sloppy: true */
-/*global window, navigator, document, importScripts, setTimeout, opera */
-
-var requirejs, require, define;
-(function (global) {
-    var req, s, head, baseElement, dataMain, src,
-        interactiveScript, currentlyAddingScript, mainScript, subPath,
-        version = '2.1.6',
-        commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,
-        cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,
-        jsSuffixRegExp = /\.js$/,
-        currDirRegExp = /^\.\//,
-        op = Object.prototype,
-        ostring = op.toString,
-        hasOwn = op.hasOwnProperty,
-        ap = Array.prototype,
-        apsp = ap.splice,
-        isBrowser = !!(typeof window !== 'undefined' && navigator && window.document),
-        isWebWorker = !isBrowser && typeof importScripts !== 'undefined',
-        //PS3 indicates loaded and complete, but need to wait for complete
-        //specifically. Sequence is 'loading', 'loaded', execution,
-        // then 'complete'. The UA check is unfortunate, but not sure how
-        //to feature test w/o causing perf issues.
-        readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ?
-                      /^complete$/ : /^(complete|loaded)$/,
-        defContextName = '_',
-        //Oh the tragedy, detecting opera. See the usage of isOpera for reason.
-        isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]',
-        contexts = {},
-        cfg = {},
-        globalDefQueue = [],
-        useInteractive = false;
-
-    function isFunction(it) {
-        return ostring.call(it) === '[object Function]';
-    }
-
-    function isArray(it) {
-        return ostring.call(it) === '[object Array]';
-    }
-
-    /**
-     * Helper function for iterating over an array. If the func returns
-     * a true value, it will break out of the loop.
-     */
-    function each(ary, func) {
-        if (ary) {
-            var i;
-            for (i = 0; i < ary.length; i += 1) {
-                if (ary[i] && func(ary[i], i, ary)) {
-                    break;
-                }
-            }
-        }
-    }
-
-    /**
-     * Helper function for iterating over an array backwards. If the func
-     * returns a true value, it will break out of the loop.
-     */
-    function eachReverse(ary, func) {
-        if (ary) {
-            var i;
-            for (i = ary.length - 1; i > -1; i -= 1) {
-                if (ary[i] && func(ary[i], i, ary)) {
-                    break;
-                }
-            }
-        }
-    }
-
-    function hasProp(obj, prop) {
-        return hasOwn.call(obj, prop);
-    }
-
-    function getOwn(obj, prop) {
-        return hasProp(obj, prop) && obj[prop];
-    }
-
-    /**
-     * Cycles over properties in an object and calls a function for each
-     * property value. If the function returns a truthy value, then the
-     * iteration is stopped.
-     */
-    function eachProp(obj, func) {
-        var prop;
-        for (prop in obj) {
-            if (hasProp(obj, prop)) {
-                if (func(obj[prop], prop)) {
-                    break;
-                }
-            }
-        }
-    }
-
-    /**
-     * Simple function to mix in properties from source into target,
-     * but only if target does not already have a property of the same name.
-     */
-    function mixin(target, source, force, deepStringMixin) {
-        if (source) {
-            eachProp(source, function (value, prop) {
-                if (force || !hasProp(target, prop)) {
-                    if (deepStringMixin && typeof value !== 'string') {
-                        if (!target[prop]) {
-                            target[prop] = {};
-                        }
-                        mixin(target[prop], value, force, deepStringMixin);
-                    } else {
-                        target[prop] = value;
-                    }
-                }
-            });
-        }
-        return target;
-    }
-
-    //Similar to Function.prototype.bind, but the 'this' object is specified
-    //first, since it is easier to read/figure out what 'this' will be.
-    function bind(obj, fn) {
-        return function () {
-            return fn.apply(obj, arguments);
-        };
-    }
-
-    function scripts() {
-        return document.getElementsByTagName('script');
-    }
-
-    function defaultOnError(err) {
-        throw err;
-    }
-
-    //Allow getting a global that expressed in
-    //dot notation, like 'a.b.c'.
-    function getGlobal(value) {
-        if (!value) {
-            return value;
-        }
-        var g = global;
-        each(value.split('.'), function (part) {
-            g = g[part];
-        });
-        return g;
-    }
-
-    /**
-     * Constructs an error with a pointer to an URL with more information.
-     * @param {String} id the error ID that maps to an ID on a web page.
-     * @param {String} message human readable error.
-     * @param {Error} [err] the original error, if there is one.
-     *
-     * @returns {Error}
-     */
-    function makeError(id, msg, err, requireModules) {
-        var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id);
-        e.requireType = id;
-        e.requireModules = requireModules;
-        if (err) {
-            e.originalError = err;
-        }
-        return e;
-    }
-
-    if (typeof define !== 'undefined') {
-        //If a define is already in play via another AMD loader,
-        //do not overwrite.
-        return;
-    }
-
-    if (typeof requirejs !== 'undefined') {
-        if (isFunction(requirejs)) {
-            //Do not overwrite and existing requirejs instance.
-            return;
-        }
-        cfg = requirejs;
-        requirejs = undefined;
-    }
-
-    //Allow for a require config object
-    if (typeof require !== 'undefined' && !isFunction(require)) {
-        //assume it is a config object.
-        cfg = require;
-        require = undefined;
-    }
-
-    function newContext(contextName) {
-        var inCheckLoaded, Module, context, handlers,
-            checkLoadedTimeoutId,
-            config = {
-                //Defaults. Do not set a default for map
-                //config to speed up normalize(), which
-                //will run faster if there is no default.
-                waitSeconds: 7,
-                baseUrl: './',
-                paths: {},
-                pkgs: {},
-                shim: {},
-                config: {}
-            },
-            registry = {},
-            //registry of just enabled modules, to speed
-            //cycle breaking code when lots of modules
-            //are registered, but not activated.
-            enabledRegistry = {},
-            undefEvents = {},
-            defQueue = [],
-            defined = {},
-            urlFetched = {},
-            requireCounter = 1,
-            unnormalizedCounter = 1;
-
-        /**
-         * Trims the . and .. from an array of path segments.
-         * It will keep a leading path segment if a .. will become
-         * the first path segment, to help with module name lookups,
-         * which act like paths, but can be remapped. But the end result,
-         * all paths that use this function should look normalized.
-         * NOTE: this method MODIFIES the input array.
-         * @param {Array} ary the array of path segments.
-         */
-        function trimDots(ary) {
-            var i, part;
-            for (i = 0; ary[i]; i += 1) {
-                part = ary[i];
-                if (part === '.') {
-                    ary.splice(i, 1);
-                    i -= 1;
-                } else if (part === '..') {
-                    if (i === 1 && (ary[2] === '..' || ary[0] === '..')) {
-                        //End of the line. Keep at least one non-dot
-                        //path segment at the front so it can be mapped
-                        //correctly to disk. Otherwise, there is likely
-                        //no path mapping for a path starting with '..'.
-                        //This can still fail, but catches the most reasonable
-                        //uses of ..
-                        break;
-                    } else if (i > 0) {
-                        ary.splice(i - 1, 2);
-                        i -= 2;
-                    }
-                }
-            }
-        }
-
-        /**
-         * Given a relative module name, like ./something, normalize it to
-         * a real name that can be mapped to a path.
-         * @param {String} name the relative name
-         * @param {String} baseName a real name that the name arg is relative
-         * to.
-         * @param {Boolean} applyMap apply the map config to the value. Should
-         * only be done if this normalization is for a dependency ID.
-         * @returns {String} normalized name
-         */
-        function normalize(name, baseName, applyMap) {
-            var pkgName, pkgConfig, mapValue, nameParts, i, j, nameSegment,
-                foundMap, foundI, foundStarMap, starI,
-                baseParts = baseName && baseName.split('/'),
-                normalizedBaseParts = baseParts,
-                map = config.map,
-                starMap = map && map['*'];
-
-            //Adjust any relative paths.
-            if (name && name.charAt(0) === '.') {
-                //If have a base name, try to normalize against it,
-                //otherwise, assume it is a top-level require that will
-                //be relative to baseUrl in the end.
-                if (baseName) {
-                    if (getOwn(config.pkgs, baseName)) {
-                        //If the baseName is a package name, then just treat it as one
-                        //name to concat the name with.
-                        normalizedBaseParts = baseParts = [baseName];
-                    } else {
-                        //Convert baseName to array, and lop off the last part,
-                        //so that . matches that 'directory' and not name of the baseName's
-                        //module. For instance, baseName of 'one/two/three', maps to
-                        //'one/two/three.js', but we want the directory, 'one/two' for
-                        //this normalization.
-                        normalizedBaseParts = baseParts.slice(0, baseParts.length - 1);
-                    }
-
-                    name = normalizedBaseParts.concat(name.split('/'));
-                    trimDots(name);
-
-                    //Some use of packages may use a . path to reference the
-                    //'main' module name, so normalize for that.
-                    pkgConfig = getOwn(config.pkgs, (pkgName = name[0]));
-                    name = name.join('/');
-                    if (pkgConfig && name === pkgName + '/' + pkgConfig.main) {
-                        name = pkgName;
-                    }
-                } else if (name.indexOf('./') === 0) {
-                    // No baseName, so this is ID is resolved relative
-                    // to baseUrl, pull off the leading dot.
-                    name = name.substring(2);
-                }
-            }
-
-            //Apply map config if available.
-            if (applyMap && map && (baseParts || starMap)) {
-                nameParts = name.split('/');
-
-                for (i = nameParts.length; i > 0; i -= 1) {
-                    nameSegment = nameParts.slice(0, i).join('/');
-
-                    if (baseParts) {
-                        //Find the longest baseName segment match in the config.
-                        //So, do joins on the biggest to smallest lengths of baseParts.
-                        for (j = baseParts.length; j > 0; j -= 1) {
-                            mapValue = getOwn(map, baseParts.slice(0, j).join('/'));
-
-                            //baseName segment has config, find if it has one for
-                            //this name.
-                            if (mapValue) {
-                                mapValue = getOwn(mapValue, nameSegment);
-                                if (mapValue) {
-                                    //Match, update name to the new value.
-                                    foundMap = mapValue;
-                                    foundI = i;
-                                    break;
-                                }
-                            }
-                        }
-                    }
-
-                    if (foundMap) {
-                        break;
-                    }
-
-                    //Check for a star map match, but just hold on to it,
-                    //if there is a shorter segment match later in a matching
-                    //config, then favor over this star map.
-                    if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) {
-                        foundStarMap = getOwn(starMap, nameSegment);
-                        starI = i;
-                    }
-                }
-
-                if (!foundMap && foundStarMap) {
-                    foundMap = foundStarMap;
-                    foundI = starI;
-                }
-
-                if (foundMap) {
-                    nameParts.splice(0, foundI, foundMap);
-                    name = nameParts.join('/');
-                }
-            }
-
-            return name;
-        }
-
-        function removeScript(name) {
-            if (isBrowser) {
-                each(scripts(), function (scriptNode) {
-                    if (scriptNode.getAttribute('data-requiremodule') === name &&
-                            scriptNode.getAttribute('data-requirecontext') === context.contextName) {
-                        scriptNode.parentNode.removeChild(scriptNode);
-                        return true;
-                    }
-                });
-            }
-        }
-
-        function hasPathFallback(id) {
-            var pathConfig = getOwn(config.paths, id);
-            if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) {
-                removeScript(id);
-                //Pop off the first array value, since it failed, and
-                //retry
-                pathConfig.shift();
-                context.require.undef(id);
-                context.require([id]);
-                return true;
-            }
-        }
-
-        //Turns a plugin!resource to [plugin, resource]
-        //with the plugin being undefined if the name
-        //did not have a plugin prefix.
-        function splitPrefix(name) {
-            var prefix,
-                index = name ? name.indexOf('!') : -1;
-            if (index > -1) {
-                prefix = name.substring(0, index);
-                name = name.substring(index + 1, name.length);
-            }
-            return [prefix, name];
-        }
-
-        /**
-         * Creates a module mapping that includes plugin prefix, module
-         * name, and path. If parentModuleMap is provided it will
-         * also normalize the name via require.normalize()
-         *
-         * @param {String} name the module name
-         * @param {String} [parentModuleMap] parent module map
-         * for the module name, used to resolve relative names.
-         * @param {Boolean} isNormalized: is the ID already normalized.
-         * This is true if this call is done for a define() module ID.
-         * @param {Boolean} applyMap: apply the map config to the ID.
-         * Should only be true if this map is for a dependency.
-         *
-         * @returns {Object}
-         */
-        function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) {
-            var url, pluginModule, suffix, nameParts,
-                prefix = null,
-                parentName = parentModuleMap ? parentModuleMap.name : null,
-                originalName = name,
-                isDefine = true,
-                normalizedName = '';
-
-            //If no name, then it means it is a require call, generate an
-            //internal name.
-            if (!name) {
-                isDefine = false;
-                name = '_@r' + (requireCounter += 1);
-            }
-
-            nameParts = splitPrefix(name);
-            prefix = nameParts[0];
-            name = nameParts[1];
-
-            if (prefix) {
-                prefix = normalize(prefix, parentName, applyMap);
-                pluginModule = getOwn(defined, prefix);
-            }
-
-            //Account for relative paths if there is a base name.
-            if (name) {
-                if (prefix) {
-                    if (pluginModule && pluginModule.normalize) {
-                        //Plugin is loaded, use its normalize method.
-                        normalizedName = pluginModule.normalize(name, function (name) {
-                            return normalize(name, parentName, applyMap);
-                        });
-                    } else {
-                        normalizedName = normalize(name, parentName, applyMap);
-                    }
-                } else {
-                    //A regular module.
-                    normalizedName = normalize(name, parentName, applyMap);
-
-                    //Normalized name may be a plugin ID due to map config
-                    //application in normalize. The map config values must
-                    //already be normalized, so do not need to redo that part.
-                    nameParts = splitPrefix(normalizedName);
-                    prefix = nameParts[0];
-                    normalizedName = nameParts[1];
-                    isNormalized = true;
-
-                    url = context.nameToUrl(normalizedName);
-                }
-            }
-
-            //If the id is a plugin id that cannot be determined if it needs
-            //normalization, stamp it with a unique ID so two matching relative
-            //ids that may conflict can be separate.
-            suffix = prefix && !pluginModule && !isNormalized ?
-                     '_unnormalized' + (unnormalizedCounter += 1) :
-                     '';
-
-            return {
-                prefix: prefix,
-                name: normalizedName,
-                parentMap: parentModuleMap,
-                unnormalized: !!suffix,
-                url: url,
-                originalName: originalName,
-                isDefine: isDefine,
-                id: (prefix ?
-                        prefix + '!' + normalizedName :
-                        normalizedName) + suffix
-            };
-        }
-
-        function getModule(depMap) {
-            var id = depMap.id,
-                mod = getOwn(registry, id);
-
-            if (!mod) {
-                mod = registry[id] = new context.Module(depMap);
-            }
-
-            return mod;
-        }
-
-        function on(depMap, name, fn) {
-            var id = depMap.id,
-                mod = getOwn(registry, id);
-
-            if (hasProp(defined, id) &&
-                    (!mod || mod.defineEmitComplete)) {
-                if (name === 'defined') {
-                    fn(defined[id]);
-                }
-            } else {
-                mod = getModule(depMap);
-                if (mod.error && name === 'error') {
-                    fn(mod.error);
-                } else {
-                    mod.on(name, fn);
-                }
-            }
-        }
-
-        function onError(err, errback) {
-            var ids = err.requireModules,
-                notified = false;
-
-            if (errback) {
-                errback(err);
-            } else {
-                each(ids, function (id) {
-                    var mod = getOwn(registry, id);
-                    if (mod) {
-                        //Set error on module, so it skips timeout checks.
-                        mod.error = err;
-                        if (mod.events.error) {
-                            notified = true;
-                            mod.emit('error', err);
-                        }
-                    }
-                });
-
-                if (!notified) {
-                    req.onError(err);
-                }
-            }
-        }
-
-        /**
-         * Internal method to transfer globalQueue items to this context's
-         * defQueue.
-         */
-        function takeGlobalQueue() {
-            //Push all the globalDefQueue items into the context's defQueue
-            if (globalDefQueue.length) {
-                //Array splice in the values since the context code has a
-                //local var ref to defQueue, so cannot just reassign the one
-                //on context.
-                apsp.apply(defQueue,
-                           [defQueue.length - 1, 0].concat(globalDefQueue));
-                globalDefQueue = [];
-            }
-        }
-
-        handlers = {
-            'require': function (mod) {
-                if (mod.require) {
-                    return mod.require;
-                } else {
-                    return (mod.require = context.makeRequire(mod.map));
-                }
-            },
-            'exports': function (mod) {
-                mod.usingExports = true;
-                if (mod.map.isDefine) {
-                    if (mod.exports) {
-                        return mod.exports;
-                    } else {
-                        return (mod.exports = defined[mod.map.id] = {});
-                    }
-                }
-            },
-            'module': function (mod) {
-                if (mod.module) {
-                    return mod.module;
-                } else {
-                    return (mod.module = {
-                        id: mod.map.id,
-                        uri: mod.map.url,
-                        config: function () {
-                            var c,
-                                pkg = getOwn(config.pkgs, mod.map.id);
-                            // For packages, only support config targeted
-                            // at the main module.
-                            c = pkg ? getOwn(config.config, mod.map.id + '/' + pkg.main) :
-                                      getOwn(config.config, mod.map.id);
-                            return  c || {};
-                        },
-                        exports: defined[mod.map.id]
-                    });
-                }
-            }
-        };
-
-        function cleanRegistry(id) {
-            //Clean up machinery used for waiting modules.
-            delete registry[id];
-            delete enabledRegistry[id];
-        }
-
-        function breakCycle(mod, traced, processed) {
-            var id = mod.map.id;
-
-            if (mod.error) {
-                mod.emit('error', mod.error);
-            } else {
-                traced[id] = true;
-                each(mod.depMaps, function (depMap, i) {
-                    var depId = depMap.id,
-                        dep = getOwn(registry, depId);
-
-                    //Only force things that have not completed
-                    //being defined, so still in the registry,
-                    //and only if it has not been matched up
-                    //in the module already.
-                    if (dep && !mod.depMatched[i] && !processed[depId]) {
-                        if (getOwn(traced, depId)) {
-                            mod.defineDep(i, defined[depId]);
-                            mod.check(); //pass false?
-                        } else {
-                            breakCycle(dep, traced, processed);
-                        }
-                    }
-                });
-                processed[id] = true;
-            }
-        }
-
-        function checkLoaded() {
-            var map, modId, err, usingPathFallback,
-                waitInterval = config.waitSeconds * 1000,
-                //It is possible to disable the wait interval by using waitSeconds of 0.
-                expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(),
-                noLoads = [],
-                reqCalls = [],
-                stillLoading = false,
-                needCycleCheck = true;
-
-            //Do not bother if this call was a result of a cycle break.
-            if (inCheckLoaded) {
-                return;
-            }
-
-            inCheckLoaded = true;
-
-            //Figure out the state of all the modules.
-            eachProp(enabledRegistry, function (mod) {
-                map = mod.map;
-                modId = map.id;
-
-                //Skip things that are not enabled or in error state.
-                if (!mod.enabled) {
-                    return;
-                }
-
-                if (!map.isDefine) {
-                    reqCalls.push(mod);
-                }
-
-                if (!mod.error) {
-                    //If the module should be executed, and it has not
-                    //been inited and time is up, remember it.
-                    if (!mod.inited && expired) {
-                        if (hasPathFallback(modId)) {
-                            usingPathFallback = true;
-                            stillLoading = true;
-                        } else {
-                            noLoads.push(modId);
-                            removeScript(modId);
-                        }
-                    } else if (!mod.inited && mod.fetched && map.isDefine) {
-                        stillLoading = true;
-                        if (!map.prefix) {
-                            //No reason to keep looking for unfinished
-                            //loading. If the only stillLoading is a
-                            //plugin resource though, keep going,
-                            //because it may be that a plugin resource
-                            //is waiting on a non-plugin cycle.
-                            return (needCycleCheck = false);
-                        }
-                    }
-                }
-            });
-
-            if (expired && noLoads.length) {
-                //If wait time expired, throw error of unloaded modules.
-                err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads);
-                err.contextName = context.contextName;
-                return onError(err);
-            }
-
-            //Not expired, check for a cycle.
-            if (needCycleCheck) {
-                each(reqCalls, function (mod) {
-                    breakCycle(mod, {}, {});
-                });
-            }
-
-            //If still waiting on loads, and the waiting load is something
-            //other than a plugin resource, or there are still outstanding
-            //scripts, then just try back later.
-            if ((!expired || usingPathFallback) && stillLoading) {
-                //Something is still waiting to load. Wait for it, but only
-                //if a timeout is not already in effect.
-                if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) {
-                    checkLoadedTimeoutId = setTimeout(function () {
-                        checkLoadedTimeoutId = 0;
-                        checkLoaded();
-                    }, 50);
-                }
-            }
-
-            inCheckLoaded = false;
-        }
-
-        Module = function (map) {
-            this.events = getOwn(undefEvents, map.id) || {};
-            this.map = map;
-            this.shim = getOwn(config.shim, map.id);
-            this.depExports = [];
-            this.depMaps = [];
-            this.depMatched = [];
-            this.pluginMaps = {};
-            this.depCount = 0;
-
-            /* this.exports this.factory
-               this.depMaps = [],
-               this.enabled, this.fetched
-            */
-        };
-
-        Module.prototype = {
-            init: function (depMaps, factory, errback, options) {
-                options = options || {};
-
-                //Do not do more inits if already done. Can happen if there
-                //are multiple define calls for the same module. That is not
-                //a normal, common case, but it is also not unexpected.
-                if (this.inited) {
-                    return;
-                }
-
-                this.factory = factory;
-
-                if (errback) {
-                    //Register for errors on this module.
-                    this.on('error', errback);
-                } else if (this.events.error) {
-                    //If no errback already, but there are error listeners
-                    //on this module, set up an errback to pass to the deps.
-                    errback = bind(this, function (err) {
-                        this.emit('error', err);
-                    });
-                }
-
-                //Do a copy of the dependency array, so that
-                //source inputs are not modified. For example
-                //"shim" deps are passed in here directly, and
-                //doing a direct modification of the depMaps array
-                //would affect that config.
-                this.depMaps = depMaps && depMaps.slice(0);
-
-                this.errback = errback;
-
-                //Indicate this module has be initialized
-                this.inited = true;
-
-                this.ignore = options.ignore;
-
-                //Could have option to init this module in enabled mode,
-                //or could have been previously marked as enabled. However,
-                //the dependencies are not known until init is called. So
-                //if enabled previously, now trigger dependencies as enabled.
-                if (options.enabled || this.enabled) {
-                    //Enable this module and dependencies.
-                    //Will call this.check()
-                    this.enable();
-                } else {
-                    this.check();
-                }
-            },
-
-            defineDep: function (i, depExports) {
-                //Because of cycles, defined callback for a given
-                //export can be called more than once.
-                if (!this.depMatched[i]) {
-                    this.depMatched[i] = true;
-                    this.depCount -= 1;
-                    this.depExports[i] = depExports;
-                }
-            },
-
-            fetch: function () {
-                if (this.fetched) {
-                    return;
-                }
-                this.fetched = true;
-
-                context.startTime = (new Date()).getTime();
-
-                var map = this.map;
-
-                //If the manager is for a plugin managed resource,
-                //ask the plugin to load it now.
-                if (this.shim) {
-                    context.makeRequire(this.map, {
-                        enableBuildCallback: true
-                    })(this.shim.deps || [], bind(this, function () {
-                        return map.prefix ? this.callPlugin() : this.load();
-                    }));
-                } else {
-                    //Regular dependency.
-                    return map.prefix ? this.callPlugin() : this.load();
-                }
-            },
-
-            load: function () {
-                var url = this.map.url;
-
-                //Regular dependency.
-                if (!urlFetched[url]) {
-                    urlFetched[url] = true;
-                    context.load(this.map.id, url);
-                }
-            },
-
-            /**
-             * Checks if the module is ready to define itself, and if so,
-             * define it.
-             */
-            check: function () {
-                if (!this.enabled || this.enabling) {
-                    return;
-                }
-
-                var err, cjsModule,
-                    id = this.map.id,
-                    depExports = this.depExports,
-                    exports = this.exports,
-                    factory = this.factory;
-
-                if (!this.inited) {
-                    this.fetch();
-                } else if (this.error) {
-                    this.emit('error', this.error);
-                } else if (!this.defining) {
-                    //The factory could trigger another require call
-                    //that would result in checking this module to
-                    //define itself again. If already in the process
-                    //of doing that, skip this work.
-                    this.defining = true;
-
-                    if (this.depCount < 1 && !this.defined) {
-                        if (isFunction(factory)) {
-                            //If there is an error listener, favor passing
-                            //to that instead of throwing an error. However,
-                            //only do it for define()'d  modules. require
-                            //errbacks should not be called for failures in
-                            //their callbacks (#699). However if a global
-                            //onError is set, use that.
-                            if ((this.events.error && this.map.isDefine) ||
-                                req.onError !== defaultOnError) {
-                                try {
-                                    exports = context.execCb(id, factory, depExports, exports);
-                                } catch (e) {
-                                    err = e;
-                                }
-                            } else {
-                                exports = context.execCb(id, factory, depExports, exports);
-                            }
-
-                            if (this.map.isDefine) {
-                                //If setting exports via 'module' is in play,
-                                //favor that over return value and exports. After that,
-                                //favor a non-undefined return value over exports use.
-                                cjsModule = this.module;
-                                if (cjsModule &&
-                                        cjsModule.exports !== undefined &&
-                                        //Make sure it is not already the exports value
-                                        cjsModule.exports !== this.exports) {
-                                    exports = cjsModule.exports;
-                                } else if (exports === undefined && this.usingExports) {
-                                    //exports already set the defined value.
-                                    exports = this.exports;
-                                }
-                            }
-
-                            if (err) {
-                                err.requireMap = this.map;
-                                err.requireModules = this.map.isDefine ? [this.map.id] : null;
-                                err.requireType = this.map.isDefine ? 'define' : 'require';
-                                return onError((this.error = err));
-                            }
-
-                        } else {
-                            //Just a literal value
-                            exports = factory;
-                        }
-
-                        this.exports = exports;
-
-                        if (this.map.isDefine && !this.ignore) {
-                            defined[id] = exports;
-
-                            if (req.onResourceLoad) {
-                                req.onResourceLoad(context, this.map, this.depMaps);
-                            }
-                        }
-
-                        //Clean up
-                        cleanRegistry(id);
-
-                        this.defined = true;
-                    }
-
-                    //Finished the define stage. Allow calling check again
-                    //to allow define notifications below in the case of a
-                    //cycle.
-                    this.defining = false;
-
-                    if (this.defined && !this.defineEmitted) {
-                        this.defineEmitted = true;
-                        this.emit('defined', this.exports);
-                        this.defineEmitComplete = true;
-                    }
-
-                }
-            },
-
-            callPlugin: function () {
-                var map = this.map,
-                    id = map.id,
-                    //Map already normalized the prefix.
-                    pluginMap = makeModuleMap(map.prefix);
-
-                //Mark this as a dependency for this plugin, so it
-                //can be traced for cycles.
-                this.depMaps.push(pluginMap);
-
-                on(pluginMap, 'defined', bind(this, function (plugin) {
-                    var load, normalizedMap, normalizedMod,
-                        name = this.map.name,
-                        parentName = this.map.parentMap ? this.map.parentMap.name : null,
-                        localRequire = context.makeRequire(map.parentMap, {
-                            enableBuildCallback: true
-                        });
-
-                    //If current map is not normalized, wait for that
-                    //normalized name to load instead of continuing.
-                    if (this.map.unnormalized) {
-                        //Normalize the ID if the plugin allows it.
-                        if (plugin.normalize) {
-                            name = plugin.normalize(name, function (name) {
-                                return normalize(name, parentName, true);
-                            }) || '';
-                        }
-
-                        //prefix and name should already be normalized, no need
-                        //for applying map config again either.
-                        normalizedMap = makeModuleMap(map.prefix + '!' + name,
-                                                      this.map.parentMap);
-                        on(normalizedMap,
-                            'defined', bind(this, function (value) {
-                                this.init([], function () { return value; }, null, {
-                                    enabled: true,
-                                    ignore: true
-                                });
-                            }));
-
-                        normalizedMod = getOwn(registry, normalizedMap.id);
-                        if (normalizedMod) {
-                            //Mark this as a dependency for this plugin, so it
-                            //can be traced for cycles.
-                            this.depMaps.push(normalizedMap);
-
-                            if (this.events.error) {
-                                normalizedMod.on('error', bind(this, function (err) {
-                                    this.emit('error', err);
-                                }));
-                            }
-                            normalizedMod.enable();
-                        }
-
-                        return;
-                    }
-
-                    load = bind(this, function (value) {
-                        this.init([], function () { return value; }, null, {
-                            enabled: true
-                        });
-                    });
-
-                    load.error = bind(this, function (err) {
-                        this.inited = true;
-                        this.error = err;
-                        err.requireModules = [id];
-
-                        //Remove temp unnormalized modules for this module,
-                        //since they will never be resolved otherwise now.
-                        eachProp(registry, function (mod) {
-                            if (mod.map.id.indexOf(id + '_unnormalized') === 0) {
-                                cleanRegistry(mod.map.id);
-                            }
-                        });
-
-                        onError(err);
-                    });
-
-                    //Allow plugins to load other code without having to know the
-                    //context or how to 'complete' the load.
-                    load.fromText = bind(this, function (text, textAlt) {
-                        /*jslint evil: true */
-                        var moduleName = map.name,
-                            moduleMap = makeModuleMap(moduleName),
-                            hasInteractive = useInteractive;
-
-                        //As of 2.1.0, support just passing the text, to reinforce
-                        //fromText only being called once per resource. Still
-                        //support old style of passing moduleName but discard
-                        //that moduleName in favor of the internal ref.
-                        if (textAlt) {
-                            text = textAlt;
-                        }
-
-                        //Turn off interactive script matching for IE for any define
-                        //calls in the text, then turn it back on at the end.
-                        if (hasInteractive) {
-                            useInteractive = false;
-                        }
-
-                        //Prime the system by creating a module instance for
-                        //it.
-                        getModule(moduleMap);
-
-                        //Transfer any config to this other module.
-                        if (hasProp(config.config, id)) {
-                            config.config[moduleName] = config.config[id];
-                        }
-
-                        try {
-                            req.exec(text);
-                        } catch (e) {
-                            return onError(makeError('fromtexteval',
-                                             'fromText eval for ' + id +
-                                            ' failed: ' + e,
-                                             e,
-                                             [id]));
-                        }
-
-                        if (hasInteractive) {
-                            useInteractive = true;
-                        }
-
-                        //Mark this as a dependency for the plugin
-                        //resource
-                        this.depMaps.push(moduleMap);
-
-                        //Support anonymous modules.
-                        context.completeLoad(moduleName);
-
-                        //Bind the value of that module to the value for this
-                        //resource ID.
-                        localRequire([moduleName], load);
-                    });
-
-                    //Use parentName here since the plugin's name is not reliable,
-                    //could be some weird string with no path that actually wants to
-                    //reference the parentName's path.
-                    plugin.load(map.name, localRequire, load, config);
-                }));
-
-                context.enable(pluginMap, this);
-                this.pluginMaps[pluginMap.id] = pluginMap;
-            },
-
-            enable: function () {
-                enabledRegistry[this.map.id] = this;
-                this.enabled = true;
-
-                //Set flag mentioning that the module is enabling,
-                //so that immediate calls to the defined callbacks
-                //for dependencies do not trigger inadvertent load
-                //with the depCount still being zero.
-                this.enabling = true;
-
-                //Enable each dependency
-                each(this.depMaps, bind(this, function (depMap, i) {
-                    var id, mod, handler;
-
-                    if (typeof depMap === 'string') {
-                        //Dependency needs to be converted to a depMap
-                        //and wired up to this module.
-                        depMap = makeModuleMap(depMap,
-                                               (this.map.isDefine ? this.map : this.map.parentMap),
-                                               false,
-                                               !this.skipMap);
-                        this.depMaps[i] = depMap;
-
-                        handler = getOwn(handlers, depMap.id);
-
-                        if (handler) {
-                            this.depExports[i] = handler(this);
-                            return;
-                        }
-
-                        this.depCount += 1;
-
-                        on(depMap, 'defined', bind(this, function (depExports) {
-                            this.defineDep(i, depExports);
-                            this.check();
-                        }));
-
-                        if (this.errback) {
-                            on(depMap, 'error', bind(this, this.errback));
-                        }
-                    }
-
-                    id = depMap.id;
-                    mod = registry[id];
-
-                    //Skip special modules like 'require', 'exports', 'module'
-                    //Also, don't call enable if it is already enabled,
-                    //important in circular dependency cases.
-                    if (!hasProp(handlers, id) && mod && !mod.enabled) {
-                        context.enable(depMap, this);
-                    }
-                }));
-
-                //Enable each plugin that is used in
-                //a dependency
-                eachProp(this.pluginMaps, bind(this, function (pluginMap) {
-                    var mod = getOwn(registry, pluginMap.id);
-                    if (mod && !mod.enabled) {
-                        context.enable(pluginMap, this);
-                    }
-                }));
-
-                this.enabling = false;
-
-                this.check();
-            },
-
-            on: function (name, cb) {
-                var cbs = this.events[name];
-                if (!cbs) {
-                    cbs = this.events[name] = [];
-                }
-                cbs.push(cb);
-            },
-
-            emit: function (name, evt) {
-                each(this.events[name], function (cb) {
-                    cb(evt);
-                });
-                if (name === 'error') {
-                    //Now that the error handler was triggered, remove
-                    //the listeners, since this broken Module instance
-                    //can stay around for a while in the registry.
-                    delete this.events[name];
-                }
-            }
-        };
-
-        function callGetModule(args) {
-            //Skip modules already defined.
-            if (!hasProp(defined, args[0])) {
-                getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]);
-            }
-        }
-
-        function removeListener(node, func, name, ieName) {
-            //Favor detachEvent because of IE9
-            //issue, see attachEvent/addEventListener comment elsewhere
-            //in this file.
-            if (node.detachEvent && !isOpera) {
-                //Probably IE. If not it will throw an error, which will be
-                //useful to know.
-                if (ieName) {
-                    node.detachEvent(ieName, func);
-                }
-            } else {
-                node.removeEventListener(name, func, false);
-            }
-        }
-
-        /**
-         * Given an event from a script node, get the requirejs info from it,
-         * and then removes the event listeners on the node.
-         * @param {Event} evt
-         * @returns {Object}
-         */
-        function getScriptData(evt) {
-            //Using currentTarget instead of target for Firefox 2.0's sake. Not
-            //all old browsers will be supported, but this one was easy enough
-            //to support and still makes sense.
-            var node = evt.currentTarget || evt.srcElement;
-
-            //Remove the listeners once here.
-            removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange');
-            removeListener(node, context.onScriptError, 'error');
-
-            return {
-                node: node,
-                id: node && node.getAttribute('data-requiremodule')
-            };
-        }
-
-        function intakeDefines() {
-            var args;
-
-            //Any defined modules in the global queue, intake them now.
-            takeGlobalQueue();
-
-            //Make sure any remaining defQueue items get properly processed.
-            while (defQueue.length) {
-                args = defQueue.shift();
-                if (args[0] === null) {
-                    return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1]));
-                } else {
-                    //args are id, deps, factory. Should be normalized by the
-                    //define() function.
-                    callGetModule(args);
-                }
-            }
-        }
-
-        context = {
-            config: config,
-            contextName: contextName,
-            registry: registry,
-            defined: defined,
-            urlFetched: urlFetched,
-            defQueue: defQueue,
-            Module: Module,
-            makeModuleMap: makeModuleMap,
-            nextTick: req.nextTick,
-            onError: onError,
-
-            /**
-             * Set a configuration for the context.
-             * @param {Object} cfg config object to integrate.
-             */
-            configure: function (cfg) {
-                //Make sure the baseUrl ends in a slash.
-                if (cfg.baseUrl) {
-                    if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') {
-                        cfg.baseUrl += '/';
-                    }
-                }
-
-                //Save off the paths and packages since they require special processing,
-                //they are additive.
-                var pkgs = config.pkgs,
-                    shim = config.shim,
-                    objs = {
-                        paths: true,
-                        config: true,
-                        map: true
-                    };
-
-                eachProp(cfg, function (value, prop) {
-                    if (objs[prop]) {
-                        if (prop === 'map') {
-                            if (!config.map) {
-                                config.map = {};
-                            }
-                            mixin(config[prop], value, true, true);
-                        } else {
-                            mixin(config[prop], value, true);
-                        }
-                    } else {
-                        config[prop] = value;
-                    }
-                });
-
-                //Merge shim
-                if (cfg.shim) {
-                    eachProp(cfg.shim, function (value, id) {
-                        //Normalize the structure
-                        if (isArray(value)) {
-                            value = {
-                                deps: value
-                            };
-                        }
-                        if ((value.exports || value.init) && !value.exportsFn) {
-                            value.exportsFn = context.makeShimExports(value);
-                        }
-                        shim[id] = value;
-                    });
-                    config.shim = shim;
-                }
-
-                //Adjust packages if necessary.
-                if (cfg.packages) {
-                    each(cfg.packages, function (pkgObj) {
-                        var location;
-
-                        pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj;
-                        location = pkgObj.location;
-
-                        //Create a brand new object on pkgs, since currentPackages can
-                        //be passed in again, and config.pkgs is the internal transformed
-                        //state for all package configs.
-                        pkgs[pkgObj.name] = {
-                            name: pkgObj.name,
-                            location: location || pkgObj.name,
-                            //Remove leading dot in main, so main paths are normalized,
-                            //and remove any trailing .js, since different package
-                            //envs have different conventions: some use a module name,
-                            //some use a file name.
-                            main: (pkgObj.main || 'main')
-                                  .replace(currDirRegExp, '')
-                                  .replace(jsSuffixRegExp, '')
-                        };
-                    });
-
-                    //Done with modifications, assing packages back to context config
-                    config.pkgs = pkgs;
-                }
-
-                //If there are any "waiting to execute" modules in the registry,
-                //update the maps for them, since their info, like URLs to load,
-                //may have changed.
-                eachProp(registry, function (mod, id) {
-                    //If module already has init called, since it is too
-                    //late to modify them, and ignore unnormalized ones
-                    //since they are transient.
-                    if (!mod.inited && !mod.map.unnormalized) {
-                        mod.map = makeModuleMap(id);
-                    }
-                });
-
-                //If a deps array or a config callback is specified, then call
-                //require with those args. This is useful when require is defined as a
-                //config object before require.js is loaded.
-                if (cfg.deps || cfg.callback) {
-                    context.require(cfg.deps || [], cfg.callback);
-                }
-            },
-
-            makeShimExports: function (value) {
-                function fn() {
-                    var ret;
-                    if (value.init) {
-                        ret = value.init.apply(global, arguments);
-                    }
-                    return ret || (value.exports && getGlobal(value.exports));
-                }
-                return fn;
-            },
-
-            makeRequire: function (relMap, options) {
-                options = options || {};
-
-                function localRequire(deps, callback, errback) {
-                    var id, map, requireMod;
-
-                    if (options.enableBuildCallback && callback && isFunction(callback)) {
-                        callback.__requireJsBuild = true;
-                    }
-
-                    if (typeof deps === 'string') {
-                        if (isFunction(callback)) {
-                            //Invalid call
-                            return onError(makeError('requireargs', 'Invalid require call'), errback);
-                        }
-
-                        //If require|exports|module are requested, get the
-                        //value for them from the special handlers. Caveat:
-                        //this only works while module is being defined.
-                        if (relMap && hasProp(handlers, deps)) {
-                            return handlers[deps](registry[relMap.id]);
-                        }
-
-                        //Synchronous access to one module. If require.get is
-                        //available (as in the Node adapter), prefer that.
-                        if (req.get) {
-                            return req.get(context, deps, relMap, localRequire);
-                        }
-
-                        //Normalize module name, if it contains . or ..
-                        map = makeModuleMap(deps, relMap, false, true);
-                        id = map.id;
-
-                        if (!hasProp(defined, id)) {
-                            return onError(makeError('notloaded', 'Module name "' +
-                                        id +
-                                        '" has not been loaded yet for context: ' +
-                                        contextName +
-                                        (relMap ? '' : '. Use require([])')));
-                        }
-                        return defined[id];
-                    }
-
-                    //Grab defines waiting in the global queue.
-                    intakeDefines();
-
-                    //Mark all the dependencies as needing to be loaded.
-                    context.nextTick(function () {
-                        //Some defines could have been added since the
-                        //require call, collect them.
-                        intakeDefines();
-
-                        requireMod = getModule(makeModuleMap(null, relMap));
-
-                        //Store if map config should be applied to this require
-                        //call for dependencies.
-                        requireMod.skipMap = options.skipMap;
-
-                        requireMod.init(deps, callback, errback, {
-                            enabled: true
-                        });
-
-                        checkLoaded();
-                    });
-
-                    return localRequire;
-                }
-
-                mixin(localRequire, {
-                    isBrowser: isBrowser,
-
-                    /**
-                     * Converts a module name + .extension into an URL path.
-                     * *Requires* the use of a module name. It does not support using
-                     * plain URLs like nameToUrl.
-                     */
-                    toUrl: function (moduleNamePlusExt) {
-                        var ext,
-                            index = moduleNamePlusExt.lastIndexOf('.'),
-                            segment = moduleNamePlusExt.split('/')[0],
-                            isRelative = segment === '.' || segment === '..';
-
-                        //Have a file extension alias, and it is not the
-                        //dots from a relative path.
-                        if (index !== -1 && (!isRelative || index > 1)) {
-                            ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length);
-                            moduleNamePlusExt = moduleNamePlusExt.substring(0, index);
-                        }
-
-                        return context.nameToUrl(normalize(moduleNamePlusExt,
-                                                relMap && relMap.id, true), ext,  true);
-                    },
-
-                    defined: function (id) {
-                        return hasProp(defined, makeModuleMap(id, relMap, false, true).id);
-                    },
-
-                    specified: function (id) {
-                        id = makeModuleMap(id, relMap, false, true).id;
-                        return hasProp(defined, id) || hasProp(registry, id);
-                    }
-                });
-
-                //Only allow undef on top level require calls
-                if (!relMap) {
-                    localRequire.undef = function (id) {
-                        //Bind any waiting define() calls to this context,
-                        //fix for #408
-                        takeGlobalQueue();
-
-                        var map = makeModuleMap(id, relMap, true),
-                            mod = getOwn(registry, id);
-
-                        delete defined[id];
-                        delete urlFetched[map.url];
-                        delete undefEvents[id];
-
-                        if (mod) {
-                            //Hold on to listeners in case the
-                            //module will be attempted to be reloaded
-                            //using a different config.
-                            if (mod.events.defined) {
-                                undefEvents[id] = mod.events;
-                            }
-
-                            cleanRegistry(id);
-                        }
-                    };
-                }
-
-                return localRequire;
-            },
-
-            /**
-             * Called to enable a module if it is still in the registry
-             * awaiting enablement. A second arg, parent, the parent module,
-             * is passed in for context, when this method is overriden by
-             * the optimizer. Not shown here to keep code compact.
-             */
-            enable: function (depMap) {
-                var mod = getOwn(registry, depMap.id);
-                if (mod) {
-                    getModule(depMap).enable();
-                }
-            },
-
-            /**
-             * Internal method used by environment adapters to complete a load event.
-             * A load event could be a script load or just a load pass from a synchronous
-             * load call.
-             * @param {String} moduleName the name of the module to potentially complete.
-             */
-            completeLoad: function (moduleName) {
-                var found, args, mod,
-                    shim = getOwn(config.shim, moduleName) || {},
-                    shExports = shim.exports;
-
-                takeGlobalQueue();
-
-                while (defQueue.length) {
-                    args = defQueue.shift();
-                    if (args[0] === null) {
-                        args[0] = moduleName;
-                        //If already found an anonymous module and bound it
-                        //to this name, then this is some other anon module
-                        //waiting for its completeLoad to fire.
-                        if (found) {
-                            break;
-                        }
-                        found = true;
-                    } else if (args[0] === moduleName) {
-                        //Found matching define call for this script!
-                        found = true;
-                    }
-
-                    callGetModule(args);
-                }
-
-                //Do this after the cycle of callGetModule in case the result
-                //of those calls/init calls changes the registry.
-                mod = getOwn(registry, moduleName);
-
-                if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) {
-                    if (config.enforceDefine && (!shExports || !getGlobal(shExports))) {
-                        if (hasPathFallback(moduleName)) {
-                            return;
-                        } else {
-                            return onError(makeError('nodefine',
-                                             'No define call for ' + moduleName,
-                                             null,
-                                             [moduleName]));
-                        }
-                    } else {
-                        //A script that does not call define(), so just simulate
-                        //the call for it.
-                        callGetModule([moduleName, (shim.deps || []), shim.exportsFn]);
-                    }
-                }
-
-                checkLoaded();
-            },
-
-            /**
-             * Converts a module name to a file path. Supports cases where
-             * moduleName may actually be just an URL.
-             * Note that it **does not** call normalize on the moduleName,
-             * it is assumed to have already been normalized. This is an
-             * internal API, not a public one. Use toUrl for the public API.
-             */
-            nameToUrl: function (moduleName, ext, skipExt) {
-                var paths, pkgs, pkg, pkgPath, syms, i, parentModule, url,
-                    parentPath;
-
-                //If a colon is in the URL, it indicates a protocol is used and it is just
-                //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?)
-                //or ends with .js, then assume the user meant to use an url and not a module id.
-                //The slash is important for protocol-less URLs as well as full paths.
-                if (req.jsExtRegExp.test(moduleName)) {
-                    //Just a plain path, not module name lookup, so just return it.
-                    //Add extension if it is included. This is a bit wonky, only non-.js things pass
-                    //an extension, this method probably needs to be reworked.
-                    url = moduleName + (ext || '');
-                } else {
-                    //A module that needs to be converted to a path.
-                    paths = config.paths;
-                    pkgs = config.pkgs;
-
-                    syms = moduleName.split('/');
-                    //For each module name segment, see if there is a path
-                    //registered for it. Start with most specific name
-                    //and work up from it.
-                    for (i = syms.length; i > 0; i -= 1) {
-                        parentModule = syms.slice(0, i).join('/');
-                        pkg = getOwn(pkgs, parentModule);
-                        parentPath = getOwn(paths, parentModule);
-                        if (parentPath) {
-                            //If an array, it means there are a few choices,
-                            //Choose the one that is desired
-                            if (isArray(parentPath)) {
-                                parentPath = parentPath[0];
-                            }
-                            syms.splice(0, i, parentPath);
-                            break;
-                        } else if (pkg) {
-                            //If module name is just the package name, then looking
-                            //for the main module.
-                            if (moduleName === pkg.name) {
-                                pkgPath = pkg.location + '/' + pkg.main;
-                            } else {
-                                pkgPath = pkg.location;
-                            }
-                            syms.splice(0, i, pkgPath);
-                            break;
-                        }
-                    }
-
-                    //Join the path parts together, then figure out if baseUrl is needed.
-                    url = syms.join('/');
-                    url += (ext || (/\?/.test(url) || skipExt ? '' : '.js'));
-                    url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url;
-                }
-
-                return config.urlArgs ? url +
-                                        ((url.indexOf('?') === -1 ? '?' : '&') +
-                                         config.urlArgs) : url;
-            },
-
-            //Delegates to req.load. Broken out as a separate function to
-            //allow overriding in the optimizer.
-            load: function (id, url) {
-                req.load(context, id, url);
-            },
-
-            /**
-             * Executes a module callback function. Broken out as a separate function
-             * solely to allow the build system to sequence the files in the built
-             * layer in the right sequence.
-             *
-             * @private
-             */
-            execCb: function (name, callback, args, exports) {
-                return callback.apply(exports, args);
-            },
-
-            /**
-             * callback for script loads, used to check status of loading.
-             *
-             * @param {Event} evt the event from the browser for the script
-             * that was loaded.
-             */
-            onScriptLoad: function (evt) {
-                //Using currentTarget instead of target for Firefox 2.0's sake. Not
-                //all old browsers will be supported, but this one was easy enough
-                //to support and still makes sense.
-                if (evt.type === 'load' ||
-                        (readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) {
-                    //Reset interactive script so a script node is not held onto for
-                    //to long.
-                    interactiveScript = null;
-
-                    //Pull out the name of the module and the context.
-                    var data = getScriptData(evt);
-                    context.completeLoad(data.id);
-                }
-            },
-
-            /**
-             * Callback for script errors.
-             */
-            onScriptError: function (evt) {
-                var data = getScriptData(evt);
-                if (!hasPathFallback(data.id)) {
-                    return onError(makeError('scripterror', 'Script error for: ' + data.id, evt, [data.id]));
-                }
-            }
-        };
-
-        context.require = context.makeRequire();
-        return context;
-    }
-
-    /**
-     * Main entry point.
-     *
-     * If the only argument to require is a string, then the module that
-     * is represented by that string is fetched for the appropriate context.
-     *
-     * If the first argument is an array, then it will be treated as an array
-     * of dependency string names to fetch. An optional function callback can
-     * be specified to execute when all of those dependencies are available.
-     *
-     * Make a local req variable to help Caja compliance (it assumes things
-     * on a require that are not standardized), and to give a short
-     * name for minification/local scope use.
-     */
-    req = requirejs = function (deps, callback, errback, optional) {
-
-        //Find the right context, use default
-        var context, config,
-            contextName = defContextName;
-
-        // Determine if have config object in the call.
-        if (!isArray(deps) && typeof deps !== 'string') {
-            // deps is a config object
-            config = deps;
-            if (isArray(callback)) {
-                // Adjust args if there are dependencies
-                deps = callback;
-                callback = errback;
-                errback = optional;
-            } else {
-                deps = [];
-            }
-        }
-
-        if (config && config.context) {
-            contextName = config.context;
-        }
-
-        context = getOwn(contexts, contextName);
-        if (!context) {
-            context = contexts[contextName] = req.s.newContext(contextName);
-        }
-
-        if (config) {
-            context.configure(config);
-        }
-
-        return context.require(deps, callback, errback);
-    };
-
-    /**
-     * Support require.config() to make it easier to cooperate with other
-     * AMD loaders on globally agreed names.
-     */
-    req.config = function (config) {
-        return req(config);
-    };
-
-    /**
-     * Execute something after the current tick
-     * of the event loop. Override for other envs
-     * that have a better solution than setTimeout.
-     * @param  {Function} fn function to execute later.
-     */
-    req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) {
-        setTimeout(fn, 4);
-    } : function (fn) { fn(); };
-
-    /**
-     * Export require as a global, but only if it does not already exist.
-     */
-    if (!require) {
-        require = req;
-    }
-
-    req.version = version;
-
-    //Used to filter out dependencies that are already paths.
-    req.jsExtRegExp = /^\/|:|\?|\.js$/;
-    req.isBrowser = isBrowser;
-    s = req.s = {
-        contexts: contexts,
-        newContext: newContext
-    };
-
-    //Create default context.
-    req({});
-
-    //Exports some context-sensitive methods on global require.
-    each([
-        'toUrl',
-        'undef',
-        'defined',
-        'specified'
-    ], function (prop) {
-        //Reference from contexts instead of early binding to default context,
-        //so that during builds, the latest instance of the default context
-        //with its config gets used.
-        req[prop] = function () {
-            var ctx = contexts[defContextName];
-            return ctx.require[prop].apply(ctx, arguments);
-        };
-    });
-
-    if (isBrowser) {
-        head = s.head = document.getElementsByTagName('head')[0];
-        //If BASE tag is in play, using appendChild is a problem for IE6.
-        //When that browser dies, this can be removed. Details in this jQuery bug:
-        //http://dev.jquery.com/ticket/2709
-        baseElement = document.getElementsByTagName('base')[0];
-        if (baseElement) {
-            head = s.head = baseElement.parentNode;
-        }
-    }
-
-    /**
-     * Any errors that require explicitly generates will be passed to this
-     * function. Intercept/override it if you want custom error handling.
-     * @param {Error} err the error object.
-     */
-    req.onError = defaultOnError;
-
-    /**
-     * Does the request to load a module for the browser case.
-     * Make this a separate function to allow other environments
-     * to override it.
-     *
-     * @param {Object} context the require context to find state.
-     * @param {String} moduleName the name of the module.
-     * @param {Object} url the URL to the module.
-     */
-    req.load = function (context, moduleName, url) {
-        var config = (context && context.config) || {},
-            node;
-        if (isBrowser) {
-            //In the browser so use a script tag
-            node = config.xhtml ?
-                    document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') :
-                    document.createElement('script');
-            node.type = config.scriptType || 'text/javascript';
-            node.charset = 'utf-8';
-            node.async = true;
-
-            node.setAttribute('data-requirecontext', context.contextName);
-            node.setAttribute('data-requiremodule', moduleName);
-
-            //Set up load listener. Test attachEvent first because IE9 has
-            //a subtle issue in its addEventListener and script onload firings
-            //that do not match the behavior of all other browsers with
-            //addEventListener support, which fire the onload event for a
-            //script right after the script execution. See:
-            //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution
-            //UNFORTUNATELY Opera implements attachEvent but does not follow the script
-            //script execution mode.
-            if (node.attachEvent &&
-                    //Check if node.attachEvent is artificially added by custom script or
-                    //natively supported by browser
-                    //read https://github.com/jrburke/requirejs/issues/187
-                    //if we can NOT find [native code] then it must NOT natively supported.
-                    //in IE8, node.attachEvent does not have toString()
-                    //Note the test for "[native code" with no closing brace, see:
-                    //https://github.com/jrburke/requirejs/issues/273
-                    !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) &&
-                    !isOpera) {
-                //Probably IE. IE (at least 6-8) do not fire
-                //script onload right after executing the script, so
-                //we cannot tie the anonymous define call to a name.
-                //However, IE reports the script as being in 'interactive'
-                //readyState at the time of the define call.
-                useInteractive = true;
-
-                node.attachEvent('onreadystatechange', context.onScriptLoad);
-                //It would be great to add an error handler here to catch
-                //404s in IE9+. However, onreadystatechange will fire before
-                //the error handler, so that does not help. If addEventListener
-                //is used, then IE will fire error before load, but we cannot
-                //use that pathway given the connect.microsoft.com issue
-                //mentioned above about not doing the 'script execute,
-                //then fire the script load event listener before execute
-                //next script' that other browsers do.
-                //Best hope: IE10 fixes the issues,
-                //and then destroys all installs of IE 6-9.
-                //node.attachEvent('onerror', context.onScriptError);
-            } else {
-                node.addEventListener('load', context.onScriptLoad, false);
-                node.addEventListener('error', context.onScriptError, false);
-            }
-            node.src = url;
-
-            //For some cache cases in IE 6-8, the script executes before the end
-            //of the appendChild execution, so to tie an anonymous define
-            //call to the module name (which is stored on the node), hold on
-            //to a reference to this node, but clear after the DOM insertion.
-            currentlyAddingScript = node;
-            if (baseElement) {
-                head.insertBefore(node, baseElement);
-            } else {
-                head.appendChild(node);
-            }
-            currentlyAddingScript = null;
-
-            return node;
-        } else if (isWebWorker) {
-            try {
-                //In a web worker, use importScripts. This is not a very
-                //efficient use of importScripts, importScripts will block until
-                //its script is downloaded and evaluated. However, if web workers
-                //are in play, the expectation that a build has been done so that
-                //only one script needs to be loaded anyway. This may need to be
-                //reevaluated if other use cases become common.
-                importScripts(url);
-
-                //Account for anonymous modules
-                context.completeLoad(moduleName);
-            } catch (e) {
-                context.onError(makeError('importscripts',
-                                'importScripts failed for ' +
-                                    moduleName + ' at ' + url,
-                                e,
-                                [moduleName]));
-            }
-        }
-    };
-
-    function getInteractiveScript() {
-        if (interactiveScript && interactiveScript.readyState === 'interactive') {
-            return interactiveScript;
-        }
-
-        eachReverse(scripts(), function (script) {
-            if (script.readyState === 'interactive') {
-                return (interactiveScript = script);
-            }
-        });
-        return interactiveScript;
-    }
-
-    //Look for a data-main script attribute, which could also adjust the baseUrl.
-    if (isBrowser) {
-        //Figure out baseUrl. Get it from the script tag with require.js in it.
-        eachReverse(scripts(), function (script) {
-            //Set the 'head' where we can append children by
-            //using the script's parent.
-            if (!head) {
-                head = script.parentNode;
-            }
-
-            //Look for a data-main attribute to set main script for the page
-            //to load. If it is there, the path to data main becomes the
-            //baseUrl, if it is not already set.
-            dataMain = script.getAttribute('data-main');
-            if (dataMain) {
-                //Preserve dataMain in case it is a path (i.e. contains '?')
-                mainScript = dataMain;
-
-                //Set final baseUrl if there is not already an explicit one.
-                if (!cfg.baseUrl) {
-                    //Pull off the directory of data-main for use as the
-                    //baseUrl.
-                    src = mainScript.split('/');
-                    mainScript = src.pop();
-                    subPath = src.length ? src.join('/')  + '/' : './';
-
-                    cfg.baseUrl = subPath;
-                }
-
-                //Strip off any trailing .js since mainScript is now
-                //like a module name.
-                mainScript = mainScript.replace(jsSuffixRegExp, '');
-
-                 //If mainScript is still a path, fall back to dataMain
-                if (req.jsExtRegExp.test(mainScript)) {
-                    mainScript = dataMain;
-                }
-
-                //Put the data-main script in the files to load.
-                cfg.deps = cfg.deps ? cfg.deps.concat(mainScript) : [mainScript];
-
-                return true;
-            }
-        });
-    }
-
-    /**
-     * The function that handles definitions of modules. Differs from
-     * require() in that a string for the module should be the first argument,
-     * and the function to execute after dependencies are loaded should
-     * return a value to define the module corresponding to the first argument's
-     * name.
-     */
-    define = function (name, deps, callback) {
-        var node, context;
-
-        //Allow for anonymous modules
-        if (typeof name !== 'string') {
-            //Adjust args appropriately
-            callback = deps;
-            deps = name;
-            name = null;
-        }
-
-        //This module may not have dependencies
-        if (!isArray(deps)) {
-            callback = deps;
-            deps = null;
-        }
-
-        //If no name, and callback is a function, then figure out if it a
-        //CommonJS thing with dependencies.
-        if (!deps && isFunction(callback)) {
-            deps = [];
-            //Remove comments from the callback string,
-            //look for require calls, and pull them into the dependencies,
-            //but only if there are function args.
-            if (callback.length) {
-                callback
-                    .toString()
-                    .replace(commentRegExp, '')
-                    .replace(cjsRequireRegExp, function (match, dep) {
-                        deps.push(dep);
-                    });
-
-                //May be a CommonJS thing even without require calls, but still
-                //could use exports, and module. Avoid doing exports and module
-                //work though if it just needs require.
-                //REQUIRES the function to expect the CommonJS variables in the
-                //order listed below.
-                deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps);
-            }
-        }
-
-        //If in IE 6-8 and hit an anonymous define() call, do the interactive
-        //work.
-        if (useInteractive) {
-            node = currentlyAddingScript || getInteractiveScript();
-            if (node) {
-                if (!name) {
-                    name = node.getAttribute('data-requiremodule');
-                }
-                context = contexts[node.getAttribute('data-requirecontext')];
-            }
-        }
-
-        //Always save off evaluating the def call until the script onload handler.
-        //This allows multiple modules to be in a file without prematurely
-        //tracing dependencies, and allows for anonymous module support,
-        //where the module name is not known until the script onload event
-        //occurs. If no context, use the global queue, and get it processed
-        //in the onscript load callback.
-        (context ? context.defQueue : globalDefQueue).push([name, deps, callback]);
-    };
-
-    define.amd = {
-        jQuery: true
-    };
-
-
-    /**
-     * Executes the text. Normally just uses eval, but can be modified
-     * to use a better, environment-specific call. Only used for transpiling
-     * loader plugins, not for plain JS modules.
-     * @param {String} text the text to execute/evaluate.
-     */
-    req.exec = function (text) {
-        /*jslint evil: true */
-        return eval(text);
-    };
-
-    //Set up with config info.
-    req(cfg);
-}(this));

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/js/libs/spin.min.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/js/libs/spin.min.js b/apps/fauxton/assets/js/libs/spin.min.js
deleted file mode 100644
index 9e61502..0000000
--- a/apps/fauxton/assets/js/libs/spin.min.js
+++ /dev/null
@@ -1 +0,0 @@
-(function(a,b,c){function O(a){H(arguments,function(b,d){a[b]===c&&(a[b]=d)});return a}function N(a){H(arguments,function(b,c){a[m][M(a,b)||b]=c});return a}function M(a,b){var d=a[m],f,g;if(d[b]!==c){return b}b=b.charAt(0).toUpperCase()+b.slice(1);for(g=0;g<E[e];g++){f=E[g]+b;if(d[f]!==c){return f}}}function L(a,b){var c=[j,b,~~(a*100)].join("-"),d="{"+j+":"+a+"}",f;if(!F[c]){for(f=0;f<E[e];f++){try{K.insertRule("@"+(E[f]&&"-"+E[f].toLowerCase()+"-"||"")+"keyframes "+c+"{0%{"+j+":1}"+b+"%"+d+"to"+d+"}",K.cssRules[e])}catch(g){}}F[c]=1}return c}function J(a,b,c){c&&!c[t]&&J(a,c),a.insertBefore(b,c||null);return a}function I(a){var c=b.createElement(a||"div");H(arguments,function(a,b){c[a]=b});return c}function H(a,b){var c=~~((a[e]-1)/2);for(var d=1;d<=c;d++){b(a[d*2-1],a[d*2])}}var d="width",e="length",f="radius",g="lines",h="trail",i="color",j="opacity",k="speed",l="shadow",m="style",n="height",o="left",p="top",q="px",r="childNodes",s="firstChild",t="parentNode",u="position",v="rel
 ative",w="absolute",x="animation",y="transform",z="Origin",A="Timeout",B="coord",C="#000",D=m+"Sheets",E="webkit0Moz0ms0O".split(0),F={},G;J(b.getElementsByTagName("head")[0],I(m));var K=b[D][b[D][e]-1],P=function(a){this.opts=O(a||{},g,12,h,100,e,7,d,5,f,10,i,C,j,0.25,k,1)},Q=P.prototype={spin:function(b){var c=this,d=c.el=c[g](c.opts);b&&J(b,N(d,o,~~(b.offsetWidth/2)+q,p,~~(b.offsetHeight/2)+q),b[s]);if(!G){var e=c.opts,f=0,i=20/e[k],l=(1-e[j])/(i*e[h]/100),m=i/e[g];(function n(){f++;for(var b=e[g];b;b--){var h=Math.max(1-(f+b*m)%i*l,e[j]);c[j](d,e[g]-b,h,e)}c[A]=c.el&&a["set"+A](n,50)})()}return c},stop:function(){var b=this,d=b.el;a["clear"+A](b[A]),d&&d[t]&&d[t].removeChild(d),b.el=c;return b}};Q[g]=function(a){function s(b,c){return N(I(),u,w,d,a[e]+a[d]+q,n,a[d]+q,"background",b,"boxShadow",c,y+z,o,y,"rotate("+~~(360/a[g]*m)+"deg) translate("+a[f]+q+",0)","borderRadius","100em")}var b=N(I(),u,v),c=L(a[j],a[h]),m=0,r;for(;m<a[g];m++){r=N(I(),u,w,p,1+~(a[d]/2)+q,y,"translate3d(
 0,0,0)",x,c+" "+1/a[k]+"s linear infinite "+(1/a[g]/a[k]*m-1/a[k])+"s"),a[l]&&J(r,N(s(C,"0 0 4px "+C),p,2+q)),J(b,J(r,s(a[i],"0 0 1px rgba(0,0,0,.1)")))}return b},Q[j]=function(a,b,c){a[r][b][m][j]=c};var R="behavior",S="url(#default#VML)",T="group0roundrect0fill0stroke".split(0);(function(){var a=N(I(T[0]),R,S),b;if(!M(a,y)&&a.adj){for(b=0;b<T[e];b++){K.addRule(T[b],R+":"+S)}Q[g]=function(){function s(c,e,l){J(k,J(N(h(),"rotation",360/a[g]*c+"deg",o,~~e),J(N(I(T[1],"arcsize",1),d,b,n,a[d],o,a[f],p,-a[d]/2,"filter",l),I(T[2],i,a[i],j,a[j]),I(T[3],j,0))))}function h(){return N(I(T[0],B+"size",c+" "+c,B+z,-b+" "+-b),d,c,n,c)}var a=this.opts,b=a[e]+a[d],c=2*b,k=h(),m=~(a[e]+a[f]+a[d])+q,r;if(a[l]){for(r=1;r<=a[g];r++){s(r,-2,"progid:DXImage"+y+".Microsoft.Blur(pixel"+f+"=2,make"+l+"=1,"+l+j+"=.3)")}}for(r=1;r<=a[g];r++){s(r)}return J(N(I(),"margin",m+" 0 0 "+m,u,v),k)},Q[j]=function(a,b,c,d){d=d[l]&&d[g]||0,a[s][r][b+d][s][s][j]=c}}else{G=M(a,x)}})(),a.Spinner=P})(window,document);
\ No newline at end of file


[28/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/img/fontawesome-webfont.woff
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/img/fontawesome-webfont.woff b/apps/fauxton/assets/img/fontawesome-webfont.woff
deleted file mode 100755
index b9bd17e..0000000
Binary files a/apps/fauxton/assets/img/fontawesome-webfont.woff and /dev/null differ

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/img/fontcustom_fauxton.eot
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/img/fontcustom_fauxton.eot b/apps/fauxton/assets/img/fontcustom_fauxton.eot
deleted file mode 100644
index 48ed90d..0000000
Binary files a/apps/fauxton/assets/img/fontcustom_fauxton.eot and /dev/null differ

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/img/fontcustom_fauxton.svg
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/img/fontcustom_fauxton.svg b/apps/fauxton/assets/img/fontcustom_fauxton.svg
deleted file mode 100644
index 79459f3..0000000
--- a/apps/fauxton/assets/img/fontcustom_fauxton.svg
+++ /dev/null
@@ -1,200 +0,0 @@
-<?xml version="1.0" standalone="no"?>
-<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" >
-<!--
-2013-7-2: Created.
--->
-<svg xmlns="http://www.w3.org/2000/svg">
-<metadata>
-Created by FontForge 20120731 at Tue Jul  2 15:07:12 2013
- By Sue Lockwood
-Created by Sue Lockwood with FontForge 2.0 (http://fontforge.sf.net)
-</metadata>
-<defs>
-<font id="fontcustom_fauxton" horiz-adv-x="512" >
-  <font-face 
-    font-family="fontcustom_fauxton"
-    font-weight="500"
-    font-stretch="normal"
-    units-per-em="512"
-    panose-1="2 0 6 9 0 0 0 0 0 0"
-    ascent="448"
-    descent="-64"
-    bbox="0 -63.7441 512.201 448"
-    underline-thickness="25.6"
-    underline-position="-51.2"
-    unicode-range="U+F100-F125"
-  />
-    <missing-glyph />
-    <glyph glyph-name="uniF100" unicode="&#xf100;" 
-d="M2.43164 128.608v142.632h507.137v-142.632h-507.137zM2.43164 81.0635h507.137v-142.632h-507.137v142.632zM493.72 -45.7197v110.936h-95.0879v-110.936h95.0879zM2.43164 445.568h507.137v-110.937h-507.137v110.937zM493.72 350.479v79.2402h-253.567v-79.2402
-h253.567z" />
-    <glyph glyph-name="uniF101" unicode="&#xf101;" 
-d="M478.972 2.39355c-48.708 -2.12891 -141.553 -10.46 -191.938 -36.6318c-2.37891 -15.2148 -14.9824 -27.0264 -30.8662 -27.0264c-15.8828 0 -28.4561 11.8115 -30.8652 27.0264c-50.3545 26.1719 -143.23 34.5029 -191.938 36.6318
-c-17.5615 0 -31.8291 14.2354 -31.8291 31.8281v381.949c0 17.5625 14.2676 31.8291 31.8291 31.8291c1.11914 0 2.03613 -0.543945 3.1543 -0.637695c218.887 -5.6416 219.648 -63.0205 219.648 -63.0205s0.761719 57.3789 219.648 63.0205
-c1.11914 0.09375 2.03613 0.637695 3.15527 0.637695c17.5928 0 31.8291 -14.2666 31.8291 -31.8291v-381.949c0 -17.5928 -14.2363 -31.8281 -31.8291 -31.8281zM224.34 348.254c-41.0615 20.8721 -108.978 29.5605 -159.146 33.2598v-317.202
-c85.4316 -4.32129 133.237 -17.127 159.146 -30.0898v314.032zM447.143 381.514c-50.1689 -3.69922 -118.085 -12.3877 -159.146 -33.2598v-314.032c25.9082 12.9316 73.7139 25.7539 159.146 30.0898v317.202zM415.312 320.684v-63.6582s-95.4863 0 -95.4863 -31.8291
-v63.6592s0 31.8281 95.4863 31.8281zM415.312 193.367v-63.6582s-95.4863 0 -95.4863 -31.8291v63.6582s0 31.8291 95.4863 31.8291zM192.511 288.855v-63.6592c0 31.8291 -95.4873 31.8291 -95.4873 31.8291v63.6582c95.4873 0 95.4873 -31.8281 95.4873 -31.8281z
-M192.511 161.538v-63.6582c0 31.8291 -95.4873 31.8291 -95.4873 31.8291v63.6582c95.4873 0 95.4873 -31.8291 95.4873 -31.8291z" />
-    <glyph glyph-name="uniF102" unicode="&#xf102;" 
-d="M167.89 -63.2324l-79.3857 79.7764l175.472 175.456l-175.472 175.472l79.8535 79.7607l255.139 -255.232z" />
-    <glyph glyph-name="uniF103" unicode="&#xf103;" 
-d="M255.092 446.464c140.025 0 253.556 -113.531 253.556 -253.556c0 -140.025 -113.546 -253.556 -253.556 -253.556c-140.024 0 -253.556 113.53 -253.556 253.556c0 140.024 113.546 253.556 253.556 253.556zM215.807 75.9111l197.201 197.215l-44.8184 44.8184
-l-152.397 -152.396l-71.8398 71.8604l-44.8096 -44.8174z" />
-    <glyph glyph-name="uniF104" unicode="&#xf104;" 
-d="M256.512 447.488c140.81 0 254.977 -114.166 254.977 -254.977c0 -140.81 -114.167 -254.976 -254.977 -254.976s-254.976 114.166 -254.976 254.976c0 140.811 114.166 254.977 254.976 254.977zM384 160.64v63.7441h-254.976v-63.7441h254.976z" />
-    <glyph glyph-name="uniF105" unicode="&#xf105;" 
-d="M256.195 446.464c140.635 0 254.659 -114.024 254.659 -254.659c0 -140.634 -114.024 -254.659 -254.659 -254.659s-254.659 114.025 -254.659 254.659c0 140.635 114.024 254.659 254.659 254.659zM383.524 159.973v63.6641h-95.498v95.498h-63.6641v-95.498h-95.4971
-v-63.6641h95.4971v-95.4961h63.665v95.4961h95.4971z" />
-    <glyph glyph-name="uniF106" unicode="&#xf106;" 
-d="M256.423 446.808c140.62 0 254.632 -114.012 254.632 -254.631c0 -140.618 -114.013 -254.631 -254.632 -254.631s-254.631 114.013 -254.631 254.631c0 140.619 114.012 254.631 254.631 254.631zM382.371 111.237l-80.9395 80.9395l80.9395 80.9404l-45.0078 45.0078
-l-80.9404 -80.9404l-80.9395 80.9404l-45.0088 -45.0078l80.9404 -80.9404l-80.9404 -80.9395l45.0088 -45.0078l80.9395 80.9395l80.9404 -80.9395z" />
-    <glyph glyph-name="uniF107" unicode="&#xf107;" 
-d="M511.744 160.645l-76.5098 -32.6094c-2.1084 -5.93457 -4.29395 -11.7754 -7.01172 -17.4912l31.5156 -76.3369l-45.2275 -45.2275l-76.7109 30.7344c-5.71582 -2.74805 -11.7129 -5.12207 -17.8037 -7.37109l-31.6406 -76.0869h-63.9678l-32.3594 75.7119
-c-6.37109 2.18652 -12.5557 4.49805 -18.6152 7.37109l-75.5244 -31.1094l-45.2275 45.2275l30.4219 75.8369c-2.99805 6.18457 -5.49609 12.4941 -7.80859 18.9912l-75.2744 31.3584v63.9688l75.2119 32.1709c2.31152 6.49609 4.74805 12.8066 7.74609 18.9902
-l-30.9844 75.3369l45.2275 45.2285l76.0244 -30.5469c6.05957 2.87305 12.1816 5.24707 18.5537 7.49609l31.6084 75.7119h63.9678l32.4219 -75.9619c6.12207 -2.18652 12.0566 -4.56055 17.8662 -7.37109l76.1494 31.3584l45.2588 -45.2266l-30.8906 -76.8369
-c2.74805 -5.7002 4.99707 -11.4941 7.12109 -17.4912l76.4619 -31.8584v-63.9678zM255.372 96.1758c52.9736 0 95.9521 42.9785 95.9521 95.9521c0 52.9746 -42.9785 95.9521 -95.9521 95.9521c-52.957 0 -95.9512 -42.9775 -95.9512 -95.9521
-c0 -52.9736 42.9932 -95.9521 95.9512 -95.9521z" />
-    <glyph glyph-name="uniF108" unicode="&#xf108;" 
-d="M256 235.195l228.377 -228.377l-68.6074 -68.6074l-159.77 159.769l-159.769 -159.769l-68.6074 68.6074zM256 445.44l228.377 -228.377l-68.6074 -68.6064l-159.77 159.768l-159.769 -159.768l-68.6074 68.6064z" />
-    <glyph glyph-name="uniF109" unicode="&#xf109;" 
-d="M512.201 -7.39062c0 -30.1455 -24.4502 -54.5957 -54.5977 -54.5957h-400.792c-30.1465 0 -54.5967 24.4502 -54.5967 54.5957v400.794c0 30.1455 24.4502 54.5967 54.5967 54.5967h400.792c30.1475 0 54.5977 -24.4512 54.5977 -54.5967v-400.794zM464.39 398.437
-c0 0.972656 -0.77832 1.75098 -1.74316 1.75098h-410.886c-0.956055 0 -1.73438 -0.77832 -1.73438 -1.75098v-410.869c0 -0.949219 0.77832 -1.74219 1.73438 -1.74219h410.886c0.96582 0 1.74316 0.792969 1.74316 1.74219v410.869zM100.945 76.1318l-38.9082 27.7959
-l96.0889 134.525l61.5615 -61.5635l65.6777 114.922l64.667 -80.8213l61.7871 98.8906l40.5586 -25.3213l-97.583 -156.103l-62.8301 78.5498l-61.8027 -108.199l-65.9346 65.9277z" />
-    <glyph glyph-name="uniF10A" unicode="&#xf10a;" 
-d="M250.592 -61.5244c-105.291 0 -190.688 42.6758 -190.688 95.3447v0v53.6611c0 -52.7305 85.4121 -85.4424 190.688 -85.4424c105.291 0 190.688 32.7119 190.688 85.4424v-53.6621v0c0 -52.668 -85.3818 -95.3438 -190.688 -95.3438zM250.592 33.8203
-c-105.291 0 -190.688 42.6748 -190.688 95.3438v53.6465c0 -52.6846 85.4121 -85.4287 190.688 -85.4287c105.291 0 190.688 32.7441 190.688 85.4287v-53.6465c0 -52.6689 -85.3818 -95.3438 -190.688 -95.3438zM250.592 129.164
-c-105.291 0 -190.688 42.6738 -190.688 95.3428v53.6475c0 -52.6846 85.4121 -85.4287 190.688 -85.4287c105.291 0 190.688 32.7432 190.688 85.4287v-53.6475c0 -52.6689 -85.3818 -95.3428 -190.688 -95.3428zM250.592 224.507
-c-105.275 0 -190.688 42.6748 -190.688 95.3438v31.7812c0 52.6689 85.3965 95.3438 190.688 95.3438s190.688 -42.6748 190.688 -95.3438v-31.7812c0 -52.6689 -85.3818 -95.3438 -190.688 -95.3438z" />
-    <glyph glyph-name="uniF10B" unicode="&#xf10b;" 
-d="M287.851 446.805l159.253 -159.222v-350.389h-382.207v509.61h222.954zM128.598 0.895508h254.805v254.806h-127.402v127.402h-127.402v-382.208z" />
-    <glyph glyph-name="uniF10C" unicode="&#xf10c;" 
-d="M335.36 446.976l158.72 -158.688v-253.983h-95.2324v-95.2314h-380.928v412.672h95.2324v95.2314h222.208zM335.36 2.55957v31.7441h-222.208v253.952h-31.7441v-285.696h253.952zM430.592 97.792v158.72h-126.976v126.977h-126.977v-285.696h253.952z" />
-    <glyph glyph-name="uniF10D" unicode="&#xf10d;" 
-d="M256 148.513l-228.994 228.995l68.793 68.793l160.201 -160.185l160.201 160.185l68.793 -68.793zM256 -62.3008l-228.994 228.993l68.793 68.7949l160.201 -160.201l160.201 160.201l68.793 -68.7949z" />
-    <glyph glyph-name="uniF10E" unicode="&#xf10e;" 
-d="M256.342 382.728c140.621 0 254.634 -188.489 254.634 -188.489s-114.013 -193.463 -254.634 -193.463s-254.635 193.463 -254.635 193.463s114.014 188.489 254.635 188.489zM256.342 64.4346c70.3105 0 127.317 57.0068 127.317 127.317
-s-57.0068 127.317 -127.317 127.317s-127.317 -57.0068 -127.317 -127.317s57.0068 -127.317 127.317 -127.317zM256.342 255.161c35.1553 0 63.6582 -28.5029 63.6582 -63.6582s-28.5029 -63.6582 -63.6582 -63.6582s-63.6592 28.5029 -63.6592 63.6582
-s28.5039 63.6582 63.6592 63.6582z" />
-    <glyph glyph-name="uniF10F" unicode="&#xf10f;" 
-d="M351.439 381.472c-52.2754 0 -94.7998 -42.5244 -94.7988 -94.8008c0 -4.9375 0.586914 -10.3701 1.85156 -17.1582l6.04785 -32.7119l-23.5146 -23.5137l-173.985 -173.985v-37.0312h63.2002v63.2002h63.1992v63.2002h63.2002v26.1689l18.5156 18.5156l2.90039 2.90137
-l23.5146 23.5146l32.7109 -6.04785c6.79004 -1.23438 12.2207 -1.85254 17.1582 -1.85254c52.2764 0 94.7998 42.5254 94.7998 94.8008s-42.5234 94.7998 -94.7998 94.7998zM351.439 444.672v0c87.2705 0 158.001 -70.7305 158.001 -158s-70.7305 -158 -158 -158
-c-9.875 0 -19.3799 1.17285 -28.6992 2.90039l-2.90137 -2.90039v-63.2002h-63.2002v-63.1992h-63.2002v-63.2002h-189.6v126.399l192.5 192.501c-1.72754 9.31934 -2.90039 18.8242 -2.90039 28.6992c0 87.2705 70.7305 158 158 158zM351.563 318.272
-c17.4658 0 31.6006 -14.1494 31.6006 -31.6006s-14.1338 -31.6006 -31.6006 -31.6006c-17.4512 0 -31.6006 14.1494 -31.6006 31.6006s14.1494 31.6006 31.6006 31.6006z" />
-    <glyph glyph-name="uniF110" unicode="&#xf110;" 
-d="M481.194 238.603l-46.6826 -46.6377c-29.1152 -29.0996 -72.3096 -34.9346 -107.445 -18.2158l107.445 107.499c12.3496 12.3418 12.3496 32.3262 0 44.6377l-44.6152 44.6914c-12.3193 12.3506 -32.2637 12.3506 -44.6143 0l-107.482 -107.507
-c-16.7266 35.1504 -10.8916 78.376 18.208 107.507l46.6055 46.6377c36.9883 36.957 96.9482 36.957 133.874 0l44.707 -44.6465c36.9268 -37.0039 36.9268 -96.9785 0 -133.966zM166.726 102.736c-12.3271 12.3496 -12.3271 32.2959 0 44.6299l133.912 133.913
-c12.3496 12.3496 32.2959 12.3496 44.6455 0c12.3496 -12.3428 12.3496 -32.2803 0 -44.6221l-133.913 -133.921c-12.3193 -12.3506 -32.3184 -12.3506 -44.6445 0zM77.4424 58.0596l44.6377 -44.6143c12.3496 -12.3496 32.3027 -12.3496 44.6289 0l107.53 107.508
-c16.75 -35.168 10.8682 -78.377 -18.2158 -107.508l-42.6768 -46.6367c-36.9961 -36.9883 -96.9395 -36.9883 -133.943 0l-48.6133 48.582c-36.957 36.9883 -36.957 96.9473 0 133.937l46.6211 42.6689c29.1621 29.0996 72.3555 34.9346 107.553 18.209l-107.521 -107.469
-c-12.3115 -12.3506 -12.3115 -32.3574 0 -44.6768z" />
-    <glyph glyph-name="uniF111" unicode="&#xf111;" 
-d="M510.208 382.88h-508.672v63.584h508.672v-63.584zM319.456 255.712h-317.92v63.584h317.92v-63.584zM510.208 64.96h-508.672v63.584h508.672v-63.584zM383.04 -62.208h-381.504v63.584h381.504v-63.584zM510.208 -30.416c0 -17.5723 -14.2812 -31.792 -31.792 -31.792
-c-17.6348 0 -31.8545 14.2188 -31.8545 31.792s14.2197 31.792 31.8545 31.792c17.5107 0 31.792 -14.2188 31.792 -31.792z" />
-    <glyph glyph-name="uniF112" unicode="&#xf112;" 
-d="M2.30371 128.576v126.848h507.393v-126.848h-507.393z" />
-    <glyph glyph-name="uniF113" unicode="&#xf113;" 
-d="M415.106 -61.2578h-317.007c-52.5352 0 -95.1025 42.5967 -95.1025 95.1016v317.006c0 52.5361 42.5664 95.1025 95.1025 95.1025h317.007c52.5039 0 95.1016 -42.5664 95.1016 -95.1025v-317.006c0 -52.5039 -42.5977 -95.1016 -95.1016 -95.1016zM446.807 350.85
-c0 17.4922 -14.1787 31.7012 -31.7002 31.7012h-317.007c-17.5225 0 -31.7012 -14.209 -31.7012 -31.7012v-317.006c0 -17.5225 14.1787 -31.7002 31.7012 -31.7002h317.007c17.5215 0 31.7002 14.1777 31.7002 31.7002v317.006zM351.704 97.2451v-47.5508
-c0 -8.74512 -7.08887 -15.8506 -15.8496 -15.8506c-8.76172 0 -15.8506 7.10547 -15.8506 15.8506v47.5508c-17.5225 0 -31.7012 14.1787 -31.7012 31.7012v31.7002c0 17.4912 14.1787 31.7002 31.7012 31.7002v142.653c0 8.74512 7.08887 15.8496 15.8506 15.8496
-c8.76074 0 15.8496 -7.10449 15.8496 -15.8496v-142.653c17.5225 0 31.7012 -14.209 31.7012 -31.7002v-31.7002c0 -17.5225 -14.1787 -31.7012 -31.7012 -31.7012zM193.201 192.347v-142.652c0 -8.74512 -7.10449 -15.8506 -15.8506 -15.8506
-s-15.8506 7.10547 -15.8506 15.8506v142.652c-17.5225 0 -31.7012 14.21 -31.7012 31.7012v31.7002c0 17.4912 14.1787 31.7012 31.7012 31.7012v47.5508c0 8.74512 7.10449 15.8496 15.8506 15.8496s15.8506 -7.10449 15.8506 -15.8496v-47.5508
-c17.5225 0 31.7012 -14.21 31.7012 -31.7012v-31.7002c-0.000976562 -17.4912 -14.1787 -31.7012 -31.7012 -31.7012z" />
-    <glyph glyph-name="uniF114" unicode="&#xf114;" 
-d="M25.3525 319.254v31.8145c0 52.7217 85.4834 95.4395 190.881 95.4395s190.882 -42.7178 190.882 -95.4395v-31.8145c0 -35.9141 -39.7363 -67.1689 -98.3926 -83.4639c-1.98828 -0.450195 -3.94531 -1.00977 -5.93359 -1.52246
-c-25.9736 -6.63281 -55.3633 -10.4541 -86.5557 -10.4541c-105.397 0.000976562 -190.881 42.7188 -190.881 95.4404zM384.062 234.299c14.6953 12.1943 23.0537 26.7178 23.0527 43.2002v-51.1074c-7.39453 3.24707 -15.1143 5.81055 -23.0527 7.90723zM205.748 1.33594
-c14.6016 -25.3037 35.8369 -46.2598 61.499 -60.2705c-16.249 -2.26855 -33.3359 -3.57324 -51.0137 -3.57324c-105.397 0 -190.881 42.749 -190.881 95.4395v53.7012c0 -50.9824 79.9062 -83.1836 180.396 -85.2969zM191.44 33.833
-c-93.6377 6.08984 -166.088 46.043 -166.089 94.54v53.7012c0 -47.4561 69.3125 -78.6484 160 -84.458c-0.589844 -5.57715 -0.931641 -11.2471 -0.931641 -16.9639c0 -16.2793 2.4541 -32.0303 7.02051 -46.8193zM192.032 129.243
-c-93.9502 5.93359 -166.68 45.9492 -166.68 94.5703v53.7012c0 -52.7373 85.4834 -85.5146 190.881 -85.5146c4.72266 0 9.35156 0.140625 13.9961 0.280273c-17.2734 -17.5381 -30.4932 -39.0527 -38.1973 -63.0371zM486.647 80.6523
-c0 -79.0674 -64.0928 -143.16 -143.16 -143.16c-79.0684 0 -143.161 64.0928 -143.161 143.16c0 79.0684 64.0938 143.161 143.161 143.161c79.0674 0.000976562 143.16 -64.0928 143.16 -143.161zM438.928 96.5605h-79.5342v79.5322h-31.8125v-79.5322h-79.5342v-31.8145
-h79.5342v-79.5342h31.8125v79.5342h79.5342v31.8145z" />
-    <glyph glyph-name="uniF115" unicode="&#xf115;" 
-d="M208.766 -59.6162c-46.3301 0 -89.874 18.0889 -122.595 50.8799c-32.7598 32.7432 -50.8096 76.2324 -50.8096 122.586c0.0302734 46.3223 18.0498 89.8584 50.8096 122.58l175.544 171.749c47.1777 47.2002 130.493 47.3848 178.093 -0.253906
-c49.1084 -49.1934 49.1084 -129.184 0 -178.322l-157.979 -154.101c-30.4199 -30.4355 -80.4199 -30.4961 -111.148 0.276367c-30.7285 30.79 -30.7285 80.7598 0 111.479l61.1465 61.1553l44.583 -44.582l-61.1465 -61.1475
-c-4.04199 -4.06348 -4.61914 -8.74414 -4.61914 -11.1465c0 -2.43066 0.577148 -7.11133 4.61914 -11.1758c8.06641 -8.03613 14.2168 -8.03613 22.291 0l157.888 154.123c24.3232 24.292 24.3232 64.2871 -0.24707 88.8965c-23.8301 23.8311 -65.334 23.8311 -89.165 0
-l-175.529 -171.766c-20.5908 -20.6211 -32.082 -48.3018 -32.082 -77.7656c0 -29.4971 11.4912 -57.2051 32.3281 -78.0195c41.6963 -41.7354 114.359 -41.7354 156.039 0l78.8203 78.8203l44.5527 -44.5674l-78.8213 -78.8193
-c-32.7275 -32.7617 -76.2568 -50.8799 -122.571 -50.8799z" />
-    <glyph glyph-name="uniF116" unicode="&#xf116;" 
-d="M192.16 1.76074l-190.368 -63.457l63.4561 190.368l317.28 317.28l126.912 -126.912zM65.248 1.76074l95.1836 31.7275l-63.4561 63.4561zM128.704 128.672l63.4561 -63.4561l190.368 190.367l-63.4561 63.457z" />
-    <glyph glyph-name="uniF117" unicode="&#xf117;" 
-d="M62.9756 448l383.425 -255.616l-383.425 -255.616v511.232z" />
-    <glyph glyph-name="uniF118" unicode="&#xf118;" 
-d="M511.232 256.288v-127.808h-191.713v-191.713h-127.808v191.713h-191.712v127.808h191.712v191.712h127.808v-191.712h191.713z" />
-    <glyph glyph-name="uniF119" unicode="&#xf119;" 
-d="M492.673 -62.7197h-474.753c0 61.3486 71.7646 112.591 169.562 129.326v25.1006c-40.3604 23.5342 -67.8223 66.7656 -67.8223 116.86v3.43066c-19.6826 7.0625 -33.918 25.3652 -33.918 47.4551c0 22.0742 14.2354 40.3916 33.9033 47.4248v3.42969
-c0.0146484 74.917 60.7275 135.645 135.644 135.645s135.644 -60.7275 135.644 -135.645v-3.42969c19.668 -7.0332 33.9033 -25.3506 33.9033 -47.4248c0 -22.0898 -14.2354 -40.3926 -33.9033 -47.4551v-3.43066c0 -50.0947 -27.4609 -93.3262 -67.8213 -116.813v-25.1016
-c97.8438 -16.7812 169.562 -68.0234 169.562 -129.372z" />
-    <glyph glyph-name="uniF11A" unicode="&#xf11a;" 
-d="M74.7285 233.082l-63.5254 63.5254c-6.20312 6.18945 -9.30469 14.3311 -9.30469 22.458c0 8.1416 3.10156 16.2686 9.30469 22.457l63.5254 63.5244c9.08887 9.04199 22.7373 11.7871 34.6172 6.90234c11.8486 -4.90137 19.6035 -16.5332 19.6035 -29.3594v-31.7939
-h31.7627v-63.5254h-31.7627v-31.7314c0 -12.8262 -7.75488 -24.459 -19.6035 -29.3594c-11.8799 -4.86914 -25.5283 -2.16992 -34.6172 6.90234zM437.271 150.931l63.5254 -63.5264c6.20312 -6.17188 9.30469 -14.2988 9.30469 -22.457
-c0 -8.12695 -3.10156 -16.2529 -9.30469 -22.4561l-63.5254 -63.5264c-9.08887 -9.05762 -22.7676 -11.7568 -34.6172 -6.88672c-11.8799 4.90137 -19.6035 16.5332 -19.6035 29.3438v31.7627h-31.7627v63.5264h31.7627v31.7627c0 12.8408 7.72363 24.4727 19.6035 29.374
-c11.8496 4.87012 25.5283 2.13965 34.6172 -6.91699zM224.237 96.7109h31.7627v-63.5264h-31.7627v63.5264zM192.475 350.796h31.7627v-63.5244h-31.7627v63.5244zM160.712 160.235c17.5254 0 31.7627 -14.2373 31.7627 -31.7617v-127.051
-c0 -17.5879 -14.2373 -31.7627 -31.7627 -31.7627h-127.052c-17.5254 0 -31.7617 14.1748 -31.7617 31.7627v127.051c0 17.5244 14.2363 31.7617 31.7617 31.7617h127.052zM128.949 33.1846v0v63.5264h-63.5254v-63.5264h63.5254zM256 350.796h31.7627v-63.5244h-31.7627
-v63.5244zM478.339 414.322c17.5566 0 31.7627 -14.2217 31.7627 -31.7627v-127.051c0 -17.541 -14.2061 -31.7637 -31.7627 -31.7637h-127.051c-17.5566 0 -31.7627 14.2227 -31.7627 31.7637v127.051c0 17.541 14.2061 31.7627 31.7627 31.7627h127.051zM446.576 287.271
-v63.5244h-63.5254v-63.5244h63.5254zM287.763 96.7109h31.7627v-63.5264h-31.7627v63.5264z" />
-    <glyph glyph-name="uniF11B" unicode="&#xf11b;" 
-d="M494.778 -2.67969c-29.6025 83.5303 -109.144 143.562 -202.873 143.562v-71.8408c0 -13.2529 -7.31543 -25.3379 -18.9727 -31.5967c-11.6572 -6.25781 -25.8516 -5.61426 -36.833 1.74902l-215.372 143.606c-10.0078 6.70898 -16.0205 17.876 -16.0205 29.8545
-c0 12.0332 6.0127 23.2129 15.9893 29.8926l215.357 143.615c11.0273 7.31641 25.1924 8.03613 36.8486 1.75586c11.6875 -6.21973 19.0029 -18.4199 19.0029 -31.6641v-71.7734c118.944 0 215.388 -96.4668 215.388 -215.44c0 -25.123 -4.58594 -49.2646 -12.5146 -71.7197
-z" />
-    <glyph glyph-name="uniF11C" unicode="&#xf11c;" 
-d="M107.919 318.031c-11.6172 0 -19.7217 8.78223 -19.7217 20.3984v86.7764c0 11.6172 8.10449 19.7217 19.7217 19.7217h148.576c11.6328 0 21.0312 -8.10449 21.0303 -19.7217v-86.0986c0 -11.6162 -8.78125 -21.0762 -20.3838 -21.0762h-149.223zM445.777 444.928
-c42.1543 0 42.1543 -42.0938 42.1553 -42.0938v-421.982c0 -39.4434 -41.416 -40.1836 -41.416 -40.1836v271.543c0 21.0166 -21.6934 22.3721 -21.6934 22.3721h-336.626c-21.0156 0 -21.0156 -21.7246 -21.0156 -21.7246v-272.807
-c-40.7988 0 -42.0938 42.0322 -42.0938 42.0322v420.75s0 42.0938 42.0938 42.0938l-0.677734 -126.882s1.07812 -20.3691 22.1562 -20.3691l335.469 -0.569336s20.2305 -0.308594 21.5859 21.3857zM404.361 212.858c0 0 20.4619 0 20.4619 -21.709v-229.404
-s0.615234 -21.6934 -21.0781 -21.6934h-295.147s-19.7217 0.615234 -19.7217 21.6934l-0.678711 230.112s-0.677734 21.001 21.6943 21.001h294.47zM330.405 45.1934c5.70117 0 10.2305 4.65234 10.2295 10.2305c0 5.5625 -4.52832 10.2148 -10.2295 10.2148h-168.929
-c-5.63867 0 -10.1689 -4.65234 -10.1689 -10.2148c0 -5.57715 4.54492 -10.2305 10.1689 -10.2305h168.929zM330.158 87.3486c5.70117 0 10.4775 4.02148 10.4775 9.86035c0 5.7168 -4.77637 10.4775 -10.4775 10.4775h-168.99
-c-5.83984 0 -10.5391 -4.76074 -10.5391 -10.4775c0 -5.83887 4.69922 -9.86035 10.5391 -9.86035h168.99zM330.405 129.38c5.70117 0 10.2305 4.53027 10.2295 10.2305c0 5.57715 -4.52832 10.1074 -10.2295 10.1074h-168.929
-c-5.63867 0 -10.1689 -4.53027 -10.1689 -10.1074c0 -5.7002 4.54492 -10.2305 10.1689 -10.2305h168.929zM381.435 318.031c-11.6475 0 -19.7217 9.45996 -19.7217 21.0762v86.0986c0 11.6172 8.07422 19.7217 19.7217 19.7217h23.666
-c11.5566 0 19.7227 -8.10547 19.7227 -19.7217v-86.0986c0 -11.6162 -8.16602 -21.0762 -19.7227 -21.0762h-23.666z" />
-    <glyph glyph-name="uniF11D" unicode="&#xf11d;" 
-d="M495.659 19.2988c18.6387 -18.6387 18.6387 -48.8457 -0.000976562 -67.4697c-18.6543 -18.6387 -48.8311 -18.6387 -67.4697 0l-111.865 111.804c-31.4941 -19.4453 -68.2607 -31.1992 -108.021 -31.1992c-114.191 0 -206.767 92.5752 -206.767 206.751
-c0 114.192 92.5752 206.768 206.767 206.768c114.192 0 206.768 -92.5752 206.768 -206.768c0 -39.7588 -11.7539 -76.541 -31.2305 -108.065zM208.303 96.0273c79.0537 0 143.159 64.1045 143.159 143.157c0 79.0537 -64.1055 143.159 -143.159 143.159
-c-79.0527 0 -143.158 -64.1055 -143.158 -143.159c0 -79.0527 64.1055 -143.157 143.158 -143.157z" />
-    <glyph glyph-name="uniF11E" unicode="&#xf11e;" 
-d="M228.974 393.2c0 -60.4707 -0.255859 -227.632 -0.255859 -227.632s170.018 -0.0644531 227.937 -0.0644531c0 -125.756 -101.94 -227.696 -227.681 -227.696c-125.756 0 -227.695 101.94 -227.695 227.696c0 125.307 101.25 226.989 226.38 227.696h1.31543z
-M510.722 201.067l-245.445 -0.353516s-0.641602 245.478 0.352539 245.478c135.386 0 245.093 -109.739 245.093 -245.124z" />
-    <glyph glyph-name="uniF11F" unicode="&#xf11f;" 
-d="M509.952 192.512c0 -10.7109 -0.868164 -21.2646 -2.16992 -31.6504c-0.326172 -2.51074 -0.744141 -5.05273 -1.14746 -7.56348c-1.37793 -8.68066 -3.13086 -17.2979 -5.34668 -25.6992c-0.417969 -1.48828 -0.744141 -3.00684 -1.13184 -4.47949
-c-6.04492 -21.002 -14.6631 -40.9824 -25.5752 -59.4111c-21.8232 -37.0293 -52.7305 -67.9209 -89.7598 -89.7764c-18.4297 -10.9121 -38.3936 -19.499 -59.4111 -25.5596c-1.48828 -0.387695 -2.97656 -0.712891 -4.47949 -1.13184
-c-8.41699 -2.21582 -16.9727 -3.96777 -25.6836 -5.34766c-2.51074 -0.387695 -5.05273 -0.836914 -7.58008 -1.13184c-10.4014 -1.33203 -20.9414 -2.20117 -31.667 -2.20117v0v0c-10.7256 0 -21.2656 0.869141 -31.6504 2.16992
-c-2.57324 0.326172 -5.05371 0.744141 -7.5957 1.14746c-8.71094 1.37891 -17.2979 3.13086 -25.7148 5.34668c-1.44043 0.418945 -2.99121 0.744141 -4.44824 1.13184c-21.0488 6.04492 -40.9814 14.6631 -59.4268 25.5752
-c-37.0137 21.8242 -67.9209 52.7305 -89.8066 89.7598c-10.8965 18.4307 -19.4834 38.3936 -25.5127 59.4121c-0.40332 1.47168 -0.744141 2.97559 -1.14746 4.47949c-2.23145 8.41602 -3.96777 16.9717 -5.31641 25.6836
-c-0.387695 2.50977 -0.836914 5.03613 -1.19336 7.5791c-1.27148 10.4023 -2.13965 20.9561 -2.13965 31.667v0v0c0 10.7109 0.868164 21.2666 2.16992 31.6504c0.30957 2.57324 0.744141 5.05273 1.17773 7.59473c1.34863 8.71191 3.10059 17.2988 5.34766 25.7148
-c0.387695 1.44238 0.728516 2.99219 1.14746 4.44922c6.0293 20.9863 14.6318 40.9668 25.5283 59.4121c21.8555 37.0137 52.793 67.9355 89.8066 89.791c18.3994 10.8652 38.3779 19.4678 59.3809 25.4971c1.47266 0.418945 2.99219 0.758789 4.44824 1.14746
-c8.40137 2.24707 17.0186 3.96777 25.6992 5.34668c2.54199 0.37207 5.02148 0.837891 7.61035 1.19336c10.3701 1.28711 20.9102 2.15527 31.6357 2.15527v0v0c10.7256 0 21.2656 -0.868164 31.6504 -2.15527c2.51172 -0.324219 5.05371 -0.758789 7.56445 -1.19238
-c8.67969 -1.34863 17.2969 -3.09961 25.6982 -5.34668c1.48828 -0.388672 3.00684 -0.729492 4.47949 -1.14746c21.0029 -6.03027 40.9834 -14.6328 59.4121 -25.498c37.0293 -21.8857 67.9209 -52.8242 89.7764 -89.8066
-c10.9121 -18.4443 19.499 -38.3779 25.5596 -59.4268c0.386719 -1.45703 0.712891 -2.97559 1.13184 -4.44824c2.21582 -8.41699 3.96777 -17.0039 5.34766 -25.7148c0.387695 -2.54199 0.835938 -5.00586 1.13086 -7.5791
-c1.33301 -10.3701 2.20117 -20.9258 2.20117 -31.6367v0v0zM108.486 250.219l-47.1973 47.2285c-16.957 -31.3887 -27.4971 -66.7432 -27.4971 -104.936c0 -38.1914 10.54 -73.5625 27.4971 -104.936l47.1973 47.1836c-7.02148 17.9482 -11.2061 37.3076 -11.2061 57.752
-c0 20.4297 4.18457 39.7744 11.2061 57.707zM256 -29.6963c38.1924 0 73.5635 10.5088 104.935 27.4668l-47.1816 47.2119c-17.9492 -6.97363 -37.3086 -11.1904 -57.7529 -11.1904c-20.4131 0 -39.7734 4.2168 -57.7217 11.2373l-47.2441 -47.2285
-c31.4189 -16.9883 66.7734 -27.4971 104.966 -27.4971zM256 414.72c-38.1924 0 -73.5469 -10.54 -104.935 -27.4971l47.2432 -47.1973c17.918 7.02246 37.2783 11.207 57.6914 11.207c20.4443 0 39.8037 -4.18457 57.7217 -11.207l47.1816 47.1973
-c-31.3398 16.957 -66.7109 27.4971 -104.903 27.4971zM378.28 224.984v0c-11.6416 43.8799 -45.8965 78.1191 -89.792 89.8076v0v0c-4.21582 1.09961 -8.43262 2.03027 -12.834 2.72852c-6.41699 1.14648 -12.8965 1.96777 -19.6543 1.96777
-s-13.2373 -0.821289 -19.6846 -1.96875c-4.34082 -0.697266 -8.60254 -1.62793 -12.7881 -2.72852v0v0c-43.8799 -11.6875 -78.1201 -45.957 -89.8066 -89.8066v0v0c-1.10059 -4.18457 -2.03027 -8.44824 -2.72852 -12.8037
-c-1.14648 -6.44727 -1.96777 -12.9258 -1.96777 -19.6689s0.821289 -13.2207 1.96777 -19.6543c0.666992 -4.40234 1.62793 -8.58594 2.72852 -12.833v0v0c11.6406 -43.8652 45.957 -78.1045 89.8066 -89.7607v0v0c4.18555 -1.10059 8.44727 -2.01562 12.7881 -2.72754
-c6.44727 -1.17871 12.9268 -2 19.6846 -2s13.2373 0.821289 19.6543 1.96777c4.40234 0.666992 8.58691 1.62891 12.834 2.72852v0v0c43.8643 11.6572 78.1045 45.8965 89.7598 89.792v0v0c1.10059 4.21582 2.01562 8.43164 2.72852 12.8184
-c1.17773 6.44824 1.99902 12.9258 1.99902 19.6689s-0.821289 13.2217 -1.96777 19.6689c-0.712891 4.35547 -1.62793 8.61914 -2.72754 12.8037v0zM450.742 297.447l-47.2129 -47.2441c6.97461 -17.917 11.1904 -37.2617 11.1904 -57.6914
-c0 -20.4443 -4.21582 -39.8037 -11.2373 -57.7217l47.2285 -47.1816c16.9883 31.3408 27.4971 66.7119 27.4971 104.903c0 38.1924 -10.5088 73.5469 -27.4658 104.936z" />
-    <glyph glyph-name="uniF120" unicode="&#xf120;" 
-d="M3.49219 294.4l101 102.399h25.0312v-78.7695h378.093v-47.2607h-378.093v-78.7695h-25.0312zM508.508 89.5996l-101.016 -102.399h-25.9082v78.7686h-378.092v47.2607h378.092v78.7705h25.9082z" />
-    <glyph glyph-name="uniF121" unicode="&#xf121;" 
-d="M443.778 287.818v-254.668c0 -52.7051 -42.7891 -95.4941 -95.4951 -95.4941h-191.005c-52.7529 0 -95.4951 42.7881 -95.4951 95.4941v254.668c-17.5625 0 -31.8311 14.2686 -31.8311 31.8311c0 17.5635 14.2686 31.832 31.8311 31.832h95.4951
-c0 52.7529 42.7422 95.4941 95.4941 95.4941c52.7217 0 95.4951 -42.7725 95.4951 -95.4941h95.4951c17.5947 0 31.832 -14.2686 31.832 -31.832c0.0146484 -17.5938 -14.207 -31.8311 -31.8164 -31.8311zM252.772 383.312c-17.5625 0 -31.8311 -14.2676 -31.8311 -31.8311
-h63.6631c0.015625 17.5635 -14.2686 31.8311 -31.832 31.8311zM380.115 287.818h-254.669v-254.668c0 -17.5781 14.2686 -31.8311 31.832 -31.8311h191.005c17.6104 0 31.832 14.2529 31.832 31.8311v254.668zM316.452 255.971h31.8311v-222.836h-31.8311v222.836z
-M220.941 255.971h63.6631v-222.836h-63.6631v222.836zM157.278 255.971h31.8311v-222.836h-31.8311v222.836z" />
-    <glyph glyph-name="uniF122" unicode="&#xf122;" 
-d="M331.522 -63.0078h-191.148c-52.7959 0 -95.5742 42.8086 -95.5742 95.5742v0c9.84668 58.4268 49.1562 107.521 99.1523 135.21c-21.8398 22.8672 -35.4355 53.667 -35.4355 87.7959v63.7158c-0.000976562 70.374 57.0576 127.432 127.432 127.432
-s127.432 -57.0576 127.432 -127.432v-63.7158c0 -34.1289 -13.5957 -64.9287 -35.4043 -87.7969c49.9648 -27.6885 89.2734 -76.7832 99.1211 -135.21v0c-0.000976562 -52.7646 -42.8096 -95.5732 -95.5742 -95.5732zM299.664 255.572v63.7158
-c0 35.1709 -28.5449 63.7158 -63.7158 63.7158c-35.1719 0 -63.7158 -28.5449 -63.7158 -63.7158v-63.7158c0 -35.1709 28.5439 -63.7158 63.7158 -63.7158c35.1709 0 63.7158 28.5449 63.7158 63.7158zM363.38 32.5654c-14.2178 54.8809 -68.1338 95.5742 -127.432 95.5742
-v0v0c-59.3291 0 -113.214 -40.6934 -127.433 -95.5742v0c0 -17.6084 14.2803 -31.8574 31.8584 -31.8574h191.148c17.6084 0 31.8574 14.249 31.8574 31.8574v0z" />
-    <glyph glyph-name="uniF123" unicode="&#xf123;" 
-d="M410.583 169.941c49.8057 -27.6006 88.9912 -76.5381 98.8057 -134.779c0 -52.5977 -42.6729 -95.2705 -95.2705 -95.2705h-43.9131c18.9473 16.5449 32.8418 38.4248 39.3848 63.5137h4.52832c17.5527 0 31.7568 14.2031 31.7568 31.7568
-c-8.1875 31.6318 -29.8184 58.1787 -57.8691 75.2666c-14.793 25.6484 -34.7344 48.7832 -58.9551 67.4834c3.64453 6.24902 6.85449 12.7773 9.59863 19.4922c25.3379 8.38867 43.7129 31.957 43.7129 60.0547v63.5137c0 28.1279 -18.375 51.6982 -43.7285 60.0557
-c-10.3574 25.1816 -27.3213 46.7197 -48.2871 63.4824c9.18066 2.12402 18.6699 3.48926 28.501 3.48926c70.1514 0 127.027 -56.877 127.027 -127.027v-63.5137c0 -34.0205 -13.5518 -64.7227 -35.292 -87.5176zM287.091 -60.1084h-190.54
-c-52.6279 0 -95.2705 42.6719 -95.2705 95.2705v0c9.81543 58.2412 49 107.179 98.8369 134.779c-21.7705 22.7949 -35.3232 53.4971 -35.3232 87.5176v63.5137c0 70.1504 56.877 127.027 127.026 127.027c70.1504 0 127.027 -56.877 127.027 -127.027v-63.5137
-c0 -34.0205 -13.5527 -64.7227 -35.292 -87.5176c49.8057 -27.6006 88.9902 -76.5381 98.8057 -134.779v0c0.000976562 -52.5986 -42.6729 -95.2705 -95.2705 -95.2705zM255.334 257.459v63.5137c0 35.0596 -28.4541 63.5137 -63.5137 63.5137
-s-63.5127 -28.4541 -63.5127 -63.5137v-63.5137c0 -35.0596 28.4531 -63.5127 63.5127 -63.5127s63.5137 28.4531 63.5137 63.5127zM318.848 35.1621c-14.1729 54.7061 -67.917 95.2695 -127.027 95.2695v0v0c-59.1396 0 -112.854 -40.5635 -127.026 -95.2695v0
-c0 -17.5537 14.2344 -31.7568 31.7568 -31.7568h190.54c17.5537 0 31.7568 14.2031 31.7568 31.7568v0z" />
-    <glyph glyph-name="uniF124" unicode="&#xf124;" 
-d="M502.882 356.449c3.70898 -11.8682 6.24414 -24.2305 6.24414 -37.3037c0 -69.8789 -56.6826 -126.592 -126.593 -126.592c-19.4707 0 -37.7676 4.79102 -54.209 12.6406l-253.556 -253.463c-7.54102 -7.66406 -18.1113 -12.3623 -29.793 -12.3623
-c-23.3652 0 -42.2188 18.915 -42.2188 42.1572c0 11.7441 4.75977 22.252 12.3633 29.917l253.493 253.431c-7.91211 16.5352 -12.6719 34.7695 -12.6719 54.2705c0 69.8789 56.6826 126.593 126.592 126.593c12.6719 0 24.7256 -2.44141 36.2842 -5.93457l-78.502 -78.4707
-v-84.374h83.0762z" />
-    <glyph glyph-name="uniF125" unicode="&#xf125;" 
-d="M511.488 39.5137l-102.029 -102.03l-152.973 153.044l-153.044 -153.044l-101.959 102.03l152.974 152.973l-152.974 152.973l101.959 102.029l153.044 -153.043l152.973 153.043l102.029 -102.029l-153.115 -152.973z" />
-  </font>
-</defs></svg>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/img/fontcustom_fauxton.ttf
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/img/fontcustom_fauxton.ttf b/apps/fauxton/assets/img/fontcustom_fauxton.ttf
deleted file mode 100644
index 4df286c..0000000
Binary files a/apps/fauxton/assets/img/fontcustom_fauxton.ttf and /dev/null differ

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/img/fontcustom_fauxton.woff
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/img/fontcustom_fauxton.woff b/apps/fauxton/assets/img/fontcustom_fauxton.woff
deleted file mode 100644
index a6a3fb2..0000000
Binary files a/apps/fauxton/assets/img/fontcustom_fauxton.woff and /dev/null differ

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/img/glyphicons-halflings-white.png
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/img/glyphicons-halflings-white.png b/apps/fauxton/assets/img/glyphicons-halflings-white.png
deleted file mode 100644
index 3bf6484..0000000
Binary files a/apps/fauxton/assets/img/glyphicons-halflings-white.png and /dev/null differ

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/img/glyphicons-halflings.png
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/img/glyphicons-halflings.png b/apps/fauxton/assets/img/glyphicons-halflings.png
deleted file mode 100644
index 79bc568..0000000
Binary files a/apps/fauxton/assets/img/glyphicons-halflings.png and /dev/null differ

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/img/linen.png
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/img/linen.png b/apps/fauxton/assets/img/linen.png
deleted file mode 100644
index 365c61a..0000000
Binary files a/apps/fauxton/assets/img/linen.png and /dev/null differ

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/img/loader.gif
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/img/loader.gif b/apps/fauxton/assets/img/loader.gif
deleted file mode 100644
index 96ff188..0000000
Binary files a/apps/fauxton/assets/img/loader.gif and /dev/null differ

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/img/minilogo.png
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/img/minilogo.png b/apps/fauxton/assets/img/minilogo.png
deleted file mode 100644
index 63e005c..0000000
Binary files a/apps/fauxton/assets/img/minilogo.png and /dev/null differ

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/index.underscore
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/index.underscore b/apps/fauxton/assets/index.underscore
deleted file mode 100644
index cbf5bd6..0000000
--- a/apps/fauxton/assets/index.underscore
+++ /dev/null
@@ -1,47 +0,0 @@
-<!doctype html>
-
-<!--
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
--->
-
-<html lang="en">
-<head>
-  <meta charset="utf-8">
-  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
-  <meta name="viewport" content="width=device-width,initial-scale=1">
-  <meta http-equiv="Content-Language" content="en" />
-
-  <title>Project Fauxton</title>
-
-  <!-- Application styles. -->
-  <link rel="stylesheet" href="<%= css %>">
-  <% if (base) { %>
-  <base href="<%= base %>"></base>
-  <% } %>
-</head>
-
-<body id="home">
-  <!-- Main container. -->
-  <div role="main" id="main">
-    <div id="global-notifications" class="container errors-container"></div>
-    <div id="app-container"></div>
-
-    <footer>
-      <div id="footer-content"></div>
-    </footer>
-  </div>
-
-  <!-- Application source. -->
-  <script data-main="/config" src="<%= requirejs %>"></script>
-</body>
-</html>


[84/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/msgfmt.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/msgfmt.h b/src/apps/couch_collate/platform/osx/icu/unicode/msgfmt.h
new file mode 100644
index 0000000..67e17cf
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/msgfmt.h
@@ -0,0 +1,940 @@
+/*
+* Copyright (C) 2007-2008, International Business Machines Corporation and others. All Rights Reserved.
+********************************************************************************
+*
+* File MSGFMT.H
+*
+* Modification History:
+*
+*   Date        Name        Description
+*   02/19/97    aliu        Converted from java.
+*   03/20/97    helena      Finished first cut of implementation.
+*   07/22/98    stephen     Removed operator!= (defined in Format)
+*   08/19/2002  srl         Removing Javaisms
+********************************************************************************
+*/
+
+#ifndef MSGFMT_H
+#define MSGFMT_H
+
+#include "unicode/utypes.h"
+
+/**
+ * \file 
+ * \brief C++ API: Formats messages in a language-neutral way.
+ */
+ 
+#if !UCONFIG_NO_FORMATTING
+
+#include "unicode/format.h"
+#include "unicode/locid.h"
+#include "unicode/parseerr.h"
+#include "unicode/uchar.h"
+
+U_NAMESPACE_BEGIN
+
+class NumberFormat;
+class DateFormat;
+
+/**
+ *
+ * A MessageFormat produces concatenated messages in a
+ * language-neutral way.  It should be used for all string
+ * concatenations that are visible to end users.
+ * <P>
+ * A MessageFormat contains an array of <EM>subformats</EM> arranged
+ * within a <EM>template string</EM>.  Together, the subformats and
+ * template string determine how the MessageFormat will operate during
+ * formatting and parsing.
+ * <P>
+ * Typically, both the subformats and the template string are
+ * specified at once in a <EM>pattern</EM>.  By using different
+ * patterns for different locales, messages may be localized.
+ * <P>
+ * During formatting, the MessageFormat takes an array of arguments
+ * and produces a user-readable string.  Each argument is a
+ * Formattable object; they may be passed in in an array, or as a
+ * single Formattable object which itself contains an array.  Each
+ * argument is matched up with its corresponding subformat, which then
+ * formats it into a string.  The resultant strings are then assembled
+ * within the string template of the MessageFormat to produce the
+ * final output string.
+ * <p>
+ * <strong>Note:</strong>
+ * In ICU 4.0 MessageFormat supports named arguments.  If a named argument
+ * is used, all arguments must be named.  Names start with a character in 
+ * <code>UCHAR_ID_START</code> and continue with characters in 
+ * <code>UCHARID_CONTINUE</code>, in particular they do not start with a digit.
+ * If named arguments are used, {@link #usesNamedArguments()} will return true.
+ * <p>
+ * The other new methods supporting named arguments are 
+ * {@link #getFormatNames(UErrorCode& status)},
+ * {@link #getFormat(const UnicodeString& formatName, UErrorCode& status)}
+ * {@link #setFormat(const UnicodeString& formatName, const Format& format, UErrorCode& status)},
+ * {@link #adoptFormat(const UnicodeString& formatName, Format* formatToAdopt, UErrorCode& status)},
+ * {@link #format(const Formattable* arguments, const UnicodeString *argumentNames, int32_t cnt, UnicodeString& appendTo, FieldPosition& status, int32_t recursionProtection, UErrorCode& success)},
+ * {@link #format(const UnicodeString* argumentNames, const Formattable* arguments, int32_t count, UnicodeString& appendTo,UErrorCode& status)}.
+ * These methods are all compatible with patterns that do not used named arguments-- 
+ * in these cases the keys in the input or output use <code>UnicodeString</code>s 
+ * that name the argument indices, e.g. "0", "1", "2"... etc.
+ * <p>
+ * When named arguments are used, certain methods on MessageFormat that take or
+ * return arrays do not perform any action, since it is not possible to
+ * identify positions in an array using a name.  UErrorCode is set to
+ * U_ARGUMENT_TYPE_MISMATCH if there is a status/success field in the method.
+ * These methods are 
+ * {@link #adoptFormats(Format** newFormats, int32_t count)},
+ * {@link #setFormats(const Format** newFormats,int32_t count)},
+ * {@link #adoptFormat(int32_t n, Format *newFormat)},
+ * {@link #getFormats(int32_t& cnt)},
+ * {@link #format(const Formattable* source,int32_t cnt,UnicodeString& appendTo, FieldPosition& ignore, UErrorCode& success)},
+ * {@link #format(const UnicodeString& pattern,const Formattable* arguments,int32_t cnt,UnicodeString& appendTo,UErrorCode& success)},
+ * {@link #format(const Formattable& source, UnicodeString& appendTo,FieldPosition& ignore, UErrorCode& success)},
+ * {@link #format(const Formattable* arguments, int32_t cnt, UnicodeString& appendTo, FieldPosition& status, int32_t recursionProtection,UErrorCode& success)},
+ * {@link #parse(const UnicodeString& source, ParsePosition& pos,int32_t& count)},
+ * {@link #parse(const UnicodeString& source, int32_t& cnt, UErrorCode& status)}
+ * <p>
+ *
+ * <P>
+ * During parsing, an input string is matched against the string
+ * template of the MessageFormat to produce an array of Formattable
+ * objects.  Plain text of the template string is matched directly
+ * against intput text.  At each position in the template string where
+ * a subformat is located, the subformat is called to parse the
+ * corresponding segment of input text to produce an output argument.
+ * In this way, an array of arguments is created which together
+ * constitute the parse result.
+ * <P>
+ * Parsing may fail or produce unexpected results in a number of
+ * circumstances.
+ * <UL>
+ * <LI>If one of the arguments does not occur in the pattern, it
+ * will be returned as a default Formattable.
+ * <LI>If the format of an argument is loses information, such as with
+ * a choice format where a large number formats to "many", then the
+ * parse may not correspond to the originally formatted argument.
+ * <LI>MessageFormat does not handle ChoiceFormat recursion during
+ * parsing; such parses will fail.
+ * <LI>Parsing will not always find a match (or the correct match) if
+ * some part of the parse is ambiguous.  For example, if the pattern
+ * "{1},{2}" is used with the string arguments {"a,b", "c"}, it will
+ * format as "a,b,c".  When the result is parsed, it will return {"a",
+ * "b,c"}.
+ * <LI>If a single argument is formatted more than once in the string,
+ * then the rightmost subformat in the pattern string will produce the
+ * parse result; prior subformats with the same argument index will
+ * have no effect.
+ * </UL>
+ * Here are some examples of usage:
+ * <P>
+ * Example 1:
+ * <pre>
+ * \code
+ *     UErrorCode success = U_ZERO_ERROR;
+ *     GregorianCalendar cal(success);
+ *     Formattable arguments[] = {
+ *         7L,
+ *         Formattable( (Date) cal.getTime(success), Formattable::kIsDate),
+ *         "a disturbance in the Force"
+ *     };
+ *
+ *     UnicodeString result;
+ *     MessageFormat::format(
+ *          "At {1,time} on {1,date}, there was {2} on planet {0,number}.",
+ *          arguments, 3, result, success );
+ *
+ *     cout << "result: " << result << endl;
+ *     //<output>: At 4:34:20 PM on 23-Mar-98, there was a disturbance
+ *     //             in the Force on planet 7.
+ * \endcode
+ * </pre>
+ * Typically, the message format will come from resources, and the
+ * arguments will be dynamically set at runtime.
+ * <P>
+ * Example 2:
+ * <pre>
+ *  \code
+ *     success = U_ZERO_ERROR;
+ *     Formattable testArgs[] = {3L, "MyDisk"};
+ *
+ *     MessageFormat form(
+ *         "The disk \"{1}\" contains {0} file(s).", success );
+ *
+ *     UnicodeString string;
+ *     FieldPosition fpos = 0;
+ *     cout << "format: " << form.format(testArgs, 2, string, fpos, success ) << endl;
+ *
+ *     // output, with different testArgs:
+ *     // output: The disk "MyDisk" contains 0 file(s).
+ *     // output: The disk "MyDisk" contains 1 file(s).
+ *     // output: The disk "MyDisk" contains 1,273 file(s).
+ *  \endcode
+ *  </pre>
+ *
+ *  The pattern is of the following form.  Legend:
+ *  <pre>
+ * \code
+ *       {optional item}
+ *       (group that may be repeated)*
+ * \endcode
+ *  </pre>
+ *  Do not confuse optional items with items inside quotes braces, such
+ *  as this: "{".  Quoted braces are literals.
+ *  <pre>
+ *  \code
+ *       messageFormatPattern := string ( "{" messageFormatElement "}" string )*
+ *
+ *       messageFormatElement := argumentIndex | argumentName { "," elementFormat }
+ *
+ *       elementFormat := "time" { "," datetimeStyle }
+ *                      | "date" { "," datetimeStyle }
+ *                      | "number" { "," numberStyle }
+ *                      | "choice" "," choiceStyle
+ *
+ *       datetimeStyle := "short"
+ *                      | "medium"
+ *                      | "long"
+ *                      | "full"
+ *                      | dateFormatPattern
+ *
+ *       numberStyle :=   "currency"
+ *                      | "percent"
+ *                      | "integer"
+ *                      | numberFormatPattern
+ *
+ *       choiceStyle :=   choiceFormatPattern
+ * 
+ *       pluralStyle := pluralFormatPattern
+ * \endcode
+ * </pre>
+ * If there is no elementFormat, then the argument must be a string,
+ * which is substituted. If there is no dateTimeStyle or numberStyle,
+ * then the default format is used (e.g.  NumberFormat::createInstance(),
+ * DateFormat::createTimeInstance(DateFormat::kDefault, ...) or DateFormat::createDateInstance(DateFormat::kDefault, ...). For
+ * a ChoiceFormat, the pattern must always be specified, since there
+ * is no default.
+ * <P>
+ * In strings, single quotes can be used to quote syntax characters.
+ * A literal single quote is represented by '', both within and outside
+ * of single-quoted segments.  Inside a
+ * messageFormatElement, quotes are <EM>not</EM> removed. For example,
+ * {1,number,$'#',##} will produce a number format with the pound-sign
+ * quoted, with a result such as: "$#31,45".
+ * <P>
+ * If a pattern is used, then unquoted braces in the pattern, if any,
+ * must match: that is, "ab {0} de" and "ab '}' de" are ok, but "ab
+ * {0'}' de" and "ab } de" are not.
+ * <p>
+ * <dl><dt><b>Warning:</b><dd>The rules for using quotes within message
+ * format patterns unfortunately have shown to be somewhat confusing.
+ * In particular, it isn't always obvious to localizers whether single
+ * quotes need to be doubled or not. Make sure to inform localizers about
+ * the rules, and tell them (for example, by using comments in resource
+ * bundle source files) which strings will be processed by MessageFormat.
+ * Note that localizers may need to use single quotes in translated
+ * strings where the original version doesn't have them.
+ * <br>Note also that the simplest way to avoid the problem is to
+ * use the real apostrophe (single quote) character U+2019 (') for
+ * human-readable text, and to use the ASCII apostrophe (U+0027 ' )
+ * only in program syntax, like quoting in MessageFormat.
+ * See the annotations for U+0027 Apostrophe in The Unicode Standard.</p>
+ * </dl>
+ * <P>
+ * The argumentIndex is a non-negative integer, which corresponds to the
+ * index of the arguments presented in an array to be formatted.  The
+ * first argument has argumentIndex 0.
+ * <P>
+ * It is acceptable to have unused arguments in the array.  With missing
+ * arguments or arguments that are not of the right class for the
+ * specified format, a failing UErrorCode result is set.
+ * <P>
+ * For more sophisticated patterns, you can use a ChoiceFormat to get
+ * output:
+ * <pre>
+ * \code
+ *     UErrorCode success = U_ZERO_ERROR;
+ *     MessageFormat* form("The disk \"{1}\" contains {0}.", success);
+ *     double filelimits[] = {0,1,2};
+ *     UnicodeString filepart[] = {"no files","one file","{0,number} files"};
+ *     ChoiceFormat* fileform = new ChoiceFormat(filelimits, filepart, 3);
+ *     form.setFormat(1, *fileform); // NOT zero, see below
+ *
+ *     Formattable testArgs[] = {1273L, "MyDisk"};
+ *
+ *     UnicodeString string;
+ *     FieldPosition fpos = 0;
+ *     cout << form.format(testArgs, 2, string, fpos, success) << endl;
+ *
+ *     // output, with different testArgs
+ *     // output: The disk "MyDisk" contains no files.
+ *     // output: The disk "MyDisk" contains one file.
+ *     // output: The disk "MyDisk" contains 1,273 files.
+ * \endcode
+ * </pre>
+ * You can either do this programmatically, as in the above example,
+ * or by using a pattern (see ChoiceFormat for more information) as in:
+ * <pre>
+ * \code
+ *    form.applyPattern(
+ *      "There {0,choice,0#are no files|1#is one file|1<are {0,number,integer} files}.");
+ * \endcode
+ * </pre>
+ * <P>
+ * <EM>Note:</EM> As we see above, the string produced by a ChoiceFormat in
+ * MessageFormat is treated specially; occurences of '{' are used to
+ * indicated subformats, and cause recursion.  If you create both a
+ * MessageFormat and ChoiceFormat programmatically (instead of using
+ * the string patterns), then be careful not to produce a format that
+ * recurses on itself, which will cause an infinite loop.
+ * <P>
+ * <EM>Note:</EM> Subformats are numbered by their order in the pattern.
+ * This is <EM>not</EM> the same as the argumentIndex.
+ * <pre>
+ * \code
+ *    For example: with "abc{2}def{3}ghi{0}...",
+ *
+ *    format0 affects the first variable {2}
+ *    format1 affects the second variable {3}
+ *    format2 affects the second variable {0}
+ * \endcode
+ * </pre>
+ *
+ * <p><em>User subclasses are not supported.</em> While clients may write
+ * subclasses, such code will not necessarily work and will not be
+ * guaranteed to work stably from release to release.
+ */
+class U_I18N_API MessageFormat : public Format {
+public:
+    /**
+     * Enum type for kMaxFormat.
+     * @obsolete ICU 3.0.  The 10-argument limit was removed as of ICU 2.6,
+     * rendering this enum type obsolete.
+     */
+    enum EFormatNumber {
+        /**
+         * The maximum number of arguments.
+         * @obsolete ICU 3.0.  The 10-argument limit was removed as of ICU 2.6,
+         * rendering this constant obsolete.
+         */
+        kMaxFormat = 10
+    };
+
+    /**
+     * Constructs a new MessageFormat using the given pattern and the
+     * default locale.
+     *
+     * @param pattern   Pattern used to construct object.
+     * @param status    Input/output error code.  If the
+     *                  pattern cannot be parsed, set to failure code.
+     * @stable ICU 2.0
+     */
+    MessageFormat(const UnicodeString& pattern,
+                  UErrorCode &status);
+
+    /**
+     * Constructs a new MessageFormat using the given pattern and locale.
+     * @param pattern   Pattern used to construct object.
+     * @param newLocale The locale to use for formatting dates and numbers.
+     * @param status    Input/output error code.  If the
+     *                  pattern cannot be parsed, set to failure code.
+     * @stable ICU 2.0
+     */
+    MessageFormat(const UnicodeString& pattern,
+                  const Locale& newLocale,
+                        UErrorCode& status);
+    /**
+     * Constructs a new MessageFormat using the given pattern and locale.
+     * @param pattern   Pattern used to construct object.
+     * @param newLocale The locale to use for formatting dates and numbers.
+     * @param parseError Struct to recieve information on position 
+     *                   of error within the pattern.
+     * @param status    Input/output error code.  If the
+     *                  pattern cannot be parsed, set to failure code.
+     * @stable ICU 2.0
+     */
+    MessageFormat(const UnicodeString& pattern,
+                  const Locale& newLocale,
+                  UParseError& parseError,
+                  UErrorCode& status);
+    /**
+     * Constructs a new MessageFormat from an existing one.
+     * @stable ICU 2.0
+     */
+    MessageFormat(const MessageFormat&);
+
+    /**
+     * Assignment operator.
+     * @stable ICU 2.0
+     */
+    const MessageFormat& operator=(const MessageFormat&);
+
+    /**
+     * Destructor.
+     * @stable ICU 2.0
+     */
+    virtual ~MessageFormat();
+
+    /**
+     * Clones this Format object polymorphically.  The caller owns the
+     * result and should delete it when done.
+     * @stable ICU 2.0
+     */
+    virtual Format* clone(void) const;
+
+    /**
+     * Returns true if the given Format objects are semantically equal.
+     * Objects of different subclasses are considered unequal.
+     * @param other  the object to be compared with.
+     * @return       true if the given Format objects are semantically equal.
+     * @stable ICU 2.0
+     */
+    virtual UBool operator==(const Format& other) const;
+
+    /**
+     * Sets the locale. This locale is used for fetching default number or date
+     * format information.
+     * @param theLocale    the new locale value to be set.
+     * @stable ICU 2.0
+     */
+    virtual void setLocale(const Locale& theLocale);
+
+    /**
+     * Gets the locale. This locale is used for fetching default number or date
+     * format information.
+     * @return    the locale of the object.
+     * @stable ICU 2.0
+     */
+    virtual const Locale& getLocale(void) const;
+
+    /**
+     * Applies the given pattern string to this message format.
+     *
+     * @param pattern   The pattern to be applied.
+     * @param status    Input/output error code.  If the
+     *                  pattern cannot be parsed, set to failure code.
+     * @stable ICU 2.0
+     */
+    virtual void applyPattern(const UnicodeString& pattern,
+                              UErrorCode& status);
+    /**
+     * Applies the given pattern string to this message format.
+     *
+     * @param pattern    The pattern to be applied.
+     * @param parseError Struct to recieve information on position 
+     *                   of error within pattern.
+     * @param status    Input/output error code.  If the
+     *                  pattern cannot be parsed, set to failure code.
+     * @stable ICU 2.0
+     */
+    virtual void applyPattern(const UnicodeString& pattern,
+                             UParseError& parseError,
+                             UErrorCode& status);
+
+    /**
+     * Returns a pattern that can be used to recreate this object.
+     *
+     * @param appendTo  Output parameter to receive the pattern.
+     *                  Result is appended to existing contents.
+     * @return          Reference to 'appendTo' parameter.
+     * @stable ICU 2.0
+     */
+    virtual UnicodeString& toPattern(UnicodeString& appendTo) const;
+
+    /**
+     * Sets subformats.
+     * See the class description about format numbering.
+     * The caller should not delete the Format objects after this call.
+     * <EM>The array formatsToAdopt is not itself adopted.</EM> Its
+     * ownership is retained by the caller. If the call fails because
+     * memory cannot be allocated, then the formats will be deleted
+     * by this method, and this object will remain unchanged.
+     * 
+     * @stable ICU 2.0
+     * @param formatsToAdopt    the format to be adopted.
+     * @param count             the size of the array.
+     */
+    virtual void adoptFormats(Format** formatsToAdopt, int32_t count);
+
+    /**
+     * Sets subformats.
+     * See the class description about format numbering.
+     * Each item in the array is cloned into the internal array.
+     * If the call fails because memory cannot be allocated, then this
+     * object will remain unchanged.
+     * 
+     * @stable ICU 2.0
+     * @param newFormats the new format to be set.
+     * @param cnt        the size of the array.
+     */
+    virtual void setFormats(const Format** newFormats, int32_t cnt);
+
+
+    /**
+     * Sets one subformat.
+     * See the class description about format numbering.
+     * The caller should not delete the Format object after this call.
+     * If the number is over the number of formats already set,
+     * the item will be deleted and ignored.
+     * @stable ICU 2.0
+     * @param formatNumber     index of the subformat.
+     * @param formatToAdopt    the format to be adopted.
+     */
+    virtual void adoptFormat(int32_t formatNumber, Format* formatToAdopt);
+
+    /**
+     * Sets one subformat.
+     * See the class description about format numbering.
+     * If the number is over the number of formats already set,
+     * the item will be ignored.
+     * @param formatNumber     index of the subformat.
+     * @param format    the format to be set.
+     * @stable ICU 2.0
+     */
+    virtual void setFormat(int32_t formatNumber, const Format& format);
+
+    /**
+     * Gets format names. This function returns formatNames in StringEnumerations
+     * which can be used with getFormat() and setFormat() to export formattable 
+     * array from current MessageFormat to another.  It is caller's resposibility 
+     * to delete the returned formatNames.
+     * @param status  output param set to success/failure code.
+     * @draft ICU 4.0
+     */
+    virtual StringEnumeration* getFormatNames(UErrorCode& status);
+    
+    /**
+     * Gets subformat pointer for given format name.   
+     * This function supports both named and numbered
+     * arguments-- if numbered, the formatName is the
+     * corresponding UnicodeStrings (e.g. "0", "1", "2"...).
+     * The returned Format object should not be deleted by the caller,
+     * nor should the ponter of other object .  The pointer and its 
+     * contents remain valid only until the next call to any method
+     * of this class is made with this object. 
+     * @param formatName the name or number specifying a format
+     * @param status  output param set to success/failure code.
+     * @draft ICU 4.0
+     */
+    virtual Format* getFormat(const UnicodeString& formatName, UErrorCode& status);
+    
+    /**
+     * Sets one subformat for given format name.
+     * See the class description about format name. 
+     * This function supports both named and numbered
+     * arguments-- if numbered, the formatName is the
+     * corresponding UnicodeStrings (e.g. "0", "1", "2"...).
+     * If there is no matched formatName or wrong type,
+     * the item will be ignored.
+     * @param formatName  Name of the subformat.
+     * @param format      the format to be set.
+     * @param status  output param set to success/failure code.
+     * @draft ICU 4.0
+     */
+    virtual void setFormat(const UnicodeString& formatName, const Format& format, UErrorCode& status);
+    
+    /**
+     * Sets one subformat for given format name.
+     * See the class description about format name. 
+     * This function supports both named and numbered
+     * arguments-- if numbered, the formatName is the
+     * corresponding UnicodeStrings (e.g. "0", "1", "2"...).
+     * If there is no matched formatName or wrong type,
+     * the item will be ignored.
+     * The caller should not delete the Format object after this call.
+     * @param formatName  Name of the subformat.
+     * @param formatToAdopt  Format to be adopted.
+     * @param status      output param set to success/failure code.
+     * @draft ICU 4.0
+     */
+    virtual void adoptFormat(const UnicodeString& formatName, Format* formatToAdopt, UErrorCode& status);
+
+
+    /**
+     * Gets an array of subformats of this object.  The returned array
+     * should not be deleted by the caller, nor should the pointers
+     * within the array.  The array and its contents remain valid only
+     * until the next call to any method of this class is made with
+     * this object.  See the class description about format numbering.
+     * @param count output parameter to receive the size of the array
+     * @return an array of count Format* objects, or NULL if out of
+     * memory.  Any or all of the array elements may be NULL.
+     * @stable ICU 2.0
+     */
+    virtual const Format** getFormats(int32_t& count) const;
+
+    /**
+     * Formats the given array of arguments into a user-readable string.
+     * Does not take ownership of the Formattable* array or its contents.
+     *
+     * @param source    An array of objects to be formatted.
+     * @param count     The number of elements of 'source'.
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     * @param ignore    Not used; inherited from base class API.
+     * @param status    Input/output error code.  If the
+     *                  pattern cannot be parsed, set to failure code.
+     * @return          Reference to 'appendTo' parameter.
+     * @stable ICU 2.0
+     */
+    UnicodeString& format(  const Formattable* source,
+                            int32_t count,
+                            UnicodeString& appendTo,
+                            FieldPosition& ignore,
+                            UErrorCode& status) const;
+
+    /**
+     * Formats the given array of arguments into a user-readable string
+     * using the given pattern.
+     *
+     * @param pattern   The pattern.
+     * @param arguments An array of objects to be formatted.
+     * @param count     The number of elements of 'source'.
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     * @param status    Input/output error code.  If the
+     *                  pattern cannot be parsed, set to failure code.
+     * @return          Reference to 'appendTo' parameter.
+     * @stable ICU 2.0
+     */
+    static UnicodeString& format(const UnicodeString& pattern,
+                                 const Formattable* arguments,
+                                 int32_t count,
+                                 UnicodeString& appendTo,
+                                 UErrorCode& status);
+
+    /**
+     * Formats the given array of arguments into a user-readable
+     * string.  The array must be stored within a single Formattable
+     * object of type kArray. If the Formattable object type is not of
+     * type kArray, then returns a failing UErrorCode.
+     *
+     * @param obj       A Formattable of type kArray containing
+     *                  arguments to be formatted.
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     * @param pos       On input: an alignment field, if desired.
+     *                  On output: the offsets of the alignment field.
+     * @param status    Input/output error code.  If the
+     *                  pattern cannot be parsed, set to failure code.
+     * @return          Reference to 'appendTo' parameter.
+     * @stable ICU 2.0
+     */
+    virtual UnicodeString& format(const Formattable& obj,
+                                  UnicodeString& appendTo,
+                                  FieldPosition& pos,
+                                  UErrorCode& status) const;
+
+    /**
+     * Formats the given array of arguments into a user-readable
+     * string.  The array must be stored within a single Formattable
+     * object of type kArray. If the Formattable object type is not of
+     * type kArray, then returns a failing UErrorCode.
+     *
+     * @param obj       The object to format
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     * @param status    Input/output error code.  If the
+     *                  pattern cannot be parsed, set to failure code.
+     * @return          Reference to 'appendTo' parameter.
+     * @stable ICU 2.0
+     */
+    UnicodeString& format(const Formattable& obj,
+                          UnicodeString& appendTo,
+                          UErrorCode& status) const;
+    
+
+    /**
+     * Formats the given array of arguments into a user-defined argument name
+     * array. This function supports both named and numbered
+     * arguments-- if numbered, the formatName is the
+     * corresponding UnicodeStrings (e.g. "0", "1", "2"...).
+     *
+     * @param argumentNames argument name array
+     * @param arguments An array of objects to be formatted.
+     * @param count     The number of elements of 'argumentNames' and 
+     *                  arguments.  The number of argumentNames and arguments
+     *                  must be the same.
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     * @param status    Input/output error code.  If the
+     *                  pattern cannot be parsed, set to failure code.
+     * @return          Reference to 'appendTo' parameter.
+     * @stable ICU 4.0
+     */
+    UnicodeString& format(const UnicodeString* argumentNames,
+                          const Formattable* arguments,
+                          int32_t count,
+                          UnicodeString& appendTo,
+                          UErrorCode& status) const;
+    /**
+     * Parses the given string into an array of output arguments.
+     *
+     * @param source    String to be parsed.
+     * @param pos       On input, starting position for parse. On output,
+     *                  final position after parse.  Unchanged if parse
+     *                  fails.
+     * @param count     Output parameter to receive the number of arguments
+     *                  parsed.
+     * @return an array of parsed arguments.  The caller owns both
+     * the array and its contents.
+     * @stable ICU 2.0
+     */
+    virtual Formattable* parse( const UnicodeString& source,
+                                ParsePosition& pos,
+                                int32_t& count) const;
+
+    /**
+     * Parses the given string into an array of output arguments.
+     *
+     * @param source    String to be parsed.
+     * @param count     Output param to receive size of returned array.
+     * @param status    Input/output error code.  If the
+     *                  pattern cannot be parsed, set to failure code. 
+     *                  If the MessageFormat is named argument, the status is 
+     *                  set to U_ARGUMENT_TYPE_MISMATCH.
+     * @return an array of parsed arguments.  The caller owns both
+     * the array and its contents. Return NULL if status is not U_ZERO_ERROR.
+     * 
+     * @stable ICU 2.0
+     */
+    virtual Formattable* parse( const UnicodeString& source,
+                                int32_t& count,
+                                UErrorCode& status) const;
+
+    /**
+     * Parses the given string into an array of output arguments
+     * stored within a single Formattable of type kArray.
+     *
+     * @param source    The string to be parsed into an object.
+     * @param result    Formattable to be set to the parse result.
+     *                  If parse fails, return contents are undefined.
+     * @param pos       On input, starting position for parse. On output,
+     *                  final position after parse.  Unchanged if parse
+     *                  fails.
+     * @stable ICU 2.0
+     */
+    virtual void parseObject(const UnicodeString& source,
+                             Formattable& result,
+                             ParsePosition& pos) const;
+
+    /**
+     * Convert an 'apostrophe-friendly' pattern into a standard
+     * pattern.  Standard patterns treat all apostrophes as
+     * quotes, which is problematic in some languages, e.g. 
+     * French, where apostrophe is commonly used.  This utility
+     * assumes that only an unpaired apostrophe immediately before
+     * a brace is a true quote.  Other unpaired apostrophes are paired,
+     * and the resulting standard pattern string is returned.
+     *
+     * <p><b>Note</b> it is not guaranteed that the returned pattern
+     * is indeed a valid pattern.  The only effect is to convert
+     * between patterns having different quoting semantics.
+     *
+     * @param pattern the 'apostrophe-friendly' patttern to convert
+     * @param status    Input/output error code.  If the pattern
+     *                  cannot be parsed, the failure code is set.
+     * @return the standard equivalent of the original pattern
+     * @stable ICU 3.4
+     */
+    static UnicodeString autoQuoteApostrophe(const UnicodeString& pattern, 
+        UErrorCode& status);
+    
+    /**
+     * Returns true if this MessageFormat uses named arguments,
+     * and false otherwise.  See class description.
+     *
+     * @return true if named arguments are used.
+     * @draft ICU 4.0
+     */
+    UBool usesNamedArguments() const;
+    
+    /**
+     * Returns a unique class ID POLYMORPHICALLY.  Pure virtual override.
+     * This method is to implement a simple version of RTTI, since not all
+     * C++ compilers support genuine RTTI.  Polymorphic operator==() and
+     * clone() methods call this method.
+     *
+     * @return          The class ID for this object. All objects of a
+     *                  given class have the same class ID.  Objects of
+     *                  other classes have different class IDs.
+     * @stable ICU 2.0
+     */
+    virtual UClassID getDynamicClassID(void) const;
+
+    /**
+     * Return the class ID for this class.  This is useful only for
+     * comparing to a return value from getDynamicClassID().  For example:
+     * <pre>
+     * .   Base* polymorphic_pointer = createPolymorphicObject();
+     * .   if (polymorphic_pointer->getDynamicClassID() ==
+     * .      Derived::getStaticClassID()) ...
+     * </pre>
+     * @return          The class ID for all objects of this class.
+     * @stable ICU 2.0
+     */
+    static UClassID U_EXPORT2 getStaticClassID(void);
+    
+private:
+
+    Locale              fLocale;
+    UnicodeString       fPattern;
+    Format**            formatAliases; // see getFormats
+    int32_t             formatAliasesCapacity;
+    UProperty           idStart;
+    UProperty           idContinue;
+
+    MessageFormat(); // default constructor not implemented
+
+    /*
+     * A structure representing one subformat of this MessageFormat.
+     * Each subformat has a Format object, an offset into the plain
+     * pattern text fPattern, and an argument number.  The argument
+     * number corresponds to the array of arguments to be formatted.
+     * @internal
+     */
+    class Subformat;
+
+    /**
+     * A MessageFormat contains an array of subformats.  This array
+     * needs to grow dynamically if the MessageFormat is modified.
+     */
+    Subformat* subformats;
+    int32_t    subformatCount;
+    int32_t    subformatCapacity;
+
+    /**
+     * A MessageFormat formats an array of arguments.  Each argument
+     * has an expected type, based on the pattern.  For example, if
+     * the pattern contains the subformat "{3,number,integer}", then
+     * we expect argument 3 to have type Formattable::kLong.  This
+     * array needs to grow dynamically if the MessageFormat is
+     * modified.
+     */
+    Formattable::Type* argTypes;
+    int32_t            argTypeCount;
+    int32_t            argTypeCapacity;
+
+    /**
+      * Is true iff all argument names are non-negative numbers.
+      * 
+      */
+    UBool isArgNumeric;
+
+    // Variable-size array management
+    UBool allocateSubformats(int32_t capacity);
+    UBool allocateArgTypes(int32_t capacity);
+
+    /**
+     * Default Format objects used when no format is specified and a
+     * numeric or date argument is formatted.  These are volatile
+     * cache objects maintained only for performance.  They do not
+     * participate in operator=(), copy constructor(), nor
+     * operator==().
+     */
+    NumberFormat* defaultNumberFormat;
+    DateFormat*   defaultDateFormat;
+
+    /**
+     * Method to retrieve default formats (or NULL on failure).
+     * These are semantically const, but may modify *this.
+     */
+    const NumberFormat* getDefaultNumberFormat(UErrorCode&) const;
+    const DateFormat*   getDefaultDateFormat(UErrorCode&) const;
+
+    /**
+     * Finds the word s, in the keyword list and returns the located index.
+     * @param s the keyword to be searched for.
+     * @param list the list of keywords to be searched with.
+     * @return the index of the list which matches the keyword s.
+     */
+    static int32_t findKeyword( const UnicodeString& s,
+                                const UChar * const *list);
+
+    /**
+     * Formats the array of arguments and copies the result into the
+     * result buffer, updates the field position.
+     *
+     * @param arguments The formattable objects array.
+     * @param cnt       The array count.
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     * @param status    Field position status.
+     * @param recursionProtection
+     *                  Initially zero. Bits 0..9 are used to indicate
+     *                  that a parameter has already been seen, to
+     *                  avoid recursion.  Currently unused.
+     * @param success   The error code status.
+     * @return          Reference to 'appendTo' parameter.
+     */
+    UnicodeString&  format( const Formattable* arguments,
+                            int32_t cnt,
+                            UnicodeString& appendTo,
+                            FieldPosition& status,
+                            int32_t recursionProtection,
+                            UErrorCode& success) const;
+    
+    UnicodeString&  format( const Formattable* arguments, 
+                            const UnicodeString *argumentNames,
+                            int32_t cnt,
+                            UnicodeString& appendTo,
+                            FieldPosition& status,
+                            int32_t recursionProtection,
+                            UErrorCode& success) const;
+
+    void             makeFormat(int32_t offsetNumber,
+                                UnicodeString* segments,
+                                UParseError& parseError,
+                                UErrorCode& success);
+
+    /**
+     * Convenience method that ought to be in NumberFormat
+     */
+    NumberFormat* createIntegerFormat(const Locale& locale, UErrorCode& status) const;
+
+    /**
+     * Checks the range of the source text to quote the special
+     * characters, { and ' and copy to target buffer.
+     * @param source
+     * @param start the text offset to start the process of in the source string
+     * @param end the text offset to end the process of in the source string
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     */
+    static void copyAndFixQuotes(const UnicodeString& appendTo, int32_t start, int32_t end, UnicodeString& target);
+
+    /**
+     * Returns array of argument types in the parsed pattern 
+     * for use in C API.  Only for the use of umsg_vformat().  Not
+     * for public consumption.
+     * @param listCount  Output parameter to receive the size of array
+     * @return           The array of formattable types in the pattern
+     * @internal
+     */
+    const Formattable::Type* getArgTypeList(int32_t& listCount) const {
+        listCount = argTypeCount;
+        return argTypes; 
+    }
+    
+    /**
+     * Returns FALSE if the argument name is not legal.
+     * @param  argName   argument name.
+     * @return TRUE if the argument name is legal, otherwise return FALSE.
+     */
+    UBool isLegalArgName(const UnicodeString& argName) const;
+    
+    friend class MessageFormatAdapter; // getFormatTypeList() access
+};
+
+inline UnicodeString&
+MessageFormat::format(const Formattable& obj,
+                      UnicodeString& appendTo,
+                      UErrorCode& status) const {
+    return Format::format(obj, appendTo, status);
+}
+U_NAMESPACE_END
+
+#endif /* #if !UCONFIG_NO_FORMATTING */
+
+#endif // _MSGFMT
+//eof
+

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/normlzr.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/normlzr.h b/src/apps/couch_collate/platform/osx/icu/unicode/normlzr.h
new file mode 100644
index 0000000..7974f1a
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/normlzr.h
@@ -0,0 +1,823 @@
+/*
+ ********************************************************************
+ * COPYRIGHT:
+ * Copyright (c) 1996-2006, International Business Machines Corporation and
+ * others. All Rights Reserved.
+ ********************************************************************
+ */
+
+#ifndef NORMLZR_H
+#define NORMLZR_H
+
+#include "unicode/utypes.h"
+
+/**
+ * \file 
+ * \brief C++ API: Unicode Normalization
+ */
+ 
+#if !UCONFIG_NO_NORMALIZATION
+
+#include "unicode/uobject.h"
+#include "unicode/unistr.h"
+#include "unicode/chariter.h"
+#include "unicode/unorm.h"
+
+
+struct UCharIterator;
+typedef struct UCharIterator UCharIterator; /**< C typedef for struct UCharIterator. @stable ICU 2.1 */
+
+U_NAMESPACE_BEGIN
+/**
+ * The Normalizer class supports the standard normalization forms described in
+ * <a href="http://www.unicode.org/unicode/reports/tr15/" target="unicode">
+ * Unicode Standard Annex #15: Unicode Normalization Forms</a>.
+ *
+ * The Normalizer class consists of two parts:
+ * - static functions that normalize strings or test if strings are normalized
+ * - a Normalizer object is an iterator that takes any kind of text and
+ *   provides iteration over its normalized form
+ *
+ * The Normalizer class is not suitable for subclassing.
+ *
+ * The static functions are basically wrappers around the C implementation,
+ * using UnicodeString instead of UChar*.
+ * For basic information about normalization forms and details about the C API
+ * please see the documentation in unorm.h.
+ *
+ * The iterator API with the Normalizer constructors and the non-static functions
+ * uses a CharacterIterator as input. It is possible to pass a string which
+ * is then internally wrapped in a CharacterIterator.
+ * The input text is not normalized all at once, but incrementally where needed
+ * (providing efficient random access).
+ * This allows to pass in a large text but spend only a small amount of time
+ * normalizing a small part of that text.
+ * However, if the entire text is normalized, then the iterator will be
+ * slower than normalizing the entire text at once and iterating over the result.
+ * A possible use of the Normalizer iterator is also to report an index into the
+ * original text that is close to where the normalized characters come from.
+ *
+ * <em>Important:</em> The iterator API was cleaned up significantly for ICU 2.0.
+ * The earlier implementation reported the getIndex() inconsistently,
+ * and previous() could not be used after setIndex(), next(), first(), and current().
+ *
+ * Normalizer allows to start normalizing from anywhere in the input text by
+ * calling setIndexOnly(), first(), or last().
+ * Without calling any of these, the iterator will start at the beginning of the text.
+ *
+ * At any time, next() returns the next normalized code point (UChar32),
+ * with post-increment semantics (like CharacterIterator::next32PostInc()).
+ * previous() returns the previous normalized code point (UChar32),
+ * with pre-decrement semantics (like CharacterIterator::previous32()).
+ *
+ * current() returns the current code point
+ * (respectively the one at the newly set index) without moving
+ * the getIndex(). Note that if the text at the current position
+ * needs to be normalized, then these functions will do that.
+ * (This is why current() is not const.)
+ * It is more efficient to call setIndexOnly() instead, which does not
+ * normalize.
+ *
+ * getIndex() always refers to the position in the input text where the normalized
+ * code points are returned from. It does not always change with each returned
+ * code point.
+ * The code point that is returned from any of the functions
+ * corresponds to text at or after getIndex(), according to the
+ * function's iteration semantics (post-increment or pre-decrement).
+ *
+ * next() returns a code point from at or after the getIndex()
+ * from before the next() call. After the next() call, the getIndex()
+ * might have moved to where the next code point will be returned from
+ * (from a next() or current() call).
+ * This is semantically equivalent to array access with array[index++]
+ * (post-increment semantics).
+ *
+ * previous() returns a code point from at or after the getIndex()
+ * from after the previous() call.
+ * This is semantically equivalent to array access with array[--index]
+ * (pre-decrement semantics).
+ *
+ * Internally, the Normalizer iterator normalizes a small piece of text
+ * starting at the getIndex() and ending at a following "safe" index.
+ * The normalized results is stored in an internal string buffer, and
+ * the code points are iterated from there.
+ * With multiple iteration calls, this is repeated until the next piece
+ * of text needs to be normalized, and the getIndex() needs to be moved.
+ *
+ * The following "safe" index, the internal buffer, and the secondary
+ * iteration index into that buffer are not exposed on the API.
+ * This also means that it is currently not practical to return to
+ * a particular, arbitrary position in the text because one would need to
+ * know, and be able to set, in addition to the getIndex(), at least also the
+ * current index into the internal buffer.
+ * It is currently only possible to observe when getIndex() changes
+ * (with careful consideration of the iteration semantics),
+ * at which time the internal index will be 0.
+ * For example, if getIndex() is different after next() than before it,
+ * then the internal index is 0 and one can return to this getIndex()
+ * later with setIndexOnly().
+ *
+ * @author Laura Werner, Mark Davis, Markus Scherer
+ * @stable ICU 2.0
+ */
+class U_COMMON_API Normalizer : public UObject {
+public:
+  /**
+   * If DONE is returned from an iteration function that returns a code point,
+   * then there are no more normalization results available.
+   * @stable ICU 2.0
+   */
+  enum {
+      DONE=0xffff
+  };
+
+  // Constructors
+
+  /**
+   * Creates a new <code>Normalizer</code> object for iterating over the
+   * normalized form of a given string.
+   * <p>
+   * @param str   The string to be normalized.  The normalization
+   *              will start at the beginning of the string.
+   *
+   * @param mode  The normalization mode.
+   * @stable ICU 2.0
+   */
+  Normalizer(const UnicodeString& str, UNormalizationMode mode);
+
+  /**
+   * Creates a new <code>Normalizer</code> object for iterating over the
+   * normalized form of a given string.
+   * <p>
+   * @param str   The string to be normalized.  The normalization
+   *              will start at the beginning of the string.
+   *
+   * @param length Length of the string, or -1 if NUL-terminated.
+   * @param mode  The normalization mode.
+   * @stable ICU 2.0
+   */
+  Normalizer(const UChar* str, int32_t length, UNormalizationMode mode);
+
+  /**
+   * Creates a new <code>Normalizer</code> object for iterating over the
+   * normalized form of the given text.
+   * <p>
+   * @param iter  The input text to be normalized.  The normalization
+   *              will start at the beginning of the string.
+   *
+   * @param mode  The normalization mode.
+   * @stable ICU 2.0
+   */
+  Normalizer(const CharacterIterator& iter, UNormalizationMode mode);
+
+  /**
+   * Copy constructor.
+   * @param copy The object to be copied.
+   * @stable ICU 2.0
+   */
+  Normalizer(const Normalizer& copy);
+
+  /**
+   * Destructor
+   * @stable ICU 2.0
+   */
+  virtual ~Normalizer();
+
+
+  //-------------------------------------------------------------------------
+  // Static utility methods
+  //-------------------------------------------------------------------------
+
+  /**
+   * Normalizes a <code>UnicodeString</code> according to the specified normalization mode.
+   * This is a wrapper for unorm_normalize(), using UnicodeString's.
+   *
+   * The <code>options</code> parameter specifies which optional
+   * <code>Normalizer</code> features are to be enabled for this operation.
+   *
+   * @param source    the input string to be normalized.
+   * @param mode      the normalization mode
+   * @param options   the optional features to be enabled (0 for no options)
+   * @param result    The normalized string (on output).
+   * @param status    The error code.
+   * @stable ICU 2.0
+   */
+  static void U_EXPORT2 normalize(const UnicodeString& source,
+                        UNormalizationMode mode, int32_t options,
+                        UnicodeString& result,
+                        UErrorCode &status);
+
+  /**
+   * Compose a <code>UnicodeString</code>.
+   * This is equivalent to normalize() with mode UNORM_NFC or UNORM_NFKC.
+   * This is a wrapper for unorm_normalize(), using UnicodeString's.
+   *
+   * The <code>options</code> parameter specifies which optional
+   * <code>Normalizer</code> features are to be enabled for this operation.
+   *
+   * @param source    the string to be composed.
+   * @param compat    Perform compatibility decomposition before composition.
+   *                  If this argument is <code>FALSE</code>, only canonical
+   *                  decomposition will be performed.
+   * @param options   the optional features to be enabled (0 for no options)
+   * @param result    The composed string (on output).
+   * @param status    The error code.
+   * @stable ICU 2.0
+   */
+  static void U_EXPORT2 compose(const UnicodeString& source,
+                      UBool compat, int32_t options,
+                      UnicodeString& result,
+                      UErrorCode &status);
+
+  /**
+   * Static method to decompose a <code>UnicodeString</code>.
+   * This is equivalent to normalize() with mode UNORM_NFD or UNORM_NFKD.
+   * This is a wrapper for unorm_normalize(), using UnicodeString's.
+   *
+   * The <code>options</code> parameter specifies which optional
+   * <code>Normalizer</code> features are to be enabled for this operation.
+   *
+   * @param source    the string to be decomposed.
+   * @param compat    Perform compatibility decomposition.
+   *                  If this argument is <code>FALSE</code>, only canonical
+   *                  decomposition will be performed.
+   * @param options   the optional features to be enabled (0 for no options)
+   * @param result    The decomposed string (on output).
+   * @param status    The error code.
+   * @stable ICU 2.0
+   */
+  static void U_EXPORT2 decompose(const UnicodeString& source,
+                        UBool compat, int32_t options,
+                        UnicodeString& result,
+                        UErrorCode &status);
+
+  /**
+   * Performing quick check on a string, to quickly determine if the string is
+   * in a particular normalization format.
+   * This is a wrapper for unorm_quickCheck(), using a UnicodeString.
+   *
+   * Three types of result can be returned UNORM_YES, UNORM_NO or
+   * UNORM_MAYBE. Result UNORM_YES indicates that the argument
+   * string is in the desired normalized format, UNORM_NO determines that
+   * argument string is not in the desired normalized format. A
+   * UNORM_MAYBE result indicates that a more thorough check is required,
+   * the user may have to put the string in its normalized form and compare the
+   * results.
+   * @param source       string for determining if it is in a normalized format
+   * @param mode         normalization format
+   * @param status A reference to a UErrorCode to receive any errors
+   * @return UNORM_YES, UNORM_NO or UNORM_MAYBE
+   *
+   * @see isNormalized
+   * @stable ICU 2.0
+   */
+  static inline UNormalizationCheckResult
+  quickCheck(const UnicodeString &source, UNormalizationMode mode, UErrorCode &status);
+
+  /**
+   * Performing quick check on a string; same as the other version of quickCheck
+   * but takes an extra options parameter like most normalization functions.
+   *
+   * @param source       string for determining if it is in a normalized format
+   * @param mode         normalization format
+   * @param options      the optional features to be enabled (0 for no options)
+   * @param status A reference to a UErrorCode to receive any errors
+   * @return UNORM_YES, UNORM_NO or UNORM_MAYBE
+   *
+   * @see isNormalized
+   * @stable ICU 2.6
+   */
+  static inline UNormalizationCheckResult
+  quickCheck(const UnicodeString &source, UNormalizationMode mode, int32_t options, UErrorCode &status);
+
+  /**
+   * Test if a string is in a given normalization form.
+   * This is semantically equivalent to source.equals(normalize(source, mode)) .
+   *
+   * Unlike unorm_quickCheck(), this function returns a definitive result,
+   * never a "maybe".
+   * For NFD, NFKD, and FCD, both functions work exactly the same.
+   * For NFC and NFKC where quickCheck may return "maybe", this function will
+   * perform further tests to arrive at a TRUE/FALSE result.
+   *
+   * @param src        String that is to be tested if it is in a normalization format.
+   * @param mode       Which normalization form to test for.
+   * @param errorCode  ICU error code in/out parameter.
+   *                   Must fulfill U_SUCCESS before the function call.
+   * @return Boolean value indicating whether the source string is in the
+   *         "mode" normalization form.
+   *
+   * @see quickCheck
+   * @stable ICU 2.2
+   */
+  static inline UBool
+  isNormalized(const UnicodeString &src, UNormalizationMode mode, UErrorCode &errorCode);
+
+  /**
+   * Test if a string is in a given normalization form; same as the other version of isNormalized
+   * but takes an extra options parameter like most normalization functions.
+   *
+   * @param src        String that is to be tested if it is in a normalization format.
+   * @param mode       Which normalization form to test for.
+   * @param options      the optional features to be enabled (0 for no options)
+   * @param errorCode  ICU error code in/out parameter.
+   *                   Must fulfill U_SUCCESS before the function call.
+   * @return Boolean value indicating whether the source string is in the
+   *         "mode" normalization form.
+   *
+   * @see quickCheck
+   * @stable ICU 2.6
+   */
+  static inline UBool
+  isNormalized(const UnicodeString &src, UNormalizationMode mode, int32_t options, UErrorCode &errorCode);
+
+  /**
+   * Concatenate normalized strings, making sure that the result is normalized as well.
+   *
+   * If both the left and the right strings are in
+   * the normalization form according to "mode/options",
+   * then the result will be
+   *
+   * \code
+   *     dest=normalize(left+right, mode, options)
+   * \endcode
+   *
+   * For details see unorm_concatenate in unorm.h.
+   *
+   * @param left Left source string.
+   * @param right Right source string.
+   * @param result The output string.
+   * @param mode The normalization mode.
+   * @param options A bit set of normalization options.
+   * @param errorCode ICU error code in/out parameter.
+   *                   Must fulfill U_SUCCESS before the function call.
+   * @return result
+   *
+   * @see unorm_concatenate
+   * @see normalize
+   * @see unorm_next
+   * @see unorm_previous
+   *
+   * @stable ICU 2.1
+   */
+  static UnicodeString &
+  U_EXPORT2 concatenate(UnicodeString &left, UnicodeString &right,
+              UnicodeString &result,
+              UNormalizationMode mode, int32_t options,
+              UErrorCode &errorCode);
+
+  /**
+   * Compare two strings for canonical equivalence.
+   * Further options include case-insensitive comparison and
+   * code point order (as opposed to code unit order).
+   *
+   * Canonical equivalence between two strings is defined as their normalized
+   * forms (NFD or NFC) being identical.
+   * This function compares strings incrementally instead of normalizing
+   * (and optionally case-folding) both strings entirely,
+   * improving performance significantly.
+   *
+   * Bulk normalization is only necessary if the strings do not fulfill the FCD
+   * conditions. Only in this case, and only if the strings are relatively long,
+   * is memory allocated temporarily.
+   * For FCD strings and short non-FCD strings there is no memory allocation.
+   *
+   * Semantically, this is equivalent to
+   *   strcmp[CodePointOrder](NFD(foldCase(s1)), NFD(foldCase(s2)))
+   * where code point order and foldCase are all optional.
+   *
+   * UAX 21 2.5 Caseless Matching specifies that for a canonical caseless match
+   * the case folding must be performed first, then the normalization.
+   *
+   * @param s1 First source string.
+   * @param s2 Second source string.
+   *
+   * @param options A bit set of options:
+   *   - U_FOLD_CASE_DEFAULT or 0 is used for default options:
+   *     Case-sensitive comparison in code unit order, and the input strings
+   *     are quick-checked for FCD.
+   *
+   *   - UNORM_INPUT_IS_FCD
+   *     Set if the caller knows that both s1 and s2 fulfill the FCD conditions.
+   *     If not set, the function will quickCheck for FCD
+   *     and normalize if necessary.
+   *
+   *   - U_COMPARE_CODE_POINT_ORDER
+   *     Set to choose code point order instead of code unit order
+   *     (see u_strCompare for details).
+   *
+   *   - U_COMPARE_IGNORE_CASE
+   *     Set to compare strings case-insensitively using case folding,
+   *     instead of case-sensitively.
+   *     If set, then the following case folding options are used.
+   *
+   *   - Options as used with case-insensitive comparisons, currently:
+   *
+   *   - U_FOLD_CASE_EXCLUDE_SPECIAL_I
+   *    (see u_strCaseCompare for details)
+   *
+   *   - regular normalization options shifted left by UNORM_COMPARE_NORM_OPTIONS_SHIFT
+   *
+   * @param errorCode ICU error code in/out parameter.
+   *                  Must fulfill U_SUCCESS before the function call.
+   * @return <0 or 0 or >0 as usual for string comparisons
+   *
+   * @see unorm_compare
+   * @see normalize
+   * @see UNORM_FCD
+   * @see u_strCompare
+   * @see u_strCaseCompare
+   *
+   * @stable ICU 2.2
+   */
+  static inline int32_t
+  compare(const UnicodeString &s1, const UnicodeString &s2,
+          uint32_t options,
+          UErrorCode &errorCode);
+
+  //-------------------------------------------------------------------------
+  // Iteration API
+  //-------------------------------------------------------------------------
+
+  /**
+   * Return the current character in the normalized text.
+   * current() may need to normalize some text at getIndex().
+   * The getIndex() is not changed.
+   *
+   * @return the current normalized code point
+   * @stable ICU 2.0
+   */
+  UChar32              current(void);
+
+  /**
+   * Return the first character in the normalized text.
+   * This is equivalent to setIndexOnly(startIndex()) followed by next().
+   * (Post-increment semantics.)
+   *
+   * @return the first normalized code point
+   * @stable ICU 2.0
+   */
+  UChar32              first(void);
+
+  /**
+   * Return the last character in the normalized text.
+   * This is equivalent to setIndexOnly(endIndex()) followed by previous().
+   * (Pre-decrement semantics.)
+   *
+   * @return the last normalized code point
+   * @stable ICU 2.0
+   */
+  UChar32              last(void);
+
+  /**
+   * Return the next character in the normalized text.
+   * (Post-increment semantics.)
+   * If the end of the text has already been reached, DONE is returned.
+   * The DONE value could be confused with a U+FFFF non-character code point
+   * in the text. If this is possible, you can test getIndex()<endIndex()
+   * before calling next(), or (getIndex()<endIndex() || last()!=DONE)
+   * after calling next(). (Calling last() will change the iterator state!)
+   *
+   * The C API unorm_next() is more efficient and does not have this ambiguity.
+   *
+   * @return the next normalized code point
+   * @stable ICU 2.0
+   */
+  UChar32              next(void);
+
+  /**
+   * Return the previous character in the normalized text and decrement.
+   * (Pre-decrement semantics.)
+   * If the beginning of the text has already been reached, DONE is returned.
+   * The DONE value could be confused with a U+FFFF non-character code point
+   * in the text. If this is possible, you can test
+   * (getIndex()>startIndex() || first()!=DONE). (Calling first() will change
+   * the iterator state!)
+   *
+   * The C API unorm_previous() is more efficient and does not have this ambiguity.
+   *
+   * @return the previous normalized code point
+   * @stable ICU 2.0
+   */
+  UChar32              previous(void);
+
+  /**
+   * Set the iteration position in the input text that is being normalized,
+   * without any immediate normalization.
+   * After setIndexOnly(), getIndex() will return the same index that is
+   * specified here.
+   *
+   * @param index the desired index in the input text.
+   * @stable ICU 2.0
+   */
+  void                 setIndexOnly(int32_t index);
+
+  /**
+   * Reset the index to the beginning of the text.
+   * This is equivalent to setIndexOnly(startIndex)).
+   * @stable ICU 2.0
+   */
+  void                reset(void);
+
+  /**
+   * Retrieve the current iteration position in the input text that is
+   * being normalized.
+   *
+   * A following call to next() will return a normalized code point from
+   * the input text at or after this index.
+   *
+   * After a call to previous(), getIndex() will point at or before the
+   * position in the input text where the normalized code point
+   * was returned from with previous().
+   *
+   * @return the current index in the input text
+   * @stable ICU 2.0
+   */
+  int32_t            getIndex(void) const;
+
+  /**
+   * Retrieve the index of the start of the input text. This is the begin index
+   * of the <code>CharacterIterator</code> or the start (i.e. index 0) of the string
+   * over which this <code>Normalizer</code> is iterating.
+   *
+   * @return the smallest index in the input text where the Normalizer operates
+   * @stable ICU 2.0
+   */
+  int32_t            startIndex(void) const;
+
+  /**
+   * Retrieve the index of the end of the input text. This is the end index
+   * of the <code>CharacterIterator</code> or the length of the string
+   * over which this <code>Normalizer</code> is iterating.
+   * This end index is exclusive, i.e., the Normalizer operates only on characters
+   * before this index.
+   *
+   * @return the first index in the input text where the Normalizer does not operate
+   * @stable ICU 2.0
+   */
+  int32_t            endIndex(void) const;
+
+  /**
+   * Returns TRUE when both iterators refer to the same character in the same
+   * input text.
+   *
+   * @param that a Normalizer object to compare this one to
+   * @return comparison result
+   * @stable ICU 2.0
+   */
+  UBool        operator==(const Normalizer& that) const;
+
+  /**
+   * Returns FALSE when both iterators refer to the same character in the same
+   * input text.
+   *
+   * @param that a Normalizer object to compare this one to
+   * @return comparison result
+   * @stable ICU 2.0
+   */
+  inline UBool        operator!=(const Normalizer& that) const;
+
+  /**
+   * Returns a pointer to a new Normalizer that is a clone of this one.
+   * The caller is responsible for deleting the new clone.
+   * @return a pointer to a new Normalizer
+   * @stable ICU 2.0
+   */
+  Normalizer*        clone(void) const;
+
+  /**
+   * Generates a hash code for this iterator.
+   *
+   * @return the hash code
+   * @stable ICU 2.0
+   */
+  int32_t                hashCode(void) const;
+
+  //-------------------------------------------------------------------------
+  // Property access methods
+  //-------------------------------------------------------------------------
+
+  /**
+   * Set the normalization mode for this object.
+   * <p>
+   * <b>Note:</b>If the normalization mode is changed while iterating
+   * over a string, calls to {@link #next() } and {@link #previous() } may
+   * return previously buffers characters in the old normalization mode
+   * until the iteration is able to re-sync at the next base character.
+   * It is safest to call {@link #setIndexOnly }, {@link #reset() },
+   * {@link #setText }, {@link #first() },
+   * {@link #last() }, etc. after calling <code>setMode</code>.
+   * <p>
+   * @param newMode the new mode for this <code>Normalizer</code>.
+   * @see #getUMode
+   * @stable ICU 2.0
+   */
+  void setMode(UNormalizationMode newMode);
+
+  /**
+   * Return the normalization mode for this object.
+   *
+   * This is an unusual name because there used to be a getMode() that
+   * returned a different type.
+   *
+   * @return the mode for this <code>Normalizer</code>
+   * @see #setMode
+   * @stable ICU 2.0
+   */
+  UNormalizationMode getUMode(void) const;
+
+  /**
+   * Set options that affect this <code>Normalizer</code>'s operation.
+   * Options do not change the basic composition or decomposition operation
+   * that is being performed, but they control whether
+   * certain optional portions of the operation are done.
+   * Currently the only available option is obsolete.
+   *
+   * It is possible to specify multiple options that are all turned on or off.
+   *
+   * @param   option  the option(s) whose value is/are to be set.
+   * @param   value   the new setting for the option.  Use <code>TRUE</code> to
+   *                  turn the option(s) on and <code>FALSE</code> to turn it/them off.
+   *
+   * @see #getOption
+   * @stable ICU 2.0
+   */
+  void setOption(int32_t option,
+         UBool value);
+
+  /**
+   * Determine whether an option is turned on or off.
+   * If multiple options are specified, then the result is TRUE if any
+   * of them are set.
+   * <p>
+   * @param option the option(s) that are to be checked
+   * @return TRUE if any of the option(s) are set
+   * @see #setOption
+   * @stable ICU 2.0
+   */
+  UBool getOption(int32_t option) const;
+
+  /**
+   * Set the input text over which this <code>Normalizer</code> will iterate.
+   * The iteration position is set to the beginning.
+   *
+   * @param newText a string that replaces the current input text
+   * @param status a UErrorCode
+   * @stable ICU 2.0
+   */
+  void setText(const UnicodeString& newText,
+           UErrorCode &status);
+
+  /**
+   * Set the input text over which this <code>Normalizer</code> will iterate.
+   * The iteration position is set to the beginning.
+   *
+   * @param newText a CharacterIterator object that replaces the current input text
+   * @param status a UErrorCode
+   * @stable ICU 2.0
+   */
+  void setText(const CharacterIterator& newText,
+           UErrorCode &status);
+
+  /**
+   * Set the input text over which this <code>Normalizer</code> will iterate.
+   * The iteration position is set to the beginning.
+   *
+   * @param newText a string that replaces the current input text
+   * @param length the length of the string, or -1 if NUL-terminated
+   * @param status a UErrorCode
+   * @stable ICU 2.0
+   */
+  void setText(const UChar* newText,
+                    int32_t length,
+            UErrorCode &status);
+  /**
+   * Copies the input text into the UnicodeString argument.
+   *
+   * @param result Receives a copy of the text under iteration.
+   * @stable ICU 2.0
+   */
+  void            getText(UnicodeString&  result);
+
+  /**
+   * ICU "poor man's RTTI", returns a UClassID for this class.
+   * @returns a UClassID for this class.
+   * @stable ICU 2.2
+   */
+  static UClassID U_EXPORT2 getStaticClassID();
+
+  /**
+   * ICU "poor man's RTTI", returns a UClassID for the actual class.
+   * @return a UClassID for the actual class.
+   * @stable ICU 2.2
+   */
+  virtual UClassID getDynamicClassID() const;
+
+private:
+  //-------------------------------------------------------------------------
+  // Private functions
+  //-------------------------------------------------------------------------
+
+  Normalizer(); // default constructor not implemented
+  Normalizer &operator=(const Normalizer &that); // assignment operator not implemented
+
+  // Private utility methods for iteration
+  // For documentation, see the source code
+  UBool nextNormalize();
+  UBool previousNormalize();
+
+  void    init(CharacterIterator *iter);
+  void    clearBuffer(void);
+
+  //-------------------------------------------------------------------------
+  // Private data
+  //-------------------------------------------------------------------------
+
+  UNormalizationMode  fUMode;
+  int32_t             fOptions;
+
+  // The input text and our position in it
+  UCharIterator       *text;
+
+  // The normalization buffer is the result of normalization
+  // of the source in [currentIndex..nextIndex[ .
+  int32_t         currentIndex, nextIndex;
+
+  // A buffer for holding intermediate results
+  UnicodeString       buffer;
+  int32_t         bufferPos;
+
+};
+
+//-------------------------------------------------------------------------
+// Inline implementations
+//-------------------------------------------------------------------------
+
+inline UBool
+Normalizer::operator!= (const Normalizer& other) const
+{ return ! operator==(other); }
+
+inline UNormalizationCheckResult
+Normalizer::quickCheck(const UnicodeString& source,
+                       UNormalizationMode mode,
+                       UErrorCode &status) {
+    if(U_FAILURE(status)) {
+        return UNORM_MAYBE;
+    }
+
+    return unorm_quickCheck(source.getBuffer(), source.length(),
+                            mode, &status);
+}
+
+inline UNormalizationCheckResult
+Normalizer::quickCheck(const UnicodeString& source,
+                       UNormalizationMode mode, int32_t options,
+                       UErrorCode &status) {
+    if(U_FAILURE(status)) {
+        return UNORM_MAYBE;
+    }
+
+    return unorm_quickCheckWithOptions(source.getBuffer(), source.length(),
+                                       mode, options, &status);
+}
+
+inline UBool
+Normalizer::isNormalized(const UnicodeString& source,
+                         UNormalizationMode mode,
+                         UErrorCode &status) {
+    if(U_FAILURE(status)) {
+        return FALSE;
+    }
+
+    return unorm_isNormalized(source.getBuffer(), source.length(),
+                              mode, &status);
+}
+
+inline UBool
+Normalizer::isNormalized(const UnicodeString& source,
+                         UNormalizationMode mode, int32_t options,
+                         UErrorCode &status) {
+    if(U_FAILURE(status)) {
+        return FALSE;
+    }
+
+    return unorm_isNormalizedWithOptions(source.getBuffer(), source.length(),
+                                         mode, options, &status);
+}
+
+inline int32_t
+Normalizer::compare(const UnicodeString &s1, const UnicodeString &s2,
+                    uint32_t options,
+                    UErrorCode &errorCode) {
+  // all argument checking is done in unorm_compare
+  return unorm_compare(s1.getBuffer(), s1.length(),
+                       s2.getBuffer(), s2.length(),
+                       options,
+                       &errorCode);
+}
+
+U_NAMESPACE_END
+
+#endif /* #if !UCONFIG_NO_NORMALIZATION */
+
+#endif // NORMLZR_H


[74/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/tzrule.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/tzrule.h b/src/apps/couch_collate/platform/osx/icu/unicode/tzrule.h
new file mode 100644
index 0000000..95ad1d0
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/tzrule.h
@@ -0,0 +1,828 @@
+/*
+*******************************************************************************
+* Copyright (C) 2007-2008, International Business Machines Corporation and    *
+* others. All Rights Reserved.                                                *
+*******************************************************************************
+*/
+#ifndef TZRULE_H
+#define TZRULE_H
+
+/**
+ * \file 
+ * \brief C++ API: Time zone rule classes
+ */
+
+#include "unicode/utypes.h"
+
+#if !UCONFIG_NO_FORMATTING
+
+#include "unicode/uobject.h"
+#include "unicode/unistr.h"
+#include "unicode/dtrule.h"
+
+U_NAMESPACE_BEGIN
+
+/**
+ * <code>TimeZoneRule</code> is a class representing a rule for time zone.
+ * <code>TimeZoneRule</code> has a set of time zone attributes, such as zone name,
+ * raw offset (UTC offset for standard time) and daylight saving time offset.
+ * 
+ * @stable ICU 4.0
+ */
+class U_I18N_API TimeZoneRule : public UObject {
+public:
+    /**
+     * Destructor.
+     * @stable ICU 4.0
+     */
+    virtual ~TimeZoneRule();
+
+    /**
+     * Clone this TimeZoneRule object polymorphically. The caller owns the result and
+     * should delete it when done.
+     * @return  A copy of the object.
+     * @stable ICU 4.0
+     */
+    virtual TimeZoneRule* clone(void) const = 0;
+
+    /**
+     * Return true if the given <code>TimeZoneRule</code> objects are semantically equal. Objects
+     * of different subclasses are considered unequal.
+     * @param that  The object to be compared with.
+     * @return  true if the given <code>TimeZoneRule</code> objects are semantically equal.
+     * @stable ICU 4.0
+     */
+    virtual UBool operator==(const TimeZoneRule& that) const;
+
+    /**
+     * Return true if the given <code>TimeZoneRule</code> objects are semantically unequal. Objects
+     * of different subclasses are considered unequal.
+     * @param that  The object to be compared with.
+     * @return  true if the given <code>TimeZoneRule</code> objects are semantically unequal.
+     * @stable ICU 4.0
+     */
+    virtual UBool operator!=(const TimeZoneRule& that) const;
+
+    /**
+     * Fills in "name" with the name of this time zone.
+     * @param name  Receives the name of this time zone.
+     * @return  A reference to "name"
+     * @stable ICU 4.0
+     */
+    UnicodeString& getName(UnicodeString& name) const;
+
+    /**
+     * Gets the standard time offset.
+     * @return  The standard time offset from UTC in milliseconds.
+     * @stable ICU 4.0
+     */
+    int32_t getRawOffset(void) const;
+
+    /**
+     * Gets the amount of daylight saving delta time from the standard time.
+     * @return  The amount of daylight saving offset used by this rule
+     *          in milliseconds.
+     * @stable ICU 4.0
+     */
+    int32_t getDSTSavings(void) const;
+
+    /**
+     * Returns if this rule represents the same rule and offsets as another.
+     * When two <code>TimeZoneRule</code> objects differ only its names, this method
+     * returns true.
+     * @param other The <code>TimeZoneRule</code> object to be compared with.
+     * @return  true if the other <code>TimeZoneRule</code> is the same as this one.
+     * @stable ICU 4.0
+     */
+    virtual UBool isEquivalentTo(const TimeZoneRule& other) const;
+
+    /**
+     * Gets the very first time when this rule takes effect.
+     * @param prevRawOffset     The standard time offset from UTC before this rule
+     *                          takes effect in milliseconds.
+     * @param prevDSTSavings    The amount of daylight saving offset from the
+     *                          standard time.
+     * @param result            Receives the very first time when this rule takes effect.
+     * @return  true if the start time is available.  When false is returned, output parameter
+     *          "result" is unchanged.
+     * @stable ICU 4.0
+     */
+    virtual UBool getFirstStart(int32_t prevRawOffset, int32_t prevDSTSavings, UDate& result) const = 0;
+
+    /**
+     * Gets the final time when this rule takes effect.
+     * @param prevRawOffset     The standard time offset from UTC before this rule
+     *                          takes effect in milliseconds.
+     * @param prevDSTSavings    The amount of daylight saving offset from the
+     *                          standard time.
+     * @param result            Receives the final time when this rule takes effect.
+     * @return  true if the start time is available.  When false is returned, output parameter
+     *          "result" is unchanged.
+     * @stable ICU 4.0
+     */
+    virtual UBool getFinalStart(int32_t prevRawOffset, int32_t prevDSTSavings, UDate& result) const = 0;
+
+    /**
+     * Gets the first time when this rule takes effect after the specified time.
+     * @param base              The first start time after this base time will be returned.
+     * @param prevRawOffset     The standard time offset from UTC before this rule
+     *                          takes effect in milliseconds.
+     * @param prevDSTSavings    The amount of daylight saving offset from the
+     *                          standard time.
+     * @param inclusive         Whether the base time is inclusive or not.
+     * @param result            Receives The first time when this rule takes effect after
+     *                          the specified base time.
+     * @return  true if the start time is available.  When false is returned, output parameter
+     *          "result" is unchanged.
+     * @stable ICU 4.0
+     */
+    virtual UBool getNextStart(UDate base, int32_t prevRawOffset, int32_t prevDSTSavings,
+        UBool inclusive, UDate& result) const = 0;
+
+    /**
+     * Gets the most recent time when this rule takes effect before the specified time.
+     * @param base              The most recent time before this base time will be returned.
+     * @param prevRawOffset     The standard time offset from UTC before this rule
+     *                          takes effect in milliseconds.
+     * @param prevDSTSavings    The amount of daylight saving offset from the
+     *                          standard time.
+     * @param inclusive         Whether the base time is inclusive or not.
+     * @param result            Receives The most recent time when this rule takes effect before
+     *                          the specified base time.
+     * @return  true if the start time is available.  When false is returned, output parameter
+     *          "result" is unchanged.
+     * @stable ICU 4.0
+     */
+    virtual UBool getPreviousStart(UDate base, int32_t prevRawOffset, int32_t prevDSTSavings,
+        UBool inclusive, UDate& result) const = 0;
+
+protected:
+
+    /**
+     * Constructs a <code>TimeZoneRule</code> with the name, the GMT offset of its
+     * standard time and the amount of daylight saving offset adjustment.
+     * @param name          The time zone name.
+     * @param rawOffset     The UTC offset of its standard time in milliseconds.
+     * @param dstSavings    The amount of daylight saving offset adjustment in milliseconds.
+     *                      If this ia a rule for standard time, the value of this argument is 0.
+     * @stable ICU 4.0
+     */
+    TimeZoneRule(const UnicodeString& name, int32_t rawOffset, int32_t dstSavings);
+
+    /**
+     * Copy constructor.
+     * @param source    The TimeZoneRule object to be copied.
+     * @stable ICU 4.0
+     */
+    TimeZoneRule(const TimeZoneRule& source);
+
+    /**
+     * Assignment operator.
+     * @param right The object to be copied.
+     * @stable ICU 4.0
+     */
+    TimeZoneRule& operator=(const TimeZoneRule& right);
+
+private:
+    UnicodeString fName; // time name
+    int32_t fRawOffset;  // UTC offset of the standard time in milliseconds
+    int32_t fDSTSavings; // DST saving amount in milliseconds
+};
+
+/**
+ * <code>InitialTimeZoneRule</code> represents a time zone rule
+ * representing a time zone effective from the beginning and
+ * has no actual start times.
+ * @stable ICU 4.0
+ */
+class U_I18N_API InitialTimeZoneRule : public TimeZoneRule {
+public:
+    /**
+     * Constructs an <code>InitialTimeZoneRule</code> with the name, the GMT offset of its
+     * standard time and the amount of daylight saving offset adjustment.
+     * @param name          The time zone name.
+     * @param rawOffset     The UTC offset of its standard time in milliseconds.
+     * @param dstSavings    The amount of daylight saving offset adjustment in milliseconds.
+     *                      If this ia a rule for standard time, the value of this argument is 0.
+     * @stable ICU 4.0
+     */
+    InitialTimeZoneRule(const UnicodeString& name, int32_t rawOffset, int32_t dstSavings);
+
+    /**
+     * Copy constructor.
+     * @param source    The InitialTimeZoneRule object to be copied.
+     * @stable ICU 4.0
+     */
+    InitialTimeZoneRule(const InitialTimeZoneRule& source);
+
+    /**
+     * Destructor.
+     * @stable ICU 4.0
+     */
+    virtual ~InitialTimeZoneRule();
+
+    /**
+     * Clone this InitialTimeZoneRule object polymorphically. The caller owns the result and
+     * should delete it when done.
+     * @return    A copy of the object.
+     * @stable ICU 4.0
+     */
+    virtual InitialTimeZoneRule* clone(void) const;
+
+    /**
+     * Assignment operator.
+     * @param right The object to be copied.
+     * @stable ICU 4.0
+     */
+    InitialTimeZoneRule& operator=(const InitialTimeZoneRule& right);
+
+    /**
+     * Return true if the given <code>TimeZoneRule</code> objects are semantically equal. Objects
+     * of different subclasses are considered unequal.
+     * @param that  The object to be compared with.
+     * @return  true if the given <code>TimeZoneRule</code> objects are semantically equal.
+     * @stable ICU 4.0
+     */
+    virtual UBool operator==(const TimeZoneRule& that) const;
+
+    /**
+     * Return true if the given <code>TimeZoneRule</code> objects are semantically unequal. Objects
+     * of different subclasses are considered unequal.
+     * @param that  The object to be compared with.
+     * @return  true if the given <code>TimeZoneRule</code> objects are semantically unequal.
+     * @stable ICU 4.0
+     */
+    virtual UBool operator!=(const TimeZoneRule& that) const;
+
+    /**
+     * Gets the time when this rule takes effect in the given year.
+     * @param year              The Gregorian year, with 0 == 1 BCE, -1 == 2 BCE, etc.
+     * @param prevRawOffset     The standard time offset from UTC before this rule
+     *                          takes effect in milliseconds.
+     * @param prevDSTSavings    The amount of daylight saving offset from the
+     *                          standard time.
+     * @param result            Receives the start time in the year.
+     * @return  true if this rule takes effect in the year and the result is set to
+     *          "result".
+     * @stable ICU 4.0
+     */
+    UBool getStartInYear(int32_t year, int32_t prevRawOffset, int32_t prevDSTSavings, UDate& result) const;
+
+    /**
+     * Returns if this rule represents the same rule and offsets as another.
+     * When two <code>TimeZoneRule</code> objects differ only its names, this method
+     * returns true.
+     * @param that  The <code>TimeZoneRule</code> object to be compared with.
+     * @return  true if the other <code>TimeZoneRule</code> is equivalent to this one.
+     * @stable ICU 4.0
+     */
+    virtual UBool isEquivalentTo(const TimeZoneRule& that) const;
+
+    /**
+     * Gets the very first time when this rule takes effect.
+     * @param prevRawOffset     The standard time offset from UTC before this rule
+     *                          takes effect in milliseconds.
+     * @param prevDSTSavings    The amount of daylight saving offset from the
+     *                          standard time.
+     * @param result            Receives the very first time when this rule takes effect.
+     * @return  true if the start time is available.  When false is returned, output parameter
+     *          "result" is unchanged.
+     * @stable ICU 4.0
+     */
+    virtual UBool getFirstStart(int32_t prevRawOffset, int32_t prevDSTSavings, UDate& result) const;
+
+    /**
+     * Gets the final time when this rule takes effect.
+     * @param prevRawOffset     The standard time offset from UTC before this rule
+     *                          takes effect in milliseconds.
+     * @param prevDSTSavings    The amount of daylight saving offset from the
+     *                          standard time.
+     * @param result            Receives the final time when this rule takes effect.
+     * @return  true if the start time is available.  When false is returned, output parameter
+     *          "result" is unchanged.
+     * @stable ICU 4.0
+     */
+    virtual UBool getFinalStart(int32_t prevRawOffset, int32_t prevDSTSavings, UDate& result) const;
+
+    /**
+     * Gets the first time when this rule takes effect after the specified time.
+     * @param base              The first start time after this base time will be returned.
+     * @param prevRawOffset     The standard time offset from UTC before this rule
+     *                          takes effect in milliseconds.
+     * @param prevDSTSavings    The amount of daylight saving offset from the
+     *                          standard time.
+     * @param inclusive         Whether the base time is inclusive or not.
+     * @param result            Receives The first time when this rule takes effect after
+     *                          the specified base time.
+     * @return  true if the start time is available.  When false is returned, output parameter
+     *          "result" is unchanged.
+     * @stable ICU 4.0
+     */
+    virtual UBool getNextStart(UDate base, int32_t prevRawOffset, int32_t prevDSTSavings,
+        UBool inclusive, UDate& result) const;
+
+    /**
+     * Gets the most recent time when this rule takes effect before the specified time.
+     * @param base              The most recent time before this base time will be returned.
+     * @param prevRawOffset     The standard time offset from UTC before this rule
+     *                          takes effect in milliseconds.
+     * @param prevDSTSavings    The amount of daylight saving offset from the
+     *                          standard time.
+     * @param inclusive         Whether the base time is inclusive or not.
+     * @param result            Receives The most recent time when this rule takes effect before
+     *                          the specified base time.
+     * @return  true if the start time is available.  When false is returned, output parameter
+     *          "result" is unchanged.
+     * @stable ICU 4.0
+     */
+    virtual UBool getPreviousStart(UDate base, int32_t prevRawOffset, int32_t prevDSTSavings,
+        UBool inclusive, UDate& result) const;
+
+public:
+    /**
+     * Return the class ID for this class. This is useful only for comparing to
+     * a return value from getDynamicClassID(). For example:
+     * <pre>
+     * .   Base* polymorphic_pointer = createPolymorphicObject();
+     * .   if (polymorphic_pointer->getDynamicClassID() ==
+     * .       erived::getStaticClassID()) ...
+     * </pre>
+     * @return          The class ID for all objects of this class.
+     * @stable ICU 4.0
+     */
+    static UClassID U_EXPORT2 getStaticClassID(void);
+
+    /**
+     * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This
+     * method is to implement a simple version of RTTI, since not all C++
+     * compilers support genuine RTTI. Polymorphic operator==() and clone()
+     * methods call this method.
+     *
+     * @return          The class ID for this object. All objects of a
+     *                  given class have the same class ID.  Objects of
+     *                  other classes have different class IDs.
+     * @stable ICU 4.0
+     */
+    virtual UClassID getDynamicClassID(void) const;
+};
+
+/**
+ * <code>AnnualTimeZoneRule</code> is a class used for representing a time zone
+ * rule which takes effect annually.  The calenday system used for the rule is
+ * is based on Gregorian calendar
+ * 
+ * @stable ICU 4.0
+ */
+class U_I18N_API AnnualTimeZoneRule : public TimeZoneRule {
+public:
+    /**
+     * The constant representing the maximum year used for designating
+     * a rule is permanent.
+     */
+    static const int32_t MAX_YEAR;
+
+    /**
+     * Constructs a <code>AnnualTimeZoneRule</code> with the name, the GMT offset of its
+     * standard time, the amount of daylight saving offset adjustment, the annual start
+     * time rule and the start/until years.  The input DateTimeRule is copied by this
+     * constructor, so the caller remains responsible for deleting the object.
+     * @param name          The time zone name.
+     * @param rawOffset     The GMT offset of its standard time in milliseconds.
+     * @param dstSavings    The amount of daylight saving offset adjustment in
+     *                      milliseconds.  If this ia a rule for standard time,
+     *                      the value of this argument is 0.
+     * @param dateTimeRule  The start date/time rule repeated annually.
+     * @param startYear     The first year when this rule takes effect.
+     * @param endYear       The last year when this rule takes effect.  If this
+     *                      rule is effective forever in future, specify MAX_YEAR.
+     * @stable ICU 4.0
+     */
+    AnnualTimeZoneRule(const UnicodeString& name, int32_t rawOffset, int32_t dstSavings,
+            const DateTimeRule& dateTimeRule, int32_t startYear, int32_t endYear);
+
+    /**
+     * Constructs a <code>AnnualTimeZoneRule</code> with the name, the GMT offset of its
+     * standard time, the amount of daylight saving offset adjustment, the annual start
+     * time rule and the start/until years.  The input DateTimeRule object is adopted
+     * by this object, therefore, the caller must not delete the object.
+     * @param name          The time zone name.
+     * @param rawOffset     The GMT offset of its standard time in milliseconds.
+     * @param dstSavings    The amount of daylight saving offset adjustment in
+     *                      milliseconds.  If this ia a rule for standard time,
+     *                      the value of this argument is 0.
+     * @param dateTimeRule  The start date/time rule repeated annually.
+     * @param startYear     The first year when this rule takes effect.
+     * @param endYear       The last year when this rule takes effect.  If this
+     *                      rule is effective forever in future, specify MAX_YEAR.
+     * @stable ICU 4.0
+     */
+    AnnualTimeZoneRule(const UnicodeString& name, int32_t rawOffset, int32_t dstSavings,
+            DateTimeRule* dateTimeRule, int32_t startYear, int32_t endYear);
+
+    /**
+     * Copy constructor.
+     * @param source    The AnnualTimeZoneRule object to be copied.
+     * @stable ICU 4.0
+     */
+    AnnualTimeZoneRule(const AnnualTimeZoneRule& source);
+
+    /**
+     * Destructor.
+     * @stable ICU 4.0
+     */
+    virtual ~AnnualTimeZoneRule();
+
+    /**
+     * Clone this AnnualTimeZoneRule object polymorphically. The caller owns the result and
+     * should delete it when done.
+     * @return    A copy of the object.
+     * @stable ICU 4.0
+     */
+    virtual AnnualTimeZoneRule* clone(void) const;
+
+    /**
+     * Assignment operator.
+     * @param right The object to be copied.
+     * @stable ICU 4.0
+     */
+    AnnualTimeZoneRule& operator=(const AnnualTimeZoneRule& right);
+
+    /**
+     * Return true if the given <code>TimeZoneRule</code> objects are semantically equal. Objects
+     * of different subclasses are considered unequal.
+     * @param that  The object to be compared with.
+     * @return  true if the given <code>TimeZoneRule</code> objects are semantically equal.
+     * @stable ICU 4.0
+     */
+    virtual UBool operator==(const TimeZoneRule& that) const;
+
+    /**
+     * Return true if the given <code>TimeZoneRule</code> objects are semantically unequal. Objects
+     * of different subclasses are considered unequal.
+     * @param that  The object to be compared with.
+     * @return  true if the given <code>TimeZoneRule</code> objects are semantically unequal.
+     * @stable ICU 4.0
+     */
+    virtual UBool operator!=(const TimeZoneRule& that) const;
+
+    /**
+     * Gets the start date/time rule used by this rule.
+     * @return  The <code>AnnualDateTimeRule</code> which represents the start date/time
+     *          rule used by this time zone rule.
+     * @stable ICU 4.0
+     */
+    const DateTimeRule* getRule(void) const;
+
+    /**
+     * Gets the first year when this rule takes effect.
+     * @return  The start year of this rule.  The year is in Gregorian calendar
+     *          with 0 == 1 BCE, -1 == 2 BCE, etc.
+     * @stable ICU 4.0
+     */
+    int32_t getStartYear(void) const;
+
+    /**
+     * Gets the end year when this rule takes effect.
+     * @return  The end year of this rule (inclusive). The year is in Gregorian calendar
+     *          with 0 == 1 BCE, -1 == 2 BCE, etc.
+     * @stable ICU 4.0
+     */
+    int32_t getEndYear(void) const;
+
+    /**
+     * Gets the time when this rule takes effect in the given year.
+     * @param year              The Gregorian year, with 0 == 1 BCE, -1 == 2 BCE, etc.
+     * @param prevRawOffset     The standard time offset from UTC before this rule
+     *                          takes effect in milliseconds.
+     * @param prevDSTSavings    The amount of daylight saving offset from the
+     *                          standard time.
+     * @param result            Receives the start time in the year.
+     * @return  true if this rule takes effect in the year and the result is set to
+     *          "result".
+     * @stable ICU 4.0
+     */
+    UBool getStartInYear(int32_t year, int32_t prevRawOffset, int32_t prevDSTSavings, UDate& result) const;
+
+    /**
+     * Returns if this rule represents the same rule and offsets as another.
+     * When two <code>TimeZoneRule</code> objects differ only its names, this method
+     * returns true.
+     * @param that  The <code>TimeZoneRule</code> object to be compared with.
+     * @return  true if the other <code>TimeZoneRule</code> is equivalent to this one.
+     * @stable ICU 4.0
+     */
+    virtual UBool isEquivalentTo(const TimeZoneRule& that) const;
+
+    /**
+     * Gets the very first time when this rule takes effect.
+     * @param prevRawOffset     The standard time offset from UTC before this rule
+     *                          takes effect in milliseconds.
+     * @param prevDSTSavings    The amount of daylight saving offset from the
+     *                          standard time.
+     * @param result            Receives the very first time when this rule takes effect.
+     * @return  true if the start time is available.  When false is returned, output parameter
+     *          "result" is unchanged.
+     * @stable ICU 4.0
+     */
+    virtual UBool getFirstStart(int32_t prevRawOffset, int32_t prevDSTSavings, UDate& result) const;
+
+    /**
+     * Gets the final time when this rule takes effect.
+     * @param prevRawOffset     The standard time offset from UTC before this rule
+     *                          takes effect in milliseconds.
+     * @param prevDSTSavings    The amount of daylight saving offset from the
+     *                          standard time.
+     * @param result            Receives the final time when this rule takes effect.
+     * @return  true if the start time is available.  When false is returned, output parameter
+     *          "result" is unchanged.
+     * @stable ICU 4.0
+     */
+    virtual UBool getFinalStart(int32_t prevRawOffset, int32_t prevDSTSavings, UDate& result) const;
+
+    /**
+     * Gets the first time when this rule takes effect after the specified time.
+     * @param base              The first start time after this base time will be returned.
+     * @param prevRawOffset     The standard time offset from UTC before this rule
+     *                          takes effect in milliseconds.
+     * @param prevDSTSavings    The amount of daylight saving offset from the
+     *                          standard time.
+     * @param inclusive         Whether the base time is inclusive or not.
+     * @param result            Receives The first time when this rule takes effect after
+     *                          the specified base time.
+     * @return  true if the start time is available.  When false is returned, output parameter
+     *          "result" is unchanged.
+     * @stable ICU 4.0
+     */
+    virtual UBool getNextStart(UDate base, int32_t prevRawOffset, int32_t prevDSTSavings,
+        UBool inclusive, UDate& result) const;
+
+    /**
+     * Gets the most recent time when this rule takes effect before the specified time.
+     * @param base              The most recent time before this base time will be returned.
+     * @param prevRawOffset     The standard time offset from UTC before this rule
+     *                          takes effect in milliseconds.
+     * @param prevDSTSavings    The amount of daylight saving offset from the
+     *                          standard time.
+     * @param inclusive         Whether the base time is inclusive or not.
+     * @param result            Receives The most recent time when this rule takes effect before
+     *                          the specified base time.
+     * @return  true if the start time is available.  When false is returned, output parameter
+     *          "result" is unchanged.
+     * @stable ICU 4.0
+     */
+    virtual UBool getPreviousStart(UDate base, int32_t prevRawOffset, int32_t prevDSTSavings,
+        UBool inclusive, UDate& result) const;
+
+
+private:
+    DateTimeRule* fDateTimeRule;
+    int32_t fStartYear;
+    int32_t fEndYear;
+
+public:
+    /**
+     * Return the class ID for this class. This is useful only for comparing to
+     * a return value from getDynamicClassID(). For example:
+     * <pre>
+     * .   Base* polymorphic_pointer = createPolymorphicObject();
+     * .   if (polymorphic_pointer->getDynamicClassID() ==
+     * .       erived::getStaticClassID()) ...
+     * </pre>
+     * @return          The class ID for all objects of this class.
+     * @stable ICU 4.0
+     */
+    static UClassID U_EXPORT2 getStaticClassID(void);
+
+    /**
+     * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This
+     * method is to implement a simple version of RTTI, since not all C++
+     * compilers support genuine RTTI. Polymorphic operator==() and clone()
+     * methods call this method.
+     *
+     * @return          The class ID for this object. All objects of a
+     *                  given class have the same class ID.  Objects of
+     *                  other classes have different class IDs.
+     * @stable ICU 4.0
+     */
+    virtual UClassID getDynamicClassID(void) const;
+};
+
+/**
+ * <code>TimeArrayTimeZoneRule</code> represents a time zone rule whose start times are
+ * defined by an array of milliseconds since the standard base time.
+ * 
+ * @stable ICU 4.0
+ */
+class U_I18N_API TimeArrayTimeZoneRule : public TimeZoneRule {
+public:
+    /**
+     * Constructs a <code>TimeArrayTimeZoneRule</code> with the name, the GMT offset of its
+     * standard time, the amount of daylight saving offset adjustment and
+     * the array of times when this rule takes effect.
+     * @param name          The time zone name.
+     * @param rawOffset     The UTC offset of its standard time in milliseconds.
+     * @param dstSavings    The amount of daylight saving offset adjustment in
+     *                      milliseconds.  If this ia a rule for standard time,
+     *                      the value of this argument is 0.
+     * @param startTimes    The array start times in milliseconds since the base time
+     *                      (January 1, 1970, 00:00:00).
+     * @param numStartTimes The number of elements in the parameter "startTimes"
+     * @param timeRuleType  The time type of the start times, which is one of
+     *                      <code>DataTimeRule::WALL_TIME</code>, <code>STANDARD_TIME</code>
+     *                      and <code>UTC_TIME</code>.
+     * @stable ICU 4.0
+     */
+    TimeArrayTimeZoneRule(const UnicodeString& name, int32_t rawOffset, int32_t dstSavings,
+        const UDate* startTimes, int32_t numStartTimes, DateTimeRule::TimeRuleType timeRuleType);
+
+    /**
+     * Copy constructor.
+     * @param source    The TimeArrayTimeZoneRule object to be copied.
+     * @stable ICU 4.0
+     */
+    TimeArrayTimeZoneRule(const TimeArrayTimeZoneRule& source);
+
+    /**
+     * Destructor.
+     * @stable ICU 4.0
+     */
+    virtual ~TimeArrayTimeZoneRule();
+
+    /**
+     * Clone this TimeArrayTimeZoneRule object polymorphically. The caller owns the result and
+     * should delete it when done.
+     * @return    A copy of the object.
+     * @stable ICU 4.0
+     */
+    virtual TimeArrayTimeZoneRule* clone(void) const;
+
+    /**
+     * Assignment operator.
+     * @param right The object to be copied.
+     * @stable ICU 4.0
+     */
+    TimeArrayTimeZoneRule& operator=(const TimeArrayTimeZoneRule& right);
+
+    /**
+     * Return true if the given <code>TimeZoneRule</code> objects are semantically equal. Objects
+     * of different subclasses are considered unequal.
+     * @param that  The object to be compared with.
+     * @return  true if the given <code>TimeZoneRule</code> objects are semantically equal.
+     * @stable ICU 4.0
+     */
+    virtual UBool operator==(const TimeZoneRule& that) const;
+
+    /**
+     * Return true if the given <code>TimeZoneRule</code> objects are semantically unequal. Objects
+     * of different subclasses are considered unequal.
+     * @param that  The object to be compared with.
+     * @return  true if the given <code>TimeZoneRule</code> objects are semantically unequal.
+     * @stable ICU 4.0
+     */
+    virtual UBool operator!=(const TimeZoneRule& that) const;
+
+    /**
+     * Gets the time type of the start times used by this rule.  The return value
+     * is either <code>DateTimeRule::WALL_TIME</code> or <code>STANDARD_TIME</code>
+     * or <code>UTC_TIME</code>.
+     * 
+     * @return The time type used of the start times used by this rule.
+     * @stable ICU 4.0
+     */
+    DateTimeRule::TimeRuleType getTimeType(void) const;
+
+    /**
+     * Gets a start time at the index stored in this rule.
+     * @param index     The index of start times
+     * @param result    Receives the start time at the index
+     * @return  true if the index is within the valid range and
+     *          and the result is set.  When false, the output
+     *          parameger "result" is unchanged.
+     * @stable ICU 4.0
+     */
+    UBool getStartTimeAt(int32_t index, UDate& result) const;
+
+    /**
+     * Returns the number of start times stored in this rule
+     * @return The number of start times.
+     * @stable ICU 4.0
+     */
+    int32_t countStartTimes(void) const;
+
+    /**
+     * Returns if this rule represents the same rule and offsets as another.
+     * When two <code>TimeZoneRule</code> objects differ only its names, this method
+     * returns true.
+     * @param that  The <code>TimeZoneRule</code> object to be compared with.
+     * @return  true if the other <code>TimeZoneRule</code> is equivalent to this one.
+     * @stable ICU 4.0
+     */
+    virtual UBool isEquivalentTo(const TimeZoneRule& that) const;
+
+    /**
+     * Gets the very first time when this rule takes effect.
+     * @param prevRawOffset     The standard time offset from UTC before this rule
+     *                          takes effect in milliseconds.
+     * @param prevDSTSavings    The amount of daylight saving offset from the
+     *                          standard time.
+     * @param result            Receives the very first time when this rule takes effect.
+     * @return  true if the start time is available.  When false is returned, output parameter
+     *          "result" is unchanged.
+     * @stable ICU 4.0
+     */
+    virtual UBool getFirstStart(int32_t prevRawOffset, int32_t prevDSTSavings, UDate& result) const;
+
+    /**
+     * Gets the final time when this rule takes effect.
+     * @param prevRawOffset     The standard time offset from UTC before this rule
+     *                          takes effect in milliseconds.
+     * @param prevDSTSavings    The amount of daylight saving offset from the
+     *                          standard time.
+     * @param result            Receives the final time when this rule takes effect.
+     * @return  true if the start time is available.  When false is returned, output parameter
+     *          "result" is unchanged.
+     * @stable ICU 4.0
+     */
+    virtual UBool getFinalStart(int32_t prevRawOffset, int32_t prevDSTSavings, UDate& result) const;
+
+    /**
+     * Gets the first time when this rule takes effect after the specified time.
+     * @param base              The first start time after this base time will be returned.
+     * @param prevRawOffset     The standard time offset from UTC before this rule
+     *                          takes effect in milliseconds.
+     * @param prevDSTSavings    The amount of daylight saving offset from the
+     *                          standard time.
+     * @param inclusive         Whether the base time is inclusive or not.
+     * @param result            Receives The first time when this rule takes effect after
+     *                          the specified base time.
+     * @return  true if the start time is available.  When false is returned, output parameter
+     *          "result" is unchanged.
+     * @stable ICU 4.0
+     */
+    virtual UBool getNextStart(UDate base, int32_t prevRawOffset, int32_t prevDSTSavings,
+        UBool inclusive, UDate& result) const;
+
+    /**
+     * Gets the most recent time when this rule takes effect before the specified time.
+     * @param base              The most recent time before this base time will be returned.
+     * @param prevRawOffset     The standard time offset from UTC before this rule
+     *                          takes effect in milliseconds.
+     * @param prevDSTSavings    The amount of daylight saving offset from the
+     *                          standard time.
+     * @param inclusive         Whether the base time is inclusive or not.
+     * @param result            Receives The most recent time when this rule takes effect before
+     *                          the specified base time.
+     * @return  true if the start time is available.  When false is returned, output parameter
+     *          "result" is unchanged.
+     * @stable ICU 4.0
+     */
+    virtual UBool getPreviousStart(UDate base, int32_t prevRawOffset, int32_t prevDSTSavings,
+        UBool inclusive, UDate& result) const;
+
+
+private:
+    enum { TIMEARRAY_STACK_BUFFER_SIZE = 32 };
+    UBool initStartTimes(const UDate source[], int32_t size, UErrorCode& ec);
+    UDate getUTC(UDate time, int32_t raw, int32_t dst) const;
+
+    DateTimeRule::TimeRuleType  fTimeRuleType;
+    int32_t fNumStartTimes;
+    UDate*  fStartTimes;
+    UDate   fLocalStartTimes[TIMEARRAY_STACK_BUFFER_SIZE];
+
+public:
+    /**
+     * Return the class ID for this class. This is useful only for comparing to
+     * a return value from getDynamicClassID(). For example:
+     * <pre>
+     * .   Base* polymorphic_pointer = createPolymorphicObject();
+     * .   if (polymorphic_pointer->getDynamicClassID() ==
+     * .       erived::getStaticClassID()) ...
+     * </pre>
+     * @return          The class ID for all objects of this class.
+     * @stable ICU 4.0
+     */
+    static UClassID U_EXPORT2 getStaticClassID(void);
+
+    /**
+     * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This
+     * method is to implement a simple version of RTTI, since not all C++
+     * compilers support genuine RTTI. Polymorphic operator==() and clone()
+     * methods call this method.
+     *
+     * @return          The class ID for this object. All objects of a
+     *                  given class have the same class ID.  Objects of
+     *                  other classes have different class IDs.
+     * @stable ICU 4.0
+     */
+    virtual UClassID getDynamicClassID(void) const;
+};
+
+
+U_NAMESPACE_END
+
+#endif /* #if !UCONFIG_NO_FORMATTING */
+
+#endif // TZRULE_H
+
+//eof

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/tztrans.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/tztrans.h b/src/apps/couch_collate/platform/osx/icu/unicode/tztrans.h
new file mode 100644
index 0000000..12f85d6
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/tztrans.h
@@ -0,0 +1,195 @@
+/*
+*******************************************************************************
+* Copyright (C) 2007-2008, International Business Machines Corporation and         *
+* others. All Rights Reserved.                                                *
+*******************************************************************************
+*/
+#ifndef TZTRANS_H
+#define TZTRANS_H
+
+/**
+ * \file 
+ * \brief C++ API: Time zone transition
+ */
+
+#include "unicode/utypes.h"
+
+#if !UCONFIG_NO_FORMATTING
+
+#include "unicode/uobject.h"
+
+U_NAMESPACE_BEGIN
+
+// Forward declaration
+class TimeZoneRule;
+
+/**
+ * <code>TimeZoneTransition</code> is a class representing a time zone transition.
+ * An instance has a time of transition and rules for both before and after the transition.
+ * @stable ICU 4.0
+ */
+class U_I18N_API TimeZoneTransition : public UObject {
+public:
+    /**
+     * Constructs a <code>TimeZoneTransition</code> with the time and the rules before/after
+     * the transition.
+     * 
+     * @param time  The time of transition in milliseconds since the base time.
+     * @param from  The time zone rule used before the transition.
+     * @param to    The time zone rule used after the transition.
+     * @stable ICU 4.0
+     */
+    TimeZoneTransition(UDate time, const TimeZoneRule& from, const TimeZoneRule& to);
+
+    /**
+     * Constructs an empty <code>TimeZoneTransition</code>
+     * @stable ICU 4.0
+     */
+    TimeZoneTransition();
+
+    /**
+     * Copy constructor.
+     * @param source    The TimeZoneTransition object to be copied.
+     * @stable ICU 4.0
+     */
+    TimeZoneTransition(const TimeZoneTransition& source);
+
+    /**
+     * Destructor.
+     * @stable ICU 4.0
+     */
+    ~TimeZoneTransition();
+
+    /**
+     * Clone this TimeZoneTransition object polymorphically. The caller owns the result and
+     * should delete it when done.
+     * @return  A copy of the object.
+     * @stable ICU 4.0
+     */
+    TimeZoneTransition* clone(void) const;
+
+    /**
+     * Assignment operator.
+     * @param right The object to be copied.
+     * @stable ICU 4.0
+     */
+    TimeZoneTransition& operator=(const TimeZoneTransition& right);
+
+    /**
+     * Return true if the given TimeZoneTransition objects are semantically equal. Objects
+     * of different subclasses are considered unequal.
+     * @param that  The object to be compared with.
+     * @return  true if the given TimeZoneTransition objects are semantically equal.
+     * @stable ICU 4.0
+     */
+    UBool operator==(const TimeZoneTransition& that) const;
+
+    /**
+     * Return true if the given TimeZoneTransition objects are semantically unequal. Objects
+     * of different subclasses are considered unequal.
+     * @param that  The object to be compared with.
+     * @return  true if the given TimeZoneTransition objects are semantically unequal.
+     * @stable ICU 4.0
+     */
+    UBool operator!=(const TimeZoneTransition& that) const;
+
+    /**
+     * Returns the time of transition in milliseconds.
+     * @return The time of the transition in milliseconds since the 1970 Jan 1 epoch time.
+     * @stable ICU 4.0
+     */
+    UDate getTime(void) const;
+
+    /**
+     * Sets the time of transition in milliseconds.
+     * @param time The time of the transition in milliseconds since the 1970 Jan 1 epoch time.
+     * @stable ICU 4.0
+     */
+    void setTime(UDate time);
+
+    /**
+     * Returns the rule used before the transition.
+     * @return The time zone rule used after the transition.
+     * @stable ICU 4.0
+     */
+    const TimeZoneRule* getFrom(void) const;
+
+    /**
+     * Sets the rule used before the transition.  The caller remains
+     * responsible for deleting the <code>TimeZoneRule</code> object.
+     * @param from The time zone rule used before the transition.
+     * @stable ICU 4.0
+     */
+    void setFrom(const TimeZoneRule& from);
+
+    /**
+     * Adopts the rule used before the transition.  The caller must
+     * not delete the <code>TimeZoneRule</code> object passed in.
+     * @param from The time zone rule used before the transition.
+     * @stable ICU 4.0
+     */
+    void adoptFrom(TimeZoneRule* from);
+
+    /**
+     * Sets the rule used after the transition.  The caller remains
+     * responsible for deleting the <code>TimeZoneRule</code> object.
+     * @param to The time zone rule used after the transition.
+     * @stable ICU 4.0
+     */
+    void setTo(const TimeZoneRule& to);
+
+    /**
+     * Adopts the rule used after the transition.  The caller must
+     * not delete the <code>TimeZoneRule</code> object passed in.
+     * @param to The time zone rule used after the transition.
+     * @stable ICU 4.0
+     */
+    void adoptTo(TimeZoneRule* to);
+
+    /**
+     * Returns the rule used after the transition.
+     * @return The time zone rule used after the transition.
+     * @stable ICU 4.0
+     */
+    const TimeZoneRule* getTo(void) const;
+
+private:
+    UDate   fTime;
+    TimeZoneRule*   fFrom;
+    TimeZoneRule*   fTo;
+
+public:
+    /**
+     * Return the class ID for this class. This is useful only for comparing to
+     * a return value from getDynamicClassID(). For example:
+     * <pre>
+     * .   Base* polymorphic_pointer = createPolymorphicObject();
+     * .   if (polymorphic_pointer->getDynamicClassID() ==
+     * .       erived::getStaticClassID()) ...
+     * </pre>
+     * @return          The class ID for all objects of this class.
+     * @stable ICU 4.0
+     */
+    static UClassID U_EXPORT2 getStaticClassID(void);
+
+    /**
+     * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This
+     * method is to implement a simple version of RTTI, since not all C++
+     * compilers support genuine RTTI. Polymorphic operator==() and clone()
+     * methods call this method.
+     *
+     * @return          The class ID for this object. All objects of a
+     *                  given class have the same class ID.  Objects of
+     *                  other classes have different class IDs.
+     * @stable ICU 4.0
+     */
+    virtual UClassID getDynamicClassID(void) const;
+};
+
+U_NAMESPACE_END
+
+#endif /* #if !UCONFIG_NO_FORMATTING */
+
+#endif // TZTRANS_H
+
+//eof


[92/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/calendar.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/calendar.h b/src/apps/couch_collate/platform/osx/icu/unicode/calendar.h
new file mode 100644
index 0000000..709b27e
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/calendar.h
@@ -0,0 +1,2170 @@
+/*
+********************************************************************************
+*   Copyright (C) 1997-2008, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+********************************************************************************
+*
+* File CALENDAR.H
+*
+* Modification History:
+*
+*   Date        Name        Description
+*   04/22/97    aliu        Expanded and corrected comments and other header
+*                           contents.
+*   05/01/97    aliu        Made equals(), before(), after() arguments const.
+*   05/20/97    aliu        Replaced fAreFieldsSet with fAreFieldsInSync and
+*                           fAreAllFieldsSet.
+*   07/27/98    stephen     Sync up with JDK 1.2
+*   11/15/99    weiv        added YEAR_WOY and DOW_LOCAL
+*                           to EDateFields
+*    8/19/2002  srl         Removed Javaisms
+*   11/07/2003  srl         Update, clean up documentation.
+********************************************************************************
+*/
+
+#ifndef CALENDAR_H
+#define CALENDAR_H
+
+#include "unicode/utypes.h"
+
+/**
+ * \file 
+ * \brief C++ API: Calendar object
+ */
+#if !UCONFIG_NO_FORMATTING
+
+#include "unicode/uobject.h"
+#include "unicode/locid.h"
+#include "unicode/timezone.h"
+#include "unicode/ucal.h"
+#include "unicode/umisc.h"
+
+U_NAMESPACE_BEGIN
+
+class ICUServiceFactory;
+
+/**
+ * @internal
+ */
+typedef int32_t UFieldResolutionTable[12][8];
+
+/**
+ * <code>Calendar</code> is an abstract base class for converting between
+ * a <code>UDate</code> object and a set of integer fields such as
+ * <code>YEAR</code>, <code>MONTH</code>, <code>DAY</code>, <code>HOUR</code>,
+ * and so on. (A <code>UDate</code> object represents a specific instant in
+ * time with millisecond precision. See UDate
+ * for information about the <code>UDate</code> class.)
+ *
+ * <p>
+ * Subclasses of <code>Calendar</code> interpret a <code>UDate</code>
+ * according to the rules of a specific calendar system.
+ * The most commonly used subclass of <code>Calendar</code> is
+ * <code>GregorianCalendar</code>. Other subclasses could represent
+ * the various types of lunar calendars in use in many parts of the world.
+ *
+ * <p>
+ * <b>NOTE</b>: (ICU 2.6) The subclass interface should be considered unstable
+ * - it WILL change.
+ *
+ * <p>
+ * Like other locale-sensitive classes, <code>Calendar</code> provides a
+ * static method, <code>createInstance</code>, for getting a generally useful
+ * object of this type. <code>Calendar</code>'s <code>createInstance</code> method
+ * returns the appropriate <code>Calendar</code> subclass whose
+ * time fields have been initialized with the current date and time:
+ * \htmlonly<blockquote>\endhtmlonly
+ * <pre>
+ * Calendar *rightNow = Calendar::createInstance(errCode);
+ * </pre>
+ * \htmlonly</blockquote>\endhtmlonly
+ *
+ * <p>
+ * A <code>Calendar</code> object can produce all the time field values
+ * needed to implement the date-time formatting for a particular language
+ * and calendar style (for example, Japanese-Gregorian, Japanese-Traditional).
+ *
+ * <p>
+ * When computing a <code>UDate</code> from time fields, two special circumstances
+ * may arise: there may be insufficient information to compute the
+ * <code>UDate</code> (such as only year and month but no day in the month),
+ * or there may be inconsistent information (such as "Tuesday, July 15, 1996"
+ * -- July 15, 1996 is actually a Monday).
+ *
+ * <p>
+ * <strong>Insufficient information.</strong> The calendar will use default
+ * information to specify the missing fields. This may vary by calendar; for
+ * the Gregorian calendar, the default for a field is the same as that of the
+ * start of the epoch: i.e., YEAR = 1970, MONTH = JANUARY, DATE = 1, etc.
+ *
+ * <p>
+ * <strong>Inconsistent information.</strong> If fields conflict, the calendar
+ * will give preference to fields set more recently. For example, when
+ * determining the day, the calendar will look for one of the following
+ * combinations of fields.  The most recent combination, as determined by the
+ * most recently set single field, will be used.
+ *
+ * \htmlonly<blockquote>\endhtmlonly
+ * <pre>
+ * MONTH + DAY_OF_MONTH
+ * MONTH + WEEK_OF_MONTH + DAY_OF_WEEK
+ * MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK
+ * DAY_OF_YEAR
+ * DAY_OF_WEEK + WEEK_OF_YEAR
+ * </pre>
+ * \htmlonly</blockquote>\endhtmlonly
+ *
+ * For the time of day:
+ *
+ * \htmlonly<blockquote>\endhtmlonly
+ * <pre>
+ * HOUR_OF_DAY
+ * AM_PM + HOUR
+ * </pre>
+ * \htmlonly</blockquote>\endhtmlonly
+ *
+ * <p>
+ * <strong>Note:</strong> for some non-Gregorian calendars, different
+ * fields may be necessary for complete disambiguation. For example, a full
+ * specification of the historial Arabic astronomical calendar requires year,
+ * month, day-of-month <em>and</em> day-of-week in some cases.
+ *
+ * <p>
+ * <strong>Note:</strong> There are certain possible ambiguities in
+ * interpretation of certain singular times, which are resolved in the
+ * following ways:
+ * <ol>
+ *     <li> 24:00:00 "belongs" to the following day. That is,
+ *          23:59 on Dec 31, 1969 &lt; 24:00 on Jan 1, 1970 &lt; 24:01:00 on Jan 1, 1970
+ *
+ *     <li> Although historically not precise, midnight also belongs to "am",
+ *          and noon belongs to "pm", so on the same day,
+ *          12:00 am (midnight) &lt; 12:01 am, and 12:00 pm (noon) &lt; 12:01 pm
+ * </ol>
+ *
+ * <p>
+ * The date or time format strings are not part of the definition of a
+ * calendar, as those must be modifiable or overridable by the user at
+ * runtime. Use {@link DateFormat}
+ * to format dates.
+ *
+ * <p>
+ * <code>Calendar</code> provides an API for field "rolling", where fields
+ * can be incremented or decremented, but wrap around. For example, rolling the
+ * month up in the date <code>December 12, <b>1996</b></code> results in
+ * <code>January 12, <b>1996</b></code>.
+ *
+ * <p>
+ * <code>Calendar</code> also provides a date arithmetic function for
+ * adding the specified (signed) amount of time to a particular time field.
+ * For example, subtracting 5 days from the date <code>September 12, 1996</code>
+ * results in <code>September 7, 1996</code>.
+ *
+ * @stable ICU 2.0
+ */
+class U_I18N_API Calendar : public UObject {
+public:
+
+    /**
+     * Field IDs for date and time. Used to specify date/time fields. ERA is calendar
+     * specific. Example ranges given are for illustration only; see specific Calendar
+     * subclasses for actual ranges.
+     * @deprecated ICU 2.6. Use C enum UCalendarDateFields defined in ucal.h
+     */
+    enum EDateFields {
+#ifndef U_HIDE_DEPRECATED_API
+        ERA,                  // Example: 0..1
+        YEAR,                 // Example: 1..big number
+        MONTH,                // Example: 0..11
+        WEEK_OF_YEAR,         // Example: 1..53
+        WEEK_OF_MONTH,        // Example: 1..4
+        DATE,                 // Example: 1..31
+        DAY_OF_YEAR,          // Example: 1..365
+        DAY_OF_WEEK,          // Example: 1..7
+        DAY_OF_WEEK_IN_MONTH, // Example: 1..4, may be specified as -1
+        AM_PM,                // Example: 0..1
+        HOUR,                 // Example: 0..11
+        HOUR_OF_DAY,          // Example: 0..23
+        MINUTE,               // Example: 0..59
+        SECOND,               // Example: 0..59
+        MILLISECOND,          // Example: 0..999
+        ZONE_OFFSET,          // Example: -12*U_MILLIS_PER_HOUR..12*U_MILLIS_PER_HOUR
+        DST_OFFSET,           // Example: 0 or U_MILLIS_PER_HOUR
+        YEAR_WOY,             // 'Y' Example: 1..big number - Year of Week of Year
+        DOW_LOCAL,            // 'e' Example: 1..7 - Day of Week / Localized
+		
+		EXTENDED_YEAR,
+		JULIAN_DAY,
+		MILLISECONDS_IN_DAY,
+		IS_LEAP_MONTH,
+
+        FIELD_COUNT = UCAL_FIELD_COUNT // See ucal.h for other fields.
+#endif /* U_HIDE_DEPRECATED_API */
+    };
+
+    /**
+     * Useful constant for days of week. Note: Calendar day-of-week is 1-based. Clients
+     * who create locale resources for the field of first-day-of-week should be aware of
+     * this. For instance, in US locale, first-day-of-week is set to 1, i.e., SUNDAY.
+     * @deprecated ICU 2.6. Use C enum UCalendarDaysOfWeek defined in ucal.h
+     */
+    enum EDaysOfWeek {
+#ifndef U_HIDE_DEPRECATED_API
+        SUNDAY = 1,
+        MONDAY,
+        TUESDAY,
+        WEDNESDAY,
+        THURSDAY,
+        FRIDAY,
+        SATURDAY
+#endif /* U_HIDE_DEPRECATED_API */
+    };
+
+    /**
+     * Useful constants for month. Note: Calendar month is 0-based.
+     * @deprecated ICU 2.6. Use C enum UCalendarMonths defined in ucal.h
+     */
+    enum EMonths {
+#ifndef U_HIDE_DEPRECATED_API
+        JANUARY,
+        FEBRUARY,
+        MARCH,
+        APRIL,
+        MAY,
+        JUNE,
+        JULY,
+        AUGUST,
+        SEPTEMBER,
+        OCTOBER,
+        NOVEMBER,
+        DECEMBER,
+        UNDECIMBER
+#endif /* U_HIDE_DEPRECATED_API */
+    };
+
+    /**
+     * Useful constants for hour in 12-hour clock. Used in GregorianCalendar.
+     * @deprecated ICU 2.6. Use C enum UCalendarAMPMs defined in ucal.h
+     */
+    enum EAmpm {
+#ifndef U_HIDE_DEPRECATED_API
+        AM,
+        PM
+#endif /* U_HIDE_DEPRECATED_API */
+    };
+
+    /**
+     * destructor
+     * @stable ICU 2.0
+     */
+    virtual ~Calendar();
+
+    /**
+     * Create and return a polymorphic copy of this calendar.
+     *
+     * @return    a polymorphic copy of this calendar.
+     * @stable ICU 2.0
+     */
+    virtual Calendar* clone(void) const = 0;
+
+    /**
+     * Creates a Calendar using the default timezone and locale. Clients are responsible
+     * for deleting the object returned.
+     *
+     * @param success  Indicates the success/failure of Calendar creation. Filled in
+     *                 with U_ZERO_ERROR if created successfully, set to a failure result
+     *                 otherwise. U_MISSING_RESOURCE_ERROR will be returned if the resource data
+     *                 requests a calendar type which has not been installed.
+     * @return         A Calendar if created successfully. NULL otherwise.
+     * @stable ICU 2.0
+     */
+    static Calendar* U_EXPORT2 createInstance(UErrorCode& success);
+
+    /**
+     * Creates a Calendar using the given timezone and the default locale.
+     * The Calendar takes ownership of zoneToAdopt; the
+     * client must not delete it.
+     *
+     * @param zoneToAdopt  The given timezone to be adopted.
+     * @param success      Indicates the success/failure of Calendar creation. Filled in
+     *                     with U_ZERO_ERROR if created successfully, set to a failure result
+     *                     otherwise.
+     * @return             A Calendar if created successfully. NULL otherwise.
+     * @stable ICU 2.0
+     */
+    static Calendar* U_EXPORT2 createInstance(TimeZone* zoneToAdopt, UErrorCode& success);
+
+    /**
+     * Creates a Calendar using the given timezone and the default locale.  The TimeZone
+     * is _not_ adopted; the client is still responsible for deleting it.
+     *
+     * @param zone  The timezone.
+     * @param success      Indicates the success/failure of Calendar creation. Filled in
+     *                     with U_ZERO_ERROR if created successfully, set to a failure result
+     *                     otherwise.
+     * @return             A Calendar if created successfully. NULL otherwise.
+     * @stable ICU 2.0
+     */
+    static Calendar* U_EXPORT2 createInstance(const TimeZone& zone, UErrorCode& success);
+
+    /**
+     * Creates a Calendar using the default timezone and the given locale.
+     *
+     * @param aLocale  The given locale.
+     * @param success  Indicates the success/failure of Calendar creation. Filled in
+     *                 with U_ZERO_ERROR if created successfully, set to a failure result
+     *                 otherwise.
+     * @return         A Calendar if created successfully. NULL otherwise.
+     * @stable ICU 2.0
+     */
+    static Calendar* U_EXPORT2 createInstance(const Locale& aLocale, UErrorCode& success);
+
+    /**
+     * Creates a Calendar using the given timezone and given locale.
+     * The Calendar takes ownership of zoneToAdopt; the
+     * client must not delete it.
+     *
+     * @param zoneToAdopt  The given timezone to be adopted.
+     * @param aLocale      The given locale.
+     * @param success      Indicates the success/failure of Calendar creation. Filled in
+     *                     with U_ZERO_ERROR if created successfully, set to a failure result
+     *                     otherwise.
+     * @return             A Calendar if created successfully. NULL otherwise.
+     * @stable ICU 2.0
+     */
+    static Calendar* U_EXPORT2 createInstance(TimeZone* zoneToAdopt, const Locale& aLocale, UErrorCode& success);
+
+    /**
+     * Gets a Calendar using the given timezone and given locale.  The TimeZone
+     * is _not_ adopted; the client is still responsible for deleting it.
+     *
+     * @param zoneToAdopt  The given timezone to be adopted.
+     * @param aLocale      The given locale.
+     * @param success      Indicates the success/failure of Calendar creation. Filled in
+     *                     with U_ZERO_ERROR if created successfully, set to a failure result
+     *                     otherwise.
+     * @return             A Calendar if created successfully. NULL otherwise.
+     * @stable ICU 2.0
+     */
+    static Calendar* U_EXPORT2 createInstance(const TimeZone& zoneToAdopt, const Locale& aLocale, UErrorCode& success);
+
+    /**
+     * Returns a list of the locales for which Calendars are installed.
+     *
+     * @param count  Number of locales returned.
+     * @return       An array of Locale objects representing the set of locales for which
+     *               Calendars are installed.  The system retains ownership of this list;
+     *               the caller must NOT delete it. Does not include user-registered Calendars.
+     * @stable ICU 2.0
+     */
+    static const Locale* U_EXPORT2 getAvailableLocales(int32_t& count);
+
+    /**
+     * Returns the current UTC (GMT) time measured in milliseconds since 0:00:00 on 1/1/70
+     * (derived from the system time).
+     *
+     * @return   The current UTC time in milliseconds.
+     * @stable ICU 2.0
+     */
+    static UDate U_EXPORT2 getNow(void);
+
+    /**
+     * Gets this Calendar's time as milliseconds. May involve recalculation of time due
+     * to previous calls to set time field values. The time specified is non-local UTC
+     * (GMT) time. Although this method is const, this object may actually be changed
+     * (semantically const).
+     *
+     * @param status  Output param set to success/failure code on exit. If any value
+     *                previously set in the time field is invalid or restricted by
+     *                leniency, this will be set to an error status.
+     * @return        The current time in UTC (GMT) time, or zero if the operation
+     *                failed.
+     * @stable ICU 2.0
+     */
+    inline UDate getTime(UErrorCode& status) const { return getTimeInMillis(status); }
+
+    /**
+     * Sets this Calendar's current time with the given UDate. The time specified should
+     * be in non-local UTC (GMT) time.
+     *
+     * @param date  The given UDate in UTC (GMT) time.
+     * @param status  Output param set to success/failure code on exit. If any value
+     *                set in the time field is invalid or restricted by
+     *                leniency, this will be set to an error status.
+     * @stable ICU 2.0
+     */
+    inline void setTime(UDate date, UErrorCode& status) { setTimeInMillis(date, status); }
+
+    /**
+     * Compares the equality of two Calendar objects. Objects of different subclasses
+     * are considered unequal. This comparison is very exacting; two Calendar objects
+     * must be in exactly the same state to be considered equal. To compare based on the
+     * represented time, use equals() instead.
+     *
+     * @param that  The Calendar object to be compared with.
+     * @return      True if the given Calendar is the same as this Calendar; false
+     *              otherwise.
+     * @stable ICU 2.0
+     */
+    virtual UBool operator==(const Calendar& that) const;
+
+    /**
+     * Compares the inequality of two Calendar objects.
+     *
+     * @param that  The Calendar object to be compared with.
+     * @return      True if the given Calendar is not the same as this Calendar; false
+     *              otherwise.
+     * @stable ICU 2.0
+     */
+    UBool operator!=(const Calendar& that) const {return !operator==(that);}
+
+    /**
+     * Returns TRUE if the given Calendar object is equivalent to this
+     * one.  An equivalent Calendar will behave exactly as this one
+     * does, but it may be set to a different time.  By contrast, for
+     * the operator==() method to return TRUE, the other Calendar must
+     * be set to the same time.
+     *
+     * @param other the Calendar to be compared with this Calendar
+     * @stable ICU 2.4
+     */
+    virtual UBool isEquivalentTo(const Calendar& other) const;
+
+    /**
+     * Compares the Calendar time, whereas Calendar::operator== compares the equality of
+     * Calendar objects.
+     *
+     * @param when    The Calendar to be compared with this Calendar. Although this is a
+     *                const parameter, the object may be modified physically
+     *                (semantically const).
+     * @param status  Output param set to success/failure code on exit. If any value
+     *                previously set in the time field is invalid or restricted by
+     *                leniency, this will be set to an error status.
+     * @return        True if the current time of this Calendar is equal to the time of
+     *                Calendar when; false otherwise.
+     * @stable ICU 2.0
+     */
+    UBool equals(const Calendar& when, UErrorCode& status) const;
+
+    /**
+     * Returns true if this Calendar's current time is before "when"'s current time.
+     *
+     * @param when    The Calendar to be compared with this Calendar. Although this is a
+     *                const parameter, the object may be modified physically
+     *                (semantically const).
+     * @param status  Output param set to success/failure code on exit. If any value
+     *                previously set in the time field is invalid or restricted by
+     *                leniency, this will be set to an error status.
+     * @return        True if the current time of this Calendar is before the time of
+     *                Calendar when; false otherwise.
+     * @stable ICU 2.0
+     */
+    UBool before(const Calendar& when, UErrorCode& status) const;
+
+    /**
+     * Returns true if this Calendar's current time is after "when"'s current time.
+     *
+     * @param when    The Calendar to be compared with this Calendar. Although this is a
+     *                const parameter, the object may be modified physically
+     *                (semantically const).
+     * @param status  Output param set to success/failure code on exit. If any value
+     *                previously set in the time field is invalid or restricted by
+     *                leniency, this will be set to an error status.
+     * @return        True if the current time of this Calendar is after the time of
+     *                Calendar when; false otherwise.
+     * @stable ICU 2.0
+     */
+    UBool after(const Calendar& when, UErrorCode& status) const;
+
+    /**
+     * UDate Arithmetic function. Adds the specified (signed) amount of time to the given
+     * time field, based on the calendar's rules. For example, to subtract 5 days from
+     * the current time of the calendar, call add(Calendar::DATE, -5). When adding on
+     * the month or Calendar::MONTH field, other fields like date might conflict and
+     * need to be changed. For instance, adding 1 month on the date 01/31/96 will result
+     * in 02/29/96.
+     *
+     * @param field   Specifies which date field to modify.
+     * @param amount  The amount of time to be added to the field, in the natural unit
+     *                for that field (e.g., days for the day fields, hours for the hour
+     *                field.)
+     * @param status  Output param set to success/failure code on exit. If any value
+     *                previously set in the time field is invalid or restricted by
+     *                leniency, this will be set to an error status.
+     * @deprecated ICU 2.6. use add(UCalendarDateFields field, int32_t amount, UErrorCode& status) instead.
+     */
+    virtual void add(EDateFields field, int32_t amount, UErrorCode& status);
+
+    /**
+     * UDate Arithmetic function. Adds the specified (signed) amount of time to the given
+     * time field, based on the calendar's rules. For example, to subtract 5 days from
+     * the current time of the calendar, call add(Calendar::DATE, -5). When adding on
+     * the month or Calendar::MONTH field, other fields like date might conflict and
+     * need to be changed. For instance, adding 1 month on the date 01/31/96 will result
+     * in 02/29/96.
+     *
+     * @param field   Specifies which date field to modify.
+     * @param amount  The amount of time to be added to the field, in the natural unit
+     *                for that field (e.g., days for the day fields, hours for the hour
+     *                field.)
+     * @param status  Output param set to success/failure code on exit. If any value
+     *                previously set in the time field is invalid or restricted by
+     *                leniency, this will be set to an error status.
+     * @stable ICU 2.6.
+     */
+    virtual void add(UCalendarDateFields field, int32_t amount, UErrorCode& status);
+
+    /**
+     * Time Field Rolling function. Rolls (up/down) a single unit of time on the given
+     * time field. For example, to roll the current date up by one day, call
+     * roll(Calendar::DATE, true). When rolling on the year or Calendar::YEAR field, it
+     * will roll the year value in the range between getMinimum(Calendar::YEAR) and the
+     * value returned by getMaximum(Calendar::YEAR). When rolling on the month or
+     * Calendar::MONTH field, other fields like date might conflict and, need to be
+     * changed. For instance, rolling the month up on the date 01/31/96 will result in
+     * 02/29/96. Rolling up always means rolling forward in time; e.g., rolling the year
+     * up on "100 BC" will result in "99 BC", for Gregorian calendar. When rolling on the
+     * hour-in-day or Calendar::HOUR_OF_DAY field, it will roll the hour value in the range
+     * between 0 and 23, which is zero-based.
+     * <P>
+     * NOTE: Do not use this method -- use roll(EDateFields, int, UErrorCode&) instead.
+     *
+     * @param field   The time field.
+     * @param up      Indicates if the value of the specified time field is to be rolled
+     *                up or rolled down. Use true if rolling up, false otherwise.
+     * @param status  Output param set to success/failure code on exit. If any value
+     *                previously set in the time field is invalid or restricted by
+     *                leniency, this will be set to an error status.
+     * @deprecated ICU 2.6. Use roll(UCalendarDateFields field, UBool up, UErrorCode& status) instead.
+     */
+    inline void roll(EDateFields field, UBool up, UErrorCode& status);
+
+    /**
+     * Time Field Rolling function. Rolls (up/down) a single unit of time on the given
+     * time field. For example, to roll the current date up by one day, call
+     * roll(Calendar::DATE, true). When rolling on the year or Calendar::YEAR field, it
+     * will roll the year value in the range between getMinimum(Calendar::YEAR) and the
+     * value returned by getMaximum(Calendar::YEAR). When rolling on the month or
+     * Calendar::MONTH field, other fields like date might conflict and, need to be
+     * changed. For instance, rolling the month up on the date 01/31/96 will result in
+     * 02/29/96. Rolling up always means rolling forward in time; e.g., rolling the year
+     * up on "100 BC" will result in "99 BC", for Gregorian calendar. When rolling on the
+     * hour-in-day or Calendar::HOUR_OF_DAY field, it will roll the hour value in the range
+     * between 0 and 23, which is zero-based.
+     * <P>
+     * NOTE: Do not use this method -- use roll(UCalendarDateFields, int, UErrorCode&) instead.
+     *
+     * @param field   The time field.
+     * @param up      Indicates if the value of the specified time field is to be rolled
+     *                up or rolled down. Use true if rolling up, false otherwise.
+     * @param status  Output param set to success/failure code on exit. If any value
+     *                previously set in the time field is invalid or restricted by
+     *                leniency, this will be set to an error status.
+     * @stable ICU 2.6.
+     */
+    inline void roll(UCalendarDateFields field, UBool up, UErrorCode& status);
+
+    /**
+     * Time Field Rolling function. Rolls by the given amount on the given
+     * time field. For example, to roll the current date up by one day, call
+     * roll(Calendar::DATE, +1, status). When rolling on the month or
+     * Calendar::MONTH field, other fields like date might conflict and, need to be
+     * changed. For instance, rolling the month up on the date 01/31/96 will result in
+     * 02/29/96.  Rolling by a positive value always means rolling forward in time;
+     * e.g., rolling the year by +1 on "100 BC" will result in "99 BC", for Gregorian
+     * calendar. When rolling on the hour-in-day or Calendar::HOUR_OF_DAY field, it will
+     * roll the hour value in the range between 0 and 23, which is zero-based.
+     * <P>
+     * The only difference between roll() and add() is that roll() does not change
+     * the value of more significant fields when it reaches the minimum or maximum
+     * of its range, whereas add() does.
+     *
+     * @param field   The time field.
+     * @param amount  Indicates amount to roll.
+     * @param status  Output param set to success/failure code on exit. If any value
+     *                previously set in the time field is invalid, this will be set to
+     *                an error status.
+     * @deprecated ICU 2.6. Use roll(UCalendarDateFields field, int32_t amount, UErrorCode& status) instead.
+     */
+    virtual void roll(EDateFields field, int32_t amount, UErrorCode& status);
+
+    /**
+     * Time Field Rolling function. Rolls by the given amount on the given
+     * time field. For example, to roll the current date up by one day, call
+     * roll(Calendar::DATE, +1, status). When rolling on the month or
+     * Calendar::MONTH field, other fields like date might conflict and, need to be
+     * changed. For instance, rolling the month up on the date 01/31/96 will result in
+     * 02/29/96.  Rolling by a positive value always means rolling forward in time;
+     * e.g., rolling the year by +1 on "100 BC" will result in "99 BC", for Gregorian
+     * calendar. When rolling on the hour-in-day or Calendar::HOUR_OF_DAY field, it will
+     * roll the hour value in the range between 0 and 23, which is zero-based.
+     * <P>
+     * The only difference between roll() and add() is that roll() does not change
+     * the value of more significant fields when it reaches the minimum or maximum
+     * of its range, whereas add() does.
+     *
+     * @param field   The time field.
+     * @param amount  Indicates amount to roll.
+     * @param status  Output param set to success/failure code on exit. If any value
+     *                previously set in the time field is invalid, this will be set to
+     *                an error status.
+     * @stable ICU 2.6.
+     */
+    virtual void roll(UCalendarDateFields field, int32_t amount, UErrorCode& status);
+
+    /**
+     * Return the difference between the given time and the time this
+     * calendar object is set to.  If this calendar is set
+     * <em>before</em> the given time, the returned value will be
+     * positive.  If this calendar is set <em>after</em> the given
+     * time, the returned value will be negative.  The
+     * <code>field</code> parameter specifies the units of the return
+     * value.  For example, if <code>fieldDifference(when,
+     * Calendar::MONTH)</code> returns 3, then this calendar is set to
+     * 3 months before <code>when</code>, and possibly some addition
+     * time less than one month.
+     *
+     * <p>As a side effect of this call, this calendar is advanced
+     * toward <code>when</code> by the given amount.  That is, calling
+     * this method has the side effect of calling <code>add(field,
+     * n)</code>, where <code>n</code> is the return value.
+     *
+     * <p>Usage: To use this method, call it first with the largest
+     * field of interest, then with progressively smaller fields.  For
+     * example:
+     *
+     * <pre>
+     * int y = cal->fieldDifference(when, Calendar::YEAR, err);
+     * int m = cal->fieldDifference(when, Calendar::MONTH, err);
+     * int d = cal->fieldDifference(when, Calendar::DATE, err);</pre>
+     *
+     * computes the difference between <code>cal</code> and
+     * <code>when</code> in years, months, and days.
+     *
+     * <p>Note: <code>fieldDifference()</code> is
+     * <em>asymmetrical</em>.  That is, in the following code:
+     *
+     * <pre>
+     * cal->setTime(date1, err);
+     * int m1 = cal->fieldDifference(date2, Calendar::MONTH, err);
+     * int d1 = cal->fieldDifference(date2, Calendar::DATE, err);
+     * cal->setTime(date2, err);
+     * int m2 = cal->fieldDifference(date1, Calendar::MONTH, err);
+     * int d2 = cal->fieldDifference(date1, Calendar::DATE, err);</pre>
+     *
+     * one might expect that <code>m1 == -m2 && d1 == -d2</code>.
+     * However, this is not generally the case, because of
+     * irregularities in the underlying calendar system (e.g., the
+     * Gregorian calendar has a varying number of days per month).
+     *
+     * @param when the date to compare this calendar's time to
+     * @param field the field in which to compute the result
+     * @param status  Output param set to success/failure code on exit. If any value
+     *                previously set in the time field is invalid, this will be set to
+     *                an error status.
+     * @return the difference, either positive or negative, between
+     * this calendar's time and <code>when</code>, in terms of
+     * <code>field</code>.
+     * @deprecated ICU 2.6. Use fieldDifference(UDate when, UCalendarDateFields field, UErrorCode& status).
+     */
+    virtual int32_t fieldDifference(UDate when, EDateFields field, UErrorCode& status);
+
+    /**
+     * Return the difference between the given time and the time this
+     * calendar object is set to.  If this calendar is set
+     * <em>before</em> the given time, the returned value will be
+     * positive.  If this calendar is set <em>after</em> the given
+     * time, the returned value will be negative.  The
+     * <code>field</code> parameter specifies the units of the return
+     * value.  For example, if <code>fieldDifference(when,
+     * Calendar::MONTH)</code> returns 3, then this calendar is set to
+     * 3 months before <code>when</code>, and possibly some addition
+     * time less than one month.
+     *
+     * <p>As a side effect of this call, this calendar is advanced
+     * toward <code>when</code> by the given amount.  That is, calling
+     * this method has the side effect of calling <code>add(field,
+     * n)</code>, where <code>n</code> is the return value.
+     *
+     * <p>Usage: To use this method, call it first with the largest
+     * field of interest, then with progressively smaller fields.  For
+     * example:
+     *
+     * <pre>
+     * int y = cal->fieldDifference(when, Calendar::YEAR, err);
+     * int m = cal->fieldDifference(when, Calendar::MONTH, err);
+     * int d = cal->fieldDifference(when, Calendar::DATE, err);</pre>
+     *
+     * computes the difference between <code>cal</code> and
+     * <code>when</code> in years, months, and days.
+     *
+     * <p>Note: <code>fieldDifference()</code> is
+     * <em>asymmetrical</em>.  That is, in the following code:
+     *
+     * <pre>
+     * cal->setTime(date1, err);
+     * int m1 = cal->fieldDifference(date2, Calendar::MONTH, err);
+     * int d1 = cal->fieldDifference(date2, Calendar::DATE, err);
+     * cal->setTime(date2, err);
+     * int m2 = cal->fieldDifference(date1, Calendar::MONTH, err);
+     * int d2 = cal->fieldDifference(date1, Calendar::DATE, err);</pre>
+     *
+     * one might expect that <code>m1 == -m2 && d1 == -d2</code>.
+     * However, this is not generally the case, because of
+     * irregularities in the underlying calendar system (e.g., the
+     * Gregorian calendar has a varying number of days per month).
+     *
+     * @param when the date to compare this calendar's time to
+     * @param field the field in which to compute the result
+     * @param status  Output param set to success/failure code on exit. If any value
+     *                previously set in the time field is invalid, this will be set to
+     *                an error status.
+     * @return the difference, either positive or negative, between
+     * this calendar's time and <code>when</code>, in terms of
+     * <code>field</code>.
+     * @stable ICU 2.6.
+     */
+    virtual int32_t fieldDifference(UDate when, UCalendarDateFields field, UErrorCode& status);
+
+    /**
+     * Sets the calendar's time zone to be the one passed in. The Calendar takes ownership
+     * of the TimeZone; the caller is no longer responsible for deleting it.  If the
+     * given time zone is NULL, this function has no effect.
+     *
+     * @param value  The given time zone.
+     * @stable ICU 2.0
+     */
+    void adoptTimeZone(TimeZone* value);
+
+    /**
+     * Sets the calendar's time zone to be the same as the one passed in. The TimeZone
+     * passed in is _not_ adopted; the client is still responsible for deleting it.
+     *
+     * @param zone  The given time zone.
+     * @stable ICU 2.0
+     */
+    void setTimeZone(const TimeZone& zone);
+
+    /**
+     * Returns a reference to the time zone owned by this calendar. The returned reference
+     * is only valid until clients make another call to adoptTimeZone or setTimeZone,
+     * or this Calendar is destroyed.
+     *
+     * @return   The time zone object associated with this calendar.
+     * @stable ICU 2.0
+     */
+    const TimeZone& getTimeZone(void) const;
+
+    /**
+     * Returns the time zone owned by this calendar. The caller owns the returned object
+     * and must delete it when done.  After this call, the new time zone associated
+     * with this Calendar is the default TimeZone as returned by TimeZone::createDefault().
+     *
+     * @return   The time zone object which was associated with this calendar.
+     * @stable ICU 2.0
+     */
+    TimeZone* orphanTimeZone(void);
+
+    /**
+     * Queries if the current date for this Calendar is in Daylight Savings Time.
+     *
+     * @param status Fill-in parameter which receives the status of this operation.
+     * @return   True if the current date for this Calendar is in Daylight Savings Time,
+     *           false, otherwise.
+     * @stable ICU 2.0
+     */
+    virtual UBool inDaylightTime(UErrorCode& status) const = 0;
+
+    /**
+     * Specifies whether or not date/time interpretation is to be lenient. With lenient
+     * interpretation, a date such as "February 942, 1996" will be treated as being
+     * equivalent to the 941st day after February 1, 1996. With strict interpretation,
+     * such dates will cause an error when computing time from the time field values
+     * representing the dates.
+     *
+     * @param lenient  True specifies date/time interpretation to be lenient.
+     *
+     * @see            DateFormat#setLenient
+     * @stable ICU 2.0
+     */
+    void setLenient(UBool lenient);
+
+    /**
+     * Tells whether date/time interpretation is to be lenient.
+     *
+     * @return   True tells that date/time interpretation is to be lenient.
+     * @stable ICU 2.0
+     */
+    UBool isLenient(void) const;
+
+    /**
+     * Sets what the first day of the week is; e.g., Sunday in US, Monday in France.
+     *
+     * @param value  The given first day of the week.
+     * @deprecated ICU 2.6. Use setFirstDayOfWeek(UCalendarDaysOfWeek value) instead.
+     */
+    void setFirstDayOfWeek(EDaysOfWeek value);
+
+    /**
+     * Sets what the first day of the week is; e.g., Sunday in US, Monday in France.
+     *
+     * @param value  The given first day of the week.
+     * @stable ICU 2.6.
+     */
+    void setFirstDayOfWeek(UCalendarDaysOfWeek value);
+
+    /**
+     * Gets what the first day of the week is; e.g., Sunday in US, Monday in France.
+     *
+     * @return   The first day of the week.
+     * @deprecated ICU 2.6 use the overload with error code
+     */
+    EDaysOfWeek getFirstDayOfWeek(void) const;
+
+    /**
+     * Gets what the first day of the week is; e.g., Sunday in US, Monday in France.
+     *
+     * @param status error code
+     * @return   The first day of the week.
+     * @stable ICU 2.6
+     */
+    UCalendarDaysOfWeek getFirstDayOfWeek(UErrorCode &status) const;
+
+    /**
+     * Sets what the minimal days required in the first week of the year are; For
+     * example, if the first week is defined as one that contains the first day of the
+     * first month of a year, call the method with value 1. If it must be a full week,
+     * use value 7.
+     *
+     * @param value  The given minimal days required in the first week of the year.
+     * @stable ICU 2.0
+     */
+    void setMinimalDaysInFirstWeek(uint8_t value);
+
+    /**
+     * Gets what the minimal days required in the first week of the year are; e.g., if
+     * the first week is defined as one that contains the first day of the first month
+     * of a year, getMinimalDaysInFirstWeek returns 1. If the minimal days required must
+     * be a full week, getMinimalDaysInFirstWeek returns 7.
+     *
+     * @return   The minimal days required in the first week of the year.
+     * @stable ICU 2.0
+     */
+    uint8_t getMinimalDaysInFirstWeek(void) const;
+
+    /**
+     * Gets the minimum value for the given time field. e.g., for Gregorian
+     * DAY_OF_MONTH, 1.
+     *
+     * @param field  The given time field.
+     * @return       The minimum value for the given time field.
+     * @deprecated ICU 2.6. Use getMinimum(UCalendarDateFields field) instead.
+     */
+    virtual int32_t getMinimum(EDateFields field) const;
+
+    /**
+     * Gets the minimum value for the given time field. e.g., for Gregorian
+     * DAY_OF_MONTH, 1.
+     *
+     * @param field  The given time field.
+     * @return       The minimum value for the given time field.
+     * @stable ICU 2.6.
+     */
+    virtual int32_t getMinimum(UCalendarDateFields field) const;
+
+    /**
+     * Gets the maximum value for the given time field. e.g. for Gregorian DAY_OF_MONTH,
+     * 31.
+     *
+     * @param field  The given time field.
+     * @return       The maximum value for the given time field.
+     * @deprecated ICU 2.6. Use getMaximum(UCalendarDateFields field) instead.
+     */
+    virtual int32_t getMaximum(EDateFields field) const;
+
+    /**
+     * Gets the maximum value for the given time field. e.g. for Gregorian DAY_OF_MONTH,
+     * 31.
+     *
+     * @param field  The given time field.
+     * @return       The maximum value for the given time field.
+     * @stable ICU 2.6.
+     */
+    virtual int32_t getMaximum(UCalendarDateFields field) const;
+
+    /**
+     * Gets the highest minimum value for the given field if varies. Otherwise same as
+     * getMinimum(). For Gregorian, no difference.
+     *
+     * @param field  The given time field.
+     * @return       The highest minimum value for the given time field.
+     * @deprecated ICU 2.6. Use getGreatestMinimum(UCalendarDateFields field) instead.
+     */
+    virtual int32_t getGreatestMinimum(EDateFields field) const;
+
+    /**
+     * Gets the highest minimum value for the given field if varies. Otherwise same as
+     * getMinimum(). For Gregorian, no difference.
+     *
+     * @param field  The given time field.
+     * @return       The highest minimum value for the given time field.
+     * @stable ICU 2.6.
+     */
+    virtual int32_t getGreatestMinimum(UCalendarDateFields field) const;
+
+    /**
+     * Gets the lowest maximum value for the given field if varies. Otherwise same as
+     * getMaximum(). e.g., for Gregorian DAY_OF_MONTH, 28.
+     *
+     * @param field  The given time field.
+     * @return       The lowest maximum value for the given time field.
+     * @deprecated ICU 2.6. Use getLeastMaximum(UCalendarDateFields field) instead.
+     */
+    virtual int32_t getLeastMaximum(EDateFields field) const;
+
+    /**
+     * Gets the lowest maximum value for the given field if varies. Otherwise same as
+     * getMaximum(). e.g., for Gregorian DAY_OF_MONTH, 28.
+     *
+     * @param field  The given time field.
+     * @return       The lowest maximum value for the given time field.
+     * @stable ICU 2.6.
+     */
+    virtual int32_t getLeastMaximum(UCalendarDateFields field) const;
+
+    /**
+     * Return the minimum value that this field could have, given the current date.
+     * For the Gregorian calendar, this is the same as getMinimum() and getGreatestMinimum().
+     *
+     * The version of this function on Calendar uses an iterative algorithm to determine the
+     * actual minimum value for the field.  There is almost always a more efficient way to
+     * accomplish this (in most cases, you can simply return getMinimum()).  GregorianCalendar
+     * overrides this function with a more efficient implementation.
+     *
+     * @param field    the field to determine the minimum of
+     * @param status   Fill-in parameter which receives the status of this operation.
+     * @return         the minimum of the given field for the current date of this Calendar
+     * @deprecated ICU 2.6. Use getActualMinimum(UCalendarDateFields field, UErrorCode& status) instead.
+     */
+    int32_t getActualMinimum(EDateFields field, UErrorCode& status) const;
+
+    /**
+     * Return the minimum value that this field could have, given the current date.
+     * For the Gregorian calendar, this is the same as getMinimum() and getGreatestMinimum().
+     *
+     * The version of this function on Calendar uses an iterative algorithm to determine the
+     * actual minimum value for the field.  There is almost always a more efficient way to
+     * accomplish this (in most cases, you can simply return getMinimum()).  GregorianCalendar
+     * overrides this function with a more efficient implementation.
+     *
+     * @param field    the field to determine the minimum of
+     * @param status   Fill-in parameter which receives the status of this operation.
+     * @return         the minimum of the given field for the current date of this Calendar
+     * @stable ICU 2.6.
+     */
+    virtual int32_t getActualMinimum(UCalendarDateFields field, UErrorCode& status) const;
+
+    /**
+     * Return the maximum value that this field could have, given the current date.
+     * For example, with the date "Feb 3, 1997" and the DAY_OF_MONTH field, the actual
+     * maximum would be 28; for "Feb 3, 1996" it s 29.  Similarly for a Hebrew calendar,
+     * for some years the actual maximum for MONTH is 12, and for others 13.
+     *
+     * The version of this function on Calendar uses an iterative algorithm to determine the
+     * actual maximum value for the field.  There is almost always a more efficient way to
+     * accomplish this (in most cases, you can simply return getMaximum()).  GregorianCalendar
+     * overrides this function with a more efficient implementation.
+     *
+     * @param field    the field to determine the maximum of
+     * @param status   Fill-in parameter which receives the status of this operation.
+     * @return         the maximum of the given field for the current date of this Calendar
+     * @deprecated ICU 2.6. Use getActualMaximum(UCalendarDateFields field, UErrorCode& status) instead.
+     */
+    int32_t getActualMaximum(EDateFields field, UErrorCode& status) const;
+
+    /**
+     * Return the maximum value that this field could have, given the current date.
+     * For example, with the date "Feb 3, 1997" and the DAY_OF_MONTH field, the actual
+     * maximum would be 28; for "Feb 3, 1996" it s 29.  Similarly for a Hebrew calendar,
+     * for some years the actual maximum for MONTH is 12, and for others 13.
+     *
+     * The version of this function on Calendar uses an iterative algorithm to determine the
+     * actual maximum value for the field.  There is almost always a more efficient way to
+     * accomplish this (in most cases, you can simply return getMaximum()).  GregorianCalendar
+     * overrides this function with a more efficient implementation.
+     *
+     * @param field    the field to determine the maximum of
+     * @param status   Fill-in parameter which receives the status of this operation.
+     * @return         the maximum of the given field for the current date of this Calendar
+     * @stable ICU 2.6.
+     */
+    virtual int32_t getActualMaximum(UCalendarDateFields field, UErrorCode& status) const;
+
+    /**
+     * Gets the value for a given time field. Recalculate the current time field values
+     * if the time value has been changed by a call to setTime(). Return zero for unset
+     * fields if any fields have been explicitly set by a call to set(). To force a
+     * recomputation of all fields regardless of the previous state, call complete().
+     * This method is semantically const, but may alter the object in memory.
+     *
+     * @param field  The given time field.
+     * @param status Fill-in parameter which receives the status of the operation.
+     * @return       The value for the given time field, or zero if the field is unset,
+     *               and set() has been called for any other field.
+     * @deprecated ICU 2.6. Use get(UCalendarDateFields field, UErrorCode& status) instead.
+     */
+    int32_t get(EDateFields field, UErrorCode& status) const;
+
+    /**
+     * Gets the value for a given time field. Recalculate the current time field values
+     * if the time value has been changed by a call to setTime(). Return zero for unset
+     * fields if any fields have been explicitly set by a call to set(). To force a
+     * recomputation of all fields regardless of the previous state, call complete().
+     * This method is semantically const, but may alter the object in memory.
+     *
+     * @param field  The given time field.
+     * @param status Fill-in parameter which receives the status of the operation.
+     * @return       The value for the given time field, or zero if the field is unset,
+     *               and set() has been called for any other field.
+     * @stable ICU 2.6.
+     */
+    int32_t get(UCalendarDateFields field, UErrorCode& status) const;
+
+    /**
+     * Determines if the given time field has a value set. This can affect in the
+     * resolving of time in Calendar. Unset fields have a value of zero, by definition.
+     *
+     * @param field  The given time field.
+     * @return   True if the given time field has a value set; false otherwise.
+     * @deprecated ICU 2.6. Use isSet(UCalendarDateFields field) instead.
+     */
+    UBool isSet(EDateFields field) const;
+
+    /**
+     * Determines if the given time field has a value set. This can affect in the
+     * resolving of time in Calendar. Unset fields have a value of zero, by definition.
+     *
+     * @param field  The given time field.
+     * @return   True if the given time field has a value set; false otherwise.
+     * @stable ICU 2.6.
+     */
+    UBool isSet(UCalendarDateFields field) const;
+
+    /**
+     * Sets the given time field with the given value.
+     *
+     * @param field  The given time field.
+     * @param value  The value to be set for the given time field.
+     * @deprecated ICU 2.6. Use set(UCalendarDateFields field, int32_t value) instead.
+     */
+    void set(EDateFields field, int32_t value);
+
+    /**
+     * Sets the given time field with the given value.
+     *
+     * @param field  The given time field.
+     * @param value  The value to be set for the given time field.
+     * @stable ICU 2.6.
+     */
+    void set(UCalendarDateFields field, int32_t value);
+
+    /**
+     * Sets the values for the fields YEAR, MONTH, and DATE. Other field values are
+     * retained; call clear() first if this is not desired.
+     *
+     * @param year   The value used to set the YEAR time field.
+     * @param month  The value used to set the MONTH time field. Month value is 0-based.
+     *               e.g., 0 for January.
+     * @param date   The value used to set the DATE time field.
+     * @stable ICU 2.0
+     */
+    void set(int32_t year, int32_t month, int32_t date);
+
+    /**
+     * Sets the values for the fields YEAR, MONTH, DATE, HOUR_OF_DAY, and MINUTE. Other
+     * field values are retained; call clear() first if this is not desired.
+     *
+     * @param year    The value used to set the YEAR time field.
+     * @param month   The value used to set the MONTH time field. Month value is
+     *                0-based. E.g., 0 for January.
+     * @param date    The value used to set the DATE time field.
+     * @param hour    The value used to set the HOUR_OF_DAY time field.
+     * @param minute  The value used to set the MINUTE time field.
+     * @stable ICU 2.0
+     */
+    void set(int32_t year, int32_t month, int32_t date, int32_t hour, int32_t minute);
+
+    /**
+     * Sets the values for the fields YEAR, MONTH, DATE, HOUR_OF_DAY, MINUTE, and SECOND.
+     * Other field values are retained; call clear() first if this is not desired.
+     *
+     * @param year    The value used to set the YEAR time field.
+     * @param month   The value used to set the MONTH time field. Month value is
+     *                0-based. E.g., 0 for January.
+     * @param date    The value used to set the DATE time field.
+     * @param hour    The value used to set the HOUR_OF_DAY time field.
+     * @param minute  The value used to set the MINUTE time field.
+     * @param second  The value used to set the SECOND time field.
+     * @stable ICU 2.0
+     */
+    void set(int32_t year, int32_t month, int32_t date, int32_t hour, int32_t minute, int32_t second);
+
+    /**
+     * Clears the values of all the time fields, making them both unset and assigning
+     * them a value of zero. The field values will be determined during the next
+     * resolving of time into time fields.
+     * @stable ICU 2.0
+     */
+    void clear(void);
+
+    /**
+     * Clears the value in the given time field, both making it unset and assigning it a
+     * value of zero. This field value will be determined during the next resolving of
+     * time into time fields.
+     *
+     * @param field  The time field to be cleared.
+     * @deprecated ICU 2.6. Use clear(UCalendarDateFields field) instead.
+     */
+    void clear(EDateFields field);
+
+    /**
+     * Clears the value in the given time field, both making it unset and assigning it a
+     * value of zero. This field value will be determined during the next resolving of
+     * time into time fields.
+     *
+     * @param field  The time field to be cleared.
+     * @stable ICU 2.6.
+     */
+    void clear(UCalendarDateFields field);
+
+    /**
+     * Returns a unique class ID POLYMORPHICALLY. Pure virtual method. This method is to
+     * implement a simple version of RTTI, since not all C++ compilers support genuine
+     * RTTI. Polymorphic operator==() and clone() methods call this method.
+     * <P>
+     * Concrete subclasses of Calendar must implement getDynamicClassID() and also a
+     * static method and data member:
+     *
+     *      static UClassID getStaticClassID() { return (UClassID)&amp;fgClassID; }
+     *      static char fgClassID;
+     *
+     * @return   The class ID for this object. All objects of a given class have the
+     *           same class ID. Objects of other classes have different class IDs.
+     * @stable ICU 2.0
+     */
+    virtual UClassID getDynamicClassID(void) const = 0;
+
+    /**
+     * Returns the resource key string used for this calendar type.
+     * For example, prepending "Eras_" to this string could return "Eras_japanese"
+     * or "Eras_gregorian".
+     *
+     * @returns static string, for example, "gregorian" or "japanese"
+     * @internal
+     */
+    virtual const char * getType() const = 0;
+
+protected:
+
+     /**
+      * Constructs a Calendar with the default time zone as returned by
+      * TimeZone::createInstance(), and the default locale.
+      *
+      * @param success  Indicates the status of Calendar object construction. Returns
+      *                 U_ZERO_ERROR if constructed successfully.
+     * @stable ICU 2.0
+      */
+    Calendar(UErrorCode& success);
+
+    /**
+     * Copy constructor
+     *
+     * @param source    Calendar object to be copied from
+     * @stable ICU 2.0
+     */
+    Calendar(const Calendar& source);
+
+    /**
+     * Default assignment operator
+     *
+     * @param right    Calendar object to be copied
+     * @stable ICU 2.0
+     */
+    Calendar& operator=(const Calendar& right);
+
+    /**
+     * Constructs a Calendar with the given time zone and locale. Clients are no longer
+     * responsible for deleting the given time zone object after it's adopted.
+     *
+     * @param zone     The given time zone.
+     * @param aLocale  The given locale.
+     * @param success  Indicates the status of Calendar object construction. Returns
+     *                 U_ZERO_ERROR if constructed successfully.
+     * @stable ICU 2.0
+     */
+    Calendar(TimeZone* zone, const Locale& aLocale, UErrorCode& success);
+
+    /**
+     * Constructs a Calendar with the given time zone and locale.
+     *
+     * @param zone     The given time zone.
+     * @param aLocale  The given locale.
+     * @param success  Indicates the status of Calendar object construction. Returns
+     *                 U_ZERO_ERROR if constructed successfully.
+     * @stable ICU 2.0
+     */
+    Calendar(const TimeZone& zone, const Locale& aLocale, UErrorCode& success);
+
+    /**
+     * Converts Calendar's time field values to GMT as milliseconds.
+     *
+     * @param status  Output param set to success/failure code on exit. If any value
+     *                previously set in the time field is invalid or restricted by
+     *                leniency, this will be set to an error status.
+     * @stable ICU 2.0
+     */
+    virtual void computeTime(UErrorCode& status);
+
+    /**
+     * Converts GMT as milliseconds to time field values. This allows you to sync up the
+     * time field values with a new time that is set for the calendar.  This method
+     * does NOT recompute the time first; to recompute the time, then the fields, use
+     * the method complete().
+     *
+     * @param status  Output param set to success/failure code on exit. If any value
+     *                previously set in the time field is invalid or restricted by
+     *                leniency, this will be set to an error status.
+     * @stable ICU 2.0
+     */
+    virtual void computeFields(UErrorCode& status);
+
+    /**
+     * Gets this Calendar's current time as a long.
+     *
+     * @param status  Output param set to success/failure code on exit. If any value
+     *                previously set in the time field is invalid or restricted by
+     *                leniency, this will be set to an error status.
+     * @return the current time as UTC milliseconds from the epoch.
+     * @stable ICU 2.0
+     */
+    double getTimeInMillis(UErrorCode& status) const;
+
+    /**
+     * Sets this Calendar's current time from the given long value.
+     * @param millis  the new time in UTC milliseconds from the epoch.
+     * @param status  Output param set to success/failure code on exit. If any value
+     *                previously set in the time field is invalid or restricted by
+     *                leniency, this will be set to an error status.
+     * @stable ICU 2.0
+     */
+    void setTimeInMillis( double millis, UErrorCode& status );
+
+    /**
+     * Recomputes the current time from currently set fields, and then fills in any
+     * unset fields in the time field list.
+     *
+     * @param status  Output param set to success/failure code on exit. If any value
+     *                previously set in the time field is invalid or restricted by
+     *                leniency, this will be set to an error status.
+     * @stable ICU 2.0
+     */
+    void complete(UErrorCode& status);
+
+    /**
+     * Gets the value for a given time field. Subclasses can use this function to get
+     * field values without forcing recomputation of time.
+     *
+     * @param field  The given time field.
+     * @return       The value for the given time field.
+     * @deprecated ICU 2.6. Use internalGet(UCalendarDateFields field) instead.
+     */
+    inline int32_t internalGet(EDateFields field) const {return fFields[field];}
+
+    /**
+     * Gets the value for a given time field. Subclasses can use this function to get
+     * field values without forcing recomputation of time. If the field's stamp is UNSET,
+     * the defaultValue is used.
+     *
+     * @param field  The given time field.
+     * @param defaultValue a default value used if the field is unset.
+     * @return       The value for the given time field.
+     * @internal
+     */
+    inline int32_t internalGet(UCalendarDateFields field, int32_t defaultValue) const {return fStamp[field]>kUnset ? fFields[field] : defaultValue;}
+
+    /**
+     * Gets the value for a given time field. Subclasses can use this function to get
+     * field values without forcing recomputation of time.
+     *
+     * @param field  The given time field.
+     * @return       The value for the given time field.
+     * @internal
+     */
+    inline int32_t internalGet(UCalendarDateFields field) const {return fFields[field];}
+
+    /**
+     * Sets the value for a given time field.  This is a fast internal method for
+     * subclasses.  It does not affect the areFieldsInSync, isTimeSet, or areAllFieldsSet
+     * flags.
+     *
+     * @param field    The given time field.
+     * @param value    The value for the given time field.
+     * @deprecated ICU 2.6. Use internalSet(UCalendarDateFields field, int32_t value) instead.
+     */
+    void internalSet(EDateFields field, int32_t value);
+
+    /**
+     * Sets the value for a given time field.  This is a fast internal method for
+     * subclasses.  It does not affect the areFieldsInSync, isTimeSet, or areAllFieldsSet
+     * flags.
+     *
+     * @param field    The given time field.
+     * @param value    The value for the given time field.
+     * @stable ICU 2.6.
+     */
+    inline void internalSet(UCalendarDateFields field, int32_t value);
+
+    /**
+     * Prepare this calendar for computing the actual minimum or maximum.
+     * This method modifies this calendar's fields; it is called on a
+     * temporary calendar.
+     * @internal
+     */
+    virtual void prepareGetActual(UCalendarDateFields field, UBool isMinimum, UErrorCode &status);
+
+    /**
+     * Limit enums. Not in sync with UCalendarLimitType (refers to internal fields).
+     * @internal
+     */
+    enum ELimitType {
+      UCAL_LIMIT_MINIMUM = 0,
+      UCAL_LIMIT_GREATEST_MINIMUM,
+      UCAL_LIMIT_LEAST_MAXIMUM,
+      UCAL_LIMIT_MAXIMUM,
+      UCAL_LIMIT_COUNT
+    };
+
+    /**
+     * Subclass API for defining limits of different types.
+     * Subclasses must implement this method to return limits for the
+     * following fields:
+     *
+     * <pre>UCAL_ERA
+     * UCAL_YEAR
+     * UCAL_MONTH
+     * UCAL_WEEK_OF_YEAR
+     * UCAL_WEEK_OF_MONTH
+     * UCAL_DATE (DAY_OF_MONTH on Java)
+     * UCAL_DAY_OF_YEAR
+     * UCAL_DAY_OF_WEEK_IN_MONTH
+     * UCAL_YEAR_WOY
+     * UCAL_EXTENDED_YEAR</pre>
+     *
+     * @param field one of the above field numbers
+     * @param limitType one of <code>MINIMUM</code>, <code>GREATEST_MINIMUM</code>,
+     * <code>LEAST_MAXIMUM</code>, or <code>MAXIMUM</code>
+     * @internal
+     */
+    virtual int32_t handleGetLimit(UCalendarDateFields field, ELimitType limitType) const = 0;
+
+    /**
+     * Return a limit for a field.
+     * @param field the field, from <code>0..UCAL_MAX_FIELD</code>
+     * @param limitType the type specifier for the limit
+     * @see #ELimitType
+     * @internal
+     */
+    virtual int32_t getLimit(UCalendarDateFields field, ELimitType limitType) const;
+
+
+    /**
+     * Return the Julian day number of day before the first day of the
+     * given month in the given extended year.  Subclasses should override
+     * this method to implement their calendar system.
+     * @param eyear the extended year
+     * @param month the zero-based month, or 0 if useMonth is false
+     * @param useMonth if false, compute the day before the first day of
+     * the given year, otherwise, compute the day before the first day of
+     * the given month
+     * @return the Julian day number of the day before the first
+     * day of the given month and year
+     * @internal
+     */
+    virtual int32_t handleComputeMonthStart(int32_t eyear, int32_t month,
+                                                   UBool useMonth) const  = 0;
+
+    /**
+     * Return the number of days in the given month of the given extended
+     * year of this calendar system.  Subclasses should override this
+     * method if they can provide a more correct or more efficient
+     * implementation than the default implementation in Calendar.
+     * @internal
+     */
+    virtual int32_t handleGetMonthLength(int32_t extendedYear, int32_t month) const ;
+
+    /**
+     * Return the number of days in the given extended year of this
+     * calendar system.  Subclasses should override this method if they can
+     * provide a more correct or more efficient implementation than the
+     * default implementation in Calendar.
+     * @stable ICU 2.0
+     */
+    virtual int32_t handleGetYearLength(int32_t eyear) const;
+
+
+    /**
+     * Return the extended year defined by the current fields.  This will
+     * use the UCAL_EXTENDED_YEAR field or the UCAL_YEAR and supra-year fields (such
+     * as UCAL_ERA) specific to the calendar system, depending on which set of
+     * fields is newer.
+     * @return the extended year
+     * @internal
+     */
+    virtual int32_t handleGetExtendedYear() = 0;
+
+    /**
+     * Subclasses may override this.  This method calls
+     * handleGetMonthLength() to obtain the calendar-specific month
+     * length.
+     * @param bestField which field to use to calculate the date
+     * @return julian day specified by calendar fields.
+     * @internal
+     */
+    virtual int32_t handleComputeJulianDay(UCalendarDateFields bestField);
+
+    /**
+     * Subclasses must override this to convert from week fields
+     * (YEAR_WOY and WEEK_OF_YEAR) to an extended year in the case
+     * where YEAR, EXTENDED_YEAR are not set.
+     * The Calendar implementation assumes yearWoy is in extended gregorian form
+     * @internal
+     * @return the extended year, UCAL_EXTENDED_YEAR
+     */
+    virtual int32_t handleGetExtendedYearFromWeekFields(int32_t yearWoy, int32_t woy);
+
+    /**
+     * Compute the Julian day from fields.  Will determine whether to use
+     * the JULIAN_DAY field directly, or other fields.
+     * @return the julian day
+     * @internal
+     */
+    int32_t computeJulianDay();
+
+    /**
+     * Compute the milliseconds in the day from the fields.  This is a
+     * value from 0 to 23:59:59.999 inclusive, unless fields are out of
+     * range, in which case it can be an arbitrary value.  This value
+     * reflects local zone wall time.
+     * @internal
+     */
+    int32_t computeMillisInDay();
+
+    /**
+     * This method can assume EXTENDED_YEAR has been set.
+     * @param millis milliseconds of the date fields
+     * @param millisInDay milliseconds of the time fields; may be out
+     * or range.
+     * @param ec Output param set to failure code on function return
+     *          when this function fails.
+     * @internal
+     */
+    int32_t computeZoneOffset(double millis, int32_t millisInDay, UErrorCode &ec);
+
+
+    /**
+     * Determine the best stamp in a range.
+     * @param start first enum to look at
+     * @param end last enum to look at
+     * @param bestSoFar stamp prior to function call
+     * @return the stamp value of the best stamp
+     * @internal
+     */
+    int32_t newestStamp(UCalendarDateFields start, UCalendarDateFields end, int32_t bestSoFar) const;
+
+    /**
+     * Values for field resolution tables
+     * @see #resolveFields
+     * @internal
+     */
+    enum {
+      /** Marker for end of resolve set (row or group). */
+      kResolveSTOP = -1,
+      /** Value to be bitwised "ORed" against resolve table field values for remapping.  Example: (UCAL_DATE | kResolveRemap) in 1st column will cause 'UCAL_DATE' to be returned, but will not examine the value of UCAL_DATE.  */
+      kResolveRemap = 32
+    };
+
+    /**
+     * Precedence table for Dates
+     * @see #resolveFields
+     * @internal
+     */
+    static const UFieldResolutionTable kDatePrecedence[];
+
+    /**
+     * Precedence table for Year
+     * @see #resolveFields
+     * @internal
+     */
+    static const UFieldResolutionTable kYearPrecedence[];
+
+    /**
+     * Precedence table for Day of Week
+     * @see #resolveFields
+     * @internal
+     */
+    static const UFieldResolutionTable kDOWPrecedence[];
+
+    /**
+     * Given a precedence table, return the newest field combination in
+     * the table, or UCAL_FIELD_COUNT if none is found.
+     *
+     * <p>The precedence table is a 3-dimensional array of integers.  It
+     * may be thought of as an array of groups.  Each group is an array of
+     * lines.  Each line is an array of field numbers.  Within a line, if
+     * all fields are set, then the time stamp of the line is taken to be
+     * the stamp of the most recently set field.  If any field of a line is
+     * unset, then the line fails to match.  Within a group, the line with
+     * the newest time stamp is selected.  The first field of the line is
+     * returned to indicate which line matched.
+     *
+     * <p>In some cases, it may be desirable to map a line to field that
+     * whose stamp is NOT examined.  For example, if the best field is
+     * DAY_OF_WEEK then the DAY_OF_WEEK_IN_MONTH algorithm may be used.  In
+     * order to do this, insert the value <code>kResolveRemap | F</code> at
+     * the start of the line, where <code>F</code> is the desired return
+     * field value.  This field will NOT be examined; it only determines
+     * the return value if the other fields in the line are the newest.
+     *
+     * <p>If all lines of a group contain at least one unset field, then no
+     * line will match, and the group as a whole will fail to match.  In
+     * that case, the next group will be processed.  If all groups fail to
+     * match, then UCAL_FIELD_COUNT is returned.
+     * @internal
+     */
+    UCalendarDateFields resolveFields(const UFieldResolutionTable *precedenceTable);
+
+
+    /**
+     * @internal
+     */
+    virtual const UFieldResolutionTable* getFieldResolutionTable() const;
+
+    /**
+     * Return the field that is newer, either defaultField, or
+     * alternateField.  If neither is newer or neither is set, return defaultField.
+     * @internal
+     */
+    UCalendarDateFields newerField(UCalendarDateFields defaultField, UCalendarDateFields alternateField) const;
+
+
+private:
+    /**
+     * Helper function for calculating limits by trial and error
+     * @param field The field being investigated
+     * @param startValue starting (least max) value of field
+     * @param endValue ending (greatest max) value of field
+     * @param status return type
+     * @internal
+     */
+    int32_t getActualHelper(UCalendarDateFields field, int32_t startValue, int32_t endValue, UErrorCode &status) const;
+
+
+protected:
+    /**
+     * The flag which indicates if the current time is set in the calendar.
+     * @stable ICU 2.0
+     */
+    UBool      fIsTimeSet;
+
+    /**
+     * True if the fields are in sync with the currently set time of this Calendar.
+     * If false, then the next attempt to get the value of a field will
+     * force a recomputation of all fields from the current value of the time
+     * field.
+     * <P>
+     * This should really be named areFieldsInSync, but the old name is retained
+     * for backward compatibility.
+     * @stable ICU 2.0
+     */
+    UBool      fAreFieldsSet;
+
+    /**
+     * True if all of the fields have been set.  This is initially false, and set to
+     * true by computeFields().
+     * @stable ICU 2.0
+     */
+    UBool      fAreAllFieldsSet;
+
+    /**
+     * True if all fields have been virtually set, but have not yet been
+     * computed.  This occurs only in setTimeInMillis().  A calendar set
+     * to this state will compute all fields from the time if it becomes
+     * necessary, but otherwise will delay such computation.
+     * @stable ICU 3.0
+     */
+    UBool fAreFieldsVirtuallySet;
+
+    /**
+     * Get the current time without recomputing.
+     *
+     * @return     the current time without recomputing.
+     * @stable ICU 2.0
+     */
+    UDate        internalGetTime(void) const     { return fTime; }
+
+    /**
+     * Set the current time without affecting flags or fields.
+     *
+     * @param time    The time to be set
+     * @return        the current time without recomputing.
+     * @stable ICU 2.0
+     */
+    void        internalSetTime(UDate time)     { fTime = time; }
+
+    /**
+     * The time fields containing values into which the millis is computed.
+     * @stable ICU 2.0
+     */
+    int32_t     fFields[UCAL_FIELD_COUNT];
+
+    /**
+     * The flags which tell if a specified time field for the calendar is set.
+     * @deprecated ICU 2.8 use (fStamp[n]!=kUnset)
+     */
+    UBool      fIsSet[UCAL_FIELD_COUNT];
+
+    /** Special values of stamp[]
+     * @stable ICU 2.0
+     */
+    enum {
+        kUnset                 = 0,
+        kInternallySet,
+        kMinimumUserStamp
+    };
+
+    /**
+     * Pseudo-time-stamps which specify when each field was set. There
+     * are two special values, UNSET and INTERNALLY_SET. Values from
+     * MINIMUM_USER_SET to Integer.MAX_VALUE are legal user set values.
+     * @stable ICU 2.0
+     */
+    int32_t        fStamp[UCAL_FIELD_COUNT];
+
+    /**
+     * Subclasses may override this method to compute several fields
+     * specific to each calendar system.  These are:
+     *
+     * <ul><li>ERA
+     * <li>YEAR
+     * <li>MONTH
+     * <li>DAY_OF_MONTH
+     * <li>DAY_OF_YEAR
+     * <li>EXTENDED_YEAR</ul>
+     *
+     * Subclasses can refer to the DAY_OF_WEEK and DOW_LOCAL fields, which
+     * will be set when this method is called.  Subclasses can also call
+     * the getGregorianXxx() methods to obtain Gregorian calendar
+     * equivalents for the given Julian day.
+     *
+     * <p>In addition, subclasses should compute any subclass-specific
+     * fields, that is, fields from BASE_FIELD_COUNT to
+     * getFieldCount() - 1.
+     *
+     * <p>The default implementation in <code>Calendar</code> implements
+     * a pure proleptic Gregorian calendar.
+     * @internal
+     */
+    virtual void handleComputeFields(int32_t julianDay, UErrorCode &status);
+
+    /**
+     * Return the extended year on the Gregorian calendar as computed by
+     * <code>computeGregorianFields()</code>.
+     * @internal
+     */
+    int32_t getGregorianYear() const {
+        return fGregorianYear;
+    }
+
+    /**
+     * Return the month (0-based) on the Gregorian calendar as computed by
+     * <code>computeGregorianFields()</code>.
+     * @internal
+     */
+    int32_t getGregorianMonth() const {
+        return fGregorianMonth;
+    }
+
+    /**
+     * Return the day of year (1-based) on the Gregorian calendar as
+     * computed by <code>computeGregorianFields()</code>.
+     * @internal
+     */
+    int32_t getGregorianDayOfYear() const {
+        return fGregorianDayOfYear;
+    }
+
+    /**
+     * Return the day of month (1-based) on the Gregorian calendar as
+     * computed by <code>computeGregorianFields()</code>.
+     * @internal
+     */
+    int32_t getGregorianDayOfMonth() const {
+      return fGregorianDayOfMonth;
+    }
+
+    /**
+     * Called by computeJulianDay.  Returns the default month (0-based) for the year,
+     * taking year and era into account.  Defaults to 0 for Gregorian, which doesn't care.
+     * @internal
+     * @internal
+     */
+    virtual int32_t getDefaultMonthInYear() ;
+
+
+    /**
+     * Called by computeJulianDay.  Returns the default day (1-based) for the month,
+     * taking currently-set year and era into account.  Defaults to 1 for Gregorian.
+     * @internal
+     */
+    virtual int32_t getDefaultDayInMonth(int32_t /*month*/);
+
+    //-------------------------------------------------------------------------
+    // Protected utility methods for use by subclasses.  These are very handy
+    // for implementing add, roll, and computeFields.
+    //-------------------------------------------------------------------------
+
+    /**
+     * Adjust the specified field so that it is within
+     * the allowable range for the date to which this calendar is set.
+     * For example, in a Gregorian calendar pinning the {@link #UCalendarDateFields DAY_OF_MONTH}
+     * field for a calendar set to April 31 would cause it to be set
+     * to April 30.
+     * <p>
+     * <b>Subclassing:</b>
+     * <br>
+     * This utility method is intended for use by subclasses that need to implement
+     * their own overrides of {@link #roll roll} and {@link #add add}.
+     * <p>
+     * <b>Note:</b>
+     * <code>pinField</code> is implemented in terms of
+     * {@link #getActualMinimum getActualMinimum}
+     * and {@link #getActualMaximum getActualMaximum}.  If either of those methods uses
+     * a slow, iterative algorithm for a particular field, it would be
+     * unwise to attempt to call <code>pinField</code> for that field.  If you
+     * really do need to do so, you should override this method to do
+     * something more efficient for that field.
+     * <p>
+     * @param field The calendar field whose value should be pinned.
+     * @param status Output param set to failure code on function return
+     *          when this function fails.
+     *
+     * @see #getActualMinimum
+     * @see #getActualMaximum
+     * @stable ICU 2.0
+     */
+    virtual void pinField(UCalendarDateFields field, UErrorCode& status);
+
+    /**
+     * Return the week number of a day, within a period. This may be the week number in
+     * a year or the week number in a month. Usually this will be a value >= 1, but if
+     * some initial days of the period are excluded from week 1, because
+     * {@link #getMinimalDaysInFirstWeek getMinimalDaysInFirstWeek} is > 1, then
+     * the week number will be zero for those
+     * initial days. This method requires the day number and day of week for some
+     * known date in the period in order to determine the day of week
+     * on the desired day.
+     * <p>
+     * <b>Subclassing:</b>
+     * <br>
+     * This method is intended for use by subclasses in implementing their
+     * {@link #computeTime computeTime} and/or {@link #computeFields computeFields} methods.
+     * It is often useful in {@link #getActualMinimum getActualMinimum} and
+     * {@link #getActualMaximum getActualMaximum} as well.
+     * <p>
+     * This variant is handy for computing the week number of some other
+     * day of a period (often the first or last day of the period) when its day
+     * of the week is not known but the day number and day of week for some other
+     * day in the period (e.g. the current date) <em>is</em> known.
+     * <p>
+     * @param desiredDay    The {@link #UCalendarDateFields DAY_OF_YEAR} or
+     *              {@link #UCalendarDateFields DAY_OF_MONTH} whose week number is desired.
+     *              Should be 1 for the first day of the period.
+     *
+     * @param dayOfPeriod   The {@link #UCalendarDateFields DAY_OF_YEAR}
+     *              or {@link #UCalendarDateFields DAY_OF_MONTH} for a day in the period whose
+     *              {@link #UCalendarDateFields DAY_OF_WEEK} is specified by the
+     *              <code>knownDayOfWeek</code> parameter.
+     *              Should be 1 for first day of period.
+     *
+     * @param dayOfWeek  The {@link #UCalendarDateFields DAY_OF_WEEK} for the day
+     *              corresponding to the <code>knownDayOfPeriod</code> parameter.
+     *              1-based with 1=Sunday.
+     *
+     * @return      The week number (one-based), or zero if the day falls before
+     *              the first week because
+     *              {@link #getMinimalDaysInFirstWeek getMinimalDaysInFirstWeek}
+     *              is more than one.
+     *
+     * @stable ICU 2.8
+     */
+    int32_t weekNumber(int32_t desiredDay, int32_t dayOfPeriod, int32_t dayOfWeek);
+
+
+    /**
+     * Return the week number of a day, within a period. This may be the week number in
+     * a year, or the week number in a month. Usually this will be a value >= 1, but if
+     * some initial days of the period are excluded from week 1, because
+     * {@link #getMinimalDaysInFirstWeek getMinimalDaysInFirstWeek} is > 1,
+     * then the week number will be zero for those
+     * initial days. This method requires the day of week for the given date in order to
+     * determine the result.
+     * <p>
+     * <b>Subclassing:</b>
+     * <br>
+     * This method is intended for use by subclasses in implementing their
+     * {@link #computeTime computeTime} and/or {@link #computeFields computeFields} methods.
+     * It is often useful in {@link #getActualMinimum getActualMinimum} and
+     * {@link #getActualMaximum getActualMaximum} as well.
+     * <p>
+     * @param dayOfPeriod   The {@link #UCalendarDateFields DAY_OF_YEAR} or
+     *                      {@link #UCalendarDateFields DAY_OF_MONTH} whose week number is desired.
+     *                      Should be 1 for the first day of the period.
+     *
+     * @param dayOfWeek     The {@link #UCalendarDateFields DAY_OF_WEEK} for the day
+     *                      corresponding to the <code>dayOfPeriod</code> parameter.
+     *                      1-based with 1=Sunday.
+     *
+     * @return      The week number (one-based), or zero if the day falls before
+     *              the first week because
+     *              {@link #getMinimalDaysInFirstWeek getMinimalDaysInFirstWeek}
+     *              is more than one.
+     * @internal
+     */
+    inline int32_t weekNumber(int32_t dayOfPeriod, int32_t dayOfWeek);
+
+    /**
+     * returns the local DOW, valid range 0..6
+     * @internal
+     */
+    int32_t getLocalDOW();
+
+private:
+
+    /**
+     * The next available value for fStamp[]
+     */
+    int32_t fNextStamp;// = MINIMUM_USER_STAMP;
+
+    /**
+     * The current time set for the calendar.
+     */
+    UDate        fTime;
+
+    /**
+     * @see   #setLenient
+     */
+    UBool      fLenient;
+
+    /**
+     * Time zone affects the time calculation done by Calendar. Calendar subclasses use
+     * the time zone data to produce the local time.
+     */
+    TimeZone*   fZone;
+
+    /**
+     * Both firstDayOfWeek and minimalDaysInFirstWeek are locale-dependent. They are
+     * used to figure out the week count for a specific date for a given locale. These
+     * must be set when a Calendar is constructed. For example, in US locale,
+     * firstDayOfWeek is SUNDAY; minimalDaysInFirstWeek is 1. They are used to figure
+     * out the week count for a specific date for a given locale. These must be set when
+     * a Calendar is constructed.
+     */
+    UCalendarDaysOfWeek fFirstDayOfWeek;
+    uint8_t     fMinimalDaysInFirstWeek;
+
+    /**
+     * Sets firstDayOfWeek and minimalDaysInFirstWeek. Called at Calendar construction
+     * time.
+     *
+     * @param desiredLocale  The given locale.
+     * @param type           The calendar type identifier, e.g: gregorian, buddhist, etc.
+     * @param success        Indicates the status of setting the week count data from
+     *                       the resource for the given locale. Returns U_ZERO_ERROR if
+     *                       constructed successfully.
+     */
+    void        setWeekCountData(const Locale& desiredLocale, const char *type, UErrorCode& success);
+
+    /**
+     * Recompute the time and update the status fields isTimeSet
+     * and areFieldsSet.  Callers should check isTimeSet and only
+     * call this method if isTimeSet is false.
+     *
+     * @param status  Output param set to success/failure code on exit. If any value
+     *                previously set in the time field is invalid or restricted by
+     *                leniency, this will be set to an error status.
+     */
+    void updateTime(UErrorCode& status);
+
+    /**
+     * The Gregorian year, as computed by computeGregorianFields() and
+     * returned by getGregorianYear().
+     * @see #computeGregorianFields
+     */
+    int32_t fGregorianYear;
+
+    /**
+     * The Gregorian month, as computed by computeGregorianFields() and
+     * returned by getGregorianMonth().
+     * @see #computeGregorianFields
+     */
+    int32_t fGregorianMonth;
+
+    /**
+     * The Gregorian day of the year, as computed by
+     * computeGregorianFields() and returned by getGregorianDayOfYear().
+     * @see #computeGregorianFields
+     */
+    int32_t fGregorianDayOfYear;
+
+    /**
+     * The Gregorian day of the month, as computed by
+     * computeGregorianFields() and returned by getGregorianDayOfMonth().
+     * @see #computeGregorianFields
+     */
+    int32_t fGregorianDayOfMonth;
+
+    /* calculations */
+
+    /**
+     * Compute the Gregorian calendar year, month, and day of month from
+     * the given Julian day.  These values are not stored in fields, but in
+     * member variables gregorianXxx.  Also compute the DAY_OF_WEEK and
+     * DOW_LOCAL fields.
+     */
+    void computeGregorianAndDOWFields(int32_t julianDay, UErrorCode &ec);
+
+	protected:
+
+    /**
+     * Compute the Gregorian calendar year, month, and day of month from the
+     * Julian day.  These values are not stored in fields, but in member
+     * variables gregorianXxx.  They are used for time zone computations and by
+     * subclasses that are Gregorian derivatives.  Subclasses may call this
+     * method to perform a Gregorian calendar millis->fields computation.
+     * To perform a Gregorian calendar fields->millis computation, call
+     * computeGregorianMonthStart().
+     * @see #computeGregorianMonthStart
+     */
+    void computeGregorianFields(int32_t julianDay, UErrorCode &ec);
+
+	private:
+
+    /**
+     * Compute the fields WEEK_OF_YEAR, YEAR_WOY, WEEK_OF_MONTH,
+     * DAY_OF_WEEK_IN_MONTH, and DOW_LOCAL from EXTENDED_YEAR, YEAR,
+     * DAY_OF_WEEK, and DAY_OF_YEAR.  The latter fields are computed by the
+     * subclass based on the calendar system.
+     *
+     * <p>The YEAR_WOY field is computed simplistically.  It is equal to YEAR
+     * most of the time, but at the year boundary it may be adjusted to YEAR-1
+     * or YEAR+1 to reflect the overlap of a week into an adjacent year.  In
+     * this case, a simple increment or decrement is performed on YEAR, even
+     * though this may yield an invalid YEAR value.  For instance, if the YEAR
+     * is part of a calendar system with an N-year cycle field CYCLE, then
+     * incrementing the YEAR may involve incrementing CYCLE and setting YEAR
+     * back to 0 or 1.  This is not handled by this code, and in fact cannot be
+     * simply handled without having subclasses define an entire parallel set of
+     * fields for fields larger than or equal to a year.  This additional
+     * complexity is not warranted, since the intention of the YEAR_WOY field is
+     * to support ISO 8601 notation, so it will typically be used with a
+     * proleptic Gregorian calendar, which has no field larger than a year.
+     */
+    void computeWeekFields(UErrorCode &ec);
+
+
+    /**
+     * Ensure that each field is within its valid range by calling {@link
+     * #validateField(int, int&)} on each field that has been set.  This method
+     * should only be called if this calendar is not lenient.
+     * @see #isLenient
+     * @see #validateField(int, int&)
+     * @internal
+     */
+    void validateFields(UErrorCode &status);
+
+    /**
+     * Validate a single field of this calendar.  Subclasses should
+     * override this method to validate any calendar-specific fields.
+     * Generic fields can be handled by
+     * <code>Calendar.validateField()</code>.
+     * @see #validateField(int, int, int, int&)
+     * @internal
+     */
+    virtual void validateField(UCalendarDateFields field, UErrorCode &status);
+
+    /**
+     * Validate a single field of this calendar given its minimum and
+     * maximum allowed value.  If the field is out of range,
+     * <code>U_ILLEGAL_ARGUMENT_ERROR</code> will be set.  Subclasses may
+     * use this method in their implementation of {@link
+     * #validateField(int, int&)}.
+     * @internal
+     */
+    void validateField(UCalendarDateFields field, int32_t min, int32_t max, UErrorCode& status);
+
+ protected:
+    /**
+     * Convert a quasi Julian date to the day of the week. The Julian date used here is
+     * not a true Julian date, since it is measured from midnight, not noon. Return
+     * value is one-based.
+     *
+     * @param julian  The given Julian date number.
+     * @return   Day number from 1..7 (SUN..SAT).
+     * @internal
+     */
+    static uint8_t julianDayToDayOfWeek(double julian);
+
+ private:
+    char validLocale[ULOC_FULLNAME_CAPACITY];
+    char actualLocale[ULOC_FULLNAME_CAPACITY];
+
+ public:
+#if !UCONFIG_NO_SERVICE
+    /**
+     * INTERNAL FOR 2.6 --  Registration.
+     */
+
+    /**
+     * Return a StringEnumeration over the locales available at the time of the call,
+     * including registered locales.
+     * @return a StringEnumeration over the locales available at the time of the call
+     * @internal
+     */
+    static StringEnumeration* getAvailableLocales(void);
+
+    /**
+     * Register a new Calendar factory.  The factory will be adopted.
+     * INTERNAL in 2.6
+     * @param toAdopt the factory instance to be adopted
+     * @param status the in/out status code, no special meanings are assigned
+     * @return a registry key that can be used to unregister this factory
+     * @internal
+     */
+    static URegistryKey registerFactory(ICUServiceFactory* toAdopt, UErrorCode& status);
+
+    /**
+     * Unregister a previously-registered CalendarFactory using the key returned from the
+     * register call.  Key becomes invalid after a successful call and should not be used again.
+     * The CalendarFactory corresponding to the key will be deleted.
+     * INTERNAL in 2.6
+     * @param key the registry key returned by a previous call to registerFactory
+     * @param status the in/out status code, no special meanings are assigned
+     * @return TRUE if the factory for the key was successfully unregistered
+     * @internal
+     */
+    static UBool unregister(URegistryKey key, UErrorCode& status);
+
+    /**
+     * Multiple Calendar Implementation
+     * @internal
+     */
+    friend class CalendarFactory;
+
+   

<TRUNCATED>

[68/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/ucnv_cb.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/ucnv_cb.h b/src/apps/couch_collate/platform/osx/icu/unicode/ucnv_cb.h
new file mode 100644
index 0000000..f0e67ba
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/ucnv_cb.h
@@ -0,0 +1,162 @@
+/*
+**********************************************************************
+*   Copyright (C) 2000-2004, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+**********************************************************************
+ *  ucnv_cb.h:
+ *  External APIs for the ICU's codeset conversion library
+ *  Helena Shih
+ * 
+ * Modification History:
+ *
+ *   Date        Name        Description
+ */
+
+/**
+ * \file 
+ * \brief C UConverter functions to aid the writers of callbacks
+ *
+ * <h2> Callback API for UConverter </h2>
+ * 
+ * These functions are provided here for the convenience of the callback
+ * writer. If you are just looking for callback functions to use, please
+ * see ucnv_err.h.  DO NOT call these functions directly when you are 
+ * working with converters, unless your code has been called as a callback
+ * via ucnv_setFromUCallback or ucnv_setToUCallback !!
+ * 
+ * A note about error codes and overflow.  Unlike other ICU functions,
+ * these functions do not expect the error status to be U_ZERO_ERROR.
+ * Callbacks must be much more careful about their error codes.
+ * The error codes used here are in/out parameters, which should be passed
+ * back in the callback's error parameter.
+ * 
+ * For example, if you call ucnv_cbfromUWriteBytes to write data out 
+ * to the output codepage, it may return U_BUFFER_OVERFLOW_ERROR if 
+ * the data did not fit in the target. But this isn't a failing error, 
+ * in fact, ucnv_cbfromUWriteBytes may be called AGAIN with the error
+ * status still U_BUFFER_OVERFLOW_ERROR to attempt to write further bytes,
+ * which will also go into the internal overflow buffers.
+ * 
+ * Concerning offsets, the 'offset' parameters here are relative to the start
+ * of SOURCE.  For example, Suppose the string "ABCD" was being converted 
+ * from Unicode into a codepage which doesn't have a mapping for 'B'.
+ * 'A' will be written out correctly, but
+ * The FromU Callback will be called on an unassigned character for 'B'.
+ * At this point, this is the state of the world:
+ *    Target:    A [..]     [points after A]
+ *    Source:  A B [C] D    [points to C - B has been consumed]
+ *             0 1  2  3 
+ *    codePoint = "B"       [the unassigned codepoint] 
+ * 
+ * Now, suppose a callback wants to write the substitution character '?' to
+ * the target. It calls ucnv_cbFromUWriteBytes() to write the ?. 
+ * It should pass ZERO as the offset, because the offset as far as the 
+ * callback is concerned is relative to the SOURCE pointer [which points 
+ * before 'C'.]  If the callback goes into the args and consumes 'C' also,
+ * it would call FromUWriteBytes with an offset of 1 (and advance the source
+ * pointer).
+ *
+ */
+
+#ifndef UCNV_CB_H
+#define UCNV_CB_H
+
+#include "unicode/utypes.h"
+
+#if !UCONFIG_NO_CONVERSION
+
+#include "unicode/ucnv.h"
+#include "unicode/ucnv_err.h"
+
+/**
+ * ONLY used by FromU callback functions.
+ * Writes out the specified byte output bytes to the target byte buffer or to converter internal buffers.
+ *
+ * @param args callback fromUnicode arguments
+ * @param source source bytes to write
+ * @param length length of bytes to write
+ * @param offsetIndex the relative offset index from callback.
+ * @param err error status. If <TT>U_BUFFER_OVERFLOW</TT> is returned, then U_BUFFER_OVERFLOW <STRONG>must</STRONG> 
+ * be returned to the user, because it means that not all data could be written into the target buffer, and some is 
+ * in the converter error buffer.
+ * @see ucnv_cbFromUWriteSub
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2
+ucnv_cbFromUWriteBytes (UConverterFromUnicodeArgs *args,
+                        const char* source,
+                        int32_t length,
+                        int32_t offsetIndex,
+                        UErrorCode * err);
+
+/**
+ * ONLY used by FromU callback functions.  
+ * This function will write out the correct substitution character sequence 
+ * to the target.
+ *
+ * @param args callback fromUnicode arguments
+ * @param offsetIndex the relative offset index from the current source pointer to be used
+ * @param err error status. If <TT>U_BUFFER_OVERFLOW</TT> is returned, then U_BUFFER_OVERFLOW <STRONG>must</STRONG> 
+ * be returned to the user, because it means that not all data could be written into the target buffer, and some is 
+ * in the converter error buffer.
+ * @see ucnv_cbFromUWriteBytes
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+ucnv_cbFromUWriteSub (UConverterFromUnicodeArgs *args,
+                      int32_t offsetIndex,
+                      UErrorCode * err);
+
+/**
+ * ONLY used by fromU callback functions.  
+ * This function will write out the error character(s) to the target UChar buffer.
+ *
+ * @param args callback fromUnicode arguments
+ * @param source pointer to pointer to first UChar to write [on exit: 1 after last UChar processed]
+ * @param sourceLimit pointer after last UChar to write
+ * @param offsetIndex the relative offset index from callback which will be set
+ * @param err error status <TT>U_BUFFER_OVERFLOW</TT>
+ * @see ucnv_cbToUWriteSub
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 ucnv_cbFromUWriteUChars(UConverterFromUnicodeArgs *args,
+                             const UChar** source,
+                             const UChar*  sourceLimit,
+                             int32_t offsetIndex,
+                             UErrorCode * err);
+
+/**
+ * ONLY used by ToU callback functions.
+ *  This function will write out the specified characters to the target 
+ * UChar buffer.
+ *
+ * @param args callback toUnicode arguments
+ * @param source source string to write
+ * @param length the length of source string
+ * @param offsetIndex the relative offset index which will be written.
+ * @param err error status <TT>U_BUFFER_OVERFLOW</TT>
+ * @see ucnv_cbToUWriteSub
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 ucnv_cbToUWriteUChars (UConverterToUnicodeArgs *args,
+                                             const UChar* source,
+                                             int32_t length,
+                                             int32_t offsetIndex,
+                                             UErrorCode * err);
+
+/**
+ * ONLY used by ToU  callback functions.  
+ * This function will write out the Unicode substitution character (U+FFFD).
+ *
+ * @param args callback fromUnicode arguments
+ * @param offsetIndex the relative offset index from callback.
+ * @param err error status <TT>U_BUFFER_OVERFLOW</TT>
+ * @see ucnv_cbToUWriteUChars
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 ucnv_cbToUWriteSub (UConverterToUnicodeArgs *args,
+                       int32_t offsetIndex,
+                       UErrorCode * err);
+#endif
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/ucnv_err.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/ucnv_err.h b/src/apps/couch_collate/platform/osx/icu/unicode/ucnv_err.h
new file mode 100644
index 0000000..6fde696
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/ucnv_err.h
@@ -0,0 +1,463 @@
+/*
+**********************************************************************
+*   Copyright (C) 1999-2007, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+**********************************************************************
+ *
+ *
+ *   ucnv_err.h:
+ */
+
+/**
+ * \file
+ * \brief C UConverter predefined error callbacks
+ *
+ *  <h2>Error Behaviour Functions</h2>
+ *  Defines some error behaviour functions called by ucnv_{from,to}Unicode
+ *  These are provided as part of ICU and many are stable, but they
+ *  can also be considered only as an example of what can be done with
+ *  callbacks.  You may of course write your own.
+ *
+ *  If you want to write your own, you may also find the functions from
+ *  ucnv_cb.h useful when writing your own callbacks.
+ *
+ *  These functions, although public, should NEVER be called directly.
+ *  They should be used as parameters to the ucnv_setFromUCallback
+ *  and ucnv_setToUCallback functions, to set the behaviour of a converter
+ *  when it encounters ILLEGAL/UNMAPPED/INVALID sequences.
+ *
+ *  usage example:  'STOP' doesn't need any context, but newContext
+ *    could be set to something other than 'NULL' if needed. The available
+ *    contexts in this header can modify the default behavior of the callback.
+ *
+ *  \code
+ *  UErrorCode err = U_ZERO_ERROR;
+ *  UConverter *myConverter = ucnv_open("ibm-949", &err);
+ *  const void *oldContext;
+ *  UConverterFromUCallback oldAction;
+ *
+ *
+ *  if (U_SUCCESS(err))
+ *  {
+ *      ucnv_setFromUCallBack(myConverter,
+ *                       UCNV_FROM_U_CALLBACK_STOP,
+ *                       NULL,
+ *                       &oldAction,
+ *                       &oldContext,
+ *                       &status);
+ *  }
+ *  \endcode
+ *
+ *  The code above tells "myConverter" to stop when it encounters an
+ *  ILLEGAL/TRUNCATED/INVALID sequences when it is used to convert from
+ *  Unicode -> Codepage. The behavior from Codepage to Unicode is not changed,
+ *  and ucnv_setToUCallBack would need to be called in order to change
+ *  that behavior too.
+ *
+ *  Here is an example with a context:
+ *
+ *  \code
+ *  UErrorCode err = U_ZERO_ERROR;
+ *  UConverter *myConverter = ucnv_open("ibm-949", &err);
+ *  const void *oldContext;
+ *  UConverterFromUCallback oldAction;
+ *
+ *
+ *  if (U_SUCCESS(err))
+ *  {
+ *      ucnv_setToUCallBack(myConverter,
+ *                       UCNV_TO_U_CALLBACK_SUBSTITUTE,
+ *                       UCNV_SUB_STOP_ON_ILLEGAL,
+ *                       &oldAction,
+ *                       &oldContext,
+ *                       &status);
+ *  }
+ *  \endcode
+ *
+ *  The code above tells "myConverter" to stop when it encounters an
+ *  ILLEGAL/TRUNCATED/INVALID sequences when it is used to convert from
+ *  Codepage -> Unicode. Any unmapped and legal characters will be
+ *  substituted to be the default substitution character.
+ */
+
+#ifndef UCNV_ERR_H
+#define UCNV_ERR_H
+
+#include "unicode/utypes.h"
+
+#if !UCONFIG_NO_CONVERSION
+
+/** Forward declaring the UConverter structure. @stable ICU 2.0 */
+struct UConverter;
+
+/** @stable ICU 2.0 */
+typedef struct UConverter UConverter;
+
+/**
+ * FROM_U, TO_U context options for sub callback
+ * @stable ICU 2.0
+ */
+#define UCNV_SUB_STOP_ON_ILLEGAL "i"
+
+/**
+ * FROM_U, TO_U context options for skip callback
+ * @stable ICU 2.0
+ */
+#define UCNV_SKIP_STOP_ON_ILLEGAL "i"
+
+/**
+ * FROM_U_CALLBACK_ESCAPE context option to escape the code unit according to ICU (%UXXXX) 
+ * @stable ICU 2.0
+ */
+#define UCNV_ESCAPE_ICU       NULL
+/**
+ * FROM_U_CALLBACK_ESCAPE context option to escape the code unit according to JAVA (\\uXXXX)
+ * @stable ICU 2.0
+ */
+#define UCNV_ESCAPE_JAVA      "J"
+/**
+ * FROM_U_CALLBACK_ESCAPE context option to escape the code unit according to C (\\uXXXX \\UXXXXXXXX)
+ * TO_U_CALLBACK_ESCAPE option to escape the character value accoding to C (\\xXXXX)
+ * @stable ICU 2.0
+ */
+#define UCNV_ESCAPE_C         "C"
+/**
+ * FROM_U_CALLBACK_ESCAPE context option to escape the code unit according to XML Decimal escape \htmlonly(&amp;#DDDD;)\endhtmlonly
+ * TO_U_CALLBACK_ESCAPE context option to escape the character value accoding to XML Decimal escape \htmlonly(&amp;#DDDD;)\endhtmlonly
+ * @stable ICU 2.0
+ */
+#define UCNV_ESCAPE_XML_DEC   "D"
+/**
+ * FROM_U_CALLBACK_ESCAPE context option to escape the code unit according to XML Hex escape \htmlonly(&amp;#xXXXX;)\endhtmlonly
+ * TO_U_CALLBACK_ESCAPE context option to escape the character value accoding to XML Hex escape \htmlonly(&amp;#xXXXX;)\endhtmlonly
+ * @stable ICU 2.0
+ */
+#define UCNV_ESCAPE_XML_HEX   "X"
+/**
+ * FROM_U_CALLBACK_ESCAPE context option to escape the code unit according to Unicode (U+XXXXX)
+ * @stable ICU 2.0
+ */
+#define UCNV_ESCAPE_UNICODE   "U"
+
+/**
+ * FROM_U_CALLBACK_ESCAPE context option to escape the code unit according to CSS2 conventions (\\HH..H<space>, that is,
+ * a backslash, 1..6 hex digits, and a space)
+ * @draft ICU 4.0
+ */
+#define UCNV_ESCAPE_CSS2   "S"
+
+/** 
+ * The process condition code to be used with the callbacks.  
+ * Codes which are greater than UCNV_IRREGULAR should be 
+ * passed on to any chained callbacks.
+ * @stable ICU 2.0
+ */
+typedef enum {
+    UCNV_UNASSIGNED = 0,  /**< The code point is unassigned.
+                             The error code U_INVALID_CHAR_FOUND will be set. */
+    UCNV_ILLEGAL = 1,     /**< The code point is illegal. For example, 
+                             \\x81\\x2E is illegal in SJIS because \\x2E
+                             is not a valid trail byte for the \\x81 
+                             lead byte.
+                             Also, starting with Unicode 3.0.1, non-shortest byte sequences
+                             in UTF-8 (like \\xC1\\xA1 instead of \\x61 for U+0061)
+                             are also illegal, not just irregular.
+                             The error code U_ILLEGAL_CHAR_FOUND will be set. */
+    UCNV_IRREGULAR = 2,   /**< The codepoint is not a regular sequence in 
+                             the encoding. For example, \\xED\\xA0\\x80..\\xED\\xBF\\xBF
+                             are irregular UTF-8 byte sequences for single surrogate
+                             code points.
+                             The error code U_INVALID_CHAR_FOUND will be set. */
+    UCNV_RESET = 3,       /**< The callback is called with this reason when a
+                             'reset' has occured. Callback should reset all
+                             state. */
+    UCNV_CLOSE = 4,        /**< Called when the converter is closed. The
+                             callback should release any allocated memory.*/
+    UCNV_CLONE = 5         /**< Called when ucnv_safeClone() is called on the
+                              converter. the pointer available as the
+                              'context' is an alias to the original converters'
+                              context pointer. If the context must be owned
+                              by the new converter, the callback must clone 
+                              the data and call ucnv_setFromUCallback 
+                              (or setToUCallback) with the correct pointer.
+                              @stable ICU 2.2
+                           */
+} UConverterCallbackReason;
+
+
+/**
+ * The structure for the fromUnicode callback function parameter.
+ * @stable ICU 2.0
+ */
+typedef struct {
+    uint16_t size;              /**< The size of this struct. @stable ICU 2.0 */
+    UBool flush;                /**< The internal state of converter will be reset and data flushed if set to TRUE. @stable ICU 2.0    */
+    UConverter *converter;      /**< Pointer to the converter that is opened and to which this struct is passed as an argument. @stable ICU 2.0  */
+    const UChar *source;        /**< Pointer to the source source buffer. @stable ICU 2.0    */
+    const UChar *sourceLimit;   /**< Pointer to the limit (end + 1) of source buffer. @stable ICU 2.0    */
+    char *target;               /**< Pointer to the target buffer. @stable ICU 2.0    */
+    const char *targetLimit;    /**< Pointer to the limit (end + 1) of target buffer. @stable ICU 2.0     */
+    int32_t *offsets;           /**< Pointer to the buffer that recieves the offsets. *offset = blah ; offset++;. @stable ICU 2.0  */
+} UConverterFromUnicodeArgs;
+
+
+/**
+ * The structure for the toUnicode callback function parameter.
+ * @stable ICU 2.0
+ */
+typedef struct {
+    uint16_t size;              /**< The size of this struct   @stable ICU 2.0 */
+    UBool flush;                /**< The internal state of converter will be reset and data flushed if set to TRUE. @stable ICU 2.0   */
+    UConverter *converter;      /**< Pointer to the converter that is opened and to which this struct is passed as an argument. @stable ICU 2.0 */
+    const char *source;         /**< Pointer to the source source buffer. @stable ICU 2.0    */
+    const char *sourceLimit;    /**< Pointer to the limit (end + 1) of source buffer. @stable ICU 2.0    */
+    UChar *target;              /**< Pointer to the target buffer. @stable ICU 2.0    */
+    const UChar *targetLimit;   /**< Pointer to the limit (end + 1) of target buffer. @stable ICU 2.0     */
+    int32_t *offsets;           /**< Pointer to the buffer that recieves the offsets. *offset = blah ; offset++;. @stable ICU 2.0  */
+} UConverterToUnicodeArgs;
+
+
+/**
+ * DO NOT CALL THIS FUNCTION DIRECTLY!
+ * This From Unicode callback STOPS at the ILLEGAL_SEQUENCE,
+ * returning the error code back to the caller immediately.
+ *
+ * @param context Pointer to the callback's private data
+ * @param fromUArgs Information about the conversion in progress
+ * @param codeUnits Points to 'length' UChars of the concerned Unicode sequence
+ * @param length Size (in bytes) of the concerned codepage sequence
+ * @param codePoint Single UChar32 (UTF-32) containing the concerend Unicode codepoint.
+ * @param reason Defines the reason the callback was invoked
+ * @param err This should always be set to a failure status prior to calling.
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 UCNV_FROM_U_CALLBACK_STOP (
+                  const void *context,
+                  UConverterFromUnicodeArgs *fromUArgs,
+                  const UChar* codeUnits,
+                  int32_t length,
+                  UChar32 codePoint,
+                  UConverterCallbackReason reason,
+                  UErrorCode * err);
+
+
+
+/**
+ * DO NOT CALL THIS FUNCTION DIRECTLY!
+ * This To Unicode callback STOPS at the ILLEGAL_SEQUENCE,
+ * returning the error code back to the caller immediately.
+ *
+ * @param context Pointer to the callback's private data
+ * @param toUArgs Information about the conversion in progress
+ * @param codeUnits Points to 'length' bytes of the concerned codepage sequence
+ * @param length Size (in bytes) of the concerned codepage sequence
+ * @param reason Defines the reason the callback was invoked
+ * @param err This should always be set to a failure status prior to calling.
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 UCNV_TO_U_CALLBACK_STOP (
+                  const void *context,
+                  UConverterToUnicodeArgs *toUArgs,
+                  const char* codeUnits,
+                  int32_t length,
+                  UConverterCallbackReason reason,
+                  UErrorCode * err);
+
+/**
+ * DO NOT CALL THIS FUNCTION DIRECTLY!
+ * This From Unicode callback skips any ILLEGAL_SEQUENCE, or
+ * skips only UNASSINGED_SEQUENCE depending on the context parameter
+ * simply ignoring those characters. 
+ *
+ * @param context  The function currently recognizes the callback options:
+ *                 UCNV_SKIP_STOP_ON_ILLEGAL: STOPS at the ILLEGAL_SEQUENCE,
+ *                      returning the error code back to the caller immediately.
+ *                 NULL: Skips any ILLEGAL_SEQUENCE
+ * @param fromUArgs Information about the conversion in progress
+ * @param codeUnits Points to 'length' UChars of the concerned Unicode sequence
+ * @param length Size (in bytes) of the concerned codepage sequence
+ * @param codePoint Single UChar32 (UTF-32) containing the concerend Unicode codepoint.
+ * @param reason Defines the reason the callback was invoked
+ * @param err Return value will be set to success if the callback was handled,
+ *      otherwise this value will be set to a failure status.
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 UCNV_FROM_U_CALLBACK_SKIP (
+                  const void *context,
+                  UConverterFromUnicodeArgs *fromUArgs,
+                  const UChar* codeUnits,
+                  int32_t length,
+                  UChar32 codePoint,
+                  UConverterCallbackReason reason,
+                  UErrorCode * err);
+
+/**
+ * DO NOT CALL THIS FUNCTION DIRECTLY!
+ * This From Unicode callback will Substitute the ILLEGAL SEQUENCE, or 
+ * UNASSIGNED_SEQUENCE depending on context parameter, with the
+ * current substitution string for the converter. This is the default
+ * callback.
+ *
+ * @param context The function currently recognizes the callback options:
+ *                 UCNV_SUB_STOP_ON_ILLEGAL: STOPS at the ILLEGAL_SEQUENCE,
+ *                      returning the error code back to the caller immediately.
+ *                 NULL: Substitutes any ILLEGAL_SEQUENCE
+ * @param fromUArgs Information about the conversion in progress
+ * @param codeUnits Points to 'length' UChars of the concerned Unicode sequence
+ * @param length Size (in bytes) of the concerned codepage sequence
+ * @param codePoint Single UChar32 (UTF-32) containing the concerend Unicode codepoint.
+ * @param reason Defines the reason the callback was invoked
+ * @param err Return value will be set to success if the callback was handled,
+ *      otherwise this value will be set to a failure status.
+ * @see ucnv_setSubstChars
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 UCNV_FROM_U_CALLBACK_SUBSTITUTE (
+                  const void *context,
+                  UConverterFromUnicodeArgs *fromUArgs,
+                  const UChar* codeUnits,
+                  int32_t length,
+                  UChar32 codePoint,
+                  UConverterCallbackReason reason,
+                  UErrorCode * err);
+
+/**
+ * DO NOT CALL THIS FUNCTION DIRECTLY!
+ * This From Unicode callback will Substitute the ILLEGAL SEQUENCE with the
+ * hexadecimal representation of the illegal codepoints
+ *
+ * @param context The function currently recognizes the callback options:
+ *        <ul>
+ *        <li>UCNV_ESCAPE_ICU: Substitues the  ILLEGAL SEQUENCE with the hexadecimal 
+ *          representation in the format  %UXXXX, e.g. "%uFFFE%u00AC%uC8FE"). 
+ *          In the Event the converter doesn't support the characters {%,U}[A-F][0-9], 
+ *          it will  substitute  the illegal sequence with the substitution characters.
+ *          Note that  codeUnit(32bit int eg: unit of a surrogate pair) is represented as
+ *          %UD84D%UDC56</li>
+ *        <li>UCNV_ESCAPE_JAVA: Substitues the  ILLEGAL SEQUENCE with the hexadecimal 
+ *          representation in the format  \\uXXXX, e.g. "\\uFFFE\\u00AC\\uC8FE"). 
+ *          In the Event the converter doesn't support the characters {\,u}[A-F][0-9], 
+ *          it will  substitute  the illegal sequence with the substitution characters.
+ *          Note that  codeUnit(32bit int eg: unit of a surrogate pair) is represented as
+ *          \\uD84D\\uDC56</li>
+ *        <li>UCNV_ESCAPE_C: Substitues the  ILLEGAL SEQUENCE with the hexadecimal 
+ *          representation in the format  \\uXXXX, e.g. "\\uFFFE\\u00AC\\uC8FE"). 
+ *          In the Event the converter doesn't support the characters {\,u,U}[A-F][0-9], 
+ *          it will  substitute  the illegal sequence with the substitution characters.
+ *          Note that  codeUnit(32bit int eg: unit of a surrogate pair) is represented as
+ *          \\U00023456</li>
+ *        <li>UCNV_ESCAPE_XML_DEC: Substitues the  ILLEGAL SEQUENCE with the decimal 
+ *          representation in the format \htmlonly&amp;#DDDDDDDD;, e.g. "&amp;#65534;&amp;#172;&amp;#51454;")\endhtmlonly. 
+ *          In the Event the converter doesn't support the characters {&amp;,#}[0-9], 
+ *          it will  substitute  the illegal sequence with the substitution characters.
+ *          Note that  codeUnit(32bit int eg: unit of a surrogate pair) is represented as
+ *          &amp;#144470; and Zero padding is ignored.</li>
+ *        <li>UCNV_ESCAPE_XML_HEX:Substitues the  ILLEGAL SEQUENCE with the decimal 
+ *          representation in the format \htmlonly&amp;#xXXXX; e.g. "&amp;#xFFFE;&amp;#x00AC;&amp;#xC8FE;")\endhtmlonly. 
+ *          In the Event the converter doesn't support the characters {&,#,x}[0-9], 
+ *          it will  substitute  the illegal sequence with the substitution characters.
+ *          Note that  codeUnit(32bit int eg: unit of a surrogate pair) is represented as
+ *          \htmlonly&amp;#x23456;\endhtmlonly</li>
+ *        </ul>
+ * @param fromUArgs Information about the conversion in progress
+ * @param codeUnits Points to 'length' UChars of the concerned Unicode sequence
+ * @param length Size (in bytes) of the concerned codepage sequence
+ * @param codePoint Single UChar32 (UTF-32) containing the concerend Unicode codepoint.
+ * @param reason Defines the reason the callback was invoked
+ * @param err Return value will be set to success if the callback was handled,
+ *      otherwise this value will be set to a failure status.
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 UCNV_FROM_U_CALLBACK_ESCAPE (
+                  const void *context,
+                  UConverterFromUnicodeArgs *fromUArgs,
+                  const UChar* codeUnits,
+                  int32_t length,
+                  UChar32 codePoint,
+                  UConverterCallbackReason reason,
+                  UErrorCode * err);
+
+
+/**
+ * DO NOT CALL THIS FUNCTION DIRECTLY!
+ * This To Unicode callback skips any ILLEGAL_SEQUENCE, or
+ * skips only UNASSINGED_SEQUENCE depending on the context parameter
+ * simply ignoring those characters. 
+ *
+ * @param context  The function currently recognizes the callback options:
+ *                 UCNV_SKIP_STOP_ON_ILLEGAL: STOPS at the ILLEGAL_SEQUENCE,
+ *                      returning the error code back to the caller immediately.
+ *                 NULL: Skips any ILLEGAL_SEQUENCE
+ * @param toUArgs Information about the conversion in progress
+ * @param codeUnits Points to 'length' bytes of the concerned codepage sequence
+ * @param length Size (in bytes) of the concerned codepage sequence
+ * @param reason Defines the reason the callback was invoked
+ * @param err Return value will be set to success if the callback was handled,
+ *      otherwise this value will be set to a failure status.
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 UCNV_TO_U_CALLBACK_SKIP (
+                  const void *context,
+                  UConverterToUnicodeArgs *toUArgs,
+                  const char* codeUnits,
+                  int32_t length,
+                  UConverterCallbackReason reason,
+                  UErrorCode * err);
+
+/**
+ * DO NOT CALL THIS FUNCTION DIRECTLY!
+ * This To Unicode callback will Substitute the ILLEGAL SEQUENCE,or 
+ * UNASSIGNED_SEQUENCE depending on context parameter,  with the
+ * Unicode substitution character, U+FFFD.
+ *
+ * @param context  The function currently recognizes the callback options:
+ *                 UCNV_SUB_STOP_ON_ILLEGAL: STOPS at the ILLEGAL_SEQUENCE,
+ *                      returning the error code back to the caller immediately.
+ *                 NULL: Substitutes any ILLEGAL_SEQUENCE
+ * @param toUArgs Information about the conversion in progress
+ * @param codeUnits Points to 'length' bytes of the concerned codepage sequence
+ * @param length Size (in bytes) of the concerned codepage sequence
+ * @param reason Defines the reason the callback was invoked
+ * @param err Return value will be set to success if the callback was handled,
+ *      otherwise this value will be set to a failure status.
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 UCNV_TO_U_CALLBACK_SUBSTITUTE (
+                  const void *context,
+                  UConverterToUnicodeArgs *toUArgs,
+                  const char* codeUnits,
+                  int32_t length,
+                  UConverterCallbackReason reason,
+                  UErrorCode * err);
+
+/**
+ * DO NOT CALL THIS FUNCTION DIRECTLY!
+ * This To Unicode callback will Substitute the ILLEGAL SEQUENCE with the
+ * hexadecimal representation of the illegal bytes
+ *  (in the format  %XNN, e.g. "%XFF%X0A%XC8%X03").
+ *
+ * @param context This function currently recognizes the callback options:
+ *      UCNV_ESCAPE_ICU, UCNV_ESCAPE_JAVA, UCNV_ESCAPE_C, UCNV_ESCAPE_XML_DEC,
+ *      UCNV_ESCAPE_XML_HEX and UCNV_ESCAPE_UNICODE.
+ * @param toUArgs Information about the conversion in progress
+ * @param codeUnits Points to 'length' bytes of the concerned codepage sequence
+ * @param length Size (in bytes) of the concerned codepage sequence
+ * @param reason Defines the reason the callback was invoked
+ * @param err Return value will be set to success if the callback was handled,
+ *      otherwise this value will be set to a failure status.
+ * @stable ICU 2.0
+ */
+
+U_STABLE void U_EXPORT2 UCNV_TO_U_CALLBACK_ESCAPE (
+                  const void *context,
+                  UConverterToUnicodeArgs *toUArgs,
+                  const char* codeUnits,
+                  int32_t length,
+                  UConverterCallbackReason reason,
+                  UErrorCode * err);
+
+#endif
+
+#endif
+
+/*UCNV_ERR_H*/ 

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/ucol.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/ucol.h b/src/apps/couch_collate/platform/osx/icu/unicode/ucol.h
new file mode 100644
index 0000000..9fd952e
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/ucol.h
@@ -0,0 +1,1132 @@
+/*
+*******************************************************************************
+* Copyright (c) 1996-2008, International Business Machines Corporation and others.
+* All Rights Reserved.
+*******************************************************************************
+*/
+
+#ifndef UCOL_H
+#define UCOL_H
+
+#include "unicode/utypes.h"
+
+#if !UCONFIG_NO_COLLATION
+
+#include "unicode/unorm.h"
+#include "unicode/parseerr.h"
+#include "unicode/uloc.h"
+#include "unicode/uset.h"
+
+/**
+ * \file
+ * \brief C API: Collator 
+ *
+ * <h2> Collator C API </h2>
+ *
+ * The C API for Collator performs locale-sensitive
+ * string comparison. You use this service to build
+ * searching and sorting routines for natural language text.
+ * <em>Important: </em>The ICU collation service has been reimplemented 
+ * in order to achieve better performance and UCA compliance. 
+ * For details, see the 
+ * <a href="http://source.icu-project.org/repos/icu/icuhtml/trunk/design/collation/ICU_collation_design.htm">
+ * collation design document</a>.
+ * <p>
+ * For more information about the collation service see 
+ * <a href="http://icu-project.org/userguide/Collate_Intro.html">the users guide</a>.
+ * <p>
+ * Collation service provides correct sorting orders for most locales supported in ICU. 
+ * If specific data for a locale is not available, the orders eventually falls back
+ * to the <a href="http://www.unicode.org/unicode/reports/tr10/">UCA sort order</a>. 
+ * <p>
+ * Sort ordering may be customized by providing your own set of rules. For more on
+ * this subject see the 
+ * <a href="http://icu-project.org/userguide/Collate_Customization.html">
+ * Collation customization</a> section of the users guide.
+ * <p>
+ * @see         UCollationResult
+ * @see         UNormalizationMode
+ * @see         UCollationStrength
+ * @see         UCollationElements
+ */
+
+/** A collator.
+*  For usage in C programs.
+*/
+struct UCollator;
+/** structure representing a collator object instance 
+ * @stable ICU 2.0
+ */
+typedef struct UCollator UCollator;
+
+
+/**
+ * UCOL_LESS is returned if source string is compared to be less than target
+ * string in the u_strcoll() method.
+ * UCOL_EQUAL is returned if source string is compared to be equal to target
+ * string in the u_strcoll() method.
+ * UCOL_GREATER is returned if source string is compared to be greater than
+ * target string in the u_strcoll() method.
+ * @see u_strcoll()
+ * <p>
+ * Possible values for a comparison result 
+ * @stable ICU 2.0
+ */
+typedef enum {
+  /** string a == string b */
+  UCOL_EQUAL    = 0,
+  /** string a > string b */
+  UCOL_GREATER    = 1,
+  /** string a < string b */
+  UCOL_LESS    = -1
+} UCollationResult ;
+
+
+/** Enum containing attribute values for controling collation behavior.
+ * Here are all the allowable values. Not every attribute can take every value. The only
+ * universal value is UCOL_DEFAULT, which resets the attribute value to the predefined  
+ * value for that locale 
+ * @stable ICU 2.0
+ */
+typedef enum {
+  /** accepted by most attributes */
+  UCOL_DEFAULT = -1,
+
+  /** Primary collation strength */
+  UCOL_PRIMARY = 0,
+  /** Secondary collation strength */
+  UCOL_SECONDARY = 1,
+  /** Tertiary collation strength */
+  UCOL_TERTIARY = 2,
+  /** Default collation strength */
+  UCOL_DEFAULT_STRENGTH = UCOL_TERTIARY,
+  UCOL_CE_STRENGTH_LIMIT,
+  /** Quaternary collation strength */
+  UCOL_QUATERNARY=3,
+  /** Identical collation strength */
+  UCOL_IDENTICAL=15,
+  UCOL_STRENGTH_LIMIT,
+
+  /** Turn the feature off - works for UCOL_FRENCH_COLLATION, 
+      UCOL_CASE_LEVEL, UCOL_HIRAGANA_QUATERNARY_MODE
+      & UCOL_DECOMPOSITION_MODE*/
+  UCOL_OFF = 16,
+  /** Turn the feature on - works for UCOL_FRENCH_COLLATION, 
+      UCOL_CASE_LEVEL, UCOL_HIRAGANA_QUATERNARY_MODE
+      & UCOL_DECOMPOSITION_MODE*/
+  UCOL_ON = 17,
+  
+  /** Valid for UCOL_ALTERNATE_HANDLING. Alternate handling will be shifted */
+  UCOL_SHIFTED = 20,
+  /** Valid for UCOL_ALTERNATE_HANDLING. Alternate handling will be non ignorable */
+  UCOL_NON_IGNORABLE = 21,
+
+  /** Valid for UCOL_CASE_FIRST - 
+      lower case sorts before upper case */
+  UCOL_LOWER_FIRST = 24,
+  /** upper case sorts before lower case */
+  UCOL_UPPER_FIRST = 25,
+
+  UCOL_ATTRIBUTE_VALUE_COUNT
+
+} UColAttributeValue;
+
+/**
+ * Base letter represents a primary difference.  Set comparison
+ * level to UCOL_PRIMARY to ignore secondary and tertiary differences.
+ * Use this to set the strength of a Collator object.
+ * Example of primary difference, "abc" &lt; "abd"
+ * 
+ * Diacritical differences on the same base letter represent a secondary
+ * difference.  Set comparison level to UCOL_SECONDARY to ignore tertiary
+ * differences. Use this to set the strength of a Collator object.
+ * Example of secondary difference, "&auml;" >> "a".
+ *
+ * Uppercase and lowercase versions of the same character represents a
+ * tertiary difference.  Set comparison level to UCOL_TERTIARY to include
+ * all comparison differences. Use this to set the strength of a Collator
+ * object.
+ * Example of tertiary difference, "abc" &lt;&lt;&lt; "ABC".
+ *
+ * Two characters are considered "identical" when they have the same
+ * unicode spellings.  UCOL_IDENTICAL.
+ * For example, "&auml;" == "&auml;".
+ *
+ * UCollationStrength is also used to determine the strength of sort keys 
+ * generated from UCollator objects
+ * These values can be now found in the UColAttributeValue enum.
+ * @stable ICU 2.0
+ **/
+typedef UColAttributeValue UCollationStrength;
+
+/** Attributes that collation service understands. All the attributes can take UCOL_DEFAULT
+ * value, as well as the values specific to each one. 
+ * @stable ICU 2.0
+ */
+typedef enum {
+     /** Attribute for direction of secondary weights - used in French.
+      * Acceptable values are UCOL_ON, which results in secondary weights
+      * being considered backwards and UCOL_OFF which treats secondary
+      * weights in the order they appear.*/
+     UCOL_FRENCH_COLLATION, 
+     /** Attribute for handling variable elements.
+      * Acceptable values are UCOL_NON_IGNORABLE (default)
+      * which treats all the codepoints with non-ignorable 
+      * primary weights in the same way,
+      * and UCOL_SHIFTED which causes codepoints with primary 
+      * weights that are equal or below the variable top value
+      * to be ignored on primary level and moved to the quaternary 
+      * level.*/
+     UCOL_ALTERNATE_HANDLING, 
+     /** Controls the ordering of upper and lower case letters.
+      * Acceptable values are UCOL_OFF (default), which orders
+      * upper and lower case letters in accordance to their tertiary
+      * weights, UCOL_UPPER_FIRST which forces upper case letters to 
+      * sort before lower case letters, and UCOL_LOWER_FIRST which does 
+      * the opposite. */
+     UCOL_CASE_FIRST, 
+     /** Controls whether an extra case level (positioned before the third
+      * level) is generated or not. Acceptable values are UCOL_OFF (default), 
+      * when case level is not generated, and UCOL_ON which causes the case
+      * level to be generated. Contents of the case level are affected by
+      * the value of UCOL_CASE_FIRST attribute. A simple way to ignore 
+      * accent differences in a string is to set the strength to UCOL_PRIMARY
+      * and enable case level. */
+     UCOL_CASE_LEVEL,
+     /** Controls whether the normalization check and necessary normalizations
+      * are performed. When set to UCOL_OFF (default) no normalization check
+      * is performed. The correctness of the result is guaranteed only if the 
+      * input data is in so-called FCD form (see users manual for more info).
+      * When set to UCOL_ON, an incremental check is performed to see whether
+      * the input data is in the FCD form. If the data is not in the FCD form,
+      * incremental NFD normalization is performed. */
+     UCOL_NORMALIZATION_MODE, 
+     /** An alias for UCOL_NORMALIZATION_MODE attribute */
+     UCOL_DECOMPOSITION_MODE = UCOL_NORMALIZATION_MODE,
+     /** The strength attribute. Can be either UCOL_PRIMARY, UCOL_SECONDARY,
+      * UCOL_TERTIARY, UCOL_QUATERNARY or UCOL_IDENTICAL. The usual strength
+      * for most locales (except Japanese) is tertiary. Quaternary strength 
+      * is useful when combined with shifted setting for alternate handling
+      * attribute and for JIS x 4061 collation, when it is used to distinguish
+      * between Katakana  and Hiragana (this is achieved by setting the 
+      * UCOL_HIRAGANA_QUATERNARY mode to on. Otherwise, quaternary level
+      * is affected only by the number of non ignorable code points in
+      * the string. Identical strength is rarely useful, as it amounts 
+      * to codepoints of the NFD form of the string. */
+     UCOL_STRENGTH,  
+     /** When turned on, this attribute positions Hiragana before all  
+      * non-ignorables on quaternary level This is a sneaky way to produce JIS
+      * sort order */
+     UCOL_HIRAGANA_QUATERNARY_MODE,
+     /** When turned on, this attribute generates a collation key
+      * for the numeric value of substrings of digits.
+      * This is a way to get '100' to sort AFTER '2'. */
+     UCOL_NUMERIC_COLLATION, 
+     UCOL_ATTRIBUTE_COUNT
+} UColAttribute;
+
+/** Options for retrieving the rule string 
+ *  @stable ICU 2.0
+ */
+typedef enum {
+  /** Retrieve tailoring only */
+  UCOL_TAILORING_ONLY, 
+  /** Retrieve UCA rules and tailoring */
+  UCOL_FULL_RULES 
+} UColRuleOption ;
+
+/**
+ * Open a UCollator for comparing strings.
+ * The UCollator pointer is used in all the calls to the Collation 
+ * service. After finished, collator must be disposed of by calling
+ * {@link #ucol_close }.
+ * @param loc The locale containing the required collation rules. 
+ *            Special values for locales can be passed in - 
+ *            if NULL is passed for the locale, the default locale
+ *            collation rules will be used. If empty string ("") or
+ *            "root" are passed, UCA rules will be used.
+ * @param status A pointer to an UErrorCode to receive any errors
+ * @return A pointer to a UCollator, or 0 if an error occurred.
+ * @see ucol_openRules
+ * @see ucol_safeClone
+ * @see ucol_close
+ * @stable ICU 2.0
+ */
+U_STABLE UCollator* U_EXPORT2 
+ucol_open(const char *loc, UErrorCode *status);
+
+/**
+ * Produce an UCollator instance according to the rules supplied.
+ * The rules are used to change the default ordering, defined in the
+ * UCA in a process called tailoring. The resulting UCollator pointer
+ * can be used in the same way as the one obtained by {@link #ucol_strcoll }.
+ * @param rules A string describing the collation rules. For the syntax
+ *              of the rules please see users guide.
+ * @param rulesLength The length of rules, or -1 if null-terminated.
+ * @param normalizationMode The normalization mode: One of
+ *             UCOL_OFF     (expect the text to not need normalization),
+ *             UCOL_ON      (normalize), or
+ *             UCOL_DEFAULT (set the mode according to the rules)
+ * @param strength The default collation strength; one of UCOL_PRIMARY, UCOL_SECONDARY,
+ * UCOL_TERTIARY, UCOL_IDENTICAL,UCOL_DEFAULT_STRENGTH - can be also set in the rules.
+ * @param parseError  A pointer to UParseError to recieve information about errors
+ *                    occurred during parsing. This argument can currently be set
+ *                    to NULL, but at users own risk. Please provide a real structure.
+ * @param status A pointer to an UErrorCode to receive any errors
+ * @return A pointer to a UCollator. It is not guaranteed that NULL be returned in case
+ *         of error - please use status argument to check for errors.
+ * @see ucol_open
+ * @see ucol_safeClone
+ * @see ucol_close
+ * @stable ICU 2.0
+ */
+U_STABLE UCollator* U_EXPORT2 
+ucol_openRules( const UChar        *rules,
+                int32_t            rulesLength,
+                UColAttributeValue normalizationMode,
+                UCollationStrength strength,
+                UParseError        *parseError,
+                UErrorCode         *status);
+
+/** 
+ * Open a collator defined by a short form string.
+ * The structure and the syntax of the string is defined in the "Naming collators"
+ * section of the users guide: 
+ * http://icu-project.org/userguide/Collate_Concepts.html#Naming_Collators
+ * Attributes are overriden by the subsequent attributes. So, for "S2_S3", final
+ * strength will be 3. 3066bis locale overrides individual locale parts.
+ * The call to this function is equivalent to a call to ucol_open, followed by a 
+ * series of calls to ucol_setAttribute and ucol_setVariableTop.
+ * @param definition A short string containing a locale and a set of attributes. 
+ *                   Attributes not explicitly mentioned are left at the default
+ *                   state for a locale.
+ * @param parseError if not NULL, structure that will get filled with error's pre
+ *                   and post context in case of error.
+ * @param forceDefaults if FALSE, the settings that are the same as the collator 
+ *                   default settings will not be applied (for example, setting
+ *                   French secondary on a French collator would not be executed). 
+ *                   If TRUE, all the settings will be applied regardless of the 
+ *                   collator default value. If the definition
+ *                   strings are to be cached, should be set to FALSE.
+ * @param status     Error code. Apart from regular error conditions connected to 
+ *                   instantiating collators (like out of memory or similar), this
+ *                   API will return an error if an invalid attribute or attribute/value
+ *                   combination is specified.
+ * @return           A pointer to a UCollator or 0 if an error occured (including an 
+ *                   invalid attribute).
+ * @see ucol_open
+ * @see ucol_setAttribute
+ * @see ucol_setVariableTop
+ * @see ucol_getShortDefinitionString
+ * @see ucol_normalizeShortDefinitionString
+ * @stable ICU 3.0
+ *
+ */
+U_STABLE UCollator* U_EXPORT2
+ucol_openFromShortString( const char *definition,
+                          UBool forceDefaults,
+                          UParseError *parseError,
+                          UErrorCode *status);
+
+/**
+ * Get a set containing the contractions defined by the collator. The set includes
+ * both the UCA contractions and the contractions defined by the collator. This set
+ * will contain only strings. If a tailoring explicitly suppresses contractions from 
+ * the UCA (like Russian), removed contractions will not be in the resulting set.
+ * @param coll collator 
+ * @param conts the set to hold the result. It gets emptied before
+ *              contractions are added. 
+ * @param status to hold the error code
+ * @return the size of the contraction set
+ *
+ * @deprecated ICU 3.4, use ucol_getContractionsAndExpansions instead
+ */
+U_DEPRECATED int32_t U_EXPORT2
+ucol_getContractions( const UCollator *coll,
+                  USet *conts,
+                  UErrorCode *status);
+
+/**
+ * Get a set containing the expansions defined by the collator. The set includes
+ * both the UCA expansions and the expansions defined by the tailoring
+ * @param coll collator
+ * @param contractions if not NULL, the set to hold the contractions
+ * @param expansions if not NULL, the set to hold the expansions
+ * @param addPrefixes add the prefix contextual elements to contractions
+ * @param status to hold the error code
+ *
+ * @stable ICU 3.4
+ */
+U_STABLE void U_EXPORT2
+ucol_getContractionsAndExpansions( const UCollator *coll,
+                  USet *contractions, USet *expansions,
+                  UBool addPrefixes, UErrorCode *status);
+
+/** 
+ * Close a UCollator.
+ * Once closed, a UCollator should not be used. Every open collator should
+ * be closed. Otherwise, a memory leak will result.
+ * @param coll The UCollator to close.
+ * @see ucol_open
+ * @see ucol_openRules
+ * @see ucol_safeClone
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+ucol_close(UCollator *coll);
+
+/**
+ * Compare two strings.
+ * The strings will be compared using the options already specified.
+ * @param coll The UCollator containing the comparison rules.
+ * @param source The source string.
+ * @param sourceLength The length of source, or -1 if null-terminated.
+ * @param target The target string.
+ * @param targetLength The length of target, or -1 if null-terminated.
+ * @return The result of comparing the strings; one of UCOL_EQUAL,
+ * UCOL_GREATER, UCOL_LESS
+ * @see ucol_greater
+ * @see ucol_greaterOrEqual
+ * @see ucol_equal
+ * @stable ICU 2.0
+ */
+U_STABLE UCollationResult U_EXPORT2 
+ucol_strcoll(    const    UCollator    *coll,
+        const    UChar        *source,
+        int32_t            sourceLength,
+        const    UChar        *target,
+        int32_t            targetLength);
+
+/**
+ * Determine if one string is greater than another.
+ * This function is equivalent to {@link #ucol_strcoll } == UCOL_GREATER
+ * @param coll The UCollator containing the comparison rules.
+ * @param source The source string.
+ * @param sourceLength The length of source, or -1 if null-terminated.
+ * @param target The target string.
+ * @param targetLength The length of target, or -1 if null-terminated.
+ * @return TRUE if source is greater than target, FALSE otherwise.
+ * @see ucol_strcoll
+ * @see ucol_greaterOrEqual
+ * @see ucol_equal
+ * @stable ICU 2.0
+ */
+U_STABLE UBool U_EXPORT2 
+ucol_greater(const UCollator *coll,
+             const UChar     *source, int32_t sourceLength,
+             const UChar     *target, int32_t targetLength);
+
+/**
+ * Determine if one string is greater than or equal to another.
+ * This function is equivalent to {@link #ucol_strcoll } != UCOL_LESS
+ * @param coll The UCollator containing the comparison rules.
+ * @param source The source string.
+ * @param sourceLength The length of source, or -1 if null-terminated.
+ * @param target The target string.
+ * @param targetLength The length of target, or -1 if null-terminated.
+ * @return TRUE if source is greater than or equal to target, FALSE otherwise.
+ * @see ucol_strcoll
+ * @see ucol_greater
+ * @see ucol_equal
+ * @stable ICU 2.0
+ */
+U_STABLE UBool U_EXPORT2 
+ucol_greaterOrEqual(const UCollator *coll,
+                    const UChar     *source, int32_t sourceLength,
+                    const UChar     *target, int32_t targetLength);
+
+/**
+ * Compare two strings for equality.
+ * This function is equivalent to {@link #ucol_strcoll } == UCOL_EQUAL
+ * @param coll The UCollator containing the comparison rules.
+ * @param source The source string.
+ * @param sourceLength The length of source, or -1 if null-terminated.
+ * @param target The target string.
+ * @param targetLength The length of target, or -1 if null-terminated.
+ * @return TRUE if source is equal to target, FALSE otherwise
+ * @see ucol_strcoll
+ * @see ucol_greater
+ * @see ucol_greaterOrEqual
+ * @stable ICU 2.0
+ */
+U_STABLE UBool U_EXPORT2 
+ucol_equal(const UCollator *coll,
+           const UChar     *source, int32_t sourceLength,
+           const UChar     *target, int32_t targetLength);
+
+/**
+ * Compare two UTF-8 encoded trings.
+ * The strings will be compared using the options already specified.
+ * @param coll The UCollator containing the comparison rules.
+ * @param sIter The source string iterator.
+ * @param tIter The target string iterator.
+ * @return The result of comparing the strings; one of UCOL_EQUAL,
+ * UCOL_GREATER, UCOL_LESS
+ * @param status A pointer to an UErrorCode to receive any errors
+ * @see ucol_strcoll
+ * @stable ICU 2.6
+ */
+U_STABLE UCollationResult U_EXPORT2 
+ucol_strcollIter(  const    UCollator    *coll,
+                  UCharIterator *sIter,
+                  UCharIterator *tIter,
+                  UErrorCode *status);
+
+/**
+ * Get the collation strength used in a UCollator.
+ * The strength influences how strings are compared.
+ * @param coll The UCollator to query.
+ * @return The collation strength; one of UCOL_PRIMARY, UCOL_SECONDARY,
+ * UCOL_TERTIARY, UCOL_QUATERNARY, UCOL_IDENTICAL
+ * @see ucol_setStrength
+ * @stable ICU 2.0
+ */
+U_STABLE UCollationStrength U_EXPORT2 
+ucol_getStrength(const UCollator *coll);
+
+/**
+ * Set the collation strength used in a UCollator.
+ * The strength influences how strings are compared.
+ * @param coll The UCollator to set.
+ * @param strength The desired collation strength; one of UCOL_PRIMARY, 
+ * UCOL_SECONDARY, UCOL_TERTIARY, UCOL_QUATERNARY, UCOL_IDENTICAL, UCOL_DEFAULT
+ * @see ucol_getStrength
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+ucol_setStrength(UCollator *coll,
+                 UCollationStrength strength);
+
+/**
+ * Get the display name for a UCollator.
+ * The display name is suitable for presentation to a user.
+ * @param objLoc The locale of the collator in question.
+ * @param dispLoc The locale for display.
+ * @param result A pointer to a buffer to receive the attribute.
+ * @param resultLength The maximum size of result.
+ * @param status A pointer to an UErrorCode to receive any errors
+ * @return The total buffer size needed; if greater than resultLength,
+ * the output was truncated.
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2 
+ucol_getDisplayName(    const    char        *objLoc,
+            const    char        *dispLoc,
+            UChar             *result,
+            int32_t         resultLength,
+            UErrorCode        *status);
+
+/**
+ * Get a locale for which collation rules are available.
+ * A UCollator in a locale returned by this function will perform the correct
+ * collation for the locale.
+ * @param index The index of the desired locale.
+ * @return A locale for which collation rules are available, or 0 if none.
+ * @see ucol_countAvailable
+ * @stable ICU 2.0
+ */
+U_STABLE const char* U_EXPORT2 
+ucol_getAvailable(int32_t index);
+
+/**
+ * Determine how many locales have collation rules available.
+ * This function is most useful as determining the loop ending condition for
+ * calls to {@link #ucol_getAvailable }.
+ * @return The number of locales for which collation rules are available.
+ * @see ucol_getAvailable
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2 
+ucol_countAvailable(void);
+
+#if !UCONFIG_NO_SERVICE
+/**
+ * Create a string enumerator of all locales for which a valid
+ * collator may be opened.
+ * @param status input-output error code
+ * @return a string enumeration over locale strings. The caller is
+ * responsible for closing the result.
+ * @stable ICU 3.0
+ */
+U_STABLE UEnumeration* U_EXPORT2
+ucol_openAvailableLocales(UErrorCode *status);
+#endif
+
+/**
+ * Create a string enumerator of all possible keywords that are relevant to
+ * collation. At this point, the only recognized keyword for this
+ * service is "collation".
+ * @param status input-output error code
+ * @return a string enumeration over locale strings. The caller is
+ * responsible for closing the result.
+ * @stable ICU 3.0
+ */
+U_STABLE UEnumeration* U_EXPORT2
+ucol_getKeywords(UErrorCode *status);
+
+/**
+ * Given a keyword, create a string enumeration of all values
+ * for that keyword that are currently in use.
+ * @param keyword a particular keyword as enumerated by
+ * ucol_getKeywords. If any other keyword is passed in, *status is set
+ * to U_ILLEGAL_ARGUMENT_ERROR.
+ * @param status input-output error code
+ * @return a string enumeration over collation keyword values, or NULL
+ * upon error. The caller is responsible for closing the result.
+ * @stable ICU 3.0
+ */
+U_STABLE UEnumeration* U_EXPORT2
+ucol_getKeywordValues(const char *keyword, UErrorCode *status);
+
+/**
+ * Return the functionally equivalent locale for the given
+ * requested locale, with respect to given keyword, for the
+ * collation service.  If two locales return the same result, then
+ * collators instantiated for these locales will behave
+ * equivalently.  The converse is not always true; two collators
+ * may in fact be equivalent, but return different results, due to
+ * internal details.  The return result has no other meaning than
+ * that stated above, and implies nothing as to the relationship
+ * between the two locales.  This is intended for use by
+ * applications who wish to cache collators, or otherwise reuse
+ * collators when possible.  The functional equivalent may change
+ * over time.  For more information, please see the <a
+ * href="http://icu-project.org/userguide/locale.html#services">
+ * Locales and Services</a> section of the ICU User Guide.
+ * @param result fillin for the functionally equivalent locale
+ * @param resultCapacity capacity of the fillin buffer
+ * @param keyword a particular keyword as enumerated by
+ * ucol_getKeywords.
+ * @param locale the requested locale
+ * @param isAvailable if non-NULL, pointer to a fillin parameter that
+ * indicates whether the requested locale was 'available' to the
+ * collation service. A locale is defined as 'available' if it
+ * physically exists within the collation locale data.
+ * @param status pointer to input-output error code
+ * @return the actual buffer size needed for the locale.  If greater
+ * than resultCapacity, the returned full name will be truncated and
+ * an error code will be returned.
+ * @stable ICU 3.0
+ */
+U_STABLE int32_t U_EXPORT2
+ucol_getFunctionalEquivalent(char* result, int32_t resultCapacity,
+                             const char* keyword, const char* locale,
+                             UBool* isAvailable, UErrorCode* status);
+
+/**
+ * Get the collation rules from a UCollator.
+ * The rules will follow the rule syntax.
+ * @param coll The UCollator to query.
+ * @param length 
+ * @return The collation rules.
+ * @stable ICU 2.0
+ */
+U_STABLE const UChar* U_EXPORT2 
+ucol_getRules(    const    UCollator    *coll, 
+        int32_t            *length);
+
+/** Get the short definition string for a collator. This API harvests the collator's
+ *  locale and the attribute set and produces a string that can be used for opening 
+ *  a collator with the same properties using the ucol_openFromShortString API.
+ *  This string will be normalized.
+ *  The structure and the syntax of the string is defined in the "Naming collators"
+ *  section of the users guide: 
+ *  http://icu-project.org/userguide/Collate_Concepts.html#Naming_Collators
+ *  This API supports preflighting.
+ *  @param coll a collator
+ *  @param locale a locale that will appear as a collators locale in the resulting
+ *                short string definition. If NULL, the locale will be harvested 
+ *                from the collator.
+ *  @param buffer space to hold the resulting string
+ *  @param capacity capacity of the buffer
+ *  @param status for returning errors. All the preflighting errors are featured
+ *  @return length of the resulting string
+ *  @see ucol_openFromShortString
+ *  @see ucol_normalizeShortDefinitionString
+ *  @stable ICU 3.0
+ */
+U_STABLE int32_t U_EXPORT2
+ucol_getShortDefinitionString(const UCollator *coll,
+                              const char *locale,
+                              char *buffer,
+                              int32_t capacity,
+                              UErrorCode *status);
+
+/** Verifies and normalizes short definition string.
+ *  Normalized short definition string has all the option sorted by the argument name,
+ *  so that equivalent definition strings are the same. 
+ *  This API supports preflighting.
+ *  @param source definition string
+ *  @param destination space to hold the resulting string
+ *  @param capacity capacity of the buffer
+ *  @param parseError if not NULL, structure that will get filled with error's pre
+ *                   and post context in case of error.
+ *  @param status     Error code. This API will return an error if an invalid attribute 
+ *                    or attribute/value combination is specified. All the preflighting 
+ *                    errors are also featured
+ *  @return length of the resulting normalized string.
+ *
+ *  @see ucol_openFromShortString
+ *  @see ucol_getShortDefinitionString
+ * 
+ *  @stable ICU 3.0
+ */
+
+U_STABLE int32_t U_EXPORT2
+ucol_normalizeShortDefinitionString(const char *source,
+                                    char *destination,
+                                    int32_t capacity,
+                                    UParseError *parseError,
+                                    UErrorCode *status);
+
+
+/**
+ * Get a sort key for a string from a UCollator.
+ * Sort keys may be compared using <TT>strcmp</TT>.
+ * @param coll The UCollator containing the collation rules.
+ * @param source The string to transform.
+ * @param sourceLength The length of source, or -1 if null-terminated.
+ * @param result A pointer to a buffer to receive the attribute.
+ * @param resultLength The maximum size of result.
+ * @return The size needed to fully store the sort key.
+ *      If there was an internal error generating the sort key,
+ *      a zero value is returned.
+ * @see ucol_keyHashCode
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2 
+ucol_getSortKey(const    UCollator    *coll,
+        const    UChar        *source,
+        int32_t        sourceLength,
+        uint8_t        *result,
+        int32_t        resultLength);
+
+
+/** Gets the next count bytes of a sort key. Caller needs
+ *  to preserve state array between calls and to provide
+ *  the same type of UCharIterator set with the same string.
+ *  The destination buffer provided must be big enough to store
+ *  the number of requested bytes. Generated sortkey is not 
+ *  compatible with sortkeys generated using ucol_getSortKey
+ *  API, since we don't do any compression. If uncompressed
+ *  sortkeys are required, this API can be used.
+ *  @param coll The UCollator containing the collation rules.
+ *  @param iter UCharIterator containing the string we need 
+ *              the sort key to be calculated for.
+ *  @param state Opaque state of sortkey iteration.
+ *  @param dest Buffer to hold the resulting sortkey part
+ *  @param count number of sort key bytes required.
+ *  @param status error code indicator.
+ *  @return the actual number of bytes of a sortkey. It can be
+ *          smaller than count if we have reached the end of 
+ *          the sort key.
+ *  @stable ICU 2.6
+ */
+U_STABLE int32_t U_EXPORT2 
+ucol_nextSortKeyPart(const UCollator *coll,
+                     UCharIterator *iter,
+                     uint32_t state[2],
+                     uint8_t *dest, int32_t count,
+                     UErrorCode *status);
+
+/** enum that is taken by ucol_getBound API 
+ * See below for explanation                
+ * do not change the values assigned to the 
+ * members of this enum. Underlying code    
+ * depends on them having these numbers     
+ * @stable ICU 2.0
+ */
+typedef enum {
+  /** lower bound */
+  UCOL_BOUND_LOWER = 0,
+  /** upper bound that will match strings of exact size */
+  UCOL_BOUND_UPPER = 1,
+  /** upper bound that will match all the strings that have the same initial substring as the given string */
+  UCOL_BOUND_UPPER_LONG = 2,
+  UCOL_BOUND_VALUE_COUNT
+} UColBoundMode;
+
+/**
+ * Produce a bound for a given sortkey and a number of levels.
+ * Return value is always the number of bytes needed, regardless of 
+ * whether the result buffer was big enough or even valid.<br>
+ * Resulting bounds can be used to produce a range of strings that are
+ * between upper and lower bounds. For example, if bounds are produced
+ * for a sortkey of string "smith", strings between upper and lower 
+ * bounds with one level would include "Smith", "SMITH", "sMiTh".<br>
+ * There are two upper bounds that can be produced. If UCOL_BOUND_UPPER
+ * is produced, strings matched would be as above. However, if bound
+ * produced using UCOL_BOUND_UPPER_LONG is used, the above example will
+ * also match "Smithsonian" and similar.<br>
+ * For more on usage, see example in cintltst/capitst.c in procedure
+ * TestBounds.
+ * Sort keys may be compared using <TT>strcmp</TT>.
+ * @param source The source sortkey.
+ * @param sourceLength The length of source, or -1 if null-terminated. 
+ *                     (If an unmodified sortkey is passed, it is always null 
+ *                      terminated).
+ * @param boundType Type of bound required. It can be UCOL_BOUND_LOWER, which 
+ *                  produces a lower inclusive bound, UCOL_BOUND_UPPER, that 
+ *                  produces upper bound that matches strings of the same length 
+ *                  or UCOL_BOUND_UPPER_LONG that matches strings that have the 
+ *                  same starting substring as the source string.
+ * @param noOfLevels  Number of levels required in the resulting bound (for most 
+ *                    uses, the recommended value is 1). See users guide for 
+ *                    explanation on number of levels a sortkey can have.
+ * @param result A pointer to a buffer to receive the resulting sortkey.
+ * @param resultLength The maximum size of result.
+ * @param status Used for returning error code if something went wrong. If the 
+ *               number of levels requested is higher than the number of levels
+ *               in the source key, a warning (U_SORT_KEY_TOO_SHORT_WARNING) is 
+ *               issued.
+ * @return The size needed to fully store the bound. 
+ * @see ucol_keyHashCode
+ * @stable ICU 2.1
+ */
+U_STABLE int32_t U_EXPORT2 
+ucol_getBound(const uint8_t       *source,
+        int32_t             sourceLength,
+        UColBoundMode       boundType,
+        uint32_t            noOfLevels,
+        uint8_t             *result,
+        int32_t             resultLength,
+        UErrorCode          *status);
+        
+/**
+ * Gets the version information for a Collator. Version is currently
+ * an opaque 32-bit number which depends, among other things, on major
+ * versions of the collator tailoring and UCA.
+ * @param coll The UCollator to query.
+ * @param info the version # information, the result will be filled in
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2
+ucol_getVersion(const UCollator* coll, UVersionInfo info);
+
+/**
+ * Gets the UCA version information for a Collator. Version is the
+ * UCA version number (3.1.1, 4.0).
+ * @param coll The UCollator to query.
+ * @param info the version # information, the result will be filled in
+ * @stable ICU 2.8
+ */
+U_STABLE void U_EXPORT2
+ucol_getUCAVersion(const UCollator* coll, UVersionInfo info);
+
+/** 
+ * Merge two sort keys. The levels are merged with their corresponding counterparts
+ * (primaries with primaries, secondaries with secondaries etc.). Between the values
+ * from the same level a separator is inserted.
+ * example (uncompressed): 
+ * 191B1D 01 050505 01 910505 00 and 1F2123 01 050505 01 910505 00
+ * will be merged as 
+ * 191B1D 02 1F212301 050505 02 050505 01 910505 02 910505 00
+ * This allows for concatenating of first and last names for sorting, among other things.
+ * If the destination buffer is not big enough, the results are undefined.
+ * If any of source lengths are zero or any of source pointers are NULL/undefined, 
+ * result is of size zero.
+ * @param src1 pointer to the first sortkey
+ * @param src1Length length of the first sortkey
+ * @param src2 pointer to the second sortkey
+ * @param src2Length length of the second sortkey
+ * @param dest buffer to hold the result
+ * @param destCapacity size of the buffer for the result
+ * @return size of the result. If the buffer is big enough size is always
+ *         src1Length+src2Length-1
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2 
+ucol_mergeSortkeys(const uint8_t *src1, int32_t src1Length,
+                   const uint8_t *src2, int32_t src2Length,
+                   uint8_t *dest, int32_t destCapacity);
+
+/**
+ * Universal attribute setter
+ * @param coll collator which attributes are to be changed
+ * @param attr attribute type 
+ * @param value attribute value
+ * @param status to indicate whether the operation went on smoothly or there were errors
+ * @see UColAttribute
+ * @see UColAttributeValue
+ * @see ucol_getAttribute
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+ucol_setAttribute(UCollator *coll, UColAttribute attr, UColAttributeValue value, UErrorCode *status);
+
+/**
+ * Universal attribute getter
+ * @param coll collator which attributes are to be changed
+ * @param attr attribute type
+ * @return attribute value
+ * @param status to indicate whether the operation went on smoothly or there were errors
+ * @see UColAttribute
+ * @see UColAttributeValue
+ * @see ucol_setAttribute
+ * @stable ICU 2.0
+ */
+U_STABLE UColAttributeValue  U_EXPORT2 
+ucol_getAttribute(const UCollator *coll, UColAttribute attr, UErrorCode *status);
+
+/** Variable top
+ * is a two byte primary value which causes all the codepoints with primary values that
+ * are less or equal than the variable top to be shifted when alternate handling is set
+ * to UCOL_SHIFTED.
+ * Sets the variable top to a collation element value of a string supplied. 
+ * @param coll collator which variable top needs to be changed
+ * @param varTop one or more (if contraction) UChars to which the variable top should be set
+ * @param len length of variable top string. If -1 it is considered to be zero terminated.
+ * @param status error code. If error code is set, the return value is undefined. 
+ *               Errors set by this function are: <br>
+ *    U_CE_NOT_FOUND_ERROR if more than one character was passed and there is no such 
+ *    a contraction<br>
+ *    U_PRIMARY_TOO_LONG_ERROR if the primary for the variable top has more than two bytes
+ * @return a 32 bit value containing the value of the variable top in upper 16 bits. 
+ *         Lower 16 bits are undefined
+ * @see ucol_getVariableTop
+ * @see ucol_restoreVariableTop
+ * @stable ICU 2.0
+ */
+U_STABLE uint32_t U_EXPORT2 
+ucol_setVariableTop(UCollator *coll, 
+                    const UChar *varTop, int32_t len, 
+                    UErrorCode *status);
+
+/** 
+ * Gets the variable top value of a Collator. 
+ * Lower 16 bits are undefined and should be ignored.
+ * @param coll collator which variable top needs to be retrieved
+ * @param status error code (not changed by function). If error code is set, 
+ *               the return value is undefined.
+ * @return the variable top value of a Collator.
+ * @see ucol_setVariableTop
+ * @see ucol_restoreVariableTop
+ * @stable ICU 2.0
+ */
+U_STABLE uint32_t U_EXPORT2 ucol_getVariableTop(const UCollator *coll, UErrorCode *status);
+
+/** 
+ * Sets the variable top to a collation element value supplied. Variable top is 
+ * set to the upper 16 bits. 
+ * Lower 16 bits are ignored.
+ * @param coll collator which variable top needs to be changed
+ * @param varTop CE value, as returned by ucol_setVariableTop or ucol)getVariableTop
+ * @param status error code (not changed by function)
+ * @see ucol_getVariableTop
+ * @see ucol_setVariableTop
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+ucol_restoreVariableTop(UCollator *coll, const uint32_t varTop, UErrorCode *status);
+
+/**
+ * Thread safe cloning operation. The result is a clone of a given collator.
+ * @param coll collator to be cloned
+ * @param stackBuffer user allocated space for the new clone. 
+ * If NULL new memory will be allocated. 
+ *  If buffer is not large enough, new memory will be allocated.
+ *  Clients can use the U_COL_SAFECLONE_BUFFERSIZE. 
+ *  This will probably be enough to avoid memory allocations.
+ * @param pBufferSize pointer to size of allocated space. 
+ *  If *pBufferSize == 0, a sufficient size for use in cloning will 
+ *  be returned ('pre-flighting')
+ *  If *pBufferSize is not enough for a stack-based safe clone, 
+ *  new memory will be allocated.
+ * @param status to indicate whether the operation went on smoothly or there were errors
+ *    An informational status value, U_SAFECLONE_ALLOCATED_ERROR, is used if any
+ * allocations were necessary.
+ * @return pointer to the new clone
+ * @see ucol_open
+ * @see ucol_openRules
+ * @see ucol_close
+ * @stable ICU 2.0
+ */
+U_STABLE UCollator* U_EXPORT2 
+ucol_safeClone(const UCollator *coll,
+               void            *stackBuffer,
+               int32_t         *pBufferSize,
+               UErrorCode      *status);
+
+/** default memory size for the new clone. It needs to be this large for os/400 large pointers 
+ * @stable ICU 2.0
+ */
+#define U_COL_SAFECLONE_BUFFERSIZE 512
+
+/**
+ * Returns current rules. Delta defines whether full rules are returned or just the tailoring. 
+ * Returns number of UChars needed to store rules. If buffer is NULL or bufferLen is not enough 
+ * to store rules, will store up to available space.
+ * @param coll collator to get the rules from
+ * @param delta one of UCOL_TAILORING_ONLY, UCOL_FULL_RULES. 
+ * @param buffer buffer to store the result in. If NULL, you'll get no rules.
+ * @param bufferLen lenght of buffer to store rules in. If less then needed you'll get only the part that fits in.
+ * @return current rules
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2 
+ucol_getRulesEx(const UCollator *coll, UColRuleOption delta, UChar *buffer, int32_t bufferLen);
+
+/**
+ * gets the locale name of the collator. If the collator
+ * is instantiated from the rules, then this function returns
+ * NULL.
+ * @param coll The UCollator for which the locale is needed
+ * @param type You can choose between requested, valid and actual
+ *             locale. For description see the definition of
+ *             ULocDataLocaleType in uloc.h
+ * @param status error code of the operation
+ * @return real locale name from which the collation data comes. 
+ *         If the collator was instantiated from rules, returns
+ *         NULL.
+ * @deprecated ICU 2.8 Use ucol_getLocaleByType instead
+ */
+U_DEPRECATED const char * U_EXPORT2
+ucol_getLocale(const UCollator *coll, ULocDataLocaleType type, UErrorCode *status);
+
+
+/**
+ * gets the locale name of the collator. If the collator
+ * is instantiated from the rules, then this function returns
+ * NULL.
+ * @param coll The UCollator for which the locale is needed
+ * @param type You can choose between requested, valid and actual
+ *             locale. For description see the definition of
+ *             ULocDataLocaleType in uloc.h
+ * @param status error code of the operation
+ * @return real locale name from which the collation data comes. 
+ *         If the collator was instantiated from rules, returns
+ *         NULL.
+ * @stable ICU 2.8
+ */
+U_STABLE const char * U_EXPORT2
+ucol_getLocaleByType(const UCollator *coll, ULocDataLocaleType type, UErrorCode *status);
+
+/**
+ * Get an Unicode set that contains all the characters and sequences tailored in 
+ * this collator. The result must be disposed of by using uset_close.
+ * @param coll        The UCollator for which we want to get tailored chars
+ * @param status      error code of the operation
+ * @return a pointer to newly created USet. Must be be disposed by using uset_close
+ * @see ucol_openRules
+ * @see uset_close
+ * @stable ICU 2.4
+ */
+U_STABLE USet * U_EXPORT2
+ucol_getTailoredSet(const UCollator *coll, UErrorCode *status);
+
+/**
+ * Universal attribute getter that returns UCOL_DEFAULT if the value is default
+ * @param coll collator which attributes are to be changed
+ * @param attr attribute type
+ * @return attribute value or UCOL_DEFAULT if the value is default
+ * @param status to indicate whether the operation went on smoothly or there were errors
+ * @see UColAttribute
+ * @see UColAttributeValue
+ * @see ucol_setAttribute
+ * @internal ICU 3.0
+ */
+U_INTERNAL UColAttributeValue  U_EXPORT2
+ucol_getAttributeOrDefault(const UCollator *coll, UColAttribute attr, UErrorCode *status);
+
+/** Check whether two collators are equal. Collators are considered equal if they
+ *  will sort strings the same. This means that both the current attributes and the
+ *  rules must be equivalent. Currently used for RuleBasedCollator::operator==.
+ *  @param source first collator
+ *  @param target second collator
+ *  @return TRUE or FALSE
+ *  @internal ICU 3.0
+ */
+U_INTERNAL UBool U_EXPORT2
+ucol_equals(const UCollator *source, const UCollator *target);
+
+/** Calculates the set of unsafe code points, given a collator.
+ *   A character is unsafe if you could append any character and cause the ordering to alter significantly.
+ *   Collation sorts in normalized order, so anything that rearranges in normalization can cause this.
+ *   Thus if you have a character like a_umlaut, and you add a lower_dot to it,
+ *   then it normalizes to a_lower_dot + umlaut, and sorts differently.
+ *  @param coll Collator
+ *  @param unsafe a fill-in set to receive the unsafe points
+ *  @param status for catching errors
+ *  @return number of elements in the set
+ *  @internal ICU 3.0
+ */
+U_INTERNAL int32_t U_EXPORT2
+ucol_getUnsafeSet( const UCollator *coll,
+                  USet *unsafe,
+                  UErrorCode *status);
+
+/** Reset UCA's static pointers. You don't want to use this, unless your static memory can go away.
+ * @internal ICU 3.2.1
+ */
+U_INTERNAL void U_EXPORT2
+ucol_forgetUCA(void);
+
+/** Touches all resources needed for instantiating a collator from a short string definition,
+ *  thus filling up the cache.
+ * @param definition A short string containing a locale and a set of attributes. 
+ *                   Attributes not explicitly mentioned are left at the default
+ *                   state for a locale.
+ * @param parseError if not NULL, structure that will get filled with error's pre
+ *                   and post context in case of error.
+ * @param forceDefaults if FALSE, the settings that are the same as the collator 
+ *                   default settings will not be applied (for example, setting
+ *                   French secondary on a French collator would not be executed). 
+ *                   If TRUE, all the settings will be applied regardless of the 
+ *                   collator default value. If the definition
+ *                   strings are to be cached, should be set to FALSE.
+ * @param status     Error code. Apart from regular error conditions connected to 
+ *                   instantiating collators (like out of memory or similar), this
+ *                   API will return an error if an invalid attribute or attribute/value
+ *                   combination is specified.
+ * @see ucol_openFromShortString
+ * @internal ICU 3.2.1
+ */
+U_INTERNAL void U_EXPORT2
+ucol_prepareShortStringOpen( const char *definition,
+                          UBool forceDefaults,
+                          UParseError *parseError,
+                          UErrorCode *status);
+
+/** Creates a binary image of a collator. This binary image can be stored and 
+ *  later used to instantiate a collator using ucol_openBinary.
+ *  This API supports preflighting.
+ *  @param coll Collator
+ *  @param buffer a fill-in buffer to receive the binary image
+ *  @param capacity capacity of the destination buffer
+ *  @param status for catching errors
+ *  @return size of the image
+ *  @see ucol_openBinary
+ *  @stable ICU 3.2
+ */
+U_STABLE int32_t U_EXPORT2
+ucol_cloneBinary(const UCollator *coll,
+                 uint8_t *buffer, int32_t capacity,
+                 UErrorCode *status);
+
+/** Opens a collator from a collator binary image created using
+ *  ucol_cloneBinary. Binary image used in instantiation of the 
+ *  collator remains owned by the user and should stay around for 
+ *  the lifetime of the collator. The API also takes a base collator
+ *  which usualy should be UCA.
+ *  @param bin binary image owned by the user and required through the
+ *             lifetime of the collator
+ *  @param length size of the image. If negative, the API will try to
+ *                figure out the length of the image
+ *  @param base fallback collator, usually UCA. Base is required to be
+ *              present through the lifetime of the collator. Currently 
+ *              it cannot be NULL.
+ *  @param status for catching errors
+ *  @return newly created collator
+ *  @see ucol_cloneBinary
+ *  @stable ICU 3.2
+ */
+U_STABLE UCollator* U_EXPORT2
+ucol_openBinary(const uint8_t *bin, int32_t length, 
+                const UCollator *base, 
+                UErrorCode *status);
+
+
+#endif /* #if !UCONFIG_NO_COLLATION */
+
+#endif
+


[24/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/js/libs/ace/ext-searchbox.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/js/libs/ace/ext-searchbox.js b/apps/fauxton/assets/js/libs/ace/ext-searchbox.js
deleted file mode 100644
index 2acaf73..0000000
--- a/apps/fauxton/assets/js/libs/ace/ext-searchbox.js
+++ /dev/null
@@ -1,420 +0,0 @@
-/* ***** BEGIN LICENSE BLOCK *****
- * Distributed under the BSD license:
- *
- * Copyright (c) 2010, Ajax.org B.V.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above copyright
- *       notice, this list of conditions and the following disclaimer in the
- *       documentation and/or other materials provided with the distribution.
- *     * Neither the name of Ajax.org B.V. nor the
- *       names of its contributors may be used to endorse or promote products
- *       derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * ***** END LICENSE BLOCK ***** */
-
-define('ace/ext/searchbox', ['require', 'exports', 'module' , 'ace/lib/dom', 'ace/lib/lang', 'ace/lib/event', 'ace/keyboard/hash_handler', 'ace/lib/keys'], function(require, exports, module) {
-
-
-var dom = require("../lib/dom");
-var lang = require("../lib/lang");
-var event = require("../lib/event");
-var searchboxCss = "\
-/* ------------------------------------------------------------------------------------------\
-* Editor Search Form\
-* --------------------------------------------------------------------------------------- */\
-.ace_search {\
-background-color: #ddd;\
-border: 1px solid #cbcbcb;\
-border-top: 0 none;\
-max-width: 297px;\
-overflow: hidden;\
-margin: 0;\
-padding: 4px;\
-padding-right: 6px;\
-padding-bottom: 0;\
-position: absolute;\
-top: 0px;\
-z-index: 99;\
-}\
-.ace_search.left {\
-border-left: 0 none;\
-border-radius: 0px 0px 5px 0px;\
-left: 0;\
-}\
-.ace_search.right {\
-border-radius: 0px 0px 0px 5px;\
-border-right: 0 none;\
-right: 0;\
-}\
-.ace_search_form, .ace_replace_form {\
-border-radius: 3px;\
-border: 1px solid #cbcbcb;\
-float: left;\
-margin-bottom: 4px;\
-overflow: hidden;\
-}\
-.ace_search_form.ace_nomatch {\
-outline: 1px solid red;\
-}\
-.ace_search_field {\
-background-color: white;\
-border-right: 1px solid #cbcbcb;\
-border: 0 none;\
--webkit-box-sizing: border-box;\
--moz-box-sizing: border-box;\
-box-sizing: border-box;\
-display: block;\
-float: left;\
-height: 22px;\
-outline: 0;\
-padding: 0 7px;\
-width: 214px;\
-margin: 0;\
-}\
-.ace_searchbtn,\
-.ace_replacebtn {\
-background: #fff;\
-border: 0 none;\
-border-left: 1px solid #dcdcdc;\
-cursor: pointer;\
-display: block;\
-float: left;\
-height: 22px;\
-margin: 0;\
-padding: 0;\
-position: relative;\
-}\
-.ace_searchbtn:last-child,\
-.ace_replacebtn:last-child {\
-border-top-right-radius: 3px;\
-border-bottom-right-radius: 3px;\
-}\
-.ace_searchbtn:disabled {\
-background: none;\
-cursor: default;\
-}\
-.ace_searchbtn {\
-background-position: 50% 50%;\
-background-repeat: no-repeat;\
-width: 27px;\
-}\
-.ace_searchbtn.prev {\
-background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAFCAYAAAB4ka1VAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAADFJREFUeNpiSU1NZUAC/6E0I0yACYskCpsJiySKIiY0SUZk40FyTEgCjGgKwTRAgAEAQJUIPCE+qfkAAAAASUVORK5CYII=);    \
-}\
-.ace_searchbtn.next {\
-background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAFCAYAAAB4ka1VAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAADRJREFUeNpiTE1NZQCC/0DMyIAKwGJMUAYDEo3M/s+EpvM/mkKwCQxYjIeLMaELoLMBAgwAU7UJObTKsvAAAAAASUVORK5CYII=);    \
-}\
-.ace_searchbtn_close {\
-background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAcCAYAAABRVo5BAAAAZ0lEQVR42u2SUQrAMAhDvazn8OjZBilCkYVVxiis8H4CT0VrAJb4WHT3C5xU2a2IQZXJjiQIRMdkEoJ5Q2yMqpfDIo+XY4k6h+YXOyKqTIj5REaxloNAd0xiKmAtsTHqW8sR2W5f7gCu5nWFUpVjZwAAAABJRU5ErkJggg==) no-repeat 50% 0;\
-border-radius: 50%;\
-border: 0 none;\
-color: #656565;\
-cursor: pointer;\
-display: block;\
-float: right;\
-font-family: Arial;\
-font-size: 16px;\
-height: 14px;\
-line-height: 16px;\
-margin: 5px 1px 9px 5px;\
-padding: 0;\
-text-align: center;\
-width: 14px;\
-}\
-.ace_searchbtn_close:hover {\
-background-color: #656565;\
-background-position: 50% 100%;\
-color: white;\
-}\
-.ace_replacebtn.prev {\
-width: 54px\
-}\
-.ace_replacebtn.next {\
-width: 27px\
-}\
-.ace_button {\
-margin-left: 2px;\
-cursor: pointer;\
--webkit-user-select: none;\
--moz-user-select: none;\
--o-user-select: none;\
--ms-user-select: none;\
-user-select: none;\
-overflow: hidden;\
-opacity: 0.7;\
-border: 1px solid rgba(100,100,100,0.23);\
-padding: 1px;\
--moz-box-sizing: border-box;\
-box-sizing:    border-box;\
-color: black;\
-}\
-.ace_button:hover {\
-background-color: #eee;\
-opacity:1;\
-}\
-.ace_button:active {\
-background-color: #ddd;\
-}\
-.ace_button.checked {\
-border-color: #3399ff;\
-opacity:1;\
-}\
-.ace_search_options{\
-margin-bottom: 3px;\
-text-align: right;\
--webkit-user-select: none;\
--moz-user-select: none;\
--o-user-select: none;\
--ms-user-select: none;\
-user-select: none;\
-}";
-var HashHandler = require("../keyboard/hash_handler").HashHandler;
-var keyUtil = require("../lib/keys");
-
-dom.importCssString(searchboxCss, "ace_searchbox");
-
-var html = '<div class="ace_search right">\
-    <button type="button" action="hide" class="ace_searchbtn_close"></button>\
-    <div class="ace_search_form">\
-        <input class="ace_search_field" placeholder="Search for" spellcheck="false"></input>\
-        <button type="button" action="findNext" class="ace_searchbtn next"></button>\
-        <button type="button" action="findPrev" class="ace_searchbtn prev"></button>\
-    </div>\
-    <div class="ace_replace_form">\
-        <input class="ace_search_field" placeholder="Replace with" spellcheck="false"></input>\
-        <button type="button" action="replaceAndFindNext" class="ace_replacebtn">Replace</button>\
-        <button type="button" action="replaceAll" class="ace_replacebtn">All</button>\
-    </div>\
-    <div class="ace_search_options">\
-        <span action="toggleRegexpMode" class="ace_button" title="RegExp Search">.*</span>\
-        <span action="toggleCaseSensitive" class="ace_button" title="CaseSensitive Search">Aa</span>\
-        <span action="toggleWholeWords" class="ace_button" title="Whole Word Search">\\b</span>\
-    </div>\
-</div>'.replace(/>\s+/g, ">");
-
-var SearchBox = function(editor, range, showReplaceForm) {
-    var div = dom.createElement("div");
-    div.innerHTML = html;
-    this.element = div.firstChild;
-
-    this.$init();
-    this.setEditor(editor);
-};
-
-(function() {
-    this.setEditor = function(editor) {
-        editor.searchBox = this;
-        editor.container.appendChild(this.element);
-        this.editor = editor;
-    };
-
-    this.$initElements = function(sb) {
-        this.searchBox = sb.querySelector(".ace_search_form");
-        this.replaceBox = sb.querySelector(".ace_replace_form");
-        this.searchOptions = sb.querySelector(".ace_search_options");
-        this.regExpOption = sb.querySelector("[action=toggleRegexpMode]");
-        this.caseSensitiveOption = sb.querySelector("[action=toggleCaseSensitive]");
-        this.wholeWordOption = sb.querySelector("[action=toggleWholeWords]");
-        this.searchInput = this.searchBox.querySelector(".ace_search_field");
-        this.replaceInput = this.replaceBox.querySelector(".ace_search_field");
-    };
-    
-    this.$init = function() {
-        var sb = this.element;
-        
-        this.$initElements(sb);
-        
-        var _this = this;
-        event.addListener(sb, "mousedown", function(e) {
-            setTimeout(function(){
-                _this.activeInput.focus();
-            }, 0);
-            event.stopPropagation(e);
-        });
-        event.addListener(sb, "click", function(e) {
-            var t = e.target || e.srcElement;
-            var action = t.getAttribute("action");
-            if (action && _this[action])
-                _this[action]();
-            else if (_this.$searchBarKb.commands[action])
-                _this.$searchBarKb.commands[action].exec(_this);
-            event.stopPropagation(e);
-        });
-
-        event.addCommandKeyListener(sb, function(e, hashId, keyCode) {
-            var keyString = keyUtil.keyCodeToString(keyCode);
-            var command = _this.$searchBarKb.findKeyCommand(hashId, keyString);
-            if (command && command.exec) {
-                command.exec(_this);
-                event.stopEvent(e);
-            }
-        });
-
-        this.$onChange = lang.delayedCall(function() {
-            _this.find(false, false);
-        });
-
-        event.addListener(this.searchInput, "input", function() {
-            _this.$onChange.schedule(20);
-        });
-        event.addListener(this.searchInput, "focus", function() {
-            _this.activeInput = _this.searchInput;
-            _this.searchInput.value && _this.highlight();
-        });
-        event.addListener(this.replaceInput, "focus", function() {
-            _this.activeInput = _this.replaceInput;
-            _this.searchInput.value && _this.highlight();
-        });
-    };
-    this.$closeSearchBarKb = new HashHandler([{
-        bindKey: "Esc",
-        name: "closeSearchBar",
-        exec: function(editor) {
-            editor.searchBox.hide();
-        }
-    }]);
-    this.$searchBarKb = new HashHandler();
-    this.$searchBarKb.bindKeys({
-        "Ctrl-f|Command-f|Ctrl-H|Command-Option-F": function(sb) {
-            var isReplace = sb.isReplace = !sb.isReplace;
-            sb.replaceBox.style.display = isReplace ? "" : "none";
-            sb[isReplace ? "replaceInput" : "searchInput"].focus();
-        },
-        "Ctrl-G|Command-G": function(sb) {
-            sb.findNext();
-        },
-        "Ctrl-Shift-G|Command-Shift-G": function(sb) {
-            sb.findPrev();
-        },
-        "esc": function(sb) {
-            setTimeout(function() { sb.hide();});
-        },
-        "Return": function(sb) {
-            if (sb.activeInput == sb.replaceInput)
-                sb.replace();
-            sb.findNext();
-        },
-        "Shift-Return": function(sb) {
-            if (sb.activeInput == sb.replaceInput)
-                sb.replace();
-            sb.findPrev();
-        },
-        "Tab": function(sb) {
-            (sb.activeInput == sb.replaceInput ? sb.searchInput : sb.replaceInput).focus();
-        }
-    });
-
-    this.$searchBarKb.addCommands([{
-        name: "toggleRegexpMode",
-        bindKey: {win: "Alt-R|Alt-/", mac: "Ctrl-Alt-R|Ctrl-Alt-/"},
-        exec: function(sb) {
-            sb.regExpOption.checked = !sb.regExpOption.checked;
-            sb.$syncOptions();
-        }
-    }, {
-        name: "toggleCaseSensitive",
-        bindKey: {win: "Alt-C|Alt-I", mac: "Ctrl-Alt-R|Ctrl-Alt-I"},
-        exec: function(sb) {
-            sb.caseSensitiveOption.checked = !sb.caseSensitiveOption.checked;
-            sb.$syncOptions();
-        }
-    }, {
-        name: "toggleWholeWords",
-        bindKey: {win: "Alt-B|Alt-W", mac: "Ctrl-Alt-B|Ctrl-Alt-W"},
-        exec: function(sb) {
-            sb.wholeWordOption.checked = !sb.wholeWordOption.checked;
-            sb.$syncOptions();
-        }
-    }]);
-
-    this.$syncOptions = function() {
-        dom.setCssClass(this.regExpOption, "checked", this.regExpOption.checked);
-        dom.setCssClass(this.wholeWordOption, "checked", this.wholeWordOption.checked);
-        dom.setCssClass(this.caseSensitiveOption, "checked", this.caseSensitiveOption.checked);
-        this.find(false, false);
-    };
-
-    this.highlight = function(re) {
-        this.editor.session.highlight(re || this.editor.$search.$options.re);
-        this.editor.renderer.updateBackMarkers()
-    };
-    this.find = function(skipCurrent, backwards) {
-        var range = this.editor.find(this.searchInput.value, {
-            skipCurrent: skipCurrent,
-            backwards: backwards,
-            wrap: true,
-            regExp: this.regExpOption.checked,
-            caseSensitive: this.caseSensitiveOption.checked,
-            wholeWord: this.wholeWordOption.checked
-        });
-        var noMatch = !range && this.searchInput.value;
-        dom.setCssClass(this.searchBox, "ace_nomatch", noMatch);
-        this.editor._emit("findSearchBox", { match: !noMatch });
-        this.highlight();
-    };
-    this.findNext = function() {
-        this.find(true, false);
-    };
-    this.findPrev = function() {
-        this.find(true, true);
-    };
-    this.replace = function() {
-        if (!this.editor.getReadOnly())
-            this.editor.replace(this.replaceInput.value);
-    };    
-    this.replaceAndFindNext = function() {
-        if (!this.editor.getReadOnly()) {
-            this.editor.replace(this.replaceInput.value);
-            this.findNext()
-        }
-    };
-    this.replaceAll = function() {
-        if (!this.editor.getReadOnly())
-            this.editor.replaceAll(this.replaceInput.value);
-    };
-
-    this.hide = function() {
-        this.element.style.display = "none";
-        this.editor.keyBinding.removeKeyboardHandler(this.$closeSearchBarKb);
-        this.editor.focus();
-    };
-    this.show = function(value, isReplace) {
-        this.element.style.display = "";
-        this.replaceBox.style.display = isReplace ? "" : "none";
-
-        this.isReplace = isReplace;
-
-        if (value)
-            this.searchInput.value = value;
-        this.searchInput.focus();
-        this.searchInput.select();
-
-        this.editor.keyBinding.addKeyboardHandler(this.$closeSearchBarKb);
-    };
-
-}).call(SearchBox.prototype);
-
-exports.SearchBox = SearchBox;
-
-exports.Search = function(editor, isReplace) {
-    var sb = editor.searchBox || new SearchBox(editor);
-    sb.show(editor.session.getTextRange(), isReplace);
-};
-
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/js/libs/ace/ext-settings_menu.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/js/libs/ace/ext-settings_menu.js b/apps/fauxton/assets/js/libs/ace/ext-settings_menu.js
deleted file mode 100644
index 5d866d1..0000000
--- a/apps/fauxton/assets/js/libs/ace/ext-settings_menu.js
+++ /dev/null
@@ -1,634 +0,0 @@
-/* ***** BEGIN LICENSE BLOCK *****
- * Distributed under the BSD license:
- *
- * Copyright (c) 2013 Matthew Christopher Kastor-Inare III, Atropa Inc. Intl
- * All rights reserved.
- *
- * Contributed to Ajax.org under the BSD license.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above copyright
- *       notice, this list of conditions and the following disclaimer in the
- *       documentation and/or other materials provided with the distribution.
- *     * Neither the name of Ajax.org B.V. nor the
- *       names of its contributors may be used to endorse or promote products
- *       derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * ***** END LICENSE BLOCK ***** */
-
-define('ace/ext/settings_menu', ['require', 'exports', 'module' , 'ace/ext/menu_tools/generate_settings_menu', 'ace/ext/menu_tools/overlay_page', 'ace/editor'], function(require, exports, module) {
-
-var generateSettingsMenu = require('./menu_tools/generate_settings_menu').generateSettingsMenu;
-var overlayPage = require('./menu_tools/overlay_page').overlayPage;
-function showSettingsMenu(editor) {
-    var sm = document.getElementById('ace_settingsmenu');
-    if (!sm)    
-        overlayPage(editor, generateSettingsMenu(editor), '0', '0', '0');
-}
-module.exports.init = function(editor) {
-    var Editor = require("ace/editor").Editor;
-    Editor.prototype.showSettingsMenu = function() {
-        showSettingsMenu(this);
-    };
-};
-});
-
-define('ace/ext/menu_tools/generate_settings_menu', ['require', 'exports', 'module' , 'ace/ext/menu_tools/element_generator', 'ace/ext/menu_tools/add_editor_menu_options', 'ace/ext/menu_tools/get_set_functions'], function(require, exports, module) {
-
-var egen = require('./element_generator');
-var addEditorMenuOptions = require('./add_editor_menu_options').addEditorMenuOptions;
-var getSetFunctions = require('./get_set_functions').getSetFunctions;
-module.exports.generateSettingsMenu = function generateSettingsMenu (editor) {
-    var elements = [];
-    function cleanupElementsList() {
-        elements.sort(function(a, b) {
-            var x = a.getAttribute('contains');
-            var y = b.getAttribute('contains');
-            return x.localeCompare(y);
-        });
-    }
-    function wrapElements() {
-        var topmenu = document.createElement('div');
-        topmenu.setAttribute('id', 'ace_settingsmenu');
-        elements.forEach(function(element) {
-            topmenu.appendChild(element);
-        });
-        return topmenu;
-    }
-    function createNewEntry(obj, clss, item, val) {
-        var el;
-        var div = document.createElement('div');
-        div.setAttribute('contains', item);
-        div.setAttribute('class', 'ace_optionsMenuEntry');
-        div.setAttribute('style', 'clear: both;');
-
-        div.appendChild(egen.createLabel(
-            item.replace(/^set/, '').replace(/([A-Z])/g, ' $1').trim(),
-            item
-        ));
-
-        if (Array.isArray(val)) {
-            el = egen.createSelection(item, val, clss);
-            el.addEventListener('change', function(e) {
-                try{
-                    editor.menuOptions[e.target.id].forEach(function(x) {
-                        if(x.textContent !== e.target.textContent) {
-                            delete x.selected;
-                        }
-                    });
-                    obj[e.target.id](e.target.value);
-                } catch (err) {
-                    throw new Error(err);
-                }
-            });
-        } else if(typeof val === 'boolean') {
-            el = egen.createCheckbox(item, val, clss);
-            el.addEventListener('change', function(e) {
-                try{
-                    obj[e.target.id](!!e.target.checked);
-                } catch (err) {
-                    throw new Error(err);
-                }
-            });
-        } else {
-            el = egen.createInput(item, val, clss);
-            el.addEventListener('change', function(e) {
-                try{
-                    if(e.target.value === 'true') {
-                        obj[e.target.id](true);
-                    } else if(e.target.value === 'false') {
-                        obj[e.target.id](false);
-                    } else {
-                        obj[e.target.id](e.target.value);
-                    }
-                } catch (err) {
-                    throw new Error(err);
-                }
-            });
-        }
-        el.style.cssText = 'float:right;';
-        div.appendChild(el);
-        return div;
-    }
-    function makeDropdown(item, esr, clss, fn) {
-        var val = editor.menuOptions[item];
-        var currentVal = esr[fn]();
-        if (typeof currentVal == 'object')
-            currentVal = currentVal.$id;
-        val.forEach(function(valuex) {
-            if (valuex.value === currentVal)
-                valuex.selected = 'selected';
-        });
-        return createNewEntry(esr, clss, item, val);
-    }
-    function handleSet(setObj) {
-        var item = setObj.functionName;
-        var esr = setObj.parentObj;
-        var clss = setObj.parentName;
-        var val;
-        var fn = item.replace(/^set/, 'get');
-        if(editor.menuOptions[item] !== undefined) {
-            elements.push(makeDropdown(item, esr, clss, fn));
-        } else if(typeof esr[fn] === 'function') {
-            try {
-                val = esr[fn]();
-                if(typeof val === 'object') {
-                    val = val.$id;
-                }
-                elements.push(
-                    createNewEntry(esr, clss, item, val)
-                );
-            } catch (e) {
-            }
-        }
-    }
-    addEditorMenuOptions(editor);
-    getSetFunctions(editor).forEach(function(setObj) {
-        handleSet(setObj);
-    });
-    cleanupElementsList();
-    return wrapElements();
-};
-
-});
-
-define('ace/ext/menu_tools/element_generator', ['require', 'exports', 'module' ], function(require, exports, module) {
-module.exports.createOption = function createOption (obj) {
-    var attribute;
-    var el = document.createElement('option');
-    for(attribute in obj) {
-        if(obj.hasOwnProperty(attribute)) {
-            if(attribute === 'selected') {
-                el.setAttribute(attribute, obj[attribute]);
-            } else {
-                el[attribute] = obj[attribute];
-            }
-        }
-    }
-    return el;
-};
-module.exports.createCheckbox = function createCheckbox (id, checked, clss) {
-    var el = document.createElement('input');
-    el.setAttribute('type', 'checkbox');
-    el.setAttribute('id', id);
-    el.setAttribute('name', id);
-    el.setAttribute('value', checked);
-    el.setAttribute('class', clss);
-    if(checked) {
-        el.setAttribute('checked', 'checked');
-    }
-    return el;
-};
-module.exports.createInput = function createInput (id, value, clss) {
-    var el = document.createElement('input');
-    el.setAttribute('type', 'text');
-    el.setAttribute('id', id);
-    el.setAttribute('name', id);
-    el.setAttribute('value', value);
-    el.setAttribute('class', clss);
-    return el;
-};
-module.exports.createLabel = function createLabel (text, labelFor) {
-    var el = document.createElement('label');
-    el.setAttribute('for', labelFor);
-    el.textContent = text;
-    return el;
-};
-module.exports.createSelection = function createSelection (id, values, clss) {
-    var el = document.createElement('select');
-    el.setAttribute('id', id);
-    el.setAttribute('name', id);
-    el.setAttribute('class', clss);
-    values.forEach(function(item) {
-        el.appendChild(module.exports.createOption(item));
-    });
-    return el;
-};
-
-});
-
-define('ace/ext/menu_tools/add_editor_menu_options', ['require', 'exports', 'module' , 'ace/ext/modelist', 'ace/ext/themelist'], function(require, exports, module) {
-module.exports.addEditorMenuOptions = function addEditorMenuOptions (editor) {
-    var modelist = require('../modelist');
-    var themelist = require('../themelist');
-    editor.menuOptions = {
-        "setNewLineMode" : [{
-            "textContent" : "unix",
-            "value" : "unix"
-        }, {
-            "textContent" : "windows",
-            "value" : "windows"
-        }, {
-            "textContent" : "auto",
-            "value" : "auto"
-        }],
-        "setTheme" : [],
-        "setMode" : [],
-        "setKeyboardHandler": [{
-            "textContent" : "ace",
-            "value" : ""
-        }, {
-            "textContent" : "vim",
-            "value" : "ace/keyboard/vim"
-        }, {
-            "textContent" : "emacs",
-            "value" : "ace/keyboard/emacs"
-        }]
-    };
-
-    editor.menuOptions.setTheme = themelist.themes.map(function(theme) {
-        return {
-            'textContent' : theme.desc,
-            'value' : theme.theme
-        };
-    });
-
-    editor.menuOptions.setMode = modelist.modes.map(function(mode) {
-        return {
-            'textContent' : mode.name,
-            'value' : mode.mode
-        };
-    });
-};
-
-
-});define('ace/ext/modelist', ['require', 'exports', 'module' ], function(require, exports, module) {
-
-
-var modes = [];
-function getModeForPath(path) {
-    var mode = modesByName.text;
-    var fileName = path.split(/[\/\\]/).pop();
-    for (var i = 0; i < modes.length; i++) {
-        if (modes[i].supportsFile(fileName)) {
-            mode = modes[i];
-            break;
-        }
-    }
-    return mode;
-}
-
-var Mode = function(name, caption, extensions) {
-    this.name = name;
-    this.caption = caption;
-    this.mode = "ace/mode/" + name;
-    this.extensions = extensions;
-    if (/\^/.test(extensions)) {
-        var re = extensions.replace(/\|(\^)?/g, function(a, b){
-            return "$|" + (b ? "^" : "^.*\\.");
-        }) + "$";
-    } else {
-        var re = "^.*\\.(" + extensions + ")$";
-    }
-
-    this.extRe = new RegExp(re, "gi");
-};
-
-Mode.prototype.supportsFile = function(filename) {
-    return filename.match(this.extRe);
-};
-var supportedModes = {
-    ABAP:        ["abap"],
-    ActionScript:["as"],
-    ADA:         ["ada|adb"],
-    AsciiDoc:    ["asciidoc"],
-    Assembly_x86:["asm"],
-    AutoHotKey:  ["ahk"],
-    BatchFile:   ["bat|cmd"],
-    C9Search:    ["c9search_results"],
-    C_Cpp:       ["cpp|c|cc|cxx|h|hh|hpp"],
-    Clojure:     ["clj"],
-    Cobol:       ["CBL|COB"],
-    coffee:      ["coffee|cf|cson|^Cakefile"],
-    ColdFusion:  ["cfm"],
-    CSharp:      ["cs"],
-    CSS:         ["css"],
-    Curly:       ["curly"],
-    D:           ["d|di"],
-    Dart:        ["dart"],
-    Diff:        ["diff|patch"],
-    Dot:         ["dot"],
-    Erlang:      ["erl|hrl"],
-    EJS:         ["ejs"],
-    Forth:       ["frt|fs|ldr"],
-    FTL:         ["ftl"],
-    Glsl:        ["glsl|frag|vert"],
-    golang:      ["go"],
-    Groovy:      ["groovy"],
-    HAML:        ["haml"],
-    Handlebars:  ["hbs|handlebars|tpl|mustache"],
-    Haskell:     ["hs"],
-    haXe:        ["hx"],
-    HTML:        ["html|htm|xhtml"],
-    HTML_Ruby:   ["erb|rhtml|html.erb"],
-    INI:         ["ini|conf|cfg|prefs"],
-    Jack:        ["jack"],
-    Jade:        ["jade"],
-    Java:        ["java"],
-    JavaScript:  ["js|jsm"],
-    JSON:        ["json"],
-    JSONiq:      ["jq"],
-    JSP:         ["jsp"],
-    JSX:         ["jsx"],
-    Julia:       ["jl"],
-    LaTeX:       ["tex|latex|ltx|bib"],
-    LESS:        ["less"],
-    Liquid:      ["liquid"],
-    Lisp:        ["lisp"],
-    LiveScript:  ["ls"],
-    LogiQL:      ["logic|lql"],
-    LSL:         ["lsl"],
-    Lua:         ["lua"],
-    LuaPage:     ["lp"],
-    Lucene:      ["lucene"],
-    Makefile:    ["^Makefile|^GNUmakefile|^makefile|^OCamlMakefile|make"],
-    MATLAB:      ["matlab"],
-    Markdown:    ["md|markdown"],
-    MySQL:       ["mysql"],
-    MUSHCode:    ["mc|mush"],
-    Nix:         ["nix"],
-    ObjectiveC:  ["m|mm"],
-    OCaml:       ["ml|mli"],
-    Pascal:      ["pas|p"],
-    Perl:        ["pl|pm"],
-    pgSQL:       ["pgsql"],
-    PHP:         ["php|phtml"],
-    Powershell:  ["ps1"],
-    Prolog:      ["plg|prolog"],
-    Properties:  ["properties"],
-    Protobuf:    ["proto"],
-    Python:      ["py"],
-    R:           ["r"],
-    RDoc:        ["Rd"],
-    RHTML:       ["Rhtml"],
-    Ruby:        ["rb|ru|gemspec|rake|^Guardfile|^Rakefile|^Gemfile"],
-    Rust:        ["rs"],
-    SASS:        ["sass"],
-    SCAD:        ["scad"],
-    Scala:       ["scala"],
-    Scheme:      ["scm|rkt"],
-    SCSS:        ["scss"],
-    SH:          ["sh|bash|^.bashrc"],
-    SJS:         ["sjs"],
-    Space:       ["space"],
-    snippets:    ["snippets"],
-    Soy_Template:["soy"],
-    SQL:         ["sql"],
-    Stylus:      ["styl|stylus"],
-    SVG:         ["svg"],
-    Tcl:         ["tcl"],
-    Tex:         ["tex"],
-    Text:        ["txt"],
-    Textile:     ["textile"],
-    Toml:        ["toml"],
-    Twig:        ["twig"],
-    Typescript:  ["ts|typescript|str"],
-    VBScript:    ["vbs"],
-    Velocity:    ["vm"],
-    Verilog:     ["v|vh|sv|svh"],
-    XML:         ["xml|rdf|rss|wsdl|xslt|atom|mathml|mml|xul|xbl"],
-    XQuery:      ["xq"],
-    YAML:        ["yaml|yml"]
-};
-
-var nameOverrides = {
-    ObjectiveC: "Objective-C",
-    CSharp: "C#",
-    golang: "Go",
-    C_Cpp: "C/C++",
-    coffee: "CoffeeScript",
-    HTML_Ruby: "HTML (Ruby)",
-    FTL: "FreeMarker"
-};
-var modesByName = {};
-for (var name in supportedModes) {
-    var data = supportedModes[name];
-    var displayName = nameOverrides[name] || name;
-    var filename = name.toLowerCase();
-    var mode = new Mode(filename, displayName, data[0]);
-    modesByName[filename] = mode;
-    modes.push(mode);
-}
-
-module.exports = {
-    getModeForPath: getModeForPath,
-    modes: modes,
-    modesByName: modesByName
-};
-
-});
-
-define('ace/ext/themelist', ['require', 'exports', 'module' , 'ace/ext/themelist_utils/themes'], function(require, exports, module) {
-module.exports.themes = require('ace/ext/themelist_utils/themes').themes;
-module.exports.ThemeDescription = function(name) {
-    this.name = name;
-    this.desc = name.split('_'
-        ).map(
-            function(namePart) {
-                return namePart[0].toUpperCase() + namePart.slice(1);
-            }
-        ).join(' ');
-    this.theme = "ace/theme/" + name;
-};
-
-module.exports.themesByName = {};
-
-module.exports.themes = module.exports.themes.map(function(name) {
-    module.exports.themesByName[name] = new module.exports.ThemeDescription(name);
-    return module.exports.themesByName[name];
-});
-
-});
-
-define('ace/ext/themelist_utils/themes', ['require', 'exports', 'module' ], function(require, exports, module) {
-
-module.exports.themes = [
-    "ambiance",
-    "chaos",
-    "chrome",
-    "clouds",
-    "clouds_midnight",
-    "cobalt",
-    "crimson_editor",
-    "dawn",
-    "dreamweaver",
-    "eclipse",
-    "github",
-    "idle_fingers",
-    "kr_theme",
-    "merbivore",
-    "merbivore_soft",
-    "mono_industrial",
-    "monokai",
-    "pastel_on_dark",
-    "solarized_dark",
-    "solarized_light",
-    "terminal",
-    "textmate",
-    "tomorrow",
-    "tomorrow_night",
-    "tomorrow_night_blue",
-    "tomorrow_night_bright",
-    "tomorrow_night_eighties",
-    "twilight",
-    "vibrant_ink",
-    "xcode"
-];
-
-});
-
-define('ace/ext/menu_tools/get_set_functions', ['require', 'exports', 'module' ], function(require, exports, module) {
-module.exports.getSetFunctions = function getSetFunctions (editor) {
-    var out = [];
-    var my = {
-        'editor' : editor,
-        'session' : editor.session,
-        'renderer' : editor.renderer
-    };
-    var opts = [];
-    var skip = [
-        'setOption',
-        'setUndoManager',
-        'setDocument',
-        'setValue',
-        'setBreakpoints',
-        'setScrollTop',
-        'setScrollLeft',
-        'setSelectionStyle',
-        'setWrapLimitRange'
-    ];
-    ['renderer', 'session', 'editor'].forEach(function(esra) {
-        var esr = my[esra];
-        var clss = esra;
-        for(var fn in esr) {
-            if(skip.indexOf(fn) === -1) {
-                if(/^set/.test(fn) && opts.indexOf(fn) === -1) {
-                    opts.push(fn);
-                    out.push({
-                        'functionName' : fn,
-                        'parentObj' : esr,
-                        'parentName' : clss
-                    });
-                }
-            }
-        }
-    });
-    return out;
-};
-
-});
-
-define('ace/ext/menu_tools/overlay_page', ['require', 'exports', 'module' , 'ace/lib/dom'], function(require, exports, module) {
-
-var dom = require("../../lib/dom");
-var cssText = "#ace_settingsmenu, #kbshortcutmenu {\
-background-color: #F7F7F7;\
-color: black;\
-box-shadow: -5px 4px 5px rgba(126, 126, 126, 0.55);\
-padding: 1em 0.5em 2em 1em;\
-overflow: auto;\
-position: absolute;\
-margin: 0;\
-bottom: 0;\
-right: 0;\
-top: 0;\
-z-index: 9991;\
-cursor: default;\
-}\
-.ace_dark #ace_settingsmenu, .ace_dark #kbshortcutmenu {\
-box-shadow: -20px 10px 25px rgba(126, 126, 126, 0.25);\
-background-color: rgba(255, 255, 255, 0.6);\
-color: black;\
-}\
-.ace_optionsMenuEntry:hover {\
-background-color: rgba(100, 100, 100, 0.1);\
--webkit-transition: all 0.5s;\
-transition: all 0.3s\
-}\
-.ace_closeButton {\
-background: rgba(245, 146, 146, 0.5);\
-border: 1px solid #F48A8A;\
-border-radius: 50%;\
-padding: 7px;\
-position: absolute;\
-right: -8px;\
-top: -8px;\
-z-index: 1000;\
-}\
-.ace_closeButton{\
-background: rgba(245, 146, 146, 0.9);\
-}\
-.ace_optionsMenuKey {\
-color: darkslateblue;\
-font-weight: bold;\
-}\
-.ace_optionsMenuCommand {\
-color: darkcyan;\
-font-weight: normal;\
-}";
-dom.importCssString(cssText);
-module.exports.overlayPage = function overlayPage(editor, contentElement, top, right, bottom, left) {
-    top = top ? 'top: ' + top + ';' : '';
-    bottom = bottom ? 'bottom: ' + bottom + ';' : '';
-    right = right ? 'right: ' + right + ';' : '';
-    left = left ? 'left: ' + left + ';' : '';
-
-    var closer = document.createElement('div');
-    var contentContainer = document.createElement('div');
-
-    function documentEscListener(e) {
-        if (e.keyCode === 27) {
-            closer.click();
-        }
-    }
-
-    closer.style.cssText = 'margin: 0; padding: 0; ' +
-        'position: fixed; top:0; bottom:0; left:0; right:0;' +
-        'z-index: 9990; ' +
-        'background-color: rgba(0, 0, 0, 0.3);';
-    closer.addEventListener('click', function() {
-        document.removeEventListener('keydown', documentEscListener);
-        closer.parentNode.removeChild(closer);
-        editor.focus();
-        closer = null;
-    });
-    document.addEventListener('keydown', documentEscListener);
-
-    contentContainer.style.cssText = top + right + bottom + left;
-    contentContainer.addEventListener('click', function(e) {
-        e.stopPropagation();
-    });
-
-    var wrapper = dom.createElement("div");
-    wrapper.style.position = "relative";
-    
-    var closeButton = dom.createElement("div");
-    closeButton.className = "ace_closeButton";
-    closeButton.addEventListener('click', function() {
-        closer.click();
-    });
-    
-    wrapper.appendChild(closeButton);
-    contentContainer.appendChild(wrapper);
-    
-    contentContainer.appendChild(contentElement);
-    closer.appendChild(contentContainer);
-    document.body.appendChild(closer);
-    editor.blur();
-};
-
-});
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/js/libs/ace/ext-spellcheck.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/js/libs/ace/ext-spellcheck.js b/apps/fauxton/assets/js/libs/ace/ext-spellcheck.js
deleted file mode 100644
index 7f50e9b..0000000
--- a/apps/fauxton/assets/js/libs/ace/ext-spellcheck.js
+++ /dev/null
@@ -1,68 +0,0 @@
-define('ace/ext/spellcheck', ['require', 'exports', 'module' , 'ace/lib/event', 'ace/editor', 'ace/config'], function(require, exports, module) {
-
-var event = require("../lib/event");
-
-exports.contextMenuHandler = function(e){
-    var host = e.target;
-    var text = host.textInput.getElement();
-    if (!host.selection.isEmpty())
-        return;
-    var c = host.getCursorPosition();
-    var r = host.session.getWordRange(c.row, c.column);
-    var w = host.session.getTextRange(r);
-
-    host.session.tokenRe.lastIndex = 0;
-    if (!host.session.tokenRe.test(w))
-        return;
-    var PLACEHOLDER = "\x01\x01";
-    var value = w + " " + PLACEHOLDER;
-    text.value = value;
-    text.setSelectionRange(w.length, w.length + 1);
-    text.setSelectionRange(0, 0);
-    text.setSelectionRange(0, w.length);
-
-    var afterKeydown = false;
-    event.addListener(text, "keydown", function onKeydown() {
-        event.removeListener(text, "keydown", onKeydown);
-        afterKeydown = true;
-    });
-
-    host.textInput.setInputHandler(function(newVal) {
-        console.log(newVal , value, text.selectionStart, text.selectionEnd)
-        if (newVal == value)
-            return '';
-        if (newVal.lastIndexOf(value, 0) === 0)
-            return newVal.slice(value.length);
-        if (newVal.substr(text.selectionEnd) == value)
-            return newVal.slice(0, -value.length);
-        if (newVal.slice(-2) == PLACEHOLDER) {
-            var val = newVal.slice(0, -2);
-            if (val.slice(-1) == " ") {
-                if (afterKeydown)
-                    return val.substring(0, text.selectionEnd);
-                val = val.slice(0, -1);
-                host.session.replace(r, val);
-                return "";
-            }
-        }
-
-        return newVal;
-    });
-};
-var Editor = require("../editor").Editor;
-require("../config").defineOptions(Editor.prototype, "editor", {
-    spellcheck: {
-        set: function(val) {
-            var text = this.textInput.getElement();
-            text.spellcheck = !!val;
-            if (!val)
-                this.removeListener("nativecontextmenu", exports.contextMenuHandler);
-            else
-                this.on("nativecontextmenu", exports.contextMenuHandler);
-        },
-        value: true
-    }
-});
-
-});
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/js/libs/ace/ext-split.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/js/libs/ace/ext-split.js b/apps/fauxton/assets/js/libs/ace/ext-split.js
deleted file mode 100644
index 6e56844..0000000
--- a/apps/fauxton/assets/js/libs/ace/ext-split.js
+++ /dev/null
@@ -1,271 +0,0 @@
-/* ***** BEGIN LICENSE BLOCK *****
- * Distributed under the BSD license:
- *
- * Copyright (c) 2010, Ajax.org B.V.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above copyright
- *       notice, this list of conditions and the following disclaimer in the
- *       documentation and/or other materials provided with the distribution.
- *     * Neither the name of Ajax.org B.V. nor the
- *       names of its contributors may be used to endorse or promote products
- *       derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * ***** END LICENSE BLOCK ***** */
-
-define('ace/ext/split', ['require', 'exports', 'module' , 'ace/split'], function(require, exports, module) {
-module.exports = require("../split");
-
-});
-
-define('ace/split', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/lib/event_emitter', 'ace/editor', 'ace/virtual_renderer', 'ace/edit_session'], function(require, exports, module) {
-
-
-var oop = require("./lib/oop");
-var lang = require("./lib/lang");
-var EventEmitter = require("./lib/event_emitter").EventEmitter;
-
-var Editor = require("./editor").Editor;
-var Renderer = require("./virtual_renderer").VirtualRenderer;
-var EditSession = require("./edit_session").EditSession;
-
-
-var Split = function(container, theme, splits) {
-    this.BELOW = 1;
-    this.BESIDE = 0;
-
-    this.$container = container;
-    this.$theme = theme;
-    this.$splits = 0;
-    this.$editorCSS = "";
-    this.$editors = [];
-    this.$orientation = this.BESIDE;
-
-    this.setSplits(splits || 1);
-    this.$cEditor = this.$editors[0];
-
-
-    this.on("focus", function(editor) {
-        this.$cEditor = editor;
-    }.bind(this));
-};
-
-(function(){
-
-    oop.implement(this, EventEmitter);
-
-    this.$createEditor = function() {
-        var el = document.createElement("div");
-        el.className = this.$editorCSS;
-        el.style.cssText = "position: absolute; top:0px; bottom:0px";
-        this.$container.appendChild(el);
-        var editor = new Editor(new Renderer(el, this.$theme));
-
-        editor.on("focus", function() {
-            this._emit("focus", editor);
-        }.bind(this));
-
-        this.$editors.push(editor);
-        editor.setFontSize(this.$fontSize);
-        return editor;
-    };
-
-    this.setSplits = function(splits) {
-        var editor;
-        if (splits < 1) {
-            throw "The number of splits have to be > 0!";
-        }
-
-        if (splits == this.$splits) {
-            return;
-        } else if (splits > this.$splits) {
-            while (this.$splits < this.$editors.length && this.$splits < splits) {
-                editor = this.$editors[this.$splits];
-                this.$container.appendChild(editor.container);
-                editor.setFontSize(this.$fontSize);
-                this.$splits ++;
-            }
-            while (this.$splits < splits) {
-                this.$createEditor();
-                this.$splits ++;
-            }
-        } else {
-            while (this.$splits > splits) {
-                editor = this.$editors[this.$splits - 1];
-                this.$container.removeChild(editor.container);
-                this.$splits --;
-            }
-        }
-        this.resize();
-    };
-    this.getSplits = function() {
-        return this.$splits;
-    };
-    this.getEditor = function(idx) {
-        return this.$editors[idx];
-    };
-    this.getCurrentEditor = function() {
-        return this.$cEditor;
-    };
-    this.focus = function() {
-        this.$cEditor.focus();
-    };
-    this.blur = function() {
-        this.$cEditor.blur();
-    };
-    this.setTheme = function(theme) {
-        this.$editors.forEach(function(editor) {
-            editor.setTheme(theme);
-        });
-    };
-    this.setKeyboardHandler = function(keybinding) {
-        this.$editors.forEach(function(editor) {
-            editor.setKeyboardHandler(keybinding);
-        });
-    };
-    this.forEach = function(callback, scope) {
-        this.$editors.forEach(callback, scope);
-    };
-
-
-    this.$fontSize = "";
-    this.setFontSize = function(size) {
-        this.$fontSize = size;
-        this.forEach(function(editor) {
-           editor.setFontSize(size);
-        });
-    };
-
-    this.$cloneSession = function(session) {
-        var s = new EditSession(session.getDocument(), session.getMode());
-
-        var undoManager = session.getUndoManager();
-        if (undoManager) {
-            var undoManagerProxy = new UndoManagerProxy(undoManager, s);
-            s.setUndoManager(undoManagerProxy);
-        }
-        s.$informUndoManager = lang.delayedCall(function() { s.$deltas = []; });
-        s.setTabSize(session.getTabSize());
-        s.setUseSoftTabs(session.getUseSoftTabs());
-        s.setOverwrite(session.getOverwrite());
-        s.setBreakpoints(session.getBreakpoints());
-        s.setUseWrapMode(session.getUseWrapMode());
-        s.setUseWorker(session.getUseWorker());
-        s.setWrapLimitRange(session.$wrapLimitRange.min,
-                            session.$wrapLimitRange.max);
-        s.$foldData = session.$cloneFoldData();
-
-        return s;
-    };
-    this.setSession = function(session, idx) {
-        var editor;
-        if (idx == null) {
-            editor = this.$cEditor;
-        } else {
-            editor = this.$editors[idx];
-        }
-        var isUsed = this.$editors.some(function(editor) {
-           return editor.session === session;
-        });
-
-        if (isUsed) {
-            session = this.$cloneSession(session);
-        }
-        editor.setSession(session);
-        return session;
-    };
-    this.getOrientation = function() {
-        return this.$orientation;
-    };
-    this.setOrientation = function(orientation) {
-        if (this.$orientation == orientation) {
-            return;
-        }
-        this.$orientation = orientation;
-        this.resize();
-    };
-    this.resize = function() {
-        var width = this.$container.clientWidth;
-        var height = this.$container.clientHeight;
-        var editor;
-
-        if (this.$orientation == this.BESIDE) {
-            var editorWidth = width / this.$splits;
-            for (var i = 0; i < this.$splits; i++) {
-                editor = this.$editors[i];
-                editor.container.style.width = editorWidth + "px";
-                editor.container.style.top = "0px";
-                editor.container.style.left = i * editorWidth + "px";
-                editor.container.style.height = height + "px";
-                editor.resize();
-            }
-        } else {
-            var editorHeight = height / this.$splits;
-            for (var i = 0; i < this.$splits; i++) {
-                editor = this.$editors[i];
-                editor.container.style.width = width + "px";
-                editor.container.style.top = i * editorHeight + "px";
-                editor.container.style.left = "0px";
-                editor.container.style.height = editorHeight + "px";
-                editor.resize();
-            }
-        }
-    };
-
-}).call(Split.prototype);
-
- 
-function UndoManagerProxy(undoManager, session) {
-    this.$u = undoManager;
-    this.$doc = session;
-}
-
-(function() {
-    this.execute = function(options) {
-        this.$u.execute(options);
-    };
-
-    this.undo = function() {
-        var selectionRange = this.$u.undo(true);
-        if (selectionRange) {
-            this.$doc.selection.setSelectionRange(selectionRange);
-        }
-    };
-
-    this.redo = function() {
-        var selectionRange = this.$u.redo(true);
-        if (selectionRange) {
-            this.$doc.selection.setSelectionRange(selectionRange);
-        }
-    };
-
-    this.reset = function() {
-        this.$u.reset();
-    };
-
-    this.hasUndo = function() {
-        return this.$u.hasUndo();
-    };
-
-    this.hasRedo = function() {
-        return this.$u.hasRedo();
-    };
-}).call(UndoManagerProxy.prototype);
-
-exports.Split = Split;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/js/libs/ace/ext-static_highlight.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/js/libs/ace/ext-static_highlight.js b/apps/fauxton/assets/js/libs/ace/ext-static_highlight.js
deleted file mode 100644
index 94ce314..0000000
--- a/apps/fauxton/assets/js/libs/ace/ext-static_highlight.js
+++ /dev/null
@@ -1,165 +0,0 @@
-/* ***** BEGIN LICENSE BLOCK *****
- * Distributed under the BSD license:
- *
- * Copyright (c) 2010, Ajax.org B.V.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above copyright
- *       notice, this list of conditions and the following disclaimer in the
- *       documentation and/or other materials provided with the distribution.
- *     * Neither the name of Ajax.org B.V. nor the
- *       names of its contributors may be used to endorse or promote products
- *       derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * ***** END LICENSE BLOCK ***** */
-
-define('ace/ext/static_highlight', ['require', 'exports', 'module' , 'ace/edit_session', 'ace/layer/text', 'ace/config', 'ace/lib/dom'], function(require, exports, module) {
-
-
-var EditSession = require("../edit_session").EditSession;
-var TextLayer = require("../layer/text").Text;
-var baseStyles = ".ace_static_highlight {\
-font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', 'Droid Sans Mono', monospace;\
-font-size: 12px;\
-}\
-.ace_static_highlight .ace_gutter {\
-width: 25px !important;\
-display: block;\
-float: left;\
-text-align: right;\
-padding: 0 3px 0 0;\
-margin-right: 3px;\
-position: static !important;\
-}\
-.ace_static_highlight .ace_line { clear: both; }\
-.ace_static_highlight .ace_gutter-cell {\
--moz-user-select: -moz-none;\
--khtml-user-select: none;\
--webkit-user-select: none;\
-user-select: none;\
-}";
-var config = require("../config");
-var dom = require("../lib/dom");
-
-exports.render = function(input, mode, theme, lineStart, disableGutter, callback) {
-    var waiting = 0;
-    var modeCache = EditSession.prototype.$modes;
-    if (typeof theme == "string") {
-        waiting++;
-        config.loadModule(['theme', theme], function(m) {
-            theme = m;
-            --waiting || done();
-        });
-    }
-
-    if (typeof mode == "string") {
-        waiting++;
-        config.loadModule(['mode', mode], function(m) {
-            if (!modeCache[mode]) modeCache[mode] = new m.Mode();
-            mode = modeCache[mode];
-            --waiting || done();
-        });
-    }
-    function done() {
-        var result = exports.renderSync(input, mode, theme, lineStart, disableGutter);
-        return callback ? callback(result) : result;
-    }
-    return waiting || done();
-};
-
-exports.renderSync = function(input, mode, theme, lineStart, disableGutter) {
-    lineStart = parseInt(lineStart || 1, 10);
-
-    var session = new EditSession("");
-    session.setUseWorker(false);
-    session.setMode(mode);
-
-    var textLayer = new TextLayer(document.createElement("div"));
-    textLayer.setSession(session);
-    textLayer.config = {
-        characterWidth: 10,
-        lineHeight: 20
-    };
-
-    session.setValue(input);
-
-    var stringBuilder = [];
-    var length =  session.getLength();
-
-    for(var ix = 0; ix < length; ix++) {
-        stringBuilder.push("<div class='ace_line'>");
-        if (!disableGutter)
-            stringBuilder.push("<span class='ace_gutter ace_gutter-cell' unselectable='on'>" + (ix + lineStart) + "</span>");
-        textLayer.$renderLine(stringBuilder, ix, true, false);
-        stringBuilder.push("</div>");
-    }
-    var html = "<div class='" + theme.cssClass + "'>" +
-        "<div class='ace_static_highlight'>" +
-            stringBuilder.join("") +
-        "</div>" +
-    "</div>";
-
-    textLayer.destroy();
-
-    return {
-        css: baseStyles + theme.cssText,
-        html: html
-    };
-};
-
-
-
-exports.highlight = function(el, opts, callback) {
-    var m = el.className.match(/lang-(\w+)/);
-    var mode = opts.mode || m && ("ace/mode/" + m[1]);
-    if (!mode)
-        return false;
-    var theme = opts.theme || "ace/theme/textmate";
-    
-    var data = "";
-    var nodes = [];
-
-    if (el.firstElementChild) {
-        var textLen = 0;
-        for (var i = 0; i < el.childNodes.length; i++) {
-            var ch = el.childNodes[i];
-            if (ch.nodeType == 3) {
-                textLen += ch.data.length;
-                data += ch.data;
-            } else {
-                nodes.push(textLen, ch);
-            }
-        }
-    } else {
-        data = dom.getInnerText(el);
-    }
-    
-    exports.render(data, mode, theme, 1, true, function (highlighted) {
-        dom.importCssString(highlighted.css, "ace_highlight");
-        el.innerHTML = highlighted.html;
-        var container = el.firstChild.firstChild
-        for (var i = 0; i < nodes.length; i += 2) {
-            var pos = highlighted.session.doc.indexToPosition(nodes[i])
-            var node = nodes[i + 1];
-            var lineEl = container.children[pos.row];
-            lineEl && lineEl.appendChild(nodes[i+1]);
-        }
-        callback && callback();
-    });
-};
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/js/libs/ace/ext-statusbar.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/js/libs/ace/ext-statusbar.js b/apps/fauxton/assets/js/libs/ace/ext-statusbar.js
deleted file mode 100644
index b751cca..0000000
--- a/apps/fauxton/assets/js/libs/ace/ext-statusbar.js
+++ /dev/null
@@ -1,47 +0,0 @@
-define('ace/ext/statusbar', ['require', 'exports', 'module' , 'ace/lib/dom', 'ace/lib/lang'], function(require, exports, module) {
-var dom = require("ace/lib/dom");
-var lang = require("ace/lib/lang");
-
-var StatusBar = function(editor, parentNode) {
-    this.element = dom.createElement("div");
-    this.element.className = "ace_status-indicator";
-    this.element.style.cssText = "display: inline-block;";
-    parentNode.appendChild(this.element);
-
-    var statusUpdate = lang.delayedCall(function(){
-        this.updateStatus(editor)
-    }.bind(this));
-    editor.on("changeStatus", function() {
-        statusUpdate.schedule(100);
-    });
-    editor.on("changeSelection", function() {
-        statusUpdate.schedule(100);
-    });
-};
-
-(function(){
-    this.updateStatus = function(editor) {
-        var status = [];
-        function add(str, separator) {
-            str && status.push(str, separator || "|");
-        }
-
-        if (editor.$vimModeHandler)
-            add(editor.$vimModeHandler.getStatusText());
-        else if (editor.commands.recording)
-            add("REC");
-
-        var c = editor.selection.lead;
-        add(c.row + ":" + c.column, " ");
-        if (!editor.selection.isEmpty()) {
-            var r = editor.getSelectionRange();
-            add("(" + (r.end.row - r.start.row) + ":"  +(r.end.column - r.start.column) + ")");
-        }
-        status.pop();
-        this.element.textContent = status.join("");
-    };
-}).call(StatusBar.prototype);
-
-exports.StatusBar = StatusBar;
-
-});
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/js/libs/ace/ext-textarea.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/js/libs/ace/ext-textarea.js b/apps/fauxton/assets/js/libs/ace/ext-textarea.js
deleted file mode 100644
index 8d4cafe..0000000
--- a/apps/fauxton/assets/js/libs/ace/ext-textarea.js
+++ /dev/null
@@ -1,478 +0,0 @@
-/* ***** BEGIN LICENSE BLOCK *****
- * Distributed under the BSD license:
- *
- * Copyright (c) 2010, Ajax.org B.V.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above copyright
- *       notice, this list of conditions and the following disclaimer in the
- *       documentation and/or other materials provided with the distribution.
- *     * Neither the name of Ajax.org B.V. nor the
- *       names of its contributors may be used to endorse or promote products
- *       derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * ***** END LICENSE BLOCK ***** */
-
-define('ace/ext/textarea', ['require', 'exports', 'module' , 'ace/lib/event', 'ace/lib/useragent', 'ace/lib/net', 'ace/ace', 'ace/theme/textmate', 'ace/mode/text'], function(require, exports, module) {
-
-
-var event = require("../lib/event");
-var UA = require("../lib/useragent");
-var net = require("../lib/net");
-var ace = require("../ace");
-
-require("../theme/textmate");
-
-module.exports = exports = ace;
-var getCSSProperty = function(element, container, property) {
-    var ret = element.style[property];
-
-    if (!ret) {
-        if (window.getComputedStyle) {
-            ret = window.getComputedStyle(element, '').getPropertyValue(property);
-        } else {
-            ret = element.currentStyle[property];
-        }
-    }
-
-    if (!ret || ret == 'auto' || ret == 'intrinsic') {
-        ret = container.style[property];
-    }
-    return ret;
-};
-
-function applyStyles(elm, styles) {
-    for (var style in styles) {
-        elm.style[style] = styles[style];
-    }
-}
-
-function setupContainer(element, getValue) {
-    if (element.type != 'textarea') {
-        throw new Error("Textarea required!");
-    }
-
-    var parentNode = element.parentNode;
-    var container = document.createElement('div');
-    var resizeEvent = function() {
-        var style = 'position:relative;';
-        [
-            'margin-top', 'margin-left', 'margin-right', 'margin-bottom'
-        ].forEach(function(item) {
-            style += item + ':' +
-                        getCSSProperty(element, container, item) + ';';
-        });
-        var width = getCSSProperty(element, container, 'width') || (element.clientWidth + "px");
-        var height = getCSSProperty(element, container, 'height')  || (element.clientHeight + "px");
-        style += 'height:' + height + ';width:' + width + ';';
-        style += 'display:inline-block;';
-        container.setAttribute('style', style);
-    };
-    event.addListener(window, 'resize', resizeEvent);
-    resizeEvent();
-    parentNode.insertBefore(container, element.nextSibling);
-    while (parentNode !== document) {
-        if (parentNode.tagName.toUpperCase() === 'FORM') {
-            var oldSumit = parentNode.onsubmit;
-            parentNode.onsubmit = function(evt) {
-                element.value = getValue();
-                if (oldSumit) {
-                    oldSumit.call(this, evt);
-                }
-            };
-            break;
-        }
-        parentNode = parentNode.parentNode;
-    }
-    return container;
-}
-
-exports.transformTextarea = function(element, loader) {
-    var session;
-    var container = setupContainer(element, function() {
-        return session.getValue();
-    });
-    element.style.display = 'none';
-    container.style.background = 'white';
-    var editorDiv = document.createElement("div");
-    applyStyles(editorDiv, {
-        top: "0px",
-        left: "0px",
-        right: "0px",
-        bottom: "0px",
-        border: "1px solid gray",
-        position: "absolute"
-    });
-    container.appendChild(editorDiv);
-
-    var settingOpener = document.createElement("div");
-    applyStyles(settingOpener, {
-        position: "absolute",
-        right: "0px",
-        bottom: "0px",
-        background: "red",
-        cursor: "nw-resize",
-        borderStyle: "solid",
-        borderWidth: "9px 8px 10px 9px",
-        width: "2px",
-        borderColor: "lightblue gray gray lightblue",
-        zIndex: 101
-    });
-
-    var settingDiv = document.createElement("div");
-    var settingDivStyles = {
-        top: "0px",
-        left: "20%",
-        right: "0px",
-        bottom: "0px",
-        position: "absolute",
-        padding: "5px",
-        zIndex: 100,
-        color: "white",
-        display: "none",
-        overflow: "auto",
-        fontSize: "14px",
-        boxShadow: "-5px 2px 3px gray"
-    };
-    if (!UA.isOldIE) {
-        settingDivStyles.backgroundColor = "rgba(0, 0, 0, 0.6)";
-    } else {
-        settingDivStyles.backgroundColor = "#333";
-    }
-
-    applyStyles(settingDiv, settingDivStyles);
-    container.appendChild(settingDiv);
-    var options = {};
-
-    var editor = ace.edit(editorDiv);
-    session = editor.getSession();
-
-    session.setValue(element.value || element.innerHTML);
-    editor.focus();
-    container.appendChild(settingOpener);
-    setupApi(editor, editorDiv, settingDiv, ace, options, loader);
-    setupSettingPanel(settingDiv, settingOpener, editor, options);
-
-    var state = "";
-    event.addListener(settingOpener, "mousemove", function(e) {
-        var rect = this.getBoundingClientRect();
-        var x = e.clientX - rect.left, y = e.clientY - rect.top;
-        if (x + y < (rect.width + rect.height)/2) {
-            this.style.cursor = "pointer";
-            state = "toggle";
-        } else {
-            state = "resize";
-            this.style.cursor = "nw-resize";
-        }
-    });
-
-    event.addListener(settingOpener, "mousedown", function(e) {
-        if (state == "toggle") {
-            editor.setDisplaySettings();
-            return;
-        }
-        container.style.zIndex = 100000;
-        var rect = container.getBoundingClientRect();
-        var startX = rect.width  + rect.left - e.clientX;
-        var startY = rect.height  + rect.top - e.clientY;
-        event.capture(settingOpener, function(e) {
-            container.style.width = e.clientX - rect.left + startX + "px";
-            container.style.height = e.clientY - rect.top + startY + "px";
-            editor.resize();
-        }, function() {});
-    });
-
-    return editor;
-};
-
-function load(url, module, callback) {
-    net.loadScript(url, function() {
-        require([module], callback);
-    });
-}
-
-function setupApi(editor, editorDiv, settingDiv, ace, options, loader) {
-    var session = editor.getSession();
-    var renderer = editor.renderer;
-    loader = loader || load;
-
-    function toBool(value) {
-        return value === "true" || value == true;
-    }
-
-    editor.setDisplaySettings = function(display) {
-        if (display == null)
-            display = settingDiv.style.display == "none";
-        if (display) {
-            settingDiv.style.display = "block";
-            settingDiv.hideButton.focus();
-            editor.on("focus", function onFocus() {
-                editor.removeListener("focus", onFocus);
-                settingDiv.style.display = "none";
-            });
-        } else {
-            editor.focus();
-        }
-    };
-
-    editor.$setOption = editor.setOption;
-    editor.setOption = function(key, value) {
-        if (options[key] == value) return;
-
-        switch (key) {
-            case "mode":
-                if (value != "text") {
-                    loader("mode-" + value + ".js", "ace/mode/" + value, function() {
-                        var aceMode = require("../mode/" + value).Mode;
-                        session.setMode(new aceMode());
-                    });
-                } else {
-                    session.setMode(new (require("../mode/text").Mode));
-                }
-            break;
-
-            case "theme":
-                if (value != "textmate") {
-                    loader("theme-" + value + ".js", "ace/theme/" + value, function() {
-                        editor.setTheme("ace/theme/" + value);
-                    });
-                } else {
-                    editor.setTheme("ace/theme/textmate");
-                }
-            break;
-
-            case "fontSize":
-                editorDiv.style.fontSize = value;
-            break;
-
-            case "keybindings":
-                switch (value) {
-                    case "vim":
-                        editor.setKeyboardHandler("ace/keyboard/vim");
-                        break;
-                    case "emacs":
-                        editor.setKeyboardHandler("ace/keyboard/emacs");
-                        break;
-                    default:
-                        editor.setKeyboardHandler(null);
-                }
-            break;
-
-            case "softWrap":
-                switch (value) {
-                    case "off":
-                        session.setUseWrapMode(false);
-                        renderer.setPrintMarginColumn(80);
-                    break;
-                    case "40":
-                        session.setUseWrapMode(true);
-                        session.setWrapLimitRange(40, 40);
-                        renderer.setPrintMarginColumn(40);
-                    break;
-                    case "80":
-                        session.setUseWrapMode(true);
-                        session.setWrapLimitRange(80, 80);
-                        renderer.setPrintMarginColumn(80);
-                    break;
-                    case "free":
-                        session.setUseWrapMode(true);
-                        session.setWrapLimitRange(null, null);
-                        renderer.setPrintMarginColumn(80);
-                    break;
-                }
-            break;
-            
-            default:
-                editor.$setOption(key, toBool(value));
-        }
-
-        options[key] = value;
-    };
-
-    editor.getOption = function(key) {
-        return options[key];
-    };
-
-    editor.getOptions = function() {
-        return options;
-    };
-
-    editor.setOptions(exports.options);
-
-    return editor;
-}
-
-function setupSettingPanel(settingDiv, settingOpener, editor, options) {
-    var BOOL = null;
-
-    var desc = {
-        mode:            "Mode:",
-        gutter:          "Display Gutter:",
-        theme:           "Theme:",
-        fontSize:        "Font Size:",
-        softWrap:        "Soft Wrap:",
-        keybindings:     "Keyboard",
-        showPrintMargin: "Show Print Margin:",
-        useSoftTabs:     "Use Soft Tabs:",
-        showInvisibles:  "Show Invisibles"
-    };
-
-    var optionValues = {
-        mode: {
-            text:       "Plain",
-            javascript: "JavaScript",
-            xml:        "XML",
-            html:       "HTML",
-            css:        "CSS",
-            scss:       "SCSS",
-            python:     "Python",
-            php:        "PHP",
-            java:       "Java",
-            ruby:       "Ruby",
-            c_cpp:      "C/C++",
-            coffee:     "CoffeeScript",
-            json:       "json",
-            perl:       "Perl",
-            clojure:    "Clojure",
-            ocaml:      "OCaml",
-            csharp:     "C#",
-            haxe:       "haXe",
-            svg:        "SVG",
-            textile:    "Textile",
-            groovy:     "Groovy",
-            liquid:     "Liquid",
-            Scala:      "Scala"
-        },
-        theme: {
-            clouds:           "Clouds",
-            clouds_midnight:  "Clouds Midnight",
-            cobalt:           "Cobalt",
-            crimson_editor:   "Crimson Editor",
-            dawn:             "Dawn",
-            eclipse:          "Eclipse",
-            idle_fingers:     "Idle Fingers",
-            kr_theme:         "Kr Theme",
-            merbivore:        "Merbivore",
-            merbivore_soft:   "Merbivore Soft",
-            mono_industrial:  "Mono Industrial",
-            monokai:          "Monokai",
-            pastel_on_dark:   "Pastel On Dark",
-            solarized_dark:   "Solarized Dark",
-            solarized_light:  "Solarized Light",
-            textmate:         "Textmate",
-            twilight:         "Twilight",
-            vibrant_ink:      "Vibrant Ink"
-        },
-        gutter: BOOL,
-        fontSize: {
-            "10px": "10px",
-            "11px": "11px",
-            "12px": "12px",
-            "14px": "14px",
-            "16px": "16px"
-        },
-        softWrap: {
-            off:    "Off",
-            40:     "40",
-            80:     "80",
-            free:   "Free"
-        },
-        keybindings: {
-            ace: "ace",
-            vim: "vim",
-            emacs: "emacs"
-        },
-        showPrintMargin:    BOOL,
-        useSoftTabs:        BOOL,
-        showInvisibles:     BOOL
-    };
-
-    var table = [];
-    table.push("<table><tr><th>Setting</th><th>Value</th></tr>");
-
-    function renderOption(builder, option, obj, cValue) {
-        if (!obj) {
-            builder.push(
-                "<input type='checkbox' title='", option, "' ",
-                    cValue == "true" ? "checked='true'" : "",
-               "'></input>"
-            );
-            return;
-        }
-        builder.push("<select title='" + option + "'>");
-        for (var value in obj) {
-            builder.push("<option value='" + value + "' ");
-
-            if (cValue == value) {
-                builder.push(" selected ");
-            }
-
-            builder.push(">",
-                obj[value],
-                "</option>");
-        }
-        builder.push("</select>");
-    }
-
-    for (var option in options) {
-        table.push("<tr><td>", desc[option], "</td>");
-        table.push("<td>");
-        renderOption(table, option, optionValues[option], options[option]);
-        table.push("</td></tr>");
-    }
-    table.push("</table>");
-    settingDiv.innerHTML = table.join("");
-
-    var onChange = function(e) {
-        var select = e.currentTarget;
-        editor.setOption(select.title, select.value);
-    };
-    var onClick = function(e) {
-        var cb = e.currentTarget;
-        editor.setOption(cb.title, cb.checked);
-    };
-    var selects = settingDiv.getElementsByTagName("select");
-    for (var i = 0; i < selects.length; i++)
-        selects[i].onchange = onChange;
-    var cbs = settingDiv.getElementsByTagName("input");
-    for (var i = 0; i < cbs.length; i++)
-        cbs[i].onclick = onClick;
-
-
-    var button = document.createElement("input");
-    button.type = "button";
-    button.value = "Hide";
-    event.addListener(button, "click", function() {
-        editor.setDisplaySettings(false);
-    });
-    settingDiv.appendChild(button);
-    settingDiv.hideButton = button;
-}
-exports.options = {
-    mode:               "text",
-    theme:              "textmate",
-    gutter:             "false",
-    fontSize:           "12px",
-    softWrap:           "off",
-    keybindings:        "ace",
-    showPrintMargin:    "false",
-    useSoftTabs:        "true",
-    showInvisibles:     "false"
-};
-
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/js/libs/ace/ext-themelist.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/js/libs/ace/ext-themelist.js b/apps/fauxton/assets/js/libs/ace/ext-themelist.js
deleted file mode 100644
index a267ba9..0000000
--- a/apps/fauxton/assets/js/libs/ace/ext-themelist.js
+++ /dev/null
@@ -1,90 +0,0 @@
-/* ***** BEGIN LICENSE BLOCK *****
- * Distributed under the BSD license:
- *
- * Copyright (c) 2013 Matthew Christopher Kastor-Inare III, Atropa Inc. Intl
- * All rights reserved.
- *
- * Contributed to Ajax.org under the BSD license.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above copyright
- *       notice, this list of conditions and the following disclaimer in the
- *       documentation and/or other materials provided with the distribution.
- *     * Neither the name of Ajax.org B.V. nor the
- *       names of its contributors may be used to endorse or promote products
- *       derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * ***** END LICENSE BLOCK ***** */
-
-define('ace/ext/themelist', ['require', 'exports', 'module' , 'ace/ext/themelist_utils/themes'], function(require, exports, module) {
-module.exports.themes = require('ace/ext/themelist_utils/themes').themes;
-module.exports.ThemeDescription = function(name) {
-    this.name = name;
-    this.desc = name.split('_'
-        ).map(
-            function(namePart) {
-                return namePart[0].toUpperCase() + namePart.slice(1);
-            }
-        ).join(' ');
-    this.theme = "ace/theme/" + name;
-};
-
-module.exports.themesByName = {};
-
-module.exports.themes = module.exports.themes.map(function(name) {
-    module.exports.themesByName[name] = new module.exports.ThemeDescription(name);
-    return module.exports.themesByName[name];
-});
-
-});
-
-define('ace/ext/themelist_utils/themes', ['require', 'exports', 'module' ], function(require, exports, module) {
-
-module.exports.themes = [
-    "ambiance",
-    "chaos",
-    "chrome",
-    "clouds",
-    "clouds_midnight",
-    "cobalt",
-    "crimson_editor",
-    "dawn",
-    "dreamweaver",
-    "eclipse",
-    "github",
-    "idle_fingers",
-    "kr_theme",
-    "merbivore",
-    "merbivore_soft",
-    "mono_industrial",
-    "monokai",
-    "pastel_on_dark",
-    "solarized_dark",
-    "solarized_light",
-    "terminal",
-    "textmate",
-    "tomorrow",
-    "tomorrow_night",
-    "tomorrow_night_blue",
-    "tomorrow_night_bright",
-    "tomorrow_night_eighties",
-    "twilight",
-    "vibrant_ink",
-    "xcode"
-];
-
-});
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/js/libs/ace/ext-whitespace.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/js/libs/ace/ext-whitespace.js b/apps/fauxton/assets/js/libs/ace/ext-whitespace.js
deleted file mode 100644
index dbfd3ee..0000000
--- a/apps/fauxton/assets/js/libs/ace/ext-whitespace.js
+++ /dev/null
@@ -1,206 +0,0 @@
-/* ***** BEGIN LICENSE BLOCK *****
- * Distributed under the BSD license:
- *
- * Copyright (c) 2010, Ajax.org B.V.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above copyright
- *       notice, this list of conditions and the following disclaimer in the
- *       documentation and/or other materials provided with the distribution.
- *     * Neither the name of Ajax.org B.V. nor the
- *       names of its contributors may be used to endorse or promote products
- *       derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * ***** END LICENSE BLOCK ***** */
-
-define('ace/ext/whitespace', ['require', 'exports', 'module' , 'ace/lib/lang'], function(require, exports, module) {
-
-
-var lang = require("../lib/lang");
-exports.$detectIndentation = function(lines, fallback) {
-    var stats = [];
-    var changes = [];
-    var tabIndents = 0;
-    var prevSpaces = 0;
-    var max = Math.min(lines.length, 1000);
-    for (var i = 0; i < max; i++) {
-        var line = lines[i];
-        if (!/^\s*[^*+\-\s]/.test(line))
-            continue;
-
-        var tabs = line.match(/^\t*/)[0].length;
-        if (line[0] == "\t")
-            tabIndents++;
-
-        var spaces = line.match(/^ */)[0].length;
-        if (spaces && line[spaces] != "\t") {
-            var diff = spaces - prevSpaces;
-            if (diff > 0 && !(prevSpaces%diff) && !(spaces%diff))
-                changes[diff] = (changes[diff] || 0) + 1;
-
-            stats[spaces] = (stats[spaces] || 0) + 1;
-        }
-        prevSpaces = spaces;
-        while (line[line.length - 1] == "\\")
-            line = lines[i++];
-    }
-
-    function getScore(indent) {
-        var score = 0;
-        for (var i = indent; i < stats.length; i += indent)
-            score += stats[i] || 0;
-        return score;
-    }
-
-    var changesTotal = changes.reduce(function(a,b){return a+b}, 0);
-
-    var first = {score: 0, length: 0};
-    var spaceIndents = 0;
-    for (var i = 1; i < 12; i++) {
-        if (i == 1) {
-            spaceIndents = getScore(i);
-            var score = 1;
-        } else
-            var score = getScore(i) / spaceIndents;
-
-        if (changes[i]) {
-            score += changes[i] / changesTotal;
-        }
-
-        if (score > first.score)
-            first = {score: score, length: i};
-    }
-
-    if (first.score && first.score > 1.4)
-        var tabLength = first.length;
-
-    if (tabIndents > spaceIndents + 1)
-        return {ch: "\t", length: tabLength};
-
-    if (spaceIndents + 1 > tabIndents)
-        return {ch: " ", length: tabLength};
-};
-
-exports.detectIndentation = function(session) {
-    var lines = session.getLines(0, 1000);
-    var indent = exports.$detectIndentation(lines) || {};
-
-    if (indent.ch)
-        session.setUseSoftTabs(indent.ch == " ");
-
-    if (indent.length)
-        session.setTabSize(indent.length);
-    return indent;
-};
-
-exports.trimTrailingSpace = function(session, trimEmpty) {
-    var doc = session.getDocument();
-    var lines = doc.getAllLines();
-    
-    var min = trimEmpty ? -1 : 0;
-
-    for (var i = 0, l=lines.length; i < l; i++) {
-        var line = lines[i];
-        var index = line.search(/\s+$/);
-
-        if (index > min)
-            doc.removeInLine(i, index, line.length);
-    }
-};
-
-exports.convertIndentation = function(session, ch, len) {
-    var oldCh = session.getTabString()[0];
-    var oldLen = session.getTabSize();
-    if (!len) len = oldLen;
-    if (!ch) ch = oldCh;
-
-    var tab = ch == "\t" ? ch: lang.stringRepeat(ch, len);
-
-    var doc = session.doc;
-    var lines = doc.getAllLines();
-
-    var cache = {};
-    var spaceCache = {};
-    for (var i = 0, l=lines.length; i < l; i++) {
-        var line = lines[i];
-        var match = line.match(/^\s*/)[0];
-        if (match) {
-            var w = session.$getStringScreenWidth(match)[0];
-            var tabCount = Math.floor(w/oldLen);
-            var reminder = w%oldLen;
-            var toInsert = cache[tabCount] || (cache[tabCount] = lang.stringRepeat(tab, tabCount));
-            toInsert += spaceCache[reminder] || (spaceCache[reminder] = lang.stringRepeat(" ", reminder));
-
-            if (toInsert != match) {
-                doc.removeInLine(i, 0, match.length);
-                doc.insertInLine({row: i, column: 0}, toInsert);
-            }
-        }
-    }
-    session.setTabSize(len);
-    session.setUseSoftTabs(ch == " ");
-};
-
-exports.$parseStringArg = function(text) {
-    var indent = {};
-    if (/t/.test(text))
-        indent.ch = "\t";
-    else if (/s/.test(text))
-        indent.ch = " ";
-    var m = text.match(/\d+/);
-    if (m)
-        indent.length = parseInt(m[0], 10);
-    return indent;
-};
-
-exports.$parseArg = function(arg) {
-    if (!arg)
-        return {};
-    if (typeof arg == "string")
-        return exports.$parseStringArg(arg);
-    if (typeof arg.text == "string")
-        return exports.$parseStringArg(arg.text);
-    return arg;
-};
-
-exports.commands = [{
-    name: "detectIndentation",
-    exec: function(editor) {
-        exports.detectIndentation(editor.session);
-    }
-}, {
-    name: "trimTrailingSpace",
-    exec: function(editor) {
-        exports.trimTrailingSpace(editor.session);
-    }
-}, {
-    name: "convertIndentation",
-    exec: function(editor, arg) {
-        var indent = exports.$parseArg(arg);
-        exports.convertIndentation(editor.session, indent.ch, indent.length);
-    }
-}, {
-    name: "setIndentation",
-    exec: function(editor, arg) {
-        var indent = exports.$parseArg(arg);
-        indent.length && editor.session.setTabSize(indent.length);
-        indent.ch && editor.session.setUseSoftTabs(indent.ch == " ");
-    }
-}];
-
-});


[89/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/dcfmtsym.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/dcfmtsym.h b/src/apps/couch_collate/platform/osx/icu/unicode/dcfmtsym.h
new file mode 100644
index 0000000..bc5547d
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/dcfmtsym.h
@@ -0,0 +1,370 @@
+/*
+********************************************************************************
+*   Copyright (C) 1997-2007, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+********************************************************************************
+*
+* File DCFMTSYM.H
+*
+* Modification History:
+* 
+*   Date        Name        Description
+*   02/19/97    aliu        Converted from java.
+*   03/18/97    clhuang     Updated per C++ implementation.
+*   03/27/97    helena      Updated to pass the simple test after code review.
+*   08/26/97    aliu        Added currency/intl currency symbol support.
+*   07/22/98    stephen     Changed to match C++ style 
+*                            currencySymbol -> fCurrencySymbol
+*                            Constants changed from CAPS to kCaps
+*   06/24/99    helena      Integrated Alan's NF enhancements and Java2 bug fixes
+*   09/22/00    grhoten     Marked deprecation tags with a pointer to replacement
+*                            functions.
+********************************************************************************
+*/
+ 
+#ifndef DCFMTSYM_H
+#define DCFMTSYM_H
+ 
+#include "unicode/utypes.h"
+
+#if !UCONFIG_NO_FORMATTING
+
+#include "unicode/uobject.h"
+#include "unicode/locid.h"
+
+/**
+ * \file 
+ * \brief C++ API: Symbols for formatting numbers.
+ */
+
+
+U_NAMESPACE_BEGIN
+
+/**
+ * This class represents the set of symbols needed by DecimalFormat
+ * to format numbers. DecimalFormat creates for itself an instance of
+ * DecimalFormatSymbols from its locale data.  If you need to change any
+ * of these symbols, you can get the DecimalFormatSymbols object from
+ * your DecimalFormat and modify it.
+ * <P>
+ * Here are the special characters used in the parts of the
+ * subpattern, with notes on their usage.
+ * <pre>
+ * \code
+ *        Symbol   Meaning
+ *          0      a digit
+ *          #      a digit, zero shows as absent
+ *          .      placeholder for decimal separator
+ *          ,      placeholder for grouping separator.
+ *          ;      separates formats.
+ *          -      default negative prefix.
+ *          %      divide by 100 and show as percentage
+ *          X      any other characters can be used in the prefix or suffix
+ *          '      used to quote special characters in a prefix or suffix.
+ * \endcode
+ *  </pre>
+ * [Notes]
+ * <P>
+ * If there is no explicit negative subpattern, - is prefixed to the
+ * positive form. That is, "0.00" alone is equivalent to "0.00;-0.00".
+ * <P>
+ * The grouping separator is commonly used for thousands, but in some
+ * countries for ten-thousands. The interval is a constant number of
+ * digits between the grouping characters, such as 100,000,000 or 1,0000,0000.
+ * If you supply a pattern with multiple grouping characters, the interval
+ * between the last one and the end of the integer is the one that is
+ * used. So "#,##,###,####" == "######,####" == "##,####,####".
+ * <P>
+ * This class only handles localized digits where the 10 digits are
+ * contiguous in Unicode, from 0 to 9. Other digits sets (such as
+ * superscripts) would need a different subclass.
+ */
+class U_I18N_API DecimalFormatSymbols : public UObject {
+public:
+    /**
+     * Constants for specifying a number format symbol.
+     * @stable ICU 2.0
+     */
+    enum ENumberFormatSymbol {
+        /** The decimal separator */
+        kDecimalSeparatorSymbol,
+        /** The grouping separator */
+        kGroupingSeparatorSymbol,
+        /** The pattern separator */
+        kPatternSeparatorSymbol,
+        /** The percent sign */
+        kPercentSymbol,
+        /** Zero*/
+        kZeroDigitSymbol,
+        /** Character representing a digit in the pattern */
+        kDigitSymbol,
+        /** The minus sign */
+        kMinusSignSymbol,
+        /** The plus sign */
+        kPlusSignSymbol,
+        /** The currency symbol */
+        kCurrencySymbol,
+        /** The international currency symbol */
+        kIntlCurrencySymbol,
+        /** The monetary separator */
+        kMonetarySeparatorSymbol,
+        /** The exponential symbol */
+        kExponentialSymbol,
+        /** Per mill symbol - replaces kPermillSymbol */
+        kPerMillSymbol,
+        /** Escape padding character */
+        kPadEscapeSymbol,
+        /** Infinity symbol */
+        kInfinitySymbol,
+        /** Nan symbol */
+        kNaNSymbol,
+        /** Significant digit symbol
+         * @stable ICU 3.0 */
+        kSignificantDigitSymbol,
+        /** The monetary grouping separator 
+         * @stable ICU 3.6
+         */
+        kMonetaryGroupingSeparatorSymbol,
+        /** count symbol constants */
+        kFormatSymbolCount
+    };
+
+    /**
+     * Create a DecimalFormatSymbols object for the given locale.
+     *
+     * @param locale    The locale to get symbols for.
+     * @param status    Input/output parameter, set to success or
+     *                  failure code upon return.
+     * @stable ICU 2.0
+     */
+    DecimalFormatSymbols(const Locale& locale, UErrorCode& status);
+
+    /**
+     * Create a DecimalFormatSymbols object for the default locale.
+     * This constructor will not fail.  If the resource file data is
+     * not available, it will use hard-coded last-resort data and
+     * set status to U_USING_FALLBACK_ERROR.
+     *
+     * @param status    Input/output parameter, set to success or
+     *                  failure code upon return.
+     * @stable ICU 2.0
+     */
+    DecimalFormatSymbols( UErrorCode& status);
+
+    /**
+     * Copy constructor.
+     * @stable ICU 2.0
+     */
+    DecimalFormatSymbols(const DecimalFormatSymbols&);
+
+    /**
+     * Assignment operator.
+     * @stable ICU 2.0
+     */
+    DecimalFormatSymbols& operator=(const DecimalFormatSymbols&);
+
+    /**
+     * Destructor.
+     * @stable ICU 2.0
+     */
+    virtual ~DecimalFormatSymbols();
+
+    /**
+     * Return true if another object is semantically equal to this one.
+     *
+     * @param other    the object to be compared with.
+     * @return         true if another object is semantically equal to this one.
+     * @stable ICU 2.0
+     */
+    UBool operator==(const DecimalFormatSymbols& other) const;
+
+    /**
+     * Return true if another object is semantically unequal to this one.
+     *
+     * @param other    the object to be compared with.
+     * @return         true if another object is semantically unequal to this one.
+     * @stable ICU 2.0
+     */
+    UBool operator!=(const DecimalFormatSymbols& other) const { return !operator==(other); }
+
+    /**
+     * Get one of the format symbols by its enum constant.
+     * Each symbol is stored as a string so that graphemes
+     * (characters with modifyer letters) can be used.
+     *
+     * @param symbol    Constant to indicate a number format symbol.
+     * @return    the format symbols by the param 'symbol'
+     * @stable ICU 2.0
+     */
+    inline UnicodeString getSymbol(ENumberFormatSymbol symbol) const;
+
+    /**
+     * Set one of the format symbols by its enum constant.
+     * Each symbol is stored as a string so that graphemes
+     * (characters with modifyer letters) can be used.
+     *
+     * @param symbol    Constant to indicate a number format symbol.
+     * @param value     value of the format sybmol
+     * @stable ICU 2.0
+     */
+    void setSymbol(ENumberFormatSymbol symbol, const UnicodeString &value);
+
+    /**
+     * Returns the locale for which this object was constructed.
+     * @stable ICU 2.6
+     */
+    inline Locale getLocale() const;
+
+    /**
+     * Returns the locale for this object. Two flavors are available:
+     * valid and actual locale.
+     * @stable ICU 2.8
+     */
+    Locale getLocale(ULocDataLocaleType type, UErrorCode& status) const;
+
+    /**
+     * ICU "poor man's RTTI", returns a UClassID for the actual class.
+     *
+     * @stable ICU 2.2
+     */
+    virtual UClassID getDynamicClassID() const;
+
+    /**
+     * ICU "poor man's RTTI", returns a UClassID for this class.
+     *
+     * @stable ICU 2.2
+     */
+    static UClassID U_EXPORT2 getStaticClassID();
+
+private:
+    DecimalFormatSymbols(); // default constructor not implemented
+
+    /**
+     * Initializes the symbols from the LocaleElements resource bundle.
+     * Note: The organization of LocaleElements badly needs to be
+     * cleaned up.
+     *
+     * @param locale               The locale to get symbols for.
+     * @param success              Input/output parameter, set to success or
+     *                             failure code upon return.
+     * @param useLastResortData    determine if use last resort data
+     */
+    void initialize(const Locale& locale, UErrorCode& success, UBool useLastResortData = FALSE);
+
+    /**
+     * Initialize the symbols from the given array of UnicodeStrings.
+     * The array must be of the correct size.
+     * 
+     * @param numberElements    the number format symbols
+     * @param numberElementsLength length of numberElements
+     */
+    void initialize(const UChar** numberElements, int32_t *numberElementsStrLen, int32_t numberElementsLength);
+
+    /**
+     * Initialize the symbols with default values.
+     */
+    void initialize();
+
+    void setCurrencyForSymbols();
+
+public:
+    /**
+     * _Internal_ function - more efficient version of getSymbol,
+     * returning a const reference to one of the symbol strings.
+     * The returned reference becomes invalid when the symbol is changed
+     * or when the DecimalFormatSymbols are destroyed.
+     * ### TODO markus 2002oct11: Consider proposing getConstSymbol() to be really public.
+     *
+     * @param symbol Constant to indicate a number format symbol.
+     * @return the format symbol by the param 'symbol'
+     * @internal
+     */
+    inline const UnicodeString &getConstSymbol(ENumberFormatSymbol symbol) const;
+
+    /**
+     * Returns that pattern stored in currecy info. Internal API for use by NumberFormat API.
+     * @internal
+     */
+    inline const UChar* getCurrencyPattern(void) const;
+
+private:
+    /**
+     * Private symbol strings.
+     * They are either loaded from a resource bundle or otherwise owned.
+     * setSymbol() clones the symbol string.
+     * Readonly aliases can only come from a resource bundle, so that we can always
+     * use fastCopyFrom() with them.
+     *
+     * If DecimalFormatSymbols becomes subclassable and the status of fSymbols changes
+     * from private to protected,
+     * or when fSymbols can be set any other way that allows them to be readonly aliases
+     * to non-resource bundle strings,
+     * then regular UnicodeString copies must be used instead of fastCopyFrom().
+     *
+     * @internal
+     */
+    UnicodeString fSymbols[kFormatSymbolCount];
+
+    /**
+     * Non-symbol variable for getConstSymbol(). Always empty.
+     * @internal
+     */
+    UnicodeString fNoSymbol;
+
+    Locale locale;
+
+    char actualLocale[ULOC_FULLNAME_CAPACITY];
+    char validLocale[ULOC_FULLNAME_CAPACITY];
+    const UChar* currPattern;
+};
+
+// -------------------------------------
+
+inline UnicodeString
+DecimalFormatSymbols::getSymbol(ENumberFormatSymbol symbol) const {
+    const UnicodeString *strPtr;
+    if(symbol < kFormatSymbolCount) {
+        strPtr = &fSymbols[symbol];
+    } else {
+        strPtr = &fNoSymbol;
+    }
+    return *strPtr;
+}
+
+inline const UnicodeString &
+DecimalFormatSymbols::getConstSymbol(ENumberFormatSymbol symbol) const {
+    const UnicodeString *strPtr;
+    if(symbol < kFormatSymbolCount) {
+        strPtr = &fSymbols[symbol];
+    } else {
+        strPtr = &fNoSymbol;
+    }
+    return *strPtr;
+}
+
+// -------------------------------------
+
+inline void
+DecimalFormatSymbols::setSymbol(ENumberFormatSymbol symbol, const UnicodeString &value) {
+    if(symbol<kFormatSymbolCount) {
+        fSymbols[symbol]=value;
+    }
+}
+
+// -------------------------------------
+
+inline Locale
+DecimalFormatSymbols::getLocale() const {
+    return locale;
+}
+
+inline const UChar*
+DecimalFormatSymbols::getCurrencyPattern() const {
+    return currPattern;
+}
+U_NAMESPACE_END
+
+#endif /* #if !UCONFIG_NO_FORMATTING */
+
+#endif // _DCFMTSYM
+//eof


[63/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/uniset.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/uniset.h b/src/apps/couch_collate/platform/osx/icu/unicode/uniset.h
new file mode 100644
index 0000000..7839661
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/uniset.h
@@ -0,0 +1,1566 @@
+/*
+***************************************************************************
+* Copyright (C) 1999-2008, International Business Machines Corporation
+* and others. All Rights Reserved.
+***************************************************************************
+*   Date        Name        Description
+*   10/20/99    alan        Creation.
+***************************************************************************
+*/
+
+#ifndef UNICODESET_H
+#define UNICODESET_H
+
+#include "unicode/unifilt.h"
+#include "unicode/unistr.h"
+#include "unicode/uset.h"
+
+/**
+ * \file
+ * \brief C++ API: Unicode Set
+ */
+
+U_NAMESPACE_BEGIN
+
+class BMPSet;
+class ParsePosition;
+class SymbolTable;
+class UnicodeSetStringSpan;
+class UVector;
+class RuleCharacterIterator;
+
+/**
+ * A mutable set of Unicode characters and multicharacter strings.  Objects of this class
+ * represent <em>character classes</em> used in regular expressions.
+ * A character specifies a subset of Unicode code points.  Legal
+ * code points are U+0000 to U+10FFFF, inclusive.
+ *
+ * <p>The UnicodeSet class is not designed to be subclassed.
+ *
+ * <p><code>UnicodeSet</code> supports two APIs. The first is the
+ * <em>operand</em> API that allows the caller to modify the value of
+ * a <code>UnicodeSet</code> object. It conforms to Java 2's
+ * <code>java.util.Set</code> interface, although
+ * <code>UnicodeSet</code> does not actually implement that
+ * interface. All methods of <code>Set</code> are supported, with the
+ * modification that they take a character range or single character
+ * instead of an <code>Object</code>, and they take a
+ * <code>UnicodeSet</code> instead of a <code>Collection</code>.  The
+ * operand API may be thought of in terms of boolean logic: a boolean
+ * OR is implemented by <code>add</code>, a boolean AND is implemented
+ * by <code>retain</code>, a boolean XOR is implemented by
+ * <code>complement</code> taking an argument, and a boolean NOT is
+ * implemented by <code>complement</code> with no argument.  In terms
+ * of traditional set theory function names, <code>add</code> is a
+ * union, <code>retain</code> is an intersection, <code>remove</code>
+ * is an asymmetric difference, and <code>complement</code> with no
+ * argument is a set complement with respect to the superset range
+ * <code>MIN_VALUE-MAX_VALUE</code>
+ *
+ * <p>The second API is the
+ * <code>applyPattern()</code>/<code>toPattern()</code> API from the
+ * <code>java.text.Format</code>-derived classes.  Unlike the
+ * methods that add characters, add categories, and control the logic
+ * of the set, the method <code>applyPattern()</code> sets all
+ * attributes of a <code>UnicodeSet</code> at once, based on a
+ * string pattern.
+ *
+ * <p><b>Pattern syntax</b></p>
+ *
+ * Patterns are accepted by the constructors and the
+ * <code>applyPattern()</code> methods and returned by the
+ * <code>toPattern()</code> method.  These patterns follow a syntax
+ * similar to that employed by version 8 regular expression character
+ * classes.  Here are some simple examples:
+ *
+ * \htmlonly<blockquote>\endhtmlonly
+ *   <table>
+ *     <tr align="top">
+ *       <td nowrap valign="top" align="left"><code>[]</code></td>
+ *       <td valign="top">No characters</td>
+ *     </tr><tr align="top">
+ *       <td nowrap valign="top" align="left"><code>[a]</code></td>
+ *       <td valign="top">The character 'a'</td>
+ *     </tr><tr align="top">
+ *       <td nowrap valign="top" align="left"><code>[ae]</code></td>
+ *       <td valign="top">The characters 'a' and 'e'</td>
+ *     </tr>
+ *     <tr>
+ *       <td nowrap valign="top" align="left"><code>[a-e]</code></td>
+ *       <td valign="top">The characters 'a' through 'e' inclusive, in Unicode code
+ *       point order</td>
+ *     </tr>
+ *     <tr>
+ *       <td nowrap valign="top" align="left"><code>[\\u4E01]</code></td>
+ *       <td valign="top">The character U+4E01</td>
+ *     </tr>
+ *     <tr>
+ *       <td nowrap valign="top" align="left"><code>[a{ab}{ac}]</code></td>
+ *       <td valign="top">The character 'a' and the multicharacter strings &quot;ab&quot; and
+ *       &quot;ac&quot;</td>
+ *     </tr>
+ *     <tr>
+ *       <td nowrap valign="top" align="left"><code>[\\p{Lu}]</code></td>
+ *       <td valign="top">All characters in the general category Uppercase Letter</td>
+ *     </tr>
+ *   </table>
+ * \htmlonly</blockquote>\endhtmlonly
+ *
+ * Any character may be preceded by a backslash in order to remove any special
+ * meaning.  White space characters, as defined by UCharacter.isWhitespace(), are
+ * ignored, unless they are escaped.
+ *
+ * <p>Property patterns specify a set of characters having a certain
+ * property as defined by the Unicode standard.  Both the POSIX-like
+ * "[:Lu:]" and the Perl-like syntax "\\p{Lu}" are recognized.  For a
+ * complete list of supported property patterns, see the User's Guide
+ * for UnicodeSet at
+ * <a href="http://icu-project.org/userguide/unicodeSet.html">
+ * http://icu-project.org/userguide/unicodeSet.html</a>.
+ * Actual determination of property data is defined by the underlying
+ * Unicode database as implemented by UCharacter.
+ *
+ * <p>Patterns specify individual characters, ranges of characters, and
+ * Unicode property sets.  When elements are concatenated, they
+ * specify their union.  To complement a set, place a '^' immediately
+ * after the opening '['.  Property patterns are inverted by modifying
+ * their delimiters; "[:^foo]" and "\\P{foo}".  In any other location,
+ * '^' has no special meaning.
+ *
+ * <p>Ranges are indicated by placing two a '-' between two
+ * characters, as in "a-z".  This specifies the range of all
+ * characters from the left to the right, in Unicode order.  If the
+ * left character is greater than or equal to the
+ * right character it is a syntax error.  If a '-' occurs as the first
+ * character after the opening '[' or '[^', or if it occurs as the
+ * last character before the closing ']', then it is taken as a
+ * literal.  Thus "[a\-b]", "[-ab]", and "[ab-]" all indicate the same
+ * set of three characters, 'a', 'b', and '-'.
+ *
+ * <p>Sets may be intersected using the '&' operator or the asymmetric
+ * set difference may be taken using the '-' operator, for example,
+ * "[[:L:]&[\\u0000-\\u0FFF]]" indicates the set of all Unicode letters
+ * with values less than 4096.  Operators ('&' and '|') have equal
+ * precedence and bind left-to-right.  Thus
+ * "[[:L:]-[a-z]-[\\u0100-\\u01FF]]" is equivalent to
+ * "[[[:L:]-[a-z]]-[\\u0100-\\u01FF]]".  This only really matters for
+ * difference; intersection is commutative.
+ *
+ * <table>
+ * <tr valign=top><td nowrap><code>[a]</code><td>The set containing 'a'
+ * <tr valign=top><td nowrap><code>[a-z]</code><td>The set containing 'a'
+ * through 'z' and all letters in between, in Unicode order
+ * <tr valign=top><td nowrap><code>[^a-z]</code><td>The set containing
+ * all characters but 'a' through 'z',
+ * that is, U+0000 through 'a'-1 and 'z'+1 through U+10FFFF
+ * <tr valign=top><td nowrap><code>[[<em>pat1</em>][<em>pat2</em>]]</code>
+ * <td>The union of sets specified by <em>pat1</em> and <em>pat2</em>
+ * <tr valign=top><td nowrap><code>[[<em>pat1</em>]&[<em>pat2</em>]]</code>
+ * <td>The intersection of sets specified by <em>pat1</em> and <em>pat2</em>
+ * <tr valign=top><td nowrap><code>[[<em>pat1</em>]-[<em>pat2</em>]]</code>
+ * <td>The asymmetric difference of sets specified by <em>pat1</em> and
+ * <em>pat2</em>
+ * <tr valign=top><td nowrap><code>[:Lu:] or \\p{Lu}</code>
+ * <td>The set of characters having the specified
+ * Unicode property; in
+ * this case, Unicode uppercase letters
+ * <tr valign=top><td nowrap><code>[:^Lu:] or \\P{Lu}</code>
+ * <td>The set of characters <em>not</em> having the given
+ * Unicode property
+ * </table>
+ *
+ * <p><b>Warning</b>: you cannot add an empty string ("") to a UnicodeSet.</p>
+ *
+ * <p><b>Formal syntax</b></p>
+ *
+ * \htmlonly<blockquote>\endhtmlonly
+ *   <table>
+ *     <tr align="top">
+ *       <td nowrap valign="top" align="right"><code>pattern :=&nbsp; </code></td>
+ *       <td valign="top"><code>('[' '^'? item* ']') |
+ *       property</code></td>
+ *     </tr>
+ *     <tr align="top">
+ *       <td nowrap valign="top" align="right"><code>item :=&nbsp; </code></td>
+ *       <td valign="top"><code>char | (char '-' char) | pattern-expr<br>
+ *       </code></td>
+ *     </tr>
+ *     <tr align="top">
+ *       <td nowrap valign="top" align="right"><code>pattern-expr :=&nbsp; </code></td>
+ *       <td valign="top"><code>pattern | pattern-expr pattern |
+ *       pattern-expr op pattern<br>
+ *       </code></td>
+ *     </tr>
+ *     <tr align="top">
+ *       <td nowrap valign="top" align="right"><code>op :=&nbsp; </code></td>
+ *       <td valign="top"><code>'&amp;' | '-'<br>
+ *       </code></td>
+ *     </tr>
+ *     <tr align="top">
+ *       <td nowrap valign="top" align="right"><code>special :=&nbsp; </code></td>
+ *       <td valign="top"><code>'[' | ']' | '-'<br>
+ *       </code></td>
+ *     </tr>
+ *     <tr align="top">
+ *       <td nowrap valign="top" align="right"><code>char :=&nbsp; </code></td>
+ *       <td valign="top"><em>any character that is not</em><code> special<br>
+ *       | ('\' </code><em>any character</em><code>)<br>
+ *       | ('\\u' hex hex hex hex)<br>
+ *       </code></td>
+ *     </tr>
+ *     <tr align="top">
+ *       <td nowrap valign="top" align="right"><code>hex :=&nbsp; </code></td>
+ *       <td valign="top"><em>any character for which
+ *       </em><code>Character.digit(c, 16)</code><em>
+ *       returns a non-negative result</em></td>
+ *     </tr>
+ *     <tr>
+ *       <td nowrap valign="top" align="right"><code>property :=&nbsp; </code></td>
+ *       <td valign="top"><em>a Unicode property set pattern</em></td>
+ *     </tr>
+ *   </table>
+ *   <br>
+ *   <table border="1">
+ *     <tr>
+ *       <td>Legend: <table>
+ *         <tr>
+ *           <td nowrap valign="top"><code>a := b</code></td>
+ *           <td width="20" valign="top">&nbsp; </td>
+ *           <td valign="top"><code>a</code> may be replaced by <code>b</code> </td>
+ *         </tr>
+ *         <tr>
+ *           <td nowrap valign="top"><code>a?</code></td>
+ *           <td valign="top"></td>
+ *           <td valign="top">zero or one instance of <code>a</code><br>
+ *           </td>
+ *         </tr>
+ *         <tr>
+ *           <td nowrap valign="top"><code>a*</code></td>
+ *           <td valign="top"></td>
+ *           <td valign="top">one or more instances of <code>a</code><br>
+ *           </td>
+ *         </tr>
+ *         <tr>
+ *           <td nowrap valign="top"><code>a | b</code></td>
+ *           <td valign="top"></td>
+ *           <td valign="top">either <code>a</code> or <code>b</code><br>
+ *           </td>
+ *         </tr>
+ *         <tr>
+ *           <td nowrap valign="top"><code>'a'</code></td>
+ *           <td valign="top"></td>
+ *           <td valign="top">the literal string between the quotes </td>
+ *         </tr>
+ *       </table>
+ *       </td>
+ *     </tr>
+ *   </table>
+ * \htmlonly</blockquote>\endhtmlonly
+ * 
+ * <p>Note:
+ *  - Most UnicodeSet methods do not take a UErrorCode parameter because
+ *   there are usually very few opportunities for failure other than a shortage
+ *   of memory, error codes in low-level C++ string methods would be inconvenient,
+ *   and the error code as the last parameter (ICU convention) would prevent
+ *   the use of default parameter values.
+ *   Instead, such methods set the UnicodeSet into a "bogus" state
+ *   (see isBogus()) if an error occurs.
+ *
+ * @author Alan Liu
+ * @stable ICU 2.0
+ */
+class U_COMMON_API UnicodeSet : public UnicodeFilter {
+
+    int32_t len; // length of list used; 0 <= len <= capacity
+    int32_t capacity; // capacity of list
+    UChar32* list; // MUST be terminated with HIGH
+    BMPSet *bmpSet; // The set is frozen iff either bmpSet or stringSpan is not NULL.
+    UChar32* buffer; // internal buffer, may be NULL
+    int32_t bufferCapacity; // capacity of buffer
+    int32_t patLen;
+
+    /**
+     * The pattern representation of this set.  This may not be the
+     * most economical pattern.  It is the pattern supplied to
+     * applyPattern(), with variables substituted and whitespace
+     * removed.  For sets constructed without applyPattern(), or
+     * modified using the non-pattern API, this string will be empty,
+     * indicating that toPattern() must generate a pattern
+     * representation from the inversion list.
+     */
+    UChar *pat;
+    UVector* strings; // maintained in sorted order
+    UnicodeSetStringSpan *stringSpan;
+
+private:
+    enum { // constants
+        kIsBogus = 1       // This set is bogus (i.e. not valid)
+    };
+    uint8_t fFlags;         // Bit flag (see constants above)
+public:
+    /**
+     * Determine if this object contains a valid set.
+     * A bogus set has no value. It is different from an empty set.
+     * It can be used to indicate that no set value is available.
+     *
+     * @return TRUE if the set is valid, FALSE otherwise
+     * @see setToBogus()
+     * @draft ICU 4.0
+     */
+    inline UBool isBogus(void) const;
+    
+    /**
+     * Make this UnicodeSet object invalid.
+     * The string will test TRUE with isBogus().
+     *
+     * A bogus set has no value. It is different from an empty set.
+     * It can be used to indicate that no set value is available.
+     *
+     * This utility function is used throughout the UnicodeSet
+     * implementation to indicate that a UnicodeSet operation failed,
+     * and may be used in other functions,
+     * especially but not exclusively when such functions do not
+     * take a UErrorCode for simplicity.
+     *
+     * @see isBogus()
+     * @draft ICU 4.0
+     */
+    void setToBogus();
+
+public:
+
+    enum {
+        /**
+         * Minimum value that can be stored in a UnicodeSet.
+         * @stable ICU 2.4
+         */
+        MIN_VALUE = 0,
+
+        /**
+         * Maximum value that can be stored in a UnicodeSet.
+         * @stable ICU 2.4
+         */
+        MAX_VALUE = 0x10ffff
+    };
+
+    //----------------------------------------------------------------
+    // Constructors &c
+    //----------------------------------------------------------------
+
+public:
+
+    /**
+     * Constructs an empty set.
+     * @stable ICU 2.0
+     */
+    UnicodeSet();
+
+    /**
+     * Constructs a set containing the given range. If <code>end >
+     * start</code> then an empty set is created.
+     *
+     * @param start first character, inclusive, of range
+     * @param end last character, inclusive, of range
+     * @stable ICU 2.4
+     */
+    UnicodeSet(UChar32 start, UChar32 end);
+
+    /**
+     * Constructs a set from the given pattern.  See the class
+     * description for the syntax of the pattern language.
+     * @param pattern a string specifying what characters are in the set
+     * @param status returns <code>U_ILLEGAL_ARGUMENT_ERROR</code> if the pattern
+     * contains a syntax error.
+     * @stable ICU 2.0
+     */
+    UnicodeSet(const UnicodeString& pattern,
+               UErrorCode& status);
+
+    /**
+     * Constructs a set from the given pattern.  See the class
+     * description for the syntax of the pattern language.
+     * @param pattern a string specifying what characters are in the set
+     * @param options bitmask for options to apply to the pattern.
+     * Valid options are USET_IGNORE_SPACE and USET_CASE_INSENSITIVE.
+     * @param symbols a symbol table mapping variable names to values
+     * and stand-in characters to UnicodeSets; may be NULL
+     * @param status returns <code>U_ILLEGAL_ARGUMENT_ERROR</code> if the pattern
+     * contains a syntax error.
+     * @internal
+     */
+    UnicodeSet(const UnicodeString& pattern,
+               uint32_t options,
+               const SymbolTable* symbols,
+               UErrorCode& status);
+
+    /**
+     * Constructs a set from the given pattern.  See the class description
+     * for the syntax of the pattern language.
+     * @param pattern a string specifying what characters are in the set
+     * @param pos on input, the position in pattern at which to start parsing.
+     * On output, the position after the last character parsed.
+     * @param options bitmask for options to apply to the pattern.
+     * Valid options are USET_IGNORE_SPACE and USET_CASE_INSENSITIVE.
+     * @param symbols a symbol table mapping variable names to values
+     * and stand-in characters to UnicodeSets; may be NULL
+     * @param status input-output error code
+     * @stable ICU 2.8
+     */
+    UnicodeSet(const UnicodeString& pattern, ParsePosition& pos,
+               uint32_t options,
+               const SymbolTable* symbols,
+               UErrorCode& status);
+
+    /**
+     * Constructs a set that is identical to the given UnicodeSet.
+     * @stable ICU 2.0
+     */
+    UnicodeSet(const UnicodeSet& o);
+
+    /**
+     * Destructs the set.
+     * @stable ICU 2.0
+     */
+    virtual ~UnicodeSet();
+
+    /**
+     * Assigns this object to be a copy of another.
+     * A frozen set will not be modified.
+     * @stable ICU 2.0
+     */
+    UnicodeSet& operator=(const UnicodeSet& o);
+
+    /**
+     * Compares the specified object with this set for equality.  Returns
+     * <tt>true</tt> if the two sets
+     * have the same size, and every member of the specified set is
+     * contained in this set (or equivalently, every member of this set is
+     * contained in the specified set).
+     *
+     * @param o set to be compared for equality with this set.
+     * @return <tt>true</tt> if the specified set is equal to this set.
+     * @stable ICU 2.0
+     */
+    virtual UBool operator==(const UnicodeSet& o) const;
+
+    /**
+     * Compares the specified object with this set for equality.  Returns
+     * <tt>true</tt> if the specified set is not equal to this set.
+     * @stable ICU 2.0
+     */
+    UBool operator!=(const UnicodeSet& o) const;
+
+    /**
+     * Returns a copy of this object.  All UnicodeFunctor objects have
+     * to support cloning in order to allow classes using
+     * UnicodeFunctors, such as Transliterator, to implement cloning.
+     * If this set is frozen, then the clone will be frozen as well.
+     * Use cloneAsThawed() for a mutable clone of a frozen set.
+     * @see cloneAsThawed
+     * @stable ICU 2.0
+     */
+    virtual UnicodeFunctor* clone() const;
+
+    /**
+     * Returns the hash code value for this set.
+     *
+     * @return the hash code value for this set.
+     * @see Object#hashCode()
+     * @stable ICU 2.0
+     */
+    virtual int32_t hashCode(void) const;
+
+    //----------------------------------------------------------------
+    // Freezable API
+    //----------------------------------------------------------------
+
+    /**
+     * Determines whether the set has been frozen (made immutable) or not.
+     * See the ICU4J Freezable interface for details.
+     * @return TRUE/FALSE for whether the set has been frozen
+     * @see freeze
+     * @see cloneAsThawed
+     * @stable ICU 4.0
+     */
+    inline UBool isFrozen() const;
+
+    /**
+     * Freeze the set (make it immutable).
+     * Once frozen, it cannot be unfrozen and is therefore thread-safe
+     * until it is deleted.
+     * See the ICU4J Freezable interface for details.
+     * Freezing the set may also make some operations faster, for example
+     * contains() and span().
+     * A frozen set will not be modified. (It remains frozen.)
+     * @return this set.
+     * @see isFrozen
+     * @see cloneAsThawed
+     * @stable ICU 4.0
+     */
+    UnicodeFunctor *freeze();
+
+    /**
+     * Clone the set and make the clone mutable.
+     * See the ICU4J Freezable interface for details.
+     * @return the mutable clone
+     * @see freeze
+     * @see isFrozen
+     * @stable ICU 4.0
+     */
+    UnicodeFunctor *cloneAsThawed() const;
+
+    //----------------------------------------------------------------
+    // Public API
+    //----------------------------------------------------------------
+
+    /**
+     * Make this object represent the range <code>start - end</code>.
+     * If <code>end > start</code> then this object is set to an
+     * an empty range.
+     * A frozen set will not be modified.
+     *
+     * @param start first character in the set, inclusive
+     * @param end last character in the set, inclusive
+     * @stable ICU 2.4
+     */
+    UnicodeSet& set(UChar32 start, UChar32 end);
+
+    /**
+     * Return true if the given position, in the given pattern, appears
+     * to be the start of a UnicodeSet pattern.
+     * @stable ICU 2.4
+     */
+    static UBool resemblesPattern(const UnicodeString& pattern,
+                                  int32_t pos);
+
+    /**
+     * Modifies this set to represent the set specified by the given
+     * pattern, optionally ignoring white space.  See the class
+     * description for the syntax of the pattern language.
+     * A frozen set will not be modified.
+     * @param pattern a string specifying what characters are in the set
+     * @param status returns <code>U_ILLEGAL_ARGUMENT_ERROR</code> if the pattern
+     * contains a syntax error.
+     * <em> Empties the set passed before applying the pattern.</em>
+     * @return a reference to this
+     * @stable ICU 2.0
+     */
+    UnicodeSet& applyPattern(const UnicodeString& pattern,
+                             UErrorCode& status);
+
+    /**
+     * Modifies this set to represent the set specified by the given
+     * pattern, optionally ignoring white space.  See the class
+     * description for the syntax of the pattern language.
+     * A frozen set will not be modified.
+     * @param pattern a string specifying what characters are in the set
+     * @param options bitmask for options to apply to the pattern.
+     * Valid options are USET_IGNORE_SPACE and USET_CASE_INSENSITIVE.
+     * @param symbols a symbol table mapping variable names to
+     * values and stand-ins to UnicodeSets; may be NULL
+     * @param status returns <code>U_ILLEGAL_ARGUMENT_ERROR</code> if the pattern
+     * contains a syntax error.
+     *<em> Empties the set passed before applying the pattern.</em>
+     * @return a reference to this
+     * @internal
+     */
+    UnicodeSet& applyPattern(const UnicodeString& pattern,
+                             uint32_t options,
+                             const SymbolTable* symbols,
+                             UErrorCode& status);
+
+    /**
+     * Parses the given pattern, starting at the given position.  The
+     * character at pattern.charAt(pos.getIndex()) must be '[', or the
+     * parse fails.  Parsing continues until the corresponding closing
+     * ']'.  If a syntax error is encountered between the opening and
+     * closing brace, the parse fails.  Upon return from a successful
+     * parse, the ParsePosition is updated to point to the character
+     * following the closing ']', and a StringBuffer containing a
+     * pairs list for the parsed pattern is returned.  This method calls
+     * itself recursively to parse embedded subpatterns.
+     *<em> Empties the set passed before applying the pattern.</em>
+     * A frozen set will not be modified.
+     *
+     * @param pattern the string containing the pattern to be parsed.
+     * The portion of the string from pos.getIndex(), which must be a
+     * '[', to the corresponding closing ']', is parsed.
+     * @param pos upon entry, the position at which to being parsing.
+     * The character at pattern.charAt(pos.getIndex()) must be a '['.
+     * Upon return from a successful parse, pos.getIndex() is either
+     * the character after the closing ']' of the parsed pattern, or
+     * pattern.length() if the closing ']' is the last character of
+     * the pattern string.
+     * @param options bitmask for options to apply to the pattern.
+     * Valid options are USET_IGNORE_SPACE and USET_CASE_INSENSITIVE.
+     * @param symbols a symbol table mapping variable names to
+     * values and stand-ins to UnicodeSets; may be NULL
+     * @param status returns <code>U_ILLEGAL_ARGUMENT_ERROR</code> if the pattern
+     * contains a syntax error.
+     * @return a reference to this
+     * @stable ICU 2.8
+     */
+    UnicodeSet& applyPattern(const UnicodeString& pattern,
+                             ParsePosition& pos,
+                             uint32_t options,
+                             const SymbolTable* symbols,
+                             UErrorCode& status);
+
+    /**
+     * Returns a string representation of this set.  If the result of
+     * calling this function is passed to a UnicodeSet constructor, it
+     * will produce another set that is equal to this one.
+     * A frozen set will not be modified.
+     * @param result the string to receive the rules.  Previous
+     * contents will be deleted.
+     * @param escapeUnprintable if TRUE then convert unprintable
+     * character to their hex escape representations, \\uxxxx or
+     * \\Uxxxxxxxx.  Unprintable characters are those other than
+     * U+000A, U+0020..U+007E.
+     * @stable ICU 2.0
+     */
+    virtual UnicodeString& toPattern(UnicodeString& result,
+                             UBool escapeUnprintable = FALSE) const;
+
+    /**
+     * Modifies this set to contain those code points which have the given value
+     * for the given binary or enumerated property, as returned by
+     * u_getIntPropertyValue.  Prior contents of this set are lost.
+     * A frozen set will not be modified.
+     *
+     * @param prop a property in the range UCHAR_BIN_START..UCHAR_BIN_LIMIT-1
+     * or UCHAR_INT_START..UCHAR_INT_LIMIT-1
+     * or UCHAR_MASK_START..UCHAR_MASK_LIMIT-1.
+     *
+     * @param value a value in the range u_getIntPropertyMinValue(prop)..
+     * u_getIntPropertyMaxValue(prop), with one exception.  If prop is
+     * UCHAR_GENERAL_CATEGORY_MASK, then value should not be a UCharCategory, but
+     * rather a mask value produced by U_GET_GC_MASK().  This allows grouped
+     * categories such as [:L:] to be represented.
+     *
+     * @param ec error code input/output parameter
+     *
+     * @return a reference to this set
+     *
+     * @stable ICU 2.4
+     */
+    UnicodeSet& applyIntPropertyValue(UProperty prop,
+                                      int32_t value,
+                                      UErrorCode& ec);
+
+    /**
+     * Modifies this set to contain those code points which have the
+     * given value for the given property.  Prior contents of this
+     * set are lost.
+     * A frozen set will not be modified.
+     *
+     * @param prop a property alias, either short or long.  The name is matched
+     * loosely.  See PropertyAliases.txt for names and a description of loose
+     * matching.  If the value string is empty, then this string is interpreted
+     * as either a General_Category value alias, a Script value alias, a binary
+     * property alias, or a special ID.  Special IDs are matched loosely and
+     * correspond to the following sets:
+     *
+     * "ANY" = [\\u0000-\\U0010FFFF],
+     * "ASCII" = [\\u0000-\\u007F],
+     * "Assigned" = [:^Cn:].
+     *
+     * @param value a value alias, either short or long.  The name is matched
+     * loosely.  See PropertyValueAliases.txt for names and a description of
+     * loose matching.  In addition to aliases listed, numeric values and
+     * canonical combining classes may be expressed numerically, e.g., ("nv",
+     * "0.5") or ("ccc", "220").  The value string may also be empty.
+     *
+     * @param ec error code input/output parameter
+     *
+     * @return a reference to this set
+     *
+     * @stable ICU 2.4
+     */
+    UnicodeSet& applyPropertyAlias(const UnicodeString& prop,
+                                   const UnicodeString& value,
+                                   UErrorCode& ec);
+
+    /**
+     * Returns the number of elements in this set (its cardinality).
+     * Note than the elements of a set may include both individual
+     * codepoints and strings.
+     *
+     * @return the number of elements in this set (its cardinality).
+     * @stable ICU 2.0
+     */
+    virtual int32_t size(void) const;
+
+    /**
+     * Returns <tt>true</tt> if this set contains no elements.
+     *
+     * @return <tt>true</tt> if this set contains no elements.
+     * @stable ICU 2.0
+     */
+    virtual UBool isEmpty(void) const;
+
+    /**
+     * Returns true if this set contains the given character.
+     * This function works faster with a frozen set.
+     * @param c character to be checked for containment
+     * @return true if the test condition is met
+     * @stable ICU 2.0
+     */
+    virtual UBool contains(UChar32 c) const;
+
+    /**
+     * Returns true if this set contains every character
+     * of the given range.
+     * @param start first character, inclusive, of the range
+     * @param end last character, inclusive, of the range
+     * @return true if the test condition is met
+     * @stable ICU 2.0
+     */
+    virtual UBool contains(UChar32 start, UChar32 end) const;
+
+    /**
+     * Returns <tt>true</tt> if this set contains the given
+     * multicharacter string.
+     * @param s string to be checked for containment
+     * @return <tt>true</tt> if this set contains the specified string
+     * @stable ICU 2.4
+     */
+    UBool contains(const UnicodeString& s) const;
+
+    /**
+     * Returns true if this set contains all the characters and strings
+     * of the given set.
+     * @param c set to be checked for containment
+     * @return true if the test condition is met
+     * @stable ICU 2.4
+     */
+    virtual UBool containsAll(const UnicodeSet& c) const;
+
+    /**
+     * Returns true if this set contains all the characters
+     * of the given string.
+     * @param s string containing characters to be checked for containment
+     * @return true if the test condition is met
+     * @stable ICU 2.4
+     */
+    UBool containsAll(const UnicodeString& s) const;
+
+    /**
+     * Returns true if this set contains none of the characters
+     * of the given range.
+     * @param start first character, inclusive, of the range
+     * @param end last character, inclusive, of the range
+     * @return true if the test condition is met
+     * @stable ICU 2.4
+     */
+    UBool containsNone(UChar32 start, UChar32 end) const;
+
+    /**
+     * Returns true if this set contains none of the characters and strings
+     * of the given set.
+     * @param c set to be checked for containment
+     * @return true if the test condition is met
+     * @stable ICU 2.4
+     */
+    UBool containsNone(const UnicodeSet& c) const;
+
+    /**
+     * Returns true if this set contains none of the characters
+     * of the given string.
+     * @param s string containing characters to be checked for containment
+     * @return true if the test condition is met
+     * @stable ICU 2.4
+     */
+    UBool containsNone(const UnicodeString& s) const;
+
+    /**
+     * Returns true if this set contains one or more of the characters
+     * in the given range.
+     * @param start first character, inclusive, of the range
+     * @param end last character, inclusive, of the range
+     * @return true if the condition is met
+     * @stable ICU 2.4
+     */
+    inline UBool containsSome(UChar32 start, UChar32 end) const;
+
+    /**
+     * Returns true if this set contains one or more of the characters
+     * and strings of the given set.
+     * @param s The set to be checked for containment
+     * @return true if the condition is met
+     * @stable ICU 2.4
+     */
+    inline UBool containsSome(const UnicodeSet& s) const;
+
+    /**
+     * Returns true if this set contains one or more of the characters
+     * of the given string.
+     * @param s string containing characters to be checked for containment
+     * @return true if the condition is met
+     * @stable ICU 2.4
+     */
+    inline UBool containsSome(const UnicodeString& s) const;
+
+    /**
+     * Returns the length of the initial substring of the input string which
+     * consists only of characters and strings that are contained in this set
+     * (USET_SPAN_CONTAINED, USET_SPAN_SIMPLE),
+     * or only of characters and strings that are not contained
+     * in this set (USET_SPAN_NOT_CONTAINED).
+     * See USetSpanCondition for details.
+     * Similar to the strspn() C library function.
+     * Unpaired surrogates are treated according to contains() of their surrogate code points.
+     * This function works faster with a frozen set and with a non-negative string length argument.
+     * @param s start of the string
+     * @param length of the string; can be -1 for NUL-terminated
+     * @param spanCondition specifies the containment condition
+     * @return the length of the initial substring according to the spanCondition;
+     *         0 if the start of the string does not fit the spanCondition
+     * @stable ICU 4.0
+     * @see USetSpanCondition
+     */
+    int32_t span(const UChar *s, int32_t length, USetSpanCondition spanCondition) const;
+
+    /**
+     * Returns the start of the trailing substring of the input string which
+     * consists only of characters and strings that are contained in this set
+     * (USET_SPAN_CONTAINED, USET_SPAN_SIMPLE),
+     * or only of characters and strings that are not contained
+     * in this set (USET_SPAN_NOT_CONTAINED).
+     * See USetSpanCondition for details.
+     * Unpaired surrogates are treated according to contains() of their surrogate code points.
+     * This function works faster with a frozen set and with a non-negative string length argument.
+     * @param s start of the string
+     * @param length of the string; can be -1 for NUL-terminated
+     * @param spanCondition specifies the containment condition
+     * @return the start of the trailing substring according to the spanCondition;
+     *         the string length if the end of the string does not fit the spanCondition
+     * @stable ICU 4.0
+     * @see USetSpanCondition
+     */
+    int32_t spanBack(const UChar *s, int32_t length, USetSpanCondition spanCondition) const;
+
+    /**
+     * Returns the length of the initial substring of the input string which
+     * consists only of characters and strings that are contained in this set
+     * (USET_SPAN_CONTAINED, USET_SPAN_SIMPLE),
+     * or only of characters and strings that are not contained
+     * in this set (USET_SPAN_NOT_CONTAINED).
+     * See USetSpanCondition for details.
+     * Similar to the strspn() C library function.
+     * Malformed byte sequences are treated according to contains(0xfffd).
+     * This function works faster with a frozen set and with a non-negative string length argument.
+     * @param s start of the string (UTF-8)
+     * @param length of the string; can be -1 for NUL-terminated
+     * @param spanCondition specifies the containment condition
+     * @return the length of the initial substring according to the spanCondition;
+     *         0 if the start of the string does not fit the spanCondition
+     * @stable ICU 4.0
+     * @see USetSpanCondition
+     */
+    int32_t spanUTF8(const char *s, int32_t length, USetSpanCondition spanCondition) const;
+
+    /**
+     * Returns the start of the trailing substring of the input string which
+     * consists only of characters and strings that are contained in this set
+     * (USET_SPAN_CONTAINED, USET_SPAN_SIMPLE),
+     * or only of characters and strings that are not contained
+     * in this set (USET_SPAN_NOT_CONTAINED).
+     * See USetSpanCondition for details.
+     * Malformed byte sequences are treated according to contains(0xfffd).
+     * This function works faster with a frozen set and with a non-negative string length argument.
+     * @param s start of the string (UTF-8)
+     * @param length of the string; can be -1 for NUL-terminated
+     * @param spanCondition specifies the containment condition
+     * @return the start of the trailing substring according to the spanCondition;
+     *         the string length if the end of the string does not fit the spanCondition
+     * @stable ICU 4.0
+     * @see USetSpanCondition
+     */
+    int32_t spanBackUTF8(const char *s, int32_t length, USetSpanCondition spanCondition) const;
+
+    /**
+     * Implement UnicodeMatcher::matches()
+     * @stable ICU 2.4
+     */
+    virtual UMatchDegree matches(const Replaceable& text,
+                         int32_t& offset,
+                         int32_t limit,
+                         UBool incremental);
+
+private:
+    /**
+     * Returns the longest match for s in text at the given position.
+     * If limit > start then match forward from start+1 to limit
+     * matching all characters except s.charAt(0).  If limit < start,
+     * go backward starting from start-1 matching all characters
+     * except s.charAt(s.length()-1).  This method assumes that the
+     * first character, text.charAt(start), matches s, so it does not
+     * check it.
+     * @param text the text to match
+     * @param start the first character to match.  In the forward
+     * direction, text.charAt(start) is matched against s.charAt(0).
+     * In the reverse direction, it is matched against
+     * s.charAt(s.length()-1).
+     * @param limit the limit offset for matching, either last+1 in
+     * the forward direction, or last-1 in the reverse direction,
+     * where last is the index of the last character to match.
+     * @return If part of s matches up to the limit, return |limit -
+     * start|.  If all of s matches before reaching the limit, return
+     * s.length().  If there is a mismatch between s and text, return
+     * 0
+     */
+    static int32_t matchRest(const Replaceable& text,
+                             int32_t start, int32_t limit,
+                             const UnicodeString& s);
+
+    /**
+     * Returns the smallest value i such that c < list[i].  Caller
+     * must ensure that c is a legal value or this method will enter
+     * an infinite loop.  This method performs a binary search.
+     * @param c a character in the range MIN_VALUE..MAX_VALUE
+     * inclusive
+     * @return the smallest integer i in the range 0..len-1,
+     * inclusive, such that c < list[i]
+     */
+    int32_t findCodePoint(UChar32 c) const;
+
+public:
+
+    /**
+     * Implementation of UnicodeMatcher API.  Union the set of all
+     * characters that may be matched by this object into the given
+     * set.
+     * @param toUnionTo the set into which to union the source characters
+     * @stable ICU 2.4
+     */
+    virtual void addMatchSetTo(UnicodeSet& toUnionTo) const;
+
+    /**
+     * Returns the index of the given character within this set, where
+     * the set is ordered by ascending code point.  If the character
+     * is not in this set, return -1.  The inverse of this method is
+     * <code>charAt()</code>.
+     * @return an index from 0..size()-1, or -1
+     * @stable ICU 2.4
+     */
+    int32_t indexOf(UChar32 c) const;
+
+    /**
+     * Returns the character at the given index within this set, where
+     * the set is ordered by ascending code point.  If the index is
+     * out of range, return (UChar32)-1.  The inverse of this method is
+     * <code>indexOf()</code>.
+     * @param index an index from 0..size()-1
+     * @return the character at the given index, or (UChar32)-1.
+     * @stable ICU 2.4
+     */
+    UChar32 charAt(int32_t index) const;
+
+    /**
+     * Adds the specified range to this set if it is not already
+     * present.  If this set already contains the specified range,
+     * the call leaves this set unchanged.  If <code>end > start</code>
+     * then an empty range is added, leaving the set unchanged.
+     * This is equivalent to a boolean logic OR, or a set UNION.
+     * A frozen set will not be modified.
+     *
+     * @param start first character, inclusive, of range to be added
+     * to this set.
+     * @param end last character, inclusive, of range to be added
+     * to this set.
+     * @stable ICU 2.0
+     */
+    virtual UnicodeSet& add(UChar32 start, UChar32 end);
+
+    /**
+     * Adds the specified character to this set if it is not already
+     * present.  If this set already contains the specified character,
+     * the call leaves this set unchanged.
+     * A frozen set will not be modified.
+     * @stable ICU 2.0
+     */
+    UnicodeSet& add(UChar32 c);
+
+    /**
+     * Adds the specified multicharacter to this set if it is not already
+     * present.  If this set already contains the multicharacter,
+     * the call leaves this set unchanged.
+     * Thus "ch" => {"ch"}
+     * <br><b>Warning: you cannot add an empty string ("") to a UnicodeSet.</b>
+     * A frozen set will not be modified.
+     * @param s the source string
+     * @return this object, for chaining
+     * @stable ICU 2.4
+     */
+    UnicodeSet& add(const UnicodeString& s);
+
+ private:
+    /**
+     * @return a code point IF the string consists of a single one.
+     * otherwise returns -1.
+     * @param string to test
+     */
+    static int32_t getSingleCP(const UnicodeString& s);
+
+    void _add(const UnicodeString& s);
+
+ public:
+    /**
+     * Adds each of the characters in this string to the set. Thus "ch" => {"c", "h"}
+     * If this set already any particular character, it has no effect on that character.
+     * A frozen set will not be modified.
+     * @param s the source string
+     * @return this object, for chaining
+     * @stable ICU 2.4
+     */
+    UnicodeSet& addAll(const UnicodeString& s);
+
+    /**
+     * Retains EACH of the characters in this string. Note: "ch" == {"c", "h"}
+     * If this set already any particular character, it has no effect on that character.
+     * A frozen set will not be modified.
+     * @param s the source string
+     * @return this object, for chaining
+     * @stable ICU 2.4
+     */
+    UnicodeSet& retainAll(const UnicodeString& s);
+
+    /**
+     * Complement EACH of the characters in this string. Note: "ch" == {"c", "h"}
+     * If this set already any particular character, it has no effect on that character.
+     * A frozen set will not be modified.
+     * @param s the source string
+     * @return this object, for chaining
+     * @stable ICU 2.4
+     */
+    UnicodeSet& complementAll(const UnicodeString& s);
+
+    /**
+     * Remove EACH of the characters in this string. Note: "ch" == {"c", "h"}
+     * If this set already any particular character, it has no effect on that character.
+     * A frozen set will not be modified.
+     * @param s the source string
+     * @return this object, for chaining
+     * @stable ICU 2.4
+     */
+    UnicodeSet& removeAll(const UnicodeString& s);
+
+    /**
+     * Makes a set from a multicharacter string. Thus "ch" => {"ch"}
+     * <br><b>Warning: you cannot add an empty string ("") to a UnicodeSet.</b>
+     * @param s the source string
+     * @return a newly created set containing the given string.
+     * The caller owns the return object and is responsible for deleting it.
+     * @stable ICU 2.4
+     */
+    static UnicodeSet* U_EXPORT2 createFrom(const UnicodeString& s);
+
+
+    /**
+     * Makes a set from each of the characters in the string. Thus "ch" => {"c", "h"}
+     * @param s the source string
+     * @return a newly created set containing the given characters
+     * The caller owns the return object and is responsible for deleting it.
+     * @stable ICU 2.4
+     */
+    static UnicodeSet* U_EXPORT2 createFromAll(const UnicodeString& s);
+
+    /**
+     * Retain only the elements in this set that are contained in the
+     * specified range.  If <code>end > start</code> then an empty range is
+     * retained, leaving the set empty.  This is equivalent to
+     * a boolean logic AND, or a set INTERSECTION.
+     * A frozen set will not be modified.
+     *
+     * @param start first character, inclusive, of range to be retained
+     * to this set.
+     * @param end last character, inclusive, of range to be retained
+     * to this set.
+     * @stable ICU 2.0
+     */
+    virtual UnicodeSet& retain(UChar32 start, UChar32 end);
+
+
+    /**
+     * Retain the specified character from this set if it is present.
+     * A frozen set will not be modified.
+     * @stable ICU 2.0
+     */
+    UnicodeSet& retain(UChar32 c);
+
+    /**
+     * Removes the specified range from this set if it is present.
+     * The set will not contain the specified range once the call
+     * returns.  If <code>end > start</code> then an empty range is
+     * removed, leaving the set unchanged.
+     * A frozen set will not be modified.
+     *
+     * @param start first character, inclusive, of range to be removed
+     * from this set.
+     * @param end last character, inclusive, of range to be removed
+     * from this set.
+     * @stable ICU 2.0
+     */
+    virtual UnicodeSet& remove(UChar32 start, UChar32 end);
+
+    /**
+     * Removes the specified character from this set if it is present.
+     * The set will not contain the specified range once the call
+     * returns.
+     * A frozen set will not be modified.
+     * @stable ICU 2.0
+     */
+    UnicodeSet& remove(UChar32 c);
+
+    /**
+     * Removes the specified string from this set if it is present.
+     * The set will not contain the specified character once the call
+     * returns.
+     * A frozen set will not be modified.
+     * @param s the source string
+     * @return this object, for chaining
+     * @stable ICU 2.4
+     */
+    UnicodeSet& remove(const UnicodeString& s);
+
+    /**
+     * Inverts this set.  This operation modifies this set so that
+     * its value is its complement.  This is equivalent to
+     * <code>complement(MIN_VALUE, MAX_VALUE)</code>.
+     * A frozen set will not be modified.
+     * @stable ICU 2.0
+     */
+    virtual UnicodeSet& complement(void);
+
+    /**
+     * Complements the specified range in this set.  Any character in
+     * the range will be removed if it is in this set, or will be
+     * added if it is not in this set.  If <code>end > start</code>
+     * then an empty range is complemented, leaving the set unchanged.
+     * This is equivalent to a boolean logic XOR.
+     * A frozen set will not be modified.
+     *
+     * @param start first character, inclusive, of range to be removed
+     * from this set.
+     * @param end last character, inclusive, of range to be removed
+     * from this set.
+     * @stable ICU 2.0
+     */
+    virtual UnicodeSet& complement(UChar32 start, UChar32 end);
+
+    /**
+     * Complements the specified character in this set.  The character
+     * will be removed if it is in this set, or will be added if it is
+     * not in this set.
+     * A frozen set will not be modified.
+     * @stable ICU 2.0
+     */
+    UnicodeSet& complement(UChar32 c);
+
+    /**
+     * Complement the specified string in this set.
+     * The set will not contain the specified string once the call
+     * returns.
+     * <br><b>Warning: you cannot add an empty string ("") to a UnicodeSet.</b>
+     * A frozen set will not be modified.
+     * @param s the string to complement
+     * @return this object, for chaining
+     * @stable ICU 2.4
+     */
+    UnicodeSet& complement(const UnicodeString& s);
+
+    /**
+     * Adds all of the elements in the specified set to this set if
+     * they're not already present.  This operation effectively
+     * modifies this set so that its value is the <i>union</i> of the two
+     * sets.  The behavior of this operation is unspecified if the specified
+     * collection is modified while the operation is in progress.
+     * A frozen set will not be modified.
+     *
+     * @param c set whose elements are to be added to this set.
+     * @see #add(UChar32, UChar32)
+     * @stable ICU 2.0
+     */
+    virtual UnicodeSet& addAll(const UnicodeSet& c);
+
+    /**
+     * Retains only the elements in this set that are contained in the
+     * specified set.  In other words, removes from this set all of
+     * its elements that are not contained in the specified set.  This
+     * operation effectively modifies this set so that its value is
+     * the <i>intersection</i> of the two sets.
+     * A frozen set will not be modified.
+     *
+     * @param c set that defines which elements this set will retain.
+     * @stable ICU 2.0
+     */
+    virtual UnicodeSet& retainAll(const UnicodeSet& c);
+
+    /**
+     * Removes from this set all of its elements that are contained in the
+     * specified set.  This operation effectively modifies this
+     * set so that its value is the <i>asymmetric set difference</i> of
+     * the two sets.
+     * A frozen set will not be modified.
+     *
+     * @param c set that defines which elements will be removed from
+     *          this set.
+     * @stable ICU 2.0
+     */
+    virtual UnicodeSet& removeAll(const UnicodeSet& c);
+
+    /**
+     * Complements in this set all elements contained in the specified
+     * set.  Any character in the other set will be removed if it is
+     * in this set, or will be added if it is not in this set.
+     * A frozen set will not be modified.
+     *
+     * @param c set that defines which elements will be xor'ed from
+     *          this set.
+     * @stable ICU 2.4
+     */
+    virtual UnicodeSet& complementAll(const UnicodeSet& c);
+
+    /**
+     * Removes all of the elements from this set.  This set will be
+     * empty after this call returns.
+     * A frozen set will not be modified.
+     * @stable ICU 2.0
+     */
+    virtual UnicodeSet& clear(void);
+
+    /**
+     * Close this set over the given attribute.  For the attribute
+     * USET_CASE, the result is to modify this set so that:
+     *
+     * 1. For each character or string 'a' in this set, all strings or
+     * characters 'b' such that foldCase(a) == foldCase(b) are added
+     * to this set.
+     *
+     * 2. For each string 'e' in the resulting set, if e !=
+     * foldCase(e), 'e' will be removed.
+     *
+     * Example: [aq\\u00DF{Bc}{bC}{Fi}] => [aAqQ\\u00DF\\uFB01{ss}{bc}{fi}]
+     *
+     * (Here foldCase(x) refers to the operation u_strFoldCase, and a
+     * == b denotes that the contents are the same, not pointer
+     * comparison.)
+     *
+     * A frozen set will not be modified.
+     *
+     * @param attribute bitmask for attributes to close over.
+     * Currently only the USET_CASE bit is supported.  Any undefined bits
+     * are ignored.
+     * @return a reference to this set.
+     * @internal
+     */
+    UnicodeSet& closeOver(int32_t attribute);
+
+    /**
+     * Remove all strings from this set.
+     *
+     * @return a reference to this set.
+     * @internal
+     */
+    virtual UnicodeSet &removeAllStrings();
+
+    /**
+     * Iteration method that returns the number of ranges contained in
+     * this set.
+     * @see #getRangeStart
+     * @see #getRangeEnd
+     * @stable ICU 2.4
+     */
+    virtual int32_t getRangeCount(void) const;
+
+    /**
+     * Iteration method that returns the first character in the
+     * specified range of this set.
+     * @see #getRangeCount
+     * @see #getRangeEnd
+     * @stable ICU 2.4
+     */
+    virtual UChar32 getRangeStart(int32_t index) const;
+
+    /**
+     * Iteration method that returns the last character in the
+     * specified range of this set.
+     * @see #getRangeStart
+     * @see #getRangeEnd
+     * @stable ICU 2.4
+     */
+    virtual UChar32 getRangeEnd(int32_t index) const;
+
+    /**
+     * Serializes this set into an array of 16-bit integers.  Serialization
+     * (currently) only records the characters in the set; multicharacter
+     * strings are ignored.
+     *
+     * The array has following format (each line is one 16-bit
+     * integer):
+     *
+     *  length     = (n+2*m) | (m!=0?0x8000:0)
+     *  bmpLength  = n; present if m!=0
+     *  bmp[0]
+     *  bmp[1]
+     *  ...
+     *  bmp[n-1]
+     *  supp-high[0]
+     *  supp-low[0]
+     *  supp-high[1]
+     *  supp-low[1]
+     *  ...
+     *  supp-high[m-1]
+     *  supp-low[m-1]
+     *
+     * The array starts with a header.  After the header are n bmp
+     * code points, then m supplementary code points.  Either n or m
+     * or both may be zero.  n+2*m is always <= 0x7FFF.
+     *
+     * If there are no supplementary characters (if m==0) then the
+     * header is one 16-bit integer, 'length', with value n.
+     *
+     * If there are supplementary characters (if m!=0) then the header
+     * is two 16-bit integers.  The first, 'length', has value
+     * (n+2*m)|0x8000.  The second, 'bmpLength', has value n.
+     *
+     * After the header the code points are stored in ascending order.
+     * Supplementary code points are stored as most significant 16
+     * bits followed by least significant 16 bits.
+     *
+     * @param dest pointer to buffer of destCapacity 16-bit integers.
+     * May be NULL only if destCapacity is zero.
+     * @param destCapacity size of dest, or zero.  Must not be negative.
+     * @param ec error code.  Will be set to U_INDEX_OUTOFBOUNDS_ERROR
+     * if n+2*m > 0x7FFF.  Will be set to U_BUFFER_OVERFLOW_ERROR if
+     * n+2*m+(m!=0?2:1) > destCapacity.
+     * @return the total length of the serialized format, including
+     * the header, that is, n+2*m+(m!=0?2:1), or 0 on error other
+     * than U_BUFFER_OVERFLOW_ERROR.
+     * @stable ICU 2.4
+     */
+    int32_t serialize(uint16_t *dest, int32_t destCapacity, UErrorCode& ec) const;
+
+    /**
+     * Reallocate this objects internal structures to take up the least
+     * possible space, without changing this object's value.
+     * A frozen set will not be modified.
+     * @stable ICU 2.4
+     */
+    virtual UnicodeSet& compact();
+
+    /**
+     * Return the class ID for this class.  This is useful only for
+     * comparing to a return value from getDynamicClassID().  For example:
+     * <pre>
+     * .      Base* polymorphic_pointer = createPolymorphicObject();
+     * .      if (polymorphic_pointer->getDynamicClassID() ==
+     * .          Derived::getStaticClassID()) ...
+     * </pre>
+     * @return          The class ID for all objects of this class.
+     * @stable ICU 2.0
+     */
+    static UClassID U_EXPORT2 getStaticClassID(void);
+
+    /**
+     * Implement UnicodeFunctor API.
+     *
+     * @return The class ID for this object. All objects of a given
+     * class have the same class ID.  Objects of other classes have
+     * different class IDs.
+     * @stable ICU 2.4
+     */
+    virtual UClassID getDynamicClassID(void) const;
+
+private:
+
+    // Private API for the USet API
+
+    friend class USetAccess;
+
+    int32_t getStringCount() const;
+
+    const UnicodeString* getString(int32_t index) const;
+
+    //----------------------------------------------------------------
+    // RuleBasedTransliterator support
+    //----------------------------------------------------------------
+
+private:
+
+    /**
+     * Returns <tt>true</tt> if this set contains any character whose low byte
+     * is the given value.  This is used by <tt>RuleBasedTransliterator</tt> for
+     * indexing.
+     */
+    virtual UBool matchesIndexValue(uint8_t v) const;
+
+private:
+
+    //----------------------------------------------------------------
+    // Implementation: Clone as thawed (see ICU4J Freezable)
+    //----------------------------------------------------------------
+
+    UnicodeSet(const UnicodeSet& o, UBool /* asThawed */);
+
+    //----------------------------------------------------------------
+    // Implementation: Pattern parsing
+    //----------------------------------------------------------------
+
+    void applyPattern(RuleCharacterIterator& chars,
+                      const SymbolTable* symbols,
+                      UnicodeString& rebuiltPat,
+                      uint32_t options,
+                      UErrorCode& ec);
+
+    //----------------------------------------------------------------
+    // Implementation: Utility methods
+    //----------------------------------------------------------------
+
+    void ensureCapacity(int32_t newLen, UErrorCode& ec);
+
+    void ensureBufferCapacity(int32_t newLen, UErrorCode& ec);
+
+    void swapBuffers(void);
+
+    UBool allocateStrings(UErrorCode &status);
+
+    UnicodeString& _toPattern(UnicodeString& result,
+                              UBool escapeUnprintable) const;
+
+    UnicodeString& _generatePattern(UnicodeString& result,
+                                    UBool escapeUnprintable) const;
+
+    static void _appendToPat(UnicodeString& buf, const UnicodeString& s, UBool escapeUnprintable);
+
+    static void _appendToPat(UnicodeString& buf, UChar32 c, UBool escapeUnprintable);
+
+    //----------------------------------------------------------------
+    // Implementation: Fundamental operators
+    //----------------------------------------------------------------
+
+    void exclusiveOr(const UChar32* other, int32_t otherLen, int8_t polarity);
+
+    void add(const UChar32* other, int32_t otherLen, int8_t polarity);
+
+    void retain(const UChar32* other, int32_t otherLen, int8_t polarity);
+
+    /**
+     * Return true if the given position, in the given pattern, appears
+     * to be the start of a property set pattern [:foo:], \\p{foo}, or
+     * \\P{foo}, or \\N{name}.
+     */
+    static UBool resemblesPropertyPattern(const UnicodeString& pattern,
+                                          int32_t pos);
+
+    static UBool resemblesPropertyPattern(RuleCharacterIterator& chars,
+                                          int32_t iterOpts);
+
+    /**
+     * Parse the given property pattern at the given parse position
+     * and set this UnicodeSet to the result.
+     *
+     * The original design document is out of date, but still useful.
+     * Ignore the property and value names:
+     * http://source.icu-project.org/repos/icu/icuhtml/trunk/design/unicodeset_properties.html
+     *
+     * Recognized syntax:
+     *
+     * [:foo:] [:^foo:] - white space not allowed within "[:" or ":]"
+     * \\p{foo} \\P{foo}  - white space not allowed within "\\p" or "\\P"
+     * \\N{name}         - white space not allowed within "\\N"
+     *
+     * Other than the above restrictions, white space is ignored.  Case
+     * is ignored except in "\\p" and "\\P" and "\\N".  In 'name' leading
+     * and trailing space is deleted, and internal runs of whitespace
+     * are collapsed to a single space.
+     *
+     * We support binary properties, enumerated properties, and the
+     * following non-enumerated properties:
+     *
+     *  Numeric_Value
+     *  Name
+     *  Unicode_1_Name
+     *
+     * @param pattern the pattern string
+     * @param ppos on entry, the position at which to begin parsing.
+     * This should be one of the locations marked '^':
+     *
+     *   [:blah:]     \\p{blah}     \\P{blah}     \\N{name}
+     *   ^       %    ^       %    ^       %    ^       %
+     *
+     * On return, the position after the last character parsed, that is,
+     * the locations marked '%'.  If the parse fails, ppos is returned
+     * unchanged.
+     * @return a reference to this.
+     */
+    UnicodeSet& applyPropertyPattern(const UnicodeString& pattern,
+                                     ParsePosition& ppos,
+                                     UErrorCode &ec);
+
+    void applyPropertyPattern(RuleCharacterIterator& chars,
+                              UnicodeString& rebuiltPat,
+                              UErrorCode& ec);
+
+    static const UnicodeSet* getInclusions(int32_t src, UErrorCode &status);
+
+    /**
+     * A filter that returns TRUE if the given code point should be
+     * included in the UnicodeSet being constructed.
+     */
+    typedef UBool (*Filter)(UChar32 codePoint, void* context);
+
+    /**
+     * Given a filter, set this UnicodeSet to the code points
+     * contained by that filter.  The filter MUST be
+     * property-conformant.  That is, if it returns value v for one
+     * code point, then it must return v for all affiliated code
+     * points, as defined by the inclusions list.  See
+     * getInclusions().
+     * src is a UPropertySource value.
+     */
+    void applyFilter(Filter filter,
+                     void* context,
+                     int32_t src,
+                     UErrorCode &status);
+
+    /**
+     * Set the new pattern to cache.
+     */
+    void setPattern(const UnicodeString& newPat);
+    /**
+     * Release existing cached pattern.
+     */
+    void releasePattern();
+
+    friend class UnicodeSetIterator;
+};
+
+inline UBool UnicodeSet::operator!=(const UnicodeSet& o) const {
+    return !operator==(o);
+}
+
+inline UBool UnicodeSet::isFrozen() const {
+    return (UBool)(bmpSet!=NULL || stringSpan!=NULL);
+}
+
+inline UBool UnicodeSet::containsSome(UChar32 start, UChar32 end) const {
+    return !containsNone(start, end);
+}
+
+inline UBool UnicodeSet::containsSome(const UnicodeSet& s) const {
+    return !containsNone(s);
+}
+
+inline UBool UnicodeSet::containsSome(const UnicodeString& s) const {
+    return !containsNone(s);
+}
+
+inline UBool UnicodeSet::isBogus() const {
+    return (UBool)(fFlags & kIsBogus);
+}
+
+U_NAMESPACE_END
+
+#endif


[15/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/js/libs/jquery.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/js/libs/jquery.js b/apps/fauxton/assets/js/libs/jquery.js
deleted file mode 100644
index c5c6482..0000000
--- a/apps/fauxton/assets/js/libs/jquery.js
+++ /dev/null
@@ -1,9789 +0,0 @@
-/*!
- * jQuery JavaScript Library v1.10.2
- * http://jquery.com/
- *
- * Includes Sizzle.js
- * http://sizzlejs.com/
- *
- * Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors
- * Released under the MIT license
- * http://jquery.org/license
- *
- * Date: 2013-07-03T13:48Z
- */
-(function( window, undefined ) {
-
-// Can't do this because several apps including ASP.NET trace
-// the stack via arguments.caller.callee and Firefox dies if
-// you try to trace through "use strict" call chains. (#13335)
-// Support: Firefox 18+
-//"use strict";
-var
-	// The deferred used on DOM ready
-	readyList,
-
-	// A central reference to the root jQuery(document)
-	rootjQuery,
-
-	// Support: IE<10
-	// For `typeof xmlNode.method` instead of `xmlNode.method !== undefined`
-	core_strundefined = typeof undefined,
-
-	// Use the correct document accordingly with window argument (sandbox)
-	location = window.location,
-	document = window.document,
-	docElem = document.documentElement,
-
-	// Map over jQuery in case of overwrite
-	_jQuery = window.jQuery,
-
-	// Map over the $ in case of overwrite
-	_$ = window.$,
-
-	// [[Class]] -> type pairs
-	class2type = {},
-
-	// List of deleted data cache ids, so we can reuse them
-	core_deletedIds = [],
-
-	core_version = "1.10.2",
-
-	// Save a reference to some core methods
-	core_concat = core_deletedIds.concat,
-	core_push = core_deletedIds.push,
-	core_slice = core_deletedIds.slice,
-	core_indexOf = core_deletedIds.indexOf,
-	core_toString = class2type.toString,
-	core_hasOwn = class2type.hasOwnProperty,
-	core_trim = core_version.trim,
-
-	// Define a local copy of jQuery
-	jQuery = function( selector, context ) {
-		// The jQuery object is actually just the init constructor 'enhanced'
-		return new jQuery.fn.init( selector, context, rootjQuery );
-	},
-
-	// Used for matching numbers
-	core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,
-
-	// Used for splitting on whitespace
-	core_rnotwhite = /\S+/g,
-
-	// Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)
-	rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
-
-	// A simple way to check for HTML strings
-	// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
-	// Strict HTML recognition (#11290: must start with <)
-	rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
-
-	// Match a standalone tag
-	rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
-
-	// JSON RegExp
-	rvalidchars = /^[\],:{}\s]*$/,
-	rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
-	rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
-	rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,
-
-	// Matches dashed string for camelizing
-	rmsPrefix = /^-ms-/,
-	rdashAlpha = /-([\da-z])/gi,
-
-	// Used by jQuery.camelCase as callback to replace()
-	fcamelCase = function( all, letter ) {
-		return letter.toUpperCase();
-	},
-
-	// The ready event handler
-	completed = function( event ) {
-
-		// readyState === "complete" is good enough for us to call the dom ready in oldIE
-		if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) {
-			detach();
-			jQuery.ready();
-		}
-	},
-	// Clean-up method for dom ready events
-	detach = function() {
-		if ( document.addEventListener ) {
-			document.removeEventListener( "DOMContentLoaded", completed, false );
-			window.removeEventListener( "load", completed, false );
-
-		} else {
-			document.detachEvent( "onreadystatechange", completed );
-			window.detachEvent( "onload", completed );
-		}
-	};
-
-jQuery.fn = jQuery.prototype = {
-	// The current version of jQuery being used
-	jquery: core_version,
-
-	constructor: jQuery,
-	init: function( selector, context, rootjQuery ) {
-		var match, elem;
-
-		// HANDLE: $(""), $(null), $(undefined), $(false)
-		if ( !selector ) {
-			return this;
-		}
-
-		// Handle HTML strings
-		if ( typeof selector === "string" ) {
-			if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
-				// Assume that strings that start and end with <> are HTML and skip the regex check
-				match = [ null, selector, null ];
-
-			} else {
-				match = rquickExpr.exec( selector );
-			}
-
-			// Match html or make sure no context is specified for #id
-			if ( match && (match[1] || !context) ) {
-
-				// HANDLE: $(html) -> $(array)
-				if ( match[1] ) {
-					context = context instanceof jQuery ? context[0] : context;
-
-					// scripts is true for back-compat
-					jQuery.merge( this, jQuery.parseHTML(
-						match[1],
-						context && context.nodeType ? context.ownerDocument || context : document,
-						true
-					) );
-
-					// HANDLE: $(html, props)
-					if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
-						for ( match in context ) {
-							// Properties of context are called as methods if possible
-							if ( jQuery.isFunction( this[ match ] ) ) {
-								this[ match ]( context[ match ] );
-
-							// ...and otherwise set as attributes
-							} else {
-								this.attr( match, context[ match ] );
-							}
-						}
-					}
-
-					return this;
-
-				// HANDLE: $(#id)
-				} else {
-					elem = document.getElementById( match[2] );
-
-					// Check parentNode to catch when Blackberry 4.6 returns
-					// nodes that are no longer in the document #6963
-					if ( elem && elem.parentNode ) {
-						// Handle the case where IE and Opera return items
-						// by name instead of ID
-						if ( elem.id !== match[2] ) {
-							return rootjQuery.find( selector );
-						}
-
-						// Otherwise, we inject the element directly into the jQuery object
-						this.length = 1;
-						this[0] = elem;
-					}
-
-					this.context = document;
-					this.selector = selector;
-					return this;
-				}
-
-			// HANDLE: $(expr, $(...))
-			} else if ( !context || context.jquery ) {
-				return ( context || rootjQuery ).find( selector );
-
-			// HANDLE: $(expr, context)
-			// (which is just equivalent to: $(context).find(expr)
-			} else {
-				return this.constructor( context ).find( selector );
-			}
-
-		// HANDLE: $(DOMElement)
-		} else if ( selector.nodeType ) {
-			this.context = this[0] = selector;
-			this.length = 1;
-			return this;
-
-		// HANDLE: $(function)
-		// Shortcut for document ready
-		} else if ( jQuery.isFunction( selector ) ) {
-			return rootjQuery.ready( selector );
-		}
-
-		if ( selector.selector !== undefined ) {
-			this.selector = selector.selector;
-			this.context = selector.context;
-		}
-
-		return jQuery.makeArray( selector, this );
-	},
-
-	// Start with an empty selector
-	selector: "",
-
-	// The default length of a jQuery object is 0
-	length: 0,
-
-	toArray: function() {
-		return core_slice.call( this );
-	},
-
-	// Get the Nth element in the matched element set OR
-	// Get the whole matched element set as a clean array
-	get: function( num ) {
-		return num == null ?
-
-			// Return a 'clean' array
-			this.toArray() :
-
-			// Return just the object
-			( num < 0 ? this[ this.length + num ] : this[ num ] );
-	},
-
-	// Take an array of elements and push it onto the stack
-	// (returning the new matched element set)
-	pushStack: function( elems ) {
-
-		// Build a new jQuery matched element set
-		var ret = jQuery.merge( this.constructor(), elems );
-
-		// Add the old object onto the stack (as a reference)
-		ret.prevObject = this;
-		ret.context = this.context;
-
-		// Return the newly-formed element set
-		return ret;
-	},
-
-	// Execute a callback for every element in the matched set.
-	// (You can seed the arguments with an array of args, but this is
-	// only used internally.)
-	each: function( callback, args ) {
-		return jQuery.each( this, callback, args );
-	},
-
-	ready: function( fn ) {
-		// Add the callback
-		jQuery.ready.promise().done( fn );
-
-		return this;
-	},
-
-	slice: function() {
-		return this.pushStack( core_slice.apply( this, arguments ) );
-	},
-
-	first: function() {
-		return this.eq( 0 );
-	},
-
-	last: function() {
-		return this.eq( -1 );
-	},
-
-	eq: function( i ) {
-		var len = this.length,
-			j = +i + ( i < 0 ? len : 0 );
-		return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
-	},
-
-	map: function( callback ) {
-		return this.pushStack( jQuery.map(this, function( elem, i ) {
-			return callback.call( elem, i, elem );
-		}));
-	},
-
-	end: function() {
-		return this.prevObject || this.constructor(null);
-	},
-
-	// For internal use only.
-	// Behaves like an Array's method, not like a jQuery method.
-	push: core_push,
-	sort: [].sort,
-	splice: [].splice
-};
-
-// Give the init function the jQuery prototype for later instantiation
-jQuery.fn.init.prototype = jQuery.fn;
-
-jQuery.extend = jQuery.fn.extend = function() {
-	var src, copyIsArray, copy, name, options, clone,
-		target = arguments[0] || {},
-		i = 1,
-		length = arguments.length,
-		deep = false;
-
-	// Handle a deep copy situation
-	if ( typeof target === "boolean" ) {
-		deep = target;
-		target = arguments[1] || {};
-		// skip the boolean and the target
-		i = 2;
-	}
-
-	// Handle case when target is a string or something (possible in deep copy)
-	if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
-		target = {};
-	}
-
-	// extend jQuery itself if only one argument is passed
-	if ( length === i ) {
-		target = this;
-		--i;
-	}
-
-	for ( ; i < length; i++ ) {
-		// Only deal with non-null/undefined values
-		if ( (options = arguments[ i ]) != null ) {
-			// Extend the base object
-			for ( name in options ) {
-				src = target[ name ];
-				copy = options[ name ];
-
-				// Prevent never-ending loop
-				if ( target === copy ) {
-					continue;
-				}
-
-				// Recurse if we're merging plain objects or arrays
-				if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
-					if ( copyIsArray ) {
-						copyIsArray = false;
-						clone = src && jQuery.isArray(src) ? src : [];
-
-					} else {
-						clone = src && jQuery.isPlainObject(src) ? src : {};
-					}
-
-					// Never move original objects, clone them
-					target[ name ] = jQuery.extend( deep, clone, copy );
-
-				// Don't bring in undefined values
-				} else if ( copy !== undefined ) {
-					target[ name ] = copy;
-				}
-			}
-		}
-	}
-
-	// Return the modified object
-	return target;
-};
-
-jQuery.extend({
-	// Unique for each copy of jQuery on the page
-	// Non-digits removed to match rinlinejQuery
-	expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ),
-
-	noConflict: function( deep ) {
-		if ( window.$ === jQuery ) {
-			window.$ = _$;
-		}
-
-		if ( deep && window.jQuery === jQuery ) {
-			window.jQuery = _jQuery;
-		}
-
-		return jQuery;
-	},
-
-	// Is the DOM ready to be used? Set to true once it occurs.
-	isReady: false,
-
-	// A counter to track how many items to wait for before
-	// the ready event fires. See #6781
-	readyWait: 1,
-
-	// Hold (or release) the ready event
-	holdReady: function( hold ) {
-		if ( hold ) {
-			jQuery.readyWait++;
-		} else {
-			jQuery.ready( true );
-		}
-	},
-
-	// Handle when the DOM is ready
-	ready: function( wait ) {
-
-		// Abort if there are pending holds or we're already ready
-		if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
-			return;
-		}
-
-		// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
-		if ( !document.body ) {
-			return setTimeout( jQuery.ready );
-		}
-
-		// Remember that the DOM is ready
-		jQuery.isReady = true;
-
-		// If a normal DOM Ready event fired, decrement, and wait if need be
-		if ( wait !== true && --jQuery.readyWait > 0 ) {
-			return;
-		}
-
-		// If there are functions bound, to execute
-		readyList.resolveWith( document, [ jQuery ] );
-
-		// Trigger any bound ready events
-		if ( jQuery.fn.trigger ) {
-			jQuery( document ).trigger("ready").off("ready");
-		}
-	},
-
-	// See test/unit/core.js for details concerning isFunction.
-	// Since version 1.3, DOM methods and functions like alert
-	// aren't supported. They return false on IE (#2968).
-	isFunction: function( obj ) {
-		return jQuery.type(obj) === "function";
-	},
-
-	isArray: Array.isArray || function( obj ) {
-		return jQuery.type(obj) === "array";
-	},
-
-	isWindow: function( obj ) {
-		/* jshint eqeqeq: false */
-		return obj != null && obj == obj.window;
-	},
-
-	isNumeric: function( obj ) {
-		return !isNaN( parseFloat(obj) ) && isFinite( obj );
-	},
-
-	type: function( obj ) {
-		if ( obj == null ) {
-			return String( obj );
-		}
-		return typeof obj === "object" || typeof obj === "function" ?
-			class2type[ core_toString.call(obj) ] || "object" :
-			typeof obj;
-	},
-
-	isPlainObject: function( obj ) {
-		var key;
-
-		// Must be an Object.
-		// Because of IE, we also have to check the presence of the constructor property.
-		// Make sure that DOM nodes and window objects don't pass through, as well
-		if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
-			return false;
-		}
-
-		try {
-			// Not own constructor property must be Object
-			if ( obj.constructor &&
-				!core_hasOwn.call(obj, "constructor") &&
-				!core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
-				return false;
-			}
-		} catch ( e ) {
-			// IE8,9 Will throw exceptions on certain host objects #9897
-			return false;
-		}
-
-		// Support: IE<9
-		// Handle iteration over inherited properties before own properties.
-		if ( jQuery.support.ownLast ) {
-			for ( key in obj ) {
-				return core_hasOwn.call( obj, key );
-			}
-		}
-
-		// Own properties are enumerated firstly, so to speed up,
-		// if last one is own, then all properties are own.
-		for ( key in obj ) {}
-
-		return key === undefined || core_hasOwn.call( obj, key );
-	},
-
-	isEmptyObject: function( obj ) {
-		var name;
-		for ( name in obj ) {
-			return false;
-		}
-		return true;
-	},
-
-	error: function( msg ) {
-		throw new Error( msg );
-	},
-
-	// data: string of html
-	// context (optional): If specified, the fragment will be created in this context, defaults to document
-	// keepScripts (optional): If true, will include scripts passed in the html string
-	parseHTML: function( data, context, keepScripts ) {
-		if ( !data || typeof data !== "string" ) {
-			return null;
-		}
-		if ( typeof context === "boolean" ) {
-			keepScripts = context;
-			context = false;
-		}
-		context = context || document;
-
-		var parsed = rsingleTag.exec( data ),
-			scripts = !keepScripts && [];
-
-		// Single tag
-		if ( parsed ) {
-			return [ context.createElement( parsed[1] ) ];
-		}
-
-		parsed = jQuery.buildFragment( [ data ], context, scripts );
-		if ( scripts ) {
-			jQuery( scripts ).remove();
-		}
-		return jQuery.merge( [], parsed.childNodes );
-	},
-
-	parseJSON: function( data ) {
-		// Attempt to parse using the native JSON parser first
-		if ( window.JSON && window.JSON.parse ) {
-			return window.JSON.parse( data );
-		}
-
-		if ( data === null ) {
-			return data;
-		}
-
-		if ( typeof data === "string" ) {
-
-			// Make sure leading/trailing whitespace is removed (IE can't handle it)
-			data = jQuery.trim( data );
-
-			if ( data ) {
-				// Make sure the incoming data is actual JSON
-				// Logic borrowed from http://json.org/json2.js
-				if ( rvalidchars.test( data.replace( rvalidescape, "@" )
-					.replace( rvalidtokens, "]" )
-					.replace( rvalidbraces, "")) ) {
-
-					return ( new Function( "return " + data ) )();
-				}
-			}
-		}
-
-		jQuery.error( "Invalid JSON: " + data );
-	},
-
-	// Cross-browser xml parsing
-	parseXML: function( data ) {
-		var xml, tmp;
-		if ( !data || typeof data !== "string" ) {
-			return null;
-		}
-		try {
-			if ( window.DOMParser ) { // Standard
-				tmp = new DOMParser();
-				xml = tmp.parseFromString( data , "text/xml" );
-			} else { // IE
-				xml = new ActiveXObject( "Microsoft.XMLDOM" );
-				xml.async = "false";
-				xml.loadXML( data );
-			}
-		} catch( e ) {
-			xml = undefined;
-		}
-		if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
-			jQuery.error( "Invalid XML: " + data );
-		}
-		return xml;
-	},
-
-	noop: function() {},
-
-	// Evaluates a script in a global context
-	// Workarounds based on findings by Jim Driscoll
-	// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
-	globalEval: function( data ) {
-		if ( data && jQuery.trim( data ) ) {
-			// We use execScript on Internet Explorer
-			// We use an anonymous function so that context is window
-			// rather than jQuery in Firefox
-			( window.execScript || function( data ) {
-				window[ "eval" ].call( window, data );
-			} )( data );
-		}
-	},
-
-	// Convert dashed to camelCase; used by the css and data modules
-	// Microsoft forgot to hump their vendor prefix (#9572)
-	camelCase: function( string ) {
-		return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
-	},
-
-	nodeName: function( elem, name ) {
-		return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
-	},
-
-	// args is for internal usage only
-	each: function( obj, callback, args ) {
-		var value,
-			i = 0,
-			length = obj.length,
-			isArray = isArraylike( obj );
-
-		if ( args ) {
-			if ( isArray ) {
-				for ( ; i < length; i++ ) {
-					value = callback.apply( obj[ i ], args );
-
-					if ( value === false ) {
-						break;
-					}
-				}
-			} else {
-				for ( i in obj ) {
-					value = callback.apply( obj[ i ], args );
-
-					if ( value === false ) {
-						break;
-					}
-				}
-			}
-
-		// A special, fast, case for the most common use of each
-		} else {
-			if ( isArray ) {
-				for ( ; i < length; i++ ) {
-					value = callback.call( obj[ i ], i, obj[ i ] );
-
-					if ( value === false ) {
-						break;
-					}
-				}
-			} else {
-				for ( i in obj ) {
-					value = callback.call( obj[ i ], i, obj[ i ] );
-
-					if ( value === false ) {
-						break;
-					}
-				}
-			}
-		}
-
-		return obj;
-	},
-
-	// Use native String.trim function wherever possible
-	trim: core_trim && !core_trim.call("\uFEFF\xA0") ?
-		function( text ) {
-			return text == null ?
-				"" :
-				core_trim.call( text );
-		} :
-
-		// Otherwise use our own trimming functionality
-		function( text ) {
-			return text == null ?
-				"" :
-				( text + "" ).replace( rtrim, "" );
-		},
-
-	// results is for internal usage only
-	makeArray: function( arr, results ) {
-		var ret = results || [];
-
-		if ( arr != null ) {
-			if ( isArraylike( Object(arr) ) ) {
-				jQuery.merge( ret,
-					typeof arr === "string" ?
-					[ arr ] : arr
-				);
-			} else {
-				core_push.call( ret, arr );
-			}
-		}
-
-		return ret;
-	},
-
-	inArray: function( elem, arr, i ) {
-		var len;
-
-		if ( arr ) {
-			if ( core_indexOf ) {
-				return core_indexOf.call( arr, elem, i );
-			}
-
-			len = arr.length;
-			i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
-
-			for ( ; i < len; i++ ) {
-				// Skip accessing in sparse arrays
-				if ( i in arr && arr[ i ] === elem ) {
-					return i;
-				}
-			}
-		}
-
-		return -1;
-	},
-
-	merge: function( first, second ) {
-		var l = second.length,
-			i = first.length,
-			j = 0;
-
-		if ( typeof l === "number" ) {
-			for ( ; j < l; j++ ) {
-				first[ i++ ] = second[ j ];
-			}
-		} else {
-			while ( second[j] !== undefined ) {
-				first[ i++ ] = second[ j++ ];
-			}
-		}
-
-		first.length = i;
-
-		return first;
-	},
-
-	grep: function( elems, callback, inv ) {
-		var retVal,
-			ret = [],
-			i = 0,
-			length = elems.length;
-		inv = !!inv;
-
-		// Go through the array, only saving the items
-		// that pass the validator function
-		for ( ; i < length; i++ ) {
-			retVal = !!callback( elems[ i ], i );
-			if ( inv !== retVal ) {
-				ret.push( elems[ i ] );
-			}
-		}
-
-		return ret;
-	},
-
-	// arg is for internal usage only
-	map: function( elems, callback, arg ) {
-		var value,
-			i = 0,
-			length = elems.length,
-			isArray = isArraylike( elems ),
-			ret = [];
-
-		// Go through the array, translating each of the items to their
-		if ( isArray ) {
-			for ( ; i < length; i++ ) {
-				value = callback( elems[ i ], i, arg );
-
-				if ( value != null ) {
-					ret[ ret.length ] = value;
-				}
-			}
-
-		// Go through every key on the object,
-		} else {
-			for ( i in elems ) {
-				value = callback( elems[ i ], i, arg );
-
-				if ( value != null ) {
-					ret[ ret.length ] = value;
-				}
-			}
-		}
-
-		// Flatten any nested arrays
-		return core_concat.apply( [], ret );
-	},
-
-	// A global GUID counter for objects
-	guid: 1,
-
-	// Bind a function to a context, optionally partially applying any
-	// arguments.
-	proxy: function( fn, context ) {
-		var args, proxy, tmp;
-
-		if ( typeof context === "string" ) {
-			tmp = fn[ context ];
-			context = fn;
-			fn = tmp;
-		}
-
-		// Quick check to determine if target is callable, in the spec
-		// this throws a TypeError, but we will just return undefined.
-		if ( !jQuery.isFunction( fn ) ) {
-			return undefined;
-		}
-
-		// Simulated bind
-		args = core_slice.call( arguments, 2 );
-		proxy = function() {
-			return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) );
-		};
-
-		// Set the guid of unique handler to the same of original handler, so it can be removed
-		proxy.guid = fn.guid = fn.guid || jQuery.guid++;
-
-		return proxy;
-	},
-
-	// Multifunctional method to get and set values of a collection
-	// The value/s can optionally be executed if it's a function
-	access: function( elems, fn, key, value, chainable, emptyGet, raw ) {
-		var i = 0,
-			length = elems.length,
-			bulk = key == null;
-
-		// Sets many values
-		if ( jQuery.type( key ) === "object" ) {
-			chainable = true;
-			for ( i in key ) {
-				jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
-			}
-
-		// Sets one value
-		} else if ( value !== undefined ) {
-			chainable = true;
-
-			if ( !jQuery.isFunction( value ) ) {
-				raw = true;
-			}
-
-			if ( bulk ) {
-				// Bulk operations run against the entire set
-				if ( raw ) {
-					fn.call( elems, value );
-					fn = null;
-
-				// ...except when executing function values
-				} else {
-					bulk = fn;
-					fn = function( elem, key, value ) {
-						return bulk.call( jQuery( elem ), value );
-					};
-				}
-			}
-
-			if ( fn ) {
-				for ( ; i < length; i++ ) {
-					fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
-				}
-			}
-		}
-
-		return chainable ?
-			elems :
-
-			// Gets
-			bulk ?
-				fn.call( elems ) :
-				length ? fn( elems[0], key ) : emptyGet;
-	},
-
-	now: function() {
-		return ( new Date() ).getTime();
-	},
-
-	// A method for quickly swapping in/out CSS properties to get correct calculations.
-	// Note: this method belongs to the css module but it's needed here for the support module.
-	// If support gets modularized, this method should be moved back to the css module.
-	swap: function( elem, options, callback, args ) {
-		var ret, name,
-			old = {};
-
-		// Remember the old values, and insert the new ones
-		for ( name in options ) {
-			old[ name ] = elem.style[ name ];
-			elem.style[ name ] = options[ name ];
-		}
-
-		ret = callback.apply( elem, args || [] );
-
-		// Revert the old values
-		for ( name in options ) {
-			elem.style[ name ] = old[ name ];
-		}
-
-		return ret;
-	}
-});
-
-jQuery.ready.promise = function( obj ) {
-	if ( !readyList ) {
-
-		readyList = jQuery.Deferred();
-
-		// Catch cases where $(document).ready() is called after the browser event has already occurred.
-		// we once tried to use readyState "interactive" here, but it caused issues like the one
-		// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
-		if ( document.readyState === "complete" ) {
-			// Handle it asynchronously to allow scripts the opportunity to delay ready
-			setTimeout( jQuery.ready );
-
-		// Standards-based browsers support DOMContentLoaded
-		} else if ( document.addEventListener ) {
-			// Use the handy event callback
-			document.addEventListener( "DOMContentLoaded", completed, false );
-
-			// A fallback to window.onload, that will always work
-			window.addEventListener( "load", completed, false );
-
-		// If IE event model is used
-		} else {
-			// Ensure firing before onload, maybe late but safe also for iframes
-			document.attachEvent( "onreadystatechange", completed );
-
-			// A fallback to window.onload, that will always work
-			window.attachEvent( "onload", completed );
-
-			// If IE and not a frame
-			// continually check to see if the document is ready
-			var top = false;
-
-			try {
-				top = window.frameElement == null && document.documentElement;
-			} catch(e) {}
-
-			if ( top && top.doScroll ) {
-				(function doScrollCheck() {
-					if ( !jQuery.isReady ) {
-
-						try {
-							// Use the trick by Diego Perini
-							// http://javascript.nwbox.com/IEContentLoaded/
-							top.doScroll("left");
-						} catch(e) {
-							return setTimeout( doScrollCheck, 50 );
-						}
-
-						// detach all dom ready events
-						detach();
-
-						// and execute any waiting functions
-						jQuery.ready();
-					}
-				})();
-			}
-		}
-	}
-	return readyList.promise( obj );
-};
-
-// Populate the class2type map
-jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
-	class2type[ "[object " + name + "]" ] = name.toLowerCase();
-});
-
-function isArraylike( obj ) {
-	var length = obj.length,
-		type = jQuery.type( obj );
-
-	if ( jQuery.isWindow( obj ) ) {
-		return false;
-	}
-
-	if ( obj.nodeType === 1 && length ) {
-		return true;
-	}
-
-	return type === "array" || type !== "function" &&
-		( length === 0 ||
-		typeof length === "number" && length > 0 && ( length - 1 ) in obj );
-}
-
-// All jQuery objects should point back to these
-rootjQuery = jQuery(document);
-/*!
- * Sizzle CSS Selector Engine v1.10.2
- * http://sizzlejs.com/
- *
- * Copyright 2013 jQuery Foundation, Inc. and other contributors
- * Released under the MIT license
- * http://jquery.org/license
- *
- * Date: 2013-07-03
- */
-(function( window, undefined ) {
-
-var i,
-	support,
-	cachedruns,
-	Expr,
-	getText,
-	isXML,
-	compile,
-	outermostContext,
-	sortInput,
-
-	// Local document vars
-	setDocument,
-	document,
-	docElem,
-	documentIsHTML,
-	rbuggyQSA,
-	rbuggyMatches,
-	matches,
-	contains,
-
-	// Instance-specific data
-	expando = "sizzle" + -(new Date()),
-	preferredDoc = window.document,
-	dirruns = 0,
-	done = 0,
-	classCache = createCache(),
-	tokenCache = createCache(),
-	compilerCache = createCache(),
-	hasDuplicate = false,
-	sortOrder = function( a, b ) {
-		if ( a === b ) {
-			hasDuplicate = true;
-			return 0;
-		}
-		return 0;
-	},
-
-	// General-purpose constants
-	strundefined = typeof undefined,
-	MAX_NEGATIVE = 1 << 31,
-
-	// Instance methods
-	hasOwn = ({}).hasOwnProperty,
-	arr = [],
-	pop = arr.pop,
-	push_native = arr.push,
-	push = arr.push,
-	slice = arr.slice,
-	// Use a stripped-down indexOf if we can't use a native one
-	indexOf = arr.indexOf || function( elem ) {
-		var i = 0,
-			len = this.length;
-		for ( ; i < len; i++ ) {
-			if ( this[i] === elem ) {
-				return i;
-			}
-		}
-		return -1;
-	},
-
-	booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
-
-	// Regular expressions
-
-	// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
-	whitespace = "[\\x20\\t\\r\\n\\f]",
-	// http://www.w3.org/TR/css3-syntax/#characters
-	characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
-
-	// Loosely modeled on CSS identifier characters
-	// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
-	// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
-	identifier = characterEncoding.replace( "w", "w#" ),
-
-	// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
-	attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
-		"*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
-
-	// Prefer arguments quoted,
-	//   then not containing pseudos/brackets,
-	//   then attribute selectors/non-parenthetical expressions,
-	//   then anything else
-	// These preferences are here to reduce the number of selectors
-	//   needing tokenize in the PSEUDO preFilter
-	pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)",
-
-	// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
-	rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
-
-	rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
-	rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
-
-	rsibling = new RegExp( whitespace + "*[+~]" ),
-	rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*)" + whitespace + "*\\]", "g" ),
-
-	rpseudo = new RegExp( pseudos ),
-	ridentifier = new RegExp( "^" + identifier + "$" ),
-
-	matchExpr = {
-		"ID": new RegExp( "^#(" + characterEncoding + ")" ),
-		"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
-		"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
-		"ATTR": new RegExp( "^" + attributes ),
-		"PSEUDO": new RegExp( "^" + pseudos ),
-		"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
-			"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
-			"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
-		"bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
-		// For use in libraries implementing .is()
-		// We use this for POS matching in `select`
-		"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
-			whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
-	},
-
-	rnative = /^[^{]+\{\s*\[native \w/,
-
-	// Easily-parseable/retrievable ID or TAG or CLASS selectors
-	rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
-
-	rinputs = /^(?:input|select|textarea|button)$/i,
-	rheader = /^h\d$/i,
-
-	rescape = /'|\\/g,
-
-	// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
-	runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
-	funescape = function( _, escaped, escapedWhitespace ) {
-		var high = "0x" + escaped - 0x10000;
-		// NaN means non-codepoint
-		// Support: Firefox
-		// Workaround erroneous numeric interpretation of +"0x"
-		return high !== high || escapedWhitespace ?
-			escaped :
-			// BMP codepoint
-			high < 0 ?
-				String.fromCharCode( high + 0x10000 ) :
-				// Supplemental Plane codepoint (surrogate pair)
-				String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
-	};
-
-// Optimize for push.apply( _, NodeList )
-try {
-	push.apply(
-		(arr = slice.call( preferredDoc.childNodes )),
-		preferredDoc.childNodes
-	);
-	// Support: Android<4.0
-	// Detect silently failing push.apply
-	arr[ preferredDoc.childNodes.length ].nodeType;
-} catch ( e ) {
-	push = { apply: arr.length ?
-
-		// Leverage slice if possible
-		function( target, els ) {
-			push_native.apply( target, slice.call(els) );
-		} :
-
-		// Support: IE<9
-		// Otherwise append directly
-		function( target, els ) {
-			var j = target.length,
-				i = 0;
-			// Can't trust NodeList.length
-			while ( (target[j++] = els[i++]) ) {}
-			target.length = j - 1;
-		}
-	};
-}
-
-function Sizzle( selector, context, results, seed ) {
-	var match, elem, m, nodeType,
-		// QSA vars
-		i, groups, old, nid, newContext, newSelector;
-
-	if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
-		setDocument( context );
-	}
-
-	context = context || document;
-	results = results || [];
-
-	if ( !selector || typeof selector !== "string" ) {
-		return results;
-	}
-
-	if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
-		return [];
-	}
-
-	if ( documentIsHTML && !seed ) {
-
-		// Shortcuts
-		if ( (match = rquickExpr.exec( selector )) ) {
-			// Speed-up: Sizzle("#ID")
-			if ( (m = match[1]) ) {
-				if ( nodeType === 9 ) {
-					elem = context.getElementById( m );
-					// Check parentNode to catch when Blackberry 4.6 returns
-					// nodes that are no longer in the document #6963
-					if ( elem && elem.parentNode ) {
-						// Handle the case where IE, Opera, and Webkit return items
-						// by name instead of ID
-						if ( elem.id === m ) {
-							results.push( elem );
-							return results;
-						}
-					} else {
-						return results;
-					}
-				} else {
-					// Context is not a document
-					if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
-						contains( context, elem ) && elem.id === m ) {
-						results.push( elem );
-						return results;
-					}
-				}
-
-			// Speed-up: Sizzle("TAG")
-			} else if ( match[2] ) {
-				push.apply( results, context.getElementsByTagName( selector ) );
-				return results;
-
-			// Speed-up: Sizzle(".CLASS")
-			} else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) {
-				push.apply( results, context.getElementsByClassName( m ) );
-				return results;
-			}
-		}
-
-		// QSA path
-		if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
-			nid = old = expando;
-			newContext = context;
-			newSelector = nodeType === 9 && selector;
-
-			// qSA works strangely on Element-rooted queries
-			// We can work around this by specifying an extra ID on the root
-			// and working up from there (Thanks to Andrew Dupont for the technique)
-			// IE 8 doesn't work on object elements
-			if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
-				groups = tokenize( selector );
-
-				if ( (old = context.getAttribute("id")) ) {
-					nid = old.replace( rescape, "\\$&" );
-				} else {
-					context.setAttribute( "id", nid );
-				}
-				nid = "[id='" + nid + "'] ";
-
-				i = groups.length;
-				while ( i-- ) {
-					groups[i] = nid + toSelector( groups[i] );
-				}
-				newContext = rsibling.test( selector ) && context.parentNode || context;
-				newSelector = groups.join(",");
-			}
-
-			if ( newSelector ) {
-				try {
-					push.apply( results,
-						newContext.querySelectorAll( newSelector )
-					);
-					return results;
-				} catch(qsaError) {
-				} finally {
-					if ( !old ) {
-						context.removeAttribute("id");
-					}
-				}
-			}
-		}
-	}
-
-	// All others
-	return select( selector.replace( rtrim, "$1" ), context, results, seed );
-}
-
-/**
- * Create key-value caches of limited size
- * @returns {Function(string, Object)} Returns the Object data after storing it on itself with
- *	property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
- *	deleting the oldest entry
- */
-function createCache() {
-	var keys = [];
-
-	function cache( key, value ) {
-		// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
-		if ( keys.push( key += " " ) > Expr.cacheLength ) {
-			// Only keep the most recent entries
-			delete cache[ keys.shift() ];
-		}
-		return (cache[ key ] = value);
-	}
-	return cache;
-}
-
-/**
- * Mark a function for special use by Sizzle
- * @param {Function} fn The function to mark
- */
-function markFunction( fn ) {
-	fn[ expando ] = true;
-	return fn;
-}
-
-/**
- * Support testing using an element
- * @param {Function} fn Passed the created div and expects a boolean result
- */
-function assert( fn ) {
-	var div = document.createElement("div");
-
-	try {
-		return !!fn( div );
-	} catch (e) {
-		return false;
-	} finally {
-		// Remove from its parent by default
-		if ( div.parentNode ) {
-			div.parentNode.removeChild( div );
-		}
-		// release memory in IE
-		div = null;
-	}
-}
-
-/**
- * Adds the same handler for all of the specified attrs
- * @param {String} attrs Pipe-separated list of attributes
- * @param {Function} handler The method that will be applied
- */
-function addHandle( attrs, handler ) {
-	var arr = attrs.split("|"),
-		i = attrs.length;
-
-	while ( i-- ) {
-		Expr.attrHandle[ arr[i] ] = handler;
-	}
-}
-
-/**
- * Checks document order of two siblings
- * @param {Element} a
- * @param {Element} b
- * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
- */
-function siblingCheck( a, b ) {
-	var cur = b && a,
-		diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
-			( ~b.sourceIndex || MAX_NEGATIVE ) -
-			( ~a.sourceIndex || MAX_NEGATIVE );
-
-	// Use IE sourceIndex if available on both nodes
-	if ( diff ) {
-		return diff;
-	}
-
-	// Check if b follows a
-	if ( cur ) {
-		while ( (cur = cur.nextSibling) ) {
-			if ( cur === b ) {
-				return -1;
-			}
-		}
-	}
-
-	return a ? 1 : -1;
-}
-
-/**
- * Returns a function to use in pseudos for input types
- * @param {String} type
- */
-function createInputPseudo( type ) {
-	return function( elem ) {
-		var name = elem.nodeName.toLowerCase();
-		return name === "input" && elem.type === type;
-	};
-}
-
-/**
- * Returns a function to use in pseudos for buttons
- * @param {String} type
- */
-function createButtonPseudo( type ) {
-	return function( elem ) {
-		var name = elem.nodeName.toLowerCase();
-		return (name === "input" || name === "button") && elem.type === type;
-	};
-}
-
-/**
- * Returns a function to use in pseudos for positionals
- * @param {Function} fn
- */
-function createPositionalPseudo( fn ) {
-	return markFunction(function( argument ) {
-		argument = +argument;
-		return markFunction(function( seed, matches ) {
-			var j,
-				matchIndexes = fn( [], seed.length, argument ),
-				i = matchIndexes.length;
-
-			// Match elements found at the specified indexes
-			while ( i-- ) {
-				if ( seed[ (j = matchIndexes[i]) ] ) {
-					seed[j] = !(matches[j] = seed[j]);
-				}
-			}
-		});
-	});
-}
-
-/**
- * Detect xml
- * @param {Element|Object} elem An element or a document
- */
-isXML = Sizzle.isXML = function( elem ) {
-	// documentElement is verified for cases where it doesn't yet exist
-	// (such as loading iframes in IE - #4833)
-	var documentElement = elem && (elem.ownerDocument || elem).documentElement;
-	return documentElement ? documentElement.nodeName !== "HTML" : false;
-};
-
-// Expose support vars for convenience
-support = Sizzle.support = {};
-
-/**
- * Sets document-related variables once based on the current document
- * @param {Element|Object} [doc] An element or document object to use to set the document
- * @returns {Object} Returns the current document
- */
-setDocument = Sizzle.setDocument = function( node ) {
-	var doc = node ? node.ownerDocument || node : preferredDoc,
-		parent = doc.defaultView;
-
-	// If no document and documentElement is available, return
-	if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
-		return document;
-	}
-
-	// Set our document
-	document = doc;
-	docElem = doc.documentElement;
-
-	// Support tests
-	documentIsHTML = !isXML( doc );
-
-	// Support: IE>8
-	// If iframe document is assigned to "document" variable and if iframe has been reloaded,
-	// IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936
-	// IE6-8 do not support the defaultView property so parent will be undefined
-	if ( parent && parent.attachEvent && parent !== parent.top ) {
-		parent.attachEvent( "onbeforeunload", function() {
-			setDocument();
-		});
-	}
-
-	/* Attributes
-	---------------------------------------------------------------------- */
-
-	// Support: IE<8
-	// Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans)
-	support.attributes = assert(function( div ) {
-		div.className = "i";
-		return !div.getAttribute("className");
-	});
-
-	/* getElement(s)By*
-	---------------------------------------------------------------------- */
-
-	// Check if getElementsByTagName("*") returns only elements
-	support.getElementsByTagName = assert(function( div ) {
-		div.appendChild( doc.createComment("") );
-		return !div.getElementsByTagName("*").length;
-	});
-
-	// Check if getElementsByClassName can be trusted
-	support.getElementsByClassName = assert(function( div ) {
-		div.innerHTML = "<div class='a'></div><div class='a i'></div>";
-
-		// Support: Safari<4
-		// Catch class over-caching
-		div.firstChild.className = "i";
-		// Support: Opera<10
-		// Catch gEBCN failure to find non-leading classes
-		return div.getElementsByClassName("i").length === 2;
-	});
-
-	// Support: IE<10
-	// Check if getElementById returns elements by name
-	// The broken getElementById methods don't pick up programatically-set names,
-	// so use a roundabout getElementsByName test
-	support.getById = assert(function( div ) {
-		docElem.appendChild( div ).id = expando;
-		return !doc.getElementsByName || !doc.getElementsByName( expando ).length;
-	});
-
-	// ID find and filter
-	if ( support.getById ) {
-		Expr.find["ID"] = function( id, context ) {
-			if ( typeof context.getElementById !== strundefined && documentIsHTML ) {
-				var m = context.getElementById( id );
-				// Check parentNode to catch when Blackberry 4.6 returns
-				// nodes that are no longer in the document #6963
-				return m && m.parentNode ? [m] : [];
-			}
-		};
-		Expr.filter["ID"] = function( id ) {
-			var attrId = id.replace( runescape, funescape );
-			return function( elem ) {
-				return elem.getAttribute("id") === attrId;
-			};
-		};
-	} else {
-		// Support: IE6/7
-		// getElementById is not reliable as a find shortcut
-		delete Expr.find["ID"];
-
-		Expr.filter["ID"] =  function( id ) {
-			var attrId = id.replace( runescape, funescape );
-			return function( elem ) {
-				var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
-				return node && node.value === attrId;
-			};
-		};
-	}
-
-	// Tag
-	Expr.find["TAG"] = support.getElementsByTagName ?
-		function( tag, context ) {
-			if ( typeof context.getElementsByTagName !== strundefined ) {
-				return context.getElementsByTagName( tag );
-			}
-		} :
-		function( tag, context ) {
-			var elem,
-				tmp = [],
-				i = 0,
-				results = context.getElementsByTagName( tag );
-
-			// Filter out possible comments
-			if ( tag === "*" ) {
-				while ( (elem = results[i++]) ) {
-					if ( elem.nodeType === 1 ) {
-						tmp.push( elem );
-					}
-				}
-
-				return tmp;
-			}
-			return results;
-		};
-
-	// Class
-	Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
-		if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) {
-			return context.getElementsByClassName( className );
-		}
-	};
-
-	/* QSA/matchesSelector
-	---------------------------------------------------------------------- */
-
-	// QSA and matchesSelector support
-
-	// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
-	rbuggyMatches = [];
-
-	// qSa(:focus) reports false when true (Chrome 21)
-	// We allow this because of a bug in IE8/9 that throws an error
-	// whenever `document.activeElement` is accessed on an iframe
-	// So, we allow :focus to pass through QSA all the time to avoid the IE error
-	// See http://bugs.jquery.com/ticket/13378
-	rbuggyQSA = [];
-
-	if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) {
-		// Build QSA regex
-		// Regex strategy adopted from Diego Perini
-		assert(function( div ) {
-			// Select is set to empty string on purpose
-			// This is to test IE's treatment of not explicitly
-			// setting a boolean content attribute,
-			// since its presence should be enough
-			// http://bugs.jquery.com/ticket/12359
-			div.innerHTML = "<select><option selected=''></option></select>";
-
-			// Support: IE8
-			// Boolean attributes and "value" are not treated correctly
-			if ( !div.querySelectorAll("[selected]").length ) {
-				rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
-			}
-
-			// Webkit/Opera - :checked should return selected option elements
-			// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
-			// IE8 throws error here and will not see later tests
-			if ( !div.querySelectorAll(":checked").length ) {
-				rbuggyQSA.push(":checked");
-			}
-		});
-
-		assert(function( div ) {
-
-			// Support: Opera 10-12/IE8
-			// ^= $= *= and empty values
-			// Should not select anything
-			// Support: Windows 8 Native Apps
-			// The type attribute is restricted during .innerHTML assignment
-			var input = doc.createElement("input");
-			input.setAttribute( "type", "hidden" );
-			div.appendChild( input ).setAttribute( "t", "" );
-
-			if ( div.querySelectorAll("[t^='']").length ) {
-				rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
-			}
-
-			// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
-			// IE8 throws error here and will not see later tests
-			if ( !div.querySelectorAll(":enabled").length ) {
-				rbuggyQSA.push( ":enabled", ":disabled" );
-			}
-
-			// Opera 10-11 does not throw on post-comma invalid pseudos
-			div.querySelectorAll("*,:x");
-			rbuggyQSA.push(",.*:");
-		});
-	}
-
-	if ( (support.matchesSelector = rnative.test( (matches = docElem.webkitMatchesSelector ||
-		docElem.mozMatchesSelector ||
-		docElem.oMatchesSelector ||
-		docElem.msMatchesSelector) )) ) {
-
-		assert(function( div ) {
-			// Check to see if it's possible to do matchesSelector
-			// on a disconnected node (IE 9)
-			support.disconnectedMatch = matches.call( div, "div" );
-
-			// This should fail with an exception
-			// Gecko does not error, returns false instead
-			matches.call( div, "[s!='']:x" );
-			rbuggyMatches.push( "!=", pseudos );
-		});
-	}
-
-	rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
-	rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );
-
-	/* Contains
-	---------------------------------------------------------------------- */
-
-	// Element contains another
-	// Purposefully does not implement inclusive descendent
-	// As in, an element does not contain itself
-	contains = rnative.test( docElem.contains ) || docElem.compareDocumentPosition ?
-		function( a, b ) {
-			var adown = a.nodeType === 9 ? a.documentElement : a,
-				bup = b && b.parentNode;
-			return a === bup || !!( bup && bup.nodeType === 1 && (
-				adown.contains ?
-					adown.contains( bup ) :
-					a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
-			));
-		} :
-		function( a, b ) {
-			if ( b ) {
-				while ( (b = b.parentNode) ) {
-					if ( b === a ) {
-						return true;
-					}
-				}
-			}
-			return false;
-		};
-
-	/* Sorting
-	---------------------------------------------------------------------- */
-
-	// Document order sorting
-	sortOrder = docElem.compareDocumentPosition ?
-	function( a, b ) {
-
-		// Flag for duplicate removal
-		if ( a === b ) {
-			hasDuplicate = true;
-			return 0;
-		}
-
-		var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b );
-
-		if ( compare ) {
-			// Disconnected nodes
-			if ( compare & 1 ||
-				(!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
-
-				// Choose the first element that is related to our preferred document
-				if ( a === doc || contains(preferredDoc, a) ) {
-					return -1;
-				}
-				if ( b === doc || contains(preferredDoc, b) ) {
-					return 1;
-				}
-
-				// Maintain original order
-				return sortInput ?
-					( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
-					0;
-			}
-
-			return compare & 4 ? -1 : 1;
-		}
-
-		// Not directly comparable, sort on existence of method
-		return a.compareDocumentPosition ? -1 : 1;
-	} :
-	function( a, b ) {
-		var cur,
-			i = 0,
-			aup = a.parentNode,
-			bup = b.parentNode,
-			ap = [ a ],
-			bp = [ b ];
-
-		// Exit early if the nodes are identical
-		if ( a === b ) {
-			hasDuplicate = true;
-			return 0;
-
-		// Parentless nodes are either documents or disconnected
-		} else if ( !aup || !bup ) {
-			return a === doc ? -1 :
-				b === doc ? 1 :
-				aup ? -1 :
-				bup ? 1 :
-				sortInput ?
-				( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
-				0;
-
-		// If the nodes are siblings, we can do a quick check
-		} else if ( aup === bup ) {
-			return siblingCheck( a, b );
-		}
-
-		// Otherwise we need full lists of their ancestors for comparison
-		cur = a;
-		while ( (cur = cur.parentNode) ) {
-			ap.unshift( cur );
-		}
-		cur = b;
-		while ( (cur = cur.parentNode) ) {
-			bp.unshift( cur );
-		}
-
-		// Walk down the tree looking for a discrepancy
-		while ( ap[i] === bp[i] ) {
-			i++;
-		}
-
-		return i ?
-			// Do a sibling check if the nodes have a common ancestor
-			siblingCheck( ap[i], bp[i] ) :
-
-			// Otherwise nodes in our document sort first
-			ap[i] === preferredDoc ? -1 :
-			bp[i] === preferredDoc ? 1 :
-			0;
-	};
-
-	return doc;
-};
-
-Sizzle.matches = function( expr, elements ) {
-	return Sizzle( expr, null, null, elements );
-};
-
-Sizzle.matchesSelector = function( elem, expr ) {
-	// Set document vars if needed
-	if ( ( elem.ownerDocument || elem ) !== document ) {
-		setDocument( elem );
-	}
-
-	// Make sure that attribute selectors are quoted
-	expr = expr.replace( rattributeQuotes, "='$1']" );
-
-	if ( support.matchesSelector && documentIsHTML &&
-		( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
-		( !rbuggyQSA     || !rbuggyQSA.test( expr ) ) ) {
-
-		try {
-			var ret = matches.call( elem, expr );
-
-			// IE 9's matchesSelector returns false on disconnected nodes
-			if ( ret || support.disconnectedMatch ||
-					// As well, disconnected nodes are said to be in a document
-					// fragment in IE 9
-					elem.document && elem.document.nodeType !== 11 ) {
-				return ret;
-			}
-		} catch(e) {}
-	}
-
-	return Sizzle( expr, document, null, [elem] ).length > 0;
-};
-
-Sizzle.contains = function( context, elem ) {
-	// Set document vars if needed
-	if ( ( context.ownerDocument || context ) !== document ) {
-		setDocument( context );
-	}
-	return contains( context, elem );
-};
-
-Sizzle.attr = function( elem, name ) {
-	// Set document vars if needed
-	if ( ( elem.ownerDocument || elem ) !== document ) {
-		setDocument( elem );
-	}
-
-	var fn = Expr.attrHandle[ name.toLowerCase() ],
-		// Don't get fooled by Object.prototype properties (jQuery #13807)
-		val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
-			fn( elem, name, !documentIsHTML ) :
-			undefined;
-
-	return val === undefined ?
-		support.attributes || !documentIsHTML ?
-			elem.getAttribute( name ) :
-			(val = elem.getAttributeNode(name)) && val.specified ?
-				val.value :
-				null :
-		val;
-};
-
-Sizzle.error = function( msg ) {
-	throw new Error( "Syntax error, unrecognized expression: " + msg );
-};
-
-/**
- * Document sorting and removing duplicates
- * @param {ArrayLike} results
- */
-Sizzle.uniqueSort = function( results ) {
-	var elem,
-		duplicates = [],
-		j = 0,
-		i = 0;
-
-	// Unless we *know* we can detect duplicates, assume their presence
-	hasDuplicate = !support.detectDuplicates;
-	sortInput = !support.sortStable && results.slice( 0 );
-	results.sort( sortOrder );
-
-	if ( hasDuplicate ) {
-		while ( (elem = results[i++]) ) {
-			if ( elem === results[ i ] ) {
-				j = duplicates.push( i );
-			}
-		}
-		while ( j-- ) {
-			results.splice( duplicates[ j ], 1 );
-		}
-	}
-
-	return results;
-};
-
-/**
- * Utility function for retrieving the text value of an array of DOM nodes
- * @param {Array|Element} elem
- */
-getText = Sizzle.getText = function( elem ) {
-	var node,
-		ret = "",
-		i = 0,
-		nodeType = elem.nodeType;
-
-	if ( !nodeType ) {
-		// If no nodeType, this is expected to be an array
-		for ( ; (node = elem[i]); i++ ) {
-			// Do not traverse comment nodes
-			ret += getText( node );
-		}
-	} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
-		// Use textContent for elements
-		// innerText usage removed for consistency of new lines (see #11153)
-		if ( typeof elem.textContent === "string" ) {
-			return elem.textContent;
-		} else {
-			// Traverse its children
-			for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
-				ret += getText( elem );
-			}
-		}
-	} else if ( nodeType === 3 || nodeType === 4 ) {
-		return elem.nodeValue;
-	}
-	// Do not include comment or processing instruction nodes
-
-	return ret;
-};
-
-Expr = Sizzle.selectors = {
-
-	// Can be adjusted by the user
-	cacheLength: 50,
-
-	createPseudo: markFunction,
-
-	match: matchExpr,
-
-	attrHandle: {},
-
-	find: {},
-
-	relative: {
-		">": { dir: "parentNode", first: true },
-		" ": { dir: "parentNode" },
-		"+": { dir: "previousSibling", first: true },
-		"~": { dir: "previousSibling" }
-	},
-
-	preFilter: {
-		"ATTR": function( match ) {
-			match[1] = match[1].replace( runescape, funescape );
-
-			// Move the given value to match[3] whether quoted or unquoted
-			match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape );
-
-			if ( match[2] === "~=" ) {
-				match[3] = " " + match[3] + " ";
-			}
-
-			return match.slice( 0, 4 );
-		},
-
-		"CHILD": function( match ) {
-			/* matches from matchExpr["CHILD"]
-				1 type (only|nth|...)
-				2 what (child|of-type)
-				3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
-				4 xn-component of xn+y argument ([+-]?\d*n|)
-				5 sign of xn-component
-				6 x of xn-component
-				7 sign of y-component
-				8 y of y-component
-			*/
-			match[1] = match[1].toLowerCase();
-
-			if ( match[1].slice( 0, 3 ) === "nth" ) {
-				// nth-* requires argument
-				if ( !match[3] ) {
-					Sizzle.error( match[0] );
-				}
-
-				// numeric x and y parameters for Expr.filter.CHILD
-				// remember that false/true cast respectively to 0/1
-				match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
-				match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
-
-			// other types prohibit arguments
-			} else if ( match[3] ) {
-				Sizzle.error( match[0] );
-			}
-
-			return match;
-		},
-
-		"PSEUDO": function( match ) {
-			var excess,
-				unquoted = !match[5] && match[2];
-
-			if ( matchExpr["CHILD"].test( match[0] ) ) {
-				return null;
-			}
-
-			// Accept quoted arguments as-is
-			if ( match[3] && match[4] !== undefined ) {
-				match[2] = match[4];
-
-			// Strip excess characters from unquoted arguments
-			} else if ( unquoted && rpseudo.test( unquoted ) &&
-				// Get excess from tokenize (recursively)
-				(excess = tokenize( unquoted, true )) &&
-				// advance to the next closing parenthesis
-				(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
-
-				// excess is a negative index
-				match[0] = match[0].slice( 0, excess );
-				match[2] = unquoted.slice( 0, excess );
-			}
-
-			// Return only captures needed by the pseudo filter method (type and argument)
-			return match.slice( 0, 3 );
-		}
-	},
-
-	filter: {
-
-		"TAG": function( nodeNameSelector ) {
-			var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
-			return nodeNameSelector === "*" ?
-				function() { return true; } :
-				function( elem ) {
-					return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
-				};
-		},
-
-		"CLASS": function( className ) {
-			var pattern = classCache[ className + " " ];
-
-			return pattern ||
-				(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
-				classCache( className, function( elem ) {
-					return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" );
-				});
-		},
-
-		"ATTR": function( name, operator, check ) {
-			return function( elem ) {
-				var result = Sizzle.attr( elem, name );
-
-				if ( result == null ) {
-					return operator === "!=";
-				}
-				if ( !operator ) {
-					return true;
-				}
-
-				result += "";
-
-				return operator === "=" ? result === check :
-					operator === "!=" ? result !== check :
-					operator === "^=" ? check && result.indexOf( check ) === 0 :
-					operator === "*=" ? check && result.indexOf( check ) > -1 :
-					operator === "$=" ? check && result.slice( -check.length ) === check :
-					operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
-					operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
-					false;
-			};
-		},
-
-		"CHILD": function( type, what, argument, first, last ) {
-			var simple = type.slice( 0, 3 ) !== "nth",
-				forward = type.slice( -4 ) !== "last",
-				ofType = what === "of-type";
-
-			return first === 1 && last === 0 ?
-
-				// Shortcut for :nth-*(n)
-				function( elem ) {
-					return !!elem.parentNode;
-				} :
-
-				function( elem, context, xml ) {
-					var cache, outerCache, node, diff, nodeIndex, start,
-						dir = simple !== forward ? "nextSibling" : "previousSibling",
-						parent = elem.parentNode,
-						name = ofType && elem.nodeName.toLowerCase(),
-						useCache = !xml && !ofType;
-
-					if ( parent ) {
-
-						// :(first|last|only)-(child|of-type)
-						if ( simple ) {
-							while ( dir ) {
-								node = elem;
-								while ( (node = node[ dir ]) ) {
-									if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) {
-										return false;
-									}
-								}
-								// Reverse direction for :only-* (if we haven't yet done so)
-								start = dir = type === "only" && !start && "nextSibling";
-							}
-							return true;
-						}
-
-						start = [ forward ? parent.firstChild : parent.lastChild ];
-
-						// non-xml :nth-child(...) stores cache data on `parent`
-						if ( forward && useCache ) {
-							// Seek `elem` from a previously-cached index
-							outerCache = parent[ expando ] || (parent[ expando ] = {});
-							cache = outerCache[ type ] || [];
-							nodeIndex = cache[0] === dirruns && cache[1];
-							diff = cache[0] === dirruns && cache[2];
-							node = nodeIndex && parent.childNodes[ nodeIndex ];
-
-							while ( (node = ++nodeIndex && node && node[ dir ] ||
-
-								// Fallback to seeking `elem` from the start
-								(diff = nodeIndex = 0) || start.pop()) ) {
-
-								// When found, cache indexes on `parent` and break
-								if ( node.nodeType === 1 && ++diff && node === elem ) {
-									outerCache[ type ] = [ dirruns, nodeIndex, diff ];
-									break;
-								}
-							}
-
-						// Use previously-cached element index if available
-						} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
-							diff = cache[1];
-
-						// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
-						} else {
-							// Use the same loop as above to seek `elem` from the start
-							while ( (node = ++nodeIndex && node && node[ dir ] ||
-								(diff = nodeIndex = 0) || start.pop()) ) {
-
-								if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) {
-									// Cache the index of each encountered element
-									if ( useCache ) {
-										(node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ];
-									}
-
-									if ( node === elem ) {
-										break;
-									}
-								}
-							}
-						}
-
-						// Incorporate the offset, then check against cycle size
-						diff -= last;
-						return diff === first || ( diff % first === 0 && diff / first >= 0 );
-					}
-				};
-		},
-
-		"PSEUDO": function( pseudo, argument ) {
-			// pseudo-class names are case-insensitive
-			// http://www.w3.org/TR/selectors/#pseudo-classes
-			// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
-			// Remember that setFilters inherits from pseudos
-			var args,
-				fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
-					Sizzle.error( "unsupported pseudo: " + pseudo );
-
-			// The user may use createPseudo to indicate that
-			// arguments are needed to create the filter function
-			// just as Sizzle does
-			if ( fn[ expando ] ) {
-				return fn( argument );
-			}
-
-			// But maintain support for old signatures
-			if ( fn.length > 1 ) {
-				args = [ pseudo, pseudo, "", argument ];
-				return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
-					markFunction(function( seed, matches ) {
-						var idx,
-							matched = fn( seed, argument ),
-							i = matched.length;
-						while ( i-- ) {
-							idx = indexOf.call( seed, matched[i] );
-							seed[ idx ] = !( matches[ idx ] = matched[i] );
-						}
-					}) :
-					function( elem ) {
-						return fn( elem, 0, args );
-					};
-			}
-
-			return fn;
-		}
-	},
-
-	pseudos: {
-		// Potentially complex pseudos
-		"not": markFunction(function( selector ) {
-			// Trim the selector passed to compile
-			// to avoid treating leading and trailing
-			// spaces as combinators
-			var input = [],
-				results = [],
-				matcher = compile( selector.replace( rtrim, "$1" ) );
-
-			return matcher[ expando ] ?
-				markFunction(function( seed, matches, context, xml ) {
-					var elem,
-						unmatched = matcher( seed, null, xml, [] ),
-						i = seed.length;
-
-					// Match elements unmatched by `matcher`
-					while ( i-- ) {
-						if ( (elem = unmatched[i]) ) {
-							seed[i] = !(matches[i] = elem);
-						}
-					}
-				}) :
-				function( elem, context, xml ) {
-					input[0] = elem;
-					matcher( input, null, xml, results );
-					return !results.pop();
-				};
-		}),
-
-		"has": markFunction(function( selector ) {
-			return function( elem ) {
-				return Sizzle( selector, elem ).length > 0;
-			};
-		}),
-
-		"contains": markFunction(function( text ) {
-			return function( elem ) {
-				return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
-			};
-		}),
-
-		// "Whether an element is represented by a :lang() selector
-		// is based solely on the element's language value
-		// being equal to the identifier C,
-		// or beginning with the identifier C immediately followed by "-".
-		// The matching of C against the element's language value is performed case-insensitively.
-		// The identifier C does not have to be a valid language name."
-		// http://www.w3.org/TR/selectors/#lang-pseudo
-		"lang": markFunction( function( lang ) {
-			// lang value must be a valid identifier
-			if ( !ridentifier.test(lang || "") ) {
-				Sizzle.error( "unsupported lang: " + lang );
-			}
-			lang = lang.replace( runescape, funescape ).toLowerCase();
-			return function( elem ) {
-				var elemLang;
-				do {
-					if ( (elemLang = documentIsHTML ?
-						elem.lang :
-						elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
-
-						elemLang = elemLang.toLowerCase();
-						return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
-					}
-				} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
-				return false;
-			};
-		}),
-
-		// Miscellaneous
-		"target": function( elem ) {
-			var hash = window.location && window.location.hash;
-			return hash && hash.slice( 1 ) === elem.id;
-		},
-
-		"root": function( elem ) {
-			return elem === docElem;
-		},
-
-		"focus": function( elem ) {
-			return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
-		},
-
-		// Boolean properties
-		"enabled": function( elem ) {
-			return elem.disabled === false;
-		},
-
-		"disabled": function( elem ) {
-			return elem.disabled === true;
-		},
-
-		"checked": function( elem ) {
-			// In CSS3, :checked should return both checked and selected elements
-			// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
-			var nodeName = elem.nodeName.toLowerCase();
-			return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
-		},
-
-		"selected": function( elem ) {
-			// Accessing this property makes selected-by-default
-			// options in Safari work properly
-			if ( elem.parentNode ) {
-				elem.parentNode.selectedIndex;
-			}
-
-			return elem.selected === true;
-		},
-
-		// Contents
-		"empty": function( elem ) {
-			// http://www.w3.org/TR/selectors/#empty-pseudo
-			// :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
-			//   not comment, processing instructions, or others
-			// Thanks to Diego Perini for the nodeName shortcut
-			//   Greater than "@" means alpha characters (specifically not starting with "#" or "?")
-			for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
-				if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) {
-					return false;
-				}
-			}
-			return true;
-		},
-
-		"parent": function( elem ) {
-			return !Expr.pseudos["empty"]( elem );
-		},
-
-		// Element/input types
-		"header": function( elem ) {
-			return rheader.test( elem.nodeName );
-		},
-
-		"input": function( elem ) {
-			return rinputs.test( elem.nodeName );
-		},
-
-		"button": function( elem ) {
-			var name = elem.nodeName.toLowerCase();
-			return name === "input" && elem.type === "button" || name === "button";
-		},
-
-		"text": function( elem ) {
-			var attr;
-			// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
-			// use getAttribute instead to test this case
-			return elem.nodeName.toLowerCase() === "input" &&
-				elem.type === "text" &&
-				( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type );
-		},
-
-		// Position-in-collection
-		"first": createPositionalPseudo(function() {
-			return [ 0 ];
-		}),
-
-		"last": createPositionalPseudo(function( matchIndexes, length ) {
-			return [ length - 1 ];
-		}),
-
-		"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
-			return [ argument < 0 ? argument + length : argument ];
-		}),
-
-		"even": createPositionalPseudo(function( matchIndexes, length ) {
-			var i = 0;
-			for ( ; i < length; i += 2 ) {
-				matchIndexes.push( i );
-			}
-			return matchIndexes;
-		}),
-
-		"odd": createPositionalPseudo(function( matchIndexes, length ) {
-			var i = 1;
-			for ( ; i < length; i += 2 ) {
-				matchIndexes.push( i );
-			}
-			return matchIndexes;
-		}),
-
-		"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
-			var i = argument < 0 ? argument + length : argument;
-			for ( ; --i >= 0; ) {
-				matchIndexes.push( i );
-			}
-			return matchIndexes;
-		}),
-
-		"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
-			var i = argument < 0 ? argument + length : argument;
-			for ( ; ++i < length; ) {
-				matchIndexes.push( i );
-			}
-			return matchIndexes;
-		})
-	}
-};
-
-Expr.pseudos["nth"] = Expr.pseudos["eq"];
-
-// Add button/input type pseudos
-for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
-	Expr.pseudos[ i ] = createInputPseudo( i );
-}
-for ( i in { submit: true, reset: true } ) {
-	Expr.pseudos[ i ] = createButtonPseudo( i );
-}
-
-// Easy API for creating new setFilters
-function setFilters() {}
-setFilters.prototype = Expr.filters = Expr.pseudos;
-Expr.setFilters = new setFilters();
-
-function tokenize( selector, parseOnly ) {
-	var matched, match, tokens, type,
-		soFar, groups, preFilters,
-		cached = tokenCache[ selector + " " ];
-
-	if ( cached ) {
-		return parseOnly ? 0 : cached.slice( 0 );
-	}
-
-	soFar = selector;
-	groups = [];
-	preFilters = Expr.preFilter;
-
-	while ( soFar ) {
-
-		// Comma and first run
-		if ( !matched || (match = rcomma.exec( soFar )) ) {
-			if ( match ) {
-				// Don't consume trailing commas as valid
-				soFar = soFar.slice( match[0].length ) || soFar;
-			}
-			groups.push( tokens = [] );
-		}
-
-		matched = false;
-
-		// Combinators
-		if ( (match = rcombinators.exec( soFar )) ) {
-			matched = match.shift();
-			tokens.push({
-				value: matched,
-				// Cast descendant combinators to space
-				type: match[0].replace( rtrim, " " )
-			});
-			soFar = soFar.slice( matched.length );
-		}
-
-		// Filters
-		for ( type in Expr.filter ) {
-			if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
-				(match = preFilters[ type ]( match ))) ) {
-				matched = match.shift();
-				tokens.push({
-					value: matched,
-					type: type,
-					matches: match
-				});
-				soFar = soFar.slice( matched.length );
-			}
-		}
-
-		if ( !matched ) {
-			break;
-		}
-	}
-
-	// Return the length of the invalid excess
-	// if we're just parsing
-	// Otherwise, throw an error or return tokens
-	return parseOnly ?
-		soFar.length :
-		soFar ?
-			Sizzle.error( selector ) :
-			// Cache the tokens
-			tokenCache( selector, groups ).slice( 0 );
-}
-
-function toSelector( tokens ) {
-	var i = 0,
-		len = tokens.length,
-		selector = "";
-	for ( ; i < len; i++ ) {
-		selector += tokens[i].value;
-	}
-	return selector;
-}
-
-function addCombinator( matcher, combinator, base ) {
-	var dir = combinator.dir,
-		checkNonElements = base && dir === "parentNode",
-		doneName = done++;
-
-	return combinator.first ?
-		// Check against closest ancestor/preceding element
-		function( elem, context, xml ) {
-			while ( (elem = elem[ dir ]) ) {
-				if ( elem.nodeType === 1 || checkNonElements ) {
-					return matcher( elem, context, xml );
-				}
-			}
-		} :
-
-		// Check against all ancestor/preceding elements
-		function( elem, context, xml ) {
-			var data, cache, outerCache,
-				dirkey = dirruns + " " + doneName;
-
-			// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
-			if ( xml ) {
-				while ( (elem = elem[ dir ]) ) {
-					if ( elem.nodeType === 1 || checkNonElements ) {
-						if ( matcher( elem, context, xml ) ) {
-							return true;
-						}
-					}
-				}
-			} else {
-				while ( (elem = elem[ dir ]) ) {
-					if ( elem.nodeType === 1 || checkNonElements ) {
-						outerCache = elem[ expando ] || (elem[ expando ] = {});
-						if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) {
-							if ( (data = cache[1]) === true || data === cachedruns ) {
-								return data === true;
-							}
-						} else {
-							cache = outerCache[ dir ] = [ dirkey ];
-							cache[1] = matcher( elem, context, xml ) || cachedruns;
-							if ( cache[1] === true ) {
-								return true;
-							}
-						}
-					}
-				}
-			}
-		};
-}
-
-function elementMatcher( matchers ) {
-	return matchers.length > 1 ?
-		function( elem, context, xml ) {
-			var i = matchers.length;
-			while ( i-- ) {
-				if ( !matchers[i]( elem, context, xml ) ) {
-					return false;
-				}
-			}
-			return true;
-		} :
-		matchers[0];
-}
-
-function condense( unmatched, map, filter, context, xml ) {
-	var elem,
-		newUnmatched = [],
-		i = 0,
-		len = unmatched.length,
-		mapped = map != null;
-
-	for ( ; i < len; i++ ) {
-		if ( (elem = unmatched[i]) ) {
-			if ( !filter || filter( elem, context, xml ) ) {
-				newUnmatched.push( elem );
-				if ( mapped ) {
-					map.push( i );
-				}
-			}
-		}
-	}
-
-	return newUnmatched;
-}
-
-function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
-	if ( postFilter && !postFilter[ expando ] ) {
-		postFilter = setMatcher( postFilter );
-	}
-	if ( postFinder && !postFinder[ expando ] ) {
-		postFinder = setMatcher( postFinder, postSelector );
-	}
-	return markFunction(function( seed, results, context, xml ) {
-		var temp, i, elem,
-			preMap = [],
-			postMap = [],
-			preexisting = results.length,
-
-			// Get initial elements from seed or context
-			elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
-
-			// Prefilter to get matcher input, preserving a map for seed-results synchronization
-			matcherIn = preFilter && ( seed || !selector ) ?
-				condense( elems, preMap, preFilter, context, xml ) :
-				elems,
-
-			matcherOut = matcher ?
-				// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
-				postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
-
-					// ...intermediate processing is necessary
-					[] :
-
-					// ...otherwise use results directly
-					results :
-				matcherIn;
-
-		// Find primary matches
-		if ( matcher ) {
-			matcher( matcherIn, matcherOut, context, xml );
-		}
-
-		// Apply postFilter
-		if ( postFilter ) {
-			temp = condense( matcherOut, postMap );
-			postFilter( temp, [], context, xml );
-
-			// Un-match failing elements by moving them back to matcherIn
-			i = temp.length;
-			while ( i-- ) {
-				if ( (elem = temp[i]) ) {
-					matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
-				}
-			}
-		}
-
-		if ( seed ) {
-			if ( postFinder || preFilter ) {
-				if ( postFinder ) {
-					// Get the final matcherOut by condensing this intermediate into postFinder contexts
-					temp = [];
-					i = matcherOut.length;
-					while ( i-- ) {
-						if ( (elem = matcherOut[i]) ) {
-							// Restore matcherIn since elem is not yet a final match
-							temp.push( (matcherIn[i] = elem) );
-						}
-					}
-					postFinder( null, (matcherOut = []), temp, xml );
-				}
-
-				// Move matched elements from seed to results to keep them synchronized
-				i = matcherOut.length;
-				while ( i-- ) {
-					if ( (elem = matcherOut[i]) &&
-						(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
-
-						seed[temp] = !(results[temp] = elem);
-					}
-				}
-			}
-
-		// Add elements to results, through postFinder if defined
-		} else {
-			matcherOut = condense(
-				matcherOut === results ?
-					matcherOut.splice( preexisting, matcherOut.length ) :
-					matcherOut
-			);
-			if ( postFinder ) {
-				postFinder( null, results, matcherOut, xml );
-			} else {
-				push.apply( results, matcherOut );
-			}
-		}
-	});
-}
-
-function matcherFromTokens( tokens ) {
-	var checkContext, matcher, j,
-		len = tokens.length,
-		leadingRelative = Expr.relative[ tokens[0].type ],
-		implicitRelative = leadingRelative || Expr.relative[" "],
-		i = leadingRelative ? 1 : 0,
-
-		// The foundational matcher ensures that elements are reachable from top-level context(s)
-		matchContext = addCombinator( function( elem ) {
-			return elem === checkContext;
-		}, implicitRelative, true ),
-		matchAnyContext = addCombinator( function( elem ) {
-			return indexOf.call( checkContext, elem ) > -1;
-		}, implicitRelative, true ),
-		matchers = [ function( elem, context, xml ) {
-			return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
-				(checkContext = context).nodeType ?
-					matchContext( elem, context, xml ) :
-					matchAnyContext( elem, context, xml ) );
-		} ];
-
-	for ( ; i < len; i++ ) {
-		if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
-			matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
-		} else {
-			matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
-
-			// Return special upon seeing a positional matcher
-			if ( matcher[ expando ] ) {
-				// Find the next relative operator (if any) for proper handling
-				j = ++i;
-				for ( ; j < len; j++ ) {
-					if ( Expr.relative[ tokens[j].type ] ) {
-						break;
-					}
-				}
-				return setMatcher(
-					i > 1 && elementMatcher( matchers ),
-					i > 1 && toSelector(
-						// If the preceding token was a descendant combinator, insert an implicit any-element `*`
-						tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
-					).replace( rtrim, "$1" ),
-					matcher,
-					i < j && matcherFromTokens( tokens.slice( i, j ) ),
-					j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
-					j < len && toSelector( tokens )
-				);
-			}
-			matchers.push( matcher );
-		}
-	}
-
-	return elementMatcher( matchers );
-}
-
-function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
-	// A counter to specify which element is currently being matched
-	var matcherCachedRuns = 0,
-		bySet = setMatchers.length > 0,
-		byElement = elementMatchers.length > 0,
-		superMatcher = function( seed, context, xml, results, expandContext ) {
-			var elem, j, matcher,
-				setMatched = [],
-				matchedCount = 0,
-				i = "0",
-				unmatched = seed && [],
-				outermost = expandContext != null,
-				contextBackup = outermostContext,
-				// We must always have either seed elements or context
-				elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ),
-				// Use integer dirruns iff this is the outermost matcher
-				dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1);
-
-			if ( outermost ) {
-				outermostContext = context !== document && context;
-				cachedruns = matcherCachedRuns;
-			}
-
-			// Add elements passing elementMatchers directly to results
-			// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
-			for ( ; (elem = elems[i]) != null; i++ ) {
-				if ( byElement && elem ) {
-					j = 0;
-					while ( (matcher = elementMatchers[j++]) ) {
-						if ( matcher( elem, context, xml ) ) {
-							results.push( elem );
-							break;
-						}
-					}
-					if ( outermost ) {
-						dirruns = dirrunsUnique;
-						cachedruns = ++matcherCachedRuns;
-					}
-				}
-
-				// Track unmatched elements for set filters
-				if ( bySet ) {
-					// They will have gone through all possible matchers
-					if ( (elem = !matcher && elem) ) {
-						matchedCount--;
-					}
-
-					// Lengthen the array for every element, matched or not
-					if ( seed ) {
-						unmatched.push( elem );
-					}
-				}
-			}
-
-			// Apply set filters to unmatched elements
-			matchedCount += i;
-			if ( bySet && i !== matchedCount ) {
-				j = 0;
-				while ( (matcher = setMatchers[j++]) ) {
-					matcher( unmatched, setMatched, context, xml );
-				}
-
-				if ( seed ) {
-					// Reintegrate element matches to eliminate the need for sorting
-					if ( matchedCount > 0 ) {
-						while ( i-- ) {
-							if ( !(unmatched[i] || setMatched[i]) ) {
-								setMatched[i] = pop.call( results );
-							}
-						}
-					}
-
-					// Discard index placeholder values to get only actual matches
-					setMatched = condense( setMatched );
-				}
-
-				// Add matches to results
-				push.apply( results, setMatched );
-
-				// Seedless set matches succeeding multiple successful matchers stipulate sorting
-				if ( outermost && !seed && setMatched.length > 0 &&
-					( matchedCount + setMatchers.length ) > 1 ) {
-
-					Sizzle.uniqueSort( results );
-				}
-			}
-
-			// Override manipulation of globals by nested matchers
-			if ( outermost ) {
-				dirruns = dirrunsUnique;
-				outermostContext = contextBackup;
-			}
-
-			return unmatched;
-		};
-
-	return bySet ?
-		markFunction( superMatcher ) :
-		superMatcher;
-}
-
-compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) {
-	var i,
-		setMatchers = [],
-		elementMatchers = [],
-		cached = compilerCache[ selector + " " ];
-
-	if ( !cached ) {
-		// Generate a function of recursive functions that can be used to check each element
-		if ( !group ) {
-			group = tokenize( selector );
-		}
-		i = group.length;
-		while ( i-- ) {
-			cached = matcherFromTokens( group[i] );
-			if ( cached[ expando ] ) {
-				setMatchers.push( cached );
-			} else {
-				elementMatchers.push( cached );
-			}
-		}
-
-		// Cache the compiled function
-		cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
-	}
-	return cached;
-};
-
-function multipleContexts( selector, contexts, results ) {
-	var i = 0,
-		len = contexts.length;
-	for ( ; i < len; i++ ) {
-		Sizzle( selector, contexts[i], results );
-	}
-	return results;
-}
-
-function select( selector, context, results, seed ) {
-	var i, tokens, token, type, find,
-		match = tokenize( selector );
-
-	if ( !seed ) {
-		// Try to minimize operations if there is only one group
-		if ( match.length === 1 ) {
-
-			// Take a shortcut and set the context if the root selector is an ID
-			tokens = match[0] = match[0].slice( 0 );
-			if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
-					support.getById && context.nodeType === 9 && documentIsHTML &&
-					Expr.relative[ tokens[1].type ] ) {
-
-				context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
-				if ( !context ) {
-					return results;
-				}
-				selector = selector.slice( tokens.shift().value.length );
-			}
-
-			// Fetch a seed set for right-to-left matching
-			i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
-			while ( i-- ) {
-				token = tokens[i];
-
-				// Abort if we hit a combinator
-				if ( Expr.relative[ (type = token.type) ] ) {
-					break;
-				}
-				if ( (find = Expr.find[ type ]) ) {
-					// Search, expanding context for leading sibling combinators
-					if ( (seed = find(
-						token.matches[0].replace( runescape, funescape ),
-						rsibling.test( tokens[0].type ) && context.parentNode || context
-					)) ) {
-
-						// If seed is empty or no tokens remain, we can return early
-						tokens.splice( i, 1 );
-						selector = seed.length && toSelector( tokens );
-						if ( !selector ) {
-							push.apply( results, seed );
-							return results;
-						}
-
-						break;
-					}
-				}
-			}
-		}
-	}
-
-	// Compile and execute a filtering function
-	// Provide `match` to avoid retokenization if we modified the selector above
-	compile( selector, match )(
-		seed,
-		context,
-		!documentIsHTML,
-		results,
-		rsibling.test( selector )
-	);
-	return results;
-}
-
-// One-time assignments
-
-// Sort stability
-support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
-
-// Support: Chrome<14
-// Always assume duplicates if they aren't passed to the comparison function
-support.detectDuplicates = hasDuplicate;
-
-// Initialize against the default document
-setDocument();
-
-// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
-// Detached nodes confoundingly follow *each other*
-support.sortDetached = assert(function( div1 ) {
-	// Should return 1, but returns 4 (following)
-	return div1.compareDocumentPosition( document.createElement("div") ) & 1;
-});
-
-// Support: IE<8
-// Prevent attribute/property "interpolation"
-// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
-if ( !assert(function( div ) {
-	div.innerHTML = "<a href='#'></a>";
-	return div.firstChild.getAttribute("href") === "#" ;
-}) ) {
-	addHandle( "type|href|height|width", function( elem, name, isXML ) {
-		if ( !isXML ) {
-			return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
-		}
-	});
-}
-
-// Support: IE<9
-// Use defaultValue in place of getAttribute("value")
-if ( !support.attributes || !assert(function( div ) {
-	div.innerHTML = "<input/>";
-	div.firstChild.setAttribute( "value", "" );
-	return div.firstChild.getAttribute( "value" ) === "";
-}) ) {
-	addHandle( "value", function( elem, name, isXML ) {
-		if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {
-			return elem.defaultValue;
-		}
-	});
-}
-
-// Support: IE<9
-// Use getAttributeNode to fetch booleans when getAttribute lies
-if ( !assert(function( div ) {
-	return div.getAttribute("disabled") == null;
-}) ) {
-	addHandle( booleans, function( elem, name, isXML ) {
-		var val;
-		if ( !isXML ) {
-			return (val = elem.getAttributeNode( name )) && val.specified ?
-				val.value :
-				elem[ name ] === true ? name.toLowerCase() : null;
-		}
-	});
-}
-
-jQuery.find = Sizzle;
-jQuery.expr = Sizzle.selectors;
-jQuery.expr[":"] = jQuery.expr.pseudos;
-jQuery.unique = Sizzle.uniqueSort;
-jQuery.text = Sizzle.getText;
-jQuery.isXMLDoc = Sizzle.isXML;
-jQuery.contains = Sizzle.contains;
-
-
-})( window );
-// String to Object options format cache
-var optionsCache = {};
-
-// Convert String-formatted options into Object-formatted ones and store in cache
-function createOptions( options ) {
-	var object = optionsCache[ options ] = {};
-	jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) {
-		object[ flag ] = true;
-	});
-	return object;
-}
-
-/*
- * Create a callback list using the following parameters:
- *
- *	options: an optional list of space-separated options that will change how
- *			the callback list behaves or a more traditional option object
- *
- * By default a callback list will act like an event callback list and can be
- * "fired" multiple times.
- *
- * Possible options:
- *
- *	once:			will ensure the callback list can only be fired once (like a Deferred)
- *
- *	memory:			will keep track of previous values and will call any callback added
- *					after the list has been fired right away with the latest "memorized"
- *					values (like a Deferred)
- *
- *	unique:			will ensure a callback can only be added once (no duplicate in the list)
- *
- *	stopOnFalse:	interrupt callings when a callback returns false
- *
- */
-jQuery.Callbacks = function( options ) {
-
-	// Convert options from String-formatted to Object-formatted if needed
-	// (we check in cache first)
-	options = typeof options === "string" ?
-		( optionsCache[ options ] || createOptions( options ) ) :
-		jQuery.extend( {}, options );
-
-	var // Flag to know if list is currently firing
-		firing,
-		// Last fire value (for non-forgettable lists)
-		memory,
-		// Flag to know if list was already fired
-		fired,
-		// End of the loop when firing
-		firingLength,
-		// Index of currently firing callback (modified by remove if needed)
-		firingIndex,
-		// First callback to fire (used internally by add and fireWith)
-		firingStart,
-		// Actual callback list
-		list = [],
-		// Stack of fire calls for repeatable lists
-		stack = !options.once && [],
-		// Fire callbacks
-		fire = function( data ) {
-			memory = options.memory && data;
-			fired = true;
-			firingIndex = firingStart || 0;
-			firingStart = 0;
-			firingLength = list.length;
-			firing = true;
-			for ( ; list && firingIndex < firingLength; firingIndex++ ) {
-				if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
-					memory = false; // To prevent further calls using add
-					break;
-				}
-			}
-			firing = false;
-			if ( list ) {
-				if ( stack ) {
-					if ( stack.length ) {
-						fire( stack.shift() );
-					}
-				} else if ( memory ) {
-					list = [];
-				} else {
-					self.disable();
-				}
-			}
-		},
-		// Actual Callbacks object
-		self = {
-			// Add a callback or a collection of callbacks to the list
-			add: function() {
-				if ( list ) {
-					// First, we save the current length
-					var start = list.length;
-					(function add( args ) {
-						jQuery.each( args, function( _, arg ) {
-							var type = jQuery.type( arg );
-							if ( type === "function" ) {
-								if ( !options.unique || !self.has( arg ) ) {
-									list.push( arg );
-								}
-							} else if ( arg && arg.length && type !== "string" ) {
-								// Inspect recursively
-								add( arg );
-							}
-						});
-					})( arguments );
-					// Do we need to add the callbacks to the
-					// current firing batch?
-					if ( firing ) {
-						firingLength = list.length;
-					// With memory, if we're not firing then
-					// we should call right away
-					} else if ( memory ) {
-						firingStart = start;
-						fire( memory );
-					}
-				}
-				return this;
-			},
-			// Remove a callback from the list
-			remove: function() {
-				if ( list ) {
-					jQuery.each( arguments, function( _, arg ) {
-						var index;
-						while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
-							list.splice( index, 1 );
-							// Handle firing indexes
-							if ( firing ) {
-								if ( index <= firingLength ) {
-									firingLength--;
-								}
-								if ( index <= firingIndex ) {
-									firingIndex--;
-								}
-							}
-						}
-					});
-				}
-				return this;
-			},
-			// Check if a given callback is in the list.
-			// If no argument is given, return whether or not list has callbacks attached.
-			has: function( fn ) {
-				return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length );
-			},
-			// Remove all callbacks from the list
-			empty: function() {
-				list = [];
-				firingLength = 0;
-				return this;
-			},
-			// Have the list do nothing anymore
-			disable: function() {
-				list = stack = memory = undefined;
-				return this;
-			},
-			// Is it disabled?
-			disabled: function() {
-				return !list;
-			},
-			// Lock the list in its current state
-			lock: function() {
-				stack = undefined;
-				if ( !memory ) {
-					self.disable();
-				}
-				return this;
-			},
-			// Is it locked?
-			locked: function() {


<TRUNCATED>

[23/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/js/libs/ace/mode-javascript.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/js/libs/ace/mode-javascript.js b/apps/fauxton/assets/js/libs/ace/mode-javascript.js
deleted file mode 100644
index c9e6f50..0000000
--- a/apps/fauxton/assets/js/libs/ace/mode-javascript.js
+++ /dev/null
@@ -1,886 +0,0 @@
-/* ***** BEGIN LICENSE BLOCK *****
- * Distributed under the BSD license:
- *
- * Copyright (c) 2010, Ajax.org B.V.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above copyright
- *       notice, this list of conditions and the following disclaimer in the
- *       documentation and/or other materials provided with the distribution.
- *     * Neither the name of Ajax.org B.V. nor the
- *       names of its contributors may be used to endorse or promote products
- *       derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * ***** END LICENSE BLOCK ***** */
-
-define('ace/mode/javascript', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/javascript_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range', 'ace/worker/worker_client', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle'], function(require, exports, module) {
-
-
-var oop = require("../lib/oop");
-var TextMode = require("./text").Mode;
-var Tokenizer = require("../tokenizer").Tokenizer;
-var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules;
-var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent;
-var Range = require("../range").Range;
-var WorkerClient = require("../worker/worker_client").WorkerClient;
-var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour;
-var CStyleFoldMode = require("./folding/cstyle").FoldMode;
-
-var Mode = function() {
-    this.HighlightRules = JavaScriptHighlightRules;
-    
-    this.$outdent = new MatchingBraceOutdent();
-    this.$behaviour = new CstyleBehaviour();
-    this.foldingRules = new CStyleFoldMode();
-};
-oop.inherits(Mode, TextMode);
-
-(function() {
-
-    this.lineCommentStart = "//";
-    this.blockComment = {start: "/*", end: "*/"};
-
-    this.getNextLineIndent = function(state, line, tab) {
-        var indent = this.$getIndent(line);
-
-        var tokenizedLine = this.getTokenizer().getLineTokens(line, state);
-        var tokens = tokenizedLine.tokens;
-        var endState = tokenizedLine.state;
-
-        if (tokens.length && tokens[tokens.length-1].type == "comment") {
-            return indent;
-        }
-
-        if (state == "start" || state == "no_regex") {
-            var match = line.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/);
-            if (match) {
-                indent += tab;
-            }
-        } else if (state == "doc-start") {
-            if (endState == "start" || endState == "no_regex") {
-                return "";
-            }
-            var match = line.match(/^\s*(\/?)\*/);
-            if (match) {
-                if (match[1]) {
-                    indent += " ";
-                }
-                indent += "* ";
-            }
-        }
-
-        return indent;
-    };
-
-    this.checkOutdent = function(state, line, input) {
-        return this.$outdent.checkOutdent(line, input);
-    };
-
-    this.autoOutdent = function(state, doc, row) {
-        this.$outdent.autoOutdent(doc, row);
-    };
-
-    this.createWorker = function(session) {
-        var worker = new WorkerClient(["ace"], "ace/mode/javascript_worker", "JavaScriptWorker");
-        worker.attachToDocument(session.getDocument());
-
-        worker.on("jslint", function(results) {
-            session.setAnnotations(results.data);
-        });
-
-        worker.on("terminate", function() {
-            session.clearAnnotations();
-        });
-
-        return worker;
-    };
-
-}).call(Mode.prototype);
-
-exports.Mode = Mode;
-});
-
-define('ace/mode/javascript_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
-
-
-var oop = require("../lib/oop");
-var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules;
-var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
-
-var JavaScriptHighlightRules = function() {
-    var keywordMapper = this.createKeywordMapper({
-        "variable.language":
-            "Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|"  + // Constructors
-            "Namespace|QName|XML|XMLList|"                                             + // E4X
-            "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|"   +
-            "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|"                    +
-            "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|"   + // Errors
-            "SyntaxError|TypeError|URIError|"                                          +
-            "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + // Non-constructor functions
-            "isNaN|parseFloat|parseInt|"                                               +
-            "JSON|Math|"                                                               + // Other
-            "this|arguments|prototype|window|document"                                 , // Pseudo
-        "keyword":
-            "const|yield|import|get|set|" +
-            "break|case|catch|continue|default|delete|do|else|finally|for|function|" +
-            "if|in|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|debugger|" +
-            "__parent__|__count__|escape|unescape|with|__proto__|" +
-            "class|enum|extends|super|export|implements|private|public|interface|package|protected|static",
-        "storage.type":
-            "const|let|var|function",
-        "constant.language":
-            "null|Infinity|NaN|undefined",
-        "support.function":
-            "alert",
-        "constant.language.boolean": "true|false"
-    }, "identifier");
-    var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield|void";
-    var identifierRe = "[a-zA-Z\\$_\u00a1-\uffff][a-zA-Z\\d\\$_\u00a1-\uffff]*\\b";
-
-    var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex
-        "u[0-9a-fA-F]{4}|" + // unicode
-        "[0-2][0-7]{0,2}|" + // oct
-        "3[0-6][0-7]?|" + // oct
-        "37[0-7]?|" + // oct
-        "[4-7][0-7]?|" + //oct
-        ".)";
-
-    this.$rules = {
-        "no_regex" : [
-            {
-                token : "comment",
-                regex : "\\/\\/",
-                next : "line_comment"
-            },
-            DocCommentHighlightRules.getStartRule("doc-start"),
-            {
-                token : "comment", // multi line comment
-                regex : /\/\*/,
-                next : "comment"
-            }, {
-                token : "string",
-                regex : "'(?=.)",
-                next  : "qstring"
-            }, {
-                token : "string",
-                regex : '"(?=.)',
-                next  : "qqstring"
-            }, {
-                token : "constant.numeric", // hex
-                regex : /0[xX][0-9a-fA-F]+\b/
-            }, {
-                token : "constant.numeric", // float
-                regex : /[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/
-            }, {
-                token : [
-                    "storage.type", "punctuation.operator", "support.function",
-                    "punctuation.operator", "entity.name.function", "text","keyword.operator"
-                ],
-                regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)",
-                next: "function_arguments"
-            }, {
-                token : [
-                    "storage.type", "punctuation.operator", "entity.name.function", "text",
-                    "keyword.operator", "text", "storage.type", "text", "paren.lparen"
-                ],
-                regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()",
-                next: "function_arguments"
-            }, {
-                token : [
-                    "entity.name.function", "text", "keyword.operator", "text", "storage.type",
-                    "text", "paren.lparen"
-                ],
-                regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()",
-                next: "function_arguments"
-            }, {
-                token : [
-                    "storage.type", "punctuation.operator", "entity.name.function", "text",
-                    "keyword.operator", "text",
-                    "storage.type", "text", "entity.name.function", "text", "paren.lparen"
-                ],
-                regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s+)(\\w+)(\\s*)(\\()",
-                next: "function_arguments"
-            }, {
-                token : [
-                    "storage.type", "text", "entity.name.function", "text", "paren.lparen"
-                ],
-                regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()",
-                next: "function_arguments"
-            }, {
-                token : [
-                    "entity.name.function", "text", "punctuation.operator",
-                    "text", "storage.type", "text", "paren.lparen"
-                ],
-                regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()",
-                next: "function_arguments"
-            }, {
-                token : [
-                    "text", "text", "storage.type", "text", "paren.lparen"
-                ],
-                regex : "(:)(\\s*)(function)(\\s*)(\\()",
-                next: "function_arguments"
-            }, {
-                token : "keyword",
-                regex : "(?:" + kwBeforeRe + ")\\b",
-                next : "start"
-            }, {
-                token : ["punctuation.operator", "support.function"],
-                regex : /(\.)(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:op|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nabl
 eExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/
-            }, {
-                token : ["punctuation.operator", "support.function.dom"],
-                regex : /(\.)(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/
-            }, {
-                token : ["punctuation.operator", "support.constant"],
-                regex : /(\.)(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thn
 ame|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/
-            }, {
-                token : ["storage.type", "punctuation.operator", "support.function.firebug"],
-                regex : /(console)(\.)(warn|info|log|error|time|timeEnd|assert)\b/
-            }, {
-                token : keywordMapper,
-                regex : identifierRe
-            }, {
-                token : "keyword.operator",
-                regex : /--|\+\+|[!$%&*+\-~]|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=/,
-                next  : "start"
-            }, {
-                token : "punctuation.operator",
-                regex : /\?|\:|\,|\;|\./,
-                next  : "start"
-            }, {
-                token : "paren.lparen",
-                regex : /[\[({]/,
-                next  : "start"
-            }, {
-                token : "paren.rparen",
-                regex : /[\])}]/
-            }, {
-                token : "keyword.operator",
-                regex : /\/=?/,
-                next  : "start"
-            }, {
-                token: "comment",
-                regex: /^#!.*$/
-            }
-        ],
-        "start": [
-            DocCommentHighlightRules.getStartRule("doc-start"),
-            {
-                token : "comment", // multi line comment
-                regex : "\\/\\*",
-                next : "comment_regex_allowed"
-            }, {
-                token : "comment",
-                regex : "\\/\\/",
-                next : "line_comment_regex_allowed"
-            }, {
-                token: "string.regexp",
-                regex: "\\/",
-                next: "regex"
-            }, {
-                token : "text",
-                regex : "\\s+|^$",
-                next : "start"
-            }, {
-                token: "empty",
-                regex: "",
-                next: "no_regex"
-            }
-        ],
-        "regex": [
-            {
-                token: "regexp.keyword.operator",
-                regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)"
-            }, {
-                token: "string.regexp",
-                regex: "/\\w*",
-                next: "no_regex"
-            }, {
-                token : "invalid",
-                regex: /\{\d+\b,?\d*\}[+*]|[+*$^?][+*]|[$^][?]|\?{3,}/
-            }, {
-                token : "constant.language.escape",
-                regex: /\(\?[:=!]|\)|\{\d+\b,?\d*\}|[+*]\?|[()$^+*?]/
-            }, {
-                token : "constant.language.delimiter",
-                regex: /\|/
-            }, {
-                token: "constant.language.escape",
-                regex: /\[\^?/,
-                next: "regex_character_class"
-            }, {
-                token: "empty",
-                regex: "$",
-                next: "no_regex"
-            }, {
-                defaultToken: "string.regexp"
-            }
-        ],
-        "regex_character_class": [
-            {
-                token: "regexp.keyword.operator",
-                regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)"
-            }, {
-                token: "constant.language.escape",
-                regex: "]",
-                next: "regex"
-            }, {
-                token: "constant.language.escape",
-                regex: "-"
-            }, {
-                token: "empty",
-                regex: "$",
-                next: "no_regex"
-            }, {
-                defaultToken: "string.regexp.charachterclass"
-            }
-        ],
-        "function_arguments": [
-            {
-                token: "variable.parameter",
-                regex: identifierRe
-            }, {
-                token: "punctuation.operator",
-                regex: "[, ]+"
-            }, {
-                token: "punctuation.operator",
-                regex: "$"
-            }, {
-                token: "empty",
-                regex: "",
-                next: "no_regex"
-            }
-        ],
-        "comment_regex_allowed" : [
-            {token : "comment", regex : "\\*\\/", next : "start"},
-            {defaultToken : "comment"}
-        ],
-        "comment" : [
-            {token : "comment", regex : "\\*\\/", next : "no_regex"},
-            {defaultToken : "comment"}
-        ],
-        "line_comment_regex_allowed" : [
-            {token : "comment", regex : "$|^", next : "start"},
-            {defaultToken : "comment"}
-        ],
-        "line_comment" : [
-            {token : "comment", regex : "$|^", next : "no_regex"},
-            {defaultToken : "comment"}
-        ],
-        "qqstring" : [
-            {
-                token : "constant.language.escape",
-                regex : escapedRe
-            }, {
-                token : "string",
-                regex : "\\\\$",
-                next  : "qqstring"
-            }, {
-                token : "string",
-                regex : '"|$',
-                next  : "no_regex"
-            }, {
-                defaultToken: "string"
-            }
-        ],
-        "qstring" : [
-            {
-                token : "constant.language.escape",
-                regex : escapedRe
-            }, {
-                token : "string",
-                regex : "\\\\$",
-                next  : "qstring"
-            }, {
-                token : "string",
-                regex : "'|$",
-                next  : "no_regex"
-            }, {
-                defaultToken: "string"
-            }
-        ]
-    };
-
-    this.embedRules(DocCommentHighlightRules, "doc-",
-        [ DocCommentHighlightRules.getEndRule("no_regex") ]);
-};
-
-oop.inherits(JavaScriptHighlightRules, TextHighlightRules);
-
-exports.JavaScriptHighlightRules = JavaScriptHighlightRules;
-});
-
-define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
-
-
-var oop = require("../lib/oop");
-var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
-
-var DocCommentHighlightRules = function() {
-
-    this.$rules = {
-        "start" : [ {
-            token : "comment.doc.tag",
-            regex : "@[\\w\\d_]+" // TODO: fix email addresses
-        }, {
-            token : "comment.doc.tag",
-            regex : "\\bTODO\\b"
-        }, {
-            defaultToken : "comment.doc"
-        }]
-    };
-};
-
-oop.inherits(DocCommentHighlightRules, TextHighlightRules);
-
-DocCommentHighlightRules.getStartRule = function(start) {
-    return {
-        token : "comment.doc", // doc comment
-        regex : "\\/\\*(?=\\*)",
-        next  : start
-    };
-};
-
-DocCommentHighlightRules.getEndRule = function (start) {
-    return {
-        token : "comment.doc", // closing comment
-        regex : "\\*\\/",
-        next  : start
-    };
-};
-
-
-exports.DocCommentHighlightRules = DocCommentHighlightRules;
-
-});
-
-define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) {
-
-
-var Range = require("../range").Range;
-
-var MatchingBraceOutdent = function() {};
-
-(function() {
-
-    this.checkOutdent = function(line, input) {
-        if (! /^\s+$/.test(line))
-            return false;
-
-        return /^\s*\}/.test(input);
-    };
-
-    this.autoOutdent = function(doc, row) {
-        var line = doc.getLine(row);
-        var match = line.match(/^(\s*\})/);
-
-        if (!match) return 0;
-
-        var column = match[1].length;
-        var openBracePos = doc.findMatchingBracket({row: row, column: column});
-
-        if (!openBracePos || openBracePos.row == row) return 0;
-
-        var indent = this.$getIndent(doc.getLine(openBracePos.row));
-        doc.replace(new Range(row, 0, row, column-1), indent);
-    };
-
-    this.$getIndent = function(line) {
-        return line.match(/^\s*/)[0];
-    };
-
-}).call(MatchingBraceOutdent.prototype);
-
-exports.MatchingBraceOutdent = MatchingBraceOutdent;
-});
-
-define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour', 'ace/token_iterator', 'ace/lib/lang'], function(require, exports, module) {
-
-
-var oop = require("../../lib/oop");
-var Behaviour = require("../behaviour").Behaviour;
-var TokenIterator = require("../../token_iterator").TokenIterator;
-var lang = require("../../lib/lang");
-
-var SAFE_INSERT_IN_TOKENS =
-    ["text", "paren.rparen", "punctuation.operator"];
-var SAFE_INSERT_BEFORE_TOKENS =
-    ["text", "paren.rparen", "punctuation.operator", "comment"];
-
-
-var autoInsertedBrackets = 0;
-var autoInsertedRow = -1;
-var autoInsertedLineEnd = "";
-var maybeInsertedBrackets = 0;
-var maybeInsertedRow = -1;
-var maybeInsertedLineStart = "";
-var maybeInsertedLineEnd = "";
-
-var CstyleBehaviour = function () {
-    
-    CstyleBehaviour.isSaneInsertion = function(editor, session) {
-        var cursor = editor.getCursorPosition();
-        var iterator = new TokenIterator(session, cursor.row, cursor.column);
-        if (!this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) {
-            var iterator2 = new TokenIterator(session, cursor.row, cursor.column + 1);
-            if (!this.$matchTokenType(iterator2.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS))
-                return false;
-        }
-        iterator.stepForward();
-        return iterator.getCurrentTokenRow() !== cursor.row ||
-            this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_BEFORE_TOKENS);
-    };
-    
-    CstyleBehaviour.$matchTokenType = function(token, types) {
-        return types.indexOf(token.type || token) > -1;
-    };
-    
-    CstyleBehaviour.recordAutoInsert = function(editor, session, bracket) {
-        var cursor = editor.getCursorPosition();
-        var line = session.doc.getLine(cursor.row);
-        if (!this.isAutoInsertedClosing(cursor, line, autoInsertedLineEnd[0]))
-            autoInsertedBrackets = 0;
-        autoInsertedRow = cursor.row;
-        autoInsertedLineEnd = bracket + line.substr(cursor.column);
-        autoInsertedBrackets++;
-    };
-    
-    CstyleBehaviour.recordMaybeInsert = function(editor, session, bracket) {
-        var cursor = editor.getCursorPosition();
-        var line = session.doc.getLine(cursor.row);
-        if (!this.isMaybeInsertedClosing(cursor, line))
-            maybeInsertedBrackets = 0;
-        maybeInsertedRow = cursor.row;
-        maybeInsertedLineStart = line.substr(0, cursor.column) + bracket;
-        maybeInsertedLineEnd = line.substr(cursor.column);
-        maybeInsertedBrackets++;
-    };
-    
-    CstyleBehaviour.isAutoInsertedClosing = function(cursor, line, bracket) {
-        return autoInsertedBrackets > 0 &&
-            cursor.row === autoInsertedRow &&
-            bracket === autoInsertedLineEnd[0] &&
-            line.substr(cursor.column) === autoInsertedLineEnd;
-    };
-    
-    CstyleBehaviour.isMaybeInsertedClosing = function(cursor, line) {
-        return maybeInsertedBrackets > 0 &&
-            cursor.row === maybeInsertedRow &&
-            line.substr(cursor.column) === maybeInsertedLineEnd &&
-            line.substr(0, cursor.column) == maybeInsertedLineStart;
-    };
-    
-    CstyleBehaviour.popAutoInsertedClosing = function() {
-        autoInsertedLineEnd = autoInsertedLineEnd.substr(1);
-        autoInsertedBrackets--;
-    };
-    
-    CstyleBehaviour.clearMaybeInsertedClosing = function() {
-        maybeInsertedBrackets = 0;
-        maybeInsertedRow = -1;
-    };
-
-    this.add("braces", "insertion", function (state, action, editor, session, text) {
-        var cursor = editor.getCursorPosition();
-        var line = session.doc.getLine(cursor.row);
-        if (text == '{') {
-            var selection = editor.getSelectionRange();
-            var selected = session.doc.getTextRange(selection);
-            if (selected !== "" && selected !== "{" && editor.getWrapBehavioursEnabled()) {
-                return {
-                    text: '{' + selected + '}',
-                    selection: false
-                };
-            } else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
-                if (/[\]\}\)]/.test(line[cursor.column])) {
-                    CstyleBehaviour.recordAutoInsert(editor, session, "}");
-                    return {
-                        text: '{}',
-                        selection: [1, 1]
-                    };
-                } else {
-                    CstyleBehaviour.recordMaybeInsert(editor, session, "{");
-                    return {
-                        text: '{',
-                        selection: [1, 1]
-                    };
-                }
-            }
-        } else if (text == '}') {
-            var rightChar = line.substring(cursor.column, cursor.column + 1);
-            if (rightChar == '}') {
-                var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row});
-                if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
-                    CstyleBehaviour.popAutoInsertedClosing();
-                    return {
-                        text: '',
-                        selection: [1, 1]
-                    };
-                }
-            }
-        } else if (text == "\n" || text == "\r\n") {
-            var closing = "";
-            if (CstyleBehaviour.isMaybeInsertedClosing(cursor, line)) {
-                closing = lang.stringRepeat("}", maybeInsertedBrackets);
-                CstyleBehaviour.clearMaybeInsertedClosing();
-            }
-            var rightChar = line.substring(cursor.column, cursor.column + 1);
-            if (rightChar == '}' || closing !== "") {
-                var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column}, '}');
-                if (!openBracePos)
-                     return null;
-
-                var indent = this.getNextLineIndent(state, line.substring(0, cursor.column), session.getTabString());
-                var next_indent = this.$getIndent(line);
-
-                return {
-                    text: '\n' + indent + '\n' + next_indent + closing,
-                    selection: [1, indent.length, 1, indent.length]
-                };
-            }
-        }
-    });
-
-    this.add("braces", "deletion", function (state, action, editor, session, range) {
-        var selected = session.doc.getTextRange(range);
-        if (!range.isMultiLine() && selected == '{') {
-            var line = session.doc.getLine(range.start.row);
-            var rightChar = line.substring(range.end.column, range.end.column + 1);
-            if (rightChar == '}') {
-                range.end.column++;
-                return range;
-            } else {
-                maybeInsertedBrackets--;
-            }
-        }
-    });
-
-    this.add("parens", "insertion", function (state, action, editor, session, text) {
-        if (text == '(') {
-            var selection = editor.getSelectionRange();
-            var selected = session.doc.getTextRange(selection);
-            if (selected !== "" && editor.getWrapBehavioursEnabled()) {
-                return {
-                    text: '(' + selected + ')',
-                    selection: false
-                };
-            } else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
-                CstyleBehaviour.recordAutoInsert(editor, session, ")");
-                return {
-                    text: '()',
-                    selection: [1, 1]
-                };
-            }
-        } else if (text == ')') {
-            var cursor = editor.getCursorPosition();
-            var line = session.doc.getLine(cursor.row);
-            var rightChar = line.substring(cursor.column, cursor.column + 1);
-            if (rightChar == ')') {
-                var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row});
-                if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
-                    CstyleBehaviour.popAutoInsertedClosing();
-                    return {
-                        text: '',
-                        selection: [1, 1]
-                    };
-                }
-            }
-        }
-    });
-
-    this.add("parens", "deletion", function (state, action, editor, session, range) {
-        var selected = session.doc.getTextRange(range);
-        if (!range.isMultiLine() && selected == '(') {
-            var line = session.doc.getLine(range.start.row);
-            var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
-            if (rightChar == ')') {
-                range.end.column++;
-                return range;
-            }
-        }
-    });
-
-    this.add("brackets", "insertion", function (state, action, editor, session, text) {
-        if (text == '[') {
-            var selection = editor.getSelectionRange();
-            var selected = session.doc.getTextRange(selection);
-            if (selected !== "" && editor.getWrapBehavioursEnabled()) {
-                return {
-                    text: '[' + selected + ']',
-                    selection: false
-                };
-            } else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
-                CstyleBehaviour.recordAutoInsert(editor, session, "]");
-                return {
-                    text: '[]',
-                    selection: [1, 1]
-                };
-            }
-        } else if (text == ']') {
-            var cursor = editor.getCursorPosition();
-            var line = session.doc.getLine(cursor.row);
-            var rightChar = line.substring(cursor.column, cursor.column + 1);
-            if (rightChar == ']') {
-                var matching = session.$findOpeningBracket(']', {column: cursor.column + 1, row: cursor.row});
-                if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
-                    CstyleBehaviour.popAutoInsertedClosing();
-                    return {
-                        text: '',
-                        selection: [1, 1]
-                    };
-                }
-            }
-        }
-    });
-
-    this.add("brackets", "deletion", function (state, action, editor, session, range) {
-        var selected = session.doc.getTextRange(range);
-        if (!range.isMultiLine() && selected == '[') {
-            var line = session.doc.getLine(range.start.row);
-            var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
-            if (rightChar == ']') {
-                range.end.column++;
-                return range;
-            }
-        }
-    });
-
-    this.add("string_dquotes", "insertion", function (state, action, editor, session, text) {
-        if (text == '"' || text == "'") {
-            var quote = text;
-            var selection = editor.getSelectionRange();
-            var selected = session.doc.getTextRange(selection);
-            if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) {
-                return {
-                    text: quote + selected + quote,
-                    selection: false
-                };
-            } else {
-                var cursor = editor.getCursorPosition();
-                var line = session.doc.getLine(cursor.row);
-                var leftChar = line.substring(cursor.column-1, cursor.column);
-                if (leftChar == '\\') {
-                    return null;
-                }
-                var tokens = session.getTokens(selection.start.row);
-                var col = 0, token;
-                var quotepos = -1; // Track whether we're inside an open quote.
-
-                for (var x = 0; x < tokens.length; x++) {
-                    token = tokens[x];
-                    if (token.type == "string") {
-                      quotepos = -1;
-                    } else if (quotepos < 0) {
-                      quotepos = token.value.indexOf(quote);
-                    }
-                    if ((token.value.length + col) > selection.start.column) {
-                        break;
-                    }
-                    col += tokens[x].value.length;
-                }
-                if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) {
-                    if (!CstyleBehaviour.isSaneInsertion(editor, session))
-                        return;
-                    return {
-                        text: quote + quote,
-                        selection: [1,1]
-                    };
-                } else if (token && token.type === "string") {
-                    var rightChar = line.substring(cursor.column, cursor.column + 1);
-                    if (rightChar == quote) {
-                        return {
-                            text: '',
-                            selection: [1, 1]
-                        };
-                    }
-                }
-            }
-        }
-    });
-
-    this.add("string_dquotes", "deletion", function (state, action, editor, session, range) {
-        var selected = session.doc.getTextRange(range);
-        if (!range.isMultiLine() && (selected == '"' || selected == "'")) {
-            var line = session.doc.getLine(range.start.row);
-            var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
-            if (rightChar == selected) {
-                range.end.column++;
-                return range;
-            }
-        }
-    });
-
-};
-
-oop.inherits(CstyleBehaviour, Behaviour);
-
-exports.CstyleBehaviour = CstyleBehaviour;
-});
-
-define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) {
-
-
-var oop = require("../../lib/oop");
-var Range = require("../../range").Range;
-var BaseFoldMode = require("./fold_mode").FoldMode;
-
-var FoldMode = exports.FoldMode = function(commentRegex) {
-    if (commentRegex) {
-        this.foldingStartMarker = new RegExp(
-            this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start)
-        );
-        this.foldingStopMarker = new RegExp(
-            this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end)
-        );
-    }
-};
-oop.inherits(FoldMode, BaseFoldMode);
-
-(function() {
-
-    this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/;
-    this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/;
-
-    this.getFoldWidgetRange = function(session, foldStyle, row) {
-        var line = session.getLine(row);
-        var match = line.match(this.foldingStartMarker);
-        if (match) {
-            var i = match.index;
-
-            if (match[1])
-                return this.openingBracketBlock(session, match[1], row, i);
-
-            return session.getCommentFoldRange(row, i + match[0].length, 1);
-        }
-
-        if (foldStyle !== "markbeginend")
-            return;
-
-        var match = line.match(this.foldingStopMarker);
-        if (match) {
-            var i = match.index + match[0].length;
-
-            if (match[1])
-                return this.closingBracketBlock(session, match[1], row, i);
-
-            return session.getCommentFoldRange(row, i, -1);
-        }
-    };
-
-}).call(FoldMode.prototype);
-
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/js/libs/ace/mode-json.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/js/libs/ace/mode-json.js b/apps/fauxton/assets/js/libs/ace/mode-json.js
deleted file mode 100644
index d1b3d47..0000000
--- a/apps/fauxton/assets/js/libs/ace/mode-json.js
+++ /dev/null
@@ -1,578 +0,0 @@
-/* ***** BEGIN LICENSE BLOCK *****
- * Distributed under the BSD license:
- *
- * Copyright (c) 2010, Ajax.org B.V.
- * All rights reserved.
- * 
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above copyright
- *       notice, this list of conditions and the following disclaimer in the
- *       documentation and/or other materials provided with the distribution.
- *     * Neither the name of Ajax.org B.V. nor the
- *       names of its contributors may be used to endorse or promote products
- *       derived from this software without specific prior written permission.
- * 
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * ***** END LICENSE BLOCK ***** */
-
-define('ace/mode/json', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/json_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle', 'ace/worker/worker_client'], function(require, exports, module) {
-
-
-var oop = require("../lib/oop");
-var TextMode = require("./text").Mode;
-var Tokenizer = require("../tokenizer").Tokenizer;
-var HighlightRules = require("./json_highlight_rules").JsonHighlightRules;
-var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent;
-var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour;
-var CStyleFoldMode = require("./folding/cstyle").FoldMode;
-var WorkerClient = require("../worker/worker_client").WorkerClient;
-
-var Mode = function() {
-    this.HighlightRules = HighlightRules;
-    this.$outdent = new MatchingBraceOutdent();
-    this.$behaviour = new CstyleBehaviour();
-    this.foldingRules = new CStyleFoldMode();
-};
-oop.inherits(Mode, TextMode);
-
-(function() {
-
-    this.getNextLineIndent = function(state, line, tab) {
-        var indent = this.$getIndent(line);
-
-        if (state == "start") {
-            var match = line.match(/^.*[\{\(\[]\s*$/);
-            if (match) {
-                indent += tab;
-            }
-        }
-
-        return indent;
-    };
-
-    this.checkOutdent = function(state, line, input) {
-        return this.$outdent.checkOutdent(line, input);
-    };
-
-    this.autoOutdent = function(state, doc, row) {
-        this.$outdent.autoOutdent(doc, row);
-    };
-
-    this.createWorker = function(session) {
-        var worker = new WorkerClient(["ace"], "ace/mode/json_worker", "JsonWorker");
-        worker.attachToDocument(session.getDocument());
-
-        worker.on("error", function(e) {
-            session.setAnnotations([e.data]);
-        });
-
-        worker.on("ok", function() {
-            session.clearAnnotations();
-        });
-
-        return worker;
-    };
-
-
-}).call(Mode.prototype);
-
-exports.Mode = Mode;
-});
-
-define('ace/mode/json_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
-
-
-var oop = require("../lib/oop");
-var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
-
-var JsonHighlightRules = function() {
-    this.$rules = {
-        "start" : [
-            {
-                token : "variable", // single line
-                regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]\\s*(?=:)'
-            }, {
-                token : "string", // single line
-                regex : '"',
-                next  : "string"
-            }, {
-                token : "constant.numeric", // hex
-                regex : "0[xX][0-9a-fA-F]+\\b"
-            }, {
-                token : "constant.numeric", // float
-                regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
-            }, {
-                token : "constant.language.boolean",
-                regex : "(?:true|false)\\b"
-            }, {
-                token : "invalid.illegal", // single quoted strings are not allowed
-                regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"
-            }, {
-                token : "invalid.illegal", // comments are not allowed
-                regex : "\\/\\/.*$"
-            }, {
-                token : "paren.lparen",
-                regex : "[[({]"
-            }, {
-                token : "paren.rparen",
-                regex : "[\\])}]"
-            }, {
-                token : "text",
-                regex : "\\s+"
-            }
-        ],
-        "string" : [
-            {
-                token : "constant.language.escape",
-                regex : /\\(?:x[0-9a-fA-F]{2}|u[0-9a-fA-F]{4}|["\\\/bfnrt])/
-            }, {
-                token : "string",
-                regex : '[^"\\\\]+'
-            }, {
-                token : "string",
-                regex : '"',
-                next  : "start"
-            }, {
-                token : "string",
-                regex : "",
-                next  : "start"
-            }
-        ]
-    };
-    
-};
-
-oop.inherits(JsonHighlightRules, TextHighlightRules);
-
-exports.JsonHighlightRules = JsonHighlightRules;
-});
-
-define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) {
-
-
-var Range = require("../range").Range;
-
-var MatchingBraceOutdent = function() {};
-
-(function() {
-
-    this.checkOutdent = function(line, input) {
-        if (! /^\s+$/.test(line))
-            return false;
-
-        return /^\s*\}/.test(input);
-    };
-
-    this.autoOutdent = function(doc, row) {
-        var line = doc.getLine(row);
-        var match = line.match(/^(\s*\})/);
-
-        if (!match) return 0;
-
-        var column = match[1].length;
-        var openBracePos = doc.findMatchingBracket({row: row, column: column});
-
-        if (!openBracePos || openBracePos.row == row) return 0;
-
-        var indent = this.$getIndent(doc.getLine(openBracePos.row));
-        doc.replace(new Range(row, 0, row, column-1), indent);
-    };
-
-    this.$getIndent = function(line) {
-        return line.match(/^\s*/)[0];
-    };
-
-}).call(MatchingBraceOutdent.prototype);
-
-exports.MatchingBraceOutdent = MatchingBraceOutdent;
-});
-
-define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour', 'ace/token_iterator', 'ace/lib/lang'], function(require, exports, module) {
-
-
-var oop = require("../../lib/oop");
-var Behaviour = require("../behaviour").Behaviour;
-var TokenIterator = require("../../token_iterator").TokenIterator;
-var lang = require("../../lib/lang");
-
-var SAFE_INSERT_IN_TOKENS =
-    ["text", "paren.rparen", "punctuation.operator"];
-var SAFE_INSERT_BEFORE_TOKENS =
-    ["text", "paren.rparen", "punctuation.operator", "comment"];
-
-
-var autoInsertedBrackets = 0;
-var autoInsertedRow = -1;
-var autoInsertedLineEnd = "";
-var maybeInsertedBrackets = 0;
-var maybeInsertedRow = -1;
-var maybeInsertedLineStart = "";
-var maybeInsertedLineEnd = "";
-
-var CstyleBehaviour = function () {
-    
-    CstyleBehaviour.isSaneInsertion = function(editor, session) {
-        var cursor = editor.getCursorPosition();
-        var iterator = new TokenIterator(session, cursor.row, cursor.column);
-        if (!this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) {
-            var iterator2 = new TokenIterator(session, cursor.row, cursor.column + 1);
-            if (!this.$matchTokenType(iterator2.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS))
-                return false;
-        }
-        iterator.stepForward();
-        return iterator.getCurrentTokenRow() !== cursor.row ||
-            this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_BEFORE_TOKENS);
-    };
-    
-    CstyleBehaviour.$matchTokenType = function(token, types) {
-        return types.indexOf(token.type || token) > -1;
-    };
-    
-    CstyleBehaviour.recordAutoInsert = function(editor, session, bracket) {
-        var cursor = editor.getCursorPosition();
-        var line = session.doc.getLine(cursor.row);
-        if (!this.isAutoInsertedClosing(cursor, line, autoInsertedLineEnd[0]))
-            autoInsertedBrackets = 0;
-        autoInsertedRow = cursor.row;
-        autoInsertedLineEnd = bracket + line.substr(cursor.column);
-        autoInsertedBrackets++;
-    };
-    
-    CstyleBehaviour.recordMaybeInsert = function(editor, session, bracket) {
-        var cursor = editor.getCursorPosition();
-        var line = session.doc.getLine(cursor.row);
-        if (!this.isMaybeInsertedClosing(cursor, line))
-            maybeInsertedBrackets = 0;
-        maybeInsertedRow = cursor.row;
-        maybeInsertedLineStart = line.substr(0, cursor.column) + bracket;
-        maybeInsertedLineEnd = line.substr(cursor.column);
-        maybeInsertedBrackets++;
-    };
-    
-    CstyleBehaviour.isAutoInsertedClosing = function(cursor, line, bracket) {
-        return autoInsertedBrackets > 0 &&
-            cursor.row === autoInsertedRow &&
-            bracket === autoInsertedLineEnd[0] &&
-            line.substr(cursor.column) === autoInsertedLineEnd;
-    };
-    
-    CstyleBehaviour.isMaybeInsertedClosing = function(cursor, line) {
-        return maybeInsertedBrackets > 0 &&
-            cursor.row === maybeInsertedRow &&
-            line.substr(cursor.column) === maybeInsertedLineEnd &&
-            line.substr(0, cursor.column) == maybeInsertedLineStart;
-    };
-    
-    CstyleBehaviour.popAutoInsertedClosing = function() {
-        autoInsertedLineEnd = autoInsertedLineEnd.substr(1);
-        autoInsertedBrackets--;
-    };
-    
-    CstyleBehaviour.clearMaybeInsertedClosing = function() {
-        maybeInsertedBrackets = 0;
-        maybeInsertedRow = -1;
-    };
-
-    this.add("braces", "insertion", function (state, action, editor, session, text) {
-        var cursor = editor.getCursorPosition();
-        var line = session.doc.getLine(cursor.row);
-        if (text == '{') {
-            var selection = editor.getSelectionRange();
-            var selected = session.doc.getTextRange(selection);
-            if (selected !== "" && selected !== "{" && editor.getWrapBehavioursEnabled()) {
-                return {
-                    text: '{' + selected + '}',
-                    selection: false
-                };
-            } else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
-                if (/[\]\}\)]/.test(line[cursor.column])) {
-                    CstyleBehaviour.recordAutoInsert(editor, session, "}");
-                    return {
-                        text: '{}',
-                        selection: [1, 1]
-                    };
-                } else {
-                    CstyleBehaviour.recordMaybeInsert(editor, session, "{");
-                    return {
-                        text: '{',
-                        selection: [1, 1]
-                    };
-                }
-            }
-        } else if (text == '}') {
-            var rightChar = line.substring(cursor.column, cursor.column + 1);
-            if (rightChar == '}') {
-                var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row});
-                if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
-                    CstyleBehaviour.popAutoInsertedClosing();
-                    return {
-                        text: '',
-                        selection: [1, 1]
-                    };
-                }
-            }
-        } else if (text == "\n" || text == "\r\n") {
-            var closing = "";
-            if (CstyleBehaviour.isMaybeInsertedClosing(cursor, line)) {
-                closing = lang.stringRepeat("}", maybeInsertedBrackets);
-                CstyleBehaviour.clearMaybeInsertedClosing();
-            }
-            var rightChar = line.substring(cursor.column, cursor.column + 1);
-            if (rightChar == '}' || closing !== "") {
-                var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column}, '}');
-                if (!openBracePos)
-                     return null;
-
-                var indent = this.getNextLineIndent(state, line.substring(0, cursor.column), session.getTabString());
-                var next_indent = this.$getIndent(line);
-
-                return {
-                    text: '\n' + indent + '\n' + next_indent + closing,
-                    selection: [1, indent.length, 1, indent.length]
-                };
-            }
-        }
-    });
-
-    this.add("braces", "deletion", function (state, action, editor, session, range) {
-        var selected = session.doc.getTextRange(range);
-        if (!range.isMultiLine() && selected == '{') {
-            var line = session.doc.getLine(range.start.row);
-            var rightChar = line.substring(range.end.column, range.end.column + 1);
-            if (rightChar == '}') {
-                range.end.column++;
-                return range;
-            } else {
-                maybeInsertedBrackets--;
-            }
-        }
-    });
-
-    this.add("parens", "insertion", function (state, action, editor, session, text) {
-        if (text == '(') {
-            var selection = editor.getSelectionRange();
-            var selected = session.doc.getTextRange(selection);
-            if (selected !== "" && editor.getWrapBehavioursEnabled()) {
-                return {
-                    text: '(' + selected + ')',
-                    selection: false
-                };
-            } else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
-                CstyleBehaviour.recordAutoInsert(editor, session, ")");
-                return {
-                    text: '()',
-                    selection: [1, 1]
-                };
-            }
-        } else if (text == ')') {
-            var cursor = editor.getCursorPosition();
-            var line = session.doc.getLine(cursor.row);
-            var rightChar = line.substring(cursor.column, cursor.column + 1);
-            if (rightChar == ')') {
-                var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row});
-                if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
-                    CstyleBehaviour.popAutoInsertedClosing();
-                    return {
-                        text: '',
-                        selection: [1, 1]
-                    };
-                }
-            }
-        }
-    });
-
-    this.add("parens", "deletion", function (state, action, editor, session, range) {
-        var selected = session.doc.getTextRange(range);
-        if (!range.isMultiLine() && selected == '(') {
-            var line = session.doc.getLine(range.start.row);
-            var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
-            if (rightChar == ')') {
-                range.end.column++;
-                return range;
-            }
-        }
-    });
-
-    this.add("brackets", "insertion", function (state, action, editor, session, text) {
-        if (text == '[') {
-            var selection = editor.getSelectionRange();
-            var selected = session.doc.getTextRange(selection);
-            if (selected !== "" && editor.getWrapBehavioursEnabled()) {
-                return {
-                    text: '[' + selected + ']',
-                    selection: false
-                };
-            } else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
-                CstyleBehaviour.recordAutoInsert(editor, session, "]");
-                return {
-                    text: '[]',
-                    selection: [1, 1]
-                };
-            }
-        } else if (text == ']') {
-            var cursor = editor.getCursorPosition();
-            var line = session.doc.getLine(cursor.row);
-            var rightChar = line.substring(cursor.column, cursor.column + 1);
-            if (rightChar == ']') {
-                var matching = session.$findOpeningBracket(']', {column: cursor.column + 1, row: cursor.row});
-                if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
-                    CstyleBehaviour.popAutoInsertedClosing();
-                    return {
-                        text: '',
-                        selection: [1, 1]
-                    };
-                }
-            }
-        }
-    });
-
-    this.add("brackets", "deletion", function (state, action, editor, session, range) {
-        var selected = session.doc.getTextRange(range);
-        if (!range.isMultiLine() && selected == '[') {
-            var line = session.doc.getLine(range.start.row);
-            var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
-            if (rightChar == ']') {
-                range.end.column++;
-                return range;
-            }
-        }
-    });
-
-    this.add("string_dquotes", "insertion", function (state, action, editor, session, text) {
-        if (text == '"' || text == "'") {
-            var quote = text;
-            var selection = editor.getSelectionRange();
-            var selected = session.doc.getTextRange(selection);
-            if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) {
-                return {
-                    text: quote + selected + quote,
-                    selection: false
-                };
-            } else {
-                var cursor = editor.getCursorPosition();
-                var line = session.doc.getLine(cursor.row);
-                var leftChar = line.substring(cursor.column-1, cursor.column);
-                if (leftChar == '\\') {
-                    return null;
-                }
-                var tokens = session.getTokens(selection.start.row);
-                var col = 0, token;
-                var quotepos = -1; // Track whether we're inside an open quote.
-
-                for (var x = 0; x < tokens.length; x++) {
-                    token = tokens[x];
-                    if (token.type == "string") {
-                      quotepos = -1;
-                    } else if (quotepos < 0) {
-                      quotepos = token.value.indexOf(quote);
-                    }
-                    if ((token.value.length + col) > selection.start.column) {
-                        break;
-                    }
-                    col += tokens[x].value.length;
-                }
-                if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) {
-                    if (!CstyleBehaviour.isSaneInsertion(editor, session))
-                        return;
-                    return {
-                        text: quote + quote,
-                        selection: [1,1]
-                    };
-                } else if (token && token.type === "string") {
-                    var rightChar = line.substring(cursor.column, cursor.column + 1);
-                    if (rightChar == quote) {
-                        return {
-                            text: '',
-                            selection: [1, 1]
-                        };
-                    }
-                }
-            }
-        }
-    });
-
-    this.add("string_dquotes", "deletion", function (state, action, editor, session, range) {
-        var selected = session.doc.getTextRange(range);
-        if (!range.isMultiLine() && (selected == '"' || selected == "'")) {
-            var line = session.doc.getLine(range.start.row);
-            var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
-            if (rightChar == selected) {
-                range.end.column++;
-                return range;
-            }
-        }
-    });
-
-};
-
-oop.inherits(CstyleBehaviour, Behaviour);
-
-exports.CstyleBehaviour = CstyleBehaviour;
-});
-
-define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) {
-
-
-var oop = require("../../lib/oop");
-var Range = require("../../range").Range;
-var BaseFoldMode = require("./fold_mode").FoldMode;
-
-var FoldMode = exports.FoldMode = function(commentRegex) {
-    if (commentRegex) {
-        this.foldingStartMarker = new RegExp(
-            this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start)
-        );
-        this.foldingStopMarker = new RegExp(
-            this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end)
-        );
-    }
-};
-oop.inherits(FoldMode, BaseFoldMode);
-
-(function() {
-
-    this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/;
-    this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/;
-
-    this.getFoldWidgetRange = function(session, foldStyle, row) {
-        var line = session.getLine(row);
-        var match = line.match(this.foldingStartMarker);
-        if (match) {
-            var i = match.index;
-
-            if (match[1])
-                return this.openingBracketBlock(session, match[1], row, i);
-
-            return session.getCommentFoldRange(row, i + match[0].length, 1);
-        }
-
-        if (foldStyle !== "markbeginend")
-            return;
-
-        var match = line.match(this.foldingStopMarker);
-        if (match) {
-            var i = match.index + match[0].length;
-
-            if (match[1])
-                return this.closingBracketBlock(session, match[1], row, i);
-
-            return session.getCommentFoldRange(row, i, -1);
-        }
-    };
-
-}).call(FoldMode.prototype);
-
-});


[62/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/unistr.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/unistr.h b/src/apps/couch_collate/platform/osx/icu/unicode/unistr.h
new file mode 100644
index 0000000..9a96bdc
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/unistr.h
@@ -0,0 +1,4230 @@
+/*
+**********************************************************************
+*   Copyright (C) 1998-2008, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+**********************************************************************
+*
+* File unistr.h
+*
+* Modification History:
+*
+*   Date        Name        Description
+*   09/25/98    stephen     Creation.
+*   11/11/98    stephen     Changed per 11/9 code review.
+*   04/20/99    stephen     Overhauled per 4/16 code review.
+*   11/18/99    aliu        Made to inherit from Replaceable.  Added method
+*                           handleReplaceBetween(); other methods unchanged.
+*   06/25/01    grhoten     Remove dependency on iostream.
+******************************************************************************
+*/
+
+#ifndef UNISTR_H
+#define UNISTR_H
+
+/**
+ * \file 
+ * \brief C++ API: Unicode String 
+ */
+
+#include "unicode/rep.h"
+
+struct UConverter;          // unicode/ucnv.h
+class  StringThreadTest;
+
+#ifndef U_COMPARE_CODE_POINT_ORDER
+/* see also ustring.h and unorm.h */
+/**
+ * Option bit for u_strCaseCompare, u_strcasecmp, unorm_compare, etc:
+ * Compare strings in code point order instead of code unit order.
+ * @stable ICU 2.2
+ */
+#define U_COMPARE_CODE_POINT_ORDER  0x8000
+#endif
+
+#ifndef USTRING_H
+/**
+ * \ingroup ustring_ustrlen
+ */
+U_STABLE int32_t U_EXPORT2
+u_strlen(const UChar *s);
+#endif
+
+U_NAMESPACE_BEGIN
+
+class Locale;               // unicode/locid.h
+class StringCharacterIterator;
+class BreakIterator;        // unicode/brkiter.h
+
+/* The <iostream> include has been moved to unicode/ustream.h */
+
+/**
+ * Constant to be used in the UnicodeString(char *, int32_t, EInvariant) constructor
+ * which constructs a Unicode string from an invariant-character char * string.
+ * About invariant characters see utypes.h.
+ * This constructor has no runtime dependency on conversion code and is
+ * therefore recommended over ones taking a charset name string
+ * (where the empty string "" indicates invariant-character conversion).
+ *
+ * @stable ICU 3.2
+ */
+#define US_INV U_NAMESPACE_QUALIFIER UnicodeString::kInvariant
+
+/**
+ * Unicode String literals in C++.
+ * Dependent on the platform properties, different UnicodeString
+ * constructors should be used to create a UnicodeString object from
+ * a string literal.
+ * The macros are defined for maximum performance.
+ * They work only for strings that contain "invariant characters", i.e.,
+ * only latin letters, digits, and some punctuation.
+ * See utypes.h for details.
+ *
+ * The string parameter must be a C string literal.
+ * The length of the string, not including the terminating
+ * <code>NUL</code>, must be specified as a constant.
+ * The U_STRING_DECL macro should be invoked exactly once for one
+ * such string variable before it is used.
+ * @stable ICU 2.0
+ */
+#if defined(U_DECLARE_UTF16)
+#   define UNICODE_STRING(cs, _length) U_NAMESPACE_QUALIFIER UnicodeString(TRUE, (const UChar *)U_DECLARE_UTF16(cs), _length)
+#elif U_SIZEOF_WCHAR_T==U_SIZEOF_UCHAR && (U_CHARSET_FAMILY==U_ASCII_FAMILY || (U_SIZEOF_UCHAR == 2 && defined(U_WCHAR_IS_UTF16)))
+#   define UNICODE_STRING(cs, _length) U_NAMESPACE_QUALIFIER UnicodeString(TRUE, (const UChar *)L ## cs, _length)
+#elif U_SIZEOF_UCHAR==1 && U_CHARSET_FAMILY==U_ASCII_FAMILY
+#   define UNICODE_STRING(cs, _length) U_NAMESPACE_QUALIFIER UnicodeString(TRUE, (const UChar *)cs, _length)
+#else
+#   define UNICODE_STRING(cs, _length) U_NAMESPACE_QUALIFIER UnicodeString(cs, _length, US_INV)
+#endif
+
+/**
+ * Unicode String literals in C++.
+ * Dependent on the platform properties, different UnicodeString
+ * constructors should be used to create a UnicodeString object from
+ * a string literal.
+ * The macros are defined for improved performance.
+ * They work only for strings that contain "invariant characters", i.e.,
+ * only latin letters, digits, and some punctuation.
+ * See utypes.h for details.
+ *
+ * The string parameter must be a C string literal.
+ * @stable ICU 2.0
+ */
+#define UNICODE_STRING_SIMPLE(cs) UNICODE_STRING(cs, -1)
+
+/**
+ * UnicodeString is a string class that stores Unicode characters directly and provides
+ * similar functionality as the Java String and StringBuffer classes.
+ * It is a concrete implementation of the abstract class Replaceable (for transliteration).
+ *
+ * The UnicodeString class is not suitable for subclassing.
+ *
+ * <p>For an overview of Unicode strings in C and C++ see the
+ * <a href="http://icu-project.org/userguide/strings.html">User Guide Strings chapter</a>.</p>
+ *
+ * <p>In ICU, a Unicode string consists of 16-bit Unicode <em>code units</em>.
+ * A Unicode character may be stored with either one code unit
+ * (the most common case) or with a matched pair of special code units
+ * ("surrogates"). The data type for code units is UChar. 
+ * For single-character handling, a Unicode character code <em>point</em> is a value
+ * in the range 0..0x10ffff. ICU uses the UChar32 type for code points.</p>
+ *
+ * <p>Indexes and offsets into and lengths of strings always count code units, not code points.
+ * This is the same as with multi-byte char* strings in traditional string handling.
+ * Operations on partial strings typically do not test for code point boundaries.
+ * If necessary, the user needs to take care of such boundaries by testing for the code unit
+ * values or by using functions like
+ * UnicodeString::getChar32Start() and UnicodeString::getChar32Limit()
+ * (or, in C, the equivalent macros U16_SET_CP_START() and U16_SET_CP_LIMIT(), see utf.h).</p>
+ *
+ * UnicodeString methods are more lenient with regard to input parameter values
+ * than other ICU APIs. In particular:
+ * - If indexes are out of bounds for a UnicodeString object
+ *   (<0 or >length()) then they are "pinned" to the nearest boundary.
+ * - If primitive string pointer values (e.g., const UChar * or char *)
+ *   for input strings are NULL, then those input string parameters are treated
+ *   as if they pointed to an empty string.
+ *   However, this is <em>not</em> the case for char * parameters for charset names
+ *   or other IDs.
+ * - Most UnicodeString methods do not take a UErrorCode parameter because
+ *   there are usually very few opportunities for failure other than a shortage
+ *   of memory, error codes in low-level C++ string methods would be inconvenient,
+ *   and the error code as the last parameter (ICU convention) would prevent
+ *   the use of default parameter values.
+ *   Instead, such methods set the UnicodeString into a "bogus" state
+ *   (see isBogus()) if an error occurs.
+ *
+ * In string comparisons, two UnicodeString objects that are both "bogus"
+ * compare equal (to be transitive and prevent endless loops in sorting),
+ * and a "bogus" string compares less than any non-"bogus" one.
+ *
+ * Const UnicodeString methods are thread-safe. Multiple threads can use
+ * const methods on the same UnicodeString object simultaneously,
+ * but non-const methods must not be called concurrently (in multiple threads)
+ * with any other (const or non-const) methods.
+ *
+ * Similarly, const UnicodeString & parameters are thread-safe.
+ * One object may be passed in as such a parameter concurrently in multiple threads.
+ * This includes the const UnicodeString & parameters for
+ * copy construction, assignment, and cloning.
+ *
+ * <p>UnicodeString uses several storage methods.
+ * String contents can be stored inside the UnicodeString object itself,
+ * in an allocated and shared buffer, or in an outside buffer that is "aliased".
+ * Most of this is done transparently, but careful aliasing in particular provides
+ * significant performance improvements.
+ * Also, the internal buffer is accessible via special functions.
+ * For details see the
+ * <a href="http://icu-project.org/userguide/strings.html">User Guide Strings chapter</a>.</p>
+ *
+ * @see utf.h
+ * @see CharacterIterator
+ * @stable ICU 2.0
+ */
+class U_COMMON_API UnicodeString : public Replaceable
+{
+public:
+
+  /**
+   * Constant to be used in the UnicodeString(char *, int32_t, EInvariant) constructor
+   * which constructs a Unicode string from an invariant-character char * string.
+   * Use the macro US_INV instead of the full qualification for this value.
+   *
+   * @see US_INV
+   * @stable ICU 3.2
+   */
+  enum EInvariant {
+    /**
+     * @see EInvariant
+     * @stable ICU 3.2
+     */
+    kInvariant
+  };
+
+  //========================================
+  // Read-only operations
+  //========================================
+
+  /* Comparison - bitwise only - for international comparison use collation */
+
+  /**
+   * Equality operator. Performs only bitwise comparison.
+   * @param text The UnicodeString to compare to this one.
+   * @return TRUE if <TT>text</TT> contains the same characters as this one,
+   * FALSE otherwise.
+   * @stable ICU 2.0
+   */
+  inline UBool operator== (const UnicodeString& text) const;
+
+  /**
+   * Inequality operator. Performs only bitwise comparison.
+   * @param text The UnicodeString to compare to this one.
+   * @return FALSE if <TT>text</TT> contains the same characters as this one,
+   * TRUE otherwise.
+   * @stable ICU 2.0
+   */
+  inline UBool operator!= (const UnicodeString& text) const;
+
+  /**
+   * Greater than operator. Performs only bitwise comparison.
+   * @param text The UnicodeString to compare to this one.
+   * @return TRUE if the characters in this are bitwise
+   * greater than the characters in <code>text</code>, FALSE otherwise
+   * @stable ICU 2.0
+   */
+  inline UBool operator> (const UnicodeString& text) const;
+
+  /**
+   * Less than operator. Performs only bitwise comparison.
+   * @param text The UnicodeString to compare to this one.
+   * @return TRUE if the characters in this are bitwise
+   * less than the characters in <code>text</code>, FALSE otherwise
+   * @stable ICU 2.0
+   */
+  inline UBool operator< (const UnicodeString& text) const;
+
+  /**
+   * Greater than or equal operator. Performs only bitwise comparison.
+   * @param text The UnicodeString to compare to this one.
+   * @return TRUE if the characters in this are bitwise
+   * greater than or equal to the characters in <code>text</code>, FALSE otherwise
+   * @stable ICU 2.0
+   */
+  inline UBool operator>= (const UnicodeString& text) const;
+
+  /**
+   * Less than or equal operator. Performs only bitwise comparison.
+   * @param text The UnicodeString to compare to this one.
+   * @return TRUE if the characters in this are bitwise
+   * less than or equal to the characters in <code>text</code>, FALSE otherwise
+   * @stable ICU 2.0
+   */
+  inline UBool operator<= (const UnicodeString& text) const;
+
+  /**
+   * Compare the characters bitwise in this UnicodeString to
+   * the characters in <code>text</code>.
+   * @param text The UnicodeString to compare to this one.
+   * @return The result of bitwise character comparison: 0 if this
+   * contains the same characters as <code>text</code>, -1 if the characters in
+   * this are bitwise less than the characters in <code>text</code>, +1 if the
+   * characters in this are bitwise greater than the characters
+   * in <code>text</code>.
+   * @stable ICU 2.0
+   */
+  inline int8_t compare(const UnicodeString& text) const;
+
+  /**
+   * Compare the characters bitwise in the range
+   * [<TT>start</TT>, <TT>start + length</TT>) with the characters
+   * in <TT>text</TT>
+   * @param start the offset at which the compare operation begins
+   * @param length the number of characters of text to compare.
+   * @param text the other text to be compared against this string.
+   * @return The result of bitwise character comparison: 0 if this
+   * contains the same characters as <code>text</code>, -1 if the characters in
+   * this are bitwise less than the characters in <code>text</code>, +1 if the
+   * characters in this are bitwise greater than the characters
+   * in <code>text</code>.
+   * @stable ICU 2.0
+   */
+  inline int8_t compare(int32_t start,
+         int32_t length,
+         const UnicodeString& text) const;
+
+  /**
+   * Compare the characters bitwise in the range
+   * [<TT>start</TT>, <TT>start + length</TT>) with the characters
+   * in <TT>srcText</TT> in the range
+   * [<TT>srcStart</TT>, <TT>srcStart + srcLength</TT>).
+   * @param start the offset at which the compare operation begins
+   * @param length the number of characters in this to compare.
+   * @param srcText the text to be compared
+   * @param srcStart the offset into <TT>srcText</TT> to start comparison
+   * @param srcLength the number of characters in <TT>src</TT> to compare
+   * @return The result of bitwise character comparison: 0 if this
+   * contains the same characters as <code>srcText</code>, -1 if the characters in
+   * this are bitwise less than the characters in <code>srcText</code>, +1 if the
+   * characters in this are bitwise greater than the characters
+   * in <code>srcText</code>.
+   * @stable ICU 2.0
+   */
+   inline int8_t compare(int32_t start,
+         int32_t length,
+         const UnicodeString& srcText,
+         int32_t srcStart,
+         int32_t srcLength) const;
+
+  /**
+   * Compare the characters bitwise in this UnicodeString with the first
+   * <TT>srcLength</TT> characters in <TT>srcChars</TT>.
+   * @param srcChars The characters to compare to this UnicodeString.
+   * @param srcLength the number of characters in <TT>srcChars</TT> to compare
+   * @return The result of bitwise character comparison: 0 if this
+   * contains the same characters as <code>srcChars</code>, -1 if the characters in
+   * this are bitwise less than the characters in <code>srcChars</code>, +1 if the
+   * characters in this are bitwise greater than the characters
+   * in <code>srcChars</code>.
+   * @stable ICU 2.0
+   */
+  inline int8_t compare(const UChar *srcChars,
+         int32_t srcLength) const;
+
+  /**
+   * Compare the characters bitwise in the range
+   * [<TT>start</TT>, <TT>start + length</TT>) with the first
+   * <TT>length</TT> characters in <TT>srcChars</TT>
+   * @param start the offset at which the compare operation begins
+   * @param length the number of characters to compare.
+   * @param srcChars the characters to be compared
+   * @return The result of bitwise character comparison: 0 if this
+   * contains the same characters as <code>srcChars</code>, -1 if the characters in
+   * this are bitwise less than the characters in <code>srcChars</code>, +1 if the
+   * characters in this are bitwise greater than the characters
+   * in <code>srcChars</code>.
+   * @stable ICU 2.0
+   */
+  inline int8_t compare(int32_t start,
+         int32_t length,
+         const UChar *srcChars) const;
+
+  /**
+   * Compare the characters bitwise in the range
+   * [<TT>start</TT>, <TT>start + length</TT>) with the characters
+   * in <TT>srcChars</TT> in the range
+   * [<TT>srcStart</TT>, <TT>srcStart + srcLength</TT>).
+   * @param start the offset at which the compare operation begins
+   * @param length the number of characters in this to compare
+   * @param srcChars the characters to be compared
+   * @param srcStart the offset into <TT>srcChars</TT> to start comparison
+   * @param srcLength the number of characters in <TT>srcChars</TT> to compare
+   * @return The result of bitwise character comparison: 0 if this
+   * contains the same characters as <code>srcChars</code>, -1 if the characters in
+   * this are bitwise less than the characters in <code>srcChars</code>, +1 if the
+   * characters in this are bitwise greater than the characters
+   * in <code>srcChars</code>.
+   * @stable ICU 2.0
+   */
+  inline int8_t compare(int32_t start,
+         int32_t length,
+         const UChar *srcChars,
+         int32_t srcStart,
+         int32_t srcLength) const;
+
+  /**
+   * Compare the characters bitwise in the range
+   * [<TT>start</TT>, <TT>limit</TT>) with the characters
+   * in <TT>srcText</TT> in the range
+   * [<TT>srcStart</TT>, <TT>srcLimit</TT>).
+   * @param start the offset at which the compare operation begins
+   * @param limit the offset immediately following the compare operation
+   * @param srcText the text to be compared
+   * @param srcStart the offset into <TT>srcText</TT> to start comparison
+   * @param srcLimit the offset into <TT>srcText</TT> to limit comparison
+   * @return The result of bitwise character comparison: 0 if this
+   * contains the same characters as <code>srcText</code>, -1 if the characters in
+   * this are bitwise less than the characters in <code>srcText</code>, +1 if the
+   * characters in this are bitwise greater than the characters
+   * in <code>srcText</code>.
+   * @stable ICU 2.0
+   */
+  inline int8_t compareBetween(int32_t start,
+            int32_t limit,
+            const UnicodeString& srcText,
+            int32_t srcStart,
+            int32_t srcLimit) const;
+
+  /**
+   * Compare two Unicode strings in code point order.
+   * The result may be different from the results of compare(), operator<, etc.
+   * if supplementary characters are present:
+   *
+   * In UTF-16, supplementary characters (with code points U+10000 and above) are
+   * stored with pairs of surrogate code units. These have values from 0xd800 to 0xdfff,
+   * which means that they compare as less than some other BMP characters like U+feff.
+   * This function compares Unicode strings in code point order.
+   * If either of the UTF-16 strings is malformed (i.e., it contains unpaired surrogates), then the result is not defined.
+   *
+   * @param text Another string to compare this one to.
+   * @return a negative/zero/positive integer corresponding to whether
+   * this string is less than/equal to/greater than the second one
+   * in code point order
+   * @stable ICU 2.0
+   */
+  inline int8_t compareCodePointOrder(const UnicodeString& text) const;
+
+  /**
+   * Compare two Unicode strings in code point order.
+   * The result may be different from the results of compare(), operator<, etc.
+   * if supplementary characters are present:
+   *
+   * In UTF-16, supplementary characters (with code points U+10000 and above) are
+   * stored with pairs of surrogate code units. These have values from 0xd800 to 0xdfff,
+   * which means that they compare as less than some other BMP characters like U+feff.
+   * This function compares Unicode strings in code point order.
+   * If either of the UTF-16 strings is malformed (i.e., it contains unpaired surrogates), then the result is not defined.
+   *
+   * @param start The start offset in this string at which the compare operation begins.
+   * @param length The number of code units from this string to compare.
+   * @param srcText Another string to compare this one to.
+   * @return a negative/zero/positive integer corresponding to whether
+   * this string is less than/equal to/greater than the second one
+   * in code point order
+   * @stable ICU 2.0
+   */
+  inline int8_t compareCodePointOrder(int32_t start,
+                                      int32_t length,
+                                      const UnicodeString& srcText) const;
+
+  /**
+   * Compare two Unicode strings in code point order.
+   * The result may be different from the results of compare(), operator<, etc.
+   * if supplementary characters are present:
+   *
+   * In UTF-16, supplementary characters (with code points U+10000 and above) are
+   * stored with pairs of surrogate code units. These have values from 0xd800 to 0xdfff,
+   * which means that they compare as less than some other BMP characters like U+feff.
+   * This function compares Unicode strings in code point order.
+   * If either of the UTF-16 strings is malformed (i.e., it contains unpaired surrogates), then the result is not defined.
+   *
+   * @param start The start offset in this string at which the compare operation begins.
+   * @param length The number of code units from this string to compare.
+   * @param srcText Another string to compare this one to.
+   * @param srcStart The start offset in that string at which the compare operation begins.
+   * @param srcLength The number of code units from that string to compare.
+   * @return a negative/zero/positive integer corresponding to whether
+   * this string is less than/equal to/greater than the second one
+   * in code point order
+   * @stable ICU 2.0
+   */
+   inline int8_t compareCodePointOrder(int32_t start,
+                                       int32_t length,
+                                       const UnicodeString& srcText,
+                                       int32_t srcStart,
+                                       int32_t srcLength) const;
+
+  /**
+   * Compare two Unicode strings in code point order.
+   * The result may be different from the results of compare(), operator<, etc.
+   * if supplementary characters are present:
+   *
+   * In UTF-16, supplementary characters (with code points U+10000 and above) are
+   * stored with pairs of surrogate code units. These have values from 0xd800 to 0xdfff,
+   * which means that they compare as less than some other BMP characters like U+feff.
+   * This function compares Unicode strings in code point order.
+   * If either of the UTF-16 strings is malformed (i.e., it contains unpaired surrogates), then the result is not defined.
+   *
+   * @param srcChars A pointer to another string to compare this one to.
+   * @param srcLength The number of code units from that string to compare.
+   * @return a negative/zero/positive integer corresponding to whether
+   * this string is less than/equal to/greater than the second one
+   * in code point order
+   * @stable ICU 2.0
+   */
+  inline int8_t compareCodePointOrder(const UChar *srcChars,
+                                      int32_t srcLength) const;
+
+  /**
+   * Compare two Unicode strings in code point order.
+   * The result may be different from the results of compare(), operator<, etc.
+   * if supplementary characters are present:
+   *
+   * In UTF-16, supplementary characters (with code points U+10000 and above) are
+   * stored with pairs of surrogate code units. These have values from 0xd800 to 0xdfff,
+   * which means that they compare as less than some other BMP characters like U+feff.
+   * This function compares Unicode strings in code point order.
+   * If either of the UTF-16 strings is malformed (i.e., it contains unpaired surrogates), then the result is not defined.
+   *
+   * @param start The start offset in this string at which the compare operation begins.
+   * @param length The number of code units from this string to compare.
+   * @param srcChars A pointer to another string to compare this one to.
+   * @return a negative/zero/positive integer corresponding to whether
+   * this string is less than/equal to/greater than the second one
+   * in code point order
+   * @stable ICU 2.0
+   */
+  inline int8_t compareCodePointOrder(int32_t start,
+                                      int32_t length,
+                                      const UChar *srcChars) const;
+
+  /**
+   * Compare two Unicode strings in code point order.
+   * The result may be different from the results of compare(), operator<, etc.
+   * if supplementary characters are present:
+   *
+   * In UTF-16, supplementary characters (with code points U+10000 and above) are
+   * stored with pairs of surrogate code units. These have values from 0xd800 to 0xdfff,
+   * which means that they compare as less than some other BMP characters like U+feff.
+   * This function compares Unicode strings in code point order.
+   * If either of the UTF-16 strings is malformed (i.e., it contains unpaired surrogates), then the result is not defined.
+   *
+   * @param start The start offset in this string at which the compare operation begins.
+   * @param length The number of code units from this string to compare.
+   * @param srcChars A pointer to another string to compare this one to.
+   * @param srcStart The start offset in that string at which the compare operation begins.
+   * @param srcLength The number of code units from that string to compare.
+   * @return a negative/zero/positive integer corresponding to whether
+   * this string is less than/equal to/greater than the second one
+   * in code point order
+   * @stable ICU 2.0
+   */
+  inline int8_t compareCodePointOrder(int32_t start,
+                                      int32_t length,
+                                      const UChar *srcChars,
+                                      int32_t srcStart,
+                                      int32_t srcLength) const;
+
+  /**
+   * Compare two Unicode strings in code point order.
+   * The result may be different from the results of compare(), operator<, etc.
+   * if supplementary characters are present:
+   *
+   * In UTF-16, supplementary characters (with code points U+10000 and above) are
+   * stored with pairs of surrogate code units. These have values from 0xd800 to 0xdfff,
+   * which means that they compare as less than some other BMP characters like U+feff.
+   * This function compares Unicode strings in code point order.
+   * If either of the UTF-16 strings is malformed (i.e., it contains unpaired surrogates), then the result is not defined.
+   *
+   * @param start The start offset in this string at which the compare operation begins.
+   * @param limit The offset after the last code unit from this string to compare.
+   * @param srcText Another string to compare this one to.
+   * @param srcStart The start offset in that string at which the compare operation begins.
+   * @param srcLimit The offset after the last code unit from that string to compare.
+   * @return a negative/zero/positive integer corresponding to whether
+   * this string is less than/equal to/greater than the second one
+   * in code point order
+   * @stable ICU 2.0
+   */
+  inline int8_t compareCodePointOrderBetween(int32_t start,
+                                             int32_t limit,
+                                             const UnicodeString& srcText,
+                                             int32_t srcStart,
+                                             int32_t srcLimit) const;
+
+  /**
+   * Compare two strings case-insensitively using full case folding.
+   * This is equivalent to this->foldCase(options).compare(text.foldCase(options)).
+   *
+   * @param text Another string to compare this one to.
+   * @param options A bit set of options:
+   *   - U_FOLD_CASE_DEFAULT or 0 is used for default options:
+   *     Comparison in code unit order with default case folding.
+   *
+   *   - U_COMPARE_CODE_POINT_ORDER
+   *     Set to choose code point order instead of code unit order
+   *     (see u_strCompare for details).
+   *
+   *   - U_FOLD_CASE_EXCLUDE_SPECIAL_I
+   *
+   * @return A negative, zero, or positive integer indicating the comparison result.
+   * @stable ICU 2.0
+   */
+  inline int8_t caseCompare(const UnicodeString& text, uint32_t options) const;
+
+  /**
+   * Compare two strings case-insensitively using full case folding.
+   * This is equivalent to this->foldCase(options).compare(srcText.foldCase(options)).
+   *
+   * @param start The start offset in this string at which the compare operation begins.
+   * @param length The number of code units from this string to compare.
+   * @param srcText Another string to compare this one to.
+   * @param options A bit set of options:
+   *   - U_FOLD_CASE_DEFAULT or 0 is used for default options:
+   *     Comparison in code unit order with default case folding.
+   *
+   *   - U_COMPARE_CODE_POINT_ORDER
+   *     Set to choose code point order instead of code unit order
+   *     (see u_strCompare for details).
+   *
+   *   - U_FOLD_CASE_EXCLUDE_SPECIAL_I
+   *
+   * @return A negative, zero, or positive integer indicating the comparison result.
+   * @stable ICU 2.0
+   */
+  inline int8_t caseCompare(int32_t start,
+         int32_t length,
+         const UnicodeString& srcText,
+         uint32_t options) const;
+
+  /**
+   * Compare two strings case-insensitively using full case folding.
+   * This is equivalent to this->foldCase(options).compare(srcText.foldCase(options)).
+   *
+   * @param start The start offset in this string at which the compare operation begins.
+   * @param length The number of code units from this string to compare.
+   * @param srcText Another string to compare this one to.
+   * @param srcStart The start offset in that string at which the compare operation begins.
+   * @param srcLength The number of code units from that string to compare.
+   * @param options A bit set of options:
+   *   - U_FOLD_CASE_DEFAULT or 0 is used for default options:
+   *     Comparison in code unit order with default case folding.
+   *
+   *   - U_COMPARE_CODE_POINT_ORDER
+   *     Set to choose code point order instead of code unit order
+   *     (see u_strCompare for details).
+   *
+   *   - U_FOLD_CASE_EXCLUDE_SPECIAL_I
+   *
+   * @return A negative, zero, or positive integer indicating the comparison result.
+   * @stable ICU 2.0
+   */
+  inline int8_t caseCompare(int32_t start,
+         int32_t length,
+         const UnicodeString& srcText,
+         int32_t srcStart,
+         int32_t srcLength,
+         uint32_t options) const;
+
+  /**
+   * Compare two strings case-insensitively using full case folding.
+   * This is equivalent to this->foldCase(options).compare(srcChars.foldCase(options)).
+   *
+   * @param srcChars A pointer to another string to compare this one to.
+   * @param srcLength The number of code units from that string to compare.
+   * @param options A bit set of options:
+   *   - U_FOLD_CASE_DEFAULT or 0 is used for default options:
+   *     Comparison in code unit order with default case folding.
+   *
+   *   - U_COMPARE_CODE_POINT_ORDER
+   *     Set to choose code point order instead of code unit order
+   *     (see u_strCompare for details).
+   *
+   *   - U_FOLD_CASE_EXCLUDE_SPECIAL_I
+   *
+   * @return A negative, zero, or positive integer indicating the comparison result.
+   * @stable ICU 2.0
+   */
+  inline int8_t caseCompare(const UChar *srcChars,
+         int32_t srcLength,
+         uint32_t options) const;
+
+  /**
+   * Compare two strings case-insensitively using full case folding.
+   * This is equivalent to this->foldCase(options).compare(srcChars.foldCase(options)).
+   *
+   * @param start The start offset in this string at which the compare operation begins.
+   * @param length The number of code units from this string to compare.
+   * @param srcChars A pointer to another string to compare this one to.
+   * @param options A bit set of options:
+   *   - U_FOLD_CASE_DEFAULT or 0 is used for default options:
+   *     Comparison in code unit order with default case folding.
+   *
+   *   - U_COMPARE_CODE_POINT_ORDER
+   *     Set to choose code point order instead of code unit order
+   *     (see u_strCompare for details).
+   *
+   *   - U_FOLD_CASE_EXCLUDE_SPECIAL_I
+   *
+   * @return A negative, zero, or positive integer indicating the comparison result.
+   * @stable ICU 2.0
+   */
+  inline int8_t caseCompare(int32_t start,
+         int32_t length,
+         const UChar *srcChars,
+         uint32_t options) const;
+
+  /**
+   * Compare two strings case-insensitively using full case folding.
+   * This is equivalent to this->foldCase(options).compare(srcChars.foldCase(options)).
+   *
+   * @param start The start offset in this string at which the compare operation begins.
+   * @param length The number of code units from this string to compare.
+   * @param srcChars A pointer to another string to compare this one to.
+   * @param srcStart The start offset in that string at which the compare operation begins.
+   * @param srcLength The number of code units from that string to compare.
+   * @param options A bit set of options:
+   *   - U_FOLD_CASE_DEFAULT or 0 is used for default options:
+   *     Comparison in code unit order with default case folding.
+   *
+   *   - U_COMPARE_CODE_POINT_ORDER
+   *     Set to choose code point order instead of code unit order
+   *     (see u_strCompare for details).
+   *
+   *   - U_FOLD_CASE_EXCLUDE_SPECIAL_I
+   *
+   * @return A negative, zero, or positive integer indicating the comparison result.
+   * @stable ICU 2.0
+   */
+  inline int8_t caseCompare(int32_t start,
+         int32_t length,
+         const UChar *srcChars,
+         int32_t srcStart,
+         int32_t srcLength,
+         uint32_t options) const;
+
+  /**
+   * Compare two strings case-insensitively using full case folding.
+   * This is equivalent to this->foldCase(options).compareBetween(text.foldCase(options)).
+   *
+   * @param start The start offset in this string at which the compare operation begins.
+   * @param limit The offset after the last code unit from this string to compare.
+   * @param srcText Another string to compare this one to.
+   * @param srcStart The start offset in that string at which the compare operation begins.
+   * @param srcLimit The offset after the last code unit from that string to compare.
+   * @param options A bit set of options:
+   *   - U_FOLD_CASE_DEFAULT or 0 is used for default options:
+   *     Comparison in code unit order with default case folding.
+   *
+   *   - U_COMPARE_CODE_POINT_ORDER
+   *     Set to choose code point order instead of code unit order
+   *     (see u_strCompare for details).
+   *
+   *   - U_FOLD_CASE_EXCLUDE_SPECIAL_I
+   *
+   * @return A negative, zero, or positive integer indicating the comparison result.
+   * @stable ICU 2.0
+   */
+  inline int8_t caseCompareBetween(int32_t start,
+            int32_t limit,
+            const UnicodeString& srcText,
+            int32_t srcStart,
+            int32_t srcLimit,
+            uint32_t options) const;
+
+  /**
+   * Determine if this starts with the characters in <TT>text</TT>
+   * @param text The text to match.
+   * @return TRUE if this starts with the characters in <TT>text</TT>,
+   * FALSE otherwise
+   * @stable ICU 2.0
+   */
+  inline UBool startsWith(const UnicodeString& text) const;
+
+  /**
+   * Determine if this starts with the characters in <TT>srcText</TT>
+   * in the range [<TT>srcStart</TT>, <TT>srcStart + srcLength</TT>).
+   * @param srcText The text to match.
+   * @param srcStart the offset into <TT>srcText</TT> to start matching
+   * @param srcLength the number of characters in <TT>srcText</TT> to match
+   * @return TRUE if this starts with the characters in <TT>text</TT>,
+   * FALSE otherwise
+   * @stable ICU 2.0
+   */
+  inline UBool startsWith(const UnicodeString& srcText,
+            int32_t srcStart,
+            int32_t srcLength) const;
+
+  /**
+   * Determine if this starts with the characters in <TT>srcChars</TT>
+   * @param srcChars The characters to match.
+   * @param srcLength the number of characters in <TT>srcChars</TT>
+   * @return TRUE if this starts with the characters in <TT>srcChars</TT>,
+   * FALSE otherwise
+   * @stable ICU 2.0
+   */
+  inline UBool startsWith(const UChar *srcChars,
+            int32_t srcLength) const;
+
+  /**
+   * Determine if this ends with the characters in <TT>srcChars</TT>
+   * in the range  [<TT>srcStart</TT>, <TT>srcStart + srcLength</TT>).
+   * @param srcChars The characters to match.
+   * @param srcStart the offset into <TT>srcText</TT> to start matching
+   * @param srcLength the number of characters in <TT>srcChars</TT> to match
+   * @return TRUE if this ends with the characters in <TT>srcChars</TT>, FALSE otherwise
+   * @stable ICU 2.0
+   */
+  inline UBool startsWith(const UChar *srcChars,
+            int32_t srcStart,
+            int32_t srcLength) const;
+
+  /**
+   * Determine if this ends with the characters in <TT>text</TT>
+   * @param text The text to match.
+   * @return TRUE if this ends with the characters in <TT>text</TT>,
+   * FALSE otherwise
+   * @stable ICU 2.0
+   */
+  inline UBool endsWith(const UnicodeString& text) const;
+
+  /**
+   * Determine if this ends with the characters in <TT>srcText</TT>
+   * in the range [<TT>srcStart</TT>, <TT>srcStart + srcLength</TT>).
+   * @param srcText The text to match.
+   * @param srcStart the offset into <TT>srcText</TT> to start matching
+   * @param srcLength the number of characters in <TT>srcText</TT> to match
+   * @return TRUE if this ends with the characters in <TT>text</TT>,
+   * FALSE otherwise
+   * @stable ICU 2.0
+   */
+  inline UBool endsWith(const UnicodeString& srcText,
+          int32_t srcStart,
+          int32_t srcLength) const;
+
+  /**
+   * Determine if this ends with the characters in <TT>srcChars</TT>
+   * @param srcChars The characters to match.
+   * @param srcLength the number of characters in <TT>srcChars</TT>
+   * @return TRUE if this ends with the characters in <TT>srcChars</TT>,
+   * FALSE otherwise
+   * @stable ICU 2.0
+   */
+  inline UBool endsWith(const UChar *srcChars,
+          int32_t srcLength) const;
+
+  /**
+   * Determine if this ends with the characters in <TT>srcChars</TT>
+   * in the range  [<TT>srcStart</TT>, <TT>srcStart + srcLength</TT>).
+   * @param srcChars The characters to match.
+   * @param srcStart the offset into <TT>srcText</TT> to start matching
+   * @param srcLength the number of characters in <TT>srcChars</TT> to match
+   * @return TRUE if this ends with the characters in <TT>srcChars</TT>,
+   * FALSE otherwise
+   * @stable ICU 2.0
+   */
+  inline UBool endsWith(const UChar *srcChars,
+          int32_t srcStart,
+          int32_t srcLength) const;
+
+
+  /* Searching - bitwise only */
+
+  /**
+   * Locate in this the first occurrence of the characters in <TT>text</TT>,
+   * using bitwise comparison.
+   * @param text The text to search for.
+   * @return The offset into this of the start of <TT>text</TT>,
+   * or -1 if not found.
+   * @stable ICU 2.0
+   */
+  inline int32_t indexOf(const UnicodeString& text) const;
+
+  /**
+   * Locate in this the first occurrence of the characters in <TT>text</TT>
+   * starting at offset <TT>start</TT>, using bitwise comparison.
+   * @param text The text to search for.
+   * @param start The offset at which searching will start.
+   * @return The offset into this of the start of <TT>text</TT>,
+   * or -1 if not found.
+   * @stable ICU 2.0
+   */
+  inline int32_t indexOf(const UnicodeString& text,
+              int32_t start) const;
+
+  /**
+   * Locate in this the first occurrence in the range
+   * [<TT>start</TT>, <TT>start + length</TT>) of the characters
+   * in <TT>text</TT>, using bitwise comparison.
+   * @param text The text to search for.
+   * @param start The offset at which searching will start.
+   * @param length The number of characters to search
+   * @return The offset into this of the start of <TT>text</TT>,
+   * or -1 if not found.
+   * @stable ICU 2.0
+   */
+  inline int32_t indexOf(const UnicodeString& text,
+              int32_t start,
+              int32_t length) const;
+
+  /**
+   * Locate in this the first occurrence in the range
+   * [<TT>start</TT>, <TT>start + length</TT>) of the characters
+   *  in <TT>srcText</TT> in the range
+   * [<TT>srcStart</TT>, <TT>srcStart + srcLength</TT>),
+   * using bitwise comparison.
+   * @param srcText The text to search for.
+   * @param srcStart the offset into <TT>srcText</TT> at which
+   * to start matching
+   * @param srcLength the number of characters in <TT>srcText</TT> to match
+   * @param start the offset into this at which to start matching
+   * @param length the number of characters in this to search
+   * @return The offset into this of the start of <TT>text</TT>,
+   * or -1 if not found.
+   * @stable ICU 2.0
+   */
+  inline int32_t indexOf(const UnicodeString& srcText,
+              int32_t srcStart,
+              int32_t srcLength,
+              int32_t start,
+              int32_t length) const;
+
+  /**
+   * Locate in this the first occurrence of the characters in
+   * <TT>srcChars</TT>
+   * starting at offset <TT>start</TT>, using bitwise comparison.
+   * @param srcChars The text to search for.
+   * @param srcLength the number of characters in <TT>srcChars</TT> to match
+   * @param start the offset into this at which to start matching
+   * @return The offset into this of the start of <TT>text</TT>,
+   * or -1 if not found.
+   * @stable ICU 2.0
+   */
+  inline int32_t indexOf(const UChar *srcChars,
+              int32_t srcLength,
+              int32_t start) const;
+
+  /**
+   * Locate in this the first occurrence in the range
+   * [<TT>start</TT>, <TT>start + length</TT>) of the characters
+   * in <TT>srcChars</TT>, using bitwise comparison.
+   * @param srcChars The text to search for.
+   * @param srcLength the number of characters in <TT>srcChars</TT>
+   * @param start The offset at which searching will start.
+   * @param length The number of characters to search
+   * @return The offset into this of the start of <TT>srcChars</TT>,
+   * or -1 if not found.
+   * @stable ICU 2.0
+   */
+  inline int32_t indexOf(const UChar *srcChars,
+              int32_t srcLength,
+              int32_t start,
+              int32_t length) const;
+
+  /**
+   * Locate in this the first occurrence in the range
+   * [<TT>start</TT>, <TT>start + length</TT>) of the characters
+   * in <TT>srcChars</TT> in the range
+   * [<TT>srcStart</TT>, <TT>srcStart + srcLength</TT>),
+   * using bitwise comparison.
+   * @param srcChars The text to search for.
+   * @param srcStart the offset into <TT>srcChars</TT> at which
+   * to start matching
+   * @param srcLength the number of characters in <TT>srcChars</TT> to match
+   * @param start the offset into this at which to start matching
+   * @param length the number of characters in this to search
+   * @return The offset into this of the start of <TT>text</TT>,
+   * or -1 if not found.
+   * @stable ICU 2.0
+   */
+  int32_t indexOf(const UChar *srcChars,
+              int32_t srcStart,
+              int32_t srcLength,
+              int32_t start,
+              int32_t length) const;
+
+  /**
+   * Locate in this the first occurrence of the BMP code point <code>c</code>,
+   * using bitwise comparison.
+   * @param c The code unit to search for.
+   * @return The offset into this of <TT>c</TT>, or -1 if not found.
+   * @stable ICU 2.0
+   */
+  inline int32_t indexOf(UChar c) const;
+
+  /**
+   * Locate in this the first occurrence of the code point <TT>c</TT>,
+   * using bitwise comparison.
+   *
+   * @param c The code point to search for.
+   * @return The offset into this of <TT>c</TT>, or -1 if not found.
+   * @stable ICU 2.0
+   */
+  inline int32_t indexOf(UChar32 c) const;
+
+  /**
+   * Locate in this the first occurrence of the BMP code point <code>c</code>,
+   * starting at offset <TT>start</TT>, using bitwise comparison.
+   * @param c The code unit to search for.
+   * @param start The offset at which searching will start.
+   * @return The offset into this of <TT>c</TT>, or -1 if not found.
+   * @stable ICU 2.0
+   */
+  inline int32_t indexOf(UChar c,
+              int32_t start) const;
+
+  /**
+   * Locate in this the first occurrence of the code point <TT>c</TT>
+   * starting at offset <TT>start</TT>, using bitwise comparison.
+   *
+   * @param c The code point to search for.
+   * @param start The offset at which searching will start.
+   * @return The offset into this of <TT>c</TT>, or -1 if not found.
+   * @stable ICU 2.0
+   */
+  inline int32_t indexOf(UChar32 c,
+              int32_t start) const;
+
+  /**
+   * Locate in this the first occurrence of the BMP code point <code>c</code>
+   * in the range [<TT>start</TT>, <TT>start + length</TT>),
+   * using bitwise comparison.
+   * @param c The code unit to search for.
+   * @param start the offset into this at which to start matching
+   * @param length the number of characters in this to search
+   * @return The offset into this of <TT>c</TT>, or -1 if not found.
+   * @stable ICU 2.0
+   */
+  inline int32_t indexOf(UChar c,
+              int32_t start,
+              int32_t length) const;
+
+  /**
+   * Locate in this the first occurrence of the code point <TT>c</TT>
+   * in the range [<TT>start</TT>, <TT>start + length</TT>),
+   * using bitwise comparison.
+   *
+   * @param c The code point to search for.
+   * @param start the offset into this at which to start matching
+   * @param length the number of characters in this to search
+   * @return The offset into this of <TT>c</TT>, or -1 if not found.
+   * @stable ICU 2.0
+   */
+  inline int32_t indexOf(UChar32 c,
+              int32_t start,
+              int32_t length) const;
+
+  /**
+   * Locate in this the last occurrence of the characters in <TT>text</TT>,
+   * using bitwise comparison.
+   * @param text The text to search for.
+   * @return The offset into this of the start of <TT>text</TT>,
+   * or -1 if not found.
+   * @stable ICU 2.0
+   */
+  inline int32_t lastIndexOf(const UnicodeString& text) const;
+
+  /**
+   * Locate in this the last occurrence of the characters in <TT>text</TT>
+   * starting at offset <TT>start</TT>, using bitwise comparison.
+   * @param text The text to search for.
+   * @param start The offset at which searching will start.
+   * @return The offset into this of the start of <TT>text</TT>,
+   * or -1 if not found.
+   * @stable ICU 2.0
+   */
+  inline int32_t lastIndexOf(const UnicodeString& text,
+              int32_t start) const;
+
+  /**
+   * Locate in this the last occurrence in the range
+   * [<TT>start</TT>, <TT>start + length</TT>) of the characters
+   * in <TT>text</TT>, using bitwise comparison.
+   * @param text The text to search for.
+   * @param start The offset at which searching will start.
+   * @param length The number of characters to search
+   * @return The offset into this of the start of <TT>text</TT>,
+   * or -1 if not found.
+   * @stable ICU 2.0
+   */
+  inline int32_t lastIndexOf(const UnicodeString& text,
+              int32_t start,
+              int32_t length) const;
+
+  /**
+   * Locate in this the last occurrence in the range
+   * [<TT>start</TT>, <TT>start + length</TT>) of the characters
+   * in <TT>srcText</TT> in the range
+   * [<TT>srcStart</TT>, <TT>srcStart + srcLength</TT>),
+   * using bitwise comparison.
+   * @param srcText The text to search for.
+   * @param srcStart the offset into <TT>srcText</TT> at which
+   * to start matching
+   * @param srcLength the number of characters in <TT>srcText</TT> to match
+   * @param start the offset into this at which to start matching
+   * @param length the number of characters in this to search
+   * @return The offset into this of the start of <TT>text</TT>,
+   * or -1 if not found.
+   * @stable ICU 2.0
+   */
+  inline int32_t lastIndexOf(const UnicodeString& srcText,
+              int32_t srcStart,
+              int32_t srcLength,
+              int32_t start,
+              int32_t length) const;
+
+  /**
+   * Locate in this the last occurrence of the characters in <TT>srcChars</TT>
+   * starting at offset <TT>start</TT>, using bitwise comparison.
+   * @param srcChars The text to search for.
+   * @param srcLength the number of characters in <TT>srcChars</TT> to match
+   * @param start the offset into this at which to start matching
+   * @return The offset into this of the start of <TT>text</TT>,
+   * or -1 if not found.
+   * @stable ICU 2.0
+   */
+  inline int32_t lastIndexOf(const UChar *srcChars,
+              int32_t srcLength,
+              int32_t start) const;
+
+  /**
+   * Locate in this the last occurrence in the range
+   * [<TT>start</TT>, <TT>start + length</TT>) of the characters
+   * in <TT>srcChars</TT>, using bitwise comparison.
+   * @param srcChars The text to search for.
+   * @param srcLength the number of characters in <TT>srcChars</TT>
+   * @param start The offset at which searching will start.
+   * @param length The number of characters to search
+   * @return The offset into this of the start of <TT>srcChars</TT>,
+   * or -1 if not found.
+   * @stable ICU 2.0
+   */
+  inline int32_t lastIndexOf(const UChar *srcChars,
+              int32_t srcLength,
+              int32_t start,
+              int32_t length) const;
+
+  /**
+   * Locate in this the last occurrence in the range
+   * [<TT>start</TT>, <TT>start + length</TT>) of the characters
+   * in <TT>srcChars</TT> in the range
+   * [<TT>srcStart</TT>, <TT>srcStart + srcLength</TT>),
+   * using bitwise comparison.
+   * @param srcChars The text to search for.
+   * @param srcStart the offset into <TT>srcChars</TT> at which
+   * to start matching
+   * @param srcLength the number of characters in <TT>srcChars</TT> to match
+   * @param start the offset into this at which to start matching
+   * @param length the number of characters in this to search
+   * @return The offset into this of the start of <TT>text</TT>,
+   * or -1 if not found.
+   * @stable ICU 2.0
+   */
+  int32_t lastIndexOf(const UChar *srcChars,
+              int32_t srcStart,
+              int32_t srcLength,
+              int32_t start,
+              int32_t length) const;
+
+  /**
+   * Locate in this the last occurrence of the BMP code point <code>c</code>,
+   * using bitwise comparison.
+   * @param c The code unit to search for.
+   * @return The offset into this of <TT>c</TT>, or -1 if not found.
+   * @stable ICU 2.0
+   */
+  inline int32_t lastIndexOf(UChar c) const;
+
+  /**
+   * Locate in this the last occurrence of the code point <TT>c</TT>,
+   * using bitwise comparison.
+   *
+   * @param c The code point to search for.
+   * @return The offset into this of <TT>c</TT>, or -1 if not found.
+   * @stable ICU 2.0
+   */
+  inline int32_t lastIndexOf(UChar32 c) const;
+
+  /**
+   * Locate in this the last occurrence of the BMP code point <code>c</code>
+   * starting at offset <TT>start</TT>, using bitwise comparison.
+   * @param c The code unit to search for.
+   * @param start The offset at which searching will start.
+   * @return The offset into this of <TT>c</TT>, or -1 if not found.
+   * @stable ICU 2.0
+   */
+  inline int32_t lastIndexOf(UChar c,
+              int32_t start) const;
+
+  /**
+   * Locate in this the last occurrence of the code point <TT>c</TT>
+   * starting at offset <TT>start</TT>, using bitwise comparison.
+   *
+   * @param c The code point to search for.
+   * @param start The offset at which searching will start.
+   * @return The offset into this of <TT>c</TT>, or -1 if not found.
+   * @stable ICU 2.0
+   */
+  inline int32_t lastIndexOf(UChar32 c,
+              int32_t start) const;
+
+  /**
+   * Locate in this the last occurrence of the BMP code point <code>c</code>
+   * in the range [<TT>start</TT>, <TT>start + length</TT>),
+   * using bitwise comparison.
+   * @param c The code unit to search for.
+   * @param start the offset into this at which to start matching
+   * @param length the number of characters in this to search
+   * @return The offset into this of <TT>c</TT>, or -1 if not found.
+   * @stable ICU 2.0
+   */
+  inline int32_t lastIndexOf(UChar c,
+              int32_t start,
+              int32_t length) const;
+
+  /**
+   * Locate in this the last occurrence of the code point <TT>c</TT>
+   * in the range [<TT>start</TT>, <TT>start + length</TT>),
+   * using bitwise comparison.
+   *
+   * @param c The code point to search for.
+   * @param start the offset into this at which to start matching
+   * @param length the number of characters in this to search
+   * @return The offset into this of <TT>c</TT>, or -1 if not found.
+   * @stable ICU 2.0
+   */
+  inline int32_t lastIndexOf(UChar32 c,
+              int32_t start,
+              int32_t length) const;
+
+
+  /* Character access */
+
+  /**
+   * Return the code unit at offset <tt>offset</tt>.
+   * If the offset is not valid (0..length()-1) then U+ffff is returned.
+   * @param offset a valid offset into the text
+   * @return the code unit at offset <tt>offset</tt>
+   *         or 0xffff if the offset is not valid for this string
+   * @stable ICU 2.0
+   */
+  inline UChar charAt(int32_t offset) const;
+
+  /**
+   * Return the code unit at offset <tt>offset</tt>.
+   * If the offset is not valid (0..length()-1) then U+ffff is returned.
+   * @param offset a valid offset into the text
+   * @return the code unit at offset <tt>offset</tt>
+   * @stable ICU 2.0
+   */
+  inline UChar operator[] (int32_t offset) const;
+
+  /**
+   * Return the code point that contains the code unit
+   * at offset <tt>offset</tt>.
+   * If the offset is not valid (0..length()-1) then U+ffff is returned.
+   * @param offset a valid offset into the text
+   * that indicates the text offset of any of the code units
+   * that will be assembled into a code point (21-bit value) and returned
+   * @return the code point of text at <tt>offset</tt>
+   *         or 0xffff if the offset is not valid for this string
+   * @stable ICU 2.0
+   */
+  inline UChar32 char32At(int32_t offset) const;
+
+  /**
+   * Adjust a random-access offset so that
+   * it points to the beginning of a Unicode character.
+   * The offset that is passed in points to
+   * any code unit of a code point,
+   * while the returned offset will point to the first code unit
+   * of the same code point.
+   * In UTF-16, if the input offset points to a second surrogate
+   * of a surrogate pair, then the returned offset will point
+   * to the first surrogate.
+   * @param offset a valid offset into one code point of the text
+   * @return offset of the first code unit of the same code point
+   * @see U16_SET_CP_START
+   * @stable ICU 2.0
+   */
+  inline int32_t getChar32Start(int32_t offset) const;
+
+  /**
+   * Adjust a random-access offset so that
+   * it points behind a Unicode character.
+   * The offset that is passed in points behind
+   * any code unit of a code point,
+   * while the returned offset will point behind the last code unit
+   * of the same code point.
+   * In UTF-16, if the input offset points behind the first surrogate
+   * (i.e., to the second surrogate)
+   * of a surrogate pair, then the returned offset will point
+   * behind the second surrogate (i.e., to the first surrogate).
+   * @param offset a valid offset after any code unit of a code point of the text
+   * @return offset of the first code unit after the same code point
+   * @see U16_SET_CP_LIMIT
+   * @stable ICU 2.0
+   */
+  inline int32_t getChar32Limit(int32_t offset) const;
+
+  /**
+   * Move the code unit index along the string by delta code points.
+   * Interpret the input index as a code unit-based offset into the string,
+   * move the index forward or backward by delta code points, and
+   * return the resulting index.
+   * The input index should point to the first code unit of a code point,
+   * if there is more than one.
+   *
+   * Both input and output indexes are code unit-based as for all
+   * string indexes/offsets in ICU (and other libraries, like MBCS char*).
+   * If delta<0 then the index is moved backward (toward the start of the string).
+   * If delta>0 then the index is moved forward (toward the end of the string).
+   *
+   * This behaves like CharacterIterator::move32(delta, kCurrent).
+   *
+   * Behavior for out-of-bounds indexes:
+   * <code>moveIndex32</code> pins the input index to 0..length(), i.e.,
+   * if the input index<0 then it is pinned to 0;
+   * if it is index>length() then it is pinned to length().
+   * Afterwards, the index is moved by <code>delta</code> code points
+   * forward or backward,
+   * but no further backward than to 0 and no further forward than to length().
+   * The resulting index return value will be in between 0 and length(), inclusively.
+   *
+   * Examples:
+   * <pre>
+   * // s has code points 'a' U+10000 'b' U+10ffff U+2029
+   * UnicodeString s=UNICODE_STRING("a\\U00010000b\\U0010ffff\\u2029", 31).unescape();
+   *
+   * // initial index: position of U+10000
+   * int32_t index=1;
+   *
+   * // the following examples will all result in index==4, position of U+10ffff
+   *
+   * // skip 2 code points from some position in the string
+   * index=s.moveIndex32(index, 2); // skips U+10000 and 'b'
+   *
+   * // go to the 3rd code point from the start of s (0-based)
+   * index=s.moveIndex32(0, 3); // skips 'a', U+10000, and 'b'
+   *
+   * // go to the next-to-last code point of s
+   * index=s.moveIndex32(s.length(), -2); // backward-skips U+2029 and U+10ffff
+   * </pre>
+   *
+   * @param index input code unit index
+   * @param delta (signed) code point count to move the index forward or backward
+   *        in the string
+   * @return the resulting code unit index
+   * @stable ICU 2.0
+   */
+  int32_t moveIndex32(int32_t index, int32_t delta) const;
+
+  /* Substring extraction */
+
+  /**
+   * Copy the characters in the range
+   * [<tt>start</tt>, <tt>start + length</tt>) into the array <tt>dst</tt>,
+   * beginning at <tt>dstStart</tt>.
+   * If the string aliases to <code>dst</code> itself as an external buffer,
+   * then extract() will not copy the contents.
+   *
+   * @param start offset of first character which will be copied into the array
+   * @param length the number of characters to extract
+   * @param dst array in which to copy characters.  The length of <tt>dst</tt>
+   * must be at least (<tt>dstStart + length</tt>).
+   * @param dstStart the offset in <TT>dst</TT> where the first character
+   * will be extracted
+   * @stable ICU 2.0
+   */
+  inline void extract(int32_t start,
+           int32_t length,
+           UChar *dst,
+           int32_t dstStart = 0) const;
+
+  /**
+   * Copy the contents of the string into dest.
+   * This is a convenience function that
+   * checks if there is enough space in dest,
+   * extracts the entire string if possible,
+   * and NUL-terminates dest if possible.
+   *
+   * If the string fits into dest but cannot be NUL-terminated
+   * (length()==destCapacity) then the error code is set to U_STRING_NOT_TERMINATED_WARNING.
+   * If the string itself does not fit into dest
+   * (length()>destCapacity) then the error code is set to U_BUFFER_OVERFLOW_ERROR.
+   *
+   * If the string aliases to <code>dest</code> itself as an external buffer,
+   * then extract() will not copy the contents.
+   *
+   * @param dest Destination string buffer.
+   * @param destCapacity Number of UChars available at dest.
+   * @param errorCode ICU error code.
+   * @return length()
+   * @stable ICU 2.0
+   */
+  int32_t
+  extract(UChar *dest, int32_t destCapacity,
+          UErrorCode &errorCode) const;
+
+  /**
+   * Copy the characters in the range
+   * [<tt>start</tt>, <tt>start + length</tt>) into the  UnicodeString
+   * <tt>target</tt>.
+   * @param start offset of first character which will be copied
+   * @param length the number of characters to extract
+   * @param target UnicodeString into which to copy characters.
+   * @return A reference to <TT>target</TT>
+   * @stable ICU 2.0
+   */
+  inline void extract(int32_t start,
+           int32_t length,
+           UnicodeString& target) const;
+
+  /**
+   * Copy the characters in the range [<tt>start</tt>, <tt>limit</tt>)
+   * into the array <tt>dst</tt>, beginning at <tt>dstStart</tt>.
+   * @param start offset of first character which will be copied into the array
+   * @param limit offset immediately following the last character to be copied
+   * @param dst array in which to copy characters.  The length of <tt>dst</tt>
+   * must be at least (<tt>dstStart + (limit - start)</tt>).
+   * @param dstStart the offset in <TT>dst</TT> where the first character
+   * will be extracted
+   * @stable ICU 2.0
+   */
+  inline void extractBetween(int32_t start,
+              int32_t limit,
+              UChar *dst,
+              int32_t dstStart = 0) const;
+
+  /**
+   * Copy the characters in the range [<tt>start</tt>, <tt>limit</tt>)
+   * into the UnicodeString <tt>target</tt>.  Replaceable API.
+   * @param start offset of first character which will be copied
+   * @param limit offset immediately following the last character to be copied
+   * @param target UnicodeString into which to copy characters.
+   * @return A reference to <TT>target</TT>
+   * @stable ICU 2.0
+   */
+  virtual void extractBetween(int32_t start,
+              int32_t limit,
+              UnicodeString& target) const;
+
+  /**
+   * Copy the characters in the range 
+   * [<tt>start</TT>, <tt>start + length</TT>) into an array of characters.
+   * All characters must be invariant (see utypes.h).
+   * Use US_INV as the last, signature-distinguishing parameter.
+   *
+   * This function does not write any more than <code>targetLength</code>
+   * characters but returns the length of the entire output string
+   * so that one can allocate a larger buffer and call the function again
+   * if necessary.
+   * The output string is NUL-terminated if possible.
+   *
+   * @param start offset of first character which will be copied
+   * @param startLength the number of characters to extract
+   * @param target the target buffer for extraction, can be NULL
+   *               if targetLength is 0
+   * @param targetCapacity the length of the target buffer
+   * @param inv Signature-distinguishing paramater, use US_INV.
+   * @return the output string length, not including the terminating NUL
+   * @stable ICU 3.2
+   */
+  int32_t extract(int32_t start,
+           int32_t startLength,
+           char *target,
+           int32_t targetCapacity,
+           enum EInvariant inv) const;
+
+#if !UCONFIG_NO_CONVERSION
+
+  /**
+   * Copy the characters in the range
+   * [<tt>start</TT>, <tt>start + length</TT>) into an array of characters
+   * in a specified codepage.
+   * The output string is NUL-terminated.
+   *
+   * Recommendation: For invariant-character strings use
+   * extract(int32_t start, int32_t length, char *target, int32_t targetCapacity, enum EInvariant inv) const
+   * because it avoids object code dependencies of UnicodeString on
+   * the conversion code.
+   *
+   * @param start offset of first character which will be copied
+   * @param startLength the number of characters to extract
+   * @param target the target buffer for extraction
+   * @param codepage the desired codepage for the characters.  0 has
+   * the special meaning of the default codepage
+   * If <code>codepage</code> is an empty string (<code>""</code>),
+   * then a simple conversion is performed on the codepage-invariant
+   * subset ("invariant characters") of the platform encoding. See utypes.h.
+   * If <TT>target</TT> is NULL, then the number of bytes required for
+   * <TT>target</TT> is returned. It is assumed that the target is big enough
+   * to fit all of the characters.
+   * @return the output string length, not including the terminating NUL
+   * @stable ICU 2.0
+   */
+  inline int32_t extract(int32_t start,
+                 int32_t startLength,
+                 char *target,
+                 const char *codepage = 0) const;
+
+  /**
+   * Copy the characters in the range
+   * [<tt>start</TT>, <tt>start + length</TT>) into an array of characters
+   * in a specified codepage.
+   * This function does not write any more than <code>targetLength</code>
+   * characters but returns the length of the entire output string
+   * so that one can allocate a larger buffer and call the function again
+   * if necessary.
+   * The output string is NUL-terminated if possible.
+   *
+   * Recommendation: For invariant-character strings use
+   * extract(int32_t start, int32_t length, char *target, int32_t targetCapacity, enum EInvariant inv) const
+   * because it avoids object code dependencies of UnicodeString on
+   * the conversion code.
+   *
+   * @param start offset of first character which will be copied
+   * @param startLength the number of characters to extract
+   * @param target the target buffer for extraction
+   * @param targetLength the length of the target buffer
+   * @param codepage the desired codepage for the characters.  0 has
+   * the special meaning of the default codepage
+   * If <code>codepage</code> is an empty string (<code>""</code>),
+   * then a simple conversion is performed on the codepage-invariant
+   * subset ("invariant characters") of the platform encoding. See utypes.h.
+   * If <TT>target</TT> is NULL, then the number of bytes required for
+   * <TT>target</TT> is returned.
+   * @return the output string length, not including the terminating NUL
+   * @stable ICU 2.0
+   */
+  int32_t extract(int32_t start,
+           int32_t startLength,
+           char *target,
+           uint32_t targetLength,
+           const char *codepage = 0) const;
+
+  /**
+   * Convert the UnicodeString into a codepage string using an existing UConverter.
+   * The output string is NUL-terminated if possible.
+   *
+   * This function avoids the overhead of opening and closing a converter if
+   * multiple strings are extracted.
+   *
+   * @param dest destination string buffer, can be NULL if destCapacity==0
+   * @param destCapacity the number of chars available at dest
+   * @param cnv the converter object to be used (ucnv_resetFromUnicode() will be called),
+   *        or NULL for the default converter
+   * @param errorCode normal ICU error code
+   * @return the length of the output string, not counting the terminating NUL;
+   *         if the length is greater than destCapacity, then the string will not fit
+   *         and a buffer of the indicated length would need to be passed in
+   * @stable ICU 2.0
+   */
+  int32_t extract(char *dest, int32_t destCapacity,
+                  UConverter *cnv,
+                  UErrorCode &errorCode) const;
+
+#endif
+
+  /* Length operations */
+
+  /**
+   * Return the length of the UnicodeString object.
+   * The length is the number of UChar code units are in the UnicodeString.
+   * If you want the number of code points, please use countChar32().
+   * @return the length of the UnicodeString object
+   * @see countChar32
+   * @stable ICU 2.0
+   */
+  inline int32_t length(void) const;
+
+  /**
+   * Count Unicode code points in the length UChar code units of the string.
+   * A code point may occupy either one or two UChar code units.
+   * Counting code points involves reading all code units.
+   *
+   * This functions is basically the inverse of moveIndex32().
+   *
+   * @param start the index of the first code unit to check
+   * @param length the number of UChar code units to check
+   * @return the number of code points in the specified code units
+   * @see length
+   * @stable ICU 2.0
+   */
+  int32_t
+  countChar32(int32_t start=0, int32_t length=INT32_MAX) const;
+
+  /**
+   * Check if the length UChar code units of the string
+   * contain more Unicode code points than a certain number.
+   * This is more efficient than counting all code points in this part of the string
+   * and comparing that number with a threshold.
+   * This function may not need to scan the string at all if the length
+   * falls within a certain range, and
+   * never needs to count more than 'number+1' code points.
+   * Logically equivalent to (countChar32(start, length)>number).
+   * A Unicode code point may occupy either one or two UChar code units.
+   *
+   * @param start the index of the first code unit to check (0 for the entire string)
+   * @param length the number of UChar code units to check
+   *               (use INT32_MAX for the entire string; remember that start/length
+   *                values are pinned)
+   * @param number The number of code points in the (sub)string is compared against
+   *               the 'number' parameter.
+   * @return Boolean value for whether the string contains more Unicode code points
+   *         than 'number'. Same as (u_countChar32(s, length)>number).
+   * @see countChar32
+   * @see u_strHasMoreChar32Than
+   * @stable ICU 2.4
+   */
+  UBool
+  hasMoreChar32Than(int32_t start, int32_t length, int32_t number) const;
+
+  /**
+   * Determine if this string is empty.
+   * @return TRUE if this string contains 0 characters, FALSE otherwise.
+   * @stable ICU 2.0
+   */
+  inline UBool isEmpty(void) const;
+
+  /**
+   * Return the capacity of the internal buffer of the UnicodeString object.
+   * This is useful together with the getBuffer functions.
+   * See there for details.
+   *
+   * @return the number of UChars available in the internal buffer
+   * @see getBuffer
+   * @stable ICU 2.0
+   */
+  inline int32_t getCapacity(void) const;
+
+  /* Other operations */
+
+  /**
+   * Generate a hash code for this object.
+   * @return The hash code of this UnicodeString.
+   * @stable ICU 2.0
+   */
+  inline int32_t hashCode(void) const;
+
+  /**
+   * Determine if this object contains a valid string.
+   * A bogus string has no value. It is different from an empty string.
+   * It can be used to indicate that no string value is available.
+   * getBuffer() and getTerminatedBuffer() return NULL, and
+   * length() returns 0.
+   *
+   * @return TRUE if the string is valid, FALSE otherwise
+   * @see setToBogus()
+   * @stable ICU 2.0
+   */
+  inline UBool isBogus(void) const;
+
+
+  //========================================
+  // Write operations
+  //========================================
+
+  /* Assignment operations */
+
+  /**
+   * Assignment operator.  Replace the characters in this UnicodeString
+   * with the characters from <TT>srcText</TT>.
+   * @param srcText The text containing the characters to replace
+   * @return a reference to this
+   * @stable ICU 2.0
+   */
+  UnicodeString &operator=(const UnicodeString &srcText);
+
+  /**
+   * Almost the same as the assignment operator.
+   * Replace the characters in this UnicodeString
+   * with the characters from <code>srcText</code>.
+   *
+   * This function works the same for all strings except for ones that
+   * are readonly aliases.
+   * Starting with ICU 2.4, the assignment operator and the copy constructor
+   * allocate a new buffer and copy the buffer contents even for readonly aliases.
+   * This function implements the old, more efficient but less safe behavior
+   * of making this string also a readonly alias to the same buffer.
+   * The fastCopyFrom function must be used only if it is known that the lifetime of
+   * this UnicodeString is at least as long as the lifetime of the aliased buffer
+   * including its contents, for example for strings from resource bundles
+   * or aliases to string contents.
+   *
+   * @param src The text containing the characters to replace.
+   * @return a reference to this
+   * @stable ICU 2.4
+   */
+  UnicodeString &fastCopyFrom(const UnicodeString &src);
+
+  /**
+   * Assignment operator.  Replace the characters in this UnicodeString
+   * with the code unit <TT>ch</TT>.
+   * @param ch the code unit to replace
+   * @return a reference to this
+   * @stable ICU 2.0
+   */
+  inline UnicodeString& operator= (UChar ch);
+
+  /**
+   * Assignment operator.  Replace the characters in this UnicodeString
+   * with the code point <TT>ch</TT>.
+   * @param ch the code point to replace
+   * @return a reference to this
+   * @stable ICU 2.0
+   */
+  inline UnicodeString& operator= (UChar32 ch);
+
+  /**
+   * Set the text in the UnicodeString object to the characters
+   * in <TT>srcText</TT> in the range
+   * [<TT>srcStart</TT>, <TT>srcText.length()</TT>).
+   * <TT>srcText</TT> is not modified.
+   * @param srcText the source for the new characters
+   * @param srcStart the offset into <TT>srcText</TT> where new characters
+   * will be obtained
+   * @return a reference to this
+   * @stable ICU 2.2
+   */
+  inline UnicodeString& setTo(const UnicodeString& srcText,
+               int32_t srcStart);
+
+  /**
+   * Set the text in the UnicodeString object to the characters
+   * in <TT>srcText</TT> in the range
+   * [<TT>srcStart</TT>, <TT>srcStart + srcLength</TT>).
+   * <TT>srcText</TT> is not modified.
+   * @param srcText the source for the new characters
+   * @param srcStart the offset into <TT>srcText</TT> where new characters
+   * will be obtained
+   * @param srcLength the number of characters in <TT>srcText</TT> in the
+   * replace string.
+   * @return a reference to this
+   * @stable ICU 2.0
+   */
+  inline UnicodeString& setTo(const UnicodeString& srcText,
+               int32_t srcStart,
+               int32_t srcLength);
+
+  /**
+   * Set the text in the UnicodeString object to the characters in
+   * <TT>srcText</TT>.
+   * <TT>srcText</TT> is not modified.
+   * @param srcText the source for the new characters
+   * @return a reference to this
+   * @stable ICU 2.0
+   */
+  inline UnicodeString& setTo(const UnicodeString& srcText);
+
+  /**
+   * Set the characters in the UnicodeString object to the characters
+   * in <TT>srcChars</TT>. <TT>srcChars</TT> is not modified.
+   * @param srcChars the source for the new characters
+   * @param srcLength the number of Unicode characters in srcChars.
+   * @return a reference to this
+   * @stable ICU 2.0
+   */
+  inline UnicodeString& setTo(const UChar *srcChars,
+               int32_t srcLength);
+
+  /**
+   * Set the characters in the UnicodeString object to the code unit
+   * <TT>srcChar</TT>.
+   * @param srcChar the code unit which becomes the UnicodeString's character
+   * content
+   * @return a reference to this
+   * @stable ICU 2.0
+   */
+  UnicodeString& setTo(UChar srcChar);
+
+  /**
+   * Set the characters in the UnicodeString object to the code point
+   * <TT>srcChar</TT>.
+   * @param srcChar the code point which becomes the UnicodeString's character
+   * content
+   * @return a reference to this
+   * @stable ICU 2.0
+   */
+  UnicodeString& setTo(UChar32 srcChar);
+
+  /**
+   * Aliasing setTo() function, analogous to the readonly-aliasing UChar* constructor.
+   * The text will be used for the UnicodeString object, but
+   * it will not be released when the UnicodeString is destroyed.
+   * This has copy-on-write semantics:
+   * When the string is modified, then the buffer is first copied into
+   * newly allocated memory.
+   * The aliased buffer is never modified.
+   * In an assignment to another UnicodeString, the text will be aliased again,
+   * so that both strings then alias the same readonly-text.
+   *
+   * @param isTerminated specifies if <code>text</code> is <code>NUL</code>-terminated.
+   *                     This must be true if <code>textLength==-1</code>.
+   * @param text The characters to alias for the UnicodeString.
+   * @param textLength The number of Unicode characters in <code>text</code> to alias.
+   *                   If -1, then this constructor will determine the length
+   *                   by calling <code>u_strlen()</code>.
+   * @return a reference to this
+   * @stable ICU 2.0
+   */
+  UnicodeString &setTo(UBool isTerminated,
+                       const UChar *text,
+                       int32_t textLength);
+
+  /**
+   * Aliasing setTo() function, analogous to the writable-aliasing UChar* constructor.
+   * The text will be used for the UnicodeString object, but
+   * it will not be released when the UnicodeString is destroyed.
+   * This has write-through semantics:
+   * For as long as the capacity of the buffer is sufficient, write operations
+   * will directly affect the buffer. When more capacity is necessary, then
+   * a new buffer will be allocated and the contents copied as with regularly
+   * constructed strings.
+   * In an assignment to another UnicodeString, the buffer will be copied.
+   * The extract(UChar *dst) function detects whether the dst pointer is the same
+   * as the string buffer itself and will in this case not copy the contents.
+   *
+   * @param buffer The characters to alias for the UnicodeString.
+   * @param buffLength The number of Unicode characters in <code>buffer</code> to alias.
+   * @param buffCapacity The size of <code>buffer</code> in UChars.
+   * @return a reference to this
+   * @stable ICU 2.0
+   */
+  UnicodeString &setTo(UChar *buffer,
+                       int32_t buffLength,
+                       int32_t buffCapacity);
+
+  /**
+   * Make this UnicodeString object invalid.
+   * The string will test TRUE with isBogus().
+   *
+   * A bogus string has no value. It is different from an empty string.
+   * It can be used to indicate that no string value is available.
+   * getBuffer() and getTerminatedBuffer() return NULL, and
+   * length() returns 0.
+   *
+   * This utility function is used throughout the UnicodeString
+   * implementation to indicate that a UnicodeString operation failed,
+   * and may be used in other functions,
+   * especially but not exclusively when such functions do not
+   * take a UErrorCode for simplicity.
+   *
+   * The following methods, and no others, will clear a string object's bogus flag:
+   * - remove()
+   * - remove(0, INT32_MAX)
+   * - truncate(0)
+   * - operator=() (assignment operator)
+   * - setTo(...)
+   *
+   * The simplest ways to turn a bogus string into an empty one
+   * is to use the remove() function.
+   * Examples for other functions that are equivalent to "set to empty string":
+   * \code
+   * if(s.isBogus()) {
+   *   s.remove();           // set to an empty string (remove all), or
+   *   s.remove(0, INT32_MAX); // set to an empty string (remove all), or
+   *   s.truncate(0);        // set to an empty string (complete truncation), or
+   *   s=UnicodeString();    // assign an empty string, or
+   *   s.setTo((UChar32)-1); // set to a pseudo code point that is out of range, or
+   *   static const UChar nul=0;
+   *   s.setTo(&nul, 0);     // set to an empty C Unicode string
+   * }
+   * \endcode
+   *
+   * @see isBogus()
+   * @stable ICU 2.0
+   */
+  void setToBogus();
+
+  /**
+   * Set the character at the specified offset to the specified character.
+   * @param offset A valid offset into the text of the character to set
+   * @param ch The new character
+   * @return A reference to this
+   * @stable ICU 2.0
+   */
+  UnicodeString& setCharAt(int32_t offset,
+               UChar ch);
+
+
+  /* Append operations */
+
+  /**
+   * Append operator. Append the code unit <TT>ch</TT> to the UnicodeString
+   * object.
+   * @param ch the code unit to be appended
+   * @return a reference to this
+   * @stable ICU 2.0
+   */
+ inline  UnicodeString& operator+= (UChar ch);
+
+  /**
+   * Append operator. Append the code point <TT>ch</TT> to the UnicodeString
+   * object.
+   * @param ch the code point to be appended
+   * @return a reference to this
+   * @stable ICU 2.0
+   */
+ inline  UnicodeString& operator+= (UChar32 ch);
+
+  /**
+   * Append operator. Append the characters in <TT>srcText</TT> to the
+   * UnicodeString object at offset <TT>start</TT>. <TT>srcText</TT> is
+   * not modified.
+   * @param srcText the source for the new characters
+   * @return a reference to this
+   * @stable ICU 2.0
+   */
+  inline UnicodeString& operator+= (const UnicodeString& srcText);
+
+  /**
+   * Append the characters
+   * in <TT>srcText</TT> in the range
+   * [<TT>srcStart</TT>, <TT>srcStart + srcLength</TT>) to the
+   * UnicodeString object at offset <TT>start</TT>. <TT>srcText</TT>
+   * is not modified.
+   * @param srcText the source for the new characters
+   * @param srcStart the offset into <TT>srcText</TT> where new characters
+   * will be obtained
+   * @param srcLength the number of characters in <TT>srcText</TT> in
+   * the append string
+   * @return a reference to this
+   * @stable ICU 2.0
+   */
+  inline UnicodeString& append(const UnicodeString& srcText,
+            int32_t srcStart,
+            int32_t srcLength);
+
+  /**
+   * Append the characters in <TT>srcText</TT> to the UnicodeString object at
+   * offset <TT>start</TT>. <TT>srcText</TT> is not modified.
+   * @param srcText the source for the new characters
+   * @return a reference to this
+   * @stable ICU 2.0
+   */
+  inline UnicodeString& append(const UnicodeString& srcText);
+
+  /**
+   * Append the characters in <TT>srcChars</TT> in the range
+   * [<TT>srcStart</TT>, <TT>srcStart + srcLength</TT>) to the UnicodeString
+   * object at offset
+   * <TT>start</TT>. <TT>srcChars</TT> is not modified.
+   * @param srcChars the source for the new characters
+   * @param srcStart the offset into <TT>srcChars</TT> where new characters
+   * will be obtained
+   * @param srcLength the number of characters in <TT>srcChars</TT> in
+   * the append string
+   * @return a reference to this
+   * @stable ICU 2.0
+   */
+  inline UnicodeString& append(const UChar *srcChars,
+            int32_t srcStart,
+            int32_t srcLength);
+
+  /**
+   * Append the characters in <TT>srcChars</TT> to the UnicodeString object
+   * at offset <TT>start</TT>. <TT>srcChars</TT> is not modified.
+   * @param srcChars the source for the new characters
+   * @param srcLength the number of Unicode characters in <TT>srcChars</TT>
+   * @return a reference to this
+   * @stable ICU 2.0
+   */
+  inline UnicodeString& append(const UChar *srcChars,
+            int32_t srcLength);
+
+  /**
+   * Append the code unit <TT>srcChar</TT> to the UnicodeString object.
+   * @param srcChar the code unit to append
+   * @return a reference to this
+   * @stable ICU 2.0
+   */
+  inline UnicodeString& append(UChar srcChar);
+
+  /**
+   * Append the code point <TT>srcChar</TT> to the UnicodeString object.
+   * @param srcChar the code point to append
+   * @return a reference to this
+   * @stable ICU 2.0
+   */
+  inline UnicodeString& append(UChar32 srcChar);
+
+
+  /* Insert operations */
+
+  /**
+   * Insert the characters in <TT>srcText</TT> in the range
+   * [<TT>srcStart</TT>, <TT>srcStart + srcLength</TT>) into the UnicodeString
+   * object at offset <TT>start</TT>. <TT>srcText</TT> is not modified.
+   * @param start the offset where the insertion begins
+   * @param srcText the source for the new characters
+   * @param srcStart the offset into <TT>srcText</TT> where new characters
+   * will be obtained
+   * @param srcLength the number of characters in <TT>srcText</TT> in
+   * the insert string
+   * @return a reference to this
+   * @stable ICU 2.0
+   */
+  inline UnicodeString& insert(int32_t start,
+            const UnicodeString& srcText,
+            int32_t srcStart,
+            int32_t srcLength);
+
+  /**
+   * Insert the characters in <TT>srcText</TT> into the UnicodeString object
+   * at offset <TT>start</TT>. <TT>srcText</TT> is not modified.
+   * @param start the offset where the insertion begins
+   * @param srcText the source for the new characters
+   * @return a reference to this
+   * @stable ICU 2.0
+   */
+  inline UnicodeString& insert(int32_t start,
+            const UnicodeString& srcText);
+
+  /**
+   * Insert the characters in <TT>srcChars</TT> in the range
+   * [<TT>srcStart</TT>, <TT>srcStart + srcLength</TT>) into the UnicodeString
+   *  object at offset <TT>start</TT>. <TT>srcChars</TT> is not modified.
+   * @param start the offset at which the insertion begins
+   * @param srcChars the source for the new characters
+   * @param srcStart the offset into <TT>srcChars</TT> where new characters
+   * will be obtained
+   * @param srcLength the number of characters in <TT>srcChars</TT>
+   * in the insert string
+   * @return a reference to this
+   * @stable ICU 2.0
+   */
+  inline UnicodeString& insert(int32_t start,
+            const UChar *srcChars,
+            int32_t srcStart,
+            int32_t srcLength);
+
+  /**
+   * Insert the characters in <TT>srcChars</TT> into the UnicodeString object
+   * at offset <TT>start</TT>. <TT>srcChars</TT> is not modified.
+   * @param start the offset where the insertion begins
+   * @param srcChars the source for the new characters
+   * @param srcLength the number of Unicode characters in srcChars.
+   * @return a reference to this
+   * @stable ICU 2.0
+   */
+  inline UnicodeString& insert(int32_t start,
+            const UChar *srcChars,
+            int32_t srcLength);
+
+  /**
+   * Insert the code unit <TT>srcChar</TT> into the UnicodeString object at
+   * offset <TT>start</TT>.
+   * @param start the offset at which the insertion occurs
+   * @param srcChar the code unit to insert
+   * @return a reference to this
+   * @stable ICU 2.0
+   */
+  inline UnicodeString& insert(int32_t start,
+            UChar srcChar);
+
+  /**
+   * Insert the code point <TT>srcChar</TT> into the UnicodeString object at
+   * offset <TT>start</TT>.
+   * @param start the offset at which the insertion occurs
+   * @param srcChar the code point to insert
+   * @return a reference to this
+   * @stable ICU 2.0
+   */
+  inline UnicodeString& insert(int32_t start,
+            UChar32 srcChar);
+
+
+  /* Replace operations */
+
+  /**
+   * Replace the characters in the range
+   * [<TT>start</TT>, <TT>start + length</TT>) with the characters in
+   * <TT>srcText</TT> in the range
+   * [<TT>srcStart</TT>, <TT>srcStart + srcLength</TT>).
+   * <TT>srcText</TT> is not modified.
+   * @param start the offset at which the replace operation begins
+   * @param length the number of characters to replace. The character at
+   * <TT>start + length</TT> is not modified.
+   * @param srcText the source for the new characters
+   * @param srcStart the offset into <TT>srcText</TT> where new characters
+   * will be obtained
+   * @param srcLength the number of characters in <TT>srcText</TT> in
+   * the replace string
+   * @return a reference to this
+   * @stable ICU 2.0
+   */
+  UnicodeString& replace(int32_t start,
+             int32_t length,
+             const UnicodeString& srcText,
+             int32_t srcStart,
+             int32_t srcLength);
+
+  /**
+   * Replace the characters in the range
+   * [<TT>start</TT>, <TT>start + length</TT>)
+   * with the characters in <TT>srcText</TT>.  <TT>srcText</TT> is
+   *  not modified.
+   * @param start the offset at which the replace operation begins
+   * @param length the number of characters to replace. The character at
+   * <TT>start + length</TT> is not modified.
+   * @param srcText the source for the new characters
+   * @return a reference to this
+   * @stable ICU 2.0
+   */
+  UnicodeString& replace(int32_t start,
+             int32_t length,
+             const UnicodeString& srcText);
+
+  /**
+   * Replace the characters in the range
+   * [<TT>start</TT>, <TT>start + length</TT>) with the characters in
+   * <TT>srcChars</TT> in the range
+   * [<TT>srcStart</TT>, <TT>srcStart + srcLength</TT>). <TT>srcChars</TT>
+   * is not modified.
+   * @param start the offset at which the replace operation begins
+   * @param length the number of characters to replace.  The character at
+   * <TT>start + length</TT> is not modified.
+   * @param srcChars the source for the new characters
+   * @param srcStart the offset into <TT>srcChars</TT> where new characters
+   * will be obtained
+   * @param srcLength the number of characters in <TT>srcChars</TT>
+   * in the replace string
+   * @return a reference to this
+   * @stable ICU 2.0
+   */
+  UnicodeString& replace(int32_t start,
+             int32_t length,
+             const UChar *srcChars,
+             int32_t srcStart,
+             int32_t srcLength);
+
+  /**
+   * Replace the characters in the range
+   * [<TT>start</TT>, <TT>start + length</TT>) with the characters in
+   * <TT>srcChars</TT>.  <TT>srcChars</TT> is not modified.
+   * @param start the offset at which the replace operation begins
+   * @param length number of characters to replace.  The character at
+   * <TT>start + length</TT> is not modified.
+   * @param srcChars the source for the new characters
+   * @param srcLength the number of Unicode characters in srcChars
+   * @return a reference to this
+   * @stable ICU 2.0
+   */
+  inline UnicodeString& replace(int32_t start,
+             int32_t length,
+             const UChar *srcChars,
+             int32_t srcLength);
+
+  /**
+   * Replace the characters in the range
+   * [<TT>start</TT>, <TT>start + length</TT>) with the code unit
+   * <TT>srcChar</TT>.
+   * @param start the offset at which the replace operation begins
+   * @param length the number of characters to replace.  The character at
+   * <TT>start + length</TT> is not modified.
+   * @param srcChar the new code unit
+   * @return a reference to this
+   * @stable ICU 2.0
+   */
+  inline UnicodeString& replace(int32_t start,
+             int32_t length,
+             UChar srcChar);
+
+  /**
+   * Replace the characters in the range
+   * [<TT>start</TT>, <TT>start + length</TT>) with the code

<TRUNCATED>

[50/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/.gitignore
----------------------------------------------------------------------
diff --git a/.gitignore b/.gitignore
index c508c28..bf1f2e9 100644
--- a/.gitignore
+++ b/.gitignore
@@ -138,28 +138,28 @@ pkg.vars.config
 rel/apache-couchdb
 
 # rebar
-support/rebar/rebar
-support/rebar/inttest/rt.work
+src/support/rebar/rebar
+src/support/rebar/inttest/rt.work
 rt.work
 rebar
 support/rebar/.test
 
 # couch_collate
-apps/couch_collate/ebin
-apps/couch_collate/priv
-apps/couch_collate/c_src/*.o
+src/apps/couch_collate/ebin
+src/apps/couch_collate/priv
+src/apps/couch_collate/c_src/*.o
 
-apps/couch/ebin
-apps/couch_replicator/ebin
-apps/couch_mrview/ebin
-apps/couch_index/ebin
-apps/couch_dbupdates/ebin
-apps/couch_plugins/ebin
-apps/couch_rel/ebin/*.beam
+src/apps/couch/ebin
+src/apps/couch_replicator/ebin
+src/apps/couch_mrview/ebin
+src/apps/couch_index/ebin
+src/apps/couch_dbupdates/ebin
+src/apps/couch_plugins/ebin
+src/apps/couch_rel/ebin/*.beam
 
 # couchjs
-apps/couch/c_src/couch_js/*.o
-apps/couch/c_src/couch_js/config.h
-apps/couch/priv/couchjs
-apps/couch/c_src/spawnkillable/*.o
-apps/couch/priv/couchspawnkillable
+src/apps/couch/c_src/couch_js/*.o
+src/apps/couch/c_src/couch_js/config.h
+src/apps/couch/priv/couchjs
+src/apps/couch/c_src/spawnkillable/*.o
+src/apps/couch/priv/couchspawnkillable

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/c_src/couch_js/help.h
----------------------------------------------------------------------
diff --git a/apps/couch/c_src/couch_js/help.h b/apps/couch/c_src/couch_js/help.h
deleted file mode 100644
index f4ddb24..0000000
--- a/apps/couch/c_src/couch_js/help.h
+++ /dev/null
@@ -1,82 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-#ifndef COUCHJS_HELP_H
-#define COUCHJS_HELP_H
-
-#include "config.h"
-
-static const char VERSION_TEMPLATE[] =
-    "%s - %s\n"
-    "\n"
-    "Licensed under the Apache License, Version 2.0 (the \"License\"); you may "
-        "not use\n"
-    "this file except in compliance with the License. You may obtain a copy of"
-        "the\n"
-    "License at\n"
-    "\n"
-    "  http://www.apache.org/licenses/LICENSE-2.0\n"
-    "\n"
-    "Unless required by applicable law or agreed to in writing, software "
-        "distributed\n"
-    "under the License is distributed on an \"AS IS\" BASIS, WITHOUT "
-        "WARRANTIES OR\n"
-    "CONDITIONS OF ANY KIND, either express or implied. See the License "
-        "for the\n"
-    "specific language governing permissions and limitations under the "
-        "License.\n";
-
-static const char USAGE_TEMPLATE[] =
-    "Usage: %s [FILE]\n"
-    "\n"
-    "The %s command runs the %s JavaScript interpreter.\n"
-    "\n"
-    "The exit status is 0 for success or 1 for failure.\n"
-    "\n"
-    "Options:\n"
-    "\n"
-    "  -h          display a short help message and exit\n"
-    "  -V          display version information and exit\n"
-    "  -H          enable %s cURL bindings (only avaiable\n"
-    "              if package was built with cURL available)\n"
-    "  -S SIZE     specify that the runtime should allow at\n"
-    "              most SIZE bytes of memory to be allocated\n"
-    "  -u FILE     path to a .uri file containing the address\n"
-    "              (or addresses) of one or more servers\n"
-    "\n"
-    "Report bugs at <%s>.\n";
-
-#define BASENAME COUCHJS_NAME
-
-#define couch_version(basename)  \
-    fprintf(                     \
-            stdout,              \
-            VERSION_TEMPLATE,    \
-            basename,            \
-            PACKAGE_STRING)
-
-#define DISPLAY_VERSION couch_version(BASENAME)
-
-
-#define couch_usage(basename) \
-    fprintf(                                    \
-            stdout,                             \
-            USAGE_TEMPLATE,                     \
-            basename,                           \
-            basename,                           \
-            PACKAGE_NAME,                       \
-            basename,                           \
-            PACKAGE_BUGREPORT)
-
-#define DISPLAY_USAGE couch_usage(BASENAME)
-
-#endif // Included help.h

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/c_src/couch_js/http.c
----------------------------------------------------------------------
diff --git a/apps/couch/c_src/couch_js/http.c b/apps/couch/c_src/couch_js/http.c
deleted file mode 100644
index 3baa59d..0000000
--- a/apps/couch/c_src/couch_js/http.c
+++ /dev/null
@@ -1,696 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <unistd.h>
-#include <jsapi.h>
-#include "utf8.h"
-#include "util.h"
-
-// Soft dependency on cURL bindings because they're
-// only used when running the JS tests from the
-// command line which is rare.
-#ifdef WITHOUT_CURL
-
-void
-http_check_enabled()
-{
-    fprintf(stderr, "HTTP API was disabled at compile time.\n");
-    exit(3);
-}
-
-
-JSBool
-http_ctor(JSContext* cx, JSObject* req)
-{
-    return JS_FALSE;
-}
-
-
-JSBool
-http_dtor(JSContext* cx, JSObject* req)
-{
-    return JS_FALSE;
-}
-
-
-JSBool
-http_open(JSContext* cx, JSObject* req, jsval mth, jsval url, jsval snc)
-{
-    return JS_FALSE;
-}
-
-
-JSBool
-http_set_hdr(JSContext* cx, JSObject* req, jsval name, jsval val)
-{
-    return JS_FALSE;
-}
-
-
-JSBool
-http_send(JSContext* cx, JSObject* req, jsval body)
-{
-    return JS_FALSE;
-}
-
-
-int
-http_status(JSContext* cx, JSObject* req, jsval body)
-{
-    return -1;
-}
-
-JSBool
-http_uri(JSContext* cx, JSObject* req, couch_args* args, jsval* uri_val)
-{
-    return JS_FALSE;
-}
-
-
-#else
-#include <curl/curl.h>
-
-void
-http_check_enabled()
-{
-    return;
-}
-
-
-// Map some of the string function names to things which exist on Windows
-#ifdef XP_WIN
-#define strcasecmp _strcmpi
-#define strncasecmp _strnicmp
-#define snprintf _snprintf
-#endif
-
-
-typedef struct curl_slist CurlHeaders;
-
-
-typedef struct {
-    int             method;
-    char*           url;
-    CurlHeaders*    req_headers;
-    jsint           last_status;
-} HTTPData;
-
-
-char* METHODS[] = {"GET", "HEAD", "POST", "PUT", "DELETE", "COPY", "OPTIONS", NULL};
-
-
-#define GET     0
-#define HEAD    1
-#define POST    2
-#define PUT     3
-#define DELETE  4
-#define COPY    5
-#define OPTIONS 6
-
-
-static JSBool
-go(JSContext* cx, JSObject* obj, HTTPData* http, char* body, size_t blen);
-
-
-static JSString*
-str_from_binary(JSContext* cx, char* data, size_t length);
-
-
-JSBool
-http_ctor(JSContext* cx, JSObject* req)
-{
-    HTTPData* http = NULL;
-    JSBool ret = JS_FALSE;
-
-    http = (HTTPData*) malloc(sizeof(HTTPData));
-    if(!http)
-    {
-        JS_ReportError(cx, "Failed to create CouchHTTP instance.");
-        goto error;
-    }
-
-    http->method = -1;
-    http->url = NULL;
-    http->req_headers = NULL;
-    http->last_status = -1;
-
-    if(!JS_SetPrivate(cx, req, http))
-    {
-        JS_ReportError(cx, "Failed to set private CouchHTTP data.");
-        goto error;
-    }
-
-    ret = JS_TRUE;
-    goto success;
-
-error:
-    if(http) free(http);
-
-success:
-    return ret;
-}
-
-
-void
-http_dtor(JSContext* cx, JSObject* obj)
-{
-    HTTPData* http = (HTTPData*) JS_GetPrivate(cx, obj);
-    if(http) {
-        if(http->url) free(http->url);
-        if(http->req_headers) curl_slist_free_all(http->req_headers);
-        free(http);
-    }
-}
-
-
-JSBool
-http_open(JSContext* cx, JSObject* req, jsval mth, jsval url, jsval snc)
-{
-    HTTPData* http = (HTTPData*) JS_GetPrivate(cx, req);
-    char* method = NULL;
-    int methid;
-    JSBool ret = JS_FALSE;
-
-    if(!http) {
-        JS_ReportError(cx, "Invalid CouchHTTP instance.");
-        goto done;
-    }
-
-    if(JSVAL_IS_VOID(mth)) {
-        JS_ReportError(cx, "You must specify a method.");
-        goto done;
-    }
-
-    method = enc_string(cx, mth, NULL);
-    if(!method) {
-        JS_ReportError(cx, "Failed to encode method.");
-        goto done;
-    }
-
-    for(methid = 0; METHODS[methid] != NULL; methid++) {
-        if(strcasecmp(METHODS[methid], method) == 0) break;
-    }
-
-    if(methid > OPTIONS) {
-        JS_ReportError(cx, "Invalid method specified.");
-        goto done;
-    }
-
-    http->method = methid;
-
-    if(JSVAL_IS_VOID(url)) {
-        JS_ReportError(cx, "You must specify a URL.");
-        goto done;
-    }
-
-    if(http->url != NULL) {
-        free(http->url);
-        http->url = NULL;
-    }
-
-    http->url = enc_string(cx, url, NULL);
-    if(http->url == NULL) {
-        JS_ReportError(cx, "Failed to encode URL.");
-        goto done;
-    }
-
-    if(JSVAL_IS_BOOLEAN(snc) && JSVAL_TO_BOOLEAN(snc)) {
-        JS_ReportError(cx, "Synchronous flag must be false.");
-        goto done;
-    }
-
-    if(http->req_headers) {
-        curl_slist_free_all(http->req_headers);
-        http->req_headers = NULL;
-    }
-
-    // Disable Expect: 100-continue
-    http->req_headers = curl_slist_append(http->req_headers, "Expect:");
-
-    ret = JS_TRUE;
-
-done:
-    if(method) free(method);
-    return ret;
-}
-
-
-JSBool
-http_set_hdr(JSContext* cx, JSObject* req, jsval name, jsval val)
-{
-    HTTPData* http = (HTTPData*) JS_GetPrivate(cx, req);
-    char* keystr = NULL;
-    char* valstr = NULL;
-    char* hdrbuf = NULL;
-    size_t hdrlen = -1;
-    JSBool ret = JS_FALSE;
-
-    if(!http) {
-        JS_ReportError(cx, "Invalid CouchHTTP instance.");
-        goto done;
-    }
-
-    if(JSVAL_IS_VOID(name))
-    {
-        JS_ReportError(cx, "You must speciy a header name.");
-        goto done;
-    }
-
-    keystr = enc_string(cx, name, NULL);
-    if(!keystr)
-    {
-        JS_ReportError(cx, "Failed to encode header name.");
-        goto done;
-    }
-
-    if(JSVAL_IS_VOID(val))
-    {
-        JS_ReportError(cx, "You must specify a header value.");
-        goto done;
-    }
-
-    valstr = enc_string(cx, val, NULL);
-    if(!valstr)
-    {
-        JS_ReportError(cx, "Failed to encode header value.");
-        goto done;
-    }
-
-    hdrlen = strlen(keystr) + strlen(valstr) + 3;
-    hdrbuf = (char*) malloc(hdrlen * sizeof(char));
-    if(!hdrbuf) {
-        JS_ReportError(cx, "Failed to allocate header buffer.");
-        goto done;
-    }
-
-    snprintf(hdrbuf, hdrlen, "%s: %s", keystr, valstr);
-    http->req_headers = curl_slist_append(http->req_headers, hdrbuf);
-
-    ret = JS_TRUE;
-
-done:
-    if(keystr) free(keystr);
-    if(valstr) free(valstr);
-    if(hdrbuf) free(hdrbuf);
-    return ret;
-}
-
-JSBool
-http_send(JSContext* cx, JSObject* req, jsval body)
-{
-    HTTPData* http = (HTTPData*) JS_GetPrivate(cx, req);
-    char* bodystr = NULL;
-    size_t bodylen = 0;
-    JSBool ret = JS_FALSE;
-
-    if(!http) {
-        JS_ReportError(cx, "Invalid CouchHTTP instance.");
-        goto done;
-    }
-
-    if(!JSVAL_IS_VOID(body)) {
-        bodystr = enc_string(cx, body, &bodylen);
-        if(!bodystr) {
-            JS_ReportError(cx, "Failed to encode body.");
-            goto done;
-        }
-    }
-
-    ret = go(cx, req, http, bodystr, bodylen);
-
-done:
-    if(bodystr) free(bodystr);
-    return ret;
-}
-
-int
-http_status(JSContext* cx, JSObject* req)
-{
-    HTTPData* http = (HTTPData*) JS_GetPrivate(cx, req);
-
-    if(!http) {
-        JS_ReportError(cx, "Invalid CouchHTTP instance.");
-        return JS_FALSE;
-    }
-
-    return http->last_status;
-}
-
-JSBool
-http_uri(JSContext* cx, JSObject* req, couch_args* args, jsval* uri_val)
-{
-    FILE* uri_fp = NULL;
-    JSString* uri_str;
-
-    // Default is http://localhost:5984/ when no uri file is specified
-    if (!args->uri_file) {
-        uri_str = JS_InternString(cx, "http://localhost:5984/");
-        *uri_val = STRING_TO_JSVAL(uri_str);
-        return JS_TRUE;
-    }
-
-    // Else check to see if the base url is cached in a reserved slot
-    if (JS_GetReservedSlot(cx, req, 0, uri_val) && !JSVAL_IS_VOID(*uri_val)) {
-        return JS_TRUE;
-    }
-
-    // Read the first line of the couch.uri file.
-    if(!((uri_fp = fopen(args->uri_file, "r")) &&
-         (uri_str = couch_readline(cx, uri_fp)))) {
-        JS_ReportError(cx, "Failed to read couch.uri file.");
-        goto error;
-    }
-
-    fclose(uri_fp);
-    *uri_val = STRING_TO_JSVAL(uri_str);
-    JS_SetReservedSlot(cx, req, 0, *uri_val);
-    return JS_TRUE;
-
-error:
-    if(uri_fp) fclose(uri_fp);
-    return JS_FALSE;
-}
-
-
-// Curl Helpers
-
-typedef struct {
-    HTTPData*   http;
-    JSContext*  cx;
-    JSObject*   resp_headers;
-    char*       sendbuf;
-    size_t      sendlen;
-    size_t      sent;
-    int         sent_once;
-    char*       recvbuf;
-    size_t      recvlen;
-    size_t      read;
-} CurlState;
-
-/*
- * I really hate doing this but this doesn't have to be
- * uber awesome, it just has to work.
- */
-CURL*       HTTP_HANDLE = NULL;
-char        ERRBUF[CURL_ERROR_SIZE];
-
-static size_t send_body(void *ptr, size_t size, size_t nmem, void *data);
-static int seek_body(void *ptr, curl_off_t offset, int origin);
-static size_t recv_body(void *ptr, size_t size, size_t nmem, void *data);
-static size_t recv_header(void *ptr, size_t size, size_t nmem, void *data);
-
-static JSBool
-go(JSContext* cx, JSObject* obj, HTTPData* http, char* body, size_t bodylen)
-{
-    CurlState state;
-    char* referer;
-    JSString* jsbody;
-    JSBool ret = JS_FALSE;
-    jsval tmp;
-
-    state.cx = cx;
-    state.http = http;
-
-    state.sendbuf = body;
-    state.sendlen = bodylen;
-    state.sent = 0;
-    state.sent_once = 0;
-
-    state.recvbuf = NULL;
-    state.recvlen = 0;
-    state.read = 0;
-
-    if(HTTP_HANDLE == NULL) {
-        HTTP_HANDLE = curl_easy_init();
-        curl_easy_setopt(HTTP_HANDLE, CURLOPT_READFUNCTION, send_body);
-        curl_easy_setopt(HTTP_HANDLE, CURLOPT_SEEKFUNCTION,
-                                        (curl_seek_callback) seek_body);
-        curl_easy_setopt(HTTP_HANDLE, CURLOPT_HEADERFUNCTION, recv_header);
-        curl_easy_setopt(HTTP_HANDLE, CURLOPT_WRITEFUNCTION, recv_body);
-        curl_easy_setopt(HTTP_HANDLE, CURLOPT_NOPROGRESS, 1);
-        curl_easy_setopt(HTTP_HANDLE, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
-        curl_easy_setopt(HTTP_HANDLE, CURLOPT_ERRORBUFFER, ERRBUF);
-        curl_easy_setopt(HTTP_HANDLE, CURLOPT_COOKIEFILE, "");
-        curl_easy_setopt(HTTP_HANDLE, CURLOPT_USERAGENT,
-                                            "CouchHTTP Client - Relax");
-    }
-
-    if(!HTTP_HANDLE) {
-        JS_ReportError(cx, "Failed to initialize cURL handle.");
-        goto done;
-    }
-
-    if(!JS_GetReservedSlot(cx, obj, 0, &tmp)) {
-      JS_ReportError(cx, "Failed to readreserved slot.");
-      goto done;
-    }
-
-    if(!(referer = enc_string(cx, tmp, NULL))) {
-      JS_ReportError(cx, "Failed to encode referer.");
-      goto done;
-    }
-    curl_easy_setopt(HTTP_HANDLE, CURLOPT_REFERER, referer);
-    free(referer);
-
-    if(http->method < 0 || http->method > OPTIONS) {
-        JS_ReportError(cx, "INTERNAL: Unknown method.");
-        goto done;
-    }
-
-    curl_easy_setopt(HTTP_HANDLE, CURLOPT_CUSTOMREQUEST, METHODS[http->method]);
-    curl_easy_setopt(HTTP_HANDLE, CURLOPT_NOBODY, 0);
-    curl_easy_setopt(HTTP_HANDLE, CURLOPT_FOLLOWLOCATION, 1);
-    curl_easy_setopt(HTTP_HANDLE, CURLOPT_UPLOAD, 0);
-
-    if(http->method == HEAD) {
-        curl_easy_setopt(HTTP_HANDLE, CURLOPT_NOBODY, 1);
-        curl_easy_setopt(HTTP_HANDLE, CURLOPT_FOLLOWLOCATION, 0);
-    } else if(http->method == POST || http->method == PUT) {
-        curl_easy_setopt(HTTP_HANDLE, CURLOPT_UPLOAD, 1);
-        curl_easy_setopt(HTTP_HANDLE, CURLOPT_FOLLOWLOCATION, 0);
-    }
-
-    if(body && bodylen) {
-        curl_easy_setopt(HTTP_HANDLE, CURLOPT_INFILESIZE, bodylen);
-    } else {
-        curl_easy_setopt(HTTP_HANDLE, CURLOPT_INFILESIZE, 0);
-    }
-
-    // curl_easy_setopt(HTTP_HANDLE, CURLOPT_VERBOSE, 1);
-
-    curl_easy_setopt(HTTP_HANDLE, CURLOPT_URL, http->url);
-    curl_easy_setopt(HTTP_HANDLE, CURLOPT_HTTPHEADER, http->req_headers);
-    curl_easy_setopt(HTTP_HANDLE, CURLOPT_READDATA, &state);
-    curl_easy_setopt(HTTP_HANDLE, CURLOPT_SEEKDATA, &state);
-    curl_easy_setopt(HTTP_HANDLE, CURLOPT_WRITEHEADER, &state);
-    curl_easy_setopt(HTTP_HANDLE, CURLOPT_WRITEDATA, &state);
-
-    if(curl_easy_perform(HTTP_HANDLE) != 0) {
-        JS_ReportError(cx, "Failed to execute HTTP request: %s", ERRBUF);
-        goto done;
-    }
-
-    if(!state.resp_headers) {
-        JS_ReportError(cx, "Failed to recieve HTTP headers.");
-        goto done;
-    }
-
-    tmp = OBJECT_TO_JSVAL(state.resp_headers);
-    if(!JS_DefineProperty(
-        cx, obj,
-        "_headers",
-        tmp,
-        NULL, NULL,
-        JSPROP_READONLY
-    )) {
-        JS_ReportError(cx, "INTERNAL: Failed to set response headers.");
-        goto done;
-    }
-
-    if(state.recvbuf) {
-        state.recvbuf[state.read] = '\0';
-        jsbody = dec_string(cx, state.recvbuf, state.read+1);
-        if(!jsbody) {
-            // If we can't decode the body as UTF-8 we forcefully
-            // convert it to a string by just forcing each byte
-            // to a jschar.
-            jsbody = str_from_binary(cx, state.recvbuf, state.read);
-            if(!jsbody) {
-                if(!JS_IsExceptionPending(cx)) {
-                    JS_ReportError(cx, "INTERNAL: Failed to decode body.");
-                }
-                goto done;
-            }
-        }
-        tmp = STRING_TO_JSVAL(jsbody);
-    } else {
-        tmp = JS_GetEmptyStringValue(cx);
-    }
-
-    if(!JS_DefineProperty(
-        cx, obj,
-        "responseText",
-        tmp,
-        NULL, NULL,
-        JSPROP_READONLY
-    )) {
-        JS_ReportError(cx, "INTERNAL: Failed to set responseText.");
-        goto done;
-    }
-
-    ret = JS_TRUE;
-
-done:
-    if(state.recvbuf) JS_free(cx, state.recvbuf);
-    return ret;
-}
-
-static size_t
-send_body(void *ptr, size_t size, size_t nmem, void *data)
-{
-    CurlState* state = (CurlState*) data;
-    size_t length = size * nmem;
-    size_t towrite = state->sendlen - state->sent;
-
-    // Assume this is cURL trying to resend a request that
-    // failed.
-    if(towrite == 0 && state->sent_once == 0) {
-        state->sent_once = 1;
-        return 0;
-    } else if(towrite == 0) {
-        state->sent = 0;
-        state->sent_once = 0;
-        towrite = state->sendlen;
-    }
-
-    if(length < towrite) towrite = length;
-
-    memcpy(ptr, state->sendbuf + state->sent, towrite);
-    state->sent += towrite;
-
-    return towrite;
-}
-
-static int
-seek_body(void* ptr, curl_off_t offset, int origin)
-{
-    CurlState* state = (CurlState*) ptr;
-    if(origin != SEEK_SET) return -1;
-
-    state->sent = (size_t) offset;
-    return (int) state->sent;
-}
-
-static size_t
-recv_header(void *ptr, size_t size, size_t nmem, void *data)
-{
-    CurlState* state = (CurlState*) data;
-    char code[4];
-    char* header = (char*) ptr;
-    size_t length = size * nmem;
-    JSString* hdr = NULL;
-    jsuint hdrlen;
-    jsval hdrval;
-
-    if(length > 7 && strncasecmp(header, "HTTP/1.", 7) == 0) {
-        if(length < 12) {
-            return CURLE_WRITE_ERROR;
-        }
-
-        memcpy(code, header+9, 3*sizeof(char));
-        code[3] = '\0';
-        state->http->last_status = atoi(code);
-
-        state->resp_headers = JS_NewArrayObject(state->cx, 0, NULL);
-        if(!state->resp_headers) {
-            return CURLE_WRITE_ERROR;
-        }
-
-        return length;
-    }
-
-    // We get a notice at the \r\n\r\n after headers.
-    if(length <= 2) {
-        return length;
-    }
-
-    // Append the new header to our array.
-    hdr = dec_string(state->cx, header, length);
-    if(!hdr) {
-        return CURLE_WRITE_ERROR;
-    }
-
-    if(!JS_GetArrayLength(state->cx, state->resp_headers, &hdrlen)) {
-        return CURLE_WRITE_ERROR;
-    }
-
-    hdrval = STRING_TO_JSVAL(hdr);
-    if(!JS_SetElement(state->cx, state->resp_headers, hdrlen, &hdrval)) {
-        return CURLE_WRITE_ERROR;
-    }
-
-    return length;
-}
-
-static size_t
-recv_body(void *ptr, size_t size, size_t nmem, void *data)
-{
-    CurlState* state = (CurlState*) data;
-    size_t length = size * nmem;
-    char* tmp = NULL;
-
-    if(!state->recvbuf) {
-        state->recvlen = 4096;
-        state->read = 0;
-        state->recvbuf = JS_malloc(state->cx, state->recvlen);
-    }
-
-    if(!state->recvbuf) {
-        return CURLE_WRITE_ERROR;
-    }
-
-    // +1 so we can add '\0' back up in the go function.
-    while(length+1 > state->recvlen - state->read) state->recvlen *= 2;
-    tmp = JS_realloc(state->cx, state->recvbuf, state->recvlen);
-    if(!tmp) return CURLE_WRITE_ERROR;
-    state->recvbuf = tmp;
-
-    memcpy(state->recvbuf + state->read, ptr, length);
-    state->read += length;
-    return length;
-}
-
-JSString*
-str_from_binary(JSContext* cx, char* data, size_t length)
-{
-    jschar* conv = (jschar*) JS_malloc(cx, length * sizeof(jschar));
-    JSString* ret = NULL;
-    size_t i;
-
-    if(!conv) return NULL;
-
-    for(i = 0; i < length; i++) {
-        conv[i] = (jschar) data[i];
-    }
-
-    ret = JS_NewUCString(cx, conv, length);
-    if(!ret) JS_free(cx, conv);
-
-    return ret;
-}
-
-#endif /* HAVE_CURL */

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/c_src/couch_js/http.h
----------------------------------------------------------------------
diff --git a/apps/couch/c_src/couch_js/http.h b/apps/couch/c_src/couch_js/http.h
deleted file mode 100644
index 63d45bd..0000000
--- a/apps/couch/c_src/couch_js/http.h
+++ /dev/null
@@ -1,27 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-#ifndef COUCH_JS_HTTP_H
-#define COUCH_JS_HTTP_H
-
-#include "util.h"
-
-void http_check_enabled();
-JSBool http_ctor(JSContext* cx, JSObject* req);
-void http_dtor(JSContext* cx, JSObject* req);
-JSBool http_open(JSContext* cx, JSObject* req, jsval mth, jsval url, jsval snc);
-JSBool http_set_hdr(JSContext* cx, JSObject* req, jsval name, jsval val);
-JSBool http_send(JSContext* cx, JSObject* req, jsval body);
-int http_status(JSContext* cx, JSObject* req);
-JSBool http_uri(JSContext* cx, JSObject *req, couch_args* args, jsval* uri);
-
-#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/c_src/couch_js/main.c
----------------------------------------------------------------------
diff --git a/apps/couch/c_src/couch_js/main.c b/apps/couch/c_src/couch_js/main.c
deleted file mode 100644
index a0fc143..0000000
--- a/apps/couch/c_src/couch_js/main.c
+++ /dev/null
@@ -1,431 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-
-#include <jsapi.h>
-#include "http.h"
-#include "utf8.h"
-#include "util.h"
-
-
-#define SETUP_REQUEST(cx) \
-    JS_SetContextThread(cx); \
-    JS_BeginRequest(cx);
-#define FINISH_REQUEST(cx) \
-    JS_EndRequest(cx); \
-    JS_ClearContextThread(cx);
-
-
-static JSClass global_class = {
-    "GlobalClass",
-    JSCLASS_GLOBAL_FLAGS,
-    JS_PropertyStub,
-    JS_PropertyStub,
-    JS_PropertyStub,
-    JS_StrictPropertyStub,
-    JS_EnumerateStub,
-    JS_ResolveStub,
-    JS_ConvertStub,
-    JS_FinalizeStub,
-    JSCLASS_NO_OPTIONAL_MEMBERS
-};
-
-
-static JSBool
-req_ctor(JSContext* cx, uintN argc, jsval* vp)
-{
-    JSBool ret;
-    JSObject* obj = JS_NewObjectForConstructor(cx, vp);
-    if(!obj) {
-        JS_ReportError(cx, "Failed to create CouchHTTP instance.\n");
-        return JS_FALSE;
-    }
-    ret = http_ctor(cx, obj);
-    JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(obj));
-    return ret;
-}
-
-
-static void
-req_dtor(JSContext* cx, JSObject* obj)
-{
-    http_dtor(cx, obj);
-}
-
-
-static JSBool
-req_open(JSContext* cx, uintN argc, jsval* vp)
-{
-    JSObject* obj = JS_THIS_OBJECT(cx, vp);
-    jsval* argv = JS_ARGV(cx, vp);
-    JSBool ret = JS_FALSE;
-
-    if(argc == 2) {
-        ret = http_open(cx, obj, argv[0], argv[1], JSVAL_FALSE);
-    } else if(argc == 3) {
-        ret = http_open(cx, obj, argv[0], argv[1], argv[2]);
-    } else {
-        JS_ReportError(cx, "Invalid call to CouchHTTP.open");
-    }
-
-    JS_SET_RVAL(cx, vp, JSVAL_VOID);
-    return ret;
-}
-
-
-static JSBool
-req_set_hdr(JSContext* cx, uintN argc, jsval* vp)
-{
-    JSObject* obj = JS_THIS_OBJECT(cx, vp);
-    jsval* argv = JS_ARGV(cx, vp);
-    JSBool ret = JS_FALSE;
-
-    if(argc == 2) {
-        ret = http_set_hdr(cx, obj, argv[0], argv[1]);
-    } else {
-        JS_ReportError(cx, "Invalid call to CouchHTTP.set_header");
-    }
-
-    JS_SET_RVAL(cx, vp, JSVAL_VOID);
-    return ret;
-}
-
-
-static JSBool
-req_send(JSContext* cx, uintN argc, jsval* vp)
-{
-    JSObject* obj = JS_THIS_OBJECT(cx, vp);
-    jsval* argv = JS_ARGV(cx, vp);
-    JSBool ret = JS_FALSE;
-
-    if(argc == 1) {
-        ret = http_send(cx, obj, argv[0]);
-    } else {
-        JS_ReportError(cx, "Invalid call to CouchHTTP.send");
-    }
-
-    JS_SET_RVAL(cx, vp, JSVAL_VOID);
-    return ret;
-}
-
-
-static JSBool
-req_status(JSContext* cx, JSObject* obj, jsid pid, jsval* vp)
-{
-    int status = http_status(cx, obj);
-    if(status < 0)
-        return JS_FALSE;
-
-    JS_SET_RVAL(cx, vp, INT_TO_JSVAL(status));
-    return JS_TRUE;
-}
-
-
-static JSBool
-base_url(JSContext *cx, JSObject* obj, jsid pid, jsval* vp)
-{
-    couch_args *args = (couch_args*)JS_GetContextPrivate(cx);
-    return http_uri(cx, obj, args, &JS_RVAL(cx, vp));
-}
-
-
-static JSBool
-evalcx(JSContext *cx, uintN argc, jsval* vp)
-{
-    jsval* argv = JS_ARGV(cx, vp);
-    JSString* str;
-    JSObject* sandbox;
-    JSObject* global;
-    JSContext* subcx;
-    JSCrossCompartmentCall* call = NULL;
-    const jschar* src;
-    size_t srclen;
-    jsval rval;
-    JSBool ret = JS_FALSE;
-    char *name = NULL;
-
-    sandbox = NULL;
-    if(!JS_ConvertArguments(cx, argc, argv, "S / o", &str, &sandbox)) {
-        return JS_FALSE;
-    }
-
-    subcx = JS_NewContext(JS_GetRuntime(cx), 8L * 1024L);
-    if(!subcx) {
-        JS_ReportOutOfMemory(cx);
-        return JS_FALSE;
-    }
-
-    SETUP_REQUEST(subcx);
-
-    src = JS_GetStringCharsAndLength(cx, str, &srclen);
-
-    // Re-use the compartment associated with the main context,
-    // rather than creating a new compartment */
-    global = JS_GetGlobalObject(cx);
-    if(global == NULL) goto done;
-    call = JS_EnterCrossCompartmentCall(subcx, global);
-
-    if(!sandbox) {
-        sandbox = JS_NewGlobalObject(subcx, &global_class);
-        if(!sandbox || !JS_InitStandardClasses(subcx, sandbox)) {
-            goto done;
-        }
-    }
-
-    if(argc > 2) {
-        name = enc_string(cx, argv[2], NULL);
-    }
-
-    if(srclen == 0) {
-        JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(sandbox));
-    } else {
-        JS_EvaluateUCScript(subcx, sandbox, src, srclen, name, 1, &rval);
-        JS_SET_RVAL(cx, vp, rval);
-    }
-
-    ret = JS_TRUE;
-
-done:
-    if(name) JS_free(cx, name);
-    JS_LeaveCrossCompartmentCall(call);
-    FINISH_REQUEST(subcx);
-    JS_DestroyContext(subcx);
-    return ret;
-}
-
-
-static JSBool
-gc(JSContext* cx, uintN argc, jsval* vp)
-{
-    JS_GC(cx);
-    JS_SET_RVAL(cx, vp, JSVAL_VOID);
-    return JS_TRUE;
-}
-
-
-static JSBool
-print(JSContext* cx, uintN argc, jsval* vp)
-{
-    jsval* argv = JS_ARGV(cx, vp);
-    couch_print(cx, argc, argv);
-    JS_SET_RVAL(cx, vp, JSVAL_VOID);
-    return JS_TRUE;
-}
-
-
-static JSBool
-quit(JSContext* cx, uintN argc, jsval* vp)
-{
-    jsval* argv = JS_ARGV(cx, vp);
-    int exit_code = 0;
-    JS_ConvertArguments(cx, argc, argv, "/i", &exit_code);
-    exit(exit_code);
-}
-
-
-static JSBool
-readline(JSContext* cx, uintN argc, jsval* vp)
-{
-    JSString* line;
-
-    /* GC Occasionally */
-    JS_MaybeGC(cx);
-
-    line = couch_readline(cx, stdin);
-    if(line == NULL) return JS_FALSE;
-
-    JS_SET_RVAL(cx, vp, STRING_TO_JSVAL(line));
-    return JS_TRUE;
-}
-
-
-static JSBool
-seal(JSContext* cx, uintN argc, jsval* vp)
-{
-    jsval* argv = JS_ARGV(cx, vp);
-    JSObject *target;
-    JSBool deep = JS_FALSE;
-    JSBool ret;
-
-    if(!JS_ConvertArguments(cx, argc, argv, "o/b", &target, &deep))
-        return JS_FALSE;
-
-    if(!target) {
-        JS_SET_RVAL(cx, vp, JSVAL_VOID);
-        return JS_TRUE;
-    }
-
-
-    ret = deep ? JS_DeepFreezeObject(cx, target) : JS_FreezeObject(cx, target);
-    JS_SET_RVAL(cx, vp, JSVAL_VOID);
-    return ret;
-}
-
-
-JSClass CouchHTTPClass = {
-    "CouchHTTP",
-    JSCLASS_HAS_PRIVATE
-        | JSCLASS_CONSTRUCT_PROTOTYPE
-        | JSCLASS_HAS_RESERVED_SLOTS(2),
-    JS_PropertyStub,
-    JS_PropertyStub,
-    JS_PropertyStub,
-    JS_StrictPropertyStub,
-    JS_EnumerateStub,
-    JS_ResolveStub,
-    JS_ConvertStub,
-    req_dtor,
-    JSCLASS_NO_OPTIONAL_MEMBERS
-};
-
-
-JSPropertySpec CouchHTTPProperties[] = {
-    {"status", 0, JSPROP_READONLY, req_status, NULL},
-    {"base_url", 0, JSPROP_READONLY | JSPROP_SHARED, base_url, NULL},
-    {0, 0, 0, 0, 0}
-};
-
-
-JSFunctionSpec CouchHTTPFunctions[] = {
-    JS_FS("_open", req_open, 3, 0),
-    JS_FS("_setRequestHeader", req_set_hdr, 2, 0),
-    JS_FS("_send", req_send, 1, 0),
-    JS_FS_END
-};
-
-
-static JSFunctionSpec global_functions[] = {
-    JS_FS("evalcx", evalcx, 0, 0),
-    JS_FS("gc", gc, 0, 0),
-    JS_FS("print", print, 0, 0),
-    JS_FS("quit", quit, 0, 0),
-    JS_FS("readline", readline, 0, 0),
-    JS_FS("seal", seal, 0, 0),
-    JS_FS_END
-};
-
-
-int
-main(int argc, const char* argv[])
-{
-    JSRuntime* rt = NULL;
-    JSContext* cx = NULL;
-    JSObject* global = NULL;
-    JSCrossCompartmentCall *call = NULL;
-    JSObject* klass = NULL;
-    JSObject* script;
-    JSString* scriptsrc;
-    const jschar* schars;
-    size_t slen;
-    jsval sroot;
-    jsval result;
-    int i;
-
-    couch_args* args = couch_parse_args(argc, argv);
-
-    rt = JS_NewRuntime(args->stack_size);
-    if(rt == NULL)
-        return 1;
-
-    cx = JS_NewContext(rt, 8L * 1024L);
-    if(cx == NULL)
-        return 1;
-
-    JS_SetErrorReporter(cx, couch_error);
-    JS_ToggleOptions(cx, JSOPTION_XML);
-    JS_SetOptions(cx, JSOPTION_METHODJIT);
-#ifdef JSOPTION_TYPE_INFERENCE
-    JS_SetOptions(cx, JSOPTION_TYPE_INFERENCE);
-#endif
-    JS_SetContextPrivate(cx, args);
-
-    SETUP_REQUEST(cx);
-
-    global = JS_NewCompartmentAndGlobalObject(cx, &global_class, NULL);
-    if(global == NULL)
-        return 1;
-
-    call = JS_EnterCrossCompartmentCall(cx, global);
-
-    JS_SetGlobalObject(cx, global);
-
-    if(!JS_InitStandardClasses(cx, global))
-        return 1;
-
-    if(couch_load_funcs(cx, global, global_functions) != JS_TRUE)
-        return 1;
-
-    if(args->use_http) {
-        http_check_enabled();
-
-        klass = JS_InitClass(
-            cx, global,
-            NULL,
-            &CouchHTTPClass, req_ctor,
-            0,
-            CouchHTTPProperties, CouchHTTPFunctions,
-            NULL, NULL
-        );
-
-        if(!klass)
-        {
-            fprintf(stderr, "Failed to initialize CouchHTTP class.\n");
-            exit(2);
-        }
-    }
-
-    for(i = 0 ; args->scripts[i] ; i++) {
-        // Convert script source to jschars.
-        scriptsrc = couch_readfile(cx, args->scripts[i]);
-        if(!scriptsrc)
-            return 1;
-
-        schars = JS_GetStringCharsAndLength(cx, scriptsrc, &slen);
-
-        // Root it so GC doesn't collect it.
-        sroot = STRING_TO_JSVAL(scriptsrc);
-        if(JS_AddValueRoot(cx, &sroot) != JS_TRUE) {
-            fprintf(stderr, "Internal root error.\n");
-            return 1;
-        }
-
-        // Compile and run
-        script = JS_CompileUCScript(cx, global, schars, slen,
-                                    args->scripts[i], 1);
-        if(!script) {
-            fprintf(stderr, "Failed to compile script.\n");
-            return 1;
-        }
-
-        if(JS_ExecuteScript(cx, global, script, &result) != JS_TRUE) {
-            fprintf(stderr, "Failed to execute script.\n");
-            return 1;
-        }
-
-        // Warning message if we don't remove it.
-        JS_RemoveValueRoot(cx, &sroot);
-
-        // Give the GC a chance to run.
-        JS_MaybeGC(cx);
-    }
-
-    JS_LeaveCrossCompartmentCall(call);
-    FINISH_REQUEST(cx);
-    JS_DestroyContext(cx);
-    JS_DestroyRuntime(rt);
-    JS_ShutDown();
-
-    return 0;
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/c_src/couch_js/utf8.c
----------------------------------------------------------------------
diff --git a/apps/couch/c_src/couch_js/utf8.c b/apps/couch/c_src/couch_js/utf8.c
deleted file mode 100644
index 2b3735a..0000000
--- a/apps/couch/c_src/couch_js/utf8.c
+++ /dev/null
@@ -1,288 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-#include <jsapi.h>
-
-static int
-enc_char(uint8 *utf8Buffer, uint32 ucs4Char)
-{
-    int utf8Length = 1;
-
-    if (ucs4Char < 0x80)
-    {
-        *utf8Buffer = (uint8)ucs4Char;
-    }
-    else
-    {
-        int i;
-        uint32 a = ucs4Char >> 11;
-        utf8Length = 2;
-        while(a)
-        {
-            a >>= 5;
-            utf8Length++;
-        }
-        i = utf8Length;
-        while(--i)
-        {
-            utf8Buffer[i] = (uint8)((ucs4Char & 0x3F) | 0x80);
-            ucs4Char >>= 6;
-        }
-        *utf8Buffer = (uint8)(0x100 - (1 << (8-utf8Length)) + ucs4Char);
-    }
-
-    return utf8Length;
-}
-
-static JSBool
-enc_charbuf(const jschar* src, size_t srclen, char* dst, size_t* dstlenp)
-{
-    size_t i;
-    size_t utf8Len;
-    size_t dstlen = *dstlenp;
-    size_t origDstlen = dstlen;
-    jschar c;
-    jschar c2;
-    uint32 v;
-    uint8 utf8buf[6];
-
-    if(!dst)
-    {
-        dstlen = origDstlen = (size_t) -1;
-    }
-
-    while(srclen)
-    {
-        c = *src++;
-        srclen--;
-
-        if(c <= 0xD7FF || c >= 0xE000)
-        {
-            v = (uint32) c;
-        }
-        else if(c >= 0xD800 && c <= 0xDBFF)
-        {
-            if(srclen < 1) goto buffer_too_small;
-            c2 = *src++;
-            srclen--;
-            if(c2 >= 0xDC00 && c2 <= 0xDFFF)
-            {
-                v = (uint32) (((c - 0xD800) << 10) + (c2 - 0xDC00) + 0x10000);
-            }
-            else
-            {
-                // Invalid second half of surrogate pair
-                v = (uint32) 0xFFFD;
-            }
-        }
-        else
-        {
-            // Invalid first half surrogate pair
-            v = (uint32) 0xFFFD;
-        }
-
-        if(v < 0x0080)
-        {
-            /* no encoding necessary - performance hack */
-            if(!dstlen) goto buffer_too_small;
-            if(dst) *dst++ = (char) v;
-            utf8Len = 1;
-        }
-        else
-        {
-            utf8Len = enc_char(utf8buf, v);
-            if(utf8Len > dstlen) goto buffer_too_small;
-            if(dst)
-            {
-                for (i = 0; i < utf8Len; i++)
-                {
-                    *dst++ = (char) utf8buf[i];
-                }
-            }
-        }
-        dstlen -= utf8Len;
-    }
-
-    *dstlenp = (origDstlen - dstlen);
-    return JS_TRUE;
-
-buffer_too_small:
-    *dstlenp = (origDstlen - dstlen);
-    return JS_FALSE;
-}
-
-char*
-enc_string(JSContext* cx, jsval arg, size_t* buflen)
-{
-    JSString* str = NULL;
-    const jschar* src = NULL;
-    char* bytes = NULL;
-    size_t srclen = 0;
-    size_t byteslen = 0;
-
-    str = JS_ValueToString(cx, arg);
-    if(!str) goto error;
-
-    src = JS_GetStringCharsAndLength(cx, str, &srclen);
-
-    if(!enc_charbuf(src, srclen, NULL, &byteslen)) goto error;
-
-    bytes = JS_malloc(cx, (byteslen) + 1);
-    bytes[byteslen] = 0;
-
-    if(!enc_charbuf(src, srclen, bytes, &byteslen)) goto error;
-
-    if(buflen) *buflen = byteslen;
-    goto success;
-
-error:
-    if(bytes != NULL) JS_free(cx, bytes);
-    bytes = NULL;
-
-success:
-    return bytes;
-}
-
-static uint32
-dec_char(const uint8 *utf8Buffer, int utf8Length)
-{
-    uint32 ucs4Char;
-    uint32 minucs4Char;
-
-    /* from Unicode 3.1, non-shortest form is illegal */
-    static const uint32 minucs4Table[] = {
-        0x00000080, 0x00000800, 0x0001000, 0x0020000, 0x0400000
-    };
-
-    if (utf8Length == 1)
-    {
-        ucs4Char = *utf8Buffer;
-    }
-    else
-    {
-        ucs4Char = *utf8Buffer++ & ((1<<(7-utf8Length))-1);
-        minucs4Char = minucs4Table[utf8Length-2];
-        while(--utf8Length)
-        {
-            ucs4Char = ucs4Char<<6 | (*utf8Buffer++ & 0x3F);
-        }
-        if(ucs4Char < minucs4Char || ucs4Char == 0xFFFE || ucs4Char == 0xFFFF)
-        {
-            ucs4Char = 0xFFFD;
-        }
-    }
-
-    return ucs4Char;
-}
-
-static JSBool
-dec_charbuf(const char *src, size_t srclen, jschar *dst, size_t *dstlenp)
-{
-    uint32 v;
-    size_t offset = 0;
-    size_t j;
-    size_t n;
-    size_t dstlen = *dstlenp;
-    size_t origDstlen = dstlen;
-
-    if(!dst) dstlen = origDstlen = (size_t) -1;
-
-    while(srclen)
-    {
-        v = (uint8) *src;
-        n = 1;
-
-        if(v & 0x80)
-        {
-            while(v & (0x80 >> n))
-            {
-                n++;
-            }
-
-            if(n > srclen) goto buffer_too_small;
-            if(n == 1 || n > 6) goto bad_character;
-
-            for(j = 1; j < n; j++)
-            {
-                if((src[j] & 0xC0) != 0x80) goto bad_character;
-            }
-
-            v = dec_char((const uint8 *) src, n);
-            if(v >= 0x10000)
-            {
-                v -= 0x10000;
-
-                if(v > 0xFFFFF || dstlen < 2)
-                {
-                    *dstlenp = (origDstlen - dstlen);
-                    return JS_FALSE;
-                }
-
-                if(dstlen < 2) goto buffer_too_small;
-
-                if(dst)
-                {
-                    *dst++ = (jschar)((v >> 10) + 0xD800);
-                    v = (jschar)((v & 0x3FF) + 0xDC00);
-                }
-                dstlen--;
-            }
-        }
-
-        if(!dstlen) goto buffer_too_small;
-        if(dst) *dst++ = (jschar) v;
-
-        dstlen--;
-        offset += n;
-        src += n;
-        srclen -= n;
-    }
-
-    *dstlenp = (origDstlen - dstlen);
-    return JS_TRUE;
-
-bad_character:
-    *dstlenp = (origDstlen - dstlen);
-    return JS_FALSE;
-
-buffer_too_small:
-    *dstlenp = (origDstlen - dstlen);
-    return JS_FALSE;
-}
-
-JSString*
-dec_string(JSContext* cx, const char* bytes, size_t byteslen)
-{
-    JSString* str = NULL;
-    jschar* chars = NULL;
-    size_t charslen;
-
-    if(!dec_charbuf(bytes, byteslen, NULL, &charslen)) goto error;
-
-    chars = JS_malloc(cx, (charslen + 1) * sizeof(jschar));
-    if(!chars) return NULL;
-    chars[charslen] = 0;
-
-    if(!dec_charbuf(bytes, byteslen, chars, &charslen)) goto error;
-
-    str = JS_NewUCString(cx, chars, charslen - 1);
-    if(!str) goto error;
-
-    goto success;
-
-error:
-    if(chars != NULL) JS_free(cx, chars);
-    str = NULL;
-
-success:
-    return str;
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/c_src/couch_js/utf8.h
----------------------------------------------------------------------
diff --git a/apps/couch/c_src/couch_js/utf8.h b/apps/couch/c_src/couch_js/utf8.h
deleted file mode 100644
index c5cb86c..0000000
--- a/apps/couch/c_src/couch_js/utf8.h
+++ /dev/null
@@ -1,19 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-#ifndef COUCH_JS_UTF_8_H
-#define COUCH_JS_UTF_8_H
-
-char* enc_string(JSContext* cx, jsval arg, size_t* buflen);
-JSString* dec_string(JSContext* cx, const char* buf, size_t buflen);
-
-#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/c_src/couch_js/util.c
----------------------------------------------------------------------
diff --git a/apps/couch/c_src/couch_js/util.c b/apps/couch/c_src/couch_js/util.c
deleted file mode 100644
index 9b46ceb..0000000
--- a/apps/couch/c_src/couch_js/util.c
+++ /dev/null
@@ -1,288 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-#include <stdlib.h>
-#include <string.h>
-
-#include <jsapi.h>
-
-#include "help.h"
-#include "util.h"
-#include "utf8.h"
-
-
-size_t
-slurp_file(const char* file, char** outbuf_p)
-{
-    FILE* fp;
-    char fbuf[16384];
-    char *buf = NULL;
-    char* tmp;
-    size_t nread = 0;
-    size_t buflen = 0;
-
-    if(strcmp(file, "-") == 0) {
-        fp = stdin;
-    } else {
-        fp = fopen(file, "r");
-        if(fp == NULL) {
-            fprintf(stderr, "Failed to read file: %s\n", file);
-            exit(3);
-        }
-    }
-
-    while((nread = fread(fbuf, 1, 16384, fp)) > 0) {
-        if(buf == NULL) {
-            buf = (char*) malloc(nread + 1);
-            if(buf == NULL) {
-                fprintf(stderr, "Out of memory.\n");
-                exit(3);
-            }
-            memcpy(buf, fbuf, nread);
-        } else {
-            tmp = (char*) malloc(buflen + nread + 1);
-            if(tmp == NULL) {
-                fprintf(stderr, "Out of memory.\n");
-                exit(3);
-            }
-            memcpy(tmp, buf, buflen);
-            memcpy(tmp+buflen, fbuf, nread);
-            free(buf);
-            buf = tmp;
-        }
-        buflen += nread;
-        buf[buflen] = '\0';
-    }
-    *outbuf_p = buf;
-    return buflen + 1;
-}
-
-couch_args*
-couch_parse_args(int argc, const char* argv[])
-{
-    couch_args* args;
-    int i = 1;
-
-    args = (couch_args*) malloc(sizeof(couch_args));
-    if(args == NULL)
-        return NULL;
-
-    memset(args, '\0', sizeof(couch_args));
-    args->stack_size = 64L * 1024L * 1024L;
-
-    while(i < argc) {
-        if(strcmp("-h", argv[i]) == 0) {
-            DISPLAY_USAGE;
-            exit(0);
-        } else if(strcmp("-V", argv[i]) == 0) {
-            DISPLAY_VERSION;
-            exit(0);
-        } else if(strcmp("-H", argv[i]) == 0) {
-            args->use_http = 1;
-        } else if(strcmp("-S", argv[i]) == 0) {
-            args->stack_size = atoi(argv[++i]);
-            if(args->stack_size <= 0) {
-                fprintf(stderr, "Invalid stack size.\n");
-                exit(2);
-            }
-        } else if(strcmp("-u", argv[i]) == 0) {
-            args->uri_file = argv[++i];
-        } else if(strcmp("--", argv[i]) == 0) {
-            i++;
-            break;
-        } else {
-            break;
-        }
-        i++;
-    }
-
-    if(i >= argc) {
-        DISPLAY_USAGE;
-        exit(3);
-    }
-    args->scripts = argv + i;
-
-    return args;
-}
-
-
-int
-couch_fgets(char* buf, int size, FILE* fp)
-{
-    int n, i, c;
-
-    if(size <= 0) return -1;
-    n = size - 1;
-
-    for(i = 0; i < n && (c = getc(fp)) != EOF; i++) {
-        buf[i] = c;
-        if(c == '\n') {
-            i++;
-            break;
-        }
-    }
-
-    buf[i] = '\0';
-    return i;
-}
-
-
-JSString*
-couch_readline(JSContext* cx, FILE* fp)
-{
-    JSString* str;
-    char* bytes = NULL;
-    char* tmp = NULL;
-    size_t used = 0;
-    size_t byteslen = 256;
-    size_t readlen = 0;
-
-    bytes = JS_malloc(cx, byteslen);
-    if(bytes == NULL) return NULL;
-
-    while((readlen = couch_fgets(bytes+used, byteslen-used, fp)) > 0) {
-        used += readlen;
-
-        if(bytes[used-1] == '\n') {
-            bytes[used-1] = '\0';
-            break;
-        }
-
-        // Double our buffer and read more.
-        byteslen *= 2;
-        tmp = JS_realloc(cx, bytes, byteslen);
-        if(!tmp) {
-            JS_free(cx, bytes);
-            return NULL;
-        }
-
-        bytes = tmp;
-    }
-
-    // Treat empty strings specially
-    if(used == 0) {
-        JS_free(cx, bytes);
-        return JSVAL_TO_STRING(JS_GetEmptyStringValue(cx));
-    }
-
-    // Shring the buffer to the actual data size
-    tmp = JS_realloc(cx, bytes, used);
-    if(!tmp) {
-        JS_free(cx, bytes);
-        return NULL;
-    }
-    bytes = tmp;
-    byteslen = used;
-
-    str = dec_string(cx, bytes, byteslen);
-    JS_free(cx, bytes);
-    return str;
-}
-
-
-JSString*
-couch_readfile(JSContext* cx, const char* filename)
-{
-    JSString *string;
-    size_t byteslen;
-    char *bytes;
-
-    if((byteslen = slurp_file(filename, &bytes))) {
-        string = dec_string(cx, bytes, byteslen);
-
-        free(bytes);
-        return string;
-    }
-    return NULL;
-}
-
-
-void
-couch_print(JSContext* cx, uintN argc, jsval* argv)
-{
-    char *bytes = NULL;
-    FILE *stream = stdout;
-
-    if (argc) {
-        if (argc > 1 && argv[1] == JSVAL_TRUE) {
-          stream = stderr;
-        }
-        bytes = enc_string(cx, argv[0], NULL);
-        if(!bytes) return;
-        fprintf(stream, "%s", bytes);
-        JS_free(cx, bytes);
-    }
-
-    fputc('\n', stream);
-    fflush(stream);
-}
-
-
-void
-couch_error(JSContext* cx, const char* mesg, JSErrorReport* report)
-{
-    jsval v, replace;
-    char* bytes;
-    JSObject* regexp, *stack;
-    jsval re_args[2];
-
-    if(!report || !JSREPORT_IS_WARNING(report->flags))
-    {
-        fprintf(stderr, "%s\n", mesg);
-
-        // Print a stack trace, if available.
-        if (JSREPORT_IS_EXCEPTION(report->flags) &&
-            JS_GetPendingException(cx, &v))
-        {
-            // Clear the exception before an JS method calls or the result is
-            // infinite, recursive error report generation.
-            JS_ClearPendingException(cx);
-
-            // Use JS regexp to indent the stack trace.
-            // If the regexp can't be created, don't JS_ReportError since it is
-            // probably not productive to wind up here again.
-            if(JS_GetProperty(cx, JSVAL_TO_OBJECT(v), "stack", &v) &&
-               (regexp = JS_NewRegExpObjectNoStatics(
-                   cx, "^(?=.)", 6, JSREG_GLOB | JSREG_MULTILINE)))
-            {
-                // Set up the arguments to ``String.replace()``
-                re_args[0] = OBJECT_TO_JSVAL(regexp);
-                re_args[1] = STRING_TO_JSVAL(JS_InternString(cx, "\t"));
-
-                // Perform the replacement
-                if(JS_ValueToObject(cx, v, &stack) &&
-                   JS_GetProperty(cx, stack, "replace", &replace) &&
-                   JS_CallFunctionValue(cx, stack, replace, 2, re_args, &v))
-                {
-                    // Print the result
-                    bytes = enc_string(cx, v, NULL);
-                    fprintf(stderr, "Stacktrace:\n%s", bytes);
-                    JS_free(cx, bytes);
-                }
-            }
-        }
-    }
-}
-
-
-JSBool
-couch_load_funcs(JSContext* cx, JSObject* obj, JSFunctionSpec* funcs)
-{
-    JSFunctionSpec* f;
-    for(f = funcs; f->name != NULL; f++) {
-        if(!JS_DefineFunction(cx, obj, f->name, f->call, f->nargs, f->flags)) {
-            fprintf(stderr, "Failed to create function: %s\n", f->name);
-            return JS_FALSE;
-        }
-    }
-    return JS_TRUE;
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/c_src/couch_js/util.h
----------------------------------------------------------------------
diff --git a/apps/couch/c_src/couch_js/util.h b/apps/couch/c_src/couch_js/util.h
deleted file mode 100644
index 65a2a06..0000000
--- a/apps/couch/c_src/couch_js/util.h
+++ /dev/null
@@ -1,35 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-#ifndef COUCHJS_UTIL_H
-#define COUCHJS_UTIL_H
-
-#include <jsapi.h>
-
-typedef struct {
-    int          use_http;
-    int          stack_size;
-    const char** scripts;
-    const char*  uri_file;
-    JSString*    uri;
-} couch_args;
-
-couch_args* couch_parse_args(int argc, const char* argv[]);
-int couch_fgets(char* buf, int size, FILE* fp);
-JSString* couch_readline(JSContext* cx, FILE* fp);
-JSString* couch_readfile(JSContext* cx, const char* filename);
-void couch_print(JSContext* cx, uintN argc, jsval* argv);
-void couch_error(JSContext* cx, const char* mesg, JSErrorReport* report);
-JSBool couch_load_funcs(JSContext* cx, JSObject* obj, JSFunctionSpec* funcs);
-
-
-#endif // Included util.h

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/c_src/spawnkillable/couchspawnkillable_win.c
----------------------------------------------------------------------
diff --git a/apps/couch/c_src/spawnkillable/couchspawnkillable_win.c b/apps/couch/c_src/spawnkillable/couchspawnkillable_win.c
deleted file mode 100644
index 0678231..0000000
--- a/apps/couch/c_src/spawnkillable/couchspawnkillable_win.c
+++ /dev/null
@@ -1,145 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License.  You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-// Do what 2 lines of shell script in couchspawnkillable does...
-// * Create a new suspended process with the same (duplicated) standard 
-//   handles as us.
-// * Write a line to stdout, consisting of the path to ourselves, plus
-//   '--kill {pid}' where {pid} is the PID of the newly created process.
-// * Un-suspend the new process.
-// * Wait for the process to terminate.
-// * Terminate with the child's exit-code.
-
-// Later, couch will call us with --kill and the PID, so we dutifully
-// terminate the specified PID.
-
-#include <stdlib.h>
-#include "windows.h"
-
-char *get_child_cmdline(int argc, char **argv)
-{
-    // make a new command-line, but skipping me.
-    // XXX - todo - spaces etc in args???
-    int i;
-    char *p, *cmdline;
-    int nchars = 0;
-    int nthis = 1;
-    for (i=1;i<argc;i++)
-        nchars += strlen(argv[i])+1;
-    cmdline = p = malloc(nchars+1);
-    if (!cmdline)
-        return NULL;
-    for (i=1;i<argc;i++) {
-        nthis = strlen(argv[i]);
-        strncpy(p, argv[i], nthis);
-        p[nthis] = ' ';
-        p += nthis+1;
-    }
-    // Replace the last space we added above with a '\0'
-    cmdline[nchars-1] = '\0';
-    return cmdline;
-}
-
-// create the child process, returning 0, or the exit-code we will
-// terminate with.
-int create_child(int argc, char **argv, PROCESS_INFORMATION *pi)
-{
-    char buf[1024];
-    DWORD dwcreate;
-    STARTUPINFO si;
-    char *cmdline;
-    if (argc < 2)
-        return 1;
-    cmdline = get_child_cmdline(argc, argv);
-    if (!cmdline)
-        return 2;
-
-    memset(&si, 0, sizeof(si));
-    si.cb = sizeof(si);
-    // depending on how *our* parent is started, we may or may not have
-    // a valid stderr stream - so although we try and duplicate it, only
-    // failing to duplicate stdin and stdout are considered fatal.
-    if (!DuplicateHandle(GetCurrentProcess(),
-                       GetStdHandle(STD_INPUT_HANDLE),
-                       GetCurrentProcess(),
-                       &si.hStdInput,
-                       0,
-                       TRUE, // inheritable
-                       DUPLICATE_SAME_ACCESS) ||
-       !DuplicateHandle(GetCurrentProcess(),
-                       GetStdHandle(STD_OUTPUT_HANDLE),
-                       GetCurrentProcess(),
-                       &si.hStdOutput,
-                       0,
-                       TRUE, // inheritable
-                       DUPLICATE_SAME_ACCESS)) {
-        return 3;
-    }
-    DuplicateHandle(GetCurrentProcess(),
-                   GetStdHandle(STD_ERROR_HANDLE),
-                   GetCurrentProcess(),
-                   &si.hStdError,
-                   0,
-                   TRUE, // inheritable
-                   DUPLICATE_SAME_ACCESS);
-
-    si.dwFlags = STARTF_USESTDHANDLES;
-    dwcreate = CREATE_SUSPENDED;
-    if (!CreateProcess( NULL, cmdline,
-                        NULL,
-                        NULL,
-                        TRUE, // inherit handles
-                        dwcreate,
-                        NULL, // environ
-                        NULL, // cwd
-                        &si,
-                        pi))
-        return 4;
-    return 0;
-}
-
-// and here we go...
-int main(int argc, char **argv)
-{
-    char out_buf[1024];
-    int rc;
-    DWORD cbwritten;
-    DWORD exitcode;
-    PROCESS_INFORMATION pi;
-    if (argc==3 && strcmp(argv[1], "--kill")==0) {
-        HANDLE h = OpenProcess(PROCESS_TERMINATE, 0, atoi(argv[2]));
-        if (!h)
-            return 1;
-        if (!TerminateProcess(h, 0))
-            return 2;
-        CloseHandle(h);
-        return 0;
-    }
-    // spawn the new suspended process
-    rc = create_child(argc, argv, &pi);
-    if (rc)
-        return rc;
-    // Write the 'terminate' command, which includes this PID, back to couch.
-    // *sob* - what about spaces etc?
-    sprintf_s(out_buf, sizeof(out_buf), "%s --kill %d\n", 
-              argv[0], pi.dwProcessId);
-    WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), out_buf, strlen(out_buf), 
-              &cbwritten, NULL);
-    // Let the child process go...
-    ResumeThread(pi.hThread);
-    // Wait for the process to terminate so we can reflect the exit code
-    // back to couch.
-    WaitForSingleObject(pi.hProcess, INFINITE);
-    if (!GetExitCodeProcess(pi.hProcess, &exitcode))
-        return 6;
-    return exitcode;
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/include/couch_db.hrl
----------------------------------------------------------------------
diff --git a/apps/couch/include/couch_db.hrl b/apps/couch/include/couch_db.hrl
deleted file mode 100644
index e0a1c82..0000000
--- a/apps/couch/include/couch_db.hrl
+++ /dev/null
@@ -1,286 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--define(LOCAL_DOC_PREFIX, "_local/").
--define(DESIGN_DOC_PREFIX0, "_design").
--define(DESIGN_DOC_PREFIX, "_design/").
--define(DEFAULT_COMPRESSION, snappy).
-
--define(MIN_STR, <<"">>).
--define(MAX_STR, <<255>>). % illegal utf string
-
-% the lowest possible database sequence number
--define(LOWEST_SEQ, 0).
-
--define(REWRITE_COUNT, couch_rewrite_count).
-
--define(JSON_ENCODE(V), jiffy:encode(V, [uescape])).
--define(JSON_DECODE(V), couch_util:json_decode(V)).
-
--define(b2l(V), binary_to_list(V)).
--define(l2b(V), list_to_binary(V)).
--define(term_to_bin(T), term_to_binary(T, [{minor_version, 1}])).
--define(term_size(T),
-    try
-        erlang:external_size(T)
-    catch _:_ ->
-        byte_size(?term_to_bin(T))
-    end).
-
--define(DEFAULT_ATTACHMENT_CONTENT_TYPE, <<"application/octet-stream">>).
-
--define(LOG_DEBUG(Format, Args),
-    case couch_log:debug_on(?MODULE) of
-        true ->
-            couch_log:debug(Format, Args);
-        false -> ok
-    end).
-
--define(LOG_INFO(Format, Args),
-    case couch_log:info_on(?MODULE) of
-        true ->
-            couch_log:info(Format, Args);
-        false -> ok
-    end).
-
--define(LOG_WARN(Format, Args),
-    case couch_log:warn_on(?MODULE) of
-        true ->
-            couch_log:warn(Format, Args);
-        false -> ok
-    end).
-
--define(LOG_ERROR(Format, Args), couch_log:error(Format, Args)).
-
-% Tree::term() is really a tree(), but we don't want to require R13B04 yet
--type branch() :: {Key::term(), Value::term(), Tree::term()}.
--type path() :: {Start::pos_integer(), branch()}.
--type tree() :: [branch()]. % sorted by key
-
--record(rev_info,
-    {
-    rev,
-    seq = 0,
-    deleted = false,
-    body_sp = nil % stream pointer
-    }).
-
--record(doc_info,
-    {
-    id = <<"">>,
-    high_seq = 0,
-    revs = [] % rev_info
-    }).
-
--record(full_doc_info,
-    {id = <<"">>,
-    update_seq = 0,
-    deleted = false,
-    rev_tree = [],
-    leafs_size = 0
-    }).
-
--record(httpd,
-    {mochi_req,
-    peer,
-    method,
-    requested_path_parts,
-    path_parts,
-    db_url_handlers,
-    user_ctx,
-    req_body = undefined,
-    design_url_handlers,
-    auth,
-    default_fun,
-    url_handlers
-    }).
-
-
--record(doc,
-    {
-    id = <<"">>,
-    revs = {0, []},
-
-    % the json body object.
-    body = {[]},
-
-    atts = [], % attachments
-
-    deleted = false,
-
-    % key/value tuple of meta information, provided when using special options:
-    % couch_db:open_doc(Db, Id, Options).
-    meta = []
-    }).
-
-
--record(att,
-    {
-    name,
-    type,
-    att_len,
-    disk_len, % length of the attachment in its identity form
-              % (that is, without a content encoding applied to it)
-              % differs from att_len when encoding /= identity
-    md5= <<>>,
-    revpos=0,
-    data,
-    encoding=identity % currently supported values are:
-                      %     identity, gzip
-                      % additional values to support in the future:
-                      %     deflate, compress
-    }).
-
-
--record(user_ctx,
-    {
-    name=null,
-    roles=[],
-    handler
-    }).
-
-% This should be updated anytime a header change happens that requires more
-% than filling in new defaults.
-%
-% As long the changes are limited to new header fields (with inline
-% defaults) added to the end of the record, then there is no need to increment
-% the disk revision number.
-%
-% if the disk revision is incremented, then new upgrade logic will need to be
-% added to couch_db_updater:init_db.
-
--define(LATEST_DISK_VERSION, 6).
-
--record(db_header,
-    {disk_version = ?LATEST_DISK_VERSION,
-     update_seq = 0,
-     unused = 0,
-     fulldocinfo_by_id_btree_state = nil,
-     docinfo_by_seq_btree_state = nil,
-     local_docs_btree_state = nil,
-     purge_seq = 0,
-     purged_docs = nil,
-     security_ptr = nil,
-     revs_limit = 1000
-    }).
-
--record(db,
-    {main_pid = nil,
-    update_pid = nil,
-    compactor_pid = nil,
-    instance_start_time, % number of microsecs since jan 1 1970 as a binary string
-    fd,
-    updater_fd,
-    fd_ref_counter,
-    header = #db_header{},
-    committed_update_seq,
-    fulldocinfo_by_id_btree,
-    docinfo_by_seq_btree,
-    local_docs_btree,
-    update_seq,
-    name,
-    filepath,
-    validate_doc_funs = [],
-    security = [],
-    security_ptr = nil,
-    user_ctx = #user_ctx{},
-    waiting_delayed_commit = nil,
-    revs_limit = 1000,
-    fsync_options = [],
-    options = [],
-    compression,
-    before_doc_update = nil, % nil | fun(Doc, Db) -> NewDoc
-    after_doc_read = nil     % nil | fun(Doc, Db) -> NewDoc
-    }).
-
-
--record(view_query_args, {
-    start_key,
-    end_key,
-    start_docid = ?MIN_STR,
-    end_docid = ?MAX_STR,
-
-    direction = fwd,
-    inclusive_end=true, % aka a closed-interval
-
-    limit = 10000000000, % Huge number to simplify logic
-    skip = 0,
-
-    group_level = 0,
-
-    view_type = nil,
-    include_docs = false,
-    doc_options = [],
-    conflicts = false,
-    stale = false,
-    multi_get = false,
-    callback = nil,
-    list = nil
-}).
-
--record(view_fold_helper_funs, {
-    reduce_count,
-    passed_end,
-    start_response,
-    send_row
-}).
-
--record(reduce_fold_helper_funs, {
-    start_response,
-    send_row
-}).
-
--record(extern_resp_args, {
-    code = 200,
-    stop = false,
-    data = <<>>,
-    ctype = "application/json",
-    headers = [],
-    json = nil
-}).
-
--record(index_header,
-    {seq=0,
-    purge_seq=0,
-    id_btree_state=nil,
-    view_states=nil
-    }).
-
-% small value used in revision trees to indicate the revision isn't stored
--define(REV_MISSING, []).
-
--record(changes_args, {
-    feed = "normal",
-    dir = fwd,
-    since = 0,
-    limit = 1000000000000000,
-    style = main_only,
-    heartbeat,
-    timeout,
-    filter = "",
-    filter_fun,
-    filter_args = [],
-    include_docs = false,
-    doc_options = [],
-    conflicts = false,
-    db_open_options = []
-}).
-
--record(btree, {
-    fd,
-    root,
-    extract_kv = fun({_Key, _Value} = KV) -> KV end,
-    assemble_kv = fun(Key, Value) -> {Key, Value} end,
-    less = fun(A, B) -> A < B end,
-    reduce = nil,
-    compression = ?DEFAULT_COMPRESSION
-}).

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/priv/couchspawnkillable.sh
----------------------------------------------------------------------
diff --git a/apps/couch/priv/couchspawnkillable.sh b/apps/couch/priv/couchspawnkillable.sh
deleted file mode 100755
index f8d042e..0000000
--- a/apps/couch/priv/couchspawnkillable.sh
+++ /dev/null
@@ -1,20 +0,0 @@
-#! /bin/sh -e
-
-# Licensed under the Apache License, Version 2.0 (the "License"); you may not
-# use this file except in compliance with the License. You may obtain a copy of
-# the License at
-#
-#   http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-# License for the specific language governing permissions and limitations under
-# the License.
-
-# The purpose of this script is to echo an OS specific command before launching
-# the actual process. This provides a way for Erlang to hard-kill its external
-# processes.
-
-echo "kill -9 $$"
-exec $*

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/priv/stat_descriptions.cfg
----------------------------------------------------------------------
diff --git a/apps/couch/priv/stat_descriptions.cfg b/apps/couch/priv/stat_descriptions.cfg
deleted file mode 100644
index b80d768..0000000
--- a/apps/couch/priv/stat_descriptions.cfg
+++ /dev/null
@@ -1,50 +0,0 @@
-%% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-%% use this file except in compliance with the License. You may obtain a copy of
-%% the License at
-%%
-%%   http://www.apache.org/licenses/LICENSE-2.0
-%%
-%% Unless required by applicable law or agreed to in writing, software
-%% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-%% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-%% License for the specific language governing permissions and limitations under
-%% the License.
-
-% Style guide for descriptions: Start with a lowercase letter & do not add
-% a trailing full-stop / period
-% Please keep this in alphabetical order
-
-{couchdb, database_writes, "number of times a database was changed"}.
-{couchdb, database_reads, "number of times a document was read from a database"}.
-{couchdb, open_databases, "number of open databases"}.
-{couchdb, open_os_files, "number of file descriptors CouchDB has open"}.
-{couchdb, request_time, "length of a request inside CouchDB without MochiWeb"}.
-{couchdb, auth_cache_hits, "number of authentication cache hits"}.
-{couchdb, auth_cache_misses, "number of authentication cache misses"}.
-
-{httpd, bulk_requests, "number of bulk requests"}.
-{httpd, requests, "number of HTTP requests"}.
-{httpd, temporary_view_reads, "number of temporary view reads"}.
-{httpd, view_reads, "number of view reads"}.
-{httpd, clients_requesting_changes, "number of clients for continuous _changes"}.
-
-{httpd_request_methods, 'COPY', "number of HTTP COPY requests"}.
-{httpd_request_methods, 'DELETE', "number of HTTP DELETE requests"}.
-{httpd_request_methods, 'GET', "number of HTTP GET requests"}.
-{httpd_request_methods, 'HEAD', "number of HTTP HEAD requests"}.
-{httpd_request_methods, 'POST', "number of HTTP POST requests"}.
-{httpd_request_methods, 'PUT', "number of HTTP PUT requests"}.
-
-{httpd_status_codes, '200', "number of HTTP 200 OK responses"}.
-{httpd_status_codes, '201', "number of HTTP 201 Created responses"}.
-{httpd_status_codes, '202', "number of HTTP 202 Accepted responses"}.
-{httpd_status_codes, '301', "number of HTTP 301 Moved Permanently responses"}.
-{httpd_status_codes, '304', "number of HTTP 304 Not Modified responses"}.
-{httpd_status_codes, '400', "number of HTTP 400 Bad Request responses"}.
-{httpd_status_codes, '401', "number of HTTP 401 Unauthorized responses"}.
-{httpd_status_codes, '403', "number of HTTP 403 Forbidden responses"}.
-{httpd_status_codes, '404', "number of HTTP 404 Not Found responses"}.
-{httpd_status_codes, '405', "number of HTTP 405 Method Not Allowed responses"}.
-{httpd_status_codes, '409', "number of HTTP 409 Conflict responses"}.
-{httpd_status_codes, '412', "number of HTTP 412 Precondition Failed responses"}.
-{httpd_status_codes, '500', "number of HTTP 500 Internal Server Error responses"}.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/rebar.config.script
----------------------------------------------------------------------
diff --git a/apps/couch/rebar.config.script b/apps/couch/rebar.config.script
deleted file mode 100644
index ca79b39..0000000
--- a/apps/couch/rebar.config.script
+++ /dev/null
@@ -1,108 +0,0 @@
-%% -*- tab-width: 4;erlang-indent-level: 4;indent-tabs-mode: nil -*-
-%% ex: ft=erlang ts=4 sw=4 et
-
-%% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-%% use this file except in compliance with the License. You may obtain a copy of
-%% the License at
-%%
-%%   http://www.apache.org/licenses/LICENSE-2.0
-%%
-%% Unless required by applicable law or agreed to in writing, software
-%% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-%% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-%% License for the specific language governing permissions and limitations under
-%% the License.
-
-
-Cfg = case file:consult("../../pkg.vars.config") of
-          {ok, Terms} ->
-              Terms;
-          _Err ->
-              []
-      end,
-
-%% get version infos
-MajorVersion = integer_to_list(proplists:get_value(version_major, Cfg, 0)),
-MinorVersion = integer_to_list(proplists:get_value(version_minor, Cfg, 0)),
-RevVersion = integer_to_list(proplists:get_value(version_revision, Cfg, 0)),
-StageVersion = proplists:get_value(version_stage, Cfg, ""),
-RelVersion = proplists:get_value(version_release, Cfg, ""),
-
-%% build the version
-BaseVersion = MajorVersion ++ "." ++ MinorVersion ++ "." ++ RevVersion,
-SecondaryVersion = StageVersion ++ RelVersion,
-Version = case os:getenv("RELEASE") of
-    "1" ->
-        BaseVersion;
-    _ ->
-        BaseVersion ++ SecondaryVersion
-end,
-
-%% couchjs name
-CouchJSName = proplists:get_value(couchjs_name, Cfg, "couchjs"),
-
-%% build config.h
-ConfigH = [{package_name, proplists:get_value(vendor_name, Cfg, "")},
-           {package_string, proplists:get_value(vendor_name, Cfg, "")
-                            ++ " " ++ Version },
-           {package_bugreport, proplists:get_value(package_bugreport, Cfg, "")},
-           {package_version, Version},
-           {couchjs_name, CouchJSName}],
-
-%% write config.h
-ConfigHStr = lists:foldl(fun({K, V}, Acc) ->
-            K1 = string:to_upper(atom_to_list(K)),
-            case K1 of
-                "VERSION_" ++ _ -> Acc;
-                _ ->
-                    ["#define ", K1, " ", $", V, $", $\n | Acc]
-            end
-        end, [], ConfigH),
-ok = file:write_file("c_src/couch_js/config.h", iolist_to_binary(ConfigHStr)),
-
-GetFlag = fun(Name, Default) ->
-        case os:getenv(Name) of
-            false -> Default;
-            Val -> Val
-        end
-    end,
-
-
-JSLIBS = GetFlag("JS_LIBS", "-lmozjs185"),
-JSCFLAGS = GetFlag("JS_CFLAGS", "-I/usr/include/js"),
-
-{CFLAGS, LDFLAGS}  = case os:type() of
-    {unix, darwin} ->
-        {"-DXP_UNIX " ++ JSCFLAGS, JSLIBS};
-    {unix, _} ->
-        {"-DXP_UNIX " ++ JSCFLAGS, JSLIBS ++ " -lm"};
-    _ ->
-        {"-DXP_WIN " ++ JSCFLAGS, JSLIBS}
-end,
-
-{CFLAGS1, LDFLAGS1} = case os:getenv("WITHOUT_CURL") of
-    "1" -> {"-DWITHOUT_CURL " ++ CFLAGS, LDFLAGS};
-    _ -> {CFLAGS, LDFLAGS ++ " -lcurl"}
-end,
-
-PortSpecs0 = case os:type() of
-    {win32, _} ->
-        [{filename:join(["priv", "couchspawnkillable"]),
-            ["c_src/spawnkillable/*.c"]}];
-    _ ->
-        {ok, _} = file:copy("priv/couchspawnkillable.sh",
-                            "priv/couchspawnkillable"),
-        os:cmd("chmod +x priv/couchspawnkillable"),
-        []
-    end,
-
-PortEnv = [{port_env, [
-            {"CFLAGS",  "$CFLAGS -Wall -c -g -O2 " ++ CFLAGS1},
-            {"LDFLAGS", "$LDFLAGS " ++ LDFLAGS1}]},
-
-           {port_specs, [
-            {filename:join(["priv", CouchJSName]),
-            ["c_src/couch_js/*.c"]}] ++ PortSpecs0}
-],
-
-lists:keymerge(1,lists:keysort(1, PortEnv), lists:keysort(1, CONFIG)).

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch.app.src
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch.app.src b/apps/couch/src/couch.app.src
deleted file mode 100644
index e69de29..0000000

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch.app.src.script
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch.app.src.script b/apps/couch/src/couch.app.src.script
deleted file mode 100644
index 45b5333..0000000
--- a/apps/couch/src/couch.app.src.script
+++ /dev/null
@@ -1,67 +0,0 @@
-%% -*- tab-width: 4;erlang-indent-level: 4;indent-tabs-mode: nil -*-
-%% ex: ft=erlang ts=4 sw=4 et
-
-%% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-%% use this file except in compliance with the License. You may obtain a copy of
-%% the License at
-%%
-%%   http://www.apache.org/licenses/LICENSE-2.0
-%%
-%% Unless required by applicable law or agreed to in writing, software
-%% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-%% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-%% License for the specific language governing permissions and limitations under
-%% the License.
-
-
-Cfg = case file:consult("../../pkg.vars.config") of
-          {ok, Terms} ->
-              Terms;
-          _Err ->
-              []
-      end,
-
-%% get version infos
-MajorVersion = integer_to_list(proplists:get_value(version_major, Cfg, 0)),
-MinorVersion = integer_to_list(proplists:get_value(version_minor, Cfg, 0)),
-RevVersion = integer_to_list(proplists:get_value(version_revision, Cfg, 0)),
-StageVersion = proplists:get_value(version_stage, Cfg, ""),
-RelVersion = proplists:get_value(version_release, Cfg, ""),
-
-%% build the version
-BaseVersion = MajorVersion ++ "." ++ MinorVersion ++ "." ++ RevVersion,
-SecondaryVersion = StageVersion ++ RelVersion,
-RelVsn = case os:getenv("RELEASE") of
-    "1" ->
-        BaseVersion;
-    _ ->
-        BaseVersion ++ SecondaryVersion
-end,
-
-
-[
-    {application, couch, [
-        {description, "Apache CouchDB"},
-        {vsn, "1.6.1"},
-        {registered, [
-            couch_config,
-            couch_db_update,
-            couch_db_update_notifier_sup,
-            couch_external_manager,
-            couch_httpd,
-            couch_log,
-            couch_primary_services,
-            couch_query_servers,
-            couch_secondary_services,
-            couch_server,
-            couch_server_sup,
-            couch_stats_aggregator,
-            couch_stats_collector,
-            couch_task_status
-        ]},
-        {mod, {couch_app, []}},
-        {env, [{couch_rel, RelVsn}]},
-        {applications, [kernel, stdlib, crypto, sasl, public_key, ssl,
-                        inets, oauth, ibrowse, mochiweb, os_mon]}
-    ]}
-].

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch.erl b/apps/couch/src/couch.erl
deleted file mode 100644
index 92c2b74..0000000
--- a/apps/couch/src/couch.erl
+++ /dev/null
@@ -1,67 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch).
-
--export([get_app_env/2,
-         version/0,
-         release_version/0,
-         start/0,
-         stop/0,
-         restart/0,
-         reload/0]).
-
-get_app_env(Env, Default) ->
-    case application:get_env(couch, Env) of
-        {ok, Val} -> Val;
-        undefined -> Default
-    end.
-
-version() ->
-    case application:get_key(couch, vsn) of
-        {ok, FullVersion} ->
-            hd(string:tokens(FullVersion, "-"));
-        _ ->
-            "0.0.0"
-    end.
-
-release_version() ->
-    case application:get_env(couch, couch_rel) of
-        {ok, Vsn} ->
-            Vsn;
-        _ ->
-            "0.0.0"
-    end.
-
-start() ->
-    application:start(couch).
-
-stop() ->
-    application:stop(couch).
-
-restart() ->
-    case stop() of
-    ok ->
-        start();
-    {error, {not_started,couch}} ->
-        start();
-    {error, Reason} ->
-        {error, Reason}
-    end.
-
-reload() ->
-    case supervisor:terminate_child(couch_server_sup, couch_config) of
-    ok ->
-        supervisor:restart_child(couch_server_sup, couch_config);
-    {error, Reason} ->
-        {error, Reason}
-    end.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_app.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_app.erl b/apps/couch/src/couch_app.erl
deleted file mode 100644
index a8d215e..0000000
--- a/apps/couch/src/couch_app.erl
+++ /dev/null
@@ -1,36 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_app).
-
--behaviour(application).
-
--include("couch_db.hrl").
-
--export([start/2, stop/1]).
-
--define(CONF_FILES, ["couch.ini", "couch_httpd.ini", "local.ini"]).
-
-start(_Type, _Args) ->
-    couch_util:start_app_deps(couch),
-    IniFiles = get_ini_files(),
-    couch_server_sup:start_link(IniFiles).
-
-stop(_) ->
-    ok.
-
-get_ini_files() ->
-    DefaultConfDir =  filename:join([code:root_dir(), "./etc"]),
-    Defaults = lists:map(fun(FName) ->
-                    filename:join(DefaultConfDir, FName)
-            end, ?CONF_FILES),
-    couch:get_app_env(config_files, Defaults).


[33/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/app.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/app.js b/apps/fauxton/app/app.js
deleted file mode 100644
index 0a51410..0000000
--- a/apps/fauxton/app/app.js
+++ /dev/null
@@ -1,122 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-  // Application.
-  "initialize",
-
-  // Libraries
-  "jquery",
-  "lodash",
-  "backbone",
-  "bootstrap",
-
-  "helpers",
-  "mixins",
-
-   // Plugins.
-  "plugins/backbone.layoutmanager",
-  "plugins/jquery.form"
-
-],
-
-function(app, $, _, Backbone, Bootstrap, Helpers, Mixins) {
-
-   // Make sure we have a console.log
-  if (typeof console == "undefined") {
-    console = {
-      log: function(){}
-    };
-  }
-
-  // Provide a global location to place configuration settings and module
-  // creation also mix in Backbone.Events
-  _.extend(app, Backbone.Events, {
-    mixins: Mixins,
-
-    renderView: function(baseView, selector, view, options, callback) {
-      baseView.setView(selector, new view(options)).render().then(callback);
-    },
-
-    // Create a custom object with a nested Views object.
-    module: function(additionalProps) {
-      return _.extend({ Views: {} }, additionalProps);
-    },
-
-    // Thanks to: http://stackoverflow.com/a/2880929
-    getParams: function(queryString) {
-      if (queryString) {
-        // I think this could be combined into one if
-        if (queryString.substring(0,1) === "?") {
-          queryString = queryString.substring(1);
-        } else if (queryString.indexOf('?') > -1) {
-          queryString = queryString.split('?')[1];
-        }
-      }
-      var hash = window.location.hash.split('?')[1];
-      queryString = queryString || hash || window.location.search.substring(1);
-      var match,
-      urlParams = {},
-      pl     = /\+/g,  // Regex for replacing addition symbol with a space
-      search = /([^&=]+)=?([^&]*)/g,
-      decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
-      query  = queryString;
-
-      if (queryString) {
-        while ((match = search.exec(query))) {
-          urlParams[decode(match[1])] = decode(match[2]);
-        }
-      }
-
-      return urlParams;
-    }
-  });
-
-  // Localize or create a new JavaScript Template object.
-  var JST = window.JST = window.JST || {};
-
-  // Configure LayoutManager with Backbone Boilerplate defaults.
-  Backbone.Layout.configure({
-    // Allow LayoutManager to augment Backbone.View.prototype.
-    manage: true,
-
-    prefix: "app/",
-
-    // Inject app/helper.js for shared functionality across all html templates
-    renderTemplate: function(template, context) {
-      return template(_.extend(Helpers, context));
-    },
-
-    fetchTemplate: function(path) {
-      // Initialize done for use in async-mode
-      var done;
-
-      // Concatenate the file extension.
-      path = path + ".html";
-
-      // If cached, use the compiled template.
-      if (JST[path]) {
-        return JST[path];
-      } else {
-        // Put fetch into `async-mode`.
-        done = this.async();
-        // Seek out the template asynchronously.
-        return $.ajax({ url: app.root + path }).then(function(contents) {
-          done(JST[path] = _.template(contents));
-        });
-      }
-    }
-  });
-
-
-  return app;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/config.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/config.js b/apps/fauxton/app/config.js
deleted file mode 100644
index 2977969..0000000
--- a/apps/fauxton/app/config.js
+++ /dev/null
@@ -1,60 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-// Set the require.js configuration for your application.
-require.config({
-
-  // Initialize the application with the main application file.
-  deps: ["main"],
-
-  paths: {
-    // JavaScript folders.
-    libs: "../assets/js/libs",
-    plugins: "../assets/js/plugins",
-
-    // Libraries.
-    jquery: "../assets/js/libs/jquery",
-    lodash: "../assets/js/libs/lodash",
-    backbone: "../assets/js/libs/backbone",
-    "backbone.layoutmanger": "../assets/js/plugins/backbone.layoutmanager",
-    bootstrap: "../assets/js/libs/bootstrap",
-    spin: "../assets/js/libs/spin.min",
-    d3: "../assets/js/libs/d3",
-    "nv.d3": "../assets/js/libs/nv.d3",
-    "ace":"../assets/js/libs/ace"
-  },
-
-  baseUrl: '/',
-
-  map: {
-    "*": {
-      'underscore': 'lodash'
-    }
-  },
-
-  shim: {
-    // Backbone library depends on lodash and jQuery.
-    backbone: {
-      deps: ["lodash", "jquery"],
-      exports: "Backbone"
-    },
-
-    bootstrap: {
-      deps: ["jquery"],
-      exports: "Bootstrap"
-    },
-
-    "plugins/prettify": [],
-
-    "plugins/jquery.form": ["jquery"]
-  }
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/helpers.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/helpers.js b/apps/fauxton/app/helpers.js
deleted file mode 100644
index 73a37ca..0000000
--- a/apps/fauxton/app/helpers.js
+++ /dev/null
@@ -1,78 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-
-// This file creates a set of helper functions that will be loaded for all html
-// templates. These functions should be self contained and not rely on any 
-// external dependencies as they are loaded prior to the application. We may
-// want to change this later, but for now this should be thought of as a
-// "purely functional" helper system.
-
-
-define([
-  "d3"
-],
-
-function() {
-
-  var Helpers = {};
-
-  Helpers.imageUrl = function(path) {
-    // TODO: add dynamic path for different deploy targets
-    return path;
-  };
-
-
-  // Get the URL for documentation, wiki, wherever we store it.
-  // update the URLs in documentation_urls.js 
-  Helpers.docs =  {
-    "docs": "http://docs.couchdb.org/en/latest/intro/api.html#documents",
-    "all_dbs": "http://docs.couchdb.org/en/latest/api/server/common.html?highlight=all_dbs#get--_all_dbs",
-    "replication_doc": "http://docs.couchdb.org/en/latest/replication/replicator.html#basics",
-    "design_doc": "http://docs.couchdb.org/en/latest/couchapp/ddocs.html#design-docs",
-    "view_functions": "http://docs.couchdb.org/en/latest/couchapp/ddocs.html#view-functions",
-    "map_functions": "http://docs.couchdb.org/en/latest/couchapp/ddocs.html#map-functions",
-    "reduce_functions": "http://docs.couchdb.org/en/latest/couchapp/ddocs.html#reduce-and-rereduce-functions",
-    "api_reference": "http://docs.couchdb.org/en/latest/http-api.html",
-    "database_permission": "http://docs.couchdb.org/en/latest/api/database/security.html#db-security",
-    "stats": "http://docs.couchdb.org/en/latest/api/server/common.html?highlight=stats#get--_stats",
-    "_active_tasks": "http://docs.couchdb.org/en/latest/api/server/common.html?highlight=stats#active-tasks",
-    "log": "http://docs.couchdb.org/en/latest/api/server/common.html?highlight=stats#log",
-    "config": "http://docs.couchdb.org/en/latest/config/index.html",
-    "views": "http://docs.couchdb.org/en/latest/intro/overview.html#views"
-  }; 
-  
-  Helpers.getDocUrl = function(docKey){
-    return Helpers.docs[docKey] || '#';
-  };
-
-  // File size pretty printing, taken from futon.format.js
-  Helpers.formatSize = function(size) {
-      var jump = 512;
-      if (size < jump) return size + " bytes";
-      var units = ["KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
-      var i = 0;
-      while (size >= jump && i < units.length) {
-        i += 1;
-        size /= 1024;
-      }
-      return size.toFixed(1) + ' ' + units[i - 1];
-    };
-
-  Helpers.formatDate = function(timestamp){
-    format = d3.time.format("%b. %e at %H:%M%p"); 
-    return format(new Date(timestamp*1000));
-  };
-
-  return Helpers;
-});
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/initialize.js.underscore
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/initialize.js.underscore b/apps/fauxton/app/initialize.js.underscore
deleted file mode 100644
index 02689a1..0000000
--- a/apps/fauxton/app/initialize.js.underscore
+++ /dev/null
@@ -1,33 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-/*
- * ::WARNING::
- * THIS IS A GENERATED FILE. DO NOT EDIT.
- */
-
-
-define([],
-function() {
-  // Provide a global location to place configuration settings and module
-  // creation.
-  var app = {
-    // The root path to run the application.
-    root: "<%= root %>",
-    version: "<%= version %>",
-    // Host is used as prefix for urls
-    host: "<%= host %>" ,
-  };
-
-  return app; 
-});
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/load_addons.js.underscore
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/load_addons.js.underscore b/apps/fauxton/app/load_addons.js.underscore
deleted file mode 100644
index 9686ad7..0000000
--- a/apps/fauxton/app/load_addons.js.underscore
+++ /dev/null
@@ -1,27 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-
-/*
- * ::WARNING::
- * THIS IS A GENERATED FILE. DO NOT EDIT.
- */
-define([
-  <%= '"' + deps.join('","') + '"' %>
-],
-function() {
-  var LoadAddons = {
-    addons: arguments
-  };
-
-  return LoadAddons;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/main.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/main.js b/apps/fauxton/app/main.js
deleted file mode 100644
index 6fe9991..0000000
--- a/apps/fauxton/app/main.js
+++ /dev/null
@@ -1,48 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-require([
-        // Application.
-        "app",
-
-        // Main Router.
-        "router"
-],
-
-function(app, Router) {
-
-  // Define your master router on the application namespace and trigger all
-  // navigation from this instance.
-  app.router = new Router();
-  // Trigger the initial route and enable HTML5 History API support, set the
-  // root folder to '/' by default.  Change in app.js.
-  Backbone.history.start({ pushState: false, root: app.root });
-  // All navigation that is relative should be passed through the navigate
-  // method, to be processed by the router. If the link has a `data-bypass`
-  // attribute, bypass the delegation completely.
-  $(document).on("click", "a:not([data-bypass])", function(evt) {
-    // Get the absolute anchor href.
-    var href = { prop: $(this).prop("href"), attr: $(this).attr("href") };
-    // Get the absolute root.
-    var root = location.protocol + "//" + location.host + app.root;
-    // Ensure the root is part of the anchor href, meaning it's relative.
-    if (href.prop && href.prop.slice(0, root.length) === root) {
-      // Stop the default event to ensure the link will not cause a page
-      // refresh.
-      evt.preventDefault();
-
-      //User app navigate so that navigate goes through a central place
-      app.router.navigate(href.attr, true);
-    }
-
-  });
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/mixins.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/mixins.js b/apps/fauxton/app/mixins.js
deleted file mode 100644
index 15af3ee..0000000
--- a/apps/fauxton/app/mixins.js
+++ /dev/null
@@ -1,65 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-
-// This file creates a set of helper functions that will be loaded for all html
-// templates. These functions should be self contained and not rely on any 
-// external dependencies as they are loaded prior to the application. We may
-// want to change this later, but for now this should be thought of as a
-// "purely functional" helper system.
-
-
-define([
-  "jquery",
-  "lodash"
-],
-
-function($, _ ) {
-
-  var mixins = {};
-
-  var onWindowResize = {};
-   
-  mixins.addWindowResize = function(fun, key){
-    onWindowResize[key]=fun;
-    // You shouldn't need to call it here. Just define it at startup and each time it will loop 
-    // through all the functions in the hash.
-    //app.initWindowResize();
-  };
-   
-  mixins.removeWindowResize = function(key){
-    delete onWindowResize[key];
-    mixins.initWindowResize();
-  };
-   
-  mixins.initWindowResize = function(){
-  //when calling this it should be overriding what was called previously
-    window.onresize = function(e) {
-       // could do this instead of the above for loop
-      _.each(onWindowResize, function (fn) {
-        fn();
-      });
-    };
-  };
-
-  mixins.removeSpecialCharacters = function(name){
-    return name.replace(/[^\w\s]/gi,"");
-  };
-
-  mixins.safeURLName = function(name){
-    var checkforBad = name.match(/[\$\-/_,+-]/g);
-    return (checkforBad !== null)?encodeURIComponent(name):name;
-  };
-
-  return mixins;
-});
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/modules/databases/base.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/modules/databases/base.js b/apps/fauxton/app/modules/databases/base.js
deleted file mode 100644
index 6ff12c6..0000000
--- a/apps/fauxton/app/modules/databases/base.js
+++ /dev/null
@@ -1,37 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-  "app",
-
-  "api",
-
-  // Modules
-  "modules/databases/routes",
-  // Views
-  "modules/databases/views"
-
-],
-
-function(app, FauxtonAPI, Databases, Views) {
-  Databases.Views = Views;
-
-  // Utility functions
-  Databases.databaseUrl = function(database) {
-    var name = _.isObject(database) ? database.id : database,
-        dbname = app.mixins.safeURLName(name);
-
-    return ["/database/", dbname, "/_all_docs?limit=" + Databases.DocLimit].join('');
-  };
-
-  return Databases;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/modules/databases/resources.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/modules/databases/resources.js b/apps/fauxton/app/modules/databases/resources.js
deleted file mode 100644
index f3bde80..0000000
--- a/apps/fauxton/app/modules/databases/resources.js
+++ /dev/null
@@ -1,193 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-  "app",
-
-  "api",
-
-  // Modules
-  "modules/documents/resources"
-],
-
-function(app, FauxtonAPI, Documents) {
-  var Databases = FauxtonAPI.module();
-
-  Databases.DocLimit = 20;
-
-  Databases.Model = Backbone.Model.extend({
-    initialize: function(options) {
-      this.status = new Databases.Status({
-        database: this
-      });
-    },
-
-    documentation: function(){
-      return "all_dbs";
-    },
-    
-    buildAllDocs: function(params) {
-      this.allDocs = new Documents.AllDocs(null, {
-        database: this,
-        params: params
-      });
-
-      return this.allDocs;
-    },
-
-    isNew: function(){
-      // Databases are never new, to make Backbone do a PUT
-      return false;
-    },
-
-    url: function(context) {
-      if (context === "index") {
-        return "/database/" + this.safeID() + "/_all_docs";
-      } else if (context === "web-index") {
-        return "#/database/"+ this.safeID() + "/_all_docs?limit=" + Databases.DocLimit;
-      } else if (context === "apiurl") { 
-        return window.location.origin + "/database/" + this.safeID() + "/_all_docs";
-      } else if (context === "changes") {
-        return "/database/" + this.safeID() + "/_changes?descending=true&limit=100&include_docs=true";
-      } else if (context === "changes-apiurl") { 
-        return window.location.origin + "/database/" + this.safeID() + "/_changes?descending=true&limit=100&include_docs=true";
-      } else if (context === "app") {
-        return "/database/" + this.safeID();
-      } else {
-        return app.host + "/" + this.safeID();
-      }
-    },
-    safeName: function(){
-      return app.mixins.safeURLName(this.get("name"));
-    },
-    safeID: function() {
-      return app.mixins.safeURLName(this.id);
-    },
-    buildChanges: function (params) {
-      this.changes = new Databases.Changes({
-        database: this,
-        params: params
-      });
-
-      return this.changes;
-    }
-  });
-
-  Databases.Changes = Backbone.Collection.extend({
-
-    initialize: function(options) {
-      this.database = options.database;
-      this.params = options.params;
-    },
-    documentation: function(){
-      return "changes";
-    },
-    url: function (context) {
-      var query = "";
-      if (this.params) {
-        query = "?" + $.param(this.params);
-      }
-      if (context === "apiurl") { 
-        return window.location.origin + '/' + this.database.safeID() + '/_changes' + query;
-      } else {
-
-      return app.host + '/' + this.database.safeID() + '/_changes' + query;
-      }
-    },
-
-    parse: function (resp) {
-      this.last_seq = resp.last_seq;
-      return resp.results;
-    }
-  });
-
-  Databases.Status = Backbone.Model.extend({
-    url: function() {
-      return app.host + "/" + this.database.safeID();
-    },
-
-    initialize: function(options) {
-      this.database = options.database;
-    },
-
-    numDocs: function() {
-      return this.get("doc_count");
-    },
-
-    updateSeq: function(full) {
-      var updateSeq = this.get("update_seq");
-      if (full || (typeof(updateSeq) === 'number')) {
-        return updateSeq;
-      } else if (updateSeq) {
-        return updateSeq.split('-')[0];
-      } else {
-        return 0;
-      }
-    },
-
-    humanSize: function() {
-      // cribbed from http://stackoverflow.com/questions/10420352/converting-file-size-in-bytes-to-human-readable
-      var i = -1;
-      var byteUnits = [' kB', ' MB', ' GB', ' TB', 'PB', 'EB', 'ZB', 'YB'];
-      var fileSizeInBytes = this.dataSize();
-
-      if (!fileSizeInBytes) {
-        return 0;
-      }
-
-      do {
-          fileSizeInBytes = fileSizeInBytes / 1024;
-          i++;
-      } while (fileSizeInBytes > 1024);
-
-      return Math.max(fileSizeInBytes, 0.1).toFixed(1) + byteUnits[i];
-    },
-    diskSize: function () {
-      return this.get("disk_size");
-    },
-
-    dataSize: function () {
-      if (this.get("other")){
-        return this.get("other").data_size;
-      }else{
-        return 0;
-      }  
-    }
-  });
-
-  // TODO: shared databases - read from the user doc
-  Databases.List = Backbone.Collection.extend({
-    model: Databases.Model,
-    documentation: function(){
-      return "all_dbs";
-    },
-    url: function(context) {
-      if (context === "apiurl") { 
-        return window.location.origin + "/_all_dbs";
-      } else {
-        return app.host + "/_all_dbs";
-      }
-    },
-
-    parse: function(resp) {
-      // TODO: pagination!
-      return _.map(resp, function(database) {
-        return {
-          id: app.mixins.safeURLName(database),
-          name: database
-        };
-      });
-    }
-  });
-
-  return Databases;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/modules/databases/routes.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/modules/databases/routes.js b/apps/fauxton/app/modules/databases/routes.js
deleted file mode 100644
index ca3d640..0000000
--- a/apps/fauxton/app/modules/databases/routes.js
+++ /dev/null
@@ -1,69 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-  "app",
-
-  "api",
-
-  // Modules
-  "modules/databases/resources",
-  // TODO:: fix the include flow modules so we don't have to require views here
-  "modules/databases/views"
-],
-
-function(app, FauxtonAPI, Databases, Views) {
-
-  var AllDbsRouteObject = FauxtonAPI.RouteObject.extend({
-    layout: "one_pane",
-
-    crumbs: [
-      {"name": "Databases", "link": "/_all_dbs"}
-    ],
-
-    routes: {
-      "": "allDatabases",
-      "index.html": "allDatabases",
-      "_all_dbs(:params)": "allDatabases"
-    },
-
-    apiUrl: function() {
-      return [this.databases.url("apiurl"), this.databases.documentation()];
-    },
-
-    selectedHeader: "Databases",
-
-    initialize: function() {
-      this.databases = new Databases.List();
-      this.deferred = FauxtonAPI.Deferred();
-    },
-
-    allDatabases: function() {
-      var params = app.getParams(),
-          dbPage = params.page;
-
-      this.databasesView = this.setView("#dashboard-content", new Views.List({
-        collection: this.databases
-      }));
-
-      this.databasesView.setPage(dbPage);
-    },
-
-    establish: function() {
-     return [this.databases.fetch()];
-    }
-  });
-
-  Databases.RouteObjects = [AllDbsRouteObject];
-
-  return Databases;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/modules/databases/views.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/modules/databases/views.js b/apps/fauxton/app/modules/databases/views.js
deleted file mode 100644
index dbeb475..0000000
--- a/apps/fauxton/app/modules/databases/views.js
+++ /dev/null
@@ -1,255 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-  "app",
-  
-  "modules/fauxton/components",
-  "api",
-  "modules/databases/resources"
-],
-
-function(app, Components, FauxtonAPI, Databases) {
-  var Views = {};
-
-  Views.Item = FauxtonAPI.View.extend({
-    template: "templates/databases/item",
-    tagName: "tr",
-    establish: function(){
-      return [this.model.fetch()];
-    },
-    serialize: function() {
-      return {
-        encoded: app.mixins.safeURLName(this.model.get("name")),
-        database: this.model,
-        docLimit: Databases.DocLimit
-      };
-    }
-  });
-
-  Views.List = FauxtonAPI.View.extend({
-    dbLimit: 20,
-    perPage: 20,
-    template: "templates/databases/list",
-    events: {
-      "click button.all": "selectAll",
-      "submit form#jump-to-db": "switchDatabase"
-    },
-
-    initialize: function(options) {
-      var params = app.getParams();
-      this.page = params.page ? parseInt(params.page, 10) : 1;
-    },
-
-    serialize: function() {
-      return {
-        databases: this.collection
-      };
-    },
-    establish: function(){
-      var currentDBs = this.paginated();
-      var deferred = FauxtonAPI.Deferred();
-
-      FauxtonAPI.when(currentDBs.map(function(database) {
-        return database.status.fetch();
-      })).always(function(resp) {
-        //make this always so that even if a user is not allowed access to a database
-        //they will still see a list of all databases
-        deferred.resolve();
-      });
-      return [deferred];
-    },
-    switchDatabase: function(event, selectedName) {
-      event && event.preventDefault();
-
-      var dbname = this.$el.find("[name='search-query']").val().trim();
-
-      if (selectedName) {
-        dbname = selectedName;
-      }
-
-      if (dbname && this.collection.where({"id":app.mixins.safeURLName(dbname)}).length > 0){
-          // TODO: switch to using a model, or Databases.databaseUrl()
-          // Neither of which are in scope right now
-          // var db = new Database.Model({id: dbname});
-          var url = ["/database/", app.mixins.safeURLName(dbname), "/_all_docs?limit=" + Databases.DocLimit].join('');
-          FauxtonAPI.navigate(url);
-      } else {
-        FauxtonAPI.addNotification({
-          msg: 'Database does not exist.',
-          type: 'error'
-        });
-      }
-    },
-
-    paginated: function() {
-      var start = (this.page - 1) * this.perPage;
-      var end = this.page * this.perPage;
-      return this.collection.slice(start, end);
-    },
-
-    beforeRender: function() {
-
-      this.insertView("#newButton", new Views.NewDatabaseButton({
-        collection: this.collection
-      }));
-
-      _.each(this.paginated(), function(database) {
-        this.insertView("table.databases tbody", new Views.Item({
-          model: database
-        }));
-      }, this);
-
-      this.insertView("#database-pagination", new Components.Pagination({
-        page: this.page,
-        perPage: this.perPage,
-        total: this.collection.length,
-        urlFun: function(page) {
-          return "#/_all_dbs?page=" + page;
-        }
-      }));
-    },
-
-    setPage: function(page) {
-      this.page = page || 1;
-    },
-
-    afterRender: function() {
-      var that = this;
-      this.dbSearchTypeahead = new Components.DbSearchTypeahead({
-        dbLimit: this.dbLimit,
-        el: "input.search-autocomplete",
-        onUpdate: function (item) {
-          that.switchDatabase(null, item);
-        }
-      });
-
-      this.dbSearchTypeahead.render();
-    },
-
-    selectAll: function(evt){
-      $("input:checkbox").attr('checked', !$(evt.target).hasClass('active'));
-    }
-  });
-
-
-  Views.NewDatabaseButton = FauxtonAPI.View.extend({
-    template: "templates/databases/newdatabase",
-    events: {
-      "click a#new": "newDatabase"
-    },
-    newDatabase: function() {
-      var notification;
-      var db;
-      // TODO: use a modal here instead of the prompt
-      var name = prompt('Name of database', 'newdatabase');
-      if (name === null) {
-        return;
-      } else if (name.length === 0) {
-        notification = FauxtonAPI.addNotification({
-          msg: "Please enter a valid database name",
-          type: "error",
-          clear: true
-        });
-        return;
-      }
-      db = new this.collection.model({
-        id: name,
-        name: name
-      });
-      notification = FauxtonAPI.addNotification({msg: "Creating database."});
-      db.save().done(function() {
-        notification = FauxtonAPI.addNotification({
-          msg: "Database created successfully",
-          type: "success",
-          clear: true
-        });
-        var route = "#/database/" +  app.mixins.safeURLName(name) + "/_all_docs?limit=" + Databases.DocLimit;
-        app.router.navigate(route, { trigger: true });
-      }
-      ).error(function(xhr) {
-        var responseText = JSON.parse(xhr.responseText).reason;
-        notification = FauxtonAPI.addNotification({
-          msg: "Create database failed: " + responseText,
-          type: "error",
-          clear: true
-        });
-      }
-      );
-    }
-  });
-
-  Views.Sidebar = FauxtonAPI.View.extend({
-    template: "templates/databases/sidebar",
-    events: {
-      "click a#new": "newDatabase",
-      "click a#owned": "showMine",
-      "click a#shared": "showShared"
-    },
-
-    newDatabase: function() {
-      var notification;
-      var db;
-      // TODO: use a modal here instead of the prompt
-      var name = prompt('Name of database', 'newdatabase');
-      if (name === null) {
-        return;
-      } else if (name.length === 0) {
-        notification = FauxtonAPI.addNotification({
-          msg: "Please enter a valid database name",
-          type: "error",
-          clear: true
-        });
-        return;
-      }
-      db = new this.collection.model({
-        id: encodeURIComponent(name),
-        name: name
-      });
-      notification = FauxtonAPI.addNotification({msg: "Creating database."});
-      db.save().done(function() {
-        notification = FauxtonAPI.addNotification({
-          msg: "Database created successfully",
-          type: "success",
-          clear: true
-        });
-        var route = "#/database/" +  name + "/_all_docs?limit=" + Databases.DocLimit;
-        app.router.navigate(route, { trigger: true });
-      }
-      ).error(function(xhr) {
-        var responseText = JSON.parse(xhr.responseText).reason;
-        notification = FauxtonAPI.addNotification({
-          msg: "Create database failed: " + responseText,
-          type: "error",
-          clear: true
-        });
-      }
-      );
-    },
-
-    showMine: function(){
-      $.contribute(
-        'Show unshared databases',
-        'app/addons/databases/views.js'
-      );
-    },
-
-    showShared: function(){
-      $.contribute(
-        'Show shared databases (e.g. continuous replications to/from the database)',
-        'app/addons/databases/views.js'
-      );
-    }
-  });
-
-  return Views;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/modules/documents/base.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/modules/documents/base.js b/apps/fauxton/app/modules/documents/base.js
deleted file mode 100644
index 96e4ada..0000000
--- a/apps/fauxton/app/modules/documents/base.js
+++ /dev/null
@@ -1,24 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-  "app",
-
-  "api",
-
-  // Modules
-  "modules/documents/routes"
-],
-
-function(app, FauxtonAPI, Documents) {
-  return Documents;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/modules/documents/resources.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/modules/documents/resources.js b/apps/fauxton/app/modules/documents/resources.js
deleted file mode 100644
index 83589ca..0000000
--- a/apps/fauxton/app/modules/documents/resources.js
+++ /dev/null
@@ -1,638 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-  "app",
-  "api"
-],
-
-function(app, FauxtonAPI) {
-  var Documents = app.module();
-
-  Documents.Doc = Backbone.Model.extend({
-    idAttribute: "_id",
-    documentation: function(){
-      return "docs";
-    },
-    url: function(context) {
-      if (context === "app") {
-        return this.getDatabase().url("app") + "/" + this.safeID();
-      } else if (context === "web-index") {
-        return this.getDatabase().url("app") + "/" + app.mixins.safeURLName(this.id);
-      } else if (context === "apiurl"){
-        return window.location.origin + "/" + this.getDatabase().safeID() + "/" + this.safeID();
-      } else {
-        return app.host + "/" + this.getDatabase().safeID() + "/" + this.safeID();
-      }
-    },
-
-    initialize: function(_attrs, options) {
-      if (this.collection && this.collection.database) {
-        this.database = this.collection.database;
-      } else if (options.database) {
-        this.database = options.database;
-      }
-    },
-
-    // HACK: the doc needs to know about the database, but it may be
-    // set directly or indirectly in all docs
-    getDatabase: function() {
-      return this.database ? this.database : this.collection.database;
-    },
-
-    validate: function(attrs, options) {
-      if (this.id && this.id !== attrs._id && this.get('_rev') ) {
-        return "Cannot change a documents id.";
-      }
-    },
-
-    docType: function() {
-      return this.id.match(/^_design/) ? "design doc" : "doc";
-    },
-
-    isEditable: function() {
-      return this.docType() != "reduction";
-    },
-
-    isDdoc: function() {
-      return this.docType() === "design doc";
-    },
-
-    hasViews: function() {
-      if (!this.isDdoc()) return false;
-      var doc = this.get('doc');
-      if (doc) {
-        return doc && doc.views && _.keys(doc.views).length > 0;
-      }
-
-      var views = this.get('views');
-      return views && _.keys(views).length > 0;
-    },
-
-    hasAttachments: function () {
-      return !!this.get('_attachments');
-    },
-
-    getDdocView: function(view) {
-      if (!this.isDdoc() || !this.hasViews()) return false;
-
-      var doc = this.get('doc');
-      if (doc) {
-        return doc.views[view];
-      }
-
-      return this.get('views')[view];
-    },
-
-    setDdocView: function (view, map, reduce) {
-      if (!this.isDdoc()) return false;
-      var views = this.get('views');
-          tempView = views[view] || {};
-
-      if (reduce) {
-        tempView.reduce=reduce;
-      } else {
-        delete tempView.reduce;
-      }
-      tempView.map= map;
-
-      views[view] = tempView;
-      this.set({views: views});
-
-      return true;
-    },
-
-    removeDdocView: function (viewName) {
-      if (!this.isDdoc()) return false;
-      var views = this.get('views');
-
-      delete views[viewName];
-      this.set({views: views});
-    },
-
-    dDocModel: function () {
-      if (!this.isDdoc()) return false;
-      var doc = this.get('doc');
-
-      if (doc) {
-        return new Documents.Doc(doc, {database: this.database});
-      } 
-
-      return this;
-    },
-
-    viewHasReduce: function(viewName) {
-      var view = this.getDdocView(viewName);
-
-      return view && view.reduce;
-    },
-
-    // Need this to work around backbone router thinking _design/foo
-    // is a separate route. Alternatively, maybe these should be
-    // treated separately. For instance, we could default into the
-    // json editor for docs, or into a ddoc specific page.
-    safeID: function() {
-      if (this.isDdoc()){
-        var ddoc = this.id.replace(/^_design\//,"");
-        return "_design/"+app.mixins.safeURLName(ddoc);
-      }else{
-        return app.mixins.safeURLName(this.id);
-      }
-    },
-
-    destroy: function() {
-      var url = this.url() + "?rev=" + this.get('_rev');
-      return $.ajax({
-        url: url,
-        dataType: 'json',
-        type: 'DELETE'
-      });
-    },
-
-    parse: function(resp) {
-      if (resp.rev) {
-        resp._rev = resp.rev;
-        delete resp.rev;
-      }
-      if (resp.id) {
-        if (typeof(this.id) === "undefined") {
-          resp._id = resp.id;
-        }
-        delete resp.id;
-      }
-      if (resp.ok) {
-        delete resp.ok;
-      }
-      return resp;
-    },
-
-    prettyJSON: function() {
-      var data = this.get("doc") ? this.get("doc") : this;
-
-      return JSON.stringify(data, null, "  ");
-    },
-
-    copy: function (copyId) {
-      return $.ajax({
-        type: 'COPY',
-        url: '/' + this.database.safeID() + '/' + this.safeID(),
-        headers: {Destination: copyId}
-      });
-    },
-
-    isNewDoc: function () {
-      return this.get('_rev') ? false : true;
-    }
-  });
-
-  Documents.DdocInfo = Backbone.Model.extend({
-    idAttribute: "_id",
-    documentation: function(){
-      return "docs";
-    },
-    initialize: function (_attrs, options) {
-      this.database = options.database;
-    },
-
-    url: function(context) {
-      if (context === "app") {
-        return this.database.url("app") + "/" + this.safeID() + '/_info';
-      } else if (context === "apiurl"){
-        return window.location.origin + "/" + this.database.safeID() + "/" + this.safeID() + '/_info';
-      } else {
-        return app.host + "/" + this.database.safeID() + "/" + this.safeID() + '/_info';
-      }
-    },
-
-    // Need this to work around backbone router thinking _design/foo
-    // is a separate route. Alternatively, maybe these should be
-    // treated separately. For instance, we could default into the
-    // json editor for docs, or into a ddoc specific page.
-    safeID: function() {
-      var ddoc = this.id.replace(/^_design\//,"");
-      return "_design/"+app.mixins.safeURLName(ddoc);
-    }
-
-  });
-
-  Documents.ViewRow = Backbone.Model.extend({
-    docType: function() {
-      if (!this.id) return "reduction";
-
-      return this.id.match(/^_design/) ? "design doc" : "doc";
-    },
-    documentation: function(){
-      return "docs";
-    },
-    url: function(context) {
-      if (!this.isEditable()) return false;
-
-      return this.collection.database.url(context) + "/" + this.safeID();
-    },
-
-    isEditable: function() {
-      return this.docType() != "reduction";
-    },
-    safeID: function() {
-      return app.mixins.safeURLName(this.id);
-    },
-
-    prettyJSON: function() {
-      //var data = this.get("doc") ? this.get("doc") : this;
-      return JSON.stringify(this, null, "  ");
-    }
-  });
-
-  Documents.NewDoc = Documents.Doc.extend({
-    fetch: function() {
-      var uuid = new FauxtonAPI.UUID();
-      var deferred = this.deferred = $.Deferred();
-      var that = this;
-
-      uuid.fetch().done(function() {
-        that.set("_id", uuid.next());
-        deferred.resolve();
-      });
-
-      return deferred.promise();
-    }
-
-  });
-
-  Documents.AllDocs = Backbone.Collection.extend({
-    model: Documents.Doc,
-    documentation: function(){
-      return "docs";
-    },
-    initialize: function(_models, options) {
-      this.database = options.database;
-      this.params = options.params;
-      this.skipFirstItem = false;
-
-      this.on("remove",this.decrementTotalRows , this);
-    },
-
-    url: function(context) {
-      var query = "";
-      if (this.params) {
-        query = "?" + $.param(this.params);
-      }
-
-      if (context === 'app') {
-        return 'database/' + this.database.safeID() + "/_all_docs" + query;
-      } else if (context === "apiurl"){
-        return window.location.origin + "/" + this.database.safeID() + "/_all_docs" + query;
-      } else {
-        return app.host + "/" + this.database.safeID() + "/_all_docs" + query;
-      }
-    },
-
-    simple: function () {
-      var docs = this.map(function (item) {
-        return {
-          _id: item.id,
-          _rev: item.get('_rev'),
-        };
-      });
-
-      return new Documents.AllDocs(docs, {
-        database: this.database,
-        params: this.params
-      });
-    },
-
-    urlNextPage: function (num, lastId) {
-      if (!lastId) {
-        var doc = this.last();
-
-        if (doc) {
-          lastId = doc.id;
-        } else {
-          lastId = '';
-        }
-      }
-
-      this.params.startkey_docid = '"' + lastId + '"';
-      this.params.startkey = '"' + lastId + '"';
-      // when paginating forward, fetch 21 and don't show
-      // the first item as it was the last item in the previous list
-      this.params.limit = num + 1;
-      return this.url('app');
-    },
-
-    urlPreviousPage: function (num, firstId) {
-      this.params.limit = num;
-      if (firstId) { 
-        this.params.startkey_docid = '"' + firstId + '"';
-        this.params.startkey = '"' + firstId + '"';
-      } else {
-        delete this.params.startkey;
-        delete this.params.startkey_docid;
-      }
-      return this.url('app');
-    },
-
-    totalRows: function() {
-      return this.viewMeta.total_rows || "unknown";
-    },
-
-    decrementTotalRows: function () {
-      if (this.viewMeta.total_rows) {
-        this.viewMeta.total_rows = this.viewMeta.total_rows -1;
-        this.trigger('totalRows:decrement');
-      }
-    },
-
-    updateSeq: function() {
-      return this.viewMeta.update_seq || false;
-    },
-
-    recordStart: function () {
-      if (this.viewMeta.offset === 0) {
-        return 1;
-      }
-
-      if (this.skipFirstItem) {
-        return this.viewMeta.offset + 2;
-      }
-
-      return this.viewMeta.offset + 1;
-    },
-
-    parse: function(resp) {
-      var rows = resp.rows;
-
-      this.viewMeta = {
-        total_rows: resp.total_rows,
-        offset: resp.offset,
-        update_seq: resp.update_seq
-      };
-
-      //Paginating, don't show first item as it was the last
-      //item in the previous page
-      if (this.skipFirstItem) {
-        rows = rows.splice(1);
-      }
-      return _.map(rows, function(row) {
-        return {
-          _id: row.id,
-          _rev: row.value.rev,
-          value: row.value,
-          key: row.key,
-          doc: row.doc || undefined
-        };
-      });
-    }
-  });
-
-  Documents.IndexCollection = Backbone.Collection.extend({
-    model: Documents.ViewRow,
-    documentation: function(){
-      return "docs";
-    },
-    initialize: function(_models, options) {
-      this.database = options.database;
-      this.params = _.extend({limit: 20, reduce: false}, options.params);
-      this.idxType = "_view";
-      this.view = options.view;
-      this.design = options.design.replace('_design/','');
-      this.skipFirstItem = false;
-    },
-
-    url: function(context) {
-      var query = "";
-      if (this.params) {
-        query = "?" + $.param(this.params);
-      }
-      
-      var startOfUrl = app.host;
-      if (context === 'app') {
-        startOfUrl = 'database';
-      } else if (context === "apiurl"){
-        startOfUrl = window.location.origin;
-      }
-      var design = app.mixins.safeURLName(this.design),
-          view = app.mixins.safeURLName(this.view);
-
-      var url = [startOfUrl, this.database.safeID(), "_design", design, this.idxType, view];
-      return url.join("/") + query;
-    },
-
-    urlNextPage: function (num, lastId) {
-      if (!lastId) {
-        lastId = this.last().id;
-      }
-
-      this.params.startkey_docid = '"' + lastId + '"';
-      this.params.startkey = '"' + lastId + '"';
-      this.params.limit = num;
-      return this.url('app');
-    },
-
-     urlPreviousPage: function (num, firstId) {
-      this.params.limit = num;
-      if (firstId) { 
-        this.params.startkey_docid = '"' + firstId + '"';
-        this.params.startkey = '"' + firstId + '"';
-      } else {
-        delete this.params.startkey;
-        delete this.params.startkey_docid;
-      }
-      return this.url('app');
-    },
-
-    recordStart: function () {
-      if (this.viewMeta.offset === 0) {
-        return 1;
-      }
-
-      if (this.skipFirstItem) {
-        return this.viewMeta.offset + 2;
-      }
-
-      return this.viewMeta.offset + 1;
-    },
-
-    totalRows: function() {
-      return this.viewMeta.total_rows || "unknown";
-    },
-
-    updateSeq: function() {
-      return this.viewMeta.update_seq || false;
-    },
-
-    simple: function () {
-      var docs = this.map(function (item) {
-        return {
-          _id: item.id,
-          key: item.get('key'),
-          value: item.get('value')
-        };
-      });
-
-      return new Documents.IndexCollection(docs, {
-        database: this.database,
-        params: this.params,
-        view: this.view,
-        design: this.design
-      });
-    },
-
-    parse: function(resp) {
-      var rows = resp.rows;
-      this.endTime = new Date().getTime();
-      this.requestDuration = (this.endTime - this.startTime);
-
-      if (this.skipFirstItem) {
-        rows = rows.splice(1);
-      }
-
-      this.viewMeta = {
-        total_rows: resp.total_rows,
-        offset: resp.offset,
-        update_seq: resp.update_seq
-      };
-      return _.map(rows, function(row) {
-        return {
-          value: row.value,
-          key: row.key,
-          doc: row.doc,
-          id: row.id
-        };
-      });
-    },
-
-    buildAllDocs: function(){
-      this.fetch();
-    },
-
-    // We implement our own fetch to store the starttime so we that
-    // we can get the request duration
-    fetch: function () {
-      this.startTime = new Date().getTime();
-      return Backbone.Collection.prototype.fetch.call(this);
-    },
-
-    allDocs: function(){
-      return this.models;
-    },
-
-    // This is taken from futon.browse.js $.timeString
-    requestDurationInString: function () {
-      var ms, sec, min, h, timeString, milliseconds = this.requestDuration;
-
-      sec = Math.floor(milliseconds / 1000.0);
-      min = Math.floor(sec / 60.0);
-      sec = (sec % 60.0).toString();
-      if (sec.length < 2) {
-         sec = "0" + sec;
-      }
-
-      h = (Math.floor(min / 60.0)).toString();
-      if (h.length < 2) {
-        h = "0" + h;
-      }
-
-      min = (min % 60.0).toString();
-      if (min.length < 2) {
-        min = "0" + min;
-      }
-
-      timeString = h + ":" + min + ":" + sec;
-
-      ms = (milliseconds % 1000.0).toString();
-      while (ms.length < 3) {
-        ms = "0" + ms;
-      }
-      timeString += "." + ms;
-
-      return timeString;
-    }
-  });
-
-  
-  Documents.PouchIndexCollection = Backbone.Collection.extend({
-    model: Documents.ViewRow,
-    documentation: function(){
-      return "docs";
-    },
-    initialize: function(_models, options) {
-      this.database = options.database;
-      this.rows = options.rows;
-      this.view = options.view;
-      this.design = options.design.replace('_design/','');
-      this.params = _.extend({limit: 20, reduce: false}, options.params);
-      this.idxType = "_view";
-    },
-
-    url: function () {
-      return '';
-    },
-
-    simple: function () {
-      var docs = this.map(function (item) {
-        return {
-          _id: item.id,
-          key: item.get('key'),
-          value: item.get('value')
-        };
-      });
-
-      return new Documents.PouchIndexCollection(docs, {
-        database: this.database,
-        params: this.params,
-        view: this.view,
-        design: this.design,
-        rows: this.rows
-      });
-
-    },
-
-    fetch: function() {
-      var deferred = FauxtonAPI.Deferred();
-      this.reset(this.rows, {silent: true});
-
-      this.viewMeta = {
-        total_rows: this.rows.length,
-        offset: 0,
-        update_seq: false
-      };
-
-      deferred.resolve();
-      return deferred;
-    },
-
-    recordStart: function () {
-      return 1;
-    },
-
-    totalRows: function() {
-      return this.viewMeta.total_rows || "unknown";
-    },
-
-    updateSeq: function() {
-      return this.viewMeta.update_seq || false;
-    },
-
-    buildAllDocs: function(){
-      this.fetch();
-    },
-
-    allDocs: function(){
-      return this.models;
-    }
-  });
-
-
-
-  return Documents;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/modules/documents/routes.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/modules/documents/routes.js b/apps/fauxton/app/modules/documents/routes.js
deleted file mode 100644
index 538cd56..0000000
--- a/apps/fauxton/app/modules/documents/routes.js
+++ /dev/null
@@ -1,408 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-       "app",
-
-       "api",
-
-       // Modules
-       "modules/documents/views",
-       "modules/databases/base"
-],
-
-function(app, FauxtonAPI, Documents, Databases) {
-
-  var DocEditorRouteObject = FauxtonAPI.RouteObject.extend({
-    layout: "one_pane",
-    disableLoader: true,
-    selectedHeader: "Databases",
-    initialize: function(route, masterLayout, options) {
-      var databaseName = options[0];
-      this.docID = options[1]||'new';
-
-      this.database = this.database || new Databases.Model({id: databaseName});
-      this.doc = new Documents.Doc({
-        _id: this.docID
-      }, {
-        database: this.database
-      });
-
-      this.tabsView = this.setView("#tabs", new Documents.Views.FieldEditorTabs({
-        disableLoader: true,
-        selected: "code_editor",
-        model: this.doc
-      }));
-
-    },
-
-    routes: {
-      // We are hiding the field_editor for this first release
-      // "database/:database/:doc/field_editor": "field_editor",
-      "database/:database/:doc/code_editor": "code_editor",
-      "database/:database/:doc": "code_editor"
-    },
-
-    events: {
-      "route:reRenderDoc": "reRenderDoc",
-      "route:duplicateDoc": "duplicateDoc"
-    },
-
-    crumbs: function() {
-      return [
-        {"name": this.database.id, "link": Databases.databaseUrl(this.database)},
-        {"name": this.docID, "link": "#"}
-      ];
-    },
-
-    code_editor: function (database, doc) {
-      this.tabsView.updateSelected('code_editor');
-
-      this.docView = this.setView("#dashboard-content", new Documents.Views.Doc({
-        model: this.doc,
-        database: this.database
-      }));
-    },
-
-    reRenderDoc: function () {
-      this.docView.forceRender();
-    },
-
-    field_editor: function(events) {
-      this.tabsView.updateSelected('field_editor');
-      this.docView = this.setView("#dashboard-content", new Documents.Views.DocFieldEditor({
-        model: this.doc
-      }));
-    },
-
-    duplicateDoc: function (newId) {
-      var doc = this.doc,
-      docView = this.docView,
-      database = this.database;
-
-      doc.copy(newId).then(function () {
-        doc.set({_id: newId}); 
-        docView.forceRender();
-        FauxtonAPI.navigate('/database/' + database.safeID() + '/' + app.mixins.safeURLName(newId), {trigger: true});
-        FauxtonAPI.addNotification({
-          msg: "Document has been duplicated."
-        });
-
-      }, function (error) {
-        var errorMsg = "Could not duplicate document, reason: " + error.responseText + ".";
-        FauxtonAPI.addNotification({
-          msg: errorMsg,
-          type: "error"
-        });
-      });
-    },
-
-    apiUrl: function() {
-      return [this.doc.url("apiurl"), this.doc.documentation()];
-    }
-  });
-
-  var NewDocEditorRouteObject = DocEditorRouteObject.extend({
-    initialize: function (route, masterLayout, options) {
-      var databaseName = options[0];
-
-      this.database = this.database || new Databases.Model({id: databaseName});
-      this.doc = new Documents.NewDoc(null,{
-        database: this.database
-      });
-
-      this.tabsView = this.setView("#tabs", new Documents.Views.FieldEditorTabs({
-        selected: "code_editor",
-        model: this.doc
-      }));
-
-    },
-    crumbs: function() {
-      return [
-        {"name": this.database.id, "link": Databases.databaseUrl(this.database)},
-        {"name": "New", "link": "#"}
-      ];
-    },
-    routes: {
-      "database/:database/new": "code_editor"
-    },
-    selectedHeader: "Databases",
-
-  });
-
-  var DocumentsRouteObject = FauxtonAPI.RouteObject.extend({
-    layout: "with_tabs_sidebar",
-    selectedHeader: "Databases",
-    routes: {
-      "database/:database/_all_docs(:extra)": "allDocs", 
-      "database/:database/_design/:ddoc/_view/:view": {
-        route: "viewFn",
-        roles: ['_admin']
-      },
-      "database/:database/new_view": "newViewEditor"
-    },
-
-    events: {
-      "route:updateAllDocs": "updateAllDocsFromView",
-      "route:updatePreviewDocs": "updateAllDocsFromPreview",
-      "route:reloadDesignDocs": "reloadDesignDocs",
-      "route:paginate": "paginate"
-    },
-
-    initialize: function (route, masterLayout, options) {
-      var docOptions = app.getParams();
-      docOptions.include_docs = true;
-
-      this.databaseName = options[0];
-
-      this.data = {
-        database: new Databases.Model({id:this.databaseName})
-      };
-
-      this.data.designDocs = new Documents.AllDocs(null, {
-        database: this.data.database,
-        params: {startkey: '"_design"',
-          endkey: '"_design1"',
-          include_docs: true}
-      });
-
-      this.sidebar = this.setView("#sidebar-content", new Documents.Views.Sidebar({
-        collection: this.data.designDocs,
-        database: this.data.database
-      }));
-    },
-
-    establish: function () {
-      return this.data.designDocs.fetch();
-    },
-
-    allDocs: function(databaseName, options) {
-      var docOptions = app.getParams(options);
-
-      docOptions.include_docs = true;
-      this.data.database.buildAllDocs(docOptions);
-
-      if (docOptions.startkey && docOptions.startkey.indexOf('_design') > -1) {
-        this.sidebar.setSelectedTab('design-docs');
-      } else {
-        this.sidebar.setSelectedTab('all-docs');
-      }
-
-      if (this.viewEditor) { this.viewEditor.remove(); }
-
-      this.toolsView = this.setView("#dashboard-upper-menu", new Documents.Views.JumpToDoc({
-        database: this.data.database,
-        collection: this.data.database.allDocs
-      }));
-
-      this.setView("#dashboard-upper-content", new Documents.Views.AllDocsLayout({
-        database: this.data.database,
-        collection: this.data.database.allDocs,
-        params: docOptions
-      }));
-
-      this.documentsView = this.setView("#dashboard-lower-content", new Documents.Views.AllDocsList({
-        collection: this.data.database.allDocs
-      }));
-
-      this.crumbs = [
-        {"name": this.data.database.id, "link": Databases.databaseUrl(this.data.database)}
-      ];
-
-      this.apiUrl = [this.data.database.allDocs.url("apiurl"), this.data.database.allDocs.documentation() ];
-    },
-
-    viewFn: function (databaseName, ddoc, view) {
-      var params = app.getParams(),
-          decodeDdoc = decodeURIComponent(ddoc);
-
-      view = view.replace(/\?.*$/,'');
-
-      this.data.indexedDocs = new Documents.IndexCollection(null, {
-        database: this.data.database,
-        design: decodeDdoc,
-        view: view,
-        params: params
-      });
-
-
-
-      var ddocInfo = {
-        id: "_design/" + decodeDdoc,
-        currView: view,
-        designDocs: this.data.designDocs
-      };
-
-      this.viewEditor = this.setView("#dashboard-upper-content", new Documents.Views.ViewEditor({
-        model: this.data.database,
-        ddocs: this.data.designDocs,
-        viewName: view,
-        params: params,
-        newView: false,
-        database: this.data.database,
-        ddocInfo: ddocInfo
-      }));
-
-      if (this.toolsView) { this.toolsView.remove(); }
-
-      this.documentsView = this.setView("#dashboard-lower-content", new Documents.Views.AllDocsList({
-        database: this.data.database,
-        collection: this.data.indexedDocs,
-        nestedView: Documents.Views.Row,
-        viewList: true,
-        ddocInfo: ddocInfo
-      }));
-
-      this.sidebar.setSelectedTab(app.mixins.removeSpecialCharacters(ddoc) + '_' + app.mixins.removeSpecialCharacters(view));
-
-      this.crumbs = function () {
-        return [
-          {"name": this.data.database.id, "link": Databases.databaseUrl(this.data.database)},
-        ];
-      };
-
-      this.apiUrl = [this.data.indexedDocs.url("apiurl"), "docs"];
-    },
-
-    newViewEditor: function () {
-      var params = app.getParams();
-
-      if (this.toolsView) {
-        this.toolsView.remove();
-      }
-
-      this.viewEditor = this.setView("#dashboard-upper-content", new Documents.Views.ViewEditor({
-        ddocs: this.data.designDocs,
-        params: params,
-        database: this.data.database,
-        newView: true
-      }));
-
-      this.sidebar.setSelectedTab('new-view');
-      this.crumbs = function () {
-        return [
-          {"name": this.data.database.id, "link": Databases.databaseUrl(this.data.database)},
-        ];
-      };
-    },
-
-    updateAllDocsFromView: function (event) {
-      var view = event.view,
-          docOptions = app.getParams(),
-          ddoc = event.ddoc;
-
-      if (event.allDocs) {
-        docOptions.include_docs = true;
-        this.data.database.buildAllDocs(docOptions);
-        return;
-      }
-
-      this.data.indexedDocs = new Documents.IndexCollection(null, {
-        database: this.data.database,
-        design: ddoc,
-        view: view,
-        params: app.getParams()
-      });
-
-      this.documentsView = this.setView("#dashboard-lower-content", new Documents.Views.AllDocsList({
-        database: this.data.database,
-        collection: this.data.indexedDocs,
-        nestedView: Documents.Views.Row,
-        viewList: true
-      }));
-    },
-
-    updateAllDocsFromPreview: function (event) {
-      var view = event.view,
-      rows = event.rows,
-      ddoc = event.ddoc;
-
-      this.data.indexedDocs = new Documents.PouchIndexCollection(null, {
-        database: this.data.database,
-        design: ddoc,
-        view: view,
-        rows: rows
-      });
-
-      this.documentsView = this.setView("#dashboard-lower-content", new Documents.Views.AllDocsList({
-        database: this.data.database,
-        collection: this.data.indexedDocs,
-        nestedView: Documents.Views.Row,
-        viewList: true
-      }));
-    },
-
-    paginate: function (direction) {
-      _.extend(this.documentsView.collection.params, app.getParams());
-      this.documentsView.forceRender();
-      if (direction === 'next') {
-        this.documentsView.collection.skipFirstItem = true;
-      } else {
-        this.documentsView.collection.skipFirstItem = false;
-      }
-    },
-
-    reloadDesignDocs: function (event) {
-      this.sidebar.forceRender();
-
-      if (event && event.selectedTab) {
-        this.sidebar.setSelectedTab(event.selectedTab);
-      }
-    }
-
-  });
-
-  var ChangesRouteObject = FauxtonAPI.RouteObject.extend({
-    layout: "with_tabs",
-    selectedHeader: "Databases",
-    crumbs: function () {
-      return [
-        {"name": this.database.id, "link": Databases.databaseUrl(this.database)},
-        {"name": "_changes", "link": "/_changes"}
-      ];
-    },
-
-    routes: {
-      "database/:database/_changes(:params)": "changes"
-    },
-
-    initialize: function (route, masterLayout, options) {
-      this.databaseName = options[0];
-      this.database = new Databases.Model({id: this.databaseName});
-
-      var docOptions = app.getParams();
-
-      this.database.buildChanges(docOptions);
-
-      this.setView("#tabs", new Documents.Views.Tabs({
-        collection: this.designDocs,
-        database: this.database,
-        active_id: 'changes'
-      }));
-    },
-
-    changes: function (event) {
-      this.setView("#dashboard-content", new Documents.Views.Changes({
-        model: this.database
-      }));
-    },
-
-    apiUrl: function() {
-      return [this.database.url("apiurl"), this.database.documentation()];
-    }
-
-  });
-
-  Documents.RouteObjects = [DocEditorRouteObject, NewDocEditorRouteObject, DocumentsRouteObject, ChangesRouteObject];
-
-  return Documents;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/modules/documents/tests/resourcesSpec.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/modules/documents/tests/resourcesSpec.js b/apps/fauxton/app/modules/documents/tests/resourcesSpec.js
deleted file mode 100644
index e78a3c3..0000000
--- a/apps/fauxton/app/modules/documents/tests/resourcesSpec.js
+++ /dev/null
@@ -1,84 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-define([
-       'modules/documents/resources',
-      'testUtils'
-], function (Models, testUtils) {
-  var assert = testUtils.assert;
-
-  describe('IndexCollection', function () {
-    var collection;
-    beforeEach(function () {
-      collection = new Models.IndexCollection([{
-        id:'myId1',
-        doc: 'num1'
-      },
-      {
-        id:'myId2',
-        doc: 'num2'
-      }], {
-        database: {id: 'databaseId'},
-        design: '_design/myDoc'
-      });
-
-    });
-
-    it('Should return urlNext', function () {
-      var url = collection.urlNextPage(20);
-
-      assert.equal(url, 'database/databaseId/_design/myDoc/_view/?limit=20&reduce=false&startkey_docid=%22myId2%22&startkey=%22myId2%22');
-
-    });
-
-    it('Should return urlPrevious', function () {
-      var url = collection.urlPreviousPage(20, 'myId1');
-
-      assert.equal(url, 'database/databaseId/_design/myDoc/_view/?limit=20&reduce=false&startkey_docid=%22myId1%22&startkey=%22myId1%22');
-
-    });
-
-  });
-
-  describe('AllDocs', function () {
-    var collection;
-    beforeEach(function () {
-      collection = new Models.AllDocs([{
-        _id:'myId1',
-        doc: 'num1'
-      },
-      {
-        _id:'myId2',
-        doc: 'num2'
-      }], {
-        database: {id: 'databaseId'},
-        params: {limit: 20}
-      });
-
-    });
-
-    it('Should return urlNext', function () {
-      var url = collection.urlNextPage(20);
-
-      assert.equal(url, 'database/databaseId/_all_docs?limit=21&startkey_docid=%22myId2%22&startkey=%22myId2%22');
-
-    });
-
-     it('Should return urlPrevious', function () {
-      var url = collection.urlPreviousPage(20, 'myId1');
-      assert.equal(url, 'database/databaseId/_all_docs?limit=20&startkey_docid=%22myId1%22&startkey=%22myId1%22');
-    });
-
-
-  });
-
-});
-


[53/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/utrace.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/utrace.h b/src/apps/couch_collate/platform/osx/icu/unicode/utrace.h
new file mode 100644
index 0000000..3c8be9f
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/utrace.h
@@ -0,0 +1,358 @@
+/*
+*******************************************************************************
+*
+*   Copyright (C) 2003-2006, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+*
+*******************************************************************************
+*   file name:  utrace.h
+*   encoding:   US-ASCII
+*   tab size:   8 (not used)
+*   indentation:4
+*
+*   created on: 2003aug06
+*   created by: Markus W. Scherer
+*
+*   Definitions for ICU tracing/logging.
+*
+*/
+
+#ifndef __UTRACE_H__
+#define __UTRACE_H__
+
+#include <stdarg.h>
+#include "unicode/utypes.h"
+
+/**
+ * \file
+ * \brief C API:  Definitions for ICU tracing/logging. 
+ *
+ * This provides API for debugging the internals of ICU without the use of
+ * a traditional debugger.
+ *
+ * By default, tracing is disabled in ICU. If you need to debug ICU with 
+ * tracing, please compile ICU with the --enable-tracing configure option.
+ */
+ 
+U_CDECL_BEGIN
+
+/**
+ * Trace severity levels.  Higher levels increase the verbosity of the trace output.
+ * @see utrace_setLevel
+ * @stable ICU 2.8
+ */
+typedef enum UTraceLevel {
+    /** Disable all tracing  @stable ICU 2.8*/
+    UTRACE_OFF=-1,
+    /** Trace error conditions only  @stable ICU 2.8*/
+    UTRACE_ERROR=0,
+    /** Trace errors and warnings  @stable ICU 2.8*/
+    UTRACE_WARNING=3,
+    /** Trace opens and closes of ICU services  @stable ICU 2.8*/
+    UTRACE_OPEN_CLOSE=5,
+    /** Trace an intermediate number of ICU operations  @stable ICU 2.8*/
+    UTRACE_INFO=7,
+    /** Trace the maximum number of ICU operations  @stable ICU 2.8*/
+    UTRACE_VERBOSE=9
+} UTraceLevel;
+
+/**
+ *  These are the ICU functions that will be traced when tracing is enabled.
+ *  @stable ICU 2.8
+ */
+typedef enum UTraceFunctionNumber {
+    UTRACE_FUNCTION_START=0,
+    UTRACE_U_INIT=UTRACE_FUNCTION_START,
+    UTRACE_U_CLEANUP,
+    UTRACE_FUNCTION_LIMIT,
+
+    UTRACE_CONVERSION_START=0x1000,
+    UTRACE_UCNV_OPEN=UTRACE_CONVERSION_START,
+    UTRACE_UCNV_OPEN_PACKAGE,
+    UTRACE_UCNV_OPEN_ALGORITHMIC,
+    UTRACE_UCNV_CLONE,
+    UTRACE_UCNV_CLOSE,
+    UTRACE_UCNV_FLUSH_CACHE,
+    UTRACE_UCNV_LOAD,
+    UTRACE_UCNV_UNLOAD,
+    UTRACE_CONVERSION_LIMIT,
+
+    UTRACE_COLLATION_START=0x2000,
+    UTRACE_UCOL_OPEN=UTRACE_COLLATION_START,
+    UTRACE_UCOL_CLOSE,
+    UTRACE_UCOL_STRCOLL,
+    UTRACE_UCOL_GET_SORTKEY,
+    UTRACE_UCOL_GETLOCALE,
+    UTRACE_UCOL_NEXTSORTKEYPART,
+    UTRACE_UCOL_STRCOLLITER,
+    UTRACE_UCOL_OPEN_FROM_SHORT_STRING,
+    UTRACE_COLLATION_LIMIT
+} UTraceFunctionNumber;
+
+/**
+ * Setter for the trace level.
+ * @param traceLevel A UTraceLevel value.
+ * @stable ICU 2.8
+ */
+U_STABLE void U_EXPORT2
+utrace_setLevel(int32_t traceLevel);
+
+/**
+ * Getter for the trace level.
+ * @return The UTraceLevel value being used by ICU.
+ * @stable ICU 2.8
+ */
+U_STABLE int32_t U_EXPORT2
+utrace_getLevel(void);
+
+/* Trace function pointers types  ----------------------------- */
+
+/**
+  *  Type signature for the trace function to be called when entering a function.
+  *  @param context value supplied at the time the trace functions are set.
+  *  @param fnNumber Enum value indicating the ICU function being entered.
+  *  @stable ICU 2.8
+  */
+typedef void U_CALLCONV
+UTraceEntry(const void *context, int32_t fnNumber);
+
+/**
+  *  Type signature for the trace function to be called when exiting from a function.
+  *  @param context value supplied at the time the trace functions are set.
+  *  @param fnNumber Enum value indicating the ICU function being exited.
+  *  @param fmt     A formatting string that describes the number and types
+  *                 of arguments included with the variable args.  The fmt
+  *                 string has the same form as the utrace_vformat format
+  *                 string.
+  *  @param args    A variable arguments list.  Contents are described by
+  *                 the fmt parameter.
+  *  @see   utrace_vformat
+  *  @stable ICU 2.8
+  */
+typedef void U_CALLCONV
+UTraceExit(const void *context, int32_t fnNumber, 
+           const char *fmt, va_list args);
+
+/**
+  *  Type signature for the trace function to be called from within an ICU function
+  *  to display data or messages.
+  *  @param context  value supplied at the time the trace functions are set.
+  *  @param fnNumber Enum value indicating the ICU function being exited.
+  *  @param level    The current tracing level
+  *  @param fmt      A format string describing the tracing data that is supplied
+  *                  as variable args
+  *  @param args     The data being traced, passed as variable args.
+  *  @stable ICU 2.8
+  */
+typedef void U_CALLCONV
+UTraceData(const void *context, int32_t fnNumber, int32_t level,
+           const char *fmt, va_list args);
+
+/**
+  *  Set ICU Tracing functions.  Installs application-provided tracing
+  *  functions into ICU.  After doing this, subsequent ICU operations
+  *  will call back to the installed functions, providing a trace
+  *  of the use of ICU.  Passing a NULL pointer for a tracing function
+  *  is allowed, and inhibits tracing action at points where that function
+  *  would be called.
+  *  <p>
+  *  Tracing and Threads:  Tracing functions are global to a process, and
+  *  will be called in response to ICU operations performed by any
+  *  thread.  If tracing of an individual thread is desired, the
+  *  tracing functions must themselves filter by checking that the
+  *  current thread is the desired thread.
+  *
+  *  @param context an uninterpretted pointer.  Whatever is passed in
+  *                 here will in turn be passed to each of the tracing
+  *                 functions UTraceEntry, UTraceExit and UTraceData.
+  *                 ICU does not use or alter this pointer.
+  *  @param e       Callback function to be called on entry to a 
+  *                 a traced ICU function.
+  *  @param x       Callback function to be called on exit from a
+  *                 traced ICU function.
+  *  @param d       Callback function to be called from within a 
+  *                 traced ICU function, for the purpose of providing
+  *                 data to the trace.
+  *
+  *  @stable ICU 2.8
+  */
+U_STABLE void U_EXPORT2
+utrace_setFunctions(const void *context,
+                    UTraceEntry *e, UTraceExit *x, UTraceData *d);
+
+/**
+  * Get the currently installed ICU tracing functions.   Note that a null function
+  *   pointer will be returned if no trace function has been set.
+  *
+  * @param context  The currently installed tracing context.
+  * @param e        The currently installed UTraceEntry function.
+  * @param x        The currently installed UTraceExit function.
+  * @param d        The currently installed UTraceData function.
+  * @stable ICU 2.8
+  */
+U_STABLE void U_EXPORT2
+utrace_getFunctions(const void **context,
+                    UTraceEntry **e, UTraceExit **x, UTraceData **d);
+
+
+
+/*
+ *
+ * ICU trace format string syntax
+ *
+ * Format Strings are passed to UTraceData functions, and define the
+ * number and types of the trace data being passed on each call.
+ *
+ * The UTraceData function, which is supplied by the application,
+ * not by ICU, can either forward the trace data (passed via
+ * varargs) and the format string back to ICU for formatting into
+ * a displayable string, or it can interpret the format itself,
+ * and do as it wishes with the trace data.
+ *
+ *
+ * Goals for the format string
+ * - basic data output
+ * - easy to use for trace programmer
+ * - sufficient provision for data types for trace output readability
+ * - well-defined types and binary portable APIs
+ *
+ * Non-goals
+ * - printf compatibility
+ * - fancy formatting
+ * - argument reordering and other internationalization features
+ *
+ * ICU trace format strings contain plain text with argument inserts,
+ * much like standard printf format strings.
+ * Each insert begins with a '%', then optionally contains a 'v',
+ * then exactly one type character.
+ * Two '%' in a row represent a '%' instead of an insert.
+ * The trace format strings need not have \n at the end.
+ *
+ *
+ * Types
+ * -----
+ *
+ * Type characters:
+ * - c A char character in the default codepage.
+ * - s A NUL-terminated char * string in the default codepage.
+ * - S A UChar * string.  Requires two params, (ptr, length).  Length=-1 for nul term.
+ * - b A byte (8-bit integer).
+ * - h A 16-bit integer.  Also a 16 bit Unicode code unit.
+ * - d A 32-bit integer.  Also a 20 bit Unicode code point value. 
+ * - l A 64-bit integer.
+ * - p A data pointer.
+ *
+ * Vectors
+ * -------
+ *
+ * If the 'v' is not specified, then one item of the specified type
+ * is passed in.
+ * If the 'v' (for "vector") is specified, then a vector of items of the
+ * specified type is passed in, via a pointer to the first item
+ * and an int32_t value for the length of the vector.
+ * Length==-1 means zero or NUL termination.  Works for vectors of all types.
+ *
+ * Note:  %vS is a vector of (UChar *) strings.  The strings must
+ *        be nul terminated as there is no way to provide a
+ *        separate length parameter for each string.  The length
+ *        parameter (required for all vectors) is the number of
+ *        strings, not the length of the strings.
+ *
+ * Examples
+ * --------
+ *
+ * These examples show the parameters that will be passed to an application's
+ *   UTraceData() function for various formats.
+ *
+ * - the precise formatting is up to the application!
+ * - the examples use type casts for arguments only to _show_ the types of
+ *   arguments without needing variable declarations in the examples;
+ *   the type casts will not be necessary in actual code
+ *
+ * UTraceDataFunc(context, fnNumber, level,
+ *              "There is a character %c in the string %s.",   // Format String 
+ *              (char)c, (const char *)s);                     // varargs parameters
+ * ->   There is a character 0x42 'B' in the string "Bravo".
+ *
+ * UTraceDataFunc(context, fnNumber, level,
+ *              "Vector of bytes %vb vector of chars %vc",
+ *              (const uint8_t *)bytes, (int32_t)bytesLength,
+ *              (const char *)chars, (int32_t)charsLength);
+ * ->  Vector of bytes
+ *      42 63 64 3f [4]
+ *     vector of chars
+ *      "Bcd?"[4]
+ *
+ * UTraceDataFunc(context, fnNumber, level,
+ *              "An int32_t %d and a whole bunch of them %vd",
+ *              (int32_t)-5, (const int32_t *)ints, (int32_t)intsLength);
+ * ->   An int32_t 0xfffffffb and a whole bunch of them
+ *      fffffffb 00000005 0000010a [3]
+ *
+ */
+
+
+
+/**
+  *  Trace output Formatter.  An application's UTraceData tracing functions may call
+  *                 back to this function to format the trace output in a
+  *                 human readable form.  Note that a UTraceData function may choose
+  *                 to not format the data;  it could, for example, save it in
+  *                 in the raw form it was received (more compact), leaving
+  *                 formatting for a later trace analyis tool.
+  *  @param outBuf  pointer to a buffer to receive the formatted output.  Output
+  *                 will be nul terminated if there is space in the buffer -
+  *                 if the length of the requested output < the output buffer size.
+  *  @param capacity  Length of the output buffer.
+  *  @param indent  Number of spaces to indent the output.  Intended to allow
+  *                 data displayed from nested functions to be indented for readability.
+  *  @param fmt     Format specification for the data to output
+  *  @param args    Data to be formatted.
+  *  @return        Length of formatted output, including the terminating NUL.
+  *                 If buffer capacity is insufficient, the required capacity is returned. 
+  *  @stable ICU 2.8
+  */
+U_STABLE int32_t U_EXPORT2
+utrace_vformat(char *outBuf, int32_t capacity,
+              int32_t indent, const char *fmt,  va_list args);
+
+/**
+  *  Trace output Formatter.  An application's UTraceData tracing functions may call
+  *                 this function to format any additional trace data, beyond that
+  *                 provided by default, in human readable form with the same
+  *                 formatting conventions used by utrace_vformat().
+  *  @param outBuf  pointer to a buffer to receive the formatted output.  Output
+  *                 will be nul terminated if there is space in the buffer -
+  *                 if the length of the requested output < the output buffer size.
+  *  @param capacity  Length of the output buffer.
+  *  @param indent  Number of spaces to indent the output.  Intended to allow
+  *                 data displayed from nested functions to be indented for readability.
+  *  @param fmt     Format specification for the data to output
+  *  @param ...     Data to be formatted.
+  *  @return        Length of formatted output, including the terminating NUL.
+  *                 If buffer capacity is insufficient, the required capacity is returned. 
+  *  @stable ICU 2.8
+  */
+U_STABLE int32_t U_EXPORT2
+utrace_format(char *outBuf, int32_t capacity,
+              int32_t indent, const char *fmt,  ...);
+
+
+
+/* Trace function numbers --------------------------------------------------- */
+
+/**
+ * Get the name of a function from its trace function number.
+ *
+ * @param fnNumber The trace number for an ICU function.
+ * @return The name string for the function.
+ *
+ * @see UTraceFunctionNumber
+ * @stable ICU 2.8
+ */
+U_STABLE const char * U_EXPORT2
+utrace_functionName(int32_t fnNumber);
+
+U_CDECL_END
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/utrans.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/utrans.h b/src/apps/couch_collate/platform/osx/icu/unicode/utrans.h
new file mode 100644
index 0000000..a460a34
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/utrans.h
@@ -0,0 +1,583 @@
+/*
+*******************************************************************************
+*   Copyright (C) 1997-2005, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+*******************************************************************************
+*   Date        Name        Description
+*   06/21/00    aliu        Creation.
+*******************************************************************************
+*/
+
+#ifndef UTRANS_H
+#define UTRANS_H
+
+#include "unicode/utypes.h"
+
+#if !UCONFIG_NO_TRANSLITERATION
+
+#include "unicode/urep.h"
+#include "unicode/parseerr.h"
+#include "unicode/uenum.h"
+
+/********************************************************************
+ * General Notes
+ ********************************************************************
+ */
+/**
+ * \file
+ * \brief C API: Transliterator
+ *
+ * <h2> Transliteration </h2>
+ * The data structures and functions described in this header provide
+ * transliteration services.  Transliteration services are implemented
+ * as C++ classes.  The comments and documentation in this header
+ * assume the reader is familiar with the C++ headers translit.h and
+ * associated documentation.
+ *
+ * A significant but incomplete subset of the C++ transliteration
+ * services are available to C code through this header.  In order to
+ * access more complex transliteration services, refer to the C++
+ * headers and documentation.
+ *
+ * There are two sets of functions for working with transliterator IDs:
+ *
+ * An old, deprecated set uses char * IDs, which works for true and pure
+ * identifiers that these APIs were designed for,
+ * for example "Cyrillic-Latin".
+ * It does not work when the ID contains filters ("[:Script=Cyrl:]")
+ * or even a complete set of rules because then the ID string contains more
+ * than just "invariant" characters (see utypes.h).
+ *
+ * A new set of functions replaces the old ones and uses UChar * IDs,
+ * paralleling the UnicodeString IDs in the C++ API. (New in ICU 2.8.)
+ */
+
+/********************************************************************
+ * Data Structures
+ ********************************************************************/
+
+/**
+ * An opaque transliterator for use in C.  Open with utrans_openxxx()
+ * and close with utrans_close() when done.  Equivalent to the C++ class
+ * Transliterator and its subclasses.
+ * @see Transliterator
+ * @stable ICU 2.0
+ */
+typedef void* UTransliterator;
+
+/**
+ * Direction constant indicating the direction in a transliterator,
+ * e.g., the forward or reverse rules of a RuleBasedTransliterator.
+ * Specified when a transliterator is opened.  An "A-B" transliterator
+ * transliterates A to B when operating in the forward direction, and
+ * B to A when operating in the reverse direction.
+ * @stable ICU 2.0
+ */
+typedef enum UTransDirection {
+    
+    /**
+     * UTRANS_FORWARD means from &lt;source&gt; to &lt;target&gt; for a
+     * transliterator with ID &lt;source&gt;-&lt;target&gt;.  For a transliterator
+     * opened using a rule, it means forward direction rules, e.g.,
+     * "A > B".
+     */
+    UTRANS_FORWARD,
+
+    /**
+     * UTRANS_REVERSE means from &lt;target&gt; to &lt;source&gt; for a
+     * transliterator with ID &lt;source&gt;-&lt;target&gt;.  For a transliterator
+     * opened using a rule, it means reverse direction rules, e.g.,
+     * "A < B".
+     */
+    UTRANS_REVERSE
+
+} UTransDirection;
+
+/**
+ * Position structure for utrans_transIncremental() incremental
+ * transliteration.  This structure defines two substrings of the text
+ * being transliterated.  The first region, [contextStart,
+ * contextLimit), defines what characters the transliterator will read
+ * as context.  The second region, [start, limit), defines what
+ * characters will actually be transliterated.  The second region
+ * should be a subset of the first.
+ *
+ * <p>After a transliteration operation, some of the indices in this
+ * structure will be modified.  See the field descriptions for
+ * details.
+ *
+ * <p>contextStart <= start <= limit <= contextLimit
+ *
+ * <p>Note: All index values in this structure must be at code point
+ * boundaries.  That is, none of them may occur between two code units
+ * of a surrogate pair.  If any index does split a surrogate pair,
+ * results are unspecified.
+ *
+ * @stable ICU 2.0
+ */
+typedef struct UTransPosition {
+
+    /**
+     * Beginning index, inclusive, of the context to be considered for
+     * a transliteration operation.  The transliterator will ignore
+     * anything before this index.  INPUT/OUTPUT parameter: This parameter
+     * is updated by a transliteration operation to reflect the maximum
+     * amount of antecontext needed by a transliterator.
+     * @stable ICU 2.4
+     */
+    int32_t contextStart;
+    
+    /**
+     * Ending index, exclusive, of the context to be considered for a
+     * transliteration operation.  The transliterator will ignore
+     * anything at or after this index.  INPUT/OUTPUT parameter: This
+     * parameter is updated to reflect changes in the length of the
+     * text, but points to the same logical position in the text.
+     * @stable ICU 2.4
+     */
+    int32_t contextLimit;
+    
+    /**
+     * Beginning index, inclusive, of the text to be transliteratd.
+     * INPUT/OUTPUT parameter: This parameter is advanced past
+     * characters that have already been transliterated by a
+     * transliteration operation.
+     * @stable ICU 2.4
+     */
+    int32_t start;
+    
+    /**
+     * Ending index, exclusive, of the text to be transliteratd.
+     * INPUT/OUTPUT parameter: This parameter is updated to reflect
+     * changes in the length of the text, but points to the same
+     * logical position in the text.
+     * @stable ICU 2.4
+     */
+    int32_t limit;
+
+} UTransPosition;
+
+/********************************************************************
+ * General API
+ ********************************************************************/
+
+/**
+ * Open a custom transliterator, given a custom rules string 
+ * OR 
+ * a system transliterator, given its ID.  
+ * Any non-NULL result from this function should later be closed with
+ * utrans_close().
+ *
+ * @param id a valid transliterator ID
+ * @param idLength the length of the ID string, or -1 if NUL-terminated
+ * @param dir the desired direction
+ * @param rules the transliterator rules.  See the C++ header rbt.h for
+ *              rules syntax. If NULL then a system transliterator matching
+ *              the ID is returned.
+ * @param rulesLength the length of the rules, or -1 if the rules
+ *                    are NUL-terminated.
+ * @param parseError a pointer to a UParseError struct to receive the details
+ *                   of any parsing errors. This parameter may be NULL if no
+ *                   parsing error details are desired.
+ * @param pErrorCode a pointer to the UErrorCode
+ * @return a transliterator pointer that may be passed to other
+ *         utrans_xxx() functions, or NULL if the open call fails.
+ * @stable ICU 2.8
+ */
+U_STABLE UTransliterator* U_EXPORT2
+utrans_openU(const UChar *id,
+             int32_t idLength,
+             UTransDirection dir,
+             const UChar *rules,
+             int32_t rulesLength,
+             UParseError *parseError,
+             UErrorCode *pErrorCode);
+
+/**
+ * Open an inverse of an existing transliterator.  For this to work,
+ * the inverse must be registered with the system.  For example, if
+ * the Transliterator "A-B" is opened, and then its inverse is opened,
+ * the result is the Transliterator "B-A", if such a transliterator is
+ * registered with the system.  Otherwise the result is NULL and a
+ * failing UErrorCode is set.  Any non-NULL result from this function
+ * should later be closed with utrans_close().
+ *
+ * @param trans the transliterator to open the inverse of.
+ * @param status a pointer to the UErrorCode
+ * @return a pointer to a newly-opened transliterator that is the
+ * inverse of trans, or NULL if the open call fails.
+ * @stable ICU 2.0
+ */
+U_STABLE UTransliterator* U_EXPORT2 
+utrans_openInverse(const UTransliterator* trans,
+                   UErrorCode* status);
+
+/**
+ * Create a copy of a transliterator.  Any non-NULL result from this
+ * function should later be closed with utrans_close().
+ *
+ * @param trans the transliterator to be copied.
+ * @param status a pointer to the UErrorCode
+ * @return a transliterator pointer that may be passed to other
+ * utrans_xxx() functions, or NULL if the clone call fails.
+ * @stable ICU 2.0
+ */
+U_STABLE UTransliterator* U_EXPORT2 
+utrans_clone(const UTransliterator* trans,
+             UErrorCode* status);
+
+/**
+ * Close a transliterator.  Any non-NULL pointer returned by
+ * utrans_openXxx() or utrans_clone() should eventually be closed.
+ * @param trans the transliterator to be closed.
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+utrans_close(UTransliterator* trans);
+
+/**
+ * Return the programmatic identifier for this transliterator.
+ * If this identifier is passed to utrans_openU(), it will open
+ * a transliterator equivalent to this one, if the ID has been
+ * registered.
+ *
+ * @param trans the transliterator to return the ID of.
+ * @param resultLength pointer to an output variable receiving the length
+ *        of the ID string; can be NULL
+ * @return the NUL-terminated ID string. This pointer remains
+ * valid until utrans_close() is called on this transliterator.
+ *
+ * @stable ICU 2.8
+ */
+U_STABLE const UChar * U_EXPORT2
+utrans_getUnicodeID(const UTransliterator *trans,
+                    int32_t *resultLength);
+
+/**
+ * Register an open transliterator with the system.  When
+ * utrans_open() is called with an ID string that is equal to that
+ * returned by utrans_getID(adoptedTrans,...), then
+ * utrans_clone(adoptedTrans,...) is returned.
+ *
+ * <p>NOTE: After this call the system owns the adoptedTrans and will
+ * close it.  The user must not call utrans_close() on adoptedTrans.
+ *
+ * @param adoptedTrans a transliterator, typically the result of
+ * utrans_openRules(), to be registered with the system.
+ * @param status a pointer to the UErrorCode
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+utrans_register(UTransliterator* adoptedTrans,
+                UErrorCode* status);
+
+/**
+ * Unregister a transliterator from the system.  After this call the
+ * system will no longer recognize the given ID when passed to
+ * utrans_open(). If the ID is invalid then nothing is done.
+ *
+ * @param id an ID to unregister
+ * @param idLength the length of id, or -1 if id is zero-terminated
+ * @stable ICU 2.8
+ */
+U_STABLE void U_EXPORT2
+utrans_unregisterID(const UChar* id, int32_t idLength);
+
+/**
+ * Set the filter used by a transliterator.  A filter can be used to
+ * make the transliterator pass certain characters through untouched.
+ * The filter is expressed using a UnicodeSet pattern.  If the
+ * filterPattern is NULL or the empty string, then the transliterator
+ * will be reset to use no filter.
+ *
+ * @param trans the transliterator
+ * @param filterPattern a pattern string, in the form accepted by
+ * UnicodeSet, specifying which characters to apply the
+ * transliteration to.  May be NULL or the empty string to indicate no
+ * filter.
+ * @param filterPatternLen the length of filterPattern, or -1 if
+ * filterPattern is zero-terminated
+ * @param status a pointer to the UErrorCode
+ * @see UnicodeSet
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+utrans_setFilter(UTransliterator* trans,
+                 const UChar* filterPattern,
+                 int32_t filterPatternLen,
+                 UErrorCode* status);
+
+/**
+ * Return the number of system transliterators.
+ * It is recommended to use utrans_openIDs() instead.
+ *
+ * @return the number of system transliterators.
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2 
+utrans_countAvailableIDs(void);
+
+/**
+ * Return a UEnumeration for the available transliterators.
+ *
+ * @param pErrorCode Pointer to the UErrorCode in/out parameter.
+ * @return UEnumeration for the available transliterators.
+ *         Close with uenum_close().
+ *
+ * @stable ICU 2.8
+ */
+U_STABLE UEnumeration * U_EXPORT2
+utrans_openIDs(UErrorCode *pErrorCode);
+
+/********************************************************************
+ * Transliteration API
+ ********************************************************************/
+
+/**
+ * Transliterate a segment of a UReplaceable string.  The string is
+ * passed in as a UReplaceable pointer rep and a UReplaceableCallbacks
+ * function pointer struct repFunc.  Functions in the repFunc struct
+ * will be called in order to modify the rep string.
+ *
+ * @param trans the transliterator
+ * @param rep a pointer to the string.  This will be passed to the
+ * repFunc functions.
+ * @param repFunc a set of function pointers that will be used to
+ * modify the string pointed to by rep.
+ * @param start the beginning index, inclusive; <code>0 <= start <=
+ * limit</code>.
+ * @param limit pointer to the ending index, exclusive; <code>start <=
+ * limit <= repFunc->length(rep)</code>.  Upon return, *limit will
+ * contain the new limit index.  The text previously occupying
+ * <code>[start, limit)</code> has been transliterated, possibly to a
+ * string of a different length, at <code>[start,
+ * </code><em>new-limit</em><code>)</code>, where <em>new-limit</em>
+ * is the return value.
+ * @param status a pointer to the UErrorCode
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+utrans_trans(const UTransliterator* trans,
+             UReplaceable* rep,
+             UReplaceableCallbacks* repFunc,
+             int32_t start,
+             int32_t* limit,
+             UErrorCode* status);
+
+/**
+ * Transliterate the portion of the UReplaceable text buffer that can
+ * be transliterated unambiguosly.  This method is typically called
+ * after new text has been inserted, e.g. as a result of a keyboard
+ * event.  The transliterator will try to transliterate characters of
+ * <code>rep</code> between <code>index.cursor</code> and
+ * <code>index.limit</code>.  Characters before
+ * <code>index.cursor</code> will not be changed.
+ *
+ * <p>Upon return, values in <code>index</code> will be updated.
+ * <code>index.start</code> will be advanced to the first
+ * character that future calls to this method will read.
+ * <code>index.cursor</code> and <code>index.limit</code> will
+ * be adjusted to delimit the range of text that future calls to
+ * this method may change.
+ *
+ * <p>Typical usage of this method begins with an initial call
+ * with <code>index.start</code> and <code>index.limit</code>
+ * set to indicate the portion of <code>text</code> to be
+ * transliterated, and <code>index.cursor == index.start</code>.
+ * Thereafter, <code>index</code> can be used without
+ * modification in future calls, provided that all changes to
+ * <code>text</code> are made via this method.
+ *
+ * <p>This method assumes that future calls may be made that will
+ * insert new text into the buffer.  As a result, it only performs
+ * unambiguous transliterations.  After the last call to this method,
+ * there may be untransliterated text that is waiting for more input
+ * to resolve an ambiguity.  In order to perform these pending
+ * transliterations, clients should call utrans_trans() with a start
+ * of index.start and a limit of index.end after the last call to this
+ * method has been made.
+ *
+ * @param trans the transliterator
+ * @param rep a pointer to the string.  This will be passed to the
+ * repFunc functions.
+ * @param repFunc a set of function pointers that will be used to
+ * modify the string pointed to by rep.
+ * @param pos a struct containing the start and limit indices of the
+ * text to be read and the text to be transliterated
+ * @param status a pointer to the UErrorCode
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+utrans_transIncremental(const UTransliterator* trans,
+                        UReplaceable* rep,
+                        UReplaceableCallbacks* repFunc,
+                        UTransPosition* pos,
+                        UErrorCode* status);
+
+/**
+ * Transliterate a segment of a UChar* string.  The string is passed
+ * in in a UChar* buffer.  The string is modified in place.  If the
+ * result is longer than textCapacity, it is truncated.  The actual
+ * length of the result is returned in *textLength, if textLength is
+ * non-NULL. *textLength may be greater than textCapacity, but only
+ * textCapacity UChars will be written to *text, including the zero
+ * terminator.
+ *
+ * @param trans the transliterator
+ * @param text a pointer to a buffer containing the text to be
+ * transliterated on input and the result text on output.
+ * @param textLength a pointer to the length of the string in text.
+ * If the length is -1 then the string is assumed to be
+ * zero-terminated.  Upon return, the new length is stored in
+ * *textLength.  If textLength is NULL then the string is assumed to
+ * be zero-terminated.
+ * @param textCapacity a pointer to the length of the text buffer.
+ * Upon return, 
+ * @param start the beginning index, inclusive; <code>0 <= start <=
+ * limit</code>.
+ * @param limit pointer to the ending index, exclusive; <code>start <=
+ * limit <= repFunc->length(rep)</code>.  Upon return, *limit will
+ * contain the new limit index.  The text previously occupying
+ * <code>[start, limit)</code> has been transliterated, possibly to a
+ * string of a different length, at <code>[start,
+ * </code><em>new-limit</em><code>)</code>, where <em>new-limit</em>
+ * is the return value.
+ * @param status a pointer to the UErrorCode
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+utrans_transUChars(const UTransliterator* trans,
+                   UChar* text,
+                   int32_t* textLength,
+                   int32_t textCapacity,
+                   int32_t start,
+                   int32_t* limit,
+                   UErrorCode* status);
+
+/**
+ * Transliterate the portion of the UChar* text buffer that can be
+ * transliterated unambiguosly.  See utrans_transIncremental().  The
+ * string is passed in in a UChar* buffer.  The string is modified in
+ * place.  If the result is longer than textCapacity, it is truncated.
+ * The actual length of the result is returned in *textLength, if
+ * textLength is non-NULL. *textLength may be greater than
+ * textCapacity, but only textCapacity UChars will be written to
+ * *text, including the zero terminator.  See utrans_transIncremental()
+ * for usage details.
+ *
+ * @param trans the transliterator
+ * @param text a pointer to a buffer containing the text to be
+ * transliterated on input and the result text on output.
+ * @param textLength a pointer to the length of the string in text.
+ * If the length is -1 then the string is assumed to be
+ * zero-terminated.  Upon return, the new length is stored in
+ * *textLength.  If textLength is NULL then the string is assumed to
+ * be zero-terminated.
+ * @param textCapacity the length of the text buffer
+ * @param pos a struct containing the start and limit indices of the
+ * text to be read and the text to be transliterated
+ * @param status a pointer to the UErrorCode
+ * @see utrans_transIncremental
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+utrans_transIncrementalUChars(const UTransliterator* trans,
+                              UChar* text,
+                              int32_t* textLength,
+                              int32_t textCapacity,
+                              UTransPosition* pos,
+                              UErrorCode* status);
+
+/* deprecated API ----------------------------------------------------------- */
+
+/* see utrans.h documentation for why these functions are deprecated */
+
+/**
+ * Deprecated, use utrans_openU() instead.
+ * Open a custom transliterator, given a custom rules string 
+ * OR 
+ * a system transliterator, given its ID.  
+ * Any non-NULL result from this function should later be closed with
+ * utrans_close().
+ *
+ * @param id a valid ID, as returned by utrans_getAvailableID()
+ * @param dir the desired direction
+ * @param rules the transliterator rules.  See the C++ header rbt.h
+ * for rules syntax. If NULL then a system transliterator matching 
+ * the ID is returned.
+ * @param rulesLength the length of the rules, or -1 if the rules
+ * are zero-terminated.
+ * @param parseError a pointer to a UParseError struct to receive the
+ * details of any parsing errors. This parameter may be NULL if no
+ * parsing error details are desired.
+ * @param status a pointer to the UErrorCode
+ * @return a transliterator pointer that may be passed to other
+ * utrans_xxx() functions, or NULL if the open call fails.
+ * @deprecated ICU 2.8 Use utrans_openU() instead, see utrans.h
+ */
+U_DEPRECATED UTransliterator* U_EXPORT2 
+utrans_open(const char* id,
+            UTransDirection dir,
+            const UChar* rules,         /* may be Null */
+            int32_t rulesLength,        /* -1 if null-terminated */ 
+            UParseError* parseError,    /* may be Null */
+            UErrorCode* status);
+
+/**
+ * Deprecated, use utrans_getUnicodeID() instead.
+ * Return the programmatic identifier for this transliterator.
+ * If this identifier is passed to utrans_open(), it will open
+ * a transliterator equivalent to this one, if the ID has been
+ * registered.
+ * @param trans the transliterator to return the ID of.
+ * @param buf the buffer in which to receive the ID.  This may be
+ * NULL, in which case no characters are copied.
+ * @param bufCapacity the capacity of the buffer.  Ignored if buf is
+ * NULL.
+ * @return the actual length of the ID, not including
+ * zero-termination.  This may be greater than bufCapacity.
+ * @deprecated ICU 2.8 Use utrans_getUnicodeID() instead, see utrans.h
+ */
+U_DEPRECATED int32_t U_EXPORT2 
+utrans_getID(const UTransliterator* trans,
+             char* buf,
+             int32_t bufCapacity);
+
+/**
+ * Deprecated, use utrans_unregisterID() instead.
+ * Unregister a transliterator from the system.  After this call the
+ * system will no longer recognize the given ID when passed to
+ * utrans_open().  If the id is invalid then nothing is done.
+ *
+ * @param id a zero-terminated ID
+ * @deprecated ICU 2.8 Use utrans_unregisterID() instead, see utrans.h
+ */
+U_DEPRECATED void U_EXPORT2 
+utrans_unregister(const char* id);
+
+/**
+ * Deprecated, use utrans_openIDs() instead.
+ * Return the ID of the index-th system transliterator.  The result
+ * is placed in the given buffer.  If the given buffer is too small,
+ * the initial substring is copied to buf.  The result in buf is
+ * always zero-terminated.
+ *
+ * @param index the number of the transliterator to return.  Must
+ * satisfy 0 <= index < utrans_countAvailableIDs().  If index is out
+ * of range then it is treated as if it were 0.
+ * @param buf the buffer in which to receive the ID.  This may be
+ * NULL, in which case no characters are copied.
+ * @param bufCapacity the capacity of the buffer.  Ignored if buf is
+ * NULL.
+ * @return the actual length of the index-th ID, not including
+ * zero-termination.  This may be greater than bufCapacity.
+ * @deprecated ICU 2.8 Use utrans_openIDs() instead, see utrans.h
+ */
+U_DEPRECATED int32_t U_EXPORT2 
+utrans_getAvailableID(int32_t index,
+                      char* buf,
+                      int32_t bufCapacity);
+
+#endif /* #if !UCONFIG_NO_TRANSLITERATION */
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/utypes.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/utypes.h b/src/apps/couch_collate/platform/osx/icu/unicode/utypes.h
new file mode 100644
index 0000000..12977ed
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/utypes.h
@@ -0,0 +1,801 @@
+/*
+**********************************************************************
+*   Copyright (C) 1996-2008, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+**********************************************************************
+*
+*  FILE NAME : UTYPES.H (formerly ptypes.h)
+*
+*   Date        Name        Description
+*   12/11/96    helena      Creation.
+*   02/27/97    aliu        Added typedefs for UClassID, int8, int16, int32,
+*                           uint8, uint16, and uint32.
+*   04/01/97    aliu        Added XP_CPLUSPLUS and modified to work under C as
+*                            well as C++.
+*                           Modified to use memcpy() for uprv_arrayCopy() fns.
+*   04/14/97    aliu        Added TPlatformUtilities.
+*   05/07/97    aliu        Added import/export specifiers (replacing the old
+*                           broken EXT_CLASS).  Added version number for our
+*                           code.  Cleaned up header.
+*    6/20/97    helena      Java class name change.
+*   08/11/98    stephen     UErrorCode changed from typedef to enum
+*   08/12/98    erm         Changed T_ANALYTIC_PACKAGE_VERSION to 3
+*   08/14/98    stephen     Added uprv_arrayCopy() for int8_t, int16_t, int32_t
+*   12/09/98    jfitz       Added BUFFER_OVERFLOW_ERROR (bug 1100066)
+*   04/20/99    stephen     Cleaned up & reworked for autoconf.
+*                           Renamed to utypes.h.
+*   05/05/99    stephen     Changed to use <inttypes.h>
+*   12/07/99    helena      Moved copyright notice string from ucnv_bld.h here.
+*******************************************************************************
+*/
+
+#ifndef UTYPES_H
+#define UTYPES_H
+
+
+#include "unicode/umachine.h"
+#include "unicode/utf.h"
+#include "unicode/uversion.h"
+#include "unicode/uconfig.h"
+
+#if !U_DEFAULT_SHOW_DRAFT && !defined(U_SHOW_DRAFT_API)
+#define U_HIDE_DRAFT_API 1
+#endif
+
+#ifdef U_HIDE_DRAFT_API
+#include "unicode/udraft.h"
+#endif
+
+#ifdef U_HIDE_DEPRECATED_API
+#include "unicode/udeprctd.h"
+#endif
+
+#ifdef U_HIDE_DEPRECATED_API
+#include "unicode/uobslete.h"
+#endif
+
+#ifdef U_HIDE_INTERNAL_API
+#include "unicode/uintrnal.h"
+#endif
+
+#ifdef U_HIDE_SYSTEM_API
+#include "unicode/usystem.h"
+#endif
+
+/*!
+ * \file
+ * \brief Basic definitions for ICU, for both C and C++ APIs
+ *
+ * This file defines basic types, constants, and enumerations directly or
+ * indirectly by including other header files, especially utf.h for the
+ * basic character and string definitions and umachine.h for consistent
+ * integer and other types.
+ */
+
+/*===========================================================================*/
+/* char Character set family                                                 */
+/*===========================================================================*/
+
+/**
+ * U_CHARSET_FAMILY is equal to this value when the platform is an ASCII based platform.
+ * @stable ICU 2.0
+ */
+#define U_ASCII_FAMILY 0
+
+/**
+ * U_CHARSET_FAMILY is equal to this value when the platform is an EBCDIC based platform.
+ * @stable ICU 2.0
+ */
+#define U_EBCDIC_FAMILY 1
+
+/**
+ * \def U_CHARSET_FAMILY
+ *
+ * <p>These definitions allow to specify the encoding of text
+ * in the char data type as defined by the platform and the compiler.
+ * It is enough to determine the code point values of "invariant characters",
+ * which are the ones shared by all encodings that are in use
+ * on a given platform.</p>
+ *
+ * <p>Those "invariant characters" should be all the uppercase and lowercase
+ * latin letters, the digits, the space, and "basic punctuation".
+ * Also, '\\n', '\\r', '\\t' should be available.</p>
+ *
+ * <p>The list of "invariant characters" is:<br>
+ * \code
+ *    A-Z  a-z  0-9  SPACE  "  %  &amp;  '  (  )  *  +  ,  -  .  /  :  ;  <  =  >  ?  _
+ * \endcode
+ * <br>
+ * (52 letters + 10 numbers + 20 punc/sym/space = 82 total)</p>
+ *
+ * <p>This matches the IBM Syntactic Character Set (CS 640).</p>
+ *
+ * <p>In other words, all the graphic characters in 7-bit ASCII should
+ * be safely accessible except the following:</p>
+ *
+ * \code
+ *    '\' <backslash>
+ *    '[' <left bracket>
+ *    ']' <right bracket>
+ *    '{' <left brace>
+ *    '}' <right brace>
+ *    '^' <circumflex>
+ *    '~' <tilde>
+ *    '!' <exclamation mark>
+ *    '#' <number sign>
+ *    '|' <vertical line>
+ *    '$' <dollar sign>
+ *    '@' <commercial at>
+ *    '`' <grave accent>
+ * \endcode
+ * @stable ICU 2.0
+ */
+
+#ifndef U_CHARSET_FAMILY
+#   define U_CHARSET_FAMILY 0
+#endif
+
+/*===========================================================================*/
+/* ICUDATA naming scheme                                                     */
+/*===========================================================================*/
+
+/**
+ * \def U_ICUDATA_TYPE_LETTER
+ *
+ * This is a platform-dependent string containing one letter:
+ * - b for big-endian, ASCII-family platforms
+ * - l for little-endian, ASCII-family platforms
+ * - e for big-endian, EBCDIC-family platforms
+ * This letter is part of the common data file name.
+ * @stable ICU 2.0
+ */
+
+/**
+ * \def U_ICUDATA_TYPE_LITLETTER
+ * The non-string form of U_ICUDATA_TYPE_LETTER
+ * @stable ICU 2.0
+ */
+#if U_CHARSET_FAMILY
+#   if U_IS_BIG_ENDIAN
+   /* EBCDIC - should always be BE */
+#     define U_ICUDATA_TYPE_LETTER "e"
+#     define U_ICUDATA_TYPE_LITLETTER e
+#   else
+#     error "Don't know what to do with little endian EBCDIC!"
+#     define U_ICUDATA_TYPE_LETTER "x"
+#     define U_ICUDATA_TYPE_LITLETTER x
+#   endif
+#else
+#   if U_IS_BIG_ENDIAN
+      /* Big-endian ASCII */
+#     define U_ICUDATA_TYPE_LETTER "b"
+#     define U_ICUDATA_TYPE_LITLETTER b
+#   else
+      /* Little-endian ASCII */
+#     define U_ICUDATA_TYPE_LETTER "l"
+#     define U_ICUDATA_TYPE_LITLETTER l
+#   endif
+#endif
+
+/**
+ * A single string literal containing the icudata stub name. i.e. 'icudt18e' for
+ * ICU 1.8.x on EBCDIC, etc..
+ * @stable ICU 2.0
+ */
+#define U_ICUDATA_NAME    "icudt" U_ICU_VERSION_SHORT U_ICUDATA_TYPE_LETTER
+
+
+/**
+ *  U_ICU_ENTRY_POINT is the name of the DLL entry point to the ICU data library.
+ *    Defined as a literal, not a string.
+ *    Tricky Preprocessor use - ## operator replaces macro paramters with the literal string
+ *                              from the corresponding macro invocation, _before_ other macro substitutions.
+ *                              Need a nested \#defines to get the actual version numbers rather than
+ *                              the literal text U_ICU_VERSION_MAJOR_NUM into the name.
+ *                              The net result will be something of the form
+ *                                  \#define U_ICU_ENTRY_POINT icudt19_dat
+ * @stable ICU 2.4
+ */
+#define U_ICUDATA_ENTRY_POINT  U_DEF2_ICUDATA_ENTRY_POINT(U_ICU_VERSION_MAJOR_NUM, U_ICU_VERSION_MINOR_NUM)
+
+/**
+ * Do not use.
+ * @internal
+ */
+#define U_DEF2_ICUDATA_ENTRY_POINT(major, minor) U_DEF_ICUDATA_ENTRY_POINT(major, minor)
+/**
+ * Do not use.
+ * @internal
+ */
+#define U_DEF_ICUDATA_ENTRY_POINT(major, minor) icudt##major##minor##_dat
+
+/**
+ * \def U_CALLCONV
+ * Similar to U_CDECL_BEGIN/U_CDECL_END, this qualifier is necessary
+ * in callback function typedefs to make sure that the calling convention
+ * is compatible.
+ *
+ * This is only used for non-ICU-API functions.
+ * When a function is a public ICU API,
+ * you must use the U_CAPI and U_EXPORT2 qualifiers.
+ * @stable ICU 2.0
+ */
+#if defined(OS390) && (__COMPILER_VER__ < 0x41020000) && defined(XP_CPLUSPLUS)
+#    define U_CALLCONV __cdecl
+#else
+#    define U_CALLCONV U_EXPORT2
+#endif
+
+/**
+ * \def NULL
+ * Define NULL if necessary, to 0 for C++ and to ((void *)0) for C.
+ * @stable ICU 2.0
+ */
+#ifndef NULL
+#ifdef XP_CPLUSPLUS
+#define NULL    0
+#else
+#define NULL    ((void *)0)
+#endif
+#endif
+
+/*===========================================================================*/
+/* Calendar/TimeZone data types                                              */
+/*===========================================================================*/
+
+/**
+ * Date and Time data type.
+ * This is a primitive data type that holds the date and time
+ * as the number of milliseconds since 1970-jan-01, 00:00 UTC.
+ * UTC leap seconds are ignored.
+ * @stable ICU 2.0
+ */
+typedef double UDate;
+
+/** The number of milliseconds per second @stable ICU 2.0 */
+#define U_MILLIS_PER_SECOND        (1000)
+/** The number of milliseconds per minute @stable ICU 2.0 */
+#define U_MILLIS_PER_MINUTE       (60000)
+/** The number of milliseconds per hour @stable ICU 2.0 */
+#define U_MILLIS_PER_HOUR       (3600000)
+/** The number of milliseconds per day @stable ICU 2.0 */
+#define U_MILLIS_PER_DAY       (86400000)
+
+
+/*===========================================================================*/
+/* UClassID-based RTTI */
+/*===========================================================================*/
+
+/**
+ * UClassID is used to identify classes without using RTTI, since RTTI
+ * is not yet supported by all C++ compilers.  Each class hierarchy which needs
+ * to implement polymorphic clone() or operator==() defines two methods,
+ * described in detail below.  UClassID values can be compared using
+ * operator==(). Nothing else should be done with them.
+ *
+ * \par
+ * getDynamicClassID() is declared in the base class of the hierarchy as
+ * a pure virtual.  Each concrete subclass implements it in the same way:
+ *
+ * \code
+ *      class Base {
+ *      public:
+ *          virtual UClassID getDynamicClassID() const = 0;
+ *      }
+ *
+ *      class Derived {
+ *      public:
+ *          virtual UClassID getDynamicClassID() const
+ *            { return Derived::getStaticClassID(); }
+ *      }
+ * \endcode
+ *
+ * Each concrete class implements getStaticClassID() as well, which allows
+ * clients to test for a specific type.
+ *
+ * \code
+ *      class Derived {
+ *      public:
+ *          static UClassID U_EXPORT2 getStaticClassID();
+ *      private:
+ *          static char fgClassID;
+ *      }
+ *
+ *      // In Derived.cpp:
+ *      UClassID Derived::getStaticClassID()
+ *        { return (UClassID)&Derived::fgClassID; }
+ *      char Derived::fgClassID = 0; // Value is irrelevant
+ * \endcode
+ * @stable ICU 2.0
+ */
+typedef void* UClassID;
+
+/*===========================================================================*/
+/* Shared library/DLL import-export API control                              */
+/*===========================================================================*/
+
+/*
+ * Control of symbol import/export.
+ * ICU is separated into three libraries.
+ */
+
+/*
+ * \def U_COMBINED_IMPLEMENTATION
+ * Set to export library symbols from inside the ICU library
+ * when all of ICU is in a single library.
+ * This can be set as a compiler option while building ICU, and it
+ * needs to be the first one tested to override U_COMMON_API, U_I18N_API, etc.
+ * @stable ICU 2.0
+ */
+
+/**
+ * \def U_DATA_API
+ * Set to export library symbols from inside the stubdata library,
+ * and to import them from outside.
+ * @stable ICU 3.0
+ */
+
+/**
+ * \def U_COMMON_API
+ * Set to export library symbols from inside the common library,
+ * and to import them from outside.
+ * @stable ICU 2.0
+ */
+
+/**
+ * \def U_I18N_API
+ * Set to export library symbols from inside the i18n library,
+ * and to import them from outside.
+ * @stable ICU 2.0
+ */
+
+/**
+ * \def U_LAYOUT_API
+ * Set to export library symbols from inside the layout engine library,
+ * and to import them from outside.
+ * @stable ICU 2.0
+ */
+
+/**
+ * \def U_LAYOUTEX_API
+ * Set to export library symbols from inside the layout extensions library,
+ * and to import them from outside.
+ * @stable ICU 2.6
+ */
+
+/**
+ * \def U_IO_API
+ * Set to export library symbols from inside the ustdio library,
+ * and to import them from outside.
+ * @stable ICU 2.0
+ */
+
+/**
+ * \def U_TOOLUTIL_API
+ * Set to export library symbols from inside the toolutil library,
+ * and to import them from outside.
+ * @stable ICU 3.4
+ */
+
+#if defined(U_COMBINED_IMPLEMENTATION)
+#define U_DATA_API     U_EXPORT
+#define U_COMMON_API   U_EXPORT
+#define U_I18N_API     U_EXPORT
+#define U_LAYOUT_API   U_EXPORT
+#define U_LAYOUTEX_API U_EXPORT
+#define U_IO_API       U_EXPORT
+#define U_TOOLUTIL_API U_EXPORT
+#elif defined(U_STATIC_IMPLEMENTATION)
+#define U_DATA_API
+#define U_COMMON_API
+#define U_I18N_API
+#define U_LAYOUT_API
+#define U_LAYOUTEX_API
+#define U_IO_API
+#define U_TOOLUTIL_API
+#elif defined(U_COMMON_IMPLEMENTATION)
+#define U_DATA_API     U_IMPORT
+#define U_COMMON_API   U_EXPORT
+#define U_I18N_API     U_IMPORT
+#define U_LAYOUT_API   U_IMPORT
+#define U_LAYOUTEX_API U_IMPORT
+#define U_IO_API       U_IMPORT
+#define U_TOOLUTIL_API U_IMPORT
+#elif defined(U_I18N_IMPLEMENTATION)
+#define U_DATA_API     U_IMPORT
+#define U_COMMON_API   U_IMPORT
+#define U_I18N_API     U_EXPORT
+#define U_LAYOUT_API   U_IMPORT
+#define U_LAYOUTEX_API U_IMPORT
+#define U_IO_API       U_IMPORT
+#define U_TOOLUTIL_API U_IMPORT
+#elif defined(U_LAYOUT_IMPLEMENTATION)
+#define U_DATA_API     U_IMPORT
+#define U_COMMON_API   U_IMPORT
+#define U_I18N_API     U_IMPORT
+#define U_LAYOUT_API   U_EXPORT
+#define U_LAYOUTEX_API U_IMPORT
+#define U_IO_API       U_IMPORT
+#define U_TOOLUTIL_API U_IMPORT
+#elif defined(U_LAYOUTEX_IMPLEMENTATION)
+#define U_DATA_API     U_IMPORT
+#define U_COMMON_API   U_IMPORT
+#define U_I18N_API     U_IMPORT
+#define U_LAYOUT_API   U_IMPORT
+#define U_LAYOUTEX_API U_EXPORT
+#define U_IO_API       U_IMPORT
+#define U_TOOLUTIL_API U_IMPORT
+#elif defined(U_IO_IMPLEMENTATION)
+#define U_DATA_API     U_IMPORT
+#define U_COMMON_API   U_IMPORT
+#define U_I18N_API     U_IMPORT
+#define U_LAYOUT_API   U_IMPORT
+#define U_LAYOUTEX_API U_IMPORT
+#define U_IO_API       U_EXPORT
+#define U_TOOLUTIL_API U_IMPORT
+#elif defined(U_TOOLUTIL_IMPLEMENTATION)
+#define U_DATA_API     U_IMPORT
+#define U_COMMON_API   U_IMPORT
+#define U_I18N_API     U_IMPORT
+#define U_LAYOUT_API   U_IMPORT
+#define U_LAYOUTEX_API U_IMPORT
+#define U_IO_API       U_IMPORT
+#define U_TOOLUTIL_API U_EXPORT
+#else
+#define U_DATA_API     U_IMPORT
+#define U_COMMON_API   U_IMPORT
+#define U_I18N_API     U_IMPORT
+#define U_LAYOUT_API   U_IMPORT
+#define U_LAYOUTEX_API U_IMPORT
+#define U_IO_API       U_IMPORT
+#define U_TOOLUTIL_API U_IMPORT
+#endif
+
+/**
+ * \def U_STANDARD_CPP_NAMESPACE
+ * Control of C++ Namespace
+ * @stable ICU 2.0
+ */
+#ifdef __cplusplus
+#define U_STANDARD_CPP_NAMESPACE        ::
+#else
+#define U_STANDARD_CPP_NAMESPACE
+#endif
+
+
+/*===========================================================================*/
+/* Global delete operator                                                    */
+/*===========================================================================*/
+
+/*
+ * The ICU4C library must not use the global new and delete operators.
+ * These operators here are defined to enable testing for this.
+ * See Jitterbug 2581 for details of why this is necessary.
+ *
+ * Verification that ICU4C's memory usage is correct, i.e.,
+ * that global new/delete are not used:
+ *
+ * a) Check for imports of global new/delete (see uobject.cpp for details)
+ * b) Verify that new is never imported.
+ * c) Verify that delete is only imported from object code for interface/mixin classes.
+ * d) Add global delete and delete[] only for the ICU4C library itself
+ *    and define them in a way that crashes or otherwise easily shows a problem.
+ *
+ * The following implements d).
+ * The operator implementations crash; this is intentional and used for library debugging.
+ *
+ * Note: This is currently only done on Windows because
+ * some Linux/Unix compilers have problems with defining global new/delete.
+ * On Windows, U_WINDOWS is defined, and it is _MSC_VER>=1200 for MSVC 6.0 and higher.
+ */
+#if defined(XP_CPLUSPLUS) && defined(U_WINDOWS) && U_DEBUG && U_OVERRIDE_CXX_ALLOCATION && (_MSC_VER>=1200) && !defined(U_STATIC_IMPLEMENTATION) && (defined(U_COMMON_IMPLEMENTATION) || defined(U_I18N_IMPLEMENTATION) || defined(U_IO_IMPLEMENTATION) || defined(U_LAYOUT_IMPLEMENTATION) || defined(U_LAYOUTEX_IMPLEMENTATION))
+
+#ifndef U_HIDE_INTERNAL_API
+/**
+ * Global operator new, defined only inside ICU4C, must not be used.
+ * Crashes intentionally.
+ * @internal
+ */
+inline void *
+operator new(size_t /*size*/) {
+    char *q=NULL;
+    *q=5; /* break it */
+    return q;
+}
+
+#ifdef _Ret_bytecap_
+/* This is only needed to suppress a Visual C++ 2008 warning for operator new[]. */
+_Ret_bytecap_(_Size)
+#endif
+/**
+ * Global operator new[], defined only inside ICU4C, must not be used.
+ * Crashes intentionally.
+ * @internal
+ */
+inline void *
+operator new[](size_t /*size*/) {
+    char *q=NULL;
+    *q=5; /* break it */
+    return q;
+}
+
+/**
+ * Global operator delete, defined only inside ICU4C, must not be used.
+ * Crashes intentionally.
+ * @internal
+ */
+inline void
+operator delete(void * /*p*/) {
+    char *q=NULL;
+    *q=5; /* break it */
+}
+
+/**
+ * Global operator delete[], defined only inside ICU4C, must not be used.
+ * Crashes intentionally.
+ * @internal
+ */
+inline void
+operator delete[](void * /*p*/) {
+    char *q=NULL;
+    *q=5; /* break it */
+}
+
+#endif /* U_HIDE_INTERNAL_API */
+#endif
+
+/*===========================================================================*/
+/* UErrorCode */
+/*===========================================================================*/
+
+/**
+ * Error code to replace exception handling, so that the code is compatible with all C++ compilers,
+ * and to use the same mechanism for C and C++.
+ *
+ * \par
+ * ICU functions that take a reference (C++) or a pointer (C) to a UErrorCode
+ * first test if(U_FAILURE(errorCode)) { return immediately; }
+ * so that in a chain of such functions the first one that sets an error code
+ * causes the following ones to not perform any operations.
+ *
+ * \par
+ * Error codes should be tested using U_FAILURE() and U_SUCCESS().
+ * @stable ICU 2.0
+ */
+typedef enum UErrorCode {
+    /* The ordering of U_ERROR_INFO_START Vs U_USING_FALLBACK_WARNING looks weird
+     * and is that way because VC++ debugger displays first encountered constant,
+     * which is not the what the code is used for
+     */
+
+    U_USING_FALLBACK_WARNING  = -128,   /**< A resource bundle lookup returned a fallback result (not an error) */
+
+    U_ERROR_WARNING_START     = -128,   /**< Start of information results (semantically successful) */
+
+    U_USING_DEFAULT_WARNING   = -127,   /**< A resource bundle lookup returned a result from the root locale (not an error) */
+
+    U_SAFECLONE_ALLOCATED_WARNING = -126, /**< A SafeClone operation required allocating memory (informational only) */
+
+    U_STATE_OLD_WARNING       = -125,   /**< ICU has to use compatibility layer to construct the service. Expect performance/memory usage degradation. Consider upgrading */
+
+    U_STRING_NOT_TERMINATED_WARNING = -124,/**< An output string could not be NUL-terminated because output length==destCapacity. */
+
+    U_SORT_KEY_TOO_SHORT_WARNING = -123, /**< Number of levels requested in getBound is higher than the number of levels in the sort key */
+
+    U_AMBIGUOUS_ALIAS_WARNING = -122,   /**< This converter alias can go to different converter implementations */
+
+    U_DIFFERENT_UCA_VERSION = -121,     /**< ucol_open encountered a mismatch between UCA version and collator image version, so the collator was constructed from rules. No impact to further function */
+
+    U_ERROR_WARNING_LIMIT,              /**< This must always be the last warning value to indicate the limit for UErrorCode warnings (last warning code +1) */
+
+
+    U_ZERO_ERROR              =  0,     /**< No error, no warning. */
+
+    U_ILLEGAL_ARGUMENT_ERROR  =  1,     /**< Start of codes indicating failure */
+    U_MISSING_RESOURCE_ERROR  =  2,     /**< The requested resource cannot be found */
+    U_INVALID_FORMAT_ERROR    =  3,     /**< Data format is not what is expected */
+    U_FILE_ACCESS_ERROR       =  4,     /**< The requested file cannot be found */
+    U_INTERNAL_PROGRAM_ERROR  =  5,     /**< Indicates a bug in the library code */
+    U_MESSAGE_PARSE_ERROR     =  6,     /**< Unable to parse a message (message format) */
+    U_MEMORY_ALLOCATION_ERROR =  7,     /**< Memory allocation error */
+    U_INDEX_OUTOFBOUNDS_ERROR =  8,     /**< Trying to access the index that is out of bounds */
+    U_PARSE_ERROR             =  9,     /**< Equivalent to Java ParseException */
+    U_INVALID_CHAR_FOUND      = 10,     /**< Character conversion: Unmappable input sequence. In other APIs: Invalid character. */
+    U_TRUNCATED_CHAR_FOUND    = 11,     /**< Character conversion: Incomplete input sequence. */
+    U_ILLEGAL_CHAR_FOUND      = 12,     /**< Character conversion: Illegal input sequence/combination of input units. */
+    U_INVALID_TABLE_FORMAT    = 13,     /**< Conversion table file found, but corrupted */
+    U_INVALID_TABLE_FILE      = 14,     /**< Conversion table file not found */
+    U_BUFFER_OVERFLOW_ERROR   = 15,     /**< A result would not fit in the supplied buffer */
+    U_UNSUPPORTED_ERROR       = 16,     /**< Requested operation not supported in current context */
+    U_RESOURCE_TYPE_MISMATCH  = 17,     /**< an operation is requested over a resource that does not support it */
+    U_ILLEGAL_ESCAPE_SEQUENCE = 18,     /**< ISO-2022 illlegal escape sequence */
+    U_UNSUPPORTED_ESCAPE_SEQUENCE = 19, /**< ISO-2022 unsupported escape sequence */
+    U_NO_SPACE_AVAILABLE      = 20,     /**< No space available for in-buffer expansion for Arabic shaping */
+    U_CE_NOT_FOUND_ERROR      = 21,     /**< Currently used only while setting variable top, but can be used generally */
+    U_PRIMARY_TOO_LONG_ERROR  = 22,     /**< User tried to set variable top to a primary that is longer than two bytes */
+    U_STATE_TOO_OLD_ERROR     = 23,     /**< ICU cannot construct a service from this state, as it is no longer supported */
+    U_TOO_MANY_ALIASES_ERROR  = 24,     /**< There are too many aliases in the path to the requested resource.
+                                             It is very possible that a circular alias definition has occured */
+    U_ENUM_OUT_OF_SYNC_ERROR  = 25,     /**< UEnumeration out of sync with underlying collection */
+    U_INVARIANT_CONVERSION_ERROR = 26,  /**< Unable to convert a UChar* string to char* with the invariant converter. */
+    U_INVALID_STATE_ERROR     = 27,     /**< Requested operation can not be completed with ICU in its current state */
+    U_COLLATOR_VERSION_MISMATCH = 28,   /**< Collator version is not compatible with the base version */
+    U_USELESS_COLLATOR_ERROR  = 29,     /**< Collator is options only and no base is specified */
+    U_NO_WRITE_PERMISSION     = 30,     /**< Attempt to modify read-only or constant data. */
+
+    U_STANDARD_ERROR_LIMIT,             /**< This must always be the last value to indicate the limit for standard errors */
+    /*
+     * the error code range 0x10000 0x10100 are reserved for Transliterator
+     */
+    U_BAD_VARIABLE_DEFINITION=0x10000,/**< Missing '$' or duplicate variable name */
+    U_PARSE_ERROR_START = 0x10000,    /**< Start of Transliterator errors */
+    U_MALFORMED_RULE,                 /**< Elements of a rule are misplaced */
+    U_MALFORMED_SET,                  /**< A UnicodeSet pattern is invalid*/
+    U_MALFORMED_SYMBOL_REFERENCE,     /**< UNUSED as of ICU 2.4 */
+    U_MALFORMED_UNICODE_ESCAPE,       /**< A Unicode escape pattern is invalid*/
+    U_MALFORMED_VARIABLE_DEFINITION,  /**< A variable definition is invalid */
+    U_MALFORMED_VARIABLE_REFERENCE,   /**< A variable reference is invalid */
+    U_MISMATCHED_SEGMENT_DELIMITERS,  /**< UNUSED as of ICU 2.4 */
+    U_MISPLACED_ANCHOR_START,         /**< A start anchor appears at an illegal position */
+    U_MISPLACED_CURSOR_OFFSET,        /**< A cursor offset occurs at an illegal position */
+    U_MISPLACED_QUANTIFIER,           /**< A quantifier appears after a segment close delimiter */
+    U_MISSING_OPERATOR,               /**< A rule contains no operator */
+    U_MISSING_SEGMENT_CLOSE,          /**< UNUSED as of ICU 2.4 */
+    U_MULTIPLE_ANTE_CONTEXTS,         /**< More than one ante context */
+    U_MULTIPLE_CURSORS,               /**< More than one cursor */
+    U_MULTIPLE_POST_CONTEXTS,         /**< More than one post context */
+    U_TRAILING_BACKSLASH,             /**< A dangling backslash */
+    U_UNDEFINED_SEGMENT_REFERENCE,    /**< A segment reference does not correspond to a defined segment */
+    U_UNDEFINED_VARIABLE,             /**< A variable reference does not correspond to a defined variable */
+    U_UNQUOTED_SPECIAL,               /**< A special character was not quoted or escaped */
+    U_UNTERMINATED_QUOTE,             /**< A closing single quote is missing */
+    U_RULE_MASK_ERROR,                /**< A rule is hidden by an earlier more general rule */
+    U_MISPLACED_COMPOUND_FILTER,      /**< A compound filter is in an invalid location */
+    U_MULTIPLE_COMPOUND_FILTERS,      /**< More than one compound filter */
+    U_INVALID_RBT_SYNTAX,             /**< A "::id" rule was passed to the RuleBasedTransliterator parser */
+    U_INVALID_PROPERTY_PATTERN,       /**< UNUSED as of ICU 2.4 */
+    U_MALFORMED_PRAGMA,               /**< A 'use' pragma is invlalid */
+    U_UNCLOSED_SEGMENT,               /**< A closing ')' is missing */
+    U_ILLEGAL_CHAR_IN_SEGMENT,        /**< UNUSED as of ICU 2.4 */
+    U_VARIABLE_RANGE_EXHAUSTED,       /**< Too many stand-ins generated for the given variable range */
+    U_VARIABLE_RANGE_OVERLAP,         /**< The variable range overlaps characters used in rules */
+    U_ILLEGAL_CHARACTER,              /**< A special character is outside its allowed context */
+    U_INTERNAL_TRANSLITERATOR_ERROR,  /**< Internal transliterator system error */
+    U_INVALID_ID,                     /**< A "::id" rule specifies an unknown transliterator */
+    U_INVALID_FUNCTION,               /**< A "&fn()" rule specifies an unknown transliterator */
+    U_PARSE_ERROR_LIMIT,              /**< The limit for Transliterator errors */
+
+    /*
+     * the error code range 0x10100 0x10200 are reserved for formatting API parsing error
+     */
+    U_UNEXPECTED_TOKEN=0x10100,       /**< Syntax error in format pattern */
+    U_FMT_PARSE_ERROR_START=0x10100,  /**< Start of format library errors */
+    U_MULTIPLE_DECIMAL_SEPARATORS,    /**< More than one decimal separator in number pattern */
+    U_MULTIPLE_DECIMAL_SEPERATORS = U_MULTIPLE_DECIMAL_SEPARATORS, /**< Typo: kept for backward compatibility. Use U_MULTIPLE_DECIMAL_SEPARATORS */
+    U_MULTIPLE_EXPONENTIAL_SYMBOLS,   /**< More than one exponent symbol in number pattern */
+    U_MALFORMED_EXPONENTIAL_PATTERN,  /**< Grouping symbol in exponent pattern */
+    U_MULTIPLE_PERCENT_SYMBOLS,       /**< More than one percent symbol in number pattern */
+    U_MULTIPLE_PERMILL_SYMBOLS,       /**< More than one permill symbol in number pattern */
+    U_MULTIPLE_PAD_SPECIFIERS,        /**< More than one pad symbol in number pattern */
+    U_PATTERN_SYNTAX_ERROR,           /**< Syntax error in format pattern */
+    U_ILLEGAL_PAD_POSITION,           /**< Pad symbol misplaced in number pattern */
+    U_UNMATCHED_BRACES,               /**< Braces do not match in message pattern */
+    U_UNSUPPORTED_PROPERTY,           /**< UNUSED as of ICU 2.4 */
+    U_UNSUPPORTED_ATTRIBUTE,          /**< UNUSED as of ICU 2.4 */
+    U_ARGUMENT_TYPE_MISMATCH,         /**< Argument name and argument index mismatch in MessageFormat functions */
+    U_DUPLICATE_KEYWORD,              /**< Duplicate keyword in PluralFormat */
+    U_UNDEFINED_KEYWORD,              /**< Undefined Pluarl keyword */
+    U_DEFAULT_KEYWORD_MISSING,        /**< Missing DEFAULT rule in plural rules */
+    U_FMT_PARSE_ERROR_LIMIT,          /**< The limit for format library errors */
+
+    /*
+     * the error code range 0x10200 0x102ff are reserved for Break Iterator related error
+     */
+    U_BRK_INTERNAL_ERROR=0x10200,          /**< An internal error (bug) was detected.             */
+    U_BRK_ERROR_START=0x10200,             /**< Start of codes indicating Break Iterator failures */
+    U_BRK_HEX_DIGITS_EXPECTED,             /**< Hex digits expected as part of a escaped char in a rule. */
+    U_BRK_SEMICOLON_EXPECTED,              /**< Missing ';' at the end of a RBBI rule.            */
+    U_BRK_RULE_SYNTAX,                     /**< Syntax error in RBBI rule.                        */
+    U_BRK_UNCLOSED_SET,                    /**< UnicodeSet witing an RBBI rule missing a closing ']'.  */
+    U_BRK_ASSIGN_ERROR,                    /**< Syntax error in RBBI rule assignment statement.   */
+    U_BRK_VARIABLE_REDFINITION,            /**< RBBI rule $Variable redefined.                    */
+    U_BRK_MISMATCHED_PAREN,                /**< Mis-matched parentheses in an RBBI rule.          */
+    U_BRK_NEW_LINE_IN_QUOTED_STRING,       /**< Missing closing quote in an RBBI rule.            */
+    U_BRK_UNDEFINED_VARIABLE,              /**< Use of an undefined $Variable in an RBBI rule.    */
+    U_BRK_INIT_ERROR,                      /**< Initialization failure.  Probable missing ICU Data. */
+    U_BRK_RULE_EMPTY_SET,                  /**< Rule contains an empty Unicode Set.               */
+    U_BRK_UNRECOGNIZED_OPTION,             /**< !!option in RBBI rules not recognized.            */
+    U_BRK_MALFORMED_RULE_TAG,              /**< The {nnn} tag on a rule is mal formed             */
+    U_BRK_ERROR_LIMIT,                     /**< This must always be the last value to indicate the limit for Break Iterator failures */
+
+    /*
+     * The error codes in the range 0x10300-0x103ff are reserved for regular expression related errrs
+     */
+    U_REGEX_INTERNAL_ERROR=0x10300,       /**< An internal error (bug) was detected.              */
+    U_REGEX_ERROR_START=0x10300,          /**< Start of codes indicating Regexp failures          */
+    U_REGEX_RULE_SYNTAX,                  /**< Syntax error in regexp pattern.                    */
+    U_REGEX_INVALID_STATE,                /**< RegexMatcher in invalid state for requested operation */
+    U_REGEX_BAD_ESCAPE_SEQUENCE,          /**< Unrecognized backslash escape sequence in pattern  */
+    U_REGEX_PROPERTY_SYNTAX,              /**< Incorrect Unicode property                         */
+    U_REGEX_UNIMPLEMENTED,                /**< Use of regexp feature that is not yet implemented. */
+    U_REGEX_MISMATCHED_PAREN,             /**< Incorrectly nested parentheses in regexp pattern.  */
+    U_REGEX_NUMBER_TOO_BIG,               /**< Decimal number is too large.                       */
+    U_REGEX_BAD_INTERVAL,                 /**< Error in {min,max} interval                        */
+    U_REGEX_MAX_LT_MIN,                   /**< In {min,max}, max is less than min.                */
+    U_REGEX_INVALID_BACK_REF,             /**< Back-reference to a non-existent capture group.    */
+    U_REGEX_INVALID_FLAG,                 /**< Invalid value for match mode flags.                */
+    U_REGEX_LOOK_BEHIND_LIMIT,            /**< Look-Behind pattern matches must have a bounded maximum length.    */
+    U_REGEX_SET_CONTAINS_STRING,          /**< Regexps cannot have UnicodeSets containing strings.*/
+    U_REGEX_OCTAL_TOO_BIG,                /**< Octal character constants must be <= 0377.         */
+    U_REGEX_MISSING_CLOSE_BRACKET,        /**< Missing closing bracket on a bracket expression.   */
+    U_REGEX_INVALID_RANGE,                /**< In a character range [x-y], x is greater than y.   */
+    U_REGEX_STACK_OVERFLOW,               /**< Regular expression backtrack stack overflow.       */
+    U_REGEX_TIME_OUT,                     /**< Maximum allowed match time exceeded                */
+    U_REGEX_STOPPED_BY_CALLER,            /**< Matching operation aborted by user callback fn.    */
+    U_REGEX_ERROR_LIMIT,                  /**< This must always be the last value to indicate the limit for regexp errors */
+
+    /*
+     * The error code in the range 0x10400-0x104ff are reserved for IDNA related error codes
+     */
+    U_IDNA_PROHIBITED_ERROR=0x10400,
+    U_IDNA_ERROR_START=0x10400,
+    U_IDNA_UNASSIGNED_ERROR,
+    U_IDNA_CHECK_BIDI_ERROR,
+    U_IDNA_STD3_ASCII_RULES_ERROR,
+    U_IDNA_ACE_PREFIX_ERROR,
+    U_IDNA_VERIFICATION_ERROR,
+    U_IDNA_LABEL_TOO_LONG_ERROR,
+    U_IDNA_ZERO_LENGTH_LABEL_ERROR,
+    U_IDNA_DOMAIN_NAME_TOO_LONG_ERROR,
+    U_IDNA_ERROR_LIMIT,
+    /*
+     * Aliases for StringPrep
+     */
+    U_STRINGPREP_PROHIBITED_ERROR = U_IDNA_PROHIBITED_ERROR,
+    U_STRINGPREP_UNASSIGNED_ERROR = U_IDNA_UNASSIGNED_ERROR,
+    U_STRINGPREP_CHECK_BIDI_ERROR = U_IDNA_CHECK_BIDI_ERROR,
+
+
+    U_ERROR_LIMIT=U_IDNA_ERROR_LIMIT      /**< This must always be the last value to indicate the limit for UErrorCode (last error code +1) */
+} UErrorCode;
+
+/* Use the following to determine if an UErrorCode represents */
+/* operational success or failure. */
+
+#ifdef XP_CPLUSPLUS
+    /**
+     * Does the error code indicate success?
+     * @stable ICU 2.0
+     */
+    static
+    inline UBool U_SUCCESS(UErrorCode code) { return (UBool)(code<=U_ZERO_ERROR); }
+    /**
+     * Does the error code indicate a failure?
+     * @stable ICU 2.0
+     */
+    static
+    inline UBool U_FAILURE(UErrorCode code) { return (UBool)(code>U_ZERO_ERROR); }
+#else
+    /**
+     * Does the error code indicate success?
+     * @stable ICU 2.0
+     */
+#   define U_SUCCESS(x) ((x)<=U_ZERO_ERROR)
+    /**
+     * Does the error code indicate a failure?
+     * @stable ICU 2.0
+     */
+#   define U_FAILURE(x) ((x)>U_ZERO_ERROR)
+#endif
+
+/**
+ * Return a string for a UErrorCode value.
+ * The string will be the same as the name of the error code constant
+ * in the UErrorCode enum above.
+ * @stable ICU 2.0
+ */
+U_STABLE const char * U_EXPORT2
+u_errorName(UErrorCode code);
+
+
+#endif /* _UTYPES */

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/uversion.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/uversion.h b/src/apps/couch_collate/platform/osx/icu/unicode/uversion.h
new file mode 100644
index 0000000..5bf7fda
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/uversion.h
@@ -0,0 +1,275 @@
+/*
+*******************************************************************************
+*   Copyright (C) 2000-2008, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+*******************************************************************************
+*
+*   file name:  uversion.h
+*   encoding:   US-ASCII
+*   tab size:   8 (not used)
+*   indentation:4
+*
+*   Created by: Vladimir Weinstein
+*
+*  Contains all the important version numbers for ICU. 
+*  Gets included by utypes.h and Windows .rc files
+*/
+
+/**
+ * \file
+ * \brief C API: Contains all the important version numbers for ICU. 
+ */
+/*===========================================================================*/
+/* Main ICU version information                                              */
+/*===========================================================================*/
+
+#ifndef UVERSION_H
+#define UVERSION_H
+
+/**
+ * IMPORTANT: When updating version, the following things need to be done:
+ * source/common/unicode/uversion.h - this file: update major, minor,
+ *        patchlevel, suffix, version, short version constants, namespace,
+ *                                                             and copyright
+ * source/common/common.vcproj - update 'Output file name' on the link tab so
+ *                   that it contains the new major/minor combination
+ * source/i18n/i18n.vcproj - same as for the common.vcproj
+ * source/layout/layout.vcproj - same as for the common.vcproj
+ * source/layoutex/layoutex.vcproj - same
+ * source/stubdata/stubdata.vcproj - same as for the common.vcproj
+ * source/io/io.vcproj - same as for the common.vcproj
+ * source/data/makedata.mak - change U_ICUDATA_NAME so that it contains
+ *                            the new major/minor combination
+ * source/tools/genren/genren.pl - use this script according to the README
+ *                    in that folder                                         
+ */
+
+#include "unicode/umachine.h"
+
+/** The standard copyright notice that gets compiled into each library. 
+ *  This value will change in the subsequent releases of ICU
+ *  @stable ICU 2.4
+ */
+#define U_COPYRIGHT_STRING \
+  " Copyright (C) 2008, International Business Machines Corporation and others. All Rights Reserved. "
+
+/** Maximum length of the copyright string.
+ *  @stable ICU 2.4
+ */
+#define U_COPYRIGHT_STRING_LENGTH  128
+
+/** The current ICU major version as an integer. 
+ *  This value will change in the subsequent releases of ICU
+ *  @stable ICU 2.4
+ */
+#define U_ICU_VERSION_MAJOR_NUM 4
+
+/** The current ICU minor version as an integer. 
+ *  This value will change in the subsequent releases of ICU
+ *  @stable ICU 2.6
+ */
+#define U_ICU_VERSION_MINOR_NUM 0
+
+/** The current ICU patchlevel version as an integer.  
+ *  This value will change in the subsequent releases of ICU
+ *  @stable ICU 2.4
+ */
+#define U_ICU_VERSION_PATCHLEVEL_NUM 0
+
+/** The current ICU build level version as an integer.  
+ *  This value is for use by ICU clients. It defaults to 0.
+ *  @draft ICU 4.0
+ */
+#ifndef U_ICU_VERSION_BUILDLEVEL_NUM
+#define U_ICU_VERSION_BUILDLEVEL_NUM 0
+#endif
+
+/** Glued version suffix for renamers 
+ *  This value will change in the subsequent releases of ICU
+ *  @stable ICU 2.6
+ */
+#define U_ICU_VERSION_SUFFIX _4_0
+
+/** The current ICU library version as a dotted-decimal string. The patchlevel
+ *  only appears in this string if it non-zero. 
+ *  This value will change in the subsequent releases of ICU
+ *  @stable ICU 2.4
+ */
+#define U_ICU_VERSION "4.0"
+
+/** The current ICU library major/minor version as a string without dots, for library name suffixes. 
+ *  This value will change in the subsequent releases of ICU
+ *  @stable ICU 2.6
+ */
+#define U_ICU_VERSION_SHORT "40"
+
+/** An ICU version consists of up to 4 numbers from 0..255.
+ *  @stable ICU 2.4
+ */
+#define U_MAX_VERSION_LENGTH 4
+
+/** In a string, ICU version fields are delimited by dots.
+ *  @stable ICU 2.4
+ */
+#define U_VERSION_DELIMITER '.'
+
+/** The maximum length of an ICU version string.
+ *  @stable ICU 2.4
+ */
+#define U_MAX_VERSION_STRING_LENGTH 20
+
+/** The binary form of a version on ICU APIs is an array of 4 uint8_t.
+ *  @stable ICU 2.4
+ */
+typedef uint8_t UVersionInfo[U_MAX_VERSION_LENGTH];
+
+/*===========================================================================*/
+/* C++ namespace if supported. Versioned unless versioning is disabled.      */
+/*===========================================================================*/
+
+/**
+ * \def U_NAMESPACE_BEGIN
+ * This is used to begin a declaration of a public ICU C++ API.
+ * If the compiler doesn't support namespaces, this does nothing.
+ * @stable ICU 2.4
+ */
+
+/**
+ * \def U_NAMESPACE_END
+ * This is used to end a declaration of a public ICU C++ API 
+ * If the compiler doesn't support namespaces, this does nothing.
+ * @stable ICU 2.4
+ */
+
+/**
+ * \def U_NAMESPACE_USE
+ * This is used to specify that the rest of the code uses the
+ * public ICU C++ API namespace.
+ * If the compiler doesn't support namespaces, this does nothing.
+ * @stable ICU 2.4
+ */
+
+/**
+ * \def U_NAMESPACE_QUALIFIER
+ * This is used to qualify that a function or class is part of
+ * the public ICU C++ API namespace.
+ * If the compiler doesn't support namespaces, this does nothing.
+ * @stable ICU 2.4
+ */
+
+/* Define namespace symbols if the compiler supports it. */
+#if U_HAVE_NAMESPACE && defined(XP_CPLUSPLUS)
+#   if U_DISABLE_RENAMING
+#       define U_ICU_NAMESPACE icu
+        namespace U_ICU_NAMESPACE { }
+#   else
+#       define U_ICU_NAMESPACE icu_4_0
+        namespace U_ICU_NAMESPACE { }
+        namespace icu = U_ICU_NAMESPACE;
+#   endif
+
+#   define U_NAMESPACE_BEGIN namespace U_ICU_NAMESPACE {
+#   define U_NAMESPACE_END  }
+#   define U_NAMESPACE_USE using namespace U_ICU_NAMESPACE;
+#   define U_NAMESPACE_QUALIFIER U_ICU_NAMESPACE::
+
+#   ifndef U_USING_ICU_NAMESPACE
+#       define U_USING_ICU_NAMESPACE 1
+#   endif
+#   if U_USING_ICU_NAMESPACE
+        U_NAMESPACE_USE
+#   endif
+#else
+#   define U_NAMESPACE_BEGIN
+#   define U_NAMESPACE_END
+#   define U_NAMESPACE_USE
+#   define U_NAMESPACE_QUALIFIER
+#endif
+
+
+/*===========================================================================*/
+/* General version helper functions. Definitions in putil.c                  */
+/*===========================================================================*/
+
+/**
+ * Parse a string with dotted-decimal version information and
+ * fill in a UVersionInfo structure with the result.
+ * Definition of this function lives in putil.c
+ *
+ * @param versionArray The destination structure for the version information.
+ * @param versionString A string with dotted-decimal version information,
+ *                      with up to four non-negative number fields with
+ *                      values of up to 255 each.
+ * @stable ICU 2.4
+ */
+U_STABLE void U_EXPORT2
+u_versionFromString(UVersionInfo versionArray, const char *versionString);
+
+/**
+ * Write a string with dotted-decimal version information according
+ * to the input UVersionInfo.
+ * Definition of this function lives in putil.c
+ *
+ * @param versionArray The version information to be written as a string.
+ * @param versionString A string buffer that will be filled in with
+ *                      a string corresponding to the numeric version
+ *                      information in versionArray.
+ *                      The buffer size must be at least U_MAX_VERSION_STRING_LENGTH.
+ * @stable ICU 2.4
+ */
+U_STABLE void U_EXPORT2
+u_versionToString(UVersionInfo versionArray, char *versionString);
+
+/**
+ * Gets the ICU release version.  The version array stores the version information
+ * for ICU.  For example, release "1.3.31.2" is then represented as 0x01031F02.
+ * Definition of this function lives in putil.c
+ *
+ * @param versionArray the version # information, the result will be filled in
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2
+u_getVersion(UVersionInfo versionArray);
+
+
+/*===========================================================================
+ * ICU collation framework version information                               
+ * Version info that can be obtained from a collator is affected by these    
+ * numbers in a secret and magic way. Please use collator version as whole
+ *===========================================================================
+ */
+
+/** Collation runtime version (sort key generator, strcoll). 
+ * If the version is different, sortkeys for the same string could be different 
+ * version 2 was in ICU 1.8.1. changed is: compression intervals, French secondary 
+ * compression, generating quad level always when strength is quad or more 
+ * version 4 - ICU 2.2 - tracking UCA changes, ignore completely ignorables 
+ * in contractions, ignore primary ignorables after shifted 
+ * version 5 - ICU 2.8 - changed implicit generation code
+ * version 6 - ICU 3.4 - with the UCA 4.1, Thai tag is no longer generated or used
+ * This value may change in the subsequent releases of ICU
+ * @stable ICU 2.4
+ */
+#define UCOL_RUNTIME_VERSION 6
+
+/** Builder code version. When this is different, same tailoring might result
+ * in assigning different collation elements to code points                  
+ * version 2 was in ICU 1.8.1. added support for prefixes, tweaked canonical 
+ * closure. However, the tailorings should probably get same CEs assigned    
+ * version 5 - ICU 2.2 - fixed some bugs, renamed some indirect values.      
+ * version 6 - ICU 2.8 - fixed bug in builder that allowed 0xFF in primary values
+ * version 7 - ICU 3.4 - with the UCA 4.1 Thai tag is no longer processed, complete ignorables
+ *                       now break contractions
+ * Backward compatible with the old rules. 
+ * This value may change in the subsequent releases of ICU
+ * @stable ICU 2.4
+ */
+#define UCOL_BUILDER_VERSION 7
+
+/** This is the version of the tailorings 
+ *  This value may change in the subsequent releases of ICU
+ *  @stable ICU 2.4
+ */
+#define UCOL_TAILORINGS_VERSION 1
+
+#endif


[71/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/uchar.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/uchar.h b/src/apps/couch_collate/platform/osx/icu/unicode/uchar.h
new file mode 100644
index 0000000..0f629c0
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/uchar.h
@@ -0,0 +1,3062 @@
+/*
+**********************************************************************
+*   Copyright (C) 1997-2008, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+**********************************************************************
+*
+* File UCHAR.H
+*
+* Modification History:
+*
+*   Date        Name        Description
+*   04/02/97    aliu        Creation.
+*   03/29/99    helena      Updated for C APIs.
+*   4/15/99     Madhu       Updated for C Implementation and Javadoc
+*   5/20/99     Madhu       Added the function u_getVersion()
+*   8/19/1999   srl         Upgraded scripts to Unicode 3.0
+*   8/27/1999   schererm    UCharDirection constants: U_...
+*   11/11/1999  weiv        added u_isalnum(), cleaned comments
+*   01/11/2000  helena      Renamed u_getVersion to u_getUnicodeVersion().
+******************************************************************************
+*/
+
+#ifndef UCHAR_H
+#define UCHAR_H
+
+#include "unicode/utypes.h"
+
+U_CDECL_BEGIN
+
+/*==========================================================================*/
+/* Unicode version number                                                   */
+/*==========================================================================*/
+/**
+ * Unicode version number, default for the current ICU version.
+ * The actual Unicode Character Database (UCD) data is stored in uprops.dat
+ * and may be generated from UCD files from a different Unicode version.
+ * Call u_getUnicodeVersion to get the actual Unicode version of the data.
+ *
+ * @see u_getUnicodeVersion
+ * @stable ICU 2.0
+ */
+#define U_UNICODE_VERSION "5.1"
+
+/**
+ * \file
+ * \brief C API: Unicode Properties
+ *
+ * This C API provides low-level access to the Unicode Character Database.
+ * In addition to raw property values, some convenience functions calculate
+ * derived properties, for example for Java-style programming.
+ *
+ * Unicode assigns each code point (not just assigned character) values for
+ * many properties.
+ * Most of them are simple boolean flags, or constants from a small enumerated list.
+ * For some properties, values are strings or other relatively more complex types.
+ *
+ * For more information see
+ * "About the Unicode Character Database" (http://www.unicode.org/ucd/)
+ * and the ICU User Guide chapter on Properties (http://icu-project.org/userguide/properties.html).
+ *
+ * Many functions are designed to match java.lang.Character functions.
+ * See the individual function documentation,
+ * and see the JDK 1.4 java.lang.Character documentation
+ * at http://java.sun.com/j2se/1.4/docs/api/java/lang/Character.html
+ *
+ * There are also functions that provide easy migration from C/POSIX functions
+ * like isblank(). Their use is generally discouraged because the C/POSIX
+ * standards do not define their semantics beyond the ASCII range, which means
+ * that different implementations exhibit very different behavior.
+ * Instead, Unicode properties should be used directly.
+ *
+ * There are also only a few, broad C/POSIX character classes, and they tend
+ * to be used for conflicting purposes. For example, the "isalpha()" class
+ * is sometimes used to determine word boundaries, while a more sophisticated
+ * approach would at least distinguish initial letters from continuation
+ * characters (the latter including combining marks).
+ * (In ICU, BreakIterator is the most sophisticated API for word boundaries.)
+ * Another example: There is no "istitle()" class for titlecase characters.
+ *
+ * ICU 3.4 and later provides API access for all twelve C/POSIX character classes.
+ * ICU implements them according to the Standard Recommendations in
+ * Annex C: Compatibility Properties of UTS #18 Unicode Regular Expressions
+ * (http://www.unicode.org/reports/tr18/#Compatibility_Properties).
+ *
+ * API access for C/POSIX character classes is as follows:
+ * - alpha:     u_isUAlphabetic(c) or u_hasBinaryProperty(c, UCHAR_ALPHABETIC)
+ * - lower:     u_isULowercase(c) or u_hasBinaryProperty(c, UCHAR_LOWERCASE)
+ * - upper:     u_isUUppercase(c) or u_hasBinaryProperty(c, UCHAR_UPPERCASE)
+ * - punct:     u_ispunct(c)
+ * - digit:     u_isdigit(c) or u_charType(c)==U_DECIMAL_DIGIT_NUMBER
+ * - xdigit:    u_isxdigit(c) or u_hasBinaryProperty(c, UCHAR_POSIX_XDIGIT)
+ * - alnum:     u_hasBinaryProperty(c, UCHAR_POSIX_ALNUM)
+ * - space:     u_isUWhiteSpace(c) or u_hasBinaryProperty(c, UCHAR_WHITE_SPACE)
+ * - blank:     u_isblank(c) or u_hasBinaryProperty(c, UCHAR_POSIX_BLANK)
+ * - cntrl:     u_charType(c)==U_CONTROL_CHAR
+ * - graph:     u_hasBinaryProperty(c, UCHAR_POSIX_GRAPH)
+ * - print:     u_hasBinaryProperty(c, UCHAR_POSIX_PRINT)
+ *
+ * Note: Some of the u_isxyz() functions in uchar.h predate, and do not match,
+ * the Standard Recommendations in UTS #18. Instead, they match Java
+ * functions according to their API documentation.
+ *
+ * \htmlonly
+ * The C/POSIX character classes are also available in UnicodeSet patterns,
+ * using patterns like [:graph:] or \p{graph}.
+ * \endhtmlonly
+ *
+ * Note: There are several ICU whitespace functions.
+ * Comparison:
+ * - u_isUWhiteSpace=UCHAR_WHITE_SPACE: Unicode White_Space property;
+ *       most of general categories "Z" (separators) + most whitespace ISO controls
+ *       (including no-break spaces, but excluding IS1..IS4 and ZWSP)
+ * - u_isWhitespace: Java isWhitespace; Z + whitespace ISO controls but excluding no-break spaces
+ * - u_isJavaSpaceChar: Java isSpaceChar; just Z (including no-break spaces)
+ * - u_isspace: Z + whitespace ISO controls (including no-break spaces)
+ * - u_isblank: "horizontal spaces" = TAB + Zs - ZWSP
+ */
+
+/**
+ * Constants.
+ */
+
+/** The lowest Unicode code point value. Code points are non-negative. @stable ICU 2.0 */
+#define UCHAR_MIN_VALUE 0
+
+/**
+ * The highest Unicode code point value (scalar value) according to
+ * The Unicode Standard. This is a 21-bit value (20.1 bits, rounded up).
+ * For a single character, UChar32 is a simple type that can hold any code point value.
+ *
+ * @see UChar32
+ * @stable ICU 2.0
+ */
+#define UCHAR_MAX_VALUE 0x10ffff
+
+/**
+ * Get a single-bit bit set (a flag) from a bit number 0..31.
+ * @stable ICU 2.1
+ */
+#define U_MASK(x) ((uint32_t)1<<(x))
+
+/*
+ * !! Note: Several comments in this file are machine-read by the
+ * genpname tool.  These comments describe the correspondence between
+ * icu enum constants and UCD entities.  Do not delete them.  Update
+ * these comments as needed.
+ *
+ * Any comment of the form "/ *[name]* /" (spaces added) is such
+ * a comment.
+ *
+ * The U_JG_* and U_GC_*_MASK constants are matched by their symbolic
+ * name, which must match PropertyValueAliases.txt.
+ */
+
+/**
+ * Selection constants for Unicode properties.
+ * These constants are used in functions like u_hasBinaryProperty to select
+ * one of the Unicode properties.
+ *
+ * The properties APIs are intended to reflect Unicode properties as defined
+ * in the Unicode Character Database (UCD) and Unicode Technical Reports (UTR).
+ * For details about the properties see http://www.unicode.org/ucd/ .
+ * For names of Unicode properties see the UCD file PropertyAliases.txt.
+ *
+ * Important: If ICU is built with UCD files from Unicode versions below, e.g., 3.2,
+ * then properties marked with "new in Unicode 3.2" are not or not fully available.
+ * Check u_getUnicodeVersion to be sure.
+ *
+ * @see u_hasBinaryProperty
+ * @see u_getIntPropertyValue
+ * @see u_getUnicodeVersion
+ * @stable ICU 2.1
+ */
+typedef enum UProperty {
+    /*  See note !!.  Comments of the form "Binary property Dash",
+        "Enumerated property Script", "Double property Numeric_Value",
+        and "String property Age" are read by genpname. */
+
+    /*  Note: Place UCHAR_ALPHABETIC before UCHAR_BINARY_START so that
+    debuggers display UCHAR_ALPHABETIC as the symbolic name for 0,
+    rather than UCHAR_BINARY_START.  Likewise for other *_START
+    identifiers. */
+
+    /** Binary property Alphabetic. Same as u_isUAlphabetic, different from u_isalpha.
+        Lu+Ll+Lt+Lm+Lo+Nl+Other_Alphabetic @stable ICU 2.1 */
+    UCHAR_ALPHABETIC=0,
+    /** First constant for binary Unicode properties. @stable ICU 2.1 */
+    UCHAR_BINARY_START=UCHAR_ALPHABETIC,
+    /** Binary property ASCII_Hex_Digit. 0-9 A-F a-f @stable ICU 2.1 */
+    UCHAR_ASCII_HEX_DIGIT=1,
+    /** Binary property Bidi_Control.
+        Format controls which have specific functions
+        in the Bidi Algorithm. @stable ICU 2.1 */
+    UCHAR_BIDI_CONTROL=2,
+    /** Binary property Bidi_Mirrored.
+        Characters that may change display in RTL text.
+        Same as u_isMirrored.
+        See Bidi Algorithm, UTR 9. @stable ICU 2.1 */
+    UCHAR_BIDI_MIRRORED=3,
+    /** Binary property Dash. Variations of dashes. @stable ICU 2.1 */
+    UCHAR_DASH=4,
+    /** Binary property Default_Ignorable_Code_Point (new in Unicode 3.2).
+        Ignorable in most processing.
+        <2060..206F, FFF0..FFFB, E0000..E0FFF>+Other_Default_Ignorable_Code_Point+(Cf+Cc+Cs-White_Space) @stable ICU 2.1 */
+    UCHAR_DEFAULT_IGNORABLE_CODE_POINT=5,
+    /** Binary property Deprecated (new in Unicode 3.2).
+        The usage of deprecated characters is strongly discouraged. @stable ICU 2.1 */
+    UCHAR_DEPRECATED=6,
+    /** Binary property Diacritic. Characters that linguistically modify
+        the meaning of another character to which they apply. @stable ICU 2.1 */
+    UCHAR_DIACRITIC=7,
+    /** Binary property Extender.
+        Extend the value or shape of a preceding alphabetic character,
+        e.g., length and iteration marks. @stable ICU 2.1 */
+    UCHAR_EXTENDER=8,
+    /** Binary property Full_Composition_Exclusion.
+        CompositionExclusions.txt+Singleton Decompositions+
+        Non-Starter Decompositions. @stable ICU 2.1 */
+    UCHAR_FULL_COMPOSITION_EXCLUSION=9,
+    /** Binary property Grapheme_Base (new in Unicode 3.2).
+        For programmatic determination of grapheme cluster boundaries.
+        [0..10FFFF]-Cc-Cf-Cs-Co-Cn-Zl-Zp-Grapheme_Link-Grapheme_Extend-CGJ @stable ICU 2.1 */
+    UCHAR_GRAPHEME_BASE=10,
+    /** Binary property Grapheme_Extend (new in Unicode 3.2).
+        For programmatic determination of grapheme cluster boundaries.
+        Me+Mn+Mc+Other_Grapheme_Extend-Grapheme_Link-CGJ @stable ICU 2.1 */
+    UCHAR_GRAPHEME_EXTEND=11,
+    /** Binary property Grapheme_Link (new in Unicode 3.2).
+        For programmatic determination of grapheme cluster boundaries. @stable ICU 2.1 */
+    UCHAR_GRAPHEME_LINK=12,
+    /** Binary property Hex_Digit.
+        Characters commonly used for hexadecimal numbers. @stable ICU 2.1 */
+    UCHAR_HEX_DIGIT=13,
+    /** Binary property Hyphen. Dashes used to mark connections
+        between pieces of words, plus the Katakana middle dot. @stable ICU 2.1 */
+    UCHAR_HYPHEN=14,
+    /** Binary property ID_Continue.
+        Characters that can continue an identifier.
+        DerivedCoreProperties.txt also says "NOTE: Cf characters should be filtered out."
+        ID_Start+Mn+Mc+Nd+Pc @stable ICU 2.1 */
+    UCHAR_ID_CONTINUE=15,
+    /** Binary property ID_Start.
+        Characters that can start an identifier.
+        Lu+Ll+Lt+Lm+Lo+Nl @stable ICU 2.1 */
+    UCHAR_ID_START=16,
+    /** Binary property Ideographic.
+        CJKV ideographs. @stable ICU 2.1 */
+    UCHAR_IDEOGRAPHIC=17,
+    /** Binary property IDS_Binary_Operator (new in Unicode 3.2).
+        For programmatic determination of
+        Ideographic Description Sequences. @stable ICU 2.1 */
+    UCHAR_IDS_BINARY_OPERATOR=18,
+    /** Binary property IDS_Trinary_Operator (new in Unicode 3.2).
+        For programmatic determination of
+        Ideographic Description Sequences. @stable ICU 2.1 */
+    UCHAR_IDS_TRINARY_OPERATOR=19,
+    /** Binary property Join_Control.
+        Format controls for cursive joining and ligation. @stable ICU 2.1 */
+    UCHAR_JOIN_CONTROL=20,
+    /** Binary property Logical_Order_Exception (new in Unicode 3.2).
+        Characters that do not use logical order and
+        require special handling in most processing. @stable ICU 2.1 */
+    UCHAR_LOGICAL_ORDER_EXCEPTION=21,
+    /** Binary property Lowercase. Same as u_isULowercase, different from u_islower.
+        Ll+Other_Lowercase @stable ICU 2.1 */
+    UCHAR_LOWERCASE=22,
+    /** Binary property Math. Sm+Other_Math @stable ICU 2.1 */
+    UCHAR_MATH=23,
+    /** Binary property Noncharacter_Code_Point.
+        Code points that are explicitly defined as illegal
+        for the encoding of characters. @stable ICU 2.1 */
+    UCHAR_NONCHARACTER_CODE_POINT=24,
+    /** Binary property Quotation_Mark. @stable ICU 2.1 */
+    UCHAR_QUOTATION_MARK=25,
+    /** Binary property Radical (new in Unicode 3.2).
+        For programmatic determination of
+        Ideographic Description Sequences. @stable ICU 2.1 */
+    UCHAR_RADICAL=26,
+    /** Binary property Soft_Dotted (new in Unicode 3.2).
+        Characters with a "soft dot", like i or j.
+        An accent placed on these characters causes
+        the dot to disappear. @stable ICU 2.1 */
+    UCHAR_SOFT_DOTTED=27,
+    /** Binary property Terminal_Punctuation.
+        Punctuation characters that generally mark
+        the end of textual units. @stable ICU 2.1 */
+    UCHAR_TERMINAL_PUNCTUATION=28,
+    /** Binary property Unified_Ideograph (new in Unicode 3.2).
+        For programmatic determination of
+        Ideographic Description Sequences. @stable ICU 2.1 */
+    UCHAR_UNIFIED_IDEOGRAPH=29,
+    /** Binary property Uppercase. Same as u_isUUppercase, different from u_isupper.
+        Lu+Other_Uppercase @stable ICU 2.1 */
+    UCHAR_UPPERCASE=30,
+    /** Binary property White_Space.
+        Same as u_isUWhiteSpace, different from u_isspace and u_isWhitespace.
+        Space characters+TAB+CR+LF-ZWSP-ZWNBSP @stable ICU 2.1 */
+    UCHAR_WHITE_SPACE=31,
+    /** Binary property XID_Continue.
+        ID_Continue modified to allow closure under
+        normalization forms NFKC and NFKD. @stable ICU 2.1 */
+    UCHAR_XID_CONTINUE=32,
+    /** Binary property XID_Start. ID_Start modified to allow
+        closure under normalization forms NFKC and NFKD. @stable ICU 2.1 */
+    UCHAR_XID_START=33,
+    /** Binary property Case_Sensitive. Either the source of a case
+        mapping or _in_ the target of a case mapping. Not the same as
+        the general category Cased_Letter. @stable ICU 2.6 */
+   UCHAR_CASE_SENSITIVE=34,
+    /** Binary property STerm (new in Unicode 4.0.1).
+        Sentence Terminal. Used in UAX #29: Text Boundaries
+        (http://www.unicode.org/reports/tr29/)
+        @stable ICU 3.0 */
+    UCHAR_S_TERM=35,
+    /** Binary property Variation_Selector (new in Unicode 4.0.1).
+        Indicates all those characters that qualify as Variation Selectors.
+        For details on the behavior of these characters,
+        see StandardizedVariants.html and 15.6 Variation Selectors.
+        @stable ICU 3.0 */
+    UCHAR_VARIATION_SELECTOR=36,
+    /** Binary property NFD_Inert.
+        ICU-specific property for characters that are inert under NFD,
+        i.e., they do not interact with adjacent characters.
+        Used for example in normalizing transforms in incremental mode
+        to find the boundary of safely normalizable text despite possible
+        text additions.
+
+        There is one such property per normalization form.
+        These properties are computed as follows - an inert character is:
+        a) unassigned, or ALL of the following:
+        b) of combining class 0.
+        c) not decomposed by this normalization form.
+        AND if NFC or NFKC,
+        d) can never compose with a previous character.
+        e) can never compose with a following character.
+        f) can never change if another character is added.
+           Example: a-breve might satisfy all but f, but if you
+           add an ogonek it changes to a-ogonek + breve
+
+        See also com.ibm.text.UCD.NFSkippable in the ICU4J repository,
+        and icu/source/common/unormimp.h .
+        @stable ICU 3.0 */
+    UCHAR_NFD_INERT=37,
+    /** Binary property NFKD_Inert.
+        ICU-specific property for characters that are inert under NFKD,
+        i.e., they do not interact with adjacent characters.
+        Used for example in normalizing transforms in incremental mode
+        to find the boundary of safely normalizable text despite possible
+        text additions.
+        @see UCHAR_NFD_INERT
+        @stable ICU 3.0 */
+    UCHAR_NFKD_INERT=38,
+    /** Binary property NFC_Inert.
+        ICU-specific property for characters that are inert under NFC,
+        i.e., they do not interact with adjacent characters.
+        Used for example in normalizing transforms in incremental mode
+        to find the boundary of safely normalizable text despite possible
+        text additions.
+        @see UCHAR_NFD_INERT
+        @stable ICU 3.0 */
+    UCHAR_NFC_INERT=39,
+    /** Binary property NFKC_Inert.
+        ICU-specific property for characters that are inert under NFKC,
+        i.e., they do not interact with adjacent characters.
+        Used for example in normalizing transforms in incremental mode
+        to find the boundary of safely normalizable text despite possible
+        text additions.
+        @see UCHAR_NFD_INERT
+        @stable ICU 3.0 */
+    UCHAR_NFKC_INERT=40,
+    /** Binary Property Segment_Starter.
+        ICU-specific property for characters that are starters in terms of
+        Unicode normalization and combining character sequences.
+        They have ccc=0 and do not occur in non-initial position of the
+        canonical decomposition of any character
+        (like " in NFD(a-umlaut) and a Jamo T in an NFD(Hangul LVT)).
+        ICU uses this property for segmenting a string for generating a set of
+        canonically equivalent strings, e.g. for canonical closure while
+        processing collation tailoring rules.
+        @stable ICU 3.0 */
+    UCHAR_SEGMENT_STARTER=41,
+    /** Binary property Pattern_Syntax (new in Unicode 4.1).
+        See UAX #31 Identifier and Pattern Syntax
+        (http://www.unicode.org/reports/tr31/)
+        @stable ICU 3.4 */
+    UCHAR_PATTERN_SYNTAX=42,
+    /** Binary property Pattern_White_Space (new in Unicode 4.1).
+        See UAX #31 Identifier and Pattern Syntax
+        (http://www.unicode.org/reports/tr31/)
+        @stable ICU 3.4 */
+    UCHAR_PATTERN_WHITE_SPACE=43,
+    /** Binary property alnum (a C/POSIX character class).
+        Implemented according to the UTS #18 Annex C Standard Recommendation.
+        See the uchar.h file documentation.
+        @stable ICU 3.4 */
+    UCHAR_POSIX_ALNUM=44,
+    /** Binary property blank (a C/POSIX character class).
+        Implemented according to the UTS #18 Annex C Standard Recommendation.
+        See the uchar.h file documentation.
+        @stable ICU 3.4 */
+    UCHAR_POSIX_BLANK=45,
+    /** Binary property graph (a C/POSIX character class).
+        Implemented according to the UTS #18 Annex C Standard Recommendation.
+        See the uchar.h file documentation.
+        @stable ICU 3.4 */
+    UCHAR_POSIX_GRAPH=46,
+    /** Binary property print (a C/POSIX character class).
+        Implemented according to the UTS #18 Annex C Standard Recommendation.
+        See the uchar.h file documentation.
+        @stable ICU 3.4 */
+    UCHAR_POSIX_PRINT=47,
+    /** Binary property xdigit (a C/POSIX character class).
+        Implemented according to the UTS #18 Annex C Standard Recommendation.
+        See the uchar.h file documentation.
+        @stable ICU 3.4 */
+    UCHAR_POSIX_XDIGIT=48,
+    /** One more than the last constant for binary Unicode properties. @stable ICU 2.1 */
+    UCHAR_BINARY_LIMIT=49,
+
+    /** Enumerated property Bidi_Class.
+        Same as u_charDirection, returns UCharDirection values. @stable ICU 2.2 */
+    UCHAR_BIDI_CLASS=0x1000,
+    /** First constant for enumerated/integer Unicode properties. @stable ICU 2.2 */
+    UCHAR_INT_START=UCHAR_BIDI_CLASS,
+    /** Enumerated property Block.
+        Same as ublock_getCode, returns UBlockCode values. @stable ICU 2.2 */
+    UCHAR_BLOCK=0x1001,
+    /** Enumerated property Canonical_Combining_Class.
+        Same as u_getCombiningClass, returns 8-bit numeric values. @stable ICU 2.2 */
+    UCHAR_CANONICAL_COMBINING_CLASS=0x1002,
+    /** Enumerated property Decomposition_Type.
+        Returns UDecompositionType values. @stable ICU 2.2 */
+    UCHAR_DECOMPOSITION_TYPE=0x1003,
+    /** Enumerated property East_Asian_Width.
+        See http://www.unicode.org/reports/tr11/
+        Returns UEastAsianWidth values. @stable ICU 2.2 */
+    UCHAR_EAST_ASIAN_WIDTH=0x1004,
+    /** Enumerated property General_Category.
+        Same as u_charType, returns UCharCategory values. @stable ICU 2.2 */
+    UCHAR_GENERAL_CATEGORY=0x1005,
+    /** Enumerated property Joining_Group.
+        Returns UJoiningGroup values. @stable ICU 2.2 */
+    UCHAR_JOINING_GROUP=0x1006,
+    /** Enumerated property Joining_Type.
+        Returns UJoiningType values. @stable ICU 2.2 */
+    UCHAR_JOINING_TYPE=0x1007,
+    /** Enumerated property Line_Break.
+        Returns ULineBreak values. @stable ICU 2.2 */
+    UCHAR_LINE_BREAK=0x1008,
+    /** Enumerated property Numeric_Type.
+        Returns UNumericType values. @stable ICU 2.2 */
+    UCHAR_NUMERIC_TYPE=0x1009,
+    /** Enumerated property Script.
+        Same as uscript_getScript, returns UScriptCode values. @stable ICU 2.2 */
+    UCHAR_SCRIPT=0x100A,
+    /** Enumerated property Hangul_Syllable_Type, new in Unicode 4.
+        Returns UHangulSyllableType values. @stable ICU 2.6 */
+    UCHAR_HANGUL_SYLLABLE_TYPE=0x100B,
+    /** Enumerated property NFD_Quick_Check.
+        Returns UNormalizationCheckResult values. @stable ICU 3.0 */
+    UCHAR_NFD_QUICK_CHECK=0x100C,
+    /** Enumerated property NFKD_Quick_Check.
+        Returns UNormalizationCheckResult values. @stable ICU 3.0 */
+    UCHAR_NFKD_QUICK_CHECK=0x100D,
+    /** Enumerated property NFC_Quick_Check.
+        Returns UNormalizationCheckResult values. @stable ICU 3.0 */
+    UCHAR_NFC_QUICK_CHECK=0x100E,
+    /** Enumerated property NFKC_Quick_Check.
+        Returns UNormalizationCheckResult values. @stable ICU 3.0 */
+    UCHAR_NFKC_QUICK_CHECK=0x100F,
+    /** Enumerated property Lead_Canonical_Combining_Class.
+        ICU-specific property for the ccc of the first code point
+        of the decomposition, or lccc(c)=ccc(NFD(c)[0]).
+        Useful for checking for canonically ordered text;
+        see UNORM_FCD and http://www.unicode.org/notes/tn5/#FCD .
+        Returns 8-bit numeric values like UCHAR_CANONICAL_COMBINING_CLASS. @stable ICU 3.0 */
+    UCHAR_LEAD_CANONICAL_COMBINING_CLASS=0x1010,
+    /** Enumerated property Trail_Canonical_Combining_Class.
+        ICU-specific property for the ccc of the last code point
+        of the decomposition, or tccc(c)=ccc(NFD(c)[last]).
+        Useful for checking for canonically ordered text;
+        see UNORM_FCD and http://www.unicode.org/notes/tn5/#FCD .
+        Returns 8-bit numeric values like UCHAR_CANONICAL_COMBINING_CLASS. @stable ICU 3.0 */
+    UCHAR_TRAIL_CANONICAL_COMBINING_CLASS=0x1011,
+    /** Enumerated property Grapheme_Cluster_Break (new in Unicode 4.1).
+        Used in UAX #29: Text Boundaries
+        (http://www.unicode.org/reports/tr29/)
+        Returns UGraphemeClusterBreak values. @stable ICU 3.4 */
+    UCHAR_GRAPHEME_CLUSTER_BREAK=0x1012,
+    /** Enumerated property Sentence_Break (new in Unicode 4.1).
+        Used in UAX #29: Text Boundaries
+        (http://www.unicode.org/reports/tr29/)
+        Returns USentenceBreak values. @stable ICU 3.4 */
+    UCHAR_SENTENCE_BREAK=0x1013,
+    /** Enumerated property Word_Break (new in Unicode 4.1).
+        Used in UAX #29: Text Boundaries
+        (http://www.unicode.org/reports/tr29/)
+        Returns UWordBreakValues values. @stable ICU 3.4 */
+    UCHAR_WORD_BREAK=0x1014,
+    /** One more than the last constant for enumerated/integer Unicode properties. @stable ICU 2.2 */
+    UCHAR_INT_LIMIT=0x1015,
+
+    /** Bitmask property General_Category_Mask.
+        This is the General_Category property returned as a bit mask.
+        When used in u_getIntPropertyValue(c), same as U_MASK(u_charType(c)),
+        returns bit masks for UCharCategory values where exactly one bit is set.
+        When used with u_getPropertyValueName() and u_getPropertyValueEnum(),
+        a multi-bit mask is used for sets of categories like "Letters".
+        Mask values should be cast to uint32_t.
+        @stable ICU 2.4 */
+    UCHAR_GENERAL_CATEGORY_MASK=0x2000,
+    /** First constant for bit-mask Unicode properties. @stable ICU 2.4 */
+    UCHAR_MASK_START=UCHAR_GENERAL_CATEGORY_MASK,
+    /** One more than the last constant for bit-mask Unicode properties. @stable ICU 2.4 */
+    UCHAR_MASK_LIMIT=0x2001,
+
+    /** Double property Numeric_Value.
+        Corresponds to u_getNumericValue. @stable ICU 2.4 */
+    UCHAR_NUMERIC_VALUE=0x3000,
+    /** First constant for double Unicode properties. @stable ICU 2.4 */
+    UCHAR_DOUBLE_START=UCHAR_NUMERIC_VALUE,
+    /** One more than the last constant for double Unicode properties. @stable ICU 2.4 */
+    UCHAR_DOUBLE_LIMIT=0x3001,
+
+    /** String property Age.
+        Corresponds to u_charAge. @stable ICU 2.4 */
+    UCHAR_AGE=0x4000,
+    /** First constant for string Unicode properties. @stable ICU 2.4 */
+    UCHAR_STRING_START=UCHAR_AGE,
+    /** String property Bidi_Mirroring_Glyph.
+        Corresponds to u_charMirror. @stable ICU 2.4 */
+    UCHAR_BIDI_MIRRORING_GLYPH=0x4001,
+    /** String property Case_Folding.
+        Corresponds to u_strFoldCase in ustring.h. @stable ICU 2.4 */
+    UCHAR_CASE_FOLDING=0x4002,
+    /** String property ISO_Comment.
+        Corresponds to u_getISOComment. @stable ICU 2.4 */
+    UCHAR_ISO_COMMENT=0x4003,
+    /** String property Lowercase_Mapping.
+        Corresponds to u_strToLower in ustring.h. @stable ICU 2.4 */
+    UCHAR_LOWERCASE_MAPPING=0x4004,
+    /** String property Name.
+        Corresponds to u_charName. @stable ICU 2.4 */
+    UCHAR_NAME=0x4005,
+    /** String property Simple_Case_Folding.
+        Corresponds to u_foldCase. @stable ICU 2.4 */
+    UCHAR_SIMPLE_CASE_FOLDING=0x4006,
+    /** String property Simple_Lowercase_Mapping.
+        Corresponds to u_tolower. @stable ICU 2.4 */
+    UCHAR_SIMPLE_LOWERCASE_MAPPING=0x4007,
+    /** String property Simple_Titlecase_Mapping.
+        Corresponds to u_totitle. @stable ICU 2.4 */
+    UCHAR_SIMPLE_TITLECASE_MAPPING=0x4008,
+    /** String property Simple_Uppercase_Mapping.
+        Corresponds to u_toupper. @stable ICU 2.4 */
+    UCHAR_SIMPLE_UPPERCASE_MAPPING=0x4009,
+    /** String property Titlecase_Mapping.
+        Corresponds to u_strToTitle in ustring.h. @stable ICU 2.4 */
+    UCHAR_TITLECASE_MAPPING=0x400A,
+    /** String property Unicode_1_Name.
+        Corresponds to u_charName. @stable ICU 2.4 */
+    UCHAR_UNICODE_1_NAME=0x400B,
+    /** String property Uppercase_Mapping.
+        Corresponds to u_strToUpper in ustring.h. @stable ICU 2.4 */
+    UCHAR_UPPERCASE_MAPPING=0x400C,
+    /** One more than the last constant for string Unicode properties. @stable ICU 2.4 */
+    UCHAR_STRING_LIMIT=0x400D,
+
+    /** Represents a nonexistent or invalid property or property value. @stable ICU 2.4 */
+    UCHAR_INVALID_CODE = -1
+} UProperty;
+
+/**
+ * Data for enumerated Unicode general category types.
+ * See http://www.unicode.org/Public/UNIDATA/UnicodeData.html .
+ * @stable ICU 2.0
+ */
+typedef enum UCharCategory
+{
+    /** See note !!.  Comments of the form "Cn" are read by genpname. */
+
+    /** Non-category for unassigned and non-character code points. @stable ICU 2.0 */
+    U_UNASSIGNED              = 0,
+    /** Cn "Other, Not Assigned (no characters in [UnicodeData.txt] have this property)" (same as U_UNASSIGNED!) @stable ICU 2.0 */
+    U_GENERAL_OTHER_TYPES     = 0,
+    /** Lu @stable ICU 2.0 */
+    U_UPPERCASE_LETTER        = 1,
+    /** Ll @stable ICU 2.0 */
+    U_LOWERCASE_LETTER        = 2,
+    /** Lt @stable ICU 2.0 */
+    U_TITLECASE_LETTER        = 3,
+    /** Lm @stable ICU 2.0 */
+    U_MODIFIER_LETTER         = 4,
+    /** Lo @stable ICU 2.0 */
+    U_OTHER_LETTER            = 5,
+    /** Mn @stable ICU 2.0 */
+    U_NON_SPACING_MARK        = 6,
+    /** Me @stable ICU 2.0 */
+    U_ENCLOSING_MARK          = 7,
+    /** Mc @stable ICU 2.0 */
+    U_COMBINING_SPACING_MARK  = 8,
+    /** Nd @stable ICU 2.0 */
+    U_DECIMAL_DIGIT_NUMBER    = 9,
+    /** Nl @stable ICU 2.0 */
+    U_LETTER_NUMBER           = 10,
+    /** No @stable ICU 2.0 */
+    U_OTHER_NUMBER            = 11,
+    /** Zs @stable ICU 2.0 */
+    U_SPACE_SEPARATOR         = 12,
+    /** Zl @stable ICU 2.0 */
+    U_LINE_SEPARATOR          = 13,
+    /** Zp @stable ICU 2.0 */
+    U_PARAGRAPH_SEPARATOR     = 14,
+    /** Cc @stable ICU 2.0 */
+    U_CONTROL_CHAR            = 15,
+    /** Cf @stable ICU 2.0 */
+    U_FORMAT_CHAR             = 16,
+    /** Co @stable ICU 2.0 */
+    U_PRIVATE_USE_CHAR        = 17,
+    /** Cs @stable ICU 2.0 */
+    U_SURROGATE               = 18,
+    /** Pd @stable ICU 2.0 */
+    U_DASH_PUNCTUATION        = 19,
+    /** Ps @stable ICU 2.0 */
+    U_START_PUNCTUATION       = 20,
+    /** Pe @stable ICU 2.0 */
+    U_END_PUNCTUATION         = 21,
+    /** Pc @stable ICU 2.0 */
+    U_CONNECTOR_PUNCTUATION   = 22,
+    /** Po @stable ICU 2.0 */
+    U_OTHER_PUNCTUATION       = 23,
+    /** Sm @stable ICU 2.0 */
+    U_MATH_SYMBOL             = 24,
+    /** Sc @stable ICU 2.0 */
+    U_CURRENCY_SYMBOL         = 25,
+    /** Sk @stable ICU 2.0 */
+    U_MODIFIER_SYMBOL         = 26,
+    /** So @stable ICU 2.0 */
+    U_OTHER_SYMBOL            = 27,
+    /** Pi @stable ICU 2.0 */
+    U_INITIAL_PUNCTUATION     = 28,
+    /** Pf @stable ICU 2.0 */
+    U_FINAL_PUNCTUATION       = 29,
+    /** One higher than the last enum UCharCategory constant. @stable ICU 2.0 */
+    U_CHAR_CATEGORY_COUNT
+} UCharCategory;
+
+/**
+ * U_GC_XX_MASK constants are bit flags corresponding to Unicode
+ * general category values.
+ * For each category, the nth bit is set if the numeric value of the
+ * corresponding UCharCategory constant is n.
+ *
+ * There are also some U_GC_Y_MASK constants for groups of general categories
+ * like L for all letter categories.
+ *
+ * @see u_charType
+ * @see U_GET_GC_MASK
+ * @see UCharCategory
+ * @stable ICU 2.1
+ */
+#define U_GC_CN_MASK    U_MASK(U_GENERAL_OTHER_TYPES)
+
+/** Mask constant for a UCharCategory. @stable ICU 2.1 */
+#define U_GC_LU_MASK    U_MASK(U_UPPERCASE_LETTER)
+/** Mask constant for a UCharCategory. @stable ICU 2.1 */
+#define U_GC_LL_MASK    U_MASK(U_LOWERCASE_LETTER)
+/** Mask constant for a UCharCategory. @stable ICU 2.1 */
+#define U_GC_LT_MASK    U_MASK(U_TITLECASE_LETTER)
+/** Mask constant for a UCharCategory. @stable ICU 2.1 */
+#define U_GC_LM_MASK    U_MASK(U_MODIFIER_LETTER)
+/** Mask constant for a UCharCategory. @stable ICU 2.1 */
+#define U_GC_LO_MASK    U_MASK(U_OTHER_LETTER)
+
+/** Mask constant for a UCharCategory. @stable ICU 2.1 */
+#define U_GC_MN_MASK    U_MASK(U_NON_SPACING_MARK)
+/** Mask constant for a UCharCategory. @stable ICU 2.1 */
+#define U_GC_ME_MASK    U_MASK(U_ENCLOSING_MARK)
+/** Mask constant for a UCharCategory. @stable ICU 2.1 */
+#define U_GC_MC_MASK    U_MASK(U_COMBINING_SPACING_MARK)
+
+/** Mask constant for a UCharCategory. @stable ICU 2.1 */
+#define U_GC_ND_MASK    U_MASK(U_DECIMAL_DIGIT_NUMBER)
+/** Mask constant for a UCharCategory. @stable ICU 2.1 */
+#define U_GC_NL_MASK    U_MASK(U_LETTER_NUMBER)
+/** Mask constant for a UCharCategory. @stable ICU 2.1 */
+#define U_GC_NO_MASK    U_MASK(U_OTHER_NUMBER)
+
+/** Mask constant for a UCharCategory. @stable ICU 2.1 */
+#define U_GC_ZS_MASK    U_MASK(U_SPACE_SEPARATOR)
+/** Mask constant for a UCharCategory. @stable ICU 2.1 */
+#define U_GC_ZL_MASK    U_MASK(U_LINE_SEPARATOR)
+/** Mask constant for a UCharCategory. @stable ICU 2.1 */
+#define U_GC_ZP_MASK    U_MASK(U_PARAGRAPH_SEPARATOR)
+
+/** Mask constant for a UCharCategory. @stable ICU 2.1 */
+#define U_GC_CC_MASK    U_MASK(U_CONTROL_CHAR)
+/** Mask constant for a UCharCategory. @stable ICU 2.1 */
+#define U_GC_CF_MASK    U_MASK(U_FORMAT_CHAR)
+/** Mask constant for a UCharCategory. @stable ICU 2.1 */
+#define U_GC_CO_MASK    U_MASK(U_PRIVATE_USE_CHAR)
+/** Mask constant for a UCharCategory. @stable ICU 2.1 */
+#define U_GC_CS_MASK    U_MASK(U_SURROGATE)
+
+/** Mask constant for a UCharCategory. @stable ICU 2.1 */
+#define U_GC_PD_MASK    U_MASK(U_DASH_PUNCTUATION)
+/** Mask constant for a UCharCategory. @stable ICU 2.1 */
+#define U_GC_PS_MASK    U_MASK(U_START_PUNCTUATION)
+/** Mask constant for a UCharCategory. @stable ICU 2.1 */
+#define U_GC_PE_MASK    U_MASK(U_END_PUNCTUATION)
+/** Mask constant for a UCharCategory. @stable ICU 2.1 */
+#define U_GC_PC_MASK    U_MASK(U_CONNECTOR_PUNCTUATION)
+/** Mask constant for a UCharCategory. @stable ICU 2.1 */
+#define U_GC_PO_MASK    U_MASK(U_OTHER_PUNCTUATION)
+
+/** Mask constant for a UCharCategory. @stable ICU 2.1 */
+#define U_GC_SM_MASK    U_MASK(U_MATH_SYMBOL)
+/** Mask constant for a UCharCategory. @stable ICU 2.1 */
+#define U_GC_SC_MASK    U_MASK(U_CURRENCY_SYMBOL)
+/** Mask constant for a UCharCategory. @stable ICU 2.1 */
+#define U_GC_SK_MASK    U_MASK(U_MODIFIER_SYMBOL)
+/** Mask constant for a UCharCategory. @stable ICU 2.1 */
+#define U_GC_SO_MASK    U_MASK(U_OTHER_SYMBOL)
+
+/** Mask constant for a UCharCategory. @stable ICU 2.1 */
+#define U_GC_PI_MASK    U_MASK(U_INITIAL_PUNCTUATION)
+/** Mask constant for a UCharCategory. @stable ICU 2.1 */
+#define U_GC_PF_MASK    U_MASK(U_FINAL_PUNCTUATION)
+
+
+/** Mask constant for multiple UCharCategory bits (L Letters). @stable ICU 2.1 */
+#define U_GC_L_MASK \
+            (U_GC_LU_MASK|U_GC_LL_MASK|U_GC_LT_MASK|U_GC_LM_MASK|U_GC_LO_MASK)
+
+/** Mask constant for multiple UCharCategory bits (LC Cased Letters). @stable ICU 2.1 */
+#define U_GC_LC_MASK \
+            (U_GC_LU_MASK|U_GC_LL_MASK|U_GC_LT_MASK)
+
+/** Mask constant for multiple UCharCategory bits (M Marks). @stable ICU 2.1 */
+#define U_GC_M_MASK (U_GC_MN_MASK|U_GC_ME_MASK|U_GC_MC_MASK)
+
+/** Mask constant for multiple UCharCategory bits (N Numbers). @stable ICU 2.1 */
+#define U_GC_N_MASK (U_GC_ND_MASK|U_GC_NL_MASK|U_GC_NO_MASK)
+
+/** Mask constant for multiple UCharCategory bits (Z Separators). @stable ICU 2.1 */
+#define U_GC_Z_MASK (U_GC_ZS_MASK|U_GC_ZL_MASK|U_GC_ZP_MASK)
+
+/** Mask constant for multiple UCharCategory bits (C Others). @stable ICU 2.1 */
+#define U_GC_C_MASK \
+            (U_GC_CN_MASK|U_GC_CC_MASK|U_GC_CF_MASK|U_GC_CO_MASK|U_GC_CS_MASK)
+
+/** Mask constant for multiple UCharCategory bits (P Punctuation). @stable ICU 2.1 */
+#define U_GC_P_MASK \
+            (U_GC_PD_MASK|U_GC_PS_MASK|U_GC_PE_MASK|U_GC_PC_MASK|U_GC_PO_MASK| \
+             U_GC_PI_MASK|U_GC_PF_MASK)
+
+/** Mask constant for multiple UCharCategory bits (S Symbols). @stable ICU 2.1 */
+#define U_GC_S_MASK (U_GC_SM_MASK|U_GC_SC_MASK|U_GC_SK_MASK|U_GC_SO_MASK)
+
+/**
+ * This specifies the language directional property of a character set.
+ * @stable ICU 2.0
+ */
+typedef enum UCharDirection {
+    /** See note !!.  Comments of the form "EN" are read by genpname. */
+
+    /** L @stable ICU 2.0 */
+    U_LEFT_TO_RIGHT               = 0,
+    /** R @stable ICU 2.0 */
+    U_RIGHT_TO_LEFT               = 1,
+    /** EN @stable ICU 2.0 */
+    U_EUROPEAN_NUMBER             = 2,
+    /** ES @stable ICU 2.0 */
+    U_EUROPEAN_NUMBER_SEPARATOR   = 3,
+    /** ET @stable ICU 2.0 */
+    U_EUROPEAN_NUMBER_TERMINATOR  = 4,
+    /** AN @stable ICU 2.0 */
+    U_ARABIC_NUMBER               = 5,
+    /** CS @stable ICU 2.0 */
+    U_COMMON_NUMBER_SEPARATOR     = 6,
+    /** B @stable ICU 2.0 */
+    U_BLOCK_SEPARATOR             = 7,
+    /** S @stable ICU 2.0 */
+    U_SEGMENT_SEPARATOR           = 8,
+    /** WS @stable ICU 2.0 */
+    U_WHITE_SPACE_NEUTRAL         = 9,
+    /** ON @stable ICU 2.0 */
+    U_OTHER_NEUTRAL               = 10,
+    /** LRE @stable ICU 2.0 */
+    U_LEFT_TO_RIGHT_EMBEDDING     = 11,
+    /** LRO @stable ICU 2.0 */
+    U_LEFT_TO_RIGHT_OVERRIDE      = 12,
+    /** AL @stable ICU 2.0 */
+    U_RIGHT_TO_LEFT_ARABIC        = 13,
+    /** RLE @stable ICU 2.0 */
+    U_RIGHT_TO_LEFT_EMBEDDING     = 14,
+    /** RLO @stable ICU 2.0 */
+    U_RIGHT_TO_LEFT_OVERRIDE      = 15,
+    /** PDF @stable ICU 2.0 */
+    U_POP_DIRECTIONAL_FORMAT      = 16,
+    /** NSM @stable ICU 2.0 */
+    U_DIR_NON_SPACING_MARK        = 17,
+    /** BN @stable ICU 2.0 */
+    U_BOUNDARY_NEUTRAL            = 18,
+    /** @stable ICU 2.0 */
+    U_CHAR_DIRECTION_COUNT
+} UCharDirection;
+
+/**
+ * Constants for Unicode blocks, see the Unicode Data file Blocks.txt
+ * @stable ICU 2.0
+ */
+enum UBlockCode {
+
+    /** New No_Block value in Unicode 4. @stable ICU 2.6 */
+    UBLOCK_NO_BLOCK = 0, /*[none]*/ /* Special range indicating No_Block */
+
+    /** @stable ICU 2.0 */
+    UBLOCK_BASIC_LATIN = 1, /*[0000]*/ /*See note !!*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_LATIN_1_SUPPLEMENT=2, /*[0080]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_LATIN_EXTENDED_A =3, /*[0100]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_LATIN_EXTENDED_B =4, /*[0180]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_IPA_EXTENSIONS =5, /*[0250]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_SPACING_MODIFIER_LETTERS =6, /*[02B0]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_COMBINING_DIACRITICAL_MARKS =7, /*[0300]*/
+
+    /**
+     * Unicode 3.2 renames this block to "Greek and Coptic".
+     * @stable ICU 2.0
+     */
+    UBLOCK_GREEK =8, /*[0370]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_CYRILLIC =9, /*[0400]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_ARMENIAN =10, /*[0530]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_HEBREW =11, /*[0590]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_ARABIC =12, /*[0600]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_SYRIAC =13, /*[0700]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_THAANA =14, /*[0780]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_DEVANAGARI =15, /*[0900]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_BENGALI =16, /*[0980]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_GURMUKHI =17, /*[0A00]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_GUJARATI =18, /*[0A80]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_ORIYA =19, /*[0B00]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_TAMIL =20, /*[0B80]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_TELUGU =21, /*[0C00]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_KANNADA =22, /*[0C80]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_MALAYALAM =23, /*[0D00]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_SINHALA =24, /*[0D80]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_THAI =25, /*[0E00]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_LAO =26, /*[0E80]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_TIBETAN =27, /*[0F00]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_MYANMAR =28, /*[1000]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_GEORGIAN =29, /*[10A0]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_HANGUL_JAMO =30, /*[1100]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_ETHIOPIC =31, /*[1200]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_CHEROKEE =32, /*[13A0]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS =33, /*[1400]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_OGHAM =34, /*[1680]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_RUNIC =35, /*[16A0]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_KHMER =36, /*[1780]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_MONGOLIAN =37, /*[1800]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_LATIN_EXTENDED_ADDITIONAL =38, /*[1E00]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_GREEK_EXTENDED =39, /*[1F00]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_GENERAL_PUNCTUATION =40, /*[2000]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_SUPERSCRIPTS_AND_SUBSCRIPTS =41, /*[2070]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_CURRENCY_SYMBOLS =42, /*[20A0]*/
+
+    /**
+     * Unicode 3.2 renames this block to "Combining Diacritical Marks for Symbols".
+     * @stable ICU 2.0
+     */
+    UBLOCK_COMBINING_MARKS_FOR_SYMBOLS =43, /*[20D0]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_LETTERLIKE_SYMBOLS =44, /*[2100]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_NUMBER_FORMS =45, /*[2150]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_ARROWS =46, /*[2190]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_MATHEMATICAL_OPERATORS =47, /*[2200]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_MISCELLANEOUS_TECHNICAL =48, /*[2300]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_CONTROL_PICTURES =49, /*[2400]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_OPTICAL_CHARACTER_RECOGNITION =50, /*[2440]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_ENCLOSED_ALPHANUMERICS =51, /*[2460]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_BOX_DRAWING =52, /*[2500]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_BLOCK_ELEMENTS =53, /*[2580]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_GEOMETRIC_SHAPES =54, /*[25A0]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_MISCELLANEOUS_SYMBOLS =55, /*[2600]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_DINGBATS =56, /*[2700]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_BRAILLE_PATTERNS =57, /*[2800]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_CJK_RADICALS_SUPPLEMENT =58, /*[2E80]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_KANGXI_RADICALS =59, /*[2F00]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_IDEOGRAPHIC_DESCRIPTION_CHARACTERS =60, /*[2FF0]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_CJK_SYMBOLS_AND_PUNCTUATION =61, /*[3000]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_HIRAGANA =62, /*[3040]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_KATAKANA =63, /*[30A0]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_BOPOMOFO =64, /*[3100]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_HANGUL_COMPATIBILITY_JAMO =65, /*[3130]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_KANBUN =66, /*[3190]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_BOPOMOFO_EXTENDED =67, /*[31A0]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_ENCLOSED_CJK_LETTERS_AND_MONTHS =68, /*[3200]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_CJK_COMPATIBILITY =69, /*[3300]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A =70, /*[3400]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_CJK_UNIFIED_IDEOGRAPHS =71, /*[4E00]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_YI_SYLLABLES =72, /*[A000]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_YI_RADICALS =73, /*[A490]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_HANGUL_SYLLABLES =74, /*[AC00]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_HIGH_SURROGATES =75, /*[D800]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_HIGH_PRIVATE_USE_SURROGATES =76, /*[DB80]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_LOW_SURROGATES =77, /*[DC00]*/
+
+    /**
+     * Same as UBLOCK_PRIVATE_USE_AREA.
+     * Until Unicode 3.1.1, the corresponding block name was "Private Use",
+     * and multiple code point ranges had this block.
+     * Unicode 3.2 renames the block for the BMP PUA to "Private Use Area" and
+     * adds separate blocks for the supplementary PUAs.
+     *
+     * @stable ICU 2.0
+     */
+    UBLOCK_PRIVATE_USE = 78,
+    /**
+     * Same as UBLOCK_PRIVATE_USE.
+     * Until Unicode 3.1.1, the corresponding block name was "Private Use",
+     * and multiple code point ranges had this block.
+     * Unicode 3.2 renames the block for the BMP PUA to "Private Use Area" and
+     * adds separate blocks for the supplementary PUAs.
+     *
+     * @stable ICU 2.0
+     */
+    UBLOCK_PRIVATE_USE_AREA =UBLOCK_PRIVATE_USE, /*[E000]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_CJK_COMPATIBILITY_IDEOGRAPHS =79, /*[F900]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_ALPHABETIC_PRESENTATION_FORMS =80, /*[FB00]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_ARABIC_PRESENTATION_FORMS_A =81, /*[FB50]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_COMBINING_HALF_MARKS =82, /*[FE20]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_CJK_COMPATIBILITY_FORMS =83, /*[FE30]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_SMALL_FORM_VARIANTS =84, /*[FE50]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_ARABIC_PRESENTATION_FORMS_B =85, /*[FE70]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_SPECIALS =86, /*[FFF0]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_HALFWIDTH_AND_FULLWIDTH_FORMS =87, /*[FF00]*/
+
+    /* New blocks in Unicode 3.1 */
+
+    /** @stable ICU 2.0 */
+    UBLOCK_OLD_ITALIC = 88  , /*[10300]*/
+    /** @stable ICU 2.0 */
+    UBLOCK_GOTHIC = 89 , /*[10330]*/
+    /** @stable ICU 2.0 */
+    UBLOCK_DESERET = 90 , /*[10400]*/
+    /** @stable ICU 2.0 */
+    UBLOCK_BYZANTINE_MUSICAL_SYMBOLS = 91 , /*[1D000]*/
+    /** @stable ICU 2.0 */
+    UBLOCK_MUSICAL_SYMBOLS = 92 , /*[1D100]*/
+    /** @stable ICU 2.0 */
+    UBLOCK_MATHEMATICAL_ALPHANUMERIC_SYMBOLS = 93  , /*[1D400]*/
+    /** @stable ICU 2.0 */
+    UBLOCK_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B  = 94 , /*[20000]*/
+    /** @stable ICU 2.0 */
+    UBLOCK_CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT = 95 , /*[2F800]*/
+    /** @stable ICU 2.0 */
+    UBLOCK_TAGS = 96, /*[E0000]*/
+
+    /* New blocks in Unicode 3.2 */
+
+    /**
+     * Unicode 4.0.1 renames the "Cyrillic Supplementary" block to "Cyrillic Supplement".
+     * @stable ICU 2.2
+     */
+    UBLOCK_CYRILLIC_SUPPLEMENTARY = 97, 
+    /** @stable ICU 3.0  */
+    UBLOCK_CYRILLIC_SUPPLEMENT = UBLOCK_CYRILLIC_SUPPLEMENTARY, /*[0500]*/
+    /** @stable ICU 2.2 */
+    UBLOCK_TAGALOG = 98, /*[1700]*/
+    /** @stable ICU 2.2 */
+    UBLOCK_HANUNOO = 99, /*[1720]*/
+    /** @stable ICU 2.2 */
+    UBLOCK_BUHID = 100, /*[1740]*/
+    /** @stable ICU 2.2 */
+    UBLOCK_TAGBANWA = 101, /*[1760]*/
+    /** @stable ICU 2.2 */
+    UBLOCK_MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A = 102, /*[27C0]*/
+    /** @stable ICU 2.2 */
+    UBLOCK_SUPPLEMENTAL_ARROWS_A = 103, /*[27F0]*/
+    /** @stable ICU 2.2 */
+    UBLOCK_SUPPLEMENTAL_ARROWS_B = 104, /*[2900]*/
+    /** @stable ICU 2.2 */
+    UBLOCK_MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B = 105, /*[2980]*/
+    /** @stable ICU 2.2 */
+    UBLOCK_SUPPLEMENTAL_MATHEMATICAL_OPERATORS = 106, /*[2A00]*/
+    /** @stable ICU 2.2 */
+    UBLOCK_KATAKANA_PHONETIC_EXTENSIONS = 107, /*[31F0]*/
+    /** @stable ICU 2.2 */
+    UBLOCK_VARIATION_SELECTORS = 108, /*[FE00]*/
+    /** @stable ICU 2.2 */
+    UBLOCK_SUPPLEMENTARY_PRIVATE_USE_AREA_A = 109, /*[F0000]*/
+    /** @stable ICU 2.2 */
+    UBLOCK_SUPPLEMENTARY_PRIVATE_USE_AREA_B = 110, /*[100000]*/
+
+    /* New blocks in Unicode 4 */
+
+    /** @stable ICU 2.6 */
+    UBLOCK_LIMBU = 111, /*[1900]*/
+    /** @stable ICU 2.6 */
+    UBLOCK_TAI_LE = 112, /*[1950]*/
+    /** @stable ICU 2.6 */
+    UBLOCK_KHMER_SYMBOLS = 113, /*[19E0]*/
+    /** @stable ICU 2.6 */
+    UBLOCK_PHONETIC_EXTENSIONS = 114, /*[1D00]*/
+    /** @stable ICU 2.6 */
+    UBLOCK_MISCELLANEOUS_SYMBOLS_AND_ARROWS = 115, /*[2B00]*/
+    /** @stable ICU 2.6 */
+    UBLOCK_YIJING_HEXAGRAM_SYMBOLS = 116, /*[4DC0]*/
+    /** @stable ICU 2.6 */
+    UBLOCK_LINEAR_B_SYLLABARY = 117, /*[10000]*/
+    /** @stable ICU 2.6 */
+    UBLOCK_LINEAR_B_IDEOGRAMS = 118, /*[10080]*/
+    /** @stable ICU 2.6 */
+    UBLOCK_AEGEAN_NUMBERS = 119, /*[10100]*/
+    /** @stable ICU 2.6 */
+    UBLOCK_UGARITIC = 120, /*[10380]*/
+    /** @stable ICU 2.6 */
+    UBLOCK_SHAVIAN = 121, /*[10450]*/
+    /** @stable ICU 2.6 */
+    UBLOCK_OSMANYA = 122, /*[10480]*/
+    /** @stable ICU 2.6 */
+    UBLOCK_CYPRIOT_SYLLABARY = 123, /*[10800]*/
+    /** @stable ICU 2.6 */
+    UBLOCK_TAI_XUAN_JING_SYMBOLS = 124, /*[1D300]*/
+    /** @stable ICU 2.6 */
+    UBLOCK_VARIATION_SELECTORS_SUPPLEMENT = 125, /*[E0100]*/
+
+    /* New blocks in Unicode 4.1 */
+
+    /** @stable ICU 3.4 */
+    UBLOCK_ANCIENT_GREEK_MUSICAL_NOTATION = 126, /*[1D200]*/
+    /** @stable ICU 3.4 */
+    UBLOCK_ANCIENT_GREEK_NUMBERS = 127, /*[10140]*/
+    /** @stable ICU 3.4 */
+    UBLOCK_ARABIC_SUPPLEMENT = 128, /*[0750]*/
+    /** @stable ICU 3.4 */
+    UBLOCK_BUGINESE = 129, /*[1A00]*/
+    /** @stable ICU 3.4 */
+    UBLOCK_CJK_STROKES = 130, /*[31C0]*/
+    /** @stable ICU 3.4 */
+    UBLOCK_COMBINING_DIACRITICAL_MARKS_SUPPLEMENT = 131, /*[1DC0]*/
+    /** @stable ICU 3.4 */
+    UBLOCK_COPTIC = 132, /*[2C80]*/
+    /** @stable ICU 3.4 */
+    UBLOCK_ETHIOPIC_EXTENDED = 133, /*[2D80]*/
+    /** @stable ICU 3.4 */
+    UBLOCK_ETHIOPIC_SUPPLEMENT = 134, /*[1380]*/
+    /** @stable ICU 3.4 */
+    UBLOCK_GEORGIAN_SUPPLEMENT = 135, /*[2D00]*/
+    /** @stable ICU 3.4 */
+    UBLOCK_GLAGOLITIC = 136, /*[2C00]*/
+    /** @stable ICU 3.4 */
+    UBLOCK_KHAROSHTHI = 137, /*[10A00]*/
+    /** @stable ICU 3.4 */
+    UBLOCK_MODIFIER_TONE_LETTERS = 138, /*[A700]*/
+    /** @stable ICU 3.4 */
+    UBLOCK_NEW_TAI_LUE = 139, /*[1980]*/
+    /** @stable ICU 3.4 */
+    UBLOCK_OLD_PERSIAN = 140, /*[103A0]*/
+    /** @stable ICU 3.4 */
+    UBLOCK_PHONETIC_EXTENSIONS_SUPPLEMENT = 141, /*[1D80]*/
+    /** @stable ICU 3.4 */
+    UBLOCK_SUPPLEMENTAL_PUNCTUATION = 142, /*[2E00]*/
+    /** @stable ICU 3.4 */
+    UBLOCK_SYLOTI_NAGRI = 143, /*[A800]*/
+    /** @stable ICU 3.4 */
+    UBLOCK_TIFINAGH = 144, /*[2D30]*/
+    /** @stable ICU 3.4 */
+    UBLOCK_VERTICAL_FORMS = 145, /*[FE10]*/
+
+    /* New blocks in Unicode 5.0 */
+
+    /** @stable ICU 3.6 */
+    UBLOCK_NKO = 146, /*[07C0]*/
+    /** @stable ICU 3.6 */
+    UBLOCK_BALINESE = 147, /*[1B00]*/
+    /** @stable ICU 3.6 */
+    UBLOCK_LATIN_EXTENDED_C = 148, /*[2C60]*/
+    /** @stable ICU 3.6 */
+    UBLOCK_LATIN_EXTENDED_D = 149, /*[A720]*/
+    /** @stable ICU 3.6 */
+    UBLOCK_PHAGS_PA = 150, /*[A840]*/
+    /** @stable ICU 3.6 */
+    UBLOCK_PHOENICIAN = 151, /*[10900]*/
+    /** @stable ICU 3.6 */
+    UBLOCK_CUNEIFORM = 152, /*[12000]*/
+    /** @stable ICU 3.6 */
+    UBLOCK_CUNEIFORM_NUMBERS_AND_PUNCTUATION = 153, /*[12400]*/
+    /** @stable ICU 3.6 */
+    UBLOCK_COUNTING_ROD_NUMERALS = 154, /*[1D360]*/
+
+    /* New blocks in Unicode 5.1 */
+
+    /** @draft ICU 4.0 */
+    UBLOCK_SUNDANESE = 155, /*[1B80]*/
+    /** @draft ICU 4.0 */
+    UBLOCK_LEPCHA = 156, /*[1C00]*/
+    /** @draft ICU 4.0 */
+    UBLOCK_OL_CHIKI = 157, /*[1C50]*/
+    /** @draft ICU 4.0 */
+    UBLOCK_CYRILLIC_EXTENDED_A = 158, /*[2DE0]*/
+    /** @draft ICU 4.0 */
+    UBLOCK_VAI = 159, /*[A500]*/
+    /** @draft ICU 4.0 */
+    UBLOCK_CYRILLIC_EXTENDED_B = 160, /*[A640]*/
+    /** @draft ICU 4.0 */
+    UBLOCK_SAURASHTRA = 161, /*[A880]*/
+    /** @draft ICU 4.0 */
+    UBLOCK_KAYAH_LI = 162, /*[A900]*/
+    /** @draft ICU 4.0 */
+    UBLOCK_REJANG = 163, /*[A930]*/
+    /** @draft ICU 4.0 */
+    UBLOCK_CHAM = 164, /*[AA00]*/
+    /** @draft ICU 4.0 */
+    UBLOCK_ANCIENT_SYMBOLS = 165, /*[10190]*/
+    /** @draft ICU 4.0 */
+    UBLOCK_PHAISTOS_DISC = 166, /*[101D0]*/
+    /** @draft ICU 4.0 */
+    UBLOCK_LYCIAN = 167, /*[10280]*/
+    /** @draft ICU 4.0 */
+    UBLOCK_CARIAN = 168, /*[102A0]*/
+    /** @draft ICU 4.0 */
+    UBLOCK_LYDIAN = 169, /*[10920]*/
+    /** @draft ICU 4.0 */
+    UBLOCK_MAHJONG_TILES = 170, /*[1F000]*/
+    /** @draft ICU 4.0 */
+    UBLOCK_DOMINO_TILES = 171, /*[1F030]*/
+
+    /** @stable ICU 2.0 */
+    UBLOCK_COUNT = 172,
+
+    /** @stable ICU 2.0 */
+    UBLOCK_INVALID_CODE=-1
+};
+
+/** @stable ICU 2.0 */
+typedef enum UBlockCode UBlockCode;
+
+/**
+ * East Asian Width constants.
+ *
+ * @see UCHAR_EAST_ASIAN_WIDTH
+ * @see u_getIntPropertyValue
+ * @stable ICU 2.2
+ */
+typedef enum UEastAsianWidth {
+    U_EA_NEUTRAL,   /*[N]*/ /*See note !!*/
+    U_EA_AMBIGUOUS, /*[A]*/
+    U_EA_HALFWIDTH, /*[H]*/
+    U_EA_FULLWIDTH, /*[F]*/
+    U_EA_NARROW,    /*[Na]*/
+    U_EA_WIDE,      /*[W]*/
+    U_EA_COUNT
+} UEastAsianWidth;
+/*
+ * Implementation note:
+ * Keep UEastAsianWidth constant values in sync with names list in genprops/props2.c.
+ */
+
+/**
+ * Selector constants for u_charName().
+ * u_charName() returns the "modern" name of a
+ * Unicode character; or the name that was defined in
+ * Unicode version 1.0, before the Unicode standard merged
+ * with ISO-10646; or an "extended" name that gives each
+ * Unicode code point a unique name.
+ *
+ * @see u_charName
+ * @stable ICU 2.0
+ */
+typedef enum UCharNameChoice {
+    U_UNICODE_CHAR_NAME,
+    U_UNICODE_10_CHAR_NAME,
+    U_EXTENDED_CHAR_NAME,
+    U_CHAR_NAME_CHOICE_COUNT
+} UCharNameChoice;
+
+/**
+ * Selector constants for u_getPropertyName() and
+ * u_getPropertyValueName().  These selectors are used to choose which
+ * name is returned for a given property or value.  All properties and
+ * values have a long name.  Most have a short name, but some do not.
+ * Unicode allows for additional names, beyond the long and short
+ * name, which would be indicated by U_LONG_PROPERTY_NAME + i, where
+ * i=1, 2,...
+ *
+ * @see u_getPropertyName()
+ * @see u_getPropertyValueName()
+ * @stable ICU 2.4
+ */
+typedef enum UPropertyNameChoice {
+    U_SHORT_PROPERTY_NAME,
+    U_LONG_PROPERTY_NAME,
+    U_PROPERTY_NAME_CHOICE_COUNT
+} UPropertyNameChoice;
+
+/**
+ * Decomposition Type constants.
+ *
+ * @see UCHAR_DECOMPOSITION_TYPE
+ * @stable ICU 2.2
+ */
+typedef enum UDecompositionType {
+    U_DT_NONE,              /*[none]*/ /*See note !!*/
+    U_DT_CANONICAL,         /*[can]*/
+    U_DT_COMPAT,            /*[com]*/
+    U_DT_CIRCLE,            /*[enc]*/
+    U_DT_FINAL,             /*[fin]*/
+    U_DT_FONT,              /*[font]*/
+    U_DT_FRACTION,          /*[fra]*/
+    U_DT_INITIAL,           /*[init]*/
+    U_DT_ISOLATED,          /*[iso]*/
+    U_DT_MEDIAL,            /*[med]*/
+    U_DT_NARROW,            /*[nar]*/
+    U_DT_NOBREAK,           /*[nb]*/
+    U_DT_SMALL,             /*[sml]*/
+    U_DT_SQUARE,            /*[sqr]*/
+    U_DT_SUB,               /*[sub]*/
+    U_DT_SUPER,             /*[sup]*/
+    U_DT_VERTICAL,          /*[vert]*/
+    U_DT_WIDE,              /*[wide]*/
+    U_DT_COUNT /* 18 */
+} UDecompositionType;
+
+/**
+ * Joining Type constants.
+ *
+ * @see UCHAR_JOINING_TYPE
+ * @stable ICU 2.2
+ */
+typedef enum UJoiningType {
+    U_JT_NON_JOINING,       /*[U]*/ /*See note !!*/
+    U_JT_JOIN_CAUSING,      /*[C]*/
+    U_JT_DUAL_JOINING,      /*[D]*/
+    U_JT_LEFT_JOINING,      /*[L]*/
+    U_JT_RIGHT_JOINING,     /*[R]*/
+    U_JT_TRANSPARENT,       /*[T]*/
+    U_JT_COUNT /* 6 */
+} UJoiningType;
+
+/**
+ * Joining Group constants.
+ *
+ * @see UCHAR_JOINING_GROUP
+ * @stable ICU 2.2
+ */
+typedef enum UJoiningGroup {
+    U_JG_NO_JOINING_GROUP,
+    U_JG_AIN,
+    U_JG_ALAPH,
+    U_JG_ALEF,
+    U_JG_BEH,
+    U_JG_BETH,
+    U_JG_DAL,
+    U_JG_DALATH_RISH,
+    U_JG_E,
+    U_JG_FEH,
+    U_JG_FINAL_SEMKATH,
+    U_JG_GAF,
+    U_JG_GAMAL,
+    U_JG_HAH,
+    U_JG_HAMZA_ON_HEH_GOAL,
+    U_JG_HE,
+    U_JG_HEH,
+    U_JG_HEH_GOAL,
+    U_JG_HETH,
+    U_JG_KAF,
+    U_JG_KAPH,
+    U_JG_KNOTTED_HEH,
+    U_JG_LAM,
+    U_JG_LAMADH,
+    U_JG_MEEM,
+    U_JG_MIM,
+    U_JG_NOON,
+    U_JG_NUN,
+    U_JG_PE,
+    U_JG_QAF,
+    U_JG_QAPH,
+    U_JG_REH,
+    U_JG_REVERSED_PE,
+    U_JG_SAD,
+    U_JG_SADHE,
+    U_JG_SEEN,
+    U_JG_SEMKATH,
+    U_JG_SHIN,
+    U_JG_SWASH_KAF,
+    U_JG_SYRIAC_WAW,
+    U_JG_TAH,
+    U_JG_TAW,
+    U_JG_TEH_MARBUTA,
+    U_JG_TETH,
+    U_JG_WAW,
+    U_JG_YEH,
+    U_JG_YEH_BARREE,
+    U_JG_YEH_WITH_TAIL,
+    U_JG_YUDH,
+    U_JG_YUDH_HE,
+    U_JG_ZAIN,
+    U_JG_FE,        /**< @stable ICU 2.6 */
+    U_JG_KHAPH,     /**< @stable ICU 2.6 */
+    U_JG_ZHAIN,     /**< @stable ICU 2.6 */
+    U_JG_BURUSHASKI_YEH_BARREE, /**< @draft ICU 4.0 */
+    U_JG_COUNT
+} UJoiningGroup;
+
+/**
+ * Grapheme Cluster Break constants.
+ *
+ * @see UCHAR_GRAPHEME_CLUSTER_BREAK
+ * @stable ICU 3.4
+ */
+typedef enum UGraphemeClusterBreak {
+    U_GCB_OTHER = 0,            /*[XX]*/ /*See note !!*/
+    U_GCB_CONTROL = 1,          /*[CN]*/
+    U_GCB_CR = 2,               /*[CR]*/
+    U_GCB_EXTEND = 3,           /*[EX]*/
+    U_GCB_L = 4,                /*[L]*/
+    U_GCB_LF = 5,               /*[LF]*/
+    U_GCB_LV = 6,               /*[LV]*/
+    U_GCB_LVT = 7,              /*[LVT]*/
+    U_GCB_T = 8,                /*[T]*/
+    U_GCB_V = 9,                /*[V]*/
+    U_GCB_SPACING_MARK = 10,    /*[SM]*/ /* from here on: new in Unicode 5.1/ICU 4.0 */
+    U_GCB_PREPEND = 11,         /*[PP]*/
+    U_GCB_COUNT = 12
+} UGraphemeClusterBreak;
+
+/**
+ * Word Break constants.
+ * (UWordBreak is a pre-existing enum type in ubrk.h for word break status tags.)
+ *
+ * @see UCHAR_WORD_BREAK
+ * @stable ICU 3.4
+ */
+typedef enum UWordBreakValues {
+    U_WB_OTHER = 0,             /*[XX]*/ /*See note !!*/
+    U_WB_ALETTER = 1,           /*[LE]*/
+    U_WB_FORMAT = 2,            /*[FO]*/
+    U_WB_KATAKANA = 3,          /*[KA]*/
+    U_WB_MIDLETTER = 4,         /*[ML]*/
+    U_WB_MIDNUM = 5,            /*[MN]*/
+    U_WB_NUMERIC = 6,           /*[NU]*/
+    U_WB_EXTENDNUMLET = 7,      /*[EX]*/
+    U_WB_CR = 8,                /*[CR]*/ /* from here on: new in Unicode 5.1/ICU 4.0 */
+    U_WB_EXTEND = 9,            /*[Extend]*/
+    U_WB_LF = 10,               /*[LF]*/
+    U_WB_MIDNUMLET =11,         /*[MB]*/
+    U_WB_NEWLINE =12,           /*[NL]*/
+    U_WB_COUNT = 13
+} UWordBreakValues;
+
+/**
+ * Sentence Break constants.
+ *
+ * @see UCHAR_SENTENCE_BREAK
+ * @stable ICU 3.4
+ */
+typedef enum USentenceBreak {
+    U_SB_OTHER = 0,             /*[XX]*/ /*See note !!*/
+    U_SB_ATERM = 1,             /*[AT]*/
+    U_SB_CLOSE = 2,             /*[CL]*/
+    U_SB_FORMAT = 3,            /*[FO]*/
+    U_SB_LOWER = 4,             /*[LO]*/
+    U_SB_NUMERIC = 5,           /*[NU]*/
+    U_SB_OLETTER = 6,           /*[LE]*/
+    U_SB_SEP = 7,               /*[SE]*/
+    U_SB_SP = 8,                /*[SP]*/
+    U_SB_STERM = 9,             /*[ST]*/
+    U_SB_UPPER = 10,            /*[UP]*/
+    U_SB_CR = 11,               /*[CR]*/ /* from here on: new in Unicode 5.1/ICU 4.0 */
+    U_SB_EXTEND = 12,           /*[EX]*/
+    U_SB_LF = 13,               /*[LF]*/
+    U_SB_SCONTINUE = 14,        /*[SC]*/
+    U_SB_COUNT = 15
+} USentenceBreak;
+
+/**
+ * Line Break constants.
+ *
+ * @see UCHAR_LINE_BREAK
+ * @stable ICU 2.2
+ */
+typedef enum ULineBreak {
+    U_LB_UNKNOWN = 0,           /*[XX]*/ /*See note !!*/
+    U_LB_AMBIGUOUS = 1,         /*[AI]*/
+    U_LB_ALPHABETIC = 2,        /*[AL]*/
+    U_LB_BREAK_BOTH = 3,        /*[B2]*/
+    U_LB_BREAK_AFTER = 4,       /*[BA]*/
+    U_LB_BREAK_BEFORE = 5,      /*[BB]*/
+    U_LB_MANDATORY_BREAK = 6,   /*[BK]*/
+    U_LB_CONTINGENT_BREAK = 7,  /*[CB]*/
+    U_LB_CLOSE_PUNCTUATION = 8, /*[CL]*/
+    U_LB_COMBINING_MARK = 9,    /*[CM]*/
+    U_LB_CARRIAGE_RETURN = 10,   /*[CR]*/
+    U_LB_EXCLAMATION = 11,       /*[EX]*/
+    U_LB_GLUE = 12,              /*[GL]*/
+    U_LB_HYPHEN = 13,            /*[HY]*/
+    U_LB_IDEOGRAPHIC = 14,       /*[ID]*/
+    U_LB_INSEPERABLE = 15,
+    /** Renamed from the misspelled "inseperable" in Unicode 4.0.1/ICU 3.0 @stable ICU 3.0 */
+    U_LB_INSEPARABLE=U_LB_INSEPERABLE,/*[IN]*/
+    U_LB_INFIX_NUMERIC = 16,     /*[IS]*/
+    U_LB_LINE_FEED = 17,         /*[LF]*/
+    U_LB_NONSTARTER = 18,        /*[NS]*/
+    U_LB_NUMERIC = 19,           /*[NU]*/
+    U_LB_OPEN_PUNCTUATION = 20,  /*[OP]*/
+    U_LB_POSTFIX_NUMERIC = 21,   /*[PO]*/
+    U_LB_PREFIX_NUMERIC = 22,    /*[PR]*/
+    U_LB_QUOTATION = 23,         /*[QU]*/
+    U_LB_COMPLEX_CONTEXT = 24,   /*[SA]*/
+    U_LB_SURROGATE = 25,         /*[SG]*/
+    U_LB_SPACE = 26,             /*[SP]*/
+    U_LB_BREAK_SYMBOLS = 27,     /*[SY]*/
+    U_LB_ZWSPACE = 28,           /*[ZW]*/
+    U_LB_NEXT_LINE = 29,         /*[NL]*/ /* from here on: new in Unicode 4/ICU 2.6 */
+    U_LB_WORD_JOINER = 30,       /*[WJ]*/
+    U_LB_H2 = 31,                /*[H2]*/ /* from here on: new in Unicode 4.1/ICU 3.4 */
+    U_LB_H3 = 32,                /*[H3]*/
+    U_LB_JL = 33,                /*[JL]*/
+    U_LB_JT = 34,                /*[JT]*/
+    U_LB_JV = 35,                /*[JV]*/
+    U_LB_COUNT = 36
+} ULineBreak;
+
+/**
+ * Numeric Type constants.
+ *
+ * @see UCHAR_NUMERIC_TYPE
+ * @stable ICU 2.2
+ */
+typedef enum UNumericType {
+    U_NT_NONE,              /*[None]*/ /*See note !!*/
+    U_NT_DECIMAL,           /*[de]*/
+    U_NT_DIGIT,             /*[di]*/
+    U_NT_NUMERIC,           /*[nu]*/
+    U_NT_COUNT
+} UNumericType;
+
+/**
+ * Hangul Syllable Type constants.
+ *
+ * @see UCHAR_HANGUL_SYLLABLE_TYPE
+ * @stable ICU 2.6
+ */
+typedef enum UHangulSyllableType {
+    U_HST_NOT_APPLICABLE,   /*[NA]*/ /*See note !!*/
+    U_HST_LEADING_JAMO,     /*[L]*/
+    U_HST_VOWEL_JAMO,       /*[V]*/
+    U_HST_TRAILING_JAMO,    /*[T]*/
+    U_HST_LV_SYLLABLE,      /*[LV]*/
+    U_HST_LVT_SYLLABLE,     /*[LVT]*/
+    U_HST_COUNT
+} UHangulSyllableType;
+
+/**
+ * Check a binary Unicode property for a code point.
+ *
+ * Unicode, especially in version 3.2, defines many more properties than the
+ * original set in UnicodeData.txt.
+ *
+ * The properties APIs are intended to reflect Unicode properties as defined
+ * in the Unicode Character Database (UCD) and Unicode Technical Reports (UTR).
+ * For details about the properties see http://www.unicode.org/ucd/ .
+ * For names of Unicode properties see the UCD file PropertyAliases.txt.
+ *
+ * Important: If ICU is built with UCD files from Unicode versions below 3.2,
+ * then properties marked with "new in Unicode 3.2" are not or not fully available.
+ *
+ * @param c Code point to test.
+ * @param which UProperty selector constant, identifies which binary property to check.
+ *        Must be UCHAR_BINARY_START<=which<UCHAR_BINARY_LIMIT.
+ * @return TRUE or FALSE according to the binary Unicode property value for c.
+ *         Also FALSE if 'which' is out of bounds or if the Unicode version
+ *         does not have data for the property at all, or not for this code point.
+ *
+ * @see UProperty
+ * @see u_getIntPropertyValue
+ * @see u_getUnicodeVersion
+ * @stable ICU 2.1
+ */
+U_STABLE UBool U_EXPORT2
+u_hasBinaryProperty(UChar32 c, UProperty which);
+
+/**
+ * Check if a code point has the Alphabetic Unicode property.
+ * Same as u_hasBinaryProperty(c, UCHAR_ALPHABETIC).
+ * This is different from u_isalpha!
+ * @param c Code point to test
+ * @return true if the code point has the Alphabetic Unicode property, false otherwise
+ *
+ * @see UCHAR_ALPHABETIC
+ * @see u_isalpha
+ * @see u_hasBinaryProperty
+ * @stable ICU 2.1
+ */
+U_STABLE UBool U_EXPORT2
+u_isUAlphabetic(UChar32 c);
+
+/**
+ * Check if a code point has the Lowercase Unicode property.
+ * Same as u_hasBinaryProperty(c, UCHAR_LOWERCASE).
+ * This is different from u_islower!
+ * @param c Code point to test
+ * @return true if the code point has the Lowercase Unicode property, false otherwise
+ *
+ * @see UCHAR_LOWERCASE
+ * @see u_islower
+ * @see u_hasBinaryProperty
+ * @stable ICU 2.1
+ */
+U_STABLE UBool U_EXPORT2
+u_isULowercase(UChar32 c);
+
+/**
+ * Check if a code point has the Uppercase Unicode property.
+ * Same as u_hasBinaryProperty(c, UCHAR_UPPERCASE).
+ * This is different from u_isupper!
+ * @param c Code point to test
+ * @return true if the code point has the Uppercase Unicode property, false otherwise
+ *
+ * @see UCHAR_UPPERCASE
+ * @see u_isupper
+ * @see u_hasBinaryProperty
+ * @stable ICU 2.1
+ */
+U_STABLE UBool U_EXPORT2
+u_isUUppercase(UChar32 c);
+
+/**
+ * Check if a code point has the White_Space Unicode property.
+ * Same as u_hasBinaryProperty(c, UCHAR_WHITE_SPACE).
+ * This is different from both u_isspace and u_isWhitespace!
+ *
+ * Note: There are several ICU whitespace functions; please see the uchar.h
+ * file documentation for a detailed comparison.
+ *
+ * @param c Code point to test
+ * @return true if the code point has the White_Space Unicode property, false otherwise.
+ *
+ * @see UCHAR_WHITE_SPACE
+ * @see u_isWhitespace
+ * @see u_isspace
+ * @see u_isJavaSpaceChar
+ * @see u_hasBinaryProperty
+ * @stable ICU 2.1
+ */
+U_STABLE UBool U_EXPORT2
+u_isUWhiteSpace(UChar32 c);
+
+/**
+ * Get the property value for an enumerated or integer Unicode property for a code point.
+ * Also returns binary and mask property values.
+ *
+ * Unicode, especially in version 3.2, defines many more properties than the
+ * original set in UnicodeData.txt.
+ *
+ * The properties APIs are intended to reflect Unicode properties as defined
+ * in the Unicode Character Database (UCD) and Unicode Technical Reports (UTR).
+ * For details about the properties see http://www.unicode.org/ .
+ * For names of Unicode properties see the UCD file PropertyAliases.txt.
+ *
+ * Sample usage:
+ * UEastAsianWidth ea=(UEastAsianWidth)u_getIntPropertyValue(c, UCHAR_EAST_ASIAN_WIDTH);
+ * UBool b=(UBool)u_getIntPropertyValue(c, UCHAR_IDEOGRAPHIC);
+ *
+ * @param c Code point to test.
+ * @param which UProperty selector constant, identifies which property to check.
+ *        Must be UCHAR_BINARY_START<=which<UCHAR_BINARY_LIMIT
+ *        or UCHAR_INT_START<=which<UCHAR_INT_LIMIT
+ *        or UCHAR_MASK_START<=which<UCHAR_MASK_LIMIT.
+ * @return Numeric value that is directly the property value or,
+ *         for enumerated properties, corresponds to the numeric value of the enumerated
+ *         constant of the respective property value enumeration type
+ *         (cast to enum type if necessary).
+ *         Returns 0 or 1 (for FALSE/TRUE) for binary Unicode properties.
+ *         Returns a bit-mask for mask properties.
+ *         Returns 0 if 'which' is out of bounds or if the Unicode version
+ *         does not have data for the property at all, or not for this code point.
+ *
+ * @see UProperty
+ * @see u_hasBinaryProperty
+ * @see u_getIntPropertyMinValue
+ * @see u_getIntPropertyMaxValue
+ * @see u_getUnicodeVersion
+ * @stable ICU 2.2
+ */
+U_STABLE int32_t U_EXPORT2
+u_getIntPropertyValue(UChar32 c, UProperty which);
+
+/**
+ * Get the minimum value for an enumerated/integer/binary Unicode property.
+ * Can be used together with u_getIntPropertyMaxValue
+ * to allocate arrays of UnicodeSet or similar.
+ *
+ * @param which UProperty selector constant, identifies which binary property to check.
+ *        Must be UCHAR_BINARY_START<=which<UCHAR_BINARY_LIMIT
+ *        or UCHAR_INT_START<=which<UCHAR_INT_LIMIT.
+ * @return Minimum value returned by u_getIntPropertyValue for a Unicode property.
+ *         0 if the property selector is out of range.
+ *
+ * @see UProperty
+ * @see u_hasBinaryProperty
+ * @see u_getUnicodeVersion
+ * @see u_getIntPropertyMaxValue
+ * @see u_getIntPropertyValue
+ * @stable ICU 2.2
+ */
+U_STABLE int32_t U_EXPORT2
+u_getIntPropertyMinValue(UProperty which);
+
+/**
+ * Get the maximum value for an enumerated/integer/binary Unicode property.
+ * Can be used together with u_getIntPropertyMinValue
+ * to allocate arrays of UnicodeSet or similar.
+ *
+ * Examples for min/max values (for Unicode 3.2):
+ *
+ * - UCHAR_BIDI_CLASS:    0/18 (U_LEFT_TO_RIGHT/U_BOUNDARY_NEUTRAL)
+ * - UCHAR_SCRIPT:        0/45 (USCRIPT_COMMON/USCRIPT_TAGBANWA)
+ * - UCHAR_IDEOGRAPHIC:   0/1  (FALSE/TRUE)
+ *
+ * For undefined UProperty constant values, min/max values will be 0/-1.
+ *
+ * @param which UProperty selector constant, identifies which binary property to check.
+ *        Must be UCHAR_BINARY_START<=which<UCHAR_BINARY_LIMIT
+ *        or UCHAR_INT_START<=which<UCHAR_INT_LIMIT.
+ * @return Maximum value returned by u_getIntPropertyValue for a Unicode property.
+ *         <=0 if the property selector is out of range.
+ *
+ * @see UProperty
+ * @see u_hasBinaryProperty
+ * @see u_getUnicodeVersion
+ * @see u_getIntPropertyMaxValue
+ * @see u_getIntPropertyValue
+ * @stable ICU 2.2
+ */
+U_STABLE int32_t U_EXPORT2
+u_getIntPropertyMaxValue(UProperty which);
+
+/**
+ * Get the numeric value for a Unicode code point as defined in the
+ * Unicode Character Database.
+ *
+ * A "double" return type is necessary because
+ * some numeric values are fractions, negative, or too large for int32_t.
+ *
+ * For characters without any numeric values in the Unicode Character Database,
+ * this function will return U_NO_NUMERIC_VALUE.
+ *
+ * Similar to java.lang.Character.getNumericValue(), but u_getNumericValue()
+ * also supports negative values, large values, and fractions,
+ * while Java's getNumericValue() returns values 10..35 for ASCII letters.
+ *
+ * @param c Code point to get the numeric value for.
+ * @return Numeric value of c, or U_NO_NUMERIC_VALUE if none is defined.
+ *
+ * @see U_NO_NUMERIC_VALUE
+ * @stable ICU 2.2
+ */
+U_STABLE double U_EXPORT2
+u_getNumericValue(UChar32 c);
+
+/**
+ * Special value that is returned by u_getNumericValue when
+ * no numeric value is defined for a code point.
+ *
+ * @see u_getNumericValue
+ * @stable ICU 2.2
+ */
+#define U_NO_NUMERIC_VALUE ((double)-123456789.)
+
+/**
+ * Determines whether the specified code point has the general category "Ll"
+ * (lowercase letter).
+ *
+ * Same as java.lang.Character.isLowerCase().
+ *
+ * This misses some characters that are also lowercase but
+ * have a different general category value.
+ * In order to include those, use UCHAR_LOWERCASE.
+ *
+ * In addition to being equivalent to a Java function, this also serves
+ * as a C/POSIX migration function.
+ * See the comments about C/POSIX character classification functions in the
+ * documentation at the top of this header file.
+ *
+ * @param c the code point to be tested
+ * @return TRUE if the code point is an Ll lowercase letter
+ *
+ * @see UCHAR_LOWERCASE
+ * @see u_isupper
+ * @see u_istitle
+ * @stable ICU 2.0
+ */
+U_STABLE UBool U_EXPORT2
+u_islower(UChar32 c);
+
+/**
+ * Determines whether the specified code point has the general category "Lu"
+ * (uppercase letter).
+ *
+ * Same as java.lang.Character.isUpperCase().
+ *
+ * This misses some characters that are also uppercase but
+ * have a different general category value.
+ * In order to include those, use UCHAR_UPPERCASE.
+ *
+ * In addition to being equivalent to a Java function, this also serves
+ * as a C/POSIX migration function.
+ * See the comments about C/POSIX character classification functions in the
+ * documentation at the top of this header file.
+ *
+ * @param c the code point to be tested
+ * @return TRUE if the code point is an Lu uppercase letter
+ *
+ * @see UCHAR_UPPERCASE
+ * @see u_islower
+ * @see u_istitle
+ * @see u_tolower
+ * @stable ICU 2.0
+ */
+U_STABLE UBool U_EXPORT2
+u_isupper(UChar32 c);
+
+/**
+ * Determines whether the specified code point is a titlecase letter.
+ * True for general category "Lt" (titlecase letter).
+ *
+ * Same as java.lang.Character.isTitleCase().
+ *
+ * @param c the code point to be tested
+ * @return TRUE if the code point is an Lt titlecase letter
+ *
+ * @see u_isupper
+ * @see u_islower
+ * @see u_totitle
+ * @stable ICU 2.0
+ */
+U_STABLE UBool U_EXPORT2
+u_istitle(UChar32 c);
+
+/**
+ * Determines whether the specified code point is a digit character according to Java.
+ * True for characters with general category "Nd" (decimal digit numbers).
+ * Beginning with Unicode 4, this is the same as
+ * testing for the Numeric_Type of Decimal.
+ *
+ * Same as java.lang.Character.isDigit().
+ *
+ * In addition to being equivalent to a Java function, this also serves
+ * as a C/POSIX migration function.
+ * See the comments about C/POSIX character classification functions in the
+ * documentation at the top of this header file.
+ *
+ * @param c the code point to be tested
+ * @return TRUE if the code point is a digit character according to Character.isDigit()
+ *
+ * @stable ICU 2.0
+ */
+U_STABLE UBool U_EXPORT2
+u_isdigit(UChar32 c);
+
+/**
+ * Determines whether the specified code point is a letter character.
+ * True for general categories "L" (letters).
+ *
+ * Same as java.lang.Character.isLetter().
+ *
+ * In addition to being equivalent to a Java function, this also serves
+ * as a C/POSIX migration function.
+ * See the comments about C/POSIX character classification functions in the
+ * documentation at the top of this header file.
+ *
+ * @param c the code point to be tested
+ * @return TRUE if the code point is a letter character
+ *
+ * @see u_isdigit
+ * @see u_isalnum
+ * @stable ICU 2.0
+ */
+U_STABLE UBool U_EXPORT2
+u_isalpha(UChar32 c);
+
+/**
+ * Determines whether the specified code point is an alphanumeric character
+ * (letter or digit) according to Java.
+ * True for characters with general categories
+ * "L" (letters) and "Nd" (decimal digit numbers).
+ *
+ * Same as java.lang.Character.isLetterOrDigit().
+ *
+ * In addition to being equivalent to a Java function, this also serves
+ * as a C/POSIX migration function.
+ * See the comments about C/POSIX character classification functions in the
+ * documentation at the top of this header file.
+ *
+ * @param c the code point to be tested
+ * @return TRUE if the code point is an alphanumeric character according to Character.isLetterOrDigit()
+ *
+ * @stable ICU 2.0
+ */
+U_STABLE UBool U_EXPORT2
+u_isalnum(UChar32 c);
+
+/**
+ * Determines whether the specified code point is a hexadecimal digit.
+ * This is equivalent to u_digit(c, 16)>=0.
+ * True for characters with general category "Nd" (decimal digit numbers)
+ * as well as Latin letters a-f and A-F in both ASCII and Fullwidth ASCII.
+ * (That is, for letters with code points
+ * 0041..0046, 0061..0066, FF21..FF26, FF41..FF46.)
+ *
+ * In order to narrow the definition of hexadecimal digits to only ASCII
+ * characters, use (c<=0x7f && u_isxdigit(c)).
+ *
+ * This is a C/POSIX migration function.
+ * See the comments about C/POSIX character classification functions in the
+ * documentation at the top of this header file.
+ *
+ * @param c the code point to be tested
+ * @return TRUE if the code point is a hexadecimal digit
+ *
+ * @stable ICU 2.6
+ */
+U_STABLE UBool U_EXPORT2
+u_isxdigit(UChar32 c);
+
+/**
+ * Determines whether the specified code point is a punctuation character.
+ * True for characters with general categories "P" (punctuation).
+ *
+ * This is a C/POSIX migration function.
+ * See the comments about C/POSIX character classification functions in the
+ * documentation at the top of this header file.
+ *
+ * @param c the code point to be tested
+ * @return TRUE if the code point is a punctuation character
+ *
+ * @stable ICU 2.6
+ */
+U_STABLE UBool U_EXPORT2
+u_ispunct(UChar32 c);
+
+/**
+ * Determines whether the specified code point is a "graphic" character
+ * (printable, excluding spaces).
+ * TRUE for all characters except those with general categories
+ * "Cc" (control codes), "Cf" (format controls), "Cs" (surrogates),
+ * "Cn" (unassigned), and "Z" (separators).
+ *
+ * This is a C/POSIX migration function.
+ * See the comments about C/POSIX character classification functions in the
+ * documentation at the top of this header file.
+ *
+ * @param c the code point to be tested
+ * @return TRUE if the code point is a "graphic" character
+ *
+ * @stable ICU 2.6
+ */
+U_STABLE UBool U_EXPORT2
+u_isgraph(UChar32 c);
+
+/**
+ * Determines whether the specified code point is a "blank" or "horizontal space",
+ * a character that visibly separates words on a line.
+ * The following are equivalent definitions:
+ *
+ * TRUE for Unicode White_Space characters except for "vertical space controls"
+ * where "vertical space controls" are the following characters:
+ * U+000A (LF) U+000B (VT) U+000C (FF) U+000D (CR) U+0085 (NEL) U+2028 (LS) U+2029 (PS)
+ *
+ * same as
+ *
+ * TRUE for U+0009 (TAB) and characters with general category "Zs" (space separators)
+ * except Zero Width Space (ZWSP, U+200B).
+ *
+ * Note: There are several ICU whitespace functions; please see the uchar.h
+ * file documentation for a detailed comparison.
+ *
+ * This is a C/POSIX migration function.
+ * See the comments about C/POSIX character classification functions in the
+ * documentation at the top of this header file.
+ *
+ * @param c the code point to be tested
+ * @return TRUE if the code point is a "blank"
+ *
+ * @stable ICU 2.6
+ */
+U_STABLE UBool U_EXPORT2
+u_isblank(UChar32 c);
+
+/**
+ * Determines whether the specified code point is "defined",
+ * which usually means that it is assigned a character.
+ * True for general categories other than "Cn" (other, not assigned),
+ * i.e., true for all code points mentioned in UnicodeData.txt.
+ *
+ * Note that non-character code points (e.g., U+FDD0) are not "defined"
+ * (they are Cn), but surrogate code points are "defined" (Cs).
+ *
+ * Same as java.lang.Character.isDefined().
+ *
+ * @param c the code point to be tested
+ * @return TRUE if the code point is assigned a character
+ *
+ * @see u_isdigit
+ * @see u_isalpha
+ * @see u_isalnum
+ * @see u_isupper
+ * @see u_islower
+ * @see u_istitle
+ * @stable ICU 2.0
+ */
+U_STABLE UBool U_EXPORT2
+u_isdefined(UChar32 c);
+
+/**
+ * Determines if the specified character is a space character or not.
+ *
+ * Note: There are several ICU whitespace functions; please see the uchar.h
+ * file documentation for a detailed comparison.
+ *
+ * This is a C/POSIX migration function.
+ * See the comments about C/POSIX character classification functions in the
+ * documentation at the top of this header file.
+ *
+ * @param c    the character to be tested
+ * @return  true if the character is a space character; false otherwise.
+ *
+ * @see u_isJavaSpaceChar
+ * @see u_isWhitespace
+ * @see u_isUWhiteSpace
+ * @stable ICU 2.0
+ */
+U_STABLE UBool U_EXPORT2
+u_isspace(UChar32 c);
+
+/**
+ * Determine if the specified code point is a space character according to Java.
+ * True for characters with general categories "Z" (separators),
+ * which does not include control codes (e.g., TAB or Line Feed).
+ *
+ * Same as java.lang.Character.isSpaceChar().
+ *
+ * Note: There are several ICU whitespace functions; please see the uchar.h
+ * file documentation for a detailed comparison.
+ *
+ * @param c the code point to be tested
+ * @return TRUE if the code point is a space character according to Character.isSpaceChar()
+ *
+ * @see u_isspace
+ * @see u_isWhitespace
+ * @see u_isUWhiteSpace
+ * @stable ICU 2.6
+ */
+U_STABLE UBool U_EXPORT2
+u_isJavaSpaceChar(UChar32 c);
+
+/**
+ * Determines if the specified code point is a whitespace character according to Java/ICU.
+ * A character is considered to be a Java whitespace character if and only
+ * if it satisfies one of the following criteria:
+ *
+ * - It is a Unicode separator (categories "Z"), but is not
+ *      a no-break space (U+00A0 NBSP or U+2007 Figure Space or U+202F Narrow NBSP).
+ * - It is U+0009 HORIZONTAL TABULATION.
+ * - It is U+000A LINE FEED.
+ * - It is U+000B VERTICAL TABULATION.
+ * - It is U+000C FORM FEED.
+ * - It is U+000D CARRIAGE RETURN.
+ * - It is U+001C FILE SEPARATOR.
+ * - It is U+001D GROUP SEPARATOR.
+ * - It is U+001E RECORD SEPARATOR.
+ * - It is U+001F UNIT SEPARATOR.
+ * - It is U+0085 NEXT LINE.
+ *
+ * Same as java.lang.Character.isWhitespace() except that Java omits U+0085.
+ *
+ * Note: There are several ICU whitespace functions; please see the uchar.h
+ * file documentation for a detailed comparison.
+ *
+ * @param c the code point to be tested
+ * @return TRUE if the code point is a whitespace character according to Java/ICU
+ *
+ * @see u_isspace
+ * @see u_isJavaSpaceChar
+ * @see u_isUWhiteSpace
+ * @stable ICU 2.0
+ */
+U_STABLE UBool U_EXPORT2
+u_isWhitespace(UChar32 c);
+
+/**
+ * Determines whether the specified code point is a control character
+ * (as defined by this function).
+ * A control character is one of the following:
+ * - ISO 8-bit control character (U+0000..U+001f and U+007f..U+009f)
+ * - U_CONTROL_CHAR (Cc)
+ * - U_FORMAT_CHAR (Cf)
+ * - U_LINE_SEPARATOR (Zl)
+ * - U_PARAGRAPH_SEPARATOR (Zp)
+ *
+ * This is a C/POSIX migration function.
+ * See the comments about C/POSIX character classification functions in the
+ * documentation at the top of this header file.
+ *
+ * @param c the code point to be tested
+ * @return TRUE if the code point is a control character
+ *
+ * @see UCHAR_DEFAULT_IGNORABLE_CODE_POINT
+ * @see u_isprint
+ * @stable ICU 2.0
+ */
+U_STABLE UBool U_EXPORT2
+u_iscntrl(UChar32 c);
+
+/**
+ * Determines whether the specified code point is an ISO control code.
+ * True for U+0000..U+001f and U+007f..U+009f (general category "Cc").
+ *
+ * Same as java.lang.Character.isISOControl().
+ *
+ * @param c the code point to be tested
+ * @return TRUE if the code point is an ISO control code
+ *
+ * @see u_iscntrl
+ * @stable ICU 2.6
+ */
+U_STABLE UBool U_EXPORT2
+u_isISOControl(UChar32 c);
+
+/**
+ * Determines whether the specified code point is a printable character.
+ * True for general categories <em>other</em> than "C" (controls).
+ *
+ * This is a C/POSIX migration function.
+ * See the comments about C/POSIX character classification functions in the
+ * documentation at the top of this header file.
+ *
+ * @param c the code point to be tested
+ * @return TRUE if the code point is a printable character
+ *
+ * @see UCHAR_DEFAULT_IGNORABLE_CODE_POINT
+ * @see u_iscntrl
+ * @stable ICU 2.0
+ */
+U_STABLE UBool U_EXPORT2
+u_isprint(UChar32 c);
+
+/**
+ * Determines whether the specified code point is a base character.
+ * True for general categories "L" (letters), "N" (numbers),
+ * "Mc" (spacing combining marks), and "Me" (enclosing marks).
+ *
+ * Note that this is different from the Unicode definition in
+ * chapter 3.5, conformance clause D13,
+ * which defines base characters to be all characters (not Cn)
+ * that do not graphically combine with preceding characters (M)
+ * and that are neither control (Cc) or format (Cf) characters.
+ *
+ * @param c the code point to be tested
+ * @return TRUE if the code point is a base character according to this function
+ *
+ * @see u_isalpha
+ * @see u_isdigit
+ * @stable ICU 2.0
+ */
+U_STABLE UBool U_EXPORT2
+u_isbase(UChar32 c);
+
+/**
+ * Returns the bidirectional category value for the code point,
+ * which is used in the Unicode bidirectional algorithm
+ * (UAX #9 http://www.unicode.org/reports/tr9/).
+ * Note that some <em>unassigned</em> code points have bidi values
+ * of R or AL because they are in blocks that are reserved
+ * for Right-To-Left scripts.
+ *
+ * Same as java.lang.Character.getDirectionality()
+ *
+ * @param c the code point to be tested
+ * @return the bidirectional category (UCharDirection) value
+ *
+ * @see UCharDirection
+ * @stable ICU 2.0
+ */
+U_STABLE UCharDirection U_EXPORT2
+u_charDirection(UChar32 c);
+
+/**
+ * Determines whether the code point has the Bidi_Mirrored property.
+ * This property is set for characters that are commonly used in
+ * Right-To-Left contexts and need to be displayed with a "mirrored"
+ * glyph.
+ *
+ * Same as java.lang.Character.isMirrored().
+ * Same as UCHAR_BIDI_MIRRORED
+ *
+ * @param c the code point to be tested
+ * @return TRUE if the character has the Bidi_Mirrored property
+ *
+ * @see UCHAR_BIDI_MIRRORED
+ * @stable ICU 2.0
+ */
+U_STABLE UBool U_EXPORT2
+u_isMirrored(UChar32 c);
+
+/**
+ * Maps the specified character to a "mirror-image" character.
+ * For characters with the Bidi_Mirrored property, implementations
+ * sometimes need a "poor man's" mapping to another Unicode
+ * character (code point) such that the default glyph may serve
+ * as the mirror-image of the default glyph of the specified
+ * character. This is useful for text conversion to and from
+ * codepages with visual order, and for displays without glyph
+ * selecetion capabilities.
+ *
+ * @param c the code point to be mapped
+ * @return another Unicode code point that may serve as a mirror-image
+ *         substitute, or c itself if there is no such mapping or c
+ *         does not have the Bidi_Mirrored property
+ *
+ * @see UCHAR_BIDI_MIRRORED
+ * @see u_isMirrored
+ * @stable ICU 2.0
+ */
+U_STABLE UChar32 U_EXPORT2
+u_charMirror(UChar32 c);
+
+/**
+ * Returns the general category value for the code point.
+ *
+ * Same as java.lang.Character.getType().
+ *
+ * @param c the code point to be tested
+ * @return the general category (UCharCategory) value
+ *
+ * @see UCharCategory
+ * @stable ICU 2.0
+ */
+U_STABLE int8_t U_EXPORT2
+u_charType(UChar32 c);
+
+/**
+ * Get a single-bit bit set for the general category of a character.
+ * This bit set can be compared bitwise with U_GC_SM_MASK, U_GC_L_MASK, etc.
+ * Same as U_MASK(u_charType(c)).
+ *
+ * @param c the code point to be tested
+ * @return a single-bit mask corresponding to the general category (UCharCategory) value
+ *
+ * @see u_charType
+ * @see UCharCategory
+ * @see U_GC_CN_MASK
+ * @stable ICU 2.1
+ */
+#define U_GET_GC_MASK(c) U_MASK(u_charType(c))
+
+/**
+ * Callback from u_enumCharTypes(), is called for each contiguous range
+ * of code points c (where start<=c<limit)
+ * with the same Unicode general category ("character type").
+ *
+ * The callback function can stop the enumeration by returning FALSE.
+ *
+ * @param context an opaque pointer, as passed into utrie_enum()
+ * @param start the first code point in a contiguous range with value
+ * @param limit one past the last code point in a contiguous range with value
+ * @param type the general category for all code points in [start..limit[
+ * @return FALSE to stop the enumeration
+ *
+ * @stable ICU 2.1
+ * @see UCharCategory
+ * @see u_enumCharTypes
+ */
+typedef UBool U_CALLCONV
+UCharEnumTypeRange(const void *context, UChar32 start, UChar32 limit, UCharCategory type);
+
+/**
+ * Enumerate efficiently all code points with their Unicode general categories.
+ *
+ * This is useful for building data structures (e.g., UnicodeSet's),
+ * for enumerating all assigned code points (type!=U_UNASSIGNED), etc.
+ *
+ * For each contiguous range of code points with a given general category ("character type"),
+ * the UCharEnumTypeRange function is called.
+ * Adjacent ranges have different types.
+ * The Unicode Standard guarantees that the numeric value of the type is 0..31.
+ *
+ * @param enumRange a pointer to a function that is called for each contiguous range
+ *                  of code points with the same general category
+ * @param context an opaque pointer that is passed on to the callback function
+ *
+ * @stable ICU 2.1
+ * @see UCharCategory
+ * @see UCharEnumTypeRange
+ */
+U_STABLE void U_EXPORT2
+u_enumCharTypes(UCharEnumTypeRange *enumRange, const void *context);
+
+#if !UCONFIG_NO_NORMALIZATION
+
+/**
+ * Returns the combining class of the code point as specified in UnicodeData.txt.
+ *
+ * @param c the code point of the character
+ * @return the combining class of the character
+ * @stable ICU 2.0
+ */
+U_STABLE uint8_t U_EXPORT2
+u_getCombiningClass(UChar32 c);
+
+#endif
+
+/**
+ * Returns the decimal digit value of a decimal digit character.
+ * Such characters have the general category "Nd" (decimal digit numbers)
+ * and a Numeric_Type of Decimal.
+ *
+ * Unlike ICU releases before 2.6, no digit values are returned for any
+ * Han characters because Han number characters are often used with a special
+ * Chinese-style number format (with characters for powers of 10 in between)
+ * instead of in decimal-positional notation.
+ * Unicode 4 explicitly assigns Han number characters the Numeric_Type
+ * Numeric instead of Decimal.
+ * See Jitterbug 1483 for more details.
+ *
+ * Use u_getIntPropertyValue(c, UCHAR_NUMERIC_TYPE) and u_getNumericValue()
+ * for complete numeric Unicode properties.
+ *
+ * @param c the code point for which to get the decimal digit value
+ * @return the decimal digit value of c,
+ *         or -1 if c is not a decimal digit character
+ *
+ * @see u_getNumericValue
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+u_charDigitValue(UChar32 c);
+
+/**
+ * Returns the Unicode allocation block that contains the character.
+ *
+ * @param c the code point to be tested
+ * @return the block value (UBlockCode) for c
+ *
+ * @see UBlockCode
+ * @stable ICU 2.0
+ */
+U_STABLE UBlockCode U_EXPORT2
+ublock_getCode(UChar32 c);
+
+/**
+ * Retrieve the name of a Unicode character.
+ * Depending on <code>nameChoice</code>, the character name written
+ * into the buffer is the "modern" name or the name that was defined
+ * in Unicode version 1.0.
+ * The name contains only "invariant" characters
+ * like A-Z, 0-9, space, and '-'.
+ * Unicode 1.0 names are only retrieved if they are different from the modern
+ * names and if the data file contains the data for them. gennames may or may
+ * not be called with a command line option to include 1.0 names in unames.dat.
+ *
+ * @param code The character (code point) for which to get the name.
+ *             It must be <code>0<=code<=0x10ffff</code>.
+ * @param nameChoice Selector for which name to get.
+ * @param buffer Destination address for copying the name.
+ *               The name will always be zero-terminated.
+ *

<TRUNCATED>

[49/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_auth_cache.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_auth_cache.erl b/apps/couch/src/couch_auth_cache.erl
deleted file mode 100644
index 42ccd44..0000000
--- a/apps/couch/src/couch_auth_cache.erl
+++ /dev/null
@@ -1,425 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_auth_cache).
--behaviour(gen_server).
-
-% public API
--export([get_user_creds/1]).
-
-% gen_server API
--export([start_link/0, init/1, handle_call/3, handle_info/2, handle_cast/2]).
--export([code_change/3, terminate/2]).
-
--include("couch_db.hrl").
--include("couch_js_functions.hrl").
-
--define(STATE, auth_state_ets).
--define(BY_USER, auth_by_user_ets).
--define(BY_ATIME, auth_by_atime_ets).
-
--record(state, {
-    max_cache_size = 0,
-    cache_size = 0,
-    db_notifier = nil,
-    db_mon_ref = nil
-}).
-
-
--spec get_user_creds(UserName::string() | binary()) ->
-    Credentials::list() | nil.
-
-get_user_creds(UserName) when is_list(UserName) ->
-    get_user_creds(?l2b(UserName));
-
-get_user_creds(UserName) ->
-    UserCreds = case couch_config:get("admins", ?b2l(UserName)) of
-    "-hashed-" ++ HashedPwdAndSalt ->
-        % the name is an admin, now check to see if there is a user doc
-        % which has a matching name, salt, and password_sha
-        [HashedPwd, Salt] = string:tokens(HashedPwdAndSalt, ","),
-        case get_from_cache(UserName) of
-        nil ->
-            make_admin_doc(HashedPwd, Salt, []);
-        UserProps when is_list(UserProps) ->
-            make_admin_doc(HashedPwd, Salt, couch_util:get_value(<<"roles">>, UserProps))
-        end;
-    "-pbkdf2-" ++ HashedPwdSaltAndIterations ->
-        [HashedPwd, Salt, Iterations] = string:tokens(HashedPwdSaltAndIterations, ","),
-        case get_from_cache(UserName) of
-        nil ->
-            make_admin_doc(HashedPwd, Salt, Iterations, []);
-        UserProps when is_list(UserProps) ->
-            make_admin_doc(HashedPwd, Salt, Iterations, couch_util:get_value(<<"roles">>, UserProps))
-    end;
-    _Else ->
-        get_from_cache(UserName)
-    end,
-    validate_user_creds(UserCreds).
-
-make_admin_doc(HashedPwd, Salt, ExtraRoles) ->
-    [{<<"roles">>, [<<"_admin">>|ExtraRoles]},
-     {<<"salt">>, ?l2b(Salt)},
-     {<<"password_scheme">>, <<"simple">>},
-     {<<"password_sha">>, ?l2b(HashedPwd)}].
-
-make_admin_doc(DerivedKey, Salt, Iterations, ExtraRoles) ->
-    [{<<"roles">>, [<<"_admin">>|ExtraRoles]},
-     {<<"salt">>, ?l2b(Salt)},
-     {<<"iterations">>, list_to_integer(Iterations)},
-     {<<"password_scheme">>, <<"pbkdf2">>},
-     {<<"derived_key">>, ?l2b(DerivedKey)}].
-
-get_from_cache(UserName) ->
-    exec_if_auth_db(
-        fun(_AuthDb) ->
-            maybe_refresh_cache(),
-            case ets:lookup(?BY_USER, UserName) of
-            [] ->
-                gen_server:call(?MODULE, {fetch, UserName}, infinity);
-            [{UserName, {Credentials, _ATime}}] ->
-                couch_stats_collector:increment({couchdb, auth_cache_hits}),
-                gen_server:cast(?MODULE, {cache_hit, UserName}),
-                Credentials
-            end
-        end,
-        nil
-    ).
-
-
-validate_user_creds(nil) ->
-    nil;
-validate_user_creds(UserCreds) ->
-    case couch_util:get_value(<<"_conflicts">>, UserCreds) of
-    undefined ->
-        ok;
-    _ConflictList ->
-        throw({unauthorized,
-            <<"User document conflicts must be resolved before the document",
-              " is used for authentication purposes.">>
-        })
-    end,
-    UserCreds.
-
-
-start_link() ->
-    gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
-
-
-init(_) ->
-    ?STATE = ets:new(?STATE, [set, protected, named_table]),
-    ?BY_USER = ets:new(?BY_USER, [set, protected, named_table]),
-    ?BY_ATIME = ets:new(?BY_ATIME, [ordered_set, private, named_table]),
-    process_flag(trap_exit, true),
-    ok = couch_config:register(
-        fun("couch_httpd_auth", "auth_cache_size", SizeList) ->
-            Size = list_to_integer(SizeList),
-            ok = gen_server:call(?MODULE, {new_max_cache_size, Size}, infinity);
-        ("couch_httpd_auth", "authentication_db", _DbName) ->
-            ok = gen_server:call(?MODULE, reinit_cache, infinity)
-        end
-    ),
-    {ok, Notifier} = couch_db_update_notifier:start_link(fun handle_db_event/1),
-    State = #state{
-        db_notifier = Notifier,
-        max_cache_size = list_to_integer(
-            couch_config:get("couch_httpd_auth", "auth_cache_size", "50")
-        )
-    },
-    {ok, reinit_cache(State)}.
-
-
-handle_db_event({Event, DbName}) ->
-    [{auth_db_name, AuthDbName}] = ets:lookup(?STATE, auth_db_name),
-    case DbName =:= AuthDbName of
-    true ->
-        case Event of
-        created -> gen_server:call(?MODULE, reinit_cache, infinity);
-        compacted -> gen_server:call(?MODULE, auth_db_compacted, infinity);
-        _Else   -> ok
-        end;
-    false ->
-        ok
-    end.
-
-
-handle_call(reinit_cache, _From, State) ->
-    catch erlang:demonitor(State#state.db_mon_ref, [flush]),
-    exec_if_auth_db(fun(AuthDb) -> catch couch_db:close(AuthDb) end),
-    {reply, ok, reinit_cache(State)};
-
-handle_call(auth_db_compacted, _From, State) ->
-    exec_if_auth_db(
-        fun(AuthDb) ->
-            true = ets:insert(?STATE, {auth_db, reopen_auth_db(AuthDb)})
-        end
-    ),
-    {reply, ok, State};
-
-handle_call({new_max_cache_size, NewSize},
-        _From, #state{cache_size = Size} = State) when NewSize >= Size ->
-    {reply, ok, State#state{max_cache_size = NewSize}};
-
-handle_call({new_max_cache_size, NewSize}, _From, State) ->
-    free_mru_cache_entries(State#state.cache_size - NewSize),
-    {reply, ok, State#state{max_cache_size = NewSize, cache_size = NewSize}};
-
-handle_call({fetch, UserName}, _From, State) ->
-    {Credentials, NewState} = case ets:lookup(?BY_USER, UserName) of
-    [{UserName, {Creds, ATime}}] ->
-        couch_stats_collector:increment({couchdb, auth_cache_hits}),
-        cache_hit(UserName, Creds, ATime),
-        {Creds, State};
-    [] ->
-        couch_stats_collector:increment({couchdb, auth_cache_misses}),
-        Creds = get_user_props_from_db(UserName),
-        State1 = add_cache_entry(UserName, Creds, erlang:now(), State),
-        {Creds, State1}
-    end,
-    {reply, Credentials, NewState};
-
-handle_call(refresh, _From, State) ->
-    exec_if_auth_db(fun refresh_entries/1),
-    {reply, ok, State}.
-
-
-handle_cast({cache_hit, UserName}, State) ->
-    case ets:lookup(?BY_USER, UserName) of
-    [{UserName, {Credentials, ATime}}] ->
-        cache_hit(UserName, Credentials, ATime);
-    _ ->
-        ok
-    end,
-    {noreply, State}.
-
-
-handle_info({'DOWN', Ref, _, _, _Reason}, #state{db_mon_ref = Ref} = State) ->
-    {noreply, reinit_cache(State)}.
-
-
-terminate(_Reason, #state{db_notifier = Notifier}) ->
-    couch_db_update_notifier:stop(Notifier),
-    exec_if_auth_db(fun(AuthDb) -> catch couch_db:close(AuthDb) end),
-    true = ets:delete(?BY_USER),
-    true = ets:delete(?BY_ATIME),
-    true = ets:delete(?STATE).
-
-
-code_change(_OldVsn, State, _Extra) ->
-    {ok, State}.
-
-
-clear_cache(State) ->
-    exec_if_auth_db(fun(AuthDb) -> catch couch_db:close(AuthDb) end),
-    true = ets:delete_all_objects(?BY_USER),
-    true = ets:delete_all_objects(?BY_ATIME),
-    State#state{cache_size = 0}.
-
-
-reinit_cache(State) ->
-    NewState = clear_cache(State),
-    AuthDbName = ?l2b(couch_config:get("couch_httpd_auth", "authentication_db")),
-    true = ets:insert(?STATE, {auth_db_name, AuthDbName}),
-    AuthDb = open_auth_db(),
-    true = ets:insert(?STATE, {auth_db, AuthDb}),
-    NewState#state{db_mon_ref = couch_db:monitor(AuthDb)}.
-
-
-add_cache_entry(_, _, _, #state{max_cache_size = 0} = State) ->
-    State;
-add_cache_entry(UserName, Credentials, ATime, State) ->
-    case State#state.cache_size >= State#state.max_cache_size of
-    true ->
-        free_mru_cache_entry();
-    false ->
-        ok
-    end,
-    true = ets:insert(?BY_ATIME, {ATime, UserName}),
-    true = ets:insert(?BY_USER, {UserName, {Credentials, ATime}}),
-    State#state{cache_size = couch_util:get_value(size, ets:info(?BY_USER))}.
-
-free_mru_cache_entries(0) ->
-    ok;
-free_mru_cache_entries(N) when N > 0 ->
-    free_mru_cache_entry(),
-    free_mru_cache_entries(N - 1).
-
-free_mru_cache_entry() ->
-    MruTime = ets:last(?BY_ATIME),
-    [{MruTime, UserName}] = ets:lookup(?BY_ATIME, MruTime),
-    true = ets:delete(?BY_ATIME, MruTime),
-    true = ets:delete(?BY_USER, UserName).
-
-
-cache_hit(UserName, Credentials, ATime) ->
-    NewATime = erlang:now(),
-    true = ets:delete(?BY_ATIME, ATime),
-    true = ets:insert(?BY_ATIME, {NewATime, UserName}),
-    true = ets:insert(?BY_USER, {UserName, {Credentials, NewATime}}).
-
-
-refresh_entries(AuthDb) ->
-    case reopen_auth_db(AuthDb) of
-    nil ->
-        ok;
-    AuthDb2 ->
-        case AuthDb2#db.update_seq > AuthDb#db.update_seq of
-        true ->
-            {ok, _, _} = couch_db:enum_docs_since(
-                AuthDb2,
-                AuthDb#db.update_seq,
-                fun(DocInfo, _, _) -> refresh_entry(AuthDb2, DocInfo) end,
-                AuthDb#db.update_seq,
-                []
-            ),
-            true = ets:insert(?STATE, {auth_db, AuthDb2});
-        false ->
-            ok
-        end
-    end.
-
-
-refresh_entry(Db, #doc_info{high_seq = DocSeq} = DocInfo) ->
-    case is_user_doc(DocInfo) of
-    {true, UserName} ->
-        case ets:lookup(?BY_USER, UserName) of
-        [] ->
-            ok;
-        [{UserName, {_OldCreds, ATime}}] ->
-            {ok, Doc} = couch_db:open_doc(Db, DocInfo, [conflicts, deleted]),
-            NewCreds = user_creds(Doc),
-            true = ets:insert(?BY_USER, {UserName, {NewCreds, ATime}})
-        end;
-    false ->
-        ok
-    end,
-    {ok, DocSeq}.
-
-
-user_creds(#doc{deleted = true}) ->
-    nil;
-user_creds(#doc{} = Doc) ->
-    {Creds} = couch_doc:to_json_obj(Doc, []),
-    Creds.
-
-
-is_user_doc(#doc_info{id = <<"org.couchdb.user:", UserName/binary>>}) ->
-    {true, UserName};
-is_user_doc(_) ->
-    false.
-
-
-maybe_refresh_cache() ->
-    case cache_needs_refresh() of
-    true ->
-        ok = gen_server:call(?MODULE, refresh, infinity);
-    false ->
-        ok
-    end.
-
-
-cache_needs_refresh() ->
-    exec_if_auth_db(
-        fun(AuthDb) ->
-            case reopen_auth_db(AuthDb) of
-            nil ->
-                false;
-            AuthDb2 ->
-                AuthDb2#db.update_seq > AuthDb#db.update_seq
-            end
-        end,
-        false
-    ).
-
-
-reopen_auth_db(AuthDb) ->
-    case (catch couch_db:reopen(AuthDb)) of
-    {ok, AuthDb2} ->
-        AuthDb2;
-    _ ->
-        nil
-    end.
-
-
-exec_if_auth_db(Fun) ->
-    exec_if_auth_db(Fun, ok).
-
-exec_if_auth_db(Fun, DefRes) ->
-    case ets:lookup(?STATE, auth_db) of
-    [{auth_db, #db{} = AuthDb}] ->
-        Fun(AuthDb);
-    _ ->
-        DefRes
-    end.
-
-
-open_auth_db() ->
-    [{auth_db_name, DbName}] = ets:lookup(?STATE, auth_db_name),
-    {ok, AuthDb} = ensure_users_db_exists(DbName, [sys_db]),
-    AuthDb.
-
-
-get_user_props_from_db(UserName) ->
-    exec_if_auth_db(
-        fun(AuthDb) ->
-            Db = reopen_auth_db(AuthDb),
-            DocId = <<"org.couchdb.user:", UserName/binary>>,
-            try
-                {ok, Doc} = couch_db:open_doc(Db, DocId, [conflicts]),
-                {DocProps} = couch_doc:to_json_obj(Doc, []),
-                DocProps
-            catch
-            _:_Error ->
-                nil
-            end
-        end,
-        nil
-    ).
-
-ensure_users_db_exists(DbName, Options) ->
-    Options1 = [{user_ctx, #user_ctx{roles=[<<"_admin">>]}}, nologifmissing | Options],
-    case couch_db:open(DbName, Options1) of
-    {ok, Db} ->
-        ensure_auth_ddoc_exists(Db, <<"_design/_auth">>),
-        {ok, Db};
-    _Error ->
-        {ok, Db} = couch_db:create(DbName, Options1),
-        ok = ensure_auth_ddoc_exists(Db, <<"_design/_auth">>),
-        {ok, Db}
-    end.
-
-ensure_auth_ddoc_exists(Db, DDocId) ->
-    case couch_db:open_doc(Db, DDocId) of
-    {not_found, _Reason} ->
-        {ok, AuthDesign} = auth_design_doc(DDocId),
-        {ok, _Rev} = couch_db:update_doc(Db, AuthDesign, []);
-    {ok, Doc} ->
-        {Props} = couch_doc:to_json_obj(Doc, []),
-        case couch_util:get_value(<<"validate_doc_update">>, Props, []) of
-            ?AUTH_DB_DOC_VALIDATE_FUNCTION ->
-                ok;
-            _ ->
-                Props1 = lists:keyreplace(<<"validate_doc_update">>, 1, Props,
-                    {<<"validate_doc_update">>,
-                    ?AUTH_DB_DOC_VALIDATE_FUNCTION}),
-                couch_db:update_doc(Db, couch_doc:from_json_obj({Props1}), [])
-        end
-    end,
-    ok.
-
-auth_design_doc(DocId) ->
-    DocProps = [
-        {<<"_id">>, DocId},
-        {<<"language">>,<<"javascript">>},
-        {<<"validate_doc_update">>, ?AUTH_DB_DOC_VALIDATE_FUNCTION}
-    ],
-    {ok, couch_doc:from_json_obj({DocProps})}.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_btree.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_btree.erl b/apps/couch/src/couch_btree.erl
deleted file mode 100644
index 789819e..0000000
--- a/apps/couch/src/couch_btree.erl
+++ /dev/null
@@ -1,714 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_btree).
-
--export([open/2, open/3, query_modify/4, add/2, add_remove/3]).
--export([fold/4, full_reduce/1, final_reduce/2, size/1, foldl/3, foldl/4]).
--export([fold_reduce/4, lookup/2, get_state/1, set_options/2]).
--export([less/3]).
-
--include("couch_db.hrl").
--define(CHUNK_THRESHOLD, 16#4ff).
-
-extract(#btree{extract_kv=Extract}, Value) ->
-    Extract(Value).
-
-assemble(#btree{assemble_kv=Assemble}, Key, Value) ->
-    Assemble(Key, Value).
-
-less(#btree{less=Less}, A, B) ->
-    Less(A, B).
-
-% pass in 'nil' for State if a new Btree.
-open(State, Fd) ->
-    {ok, #btree{root=State, fd=Fd}}.
-
-set_options(Bt, []) ->
-    Bt;
-set_options(Bt, [{split, Extract}|Rest]) ->
-    set_options(Bt#btree{extract_kv=Extract}, Rest);
-set_options(Bt, [{join, Assemble}|Rest]) ->
-    set_options(Bt#btree{assemble_kv=Assemble}, Rest);
-set_options(Bt, [{less, Less}|Rest]) ->
-    set_options(Bt#btree{less=Less}, Rest);
-set_options(Bt, [{reduce, Reduce}|Rest]) ->
-    set_options(Bt#btree{reduce=Reduce}, Rest);
-set_options(Bt, [{compression, Comp}|Rest]) ->
-    set_options(Bt#btree{compression=Comp}, Rest).
-
-open(State, Fd, Options) ->
-    {ok, set_options(#btree{root=State, fd=Fd}, Options)}.
-
-get_state(#btree{root=Root}) ->
-    Root.
-
-final_reduce(#btree{reduce=Reduce}, Val) ->
-    final_reduce(Reduce, Val);
-final_reduce(Reduce, {[], []}) ->
-    Reduce(reduce, []);
-final_reduce(_Bt, {[], [Red]}) ->
-    Red;
-final_reduce(Reduce, {[], Reductions}) ->
-    Reduce(rereduce, Reductions);
-final_reduce(Reduce, {KVs, Reductions}) ->
-    Red = Reduce(reduce, KVs),
-    final_reduce(Reduce, {[], [Red | Reductions]}).
-
-fold_reduce(#btree{root=Root}=Bt, Fun, Acc, Options) ->
-    Dir = couch_util:get_value(dir, Options, fwd),
-    StartKey = couch_util:get_value(start_key, Options),
-    InEndRangeFun = make_key_in_end_range_function(Bt, Dir, Options),
-    KeyGroupFun = couch_util:get_value(key_group_fun, Options, fun(_,_) -> true end),
-    try
-        {ok, Acc2, GroupedRedsAcc2, GroupedKVsAcc2, GroupedKey2} =
-            reduce_stream_node(Bt, Dir, Root, StartKey, InEndRangeFun, undefined, [], [],
-            KeyGroupFun, Fun, Acc),
-        if GroupedKey2 == undefined ->
-            {ok, Acc2};
-        true ->
-            case Fun(GroupedKey2, {GroupedKVsAcc2, GroupedRedsAcc2}, Acc2) of
-            {ok, Acc3} -> {ok, Acc3};
-            {stop, Acc3} -> {ok, Acc3}
-            end
-        end
-    catch
-        throw:{stop, AccDone} -> {ok, AccDone}
-    end.
-
-full_reduce(#btree{root=nil,reduce=Reduce}) ->
-    {ok, Reduce(reduce, [])};
-full_reduce(#btree{root=Root}) ->
-    {ok, element(2, Root)}.
-
-size(#btree{root = nil}) ->
-    0;
-size(#btree{root = {_P, _Red}}) ->
-    % pre 1.2 format
-    nil;
-size(#btree{root = {_P, _Red, Size}}) ->
-    Size.
-
-% wraps a 2 arity function with the proper 3 arity function
-convert_fun_arity(Fun) when is_function(Fun, 2) ->
-    fun
-        (visit, KV, _Reds, AccIn) -> Fun(KV, AccIn);
-        (traverse, _K, _Red, AccIn) -> {ok, AccIn}
-    end;
-convert_fun_arity(Fun) when is_function(Fun, 3) ->
-    fun
-        (visit, KV, Reds, AccIn) -> Fun(KV, Reds, AccIn);
-        (traverse, _K, _Red, AccIn) -> {ok, AccIn}
-    end;
-convert_fun_arity(Fun) when is_function(Fun, 4) ->
-    Fun.    % Already arity 4
-
-make_key_in_end_range_function(#btree{less=Less}, fwd, Options) ->
-    case couch_util:get_value(end_key_gt, Options) of
-    undefined ->
-        case couch_util:get_value(end_key, Options) of
-        undefined ->
-            fun(_Key) -> true end;
-        LastKey ->
-            fun(Key) -> not Less(LastKey, Key) end
-        end;
-    EndKey ->
-        fun(Key) -> Less(Key, EndKey) end
-    end;
-make_key_in_end_range_function(#btree{less=Less}, rev, Options) ->
-    case couch_util:get_value(end_key_gt, Options) of
-    undefined ->
-        case couch_util:get_value(end_key, Options) of
-        undefined ->
-            fun(_Key) -> true end;
-        LastKey ->
-            fun(Key) -> not Less(Key, LastKey) end
-        end;
-    EndKey ->
-        fun(Key) -> Less(EndKey, Key) end
-    end.
-
-
-foldl(Bt, Fun, Acc) ->
-    fold(Bt, Fun, Acc, []).
-
-foldl(Bt, Fun, Acc, Options) ->
-    fold(Bt, Fun, Acc, Options).
-
-
-fold(#btree{root=nil}, _Fun, Acc, _Options) ->
-    {ok, {[], []}, Acc};
-fold(#btree{root=Root}=Bt, Fun, Acc, Options) ->
-    Dir = couch_util:get_value(dir, Options, fwd),
-    InRange = make_key_in_end_range_function(Bt, Dir, Options),
-    Result =
-    case couch_util:get_value(start_key, Options) of
-    undefined ->
-        stream_node(Bt, [], Bt#btree.root, InRange, Dir,
-                convert_fun_arity(Fun), Acc);
-    StartKey ->
-        stream_node(Bt, [], Bt#btree.root, StartKey, InRange, Dir,
-                convert_fun_arity(Fun), Acc)
-    end,
-    case Result of
-    {ok, Acc2}->
-        FullReduction = element(2, Root),
-        {ok, {[], [FullReduction]}, Acc2};
-    {stop, LastReduction, Acc2} ->
-        {ok, LastReduction, Acc2}
-    end.
-
-add(Bt, InsertKeyValues) ->
-    add_remove(Bt, InsertKeyValues, []).
-
-add_remove(Bt, InsertKeyValues, RemoveKeys) ->
-    {ok, [], Bt2} = query_modify(Bt, [], InsertKeyValues, RemoveKeys),
-    {ok, Bt2}.
-
-query_modify(Bt, LookupKeys, InsertValues, RemoveKeys) ->
-    #btree{root=Root} = Bt,
-    InsertActions = lists:map(
-        fun(KeyValue) ->
-            {Key, Value} = extract(Bt, KeyValue),
-            {insert, Key, Value}
-        end, InsertValues),
-    RemoveActions = [{remove, Key, nil} || Key <- RemoveKeys],
-    FetchActions = [{fetch, Key, nil} || Key <- LookupKeys],
-    SortFun =
-        fun({OpA, A, _}, {OpB, B, _}) ->
-            case A == B of
-            % A and B are equal, sort by op.
-            true -> op_order(OpA) < op_order(OpB);
-            false ->
-                less(Bt, A, B)
-            end
-        end,
-    Actions = lists:sort(SortFun, lists:append([InsertActions, RemoveActions, FetchActions])),
-    {ok, KeyPointers, QueryResults} = modify_node(Bt, Root, Actions, []),
-    {ok, NewRoot} = complete_root(Bt, KeyPointers),
-    {ok, QueryResults, Bt#btree{root=NewRoot}}.
-
-% for ordering different operations with the same key.
-% fetch < remove < insert
-op_order(fetch) -> 1;
-op_order(remove) -> 2;
-op_order(insert) -> 3.
-
-lookup(#btree{root=Root, less=Less}=Bt, Keys) ->
-    SortedKeys = lists:sort(Less, Keys),
-    {ok, SortedResults} = lookup(Bt, Root, SortedKeys),
-    % We want to return the results in the same order as the keys were input
-    % but we may have changed the order when we sorted. So we need to put the
-    % order back into the results.
-    couch_util:reorder_results(Keys, SortedResults).
-
-lookup(_Bt, nil, Keys) ->
-    {ok, [{Key, not_found} || Key <- Keys]};
-lookup(Bt, Node, Keys) ->
-    Pointer = element(1, Node),
-    {NodeType, NodeList} = get_node(Bt, Pointer),
-    case NodeType of
-    kp_node ->
-        lookup_kpnode(Bt, list_to_tuple(NodeList), 1, Keys, []);
-    kv_node ->
-        lookup_kvnode(Bt, list_to_tuple(NodeList), 1, Keys, [])
-    end.
-
-lookup_kpnode(_Bt, _NodeTuple, _LowerBound, [], Output) ->
-    {ok, lists:reverse(Output)};
-lookup_kpnode(_Bt, NodeTuple, LowerBound, Keys, Output) when tuple_size(NodeTuple) < LowerBound ->
-    {ok, lists:reverse(Output, [{Key, not_found} || Key <- Keys])};
-lookup_kpnode(Bt, NodeTuple, LowerBound, [FirstLookupKey | _] = LookupKeys, Output) ->
-    N = find_first_gteq(Bt, NodeTuple, LowerBound, tuple_size(NodeTuple), FirstLookupKey),
-    {Key, PointerInfo} = element(N, NodeTuple),
-    SplitFun = fun(LookupKey) -> not less(Bt, Key, LookupKey) end,
-    case lists:splitwith(SplitFun, LookupKeys) of
-    {[], GreaterQueries} ->
-        lookup_kpnode(Bt, NodeTuple, N + 1, GreaterQueries, Output);
-    {LessEqQueries, GreaterQueries} ->
-        {ok, Results} = lookup(Bt, PointerInfo, LessEqQueries),
-        lookup_kpnode(Bt, NodeTuple, N + 1, GreaterQueries, lists:reverse(Results, Output))
-    end.
-
-
-lookup_kvnode(_Bt, _NodeTuple, _LowerBound, [], Output) ->
-    {ok, lists:reverse(Output)};
-lookup_kvnode(_Bt, NodeTuple, LowerBound, Keys, Output) when tuple_size(NodeTuple) < LowerBound ->
-    % keys not found
-    {ok, lists:reverse(Output, [{Key, not_found} || Key <- Keys])};
-lookup_kvnode(Bt, NodeTuple, LowerBound, [LookupKey | RestLookupKeys], Output) ->
-    N = find_first_gteq(Bt, NodeTuple, LowerBound, tuple_size(NodeTuple), LookupKey),
-    {Key, Value} = element(N, NodeTuple),
-    case less(Bt, LookupKey, Key) of
-    true ->
-        % LookupKey is less than Key
-        lookup_kvnode(Bt, NodeTuple, N, RestLookupKeys, [{LookupKey, not_found} | Output]);
-    false ->
-        case less(Bt, Key, LookupKey) of
-        true ->
-            % LookupKey is greater than Key
-            lookup_kvnode(Bt, NodeTuple, N+1, RestLookupKeys, [{LookupKey, not_found} | Output]);
-        false ->
-            % LookupKey is equal to Key
-            lookup_kvnode(Bt, NodeTuple, N, RestLookupKeys, [{LookupKey, {ok, assemble(Bt, LookupKey, Value)}} | Output])
-        end
-    end.
-
-
-complete_root(_Bt, []) ->
-    {ok, nil};
-complete_root(_Bt, [{_Key, PointerInfo}])->
-    {ok, PointerInfo};
-complete_root(Bt, KPs) ->
-    {ok, ResultKeyPointers} = write_node(Bt, kp_node, KPs),
-    complete_root(Bt, ResultKeyPointers).
-
-%%%%%%%%%%%%% The chunkify function sucks! %%%%%%%%%%%%%
-% It is inaccurate as it does not account for compression when blocks are
-% written. Plus with the "case byte_size(term_to_binary(InList)) of" code
-% it's probably really inefficient.
-
-chunkify(InList) ->
-    case ?term_size(InList) of
-    Size when Size > ?CHUNK_THRESHOLD ->
-        NumberOfChunksLikely = ((Size div ?CHUNK_THRESHOLD) + 1),
-        ChunkThreshold = Size div NumberOfChunksLikely,
-        chunkify(InList, ChunkThreshold, [], 0, []);
-    _Else ->
-        [InList]
-    end.
-
-chunkify([], _ChunkThreshold, [], 0, OutputChunks) ->
-    lists:reverse(OutputChunks);
-chunkify([], _ChunkThreshold, OutList, _OutListSize, OutputChunks) ->
-    lists:reverse([lists:reverse(OutList) | OutputChunks]);
-chunkify([InElement | RestInList], ChunkThreshold, OutList, OutListSize, OutputChunks) ->
-    case ?term_size(InElement) of
-    Size when (Size + OutListSize) > ChunkThreshold andalso OutList /= [] ->
-        chunkify(RestInList, ChunkThreshold, [], 0, [lists:reverse([InElement | OutList]) | OutputChunks]);
-    Size ->
-        chunkify(RestInList, ChunkThreshold, [InElement | OutList], OutListSize + Size, OutputChunks)
-    end.
-
-modify_node(Bt, RootPointerInfo, Actions, QueryOutput) ->
-    case RootPointerInfo of
-    nil ->
-        NodeType = kv_node,
-        NodeList = [];
-    _Tuple ->
-        Pointer = element(1, RootPointerInfo),
-        {NodeType, NodeList} = get_node(Bt, Pointer)
-    end,
-    NodeTuple = list_to_tuple(NodeList),
-
-    {ok, NewNodeList, QueryOutput2} =
-    case NodeType of
-    kp_node -> modify_kpnode(Bt, NodeTuple, 1, Actions, [], QueryOutput);
-    kv_node -> modify_kvnode(Bt, NodeTuple, 1, Actions, [], QueryOutput)
-    end,
-    case NewNodeList of
-    [] ->  % no nodes remain
-        {ok, [], QueryOutput2};
-    NodeList ->  % nothing changed
-        {LastKey, _LastValue} = element(tuple_size(NodeTuple), NodeTuple),
-        {ok, [{LastKey, RootPointerInfo}], QueryOutput2};
-    _Else2 ->
-        {ok, ResultList} = write_node(Bt, NodeType, NewNodeList),
-        {ok, ResultList, QueryOutput2}
-    end.
-
-reduce_node(#btree{reduce=nil}, _NodeType, _NodeList) ->
-    [];
-reduce_node(#btree{reduce=R}, kp_node, NodeList) ->
-    R(rereduce, [element(2, Node) || {_K, Node} <- NodeList]);
-reduce_node(#btree{reduce=R}=Bt, kv_node, NodeList) ->
-    R(reduce, [assemble(Bt, K, V) || {K, V} <- NodeList]).
-
-reduce_tree_size(kv_node, NodeSize, _KvList) ->
-    NodeSize;
-reduce_tree_size(kp_node, NodeSize, []) ->
-    NodeSize;
-reduce_tree_size(kp_node, _NodeSize, [{_K, {_P, _Red}} | _]) ->
-    % pre 1.2 format
-    nil;
-reduce_tree_size(kp_node, _NodeSize, [{_K, {_P, _Red, nil}} | _]) ->
-    nil;
-reduce_tree_size(kp_node, NodeSize, [{_K, {_P, _Red, Sz}} | NodeList]) ->
-    reduce_tree_size(kp_node, NodeSize + Sz, NodeList).
-
-get_node(#btree{fd = Fd}, NodePos) ->
-    {ok, {NodeType, NodeList}} = couch_file:pread_term(Fd, NodePos),
-    {NodeType, NodeList}.
-
-write_node(#btree{fd = Fd, compression = Comp} = Bt, NodeType, NodeList) ->
-    % split up nodes into smaller sizes
-    NodeListList = chunkify(NodeList),
-    % now write out each chunk and return the KeyPointer pairs for those nodes
-    ResultList = [
-        begin
-            {ok, Pointer, Size} = couch_file:append_term(
-                Fd, {NodeType, ANodeList}, [{compression, Comp}]),
-            {LastKey, _} = lists:last(ANodeList),
-            SubTreeSize = reduce_tree_size(NodeType, Size, ANodeList),
-            {LastKey, {Pointer, reduce_node(Bt, NodeType, ANodeList), SubTreeSize}}
-        end
-    ||
-        ANodeList <- NodeListList
-    ],
-    {ok, ResultList}.
-
-modify_kpnode(Bt, {}, _LowerBound, Actions, [], QueryOutput) ->
-    modify_node(Bt, nil, Actions, QueryOutput);
-modify_kpnode(_Bt, NodeTuple, LowerBound, [], ResultNode, QueryOutput) ->
-    {ok, lists:reverse(ResultNode, bounded_tuple_to_list(NodeTuple, LowerBound,
-            tuple_size(NodeTuple), [])), QueryOutput};
-modify_kpnode(Bt, NodeTuple, LowerBound,
-        [{_, FirstActionKey, _}|_]=Actions, ResultNode, QueryOutput) ->
-    Sz = tuple_size(NodeTuple),
-    N = find_first_gteq(Bt, NodeTuple, LowerBound, Sz, FirstActionKey),
-    case N =:= Sz of
-    true  ->
-        % perform remaining actions on last node
-        {_, PointerInfo} = element(Sz, NodeTuple),
-        {ok, ChildKPs, QueryOutput2} =
-            modify_node(Bt, PointerInfo, Actions, QueryOutput),
-        NodeList = lists:reverse(ResultNode, bounded_tuple_to_list(NodeTuple, LowerBound,
-            Sz - 1, ChildKPs)),
-        {ok, NodeList, QueryOutput2};
-    false ->
-        {NodeKey, PointerInfo} = element(N, NodeTuple),
-        SplitFun = fun({_ActionType, ActionKey, _ActionValue}) ->
-                not less(Bt, NodeKey, ActionKey)
-            end,
-        {LessEqQueries, GreaterQueries} = lists:splitwith(SplitFun, Actions),
-        {ok, ChildKPs, QueryOutput2} =
-                modify_node(Bt, PointerInfo, LessEqQueries, QueryOutput),
-        ResultNode2 = lists:reverse(ChildKPs, bounded_tuple_to_revlist(NodeTuple,
-                LowerBound, N - 1, ResultNode)),
-        modify_kpnode(Bt, NodeTuple, N+1, GreaterQueries, ResultNode2, QueryOutput2)
-    end.
-
-bounded_tuple_to_revlist(_Tuple, Start, End, Tail) when Start > End ->
-    Tail;
-bounded_tuple_to_revlist(Tuple, Start, End, Tail) ->
-    bounded_tuple_to_revlist(Tuple, Start+1, End, [element(Start, Tuple)|Tail]).
-
-bounded_tuple_to_list(Tuple, Start, End, Tail) ->
-    bounded_tuple_to_list2(Tuple, Start, End, [], Tail).
-
-bounded_tuple_to_list2(_Tuple, Start, End, Acc, Tail) when Start > End ->
-    lists:reverse(Acc, Tail);
-bounded_tuple_to_list2(Tuple, Start, End, Acc, Tail) ->
-    bounded_tuple_to_list2(Tuple, Start + 1, End, [element(Start, Tuple) | Acc], Tail).
-
-find_first_gteq(_Bt, _Tuple, Start, End, _Key) when Start == End ->
-    End;
-find_first_gteq(Bt, Tuple, Start, End, Key) ->
-    Mid = Start + ((End - Start) div 2),
-    {TupleKey, _} = element(Mid, Tuple),
-    case less(Bt, TupleKey, Key) of
-    true ->
-        find_first_gteq(Bt, Tuple, Mid+1, End, Key);
-    false ->
-        find_first_gteq(Bt, Tuple, Start, Mid, Key)
-    end.
-
-modify_kvnode(_Bt, NodeTuple, LowerBound, [], ResultNode, QueryOutput) ->
-    {ok, lists:reverse(ResultNode, bounded_tuple_to_list(NodeTuple, LowerBound, tuple_size(NodeTuple), [])), QueryOutput};
-modify_kvnode(Bt, NodeTuple, LowerBound, [{ActionType, ActionKey, ActionValue} | RestActions], ResultNode, QueryOutput) when LowerBound > tuple_size(NodeTuple) ->
-    case ActionType of
-    insert ->
-        modify_kvnode(Bt, NodeTuple, LowerBound, RestActions, [{ActionKey, ActionValue} | ResultNode], QueryOutput);
-    remove ->
-        % just drop the action
-        modify_kvnode(Bt, NodeTuple, LowerBound, RestActions, ResultNode, QueryOutput);
-    fetch ->
-        % the key/value must not exist in the tree
-        modify_kvnode(Bt, NodeTuple, LowerBound, RestActions, ResultNode, [{not_found, {ActionKey, nil}} | QueryOutput])
-    end;
-modify_kvnode(Bt, NodeTuple, LowerBound, [{ActionType, ActionKey, ActionValue} | RestActions], AccNode, QueryOutput) ->
-    N = find_first_gteq(Bt, NodeTuple, LowerBound, tuple_size(NodeTuple), ActionKey),
-    {Key, Value} = element(N, NodeTuple),
-    ResultNode =  bounded_tuple_to_revlist(NodeTuple, LowerBound, N - 1, AccNode),
-    case less(Bt, ActionKey, Key) of
-    true ->
-        case ActionType of
-        insert ->
-            % ActionKey is less than the Key, so insert
-            modify_kvnode(Bt, NodeTuple, N, RestActions, [{ActionKey, ActionValue} | ResultNode], QueryOutput);
-        remove ->
-            % ActionKey is less than the Key, just drop the action
-            modify_kvnode(Bt, NodeTuple, N, RestActions, ResultNode, QueryOutput);
-        fetch ->
-            % ActionKey is less than the Key, the key/value must not exist in the tree
-            modify_kvnode(Bt, NodeTuple, N, RestActions, ResultNode, [{not_found, {ActionKey, nil}} | QueryOutput])
-        end;
-    false ->
-        % ActionKey and Key are maybe equal.
-        case less(Bt, Key, ActionKey) of
-        false ->
-            case ActionType of
-            insert ->
-                modify_kvnode(Bt, NodeTuple, N+1, RestActions, [{ActionKey, ActionValue} | ResultNode], QueryOutput);
-            remove ->
-                modify_kvnode(Bt, NodeTuple, N+1, RestActions, ResultNode, QueryOutput);
-            fetch ->
-                % ActionKey is equal to the Key, insert into the QueryOuput, but re-process the node
-                % since an identical action key can follow it.
-                modify_kvnode(Bt, NodeTuple, N, RestActions, ResultNode, [{ok, assemble(Bt, Key, Value)} | QueryOutput])
-            end;
-        true ->
-            modify_kvnode(Bt, NodeTuple, N + 1, [{ActionType, ActionKey, ActionValue} | RestActions], [{Key, Value} | ResultNode], QueryOutput)
-        end
-    end.
-
-
-reduce_stream_node(_Bt, _Dir, nil, _KeyStart, _InEndRangeFun, GroupedKey, GroupedKVsAcc,
-        GroupedRedsAcc, _KeyGroupFun, _Fun, Acc) ->
-    {ok, Acc, GroupedRedsAcc, GroupedKVsAcc, GroupedKey};
-reduce_stream_node(Bt, Dir, Node, KeyStart, InEndRangeFun, GroupedKey, GroupedKVsAcc,
-        GroupedRedsAcc, KeyGroupFun, Fun, Acc) ->
-    P = element(1, Node),
-    case get_node(Bt, P) of
-    {kp_node, NodeList} ->
-        NodeList2 = adjust_dir(Dir, NodeList),
-        reduce_stream_kp_node(Bt, Dir, NodeList2, KeyStart, InEndRangeFun, GroupedKey,
-                GroupedKVsAcc, GroupedRedsAcc, KeyGroupFun, Fun, Acc);
-    {kv_node, KVs} ->
-        KVs2 = adjust_dir(Dir, KVs),
-        reduce_stream_kv_node(Bt, Dir, KVs2, KeyStart, InEndRangeFun, GroupedKey,
-                GroupedKVsAcc, GroupedRedsAcc, KeyGroupFun, Fun, Acc)
-    end.
-
-reduce_stream_kv_node(Bt, Dir, KVs, KeyStart, InEndRangeFun,
-                        GroupedKey, GroupedKVsAcc, GroupedRedsAcc,
-                        KeyGroupFun, Fun, Acc) ->
-
-    GTEKeyStartKVs =
-    case KeyStart of
-    undefined ->
-        KVs;
-    _ ->
-        DropFun = case Dir of
-        fwd ->
-            fun({Key, _}) -> less(Bt, Key, KeyStart) end;
-        rev ->
-            fun({Key, _}) -> less(Bt, KeyStart, Key) end
-        end,
-        lists:dropwhile(DropFun, KVs)
-    end,
-    KVs2 = lists:takewhile(
-        fun({Key, _}) -> InEndRangeFun(Key) end, GTEKeyStartKVs),
-    reduce_stream_kv_node2(Bt, KVs2, GroupedKey, GroupedKVsAcc, GroupedRedsAcc,
-                        KeyGroupFun, Fun, Acc).
-
-
-reduce_stream_kv_node2(_Bt, [], GroupedKey, GroupedKVsAcc, GroupedRedsAcc,
-        _KeyGroupFun, _Fun, Acc) ->
-    {ok, Acc, GroupedRedsAcc, GroupedKVsAcc, GroupedKey};
-reduce_stream_kv_node2(Bt, [{Key, Value}| RestKVs], GroupedKey, GroupedKVsAcc,
-        GroupedRedsAcc, KeyGroupFun, Fun, Acc) ->
-    case GroupedKey of
-    undefined ->
-        reduce_stream_kv_node2(Bt, RestKVs, Key,
-                [assemble(Bt,Key,Value)], [], KeyGroupFun, Fun, Acc);
-    _ ->
-
-        case KeyGroupFun(GroupedKey, Key) of
-        true ->
-            reduce_stream_kv_node2(Bt, RestKVs, GroupedKey,
-                [assemble(Bt,Key,Value)|GroupedKVsAcc], GroupedRedsAcc, KeyGroupFun,
-                Fun, Acc);
-        false ->
-            case Fun(GroupedKey, {GroupedKVsAcc, GroupedRedsAcc}, Acc) of
-            {ok, Acc2} ->
-                reduce_stream_kv_node2(Bt, RestKVs, Key, [assemble(Bt,Key,Value)],
-                    [], KeyGroupFun, Fun, Acc2);
-            {stop, Acc2} ->
-                throw({stop, Acc2})
-            end
-        end
-    end.
-
-reduce_stream_kp_node(Bt, Dir, NodeList, KeyStart, InEndRangeFun,
-                        GroupedKey, GroupedKVsAcc, GroupedRedsAcc,
-                        KeyGroupFun, Fun, Acc) ->
-    Nodes =
-    case KeyStart of
-    undefined ->
-        NodeList;
-    _ ->
-        case Dir of
-        fwd ->
-            lists:dropwhile(fun({Key, _}) -> less(Bt, Key, KeyStart) end, NodeList);
-        rev ->
-            RevKPs = lists:reverse(NodeList),
-            case lists:splitwith(fun({Key, _}) -> less(Bt, Key, KeyStart) end, RevKPs) of
-            {_Before, []} ->
-                NodeList;
-            {Before, [FirstAfter | _]} ->
-                [FirstAfter | lists:reverse(Before)]
-            end
-        end
-    end,
-    {InRange, MaybeInRange} = lists:splitwith(
-        fun({Key, _}) -> InEndRangeFun(Key) end, Nodes),
-    NodesInRange = case MaybeInRange of
-    [FirstMaybeInRange | _] when Dir =:= fwd ->
-        InRange ++ [FirstMaybeInRange];
-    _ ->
-        InRange
-    end,
-    reduce_stream_kp_node2(Bt, Dir, NodesInRange, KeyStart, InEndRangeFun,
-        GroupedKey, GroupedKVsAcc, GroupedRedsAcc, KeyGroupFun, Fun, Acc).
-
-
-reduce_stream_kp_node2(Bt, Dir, [{_Key, NodeInfo} | RestNodeList], KeyStart, InEndRangeFun,
-                        undefined, [], [], KeyGroupFun, Fun, Acc) ->
-    {ok, Acc2, GroupedRedsAcc2, GroupedKVsAcc2, GroupedKey2} =
-            reduce_stream_node(Bt, Dir, NodeInfo, KeyStart, InEndRangeFun, undefined,
-                [], [], KeyGroupFun, Fun, Acc),
-    reduce_stream_kp_node2(Bt, Dir, RestNodeList, KeyStart, InEndRangeFun, GroupedKey2,
-            GroupedKVsAcc2, GroupedRedsAcc2, KeyGroupFun, Fun, Acc2);
-reduce_stream_kp_node2(Bt, Dir, NodeList, KeyStart, InEndRangeFun,
-        GroupedKey, GroupedKVsAcc, GroupedRedsAcc, KeyGroupFun, Fun, Acc) ->
-    {Grouped0, Ungrouped0} = lists:splitwith(fun({Key,_}) ->
-        KeyGroupFun(GroupedKey, Key) end, NodeList),
-    {GroupedNodes, UngroupedNodes} =
-    case Grouped0 of
-    [] ->
-        {Grouped0, Ungrouped0};
-    _ ->
-        [FirstGrouped | RestGrouped] = lists:reverse(Grouped0),
-        {RestGrouped, [FirstGrouped | Ungrouped0]}
-    end,
-    GroupedReds = [element(2, Node) || {_, Node} <- GroupedNodes],
-    case UngroupedNodes of
-    [{_Key, NodeInfo}|RestNodes] ->
-        {ok, Acc2, GroupedRedsAcc2, GroupedKVsAcc2, GroupedKey2} =
-            reduce_stream_node(Bt, Dir, NodeInfo, KeyStart, InEndRangeFun, GroupedKey,
-                GroupedKVsAcc, GroupedReds ++ GroupedRedsAcc, KeyGroupFun, Fun, Acc),
-        reduce_stream_kp_node2(Bt, Dir, RestNodes, KeyStart, InEndRangeFun, GroupedKey2,
-                GroupedKVsAcc2, GroupedRedsAcc2, KeyGroupFun, Fun, Acc2);
-    [] ->
-        {ok, Acc, GroupedReds ++ GroupedRedsAcc, GroupedKVsAcc, GroupedKey}
-    end.
-
-adjust_dir(fwd, List) ->
-    List;
-adjust_dir(rev, List) ->
-    lists:reverse(List).
-
-stream_node(Bt, Reds, Node, StartKey, InRange, Dir, Fun, Acc) ->
-    Pointer = element(1, Node),
-    {NodeType, NodeList} = get_node(Bt, Pointer),
-    case NodeType of
-    kp_node ->
-        stream_kp_node(Bt, Reds, adjust_dir(Dir, NodeList), StartKey, InRange, Dir, Fun, Acc);
-    kv_node ->
-        stream_kv_node(Bt, Reds, adjust_dir(Dir, NodeList), StartKey, InRange, Dir, Fun, Acc)
-    end.
-
-stream_node(Bt, Reds, Node, InRange, Dir, Fun, Acc) ->
-    Pointer = element(1, Node),
-    {NodeType, NodeList} = get_node(Bt, Pointer),
-    case NodeType of
-    kp_node ->
-        stream_kp_node(Bt, Reds, adjust_dir(Dir, NodeList), InRange, Dir, Fun, Acc);
-    kv_node ->
-        stream_kv_node2(Bt, Reds, [], adjust_dir(Dir, NodeList), InRange, Dir, Fun, Acc)
-    end.
-
-stream_kp_node(_Bt, _Reds, [], _InRange, _Dir, _Fun, Acc) ->
-    {ok, Acc};
-stream_kp_node(Bt, Reds, [{Key, Node} | Rest], InRange, Dir, Fun, Acc) ->
-    Red = element(2, Node),
-    case Fun(traverse, Key, Red, Acc) of
-    {ok, Acc2} ->
-        case stream_node(Bt, Reds, Node, InRange, Dir, Fun, Acc2) of
-        {ok, Acc3} ->
-            stream_kp_node(Bt, [Red | Reds], Rest, InRange, Dir, Fun, Acc3);
-        {stop, LastReds, Acc3} ->
-            {stop, LastReds, Acc3}
-        end;
-    {skip, Acc2} ->
-        stream_kp_node(Bt, [Red | Reds], Rest, InRange, Dir, Fun, Acc2)
-    end.
-
-drop_nodes(_Bt, Reds, _StartKey, []) ->
-    {Reds, []};
-drop_nodes(Bt, Reds, StartKey, [{NodeKey, Node} | RestKPs]) ->
-    case less(Bt, NodeKey, StartKey) of
-    true ->
-        drop_nodes(Bt, [element(2, Node) | Reds], StartKey, RestKPs);
-    false ->
-        {Reds, [{NodeKey, Node} | RestKPs]}
-    end.
-
-stream_kp_node(Bt, Reds, KPs, StartKey, InRange, Dir, Fun, Acc) ->
-    {NewReds, NodesToStream} =
-    case Dir of
-    fwd ->
-        % drop all nodes sorting before the key
-        drop_nodes(Bt, Reds, StartKey, KPs);
-    rev ->
-        % keep all nodes sorting before the key, AND the first node to sort after
-        RevKPs = lists:reverse(KPs),
-         case lists:splitwith(fun({Key, _Pointer}) -> less(Bt, Key, StartKey) end, RevKPs) of
-        {_RevsBefore, []} ->
-            % everything sorts before it
-            {Reds, KPs};
-        {RevBefore, [FirstAfter | Drop]} ->
-            {[element(2, Node) || {_K, Node} <- Drop] ++ Reds,
-                 [FirstAfter | lists:reverse(RevBefore)]}
-        end
-    end,
-    case NodesToStream of
-    [] ->
-        {ok, Acc};
-    [{_Key, Node} | Rest] ->
-        case stream_node(Bt, NewReds, Node, StartKey, InRange, Dir, Fun, Acc) of
-        {ok, Acc2} ->
-            Red = element(2, Node),
-            stream_kp_node(Bt, [Red | NewReds], Rest, InRange, Dir, Fun, Acc2);
-        {stop, LastReds, Acc2} ->
-            {stop, LastReds, Acc2}
-        end
-    end.
-
-stream_kv_node(Bt, Reds, KVs, StartKey, InRange, Dir, Fun, Acc) ->
-    DropFun =
-    case Dir of
-    fwd ->
-        fun({Key, _}) -> less(Bt, Key, StartKey) end;
-    rev ->
-        fun({Key, _}) -> less(Bt, StartKey, Key) end
-    end,
-    {LTKVs, GTEKVs} = lists:splitwith(DropFun, KVs),
-    AssembleLTKVs = [assemble(Bt,K,V) || {K,V} <- LTKVs],
-    stream_kv_node2(Bt, Reds, AssembleLTKVs, GTEKVs, InRange, Dir, Fun, Acc).
-
-stream_kv_node2(_Bt, _Reds, _PrevKVs, [], _InRange, _Dir, _Fun, Acc) ->
-    {ok, Acc};
-stream_kv_node2(Bt, Reds, PrevKVs, [{K,V} | RestKVs], InRange, Dir, Fun, Acc) ->
-    case InRange(K) of
-    false ->
-        {stop, {PrevKVs, Reds}, Acc};
-    true ->
-        AssembledKV = assemble(Bt, K, V),
-        case Fun(visit, AssembledKV, {PrevKVs, Reds}, Acc) of
-        {ok, Acc2} ->
-            stream_kv_node2(Bt, Reds, [AssembledKV | PrevKVs], RestKVs, InRange, Dir, Fun, Acc2);
-        {stop, Acc2} ->
-            {stop, {PrevKVs, Reds}, Acc2}
-        end
-    end.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_changes.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_changes.erl b/apps/couch/src/couch_changes.erl
deleted file mode 100644
index 6edde32..0000000
--- a/apps/couch/src/couch_changes.erl
+++ /dev/null
@@ -1,577 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_changes).
--include("couch_db.hrl").
-
--export([handle_changes/3]).
-
-% For the builtin filter _docs_ids, this is the maximum number
-% of documents for which we trigger the optimized code path.
--define(MAX_DOC_IDS, 100).
-
--record(changes_acc, {
-    db,
-    seq,
-    prepend,
-    filter,
-    callback,
-    user_acc,
-    resp_type,
-    limit,
-    include_docs,
-    doc_options,
-    conflicts,
-    timeout,
-    timeout_fun
-}).
-
-%% @type Req -> #httpd{} | {json_req, JsonObj()}
-handle_changes(Args1, Req, Db0) ->
-    #changes_args{
-        style = Style,
-        filter = FilterName,
-        feed = Feed,
-        dir = Dir,
-        since = Since
-    } = Args1,
-    {FilterFun, FilterArgs} = make_filter_fun(FilterName, Style, Req, Db0),
-    Args = Args1#changes_args{filter_fun = FilterFun, filter_args = FilterArgs},
-    Start = fun() ->
-        {ok, Db} = couch_db:reopen(Db0),
-        StartSeq = case Dir of
-        rev ->
-            couch_db:get_update_seq(Db);
-        fwd ->
-            Since
-        end,
-        {Db, StartSeq}
-    end,
-    % begin timer to deal with heartbeat when filter function fails
-    case Args#changes_args.heartbeat of
-    undefined ->
-        erlang:erase(last_changes_heartbeat);
-    Val when is_integer(Val); Val =:= true ->
-        put(last_changes_heartbeat, now())
-    end,
-
-    case lists:member(Feed, ["continuous", "longpoll", "eventsource"]) of
-    true ->
-        fun(CallbackAcc) ->
-            {Callback, UserAcc} = get_callback_acc(CallbackAcc),
-            Self = self(),
-            {ok, Notify} = couch_db_update_notifier:start_link(
-                fun({_, DbName}) when  Db0#db.name == DbName ->
-                    Self ! db_updated;
-                (_) ->
-                    ok
-                end
-            ),
-            {Db, StartSeq} = Start(),
-            UserAcc2 = start_sending_changes(Callback, UserAcc, Feed),
-            {Timeout, TimeoutFun} = get_changes_timeout(Args, Callback),
-            Acc0 = build_acc(Args, Callback, UserAcc2, Db, StartSeq,
-                             <<"">>, Timeout, TimeoutFun),
-            try
-                keep_sending_changes(
-                    Args#changes_args{dir=fwd},
-                    Acc0,
-                    true)
-            after
-                couch_db_update_notifier:stop(Notify),
-                get_rest_db_updated(ok) % clean out any remaining update messages
-            end
-        end;
-    false ->
-        fun(CallbackAcc) ->
-            {Callback, UserAcc} = get_callback_acc(CallbackAcc),
-            UserAcc2 = start_sending_changes(Callback, UserAcc, Feed),
-            {Timeout, TimeoutFun} = get_changes_timeout(Args, Callback),
-            {Db, StartSeq} = Start(),
-            Acc0 = build_acc(Args#changes_args{feed="normal"}, Callback,
-                             UserAcc2, Db, StartSeq, <<>>, Timeout, TimeoutFun),
-            {ok, #changes_acc{seq = LastSeq, user_acc = UserAcc3}} =
-                send_changes(
-                    Args#changes_args{feed="normal"},
-                    Acc0,
-                    true),
-            end_sending_changes(Callback, UserAcc3, LastSeq, Feed)
-        end
-    end.
-
-get_callback_acc({Callback, _UserAcc} = Pair) when is_function(Callback, 3) ->
-    Pair;
-get_callback_acc(Callback) when is_function(Callback, 2) ->
-    {fun(Ev, Data, _) -> Callback(Ev, Data) end, ok}.
-
-%% @type Req -> #httpd{} | {json_req, JsonObj()}
-make_filter_fun([$_ | _] = FilterName, Style, Req, Db) ->
-    builtin_filter_fun(FilterName, Style, Req, Db);
-make_filter_fun(FilterName, Style, Req, Db) ->
-    {os_filter_fun(FilterName, Style, Req, Db), []}.
-
-os_filter_fun(FilterName, Style, Req, Db) ->
-    case [list_to_binary(couch_httpd:unquote(Part))
-            || Part <- string:tokens(FilterName, "/")] of
-    [] ->
-        fun(_Db2, #doc_info{revs=Revs}) ->
-                builtin_results(Style, Revs)
-        end;
-    [DName, FName] ->
-        DesignId = <<"_design/", DName/binary>>,
-        DDoc = couch_httpd_db:couch_doc_open(Db, DesignId, nil, [ejson_body]),
-        % validate that the ddoc has the filter fun
-        #doc{body={Props}} = DDoc,
-        couch_util:get_nested_json_value({Props}, [<<"filters">>, FName]),
-        fun(Db2, DocInfo) ->
-            DocInfos =
-            case Style of
-            main_only ->
-                [DocInfo];
-            all_docs ->
-                [DocInfo#doc_info{revs=[Rev]}|| Rev <- DocInfo#doc_info.revs]
-            end,
-            Docs = [Doc || {ok, Doc} <- [
-                    couch_db:open_doc(Db2, DocInfo2, [deleted, conflicts])
-                        || DocInfo2 <- DocInfos]],
-            {ok, Passes} = couch_query_servers:filter_docs(
-                Req, Db2, DDoc, FName, Docs
-            ),
-            [{[{<<"rev">>, couch_doc:rev_to_str({RevPos,RevId})}]}
-                || {Pass, #doc{revs={RevPos,[RevId|_]}}}
-                <- lists:zip(Passes, Docs), Pass == true]
-        end;
-    _Else ->
-        throw({bad_request,
-            "filter parameter must be of the form `designname/filtername`"})
-    end.
-
-builtin_filter_fun("_doc_ids", Style, {json_req, {Props}}, _Db) ->
-    DocIds = couch_util:get_value(<<"doc_ids">>, Props),
-    {filter_docids(DocIds, Style), DocIds};
-builtin_filter_fun("_doc_ids", Style, #httpd{method='POST'}=Req, _Db) ->
-    {Props} = couch_httpd:json_body_obj(Req),
-    DocIds =  couch_util:get_value(<<"doc_ids">>, Props, nil),
-    {filter_docids(DocIds, Style), DocIds};
-builtin_filter_fun("_doc_ids", Style, #httpd{method='GET'}=Req, _Db) ->
-    DocIds = ?JSON_DECODE(couch_httpd:qs_value(Req, "doc_ids", "null")),
-    {filter_docids(DocIds, Style), DocIds};
-builtin_filter_fun("_design", Style, _Req, _Db) ->
-    {filter_designdoc(Style), []};
-builtin_filter_fun("_view", Style, Req, Db) ->
-    ViewName = couch_httpd:qs_value(Req, "view", ""),
-    {filter_view(ViewName, Style, Db), []};
-builtin_filter_fun(_FilterName, _Style, _Req, _Db) ->
-    throw({bad_request, "unknown builtin filter name"}).
-
-filter_docids(DocIds, Style) when is_list(DocIds)->
-    fun(_Db, #doc_info{id=DocId, revs=Revs}) ->
-            case lists:member(DocId, DocIds) of
-                true ->
-                    builtin_results(Style, Revs);
-                _ -> []
-            end
-    end;
-filter_docids(_, _) ->
-    throw({bad_request, "`doc_ids` filter parameter is not a list."}).
-
-filter_designdoc(Style) ->
-    fun(_Db, #doc_info{id=DocId, revs=Revs}) ->
-            case DocId of
-            <<"_design", _/binary>> ->
-                    builtin_results(Style, Revs);
-                _ -> []
-            end
-    end.
-
-filter_view("", _Style, _Db) ->
-    throw({bad_request, "`view` filter parameter is not provided."});
-filter_view(ViewName, Style, Db) ->
-    case [list_to_binary(couch_httpd:unquote(Part))
-            || Part <- string:tokens(ViewName, "/")] of
-        [] ->
-            throw({bad_request, "Invalid `view` parameter."});
-        [DName, VName] ->
-            DesignId = <<"_design/", DName/binary>>,
-            DDoc = couch_httpd_db:couch_doc_open(Db, DesignId, nil, [ejson_body]),
-            % validate that the ddoc has the filter fun
-            #doc{body={Props}} = DDoc,
-            couch_util:get_nested_json_value({Props}, [<<"views">>, VName]),
-            fun(Db2, DocInfo) ->
-                DocInfos =
-                case Style of
-                main_only ->
-                    [DocInfo];
-                all_docs ->
-                    [DocInfo#doc_info{revs=[Rev]}|| Rev <- DocInfo#doc_info.revs]
-                end,
-                Docs = [Doc || {ok, Doc} <- [
-                        couch_db:open_doc(Db2, DocInfo2, [deleted, conflicts])
-                            || DocInfo2 <- DocInfos]],
-                {ok, Passes} = couch_query_servers:filter_view(
-                    DDoc, VName, Docs
-                ),
-                [{[{<<"rev">>, couch_doc:rev_to_str({RevPos,RevId})}]}
-                    || {Pass, #doc{revs={RevPos,[RevId|_]}}}
-                    <- lists:zip(Passes, Docs), Pass == true]
-            end
-        end.
-
-builtin_results(Style, [#rev_info{rev=Rev}|_]=Revs) ->
-    case Style of
-        main_only ->
-            [{[{<<"rev">>, couch_doc:rev_to_str(Rev)}]}];
-        all_docs ->
-            [{[{<<"rev">>, couch_doc:rev_to_str(R)}]}
-                || #rev_info{rev=R} <- Revs]
-    end.
-
-get_changes_timeout(Args, Callback) ->
-    #changes_args{
-        heartbeat = Heartbeat,
-        timeout = Timeout,
-        feed = ResponseType
-    } = Args,
-    DefaultTimeout = list_to_integer(
-        couch_config:get("httpd", "changes_timeout", "60000")
-    ),
-    case Heartbeat of
-    undefined ->
-        case Timeout of
-        undefined ->
-            {DefaultTimeout, fun(UserAcc) -> {stop, UserAcc} end};
-        infinity ->
-            {infinity, fun(UserAcc) -> {stop, UserAcc} end};
-        _ ->
-            {lists:min([DefaultTimeout, Timeout]),
-                fun(UserAcc) -> {stop, UserAcc} end}
-        end;
-    true ->
-        {DefaultTimeout,
-            fun(UserAcc) -> {ok, Callback(timeout, ResponseType, UserAcc)} end};
-    _ ->
-        {lists:min([DefaultTimeout, Heartbeat]),
-            fun(UserAcc) -> {ok, Callback(timeout, ResponseType, UserAcc)} end}
-    end.
-
-start_sending_changes(_Callback, UserAcc, ResponseType)
-        when ResponseType =:= "continuous"
-        orelse ResponseType =:= "eventsource" ->
-    UserAcc;
-start_sending_changes(Callback, UserAcc, ResponseType) ->
-    Callback(start, ResponseType, UserAcc).
-
-build_acc(Args, Callback, UserAcc, Db, StartSeq, Prepend, Timeout, TimeoutFun) ->
-    #changes_args{
-        include_docs = IncludeDocs,
-        doc_options = DocOpts,
-        conflicts = Conflicts,
-        limit = Limit,
-        feed = ResponseType,
-        filter_fun = FilterFun
-    } = Args,
-    #changes_acc{
-        db = Db,
-        seq = StartSeq,
-        prepend = Prepend,
-        filter = FilterFun,
-        callback = Callback,
-        user_acc = UserAcc,
-        resp_type = ResponseType,
-        limit = Limit,
-        include_docs = IncludeDocs,
-        doc_options = DocOpts,
-        conflicts = Conflicts,
-        timeout = Timeout,
-        timeout_fun = TimeoutFun
-    }.
-
-send_changes(Args, Acc0, FirstRound) ->
-    #changes_args{
-        dir = Dir,
-        filter = FilterName,
-        filter_args = FilterArgs
-    } = Args,
-    #changes_acc{
-        db = Db,
-        seq = StartSeq
-    } = Acc0,
-    case FirstRound of
-    true ->
-        case FilterName of
-        "_doc_ids" when length(FilterArgs) =< ?MAX_DOC_IDS ->
-            send_changes_doc_ids(
-                FilterArgs, Db, StartSeq, Dir, fun changes_enumerator/2, Acc0);
-        "_design" ->
-            send_changes_design_docs(
-                Db, StartSeq, Dir, fun changes_enumerator/2, Acc0);
-        _ ->
-            couch_db:changes_since(
-                Db, StartSeq, fun changes_enumerator/2, [{dir, Dir}], Acc0)
-        end;
-    false ->
-        couch_db:changes_since(
-            Db, StartSeq, fun changes_enumerator/2, [{dir, Dir}], Acc0)
-    end.
-
-
-send_changes_doc_ids(DocIds, Db, StartSeq, Dir, Fun, Acc0) ->
-    Lookups = couch_btree:lookup(Db#db.fulldocinfo_by_id_btree, DocIds),
-    FullDocInfos = lists:foldl(
-        fun({ok, FDI}, Acc) ->
-            [FDI | Acc];
-        (not_found, Acc) ->
-            Acc
-        end,
-        [], Lookups),
-    send_lookup_changes(FullDocInfos, StartSeq, Dir, Db, Fun, Acc0).
-
-
-send_changes_design_docs(Db, StartSeq, Dir, Fun, Acc0) ->
-    FoldFun = fun(FullDocInfo, _, Acc) ->
-        {ok, [FullDocInfo | Acc]}
-    end,
-    KeyOpts = [{start_key, <<"_design/">>}, {end_key_gt, <<"_design0">>}],
-    {ok, _, FullDocInfos} = couch_btree:fold(
-        Db#db.fulldocinfo_by_id_btree, FoldFun, [], KeyOpts),
-    send_lookup_changes(FullDocInfos, StartSeq, Dir, Db, Fun, Acc0).
-
-
-send_lookup_changes(FullDocInfos, StartSeq, Dir, Db, Fun, Acc0) ->
-    FoldFun = case Dir of
-    fwd ->
-        fun lists:foldl/3;
-    rev ->
-        fun lists:foldr/3
-    end,
-    GreaterFun = case Dir of
-    fwd ->
-        fun(A, B) -> A > B end;
-    rev ->
-        fun(A, B) -> A =< B end
-    end,
-    DocInfos = lists:foldl(
-        fun(FDI, Acc) ->
-            DI = couch_doc:to_doc_info(FDI),
-            case GreaterFun(DI#doc_info.high_seq, StartSeq) of
-            true ->
-                [DI | Acc];
-            false ->
-                Acc
-            end
-        end,
-        [], FullDocInfos),
-    SortedDocInfos = lists:keysort(#doc_info.high_seq, DocInfos),
-    FinalAcc = try
-        FoldFun(
-            fun(DocInfo, Acc) ->
-                case Fun(DocInfo, Acc) of
-                {ok, NewAcc} ->
-                    NewAcc;
-                {stop, NewAcc} ->
-                    throw({stop, NewAcc})
-                end
-            end,
-            Acc0, SortedDocInfos)
-    catch
-    throw:{stop, Acc} ->
-        Acc
-    end,
-    case Dir of
-    fwd ->
-        {ok, FinalAcc#changes_acc{seq = couch_db:get_update_seq(Db)}};
-    rev ->
-        {ok, FinalAcc}
-    end.
-
-
-keep_sending_changes(Args, Acc0, FirstRound) ->
-    #changes_args{
-        feed = ResponseType,
-        limit = Limit,
-        db_open_options = DbOptions
-    } = Args,
-
-    {ok, ChangesAcc} = send_changes(
-        Args#changes_args{dir=fwd},
-        Acc0,
-        FirstRound),
-    #changes_acc{
-        db = Db, callback = Callback, timeout = Timeout, timeout_fun = TimeoutFun,
-        seq = EndSeq, prepend = Prepend2, user_acc = UserAcc2, limit = NewLimit
-    } = ChangesAcc,
-
-    couch_db:close(Db),
-    if Limit > NewLimit, ResponseType == "longpoll" ->
-        end_sending_changes(Callback, UserAcc2, EndSeq, ResponseType);
-    true ->
-        case wait_db_updated(Timeout, TimeoutFun, UserAcc2) of
-        {updated, UserAcc4} ->
-            DbOptions1 = [{user_ctx, Db#db.user_ctx} | DbOptions],
-            case couch_db:open(Db#db.name, DbOptions1) of
-            {ok, Db2} ->
-                keep_sending_changes(
-                  Args#changes_args{limit=NewLimit},
-                  ChangesAcc#changes_acc{
-                    db = Db2,
-                    user_acc = UserAcc4,
-                    seq = EndSeq,
-                    prepend = Prepend2,
-                    timeout = Timeout,
-                    timeout_fun = TimeoutFun},
-                  false);
-            _Else ->
-                end_sending_changes(Callback, UserAcc2, EndSeq, ResponseType)
-            end;
-        {stop, UserAcc4} ->
-            end_sending_changes(Callback, UserAcc4, EndSeq, ResponseType)
-        end
-    end.
-
-end_sending_changes(Callback, UserAcc, EndSeq, ResponseType) ->
-    Callback({stop, EndSeq}, ResponseType, UserAcc).
-
-changes_enumerator(DocInfo, #changes_acc{resp_type = ResponseType} = Acc)
-        when ResponseType =:= "continuous"
-        orelse ResponseType =:= "eventsource" ->
-    #changes_acc{
-        filter = FilterFun, callback = Callback,
-        user_acc = UserAcc, limit = Limit, db = Db,
-        timeout = Timeout, timeout_fun = TimeoutFun
-    } = Acc,
-    #doc_info{high_seq = Seq} = DocInfo,
-    Results0 = FilterFun(Db, DocInfo),
-    Results = [Result || Result <- Results0, Result /= null],
-    %% TODO: I'm thinking this should be < 1 and not =< 1
-    Go = if Limit =< 1 -> stop; true -> ok end,
-    case Results of
-    [] ->
-        {Done, UserAcc2} = maybe_heartbeat(Timeout, TimeoutFun, UserAcc),
-        case Done of
-        stop ->
-            {stop, Acc#changes_acc{seq = Seq, user_acc = UserAcc2}};
-        ok ->
-            {Go, Acc#changes_acc{seq = Seq, user_acc = UserAcc2}}
-        end;
-    _ ->
-        ChangesRow = changes_row(Results, DocInfo, Acc),
-        UserAcc2 = Callback({change, ChangesRow, <<>>}, ResponseType, UserAcc),
-        reset_heartbeat(),
-        {Go, Acc#changes_acc{seq = Seq, user_acc = UserAcc2, limit = Limit - 1}}
-    end;
-changes_enumerator(DocInfo, Acc) ->
-    #changes_acc{
-        filter = FilterFun, callback = Callback, prepend = Prepend,
-        user_acc = UserAcc, limit = Limit, resp_type = ResponseType, db = Db,
-        timeout = Timeout, timeout_fun = TimeoutFun
-    } = Acc,
-    #doc_info{high_seq = Seq} = DocInfo,
-    Results0 = FilterFun(Db, DocInfo),
-    Results = [Result || Result <- Results0, Result /= null],
-    Go = if (Limit =< 1) andalso Results =/= [] -> stop; true -> ok end,
-    case Results of
-    [] ->
-        {Done, UserAcc2} = maybe_heartbeat(Timeout, TimeoutFun, UserAcc),
-        case Done of
-        stop ->
-            {stop, Acc#changes_acc{seq = Seq, user_acc = UserAcc2}};
-        ok ->
-            {Go, Acc#changes_acc{seq = Seq, user_acc = UserAcc2}}
-        end;
-    _ ->
-        ChangesRow = changes_row(Results, DocInfo, Acc),
-        UserAcc2 = Callback({change, ChangesRow, Prepend}, ResponseType, UserAcc),
-        reset_heartbeat(),
-        {Go, Acc#changes_acc{
-            seq = Seq, prepend = <<",\n">>,
-            user_acc = UserAcc2, limit = Limit - 1}}
-    end.
-
-
-changes_row(Results, DocInfo, Acc) ->
-    #doc_info{
-        id = Id, high_seq = Seq, revs = [#rev_info{deleted = Del} | _]
-    } = DocInfo,
-    #changes_acc{
-        db = Db,
-        include_docs = IncDoc,
-        doc_options = DocOpts,
-        conflicts = Conflicts
-    } = Acc,
-    {[{<<"seq">>, Seq}, {<<"id">>, Id}, {<<"changes">>, Results}] ++
-        deleted_item(Del) ++ case IncDoc of
-            true ->
-                Opts = case Conflicts of
-                    true -> [deleted, conflicts];
-                    false -> [deleted]
-                end,
-                Doc = couch_index_util:load_doc(Db, DocInfo, Opts),
-                case Doc of
-                    null ->
-                        [{doc, null}];
-                    _ ->
-                        [{doc, couch_doc:to_json_obj(Doc, DocOpts)}]
-                end;
-            false ->
-                []
-        end}.
-
-deleted_item(true) -> [{<<"deleted">>, true}];
-deleted_item(_) -> [].
-
-% waits for a db_updated msg, if there are multiple msgs, collects them.
-wait_db_updated(Timeout, TimeoutFun, UserAcc) ->
-    receive
-    db_updated ->
-        get_rest_db_updated(UserAcc)
-    after Timeout ->
-        {Go, UserAcc2} = TimeoutFun(UserAcc),
-        case Go of
-        ok ->
-            wait_db_updated(Timeout, TimeoutFun, UserAcc2);
-        stop ->
-            {stop, UserAcc2}
-        end
-    end.
-
-get_rest_db_updated(UserAcc) ->
-    receive
-    db_updated ->
-        get_rest_db_updated(UserAcc)
-    after 0 ->
-        {updated, UserAcc}
-    end.
-
-reset_heartbeat() ->
-    case get(last_changes_heartbeat) of
-    undefined ->
-        ok;
-    _ ->
-        put(last_changes_heartbeat, now())
-    end.
-
-maybe_heartbeat(Timeout, TimeoutFun, Acc) ->
-    Before = get(last_changes_heartbeat),
-    case Before of
-    undefined ->
-        {ok, Acc};
-    _ ->
-        Now = now(),
-        case timer:now_diff(Now, Before) div 1000 >= Timeout of
-        true ->
-            Acc2 = TimeoutFun(Acc),
-            put(last_changes_heartbeat, Now),
-            Acc2;
-        false ->
-            {ok, Acc}
-        end
-    end.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_compaction_daemon.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_compaction_daemon.erl b/apps/couch/src/couch_compaction_daemon.erl
deleted file mode 100644
index 18a51a4..0000000
--- a/apps/couch/src/couch_compaction_daemon.erl
+++ /dev/null
@@ -1,504 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_compaction_daemon).
--behaviour(gen_server).
-
-% public API
--export([start_link/0, config_change/3]).
-
-% gen_server callbacks
--export([init/1, handle_call/3, handle_info/2, handle_cast/2]).
--export([code_change/3, terminate/2]).
-
--include("couch_db.hrl").
-
--define(CONFIG_ETS, couch_compaction_daemon_config).
-
--record(state, {
-    loop_pid
-}).
-
--record(config, {
-    db_frag = nil,
-    view_frag = nil,
-    period = nil,
-    cancel = false,
-    parallel_view_compact = false
-}).
-
--record(period, {
-    from = nil,
-    to = nil
-}).
-
-
-start_link() ->
-    gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
-
-
-init(_) ->
-    process_flag(trap_exit, true),
-    ?CONFIG_ETS = ets:new(?CONFIG_ETS, [named_table, set, protected]),
-    ok = couch_config:register(fun ?MODULE:config_change/3),
-    load_config(),
-    Server = self(),
-    Loop = spawn_link(fun() -> compact_loop(Server) end),
-    {ok, #state{loop_pid = Loop}}.
-
-
-config_change("compactions", DbName, NewValue) ->
-    ok = gen_server:cast(?MODULE, {config_update, DbName, NewValue}).
-
-
-handle_cast({config_update, DbName, deleted}, State) ->
-    true = ets:delete(?CONFIG_ETS, ?l2b(DbName)),
-    {noreply, State};
-
-handle_cast({config_update, DbName, Config}, #state{loop_pid = Loop} = State) ->
-    case parse_config(DbName, Config) of
-    {ok, NewConfig} ->
-        WasEmpty = (ets:info(?CONFIG_ETS, size) =:= 0),
-        true = ets:insert(?CONFIG_ETS, {?l2b(DbName), NewConfig}),
-        case WasEmpty of
-        true ->
-            Loop ! {self(), have_config};
-        false ->
-            ok
-        end;
-    error ->
-        ok
-    end,
-    {noreply, State}.
-
-
-handle_call(Msg, _From, State) ->
-    {stop, {unexpected_call, Msg}, State}.
-
-
-handle_info({'EXIT', Pid, Reason}, #state{loop_pid = Pid} = State) ->
-    {stop, {compaction_loop_died, Reason}, State}.
-
-
-terminate(_Reason, _State) ->
-    true = ets:delete(?CONFIG_ETS).
-
-
-code_change(_OldVsn, State, _Extra) ->
-    {ok, State}.
-
-
-compact_loop(Parent) ->
-    {ok, _} = couch_server:all_databases(
-        fun(DbName, Acc) ->
-            case ets:info(?CONFIG_ETS, size) =:= 0 of
-            true ->
-                {stop, Acc};
-            false ->
-                case get_db_config(DbName) of
-                nil ->
-                    ok;
-                {ok, Config} ->
-                    case check_period(Config) of
-                    true ->
-                        maybe_compact_db(DbName, Config);
-                    false ->
-                        ok
-                    end
-                end,
-                {ok, Acc}
-            end
-        end, ok),
-    case ets:info(?CONFIG_ETS, size) =:= 0 of
-    true ->
-        receive {Parent, have_config} -> ok end;
-    false ->
-        PausePeriod = list_to_integer(
-            couch_config:get("compaction_daemon", "check_interval", "300")),
-        ok = timer:sleep(PausePeriod * 1000)
-    end,
-    compact_loop(Parent).
-
-
-maybe_compact_db(DbName, Config) ->
-    case (catch couch_db:open_int(DbName, [{user_ctx, #user_ctx{roles=[<<"_admin">>]}}])) of
-    {ok, Db} ->
-        DDocNames = db_ddoc_names(Db),
-        case can_db_compact(Config, Db) of
-        true ->
-            {ok, DbCompactPid} = couch_db:start_compact(Db),
-            TimeLeft = compact_time_left(Config),
-            case Config#config.parallel_view_compact of
-            true ->
-                ViewsCompactPid = spawn_link(fun() ->
-                    maybe_compact_views(DbName, DDocNames, Config)
-                end),
-                ViewsMonRef = erlang:monitor(process, ViewsCompactPid);
-            false ->
-                ViewsCompactPid = nil,
-                ViewsMonRef = nil
-            end,
-            DbMonRef = erlang:monitor(process, DbCompactPid),
-            receive
-            {'DOWN', DbMonRef, process, _, normal} ->
-                couch_db:close(Db),
-                case Config#config.parallel_view_compact of
-                true ->
-                    ok;
-                false ->
-                    maybe_compact_views(DbName, DDocNames, Config)
-                end;
-            {'DOWN', DbMonRef, process, _, Reason} ->
-                couch_db:close(Db),
-                ?LOG_ERROR("Compaction daemon - an error ocurred while"
-                    " compacting the database `~s`: ~p", [DbName, Reason])
-            after TimeLeft ->
-                ?LOG_INFO("Compaction daemon - canceling compaction for database"
-                    " `~s` because it's exceeding the allowed period.",
-                    [DbName]),
-                erlang:demonitor(DbMonRef, [flush]),
-                ok = couch_db:cancel_compact(Db),
-                couch_db:close(Db)
-            end,
-            case ViewsMonRef of
-            nil ->
-                ok;
-            _ ->
-                receive
-                {'DOWN', ViewsMonRef, process, _, _Reason} ->
-                    ok
-                after TimeLeft + 1000 ->
-                    % Under normal circunstances, the view compaction process
-                    % should have finished already.
-                    erlang:demonitor(ViewsMonRef, [flush]),
-                    unlink(ViewsCompactPid),
-                    exit(ViewsCompactPid, kill)
-                end
-            end;
-        false ->
-            couch_db:close(Db),
-            maybe_compact_views(DbName, DDocNames, Config)
-        end;
-    _ ->
-        ok
-    end.
-
-
-maybe_compact_views(_DbName, [], _Config) ->
-    ok;
-maybe_compact_views(DbName, [DDocName | Rest], Config) ->
-    case check_period(Config) of
-    true ->
-        case maybe_compact_view(DbName, DDocName, Config) of
-        ok ->
-            maybe_compact_views(DbName, Rest, Config);
-        timeout ->
-            ok
-        end;
-    false ->
-        ok
-    end.
-
-
-db_ddoc_names(Db) ->
-    {ok, _, DDocNames} = couch_db:enum_docs(
-        Db,
-        fun(#full_doc_info{id = <<"_design/", _/binary>>, deleted = true}, _, Acc) ->
-            {ok, Acc};
-        (#full_doc_info{id = <<"_design/", Id/binary>>}, _, Acc) ->
-            {ok, [Id | Acc]};
-        (_, _, Acc) ->
-            {stop, Acc}
-        end, [], [{start_key, <<"_design/">>}, {end_key_gt, <<"_design0">>}]),
-    DDocNames.
-
-
-maybe_compact_view(DbName, GroupId, Config) ->
-    DDocId = <<"_design/", GroupId/binary>>,
-    case (catch couch_mrview:get_info(DbName, DDocId)) of
-    {ok, GroupInfo} ->
-        case can_view_compact(Config, DbName, GroupId, GroupInfo) of
-        true ->
-            {ok, MonRef} = couch_mrview:compact(DbName, DDocId, [monitor]),
-            TimeLeft = compact_time_left(Config),
-            receive
-            {'DOWN', MonRef, process, _, normal} ->
-                ok;
-            {'DOWN', MonRef, process, _, Reason} ->
-                ?LOG_ERROR("Compaction daemon - an error ocurred while compacting"
-                    " the view group `~s` from database `~s`: ~p",
-                    [GroupId, DbName, Reason]),
-                ok
-            after TimeLeft ->
-                ?LOG_INFO("Compaction daemon - canceling the compaction for the "
-                    "view group `~s` of the database `~s` because it's exceeding"
-                    " the allowed period.", [GroupId, DbName]),
-                erlang:demonitor(MonRef, [flush]),
-                ok = couch_mrview:cancel_compaction(DbName, DDocId),
-                timeout
-            end;
-        false ->
-            ok
-        end;
-    Error ->
-        ?LOG_ERROR("Error opening view group `~s` from database `~s`: ~p",
-            [GroupId, DbName, Error]),
-        ok
-    end.
-
-
-compact_time_left(#config{cancel = false}) ->
-    infinity;
-compact_time_left(#config{period = nil}) ->
-    infinity;
-compact_time_left(#config{period = #period{to = {ToH, ToM} = To}}) ->
-    {H, M, _} = time(),
-    case To > {H, M} of
-    true ->
-        ((ToH - H) * 60 * 60 * 1000) + (abs(ToM - M) * 60 * 1000);
-    false ->
-        ((24 - H + ToH) * 60 * 60 * 1000) + (abs(ToM - M) * 60 * 1000)
-    end.
-
-
-get_db_config(DbName) ->
-    case ets:lookup(?CONFIG_ETS, DbName) of
-    [] ->
-        case ets:lookup(?CONFIG_ETS, <<"_default">>) of
-        [] ->
-            nil;
-        [{<<"_default">>, Config}] ->
-            {ok, Config}
-        end;
-    [{DbName, Config}] ->
-        {ok, Config}
-    end.
-
-
-can_db_compact(#config{db_frag = Threshold} = Config, Db) ->
-    case check_period(Config) of
-    false ->
-        false;
-    true ->
-        {ok, DbInfo} = couch_db:get_db_info(Db),
-        {Frag, SpaceRequired} = frag(DbInfo),
-        ?LOG_DEBUG("Fragmentation for database `~s` is ~p%, estimated space for"
-           " compaction is ~p bytes.", [Db#db.name, Frag, SpaceRequired]),
-        case check_frag(Threshold, Frag) of
-        false ->
-            false;
-        true ->
-            Free = free_space(couch_config:get("couchdb", "database_dir")),
-            case Free >= SpaceRequired of
-            true ->
-                true;
-            false ->
-                ?LOG_WARN("Compaction daemon - skipping database `~s` "
-                    "compaction: the estimated necessary disk space is about ~p"
-                    " bytes but the currently available disk space is ~p bytes.",
-                   [Db#db.name, SpaceRequired, Free]),
-                false
-            end
-        end
-    end.
-
-can_view_compact(Config, DbName, GroupId, GroupInfo) ->
-    case check_period(Config) of
-    false ->
-        false;
-    true ->
-        case couch_util:get_value(updater_running, GroupInfo) of
-        true ->
-            false;
-        false ->
-            {Frag, SpaceRequired} = frag(GroupInfo),
-            ?LOG_DEBUG("Fragmentation for view group `~s` (database `~s`) is "
-                "~p%, estimated space for compaction is ~p bytes.",
-                [GroupId, DbName, Frag, SpaceRequired]),
-            case check_frag(Config#config.view_frag, Frag) of
-            false ->
-                false;
-            true ->
-                Free = free_space(couch_index_util:root_dir()),
-                case Free >= SpaceRequired of
-                true ->
-                    true;
-                false ->
-                    ?LOG_WARN("Compaction daemon - skipping view group `~s` "
-                        "compaction (database `~s`): the estimated necessary "
-                        "disk space is about ~p bytes but the currently available"
-                        " disk space is ~p bytes.",
-                        [GroupId, DbName, SpaceRequired, Free]),
-                    false
-                end
-            end
-        end
-    end.
-
-
-check_period(#config{period = nil}) ->
-    true;
-check_period(#config{period = #period{from = From, to = To}}) ->
-    {HH, MM, _} = erlang:time(),
-    case From < To of
-    true ->
-        ({HH, MM} >= From) andalso ({HH, MM} < To);
-    false ->
-        ({HH, MM} >= From) orelse ({HH, MM} < To)
-    end.
-
-
-check_frag(nil, _) ->
-    true;
-check_frag(Threshold, Frag) ->
-    Frag >= Threshold.
-
-
-frag(Props) ->
-    FileSize = couch_util:get_value(disk_size, Props),
-    MinFileSize = list_to_integer(
-        couch_config:get("compaction_daemon", "min_file_size", "131072")),
-    case FileSize < MinFileSize of
-    true ->
-        {0, FileSize};
-    false ->
-        case couch_util:get_value(data_size, Props) of
-        null ->
-            {100, FileSize};
-        0 ->
-            {0, FileSize};
-        DataSize ->
-            Frag = round(((FileSize - DataSize) / FileSize * 100)),
-            {Frag, space_required(DataSize)}
-        end
-    end.
-
-% Rough, and pessimistic, estimation of necessary disk space to compact a
-% database or view index.
-space_required(DataSize) ->
-    round(DataSize * 2.0).
-
-
-load_config() ->
-    lists:foreach(
-        fun({DbName, ConfigString}) ->
-            case parse_config(DbName, ConfigString) of
-            {ok, Config} ->
-                true = ets:insert(?CONFIG_ETS, {?l2b(DbName), Config});
-            error ->
-                ok
-            end
-        end,
-        couch_config:get("compactions")).
-
-parse_config(DbName, ConfigString) ->
-    case (catch do_parse_config(ConfigString)) of
-    {ok, Conf} ->
-        {ok, Conf};
-    incomplete_period ->
-        ?LOG_ERROR("Incomplete period ('to' or 'from' missing) in the compaction"
-            " configuration for database `~s`", [DbName]),
-        error;
-    _ ->
-        ?LOG_ERROR("Invalid compaction configuration for database "
-            "`~s`: `~s`", [DbName, ConfigString]),
-        error
-    end.
-
-do_parse_config(ConfigString) ->
-    {ok, ConfProps} = couch_util:parse_term(ConfigString),
-    {ok, #config{period = Period} = Conf} = config_record(ConfProps, #config{}),
-    case Period of
-    nil ->
-        {ok, Conf};
-    #period{from = From, to = To} when From =/= nil, To =/= nil ->
-        {ok, Conf};
-    #period{} ->
-        incomplete_period
-    end.
-
-config_record([], Config) ->
-    {ok, Config};
-
-config_record([{db_fragmentation, V} | Rest], Config) ->
-    [Frag] = string:tokens(V, "%"),
-    config_record(Rest, Config#config{db_frag = list_to_integer(Frag)});
-
-config_record([{view_fragmentation, V} | Rest], Config) ->
-    [Frag] = string:tokens(V, "%"),
-    config_record(Rest, Config#config{view_frag = list_to_integer(Frag)});
-
-config_record([{from, V} | Rest], #config{period = Period0} = Config) ->
-    Time = parse_time(V),
-    Period = case Period0 of
-    nil ->
-        #period{from = Time};
-    #period{} ->
-        Period0#period{from = Time}
-    end,
-    config_record(Rest, Config#config{period = Period});
-
-config_record([{to, V} | Rest], #config{period = Period0} = Config) ->
-    Time = parse_time(V),
-    Period = case Period0 of
-    nil ->
-        #period{to = Time};
-    #period{} ->
-        Period0#period{to = Time}
-    end,
-    config_record(Rest, Config#config{period = Period});
-
-config_record([{strict_window, true} | Rest], Config) ->
-    config_record(Rest, Config#config{cancel = true});
-
-config_record([{strict_window, false} | Rest], Config) ->
-    config_record(Rest, Config#config{cancel = false});
-
-config_record([{parallel_view_compaction, true} | Rest], Config) ->
-    config_record(Rest, Config#config{parallel_view_compact = true});
-
-config_record([{parallel_view_compaction, false} | Rest], Config) ->
-    config_record(Rest, Config#config{parallel_view_compact = false}).
-
-
-parse_time(String) ->
-    [HH, MM] = string:tokens(String, ":"),
-    {list_to_integer(HH), list_to_integer(MM)}.
-
-
-free_space(Path) ->
-    DiskData = lists:sort(
-        fun({PathA, _, _}, {PathB, _, _}) ->
-            length(filename:split(PathA)) > length(filename:split(PathB))
-        end,
-        disksup:get_disk_data()),
-    free_space_rec(abs_path(Path), DiskData).
-
-free_space_rec(_Path, []) ->
-    undefined;
-free_space_rec(Path, [{MountPoint0, Total, Usage} | Rest]) ->
-    MountPoint = abs_path(MountPoint0),
-    case MountPoint =:= string:substr(Path, 1, length(MountPoint)) of
-    false ->
-        free_space_rec(Path, Rest);
-    true ->
-        trunc(Total - (Total * (Usage / 100))) * 1024
-    end.
-
-abs_path(Path0) ->
-    Path = filename:absname(Path0),
-    case lists:last(Path) of
-    $/ ->
-        Path;
-    _ ->
-        Path ++ "/"
-    end.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_compress.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_compress.erl b/apps/couch/src/couch_compress.erl
deleted file mode 100644
index ac386fd..0000000
--- a/apps/couch/src/couch_compress.erl
+++ /dev/null
@@ -1,84 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_compress).
-
--export([compress/2, decompress/1, is_compressed/2]).
--export([get_compression_method/0]).
-
--include("couch_db.hrl").
-
-% binaries compressed with snappy have their first byte set to this value
--define(SNAPPY_PREFIX, 1).
-% Term prefixes documented at:
-%      http://www.erlang.org/doc/apps/erts/erl_ext_dist.html
--define(TERM_PREFIX, 131).
--define(COMPRESSED_TERM_PREFIX, 131, 80).
-
-
-get_compression_method() ->
-    case couch_config:get("couchdb", "file_compression") of
-    undefined ->
-        ?DEFAULT_COMPRESSION;
-    Method1 ->
-        case string:tokens(Method1, "_") of
-        [Method] ->
-            list_to_existing_atom(Method);
-        [Method, Level] ->
-            {list_to_existing_atom(Method), list_to_integer(Level)}
-        end
-    end.
-
-
-compress(<<?SNAPPY_PREFIX, _/binary>> = Bin, snappy) ->
-    Bin;
-compress(<<?SNAPPY_PREFIX, _/binary>> = Bin, Method) ->
-    compress(decompress(Bin), Method);
-compress(<<?TERM_PREFIX, _/binary>> = Bin, Method) ->
-    compress(decompress(Bin), Method);
-compress(Term, none) ->
-    ?term_to_bin(Term);
-compress(Term, {deflate, Level}) ->
-    term_to_binary(Term, [{minor_version, 1}, {compressed, Level}]);
-compress(Term, snappy) ->
-    Bin = ?term_to_bin(Term),
-    try
-        {ok, CompressedBin} = snappy:compress(Bin),
-        case byte_size(CompressedBin) < byte_size(Bin) of
-        true ->
-            <<?SNAPPY_PREFIX, CompressedBin/binary>>;
-        false ->
-            Bin
-        end
-    catch exit:snappy_nif_not_loaded ->
-        Bin
-    end.
-
-
-decompress(<<?SNAPPY_PREFIX, Rest/binary>>) ->
-    {ok, TermBin} = snappy:decompress(Rest),
-    binary_to_term(TermBin);
-decompress(<<?TERM_PREFIX, _/binary>> = Bin) ->
-    binary_to_term(Bin).
-
-
-is_compressed(<<?SNAPPY_PREFIX, _/binary>>, Method) ->
-    Method =:= snappy;
-is_compressed(<<?COMPRESSED_TERM_PREFIX, _/binary>>, {deflate, _Level}) ->
-    true;
-is_compressed(<<?COMPRESSED_TERM_PREFIX, _/binary>>, _Method) ->
-    false;
-is_compressed(<<?TERM_PREFIX, _/binary>>, Method) ->
-    Method =:= none;
-is_compressed(Term, _Method) when not is_binary(Term) ->
-    false.
-


[90/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/coll.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/coll.h b/src/apps/couch_collate/platform/osx/icu/unicode/coll.h
new file mode 100644
index 0000000..5733f58
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/coll.h
@@ -0,0 +1,1035 @@
+/*
+******************************************************************************
+*   Copyright (C) 1996-2008, International Business Machines                 *
+*   Corporation and others.  All Rights Reserved.                            *
+******************************************************************************
+*/
+
+/**
+ * \file 
+ * \brief C++ API: Collation Service.
+ */
+ 
+/**
+* File coll.h
+*
+* Created by: Helena Shih
+*
+* Modification History:
+*
+*  Date        Name        Description
+* 02/5/97      aliu        Modified createDefault to load collation data from
+*                          binary files when possible.  Added related methods
+*                          createCollationFromFile, chopLocale, createPathName.
+* 02/11/97     aliu        Added members addToCache, findInCache, and fgCache.
+* 02/12/97     aliu        Modified to create objects from RuleBasedCollator cache.
+*                          Moved cache out of Collation class.
+* 02/13/97     aliu        Moved several methods out of this class and into
+*                          RuleBasedCollator, with modifications.  Modified
+*                          createDefault() to call new RuleBasedCollator(Locale&)
+*                          constructor.  General clean up and documentation.
+* 02/20/97     helena      Added clone, operator==, operator!=, operator=, copy
+*                          constructor and getDynamicClassID.
+* 03/25/97     helena      Updated with platform independent data types.
+* 05/06/97     helena      Added memory allocation error detection.
+* 06/20/97     helena      Java class name change.
+* 09/03/97     helena      Added createCollationKeyValues().
+* 02/10/98     damiba      Added compare() with length as parameter.
+* 04/23/99     stephen     Removed EDecompositionMode, merged with
+*                          Normalizer::EMode.
+* 11/02/99     helena      Collator performance enhancements.  Eliminates the
+*                          UnicodeString construction and special case for NO_OP.
+* 11/23/99     srl         More performance enhancements. Inlining of
+*                          critical accessors.
+* 05/15/00     helena      Added version information API.
+* 01/29/01     synwee      Modified into a C++ wrapper which calls C apis
+*                          (ucoll.h).
+*/
+
+#ifndef COLL_H
+#define COLL_H
+
+#include "unicode/utypes.h"
+
+#if !UCONFIG_NO_COLLATION
+
+#include "unicode/uobject.h"
+#include "unicode/ucol.h"
+#include "unicode/normlzr.h"
+#include "unicode/locid.h"
+#include "unicode/uniset.h"
+#include "unicode/umisc.h"
+
+U_NAMESPACE_BEGIN
+
+class StringEnumeration;
+
+#if !UCONFIG_NO_SERVICE
+/**
+ * @stable ICU 2.6
+ */
+class CollatorFactory;
+#endif
+
+/**
+* @stable ICU 2.0
+*/
+class CollationKey;
+
+/**
+* The <code>Collator</code> class performs locale-sensitive string
+* comparison.<br>
+* You use this class to build searching and sorting routines for natural
+* language text.<br>
+* <em>Important: </em>The ICU collation service has been reimplemented
+* in order to achieve better performance and UCA compliance.
+* For details, see the
+* <a href="http://source.icu-project.org/repos/icu/icuhtml/trunk/design/collation/ICU_collation_design.htm">
+* collation design document</a>.
+* <p>
+* <code>Collator</code> is an abstract base class. Subclasses implement
+* specific collation strategies. One subclass,
+* <code>RuleBasedCollator</code>, is currently provided and is applicable
+* to a wide set of languages. Other subclasses may be created to handle more
+* specialized needs.
+* <p>
+* Like other locale-sensitive classes, you can use the static factory method,
+* <code>createInstance</code>, to obtain the appropriate
+* <code>Collator</code> object for a given locale. You will only need to
+* look at the subclasses of <code>Collator</code> if you need to
+* understand the details of a particular collation strategy or if you need to
+* modify that strategy.
+* <p>
+* The following example shows how to compare two strings using the
+* <code>Collator</code> for the default locale.
+* \htmlonly<blockquote>\endhtmlonly
+* <pre>
+* \code
+* // Compare two strings in the default locale
+* UErrorCode success = U_ZERO_ERROR;
+* Collator* myCollator = Collator::createInstance(success);
+* if (myCollator->compare("abc", "ABC") < 0)
+*   cout << "abc is less than ABC" << endl;
+* else
+*   cout << "abc is greater than or equal to ABC" << endl;
+* \endcode
+* </pre>
+* \htmlonly</blockquote>\endhtmlonly
+* <p>
+* You can set a <code>Collator</code>'s <em>strength</em> property to
+* determine the level of difference considered significant in comparisons.
+* Five strengths are provided: <code>PRIMARY</code>, <code>SECONDARY</code>,
+* <code>TERTIARY</code>, <code>QUATERNARY</code> and <code>IDENTICAL</code>.
+* The exact assignment of strengths to language features is locale dependant.
+* For example, in Czech, "e" and "f" are considered primary differences,
+* while "e" and "\u00EA" are secondary differences, "e" and "E" are tertiary
+* differences and "e" and "e" are identical. The following shows how both case
+* and accents could be ignored for US English.
+* \htmlonly<blockquote>\endhtmlonly
+* <pre>
+* \code
+* //Get the Collator for US English and set its strength to PRIMARY
+* UErrorCode success = U_ZERO_ERROR;
+* Collator* usCollator = Collator::createInstance(Locale::US, success);
+* usCollator->setStrength(Collator::PRIMARY);
+* if (usCollator->compare("abc", "ABC") == 0)
+*     cout << "'abc' and 'ABC' strings are equivalent with strength PRIMARY" << endl;
+* \endcode
+* </pre>
+* \htmlonly</blockquote>\endhtmlonly
+* <p>
+* For comparing strings exactly once, the <code>compare</code> method
+* provides the best performance. When sorting a list of strings however, it
+* is generally necessary to compare each string multiple times. In this case,
+* sort keys provide better performance. The <code>getSortKey</code> methods
+* convert a string to a series of bytes that can be compared bitwise against
+* other sort keys using <code>strcmp()</code>. Sort keys are written as
+* zero-terminated byte strings. They consist of several substrings, one for
+* each collation strength level, that are delimited by 0x01 bytes.
+* If the string code points are appended for UCOL_IDENTICAL, then they are
+* processed for correct code point order comparison and may contain 0x01
+* bytes but not zero bytes.
+* </p>
+* <p>
+* An older set of APIs returns a <code>CollationKey</code> object that wraps
+* the sort key bytes instead of returning the bytes themselves.
+* Its use is deprecated, but it is still available for compatibility with
+* Java.
+* </p>
+* <p>
+* <strong>Note:</strong> <code>Collator</code>s with different Locale,
+* and CollationStrength settings will return different sort
+* orders for the same set of strings. Locales have specific collation rules,
+* and the way in which secondary and tertiary differences are taken into
+* account, for example, will result in a different sorting order for same
+* strings.
+* </p>
+* @see         RuleBasedCollator
+* @see         CollationKey
+* @see         CollationElementIterator
+* @see         Locale
+* @see         Normalizer
+* @version     2.0 11/15/01
+*/
+
+class U_I18N_API Collator : public UObject {
+public:
+
+    // Collator public enums -----------------------------------------------
+
+    /**
+     * Base letter represents a primary difference. Set comparison level to
+     * PRIMARY to ignore secondary and tertiary differences.<br>
+     * Use this to set the strength of a Collator object.<br>
+     * Example of primary difference, "abc" &lt; "abd"
+     *
+     * Diacritical differences on the same base letter represent a secondary
+     * difference. Set comparison level to SECONDARY to ignore tertiary
+     * differences. Use this to set the strength of a Collator object.<br>
+     * Example of secondary difference, "&auml;" >> "a".
+     *
+     * Uppercase and lowercase versions of the same character represents a
+     * tertiary difference.  Set comparison level to TERTIARY to include all
+     * comparison differences. Use this to set the strength of a Collator
+     * object.<br>
+     * Example of tertiary difference, "abc" &lt;&lt;&lt; "ABC".
+     *
+     * Two characters are considered "identical" when they have the same unicode
+     * spellings.<br>
+     * For example, "&auml;" == "&auml;".
+     *
+     * UCollationStrength is also used to determine the strength of sort keys
+     * generated from Collator objects.
+     * @stable ICU 2.0
+     */
+    enum ECollationStrength
+    {
+        PRIMARY    = 0,
+        SECONDARY  = 1,
+        TERTIARY   = 2,
+        QUATERNARY = 3,
+        IDENTICAL  = 15
+    };
+
+    /**
+     * LESS is returned if source string is compared to be less than target
+     * string in the compare() method.
+     * EQUAL is returned if source string is compared to be equal to target
+     * string in the compare() method.
+     * GREATER is returned if source string is compared to be greater than
+     * target string in the compare() method.
+     * @see Collator#compare
+     * @deprecated ICU 2.6. Use C enum UCollationResult defined in ucol.h
+     */
+    enum EComparisonResult
+    {
+        LESS = -1,
+        EQUAL = 0,
+        GREATER = 1
+    };
+
+    // Collator public destructor -----------------------------------------
+
+    /**
+     * Destructor
+     * @stable ICU 2.0
+     */
+    virtual ~Collator();
+
+    // Collator public methods --------------------------------------------
+
+    /**
+     * Returns true if "other" is the same as "this"
+     * @param other Collator object to be compared
+     * @return true if other is the same as this.
+     * @stable ICU 2.0
+     */
+    virtual UBool operator==(const Collator& other) const;
+
+    /**
+     * Returns true if "other" is not the same as "this".
+     * @param other Collator object to be compared
+     * @return true if other is not the same as this.
+     * @stable ICU 2.0
+     */
+    virtual UBool operator!=(const Collator& other) const;
+
+    /**
+     * Makes a shallow copy of the current object.
+     * @return a copy of this object
+     * @stable ICU 2.0
+     */
+    virtual Collator* clone(void) const = 0;
+
+    /**
+     * Creates the Collator object for the current default locale.
+     * The default locale is determined by Locale::getDefault.
+     * The UErrorCode& err parameter is used to return status information to the user.
+     * To check whether the construction succeeded or not, you should check the
+     * value of U_SUCCESS(err).  If you wish more detailed information, you can
+     * check for informational error results which still indicate success.
+     * U_USING_FALLBACK_ERROR indicates that a fall back locale was used. For
+     * example, 'de_CH' was requested, but nothing was found there, so 'de' was
+     * used. U_USING_DEFAULT_ERROR indicates that the default locale data was
+     * used; neither the requested locale nor any of its fall back locales
+     * could be found.
+     * The caller owns the returned object and is responsible for deleting it.
+     *
+     * @param err    the error code status.
+     * @return       the collation object of the default locale.(for example, en_US)
+     * @see Locale#getDefault
+     * @stable ICU 2.0
+     */
+    static Collator* U_EXPORT2 createInstance(UErrorCode&  err);
+
+    /**
+     * Gets the table-based collation object for the desired locale. The
+     * resource of the desired locale will be loaded by ResourceLoader.
+     * Locale::ENGLISH is the base collation table and all other languages are
+     * built on top of it with additional language-specific modifications.
+     * The UErrorCode& err parameter is used to return status information to the user.
+     * To check whether the construction succeeded or not, you should check
+     * the value of U_SUCCESS(err).  If you wish more detailed information, you
+     * can check for informational error results which still indicate success.
+     * U_USING_FALLBACK_ERROR indicates that a fall back locale was used.  For
+     * example, 'de_CH' was requested, but nothing was found there, so 'de' was
+     * used.  U_USING_DEFAULT_ERROR indicates that the default locale data was
+     * used; neither the requested locale nor any of its fall back locales
+     * could be found.
+     * The caller owns the returned object and is responsible for deleting it.
+     * @param loc    The locale ID for which to open a collator.
+     * @param err    the error code status.
+     * @return       the created table-based collation object based on the desired
+     *               locale.
+     * @see Locale
+     * @see ResourceLoader
+     * @stable ICU 2.2
+     */
+    static Collator* U_EXPORT2 createInstance(const Locale& loc, UErrorCode& err);
+
+#ifdef U_USE_COLLATION_OBSOLETE_2_6
+    /**
+     * Create a Collator with a specific version.
+     * This is the same as createInstance(loc, err) except that getVersion() of
+     * the returned object is guaranteed to be the same as the version
+     * parameter.
+     * This is designed to be used to open the same collator for a given
+     * locale even when ICU is updated.
+     * The same locale and version guarantees the same sort keys and
+     * comparison results.
+     * <p>
+     * Note: this API will be removed in a future release.  Use
+     * <tt>createInstance(const Locale&, UErrorCode&) instead.</tt></p>
+     *
+     * @param loc The locale ID for which to open a collator.
+     * @param version The requested collator version.
+     * @param err A reference to a UErrorCode,
+     *            must not indicate a failure before calling this function.
+     * @return A pointer to a Collator, or 0 if an error occurred
+     *         or a collator with the requested version is not available.
+     *
+     * @see getVersion
+     * @obsolete ICU 2.6
+     */
+    static Collator *createInstance(const Locale &loc, UVersionInfo version, UErrorCode &err);
+#endif
+
+    /**
+     * The comparison function compares the character data stored in two
+     * different strings. Returns information about whether a string is less
+     * than, greater than or equal to another string.
+     * @param source the source string to be compared with.
+     * @param target the string that is to be compared with the source string.
+     * @return Returns a byte value. GREATER if source is greater
+     * than target; EQUAL if source is equal to target; LESS if source is less
+     * than target
+     * @deprecated ICU 2.6 use the overload with UErrorCode &
+     */
+    virtual EComparisonResult compare(const UnicodeString& source,
+                                      const UnicodeString& target) const;
+
+    /**
+     * The comparison function compares the character data stored in two
+     * different strings. Returns information about whether a string is less
+     * than, greater than or equal to another string.
+     * @param source the source string to be compared with.
+     * @param target the string that is to be compared with the source string.
+     * @param status possible error code
+     * @return Returns an enum value. UCOL_GREATER if source is greater
+     * than target; UCOL_EQUAL if source is equal to target; UCOL_LESS if source is less
+     * than target
+     * @stable ICU 2.6
+     */
+    virtual UCollationResult compare(const UnicodeString& source,
+                                      const UnicodeString& target,
+                                      UErrorCode &status) const = 0;
+
+    /**
+     * Does the same thing as compare but limits the comparison to a specified
+     * length
+     * @param source the source string to be compared with.
+     * @param target the string that is to be compared with the source string.
+     * @param length the length the comparison is limited to
+     * @return Returns a byte value. GREATER if source (up to the specified
+     *         length) is greater than target; EQUAL if source (up to specified
+     *         length) is equal to target; LESS if source (up to the specified
+     *         length) is less  than target.
+     * @deprecated ICU 2.6 use the overload with UErrorCode &
+     */
+    virtual EComparisonResult compare(const UnicodeString& source,
+                                      const UnicodeString& target,
+                                      int32_t length) const;
+
+    /**
+     * Does the same thing as compare but limits the comparison to a specified
+     * length
+     * @param source the source string to be compared with.
+     * @param target the string that is to be compared with the source string.
+     * @param length the length the comparison is limited to
+     * @param status possible error code
+     * @return Returns an enum value. UCOL_GREATER if source (up to the specified
+     *         length) is greater than target; UCOL_EQUAL if source (up to specified
+     *         length) is equal to target; UCOL_LESS if source (up to the specified
+     *         length) is less  than target.
+     * @stable ICU 2.6
+     */
+    virtual UCollationResult compare(const UnicodeString& source,
+                                      const UnicodeString& target,
+                                      int32_t length,
+                                      UErrorCode &status) const = 0;
+
+    /**
+     * The comparison function compares the character data stored in two
+     * different string arrays. Returns information about whether a string array
+     * is less than, greater than or equal to another string array.
+     * @param source the source string array to be compared with.
+     * @param sourceLength the length of the source string array.  If this value
+     *        is equal to -1, the string array is null-terminated.
+     * @param target the string that is to be compared with the source string.
+     * @param targetLength the length of the target string array.  If this value
+     *        is equal to -1, the string array is null-terminated.
+     * @return Returns a byte value. GREATER if source is greater than target;
+     *         EQUAL if source is equal to target; LESS if source is less than
+     *         target
+     * @deprecated ICU 2.6 use the overload with UErrorCode &
+     */
+    virtual EComparisonResult compare(const UChar* source, int32_t sourceLength,
+                                      const UChar* target, int32_t targetLength)
+                                      const;
+
+    /**
+     * The comparison function compares the character data stored in two
+     * different string arrays. Returns information about whether a string array
+     * is less than, greater than or equal to another string array.
+     * @param source the source string array to be compared with.
+     * @param sourceLength the length of the source string array.  If this value
+     *        is equal to -1, the string array is null-terminated.
+     * @param target the string that is to be compared with the source string.
+     * @param targetLength the length of the target string array.  If this value
+     *        is equal to -1, the string array is null-terminated.
+     * @param status possible error code
+     * @return Returns an enum value. UCOL_GREATER if source is greater
+     * than target; UCOL_EQUAL if source is equal to target; UCOL_LESS if source is less
+     * than target
+     * @stable ICU 2.6
+     */
+    virtual UCollationResult compare(const UChar* source, int32_t sourceLength,
+                                      const UChar* target, int32_t targetLength,
+                                      UErrorCode &status) const = 0;
+
+    /**
+     * Transforms the string into a series of characters that can be compared
+     * with CollationKey::compareTo. It is not possible to restore the original
+     * string from the chars in the sort key.  The generated sort key handles
+     * only a limited number of ignorable characters.
+     * <p>Use CollationKey::equals or CollationKey::compare to compare the
+     * generated sort keys.
+     * If the source string is null, a null collation key will be returned.
+     * @param source the source string to be transformed into a sort key.
+     * @param key the collation key to be filled in
+     * @param status the error code status.
+     * @return the collation key of the string based on the collation rules.
+     * @see CollationKey#compare
+     * @deprecated ICU 2.8 Use getSortKey(...) instead
+     */
+    virtual CollationKey& getCollationKey(const UnicodeString&  source,
+                                          CollationKey& key,
+                                          UErrorCode& status) const = 0;
+
+    /**
+     * Transforms the string into a series of characters that can be compared
+     * with CollationKey::compareTo. It is not possible to restore the original
+     * string from the chars in the sort key.  The generated sort key handles
+     * only a limited number of ignorable characters.
+     * <p>Use CollationKey::equals or CollationKey::compare to compare the
+     * generated sort keys.
+     * <p>If the source string is null, a null collation key will be returned.
+     * @param source the source string to be transformed into a sort key.
+     * @param sourceLength length of the collation key
+     * @param key the collation key to be filled in
+     * @param status the error code status.
+     * @return the collation key of the string based on the collation rules.
+     * @see CollationKey#compare
+     * @deprecated ICU 2.8 Use getSortKey(...) instead
+     */
+    virtual CollationKey& getCollationKey(const UChar*source,
+                                          int32_t sourceLength,
+                                          CollationKey& key,
+                                          UErrorCode& status) const = 0;
+    /**
+     * Generates the hash code for the collation object
+     * @stable ICU 2.0
+     */
+    virtual int32_t hashCode(void) const = 0;
+
+    /**
+     * Gets the locale of the Collator
+     *
+     * @param type can be either requested, valid or actual locale. For more
+     *             information see the definition of ULocDataLocaleType in
+     *             uloc.h
+     * @param status the error code status.
+     * @return locale where the collation data lives. If the collator
+     *         was instantiated from rules, locale is empty.
+     * @deprecated ICU 2.8 This API is under consideration for revision
+     * in ICU 3.0.
+     */
+    virtual const Locale getLocale(ULocDataLocaleType type, UErrorCode& status) const = 0;
+
+    /**
+     * Convenience method for comparing two strings based on the collation rules.
+     * @param source the source string to be compared with.
+     * @param target the target string to be compared with.
+     * @return true if the first string is greater than the second one,
+     *         according to the collation rules. false, otherwise.
+     * @see Collator#compare
+     * @stable ICU 2.0
+     */
+    UBool greater(const UnicodeString& source, const UnicodeString& target)
+                  const;
+
+    /**
+     * Convenience method for comparing two strings based on the collation rules.
+     * @param source the source string to be compared with.
+     * @param target the target string to be compared with.
+     * @return true if the first string is greater than or equal to the second
+     *         one, according to the collation rules. false, otherwise.
+     * @see Collator#compare
+     * @stable ICU 2.0
+     */
+    UBool greaterOrEqual(const UnicodeString& source,
+                         const UnicodeString& target) const;
+
+    /**
+     * Convenience method for comparing two strings based on the collation rules.
+     * @param source the source string to be compared with.
+     * @param target the target string to be compared with.
+     * @return true if the strings are equal according to the collation rules.
+     *         false, otherwise.
+     * @see Collator#compare
+     * @stable ICU 2.0
+     */
+    UBool equals(const UnicodeString& source, const UnicodeString& target) const;
+
+    /**
+     * Determines the minimum strength that will be use in comparison or
+     * transformation.
+     * <p>E.g. with strength == SECONDARY, the tertiary difference is ignored
+     * <p>E.g. with strength == PRIMARY, the secondary and tertiary difference
+     * are ignored.
+     * @return the current comparison level.
+     * @see Collator#setStrength
+     * @deprecated ICU 2.6 Use getAttribute(UCOL_STRENGTH...) instead
+     */
+    virtual ECollationStrength getStrength(void) const = 0;
+
+    /**
+     * Sets the minimum strength to be used in comparison or transformation.
+     * <p>Example of use:
+     * <pre>
+     *  \code
+     *  UErrorCode status = U_ZERO_ERROR;
+     *  Collator*myCollation = Collator::createInstance(Locale::US, status);
+     *  if (U_FAILURE(status)) return;
+     *  myCollation->setStrength(Collator::PRIMARY);
+     *  // result will be "abc" == "ABC"
+     *  // tertiary differences will be ignored
+     *  Collator::ComparisonResult result = myCollation->compare("abc", "ABC");
+     * \endcode
+     * </pre>
+     * @see Collator#getStrength
+     * @param newStrength the new comparison level.
+     * @deprecated ICU 2.6 Use setAttribute(UCOL_STRENGTH...) instead
+     */
+    virtual void setStrength(ECollationStrength newStrength) = 0;
+
+    /**
+     * Get name of the object for the desired Locale, in the desired langauge
+     * @param objectLocale must be from getAvailableLocales
+     * @param displayLocale specifies the desired locale for output
+     * @param name the fill-in parameter of the return value
+     * @return display-able name of the object for the object locale in the
+     *         desired language
+     * @stable ICU 2.0
+     */
+    static UnicodeString& U_EXPORT2 getDisplayName(const Locale& objectLocale,
+                                         const Locale& displayLocale,
+                                         UnicodeString& name);
+
+    /**
+    * Get name of the object for the desired Locale, in the langauge of the
+    * default locale.
+    * @param objectLocale must be from getAvailableLocales
+    * @param name the fill-in parameter of the return value
+    * @return name of the object for the desired locale in the default language
+    * @stable ICU 2.0
+    */
+    static UnicodeString& U_EXPORT2 getDisplayName(const Locale& objectLocale,
+                                         UnicodeString& name);
+
+    /**
+     * Get the set of Locales for which Collations are installed.
+     *
+     * <p>Note this does not include locales supported by registered collators.
+     * If collators might have been registered, use the overload of getAvailableLocales
+     * that returns a StringEnumeration.</p>
+     *
+     * @param count the output parameter of number of elements in the locale list
+     * @return the list of available locales for which collations are installed
+     * @stable ICU 2.0
+     */
+    static const Locale* U_EXPORT2 getAvailableLocales(int32_t& count);
+
+    /**
+     * Return a StringEnumeration over the locales available at the time of the call,
+     * including registered locales.  If a severe error occurs (such as out of memory
+     * condition) this will return null. If there is no locale data, an empty enumeration
+     * will be returned.
+     * @return a StringEnumeration over the locales available at the time of the call
+     * @stable ICU 2.6
+     */
+    static StringEnumeration* U_EXPORT2 getAvailableLocales(void);
+
+    /**
+     * Create a string enumerator of all possible keywords that are relevant to
+     * collation. At this point, the only recognized keyword for this
+     * service is "collation".
+     * @param status input-output error code
+     * @return a string enumeration over locale strings. The caller is
+     * responsible for closing the result.
+     * @stable ICU 3.0
+     */
+    static StringEnumeration* U_EXPORT2 getKeywords(UErrorCode& status);
+
+    /**
+     * Given a keyword, create a string enumeration of all values
+     * for that keyword that are currently in use.
+     * @param keyword a particular keyword as enumerated by
+     * ucol_getKeywords. If any other keyword is passed in, status is set
+     * to U_ILLEGAL_ARGUMENT_ERROR.
+     * @param status input-output error code
+     * @return a string enumeration over collation keyword values, or NULL
+     * upon error. The caller is responsible for deleting the result.
+     * @stable ICU 3.0
+     */
+    static StringEnumeration* U_EXPORT2 getKeywordValues(const char *keyword, UErrorCode& status);
+
+    /**
+     * Return the functionally equivalent locale for the given
+     * requested locale, with respect to given keyword, for the
+     * collation service.  If two locales return the same result, then
+     * collators instantiated for these locales will behave
+     * equivalently.  The converse is not always true; two collators
+     * may in fact be equivalent, but return different results, due to
+     * internal details.  The return result has no other meaning than
+     * that stated above, and implies nothing as to the relationship
+     * between the two locales.  This is intended for use by
+     * applications who wish to cache collators, or otherwise reuse
+     * collators when possible.  The functional equivalent may change
+     * over time.  For more information, please see the <a
+     * href="http://icu-project.org/userguide/locale.html#services">
+     * Locales and Services</a> section of the ICU User Guide.
+     * @param keyword a particular keyword as enumerated by
+     * ucol_getKeywords.
+     * @param locale the requested locale
+     * @param isAvailable reference to a fillin parameter that
+     * indicates whether the requested locale was 'available' to the
+     * collation service. A locale is defined as 'available' if it
+     * physically exists within the collation locale data.
+     * @param status reference to input-output error code
+     * @return the functionally equivalent collation locale, or the root
+     * locale upon error.
+     * @stable ICU 3.0
+     */
+    static Locale U_EXPORT2 getFunctionalEquivalent(const char* keyword, const Locale& locale,
+                                          UBool& isAvailable, UErrorCode& status);
+
+#if !UCONFIG_NO_SERVICE
+    /**
+     * Register a new Collator.  The collator will be adopted.
+     * @param toAdopt the Collator instance to be adopted
+     * @param locale the locale with which the collator will be associated
+     * @param status the in/out status code, no special meanings are assigned
+     * @return a registry key that can be used to unregister this collator
+     * @stable ICU 2.6
+     */
+    static URegistryKey U_EXPORT2 registerInstance(Collator* toAdopt, const Locale& locale, UErrorCode& status);
+
+    /**
+     * Register a new CollatorFactory.  The factory will be adopted.
+     * @param toAdopt the CollatorFactory instance to be adopted
+     * @param status the in/out status code, no special meanings are assigned
+     * @return a registry key that can be used to unregister this collator
+     * @stable ICU 2.6
+     */
+    static URegistryKey U_EXPORT2 registerFactory(CollatorFactory* toAdopt, UErrorCode& status);
+
+    /**
+     * Unregister a previously-registered Collator or CollatorFactory
+     * using the key returned from the register call.  Key becomes
+     * invalid after a successful call and should not be used again.
+     * The object corresponding to the key will be deleted.
+     * @param key the registry key returned by a previous call to registerInstance
+     * @param status the in/out status code, no special meanings are assigned
+     * @return TRUE if the collator for the key was successfully unregistered
+     * @stable ICU 2.6
+     */
+    static UBool U_EXPORT2 unregister(URegistryKey key, UErrorCode& status);
+#endif /* UCONFIG_NO_SERVICE */
+
+    /**
+     * Gets the version information for a Collator.
+     * @param info the version # information, the result will be filled in
+     * @stable ICU 2.0
+     */
+    virtual void getVersion(UVersionInfo info) const = 0;
+
+    /**
+     * Returns a unique class ID POLYMORPHICALLY. Pure virtual method.
+     * This method is to implement a simple version of RTTI, since not all C++
+     * compilers support genuine RTTI. Polymorphic operator==() and clone()
+     * methods call this method.
+     * @return The class ID for this object. All objects of a given class have
+     *         the same class ID.  Objects of other classes have different class
+     *         IDs.
+     * @stable ICU 2.0
+     */
+    virtual UClassID getDynamicClassID(void) const = 0;
+
+    /**
+     * Universal attribute setter
+     * @param attr attribute type
+     * @param value attribute value
+     * @param status to indicate whether the operation went on smoothly or
+     *        there were errors
+     * @stable ICU 2.2
+     */
+    virtual void setAttribute(UColAttribute attr, UColAttributeValue value,
+                              UErrorCode &status) = 0;
+
+    /**
+     * Universal attribute getter
+     * @param attr attribute type
+     * @param status to indicate whether the operation went on smoothly or
+     *        there were errors
+     * @return attribute value
+     * @stable ICU 2.2
+     */
+    virtual UColAttributeValue getAttribute(UColAttribute attr,
+                                            UErrorCode &status) = 0;
+
+    /**
+     * Sets the variable top to a collation element value of a string supplied.
+     * @param varTop one or more (if contraction) UChars to which the variable top should be set
+     * @param len length of variable top string. If -1 it is considered to be zero terminated.
+     * @param status error code. If error code is set, the return value is undefined. Errors set by this function are: <br>
+     *    U_CE_NOT_FOUND_ERROR if more than one character was passed and there is no such a contraction<br>
+     *    U_PRIMARY_TOO_LONG_ERROR if the primary for the variable top has more than two bytes
+     * @return a 32 bit value containing the value of the variable top in upper 16 bits. Lower 16 bits are undefined
+     * @stable ICU 2.0
+     */
+    virtual uint32_t setVariableTop(const UChar *varTop, int32_t len, UErrorCode &status) = 0;
+
+    /**
+     * Sets the variable top to a collation element value of a string supplied.
+     * @param varTop an UnicodeString size 1 or more (if contraction) of UChars to which the variable top should be set
+     * @param status error code. If error code is set, the return value is undefined. Errors set by this function are: <br>
+     *    U_CE_NOT_FOUND_ERROR if more than one character was passed and there is no such a contraction<br>
+     *    U_PRIMARY_TOO_LONG_ERROR if the primary for the variable top has more than two bytes
+     * @return a 32 bit value containing the value of the variable top in upper 16 bits. Lower 16 bits are undefined
+     * @stable ICU 2.0
+     */
+    virtual uint32_t setVariableTop(const UnicodeString varTop, UErrorCode &status) = 0;
+
+    /**
+     * Sets the variable top to a collation element value supplied. Variable top is set to the upper 16 bits.
+     * Lower 16 bits are ignored.
+     * @param varTop CE value, as returned by setVariableTop or ucol)getVariableTop
+     * @param status error code (not changed by function)
+     * @stable ICU 2.0
+     */
+    virtual void setVariableTop(const uint32_t varTop, UErrorCode &status) = 0;
+
+    /**
+     * Gets the variable top value of a Collator.
+     * Lower 16 bits are undefined and should be ignored.
+     * @param status error code (not changed by function). If error code is set, the return value is undefined.
+     * @stable ICU 2.0
+     */
+    virtual uint32_t getVariableTop(UErrorCode &status) const = 0;
+
+    /**
+     * Get an UnicodeSet that contains all the characters and sequences
+     * tailored in this collator.
+     * @param status      error code of the operation
+     * @return a pointer to a UnicodeSet object containing all the
+     *         code points and sequences that may sort differently than
+     *         in the UCA. The object must be disposed of by using delete
+     * @stable ICU 2.4
+     */
+    virtual UnicodeSet *getTailoredSet(UErrorCode &status) const;
+
+
+    /**
+     * Thread safe cloning operation
+     * @return pointer to the new clone, user should remove it.
+     * @stable ICU 2.2
+     */
+    virtual Collator* safeClone(void) = 0;
+
+    /**
+     * Get the sort key as an array of bytes from an UnicodeString.
+     * Sort key byte arrays are zero-terminated and can be compared using
+     * strcmp().
+     * @param source string to be processed.
+     * @param result buffer to store result in. If NULL, number of bytes needed
+     *        will be returned.
+     * @param resultLength length of the result buffer. If if not enough the
+     *        buffer will be filled to capacity.
+     * @return Number of bytes needed for storing the sort key
+     * @stable ICU 2.2
+     */
+    virtual int32_t getSortKey(const UnicodeString& source,
+                              uint8_t* result,
+                              int32_t resultLength) const = 0;
+
+    /**
+     * Get the sort key as an array of bytes from an UChar buffer.
+     * Sort key byte arrays are zero-terminated and can be compared using
+     * strcmp().
+     * @param source string to be processed.
+     * @param sourceLength length of string to be processed.
+     *        If -1, the string is 0 terminated and length will be decided by the
+     *        function.
+     * @param result buffer to store result in. If NULL, number of bytes needed
+     *        will be returned.
+     * @param resultLength length of the result buffer. If if not enough the
+     *        buffer will be filled to capacity.
+     * @return Number of bytes needed for storing the sort key
+     * @stable ICU 2.2
+     */
+    virtual int32_t getSortKey(const UChar*source, int32_t sourceLength,
+                               uint8_t*result, int32_t resultLength) const = 0;
+
+    /**
+     * Produce a bound for a given sortkey and a number of levels.
+     * Return value is always the number of bytes needed, regardless of
+     * whether the result buffer was big enough or even valid.<br>
+     * Resulting bounds can be used to produce a range of strings that are
+     * between upper and lower bounds. For example, if bounds are produced
+     * for a sortkey of string "smith", strings between upper and lower
+     * bounds with one level would include "Smith", "SMITH", "sMiTh".<br>
+     * There are two upper bounds that can be produced. If UCOL_BOUND_UPPER
+     * is produced, strings matched would be as above. However, if bound
+     * produced using UCOL_BOUND_UPPER_LONG is used, the above example will
+     * also match "Smithsonian" and similar.<br>
+     * For more on usage, see example in cintltst/capitst.c in procedure
+     * TestBounds.
+     * Sort keys may be compared using <TT>strcmp</TT>.
+     * @param source The source sortkey.
+     * @param sourceLength The length of source, or -1 if null-terminated.
+     *                     (If an unmodified sortkey is passed, it is always null
+     *                      terminated).
+     * @param boundType Type of bound required. It can be UCOL_BOUND_LOWER, which
+     *                  produces a lower inclusive bound, UCOL_BOUND_UPPER, that
+     *                  produces upper bound that matches strings of the same length
+     *                  or UCOL_BOUND_UPPER_LONG that matches strings that have the
+     *                  same starting substring as the source string.
+     * @param noOfLevels  Number of levels required in the resulting bound (for most
+     *                    uses, the recommended value is 1). See users guide for
+     *                    explanation on number of levels a sortkey can have.
+     * @param result A pointer to a buffer to receive the resulting sortkey.
+     * @param resultLength The maximum size of result.
+     * @param status Used for returning error code if something went wrong. If the
+     *               number of levels requested is higher than the number of levels
+     *               in the source key, a warning (U_SORT_KEY_TOO_SHORT_WARNING) is
+     *               issued.
+     * @return The size needed to fully store the bound.
+     * @see ucol_keyHashCode
+     * @stable ICU 2.1
+     */
+    static int32_t U_EXPORT2 getBound(const uint8_t       *source,
+            int32_t             sourceLength,
+            UColBoundMode       boundType,
+            uint32_t            noOfLevels,
+            uint8_t             *result,
+            int32_t             resultLength,
+            UErrorCode          &status);
+
+
+protected:
+
+    // Collator protected constructors -------------------------------------
+
+    /**
+    * Default constructor.
+    * Constructor is different from the old default Collator constructor.
+    * The task for determing the default collation strength and normalization
+    * mode is left to the child class.
+    * @stable ICU 2.0
+    */
+    Collator();
+
+    /**
+    * Constructor.
+    * Empty constructor, does not handle the arguments.
+    * This constructor is done for backward compatibility with 1.7 and 1.8.
+    * The task for handling the argument collation strength and normalization
+    * mode is left to the child class.
+    * @param collationStrength collation strength
+    * @param decompositionMode
+    * @deprecated ICU 2.4. Subclasses should use the default constructor
+    * instead and handle the strength and normalization mode themselves.
+    */
+    Collator(UCollationStrength collationStrength,
+             UNormalizationMode decompositionMode);
+
+    /**
+    * Copy constructor.
+    * @param other Collator object to be copied from
+    * @stable ICU 2.0
+    */
+    Collator(const Collator& other);
+
+    // Collator protected methods -----------------------------------------
+
+
+   /**
+    * Used internally by registraton to define the requested and valid locales.
+    * @param requestedLocale the requsted locale
+    * @param validLocale the valid locale
+    * @internal
+    */
+    virtual void setLocales(const Locale& requestedLocale, const Locale& validLocale, const Locale& actualLocale);
+
+public:
+#if !UCONFIG_NO_SERVICE
+    /**
+     * used only by ucol_open, not for public use
+     * @internal
+     */
+    static UCollator* createUCollator(const char* loc, UErrorCode* status);
+#endif
+private:
+    /**
+     * Assignment operator. Private for now.
+     * @internal
+     */
+    Collator& operator=(const Collator& other);
+
+    friend class CFactory;
+    friend class SimpleCFactory;
+    friend class ICUCollatorFactory;
+    friend class ICUCollatorService;
+    static Collator* makeInstance(const Locale& desiredLocale,
+                                  UErrorCode& status);
+
+    // Collator private data members ---------------------------------------
+
+    /*
+    synwee : removed as attributes to be handled by child class
+    UCollationStrength  strength;
+    Normalizer::EMode  decmp;
+    */
+    /* This is useless information */
+/*  static const UVersionInfo fVersion;*/
+};
+
+#if !UCONFIG_NO_SERVICE
+/**
+ * A factory, used with registerFactory, the creates multiple collators and provides
+ * display names for them.  A factory supports some number of locales-- these are the
+ * locales for which it can create collators.  The factory can be visible, in which
+ * case the supported locales will be enumerated by getAvailableLocales, or invisible,
+ * in which they are not.  Invisible locales are still supported, they are just not
+ * listed by getAvailableLocales.
+ * <p>
+ * If standard locale display names are sufficient, Collator instances can
+ * be registered using registerInstance instead.</p>
+ * <p>
+ * Note: if the collators are to be used from C APIs, they must be instances
+ * of RuleBasedCollator.</p>
+ *
+ * @stable ICU 2.6
+ */
+class U_I18N_API CollatorFactory : public UObject {
+public:
+
+    /**
+     * Destructor
+     * @stable ICU 3.0
+     */
+    virtual ~CollatorFactory();
+
+    /**
+     * Return true if this factory is visible.  Default is true.
+     * If not visible, the locales supported by this factory will not
+     * be listed by getAvailableLocales.
+     * @return true if the factory is visible.
+     * @stable ICU 2.6
+     */
+    virtual UBool visible(void) const;
+
+    /**
+     * Return a collator for the provided locale.  If the locale
+     * is not supported, return NULL.
+     * @param loc the locale identifying the collator to be created.
+     * @return a new collator if the locale is supported, otherwise NULL.
+     * @stable ICU 2.6
+     */
+    virtual Collator* createCollator(const Locale& loc) = 0;
+
+    /**
+     * Return the name of the collator for the objectLocale, localized for the displayLocale.
+     * If objectLocale is not supported, or the factory is not visible, set the result string
+     * to bogus.
+     * @param objectLocale the locale identifying the collator
+     * @param displayLocale the locale for which the display name of the collator should be localized
+     * @param result an output parameter for the display name, set to bogus if not supported.
+     * @return the display name
+     * @stable ICU 2.6
+     */
+    virtual  UnicodeString& getDisplayName(const Locale& objectLocale,
+                                           const Locale& displayLocale,
+                                           UnicodeString& result);
+
+    /**
+     * Return an array of all the locale names directly supported by this factory.
+     * The number of names is returned in count.  This array is owned by the factory.
+     * Its contents must never change.
+     * @param count output parameter for the number of locales supported by the factory
+     * @param status the in/out error code
+     * @return a pointer to an array of count UnicodeStrings.
+     * @stable ICU 2.6
+     */
+    virtual const UnicodeString * getSupportedIDs(int32_t &count, UErrorCode& status) = 0;
+};
+#endif /* UCONFIG_NO_SERVICE */
+
+// Collator inline methods -----------------------------------------------
+
+U_NAMESPACE_END
+
+#endif /* #if !UCONFIG_NO_COLLATION */
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/curramt.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/curramt.h b/src/apps/couch_collate/platform/osx/icu/unicode/curramt.h
new file mode 100644
index 0000000..c33e6f1
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/curramt.h
@@ -0,0 +1,130 @@
+/*
+**********************************************************************
+* Copyright (c) 2004-2006, International Business Machines
+* Corporation and others.  All Rights Reserved.
+**********************************************************************
+* Author: Alan Liu
+* Created: April 26, 2004
+* Since: ICU 3.0
+**********************************************************************
+*/
+#ifndef __CURRENCYAMOUNT_H__
+#define __CURRENCYAMOUNT_H__
+
+#include "unicode/utypes.h"
+
+#if !UCONFIG_NO_FORMATTING
+
+#include "unicode/measure.h"
+#include "unicode/currunit.h"
+
+/**
+ * \file 
+ * \brief C++ API: Currency Amount Object.
+ */
+ 
+U_NAMESPACE_BEGIN
+
+/**
+ *
+ * A currency together with a numeric amount, such as 200 USD.
+ *
+ * @author Alan Liu
+ * @stable ICU 3.0
+ */
+class U_I18N_API CurrencyAmount: public Measure {
+ public:
+    /**
+     * Construct an object with the given numeric amount and the given
+     * ISO currency code.
+     * @param amount a numeric object; amount.isNumeric() must be TRUE
+     * @param isoCode the 3-letter ISO 4217 currency code; must not be
+     * NULL and must have length 3
+     * @param ec input-output error code. If the amount or the isoCode
+     * is invalid, then this will be set to a failing value.
+     * @stable ICU 3.0
+     */
+    CurrencyAmount(const Formattable& amount, const UChar* isoCode,
+                   UErrorCode &ec);
+
+    /**
+     * Construct an object with the given numeric amount and the given
+     * ISO currency code.
+     * @param amount the amount of the given currency
+     * @param isoCode the 3-letter ISO 4217 currency code; must not be
+     * NULL and must have length 3
+     * @param ec input-output error code. If the isoCode is invalid,
+     * then this will be set to a failing value.
+     * @stable ICU 3.0
+     */
+    CurrencyAmount(double amount, const UChar* isoCode,
+                   UErrorCode &ec);
+
+    /**
+     * Copy constructor
+     * @stable ICU 3.0
+     */
+    CurrencyAmount(const CurrencyAmount& other);
+ 
+    /**
+     * Assignment operator
+     * @stable ICU 3.0
+     */
+    CurrencyAmount& operator=(const CurrencyAmount& other);
+
+    /**
+     * Return a polymorphic clone of this object.  The result will
+     * have the same class as returned by getDynamicClassID().
+     * @stable ICU 3.0
+     */
+    virtual UObject* clone() const;
+
+    /**
+     * Destructor
+     * @stable ICU 3.0
+     */
+    virtual ~CurrencyAmount();
+    
+    /**
+     * Returns a unique class ID for this object POLYMORPHICALLY.
+     * This method implements a simple form of RTTI used by ICU.
+     * @return The class ID for this object. All objects of a given
+     * class have the same class ID.  Objects of other classes have
+     * different class IDs.
+     * @stable ICU 3.0
+     */
+    virtual UClassID getDynamicClassID() const;
+
+    /**
+     * Returns the class ID for this class. This is used to compare to
+     * the return value of getDynamicClassID().
+     * @return The class ID for all objects of this class.
+     * @stable ICU 3.0
+     */
+    static UClassID U_EXPORT2 getStaticClassID();
+
+    /**
+     * Return the currency unit object of this object.
+     * @stable ICU 3.0
+     */
+    inline const CurrencyUnit& getCurrency() const;
+
+    /**
+     * Return the ISO currency code of this object.
+     * @stable ICU 3.0
+     */
+    inline const UChar* getISOCurrency() const;
+};
+
+inline const CurrencyUnit& CurrencyAmount::getCurrency() const {
+    return (const CurrencyUnit&) getUnit();
+}
+
+inline const UChar* CurrencyAmount::getISOCurrency() const {
+    return getCurrency().getISOCurrency();
+}
+
+U_NAMESPACE_END
+
+#endif // !UCONFIG_NO_FORMATTING
+#endif // __CURRENCYAMOUNT_H__

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/currunit.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/currunit.h b/src/apps/couch_collate/platform/osx/icu/unicode/currunit.h
new file mode 100644
index 0000000..ecd9411
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/currunit.h
@@ -0,0 +1,117 @@
+/*
+**********************************************************************
+* Copyright (c) 2004-2006, International Business Machines
+* Corporation and others.  All Rights Reserved.
+**********************************************************************
+* Author: Alan Liu
+* Created: April 26, 2004
+* Since: ICU 3.0
+**********************************************************************
+*/
+#ifndef __CURRENCYUNIT_H__
+#define __CURRENCYUNIT_H__
+
+#include "unicode/utypes.h"
+
+#if !UCONFIG_NO_FORMATTING
+
+#include "unicode/measunit.h"
+
+/**
+ * \file 
+ * \brief C++ API: Currency Unit Information.
+ */
+ 
+U_NAMESPACE_BEGIN
+
+/**
+ * A unit of currency, such as USD (U.S. dollars) or JPY (Japanese
+ * yen).  This class is a thin wrapper over a UChar string that
+ * subclasses MeasureUnit, for use with Measure and MeasureFormat.
+ *
+ * @author Alan Liu
+ * @stable ICU 3.0
+ */
+class U_I18N_API CurrencyUnit: public MeasureUnit {
+ public:
+    /**
+     * Construct an object with the given ISO currency code.
+     * @param isoCode the 3-letter ISO 4217 currency code; must not be
+     * NULL and must have length 3
+     * @param ec input-output error code. If the isoCode is invalid,
+     * then this will be set to a failing value.
+     * @stable ICU 3.0
+     */
+    CurrencyUnit(const UChar* isoCode, UErrorCode &ec);
+
+    /**
+     * Copy constructor
+     * @stable ICU 3.0
+     */
+    CurrencyUnit(const CurrencyUnit& other);
+
+    /**
+     * Assignment operator
+     * @stable ICU 3.0
+     */
+    CurrencyUnit& operator=(const CurrencyUnit& other);
+
+    /**
+     * Return a polymorphic clone of this object.  The result will
+     * have the same class as returned by getDynamicClassID().
+     * @stable ICU 3.0
+     */
+    virtual UObject* clone() const;
+
+    /**
+     * Destructor
+     * @stable ICU 3.0
+     */
+    virtual ~CurrencyUnit();
+
+    /**
+     * Equality operator.  Return true if this object is equal
+     * to the given object.
+     * @stable ICU 3.0
+     */
+    UBool operator==(const UObject& other) const;
+
+    /**
+     * Returns a unique class ID for this object POLYMORPHICALLY.
+     * This method implements a simple form of RTTI used by ICU.
+     * @return The class ID for this object. All objects of a given
+     * class have the same class ID.  Objects of other classes have
+     * different class IDs.
+     * @stable ICU 3.0
+     */
+    virtual UClassID getDynamicClassID() const;
+
+    /**
+     * Returns the class ID for this class. This is used to compare to
+     * the return value of getDynamicClassID().
+     * @return The class ID for all objects of this class.
+     * @stable ICU 3.0
+     */
+    static UClassID U_EXPORT2 getStaticClassID();
+
+    /**
+     * Return the ISO currency code of this object.
+     * @stable ICU 3.0
+     */
+    inline const UChar* getISOCurrency() const;
+
+ private:
+    /**
+     * The ISO 4217 code of this object.
+     */
+    UChar isoCode[4];
+};
+
+inline const UChar* CurrencyUnit::getISOCurrency() const {
+    return isoCode;
+}
+
+U_NAMESPACE_END
+
+#endif // !UCONFIG_NO_FORMATTING
+#endif // __CURRENCYUNIT_H__

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/datefmt.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/datefmt.h b/src/apps/couch_collate/platform/osx/icu/unicode/datefmt.h
new file mode 100644
index 0000000..7aeab2c
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/datefmt.h
@@ -0,0 +1,700 @@
+/*
+ ********************************************************************************
+ *   Copyright (C) 1997-2008, International Business Machines
+ *   Corporation and others.  All Rights Reserved.
+ ********************************************************************************
+ *
+ * File DATEFMT.H
+ *
+ * Modification History:
+ *
+ *   Date        Name        Description
+ *   02/19/97    aliu        Converted from java.
+ *   04/01/97    aliu        Added support for centuries.
+ *   07/23/98    stephen     JDK 1.2 sync
+ *   11/15/99    weiv        Added support for week of year/day of week formatting
+ ********************************************************************************
+ */
+
+#ifndef DATEFMT_H
+#define DATEFMT_H
+
+#include "unicode/utypes.h"
+
+#if !UCONFIG_NO_FORMATTING
+
+#include "unicode/udat.h"
+#include "unicode/calendar.h"
+#include "unicode/numfmt.h"
+#include "unicode/format.h"
+#include "unicode/locid.h"
+
+/**
+ * \file 
+ * \brief C++ API: Abstract class for converting dates.
+ */
+
+U_NAMESPACE_BEGIN
+
+class TimeZone;
+
+/**
+ * DateFormat is an abstract class for a family of classes that convert dates and
+ * times from their internal representations to textual form and back again in a
+ * language-independent manner. Converting from the internal representation (milliseconds
+ * since midnight, January 1, 1970) to text is known as "formatting," and converting
+ * from text to millis is known as "parsing."  We currently define only one concrete
+ * subclass of DateFormat: SimpleDateFormat, which can handle pretty much all normal
+ * date formatting and parsing actions.
+ * <P>
+ * DateFormat helps you to format and parse dates for any locale. Your code can
+ * be completely independent of the locale conventions for months, days of the
+ * week, or even the calendar format: lunar vs. solar.
+ * <P>
+ * To format a date for the current Locale, use one of the static factory
+ * methods:
+ * <pre>
+ * \code
+ *      DateFormat* dfmt = DateFormat::createDateInstance();
+ *      UDate myDate = Calendar::getNow();
+ *      UnicodeString myString;
+ *      myString = dfmt->format( myDate, myString );
+ * \endcode
+ * </pre>
+ * If you are formatting multiple numbers, it is more efficient to get the
+ * format and use it multiple times so that the system doesn't have to fetch the
+ * information about the local language and country conventions multiple times.
+ * <pre>
+ * \code
+ *      DateFormat* df = DateFormat::createDateInstance();
+ *      UnicodeString myString;
+ *      UDate myDateArr[] = { 0.0, 100000000.0, 2000000000.0 }; // test values
+ *      for (int32_t i = 0; i < 3; ++i) {
+ *          myString.remove();
+ *          cout << df->format( myDateArr[i], myString ) << endl;
+ *      }
+ * \endcode
+ * </pre>
+ * To get specific fields of a date, you can use UFieldPosition to
+ * get specific fields.
+ * <pre>
+ * \code
+ *      DateFormat* dfmt = DateFormat::createDateInstance();
+ *      FieldPosition pos(DateFormat::YEAR_FIELD);
+ *      UnicodeString myString;
+ *      myString = dfmt->format( myDate, myString );
+ *      cout << myString << endl;
+ *      cout << pos.getBeginIndex() << "," << pos. getEndIndex() << endl;
+ * \endcode
+ * </pre>
+ * To format a date for a different Locale, specify it in the call to
+ * createDateInstance().
+ * <pre>
+ * \code
+ *       DateFormat* df =
+ *           DateFormat::createDateInstance( DateFormat::SHORT, Locale::getFrance());
+ * \endcode
+ * </pre>
+ * You can use a DateFormat to parse also.
+ * <pre>
+ * \code
+ *       UErrorCode status = U_ZERO_ERROR;
+ *       UDate myDate = df->parse(myString, status);
+ * \endcode
+ * </pre>
+ * Use createDateInstance() to produce the normal date format for that country.
+ * There are other static factory methods available. Use createTimeInstance()
+ * to produce the normal time format for that country. Use createDateTimeInstance()
+ * to produce a DateFormat that formats both date and time. You can pass in
+ * different options to these factory methods to control the length of the
+ * result; from SHORT to MEDIUM to LONG to FULL. The exact result depends on the
+ * locale, but generally:
+ * <ul type=round>
+ *   <li>   SHORT is completely numeric, such as 12/13/52 or 3:30pm
+ *   <li>   MEDIUM is longer, such as Jan 12, 1952
+ *   <li>   LONG is longer, such as January 12, 1952 or 3:30:32pm
+ *   <li>   FULL is pretty completely specified, such as
+ *          Tuesday, April 12, 1952 AD or 3:30:42pm PST.
+ * </ul>
+ * You can also set the time zone on the format if you wish. If you want even
+ * more control over the format or parsing, (or want to give your users more
+ * control), you can try casting the DateFormat you get from the factory methods
+ * to a SimpleDateFormat. This will work for the majority of countries; just
+ * remember to chck getDynamicClassID() before carrying out the cast.
+ * <P>
+ * You can also use forms of the parse and format methods with ParsePosition and
+ * FieldPosition to allow you to
+ * <ul type=round>
+ *   <li>   Progressively parse through pieces of a string.
+ *   <li>   Align any particular field, or find out where it is for selection
+ *          on the screen.
+ * </ul>
+ *
+ * <p><em>User subclasses are not supported.</em> While clients may write
+ * subclasses, such code will not necessarily work and will not be
+ * guaranteed to work stably from release to release.
+ */
+class U_I18N_API DateFormat : public Format {
+public:
+
+    /**
+     * Constants for various style patterns. These reflect the order of items in
+     * the DateTimePatterns resource. There are 4 time patterns, 4 date patterns,
+     * and then the date-time pattern. Each block of 4 values in the resource occurs
+     * in the order full, long, medium, short.
+     * @stable ICU 2.4
+     */
+    enum EStyle
+    {
+        kNone   = -1,
+
+        kFull   = 0,
+        kLong   = 1,
+        kMedium = 2,
+        kShort  = 3,
+
+        kDateOffset   = kShort + 1,
+     // kFull   + kDateOffset = 4
+     // kLong   + kDateOffset = 5
+     // kMedium + kDateOffset = 6
+     // kShort  + kDateOffset = 7
+
+        kDateTime             = 8,
+        
+
+        // relative dates
+        kRelative = (1 << 7),
+        
+        kFullRelative = (kFull | kRelative),
+            
+        kLongRelative = kLong | kRelative,
+        
+        kMediumRelative = kMedium | kRelative,
+        
+        kShortRelative = kShort | kRelative,
+        
+
+        kDefault      = kMedium,
+
+
+
+    /**
+     * These constants are provided for backwards compatibility only.
+     * Please use the C++ style constants defined above.
+     */
+        FULL        = kFull,
+        LONG        = kLong,
+        MEDIUM        = kMedium,
+        SHORT        = kShort,
+        DEFAULT        = kDefault,
+        DATE_OFFSET    = kDateOffset,
+        NONE        = kNone,
+        DATE_TIME    = kDateTime
+    };
+
+    /**
+     * Destructor.
+     * @stable ICU 2.0
+     */
+    virtual ~DateFormat();
+
+    /**
+     * Equality operator.  Returns true if the two formats have the same behavior.
+     * @stable ICU 2.0
+     */
+    virtual UBool operator==(const Format&) const;
+
+    /**
+     * Format an object to produce a string. This method handles Formattable
+     * objects with a UDate type. If a the Formattable object type is not a Date,
+     * then it returns a failing UErrorCode.
+     *
+     * @param obj       The object to format. Must be a Date.
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     * @param pos       On input: an alignment field, if desired.
+     *                  On output: the offsets of the alignment field.
+     * @param status    Output param filled with success/failure status.
+     * @return          Reference to 'appendTo' parameter.
+     * @stable ICU 2.0
+     */
+    virtual UnicodeString& format(const Formattable& obj,
+                                  UnicodeString& appendTo,
+                                  FieldPosition& pos,
+                                  UErrorCode& status) const;
+
+    /**
+     * Formats a date into a date/time string. This is an abstract method which
+     * concrete subclasses must implement.
+     * <P>
+     * On input, the FieldPosition parameter may have its "field" member filled with
+     * an enum value specifying a field.  On output, the FieldPosition will be filled
+     * in with the text offsets for that field.
+     * <P> For example, given a time text
+     * "1996.07.10 AD at 15:08:56 PDT", if the given fieldPosition.field is
+     * UDAT_YEAR_FIELD, the offsets fieldPosition.beginIndex and
+     * statfieldPositionus.getEndIndex will be set to 0 and 4, respectively.
+     * <P> Notice
+     * that if the same time field appears more than once in a pattern, the status will
+     * be set for the first occurence of that time field. For instance,
+     * formatting a UDate to the time string "1 PM PDT (Pacific Daylight Time)"
+     * using the pattern "h a z (zzzz)" and the alignment field
+     * DateFormat::TIMEZONE_FIELD, the offsets fieldPosition.beginIndex and
+     * fieldPosition.getEndIndex will be set to 5 and 8, respectively, for the first
+     * occurence of the timezone pattern character 'z'.
+     *
+     * @param cal           Calendar set to the date and time to be formatted
+     *                      into a date/time string.
+     * @param appendTo      Output parameter to receive result.
+     *                      Result is appended to existing contents.
+     * @param fieldPosition On input: an alignment field, if desired (see examples above)
+     *                      On output: the offsets of the alignment field (see examples above)
+     * @return              Reference to 'appendTo' parameter.
+     * @stable ICU 2.1
+     */
+    virtual UnicodeString& format(  Calendar& cal,
+                                    UnicodeString& appendTo,
+                                    FieldPosition& fieldPosition) const = 0;
+
+    /**
+     * Formats a UDate into a date/time string.
+     * <P>
+     * On input, the FieldPosition parameter may have its "field" member filled with
+     * an enum value specifying a field.  On output, the FieldPosition will be filled
+     * in with the text offsets for that field.
+     * <P> For example, given a time text
+     * "1996.07.10 AD at 15:08:56 PDT", if the given fieldPosition.field is
+     * UDAT_YEAR_FIELD, the offsets fieldPosition.beginIndex and
+     * statfieldPositionus.getEndIndex will be set to 0 and 4, respectively.
+     * <P> Notice
+     * that if the same time field appears more than once in a pattern, the status will
+     * be set for the first occurence of that time field. For instance,
+     * formatting a UDate to the time string "1 PM PDT (Pacific Daylight Time)"
+     * using the pattern "h a z (zzzz)" and the alignment field
+     * DateFormat::TIMEZONE_FIELD, the offsets fieldPosition.beginIndex and
+     * fieldPosition.getEndIndex will be set to 5 and 8, respectively, for the first
+     * occurence of the timezone pattern character 'z'.
+     *
+     * @param date          UDate to be formatted into a date/time string.
+     * @param appendTo      Output parameter to receive result.
+     *                      Result is appended to existing contents.
+     * @param fieldPosition On input: an alignment field, if desired (see examples above)
+     *                      On output: the offsets of the alignment field (see examples above)
+     * @return              Reference to 'appendTo' parameter.
+     * @stable ICU 2.0
+     */
+    UnicodeString& format(  UDate date,
+                            UnicodeString& appendTo,
+                            FieldPosition& fieldPosition) const;
+
+    /**
+     * Formats a UDate into a date/time string. If there is a problem, you won't
+     * know, using this method. Use the overloaded format() method which takes a
+     * FieldPosition& to detect formatting problems.
+     *
+     * @param date      The UDate value to be formatted into a string.
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     * @return          Reference to 'appendTo' parameter.
+     * @stable ICU 2.0
+     */
+    UnicodeString& format(UDate date, UnicodeString& appendTo) const;
+
+    /**
+     * Redeclared Format method.
+     *
+     * @param obj       The object to be formatted into a string.
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     * @param status    Output param filled with success/failure status.
+     * @return          Reference to 'appendTo' parameter.
+     * @stable ICU 2.0
+     */
+    UnicodeString& format(const Formattable& obj,
+                          UnicodeString& appendTo,
+                          UErrorCode& status) const;
+
+    /**
+     * Parse a date/time string.
+     *
+     * @param text      The string to be parsed into a UDate value.
+     * @param status    Output param to be set to success/failure code. If
+     *                  'text' cannot be parsed, it will be set to a failure
+     *                  code.
+     * @result          The parsed UDate value, if successful.
+     * @stable ICU 2.0
+     */
+    virtual UDate parse( const UnicodeString& text,
+                        UErrorCode& status) const;
+
+    /**
+     * Parse a date/time string beginning at the given parse position. For
+     * example, a time text "07/10/96 4:5 PM, PDT" will be parsed into a Date
+     * that is equivalent to Date(837039928046).
+     * <P>
+     * By default, parsing is lenient: If the input is not in the form used by
+     * this object's format method but can still be parsed as a date, then the
+     * parse succeeds. Clients may insist on strict adherence to the format by
+     * calling setLenient(false).
+     *
+     * @see DateFormat::setLenient(boolean)
+     *
+     * @param text  The date/time string to be parsed
+     * @param cal   a Calendar set to the date and time to be formatted
+     *              into a date/time string.
+     * @param pos   On input, the position at which to start parsing; on
+     *              output, the position at which parsing terminated, or the
+     *              start position if the parse failed.
+     * @return      A valid UDate if the input could be parsed.
+     * @stable ICU 2.1
+     */
+    virtual void parse( const UnicodeString& text,
+                        Calendar& cal,
+                        ParsePosition& pos) const = 0;
+
+    /**
+     * Parse a date/time string beginning at the given parse position. For
+     * example, a time text "07/10/96 4:5 PM, PDT" will be parsed into a Date
+     * that is equivalent to Date(837039928046).
+     * <P>
+     * By default, parsing is lenient: If the input is not in the form used by
+     * this object's format method but can still be parsed as a date, then the
+     * parse succeeds. Clients may insist on strict adherence to the format by
+     * calling setLenient(false).
+     *
+     * @see DateFormat::setLenient(boolean)
+     *
+     * @param text  The date/time string to be parsed
+     * @param pos   On input, the position at which to start parsing; on
+     *              output, the position at which parsing terminated, or the
+     *              start position if the parse failed.
+     * @return      A valid UDate if the input could be parsed.
+     * @stable ICU 2.0
+     */
+    UDate parse( const UnicodeString& text,
+                 ParsePosition& pos) const;
+
+    /**
+     * Parse a string to produce an object. This methods handles parsing of
+     * date/time strings into Formattable objects with UDate types.
+     * <P>
+     * Before calling, set parse_pos.index to the offset you want to start
+     * parsing at in the source. After calling, parse_pos.index is the end of
+     * the text you parsed. If error occurs, index is unchanged.
+     * <P>
+     * When parsing, leading whitespace is discarded (with a successful parse),
+     * while trailing whitespace is left as is.
+     * <P>
+     * See Format::parseObject() for more.
+     *
+     * @param source    The string to be parsed into an object.
+     * @param result    Formattable to be set to the parse result.
+     *                  If parse fails, return contents are undefined.
+     * @param parse_pos The position to start parsing at. Upon return
+     *                  this param is set to the position after the
+     *                  last character successfully parsed. If the
+     *                  source is not parsed successfully, this param
+     *                  will remain unchanged.
+     * @return          A newly created Formattable* object, or NULL
+     *                  on failure.  The caller owns this and should
+     *                  delete it when done.
+     * @stable ICU 2.0
+     */
+    virtual void parseObject(const UnicodeString& source,
+                             Formattable& result,
+                             ParsePosition& parse_pos) const;
+
+    /**
+     * Create a default date/time formatter that uses the SHORT style for both
+     * the date and the time.
+     *
+     * @return A date/time formatter which the caller owns.
+     * @stable ICU 2.0
+     */
+    static DateFormat* U_EXPORT2 createInstance(void);
+
+    /**
+     * This is for ICU internal use only. Please do not use.
+     * Create a date/time formatter from skeleton and a given locale.
+     *
+     * Users are encouraged to use the skeleton macros defined in udat.h.
+     * For example, MONTH_WEEKDAY_DAY, which is "MMMMEEEEd",
+     * and which means the pattern should have day, month, and day-of-week 
+     * fields, and follow the long date format defined in date time pattern.
+     * For example, for English, the full pattern should be 
+     * "EEEE, MMMM d".
+     * 
+     * Temporarily, this is an internal API, used by DateIntevalFormat only.
+     * There will be a new set of APIs for the same purpose coming soon.
+     * After which, this API will be replaced.
+     *
+     * @param skeleton  the skeleton on which date format based.
+     * @param locale    the given locale.
+     * @param status    Output param to be set to success/failure code.
+     *                  If it is failure, the returned date formatter will
+     *                  be NULL.
+     * @return          a simple date formatter which the caller owns.
+     * @internal ICU 4.0
+     */
+    static DateFormat* U_EXPORT2 createPatternInstance(
+                                                const UnicodeString& skeleton,
+                                                const Locale& locale,
+                                                UErrorCode& status);
+
+    /**
+     * Creates a time formatter with the given formatting style for the given
+     * locale.
+     *
+     * @param style     The given formatting style. For example,
+     *                  SHORT for "h:mm a" in the US locale.
+     * @param aLocale   The given locale.
+     * @return          A time formatter which the caller owns.
+     * @stable ICU 2.0
+     */
+    static DateFormat* U_EXPORT2 createTimeInstance(EStyle style = kDefault,
+                                          const Locale& aLocale = Locale::getDefault());
+
+    /**
+     * Creates a date formatter with the given formatting style for the given
+     * const locale.
+     *
+     * @param style     The given formatting style. For example,
+     *                  SHORT for "M/d/yy" in the US locale.
+     * @param aLocale   The given locale.
+     * @return          A date formatter which the caller owns.
+     * @stable ICU 2.0
+     */
+    static DateFormat* U_EXPORT2 createDateInstance(EStyle style = kDefault,
+                                          const Locale& aLocale = Locale::getDefault());
+
+    /**
+     * Creates a date/time formatter with the given formatting styles for the
+     * given locale.
+     *
+     * @param dateStyle The given formatting style for the date portion of the result.
+     *                  For example, SHORT for "M/d/yy" in the US locale.
+     * @param timeStyle The given formatting style for the time portion of the result.
+     *                  For example, SHORT for "h:mm a" in the US locale.
+     * @param aLocale   The given locale.
+     * @return          A date/time formatter which the caller owns.
+     * @stable ICU 2.0
+     */
+    static DateFormat* U_EXPORT2 createDateTimeInstance(EStyle dateStyle = kDefault,
+                                              EStyle timeStyle = kDefault,
+                                              const Locale& aLocale = Locale::getDefault());
+
+    /**
+     * Gets the set of locales for which DateFormats are installed.
+     * @param count Filled in with the number of locales in the list that is returned.
+     * @return the set of locales for which DateFormats are installed.  The caller
+     *  does NOT own this list and must not delete it.
+     * @stable ICU 2.0
+     */
+    static const Locale* U_EXPORT2 getAvailableLocales(int32_t& count);
+
+    /**
+     * Returns true if the formatter is set for lenient parsing.
+     * @stable ICU 2.0
+     */
+    virtual UBool isLenient(void) const;
+
+    /**
+     * Specify whether or not date/time parsing is to be lenient. With lenient
+     * parsing, the parser may use heuristics to interpret inputs that do not
+     * precisely match this object's format. With strict parsing, inputs must
+     * match this object's format.
+     *
+     * @param lenient  True specifies date/time interpretation to be lenient.
+     * @see Calendar::setLenient
+     * @stable ICU 2.0
+     */
+    virtual void setLenient(UBool lenient);
+
+    /**
+     * Gets the calendar associated with this date/time formatter.
+     * @return the calendar associated with this date/time formatter.
+     * @stable ICU 2.0
+     */
+    virtual const Calendar* getCalendar(void) const;
+
+    /**
+     * Set the calendar to be used by this date format. Initially, the default
+     * calendar for the specified or default locale is used.  The caller should
+     * not delete the Calendar object after it is adopted by this call.
+     * Adopting a new calendar will change to the default symbols.
+     *
+     * @param calendarToAdopt    Calendar object to be adopted.
+     * @stable ICU 2.0
+     */
+    virtual void adoptCalendar(Calendar* calendarToAdopt);
+
+    /**
+     * Set the calendar to be used by this date format. Initially, the default
+     * calendar for the specified or default locale is used.
+     *
+     * @param newCalendar Calendar object to be set.
+     * @stable ICU 2.0
+     */
+    virtual void setCalendar(const Calendar& newCalendar);
+
+
+    /**
+     * Gets the number formatter which this date/time formatter uses to format
+     * and parse the numeric portions of the pattern.
+     * @return the number formatter which this date/time formatter uses.
+     * @stable ICU 2.0
+     */
+    virtual const NumberFormat* getNumberFormat(void) const;
+
+    /**
+     * Allows you to set the number formatter.  The caller should
+     * not delete the NumberFormat object after it is adopted by this call.
+     * @param formatToAdopt     NumberFormat object to be adopted.
+     * @stable ICU 2.0
+     */
+    virtual void adoptNumberFormat(NumberFormat* formatToAdopt);
+
+    /**
+     * Allows you to set the number formatter.
+     * @param newNumberFormat  NumberFormat object to be set.
+     * @stable ICU 2.0
+     */
+    virtual void setNumberFormat(const NumberFormat& newNumberFormat);
+
+    /**
+     * Returns a reference to the TimeZone used by this DateFormat's calendar.
+     * @return the time zone associated with the calendar of DateFormat.
+     * @stable ICU 2.0
+     */
+    virtual const TimeZone& getTimeZone(void) const;
+
+    /**
+     * Sets the time zone for the calendar of this DateFormat object. The caller
+     * no longer owns the TimeZone object and should not delete it after this call.
+     * @param zoneToAdopt the TimeZone to be adopted.
+     * @stable ICU 2.0
+     */
+    virtual void adoptTimeZone(TimeZone* zoneToAdopt);
+
+    /**
+     * Sets the time zone for the calendar of this DateFormat object.
+     * @param zone the new time zone.
+     * @stable ICU 2.0
+     */
+    virtual void setTimeZone(const TimeZone& zone);
+
+protected:
+    /**
+     * Default constructor.  Creates a DateFormat with no Calendar or NumberFormat
+     * associated with it.  This constructor depends on the subclasses to fill in
+     * the calendar and numberFormat fields.
+     * @stable ICU 2.0
+     */
+    DateFormat();
+
+    /**
+     * Copy constructor.
+     * @stable ICU 2.0
+     */
+    DateFormat(const DateFormat&);
+
+    /**
+     * Default assignment operator.
+     * @stable ICU 2.0
+     */
+    DateFormat& operator=(const DateFormat&);
+
+    /**
+     * The calendar that DateFormat uses to produce the time field values needed
+     * to implement date/time formatting. Subclasses should generally initialize
+     * this to the default calendar for the locale associated with this DateFormat.
+     * @stable ICU 2.4
+     */
+    Calendar* fCalendar;
+
+    /**
+     * The number formatter that DateFormat uses to format numbers in dates and
+     * times. Subclasses should generally initialize this to the default number
+     * format for the locale associated with this DateFormat.
+     * @stable ICU 2.4
+     */
+    NumberFormat* fNumberFormat;
+
+private:
+    /**
+     * Gets the date/time formatter with the given formatting styles for the
+     * given locale.
+     * @param dateStyle the given date formatting style.
+     * @param timeStyle the given time formatting style.
+     * @param inLocale the given locale.
+     * @return a date/time formatter, or 0 on failure.
+     */
+    static DateFormat* U_EXPORT2 create(EStyle timeStyle, EStyle dateStyle, const Locale&);
+
+public:
+    /**
+     * Field selector for FieldPosition for DateFormat fields.
+     * @obsolete ICU 3.4 use UDateFormatField instead, since this API will be
+     * removed in that release
+     */
+    enum EField
+    {
+        // Obsolete; use UDateFormatField instead
+        kEraField = UDAT_ERA_FIELD,
+        kYearField = UDAT_YEAR_FIELD,
+        kMonthField = UDAT_MONTH_FIELD,
+        kDateField = UDAT_DATE_FIELD,
+        kHourOfDay1Field = UDAT_HOUR_OF_DAY1_FIELD,
+        kHourOfDay0Field = UDAT_HOUR_OF_DAY0_FIELD,
+        kMinuteField = UDAT_MINUTE_FIELD,
+        kSecondField = UDAT_SECOND_FIELD,
+        kMillisecondField = UDAT_FRACTIONAL_SECOND_FIELD,
+        kDayOfWeekField = UDAT_DAY_OF_WEEK_FIELD,
+        kDayOfYearField = UDAT_DAY_OF_YEAR_FIELD,
+        kDayOfWeekInMonthField = UDAT_DAY_OF_WEEK_IN_MONTH_FIELD,
+        kWeekOfYearField = UDAT_WEEK_OF_YEAR_FIELD,
+        kWeekOfMonthField = UDAT_WEEK_OF_MONTH_FIELD,
+        kAmPmField = UDAT_AM_PM_FIELD,
+        kHour1Field = UDAT_HOUR1_FIELD,
+        kHour0Field = UDAT_HOUR0_FIELD,
+        kTimezoneField = UDAT_TIMEZONE_FIELD,
+        kYearWOYField = UDAT_YEAR_WOY_FIELD,
+        kDOWLocalField = UDAT_DOW_LOCAL_FIELD,
+        kExtendedYearField = UDAT_EXTENDED_YEAR_FIELD,
+        kJulianDayField = UDAT_JULIAN_DAY_FIELD,
+        kMillisecondsInDayField = UDAT_MILLISECONDS_IN_DAY_FIELD,
+
+        // Obsolete; use UDateFormatField instead
+        ERA_FIELD = UDAT_ERA_FIELD,
+        YEAR_FIELD = UDAT_YEAR_FIELD,
+        MONTH_FIELD = UDAT_MONTH_FIELD,
+        DATE_FIELD = UDAT_DATE_FIELD,
+        HOUR_OF_DAY1_FIELD = UDAT_HOUR_OF_DAY1_FIELD,
+        HOUR_OF_DAY0_FIELD = UDAT_HOUR_OF_DAY0_FIELD,
+        MINUTE_FIELD = UDAT_MINUTE_FIELD,
+        SECOND_FIELD = UDAT_SECOND_FIELD,
+        MILLISECOND_FIELD = UDAT_FRACTIONAL_SECOND_FIELD,
+        DAY_OF_WEEK_FIELD = UDAT_DAY_OF_WEEK_FIELD,
+        DAY_OF_YEAR_FIELD = UDAT_DAY_OF_YEAR_FIELD,
+        DAY_OF_WEEK_IN_MONTH_FIELD = UDAT_DAY_OF_WEEK_IN_MONTH_FIELD,
+        WEEK_OF_YEAR_FIELD = UDAT_WEEK_OF_YEAR_FIELD,
+        WEEK_OF_MONTH_FIELD = UDAT_WEEK_OF_MONTH_FIELD,
+        AM_PM_FIELD = UDAT_AM_PM_FIELD,
+        HOUR1_FIELD = UDAT_HOUR1_FIELD,
+        HOUR0_FIELD = UDAT_HOUR0_FIELD,
+        TIMEZONE_FIELD = UDAT_TIMEZONE_FIELD
+    };
+};
+
+inline UnicodeString&
+DateFormat::format(const Formattable& obj,
+                   UnicodeString& appendTo,
+                   UErrorCode& status) const {
+    return Format::format(obj, appendTo, status);
+}
+U_NAMESPACE_END
+
+#endif /* #if !UCONFIG_NO_FORMATTING */
+
+#endif // _DATEFMT
+//eof

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/dbbi.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/dbbi.h b/src/apps/couch_collate/platform/osx/icu/unicode/dbbi.h
new file mode 100644
index 0000000..c7984ef
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/dbbi.h
@@ -0,0 +1,41 @@
+/*
+**********************************************************************
+*   Copyright (C) 1999-2006 IBM Corp. All rights reserved.
+**********************************************************************
+*   Date        Name        Description
+*   12/1/99    rgillam     Complete port from Java.
+*   01/13/2000 helena      Added UErrorCode to ctors.
+**********************************************************************
+*/
+
+#ifndef DBBI_H
+#define DBBI_H
+
+#include "unicode/rbbi.h"
+
+#if !UCONFIG_NO_BREAK_ITERATION
+
+/**
+ * \file
+ * \brief C++ API: Dictionary Based Break Iterator
+ */
+ 
+U_NAMESPACE_BEGIN
+
+/**
+ * An obsolete subclass of RuleBasedBreakIterator. Handling of dictionary-
+ * based break iteration has been folded into the base class. This class
+ * is deprecated as of ICU 3.6.
+ */
+ 
+#ifndef U_HIDE_DEPRECATED_API
+
+typedef RuleBasedBreakIterator DictionaryBasedBreakIterator;
+
+#endif
+
+U_NAMESPACE_END
+
+#endif /* #if !UCONFIG_NO_BREAK_ITERATION */
+
+#endif


[91/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/caniter.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/caniter.h b/src/apps/couch_collate/platform/osx/icu/unicode/caniter.h
new file mode 100644
index 0000000..84a6595
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/caniter.h
@@ -0,0 +1,201 @@
+/*
+ *******************************************************************************
+ * Copyright (C) 1996-2006, International Business Machines Corporation and    *
+ * others. All Rights Reserved.                                                *
+ *******************************************************************************
+ */
+
+#ifndef CANITER_H
+#define CANITER_H
+
+#include "unicode/utypes.h"
+
+#if !UCONFIG_NO_NORMALIZATION
+
+#include "unicode/uobject.h"
+#include "unicode/unistr.h"
+
+/**
+ * \file
+ * \brief C++ API: Canonical Iterator
+ */
+ 
+/** Should permutation skip characters with combining class zero
+ *  Should be either TRUE or FALSE. This is a compile time option
+ *  @stable ICU 2.4
+ */
+#ifndef CANITER_SKIP_ZEROES
+#define CANITER_SKIP_ZEROES TRUE
+#endif
+
+U_NAMESPACE_BEGIN
+
+class Hashtable;
+
+/**
+ * This class allows one to iterate through all the strings that are canonically equivalent to a given
+ * string. For example, here are some sample results:
+Results for: {LATIN CAPITAL LETTER A WITH RING ABOVE}{LATIN SMALL LETTER D}{COMBINING DOT ABOVE}{COMBINING CEDILLA}
+1: \\u0041\\u030A\\u0064\\u0307\\u0327
+ = {LATIN CAPITAL LETTER A}{COMBINING RING ABOVE}{LATIN SMALL LETTER D}{COMBINING DOT ABOVE}{COMBINING CEDILLA}
+2: \\u0041\\u030A\\u0064\\u0327\\u0307
+ = {LATIN CAPITAL LETTER A}{COMBINING RING ABOVE}{LATIN SMALL LETTER D}{COMBINING CEDILLA}{COMBINING DOT ABOVE}
+3: \\u0041\\u030A\\u1E0B\\u0327
+ = {LATIN CAPITAL LETTER A}{COMBINING RING ABOVE}{LATIN SMALL LETTER D WITH DOT ABOVE}{COMBINING CEDILLA}
+4: \\u0041\\u030A\\u1E11\\u0307
+ = {LATIN CAPITAL LETTER A}{COMBINING RING ABOVE}{LATIN SMALL LETTER D WITH CEDILLA}{COMBINING DOT ABOVE}
+5: \\u00C5\\u0064\\u0307\\u0327
+ = {LATIN CAPITAL LETTER A WITH RING ABOVE}{LATIN SMALL LETTER D}{COMBINING DOT ABOVE}{COMBINING CEDILLA}
+6: \\u00C5\\u0064\\u0327\\u0307
+ = {LATIN CAPITAL LETTER A WITH RING ABOVE}{LATIN SMALL LETTER D}{COMBINING CEDILLA}{COMBINING DOT ABOVE}
+7: \\u00C5\\u1E0B\\u0327
+ = {LATIN CAPITAL LETTER A WITH RING ABOVE}{LATIN SMALL LETTER D WITH DOT ABOVE}{COMBINING CEDILLA}
+8: \\u00C5\\u1E11\\u0307
+ = {LATIN CAPITAL LETTER A WITH RING ABOVE}{LATIN SMALL LETTER D WITH CEDILLA}{COMBINING DOT ABOVE}
+9: \\u212B\\u0064\\u0307\\u0327
+ = {ANGSTROM SIGN}{LATIN SMALL LETTER D}{COMBINING DOT ABOVE}{COMBINING CEDILLA}
+10: \\u212B\\u0064\\u0327\\u0307
+ = {ANGSTROM SIGN}{LATIN SMALL LETTER D}{COMBINING CEDILLA}{COMBINING DOT ABOVE}
+11: \\u212B\\u1E0B\\u0327
+ = {ANGSTROM SIGN}{LATIN SMALL LETTER D WITH DOT ABOVE}{COMBINING CEDILLA}
+12: \\u212B\\u1E11\\u0307
+ = {ANGSTROM SIGN}{LATIN SMALL LETTER D WITH CEDILLA}{COMBINING DOT ABOVE}
+ *<br>Note: the code is intended for use with small strings, and is not suitable for larger ones,
+ * since it has not been optimized for that situation.
+ * Note, CanonicalIterator is not intended to be subclassed.
+ * @author M. Davis
+ * @author C++ port by V. Weinstein
+ * @stable ICU 2.4
+ */
+class U_COMMON_API CanonicalIterator : public UObject {
+public:
+    /**
+     * Construct a CanonicalIterator object
+     * @param source    string to get results for
+     * @param status    Fill-in parameter which receives the status of this operation.
+     * @stable ICU 2.4
+     */
+    CanonicalIterator(const UnicodeString &source, UErrorCode &status);
+
+    /** Destructor
+     *  Cleans pieces
+     * @stable ICU 2.4
+     */
+    virtual ~CanonicalIterator();
+
+    /**
+     * Gets the NFD form of the current source we are iterating over.
+     * @return gets the source: NOTE: it is the NFD form of source
+     * @stable ICU 2.4
+     */
+    UnicodeString getSource();
+
+    /**
+     * Resets the iterator so that one can start again from the beginning.
+     * @stable ICU 2.4
+     */
+    void reset();
+
+    /**
+     * Get the next canonically equivalent string.
+     * <br><b>Warning: The strings are not guaranteed to be in any particular order.</b>
+     * @return the next string that is canonically equivalent. A bogus string is returned when
+     * the iteration is done.
+     * @stable ICU 2.4
+     */
+    UnicodeString next();
+
+    /**
+     * Set a new source for this iterator. Allows object reuse.
+     * @param newSource     the source string to iterate against. This allows the same iterator to be used
+     *                     while changing the source string, saving object creation.
+     * @param status        Fill-in parameter which receives the status of this operation.
+     * @stable ICU 2.4
+     */
+    void setSource(const UnicodeString &newSource, UErrorCode &status);
+
+    /**
+     * Dumb recursive implementation of permutation.
+     * TODO: optimize
+     * @param source     the string to find permutations for
+     * @param skipZeros  determine if skip zeros
+     * @param result     the results in a set.
+     * @param status       Fill-in parameter which receives the status of this operation.
+     * @internal
+     */
+    static void U_EXPORT2 permute(UnicodeString &source, UBool skipZeros, Hashtable *result, UErrorCode &status);
+
+    /**
+     * ICU "poor man's RTTI", returns a UClassID for this class.
+     *
+     * @stable ICU 2.2
+     */
+    static UClassID U_EXPORT2 getStaticClassID();
+
+    /**
+     * ICU "poor man's RTTI", returns a UClassID for the actual class.
+     *
+     * @stable ICU 2.2
+     */
+    virtual UClassID getDynamicClassID() const;
+
+private:
+    // ===================== PRIVATES ==============================
+    // private default constructor
+    CanonicalIterator();
+
+
+    /**
+     * Copy constructor. Private for now.
+     * @internal
+     */
+    CanonicalIterator(const CanonicalIterator& other);
+
+    /**
+     * Assignment operator. Private for now.
+     * @internal
+     */
+    CanonicalIterator& operator=(const CanonicalIterator& other);
+
+    // fields
+    UnicodeString source;
+    UBool done;
+
+    // 2 dimensional array holds the pieces of the string with
+    // their different canonically equivalent representations
+    UnicodeString **pieces;
+    int32_t pieces_length;
+    int32_t *pieces_lengths;
+
+    // current is used in iterating to combine pieces
+    int32_t *current;
+    int32_t current_length;
+
+    // transient fields
+    UnicodeString buffer;
+
+    // we have a segment, in NFD. Find all the strings that are canonically equivalent to it.
+    UnicodeString *getEquivalents(const UnicodeString &segment, int32_t &result_len, UErrorCode &status); //private String[] getEquivalents(String segment)
+
+    //Set getEquivalents2(String segment);
+    Hashtable *getEquivalents2(Hashtable *fillinResult, const UChar *segment, int32_t segLen, UErrorCode &status);
+    //Hashtable *getEquivalents2(const UnicodeString &segment, int32_t segLen, UErrorCode &status);
+
+    /**
+     * See if the decomposition of cp2 is at segment starting at segmentPos
+     * (with canonical rearrangment!)
+     * If so, take the remainder, and return the equivalents
+     */
+    //Set extract(int comp, String segment, int segmentPos, StringBuffer buffer);
+    Hashtable *extract(Hashtable *fillinResult, UChar32 comp, const UChar *segment, int32_t segLen, int32_t segmentPos, UErrorCode &status);
+    //Hashtable *extract(UChar32 comp, const UnicodeString &segment, int32_t segLen, int32_t segmentPos, UErrorCode &status);
+
+    void cleanPieces();
+
+};
+
+U_NAMESPACE_END
+
+#endif /* #if !UCONFIG_NO_NORMALIZATION */
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/chariter.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/chariter.h b/src/apps/couch_collate/platform/osx/icu/unicode/chariter.h
new file mode 100644
index 0000000..12fc924
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/chariter.h
@@ -0,0 +1,716 @@
+/*
+********************************************************************
+*
+*   Copyright (C) 1997-2005, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+*
+********************************************************************
+*/
+
+#ifndef CHARITER_H
+#define CHARITER_H
+
+#include "unicode/utypes.h"
+#include "unicode/uobject.h"
+#include "unicode/unistr.h"
+/**
+ * \file
+ * \brief C++ API: Character Iterator
+ */
+ 
+U_NAMESPACE_BEGIN
+/**
+ * Abstract class that defines an API for forward-only iteration
+ * on text objects.
+ * This is a minimal interface for iteration without random access
+ * or backwards iteration. It is especially useful for wrapping
+ * streams with converters into an object for collation or
+ * normalization.
+ *
+ * <p>Characters can be accessed in two ways: as code units or as
+ * code points.
+ * Unicode code points are 21-bit integers and are the scalar values
+ * of Unicode characters. ICU uses the type UChar32 for them.
+ * Unicode code units are the storage units of a given
+ * Unicode/UCS Transformation Format (a character encoding scheme).
+ * With UTF-16, all code points can be represented with either one
+ * or two code units ("surrogates").
+ * String storage is typically based on code units, while properties
+ * of characters are typically determined using code point values.
+ * Some processes may be designed to work with sequences of code units,
+ * or it may be known that all characters that are important to an
+ * algorithm can be represented with single code units.
+ * Other processes will need to use the code point access functions.</p>
+ *
+ * <p>ForwardCharacterIterator provides nextPostInc() to access
+ * a code unit and advance an internal position into the text object,
+ * similar to a <code>return text[position++]</code>.<br>
+ * It provides next32PostInc() to access a code point and advance an internal
+ * position.</p>
+ *
+ * <p>next32PostInc() assumes that the current position is that of
+ * the beginning of a code point, i.e., of its first code unit.
+ * After next32PostInc(), this will be true again.
+ * In general, access to code units and code points in the same
+ * iteration loop should not be mixed. In UTF-16, if the current position
+ * is on a second code unit (Low Surrogate), then only that code unit
+ * is returned even by next32PostInc().</p>
+ *
+ * <p>For iteration with either function, there are two ways to
+ * check for the end of the iteration. When there are no more
+ * characters in the text object:
+ * <ul>
+ * <li>The hasNext() function returns FALSE.</li>
+ * <li>nextPostInc() and next32PostInc() return DONE
+ *     when one attempts to read beyond the end of the text object.</li>
+ * </ul>
+ *
+ * Example:
+ * \code 
+ * void function1(ForwardCharacterIterator &it) {
+ *     UChar32 c;
+ *     while(it.hasNext()) {
+ *         c=it.next32PostInc();
+ *         // use c
+ *     }
+ * }
+ *
+ * void function1(ForwardCharacterIterator &it) {
+ *     UChar c;
+ *     while((c=it.nextPostInc())!=ForwardCharacterIterator::DONE) {
+ *         // use c
+ *      }
+ *  }
+ * \endcode
+ * </p>
+ *
+ * @stable ICU 2.0
+ */
+class U_COMMON_API ForwardCharacterIterator : public UObject {
+public:
+    /**
+     * Value returned by most of ForwardCharacterIterator's functions
+     * when the iterator has reached the limits of its iteration.
+     * @stable ICU 2.0
+     */
+    enum { DONE = 0xffff };
+    
+    /**
+     * Destructor.  
+     * @stable ICU 2.0
+     */
+    virtual ~ForwardCharacterIterator();
+    
+    /**
+     * Returns true when both iterators refer to the same
+     * character in the same character-storage object.  
+     * @param that The ForwardCharacterIterator to be compared for equality
+     * @return true when both iterators refer to the same
+     * character in the same character-storage object
+     * @stable ICU 2.0
+     */
+    virtual UBool operator==(const ForwardCharacterIterator& that) const = 0;
+    
+    /**
+     * Returns true when the iterators refer to different
+     * text-storage objects, or to different characters in the
+     * same text-storage object.  
+     * @param that The ForwardCharacterIterator to be compared for inequality
+     * @return true when the iterators refer to different
+     * text-storage objects, or to different characters in the
+     * same text-storage object
+     * @stable ICU 2.0
+     */
+    inline UBool operator!=(const ForwardCharacterIterator& that) const;
+    
+    /**
+     * Generates a hash code for this iterator.  
+     * @return the hash code.
+     * @stable ICU 2.0
+     */
+    virtual int32_t hashCode(void) const = 0;
+    
+    /**
+     * Returns a UClassID for this ForwardCharacterIterator ("poor man's
+     * RTTI").<P> Despite the fact that this function is public,
+     * DO NOT CONSIDER IT PART OF CHARACTERITERATOR'S API! 
+     * @return a UClassID for this ForwardCharacterIterator 
+     * @stable ICU 2.0
+     */
+    virtual UClassID getDynamicClassID(void) const = 0;
+    
+    /**
+     * Gets the current code unit for returning and advances to the next code unit
+     * in the iteration range
+     * (toward endIndex()).  If there are
+     * no more code units to return, returns DONE.
+     * @return the current code unit.
+     * @stable ICU 2.0
+     */
+    virtual UChar         nextPostInc(void) = 0;
+    
+    /**
+     * Gets the current code point for returning and advances to the next code point
+     * in the iteration range
+     * (toward endIndex()).  If there are
+     * no more code points to return, returns DONE.
+     * @return the current code point.
+     * @stable ICU 2.0
+     */
+    virtual UChar32       next32PostInc(void) = 0;
+    
+    /**
+     * Returns FALSE if there are no more code units or code points
+     * at or after the current position in the iteration range.
+     * This is used with nextPostInc() or next32PostInc() in forward
+     * iteration.
+     * @returns FALSE if there are no more code units or code points
+     * at or after the current position in the iteration range.
+     * @stable ICU 2.0
+     */
+    virtual UBool        hasNext() = 0;
+    
+protected:
+    /** Default constructor to be overridden in the implementing class. @stable ICU 2.0*/
+    ForwardCharacterIterator();
+    
+    /** Copy constructor to be overridden in the implementing class. @stable ICU 2.0*/
+    ForwardCharacterIterator(const ForwardCharacterIterator &other);
+    
+    /**
+     * Assignment operator to be overridden in the implementing class.
+     * @stable ICU 2.0
+     */
+    ForwardCharacterIterator &operator=(const ForwardCharacterIterator&) { return *this; }
+};
+
+/**
+ * Abstract class that defines an API for iteration
+ * on text objects.
+ * This is an interface for forward and backward iteration
+ * and random access into a text object.
+ *
+ * <p>The API provides backward compatibility to the Java and older ICU
+ * CharacterIterator classes but extends them significantly:
+ * <ol>
+ * <li>CharacterIterator is now a subclass of ForwardCharacterIterator.</li>
+ * <li>While the old API functions provided forward iteration with
+ *     "pre-increment" semantics, the new one also provides functions
+ *     with "post-increment" semantics. They are more efficient and should
+ *     be the preferred iterator functions for new implementations.
+ *     The backward iteration always had "pre-decrement" semantics, which
+ *     are efficient.</li>
+ * <li>Just like ForwardCharacterIterator, it provides access to
+ *     both code units and code points. Code point access versions are available
+ *     for the old and the new iteration semantics.</li>
+ * <li>There are new functions for setting and moving the current position
+ *     without returning a character, for efficiency.</li>
+ * </ol>
+ *
+ * See ForwardCharacterIterator for examples for using the new forward iteration
+ * functions. For backward iteration, there is also a hasPrevious() function
+ * that can be used analogously to hasNext().
+ * The old functions work as before and are shown below.</p>
+ *
+ * <p>Examples for some of the new functions:</p>
+ *
+ * Forward iteration with hasNext():
+ * \code
+ * void forward1(CharacterIterator &it) {
+ *     UChar32 c;
+ *     for(it.setToStart(); it.hasNext();) {
+ *         c=it.next32PostInc();
+ *         // use c
+ *     }
+ *  }
+ * \endcode
+ * Forward iteration more similar to loops with the old forward iteration,
+ * showing a way to convert simple for() loops:
+ * \code
+ * void forward2(CharacterIterator &it) {
+ *     UChar c;
+ *     for(c=it.firstPostInc(); c!=CharacterIterator::DONE; c=it.nextPostInc()) {
+ *          // use c
+ *      }
+ * }
+ * \endcode
+ * Backward iteration with setToEnd() and hasPrevious():
+ * \code
+ *  void backward1(CharacterIterator &it) {
+ *      UChar32 c;
+ *      for(it.setToEnd(); it.hasPrevious();) {
+ *         c=it.previous32();
+ *          // use c
+ *      }
+ *  }
+ * \endcode
+ * Backward iteration with a more traditional for() loop:
+ * \code
+ * void backward2(CharacterIterator &it) {
+ *     UChar c;
+ *     for(c=it.last(); c!=CharacterIterator::DONE; c=it.previous()) {
+ *         // use c
+ *      }
+ *  }
+ * \endcode
+ *
+ * Example for random access:
+ * \code
+ *  void random(CharacterIterator &it) {
+ *      // set to the third code point from the beginning
+ *      it.move32(3, CharacterIterator::kStart);
+ *      // get a code point from here without moving the position
+ *      UChar32 c=it.current32();
+ *      // get the position
+ *      int32_t pos=it.getIndex();
+ *      // get the previous code unit
+ *      UChar u=it.previous();
+ *      // move back one more code unit
+ *      it.move(-1, CharacterIterator::kCurrent);
+ *      // set the position back to where it was
+ *      // and read the same code point c and move beyond it
+ *      it.setIndex(pos);
+ *      if(c!=it.next32PostInc()) {
+ *          exit(1); // CharacterIterator inconsistent
+ *      }
+ *  }
+ * \endcode
+ *
+ * <p>Examples, especially for the old API:</p>
+ *
+ * Function processing characters, in this example simple output
+ * <pre>
+ * \code
+ *  void processChar( UChar c )
+ *  {
+ *      cout << " " << c;
+ *  }
+ * \endcode
+ * </pre>
+ * Traverse the text from start to finish
+ * <pre> 
+ * \code
+ *  void traverseForward(CharacterIterator& iter)
+ *  {
+ *      for(UChar c = iter.first(); c != CharacterIterator.DONE; c = iter.next()) {
+ *          processChar(c);
+ *      }
+ *  }
+ * \endcode
+ * </pre>
+ * Traverse the text backwards, from end to start
+ * <pre>
+ * \code
+ *  void traverseBackward(CharacterIterator& iter)
+ *  {
+ *      for(UChar c = iter.last(); c != CharacterIterator.DONE; c = iter.previous()) {
+ *          processChar(c);
+ *      }
+ *  }
+ * \endcode
+ * </pre>
+ * Traverse both forward and backward from a given position in the text. 
+ * Calls to notBoundary() in this example represents some additional stopping criteria.
+ * <pre>
+ * \code
+ * void traverseOut(CharacterIterator& iter, int32_t pos)
+ * {
+ *      UChar c;
+ *      for (c = iter.setIndex(pos);
+ *      c != CharacterIterator.DONE && (Unicode::isLetter(c) || Unicode::isDigit(c));
+ *          c = iter.next()) {}
+ *      int32_t end = iter.getIndex();
+ *      for (c = iter.setIndex(pos);
+ *          c != CharacterIterator.DONE && (Unicode::isLetter(c) || Unicode::isDigit(c));
+ *          c = iter.previous()) {}
+ *      int32_t start = iter.getIndex() + 1;
+ *  
+ *      cout << "start: " << start << " end: " << end << endl;
+ *      for (c = iter.setIndex(start); iter.getIndex() < end; c = iter.next() ) {
+ *          processChar(c);
+ *     }
+ *  }
+ * \endcode
+ * </pre>
+ * Creating a StringCharacterIterator and calling the test functions
+ * <pre>
+ * \code
+ *  void CharacterIterator_Example( void )
+ *   {
+ *       cout << endl << "===== CharacterIterator_Example: =====" << endl;
+ *       UnicodeString text("Ein kleiner Satz.");
+ *       StringCharacterIterator iterator(text);
+ *       cout << "----- traverseForward: -----------" << endl;
+ *       traverseForward( iterator );
+ *       cout << endl << endl << "----- traverseBackward: ----------" << endl;
+ *       traverseBackward( iterator );
+ *       cout << endl << endl << "----- traverseOut: ---------------" << endl;
+ *       traverseOut( iterator, 7 );
+ *       cout << endl << endl << "-----" << endl;
+ *   }
+ * \endcode
+ * </pre>
+ *
+ * @stable ICU 2.0
+ */
+class U_COMMON_API CharacterIterator : public ForwardCharacterIterator {
+public:
+    /**
+     * Origin enumeration for the move() and move32() functions.
+     * @stable ICU 2.0
+     */
+    enum EOrigin { kStart, kCurrent, kEnd };
+
+    /**
+     * Returns a pointer to a new CharacterIterator of the same
+     * concrete class as this one, and referring to the same
+     * character in the same text-storage object as this one.  The
+     * caller is responsible for deleting the new clone.  
+     * @return a pointer to a new CharacterIterator
+     * @stable ICU 2.0
+     */
+    virtual CharacterIterator* clone(void) const = 0;
+
+    /**
+     * Sets the iterator to refer to the first code unit in its
+     * iteration range, and returns that code unit.
+     * This can be used to begin an iteration with next().
+     * @return the first code unit in its iteration range.
+     * @stable ICU 2.0
+     */
+    virtual UChar         first(void) = 0;
+
+    /**
+     * Sets the iterator to refer to the first code unit in its
+     * iteration range, returns that code unit, and moves the position
+     * to the second code unit. This is an alternative to setToStart()
+     * for forward iteration with nextPostInc().
+     * @return the first code unit in its iteration range.
+     * @stable ICU 2.0
+     */
+    virtual UChar         firstPostInc(void);
+
+    /**
+     * Sets the iterator to refer to the first code point in its
+     * iteration range, and returns that code unit,
+     * This can be used to begin an iteration with next32().
+     * Note that an iteration with next32PostInc(), beginning with,
+     * e.g., setToStart() or firstPostInc(), is more efficient.
+     * @return the first code point in its iteration range.
+     * @stable ICU 2.0
+     */
+    virtual UChar32       first32(void) = 0;
+
+    /**
+     * Sets the iterator to refer to the first code point in its
+     * iteration range, returns that code point, and moves the position
+     * to the second code point. This is an alternative to setToStart()
+     * for forward iteration with next32PostInc().
+     * @return the first code point in its iteration range.
+     * @stable ICU 2.0
+     */
+    virtual UChar32       first32PostInc(void);
+
+    /**
+     * Sets the iterator to refer to the first code unit or code point in its
+     * iteration range. This can be used to begin a forward
+     * iteration with nextPostInc() or next32PostInc().
+     * @return the start position of the iteration range
+     * @stable ICU 2.0
+     */
+    inline int32_t    setToStart();
+
+    /**
+     * Sets the iterator to refer to the last code unit in its
+     * iteration range, and returns that code unit.
+     * This can be used to begin an iteration with previous().
+     * @return the last code unit.
+     * @stable ICU 2.0
+     */
+    virtual UChar         last(void) = 0;
+        
+    /**
+     * Sets the iterator to refer to the last code point in its
+     * iteration range, and returns that code unit.
+     * This can be used to begin an iteration with previous32().
+     * @return the last code point.
+     * @stable ICU 2.0
+     */
+    virtual UChar32       last32(void) = 0;
+
+    /**
+     * Sets the iterator to the end of its iteration range, just behind
+     * the last code unit or code point. This can be used to begin a backward
+     * iteration with previous() or previous32().
+     * @return the end position of the iteration range
+     * @stable ICU 2.0
+     */
+    inline int32_t    setToEnd();
+
+    /**
+     * Sets the iterator to refer to the "position"-th code unit
+     * in the text-storage object the iterator refers to, and
+     * returns that code unit.  
+     * @param position the "position"-th code unit in the text-storage object
+     * @return the "position"-th code unit.
+     * @stable ICU 2.0
+     */
+    virtual UChar         setIndex(int32_t position) = 0;
+
+    /**
+     * Sets the iterator to refer to the beginning of the code point
+     * that contains the "position"-th code unit
+     * in the text-storage object the iterator refers to, and
+     * returns that code point.
+     * The current position is adjusted to the beginning of the code point
+     * (its first code unit).
+     * @param position the "position"-th code unit in the text-storage object
+     * @return the "position"-th code point.
+     * @stable ICU 2.0
+     */
+    virtual UChar32       setIndex32(int32_t position) = 0;
+
+    /**
+     * Returns the code unit the iterator currently refers to. 
+     * @return the current code unit. 
+     * @stable ICU 2.0
+     */
+    virtual UChar         current(void) const = 0;
+        
+    /**
+     * Returns the code point the iterator currently refers to.  
+     * @return the current code point.
+     * @stable ICU 2.0
+     */
+    virtual UChar32       current32(void) const = 0;
+        
+    /**
+     * Advances to the next code unit in the iteration range
+     * (toward endIndex()), and returns that code unit.  If there are
+     * no more code units to return, returns DONE.
+     * @return the next code unit.
+     * @stable ICU 2.0
+     */
+    virtual UChar         next(void) = 0;
+        
+    /**
+     * Advances to the next code point in the iteration range
+     * (toward endIndex()), and returns that code point.  If there are
+     * no more code points to return, returns DONE.
+     * Note that iteration with "pre-increment" semantics is less
+     * efficient than iteration with "post-increment" semantics
+     * that is provided by next32PostInc().
+     * @return the next code point.
+     * @stable ICU 2.0
+     */
+    virtual UChar32       next32(void) = 0;
+        
+    /**
+     * Advances to the previous code unit in the iteration range
+     * (toward startIndex()), and returns that code unit.  If there are
+     * no more code units to return, returns DONE.  
+     * @return the previous code unit.
+     * @stable ICU 2.0
+     */
+    virtual UChar         previous(void) = 0;
+
+    /**
+     * Advances to the previous code point in the iteration range
+     * (toward startIndex()), and returns that code point.  If there are
+     * no more code points to return, returns DONE. 
+     * @return the previous code point. 
+     * @stable ICU 2.0
+     */
+    virtual UChar32       previous32(void) = 0;
+
+    /**
+     * Returns FALSE if there are no more code units or code points
+     * before the current position in the iteration range.
+     * This is used with previous() or previous32() in backward
+     * iteration.
+     * @return FALSE if there are no more code units or code points
+     * before the current position in the iteration range, return TRUE otherwise.
+     * @stable ICU 2.0
+     */
+    virtual UBool        hasPrevious() = 0;
+
+    /**
+     * Returns the numeric index in the underlying text-storage
+     * object of the character returned by first().  Since it's
+     * possible to create an iterator that iterates across only
+     * part of a text-storage object, this number isn't
+     * necessarily 0.  
+     * @returns the numeric index in the underlying text-storage
+     * object of the character returned by first().
+     * @stable ICU 2.0
+     */
+    inline int32_t       startIndex(void) const;
+        
+    /**
+     * Returns the numeric index in the underlying text-storage
+     * object of the position immediately BEYOND the character
+     * returned by last().  
+     * @return the numeric index in the underlying text-storage
+     * object of the position immediately BEYOND the character
+     * returned by last().
+     * @stable ICU 2.0
+     */
+    inline int32_t       endIndex(void) const;
+        
+    /**
+     * Returns the numeric index in the underlying text-storage
+     * object of the character the iterator currently refers to
+     * (i.e., the character returned by current()).  
+     * @return the numberic index in the text-storage object of 
+     * the character the iterator currently refers to
+     * @stable ICU 2.0
+     */
+    inline int32_t       getIndex(void) const;
+
+    /**
+     * Returns the length of the entire text in the underlying
+     * text-storage object.
+     * @return the length of the entire text in the text-storage object
+     * @stable ICU 2.0
+     */
+    inline int32_t           getLength() const;
+
+    /**
+     * Moves the current position relative to the start or end of the
+     * iteration range, or relative to the current position itself.
+     * The movement is expressed in numbers of code units forward
+     * or backward by specifying a positive or negative delta.
+     * @param delta the position relative to origin. A positive delta means forward;
+     * a negative delta means backward.
+     * @param origin Origin enumeration {kStart, kCurrent, kEnd}
+     * @return the new position
+     * @stable ICU 2.0
+     */
+    virtual int32_t      move(int32_t delta, EOrigin origin) = 0;
+
+    /**
+     * Moves the current position relative to the start or end of the
+     * iteration range, or relative to the current position itself.
+     * The movement is expressed in numbers of code points forward
+     * or backward by specifying a positive or negative delta.
+     * @param delta the position relative to origin. A positive delta means forward;
+     * a negative delta means backward.
+     * @param origin Origin enumeration {kStart, kCurrent, kEnd}
+     * @return the new position
+     * @stable ICU 2.0
+     */
+    virtual int32_t      move32(int32_t delta, EOrigin origin) = 0;
+
+    /**
+     * Copies the text under iteration into the UnicodeString
+     * referred to by "result".  
+     * @param result Receives a copy of the text under iteration.  
+     * @stable ICU 2.0
+     */
+    virtual void            getText(UnicodeString&  result) = 0;
+
+protected:
+    /**
+     * Empty constructor.
+     * @stable ICU 2.0
+     */
+    CharacterIterator();
+
+    /**
+     * Constructor, just setting the length field in this base class.
+     * @stable ICU 2.0
+     */
+    CharacterIterator(int32_t length);
+
+    /**
+     * Constructor, just setting the length and position fields in this base class.
+     * @stable ICU 2.0
+     */
+    CharacterIterator(int32_t length, int32_t position);
+
+    /**
+     * Constructor, just setting the length, start, end, and position fields in this base class.
+     * @stable ICU 2.0
+     */
+    CharacterIterator(int32_t length, int32_t textBegin, int32_t textEnd, int32_t position);
+  
+    /**
+     * Copy constructor.
+     *
+     * @param that The CharacterIterator to be copied
+     * @stable ICU 2.0
+     */
+    CharacterIterator(const CharacterIterator &that);
+
+    /**
+     * Assignment operator.  Sets this CharacterIterator to have the same behavior,
+     * as the one passed in.
+     * @param that The CharacterIterator passed in.
+     * @return the newly set CharacterIterator.
+     * @stable ICU 2.0
+     */
+    CharacterIterator &operator=(const CharacterIterator &that);
+
+    /**
+     * Base class text length field.
+     * Necessary this for correct getText() and hashCode().
+     * @stable ICU 2.0
+     */
+    int32_t textLength;
+
+    /**
+     * Base class field for the current position.
+     * @stable ICU 2.0
+     */
+    int32_t  pos;
+
+    /**
+     * Base class field for the start of the iteration range.
+     * @stable ICU 2.0
+     */
+    int32_t  begin;
+
+    /**
+     * Base class field for the end of the iteration range.
+     * @stable ICU 2.0
+     */
+    int32_t  end;
+};
+
+inline UBool
+ForwardCharacterIterator::operator!=(const ForwardCharacterIterator& that) const {
+    return !operator==(that);
+}
+
+inline int32_t
+CharacterIterator::setToStart() {
+    return move(0, kStart);
+}
+
+inline int32_t
+CharacterIterator::setToEnd() {
+    return move(0, kEnd);
+}
+
+inline int32_t
+CharacterIterator::startIndex(void) const {
+    return begin;
+}
+
+inline int32_t
+CharacterIterator::endIndex(void) const {
+    return end;
+}
+
+inline int32_t
+CharacterIterator::getIndex(void) const {
+    return pos;
+}
+
+inline int32_t
+CharacterIterator::getLength(void) const {
+    return textLength;
+}
+
+U_NAMESPACE_END
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/choicfmt.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/choicfmt.h b/src/apps/couch_collate/platform/osx/icu/unicode/choicfmt.h
new file mode 100644
index 0000000..8484648
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/choicfmt.h
@@ -0,0 +1,746 @@
+/*
+********************************************************************************
+*   Copyright (C) 1997-2008, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+********************************************************************************
+*
+* File CHOICFMT.H
+*
+* Modification History:
+*
+*   Date        Name        Description
+*   02/19/97    aliu        Converted from java.
+*   03/20/97    helena      Finished first cut of implementation and got rid 
+*                           of nextDouble/previousDouble and replaced with
+*                           boolean array.
+*   4/10/97     aliu        Clean up.  Modified to work on AIX.
+*   8/6/97      nos         Removed overloaded constructor, member var 'buffer'.
+*   07/22/98    stephen     Removed operator!= (implemented in Format)
+********************************************************************************
+*/
+ 
+#ifndef CHOICFMT_H
+#define CHOICFMT_H
+ 
+#include "unicode/utypes.h"
+
+/**
+ * \file 
+ * \brief C++ API: Choice Format.
+ */
+ 
+#if !UCONFIG_NO_FORMATTING
+
+#include "unicode/unistr.h"
+#include "unicode/numfmt.h"
+#include "unicode/fieldpos.h"
+#include "unicode/format.h"
+
+U_NAMESPACE_BEGIN
+
+class MessageFormat;
+
+/**
+ * ChoiceFormat converts between ranges of numeric values
+ * and string names for those ranges. A <code>ChoiceFormat</code> splits
+ * the real number line <code>-Inf</code> to <code>+Inf</code> into two
+ * or more contiguous ranges. Each range is mapped to a
+ * string. <code>ChoiceFormat</code> is generally used in a
+ * <code>MessageFormat</code> for displaying grammatically correct
+ * plurals such as &quot;There are 2 files.&quot;</p>
+ * 
+ * <p>There are two methods of defining a <code>ChoiceFormat</code>; both
+ * are equivalent.  The first is by using a string pattern. This is the
+ * preferred method in most cases.  The second method is through direct
+ * specification of the arrays that make up the
+ * <code>ChoiceFormat</code>.</p>
+ * 
+ * <p><strong>Patterns</strong></p>
+ * 
+ * <p>In most cases, the preferred way to define a
+ * <code>ChoiceFormat</code> is with a pattern. Here is an example of a
+ * <code>ChoiceFormat</code> pattern:</p>
+ *
+ * \htmlonly<pre>    0&#x2264;are no files|1&#x2264;is one file|1&lt;are many files</pre>\endhtmlonly
+ * 
+ * <p>or equivalently,</p>
+ * 
+ * \htmlonly<pre>    0#are no files|1#is one file|1&lt;are many files</pre>\endhtmlonly
+ * 
+ * <p>The pattern consists of a number or <em>range specifiers</em>
+ * separated by vertical bars '|' (U+007C). There is no
+ * vertical bar after the last range.  Each range specifier is of the
+ * form:</p>
+ *
+ * \htmlonly<blockquote><em>Number Separator String</em></blockquote>\endhtmlonly
+ * 
+ * <p><em>Number</em> is a floating point number that can be parsed by a
+ * default <code>NumberFormat</code> for the US locale. It gives the
+ * lower limit of this range. The lower limit is either inclusive or
+ * exclusive, depending on the <em>separator</em>. The upper limit is
+ * given by the lower limit of the next range.  The Unicode infinity
+ * sign \htmlonly&#x221E \endhtmlonly (U+221E) is recognized for positive infinity. It may be preceded by
+ * '-' (U+002D) to indicate negative infinity.</p>
+ * 
+ * <p><em>String</em> is the format string for this range, with special
+ * characters enclosed in single quotes (<code>'The #
+ * sign'</code>). Single quotes themselves are indicated by two single
+ * quotes in a row (<code>'o''clock'</code>).</p>
+ * 
+ * <p><em>Separator</em> is one of the following single characters:
+ * 
+ * <ul>
+ *   <li>\htmlonly'&#x2264;' \endhtmlonly (U+2264) or '#' (U+0023)
+ *   indicates that the lower limit given by <em>Number</em> is
+ *   inclusive.  (The two characters are equivalent to ChoiceFormat.)
+ *   This means that the limit value <em>Number</em> belongs to this
+ *   range.  Another way of saying this is that the corresponding
+ *   closure is <code>FALSE</code>.</li>
+ *
+ *   <li>'<' (U+003C) indicates that the lower limit given by
+ *   <em>Number</em> is exclusive.  This means that the value
+ *   <em>Number</em> belongs to the prior range.</li> Another way of
+ *   saying this is that the corresponding closure is
+ *   <code>TRUE</code>.
+ * </ul>
+ * 
+ * <p>See below for more information about closures.</p>
+ * 
+ * <p><strong>Arrays</strong></p>
+ * 
+ * <p>A <code>ChoiceFormat</code> defining <code>n</code> intervals
+ * (<code>n</code> &gt;= 2) is specified by three arrays of
+ * <code>n</code> items:
+ * 
+ * <ul>
+ *   <li><code>double limits[]</code> gives the start of each
+ *     interval. This must be a non-decreasing list of values, none of
+ *     which may be <code>NaN</code>.</li>
+ *   <li><code>UBool closures[]</code> determines whether each limit
+ *     value is contained in the interval below it or in the interval
+ *     above it. If <code>closures[i]</code> is <code>FALSE</code>, then
+ *     <code>limits[i]</code> is a member of interval
+ *     <code>i</code>. Otherwise it is a member of interval
+ *     <code>i+1</code>. If no closures array is specified, this is
+ *     equivalent to having all closures be <code>FALSE</code>. Closures
+ *     allow one to specify half-open, open, or closed intervals.</li>
+ *   <li><code>UnicodeString formats[]</code> gives the string label
+ *     associated with each interval.</li>
+ * </ul>
+ * 
+ * <p><strong>Formatting and Parsing</strong></p>
+ * 
+ * <p>During formatting, a number is converted to a
+ * string. <code>ChoiceFormat</code> accomplishes this by mapping the
+ * number to an interval using the following rule. Given a number
+ * <code>X</code> and and index value <code>j</code> in the range
+ * <code>0..n-1</code>, where <code>n</code> is the number of ranges:</p>
+ * 
+ * \htmlonly<blockquote>\endhtmlonly<code>X</code> matches <code>j</code> if and only if
+ * <code>limit[j] &lt;= X &lt; limit[j+1]</code>
+ * \htmlonly</blockquote>\endhtmlonly
+ * 
+ * <p>(This assumes that all closures are <code>FALSE</code>.  If some
+ * closures are <code>TRUE</code> then the relations must be changed to
+ * <code>&lt;=</code> or <code>&lt;</code> as appropriate.) If there is
+ * no match, then either the first or last index is used, depending on
+ * whether the number is too low or too high. Once a number is mapped to
+ * an interval <code>j</code>, the string <code>formats[j]</code> is
+ * output.</p>
+ * 
+ * <p>During parsing, a string is converted to a
+ * number. <code>ChoiceFormat</code> finds the element
+ * <code>formats[j]</code> equal to the string, and returns
+ * <code>limits[j]</code> as the parsed value.</p>
+ * 
+ * <p><strong>Notes</strong></p>
+ * 
+ * <p>The first limit value does not define a range boundary. For
+ * example, in the pattern \htmlonly&quot;<code>1.0#a|2.0#b</code>&quot;\endhtmlonly, the
+ * intervals are [-Inf, 2.0) and [2.0, +Inf].  It appears that the first
+ * interval should be [1.0, 2.0).  However, since all values that are too
+ * small are mapped to range zero, the first interval is effectively
+ * [-Inf, 2.0).  However, the first limit value <em>is</em> used during
+ * formatting. In this example, <code>parse(&quot;a&quot;)</code> returns
+ * 1.0.</p>
+ * 
+ * <p>There are no gaps between intervals and the entire number line is
+ * covered.  A <code>ChoiceFormat</code> maps <em>all</em> possible
+ * double values to a finite set of intervals.</p>
+ * 
+ * <p>The non-number <code>NaN</code> is mapped to interval zero during
+ * formatting.</p>
+ * 
+ * <p><strong>Examples</strong></p>
+ * 
+ * <p>Here is an example of two arrays that map the number
+ * <code>1..7</code> to the English day of the week abbreviations
+ * <code>Sun..Sat</code>. No closures array is given; this is the same as
+ * specifying all closures to be <code>FALSE</code>.</p>
+ * 
+ * <pre>    {1,2,3,4,5,6,7},
+ *     {&quot;Sun&quot;,&quot;Mon&quot;,&quot;Tue&quot;,&quot;Wed&quot;,&quot;Thur&quot;,&quot;Fri&quot;,&quot;Sat&quot;}</pre>
+ * 
+ * <p>Here is an example that maps the ranges [-Inf, 1), [1, 1], and (1,
+ * +Inf] to three strings. That is, the number line is split into three
+ * ranges: x &lt; 1.0, x = 1.0, and x &gt; 1.0.</p>
+ * 
+ * <pre>    {0, 1, 1},
+ *     {FALSE, FALSE, TRUE},
+ *     {&quot;no files&quot;, &quot;one file&quot;, &quot;many files&quot;}</pre>
+ * 
+ * <p>Here is a simple example that shows formatting and parsing: </p>
+ * 
+ * \code
+ *   #include <unicode/choicfmt.h>
+ *   #include <unicode/unistr.h>
+ *   #include <iostream.h>
+ *   
+ *   int main(int argc, char *argv[]) {
+ *       double limits[] = {1,2,3,4,5,6,7};
+ *       UnicodeString monthNames[] = {
+ *           "Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
+ *       ChoiceFormat fmt(limits, monthNames, 7);
+ *       UnicodeString str;
+ *       char buf[256];
+ *       for (double x = 1.0; x <= 8.0; x += 1.0) {
+ *           fmt.format(x, str);
+ *           str.extract(0, str.length(), buf, 256, "");
+ *           str.truncate(0);
+ *           cout << x << " -> "
+ *                << buf << endl;
+ *       }
+ *       cout << endl;
+ *       return 0;
+ *   }
+ * \endcode
+ * 
+ * <p>Here is a more complex example using a <code>ChoiceFormat</code>
+ * constructed from a pattern together with a
+ * <code>MessageFormat</code>.</p>
+ * 
+ * \code
+ *   #include <unicode/choicfmt.h>
+ *   #include <unicode/msgfmt.h>
+ *   #include <unicode/unistr.h>
+ *   #include <iostream.h>
+ * 
+ *   int main(int argc, char *argv[]) {
+ *       UErrorCode status = U_ZERO_ERROR;
+ *       double filelimits[] = {0,1,2};
+ *       UnicodeString filepart[] =
+ *           {"are no files","is one file","are {0} files"};
+ *       ChoiceFormat* fileform = new ChoiceFormat(filelimits, filepart, 3 );
+ *       Format* testFormats[] =
+ *           {fileform, NULL, NumberFormat::createInstance(status)};
+ *       MessageFormat pattform("There {0} on {1}", status );
+ *       pattform.adoptFormats(testFormats, 3);
+ *       Formattable testArgs[] = {0L, "Disk A"};
+ *       FieldPosition fp(0);
+ *       UnicodeString str;
+ *       char buf[256];
+ *       for (int32_t i = 0; i < 4; ++i) {
+ *           Formattable fInt(i);
+ *           testArgs[0] = fInt;
+ *           pattform.format(testArgs, 2, str, fp, status );
+ *           str.extract(0, str.length(), buf, "");
+ *           str.truncate(0);
+ *           cout << "Output for i=" << i << " : " << buf << endl;
+ *       }
+ *       cout << endl;
+ *       return 0;
+ *   }
+ * \endcode
+ *
+ * <p><em>User subclasses are not supported.</em> While clients may write
+ * subclasses, such code will not necessarily work and will not be
+ * guaranteed to work stably from release to release.
+ */
+class U_I18N_API ChoiceFormat: public NumberFormat {
+public:
+    /**
+     * Construct a new ChoiceFormat with the limits and the corresponding formats
+     * based on the pattern.
+     *
+     * @param pattern   Pattern used to construct object.
+     * @param status    Output param to receive success code.  If the
+     *                  pattern cannot be parsed, set to failure code.
+     * @stable ICU 2.0
+     */
+    ChoiceFormat(const UnicodeString& pattern,
+                 UErrorCode& status);
+
+
+    /**
+     * Construct a new ChoiceFormat with the given limits and formats.  Copy
+     * the limits and formats instead of adopting them.
+     *
+     * @param limits    Array of limit values.
+     * @param formats   Array of formats.
+     * @param count     Size of 'limits' and 'formats' arrays.
+     * @stable ICU 2.0
+     */
+    
+    ChoiceFormat(const double* limits,
+                 const UnicodeString* formats,
+                 int32_t count );
+
+    /**
+     * Construct a new ChoiceFormat with the given limits and formats.
+     * Copy the limits and formats (instead of adopting them).  By
+     * default, each limit in the array specifies the inclusive lower
+     * bound of its range, and the exclusive upper bound of the previous
+     * range.  However, if the isLimitOpen element corresponding to a
+     * limit is TRUE, then the limit is the exclusive lower bound of its
+     * range, and the inclusive upper bound of the previous range.
+     * @param limits Array of limit values
+     * @param closures Array of booleans specifying whether each
+     * element of 'limits' is open or closed.  If FALSE, then the
+     * corresponding limit is a member of the range above it.  If TRUE,
+     * then the limit belongs to the range below it.
+     * @param formats Array of formats
+     * @param count Size of 'limits', 'closures', and 'formats' arrays
+     * @stable ICU 2.4
+     */
+    ChoiceFormat(const double* limits,
+                 const UBool* closures,
+                 const UnicodeString* formats,
+                 int32_t count);
+
+    /**
+     * Copy constructor.
+     *
+     * @param that   ChoiceFormat object to be copied from
+     * @stable ICU 2.0
+     */
+    ChoiceFormat(const ChoiceFormat& that);
+
+    /**
+     * Assignment operator.
+     *
+     * @param that   ChoiceFormat object to be copied
+     * @stable ICU 2.0
+     */
+    const ChoiceFormat& operator=(const ChoiceFormat& that);
+
+    /**
+     * Destructor.
+     * @stable ICU 2.0
+     */
+    virtual ~ChoiceFormat();
+
+    /**
+     * Clone this Format object polymorphically. The caller owns the
+     * result and should delete it when done.
+     *
+     * @return a copy of this object
+     * @stable ICU 2.0
+     */
+    virtual Format* clone(void) const;
+
+    /**
+     * Return true if the given Format objects are semantically equal.
+     * Objects of different subclasses are considered unequal.
+     *
+     * @param other    ChoiceFormat object to be compared 
+     * @return         true if other is the same as this. 
+     * @stable ICU 2.0
+     */
+    virtual UBool operator==(const Format& other) const;
+
+    /**
+     * Sets the pattern.
+     * @param pattern   The pattern to be applied.
+     * @param status    Output param set to success/failure code on
+     *                  exit. If the pattern is invalid, this will be
+     *                  set to a failure result.
+     * @stable ICU 2.0
+     */
+    virtual void applyPattern(const UnicodeString& pattern,
+                              UErrorCode& status);
+
+    /**
+     * Sets the pattern.
+     * @param pattern    The pattern to be applied.
+     * @param parseError Struct to recieve information on position 
+     *                   of error if an error is encountered
+     * @param status     Output param set to success/failure code on
+     *                   exit. If the pattern is invalid, this will be
+     *                   set to a failure result.
+     * @stable ICU 2.0
+     */
+    virtual void applyPattern(const UnicodeString& pattern,
+                             UParseError& parseError,
+                             UErrorCode& status);
+    /**
+     * Gets the pattern.
+     * 
+     * @param pattern    Output param which will recieve the pattern
+     *                   Previous contents are deleted.
+     * @return    A reference to 'pattern'
+     * @stable ICU 2.0
+     */
+    virtual UnicodeString& toPattern(UnicodeString &pattern) const;
+
+    /**
+     * Set the choices to be used in formatting.
+     *
+     * @param limitsToCopy      Contains the top value that you want
+     *                          parsed with that format,and should be in
+     *                          ascending sorted order. When formatting X,
+     *                          the choice will be the i, where limit[i]
+     *                          &lt;= X &lt; limit[i+1].
+     * @param formatsToCopy     The format strings you want to use for each limit.
+     * @param count             The size of the above arrays.
+     * @stable ICU 2.0
+     */
+    virtual void setChoices(const double* limitsToCopy,
+                            const UnicodeString* formatsToCopy,
+                            int32_t count );    
+
+    /**
+     * Set the choices to be used in formatting.  See class description
+     * for documenatation of the limits, closures, and formats arrays.
+     * @param limits Array of limits
+     * @param closures Array of limit booleans
+     * @param formats Array of format string
+     * @param count The size of the above arrays
+     * @stable ICU 2.4
+     */
+    virtual void setChoices(const double* limits,
+                            const UBool* closures,
+                            const UnicodeString* formats,
+                            int32_t count);
+
+    /**
+     * Get the limits passed in the constructor.
+     *
+     * @param count    The size of the limits arrays
+     * @return the limits.
+     * @stable ICU 2.0
+     */
+    virtual const double* getLimits(int32_t& count) const;
+    
+    /**
+     * Get the limit booleans passed in the constructor.  The caller
+     * must not delete the result.
+     *
+     * @param count   The size of the arrays
+     * @return the closures
+     * @stable ICU 2.4
+     */
+    virtual const UBool* getClosures(int32_t& count) const;
+
+    /**
+     * Get the formats passed in the constructor.
+     *
+     * @param count   The size of the arrays
+     * @return the formats.
+     * @stable ICU 2.0
+     */
+    virtual const UnicodeString* getFormats(int32_t& count) const;
+
+    /**
+     * Format a double or long number using this object's choices.
+     *
+     * @param number    The value to be formatted.
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     * @param pos       On input: an alignment field, if desired.
+     *                  On output: the offsets of the alignment field.
+     * @return          Reference to 'appendTo' parameter.
+     * @stable ICU 2.0
+     */
+    virtual UnicodeString& format(double number,
+                                  UnicodeString& appendTo,
+                                  FieldPosition& pos) const;
+    /**
+     * Format a int_32t number using this object's choices.
+     *
+     * @param number    The value to be formatted.
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     * @param pos       On input: an alignment field, if desired.
+     *                  On output: the offsets of the alignment field.
+     * @return          Reference to 'appendTo' parameter.
+     * @stable ICU 2.0
+     */
+    virtual UnicodeString& format(int32_t number,
+                                  UnicodeString& appendTo,
+                                  FieldPosition& pos) const;
+
+    /**
+     * Format an int64_t number using this object's choices.
+     *
+     * @param number    The value to be formatted.
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     * @param pos       On input: an alignment field, if desired.
+     *                  On output: the offsets of the alignment field.
+     * @return          Reference to 'appendTo' parameter.
+     * @stable ICU 2.8
+     */
+    virtual UnicodeString& format(int64_t number,
+                                  UnicodeString& appendTo,
+                                  FieldPosition& pos) const;
+
+    /**
+     * Format an array of objects using this object's choices.
+     *
+     * @param objs      The array of objects to be formatted.
+     * @param cnt       The size of objs.
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     * @param pos       On input: an alignment field, if desired.
+     *                  On output: the offsets of the alignment field.
+     * @param success   Output param set to success/failure code on
+     *                  exit. 
+     * @return          Reference to 'appendTo' parameter.
+     * @stable ICU 2.0
+     */
+    virtual UnicodeString& format(const Formattable* objs,
+                                  int32_t cnt,
+                                  UnicodeString& appendTo,
+                                  FieldPosition& pos,
+                                  UErrorCode& success) const;
+    /**
+     * Format an object using this object's choices.
+     *
+     *
+     * @param obj       The object to be formatted.
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     * @param pos       On input: an alignment field, if desired.
+     *                  On output: the offsets of the alignment field.
+     * @param status    Output param set to success/failure code on
+     *                  exit. 
+     * @return          Reference to 'appendTo' parameter.
+     * @stable ICU 2.0
+     */
+    virtual UnicodeString& format(const Formattable& obj,
+                                  UnicodeString& appendTo,
+                                  FieldPosition& pos, 
+                                  UErrorCode& status) const;
+
+    /**
+     * Redeclared NumberFormat method.
+     *
+     * @param obj       The object to be formatted.
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     * @param status    Output param set to success/failure code on
+     *                  exit. 
+     * @return          Reference to 'appendTo' parameter.
+     * @stable ICU 2.0
+     */
+    UnicodeString& format(const Formattable& obj,
+                          UnicodeString& appendTo,
+                          UErrorCode& status) const;
+
+    /**
+     * Redeclared NumberFormat method.
+     * Format a double number. These methods call the NumberFormat
+     * pure virtual format() methods with the default FieldPosition.
+     *
+     * @param number    The value to be formatted.
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     * @return          Reference to 'appendTo' parameter.
+     * @stable ICU 2.0
+     */
+    UnicodeString& format(  double number,
+                            UnicodeString& appendTo) const;
+
+    /**
+     * Redeclared NumberFormat method.
+     * Format a long number. These methods call the NumberFormat
+     * pure virtual format() methods with the default FieldPosition.
+     *
+     * @param number    The value to be formatted.
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     * @return          Reference to 'appendTo' parameter.
+     * @stable ICU 2.0
+     */
+    UnicodeString& format(  int32_t number,
+                            UnicodeString& appendTo) const;
+
+   /**
+    * Return a long if possible (e.g. within range LONG_MAX,
+    * LONG_MAX], and with no decimals), otherwise a double.  If
+    * IntegerOnly is set, will stop at a decimal point (or equivalent;
+    * e.g. for rational numbers "1 2/3", will stop after the 1).
+    * <P>
+    * If no object can be parsed, parsePosition is unchanged, and NULL is
+    * returned.
+    *
+    * @param text           The text to be parsed.
+    * @param result         Formattable to be set to the parse result.
+    *                       If parse fails, return contents are undefined.
+    * @param parsePosition  The position to start parsing at on input.
+    *                       On output, moved to after the last successfully
+    *                       parse character. On parse failure, does not change.
+    * @see                  NumberFormat::isParseIntegerOnly
+    * @stable ICU 2.0
+    */
+    virtual void parse(const UnicodeString& text,
+                       Formattable& result,
+                       ParsePosition& parsePosition) const;
+    
+    /**
+    * Return a long if possible (e.g. within range LONG_MAX,
+    * LONG_MAX], and with no decimals), otherwise a double.  If
+    * IntegerOnly is set, will stop at a decimal point (or equivalent;
+    * e.g. for rational numbers "1 2/3", will stop after the 1).
+    * <P>
+    * If no object can be parsed, parsePosition is unchanged, and NULL is
+    * returned.
+    *
+    * @param text           The text to be parsed.
+    * @param result         Formattable to be set to the parse result.
+    *                       If parse fails, return contents are undefined.
+    * @param status         Output param with the formatted string.
+    * @see                  NumberFormat::isParseIntegerOnly
+    * @stable ICU 2.0
+    */
+    virtual void parse(const UnicodeString& text,
+                       Formattable& result,
+                       UErrorCode& status) const;
+    
+    
+public:
+    /**
+     * Returns a unique class ID POLYMORPHICALLY.  Pure virtual override.
+     * This method is to implement a simple version of RTTI, since not all
+     * C++ compilers support genuine RTTI.  Polymorphic operator==() and
+     * clone() methods call this method.
+     *
+     * @return          The class ID for this object. All objects of a
+     *                  given class have the same class ID.  Objects of
+     *                  other classes have different class IDs.
+     * @stable ICU 2.0
+     */
+    virtual UClassID getDynamicClassID(void) const;
+
+    /**
+     * Return the class ID for this class.  This is useful only for
+     * comparing to a return value from getDynamicClassID().  For example:
+     * <pre>
+     * .       Base* polymorphic_pointer = createPolymorphicObject();
+     * .       if (polymorphic_pointer->getDynamicClassID() ==
+     * .           Derived::getStaticClassID()) ...
+     * </pre>
+     * @return          The class ID for all objects of this class.
+     * @stable ICU 2.0
+     */
+    static UClassID U_EXPORT2 getStaticClassID(void);
+
+private:
+    // static cache management (thread-safe)
+  //  static NumberFormat* getNumberFormat(UErrorCode &status); // call this function to 'check out' a numberformat from the cache.
+  //  static void          releaseNumberFormat(NumberFormat *adopt); // call this function to 'return' the number format to the cache.
+    
+    /**
+     * Converts a string to a double value using a default NumberFormat object
+     * which is static (shared by all ChoiceFormat instances).
+     * @param string the string to be converted with.
+     * @return the converted double number.
+     */
+    static double stod(const UnicodeString& string);
+
+    /**
+     * Converts a double value to a string using a default NumberFormat object
+     * which is static (shared by all ChoiceFormat instances).
+     * @param value the double number to be converted with.
+     * @param string the result string.
+     * @return the converted string.
+     */
+    static UnicodeString& dtos(double value, UnicodeString& string);
+
+    ChoiceFormat(); // default constructor not implemented
+
+    /**
+     * Construct a new ChoiceFormat with the limits and the corresponding formats
+     * based on the pattern.
+     *
+     * @param newPattern   Pattern used to construct object.
+     * @param parseError   Struct to recieve information on position 
+     *                     of error if an error is encountered.
+     * @param status       Output param to receive success code.  If the
+     *                     pattern cannot be parsed, set to failure code.
+     * @stable ICU 2.0
+     */
+    ChoiceFormat(const UnicodeString& newPattern,
+                 UParseError& parseError,
+                 UErrorCode& status);
+
+    friend class MessageFormat;
+    /**
+     * Each ChoiceFormat divides the range -Inf..+Inf into fCount
+     * intervals.  The intervals are:
+     *
+     *         0: fChoiceLimits[0]..fChoiceLimits[1]
+     *         1: fChoiceLimits[1]..fChoiceLimits[2]
+     *        ...
+     *  fCount-2: fChoiceLimits[fCount-2]..fChoiceLimits[fCount-1]
+     *  fCount-1: fChoiceLimits[fCount-1]..+Inf
+     *
+     * Interval 0 is special; during formatting (mapping numbers to
+     * strings), it also contains all numbers less than
+     * fChoiceLimits[0], as well as NaN values.
+     *
+     * Interval i maps to and from string fChoiceFormats[i].  When
+     * parsing (mapping strings to numbers), then intervals map to
+     * their lower limit, that is, interval i maps to fChoiceLimit[i].
+     *
+     * The intervals may be closed, half open, or open.  This affects
+     * formatting but does not affect parsing.  Interval i is affected
+     * by fClosures[i] and fClosures[i+1].  If fClosures[i]
+     * is FALSE, then the value fChoiceLimits[i] is in interval i.
+     * That is, intervals i and i are:
+     *
+     *  i-1:                 ... x < fChoiceLimits[i]
+     *    i: fChoiceLimits[i] <= x ...
+     *
+     * If fClosures[i] is TRUE, then the value fChoiceLimits[i] is
+     * in interval i-1.  That is, intervals i-1 and i are:
+     *
+     *  i-1:                ... x <= fChoiceLimits[i]
+     *    i: fChoiceLimits[i] < x ...
+     *
+     * Because of the nature of interval 0, fClosures[0] has no
+     * effect.
+
+     */
+    double*         fChoiceLimits;
+    UBool*          fClosures;
+    UnicodeString*  fChoiceFormats;
+    int32_t         fCount;
+};
+ 
+inline UnicodeString&
+ChoiceFormat::format(const Formattable& obj,
+                     UnicodeString& appendTo,
+                     UErrorCode& status) const {
+    // Don't use Format:: - use immediate base class only,
+    // in case immediate base modifies behavior later.
+    return NumberFormat::format(obj, appendTo, status);
+}
+
+inline UnicodeString&
+ChoiceFormat::format(double number,
+                     UnicodeString& appendTo) const {
+    return NumberFormat::format(number, appendTo);
+}
+
+inline UnicodeString&
+ChoiceFormat::format(int32_t number,
+                     UnicodeString& appendTo) const {
+    return NumberFormat::format(number, appendTo);
+}
+U_NAMESPACE_END
+
+#endif /* #if !UCONFIG_NO_FORMATTING */
+
+#endif // _CHOICFMT
+//eof

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/coleitr.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/coleitr.h b/src/apps/couch_collate/platform/osx/icu/unicode/coleitr.h
new file mode 100644
index 0000000..4025a41
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/coleitr.h
@@ -0,0 +1,400 @@
+/*
+ ******************************************************************************
+ *   Copyright (C) 1997-2008, International Business Machines
+ *   Corporation and others.  All Rights Reserved.
+ ******************************************************************************
+ */
+
+/**
+ * \file 
+ * \brief C++ API: Collation Element Iterator.
+ */
+
+/**
+* File coleitr.h
+*
+* 
+*
+* Created by: Helena Shih
+*
+* Modification History:
+*
+*  Date       Name        Description
+*
+*  8/18/97    helena      Added internal API documentation.
+* 08/03/98    erm         Synched with 1.2 version CollationElementIterator.java
+* 12/10/99    aliu        Ported Thai collation support from Java.
+* 01/25/01    swquek      Modified into a C++ wrapper calling C APIs (ucoliter.h)
+* 02/19/01    swquek      Removed CollationElementsIterator() since it is 
+*                         private constructor and no calls are made to it
+*/
+
+#ifndef COLEITR_H
+#define COLEITR_H
+
+#include "unicode/utypes.h"
+
+ 
+#if !UCONFIG_NO_COLLATION
+
+#include "unicode/uobject.h"
+#include "unicode/tblcoll.h"
+#include "unicode/ucoleitr.h"
+
+/** 
+ * The UCollationElements struct.
+ * For usage in C programs.
+ * @stable ICU 2.0
+ */
+typedef struct UCollationElements UCollationElements;
+
+U_NAMESPACE_BEGIN
+
+/**
+* The CollationElementIterator class is used as an iterator to walk through     
+* each character of an international string. Use the iterator to return the
+* ordering priority of the positioned character. The ordering priority of a 
+* character, which we refer to as a key, defines how a character is collated in 
+* the given collation object.
+* For example, consider the following in Spanish:
+* <pre>
+*        "ca" -> the first key is key('c') and second key is key('a').
+*        "cha" -> the first key is key('ch') and second key is key('a').</pre>
+* And in German,
+* <pre> \htmlonly       "&#x00E6;b"-> the first key is key('a'), the second key is key('e'), and
+*        the third key is key('b'). \endhtmlonly </pre>
+* The key of a character, is an integer composed of primary order(short),
+* secondary order(char), and tertiary order(char). Java strictly defines the 
+* size and signedness of its primitive data types. Therefore, the static
+* functions primaryOrder(), secondaryOrder(), and tertiaryOrder() return 
+* int32_t to ensure the correctness of the key value.
+* <p>Example of the iterator usage: (without error checking)
+* <pre>
+* \code
+*   void CollationElementIterator_Example()
+*   {
+*       UnicodeString str = "This is a test";
+*       UErrorCode success = U_ZERO_ERROR;
+*       RuleBasedCollator* rbc =
+*           (RuleBasedCollator*) RuleBasedCollator::createInstance(success);
+*       CollationElementIterator* c =
+*           rbc->createCollationElementIterator( str );
+*       int32_t order = c->next(success);
+*       c->reset();
+*       order = c->previous(success);
+*       delete c;
+*       delete rbc;
+*   }
+* \endcode
+* </pre>
+* <p>
+* CollationElementIterator::next returns the collation order of the next
+* character based on the comparison level of the collator. 
+* CollationElementIterator::previous returns the collation order of the 
+* previous character based on the comparison level of the collator. 
+* The Collation Element Iterator moves only in one direction between calls to
+* CollationElementIterator::reset. That is, CollationElementIterator::next() 
+* and CollationElementIterator::previous can not be inter-used. Whenever 
+* CollationElementIterator::previous is to be called after 
+* CollationElementIterator::next() or vice versa, 
+* CollationElementIterator::reset has to be called first to reset the status, 
+* shifting pointers to either the end or the start of the string. Hence at the 
+* next call of CollationElementIterator::previous or 
+* CollationElementIterator::next(), the first or last collation order will be 
+* returned. 
+* If a change of direction is done without a CollationElementIterator::reset(), 
+* the result is undefined.
+* The result of a forward iterate (CollationElementIterator::next) and 
+* reversed result of the backward iterate (CollationElementIterator::previous) 
+* on the same string are equivalent, if collation orders with the value 
+* UCOL_IGNORABLE are ignored.
+* Character based on the comparison level of the collator.  A collation order 
+* consists of primary order, secondary order and tertiary order.  The data 
+* type of the collation order is <strong>t_int32</strong>. 
+*
+* Note, CollationElementIterator should not be subclassed.
+* @see     Collator
+* @see     RuleBasedCollator
+* @version 1.8 Jan 16 2001
+*/
+class U_I18N_API CollationElementIterator : public UObject {
+public: 
+
+    // CollationElementIterator public data member ------------------------------
+
+    enum {
+        /**
+         * NULLORDER indicates that an error has occured while processing
+         * @stable ICU 2.0
+         */
+        NULLORDER = (int32_t)0xffffffff
+    };
+
+    // CollationElementIterator public constructor/destructor -------------------
+
+    /**
+    * Copy constructor.
+    *
+    * @param other    the object to be copied from
+    * @stable ICU 2.0
+    */
+    CollationElementIterator(const CollationElementIterator& other);
+
+    /** 
+    * Destructor
+    * @stable ICU 2.0
+    */
+    virtual ~CollationElementIterator();
+
+    // CollationElementIterator public methods ----------------------------------
+
+    /**
+    * Returns true if "other" is the same as "this"
+    *
+    * @param other    the object to be compared
+    * @return         true if "other" is the same as "this"
+    * @stable ICU 2.0
+    */
+    UBool operator==(const CollationElementIterator& other) const;
+
+    /**
+    * Returns true if "other" is not the same as "this".
+    *
+    * @param other    the object to be compared
+    * @return         true if "other" is not the same as "this"
+    * @stable ICU 2.0
+    */
+    UBool operator!=(const CollationElementIterator& other) const;
+
+    /**
+    * Resets the cursor to the beginning of the string.
+    * @stable ICU 2.0
+    */
+    void reset(void);
+
+    /**
+    * Gets the ordering priority of the next character in the string.
+    * @param status the error code status.
+    * @return the next character's ordering. otherwise returns NULLORDER if an 
+    *         error has occured or if the end of string has been reached
+    * @stable ICU 2.0
+    */
+    int32_t next(UErrorCode& status);
+
+    /**
+    * Get the ordering priority of the previous collation element in the string.
+    * @param status the error code status.
+    * @return the previous element's ordering. otherwise returns NULLORDER if an 
+    *         error has occured or if the start of string has been reached
+    * @stable ICU 2.0
+    */
+    int32_t previous(UErrorCode& status);
+
+    /**
+    * Gets the primary order of a collation order.
+    * @param order the collation order
+    * @return the primary order of a collation order.
+    * @stable ICU 2.0
+    */
+    static inline int32_t primaryOrder(int32_t order);
+
+    /**
+    * Gets the secondary order of a collation order.
+    * @param order the collation order
+    * @return the secondary order of a collation order.
+    * @stable ICU 2.0
+    */
+    static inline int32_t secondaryOrder(int32_t order);
+
+    /**
+    * Gets the tertiary order of a collation order.
+    * @param order the collation order
+    * @return the tertiary order of a collation order.
+    * @stable ICU 2.0
+    */
+    static inline int32_t tertiaryOrder(int32_t order);
+
+    /**
+    * Return the maximum length of any expansion sequences that end with the 
+    * specified comparison order.
+    * @param order a collation order returned by previous or next.
+    * @return maximum size of the expansion sequences ending with the collation 
+    *         element or 1 if collation element does not occur at the end of any 
+    *         expansion sequence
+    * @stable ICU 2.0
+    */
+    int32_t getMaxExpansion(int32_t order) const;
+
+    /**
+    * Gets the comparison order in the desired strength. Ignore the other
+    * differences.
+    * @param order The order value
+    * @stable ICU 2.0
+    */
+    int32_t strengthOrder(int32_t order) const;
+
+    /**
+    * Sets the source string.
+    * @param str the source string.
+    * @param status the error code status.
+    * @stable ICU 2.0
+    */
+    void setText(const UnicodeString& str, UErrorCode& status);
+
+    /**
+    * Sets the source string.
+    * @param str the source character iterator.
+    * @param status the error code status.
+    * @stable ICU 2.0
+    */
+    void setText(CharacterIterator& str, UErrorCode& status);
+
+    /**
+    * Checks if a comparison order is ignorable.
+    * @param order the collation order.
+    * @return TRUE if a character is ignorable, FALSE otherwise.
+    * @stable ICU 2.0
+    */
+    static inline UBool isIgnorable(int32_t order);
+
+    /**
+    * Gets the offset of the currently processed character in the source string.
+    * @return the offset of the character.
+    * @stable ICU 2.0
+    */
+    int32_t getOffset(void) const;
+
+    /**
+    * Sets the offset of the currently processed character in the source string.
+    * @param newOffset the new offset.
+    * @param status the error code status.
+    * @return the offset of the character.
+    * @stable ICU 2.0
+    */
+    void setOffset(int32_t newOffset, UErrorCode& status);
+
+    /**
+    * ICU "poor man's RTTI", returns a UClassID for the actual class.
+    *
+    * @stable ICU 2.2
+    */
+    virtual UClassID getDynamicClassID() const;
+
+    /**
+    * ICU "poor man's RTTI", returns a UClassID for this class.
+    *
+    * @stable ICU 2.2
+    */
+    static UClassID U_EXPORT2 getStaticClassID();
+
+protected:
+  
+    // CollationElementIterator protected constructors --------------------------
+    /**
+    * @stable ICU 2.0
+    */
+    friend class RuleBasedCollator;
+
+    /**
+    * CollationElementIterator constructor. This takes the source string and the 
+    * collation object. The cursor will walk thru the source string based on the 
+    * predefined collation rules. If the source string is empty, NULLORDER will 
+    * be returned on the calls to next().
+    * @param sourceText    the source string.
+    * @param order         the collation object.
+    * @param status        the error code status.
+    * @stable ICU 2.0
+    */
+    CollationElementIterator(const UnicodeString& sourceText,
+        const RuleBasedCollator* order, UErrorCode& status);
+
+    /**
+    * CollationElementIterator constructor. This takes the source string and the 
+    * collation object.  The cursor will walk thru the source string based on the 
+    * predefined collation rules.  If the source string is empty, NULLORDER will 
+    * be returned on the calls to next().
+    * @param sourceText    the source string.
+    * @param order         the collation object.
+    * @param status        the error code status.
+    * @stable ICU 2.0
+    */
+    CollationElementIterator(const CharacterIterator& sourceText,
+        const RuleBasedCollator* order, UErrorCode& status);
+
+    // CollationElementIterator protected methods -------------------------------
+
+    /**
+    * Assignment operator
+    *
+    * @param other    the object to be copied
+    * @stable ICU 2.0
+    */
+    const CollationElementIterator&
+        operator=(const CollationElementIterator& other);
+
+private:
+    CollationElementIterator(); // default constructor not implemented
+
+    // CollationElementIterator private data members ----------------------------
+
+    /**
+    * Data wrapper for collation elements
+    */
+    UCollationElements *m_data_;
+
+    /**
+    * Indicates if m_data_ belongs to this object.
+    */
+    UBool isDataOwned_;
+
+};
+
+// CollationElementIterator inline method defination --------------------------
+
+/**
+* Get the primary order of a collation order.
+* @param order the collation order
+* @return the primary order of a collation order.
+*/
+inline int32_t CollationElementIterator::primaryOrder(int32_t order)
+{
+    order &= RuleBasedCollator::PRIMARYORDERMASK;
+    return (order >> RuleBasedCollator::PRIMARYORDERSHIFT);
+}
+
+/**
+* Get the secondary order of a collation order.
+* @param order the collation order
+* @return the secondary order of a collation order.
+*/
+inline int32_t CollationElementIterator::secondaryOrder(int32_t order)
+{
+    order = order & RuleBasedCollator::SECONDARYORDERMASK;
+    return (order >> RuleBasedCollator::SECONDARYORDERSHIFT);
+}
+
+/**
+* Get the tertiary order of a collation order.
+* @param order the collation order
+* @return the tertiary order of a collation order.
+*/
+inline int32_t CollationElementIterator::tertiaryOrder(int32_t order)
+{
+    return (order &= RuleBasedCollator::TERTIARYORDERMASK);
+}
+
+inline int32_t CollationElementIterator::getMaxExpansion(int32_t order) const
+{
+    return ucol_getMaxExpansion(m_data_, (uint32_t)order);
+}
+
+inline UBool CollationElementIterator::isIgnorable(int32_t order)
+{
+    return (primaryOrder(order) == RuleBasedCollator::PRIMIGNORABLE);
+}
+
+U_NAMESPACE_END
+
+#endif /* #if !UCONFIG_NO_COLLATION */
+
+#endif


[46/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_file.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_file.erl b/apps/couch/src/couch_file.erl
deleted file mode 100644
index ee5dafb..0000000
--- a/apps/couch/src/couch_file.erl
+++ /dev/null
@@ -1,532 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_file).
--behaviour(gen_server).
-
--include("couch_db.hrl").
-
--define(SIZE_BLOCK, 4096).
-
--record(file, {
-    fd,
-    eof = 0
-}).
-
-% public API
--export([open/1, open/2, close/1, bytes/1, sync/1, truncate/2]).
--export([pread_term/2, pread_iolist/2, pread_binary/2]).
--export([append_binary/2, append_binary_md5/2]).
--export([append_raw_chunk/2, assemble_file_chunk/1, assemble_file_chunk/2]).
--export([append_term/2, append_term/3, append_term_md5/2, append_term_md5/3]).
--export([write_header/2, read_header/1]).
--export([delete/2, delete/3, nuke_dir/2, init_delete_dir/1]).
-
-% gen_server callbacks
--export([init/1, terminate/2, code_change/3]).
--export([handle_call/3, handle_cast/2, handle_info/2]).
-
-%%----------------------------------------------------------------------
-%% Args:   Valid Options are [create] and [create,overwrite].
-%%  Files are opened in read/write mode.
-%% Returns: On success, {ok, Fd}
-%%  or {error, Reason} if the file could not be opened.
-%%----------------------------------------------------------------------
-
-open(Filepath) ->
-    open(Filepath, []).
-
-open(Filepath, Options) ->
-    case gen_server:start_link(couch_file,
-            {Filepath, Options, self(), Ref = make_ref()}, []) of
-    {ok, Fd} ->
-        {ok, Fd};
-    ignore ->
-        % get the error
-        receive
-        {Ref, Pid, {error, Reason} = Error} ->
-            case process_info(self(), trap_exit) of
-            {trap_exit, true} -> receive {'EXIT', Pid, _} -> ok end;
-            {trap_exit, false} -> ok
-            end,
-            case {lists:member(nologifmissing, Options), Reason} of
-            {true, enoent} -> ok;
-            _ ->
-            ?LOG_ERROR("Could not open file ~s: ~s",
-                [Filepath, file:format_error(Reason)])
-            end,
-            Error
-        end;
-    Error ->
-        % We can't say much here, because it could be any kind of error.
-        % Just let it bubble and an encapsulating subcomponent can perhaps
-        % be more informative. It will likely appear in the SASL log, anyway.
-        Error
-    end.
-
-
-%%----------------------------------------------------------------------
-%% Purpose: To append an Erlang term to the end of the file.
-%% Args:    Erlang term to serialize and append to the file.
-%% Returns: {ok, Pos, NumBytesWritten} where Pos is the file offset to
-%%  the beginning the serialized  term. Use pread_term to read the term
-%%  back.
-%%  or {error, Reason}.
-%%----------------------------------------------------------------------
-
-append_term(Fd, Term) ->
-    append_term(Fd, Term, []).
-
-append_term(Fd, Term, Options) ->
-    Comp = couch_util:get_value(compression, Options, ?DEFAULT_COMPRESSION),
-    append_binary(Fd, couch_compress:compress(Term, Comp)).
-
-append_term_md5(Fd, Term) ->
-    append_term_md5(Fd, Term, []).
-
-append_term_md5(Fd, Term, Options) ->
-    Comp = couch_util:get_value(compression, Options, ?DEFAULT_COMPRESSION),
-    append_binary_md5(Fd, couch_compress:compress(Term, Comp)).
-
-%%----------------------------------------------------------------------
-%% Purpose: To append an Erlang binary to the end of the file.
-%% Args:    Erlang term to serialize and append to the file.
-%% Returns: {ok, Pos, NumBytesWritten} where Pos is the file offset to the
-%%  beginning the serialized term. Use pread_term to read the term back.
-%%  or {error, Reason}.
-%%----------------------------------------------------------------------
-
-append_binary(Fd, Bin) ->
-    gen_server:call(Fd, {append_bin, assemble_file_chunk(Bin)}, infinity).
-    
-append_binary_md5(Fd, Bin) ->
-    gen_server:call(Fd,
-        {append_bin, assemble_file_chunk(Bin, couch_util:md5(Bin))}, infinity).
-
-append_raw_chunk(Fd, Chunk) ->
-    gen_server:call(Fd, {append_bin, Chunk}, infinity).
-
-
-assemble_file_chunk(Bin) ->
-    [<<0:1/integer, (iolist_size(Bin)):31/integer>>, Bin].
-
-assemble_file_chunk(Bin, Md5) ->
-    [<<1:1/integer, (iolist_size(Bin)):31/integer>>, Md5, Bin].
-
-%%----------------------------------------------------------------------
-%% Purpose: Reads a term from a file that was written with append_term
-%% Args:    Pos, the offset into the file where the term is serialized.
-%% Returns: {ok, Term}
-%%  or {error, Reason}.
-%%----------------------------------------------------------------------
-
-
-pread_term(Fd, Pos) ->
-    {ok, Bin} = pread_binary(Fd, Pos),
-    {ok, couch_compress:decompress(Bin)}.
-
-
-%%----------------------------------------------------------------------
-%% Purpose: Reads a binrary from a file that was written with append_binary
-%% Args:    Pos, the offset into the file where the term is serialized.
-%% Returns: {ok, Term}
-%%  or {error, Reason}.
-%%----------------------------------------------------------------------
-
-pread_binary(Fd, Pos) ->
-    {ok, L} = pread_iolist(Fd, Pos),
-    {ok, iolist_to_binary(L)}.
-
-
-pread_iolist(Fd, Pos) ->
-    case gen_server:call(Fd, {pread_iolist, Pos}, infinity) of
-    {ok, IoList, <<>>} ->
-        {ok, IoList};
-    {ok, IoList, Md5} ->
-        case couch_util:md5(IoList) of
-        Md5 ->
-            {ok, IoList};
-        _ ->
-            exit({file_corruption, <<"file corruption">>})
-        end;
-    Error ->
-        Error
-    end.
-
-%%----------------------------------------------------------------------
-%% Purpose: The length of a file, in bytes.
-%% Returns: {ok, Bytes}
-%%  or {error, Reason}.
-%%----------------------------------------------------------------------
-
-% length in bytes
-bytes(Fd) ->
-    gen_server:call(Fd, bytes, infinity).
-
-%%----------------------------------------------------------------------
-%% Purpose: Truncate a file to the number of bytes.
-%% Returns: ok
-%%  or {error, Reason}.
-%%----------------------------------------------------------------------
-
-truncate(Fd, Pos) ->
-    gen_server:call(Fd, {truncate, Pos}, infinity).
-
-%%----------------------------------------------------------------------
-%% Purpose: Ensure all bytes written to the file are flushed to disk.
-%% Returns: ok
-%%  or {error, Reason}.
-%%----------------------------------------------------------------------
-
-sync(Filepath) when is_list(Filepath) ->
-    {ok, Fd} = file:open(Filepath, [append, raw]),
-    try ok = file:sync(Fd) after ok = file:close(Fd) end;
-sync(Fd) ->
-    gen_server:call(Fd, sync, infinity).
-
-%%----------------------------------------------------------------------
-%% Purpose: Close the file.
-%% Returns: ok
-%%----------------------------------------------------------------------
-close(Fd) ->
-    couch_util:shutdown_sync(Fd).
-
-
-delete(RootDir, Filepath) ->
-    delete(RootDir, Filepath, true).
-
-
-delete(RootDir, Filepath, Async) ->
-    DelFile = filename:join([RootDir,".delete", ?b2l(couch_uuids:random())]),
-    case file:rename(Filepath, DelFile) of
-    ok ->
-        if (Async) ->
-            spawn(file, delete, [DelFile]),
-            ok;
-        true ->
-            file:delete(DelFile)
-        end;
-    Error ->
-        Error
-    end.
-
-
-nuke_dir(RootDelDir, Dir) ->
-    FoldFun = fun(File) ->
-        Path = Dir ++ "/" ++ File,
-        case filelib:is_dir(Path) of
-            true ->
-                ok = nuke_dir(RootDelDir, Path),
-                file:del_dir(Path);
-            false ->
-                delete(RootDelDir, Path, false)
-        end
-    end,
-    case file:list_dir(Dir) of
-        {ok, Files} ->
-            lists:foreach(FoldFun, Files),
-            ok = file:del_dir(Dir);
-        {error, enoent} ->
-            ok
-    end.
-
-
-init_delete_dir(RootDir) ->
-    Dir = filename:join(RootDir,".delete"),
-    % note: ensure_dir requires an actual filename companent, which is the
-    % reason for "foo".
-    filelib:ensure_dir(filename:join(Dir,"foo")),
-    filelib:fold_files(Dir, ".*", true,
-        fun(Filename, _) ->
-            ok = file:delete(Filename)
-        end, ok).
-
-
-read_header(Fd) ->
-    case gen_server:call(Fd, find_header, infinity) of
-    {ok, Bin} ->
-        {ok, binary_to_term(Bin)};
-    Else ->
-        Else
-    end.
-
-write_header(Fd, Data) ->
-    Bin = term_to_binary(Data),
-    Md5 = couch_util:md5(Bin),
-    % now we assemble the final header binary and write to disk
-    FinalBin = <<Md5/binary, Bin/binary>>,
-    gen_server:call(Fd, {write_header, FinalBin}, infinity).
-
-
-
-
-init_status_error(ReturnPid, Ref, Error) ->
-    ReturnPid ! {Ref, self(), Error},
-    ignore.
-
-% server functions
-
-init({Filepath, Options, ReturnPid, Ref}) ->
-    process_flag(trap_exit, true),
-    OpenOptions = file_open_options(Options),
-    case lists:member(create, Options) of
-    true ->
-        filelib:ensure_dir(Filepath),
-        case file:open(Filepath, OpenOptions) of
-        {ok, Fd} ->
-            {ok, Length} = file:position(Fd, eof),
-            case Length > 0 of
-            true ->
-                % this means the file already exists and has data.
-                % FYI: We don't differentiate between empty files and non-existant
-                % files here.
-                case lists:member(overwrite, Options) of
-                true ->
-                    {ok, 0} = file:position(Fd, 0),
-                    ok = file:truncate(Fd),
-                    ok = file:sync(Fd),
-                    maybe_track_open_os_files(Options),
-                    {ok, #file{fd=Fd}};
-                false ->
-                    ok = file:close(Fd),
-                    init_status_error(ReturnPid, Ref, {error, eexist})
-                end;
-            false ->
-                maybe_track_open_os_files(Options),
-                {ok, #file{fd=Fd}}
-            end;
-        Error ->
-            init_status_error(ReturnPid, Ref, Error)
-        end;
-    false ->
-        % open in read mode first, so we don't create the file if it doesn't exist.
-        case file:open(Filepath, [read, raw]) of
-        {ok, Fd_Read} ->
-            {ok, Fd} = file:open(Filepath, OpenOptions),
-            ok = file:close(Fd_Read),
-            maybe_track_open_os_files(Options),
-            {ok, Eof} = file:position(Fd, eof),
-            {ok, #file{fd=Fd, eof=Eof}};
-        Error ->
-            init_status_error(ReturnPid, Ref, Error)
-        end
-    end.
-
-file_open_options(Options) ->
-    [read, raw, binary] ++ case lists:member(read_only, Options) of
-    true ->
-        [];
-    false ->
-        [append]
-    end.
-
-maybe_track_open_os_files(FileOptions) ->
-    case lists:member(sys_db, FileOptions) of
-    true ->
-        ok;
-    false ->
-        couch_stats_collector:track_process_count({couchdb, open_os_files})
-    end.
-
-terminate(_Reason, #file{fd = Fd}) ->
-    ok = file:close(Fd).
-
-
-handle_call({pread_iolist, Pos}, _From, File) ->
-    {RawData, NextPos} = try
-        % up to 8Kbs of read ahead
-        read_raw_iolist_int(File, Pos, 2 * ?SIZE_BLOCK - (Pos rem ?SIZE_BLOCK))
-    catch
-    _:_ ->
-        read_raw_iolist_int(File, Pos, 4)
-    end,
-    <<Prefix:1/integer, Len:31/integer, RestRawData/binary>> =
-        iolist_to_binary(RawData),
-    case Prefix of
-    1 ->
-        {Md5, IoList} = extract_md5(
-            maybe_read_more_iolist(RestRawData, 16 + Len, NextPos, File)),
-        {reply, {ok, IoList, Md5}, File};
-    0 ->
-        IoList = maybe_read_more_iolist(RestRawData, Len, NextPos, File),
-        {reply, {ok, IoList, <<>>}, File}
-    end;
-
-handle_call(bytes, _From, #file{fd = Fd} = File) ->
-    {reply, file:position(Fd, eof), File};
-
-handle_call(sync, _From, #file{fd=Fd}=File) ->
-    {reply, file:sync(Fd), File};
-
-handle_call({truncate, Pos}, _From, #file{fd=Fd}=File) ->
-    {ok, Pos} = file:position(Fd, Pos),
-    case file:truncate(Fd) of
-    ok ->
-        {reply, ok, File#file{eof = Pos}};
-    Error ->
-        {reply, Error, File}
-    end;
-
-handle_call({append_bin, Bin}, _From, #file{fd = Fd, eof = Pos} = File) ->
-    Blocks = make_blocks(Pos rem ?SIZE_BLOCK, Bin),
-    Size = iolist_size(Blocks),
-    case file:write(Fd, Blocks) of
-    ok ->
-        {reply, {ok, Pos, Size}, File#file{eof = Pos + Size}};
-    Error ->
-        {reply, Error, File}
-    end;
-
-handle_call({write_header, Bin}, _From, #file{fd = Fd, eof = Pos} = File) ->
-    BinSize = byte_size(Bin),
-    case Pos rem ?SIZE_BLOCK of
-    0 ->
-        Padding = <<>>;
-    BlockOffset ->
-        Padding = <<0:(8*(?SIZE_BLOCK-BlockOffset))>>
-    end,
-    FinalBin = [Padding, <<1, BinSize:32/integer>> | make_blocks(5, [Bin])],
-    case file:write(Fd, FinalBin) of
-    ok ->
-        {reply, ok, File#file{eof = Pos + iolist_size(FinalBin)}};
-    Error ->
-        {reply, Error, File}
-    end;
-
-handle_call(find_header, _From, #file{fd = Fd, eof = Pos} = File) ->
-    {reply, find_header(Fd, Pos div ?SIZE_BLOCK), File}.
-
-handle_cast(close, Fd) ->
-    {stop,normal,Fd}.
-
-code_change(_OldVsn, State, _Extra) ->
-    {ok, State}.
-
-handle_info({'EXIT', _, normal}, Fd) ->
-    {noreply, Fd};
-handle_info({'EXIT', _, Reason}, Fd) ->
-    {stop, Reason, Fd}.
-
-
-find_header(_Fd, -1) ->
-    no_valid_header;
-find_header(Fd, Block) ->
-    case (catch load_header(Fd, Block)) of
-    {ok, Bin} ->
-        {ok, Bin};
-    _Error ->
-        find_header(Fd, Block -1)
-    end.
-
-load_header(Fd, Block) ->
-    {ok, <<1, HeaderLen:32/integer, RestBlock/binary>>} =
-        file:pread(Fd, Block * ?SIZE_BLOCK, ?SIZE_BLOCK),
-    TotalBytes = calculate_total_read_len(5, HeaderLen),
-    case TotalBytes > byte_size(RestBlock) of
-    false ->
-        <<RawBin:TotalBytes/binary, _/binary>> = RestBlock;
-    true ->
-        {ok, Missing} = file:pread(
-            Fd, (Block * ?SIZE_BLOCK) + 5 + byte_size(RestBlock),
-            TotalBytes - byte_size(RestBlock)),
-        RawBin = <<RestBlock/binary, Missing/binary>>
-    end,
-    <<Md5Sig:16/binary, HeaderBin/binary>> =
-        iolist_to_binary(remove_block_prefixes(5, RawBin)),
-    Md5Sig = couch_util:md5(HeaderBin),
-    {ok, HeaderBin}.
-
-maybe_read_more_iolist(Buffer, DataSize, _, _)
-    when DataSize =< byte_size(Buffer) ->
-    <<Data:DataSize/binary, _/binary>> = Buffer,
-    [Data];
-maybe_read_more_iolist(Buffer, DataSize, NextPos, File) ->
-    {Missing, _} =
-        read_raw_iolist_int(File, NextPos, DataSize - byte_size(Buffer)),
-    [Buffer, Missing].
-
--spec read_raw_iolist_int(#file{}, Pos::non_neg_integer(), Len::non_neg_integer()) ->
-    {Data::iolist(), CurPos::non_neg_integer()}.
-read_raw_iolist_int(Fd, {Pos, _Size}, Len) -> % 0110 UPGRADE CODE
-    read_raw_iolist_int(Fd, Pos, Len);
-read_raw_iolist_int(#file{fd = Fd}, Pos, Len) ->
-    BlockOffset = Pos rem ?SIZE_BLOCK,
-    TotalBytes = calculate_total_read_len(BlockOffset, Len),
-    {ok, <<RawBin:TotalBytes/binary>>} = file:pread(Fd, Pos, TotalBytes),
-    {remove_block_prefixes(BlockOffset, RawBin), Pos + TotalBytes}.
-
--spec extract_md5(iolist()) -> {binary(), iolist()}.
-extract_md5(FullIoList) ->
-    {Md5List, IoList} = split_iolist(FullIoList, 16, []),
-    {iolist_to_binary(Md5List), IoList}.
-
-calculate_total_read_len(0, FinalLen) ->
-    calculate_total_read_len(1, FinalLen) + 1;
-calculate_total_read_len(BlockOffset, FinalLen) ->
-    case ?SIZE_BLOCK - BlockOffset of
-    BlockLeft when BlockLeft >= FinalLen ->
-        FinalLen;
-    BlockLeft ->
-        FinalLen + ((FinalLen - BlockLeft) div (?SIZE_BLOCK -1)) +
-            if ((FinalLen - BlockLeft) rem (?SIZE_BLOCK -1)) =:= 0 -> 0;
-                true -> 1 end
-    end.
-
-remove_block_prefixes(_BlockOffset, <<>>) ->
-    [];
-remove_block_prefixes(0, <<_BlockPrefix,Rest/binary>>) ->
-    remove_block_prefixes(1, Rest);
-remove_block_prefixes(BlockOffset, Bin) ->
-    BlockBytesAvailable = ?SIZE_BLOCK - BlockOffset,
-    case size(Bin) of
-    Size when Size > BlockBytesAvailable ->
-        <<DataBlock:BlockBytesAvailable/binary,Rest/binary>> = Bin,
-        [DataBlock | remove_block_prefixes(0, Rest)];
-    _Size ->
-        [Bin]
-    end.
-
-make_blocks(_BlockOffset, []) ->
-    [];
-make_blocks(0, IoList) ->
-    [<<0>> | make_blocks(1, IoList)];
-make_blocks(BlockOffset, IoList) ->
-    case split_iolist(IoList, (?SIZE_BLOCK - BlockOffset), []) of
-    {Begin, End} ->
-        [Begin | make_blocks(0, End)];
-    _SplitRemaining ->
-        IoList
-    end.
-
-%% @doc Returns a tuple where the first element contains the leading SplitAt
-%% bytes of the original iolist, and the 2nd element is the tail. If SplitAt
-%% is larger than byte_size(IoList), return the difference.
--spec split_iolist(IoList::iolist(), SplitAt::non_neg_integer(), Acc::list()) ->
-    {iolist(), iolist()} | non_neg_integer().
-split_iolist(List, 0, BeginAcc) ->
-    {lists:reverse(BeginAcc), List};
-split_iolist([], SplitAt, _BeginAcc) ->
-    SplitAt;
-split_iolist([<<Bin/binary>> | Rest], SplitAt, BeginAcc) when SplitAt > byte_size(Bin) ->
-    split_iolist(Rest, SplitAt - byte_size(Bin), [Bin | BeginAcc]);
-split_iolist([<<Bin/binary>> | Rest], SplitAt, BeginAcc) ->
-    <<Begin:SplitAt/binary,End/binary>> = Bin,
-    split_iolist([End | Rest], 0, [Begin | BeginAcc]);
-split_iolist([Sublist| Rest], SplitAt, BeginAcc) when is_list(Sublist) ->
-    case split_iolist(Sublist, SplitAt, BeginAcc) of
-    {Begin, End} ->
-        {Begin, [End | Rest]};
-    SplitRemaining ->
-        split_iolist(Rest, SplitAt - (SplitAt - SplitRemaining), [Sublist | BeginAcc])
-    end;
-split_iolist([Byte | Rest], SplitAt, BeginAcc) when is_integer(Byte) ->
-    split_iolist(Rest, SplitAt - 1, [Byte | BeginAcc]).

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_httpd.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_httpd.erl b/apps/couch/src/couch_httpd.erl
deleted file mode 100644
index 28932ba..0000000
--- a/apps/couch/src/couch_httpd.erl
+++ /dev/null
@@ -1,1114 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_httpd).
--include("couch_db.hrl").
-
--export([start_link/0, start_link/1, stop/0, config_change/2,
-        handle_request/5]).
-
--export([header_value/2,header_value/3,qs_value/2,qs_value/3,qs/1,qs_json_value/3]).
--export([path/1,absolute_uri/2,body_length/1]).
--export([verify_is_server_admin/1,unquote/1,quote/1,recv/2,recv_chunked/4,error_info/1]).
--export([make_fun_spec_strs/1]).
--export([make_arity_1_fun/1, make_arity_2_fun/1, make_arity_3_fun/1]).
--export([parse_form/1,json_body/1,json_body_obj/1,body/1]).
--export([doc_etag/1, make_etag/1, etag_match/2, etag_respond/3, etag_maybe/2]).
--export([primary_header_value/2,partition/1,serve_file/3,serve_file/4, server_header/0]).
--export([start_chunked_response/3,send_chunk/2,log_request/2]).
--export([start_response_length/4, start_response/3, send/2]).
--export([start_json_response/2, start_json_response/3, end_json_response/1]).
--export([send_response/4,send_method_not_allowed/2,send_error/4, send_redirect/2,send_chunked_error/2]).
--export([send_json/2,send_json/3,send_json/4,last_chunk/1,parse_multipart_request/3]).
--export([accepted_encodings/1,handle_request_int/5,validate_referer/1,validate_ctype/2]).
--export([http_1_0_keep_alive/2]).
-
-start_link() ->
-    start_link(http).
-start_link(http) ->
-    Port = couch_config:get("httpd", "port", "5984"),
-    start_link(?MODULE, [{port, Port}]);
-start_link(https) ->
-    Port = couch_config:get("ssl", "port", "6984"),
-    CertFile = couch_config:get("ssl", "cert_file", nil),
-    KeyFile = couch_config:get("ssl", "key_file", nil),
-    Options = case CertFile /= nil andalso KeyFile /= nil of
-        true ->
-            SslOpts = [{certfile, CertFile}, {keyfile, KeyFile}],
-
-            %% set password if one is needed for the cert
-            SslOpts1 = case couch_config:get("ssl", "password", nil) of
-                nil -> SslOpts;
-                Password ->
-                    SslOpts ++ [{password, Password}]
-            end,
-            % do we verify certificates ?
-            FinalSslOpts = case couch_config:get("ssl",
-                    "verify_ssl_certificates", "false") of
-                "false" -> SslOpts1;
-                "true" ->
-                    case couch_config:get("ssl",
-                            "cacert_file", nil) of
-                        nil ->
-                            io:format("Verify SSL certificate "
-                                ++"enabled but file containing "
-                                ++"PEM encoded CA certificates is "
-                                ++"missing", []),
-                            throw({error, missing_cacerts});
-                        CaCertFile ->
-                            Depth = list_to_integer(couch_config:get("ssl",
-                                    "ssl_certificate_max_depth",
-                                    "1")),
-                            FinalOpts = [
-                                {cacertfile, CaCertFile},
-                                {depth, Depth},
-                                {verify, verify_peer}],
-                            % allows custom verify fun.
-                            case couch_config:get("ssl",
-                                    "verify_fun", nil) of
-                                nil -> FinalOpts;
-                                SpecStr ->
-                                    FinalOpts
-                                    ++ [{verify_fun, make_arity_3_fun(SpecStr)}]
-                            end
-                    end
-            end,
-
-            [{port, Port},
-                {ssl, true},
-                {ssl_opts, FinalSslOpts}];
-        false ->
-            io:format("SSL enabled but PEM certificates are missing.", []),
-            throw({error, missing_certs})
-    end,
-    start_link(https, Options).
-start_link(Name, Options) ->
-    % read config and register for configuration changes
-
-    % just stop if one of the config settings change. couch_server_sup
-    % will restart us and then we will pick up the new settings.
-
-    BindAddress = couch_config:get("httpd", "bind_address", any),
-    validate_bind_address(BindAddress),
-    DefaultSpec = "{couch_httpd_db, handle_request}",
-    DefaultFun = make_arity_1_fun(
-        couch_config:get("httpd", "default_handler", DefaultSpec)
-    ),
-
-    UrlHandlersList = lists:map(
-        fun({UrlKey, SpecStr}) ->
-            {?l2b(UrlKey), make_arity_1_fun(SpecStr)}
-        end, couch_config:get("httpd_global_handlers")),
-
-    DbUrlHandlersList = lists:map(
-        fun({UrlKey, SpecStr}) ->
-            {?l2b(UrlKey), make_arity_2_fun(SpecStr)}
-        end, couch_config:get("httpd_db_handlers")),
-
-    DesignUrlHandlersList = lists:map(
-        fun({UrlKey, SpecStr}) ->
-            {?l2b(UrlKey), make_arity_3_fun(SpecStr)}
-        end, couch_config:get("httpd_design_handlers")),
-
-    UrlHandlers = dict:from_list(UrlHandlersList),
-    DbUrlHandlers = dict:from_list(DbUrlHandlersList),
-    DesignUrlHandlers = dict:from_list(DesignUrlHandlersList),
-    {ok, ServerOptions} = couch_util:parse_term(
-        couch_config:get("httpd", "server_options", "[]")),
-    {ok, SocketOptions} = couch_util:parse_term(
-        couch_config:get("httpd", "socket_options", "[]")),
-
-    set_auth_handlers(),
-
-    % ensure uuid is set so that concurrent replications
-    % get the same value.
-    couch_server:get_uuid(),
-
-    Loop = fun(Req)->
-        case SocketOptions of
-        [] ->
-            ok;
-        _ ->
-            ok = mochiweb_socket:setopts(Req:get(socket), SocketOptions)
-        end,
-        apply(?MODULE, handle_request, [
-            Req, DefaultFun, UrlHandlers, DbUrlHandlers, DesignUrlHandlers
-        ])
-    end,
-
-    % set mochiweb options
-    FinalOptions = lists:append([Options, ServerOptions, [
-            {loop, Loop},
-            {name, Name},
-            {ip, BindAddress}]]),
-
-    % launch mochiweb
-    {ok, Pid} = case mochiweb_http:start(FinalOptions) of
-        {ok, MochiPid} ->
-            {ok, MochiPid};
-        {error, Reason} ->
-            io:format("Failure to start Mochiweb: ~s~n",[Reason]),
-            throw({error, Reason})
-    end,
-
-    ok = couch_config:register(fun ?MODULE:config_change/2, Pid),
-    {ok, Pid}.
-
-
-stop() ->
-    mochiweb_http:stop(couch_httpd),
-    mochiweb_http:stop(https).
-
-config_change("httpd", "bind_address") ->
-    ?MODULE:stop();
-config_change("httpd", "port") ->
-    ?MODULE:stop();
-config_change("httpd", "default_handler") ->
-    ?MODULE:stop();
-config_change("httpd", "server_options") ->
-    ?MODULE:stop();
-config_change("httpd", "socket_options") ->
-    ?MODULE:stop();
-config_change("httpd", "authentication_handlers") ->
-    set_auth_handlers();
-config_change("httpd_global_handlers", _) ->
-    ?MODULE:stop();
-config_change("httpd_db_handlers", _) ->
-    ?MODULE:stop();
-config_change("ssl", _) ->
-    ?MODULE:stop().
-
-set_auth_handlers() ->
-    AuthenticationSrcs = make_fun_spec_strs(
-        couch_config:get("httpd", "authentication_handlers", "")),
-    AuthHandlers = lists:map(
-        fun(A) -> {make_arity_1_fun(A), ?l2b(A)} end, AuthenticationSrcs),
-    ok = application:set_env(couch, auth_handlers, AuthHandlers).
-
-% SpecStr is a string like "{my_module, my_fun}"
-%  or "{my_module, my_fun, <<"my_arg">>}"
-make_arity_1_fun(SpecStr) ->
-    case couch_util:parse_term(SpecStr) of
-    {ok, {Mod, Fun, SpecArg}} ->
-        fun(Arg) -> Mod:Fun(Arg, SpecArg) end;
-    {ok, {Mod, Fun}} ->
-        fun(Arg) -> Mod:Fun(Arg) end
-    end.
-
-make_arity_2_fun(SpecStr) ->
-    case couch_util:parse_term(SpecStr) of
-    {ok, {Mod, Fun, SpecArg}} ->
-        fun(Arg1, Arg2) -> Mod:Fun(Arg1, Arg2, SpecArg) end;
-    {ok, {Mod, Fun}} ->
-        fun(Arg1, Arg2) -> Mod:Fun(Arg1, Arg2) end
-    end.
-
-make_arity_3_fun(SpecStr) ->
-    case couch_util:parse_term(SpecStr) of
-    {ok, {Mod, Fun, SpecArg}} ->
-        fun(Arg1, Arg2, Arg3) -> Mod:Fun(Arg1, Arg2, Arg3, SpecArg) end;
-    {ok, {Mod, Fun}} ->
-        fun(Arg1, Arg2, Arg3) -> Mod:Fun(Arg1, Arg2, Arg3) end
-    end.
-
-% SpecStr is "{my_module, my_fun}, {my_module2, my_fun2}"
-make_fun_spec_strs(SpecStr) ->
-    re:split(SpecStr, "(?<=})\\s*,\\s*(?={)", [{return, list}]).
-
-handle_request(MochiReq, DefaultFun, UrlHandlers, DbUrlHandlers,
-    DesignUrlHandlers) ->
-    %% reset rewrite count for new request
-    erlang:put(?REWRITE_COUNT, 0),
-
-    MochiReq1 = couch_httpd_vhost:dispatch_host(MochiReq),
-
-    handle_request_int(MochiReq1, DefaultFun,
-                UrlHandlers, DbUrlHandlers, DesignUrlHandlers).
-
-handle_request_int(MochiReq, DefaultFun,
-            UrlHandlers, DbUrlHandlers, DesignUrlHandlers) ->
-    Begin = now(),
-    % for the path, use the raw path with the query string and fragment
-    % removed, but URL quoting left intact
-    RawUri = MochiReq:get(raw_path),
-    {"/" ++ Path, _, _} = mochiweb_util:urlsplit_path(RawUri),
-
-    Headers = MochiReq:get(headers),
-
-    % get requested path
-    RequestedPath = case MochiReq:get_header_value("x-couchdb-vhost-path") of
-        undefined ->
-            case MochiReq:get_header_value("x-couchdb-requested-path") of
-                undefined -> RawUri;
-                R -> R
-            end;
-        P -> P
-    end,
-
-    HandlerKey =
-    case mochiweb_util:partition(Path, "/") of
-    {"", "", ""} ->
-        <<"/">>; % Special case the root url handler
-    {FirstPart, _, _} ->
-        list_to_binary(FirstPart)
-    end,
-    ?LOG_DEBUG("~p ~s ~p from ~p~nHeaders: ~p", [
-        MochiReq:get(method),
-        RawUri,
-        MochiReq:get(version),
-        MochiReq:get(peer),
-        mochiweb_headers:to_list(MochiReq:get(headers))
-    ]),
-
-    Method1 =
-    case MochiReq:get(method) of
-        % already an atom
-        Meth when is_atom(Meth) -> Meth;
-
-        % Non standard HTTP verbs aren't atoms (COPY, MOVE etc) so convert when
-        % possible (if any module references the atom, then it's existing).
-        Meth -> couch_util:to_existing_atom(Meth)
-    end,
-    increment_method_stats(Method1),
-
-    % allow broken HTTP clients to fake a full method vocabulary with an X-HTTP-METHOD-OVERRIDE header
-    MethodOverride = MochiReq:get_primary_header_value("X-HTTP-Method-Override"),
-    Method2 = case lists:member(MethodOverride, ["GET", "HEAD", "POST",
-                                                 "PUT", "DELETE",
-                                                 "TRACE", "CONNECT",
-                                                 "COPY"]) of
-    true ->
-        ?LOG_INFO("MethodOverride: ~s (real method was ~s)", [MethodOverride, Method1]),
-        case Method1 of
-        'POST' -> couch_util:to_existing_atom(MethodOverride);
-        _ ->
-            % Ignore X-HTTP-Method-Override when the original verb isn't POST.
-            % I'd like to send a 406 error to the client, but that'd require a nasty refactor.
-            % throw({not_acceptable, <<"X-HTTP-Method-Override may only be used with POST requests.">>})
-            Method1
-        end;
-    _ -> Method1
-    end,
-
-    % alias HEAD to GET as mochiweb takes care of stripping the body
-    Method = case Method2 of
-        'HEAD' -> 'GET';
-        Other -> Other
-    end,
-
-    HttpReq = #httpd{
-        mochi_req = MochiReq,
-        peer = MochiReq:get(peer),
-        method = Method,
-        requested_path_parts =
-            [?l2b(unquote(Part)) || Part <- string:tokens(RequestedPath, "/")],
-        path_parts = [?l2b(unquote(Part)) || Part <- string:tokens(Path, "/")],
-        db_url_handlers = DbUrlHandlers,
-        design_url_handlers = DesignUrlHandlers,
-        default_fun = DefaultFun,
-        url_handlers = UrlHandlers,
-        user_ctx = erlang:erase(pre_rewrite_user_ctx),
-        auth = erlang:erase(pre_rewrite_auth)
-    },
-
-    HandlerFun = couch_util:dict_find(HandlerKey, UrlHandlers, DefaultFun),
-    {ok, AuthHandlers} = application:get_env(couch, auth_handlers),
-
-    {ok, Resp} =
-    try
-        case couch_httpd_cors:is_preflight_request(HttpReq) of
-        #httpd{} ->
-            case authenticate_request(HttpReq, AuthHandlers) of
-            #httpd{} = Req ->
-                HandlerFun(Req);
-            Response ->
-                Response
-            end;
-        Response ->
-            Response
-        end
-    catch
-        throw:{http_head_abort, Resp0} ->
-            {ok, Resp0};
-        throw:{invalid_json, S} ->
-            ?LOG_ERROR("attempted upload of invalid JSON (set log_level to debug to log it)", []),
-            ?LOG_DEBUG("Invalid JSON: ~p",[S]),
-            send_error(HttpReq, {bad_request, invalid_json});
-        throw:unacceptable_encoding ->
-            ?LOG_ERROR("unsupported encoding method for the response", []),
-            send_error(HttpReq, {not_acceptable, "unsupported encoding"});
-        throw:bad_accept_encoding_value ->
-            ?LOG_ERROR("received invalid Accept-Encoding header", []),
-            send_error(HttpReq, bad_request);
-        exit:normal ->
-            exit(normal);
-        exit:snappy_nif_not_loaded ->
-            ErrorReason = "To access the database or view index, Apache CouchDB"
-                " must be built with Erlang OTP R13B04 or higher.",
-            ?LOG_ERROR("~s", [ErrorReason]),
-            send_error(HttpReq, {bad_otp_release, ErrorReason});
-        exit:{body_too_large, _} ->
-            send_error(HttpReq, request_entity_too_large);
-        throw:Error ->
-            Stack = erlang:get_stacktrace(),
-            ?LOG_DEBUG("Minor error in HTTP request: ~p",[Error]),
-            ?LOG_DEBUG("Stacktrace: ~p",[Stack]),
-            send_error(HttpReq, Error);
-        error:badarg ->
-            Stack = erlang:get_stacktrace(),
-            ?LOG_ERROR("Badarg error in HTTP request",[]),
-            ?LOG_INFO("Stacktrace: ~p",[Stack]),
-            send_error(HttpReq, badarg);
-        error:function_clause ->
-            Stack = erlang:get_stacktrace(),
-            ?LOG_ERROR("function_clause error in HTTP request",[]),
-            ?LOG_INFO("Stacktrace: ~p",[Stack]),
-            send_error(HttpReq, function_clause);
-        Tag:Error ->
-            Stack = erlang:get_stacktrace(),
-            ?LOG_ERROR("Uncaught error in HTTP request: ~p",[{Tag, Error}]),
-            ?LOG_INFO("Stacktrace: ~p",[Stack]),
-            send_error(HttpReq, Error)
-    end,
-    RequestTime = round(timer:now_diff(now(), Begin)/1000),
-    couch_stats_collector:record({couchdb, request_time}, RequestTime),
-    couch_stats_collector:increment({httpd, requests}),
-    {ok, Resp}.
-
-% Try authentication handlers in order until one sets a user_ctx
-% the auth funs also have the option of returning a response
-% move this to couch_httpd_auth?
-authenticate_request(#httpd{user_ctx=#user_ctx{}} = Req, _AuthHandlers) ->
-    Req;
-authenticate_request(#httpd{} = Req, []) ->
-    case couch_config:get("couch_httpd_auth", "require_valid_user", "false") of
-    "true" ->
-        throw({unauthorized, <<"Authentication required.">>});
-    "false" ->
-        Req#httpd{user_ctx=#user_ctx{}}
-    end;
-authenticate_request(#httpd{} = Req, [{AuthFun, AuthSrc} | RestAuthHandlers]) ->
-    R = case AuthFun(Req) of
-        #httpd{user_ctx=#user_ctx{}=UserCtx}=Req2 ->
-            Req2#httpd{user_ctx=UserCtx#user_ctx{handler=AuthSrc}};
-        Else -> Else
-    end,
-    authenticate_request(R, RestAuthHandlers);
-authenticate_request(Response, _AuthSrcs) ->
-    Response.
-
-increment_method_stats(Method) ->
-    couch_stats_collector:increment({httpd_request_methods, Method}).
-
-validate_referer(Req) ->
-    Host = host_for_request(Req),
-    Referer = header_value(Req, "Referer", fail),
-    case Referer of
-    fail ->
-        throw({bad_request, <<"Referer header required.">>});
-    Referer ->
-        {_,RefererHost,_,_,_} = mochiweb_util:urlsplit(Referer),
-        if
-            RefererHost =:= Host -> ok;
-            true -> throw({bad_request, <<"Referer header must match host.">>})
-        end
-    end.
-
-validate_ctype(Req, Ctype) ->
-    case header_value(Req, "Content-Type") of
-    undefined ->
-        throw({bad_ctype, "Content-Type must be "++Ctype});
-    ReqCtype ->
-        case string:tokens(ReqCtype, ";") of
-        [Ctype] -> ok;
-        [Ctype, _Rest] -> ok;
-        _Else ->
-            throw({bad_ctype, "Content-Type must be "++Ctype})
-        end
-    end.
-
-% Utilities
-
-partition(Path) ->
-    mochiweb_util:partition(Path, "/").
-
-header_value(#httpd{mochi_req=MochiReq}, Key) ->
-    MochiReq:get_header_value(Key).
-
-header_value(#httpd{mochi_req=MochiReq}, Key, Default) ->
-    case MochiReq:get_header_value(Key) of
-    undefined -> Default;
-    Value -> Value
-    end.
-
-primary_header_value(#httpd{mochi_req=MochiReq}, Key) ->
-    MochiReq:get_primary_header_value(Key).
-
-accepted_encodings(#httpd{mochi_req=MochiReq}) ->
-    case MochiReq:accepted_encodings(["gzip", "identity"]) of
-    bad_accept_encoding_value ->
-        throw(bad_accept_encoding_value);
-    [] ->
-        throw(unacceptable_encoding);
-    EncList ->
-        EncList
-    end.
-
-serve_file(Req, RelativePath, DocumentRoot) ->
-    serve_file(Req, RelativePath, DocumentRoot, []).
-
-serve_file(#httpd{mochi_req=MochiReq}=Req, RelativePath, DocumentRoot,
-           ExtraHeaders) ->
-    log_request(Req, 200),
-    ResponseHeaders = server_header()
-        ++ couch_httpd_auth:cookie_auth_header(Req, [])
-        ++ ExtraHeaders,
-    {ok, MochiReq:serve_file(RelativePath, DocumentRoot,
-            couch_httpd_cors:cors_headers(Req, ResponseHeaders))}.
-
-qs_value(Req, Key) ->
-    qs_value(Req, Key, undefined).
-
-qs_value(Req, Key, Default) ->
-    couch_util:get_value(Key, qs(Req), Default).
-
-qs_json_value(Req, Key, Default) ->
-    case qs_value(Req, Key, Default) of
-    Default ->
-        Default;
-    Result ->
-        ?JSON_DECODE(Result)
-    end.
-
-qs(#httpd{mochi_req=MochiReq}) ->
-    MochiReq:parse_qs().
-
-path(#httpd{mochi_req=MochiReq}) ->
-    MochiReq:get(path).
-
-host_for_request(#httpd{mochi_req=MochiReq}) ->
-    XHost = couch_config:get("httpd", "x_forwarded_host", "X-Forwarded-Host"),
-    case MochiReq:get_header_value(XHost) of
-        undefined ->
-            case MochiReq:get_header_value("Host") of
-                undefined ->
-                    {ok, {Address, Port}} = case MochiReq:get(socket) of
-                        {ssl, SslSocket} -> ssl:sockname(SslSocket);
-                        Socket -> inet:sockname(Socket)
-                    end,
-                    inet_parse:ntoa(Address) ++ ":" ++ integer_to_list(Port);
-                Value1 ->
-                    Value1
-            end;
-        Value -> Value
-    end.
-
-absolute_uri(#httpd{mochi_req=MochiReq}=Req, Path) ->
-    Host = host_for_request(Req),
-    XSsl = couch_config:get("httpd", "x_forwarded_ssl", "X-Forwarded-Ssl"),
-    Scheme = case MochiReq:get_header_value(XSsl) of
-                 "on" -> "https";
-                 _ ->
-                     XProto = couch_config:get("httpd", "x_forwarded_proto", "X-Forwarded-Proto"),
-                     case MochiReq:get_header_value(XProto) of
-                         %% Restrict to "https" and "http" schemes only
-                         "https" -> "https";
-                         _ -> case MochiReq:get(scheme) of
-                                  https -> "https";
-                                  http -> "http"
-                              end
-                     end
-             end,
-    Scheme ++ "://" ++ Host ++ Path.
-
-unquote(UrlEncodedString) ->
-    mochiweb_util:unquote(UrlEncodedString).
-
-quote(UrlDecodedString) ->
-    mochiweb_util:quote_plus(UrlDecodedString).
-
-parse_form(#httpd{mochi_req=MochiReq}) ->
-    mochiweb_multipart:parse_form(MochiReq).
-
-recv(#httpd{mochi_req=MochiReq}, Len) ->
-    MochiReq:recv(Len).
-
-recv_chunked(#httpd{mochi_req=MochiReq}, MaxChunkSize, ChunkFun, InitState) ->
-    % Fun is called once with each chunk
-    % Fun({Length, Binary}, State)
-    % called with Length == 0 on the last time.
-    MochiReq:stream_body(MaxChunkSize, ChunkFun, InitState).
-
-body_length(#httpd{mochi_req=MochiReq}) ->
-    MochiReq:get(body_length).
-
-body(#httpd{mochi_req=MochiReq, req_body=undefined}) ->
-    MaxSize = list_to_integer(
-        couch_config:get("couchdb", "max_document_size", "4294967296")),
-    MochiReq:recv_body(MaxSize);
-body(#httpd{req_body=ReqBody}) ->
-    ReqBody.
-
-json_body(Httpd) ->
-    ?JSON_DECODE(body(Httpd)).
-
-json_body_obj(Httpd) ->
-    case json_body(Httpd) of
-        {Props} -> {Props};
-        _Else ->
-            throw({bad_request, "Request body must be a JSON object"})
-    end.
-
-
-
-doc_etag(#doc{revs={Start, [DiskRev|_]}}) ->
-    "\"" ++ ?b2l(couch_doc:rev_to_str({Start, DiskRev})) ++ "\"".
-
-make_etag(Term) ->
-    <<SigInt:128/integer>> = couch_util:md5(term_to_binary(Term)),
-    iolist_to_binary([$", io_lib:format("~.36B", [SigInt]), $"]).
-
-etag_match(Req, CurrentEtag) when is_binary(CurrentEtag) ->
-    etag_match(Req, binary_to_list(CurrentEtag));
-
-etag_match(Req, CurrentEtag) ->
-    EtagsToMatch = string:tokens(
-        header_value(Req, "If-None-Match", ""), ", "),
-    lists:member(CurrentEtag, EtagsToMatch).
-
-etag_respond(Req, CurrentEtag, RespFun) ->
-    case etag_match(Req, CurrentEtag) of
-    true ->
-        % the client has this in their cache.
-        send_response(Req, 304, [{"ETag", CurrentEtag}], <<>>);
-    false ->
-        % Run the function.
-        RespFun()
-    end.
-
-etag_maybe(Req, RespFun) ->
-    try
-        RespFun()
-    catch
-        throw:{etag_match, ETag} ->
-            send_response(Req, 304, [{"ETag", ETag}], <<>>)
-    end.
-
-verify_is_server_admin(#httpd{user_ctx=UserCtx}) ->
-    verify_is_server_admin(UserCtx);
-verify_is_server_admin(#user_ctx{roles=Roles}) ->
-    case lists:member(<<"_admin">>, Roles) of
-    true -> ok;
-    false -> throw({unauthorized, <<"You are not a server admin.">>})
-    end.
-
-log_request(#httpd{mochi_req=MochiReq,peer=Peer}=Req, Code) ->
-    ?LOG_INFO("~s - - ~s ~s ~B", [
-        Peer,
-        MochiReq:get(method),
-        MochiReq:get(raw_path),
-        Code
-    ]),
-    gen_event:notify(couch_plugin, {log_request, Req, Code}).
-
-
-start_response_length(#httpd{mochi_req=MochiReq}=Req, Code, Headers, Length) ->
-    log_request(Req, Code),
-    couch_stats_collector:increment({httpd_status_codes, Code}),
-    Headers1 = Headers ++ server_header() ++
-               couch_httpd_auth:cookie_auth_header(Req, Headers),
-    Headers2 = couch_httpd_cors:cors_headers(Req, Headers1),
-    Resp = MochiReq:start_response_length({Code, Headers2, Length}),
-    case MochiReq:get(method) of
-    'HEAD' -> throw({http_head_abort, Resp});
-    _ -> ok
-    end,
-    {ok, Resp}.
-
-start_response(#httpd{mochi_req=MochiReq}=Req, Code, Headers) ->
-    log_request(Req, Code),
-    couch_stats_collector:increment({httpd_status_codes, Code}),
-    CookieHeader = couch_httpd_auth:cookie_auth_header(Req, Headers),
-    Headers1 = Headers ++ server_header() ++ CookieHeader,
-    Headers2 = couch_httpd_cors:cors_headers(Req, Headers1),
-    Resp = MochiReq:start_response({Code, Headers2}),
-    case MochiReq:get(method) of
-        'HEAD' -> throw({http_head_abort, Resp});
-        _ -> ok
-    end,
-    {ok, Resp}.
-
-send(Resp, Data) ->
-    Resp:send(Data),
-    {ok, Resp}.
-
-no_resp_conn_header([]) ->
-    true;
-no_resp_conn_header([{Hdr, _}|Rest]) ->
-    case string:to_lower(Hdr) of
-        "connection" -> false;
-        _ -> no_resp_conn_header(Rest)
-    end.
-
-http_1_0_keep_alive(Req, Headers) ->
-    KeepOpen = Req:should_close() == false,
-    IsHttp10 = Req:get(version) == {1, 0},
-    NoRespHeader = no_resp_conn_header(Headers),
-    case KeepOpen andalso IsHttp10 andalso NoRespHeader of
-        true -> [{"Connection", "Keep-Alive"} | Headers];
-        false -> Headers
-    end.
-
-start_chunked_response(#httpd{mochi_req=MochiReq}=Req, Code, Headers) ->
-    log_request(Req, Code),
-    couch_stats_collector:increment({httpd_status_codes, Code}),
-    Headers1 = http_1_0_keep_alive(MochiReq, Headers),
-    Headers2 = Headers1 ++ server_header() ++
-               couch_httpd_auth:cookie_auth_header(Req, Headers1),
-    Headers3 = couch_httpd_cors:cors_headers(Req, Headers2),
-    Resp = MochiReq:respond({Code, Headers3, chunked}),
-    case MochiReq:get(method) of
-    'HEAD' -> throw({http_head_abort, Resp});
-    _ -> ok
-    end,
-    {ok, Resp}.
-
-send_chunk(Resp, Data) ->
-    case iolist_size(Data) of
-    0 -> ok; % do nothing
-    _ -> Resp:write_chunk(Data)
-    end,
-    {ok, Resp}.
-
-last_chunk(Resp) ->
-    Resp:write_chunk([]),
-    {ok, Resp}.
-
-send_response(#httpd{mochi_req=MochiReq}=Req, Code, Headers, Body) ->
-    log_request(Req, Code),
-    couch_stats_collector:increment({httpd_status_codes, Code}),
-    Headers1 = http_1_0_keep_alive(MochiReq, Headers),
-    if Code >= 500 ->
-        ?LOG_ERROR("httpd ~p error response:~n ~s", [Code, Body]);
-    Code >= 400 ->
-        ?LOG_DEBUG("httpd ~p error response:~n ~s", [Code, Body]);
-    true -> ok
-    end,
-    Headers2 = Headers1 ++ server_header() ++
-               couch_httpd_auth:cookie_auth_header(Req, Headers1),
-    Headers3 = couch_httpd_cors:cors_headers(Req, Headers2),
-
-    {ok, MochiReq:respond({Code, Headers3, Body})}.
-
-send_method_not_allowed(Req, Methods) ->
-    send_error(Req, 405, [{"Allow", Methods}], <<"method_not_allowed">>, ?l2b("Only " ++ Methods ++ " allowed")).
-
-send_json(Req, Value) ->
-    send_json(Req, 200, Value).
-
-send_json(Req, Code, Value) ->
-    send_json(Req, Code, [], Value).
-
-send_json(Req, Code, Headers, Value) ->
-    initialize_jsonp(Req),
-    DefaultHeaders = [
-        {"Content-Type", negotiate_content_type(Req)},
-        {"Cache-Control", "must-revalidate"}
-    ],
-    Body = [start_jsonp(), ?JSON_ENCODE(Value), end_jsonp(), $\n],
-    send_response(Req, Code, DefaultHeaders ++ Headers, Body).
-
-start_json_response(Req, Code) ->
-    start_json_response(Req, Code, []).
-
-start_json_response(Req, Code, Headers) ->
-    initialize_jsonp(Req),
-    DefaultHeaders = [
-        {"Content-Type", negotiate_content_type(Req)},
-        {"Cache-Control", "must-revalidate"}
-    ],
-    {ok, Resp} = start_chunked_response(Req, Code, DefaultHeaders ++ Headers),
-    case start_jsonp() of
-        [] -> ok;
-        Start -> send_chunk(Resp, Start)
-    end,
-    {ok, Resp}.
-
-end_json_response(Resp) ->
-    send_chunk(Resp, end_jsonp() ++ [$\n]),
-    last_chunk(Resp).
-
-initialize_jsonp(Req) ->
-    case get(jsonp) of
-        undefined -> put(jsonp, qs_value(Req, "callback", no_jsonp));
-        _ -> ok
-    end,
-    case get(jsonp) of
-        no_jsonp -> [];
-        [] -> [];
-        CallBack ->
-            try
-                % make sure jsonp is configured on (default off)
-                case couch_config:get("httpd", "allow_jsonp", "false") of
-                "true" ->
-                    validate_callback(CallBack);
-                _Else ->
-                    put(jsonp, no_jsonp)
-                end
-            catch
-                Error ->
-                    put(jsonp, no_jsonp),
-                    throw(Error)
-            end
-    end.
-
-start_jsonp() ->
-    case get(jsonp) of
-        no_jsonp -> [];
-        [] -> [];
-        CallBack -> ["/* CouchDB */", CallBack, "("]
-    end.
-
-end_jsonp() ->
-    case erlang:erase(jsonp) of
-        no_jsonp -> [];
-        [] -> [];
-        _ -> ");"
-    end.
-
-validate_callback(CallBack) when is_binary(CallBack) ->
-    validate_callback(binary_to_list(CallBack));
-validate_callback([]) ->
-    ok;
-validate_callback([Char | Rest]) ->
-    case Char of
-        _ when Char >= $a andalso Char =< $z -> ok;
-        _ when Char >= $A andalso Char =< $Z -> ok;
-        _ when Char >= $0 andalso Char =< $9 -> ok;
-        _ when Char == $. -> ok;
-        _ when Char == $_ -> ok;
-        _ when Char == $[ -> ok;
-        _ when Char == $] -> ok;
-        _ ->
-            throw({bad_request, invalid_callback})
-    end,
-    validate_callback(Rest).
-
-
-error_info({Error, Reason}) when is_list(Reason) ->
-    error_info({Error, ?l2b(Reason)});
-error_info(bad_request) ->
-    {400, <<"bad_request">>, <<>>};
-error_info({bad_request, Reason}) ->
-    {400, <<"bad_request">>, Reason};
-error_info({query_parse_error, Reason}) ->
-    {400, <<"query_parse_error">>, Reason};
-% Prior art for md5 mismatch resulting in a 400 is from AWS S3
-error_info(md5_mismatch) ->
-    {400, <<"content_md5_mismatch">>, <<"Possible message corruption.">>};
-error_info(not_found) ->
-    {404, <<"not_found">>, <<"missing">>};
-error_info({not_found, Reason}) ->
-    {404, <<"not_found">>, Reason};
-error_info({not_acceptable, Reason}) ->
-    {406, <<"not_acceptable">>, Reason};
-error_info(conflict) ->
-    {409, <<"conflict">>, <<"Document update conflict.">>};
-error_info({forbidden, Msg}) ->
-    {403, <<"forbidden">>, Msg};
-error_info({unauthorized, Msg}) ->
-    {401, <<"unauthorized">>, Msg};
-error_info(file_exists) ->
-    {412, <<"file_exists">>, <<"The database could not be "
-        "created, the file already exists.">>};
-error_info(request_entity_too_large) ->
-    {413, <<"too_large">>, <<"the request entity is too large">>};
-error_info({bad_ctype, Reason}) ->
-    {415, <<"bad_content_type">>, Reason};
-error_info(requested_range_not_satisfiable) ->
-    {416, <<"requested_range_not_satisfiable">>, <<"Requested range not satisfiable">>};
-error_info({error, illegal_database_name, Name}) ->
-    Message = "Name: '" ++ Name ++ "'. Only lowercase characters (a-z), "
-        ++ "digits (0-9), and any of the characters _, $, (, ), +, -, and / "
-        ++ "are allowed. Must begin with a letter.",
-    {400, <<"illegal_database_name">>, couch_util:to_binary(Message)};
-error_info({missing_stub, Reason}) ->
-    {412, <<"missing_stub">>, Reason};
-error_info({Error, Reason}) ->
-    {500, couch_util:to_binary(Error), couch_util:to_binary(Reason)};
-error_info(Error) ->
-    {500, <<"unknown_error">>, couch_util:to_binary(Error)}.
-
-error_headers(#httpd{mochi_req=MochiReq}=Req, Code, ErrorStr, ReasonStr) ->
-    if Code == 401 ->
-        % this is where the basic auth popup is triggered
-        case MochiReq:get_header_value("X-CouchDB-WWW-Authenticate") of
-        undefined ->
-            case couch_config:get("httpd", "WWW-Authenticate", nil) of
-            nil ->
-                % If the client is a browser and the basic auth popup isn't turned on
-                % redirect to the session page.
-                case ErrorStr of
-                <<"unauthorized">> ->
-                    case couch_config:get("couch_httpd_auth", "authentication_redirect", nil) of
-                    nil -> {Code, []};
-                    AuthRedirect ->
-                        case couch_config:get("couch_httpd_auth", "require_valid_user", "false") of
-                        "true" ->
-                            % send the browser popup header no matter what if we are require_valid_user
-                            {Code, [{"WWW-Authenticate", "Basic realm=\"server\""}]};
-                        _False ->
-                            case MochiReq:accepts_content_type("application/json") of
-                            true ->
-                                {Code, []};
-                            false ->
-                                case MochiReq:accepts_content_type("text/html") of
-                                true ->
-                                    % Redirect to the path the user requested, not
-                                    % the one that is used internally.
-                                    UrlReturnRaw = case MochiReq:get_header_value("x-couchdb-vhost-path") of
-                                    undefined ->
-                                        MochiReq:get(path);
-                                    VHostPath ->
-                                        VHostPath
-                                    end,
-                                    RedirectLocation = lists:flatten([
-                                        AuthRedirect,
-                                        "?return=", couch_util:url_encode(UrlReturnRaw),
-                                        "&reason=", couch_util:url_encode(ReasonStr)
-                                    ]),
-                                    {302, [{"Location", absolute_uri(Req, RedirectLocation)}]};
-                                false ->
-                                    {Code, []}
-                                end
-                            end
-                        end
-                    end;
-                _Else ->
-                    {Code, []}
-                end;
-            Type ->
-                {Code, [{"WWW-Authenticate", Type}]}
-            end;
-        Type ->
-           {Code, [{"WWW-Authenticate", Type}]}
-        end;
-    true ->
-        {Code, []}
-    end.
-
-send_error(_Req, {already_sent, Resp, _Error}) ->
-    {ok, Resp};
-
-send_error(Req, Error) ->
-    {Code, ErrorStr, ReasonStr} = error_info(Error),
-    {Code1, Headers} = error_headers(Req, Code, ErrorStr, ReasonStr),
-    send_error(Req, Code1, Headers, ErrorStr, ReasonStr).
-
-send_error(Req, Code, ErrorStr, ReasonStr) ->
-    send_error(Req, Code, [], ErrorStr, ReasonStr).
-
-send_error(Req, Code, Headers, ErrorStr, ReasonStr) ->
-    send_json(Req, Code, Headers,
-        {[{<<"error">>,  ErrorStr},
-         {<<"reason">>, ReasonStr}]}).
-
-% give the option for list functions to output html or other raw errors
-send_chunked_error(Resp, {_Error, {[{<<"body">>, Reason}]}}) ->
-    send_chunk(Resp, Reason),
-    last_chunk(Resp);
-
-send_chunked_error(Resp, Error) ->
-    {Code, ErrorStr, ReasonStr} = error_info(Error),
-    JsonError = {[{<<"code">>, Code},
-        {<<"error">>,  ErrorStr},
-        {<<"reason">>, ReasonStr}]},
-    send_chunk(Resp, ?l2b([$\n,?JSON_ENCODE(JsonError),$\n])),
-    last_chunk(Resp).
-
-send_redirect(Req, Path) ->
-     send_response(Req, 301, [{"Location", absolute_uri(Req, Path)}], <<>>).
-
-negotiate_content_type(Req) ->
-    case get(jsonp) of
-        no_jsonp -> negotiate_content_type1(Req);
-        [] -> negotiate_content_type1(Req);
-        _Callback -> "text/javascript"
-    end.
-
-negotiate_content_type1(#httpd{mochi_req=MochiReq}) ->
-    %% Determine the appropriate Content-Type header for a JSON response
-    %% depending on the Accept header in the request. A request that explicitly
-    %% lists the correct JSON MIME type will get that type, otherwise the
-    %% response will have the generic MIME type "text/plain"
-    AcceptedTypes = case MochiReq:get_header_value("Accept") of
-        undefined       -> [];
-        AcceptHeader    -> string:tokens(AcceptHeader, ", ")
-    end,
-    case lists:member("application/json", AcceptedTypes) of
-        true  -> "application/json";
-        false -> "text/plain; charset=utf-8"
-    end.
-
-server_header() ->
-    [{"Server", "CouchDB/" ++ couch_server:get_version() ++
-                " (Erlang OTP/" ++ erlang:system_info(otp_release) ++ ")"}].
-
-
--record(mp, {boundary, buffer, data_fun, callback}).
-
-
-parse_multipart_request(ContentType, DataFun, Callback) ->
-    Boundary0 = iolist_to_binary(get_boundary(ContentType)),
-    Boundary = <<"\r\n--", Boundary0/binary>>,
-    Mp = #mp{boundary= Boundary,
-            buffer= <<>>,
-            data_fun=DataFun,
-            callback=Callback},
-    {Mp2, _NilCallback} = read_until(Mp, <<"--", Boundary0/binary>>,
-        fun nil_callback/1),
-    #mp{buffer=Buffer, data_fun=DataFun2, callback=Callback2} =
-            parse_part_header(Mp2),
-    {Buffer, DataFun2, Callback2}.
-
-nil_callback(_Data)->
-    fun nil_callback/1.
-
-get_boundary({"multipart/" ++ _, Opts}) ->
-    case couch_util:get_value("boundary", Opts) of
-        S when is_list(S) ->
-            S
-    end;
-get_boundary(ContentType) ->
-    {"multipart/" ++ _ , Opts} = mochiweb_util:parse_header(ContentType),
-    get_boundary({"multipart/", Opts}).
-
-
-
-split_header(<<>>) ->
-    [];
-split_header(Line) ->
-    {Name, [$: | Value]} = lists:splitwith(fun (C) -> C =/= $: end,
-                                           binary_to_list(Line)),
-    [{string:to_lower(string:strip(Name)),
-     mochiweb_util:parse_header(Value)}].
-
-read_until(#mp{data_fun=DataFun, buffer=Buffer}=Mp, Pattern, Callback) ->
-    case find_in_binary(Pattern, Buffer) of
-    not_found ->
-        Callback2 = Callback(Buffer),
-        {Buffer2, DataFun2} = DataFun(),
-        Buffer3 = iolist_to_binary(Buffer2),
-        read_until(Mp#mp{data_fun=DataFun2,buffer=Buffer3}, Pattern, Callback2);
-    {partial, 0} ->
-        {NewData, DataFun2} = DataFun(),
-        read_until(Mp#mp{data_fun=DataFun2,
-                buffer= iolist_to_binary([Buffer,NewData])},
-                Pattern, Callback);
-    {partial, Skip} ->
-        <<DataChunk:Skip/binary, Rest/binary>> = Buffer,
-        Callback2 = Callback(DataChunk),
-        {NewData, DataFun2} = DataFun(),
-        read_until(Mp#mp{data_fun=DataFun2,
-                buffer= iolist_to_binary([Rest | NewData])},
-                Pattern, Callback2);
-    {exact, 0} ->
-        PatternLen = size(Pattern),
-        <<_:PatternLen/binary, Rest/binary>> = Buffer,
-        {Mp#mp{buffer= Rest}, Callback};
-    {exact, Skip} ->
-        PatternLen = size(Pattern),
-        <<DataChunk:Skip/binary, _:PatternLen/binary, Rest/binary>> = Buffer,
-        Callback2 = Callback(DataChunk),
-        {Mp#mp{buffer= Rest}, Callback2}
-    end.
-
-
-parse_part_header(#mp{callback=UserCallBack}=Mp) ->
-    {Mp2, AccCallback} = read_until(Mp, <<"\r\n\r\n">>,
-            fun(Next) -> acc_callback(Next, []) end),
-    HeaderData = AccCallback(get_data),
-
-    Headers =
-    lists:foldl(fun(Line, Acc) ->
-            split_header(Line) ++ Acc
-        end, [], re:split(HeaderData,<<"\r\n">>, [])),
-    NextCallback = UserCallBack({headers, Headers}),
-    parse_part_body(Mp2#mp{callback=NextCallback}).
-
-parse_part_body(#mp{boundary=Prefix, callback=Callback}=Mp) ->
-    {Mp2, WrappedCallback} = read_until(Mp, Prefix,
-            fun(Data) -> body_callback_wrapper(Data, Callback) end),
-    Callback2 = WrappedCallback(get_callback),
-    Callback3 = Callback2(body_end),
-    case check_for_last(Mp2#mp{callback=Callback3}) of
-    {last, #mp{callback=Callback3}=Mp3} ->
-        Mp3#mp{callback=Callback3(eof)};
-    {more, Mp3} ->
-        parse_part_header(Mp3)
-    end.
-
-acc_callback(get_data, Acc)->
-    iolist_to_binary(lists:reverse(Acc));
-acc_callback(Data, Acc)->
-    fun(Next) -> acc_callback(Next, [Data | Acc]) end.
-
-body_callback_wrapper(get_callback, Callback) ->
-    Callback;
-body_callback_wrapper(Data, Callback) ->
-    Callback2 = Callback({body, Data}),
-    fun(Next) -> body_callback_wrapper(Next, Callback2) end.
-
-
-check_for_last(#mp{buffer=Buffer, data_fun=DataFun}=Mp) ->
-    case Buffer of
-    <<"--",_/binary>> -> {last, Mp};
-    <<_, _, _/binary>> -> {more, Mp};
-    _ -> % not long enough
-        {Data, DataFun2} = DataFun(),
-        check_for_last(Mp#mp{buffer= <<Buffer/binary, Data/binary>>,
-                data_fun = DataFun2})
-    end.
-
-find_in_binary(_B, <<>>) ->
-    not_found;
-
-find_in_binary(B, Data) ->
-    case binary:match(Data, [B], []) of
-    nomatch ->
-        partial_find(binary:part(B, {0, byte_size(B) - 1}),
-                     binary:part(Data, {byte_size(Data), -byte_size(Data) + 1}), 1);
-    {Pos, _Len} ->
-        {exact, Pos}
-    end.
-
-partial_find(<<>>, _Data, _Pos) ->
-    not_found;
-
-partial_find(B, Data, N) when byte_size(Data) > 0 ->
-    case binary:match(Data, [B], []) of
-    nomatch ->
-        partial_find(binary:part(B, {0, byte_size(B) - 1}),
-                     binary:part(Data, {byte_size(Data), -byte_size(Data) + 1}), N + 1);
-    {Pos, _Len} ->
-        {partial, N + Pos}
-    end;
-
-partial_find(_B, _Data, _N) ->
-    not_found.
-
-
-validate_bind_address(Address) ->
-    case inet_parse:address(Address) of
-        {ok, _} -> ok;
-        _ -> throw({error, invalid_bind_address})
-    end.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_httpd_auth.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_httpd_auth.erl b/apps/couch/src/couch_httpd_auth.erl
deleted file mode 100644
index b8c4e26..0000000
--- a/apps/couch/src/couch_httpd_auth.erl
+++ /dev/null
@@ -1,380 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License.  You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_httpd_auth).
--include("couch_db.hrl").
-
--export([default_authentication_handler/1,special_test_authentication_handler/1]).
--export([cookie_authentication_handler/1]).
--export([null_authentication_handler/1]).
--export([proxy_authentication_handler/1, proxy_authentification_handler/1]).
--export([cookie_auth_header/2]).
--export([handle_session_req/1]).
-
--import(couch_httpd, [header_value/2, send_json/2,send_json/4, send_method_not_allowed/2]).
-
-special_test_authentication_handler(Req) ->
-    case header_value(Req, "WWW-Authenticate") of
-    "X-Couch-Test-Auth " ++ NamePass ->
-        % NamePass is a colon separated string: "joe schmoe:a password".
-        [Name, Pass] = re:split(NamePass, ":", [{return, list}, {parts, 2}]),
-        case {Name, Pass} of
-        {"Jan Lehnardt", "apple"} -> ok;
-        {"Christopher Lenz", "dog food"} -> ok;
-        {"Noah Slater", "biggiesmalls endian"} -> ok;
-        {"Chris Anderson", "mp3"} -> ok;
-        {"Damien Katz", "pecan pie"} -> ok;
-        {_, _} ->
-            throw({unauthorized, <<"Name or password is incorrect.">>})
-        end,
-        Req#httpd{user_ctx=#user_ctx{name=?l2b(Name)}};
-    _ ->
-        % No X-Couch-Test-Auth credentials sent, give admin access so the
-        % previous authentication can be restored after the test
-        Req#httpd{user_ctx=#user_ctx{roles=[<<"_admin">>]}}
-    end.
-
-basic_name_pw(Req) ->
-    AuthorizationHeader = header_value(Req, "Authorization"),
-    case AuthorizationHeader of
-    "Basic " ++ Base64Value ->
-        case re:split(base64:decode(Base64Value), ":",
-                      [{return, list}, {parts, 2}]) of
-        ["_", "_"] ->
-            % special name and pass to be logged out
-            nil;
-        [User, Pass] ->
-            {User, Pass};
-        _ ->
-            nil
-        end;
-    _ ->
-        nil
-    end.
-
-default_authentication_handler(Req) ->
-    case basic_name_pw(Req) of
-    {User, Pass} ->
-        case couch_auth_cache:get_user_creds(User) of
-            nil ->
-                throw({unauthorized, <<"Name or password is incorrect.">>});
-            UserProps ->
-                case authenticate(?l2b(Pass), UserProps) of
-                    true ->
-                        Req#httpd{user_ctx=#user_ctx{
-                            name=?l2b(User),
-                            roles=couch_util:get_value(<<"roles">>, UserProps, [])
-                        }};
-                    _Else ->
-                        throw({unauthorized, <<"Name or password is incorrect.">>})
-                end
-        end;
-    nil ->
-        case couch_server:has_admins() of
-        true ->
-            Req;
-        false ->
-            case couch_config:get("couch_httpd_auth", "require_valid_user", "false") of
-                "true" -> Req;
-                % If no admins, and no user required, then everyone is admin!
-                % Yay, admin party!
-                _ -> Req#httpd{user_ctx=#user_ctx{roles=[<<"_admin">>]}}
-            end
-        end
-    end.
-
-null_authentication_handler(Req) ->
-    Req#httpd{user_ctx=#user_ctx{roles=[<<"_admin">>]}}.
-
-%% @doc proxy auth handler.
-%
-% This handler allows creation of a userCtx object from a user authenticated remotly.
-% The client just pass specific headers to CouchDB and the handler create the userCtx.
-% Headers  name can be defined in local.ini. By thefault they are :
-%
-%   * X-Auth-CouchDB-UserName : contain the username, (x_auth_username in
-%   couch_httpd_auth section)
-%   * X-Auth-CouchDB-Roles : contain the user roles, list of roles separated by a
-%   comma (x_auth_roles in couch_httpd_auth section)
-%   * X-Auth-CouchDB-Token : token to authenticate the authorization (x_auth_token
-%   in couch_httpd_auth section). This token is an hmac-sha1 created from secret key
-%   and username. The secret key should be the same in the client and couchdb node. s
-%   ecret key is the secret key in couch_httpd_auth section of ini. This token is optional
-%   if value of proxy_use_secret key in couch_httpd_auth section of ini isn't true.
-%
-proxy_authentication_handler(Req) ->
-    case proxy_auth_user(Req) of
-        nil -> Req;
-        Req2 -> Req2
-    end.
-
-%% @deprecated
-proxy_authentification_handler(Req) ->
-    proxy_authentication_handler(Req).
-    
-proxy_auth_user(Req) ->
-    XHeaderUserName = couch_config:get("couch_httpd_auth", "x_auth_username",
-                                "X-Auth-CouchDB-UserName"),
-    XHeaderRoles = couch_config:get("couch_httpd_auth", "x_auth_roles",
-                                "X-Auth-CouchDB-Roles"),
-    XHeaderToken = couch_config:get("couch_httpd_auth", "x_auth_token",
-                                "X-Auth-CouchDB-Token"),
-    case header_value(Req, XHeaderUserName) of
-        undefined -> nil;
-        UserName ->
-            Roles = case header_value(Req, XHeaderRoles) of
-                undefined -> [];
-                Else ->
-                    [?l2b(R) || R <- string:tokens(Else, ",")]
-            end,
-            case couch_config:get("couch_httpd_auth", "proxy_use_secret", "false") of
-                "true" ->
-                    case couch_config:get("couch_httpd_auth", "secret", nil) of
-                        nil ->
-                            Req#httpd{user_ctx=#user_ctx{name=?l2b(UserName), roles=Roles}};
-                        Secret ->
-                            ExpectedToken = couch_util:to_hex(crypto:sha_mac(Secret, UserName)),
-                            case header_value(Req, XHeaderToken) of
-                                Token when Token == ExpectedToken ->
-                                    Req#httpd{user_ctx=#user_ctx{name=?l2b(UserName),
-                                                            roles=Roles}};
-                                _ -> nil
-                            end
-                    end;
-                _ ->
-                    Req#httpd{user_ctx=#user_ctx{name=?l2b(UserName), roles=Roles}}
-            end
-    end.
-
-
-cookie_authentication_handler(#httpd{mochi_req=MochiReq}=Req) ->
-    case MochiReq:get_cookie_value("AuthSession") of
-    undefined -> Req;
-    [] -> Req;
-    Cookie ->
-        [User, TimeStr, HashStr] = try
-            AuthSession = couch_util:decodeBase64Url(Cookie),
-            [_A, _B, _Cs] = re:split(?b2l(AuthSession), ":",
-                                     [{return, list}, {parts, 3}])
-        catch
-            _:_Error ->
-                Reason = <<"Malformed AuthSession cookie. Please clear your cookies.">>,
-                throw({bad_request, Reason})
-        end,
-        % Verify expiry and hash
-        CurrentTime = make_cookie_time(),
-        case couch_config:get("couch_httpd_auth", "secret", nil) of
-        nil ->
-            ?LOG_DEBUG("cookie auth secret is not set",[]),
-            Req;
-        SecretStr ->
-            Secret = ?l2b(SecretStr),
-            case couch_auth_cache:get_user_creds(User) of
-            nil -> Req;
-            UserProps ->
-                UserSalt = couch_util:get_value(<<"salt">>, UserProps, <<"">>),
-                FullSecret = <<Secret/binary, UserSalt/binary>>,
-                ExpectedHash = crypto:sha_mac(FullSecret, User ++ ":" ++ TimeStr),
-                Hash = ?l2b(HashStr),
-                Timeout = list_to_integer(
-                    couch_config:get("couch_httpd_auth", "timeout", "600")),
-                ?LOG_DEBUG("timeout ~p", [Timeout]),
-                case (catch erlang:list_to_integer(TimeStr, 16)) of
-                    TimeStamp when CurrentTime < TimeStamp + Timeout ->
-                        case couch_passwords:verify(ExpectedHash, Hash) of
-                            true ->
-                                TimeLeft = TimeStamp + Timeout - CurrentTime,
-                                ?LOG_DEBUG("Successful cookie auth as: ~p", [User]),
-                                Req#httpd{user_ctx=#user_ctx{
-                                    name=?l2b(User),
-                                    roles=couch_util:get_value(<<"roles">>, UserProps, [])
-                                }, auth={FullSecret, TimeLeft < Timeout*0.9}};
-                            _Else ->
-                                Req
-                        end;
-                    _Else ->
-                        Req
-                end
-            end
-        end
-    end.
-
-cookie_auth_header(#httpd{user_ctx=#user_ctx{name=null}}, _Headers) -> [];
-cookie_auth_header(#httpd{user_ctx=#user_ctx{name=User}, auth={Secret, true}}=Req, Headers) ->
-    % Note: we only set the AuthSession cookie if:
-    %  * a valid AuthSession cookie has been received
-    %  * we are outside a 10% timeout window
-    %  * and if an AuthSession cookie hasn't already been set e.g. by a login
-    %    or logout handler.
-    % The login and logout handlers need to set the AuthSession cookie
-    % themselves.
-    CookieHeader = couch_util:get_value("Set-Cookie", Headers, ""),
-    Cookies = mochiweb_cookies:parse_cookie(CookieHeader),
-    AuthSession = couch_util:get_value("AuthSession", Cookies),
-    if AuthSession == undefined ->
-        TimeStamp = make_cookie_time(),
-        [cookie_auth_cookie(Req, ?b2l(User), Secret, TimeStamp)];
-    true ->
-        []
-    end;
-cookie_auth_header(_Req, _Headers) -> [].
-
-cookie_auth_cookie(Req, User, Secret, TimeStamp) ->
-    SessionData = User ++ ":" ++ erlang:integer_to_list(TimeStamp, 16),
-    Hash = crypto:sha_mac(Secret, SessionData),
-    mochiweb_cookies:cookie("AuthSession",
-        couch_util:encodeBase64Url(SessionData ++ ":" ++ ?b2l(Hash)),
-        [{path, "/"}] ++ cookie_scheme(Req) ++ max_age()).
-
-ensure_cookie_auth_secret() ->
-    case couch_config:get("couch_httpd_auth", "secret", nil) of
-        nil ->
-            NewSecret = ?b2l(couch_uuids:random()),
-            couch_config:set("couch_httpd_auth", "secret", NewSecret),
-            NewSecret;
-        Secret -> Secret
-    end.
-
-% session handlers
-% Login handler with user db
-handle_session_req(#httpd{method='POST', mochi_req=MochiReq}=Req) ->
-    ReqBody = MochiReq:recv_body(),
-    Form = case MochiReq:get_primary_header_value("content-type") of
-        % content type should be json
-        "application/x-www-form-urlencoded" ++ _ ->
-            mochiweb_util:parse_qs(ReqBody);
-        "application/json" ++ _ ->
-            {Pairs} = ?JSON_DECODE(ReqBody),
-            lists:map(fun({Key, Value}) ->
-              {?b2l(Key), ?b2l(Value)}
-            end, Pairs);
-        _ ->
-            []
-    end,
-    UserName = ?l2b(couch_util:get_value("name", Form, "")),
-    Password = ?l2b(couch_util:get_value("password", Form, "")),
-    ?LOG_DEBUG("Attempt Login: ~s",[UserName]),
-    User = case couch_auth_cache:get_user_creds(UserName) of
-        nil -> [];
-        Result -> Result
-    end,
-    UserSalt = couch_util:get_value(<<"salt">>, User, <<>>),
-    case authenticate(Password, User) of
-        true ->
-            % setup the session cookie
-            Secret = ?l2b(ensure_cookie_auth_secret()),
-            CurrentTime = make_cookie_time(),
-            Cookie = cookie_auth_cookie(Req, ?b2l(UserName), <<Secret/binary, UserSalt/binary>>, CurrentTime),
-            % TODO document the "next" feature in Futon
-            {Code, Headers} = case couch_httpd:qs_value(Req, "next", nil) of
-                nil ->
-                    {200, [Cookie]};
-                Redirect ->
-                    {302, [Cookie, {"Location", couch_httpd:absolute_uri(Req, Redirect)}]}
-            end,
-            send_json(Req#httpd{req_body=ReqBody}, Code, Headers,
-                {[
-                    {ok, true},
-                    {name, couch_util:get_value(<<"name">>, User, null)},
-                    {roles, couch_util:get_value(<<"roles">>, User, [])}
-                ]});
-        _Else ->
-            % clear the session
-            Cookie = mochiweb_cookies:cookie("AuthSession", "", [{path, "/"}] ++ cookie_scheme(Req)),
-            {Code, Headers} = case couch_httpd:qs_value(Req, "fail", nil) of
-                nil ->
-                    {401, [Cookie]};
-                Redirect ->
-                    {302, [Cookie, {"Location", couch_httpd:absolute_uri(Req, Redirect)}]}
-            end,
-            send_json(Req, Code, Headers, {[{error, <<"unauthorized">>},{reason, <<"Name or password is incorrect.">>}]})
-    end;
-% get user info
-% GET /_session
-handle_session_req(#httpd{method='GET', user_ctx=UserCtx}=Req) ->
-    Name = UserCtx#user_ctx.name,
-    ForceLogin = couch_httpd:qs_value(Req, "basic", "false"),
-    case {Name, ForceLogin} of
-        {null, "true"} ->
-            throw({unauthorized, <<"Please login.">>});
-        {Name, _} ->
-            send_json(Req, {[
-                % remove this ok
-                {ok, true},
-                {<<"userCtx">>, {[
-                    {name, Name},
-                    {roles, UserCtx#user_ctx.roles}
-                ]}},
-                {info, {[
-                    {authentication_db, ?l2b(couch_config:get("couch_httpd_auth", "authentication_db"))},
-                    {authentication_handlers, [auth_name(H) || H <- couch_httpd:make_fun_spec_strs(
-                            couch_config:get("httpd", "authentication_handlers"))]}
-                ] ++ maybe_value(authenticated, UserCtx#user_ctx.handler, fun(Handler) ->
-                        auth_name(?b2l(Handler))
-                    end)}}
-            ]})
-    end;
-% logout by deleting the session
-handle_session_req(#httpd{method='DELETE'}=Req) ->
-    Cookie = mochiweb_cookies:cookie("AuthSession", "", [{path, "/"}] ++ cookie_scheme(Req)),
-    {Code, Headers} = case couch_httpd:qs_value(Req, "next", nil) of
-        nil ->
-            {200, [Cookie]};
-        Redirect ->
-            {302, [Cookie, {"Location", couch_httpd:absolute_uri(Req, Redirect)}]}
-    end,
-    send_json(Req, Code, Headers, {[{ok, true}]});
-handle_session_req(Req) ->
-    send_method_not_allowed(Req, "GET,HEAD,POST,DELETE").
-
-maybe_value(_Key, undefined, _Fun) -> [];
-maybe_value(Key, Else, Fun) ->
-    [{Key, Fun(Else)}].
-
-authenticate(Pass, UserProps) ->
-    UserSalt = couch_util:get_value(<<"salt">>, UserProps, <<>>),
-    {PasswordHash, ExpectedHash} =
-        case couch_util:get_value(<<"password_scheme">>, UserProps, <<"simple">>) of
-        <<"simple">> ->
-            {couch_passwords:simple(Pass, UserSalt),
-            couch_util:get_value(<<"password_sha">>, UserProps, nil)};
-        <<"pbkdf2">> ->
-            Iterations = couch_util:get_value(<<"iterations">>, UserProps, 10000),
-            {couch_passwords:pbkdf2(Pass, UserSalt, Iterations),
-             couch_util:get_value(<<"derived_key">>, UserProps, nil)}
-    end,
-    couch_passwords:verify(PasswordHash, ExpectedHash).
-
-auth_name(String) when is_list(String) ->
-    [_,_,_,_,_,Name|_] = re:split(String, "[\\W_]", [{return, list}]),
-    ?l2b(Name).
-
-make_cookie_time() ->
-    {NowMS, NowS, _} = erlang:now(),
-    NowMS * 1000000 + NowS.
-
-cookie_scheme(#httpd{mochi_req=MochiReq}) ->
-    [{http_only, true}] ++
-    case MochiReq:get(scheme) of
-        http -> [];
-        https -> [{secure, true}]
-    end.
-
-max_age() ->
-    case couch_config:get("couch_httpd_auth", "allow_persistent_cookies", "false") of
-        "false" ->
-            [];
-        "true" ->
-            Timeout = list_to_integer(
-                couch_config:get("couch_httpd_auth", "timeout", "600")),
-            [{max_age, Timeout}]
-    end.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_httpd_cors.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_httpd_cors.erl b/apps/couch/src/couch_httpd_cors.erl
deleted file mode 100644
index d9462d1..0000000
--- a/apps/couch/src/couch_httpd_cors.erl
+++ /dev/null
@@ -1,351 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
-%% @doc module to handle Cross-Origin Resource Sharing
-%%
-%% This module handles CORS requests and preflight request for
-%% CouchDB. The configuration is done in the ini file.
-%%
-%% This implements http://www.w3.org/TR/cors/
-
-
--module(couch_httpd_cors).
-
--include("couch_db.hrl").
-
--export([is_preflight_request/1, cors_headers/2]).
-
--define(SUPPORTED_HEADERS, "Accept, Accept-Language, Content-Type," ++
-        "Expires, Last-Modified, Pragma, Origin, Content-Length," ++
-        "If-Match, Destination, X-Requested-With, " ++
-        "X-Http-Method-Override, Content-Range").
-
--define(SUPPORTED_METHODS, "GET, HEAD, POST, PUT, DELETE," ++
-        "TRACE, CONNECT, COPY, OPTIONS").
-
-% as defined in http://www.w3.org/TR/cors/#terminology
--define(SIMPLE_HEADERS, ["Cache-Control", "Content-Language",
-        "Content-Type", "Expires", "Last-Modified", "Pragma"]).
--define(ALLOWED_HEADERS, lists:sort(["Server", "Etag",
-        "Accept-Ranges" | ?SIMPLE_HEADERS])).
--define(SIMPLE_CONTENT_TYPE_VALUES, ["application/x-www-form-urlencoded",
-        "multipart/form-data", "text/plain"]).
-
-% TODO: - pick a sane default
--define(CORS_DEFAULT_MAX_AGE, 12345).
-
-%% is_preflight_request/1
-
-% http://www.w3.org/TR/cors/#resource-preflight-requests
-
-is_preflight_request(#httpd{method=Method}=Req) when Method /= 'OPTIONS' ->
-    Req;
-is_preflight_request(Req) ->
-    EnableCors = enable_cors(),
-    is_preflight_request(Req, EnableCors).
-
-is_preflight_request(Req, false) ->
-    Req;
-is_preflight_request(#httpd{mochi_req=MochiReq}=Req, true) ->
-    case preflight_request(MochiReq) of
-    {ok, PreflightHeaders} ->
-        send_preflight_response(Req, PreflightHeaders);
-    _ ->
-        Req
-    end.
-
-
-preflight_request(MochiReq) ->
-    Origin = MochiReq:get_header_value("Origin"),
-    preflight_request(MochiReq, Origin).
-
-preflight_request(MochiReq, undefined) ->
-    % If the Origin header is not present terminate this set of
-    % steps. The request is outside the scope of this specification.
-    % http://www.w3.org/TR/cors/#resource-preflight-requests
-    MochiReq;
-preflight_request(MochiReq, Origin) ->
-    Host = couch_httpd_vhost:host(MochiReq),
-    AcceptedOrigins = get_accepted_origins(Host),
-    AcceptAll = lists:member("*", AcceptedOrigins),
-
-    HandlerFun = fun() ->
-        OriginList = couch_util:to_list(Origin),
-        handle_preflight_request(OriginList, Host, MochiReq)
-    end,
-
-    case AcceptAll of
-    true ->
-        % Always matching is acceptable since the list of
-        % origins can be unbounded.
-        % http://www.w3.org/TR/cors/#resource-preflight-requests
-        HandlerFun();
-    false ->
-        case lists:member(Origin, AcceptedOrigins) of
-        % The Origin header can only contain a single origin as
-        % the user agent will not follow redirects.
-        % http://www.w3.org/TR/cors/#resource-preflight-requests
-        % TODO: Square against multi origin thinger in Security Considerations
-        true ->
-            HandlerFun();
-        false ->
-            % If the value of the Origin header is not a
-            % case-sensitive match for any of the values
-            % in list of origins do not set any additional
-            % headers and terminate this set of steps.
-            % http://www.w3.org/TR/cors/#resource-preflight-requests
-            false
-        end
-    end.
-
-
-handle_preflight_request(Origin, Host, MochiReq) ->
-    %% get supported methods
-    SupportedMethods = split_list(cors_config(Host, "methods",
-                                              ?SUPPORTED_METHODS)),
-
-    % get supported headers
-    AllSupportedHeaders = split_list(cors_config(Host, "headers",
-                                                 ?SUPPORTED_HEADERS)),
-
-    SupportedHeaders = [string:to_lower(H) || H <- AllSupportedHeaders],
-
-    % get max age
-    MaxAge = cors_config(Host, "max_age", ?CORS_DEFAULT_MAX_AGE),
-
-    PreflightHeaders0 = maybe_add_credentials(Origin, Host, [
-        {"Access-Control-Allow-Origin", Origin},
-        {"Access-Control-Max-Age", MaxAge},
-        {"Access-Control-Allow-Methods",
-            string:join(SupportedMethods, ", ")}]),
-
-    case MochiReq:get_header_value("Access-Control-Request-Method") of
-    undefined ->
-        % If there is no Access-Control-Request-Method header
-        % or if parsing failed, do not set any additional headers
-        % and terminate this set of steps. The request is outside
-        % the scope of this specification.
-        % http://www.w3.org/TR/cors/#resource-preflight-requests
-        {ok, PreflightHeaders0};
-    Method ->
-        case lists:member(Method, SupportedMethods) of
-        true ->
-            % method ok , check headers
-            AccessHeaders = MochiReq:get_header_value(
-                    "Access-Control-Request-Headers"),
-            {FinalReqHeaders, ReqHeaders} = case AccessHeaders of
-                undefined -> {"", []};
-                Headers ->
-                    % transform header list in something we
-                    % could check. make sure everything is a
-                    % list
-                    RH = [string:to_lower(H)
-                          || H <- split_headers(Headers)],
-                    {Headers, RH}
-            end,
-            % check if headers are supported
-            case ReqHeaders -- SupportedHeaders of
-            [] ->
-                PreflightHeaders = PreflightHeaders0 ++
-                                   [{"Access-Control-Allow-Headers",
-                                     FinalReqHeaders}],
-                {ok, PreflightHeaders};
-            _ ->
-                false
-            end;
-        false ->
-        % If method is not a case-sensitive match for any of
-        % the values in list of methods do not set any additional
-        % headers and terminate this set of steps.
-        % http://www.w3.org/TR/cors/#resource-preflight-requests
-            false
-        end
-    end.
-
-
-send_preflight_response(#httpd{mochi_req=MochiReq}=Req, Headers) ->
-    couch_httpd:log_request(Req, 204),
-    couch_stats_collector:increment({httpd_status_codes, 204}),
-    Headers1 = couch_httpd:http_1_0_keep_alive(MochiReq, Headers),
-    Headers2 = Headers1 ++ couch_httpd:server_header() ++
-               couch_httpd_auth:cookie_auth_header(Req, Headers1),
-    {ok, MochiReq:respond({204, Headers2, <<>>})}.
-
-
-% cors_headers/1
-
-cors_headers(MochiReq, RequestHeaders) ->
-    EnableCors = enable_cors(),
-    CorsHeaders = do_cors_headers(MochiReq, EnableCors),
-    maybe_apply_cors_headers(CorsHeaders, RequestHeaders).
-
-do_cors_headers(#httpd{mochi_req=MochiReq}, true) ->
-    Host = couch_httpd_vhost:host(MochiReq),
-    AcceptedOrigins = get_accepted_origins(Host),
-    case MochiReq:get_header_value("Origin") of
-    undefined ->
-        % If the Origin header is not present terminate
-        % this set of steps. The request is outside the scope
-        % of this specification.
-        % http://www.w3.org/TR/cors/#resource-processing-model
-        [];
-    Origin ->
-        handle_cors_headers(couch_util:to_list(Origin),
-                            Host, AcceptedOrigins)
-    end;
-do_cors_headers(_MochiReq, false) ->
-    [].
-
-maybe_apply_cors_headers([], RequestHeaders) ->
-    RequestHeaders;
-maybe_apply_cors_headers(CorsHeaders, RequestHeaders0) ->
-    % for each RequestHeader that isn't in SimpleHeaders,
-    % (or Content-Type with SIMPLE_CONTENT_TYPE_VALUES)
-    % append to Access-Control-Expose-Headers
-    % return: RequestHeaders ++ CorsHeaders ++ ACEH
-
-    RequestHeaders = [K || {K,_V} <- RequestHeaders0],
-    ExposedHeaders0 = reduce_headers(RequestHeaders, ?ALLOWED_HEADERS),
-
-    % here we may have not moved Content-Type into ExposedHeaders,
-    % now we need to check whether the Content-Type valus is
-    % in ?SIMPLE_CONTENT_TYPE_VALUES and if it isn’t add Content-
-    % Type to to ExposedHeaders
-    ContentType =  proplists:get_value("Content-Type", RequestHeaders0),
-    IncludeContentType = case ContentType of
-    undefined ->
-        false;
-    _ ->
-        ContentType_ = string:to_lower(ContentType),
-        lists:member(ContentType_, ?SIMPLE_CONTENT_TYPE_VALUES)
-    end,
-    ExposedHeaders = case IncludeContentType of
-    false ->
-        lists:umerge(ExposedHeaders0, ["Content-Type"]);
-    true ->
-        ExposedHeaders0
-    end,
-    CorsHeaders
-    ++ RequestHeaders0
-    ++ [{"Access-Control-Expose-Headers",
-            string:join(ExposedHeaders, ", ")}].
-
-
-reduce_headers(A, B) ->
-    reduce_headers0(A, B, []).
-
-reduce_headers0([], _B, Result) ->
-    lists:sort(Result);
-reduce_headers0([ElmA|RestA], B, Result) ->
-    R = case member_nocase(ElmA, B) of
-    false -> Result;
-    _Else -> [ElmA | Result]
-    end,
-    reduce_headers0(RestA, B, R).
-
-member_nocase(ElmA, List) ->
-    lists:any(fun(ElmB) ->
-        string:to_lower(ElmA) =:= string:to_lower(ElmB)
-    end, List).
-
-handle_cors_headers(_Origin, _Host, []) ->
-    [];
-handle_cors_headers(Origin, Host, AcceptedOrigins) ->
-    AcceptAll = lists:member("*", AcceptedOrigins),
-    case {AcceptAll, lists:member(Origin, AcceptedOrigins)} of
-    {true, _} ->
-        make_cors_header(Origin, Host);
-    {false, true}  ->
-        make_cors_header(Origin, Host);
-    _ ->
-        % If the value of the Origin header is not a
-        % case-sensitive match for any of the values
-        % in list of origins, do not set any additional
-        % headers and terminate this set of steps.
-        % http://www.w3.org/TR/cors/#resource-requests
-        []
-    end.
-
-
-make_cors_header(Origin, Host) ->
-    Headers = [{"Access-Control-Allow-Origin", Origin}],
-    maybe_add_credentials(Origin, Host, Headers).
-
-
-%% util
-
-maybe_add_credentials(Origin, Host, Headers) ->
-    maybe_add_credentials(Headers, allow_credentials(Origin, Host)).
-
-maybe_add_credentials(Headers, false) ->
-    Headers;
-maybe_add_credentials(Headers, true) ->
-    Headers ++ [{"Access-Control-Allow-Credentials", "true"}].
-
-
-allow_credentials("*", _Host) ->
-    false;
-allow_credentials(_Origin, Host) ->
-    Default = get_bool_config("cors", "credentials", false),
-    get_bool_config(cors_section(Host), "credentials", Default).
-
-
-
-cors_config(Host, Key, Default) ->
-    couch_config:get(cors_section(Host), Key,
-                     couch_config:get("cors", Key, Default)).
-
-cors_section(Host0) ->
-    {Host, _Port} = split_host_port(Host0),
-    "cors:" ++ Host.
-
-enable_cors() ->
-    get_bool_config("httpd", "enable_cors", false).
-
-get_bool_config(Section, Key, Default) ->
-    case couch_config:get(Section, Key) of
-    undefined ->
-        Default;
-    "true" ->
-        true;
-    "false" ->
-        false
-    end.
-
-get_accepted_origins(Host) ->
-    split_list(cors_config(Host, "origins", [])).
-
-split_list(S) ->
-    re:split(S, "\\s*,\\s*", [trim, {return, list}]).
-
-split_headers(H) ->
-    re:split(H, ",\\s*", [{return,list}, trim]).
-
-split_host_port(HostAsString) ->
-    % split at semicolon ":"
-    Split = string:rchr(HostAsString, $:),
-    split_host_port(HostAsString, Split).
-
-split_host_port(HostAsString, 0) ->
-    % no semicolon
-    {HostAsString, '*'};
-split_host_port(HostAsString, N) ->
-    HostPart = string:substr(HostAsString, 1, N-1),
-    % parse out port
-    % is there a nicer way?
-    case (catch erlang:list_to_integer(string:substr(HostAsString,
-                    N+1, length(HostAsString)))) of
-    {'EXIT', _} ->
-        {HostAsString, '*'};
-    Port ->
-        {HostPart, Port}
-    end.


[06/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/test/core/layoutSpec.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/test/core/layoutSpec.js b/apps/fauxton/test/core/layoutSpec.js
deleted file mode 100644
index 3876b70..0000000
--- a/apps/fauxton/test/core/layoutSpec.js
+++ /dev/null
@@ -1,94 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-define([
-       'modules/fauxton/layout',
-      'testUtils'
-], function (Layout, testUtils) {
-  var assert = testUtils.assert;
-
-  describe("Faxuton Layout", function () {
-    var layout;
-
-    beforeEach(function () {
-      var navBar = new Backbone.View();
-      var apiBar = new Backbone.View();
-      layout = new Layout(navBar, apiBar);
-    });
-
-    describe('#setTemplate', function () {
-
-      it("Should set template without prefix", function () {
-        layout.setTemplate('myTemplate');
-
-        assert.equal(layout.layout.template, 'templates/layouts/myTemplate');
-
-      });
-
-      it("Should set template with prefix", function () {
-        layout.setTemplate({name: 'myTemplate', prefix: 'myPrefix/'});
-
-        assert.equal(layout.layout.template, 'myPrefix/myTemplate');
-      });
-
-      it("Should remove old views", function () {
-        var view = {
-          remove: function () {}
-        };
-
-        layout.layoutViews = {
-          'selector': view
-        };
-
-        var mockRemove = sinon.spy(view, 'remove');
-        layout.setTemplate('myTemplate');
-        assert.ok(mockRemove.calledOnce);
-
-      });
-
-      it("Should render", function () {
-        var mockRender = sinon.spy(layout, 'render');
-
-        layout.setTemplate('myTemplate');
-
-        assert.ok(mockRender.calledOnce);
-
-      });
-
-    });
-
-    describe('#renderView', function () {
-
-      it('Should render existing view', function () {
-        var view = new Backbone.View();
-        var mockRender = sinon.spy(view, 'render');
-        layout.layoutViews = {
-          '#selector': view
-        };
-
-        var out = layout.renderView('#selector');
-
-        assert.ok(mockRender.calledOnce);
-      });
-
-      it('Should return false for non-existing view', function () {
-        var view = new Backbone.View();
-        layout.layoutViews = {
-          'selector': view
-        };
-
-        var out = layout.renderView('wrongSelector');
-        assert.notOk(out, 'No view found');
-      });
-    });
-
-  });
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/test/core/navbarSpec.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/test/core/navbarSpec.js b/apps/fauxton/test/core/navbarSpec.js
deleted file mode 100644
index ec3e71f..0000000
--- a/apps/fauxton/test/core/navbarSpec.js
+++ /dev/null
@@ -1,107 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-define([
-       'modules/fauxton/base',
-      'testUtils'
-], function (Fauxton, testUtils) {
-  var assert = testUtils.assert,
-      NavBar = Fauxton.NavBar;
-
-  describe('NavBar', function () {
-
-    describe('adding links', function () {
-      var navBar;
-
-      beforeEach(function () {
-        navBar = new NavBar();
-        navBar.navLinks = [];
-        navBar.bottomNavLinks = [];
-        navBar.footerNavLinks = [];
-      });
-
-      it('Should add link to navlinks', function () {
-        navBar.addLink({href: '#/test', title: 'Test Title'});
-
-        assert.equal(navBar.navLinks.length, 1);
-        assert.equal(navBar.footerNavLinks.length, 0);
-        assert.equal(navBar.bottomNavLinks.length, 0);
-      });
-
-      it('Should add link to bottom links', function () {
-        navBar.addLink({href: '#/test', bottomNav: true, title: 'Test Title'});
-
-        assert.equal(navBar.bottomNavLinks.length, 1);
-        assert.equal(navBar.navLinks.length, 0);
-        assert.equal(navBar.footerNavLinks.length, 0);
-      });
-
-      it('Should add link to footer links', function () {
-        navBar.addLink({href: '#/test', footerNav: true, title: 'Test Title'});
-
-        assert.equal(navBar.footerNavLinks.length, 1);
-        assert.equal(navBar.bottomNavLinks.length, 0);
-        assert.equal(navBar.navLinks.length, 0);
-      });
-    });
-
-    describe('removing links', function () {
-      var navBar;
-
-      beforeEach(function () {
-        navBar = new NavBar();
-        navBar.navLinks = [];
-        navBar.bottomNavLinks = [];
-        navBar.footerNavLinks = [];
-        navBar.addLink({
-          href: '#/test', 
-          footerNav: true, 
-          title: 'Test Title Footer'
-        });
-
-        navBar.addLink({
-          href: '#/test', 
-          bottomNav: true, 
-          title: 'Test Title Bottom'
-        });
-
-        navBar.addLink({
-          href: '#/test', 
-          title: 'Test Title'
-        });
-      });
-
-      it("should remove links from list", function () {
-        navBar.removeLink({
-          title: 'Test Title Footer',
-          footerNav: true
-        });
-
-        assert.equal(navBar.footerNavLinks.length, 0);
-        assert.equal(navBar.bottomNavLinks.length, 1);
-        assert.equal(navBar.navLinks.length, 1);
-      });
-
-      it("Should call render after removing links", function () {
-        var renderSpy = sinon.stub(navBar,'render');
-
-        navBar.removeLink({
-          title: 'Test Title Footer',
-          footerNav: true
-        });
-
-        assert.ok(renderSpy.calledOnce);
-      });
-
-    });
-  });
-
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/test/core/paginateSpec.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/test/core/paginateSpec.js b/apps/fauxton/test/core/paginateSpec.js
deleted file mode 100644
index 114c434..0000000
--- a/apps/fauxton/test/core/paginateSpec.js
+++ /dev/null
@@ -1,109 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-define([
-       'api',
-       'modules/fauxton/components',
-       'modules/documents/resources',
-       'testUtils',
-       'app'
-], function (FauxtonAPI, Views, Models, testUtils, app) {
-  var assert = testUtils.assert,
-  ViewSandbox = testUtils.ViewSandbox;
-
-
-  describe('IndexPaginate', function () {
-    var viewSandbox, paginate, collection, navigateMock;
-    beforeEach(function () {
-      app.router = {
-        navigate: function () {}
-      };
-
-      collection = new Models.IndexCollection([{
-        id:'myId1',
-        doc: 'num1'
-      },
-      {
-        id:'myId2',
-        doc: 'num2'
-      }], {
-        database: {id: 'databaseId'},
-        design: '_design/myDoc'
-      });
-
-      paginate = new Views.IndexPagination({
-        collection: collection,
-        previousUrlfn: function () {},
-        nextUrlfn: function () {},
-        canShowPreviousfn: function () { return true; },
-        canShowNextfn: function () { return true;}
-      });
-      viewSandbox = new ViewSandbox();
-      viewSandbox.renderView(paginate); 
-    });
-
-    afterEach(function () {
-      viewSandbox.remove();
-    });
-
-    describe('#next', function () {
-      beforeEach(function () {
-        //do this so it doesn't throw an error on other unwired up components
-        FauxtonAPI.triggerRouteEvent = function () {};
-        //FauxtonAPI.triggerRouteEvent.restore && FauxtonAPI.triggerRouteEvent.restore();
-        //FauxtonAPI.navigate.restore && FauxtonAPI.navigate.restore(); 
-      });
-
-      it('Should navigate', function () {
-        var navigateMock = sinon.spy(FauxtonAPI, 'navigate');
-
-        paginate.$('a#next').click();
-
-        assert.ok(navigateMock.calledOnce);
-        FauxtonAPI.navigate.restore();
-      });
-
-      it('Should trigger routeEvent', function () {
-        var navigateMock = sinon.spy(FauxtonAPI, 'triggerRouteEvent');
-
-        paginate.$('a#next').click();
-
-        assert.ok(navigateMock.calledOnce);
-        FauxtonAPI.triggerRouteEvent.restore();
-      });
-
-    });
-
-
-    describe('#previous', function () {
-
-      it('Should navigate', function () {
-        var navigateMock = sinon.spy(FauxtonAPI, 'navigate');
-
-        paginate.$('a#previous').click();
-
-        assert.ok(navigateMock.calledOnce);
-        FauxtonAPI.navigate.restore();
-      });
-
-      it('Should trigger routeEvent', function () {
-        var navigateMock = sinon.spy(FauxtonAPI, 'triggerRouteEvent');
-
-        paginate.$('a#previous').click();
-
-        assert.ok(navigateMock.calledOnce);
-        FauxtonAPI.triggerRouteEvent.restore();
-      });
-
-    });
-
-  });
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/test/core/routeObjectSpec.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/test/core/routeObjectSpec.js b/apps/fauxton/test/core/routeObjectSpec.js
deleted file mode 100644
index 987d5b7..0000000
--- a/apps/fauxton/test/core/routeObjectSpec.js
+++ /dev/null
@@ -1,105 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-define([
-       'api',
-      'testUtils'
-], function (FauxtonAPI, testUtils) {
-  var assert = testUtils.assert,
-      RouteObject = FauxtonAPI.RouteObject;
-
-  describe('RouteObjects', function () {
-
-    describe('renderWith', function () {
-      var TestRouteObject, testRouteObject, mockLayout;
-
-      beforeEach(function () {
-        TestRouteObject = RouteObject.extend({
-          crumbs: ['mycrumbs']
-        });
-
-        testRouteObject = new TestRouteObject();
-        var apiBar = {};
-        apiBar.hide = sinon.spy();
-
-        // Need to find a better way of doing this
-        mockLayout = {
-          setTemplate: sinon.spy(),
-          clearBreadcrumbs: sinon.spy(),
-          setView: sinon.spy(),
-          renderView: sinon.spy(),
-          hooks: [],
-          setBreadcrumbs: sinon.spy(),
-          apiBar: apiBar
-        };
-
-      });
-
-      it('Should set template for first render ', function () {
-        testRouteObject.renderWith('the-route', mockLayout, 'args');
-
-        assert.ok(mockLayout.setTemplate.calledOnce, 'setTempalte was called');
-      });
-
-      it('Should not set template after first render', function () {
-        testRouteObject.renderWith('the-route', mockLayout, 'args');
-
-        testRouteObject.renderWith('the-route', mockLayout, 'args');
-
-        assert.ok(mockLayout.setTemplate.calledOnce, 'SetTemplate not meant to be called');
-      });
-
-      it('Should clear breadcrumbs', function () {
-        testRouteObject.renderWith('the-route', mockLayout, 'args');
-        assert.ok(mockLayout.clearBreadcrumbs.calledOnce, 'Clear Breadcrumbs called');
-      });
-
-      it('Should set breadcrumbs when breadcrumbs exist', function () {
-        testRouteObject.renderWith('the-route', mockLayout, 'args');
-        assert.ok(mockLayout.setBreadcrumbs.calledOnce, 'Set Breadcrumbs was called');
-      });
-
-      it("Should call establish of routeObject", function () {
-        var establishSpy = sinon.spy(testRouteObject,"establish");
-
-        testRouteObject.renderWith('the-route', mockLayout, 'args');
-        assert.ok(establishSpy.calledOnce, 'Calls establish');
-      });
-
-      it("Should render views", function () {
-        var view = new FauxtonAPI.View(),
-            getViewsSpy = sinon.stub(testRouteObject,"getViews"),
-            viewSpy = sinon.stub(view, "establish");
-        
-        view.hasRendered = false;
-        getViewsSpy.returns({'#view': view});
-
-        testRouteObject.renderWith('the-route', mockLayout, 'args');
-        assert.ok(viewSpy.calledOnce, 'Should render view');
-      });
-
-      it("Should not re-render a view", function () {
-        var view = new FauxtonAPI.View(),
-            getViewsSpy = sinon.stub(testRouteObject,"getViews"),
-            viewSpy = sinon.stub(view, "establish");
-        
-        view.hasRendered = true;
-        getViewsSpy.returns({'#view': view});
-
-        testRouteObject.renderWith('the-route', mockLayout, 'args');
-        assert.notOk(viewSpy.calledOnce, 'Should render view');
-      });
-    });
-
-  });
-
-
-});


[76/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/timezone.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/timezone.h b/src/apps/couch_collate/platform/osx/icu/unicode/timezone.h
new file mode 100644
index 0000000..1b9118b
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/timezone.h
@@ -0,0 +1,803 @@
+/*************************************************************************
+* Copyright (c) 1997-2008, International Business Machines Corporation
+* and others. All Rights Reserved.
+**************************************************************************
+*
+* File TIMEZONE.H
+*
+* Modification History:
+*
+*   Date        Name        Description
+*   04/21/97    aliu        Overhauled header.
+*   07/09/97    helena      Changed createInstance to createDefault.
+*   08/06/97    aliu        Removed dependency on internal header for Hashtable.
+*   08/10/98    stephen        Changed getDisplayName() API conventions to match
+*   08/19/98    stephen        Changed createTimeZone() to never return 0
+*   09/02/98    stephen        Sync to JDK 1.2 8/31
+*                            - Added getOffset(... monthlen ...)
+*                            - Added hasSameRules()
+*   09/15/98    stephen        Added getStaticClassID
+*   12/03/99    aliu        Moved data out of static table into icudata.dll.
+*                           Hashtable replaced by new static data structures.
+*   12/14/99    aliu        Made GMT public.
+*   08/15/01    grhoten     Made GMT private and added the getGMT() function
+**************************************************************************
+*/
+
+#ifndef TIMEZONE_H
+#define TIMEZONE_H
+
+#include "unicode/utypes.h"
+
+/**
+ * \file 
+ * \brief C++ API: TimeZone object
+ */
+
+#if !UCONFIG_NO_FORMATTING
+
+#include "unicode/uobject.h"
+#include "unicode/unistr.h"
+#include "unicode/ures.h"
+
+U_NAMESPACE_BEGIN
+
+class StringEnumeration;
+
+/**
+ *
+ * <code>TimeZone</code> represents a time zone offset, and also figures out daylight
+ * savings.
+ *
+ * <p>
+ * Typically, you get a <code>TimeZone</code> using <code>createDefault</code>
+ * which creates a <code>TimeZone</code> based on the time zone where the program
+ * is running. For example, for a program running in Japan, <code>createDefault</code>
+ * creates a <code>TimeZone</code> object based on Japanese Standard Time.
+ *
+ * <p>
+ * You can also get a <code>TimeZone</code> using <code>createTimeZone</code> along
+ * with a time zone ID. For instance, the time zone ID for the Pacific
+ * Standard Time zone is "PST". So, you can get a PST <code>TimeZone</code> object
+ * with:
+ * \htmlonly<blockquote>\endhtmlonly
+ * <pre>
+ * TimeZone *tz = TimeZone::createTimeZone("PST");
+ * </pre>
+ * \htmlonly</blockquote>\endhtmlonly
+ * You can use <code>getAvailableIDs</code> method to iterate through
+ * all the supported time zone IDs. You can then choose a
+ * supported ID to get a <code>TimeZone</code>.
+ * If the time zone you want is not represented by one of the
+ * supported IDs, then you can create a custom time zone ID with
+ * the following syntax:
+ *
+ * \htmlonly<blockquote>\endhtmlonly
+ * <pre>
+ * GMT[+|-]hh[[:]mm]
+ * </pre>
+ * \htmlonly</blockquote>\endhtmlonly
+ *
+ * For example, you might specify GMT+14:00 as a custom
+ * time zone ID.  The <code>TimeZone</code> that is returned
+ * when you specify a custom time zone ID does not include
+ * daylight savings time.
+ *
+ * TimeZone is an abstract class representing a time zone.  A TimeZone is needed for
+ * Calendar to produce local time for a particular time zone.  A TimeZone comprises
+ * three basic pieces of information:
+ * <ul>
+ *    <li>A time zone offset; that, is the number of milliseconds to add or subtract
+ *      from a time expressed in terms of GMT to convert it to the same time in that
+ *      time zone (without taking daylight savings time into account).</li>
+ *    <li>Logic necessary to take daylight savings time into account if daylight savings
+ *      time is observed in that time zone (e.g., the days and hours on which daylight
+ *      savings time begins and ends).</li>
+ *    <li>An ID.  This is a text string that uniquely identifies the time zone.</li>
+ * </ul>
+ *
+ * (Only the ID is actually implemented in TimeZone; subclasses of TimeZone may handle
+ * daylight savings time and GMT offset in different ways.  Currently we only have one
+ * TimeZone subclass: SimpleTimeZone.)
+ * <P>
+ * The TimeZone class contains a static list containing a TimeZone object for every
+ * combination of GMT offset and daylight-savings time rules currently in use in the
+ * world, each with a unique ID.  Each ID consists of a region (usually a continent or
+ * ocean) and a city in that region, separated by a slash, (for example, Pacific
+ * Standard Time is "America/Los_Angeles.")  Because older versions of this class used
+ * three- or four-letter abbreviations instead, there is also a table that maps the older
+ * abbreviations to the newer ones (for example, "PST" maps to "America/LosAngeles").
+ * Anywhere the API requires an ID, you can use either form.
+ * <P>
+ * To create a new TimeZone, you call the factory function TimeZone::createTimeZone()
+ * and pass it a time zone ID.  You can use the createEnumeration() function to
+ * obtain a list of all the time zone IDs recognized by createTimeZone().
+ * <P>
+ * You can also use TimeZone::createDefault() to create a TimeZone.  This function uses
+ * platform-specific APIs to produce a TimeZone for the time zone corresponding to
+ * the client's computer's physical location.  For example, if you're in Japan (assuming
+ * your machine is set up correctly), TimeZone::createDefault() will return a TimeZone
+ * for Japanese Standard Time ("Asia/Tokyo").
+ */
+class U_I18N_API TimeZone : public UObject {
+public:
+    /**
+     * @stable ICU 2.0
+     */
+    virtual ~TimeZone();
+
+    /**
+     * The GMT time zone has a raw offset of zero and does not use daylight
+     * savings time. This is a commonly used time zone.
+     * @return the GMT time zone.
+     * @stable ICU 2.0
+     */
+    static const TimeZone* U_EXPORT2 getGMT(void);
+
+    /**
+     * Creates a <code>TimeZone</code> for the given ID.
+     * @param ID the ID for a <code>TimeZone</code>, either an abbreviation such as
+     * "PST", a full name such as "America/Los_Angeles", or a custom ID
+     * such as "GMT-8:00".
+     * @return the specified <code>TimeZone</code>, or the GMT zone if the given ID
+     * cannot be understood.  Return result guaranteed to be non-null.  If you
+     * require that the specific zone asked for be returned, check the ID of the
+     * return result.
+     * @stable ICU 2.0
+     */
+    static TimeZone* U_EXPORT2 createTimeZone(const UnicodeString& ID);
+
+    /**
+     * Returns an enumeration over all recognized time zone IDs. (i.e.,
+     * all strings that createTimeZone() accepts)
+     *
+     * @return an enumeration object, owned by the caller.
+     * @stable ICU 2.4
+     */
+    static StringEnumeration* U_EXPORT2 createEnumeration();
+
+    /**
+     * Returns an enumeration over time zone IDs with a given raw
+     * offset from GMT.  There may be several times zones with the
+     * same GMT offset that differ in the way they handle daylight
+     * savings time.  For example, the state of Arizona doesn't
+     * observe daylight savings time.  If you ask for the time zone
+     * IDs corresponding to GMT-7:00, you'll get back an enumeration
+     * over two time zone IDs: "America/Denver," which corresponds to
+     * Mountain Standard Time in the winter and Mountain Daylight Time
+     * in the summer, and "America/Phoenix", which corresponds to
+     * Mountain Standard Time year-round, even in the summer.
+     *
+     * @param rawOffset an offset from GMT in milliseconds, ignoring
+     * the effect of daylight savings time, if any
+     * @return an enumeration object, owned by the caller
+     * @stable ICU 2.4
+     */
+    static StringEnumeration* U_EXPORT2 createEnumeration(int32_t rawOffset);
+
+    /**
+     * Returns an enumeration over time zone IDs associated with the
+     * given country.  Some zones are affiliated with no country
+     * (e.g., "UTC"); these may also be retrieved, as a group.
+     *
+     * @param country The ISO 3166 two-letter country code, or NULL to
+     * retrieve zones not affiliated with any country.
+     * @return an enumeration object, owned by the caller
+     * @stable ICU 2.4
+     */
+    static StringEnumeration* U_EXPORT2 createEnumeration(const char* country);
+
+#ifdef U_USE_TIMEZONE_OBSOLETE_2_8
+    /**
+     * Returns a list of time zone IDs, one for each time zone with a given GMT offset.
+     * The return value is a list because there may be several times zones with the same
+     * GMT offset that differ in the way they handle daylight savings time.  For example,
+     * the state of Arizona doesn't observe Daylight Savings time.  So if you ask for
+     * the time zone IDs corresponding to GMT-7:00, you'll get back two time zone IDs:
+     * "America/Denver," which corresponds to Mountain Standard Time in the winter and
+     * Mountain Daylight Time in the summer, and "America/Phoenix", which corresponds to
+     * Mountain Standard Time year-round, even in the summer.
+     * <P>
+     * The caller owns the list that is returned, but does not own the strings contained
+     * in that list.  Delete the array with uprv_free(), but DON'T delete the elements in the array.
+     *
+     * <p>NOTE: uprv_free() is declared in the private header source/common/cmemory.h.
+     *
+     * @param rawOffset  An offset from GMT in milliseconds.
+     * @param numIDs     Receives the number of items in the array that is returned.
+     * @return           An array of UnicodeString pointers, where each UnicodeString is
+     *                   a time zone ID for a time zone with the given GMT offset.  If
+     *                   there is no timezone that matches the GMT offset
+     *                   specified, NULL is returned.
+     * @obsolete ICU 2.8.  Use createEnumeration(int32_t) instead since this API will be removed in that release.
+     */
+    static const UnicodeString** createAvailableIDs(int32_t rawOffset, int32_t& numIDs);
+
+    /**
+     * Returns a list of time zone IDs associated with the given
+     * country.  Some zones are affiliated with no country (e.g.,
+     * "UTC"); these may also be retrieved, as a group.
+     *
+     * <P>The caller owns the list that is returned, but does not own
+     * the strings contained in that list.  Delete the array with uprv_free(), but
+     * <b>DON'T</b> delete the elements in the array.
+     *
+     * <p>NOTE: uprv_free() is declared in the private header source/common/cmemory.h.
+     *
+     * @param country The ISO 3166 two-letter country code, or NULL to
+     * retrieve zones not affiliated with any country.
+     * @param numIDs Receives the number of items in the array that is
+     * returned.
+     * @return An array of UnicodeString pointers, where each
+     * UnicodeString is a time zone ID for a time zone with the given
+     * country.  If there is no timezone that matches the country
+     * specified, NULL is returned.
+     * @obsolete ICU 2.8.  Use createEnumeration(const char*) instead since this API will be removed in that release.
+     */
+    static const UnicodeString** createAvailableIDs(const char* country,
+                                                          int32_t& numIDs);
+
+    /**
+     * Returns a list of all time zone IDs supported by the TimeZone class (i.e., all
+     * IDs that it's legal to pass to createTimeZone()).  The caller owns the list that
+     * is returned, but does not own the strings contained in that list.  Delete the array with uprv_free(),
+     * but DON'T delete the elements in the array.
+     *
+     * <p>NOTE: uprv_free() is declared in the private header source/common/cmemory.h.
+     *
+     * @param numIDs  Receives the number of zone IDs returned.
+     * @return        An array of UnicodeString pointers, where each is a time zone ID
+     *                supported by the TimeZone class.
+     * @obsolete ICU 2.8.  Use createEnumeration(void) instead since this API will be removed in that release.
+     */
+    static const UnicodeString** createAvailableIDs(int32_t& numIDs);
+#endif
+
+    /**
+     * Returns the number of IDs in the equivalency group that
+     * includes the given ID.  An equivalency group contains zones
+     * that have the same GMT offset and rules.
+     *
+     * <p>The returned count includes the given ID; it is always >= 1.
+     * The given ID must be a system time zone.  If it is not, returns
+     * zero.
+     * @param id a system time zone ID
+     * @return the number of zones in the equivalency group containing
+     * 'id', or zero if 'id' is not a valid system ID
+     * @see #getEquivalentID
+     * @stable ICU 2.0
+     */
+    static int32_t U_EXPORT2 countEquivalentIDs(const UnicodeString& id);
+
+    /**
+     * Returns an ID in the equivalency group that
+     * includes the given ID.  An equivalency group contains zones
+     * that have the same GMT offset and rules.
+     *
+     * <p>The given index must be in the range 0..n-1, where n is the
+     * value returned by <code>countEquivalentIDs(id)</code>.  For
+     * some value of 'index', the returned value will be equal to the
+     * given id.  If the given id is not a valid system time zone, or
+     * if 'index' is out of range, then returns an empty string.
+     * @param id a system time zone ID
+     * @param index a value from 0 to n-1, where n is the value
+     * returned by <code>countEquivalentIDs(id)</code>
+     * @return the ID of the index-th zone in the equivalency group
+     * containing 'id', or an empty string if 'id' is not a valid
+     * system ID or 'index' is out of range
+     * @see #countEquivalentIDs
+     * @stable ICU 2.0
+     */
+    static const UnicodeString U_EXPORT2 getEquivalentID(const UnicodeString& id,
+                                               int32_t index);
+
+    /**
+     * Creates a new copy of the default TimeZone for this host. Unless the default time
+     * zone has already been set using adoptDefault() or setDefault(), the default is
+     * determined by querying the system using methods in TPlatformUtilities. If the
+     * system routines fail, or if they specify a TimeZone or TimeZone offset which is not
+     * recognized, the TimeZone indicated by the ID kLastResortID is instantiated
+     * and made the default.
+     *
+     * @return   A default TimeZone. Clients are responsible for deleting the time zone
+     *           object returned.
+     * @stable ICU 2.0
+     */
+    static TimeZone* U_EXPORT2 createDefault(void);
+
+    /**
+     * Sets the default time zone (i.e., what's returned by createDefault()) to be the
+     * specified time zone.  If NULL is specified for the time zone, the default time
+     * zone is set to the default host time zone.  This call adopts the TimeZone object
+     * passed in; the clent is no longer responsible for deleting it.
+     *
+     * @param zone  A pointer to the new TimeZone object to use as the default.
+     * @stable ICU 2.0
+     */
+    static void U_EXPORT2 adoptDefault(TimeZone* zone);
+
+    /**
+     * Same as adoptDefault(), except that the TimeZone object passed in is NOT adopted;
+     * the caller remains responsible for deleting it.
+     *
+     * @param zone  The given timezone.
+     * @system
+     */
+    static void U_EXPORT2 setDefault(const TimeZone& zone);
+
+    /**
+     * Returns the timezone data version currently used by ICU.
+     * @param status Output param to filled in with a success or an error.
+     * @return the version string, such as "2007f"
+     * @stable ICU 4.0
+     */
+    static const char* U_EXPORT2 getTZDataVersion(UErrorCode& status);
+
+    /**
+     * Returns the canonical system timezone ID or the normalized
+     * custom time zone ID for the given time zone ID.
+     * @param id            The input timezone ID to be canonicalized.
+     * @param canonicalID   Receives the canonical system timezone ID
+     *                      or the custom timezone ID in normalized format.
+     * @param status        Recevies the status.  When the given timezone ID
+     *                      is neither a known system time zone ID nor a
+     *                      valid custom timezone ID, U_ILLEGAL_ARGUMENT_ERROR
+     *                      is set.
+     * @return A reference to the result.
+     * @draft ICU 4.0
+     */
+    static UnicodeString& U_EXPORT2 getCanonicalID(const UnicodeString& id,
+        UnicodeString& canonicalID, UErrorCode& status);
+
+    /**
+     * Returns the canonical system timezone ID or the normalized
+     * custom time zone ID for the given time zone ID.
+     * @param id            The input timezone ID to be canonicalized.
+     * @param canonicalID   Receives the canonical system timezone ID
+     *                      or the custom timezone ID in normalized format.
+     * @param isSystemID    Receives if the given ID is a known system
+     *                      timezone ID.
+     * @param status        Recevies the status.  When the given timezone ID
+     *                      is neither a known system time zone ID nor a
+     *                      valid custom timezone ID, U_ILLEGAL_ARGUMENT_ERROR
+     *                      is set.
+     * @return A reference to the result.
+     * @draft ICU 4.0
+     */
+    static UnicodeString& U_EXPORT2 getCanonicalID(const UnicodeString& id,
+        UnicodeString& canonicalID, UBool& isSystemID, UErrorCode& status);
+
+    /**
+     * Returns true if the two TimeZones are equal.  (The TimeZone version only compares
+     * IDs, but subclasses are expected to also compare the fields they add.)
+     *
+     * @param that  The TimeZone object to be compared with.
+     * @return      True if the given TimeZone is equal to this TimeZone; false
+     *              otherwise.
+     * @stable ICU 2.0
+     */
+    virtual UBool operator==(const TimeZone& that) const;
+
+    /**
+     * Returns true if the two TimeZones are NOT equal; that is, if operator==() returns
+     * false.
+     *
+     * @param that  The TimeZone object to be compared with.
+     * @return      True if the given TimeZone is not equal to this TimeZone; false
+     *              otherwise.
+     * @stable ICU 2.0
+     */
+    UBool operator!=(const TimeZone& that) const {return !operator==(that);}
+
+    /**
+     * Returns the TimeZone's adjusted GMT offset (i.e., the number of milliseconds to add
+     * to GMT to get local time in this time zone, taking daylight savings time into
+     * account) as of a particular reference date.  The reference date is used to determine
+     * whether daylight savings time is in effect and needs to be figured into the offset
+     * that is returned (in other words, what is the adjusted GMT offset in this time zone
+     * at this particular date and time?).  For the time zones produced by createTimeZone(),
+     * the reference data is specified according to the Gregorian calendar, and the date
+     * and time fields are local standard time.
+     *
+     * <p>Note: Don't call this method. Instead, call the getOffset(UDate...) overload,
+     * which returns both the raw and the DST offset for a given time. This method
+     * is retained only for backward compatibility.
+     *
+     * @param era        The reference date's era
+     * @param year       The reference date's year
+     * @param month      The reference date's month (0-based; 0 is January)
+     * @param day        The reference date's day-in-month (1-based)
+     * @param dayOfWeek  The reference date's day-of-week (1-based; 1 is Sunday)
+     * @param millis     The reference date's milliseconds in day, local standard time
+     * @param status     Output param to filled in with a success or an error.
+     * @return           The offset in milliseconds to add to GMT to get local time.
+     * @stable ICU 2.0
+     */
+    virtual int32_t getOffset(uint8_t era, int32_t year, int32_t month, int32_t day,
+                              uint8_t dayOfWeek, int32_t millis, UErrorCode& status) const = 0;
+
+    /**
+     * Gets the time zone offset, for current date, modified in case of
+     * daylight savings. This is the offset to add *to* UTC to get local time.
+     *
+     * <p>Note: Don't call this method. Instead, call the getOffset(UDate...) overload,
+     * which returns both the raw and the DST offset for a given time. This method
+     * is retained only for backward compatibility.
+     *
+     * @param era the era of the given date.
+     * @param year the year in the given date.
+     * @param month the month in the given date.
+     * Month is 0-based. e.g., 0 for January.
+     * @param day the day-in-month of the given date.
+     * @param dayOfWeek the day-of-week of the given date.
+     * @param milliseconds the millis in day in <em>standard</em> local time.
+     * @param monthLength the length of the given month in days.
+     * @param status     Output param to filled in with a success or an error.
+     * @return the offset to add *to* GMT to get local time.
+     * @stable ICU 2.0
+     */
+    virtual int32_t getOffset(uint8_t era, int32_t year, int32_t month, int32_t day,
+                           uint8_t dayOfWeek, int32_t milliseconds,
+                           int32_t monthLength, UErrorCode& status) const = 0;
+
+    /**
+     * Returns the time zone raw and GMT offset for the given moment
+     * in time.  Upon return, local-millis = GMT-millis + rawOffset +
+     * dstOffset.  All computations are performed in the proleptic
+     * Gregorian calendar.  The default implementation in the TimeZone
+     * class delegates to the 8-argument getOffset().
+     *
+     * @param date moment in time for which to return offsets, in
+     * units of milliseconds from January 1, 1970 0:00 GMT, either GMT
+     * time or local wall time, depending on `local'.
+     * @param local if true, `date' is local wall time; otherwise it
+     * is in GMT time.
+     * @param rawOffset output parameter to receive the raw offset, that
+     * is, the offset not including DST adjustments
+     * @param dstOffset output parameter to receive the DST offset,
+     * that is, the offset to be added to `rawOffset' to obtain the
+     * total offset between local and GMT time. If DST is not in
+     * effect, this value is zero; otherwise it is a positive value,
+     * typically one hour.
+     * @param ec input-output error code
+     *
+     * @stable ICU 2.8
+     */
+    virtual void getOffset(UDate date, UBool local, int32_t& rawOffset,
+                           int32_t& dstOffset, UErrorCode& ec) const;
+
+    /**
+     * Sets the TimeZone's raw GMT offset (i.e., the number of milliseconds to add
+     * to GMT to get local time, before taking daylight savings time into account).
+     *
+     * @param offsetMillis  The new raw GMT offset for this time zone.
+     * @stable ICU 2.0
+     */
+    virtual void setRawOffset(int32_t offsetMillis) = 0;
+
+    /**
+     * Returns the TimeZone's raw GMT offset (i.e., the number of milliseconds to add
+     * to GMT to get local time, before taking daylight savings time into account).
+     *
+     * @return   The TimeZone's raw GMT offset.
+     * @stable ICU 2.0
+     */
+    virtual int32_t getRawOffset(void) const = 0;
+
+    /**
+     * Fills in "ID" with the TimeZone's ID.
+     *
+     * @param ID  Receives this TimeZone's ID.
+     * @return    A reference to 'ID'
+     * @stable ICU 2.0
+     */
+    UnicodeString& getID(UnicodeString& ID) const;
+
+    /**
+     * Sets the TimeZone's ID to the specified value.  This doesn't affect any other
+     * fields (for example, if you say<
+     * blockquote><pre>
+     * .     TimeZone* foo = TimeZone::createTimeZone("America/New_York");
+     * .     foo.setID("America/Los_Angeles");
+     * </pre>\htmlonly</blockquote>\endhtmlonly
+     * the time zone's GMT offset and daylight-savings rules don't change to those for
+     * Los Angeles.  They're still those for New York.  Only the ID has changed.)
+     *
+     * @param ID  The new timezone ID.
+     * @stable ICU 2.0
+     */
+    void setID(const UnicodeString& ID);
+
+    /**
+     * Enum for use with getDisplayName
+     * @stable ICU 2.4
+     */
+    enum EDisplayType {
+        /**
+         * Selector for short display name
+         * @stable ICU 2.4
+         */
+        SHORT = 1,
+        /**
+         * Selector for long display name
+         * @stable ICU 2.4
+         */
+        LONG
+    };
+
+    /**
+     * Returns a name of this time zone suitable for presentation to the user
+     * in the default locale.
+     * This method returns the long name, not including daylight savings.
+     * If the display name is not available for the locale,
+     * then this method returns a string in the format
+     * <code>GMT[+-]hh:mm</code>.
+     * @param result the human-readable name of this time zone in the default locale.
+     * @return       A reference to 'result'.
+     * @stable ICU 2.0
+     */
+    UnicodeString& getDisplayName(UnicodeString& result) const;
+
+    /**
+     * Returns a name of this time zone suitable for presentation to the user
+     * in the specified locale.
+     * This method returns the long name, not including daylight savings.
+     * If the display name is not available for the locale,
+     * then this method returns a string in the format
+     * <code>GMT[+-]hh:mm</code>.
+     * @param locale the locale in which to supply the display name.
+     * @param result the human-readable name of this time zone in the given locale
+     *               or in the default locale if the given locale is not recognized.
+     * @return       A reference to 'result'.
+     * @stable ICU 2.0
+     */
+    UnicodeString& getDisplayName(const Locale& locale, UnicodeString& result) const;
+
+    /**
+     * Returns a name of this time zone suitable for presentation to the user
+     * in the default locale.
+     * If the display name is not available for the locale,
+     * then this method returns a string in the format
+     * <code>GMT[+-]hh:mm</code>.
+     * @param daylight if true, return the daylight savings name.
+     * @param style either <code>LONG</code> or <code>SHORT</code>
+     * @param result the human-readable name of this time zone in the default locale.
+     * @return       A reference to 'result'.
+     * @stable ICU 2.0
+     */
+    UnicodeString& getDisplayName(UBool daylight, EDisplayType style, UnicodeString& result) const;
+
+    /**
+     * Returns a name of this time zone suitable for presentation to the user
+     * in the specified locale.
+     * If the display name is not available for the locale,
+     * then this method returns a string in the format
+     * <code>GMT[+-]hh:mm</code>.
+     * @param daylight if true, return the daylight savings name.
+     * @param style either <code>LONG</code> or <code>SHORT</code>
+     * @param locale the locale in which to supply the display name.
+     * @param result the human-readable name of this time zone in the given locale
+     *               or in the default locale if the given locale is not recognized.
+     * @return       A refence to 'result'.
+     * @stable ICU 2.0
+     */
+    UnicodeString& getDisplayName(UBool daylight, EDisplayType style, const Locale& locale, UnicodeString& result) const;
+
+    /**
+     * Queries if this time zone uses daylight savings time.
+     * @return true if this time zone uses daylight savings time,
+     * false, otherwise.
+     * @stable ICU 2.0
+     */
+    virtual UBool useDaylightTime(void) const = 0;
+
+    /**
+     * Queries if the given date is in daylight savings time in
+     * this time zone.
+     * This method is wasteful since it creates a new GregorianCalendar and
+     * deletes it each time it is called. This is a deprecated method
+     * and provided only for Java compatibility.
+     *
+     * @param date the given UDate.
+     * @param status Output param filled in with success/error code.
+     * @return true if the given date is in daylight savings time,
+     * false, otherwise.
+     * @deprecated ICU 2.4. Use Calendar::inDaylightTime() instead.
+     */
+    virtual UBool inDaylightTime(UDate date, UErrorCode& status) const = 0;
+
+    /**
+     * Returns true if this zone has the same rule and offset as another zone.
+     * That is, if this zone differs only in ID, if at all.
+     * @param other the <code>TimeZone</code> object to be compared with
+     * @return true if the given zone is the same as this one,
+     * with the possible exception of the ID
+     * @stable ICU 2.0
+     */
+    virtual UBool hasSameRules(const TimeZone& other) const;
+
+    /**
+     * Clones TimeZone objects polymorphically. Clients are responsible for deleting
+     * the TimeZone object cloned.
+     *
+     * @return   A new copy of this TimeZone object.
+     * @stable ICU 2.0
+     */
+    virtual TimeZone* clone(void) const = 0;
+
+    /**
+     * Return the class ID for this class.  This is useful only for
+     * comparing to a return value from getDynamicClassID().
+     * @return The class ID for all objects of this class.
+     * @stable ICU 2.0
+     */
+    static UClassID U_EXPORT2 getStaticClassID(void);
+
+    /**
+     * Returns a unique class ID POLYMORPHICALLY. This method is to
+     * implement a simple version of RTTI, since not all C++ compilers support genuine
+     * RTTI. Polymorphic operator==() and clone() methods call this method.
+     * <P>
+     * Concrete subclasses of TimeZone must use the UOBJECT_DEFINE_RTTI_IMPLEMENTATION
+     *  macro from uobject.h in their implementation to provide correct RTTI information.
+     * @return   The class ID for this object. All objects of a given class have the
+     *           same class ID. Objects of other classes have different class IDs.
+     * @stable ICU 2.0
+     */
+    virtual UClassID getDynamicClassID(void) const = 0;
+    
+    /**
+     * Returns the amount of time to be added to local standard time
+     * to get local wall clock time.
+     * <p>
+     * The default implementation always returns 3600000 milliseconds
+     * (i.e., one hour) if this time zone observes Daylight Saving
+     * Time. Otherwise, 0 (zero) is returned.
+     * <p>
+     * If an underlying TimeZone implementation subclass supports
+     * historical Daylight Saving Time changes, this method returns
+     * the known latest daylight saving value.
+     *
+     * @return the amount of saving time in milliseconds
+     * @stable ICU 3.6
+     */
+    virtual int32_t getDSTSavings() const;
+
+protected:
+
+    /**
+     * Default constructor.  ID is initialized to the empty string.
+     * @stable ICU 2.0
+     */
+    TimeZone();
+
+    /**
+     * Construct a timezone with a given ID.
+     * @param id a system time zone ID
+     * @stable ICU 2.0
+     */
+    TimeZone(const UnicodeString &id);
+
+    /**
+     * Copy constructor.
+     * @param source the object to be copied.
+     * @stable ICU 2.0
+     */
+    TimeZone(const TimeZone& source);
+
+    /**
+     * Default assignment operator.
+     * @param right the object to be copied.
+     * @stable ICU 2.0
+     */
+    TimeZone& operator=(const TimeZone& right);
+
+    /**
+     * Utility function. For internally loading rule data.
+     * @param top Top resource bundle for tz data
+     * @param ruleid ID of rule to load
+     * @param oldbundle Old bundle to reuse or NULL
+     * @param status Status parameter
+     * @return either a new bundle or *oldbundle
+     * @internal
+     */
+    static UResourceBundle* loadRule(const UResourceBundle* top, const UnicodeString& ruleid, UResourceBundle* oldbundle, UErrorCode&status);
+
+private:
+    friend class ZoneMeta;
+
+
+    static TimeZone*        createCustomTimeZone(const UnicodeString&); // Creates a time zone based on the string.
+
+    /**
+     * Resolve a link in Olson tzdata.  When the given id is known and it's not a link,
+     * the id itself is returned.  When the given id is known and it is a link, then
+     * dereferenced zone id is returned.  When the given id is unknown, then it returns
+     * empty string.
+     * @param linkTo Input zone id string
+     * @param linkFrom Receives the dereferenced zone id string
+     * @return The reference to the result (linkFrom)
+     */
+    static UnicodeString& dereferOlsonLink(const UnicodeString& linkTo, UnicodeString& linkFrom);
+
+    /**
+     * Parses the given custom time zone identifier
+     * @param id id A string of the form GMT[+-]hh:mm, GMT[+-]hhmm, or
+     * GMT[+-]hh.
+     * @param sign Receves parsed sign, 1 for positive, -1 for negative.
+     * @param hour Receives parsed hour field
+     * @param minute Receives parsed minute field
+     * @param second Receives parsed second field
+     * @return Returns TRUE when the given custom id is valid.
+     */
+    static UBool parseCustomID(const UnicodeString& id, int32_t& sign, int32_t& hour,
+        int32_t& min, int32_t& sec);
+
+    /**
+     * Parse a custom time zone identifier and return the normalized
+     * custom time zone identifier for the given custom id string.
+     * @param id a string of the form GMT[+-]hh:mm, GMT[+-]hhmm, or
+     * GMT[+-]hh.
+     * @param normalized Receives the normalized custom ID
+     * @param status Receives the status.  When the input ID string is invalid,
+     * U_ILLEGAL_ARGUMENT_ERROR is set.
+     * @return The normalized custom id string.
+    */
+    static UnicodeString& getCustomID(const UnicodeString& id, UnicodeString& normalized,
+        UErrorCode& status);
+
+    /**
+     * Returns the normalized custome timezone ID for the given offset fields.
+     * @param hour offset hours
+     * @param min offset minutes
+     * @param sec offset seconds
+     * @param netative sign of the offset, TRUE for negative offset.
+     * @param id Receves the format result (normalized custom ID)
+     * @return The reference to id
+     */
+    static UnicodeString& formatCustomID(int32_t hour, int32_t min, int32_t sec,
+        UBool negative, UnicodeString& id);
+
+    /**
+     * Responsible for setting up DEFAULT_ZONE.  Uses routines in TPlatformUtilities
+     * (i.e., platform-specific calls) to get the current system time zone.  Failing
+     * that, uses the platform-specific default time zone.  Failing that, uses GMT.
+     */
+    static void             initDefault(void);
+
+    // See source file for documentation
+    /**
+     * Lookup the given name in our system zone table.  If found,
+     * instantiate a new zone of that name and return it.  If not
+     * found, return 0.
+     * @param name tthe given name of a system time zone.
+     * @return the timezone indicated by the 'name'.
+     */
+    static TimeZone*        createSystemTimeZone(const UnicodeString& name);
+
+    UnicodeString           fID;    // this time zone's ID
+};
+
+
+// -------------------------------------
+
+inline UnicodeString&
+TimeZone::getID(UnicodeString& ID) const
+{
+    ID = fID;
+    return ID;
+}
+
+// -------------------------------------
+
+inline void
+TimeZone::setID(const UnicodeString& ID)
+{
+    fID = ID;
+}
+U_NAMESPACE_END
+
+#endif /* #if !UCONFIG_NO_FORMATTING */
+
+#endif //_TIMEZONE
+//eof


[03/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/test/mocha/mocha.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/test/mocha/mocha.js b/apps/fauxton/test/mocha/mocha.js
deleted file mode 100755
index a55115a..0000000
--- a/apps/fauxton/test/mocha/mocha.js
+++ /dev/null
@@ -1,5428 +0,0 @@
-;(function(){
-
-// CommonJS require()
-
-function require(p){
-    var path = require.resolve(p)
-      , mod = require.modules[path];
-    if (!mod) throw new Error('failed to require "' + p + '"');
-    if (!mod.exports) {
-      mod.exports = {};
-      mod.call(mod.exports, mod, mod.exports, require.relative(path));
-    }
-    return mod.exports;
-  }
-
-require.modules = {};
-
-require.resolve = function (path){
-    var orig = path
-      , reg = path + '.js'
-      , index = path + '/index.js';
-    return require.modules[reg] && reg
-      || require.modules[index] && index
-      || orig;
-  };
-
-require.register = function (path, fn){
-    require.modules[path] = fn;
-  };
-
-require.relative = function (parent) {
-    return function(p){
-      if ('.' != p.charAt(0)) return require(p);
-
-      var path = parent.split('/')
-        , segs = p.split('/');
-      path.pop();
-
-      for (var i = 0; i < segs.length; i++) {
-        var seg = segs[i];
-        if ('..' == seg) path.pop();
-        else if ('.' != seg) path.push(seg);
-      }
-
-      return require(path.join('/'));
-    };
-  };
-
-
-require.register("browser/debug.js", function(module, exports, require){
-
-module.exports = function(type){
-  return function(){
-  }
-};
-
-}); // module: browser/debug.js
-
-require.register("browser/diff.js", function(module, exports, require){
-/* See license.txt for terms of usage */
-
-/*
- * Text diff implementation.
- * 
- * This library supports the following APIS:
- * JsDiff.diffChars: Character by character diff
- * JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace
- * JsDiff.diffLines: Line based diff
- * 
- * JsDiff.diffCss: Diff targeted at CSS content
- * 
- * These methods are based on the implementation proposed in
- * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986).
- * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927
- */
-var JsDiff = (function() {
-  function clonePath(path) {
-    return { newPos: path.newPos, components: path.components.slice(0) };
-  }
-  function removeEmpty(array) {
-    var ret = [];
-    for (var i = 0; i < array.length; i++) {
-      if (array[i]) {
-        ret.push(array[i]);
-      }
-    }
-    return ret;
-  }
-  function escapeHTML(s) {
-    var n = s;
-    n = n.replace(/&/g, "&amp;");
-    n = n.replace(/</g, "&lt;");
-    n = n.replace(/>/g, "&gt;");
-    n = n.replace(/"/g, "&quot;");
-
-    return n;
-  }
-
-
-  var fbDiff = function(ignoreWhitespace) {
-    this.ignoreWhitespace = ignoreWhitespace;
-  };
-  fbDiff.prototype = {
-      diff: function(oldString, newString) {
-        // Handle the identity case (this is due to unrolling editLength == 0
-        if (newString == oldString) {
-          return [{ value: newString }];
-        }
-        if (!newString) {
-          return [{ value: oldString, removed: true }];
-        }
-        if (!oldString) {
-          return [{ value: newString, added: true }];
-        }
-
-        newString = this.tokenize(newString);
-        oldString = this.tokenize(oldString);
-
-        var newLen = newString.length, oldLen = oldString.length;
-        var maxEditLength = newLen + oldLen;
-        var bestPath = [{ newPos: -1, components: [] }];
-
-        // Seed editLength = 0
-        var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
-        if (bestPath[0].newPos+1 >= newLen && oldPos+1 >= oldLen) {
-          return bestPath[0].components;
-        }
-
-        for (var editLength = 1; editLength <= maxEditLength; editLength++) {
-          for (var diagonalPath = -1*editLength; diagonalPath <= editLength; diagonalPath+=2) {
-            var basePath;
-            var addPath = bestPath[diagonalPath-1],
-                removePath = bestPath[diagonalPath+1];
-            oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
-            if (addPath) {
-              // No one else is going to attempt to use this value, clear it
-              bestPath[diagonalPath-1] = undefined;
-            }
-
-            var canAdd = addPath && addPath.newPos+1 < newLen;
-            var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
-            if (!canAdd && !canRemove) {
-              bestPath[diagonalPath] = undefined;
-              continue;
-            }
-
-            // Select the diagonal that we want to branch from. We select the prior
-            // path whose position in the new string is the farthest from the origin
-            // and does not pass the bounds of the diff graph
-            if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
-              basePath = clonePath(removePath);
-              this.pushComponent(basePath.components, oldString[oldPos], undefined, true);
-            } else {
-              basePath = clonePath(addPath);
-              basePath.newPos++;
-              this.pushComponent(basePath.components, newString[basePath.newPos], true, undefined);
-            }
-
-            var oldPos = this.extractCommon(basePath, newString, oldString, diagonalPath);
-
-            if (basePath.newPos+1 >= newLen && oldPos+1 >= oldLen) {
-              return basePath.components;
-            } else {
-              bestPath[diagonalPath] = basePath;
-            }
-          }
-        }
-      },
-
-      pushComponent: function(components, value, added, removed) {
-        var last = components[components.length-1];
-        if (last && last.added === added && last.removed === removed) {
-          // We need to clone here as the component clone operation is just
-          // as shallow array clone
-          components[components.length-1] =
-            {value: this.join(last.value, value), added: added, removed: removed };
-        } else {
-          components.push({value: value, added: added, removed: removed });
-        }
-      },
-      extractCommon: function(basePath, newString, oldString, diagonalPath) {
-        var newLen = newString.length,
-            oldLen = oldString.length,
-            newPos = basePath.newPos,
-            oldPos = newPos - diagonalPath;
-        while (newPos+1 < newLen && oldPos+1 < oldLen && this.equals(newString[newPos+1], oldString[oldPos+1])) {
-          newPos++;
-          oldPos++;
-          
-          this.pushComponent(basePath.components, newString[newPos], undefined, undefined);
-        }
-        basePath.newPos = newPos;
-        return oldPos;
-      },
-
-      equals: function(left, right) {
-        var reWhitespace = /\S/;
-        if (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right)) {
-          return true;
-        } else {
-          return left == right;
-        }
-      },
-      join: function(left, right) {
-        return left + right;
-      },
-      tokenize: function(value) {
-        return value;
-      }
-  };
-  
-  var CharDiff = new fbDiff();
-  
-  var WordDiff = new fbDiff(true);
-  WordDiff.tokenize = function(value) {
-    return removeEmpty(value.split(/(\s+|\b)/));
-  };
-  
-  var CssDiff = new fbDiff(true);
-  CssDiff.tokenize = function(value) {
-    return removeEmpty(value.split(/([{}:;,]|\s+)/));
-  };
-  
-  var LineDiff = new fbDiff();
-  LineDiff.tokenize = function(value) {
-    return value.split(/^/m);
-  };
-  
-  return {
-    diffChars: function(oldStr, newStr) { return CharDiff.diff(oldStr, newStr); },
-    diffWords: function(oldStr, newStr) { return WordDiff.diff(oldStr, newStr); },
-    diffLines: function(oldStr, newStr) { return LineDiff.diff(oldStr, newStr); },
-
-    diffCss: function(oldStr, newStr) { return CssDiff.diff(oldStr, newStr); },
-
-    createPatch: function(fileName, oldStr, newStr, oldHeader, newHeader) {
-      var ret = [];
-
-      ret.push("Index: " + fileName);
-      ret.push("===================================================================");
-      ret.push("--- " + fileName + (typeof oldHeader === "undefined" ? "" : "\t" + oldHeader));
-      ret.push("+++ " + fileName + (typeof newHeader === "undefined" ? "" : "\t" + newHeader));
-
-      var diff = LineDiff.diff(oldStr, newStr);
-      if (!diff[diff.length-1].value) {
-        diff.pop();   // Remove trailing newline add
-      }
-      diff.push({value: "", lines: []});   // Append an empty value to make cleanup easier
-
-      function contextLines(lines) {
-        return lines.map(function(entry) { return ' ' + entry; });
-      }
-      function eofNL(curRange, i, current) {
-        var last = diff[diff.length-2],
-            isLast = i === diff.length-2,
-            isLastOfType = i === diff.length-3 && (current.added === !last.added || current.removed === !last.removed);
-
-        // Figure out if this is the last line for the given file and missing NL
-        if (!/\n$/.test(current.value) && (isLast || isLastOfType)) {
-          curRange.push('\\ No newline at end of file');
-        }
-      }
-
-      var oldRangeStart = 0, newRangeStart = 0, curRange = [],
-          oldLine = 1, newLine = 1;
-      for (var i = 0; i < diff.length; i++) {
-        var current = diff[i],
-            lines = current.lines || current.value.replace(/\n$/, "").split("\n");
-        current.lines = lines;
-
-        if (current.added || current.removed) {
-          if (!oldRangeStart) {
-            var prev = diff[i-1];
-            oldRangeStart = oldLine;
-            newRangeStart = newLine;
-            
-            if (prev) {
-              curRange = contextLines(prev.lines.slice(-4));
-              oldRangeStart -= curRange.length;
-              newRangeStart -= curRange.length;
-            }
-          }
-          curRange.push.apply(curRange, lines.map(function(entry) { return (current.added?"+":"-") + entry; }));
-          eofNL(curRange, i, current);
-
-          if (current.added) {
-            newLine += lines.length;
-          } else {
-            oldLine += lines.length;
-          }
-        } else {
-          if (oldRangeStart) {
-            // Close out any changes that have been output (or join overlapping)
-            if (lines.length <= 8 && i < diff.length-2) {
-              // Overlapping
-              curRange.push.apply(curRange, contextLines(lines));
-            } else {
-              // end the range and output
-              var contextSize = Math.min(lines.length, 4);
-              ret.push(
-                  "@@ -" + oldRangeStart + "," + (oldLine-oldRangeStart+contextSize)
-                  + " +" + newRangeStart + "," + (newLine-newRangeStart+contextSize)
-                  + " @@");
-              ret.push.apply(ret, curRange);
-              ret.push.apply(ret, contextLines(lines.slice(0, contextSize)));
-              if (lines.length <= 4) {
-                eofNL(ret, i, current);
-              }
-
-              oldRangeStart = 0;  newRangeStart = 0; curRange = [];
-            }
-          }
-          oldLine += lines.length;
-          newLine += lines.length;
-        }
-      }
-
-      return ret.join('\n') + '\n';
-    },
-
-    convertChangesToXML: function(changes){
-      var ret = [];
-      for ( var i = 0; i < changes.length; i++) {
-        var change = changes[i];
-        if (change.added) {
-          ret.push("<ins>");
-        } else if (change.removed) {
-          ret.push("<del>");
-        }
-
-        ret.push(escapeHTML(change.value));
-
-        if (change.added) {
-          ret.push("</ins>");
-        } else if (change.removed) {
-          ret.push("</del>");
-        }
-      }
-      return ret.join("");
-    }
-  };
-})();
-
-if (typeof module !== "undefined") {
-    module.exports = JsDiff;
-}
-
-}); // module: browser/diff.js
-
-require.register("browser/events.js", function(module, exports, require){
-
-/**
- * Module exports.
- */
-
-exports.EventEmitter = EventEmitter;
-
-/**
- * Check if `obj` is an array.
- */
-
-function isArray(obj) {
-  return '[object Array]' == {}.toString.call(obj);
-}
-
-/**
- * Event emitter constructor.
- *
- * @api public
- */
-
-function EventEmitter(){};
-
-/**
- * Adds a listener.
- *
- * @api public
- */
-
-EventEmitter.prototype.on = function (name, fn) {
-  if (!this.$events) {
-    this.$events = {};
-  }
-
-  if (!this.$events[name]) {
-    this.$events[name] = fn;
-  } else if (isArray(this.$events[name])) {
-    this.$events[name].push(fn);
-  } else {
-    this.$events[name] = [this.$events[name], fn];
-  }
-
-  return this;
-};
-
-EventEmitter.prototype.addListener = EventEmitter.prototype.on;
-
-/**
- * Adds a volatile listener.
- *
- * @api public
- */
-
-EventEmitter.prototype.once = function (name, fn) {
-  var self = this;
-
-  function on () {
-    self.removeListener(name, on);
-    fn.apply(this, arguments);
-  };
-
-  on.listener = fn;
-  this.on(name, on);
-
-  return this;
-};
-
-/**
- * Removes a listener.
- *
- * @api public
- */
-
-EventEmitter.prototype.removeListener = function (name, fn) {
-  if (this.$events && this.$events[name]) {
-    var list = this.$events[name];
-
-    if (isArray(list)) {
-      var pos = -1;
-
-      for (var i = 0, l = list.length; i < l; i++) {
-        if (list[i] === fn || (list[i].listener && list[i].listener === fn)) {
-          pos = i;
-          break;
-        }
-      }
-
-      if (pos < 0) {
-        return this;
-      }
-
-      list.splice(pos, 1);
-
-      if (!list.length) {
-        delete this.$events[name];
-      }
-    } else if (list === fn || (list.listener && list.listener === fn)) {
-      delete this.$events[name];
-    }
-  }
-
-  return this;
-};
-
-/**
- * Removes all listeners for an event.
- *
- * @api public
- */
-
-EventEmitter.prototype.removeAllListeners = function (name) {
-  if (name === undefined) {
-    this.$events = {};
-    return this;
-  }
-
-  if (this.$events && this.$events[name]) {
-    this.$events[name] = null;
-  }
-
-  return this;
-};
-
-/**
- * Gets all listeners for a certain event.
- *
- * @api public
- */
-
-EventEmitter.prototype.listeners = function (name) {
-  if (!this.$events) {
-    this.$events = {};
-  }
-
-  if (!this.$events[name]) {
-    this.$events[name] = [];
-  }
-
-  if (!isArray(this.$events[name])) {
-    this.$events[name] = [this.$events[name]];
-  }
-
-  return this.$events[name];
-};
-
-/**
- * Emits an event.
- *
- * @api public
- */
-
-EventEmitter.prototype.emit = function (name) {
-  if (!this.$events) {
-    return false;
-  }
-
-  var handler = this.$events[name];
-
-  if (!handler) {
-    return false;
-  }
-
-  var args = [].slice.call(arguments, 1);
-
-  if ('function' == typeof handler) {
-    handler.apply(this, args);
-  } else if (isArray(handler)) {
-    var listeners = handler.slice();
-
-    for (var i = 0, l = listeners.length; i < l; i++) {
-      listeners[i].apply(this, args);
-    }
-  } else {
-    return false;
-  }
-
-  return true;
-};
-}); // module: browser/events.js
-
-require.register("browser/fs.js", function(module, exports, require){
-
-}); // module: browser/fs.js
-
-require.register("browser/path.js", function(module, exports, require){
-
-}); // module: browser/path.js
-
-require.register("browser/progress.js", function(module, exports, require){
-
-/**
- * Expose `Progress`.
- */
-
-module.exports = Progress;
-
-/**
- * Initialize a new `Progress` indicator.
- */
-
-function Progress() {
-  this.percent = 0;
-  this.size(0);
-  this.fontSize(11);
-  this.font('helvetica, arial, sans-serif');
-}
-
-/**
- * Set progress size to `n`.
- *
- * @param {Number} n
- * @return {Progress} for chaining
- * @api public
- */
-
-Progress.prototype.size = function(n){
-  this._size = n;
-  return this;
-};
-
-/**
- * Set text to `str`.
- *
- * @param {String} str
- * @return {Progress} for chaining
- * @api public
- */
-
-Progress.prototype.text = function(str){
-  this._text = str;
-  return this;
-};
-
-/**
- * Set font size to `n`.
- *
- * @param {Number} n
- * @return {Progress} for chaining
- * @api public
- */
-
-Progress.prototype.fontSize = function(n){
-  this._fontSize = n;
-  return this;
-};
-
-/**
- * Set font `family`.
- *
- * @param {String} family
- * @return {Progress} for chaining
- */
-
-Progress.prototype.font = function(family){
-  this._font = family;
-  return this;
-};
-
-/**
- * Update percentage to `n`.
- *
- * @param {Number} n
- * @return {Progress} for chaining
- */
-
-Progress.prototype.update = function(n){
-  this.percent = n;
-  return this;
-};
-
-/**
- * Draw on `ctx`.
- *
- * @param {CanvasRenderingContext2d} ctx
- * @return {Progress} for chaining
- */
-
-Progress.prototype.draw = function(ctx){
-  var percent = Math.min(this.percent, 100)
-    , size = this._size
-    , half = size / 2
-    , x = half
-    , y = half
-    , rad = half - 1
-    , fontSize = this._fontSize;
-
-  ctx.font = fontSize + 'px ' + this._font;
-
-  var angle = Math.PI * 2 * (percent / 100);
-  ctx.clearRect(0, 0, size, size);
-
-  // outer circle
-  ctx.strokeStyle = '#9f9f9f';
-  ctx.beginPath();
-  ctx.arc(x, y, rad, 0, angle, false);
-  ctx.stroke();
-
-  // inner circle
-  ctx.strokeStyle = '#eee';
-  ctx.beginPath();
-  ctx.arc(x, y, rad - 1, 0, angle, true);
-  ctx.stroke();
-
-  // text
-  var text = this._text || (percent | 0) + '%'
-    , w = ctx.measureText(text).width;
-
-  ctx.fillText(
-      text
-    , x - w / 2 + 1
-    , y + fontSize / 2 - 1);
-
-  return this;
-};
-
-}); // module: browser/progress.js
-
-require.register("browser/tty.js", function(module, exports, require){
-
-exports.isatty = function(){
-  return true;
-};
-
-exports.getWindowSize = function(){
-  if ('innerHeight' in global) {
-    return [global.innerHeight, global.innerWidth];
-  } else {
-    // In a Web Worker, the DOM Window is not available.
-    return [640, 480];
-  }
-};
-
-}); // module: browser/tty.js
-
-require.register("context.js", function(module, exports, require){
-
-/**
- * Expose `Context`.
- */
-
-module.exports = Context;
-
-/**
- * Initialize a new `Context`.
- *
- * @api private
- */
-
-function Context(){}
-
-/**
- * Set or get the context `Runnable` to `runnable`.
- *
- * @param {Runnable} runnable
- * @return {Context}
- * @api private
- */
-
-Context.prototype.runnable = function(runnable){
-  if (0 == arguments.length) return this._runnable;
-  this.test = this._runnable = runnable;
-  return this;
-};
-
-/**
- * Set test timeout `ms`.
- *
- * @param {Number} ms
- * @return {Context} self
- * @api private
- */
-
-Context.prototype.timeout = function(ms){
-  this.runnable().timeout(ms);
-  return this;
-};
-
-/**
- * Set test slowness threshold `ms`.
- *
- * @param {Number} ms
- * @return {Context} self
- * @api private
- */
-
-Context.prototype.slow = function(ms){
-  this.runnable().slow(ms);
-  return this;
-};
-
-/**
- * Inspect the context void of `._runnable`.
- *
- * @return {String}
- * @api private
- */
-
-Context.prototype.inspect = function(){
-  return JSON.stringify(this, function(key, val){
-    if ('_runnable' == key) return;
-    if ('test' == key) return;
-    return val;
-  }, 2);
-};
-
-}); // module: context.js
-
-require.register("hook.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var Runnable = require('./runnable');
-
-/**
- * Expose `Hook`.
- */
-
-module.exports = Hook;
-
-/**
- * Initialize a new `Hook` with the given `title` and callback `fn`.
- *
- * @param {String} title
- * @param {Function} fn
- * @api private
- */
-
-function Hook(title, fn) {
-  Runnable.call(this, title, fn);
-  this.type = 'hook';
-}
-
-/**
- * Inherit from `Runnable.prototype`.
- */
-
-function F(){};
-F.prototype = Runnable.prototype;
-Hook.prototype = new F;
-Hook.prototype.constructor = Hook;
-
-
-/**
- * Get or set the test `err`.
- *
- * @param {Error} err
- * @return {Error}
- * @api public
- */
-
-Hook.prototype.error = function(err){
-  if (0 == arguments.length) {
-    var err = this._error;
-    this._error = null;
-    return err;
-  }
-
-  this._error = err;
-};
-
-}); // module: hook.js
-
-require.register("interfaces/bdd.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var Suite = require('../suite')
-  , Test = require('../test');
-
-/**
- * BDD-style interface:
- *
- *      describe('Array', function(){
- *        describe('#indexOf()', function(){
- *          it('should return -1 when not present', function(){
- *
- *          });
- *
- *          it('should return the index when present', function(){
- *
- *          });
- *        });
- *      });
- *
- */
-
-module.exports = function(suite){
-  var suites = [suite];
-
-  suite.on('pre-require', function(context, file, mocha){
-
-    /**
-     * Execute before running tests.
-     */
-
-    context.before = function(fn){
-      suites[0].beforeAll(fn);
-    };
-
-    /**
-     * Execute after running tests.
-     */
-
-    context.after = function(fn){
-      suites[0].afterAll(fn);
-    };
-
-    /**
-     * Execute before each test case.
-     */
-
-    context.beforeEach = function(fn){
-      suites[0].beforeEach(fn);
-    };
-
-    /**
-     * Execute after each test case.
-     */
-
-    context.afterEach = function(fn){
-      suites[0].afterEach(fn);
-    };
-
-    /**
-     * Describe a "suite" with the given `title`
-     * and callback `fn` containing nested suites
-     * and/or tests.
-     */
-
-    context.describe = context.context = function(title, fn){
-      var suite = Suite.create(suites[0], title);
-      suites.unshift(suite);
-      fn.call(suite);
-      suites.shift();
-      return suite;
-    };
-
-    /**
-     * Pending describe.
-     */
-
-    context.xdescribe =
-    context.xcontext =
-    context.describe.skip = function(title, fn){
-      var suite = Suite.create(suites[0], title);
-      suite.pending = true;
-      suites.unshift(suite);
-      fn.call(suite);
-      suites.shift();
-    };
-
-    /**
-     * Exclusive suite.
-     */
-
-    context.describe.only = function(title, fn){
-      var suite = context.describe(title, fn);
-      mocha.grep(suite.fullTitle());
-    };
-
-    /**
-     * Describe a specification or test-case
-     * with the given `title` and callback `fn`
-     * acting as a thunk.
-     */
-
-    context.it = context.specify = function(title, fn){
-      var suite = suites[0];
-      if (suite.pending) var fn = null;
-      var test = new Test(title, fn);
-      suite.addTest(test);
-      return test;
-    };
-
-    /**
-     * Exclusive test-case.
-     */
-
-    context.it.only = function(title, fn){
-      var test = context.it(title, fn);
-      mocha.grep(test.fullTitle());
-    };
-
-    /**
-     * Pending test case.
-     */
-
-    context.xit =
-    context.xspecify =
-    context.it.skip = function(title){
-      context.it(title);
-    };
-  });
-};
-
-}); // module: interfaces/bdd.js
-
-require.register("interfaces/exports.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var Suite = require('../suite')
-  , Test = require('../test');
-
-/**
- * TDD-style interface:
- *
- *     exports.Array = {
- *       '#indexOf()': {
- *         'should return -1 when the value is not present': function(){
- *
- *         },
- *
- *         'should return the correct index when the value is present': function(){
- *
- *         }
- *       }
- *     };
- *
- */
-
-module.exports = function(suite){
-  var suites = [suite];
-
-  suite.on('require', visit);
-
-  function visit(obj) {
-    var suite;
-    for (var key in obj) {
-      if ('function' == typeof obj[key]) {
-        var fn = obj[key];
-        switch (key) {
-          case 'before':
-            suites[0].beforeAll(fn);
-            break;
-          case 'after':
-            suites[0].afterAll(fn);
-            break;
-          case 'beforeEach':
-            suites[0].beforeEach(fn);
-            break;
-          case 'afterEach':
-            suites[0].afterEach(fn);
-            break;
-          default:
-            suites[0].addTest(new Test(key, fn));
-        }
-      } else {
-        var suite = Suite.create(suites[0], key);
-        suites.unshift(suite);
-        visit(obj[key]);
-        suites.shift();
-      }
-    }
-  }
-};
-
-}); // module: interfaces/exports.js
-
-require.register("interfaces/index.js", function(module, exports, require){
-
-exports.bdd = require('./bdd');
-exports.tdd = require('./tdd');
-exports.qunit = require('./qunit');
-exports.exports = require('./exports');
-
-}); // module: interfaces/index.js
-
-require.register("interfaces/qunit.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var Suite = require('../suite')
-  , Test = require('../test');
-
-/**
- * QUnit-style interface:
- *
- *     suite('Array');
- *
- *     test('#length', function(){
- *       var arr = [1,2,3];
- *       ok(arr.length == 3);
- *     });
- *
- *     test('#indexOf()', function(){
- *       var arr = [1,2,3];
- *       ok(arr.indexOf(1) == 0);
- *       ok(arr.indexOf(2) == 1);
- *       ok(arr.indexOf(3) == 2);
- *     });
- *
- *     suite('String');
- *
- *     test('#length', function(){
- *       ok('foo'.length == 3);
- *     });
- *
- */
-
-module.exports = function(suite){
-  var suites = [suite];
-
-  suite.on('pre-require', function(context, file, mocha){
-
-    /**
-     * Execute before running tests.
-     */
-
-    context.before = function(fn){
-      suites[0].beforeAll(fn);
-    };
-
-    /**
-     * Execute after running tests.
-     */
-
-    context.after = function(fn){
-      suites[0].afterAll(fn);
-    };
-
-    /**
-     * Execute before each test case.
-     */
-
-    context.beforeEach = function(fn){
-      suites[0].beforeEach(fn);
-    };
-
-    /**
-     * Execute after each test case.
-     */
-
-    context.afterEach = function(fn){
-      suites[0].afterEach(fn);
-    };
-
-    /**
-     * Describe a "suite" with the given `title`.
-     */
-
-    context.suite = function(title){
-      if (suites.length > 1) suites.shift();
-      var suite = Suite.create(suites[0], title);
-      suites.unshift(suite);
-      return suite;
-    };
-
-    /**
-     * Exclusive test-case.
-     */
-
-    context.suite.only = function(title, fn){
-      var suite = context.suite(title, fn);
-      mocha.grep(suite.fullTitle());
-    };
-
-    /**
-     * Describe a specification or test-case
-     * with the given `title` and callback `fn`
-     * acting as a thunk.
-     */
-
-    context.test = function(title, fn){
-      var test = new Test(title, fn);
-      suites[0].addTest(test);
-      return test;
-    };
-
-    /**
-     * Exclusive test-case.
-     */
-
-    context.test.only = function(title, fn){
-      var test = context.test(title, fn);
-      mocha.grep(test.fullTitle());
-    };
-
-    /**
-     * Pending test case.
-     */
-
-    context.test.skip = function(title){
-      context.test(title);
-    };
-  });
-};
-
-}); // module: interfaces/qunit.js
-
-require.register("interfaces/tdd.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var Suite = require('../suite')
-  , Test = require('../test');
-
-/**
- * TDD-style interface:
- *
- *      suite('Array', function(){
- *        suite('#indexOf()', function(){
- *          suiteSetup(function(){
- *
- *          });
- *
- *          test('should return -1 when not present', function(){
- *
- *          });
- *
- *          test('should return the index when present', function(){
- *
- *          });
- *
- *          suiteTeardown(function(){
- *
- *          });
- *        });
- *      });
- *
- */
-
-module.exports = function(suite){
-  var suites = [suite];
-
-  suite.on('pre-require', function(context, file, mocha){
-
-    /**
-     * Execute before each test case.
-     */
-
-    context.setup = function(fn){
-      suites[0].beforeEach(fn);
-    };
-
-    /**
-     * Execute after each test case.
-     */
-
-    context.teardown = function(fn){
-      suites[0].afterEach(fn);
-    };
-
-    /**
-     * Execute before the suite.
-     */
-
-    context.suiteSetup = function(fn){
-      suites[0].beforeAll(fn);
-    };
-
-    /**
-     * Execute after the suite.
-     */
-
-    context.suiteTeardown = function(fn){
-      suites[0].afterAll(fn);
-    };
-
-    /**
-     * Describe a "suite" with the given `title`
-     * and callback `fn` containing nested suites
-     * and/or tests.
-     */
-
-    context.suite = function(title, fn){
-      var suite = Suite.create(suites[0], title);
-      suites.unshift(suite);
-      fn.call(suite);
-      suites.shift();
-      return suite;
-    };
-
-    /**
-     * Pending suite.
-     */
-    context.suite.skip = function(title, fn) {
-      var suite = Suite.create(suites[0], title);
-      suite.pending = true;
-      suites.unshift(suite);
-      fn.call(suite);
-      suites.shift();
-    };
-
-    /**
-     * Exclusive test-case.
-     */
-
-    context.suite.only = function(title, fn){
-      var suite = context.suite(title, fn);
-      mocha.grep(suite.fullTitle());
-    };
-
-    /**
-     * Describe a specification or test-case
-     * with the given `title` and callback `fn`
-     * acting as a thunk.
-     */
-
-    context.test = function(title, fn){
-      var suite = suites[0];
-      if (suite.pending) var fn = null;
-      var test = new Test(title, fn);
-      suite.addTest(test);
-      return test;
-    };
-
-    /**
-     * Exclusive test-case.
-     */
-
-    context.test.only = function(title, fn){
-      var test = context.test(title, fn);
-      mocha.grep(test.fullTitle());
-    };
-
-    /**
-     * Pending test case.
-     */
-
-    context.test.skip = function(title){
-      context.test(title);
-    };
-  });
-};
-
-}); // module: interfaces/tdd.js
-
-require.register("mocha.js", function(module, exports, require){
-/*!
- * mocha
- * Copyright(c) 2011 TJ Holowaychuk <tj...@vision-media.ca>
- * MIT Licensed
- */
-
-/**
- * Module dependencies.
- */
-
-var path = require('browser/path')
-  , utils = require('./utils');
-
-/**
- * Expose `Mocha`.
- */
-
-exports = module.exports = Mocha;
-
-/**
- * Expose internals.
- */
-
-exports.utils = utils;
-exports.interfaces = require('./interfaces');
-exports.reporters = require('./reporters');
-exports.Runnable = require('./runnable');
-exports.Context = require('./context');
-exports.Runner = require('./runner');
-exports.Suite = require('./suite');
-exports.Hook = require('./hook');
-exports.Test = require('./test');
-
-/**
- * Return image `name` path.
- *
- * @param {String} name
- * @return {String}
- * @api private
- */
-
-function image(name) {
-  return __dirname + '/../images/' + name + '.png';
-}
-
-/**
- * Setup mocha with `options`.
- *
- * Options:
- *
- *   - `ui` name "bdd", "tdd", "exports" etc
- *   - `reporter` reporter instance, defaults to `mocha.reporters.Dot`
- *   - `globals` array of accepted globals
- *   - `timeout` timeout in milliseconds
- *   - `bail` bail on the first test failure
- *   - `slow` milliseconds to wait before considering a test slow
- *   - `ignoreLeaks` ignore global leaks
- *   - `grep` string or regexp to filter tests with
- *
- * @param {Object} options
- * @api public
- */
-
-function Mocha(options) {
-  options = options || {};
-  this.files = [];
-  this.options = options;
-  this.grep(options.grep);
-  this.suite = new exports.Suite('', new exports.Context);
-  this.ui(options.ui);
-  this.bail(options.bail);
-  this.reporter(options.reporter);
-  if (options.timeout) this.timeout(options.timeout);
-  if (options.slow) this.slow(options.slow);
-}
-
-/**
- * Enable or disable bailing on the first failure.
- *
- * @param {Boolean} [bail]
- * @api public
- */
-
-Mocha.prototype.bail = function(bail){
-  if (0 == arguments.length) bail = true;
-  this.suite.bail(bail);
-  return this;
-};
-
-/**
- * Add test `file`.
- *
- * @param {String} file
- * @api public
- */
-
-Mocha.prototype.addFile = function(file){
-  this.files.push(file);
-  return this;
-};
-
-/**
- * Set reporter to `reporter`, defaults to "dot".
- *
- * @param {String|Function} reporter name or constructor
- * @api public
- */
-
-Mocha.prototype.reporter = function(reporter){
-  if ('function' == typeof reporter) {
-    this._reporter = reporter;
-  } else {
-    reporter = reporter || 'dot';
-    try {
-      this._reporter = require('./reporters/' + reporter);
-    } catch (err) {
-      this._reporter = require(reporter);
-    }
-    if (!this._reporter) throw new Error('invalid reporter "' + reporter + '"');
-  }
-  return this;
-};
-
-/**
- * Set test UI `name`, defaults to "bdd".
- *
- * @param {String} bdd
- * @api public
- */
-
-Mocha.prototype.ui = function(name){
-  name = name || 'bdd';
-  this._ui = exports.interfaces[name];
-  if (!this._ui) throw new Error('invalid interface "' + name + '"');
-  this._ui = this._ui(this.suite);
-  return this;
-};
-
-/**
- * Load registered files.
- *
- * @api private
- */
-
-Mocha.prototype.loadFiles = function(fn){
-  var self = this;
-  var suite = this.suite;
-  var pending = this.files.length;
-  this.files.forEach(function(file){
-    file = path.resolve(file);
-    suite.emit('pre-require', global, file, self);
-    suite.emit('require', require(file), file, self);
-    suite.emit('post-require', global, file, self);
-    --pending || (fn && fn());
-  });
-};
-
-/**
- * Enable growl support.
- *
- * @api private
- */
-
-Mocha.prototype._growl = function(runner, reporter) {
-  var notify = require('growl');
-
-  runner.on('end', function(){
-    var stats = reporter.stats;
-    if (stats.failures) {
-      var msg = stats.failures + ' of ' + runner.total + ' tests failed';
-      notify(msg, { name: 'mocha', title: 'Failed', image: image('error') });
-    } else {
-      notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', {
-          name: 'mocha'
-        , title: 'Passed'
-        , image: image('ok')
-      });
-    }
-  });
-};
-
-/**
- * Add regexp to grep, if `re` is a string it is escaped.
- *
- * @param {RegExp|String} re
- * @return {Mocha}
- * @api public
- */
-
-Mocha.prototype.grep = function(re){
-  this.options.grep = 'string' == typeof re
-    ? new RegExp(utils.escapeRegexp(re))
-    : re;
-  return this;
-};
-
-/**
- * Invert `.grep()` matches.
- *
- * @return {Mocha}
- * @api public
- */
-
-Mocha.prototype.invert = function(){
-  this.options.invert = true;
-  return this;
-};
-
-/**
- * Ignore global leaks.
- *
- * @param {Boolean} ignore
- * @return {Mocha}
- * @api public
- */
-
-Mocha.prototype.ignoreLeaks = function(ignore){
-  this.options.ignoreLeaks = !!ignore;
-  return this;
-};
-
-/**
- * Enable global leak checking.
- *
- * @return {Mocha}
- * @api public
- */
-
-Mocha.prototype.checkLeaks = function(){
-  this.options.ignoreLeaks = false;
-  return this;
-};
-
-/**
- * Enable growl support.
- *
- * @return {Mocha}
- * @api public
- */
-
-Mocha.prototype.growl = function(){
-  this.options.growl = true;
-  return this;
-};
-
-/**
- * Ignore `globals` array or string.
- *
- * @param {Array|String} globals
- * @return {Mocha}
- * @api public
- */
-
-Mocha.prototype.globals = function(globals){
-  this.options.globals = (this.options.globals || []).concat(globals);
-  return this;
-};
-
-/**
- * Set the timeout in milliseconds.
- *
- * @param {Number} timeout
- * @return {Mocha}
- * @api public
- */
-
-Mocha.prototype.timeout = function(timeout){
-  this.suite.timeout(timeout);
-  return this;
-};
-
-/**
- * Set slowness threshold in milliseconds.
- *
- * @param {Number} slow
- * @return {Mocha}
- * @api public
- */
-
-Mocha.prototype.slow = function(slow){
-  this.suite.slow(slow);
-  return this;
-};
-
-/**
- * Makes all tests async (accepting a callback)
- *
- * @return {Mocha}
- * @api public
- */
-
-Mocha.prototype.asyncOnly = function(){
-  this.options.asyncOnly = true;
-  return this;
-};
-
-/**
- * Run tests and invoke `fn()` when complete.
- *
- * @param {Function} fn
- * @return {Runner}
- * @api public
- */
-
-Mocha.prototype.run = function(fn){
-  if (this.files.length) this.loadFiles();
-  var suite = this.suite;
-  var options = this.options;
-  var runner = new exports.Runner(suite);
-  var reporter = new this._reporter(runner);
-  runner.ignoreLeaks = false !== options.ignoreLeaks;
-  runner.asyncOnly = options.asyncOnly;
-  if (options.grep) runner.grep(options.grep, options.invert);
-  if (options.globals) runner.globals(options.globals);
-  if (options.growl) this._growl(runner, reporter);
-  return runner.run(fn);
-};
-
-}); // module: mocha.js
-
-require.register("ms.js", function(module, exports, require){
-
-/**
- * Helpers.
- */
-
-var s = 1000;
-var m = s * 60;
-var h = m * 60;
-var d = h * 24;
-
-/**
- * Parse or format the given `val`.
- *
- * @param {String|Number} val
- * @return {String|Number}
- * @api public
- */
-
-module.exports = function(val){
-  if ('string' == typeof val) return parse(val);
-  return format(val);
-}
-
-/**
- * Parse the given `str` and return milliseconds.
- *
- * @param {String} str
- * @return {Number}
- * @api private
- */
-
-function parse(str) {
-  var m = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str);
-  if (!m) return;
-  var n = parseFloat(m[1]);
-  var type = (m[2] || 'ms').toLowerCase();
-  switch (type) {
-    case 'years':
-    case 'year':
-    case 'y':
-      return n * 31557600000;
-    case 'days':
-    case 'day':
-    case 'd':
-      return n * 86400000;
-    case 'hours':
-    case 'hour':
-    case 'h':
-      return n * 3600000;
-    case 'minutes':
-    case 'minute':
-    case 'm':
-      return n * 60000;
-    case 'seconds':
-    case 'second':
-    case 's':
-      return n * 1000;
-    case 'ms':
-      return n;
-  }
-}
-
-/**
- * Format the given `ms`.
- *
- * @param {Number} ms
- * @return {String}
- * @api public
- */
-
-function format(ms) {
-  if (ms == d) return Math.round(ms / d) + ' day';
-  if (ms > d) return Math.round(ms / d) + ' days';
-  if (ms == h) return Math.round(ms / h) + ' hour';
-  if (ms > h) return Math.round(ms / h) + ' hours';
-  if (ms == m) return Math.round(ms / m) + ' minute';
-  if (ms > m) return Math.round(ms / m) + ' minutes';
-  if (ms == s) return Math.round(ms / s) + ' second';
-  if (ms > s) return Math.round(ms / s) + ' seconds';
-  return ms + ' ms';
-}
-}); // module: ms.js
-
-require.register("reporters/base.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var tty = require('browser/tty')
-  , diff = require('browser/diff')
-  , ms = require('../ms');
-
-/**
- * Save timer references to avoid Sinon interfering (see GH-237).
- */
-
-var Date = global.Date
-  , setTimeout = global.setTimeout
-  , setInterval = global.setInterval
-  , clearTimeout = global.clearTimeout
-  , clearInterval = global.clearInterval;
-
-/**
- * Check if both stdio streams are associated with a tty.
- */
-
-var isatty = tty.isatty(1) && tty.isatty(2);
-
-/**
- * Expose `Base`.
- */
-
-exports = module.exports = Base;
-
-/**
- * Enable coloring by default.
- */
-
-exports.useColors = isatty;
-
-/**
- * Default color map.
- */
-
-exports.colors = {
-    'pass': 90
-  , 'fail': 31
-  , 'bright pass': 92
-  , 'bright fail': 91
-  , 'bright yellow': 93
-  , 'pending': 36
-  , 'suite': 0
-  , 'error title': 0
-  , 'error message': 31
-  , 'error stack': 90
-  , 'checkmark': 32
-  , 'fast': 90
-  , 'medium': 33
-  , 'slow': 31
-  , 'green': 32
-  , 'light': 90
-  , 'diff gutter': 90
-  , 'diff added': 42
-  , 'diff removed': 41
-};
-
-/**
- * Default symbol map.
- */
-
-exports.symbols = {
-  ok: '✓',
-  err: '✖',
-  dot: '․'
-};
-
-// With node.js on Windows: use symbols available in terminal default fonts
-if ('win32' == process.platform) {
-  exports.symbols.ok = '\u221A';
-  exports.symbols.err = '\u00D7';
-  exports.symbols.dot = '.';
-}
-
-/**
- * Color `str` with the given `type`,
- * allowing colors to be disabled,
- * as well as user-defined color
- * schemes.
- *
- * @param {String} type
- * @param {String} str
- * @return {String}
- * @api private
- */
-
-var color = exports.color = function(type, str) {
-  if (!exports.useColors) return str;
-  return '\u001b[' + exports.colors[type] + 'm' + str + '\u001b[0m';
-};
-
-/**
- * Expose term window size, with some
- * defaults for when stderr is not a tty.
- */
-
-exports.window = {
-  width: isatty
-    ? process.stdout.getWindowSize
-      ? process.stdout.getWindowSize(1)[0]
-      : tty.getWindowSize()[1]
-    : 75
-};
-
-/**
- * Expose some basic cursor interactions
- * that are common among reporters.
- */
-
-exports.cursor = {
-  hide: function(){
-    process.stdout.write('\u001b[?25l');
-  },
-
-  show: function(){
-    process.stdout.write('\u001b[?25h');
-  },
-
-  deleteLine: function(){
-    process.stdout.write('\u001b[2K');
-  },
-
-  beginningOfLine: function(){
-    process.stdout.write('\u001b[0G');
-  },
-
-  CR: function(){
-    exports.cursor.deleteLine();
-    exports.cursor.beginningOfLine();
-  }
-};
-
-/**
- * Outut the given `failures` as a list.
- *
- * @param {Array} failures
- * @api public
- */
-
-exports.list = function(failures){
-  console.error();
-  failures.forEach(function(test, i){
-    // format
-    var fmt = color('error title', '  %s) %s:\n')
-      + color('error message', '     %s')
-      + color('error stack', '\n%s\n');
-
-    // msg
-    var err = test.err
-      , message = err.message || ''
-      , stack = err.stack || message
-      , index = stack.indexOf(message) + message.length
-      , msg = stack.slice(0, index)
-      , actual = err.actual
-      , expected = err.expected
-      , escape = true;
-
-    // uncaught
-    if (err.uncaught) {
-      msg = 'Uncaught ' + msg;
-    }
-
-    // explicitly show diff
-    if (err.showDiff && sameType(actual, expected)) {
-      escape = false;
-      err.actual = actual = stringify(actual);
-      err.expected = expected = stringify(expected);
-    }
-
-    // actual / expected diff
-    if ('string' == typeof actual && 'string' == typeof expected) {
-      msg = errorDiff(err, 'Words', escape);
-
-      // linenos
-      var lines = msg.split('\n');
-      if (lines.length > 4) {
-        var width = String(lines.length).length;
-        msg = lines.map(function(str, i){
-          return pad(++i, width) + ' |' + ' ' + str;
-        }).join('\n');
-      }
-
-      // legend
-      msg = '\n'
-        + color('diff removed', 'actual')
-        + ' '
-        + color('diff added', 'expected')
-        + '\n\n'
-        + msg
-        + '\n';
-
-      // indent
-      msg = msg.replace(/^/gm, '      ');
-
-      fmt = color('error title', '  %s) %s:\n%s')
-        + color('error stack', '\n%s\n');
-    }
-
-    // indent stack trace without msg
-    stack = stack.slice(index ? index + 1 : index)
-      .replace(/^/gm, '  ');
-
-    console.error(fmt, (i + 1), test.fullTitle(), msg, stack);
-  });
-};
-
-/**
- * Initialize a new `Base` reporter.
- *
- * All other reporters generally
- * inherit from this reporter, providing
- * stats such as test duration, number
- * of tests passed / failed etc.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function Base(runner) {
-  var self = this
-    , stats = this.stats = { suites: 0, tests: 0, passes: 0, pending: 0, failures: 0 }
-    , failures = this.failures = [];
-
-  if (!runner) return;
-  this.runner = runner;
-
-  runner.stats = stats;
-
-  runner.on('start', function(){
-    stats.start = new Date;
-  });
-
-  runner.on('suite', function(suite){
-    stats.suites = stats.suites || 0;
-    suite.root || stats.suites++;
-  });
-
-  runner.on('test end', function(test){
-    stats.tests = stats.tests || 0;
-    stats.tests++;
-  });
-
-  runner.on('pass', function(test){
-    stats.passes = stats.passes || 0;
-
-    var medium = test.slow() / 2;
-    test.speed = test.duration > test.slow()
-      ? 'slow'
-      : test.duration > medium
-        ? 'medium'
-        : 'fast';
-
-    stats.passes++;
-  });
-
-  runner.on('fail', function(test, err){
-    stats.failures = stats.failures || 0;
-    stats.failures++;
-    test.err = err;
-    failures.push(test);
-  });
-
-  runner.on('end', function(){
-    stats.end = new Date;
-    stats.duration = new Date - stats.start;
-  });
-
-  runner.on('pending', function(){
-    stats.pending++;
-  });
-}
-
-/**
- * Output common epilogue used by many of
- * the bundled reporters.
- *
- * @api public
- */
-
-Base.prototype.epilogue = function(){
-  var stats = this.stats;
-  var tests;
-  var fmt;
-
-  console.log();
-
-  // passes
-  fmt = color('bright pass', ' ')
-    + color('green', ' %d passing')
-    + color('light', ' (%s)');
-
-  console.log(fmt,
-    stats.passes || 0,
-    ms(stats.duration));
-
-  // pending
-  if (stats.pending) {
-    fmt = color('pending', ' ')
-      + color('pending', ' %d pending');
-
-    console.log(fmt, stats.pending);
-  }
-
-  // failures
-  if (stats.failures) {
-    fmt = color('fail', '  %d failing');
-
-    console.error(fmt,
-      stats.failures);
-
-    Base.list(this.failures);
-    console.error();
-  }
-
-  console.log();
-};
-
-/**
- * Pad the given `str` to `len`.
- *
- * @param {String} str
- * @param {String} len
- * @return {String}
- * @api private
- */
-
-function pad(str, len) {
-  str = String(str);
-  return Array(len - str.length + 1).join(' ') + str;
-}
-
-/**
- * Return a character diff for `err`.
- *
- * @param {Error} err
- * @return {String}
- * @api private
- */
-
-function errorDiff(err, type, escape) {
-  return diff['diff' + type](err.actual, err.expected).map(function(str){
-    if (escape) {
-      str.value = str.value
-        .replace(/\t/g, '<tab>')
-        .replace(/\r/g, '<CR>')
-        .replace(/\n/g, '<LF>\n');
-    }
-    if (str.added) return colorLines('diff added', str.value);
-    if (str.removed) return colorLines('diff removed', str.value);
-    return str.value;
-  }).join('');
-}
-
-/**
- * Color lines for `str`, using the color `name`.
- *
- * @param {String} name
- * @param {String} str
- * @return {String}
- * @api private
- */
-
-function colorLines(name, str) {
-  return str.split('\n').map(function(str){
-    return color(name, str);
-  }).join('\n');
-}
-
-/**
- * Stringify `obj`.
- *
- * @param {Mixed} obj
- * @return {String}
- * @api private
- */
-
-function stringify(obj) {
-  if (obj instanceof RegExp) return obj.toString();
-  return JSON.stringify(obj, null, 2);
-}
-
-/**
- * Check that a / b have the same type.
- *
- * @param {Object} a
- * @param {Object} b
- * @return {Boolean}
- * @api private
- */
-
-function sameType(a, b) {
-  a = Object.prototype.toString.call(a);
-  b = Object.prototype.toString.call(b);
-  return a == b;
-}
-
-}); // module: reporters/base.js
-
-require.register("reporters/doc.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var Base = require('./base')
-  , utils = require('../utils');
-
-/**
- * Expose `Doc`.
- */
-
-exports = module.exports = Doc;
-
-/**
- * Initialize a new `Doc` reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function Doc(runner) {
-  Base.call(this, runner);
-
-  var self = this
-    , stats = this.stats
-    , total = runner.total
-    , indents = 2;
-
-  function indent() {
-    return Array(indents).join('  ');
-  }
-
-  runner.on('suite', function(suite){
-    if (suite.root) return;
-    ++indents;
-    console.log('%s<section class="suite">', indent());
-    ++indents;
-    console.log('%s<h1>%s</h1>', indent(), utils.escape(suite.title));
-    console.log('%s<dl>', indent());
-  });
-
-  runner.on('suite end', function(suite){
-    if (suite.root) return;
-    console.log('%s</dl>', indent());
-    --indents;
-    console.log('%s</section>', indent());
-    --indents;
-  });
-
-  runner.on('pass', function(test){
-    console.log('%s  <dt>%s</dt>', indent(), utils.escape(test.title));
-    var code = utils.escape(utils.clean(test.fn.toString()));
-    console.log('%s  <dd><pre><code>%s</code></pre></dd>', indent(), code);
-  });
-}
-
-}); // module: reporters/doc.js
-
-require.register("reporters/dot.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var Base = require('./base')
-  , color = Base.color;
-
-/**
- * Expose `Dot`.
- */
-
-exports = module.exports = Dot;
-
-/**
- * Initialize a new `Dot` matrix test reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function Dot(runner) {
-  Base.call(this, runner);
-
-  var self = this
-    , stats = this.stats
-    , width = Base.window.width * .75 | 0
-    , n = 0;
-
-  runner.on('start', function(){
-    process.stdout.write('\n  ');
-  });
-
-  runner.on('pending', function(test){
-    process.stdout.write(color('pending', Base.symbols.dot));
-  });
-
-  runner.on('pass', function(test){
-    if (++n % width == 0) process.stdout.write('\n  ');
-    if ('slow' == test.speed) {
-      process.stdout.write(color('bright yellow', Base.symbols.dot));
-    } else {
-      process.stdout.write(color(test.speed, Base.symbols.dot));
-    }
-  });
-
-  runner.on('fail', function(test, err){
-    if (++n % width == 0) process.stdout.write('\n  ');
-    process.stdout.write(color('fail', Base.symbols.dot));
-  });
-
-  runner.on('end', function(){
-    console.log();
-    self.epilogue();
-  });
-}
-
-/**
- * Inherit from `Base.prototype`.
- */
-
-function F(){};
-F.prototype = Base.prototype;
-Dot.prototype = new F;
-Dot.prototype.constructor = Dot;
-
-}); // module: reporters/dot.js
-
-require.register("reporters/html-cov.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var JSONCov = require('./json-cov')
-  , fs = require('browser/fs');
-
-/**
- * Expose `HTMLCov`.
- */
-
-exports = module.exports = HTMLCov;
-
-/**
- * Initialize a new `JsCoverage` reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function HTMLCov(runner) {
-  var jade = require('jade')
-    , file = __dirname + '/templates/coverage.jade'
-    , str = fs.readFileSync(file, 'utf8')
-    , fn = jade.compile(str, { filename: file })
-    , self = this;
-
-  JSONCov.call(this, runner, false);
-
-  runner.on('end', function(){
-    process.stdout.write(fn({
-        cov: self.cov
-      , coverageClass: coverageClass
-    }));
-  });
-}
-
-/**
- * Return coverage class for `n`.
- *
- * @return {String}
- * @api private
- */
-
-function coverageClass(n) {
-  if (n >= 75) return 'high';
-  if (n >= 50) return 'medium';
-  if (n >= 25) return 'low';
-  return 'terrible';
-}
-}); // module: reporters/html-cov.js
-
-require.register("reporters/html.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var Base = require('./base')
-  , utils = require('../utils')
-  , Progress = require('../browser/progress')
-  , escape = utils.escape;
-
-/**
- * Save timer references to avoid Sinon interfering (see GH-237).
- */
-
-var Date = global.Date
-  , setTimeout = global.setTimeout
-  , setInterval = global.setInterval
-  , clearTimeout = global.clearTimeout
-  , clearInterval = global.clearInterval;
-
-/**
- * Expose `Doc`.
- */
-
-exports = module.exports = HTML;
-
-/**
- * Stats template.
- */
-
-var statsTemplate = '<ul id="mocha-stats">'
-  + '<li class="progress"><canvas width="40" height="40"></canvas></li>'
-  + '<li class="passes"><a href="#">passes:</a> <em>0</em></li>'
-  + '<li class="failures"><a href="#">failures:</a> <em>0</em></li>'
-  + '<li class="duration">duration: <em>0</em>s</li>'
-  + '</ul>';
-
-/**
- * Initialize a new `Doc` reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function HTML(runner, root) {
-  Base.call(this, runner);
-
-  var self = this
-    , stats = this.stats
-    , total = runner.total
-    , stat = fragment(statsTemplate)
-    , items = stat.getElementsByTagName('li')
-    , passes = items[1].getElementsByTagName('em')[0]
-    , passesLink = items[1].getElementsByTagName('a')[0]
-    , failures = items[2].getElementsByTagName('em')[0]
-    , failuresLink = items[2].getElementsByTagName('a')[0]
-    , duration = items[3].getElementsByTagName('em')[0]
-    , canvas = stat.getElementsByTagName('canvas')[0]
-    , report = fragment('<ul id="mocha-report"></ul>')
-    , stack = [report]
-    , progress
-    , ctx
-
-  root = root || document.getElementById('mocha');
-
-  if (canvas.getContext) {
-    var ratio = window.devicePixelRatio || 1;
-    canvas.style.width = canvas.width;
-    canvas.style.height = canvas.height;
-    canvas.width *= ratio;
-    canvas.height *= ratio;
-    ctx = canvas.getContext('2d');
-    ctx.scale(ratio, ratio);
-    progress = new Progress;
-  }
-
-  if (!root) return error('#mocha div missing, add it to your document');
-
-  // pass toggle
-  on(passesLink, 'click', function(){
-    unhide();
-    var name = /pass/.test(report.className) ? '' : ' pass';
-    report.className = report.className.replace(/fail|pass/g, '') + name;
-    if (report.className.trim()) hideSuitesWithout('test pass');
-  });
-
-  // failure toggle
-  on(failuresLink, 'click', function(){
-    unhide();
-    var name = /fail/.test(report.className) ? '' : ' fail';
-    report.className = report.className.replace(/fail|pass/g, '') + name;
-    if (report.className.trim()) hideSuitesWithout('test fail');
-  });
-
-  root.appendChild(stat);
-  root.appendChild(report);
-
-  if (progress) progress.size(40);
-
-  runner.on('suite', function(suite){
-    if (suite.root) return;
-
-    // suite
-    var url = '?grep=' + encodeURIComponent(suite.fullTitle());
-    var el = fragment('<li class="suite"><h1><a href="%s">%s</a></h1></li>', url, escape(suite.title));
-
-    // container
-    stack[0].appendChild(el);
-    stack.unshift(document.createElement('ul'));
-    el.appendChild(stack[0]);
-  });
-
-  runner.on('suite end', function(suite){
-    if (suite.root) return;
-    stack.shift();
-  });
-
-  runner.on('fail', function(test, err){
-    if ('hook' == test.type) runner.emit('test end', test);
-  });
-
-  runner.on('test end', function(test){
-    // TODO: add to stats
-    var percent = stats.tests / this.total * 100 | 0;
-    if (progress) progress.update(percent).draw(ctx);
-
-    // update stats
-    var ms = new Date - stats.start;
-    text(passes, stats.passes);
-    text(failures, stats.failures);
-    text(duration, (ms / 1000).toFixed(2));
-
-    // test
-    if ('passed' == test.state) {
-      var el = fragment('<li class="test pass %e"><h2>%e<span class="duration">%ems</span> <a href="?grep=%e" class="replay">‣</a></h2></li>', test.speed, test.title, test.duration, encodeURIComponent(test.fullTitle()));
-    } else if (test.pending) {
-      var el = fragment('<li class="test pass pending"><h2>%e</h2></li>', test.title);
-    } else {
-      var el = fragment('<li class="test fail"><h2>%e <a href="?grep=%e" class="replay">‣</a></h2></li>', test.title, encodeURIComponent(test.fullTitle()));
-      var str = test.err.stack || test.err.toString();
-
-      // FF / Opera do not add the message
-      if (!~str.indexOf(test.err.message)) {
-        str = test.err.message + '\n' + str;
-      }
-
-      // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we
-      // check for the result of the stringifying.
-      if ('[object Error]' == str) str = test.err.message;
-
-      // Safari doesn't give you a stack. Let's at least provide a source line.
-      if (!test.err.stack && test.err.sourceURL && test.err.line !== undefined) {
-        str += "\n(" + test.err.sourceURL + ":" + test.err.line + ")";
-      }
-
-      el.appendChild(fragment('<pre class="error">%e</pre>', str));
-    }
-
-    // toggle code
-    // TODO: defer
-    if (!test.pending) {
-      var h2 = el.getElementsByTagName('h2')[0];
-
-      on(h2, 'click', function(){
-        pre.style.display = 'none' == pre.style.display
-          ? 'block'
-          : 'none';
-      });
-
-      var pre = fragment('<pre><code>%e</code></pre>', utils.clean(test.fn.toString()));
-      el.appendChild(pre);
-      pre.style.display = 'none';
-    }
-
-    // Don't call .appendChild if #mocha-report was already .shift()'ed off the stack.
-    if (stack[0]) stack[0].appendChild(el);
-  });
-}
-
-/**
- * Display error `msg`.
- */
-
-function error(msg) {
-  document.body.appendChild(fragment('<div id="mocha-error">%s</div>', msg));
-}
-
-/**
- * Return a DOM fragment from `html`.
- */
-
-function fragment(html) {
-  var args = arguments
-    , div = document.createElement('div')
-    , i = 1;
-
-  div.innerHTML = html.replace(/%([se])/g, function(_, type){
-    switch (type) {
-      case 's': return String(args[i++]);
-      case 'e': return escape(args[i++]);
-    }
-  });
-
-  return div.firstChild;
-}
-
-/**
- * Check for suites that do not have elements
- * with `classname`, and hide them.
- */
-
-function hideSuitesWithout(classname) {
-  var suites = document.getElementsByClassName('suite');
-  for (var i = 0; i < suites.length; i++) {
-    var els = suites[i].getElementsByClassName(classname);
-    if (0 == els.length) suites[i].className += ' hidden';
-  }
-}
-
-/**
- * Unhide .hidden suites.
- */
-
-function unhide() {
-  var els = document.getElementsByClassName('suite hidden');
-  for (var i = 0; i < els.length; ++i) {
-    els[i].className = els[i].className.replace('suite hidden', 'suite');
-  }
-}
-
-/**
- * Set `el` text to `str`.
- */
-
-function text(el, str) {
-  if (el.textContent) {
-    el.textContent = str;
-  } else {
-    el.innerText = str;
-  }
-}
-
-/**
- * Listen on `event` with callback `fn`.
- */
-
-function on(el, event, fn) {
-  if (el.addEventListener) {
-    el.addEventListener(event, fn, false);
-  } else {
-    el.attachEvent('on' + event, fn);
-  }
-}
-
-}); // module: reporters/html.js
-
-require.register("reporters/index.js", function(module, exports, require){
-
-exports.Base = require('./base');
-exports.Dot = require('./dot');
-exports.Doc = require('./doc');
-exports.TAP = require('./tap');
-exports.JSON = require('./json');
-exports.HTML = require('./html');
-exports.List = require('./list');
-exports.Min = require('./min');
-exports.Spec = require('./spec');
-exports.Nyan = require('./nyan');
-exports.XUnit = require('./xunit');
-exports.Markdown = require('./markdown');
-exports.Progress = require('./progress');
-exports.Landing = require('./landing');
-exports.JSONCov = require('./json-cov');
-exports.HTMLCov = require('./html-cov');
-exports.JSONStream = require('./json-stream');
-exports.Teamcity = require('./teamcity');
-
-}); // module: reporters/index.js
-
-require.register("reporters/json-cov.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var Base = require('./base');
-
-/**
- * Expose `JSONCov`.
- */
-
-exports = module.exports = JSONCov;
-
-/**
- * Initialize a new `JsCoverage` reporter.
- *
- * @param {Runner} runner
- * @param {Boolean} output
- * @api public
- */
-
-function JSONCov(runner, output) {
-  var self = this
-    , output = 1 == arguments.length ? true : output;
-
-  Base.call(this, runner);
-
-  var tests = []
-    , failures = []
-    , passes = [];
-
-  runner.on('test end', function(test){
-    tests.push(test);
-  });
-
-  runner.on('pass', function(test){
-    passes.push(test);
-  });
-
-  runner.on('fail', function(test){
-    failures.push(test);
-  });
-
-  runner.on('end', function(){
-    var cov = global._$jscoverage || {};
-    var result = self.cov = map(cov);
-    result.stats = self.stats;
-    result.tests = tests.map(clean);
-    result.failures = failures.map(clean);
-    result.passes = passes.map(clean);
-    if (!output) return;
-    process.stdout.write(JSON.stringify(result, null, 2 ));
-  });
-}
-
-/**
- * Map jscoverage data to a JSON structure
- * suitable for reporting.
- *
- * @param {Object} cov
- * @return {Object}
- * @api private
- */
-
-function map(cov) {
-  var ret = {
-      instrumentation: 'node-jscoverage'
-    , sloc: 0
-    , hits: 0
-    , misses: 0
-    , coverage: 0
-    , files: []
-  };
-
-  for (var filename in cov) {
-    var data = coverage(filename, cov[filename]);
-    ret.files.push(data);
-    ret.hits += data.hits;
-    ret.misses += data.misses;
-    ret.sloc += data.sloc;
-  }
-
-  ret.files.sort(function(a, b) {
-    return a.filename.localeCompare(b.filename);
-  });
-
-  if (ret.sloc > 0) {
-    ret.coverage = (ret.hits / ret.sloc) * 100;
-  }
-
-  return ret;
-};
-
-/**
- * Map jscoverage data for a single source file
- * to a JSON structure suitable for reporting.
- *
- * @param {String} filename name of the source file
- * @param {Object} data jscoverage coverage data
- * @return {Object}
- * @api private
- */
-
-function coverage(filename, data) {
-  var ret = {
-    filename: filename,
-    coverage: 0,
-    hits: 0,
-    misses: 0,
-    sloc: 0,
-    source: {}
-  };
-
-  data.source.forEach(function(line, num){
-    num++;
-
-    if (data[num] === 0) {
-      ret.misses++;
-      ret.sloc++;
-    } else if (data[num] !== undefined) {
-      ret.hits++;
-      ret.sloc++;
-    }
-
-    ret.source[num] = {
-        source: line
-      , coverage: data[num] === undefined
-        ? ''
-        : data[num]
-    };
-  });
-
-  ret.coverage = ret.hits / ret.sloc * 100;
-
-  return ret;
-}
-
-/**
- * Return a plain-object representation of `test`
- * free of cyclic properties etc.
- *
- * @param {Object} test
- * @return {Object}
- * @api private
- */
-
-function clean(test) {
-  return {
-      title: test.title
-    , fullTitle: test.fullTitle()
-    , duration: test.duration
-  }
-}
-
-}); // module: reporters/json-cov.js
-
-require.register("reporters/json-stream.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var Base = require('./base')
-  , color = Base.color;
-
-/**
- * Expose `List`.
- */
-
-exports = module.exports = List;
-
-/**
- * Initialize a new `List` test reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function List(runner) {
-  Base.call(this, runner);
-
-  var self = this
-    , stats = this.stats
-    , total = runner.total;
-
-  runner.on('start', function(){
-    console.log(JSON.stringify(['start', { total: total }]));
-  });
-
-  runner.on('pass', function(test){
-    console.log(JSON.stringify(['pass', clean(test)]));
-  });
-
-  runner.on('fail', function(test, err){
-    console.log(JSON.stringify(['fail', clean(test)]));
-  });
-
-  runner.on('end', function(){
-    process.stdout.write(JSON.stringify(['end', self.stats]));
-  });
-}
-
-/**
- * Return a plain-object representation of `test`
- * free of cyclic properties etc.
- *
- * @param {Object} test
- * @return {Object}
- * @api private
- */
-
-function clean(test) {
-  return {
-      title: test.title
-    , fullTitle: test.fullTitle()
-    , duration: test.duration
-  }
-}
-}); // module: reporters/json-stream.js
-
-require.register("reporters/json.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var Base = require('./base')
-  , cursor = Base.cursor
-  , color = Base.color;
-
-/**
- * Expose `JSON`.
- */
-
-exports = module.exports = JSONReporter;
-
-/**
- * Initialize a new `JSON` reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function JSONReporter(runner) {
-  var self = this;
-  Base.call(this, runner);
-
-  var tests = []
-    , failures = []
-    , passes = [];
-
-  runner.on('test end', function(test){
-    tests.push(test);
-  });
-
-  runner.on('pass', function(test){
-    passes.push(test);
-  });
-
-  runner.on('fail', function(test){
-    failures.push(test);
-  });
-
-  runner.on('end', function(){
-    var obj = {
-        stats: self.stats
-      , tests: tests.map(clean)
-      , failures: failures.map(clean)
-      , passes: passes.map(clean)
-    };
-
-    process.stdout.write(JSON.stringify(obj, null, 2));
-  });
-}
-
-/**
- * Return a plain-object representation of `test`
- * free of cyclic properties etc.
- *
- * @param {Object} test
- * @return {Object}
- * @api private
- */
-
-function clean(test) {
-  return {
-      title: test.title
-    , fullTitle: test.fullTitle()
-    , duration: test.duration
-  }
-}
-}); // module: reporters/json.js
-
-require.register("reporters/landing.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var Base = require('./base')
-  , cursor = Base.cursor
-  , color = Base.color;
-
-/**
- * Expose `Landing`.
- */
-
-exports = module.exports = Landing;
-
-/**
- * Airplane color.
- */
-
-Base.colors.plane = 0;
-
-/**
- * Airplane crash color.
- */
-
-Base.colors['plane crash'] = 31;
-
-/**
- * Runway color.
- */
-
-Base.colors.runway = 90;
-
-/**
- * Initialize a new `Landing` reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function Landing(runner) {
-  Base.call(this, runner);
-
-  var self = this
-    , stats = this.stats
-    , width = Base.window.width * .75 | 0
-    , total = runner.total
-    , stream = process.stdout
-    , plane = color('plane', '✈')
-    , crashed = -1
-    , n = 0;
-
-  function runway() {
-    var buf = Array(width).join('-');
-    return '  ' + color('runway', buf);
-  }
-
-  runner.on('start', function(){
-    stream.write('\n  ');
-    cursor.hide();
-  });
-
-  runner.on('test end', function(test){
-    // check if the plane crashed
-    var col = -1 == crashed
-      ? width * ++n / total | 0
-      : crashed;
-
-    // show the crash
-    if ('failed' == test.state) {
-      plane = color('plane crash', '✈');
-      crashed = col;
-    }
-
-    // render landing strip
-    stream.write('\u001b[4F\n\n');
-    stream.write(runway());
-    stream.write('\n  ');
-    stream.write(color('runway', Array(col).join('⋅')));
-    stream.write(plane)
-    stream.write(color('runway', Array(width - col).join('⋅') + '\n'));
-    stream.write(runway());
-    stream.write('\u001b[0m');
-  });
-
-  runner.on('end', function(){
-    cursor.show();
-    console.log();
-    self.epilogue();
-  });
-}
-
-/**
- * Inherit from `Base.prototype`.
- */
-
-function F(){};
-F.prototype = Base.prototype;
-Landing.prototype = new F;
-Landing.prototype.constructor = Landing;
-
-}); // module: reporters/landing.js
-
-require.register("reporters/list.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var Base = require('./base')
-  , cursor = Base.cursor
-  , color = Base.color;
-
-/**
- * Expose `List`.
- */
-
-exports = module.exports = List;
-
-/**
- * Initialize a new `List` test reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function List(runner) {
-  Base.call(this, runner);
-
-  var self = this
-    , stats = this.stats
-    , n = 0;
-
-  runner.on('start', function(){
-    console.log();
-  });
-
-  runner.on('test', function(test){
-    process.stdout.write(color('pass', '    ' + test.fullTitle() + ': '));
-  });
-
-  runner.on('pending', function(test){
-    var fmt = color('checkmark', '  -')
-      + color('pending', ' %s');
-    console.log(fmt, test.fullTitle());
-  });
-
-  runner.on('pass', function(test){
-    var fmt = color('checkmark', '  '+Base.symbols.dot)
-      + color('pass', ' %s: ')
-      + color(test.speed, '%dms');
-    cursor.CR();
-    console.log(fmt, test.fullTitle(), test.duration);
-  });
-
-  runner.on('fail', function(test, err){
-    cursor.CR();
-    console.log(color('fail', '  %d) %s'), ++n, test.fullTitle());
-  });
-
-  runner.on('end', self.epilogue.bind(self));
-}
-
-/**
- * Inherit from `Base.prototype`.
- */
-
-function F(){};
-F.prototype = Base.prototype;
-List.prototype = new F;
-List.prototype.constructor = List;
-
-
-}); // module: reporters/list.js
-
-require.register("reporters/markdown.js", function(module, exports, require){
-/**
- * Module dependencies.
- */
-
-var Base = require('./base')
-  , utils = require('../utils');
-
-/**
- * Expose `Markdown`.
- */
-
-exports = module.exports = Markdown;
-
-/**
- * Initialize a new `Markdown` reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function Markdown(runner) {
-  Base.call(this, runner);
-
-  var self = this
-    , stats = this.stats
-    , level = 0
-    , buf = '';
-
-  function title(str) {
-    return Array(level).join('#') + ' ' + str;
-  }
-
-  function indent() {
-    return Array(level).join('  ');
-  }
-
-  function mapTOC(suite, obj) {
-    var ret = obj;
-    obj = obj[suite.title] = obj[suite.title] || { suite: suite };
-    suite.suites.forEach(function(suite){
-      mapTOC(suite, obj);
-    });
-    return ret;
-  }
-
-  function stringifyTOC(obj, level) {
-    ++level;
-    var buf = '';
-    var link;
-    for (var key in obj) {
-      if ('suite' == key) continue;
-      if (key) link = ' - [' + key + '](#' + utils.slug(obj[key].suite.fullTitle()) + ')\n';
-      if (key) buf += Array(level).join('  ') + link;
-      buf += stringifyTOC(obj[key], level);
-    }
-    --level;
-    return buf;
-  }
-
-  function generateTOC(suite) {
-    var obj = mapTOC(suite, {});
-    return stringifyTOC(obj, 0);
-  }
-
-  generateTOC(runner.suite);
-
-  runner.on('suite', function(suite){
-    ++level;
-    var slug = utils.slug(suite.fullTitle());
-    buf += '<a name="' + slug + '"></a>' + '\n';
-    buf += title(suite.title) + '\n';
-  });
-
-  runner.on('suite end', function(suite){
-    --level;
-  });
-
-  runner.on('pass', function(test){
-    var code = utils.clean(test.fn.toString());
-    buf += test.title + '.\n';
-    buf += '\n```js\n';
-    buf += code + '\n';
-    buf += '```\n\n';
-  });
-
-  runner.on('end', function(){
-    process.stdout.write('# TOC\n');
-    process.stdout.write(generateTOC(runner.suite));
-    process.stdout.write(buf);
-  });
-}
-}); // module: reporters/markdown.js
-
-require.register("reporters/min.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var Base = require('./base');
-
-/**
- * Expose `Min`.
- */
-
-exports = module.exports = Min;
-
-/**
- * Initialize a new `Min` minimal test reporter (best used with --watch).
- *
- * @param {Runner} runner
- * @api public
- */
-
-function Min(runner) {
-  Base.call(this, runner);
-
-  runner.on('start', function(){
-    // clear screen
-    process.stdout.write('\u001b[2J');
-    // set cursor position
-    process.stdout.write('\u001b[1;3H');
-  });
-
-  runner.on('end', this.epilogue.bind(this));
-}
-
-/**
- * Inherit from `Base.prototype`.
- */
-
-function F(){};
-F.prototype = Base.prototype;
-Min.prototype = new F;
-Min.prototype.constructor = Min;
-
-
-}); // module: reporters/min.js
-
-require.register("reporters/nyan.js", function(module, exports, require){
-/**
- * Module dependencies.
- */
-
-var Base = require('./base')
-  , color = Base.color;
-
-/**
- * Expose `Dot`.
- */
-
-exports = module.exports = NyanCat;
-
-/**
- * Initialize a new `Dot` matrix test reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function NyanCat(runner) {
-  Base.call(this, runner);
-
-  var self = this
-    , stats = this.stats
-    , width = Base.window.width * .75 | 0
-    , rainbowColors = this.rainbowColors = self.generateColors()
-    , colorIndex = this.colorIndex = 0
-    , numerOfLines = this.numberOfLines = 4
-    , trajectories = this.trajectories = [[], [], [], []]
-    , nyanCatWidth = this.nyanCatWidth = 11
-    , trajectoryWidthMax = this.trajectoryWidthMax = (width - nyanCatWidth)
-    , scoreboardWidth = this.scoreboardWidth = 5
-    , tick = this.tick = 0
-    , n = 0;
-
-  runner.on('start', function(){
-    Base.cursor.hide();
-    self.draw('start');
-  });
-
-  runner.on('pending', function(test){
-    self.draw('pending');
-  });
-
-  runner.on('pass', function(test){
-    self.draw('pass');
-  });
-
-  runner.on('fail', function(test, err){
-    self.draw('fail');
-  });
-
-  runner.on('end', function(){
-    Base.cursor.show();
-    for (var i = 0; i < self.numberOfLines; i++) write('\n');
-    self.epilogue();
-  });
-}
-
-/**
- * Draw the nyan cat with runner `status`.
- *
- * @param {String} status
- * @api private
- */
-
-NyanCat.prototype.draw = function(status){
-  this.appendRainbow();
-  this.drawScoreboard();
-  this.drawRainbow();
-  this.drawNyanCat(status);
-  this.tick = !this.tick;
-};
-
-/**
- * Draw the "scoreboard" showing the number
- * of passes, failures and pending tests.
- *
- * @api private
- */
-
-NyanCat.prototype.drawScoreboard = function(){
-  var stats = this.stats;
-  var colors = Base.colors;
-
-  function draw(color, n) {
-    write(' ');
-    write('\u001b[' + color + 'm' + n + '\u001b[0m');
-    write('\n');
-  }
-
-  draw(colors.green, stats.passes);
-  draw(colors.fail, stats.failures);
-  draw(colors.pending, stats.pending);
-  write('\n');
-
-  this.cursorUp(this.numberOfLines);
-};
-
-/**
- * Append the rainbow.
- *
- * @api private
- */
-
-NyanCat.prototype.appendRainbow = function(){
-  var segment = this.tick ? '_' : '-';
-  var rainbowified = this.rainbowify(segment);
-
-  for (var index = 0; index < this.numberOfLines; index++) {
-    var trajectory = this.trajectories[index];
-    if (trajectory.length >= this.trajectoryWidthMax) trajectory.shift();
-    trajectory.push(rainbowified);
-  }
-};
-
-/**
- * Draw the rainbow.
- *
- * @api private
- */
-
-NyanCat.prototype.drawRainbow = function(){
-  var self = this;
-
-  this.trajectories.forEach(function(line, index) {
-    write('\u001b[' + self.scoreboardWidth + 'C');
-    write(line.join(''));
-    write('\n');
-  });
-
-  this.cursorUp(this.numberOfLines);
-};
-
-/**
- * Draw the nyan cat with `status`.
- *
- * @param {String} status
- * @api private
- */
-
-NyanCat.prototype.drawNyanCat = function(status) {
-  var self = this;
-  var startWidth = this.scoreboardWidth + this.trajectories[0].length;
-  var color = '\u001b[' + startWidth + 'C';
-  var padding = '';
-  
-  write(color);
-  write('_,------,');
-  write('\n');
-  
-  write(color);
-  padding = self.tick ? '  ' : '   ';
-  write('_|' + padding + '/\\_/\\ ');
-  write('\n');
-  
-  write(color);
-  padding = self.tick ? '_' : '__';
-  var tail = self.tick ? '~' : '^';
-  var face;
-  switch (status) {
-    case 'pass':
-      face = '( ^ .^)';
-      break;
-    case 'fail':
-      face = '( o .o)';
-      break;
-    default:
-      face = '( - .-)';
-  }
-  write(tail + '|' + padding + face + ' ');
-  write('\n');
-  
-  write(color);
-  padding = self.tick ? ' ' : '  ';
-  write(padding + '""  "" ');
-  write('\n');
-
-  this.cursorUp(this.numberOfLines);
-};
-
-/**
- * Move cursor up `n`.
- *
- * @param {Number} n
- * @api private
- */
-
-NyanCat.prototype.cursorUp = function(n) {
-  write('\u001b[' + n + 'A');
-};
-
-/**
- * Move cursor down `n`.
- *
- * @param {Number} n
- * @api private
- */
-
-NyanCat.prototype.cursorDown = function(n) {
-  write('\u001b[' + n + 'B');
-};
-
-/**
- * Generate rainbow colors.
- *
- * @return {Array}
- * @api private
- */
-
-NyanCat.prototype.generateColors = function(){
-  var colors = [];
-
-  for (var i = 0; i < (6 * 7); i++) {
-    var pi3 = Math.floor(Math.PI / 3);
-    var n = (i * (1.0 / 6));
-    var r = Math.floor(3 * Math.sin(n) + 3);
-    var g = Math.floor(3 * Math.sin(n + 2 * pi3) + 3);
-    var b = Math.floor(3 * Math.sin(n + 4 * pi3) + 3);
-    colors.push(36 * r + 6 * g + b + 16);
-  }
-
-  return colors;
-};
-
-/**
- * Apply rainbow to the given `str`.
- *
- * @param {String} str
- * @return {String}
- * @api private
- */
-
-NyanCat.prototype.rainbowify = function(str){
-  var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length];
-  this.colorIndex += 1;
-  return '\u001b[38;5;' + color + 'm' + str + '\u001b[0m';
-};
-
-/**
- * Stdout helper.
- */
-
-function write(string) {
-  process.stdout.write(string);
-}
-
-/**
- * Inherit from `Base.prototype`.
- */
-
-function F(){};
-F.prototype = Base.prototype;
-NyanCat.prototype = new F;
-NyanCat.prototype.constructor = NyanCat;
-
-
-}); // module: reporters/nyan.js
-
-require.register("reporters/progress.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var Base = require('./base')
-  , cursor = Base.cursor
-  , color = Base.color;
-
-/**
- * Expose `Progress`.
- */
-
-exports = module.exports = Progress;
-
-/**
- * General progress bar color.
- */
-
-Base.colors.progress = 90;
-
-/**
- * Initialize a new `Progress` bar test reporter.
- *
- * @param {Runner} runner
- * @param {Object} options
- * @api public
- */
-
-function Progress(runner, options) {
-  Base.call(this, runner);
-
-  var self = this
-    , options = options || {}
-    , stats = this.stats
-    , width = Base.window.width * .50 | 0
-    , total = runner.total
-    , complete = 0
-    , max = Math.max;
-
-  // default chars
-  options.open = options.open || '[';
-  options.complete = options.complete || '▬';
-  options.incomplete = options.incomplete || Base.symbols.dot;
-  options.close = options.close || ']';
-  options.verbose = false;
-
-  // tests started
-  runner.on('start', function(){
-    console.log();
-    cursor.hide();
-  });
-
-  // tests complete
-  runner.on('test end', function(){
-    complete++;
-    var incomplete = total - complete
-      , percent = complete / total
-      , n = width * percent | 0
-      , i = width - n;
-
-    cursor.CR();
-    process.stdout.write('\u001b[J');
-    process.stdout.write(color('progress', '  ' + options.open));
-    process.stdout.write(Array(n).join(options.complete));
-    process.stdout.write(Array(i).join(options.incomplete));
-    process.stdout.write(color('progress', options.close));
-    if (options.verbose) {
-      process.stdout.write(color('progress', ' ' + complete + ' of ' + total));
-    }
-  });
-
-  // tests are complete, output some stats
-  // and the failures if any
-  runner.on('end', function(){
-    cursor.show();
-    console.log();
-    self.epilogue();
-  });
-}
-
-/**
- * Inherit from `Base.prototype`.
- */
-
-function F(){};
-F.prototype = Base.prototype;
-Progress.prototype = new F;
-Progress.prototype.constructor = Progress;
-
-
-}); // module: reporters/progress.js
-
-require.register("reporters/spec.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var Base = require('./base')
-  , cursor = Base.cursor
-  , color = Base.color;
-
-/**
- * Expose `Spec`.
- */
-
-exports = module.exports = Spec;
-
-/**
- * Initialize a new `Spec` test reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function Spec(runner) {
-  Base.call(this, runner);
-
-  var self = this
-    , stats = this.stats
-    , indents = 0
-    , n = 0;
-
-  function indent() {
-    return Array(indents).join('  ')
-  }
-
-  runner.on('start', function(){
-    console.log();
-  });
-
-  runner.on('suite', function(suite){
-    ++indents;
-    console.log(color('suite', '%s%s'), indent(), suite.title);
-  });
-
-  runner.on('suite end', function(suite){
-    --indents;
-    if (1 == indents) console.log();
-  });
-
-  runner.on('test', function(test){
-    process.stdout.write(indent() + color('pass', '  ◦ ' + test.title + ': '));
-  });
-
-  runner.on('pending', function(test){
-    var fmt = indent() + color('pending', '  - %s');
-    console.log(fmt, test.title);
-  });
-
-  runner.on('pass', function(test){
-    if ('fast' == test.speed) {
-      var fmt = indent()
-        + color('checkmark', '  ' + Base.symbols.ok)
-        + color('pass', ' %s ');
-      cursor.CR();
-      console.log(fmt, test.title);
-    } else {
-      var fmt = indent()
-        + color('checkmark', '  ' + Base.symbols.ok)
-        + color('pass', ' %s ')
-        + color(test.speed, '(%dms)');
-      cursor.CR();
-      console.log(fmt, test.title, test.duration);
-    }
-  });
-
-  runner.on('fail', function(test, err){
-    cursor.CR();
-    console.log(indent() + color('fail', '  %d) %s'), ++n, test.title);
-  });
-
-  runner.on('end', self.epilogue.bind(self));
-}
-
-/**
- * Inherit from `Base.prototype`.
- */
-
-function F(){};
-F.prototype = Base.prototype;
-Spec.prototype = new F;
-Spec.prototype.constructor = Spec;
-
-
-}); // module: reporters/spec.js
-
-require.register("reporters/tap.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var Base = require('./base')
-  , cursor = Base.cursor
-  , color = Base.color;
-
-/**
- * Expose `TAP`.
- */
-
-exports = module.exports = TAP;
-
-/**
- * Initialize a new `TAP` reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function TAP(runner) {
-  Base.call(this, runner);
-
-  var self = this
-    , stats = this.stats
-    , n = 1
-    , passes = 0
-    , failures = 0;
-
-  runner.on('start', function(){
-    var total = runner.grepTotal(runner.suite);
-    console.log('%d..%d', 1, total);
-  });
-
-  runner.on('test end', function(){
-    ++n;
-  });
-
-  runner.on('pending', function(test){
-    console.log('ok %d %s # SKIP -', n, title(test));
-  });
-
-  runner.on('pass', function(test){
-    passes++;
-    console.log('ok %d %s', n, title(test));
-  });
-
-  runner.on('fail', function(test, err){
-    failures++;
-    console.log('not ok %d %s', n, title(test));
-    if (err.stack) console.log(err.stack.replace(/^/gm, '  '));
-  });
-
-  runner.on('end', function(){
-    console.log('# tests ' + (passes + failures));
-    console.log('# pass ' + passes);
-    console.log('# fail ' + failures);
-  });
-}
-
-/**
- * Return a TAP-safe title of `test`
- *
- * @param {Object} test
- * @return {String}
- * @api private
- */
-
-function title(test) {
-  return test.fullTitle().replace(/#/g, '');
-}
-
-}); // module: reporters/tap.js
-
-require.register("reporters/teamcity.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var Base = require('./base');
-
-/**
- * Expose `Teamcity`.
- */
-
-exports = module.exports = Teamcity;
-
-/**
- * Initialize a new `Teamcity` reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function Teamcity(runner) {
-  Base.call(this, runner);
-  var stats = this.stats;
-
-  runner.on('start', function() {
-    console.log("##teamcity[testSuiteStarted name='mocha.suite']");
-  });
-
-  runner.on('test', function(test) {
-    console.log("##teamcity[testStarted name='" + escape(test.fullTitle()) + "']");
-  });
-
-  runner.on('fail', function(test, err) {
-    console.log("##teamcity[testFailed name='" + escape(test.fullTitle()) + "' message='" + escape(err.message) + "']");
-  });
-
-  runner.on('pending', function(test) {
-    console.log("##teamcity[testIgnored name='" + escape(test.fullTitle()) + "' message='pending']");
-  });
-
-  runner.on('test end', function(test) {
-    console.log("##teamcity[testFinished name='" + escape(test.fullTitle()) + "' duration='" + test.duration + "']");
-  });
-
-  runner.on('end', function() {
-    console.log("##teamcity[testSuiteFinished name='mocha.suite' duration='" + stats.duration + "']");
-  });
-}
-
-/**
- * Escape the given `str`.
- */
-
-function escape(str) {
-  return str
-    .replace(/\|/g, "||")
-    .replace(/\n/g, "|n")
-    .replace(/\r/g, "|r")
-    .replace(/\[/g, "|[")
-    .replace(/\]/g, "|]")
-    .replace(/\u0085/g, "|x")
-    .replace(/\u2028/g, "|l")
-    .replace(/\u2029/g, "|p")
-    .replace(/'/g, "|'");
-}
-
-}); // module: reporters/teamcity.js
-
-require.register("reporters/xunit.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var Base = require('./base')
-  , utils = require('../utils')
-  , escape = utils.escape;
-
-/**
- * Save timer references to avoid Sinon interfering (see GH-237).
- */
-
-var Date = global.Date
-  , setTimeout = global.setTimeout
-  , setInterval = global.setInterval
-  , clearTimeout = global.clearTimeout
-  , clearInterval = global.clearInterval;
-
-/**
- * Expose `XUnit`.
- */
-
-exports = module.exports = XUnit;
-
-/**
- * Initialize a new `XUnit` reporter.
- *
- * @param {Runner} runner
- * @api public
- */
-
-function XUnit(runner) {
-  Base.call(this, runner);
-  var stats = this.stats
-    , tests = []
-    , self = this;
-
-  runner.on('pass', function(test){
-    tests.push(test);
-  });
-
-  runner.on('fail', function(test){
-    tests.push(test);
-  });
-
-  runner.on('end', function(){
-    console.log(tag('testsuite', {
-        name: 'Mocha Tests'
-      , tests: stats.tests
-      , failures: stats.failures
-      , errors: stats.failures
-      , skipped: stats.tests - stats.failures - stats.passes
-      , timestamp: (new Date).toUTCString()
-      , time: (stats.duration / 1000) || 0
-    }, false));
-
-    tests.forEach(test);
-    console.log('</testsuite>');
-  });
-}
-
-/**
- * Inherit from `Base.prototype`.
- */
-
-function F(){};
-F.prototype = Base.prototype;
-XUnit.prototype = new F;
-XUnit.prototype.constructor = XUnit;
-
-
-/**
- * Output tag for the given `test.`
- */
-
-function test(test) {
-  var attrs = {
-      classname: test.parent.fullTitle()
-    , name: test.title
-    , time: test.duration / 1000
-  };
-
-  if ('failed' == test.state) {
-    var err = test.err;
-    attrs.message = escape(err.message);
-    console.log(tag('testcase', attrs, false, tag('failure', attrs, false, cdata(err.stack))));
-  } else if (test.pending) {
-    console.log(tag('testcase', attrs, false, tag('skipped', {}, true)));
-  } else {
-    console.log(tag('testcase', attrs, true) );
-  }
-}
-
-/**
- * HTML tag helper.
- */
-
-function tag(name, attrs, close, content) {
-  var end = close ? '/>' : '>'
-    , pairs = []
-    , tag;
-
-  for (var key in attrs) {
-    pairs.push(key + '="' + escape(attrs[key]) + '"');
-  }
-
-  tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end;
-  if (content) tag += content + '</' + name + end;
-  return tag;
-}
-
-/**
- * Return cdata escaped CDATA `str`.
- */
-
-function cdata(str) {
-  return '<![CDATA[' + escape(str) + ']]>';
-}
-
-}); // module: reporters/xunit.js
-
-require.register("runnable.js", function(module, exports, require){
-
-/**
- * Module dependencies.
- */
-
-var EventEmitter = require('browser/events').EventEmitter
-  , debug = require('browser/debug')('mocha:runnable')
-  , milliseconds = require('./ms');
-
-/**
- * Save timer references to avoid Sinon interfering (see GH-237).
- */
-
-var Date = global.Date
-  , setTimeout = global.setTimeout
-  , setInterval = global.setInterval
-  , clearTimeout = global.clearTimeout
-  , clearInterval = global.clearInterval;
-
-/**
- * Object#toString().
- */
-
-var toString = Object.prototype.toString;
-
-/**
- * Expose `Runnable`.
- */
-
-module.exports = Runnable;
-
-/**
- * Initialize a new `Runnable` with the given `title` and callback `fn`.
- *
- * @param {String} title
- * @param {Function} fn
- * @api private
- */
-
-function Runnable(title, fn) {
-  this.title = title;
-  this.fn = fn;
-  this.async = fn && fn.length;
-  this.sync = ! this.async;
-  this._timeout = 2000;
-  this._slow = 75;
-  this.timedOut = false;
-}
-
-/**
- * Inherit from `EventEmitter.prototype`.
- */
-
-function F(){};
-F.prototype = EventEmitter.prototype;
-Runnable.prototype = new F;
-Runnable.prototype.constructor = Runnable;
-
-
-/**
- * Set & get timeout `ms`.
- *
- * @param {Number|String} ms
- * @return {Runnable|Number} ms or self
- * @api private
- */
-
-Runnable.prototype.timeout = function(ms){
-  if (0 == arguments.length) return this._timeout;
-  if ('string' == typeof ms) ms = milliseconds(ms);
-  debug('timeout %d', ms);
-  this._timeout = ms;
-  if (this.timer) this.resetTimeout();
-  return this;
-};
-
-/**
- * Set & get slow `ms`.
- *
- * @param {Number|String} ms
- * @return {Runnable|Number} ms or self
- * @api private
- */
-
-Runnable.prototype.slow = function(ms){
-  if (0 === arguments.length) return this._slow;
-  if ('string' == typeof ms) ms = milliseconds(ms);
-  debug('timeout %d', ms);
-  this._slow = ms;
-  return this;
-};
-
-/**
- * Return the full title generated by recursively
- * concatenating the parent's full title.
- *
- * @return {String}
- * @api public
- */
-
-Runnable.prototype.fullTitle = function(){
-  return this.parent.fullTitle() + ' ' + this.title;
-};
-
-/**
- * Clear the timeout.
- *
- * @api private
- */
-
-Runnable.prototype.clearTimeout = function(){
-  clearTimeout(this.timer);
-};
-
-/**
- * Inspect the runnable void of private properties.
- *
- * @return {String}
- * @api private
- */
-
-Runnable.prototype.inspect = function(){
-  return JSON.stringify(this, function(key, val){
-    if ('_' == key[0]) return;
-    if ('parent' == key) return '#<Suite>';
-    if ('ctx' == key) return '#<Context>';
-    return val;
-  }, 2);
-};
-
-/**
- * Reset the timeout.
- *
- * @api private
- */
-
-Runnable.prototype.resetTimeout = function(){
-  var self = this;
-  var ms = this.timeout() || 1e9;
-
-  this.clearTimeout();
-  this.timer = setTimeout(function(){
-    self.callback(new Error('timeout of ' + ms + 'ms exceeded'));
-    self.timedOut = true;
-  }, ms);
-};
-
-/**
- * Run the test and invoke `fn(err)`.
- *
- * @param {Function} fn
- * @api private
- */
-
-Runnable.prototype.run = function(fn){
-  var self = this
-    , ms = this.timeout()
-    , start = new Date
-    , ctx = this.ctx
-    , finished
-    , emitted;
-
-

<TRUNCATED>

[60/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/uregex.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/uregex.h b/src/apps/couch_collate/platform/osx/icu/unicode/uregex.h
new file mode 100644
index 0000000..d646047
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/uregex.h
@@ -0,0 +1,989 @@
+/*
+**********************************************************************
+*   Copyright (C) 2004-2008, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+**********************************************************************
+*   file name:  regex.h
+*   encoding:   US-ASCII
+*   indentation:4
+*
+*   created on: 2004mar09
+*   created by: Andy Heninger
+*
+*   ICU Regular Expressions, API for C
+*/
+
+/**
+ * \file
+ * \brief C API: Regular Expressions
+ *
+ * <p>This is a C wrapper around the C++ RegexPattern and RegexMatcher classes.</p>
+ */
+
+#ifndef UREGEX_H
+#define UREGEX_H
+
+#include "unicode/utypes.h"
+
+#if !UCONFIG_NO_REGULAR_EXPRESSIONS
+
+#include "unicode/parseerr.h"
+
+struct URegularExpression;
+/**
+  * Structure represeting a compiled regular rexpression, plus the results
+  *    of a match operation.
+  * @stable ICU 3.0
+  */
+typedef struct URegularExpression URegularExpression;
+
+
+/**
+ * Constants for Regular Expression Match Modes.
+ * @stable ICU 2.4
+ */
+typedef enum URegexpFlag{
+
+#ifndef U_HIDE_DRAFT_API 
+    /** Forces normalization of pattern and strings. 
+    Not implemented yet, just a placeholder, hence draft. 
+    @draft ICU 2.4 */
+    UREGEX_CANON_EQ         = 128,
+#endif
+    /**  Enable case insensitive matching.  @stable ICU 2.4 */
+    UREGEX_CASE_INSENSITIVE = 2,
+
+    /**  Allow white space and comments within patterns  @stable ICU 2.4 */
+    UREGEX_COMMENTS         = 4,
+
+    /**  If set, '.' matches line terminators,  otherwise '.' matching stops at line end.
+      *  @stable ICU 2.4 */
+    UREGEX_DOTALL           = 32,
+    
+    /**  If set, treat the entire pattern as a literal string.  
+      *  Metacharacters or escape sequences in the input sequence will be given 
+      *  no special meaning.
+      *
+      *  The flags CASE_INSENSITIVE and UNICODE_CASE retain their impact
+      *  on matching when used in conjunction with this flag.
+      *  The other flags become superfluous.
+      *  TODO:  say which escapes are still handled; anything Java does
+      *         early (\u) we should still do.
+      * @draft ICU 4.0
+      */
+    UREGEX_LITERAL = 16,
+
+    /**   Control behavior of "$" and "^"
+      *    If set, recognize line terminators within string,
+      *    otherwise, match only at start and end of input string.
+      *   @stable ICU 2.4 */
+    UREGEX_MULTILINE        = 8,
+    
+    /**   Unix-only line endings.
+      *   When this mode is enabled, only \u000a is recognized as a line ending
+      *    in the behavior of ., ^, and $.
+      *   @draft ICU 4.0
+      */
+    UREGEX_UNIX_LINES = 1,
+
+    /**  Unicode word boundaries.
+      *     If set, \b uses the Unicode TR 29 definition of word boundaries.
+      *     Warning: Unicode word boundaries are quite different from
+      *     traditional regular expression word boundaries.  See
+      *     http://unicode.org/reports/tr29/#Word_Boundaries
+      *     @stable ICU 2.8
+      */
+    UREGEX_UWORD            = 256,
+
+     /**  Error on Unrecognized backslash escapes.
+       *     If set, fail with an error on patterns that contain
+       *     backslash-escaped ASCII letters without a known specail
+       *     meaning.  If this flag is not set, these
+       *     escaped letters represent themselves.
+       *     @draft ICU 4.0
+       */
+     UREGEX_ERROR_ON_UNKNOWN_ESCAPES = 512
+
+}  URegexpFlag;
+
+/**
+  *  Open (compile) an ICU regular expression.  Compiles the regular expression in
+  *  string form into an internal representation using the specified match mode flags.
+  *  The resulting regular expression handle can then be used to perform various
+  *   matching operations.
+  *
+  * @param pattern        The Regular Expression pattern to be compiled. 
+  * @param patternLength  The length of the pattern, or -1 if the pattern is
+  *                       NUL termintated.
+  * @param flags          Flags that alter the default matching behavior for
+  *                       the regular expression, UREGEX_CASE_INSENSITIVE, for
+  *                       example.  For default behavior, set this parameter to zero.
+  *                       See <code>enum URegexpFlag</code>.  All desired flags
+  *                       are bitwise-ORed together.
+  * @param pe             Receives the position (line and column nubers) of any syntax
+  *                       error within the source regular expression string.  If this
+  *                       information is not wanted, pass NULL for this parameter.
+  * @param status         Receives error detected by this function.
+  * @stable ICU 3.0
+  *
+  */
+U_STABLE URegularExpression * U_EXPORT2
+uregex_open( const  UChar          *pattern,
+                    int32_t         patternLength,
+                    uint32_t        flags,
+                    UParseError    *pe,
+                    UErrorCode     *status);
+
+/**
+  *  Open (compile) an ICU regular expression.  The resulting regular expression
+  *   handle can then be used to perform various matching operations.
+  *  <p>
+  *   This function is the same as uregex_open, except that the pattern
+  *   is supplied as an 8 bit char * string in the default code page.
+  *
+  * @param pattern        The Regular Expression pattern to be compiled, 
+  *                       NUL termintated.  
+  * @param flags          Flags that alter the default matching behavior for
+  *                       the regular expression, UREGEX_CASE_INSENSITIVE, for
+  *                       example.  For default behavior, set this parameter to zero.
+  *                       See <code>enum URegexpFlag</code>.  All desired flags
+  *                       are bitwise-ORed together.
+  * @param pe             Receives the position (line and column nubers) of any syntax
+  *                       error within the source regular expression string.  If this
+  *                       information is not wanted, pass NULL for this parameter.
+  * @param status         Receives errors detected by this function.
+  * @return               The URegularExpression object representing the compiled
+  *                       pattern.
+  *
+  * @stable ICU 3.0
+  */
+#if !UCONFIG_NO_CONVERSION
+U_STABLE URegularExpression * U_EXPORT2
+uregex_openC( const char           *pattern,
+                    uint32_t        flags,
+                    UParseError    *pe,
+                    UErrorCode     *status);
+#endif
+
+
+
+/**
+  *  Close the regular expression, recovering all resources (memory) it
+  *   was holding.
+  *
+  * @param regexp   The regular expression to be closed.
+  * @stable ICU 3.0
+  */
+U_STABLE void U_EXPORT2 
+uregex_close(URegularExpression *regexp);
+
+/**
+ * Make a copy of a compiled regular expression.  Cloning a regular
+ * expression is faster than opening a second instance from the source
+ * form of the expression, and requires less memory.
+ * <p>
+ * Note that the current input string and the position of any matched text
+ *  within it are not cloned; only the pattern itself and and the
+ *  match mode flags are copied.
+ * <p>
+ * Cloning can be particularly useful to threaded applications that perform
+ * multiple match operations in parallel.  Each concurrent RE
+ * operation requires its own instance of a URegularExpression.
+ *
+ * @param regexp   The compiled regular expression to be cloned.
+ * @param status   Receives indication of any errors encountered
+ * @return the cloned copy of the compiled regular expression.
+ * @stable ICU 3.0
+ */
+U_STABLE URegularExpression * U_EXPORT2 
+uregex_clone(const URegularExpression *regexp, UErrorCode *status);
+
+/**
+ *  Return a pointer to the source form of the pattern for this regular expression.
+ *
+ * @param regexp     The compiled regular expression.
+ * @param patLength  This output parameter will be set to the length of the
+ *                   pattern string.  A NULL pointer may be used here if the
+ *                   pattern length is not needed, as would be the case if
+ *                   the pattern is known in advance to be a NUL terminated
+ *                   string.
+ * @param status     Receives errors detected by this function.
+ * @return a pointer to the pattern string.  The storage for the string is
+ *                   owned by the regular expression object, and must not be
+ *                   altered or deleted by the application.  The returned string
+ *                   will remain valid until the regular expression is closed.
+ * @stable ICU 3.0
+ */
+U_STABLE const UChar * U_EXPORT2 
+uregex_pattern(const  URegularExpression   *regexp,
+                         int32_t           *patLength,
+                         UErrorCode        *status);
+
+
+/**
+  * Get the match mode flags that were specified when compiling this regular expression.
+  * @param status   Receives errors detected by this function.
+  * @param regexp   The compiled regular expression.
+  * @return         The match mode flags
+  * @see URegexpFlag
+  * @stable ICU 3.0
+  */
+U_STABLE int32_t U_EXPORT2 
+uregex_flags(const  URegularExpression   *regexp,
+                    UErrorCode           *status);
+
+
+/**
+  *  Set the subject text string upon which the regular expression will look for matches.
+  *  This function may be called any number of times, allowing the regular
+  *  expression pattern to be applied to different strings.
+  *  <p>
+  *  Regular expression matching operations work directly on the application's
+  *  string data.  No copy is made.  The subject string data must not be
+  *  altered after calling this function until after all regular expression
+  *  operations involving this string data are completed.  
+  *  <p>
+  *  Zero length strings are permitted.  In this case, no subsequent match
+  *  operation will dereference the text string pointer.
+  *
+  * @param regexp     The compiled regular expression.
+  * @param text       The subject text string.
+  * @param textLength The length of the subject text, or -1 if the string
+  *                   is NUL terminated.
+  * @param status     Receives errors detected by this function.
+  * @stable ICU 3.0
+  */
+U_STABLE void U_EXPORT2 
+uregex_setText(URegularExpression *regexp,
+               const UChar        *text,
+               int32_t             textLength,
+               UErrorCode         *status);
+
+/**
+  *  Get the subject text that is currently associated with this 
+  *   regular expression object.  This simply returns whatever string
+  *   pointer was previously supplied via uregex_setText().
+  *
+  * @param regexp      The compiled regular expression.
+  * @param textLength  The length of the string is returned in this output parameter. 
+  *                    A NULL pointer may be used here if the
+  *                    text length is not needed, as would be the case if
+  *                    the text is known in advance to be a NUL terminated
+  *                    string.
+  * @param status      Receives errors detected by this function.
+  * @return            Poiner to the subject text string currently associated with
+  *                    this regular expression.
+  * @stable ICU 3.0
+  */
+U_STABLE const UChar * U_EXPORT2 
+uregex_getText(URegularExpression *regexp,
+               int32_t            *textLength,
+               UErrorCode         *status);
+
+/**
+  *   Attempts to match the input string against the pattern.
+  *   To succeed, the match must extend to the end of the string,
+  *   or cover the complete match region.
+  *
+  *   If startIndex >= zero the match operation starts at the specified
+  *   index and must extend to the end of the input string.  Any region
+  *   that has been specified is reset.
+  *
+  *   If startIndex == -1 the match must cover the input region, or the entire
+  *   input string if no region has been set.  This directly corresponds to
+  *   Matcher.matches() in Java
+  *
+  *    @param  regexp      The compiled regular expression.
+  *    @param  startIndex  The input string index at which to begin matching, or -1
+  *                        to match the input Region.
+  *    @param  status      Receives errors detected by this function.
+  *    @return             TRUE if there is a match
+  *    @stable ICU 3.0
+  */
+U_STABLE UBool U_EXPORT2 
+uregex_matches(URegularExpression *regexp,
+                int32_t            startIndex,
+                UErrorCode        *status);
+
+/**
+  *   Attempts to match the input string, starting from the specified index, against the pattern.
+  *   The match may be of any length, and is not required to extend to the end
+  *   of the input string.  Contrast with uregex_matches().
+  *
+  *   <p>If startIndex is >= 0 any input region that was set for this
+  *   URegularExpression is reset before the operation begins.
+  *
+  *   <p>If the specified starting index == -1 the match begins at the start of the input 
+  *   region, or at the start of the full string if no region has been specified.
+  *   This corresponds directly with Matcher.lookingAt() in Java.
+  *
+  *   <p>If the match succeeds then more information can be obtained via the
+  *    <code>uregexp_start()</code>, <code>uregexp_end()</code>,
+  *    and <code>uregexp_group()</code> functions.</p>
+  *
+  *    @param   regexp      The compiled regular expression.
+  *    @param   startIndex  The input string index at which to begin matching, or
+  *                         -1 to match the Input Region
+  *    @param   status      A reference to a UErrorCode to receive any errors.
+  *    @return  TRUE if there is a match.
+  *    @stable ICU 3.0
+  */
+U_STABLE UBool U_EXPORT2 
+uregex_lookingAt(URegularExpression *regexp,
+                 int32_t             startIndex,
+                 UErrorCode         *status);
+
+/**
+  *   Find the first matching substring of the input string that matches the pattern.
+  *   If startIndex is >= zero the search for a match begins at the specified index,
+  *          and any match region is reset.  This corresponds directly with
+  *          Matcher.find(startIndex) in Java.
+  *
+  *   If startIndex == -1 the search begins at the start of the input region,
+  *           or at the start of the full string if no region has been specified.
+  *
+  *   If a match is found, <code>uregex_start(), uregex_end()</code>, and
+  *   <code>uregex_group()</code> will provide more information regarding the match.
+  *
+  *   @param   regexp      The compiled regular expression.
+  *   @param   startIndex  The position in the input string to begin the search, or
+  *                        -1 to search within the Input Region.
+  *   @param   status      A reference to a UErrorCode to receive any errors.
+  *   @return              TRUE if a match is found.
+  *   @stable ICU 3.0
+  */
+U_STABLE UBool U_EXPORT2 
+uregex_find(URegularExpression *regexp,
+            int32_t             startIndex, 
+            UErrorCode         *status);
+
+/**
+  *  Find the next pattern match in the input string.  Begin searching 
+  *  the input at the location following the end of he previous match, 
+  *  or at the start of the string (or region) if there is no 
+  *  previous match.  If a match is found, <code>uregex_start(), uregex_end()</code>, and
+  *  <code>uregex_group()</code> will provide more information regarding the match.
+  *
+  *  @param   regexp      The compiled regular expression.
+  *  @param   status      A reference to a UErrorCode to receive any errors.
+  *  @return              TRUE if a match is found.
+  *  @see uregex_reset
+  *  @stable ICU 3.0
+  */
+U_STABLE UBool U_EXPORT2 
+uregex_findNext(URegularExpression *regexp,
+                UErrorCode         *status);
+
+/**
+  *   Get the number of capturing groups in this regular expression's pattern.
+  *   @param   regexp      The compiled regular expression.
+  *   @param   status      A reference to a UErrorCode to receive any errors.
+  *   @return the number of capture groups
+  *   @stable ICU 3.0
+  */
+U_STABLE int32_t U_EXPORT2 
+uregex_groupCount(URegularExpression *regexp,
+                  UErrorCode         *status);
+
+/** Extract the string for the specified matching expression or subexpression.
+  * Group #0 is the complete string of matched text.
+  * Group #1 is the text matched by the first set of capturing parentheses.
+  *
+  *   @param   regexp       The compiled regular expression.
+  *   @param   groupNum     The capture group to extract.  Group 0 is the complete
+  *                         match.  The value of this parameter must be
+  *                         less than or equal to the number of capture groups in
+  *                         the pattern.
+  *   @param   dest         Buffer to receive the matching string data
+  *   @param   destCapacity Capacity of the dest buffer.
+  *   @param   status       A reference to a UErrorCode to receive any errors.
+  *   @return               Length of matching data,
+  *                         or -1 if no applicable match.
+  *   @stable ICU 3.0
+  */
+U_STABLE int32_t U_EXPORT2 
+uregex_group(URegularExpression *regexp,
+             int32_t             groupNum,
+             UChar              *dest,
+             int32_t             destCapacity,
+             UErrorCode          *status);
+
+
+/**
+  *   Returns the index in the input string of the start of the text matched by the
+  *   specified capture group during the previous match operation.  Return -1 if
+  *   the capture group was not part of the last match.
+  *   Group #0 refers to the complete range of matched text.
+  *   Group #1 refers to the text matched by the first set of capturing parentheses.
+  *
+  *    @param   regexp      The compiled regular expression.
+  *    @param   groupNum    The capture group number
+  *    @param   status      A reference to a UErrorCode to receive any errors.
+  *    @return              the starting position in the input of the text matched 
+  *                         by the specified group.
+  *    @stable ICU 3.0
+  */
+U_STABLE int32_t U_EXPORT2 
+uregex_start(URegularExpression *regexp,
+             int32_t             groupNum,
+             UErrorCode          *status);
+
+/**
+  *   Returns the index in the input string of the position following the end
+  *   of the text matched by the specified capture group.
+  *   Return -1 if the capture group was not part of the last match.
+  *   Group #0 refers to the complete range of matched text.
+  *   Group #1 refers to the text matched by the first set of capturing parentheses.
+  *
+  *    @param   regexp      The compiled regular expression.
+  *    @param   groupNum    The capture group number
+  *    @param   status      A reference to a UErrorCode to receive any errors.
+  *    @return              the index of the position following the last matched character.
+  *    @stable ICU 3.0
+  */
+U_STABLE int32_t U_EXPORT2 
+uregex_end(URegularExpression   *regexp,
+           int32_t               groupNum,
+           UErrorCode           *status);
+
+/**
+  *  Reset any saved state from the previous match.  Has the effect of
+  *  causing uregex_findNext to begin at the specified index, and causing
+  *  uregex_start(), uregex_end() and uregex_group() to return an error 
+  *  indicating that there is no match information available.  Clears any
+  *  match region that may have been set.
+  *
+  *    @param   regexp      The compiled regular expression.
+  *    @param   index       The position in the text at which a
+  *                         uregex_findNext() should begin searching.
+  *    @param   status      A reference to a UErrorCode to receive any errors.
+  *    @stable ICU 3.0
+  */
+U_STABLE void U_EXPORT2 
+uregex_reset(URegularExpression    *regexp,
+             int32_t               index,
+             UErrorCode            *status);
+             
+             
+/** Sets the limits of the matching region for this URegularExpression.
+  * The region is the part of the input string that will be considered when matching.
+  * Invoking this method resets any saved state from the previous match, 
+  * then sets the region to start at the index specified by the start parameter
+  * and end at the index specified by the end parameter.
+  *
+  * Depending on the transparency and anchoring being used (see useTransparentBounds
+  * and useAnchoringBounds), certain constructs such as anchors may behave differently
+  * at or around the boundaries of the region
+  *
+  * The function will fail if start is greater than limit, or if either index
+  *  is less than zero or greater than the length of the string being matched.
+  *
+  * @param regexp The compiled regular expression.
+  * @param regionStart  The index to begin searches at.
+  * @param regionLimit  The index to end searches at (exclusive).
+  * @param status A pointer to a UErrorCode to receive any errors.
+  * @draft ICU 4.0
+  */
+U_DRAFT void U_EXPORT2
+uregex_setRegion(URegularExpression   *regexp,
+                 int32_t               regionStart,
+                 int32_t               regionLimit,
+                 UErrorCode           *status);
+
+/**
+  * Reports the start index of the matching region. Any matches found are limited to
+  * to the region bounded by regionStart (inclusive) and regionEnd (exclusive).
+  *
+  * @param regexp The compiled regular expression.
+  * @param status A pointer to a UErrorCode to receive any errors.
+  * @return The starting index of this matcher's region.
+  * @draft ICU 4.0
+  */
+U_DRAFT int32_t U_EXPORT2
+uregex_regionStart(const  URegularExpression   *regexp,
+                          UErrorCode           *status);
+
+
+
+/**
+  * Reports the end index (exclusive) of the matching region for this URegularExpression.
+  * Any matches found are limited to to the region bounded by regionStart (inclusive)
+  * and regionEnd (exclusive).
+  *
+  * @param regexp The compiled regular expression.
+  * @param status A pointer to a UErrorCode to receive any errors.
+  * @return The ending point of this matcher's region.
+  * @draft ICU 4.0
+  */
+U_DRAFT int32_t U_EXPORT2
+uregex_regionEnd(const  URegularExpression   *regexp,
+                        UErrorCode           *status);
+
+/**
+  * Queries the transparency of region bounds for this URegularExpression.
+  * See useTransparentBounds for a description of transparent and opaque bounds.
+  * By default, matching boundaries are opaque.
+  *
+  * @param regexp The compiled regular expression.
+  * @param status A pointer to a UErrorCode to receive any errors.
+  * @return TRUE if this matcher is using opaque bounds, false if it is not.
+  * @draft ICU 4.0
+  */
+U_DRAFT UBool U_EXPORT2
+uregex_hasTransparentBounds(const  URegularExpression   *regexp,
+                                   UErrorCode           *status);
+
+
+/**
+  * Sets the transparency of region bounds for this URegularExpression.
+  * Invoking this function with an argument of TRUE will set matches to use transparent bounds.
+  * If the boolean argument is FALSE, then opaque bounds will be used.
+  *
+  * Using transparent bounds, the boundaries of the matching region are transparent
+  * to lookahead, lookbehind, and boundary matching constructs. Those constructs can
+  * see text beyond the boundaries of the region while checking for a match.
+  *
+  * With opaque bounds, no text outside of the matching region is visible to lookahead,
+  * lookbehind, and boundary matching constructs.
+  *
+  * By default, opaque bounds are used.
+  *
+  * @param   regexp The compiled regular expression.
+  * @param   b      TRUE for transparent bounds; FALSE for opaque bounds
+  * @param   status A pointer to a UErrorCode to receive any errors.
+  * @draft   ICU 4.0
+  **/
+U_DRAFT void U_EXPORT2  
+uregex_useTransparentBounds(URegularExpression   *regexp, 
+                            UBool                b,
+                            UErrorCode           *status);
+
+
+/**
+  * Return true if this URegularExpression is using anchoring bounds.
+  * By default, anchoring region bounds are used.
+  *
+  * @param  regexp The compiled regular expression.
+  * @param  status A pointer to a UErrorCode to receive any errors.
+  * @return TRUE if this matcher is using anchoring bounds.
+  * @draft  ICU 4.0
+  */
+U_DRAFT UBool U_EXPORT2
+uregex_hasAnchoringBounds(const  URegularExpression   *regexp,
+                                 UErrorCode           *status);
+
+
+/**
+  * Set whether this URegularExpression is using Anchoring Bounds for its region.
+  * With anchoring bounds, pattern anchors such as ^ and $ will match at the start
+  * and end of the region.  Without Anchoring Bounds, anchors will only match at
+  * the positions they would in the complete text.
+  *
+  * Anchoring Bounds are the default for regions.
+  *
+  * @param regexp The compiled regular expression.
+  * @param b      TRUE if to enable anchoring bounds; FALSE to disable them.
+  * @param status A pointer to a UErrorCode to receive any errors.
+  * @draft   ICU 4.0
+  */
+U_DRAFT void U_EXPORT2
+uregex_useAnchoringBounds(URegularExpression   *regexp,
+                          UBool                 b,
+                          UErrorCode           *status);
+
+/**
+  * Return TRUE if the most recent matching operation touched the
+  *  end of the text being processed.  In this case, additional input text could
+  *  change the results of that match.
+  *
+  *  @param regexp The compiled regular expression.
+  *  @param status A pointer to a UErrorCode to receive any errors.
+  *  @return  TRUE if the most recent match hit the end of input
+  *  @draft   ICU 4.0
+  */
+U_DRAFT UBool U_EXPORT2
+uregex_hitEnd(const  URegularExpression   *regexp,
+                     UErrorCode           *status);
+
+/**
+  * Return TRUE the most recent match succeeded and additional input could cause
+  * it to fail. If this function returns false and a match was found, then more input
+  * might change the match but the match won't be lost. If a match was not found,
+  * then requireEnd has no meaning.
+  *
+  * @param regexp The compiled regular expression.
+  * @param status A pointer to a UErrorCode to receive any errors.
+  * @return TRUE  if more input could cause the most recent match to no longer match.
+  * @draft  ICU 4.0
+  */
+U_DRAFT UBool U_EXPORT2   
+uregex_requireEnd(const  URegularExpression   *regexp,
+                         UErrorCode           *status);
+
+
+
+
+
+/**
+  *    Replaces every substring of the input that matches the pattern
+  *    with the given replacement string.  This is a convenience function that
+  *    provides a complete find-and-replace-all operation.
+  *
+  *    This method scans the input string looking for matches of the pattern. 
+  *    Input that is not part of any match is copied unchanged to the
+  *    destination buffer.  Matched regions are replaced in the output
+  *    buffer by the replacement string.   The replacement string may contain
+  *    references to capture groups; these take the form of $1, $2, etc.
+  *
+  *    @param   regexp             The compiled regular expression.
+  *    @param   replacementText    A string containing the replacement text.
+  *    @param   replacementLength  The length of the replacement string, or
+  *                                -1 if it is NUL terminated.
+  *    @param   destBuf            A (UChar *) buffer that will receive the result.
+  *    @param   destCapacity       The capacity of the desitnation buffer.
+  *    @param   status             A reference to a UErrorCode to receive any errors.
+  *    @return                     The length of the string resulting from the find
+  *                                and replace operation.  In the event that the
+  *                                destination capacity is inadequate, the return value
+  *                                is still the full length of the untruncated string.
+  *    @stable ICU 3.0
+  */
+U_STABLE int32_t U_EXPORT2 
+uregex_replaceAll(URegularExpression    *regexp,
+                  const UChar           *replacementText,
+                  int32_t                replacementLength,
+                  UChar                 *destBuf,
+                  int32_t                destCapacity,
+                  UErrorCode            *status);
+
+
+/**
+  *    Replaces the first substring of the input that matches the pattern
+  *    with the given replacement string.  This is a convenience function that
+  *    provides a complete find-and-replace operation.
+  *
+  *    This method scans the input string looking for a match of the pattern. 
+  *    All input that is not part of the match is copied unchanged to the
+  *    destination buffer.  The matched region is replaced in the output
+  *    buffer by the replacement string.   The replacement string may contain
+  *    references to capture groups; these take the form of $1, $2, etc.
+  *
+  *    @param   regexp             The compiled regular expression.
+  *    @param   replacementText    A string containing the replacement text.
+  *    @param   replacementLength  The length of the replacement string, or
+  *                                -1 if it is NUL terminated.
+  *    @param   destBuf            A (UChar *) buffer that will receive the result.
+  *    @param   destCapacity       The capacity of the desitnation buffer.
+  *    @param   status             a reference to a UErrorCode to receive any errors.
+  *    @return                     The length of the string resulting from the find
+  *                                and replace operation.  In the event that the
+  *                                destination capacity is inadequate, the return value
+  *                                is still the full length of the untruncated string.
+  *    @stable ICU 3.0
+  */
+U_STABLE int32_t U_EXPORT2 
+uregex_replaceFirst(URegularExpression  *regexp,
+                    const UChar         *replacementText,
+                    int32_t              replacementLength,
+                    UChar               *destBuf,
+                    int32_t              destCapacity,
+                    UErrorCode          *status);
+
+
+/**
+  *   Implements a replace operation intended to be used as part of an
+  *   incremental find-and-replace.
+  *
+  *   <p>The input string, starting from the end of the previous match and ending at
+  *   the start of the current match, is appended to the destination string.  Then the
+  *   replacement string is appended to the output string,
+  *   including handling any substitutions of captured text.</p>
+  *
+  *   <p>A note on preflight computation of buffersize and error handling:
+  *   Calls to uregex_appendReplacement() and uregex_appendTail() are
+  *   designed to be chained, one after another, with the destination
+  *   buffer pointer and buffer capacity updated after each in preparation
+  *   to for the next.  If the destination buffer is exhausted partway through such a
+  *   sequence, a U_BUFFER_OVERFLOW_ERROR status will be returned.  Normal
+  *   ICU conventions are for a function to perform no action if it is
+  *   called with an error status, but for this one case, uregex_appendRepacement()
+  *   will operate normally so that buffer size computations will complete
+  *   correctly.
+  *
+  *   <p>For simple, prepackaged, non-incremental find-and-replace
+  *      operations, see replaceFirst() or replaceAll().</p>
+  *
+  *   @param   regexp      The regular expression object.  
+  *   @param   replacementText The string that will replace the matched portion of the
+  *                        input string as it is copied to the destination buffer.
+  *                        The replacement text may contain references ($1, for
+  *                        example) to capture groups from the match.
+  *   @param   replacementLength  The length of the replacement text string,
+  *                        or -1 if the string is NUL terminated.
+  *   @param   destBuf     The buffer into which the results of the
+  *                        find-and-replace are placed.  On return, this pointer
+  *                        will be updated to refer to the beginning of the
+  *                        unused portion of buffer, leaving it in position for
+  *                        a subsequent call to this function.
+  *   @param   destCapacity The size of the output buffer,  On return, this
+  *                        parameter will be updated to reflect the space remaining
+  *                        unused in the output buffer.
+  *   @param   status      A reference to a UErrorCode to receive any errors. 
+  *   @return              The length of the result string.  In the event that
+  *                        destCapacity is inadequate, the full length of the
+  *                        untruncated output string is returned.
+  *
+  *   @stable ICU 3.0
+  *
+  */
+U_STABLE int32_t U_EXPORT2 
+uregex_appendReplacement(URegularExpression    *regexp,
+                  const UChar           *replacementText,
+                  int32_t                replacementLength,
+                  UChar                **destBuf,
+                  int32_t               *destCapacity,
+                  UErrorCode            *status);
+
+
+/**
+  * As the final step in a find-and-replace operation, append the remainder
+  * of the input string, starting at the position following the last match,
+  * to the destination string. <code>uregex_appendTail()</code> is intended 
+  *  to be invoked after one or more invocations of the
+  *  <code>uregex_appendReplacement()</code> function.
+  *
+  *   @param   regexp      The regular expression object.  This is needed to 
+  *                        obtain the input string and with the position
+  *                        of the last match within it.
+  *   @param   destBuf     The buffer in which the results of the
+  *                        find-and-replace are placed.  On return, the pointer
+  *                        will be updated to refer to the beginning of the
+  *                        unused portion of buffer.
+  *   @param   destCapacity The size of the output buffer,  On return, this
+  *                        value will be updated to reflect the space remaining
+  *                        unused in the output buffer.
+  *   @param   status      A reference to a UErrorCode to receive any errors. 
+  *   @return              The length of the result string.  In the event that
+  *                        destCapacity is inadequate, the full length of the
+  *                        untruncated output string is returned.
+  *
+  *   @stable ICU 3.0
+  */
+U_STABLE int32_t U_EXPORT2 
+uregex_appendTail(URegularExpression    *regexp,
+                  UChar                **destBuf,
+                  int32_t               *destCapacity,
+                  UErrorCode            *status);
+
+
+
+
+ /**
+   * Split a string into fields.  Somewhat like split() from Perl.
+   *  The pattern matches identify delimiters that separate the input
+   *  into fields.  The input data between the matches becomes the
+   *  fields themselves.
+   * <p>
+   *  Each of the fields is copied from the input string to the destination
+   *  buffer, and the NUL terminated.  The position of each field within
+   *  the destination buffer is returned in the destFields array.
+   *
+   *  Note:  another choice for the design of this function would be to not
+   *         copy the resulting fields at all, but to return indexes and
+   *         lengths within the source text.  
+   *           Advantages would be
+   *             o  Faster.  No Copying.
+   *             o  Nothing extra needed when field data may contain embedded NUL chars.
+   *             o  Less memory needed if working on large data.
+   *           Disadvantages
+   *             o  Less consistent with C++ split, which copies into an
+   *                array of UnicodeStrings.
+   *             o  No NUL termination, extracted fields would be less convenient
+   *                to use in most cases.
+   *             o  Possible problems in the future, when support Unicode Normalization
+   *                could cause the fields to not correspond exactly to
+   *                a range of the source text.
+   * 
+   *    @param   regexp      The compiled regular expression.
+   *    @param   destBuf     A (UChar *) buffer to receive the fields that
+   *                         are extracted from the input string. These
+   *                         field pointers will refer to positions within the
+   *                         destination buffer supplied by the caller.  Any
+   *                         extra positions within the destFields array will be
+   *                         set to NULL.
+   *    @param   destCapacity The capacity of the destBuf.
+   *    @param   requiredCapacity  The actual capacity required of the destBuf.
+   *                         If destCapacity is too small, requiredCapacity will return 
+   *                         the total capacity required to hold all of the output, and
+   *                         a U_BUFFER_OVERFLOW_ERROR will be returned.
+   *    @param   destFields  An array to be filled with the position of each
+   *                         of the extracted fields within destBuf.
+   *    @param   destFieldsCapacity  The number of elements in the destFields array.
+   *                If the number of fields found is less than destFieldsCapacity,
+   *                the extra destFields elements are set to zero.
+   *                If destFieldsCapacity is too small, the trailing part of the
+   *                input, including any field delimiters, is treated as if it
+   *                were the last field - it is copied to the destBuf, and
+   *                its position is in the destBuf is stored in the last element
+   *                of destFields.  This behavior mimics that of Perl.  It is not
+   *                an error condition, and no error status is returned when all destField
+   *                positions are used.
+   * @param status  A reference to a UErrorCode to receive any errors.
+   * @return        The number of fields into which the input string was split.
+   * @stable ICU 3.0
+   */
+U_STABLE int32_t U_EXPORT2 
+uregex_split(   URegularExpression      *regexp,
+                  UChar                 *destBuf,
+                  int32_t                destCapacity,
+                  int32_t               *requiredCapacity,
+                  UChar                 *destFields[],
+                  int32_t                destFieldsCapacity,
+                  UErrorCode            *status);
+
+
+
+
+/**
+ * Set a processing time limit for match operations with this URegularExpression.
+ *
+ * Some patterns, when matching certain strings, can run in exponential time.
+ * For practical purposes, the match operation may appear to be in an
+ * infinite loop.
+ * When a limit is set a match operation will fail with an error if the
+ * limit is exceeded.
+ * <p>
+ * The units of the limit are steps of the match engine.
+ * Correspondence with actual processor time will depend on the speed
+ * of the processor and the details of the specific pattern, but will
+ * typically be on the order of milliseconds.
+ * <p>
+ * By default, the matching time is not limited.
+ * <p>
+ *
+ * @param   regexp      The compiled regular expression.
+ * @param   limit       The limit value, or 0 for no limit.
+ * @param   status      A reference to a UErrorCode to receive any errors.
+ * @draft ICU 4.0
+ */
+U_DRAFT void U_EXPORT2
+uregex_setTimeLimit(URegularExpression      *regexp,
+                    int32_t                  limit,
+                    UErrorCode              *status);
+
+/**
+ * Get the time limit for for matches with this URegularExpression.
+ * A return value of zero indicates that there is no limit.
+ *
+ * @param   regexp      The compiled regular expression.
+ * @param   status      A reference to a UErrorCode to receive any errors.
+ * @return the maximum allowed time for a match, in units of processing steps.
+ * @draft ICU 4.0
+ */
+U_DRAFT int32_t U_EXPORT2
+uregex_getTimeLimit(const URegularExpression      *regexp,
+                          UErrorCode              *status);
+
+/**
+ * Set the amount of heap storage avaliable for use by the match backtracking stack.
+ * <p>
+ * ICU uses a backtracking regular expression engine, with the backtrack stack
+ * maintained on the heap.  This function sets the limit to the amount of memory
+ * that can be used  for this purpose.  A backtracking stack overflow will
+ * result in an error from the match operation that caused it.
+ * <p>
+ * A limit is desirable because a malicious or poorly designed pattern can use
+ * excessive memory, potentially crashing the process.  A limit is enabled
+ * by default.
+ * <p>
+ * @param   regexp      The compiled regular expression.
+ * @param   limit       The maximum size, in bytes, of the matching backtrack stack.
+ *                      A value of -1 means no limit.
+ *                      The limit must be greater than zero, or -1.
+ * @param   status      A reference to a UErrorCode to receive any errors.
+ *
+ * @draft ICU 4.0
+ */
+U_DRAFT void U_EXPORT2
+uregex_setStackLimit(URegularExpression      *regexp,
+                     int32_t                  limit,
+                     UErrorCode              *status);
+
+/**
+ * Get the size of the heap storage available for use by the back tracking stack.
+ *
+ * @return  the maximum backtracking stack size, in bytes, or zero if the
+ *          stack size is unlimited.
+ * @draft ICU 4.0
+ */
+U_DRAFT int32_t U_EXPORT2
+uregex_getStackLimit(const URegularExpression      *regexp,
+                           UErrorCode              *status);
+
+
+/**
+ * Function pointer for a regular expression matching callback function.
+ * When set, a callback function will be called periodically during matching
+ * operations.  If the call back function returns FALSE, the matching
+ * operation will be terminated early.
+ *
+ * Note:  the callback function must not call other functions on this
+ *        URegularExpression.
+ *
+ * @param context  context pointer.  The callback function will be invoked
+ *                 with the context specified at the time that
+ *                 uregex_setMatchCallback() is called.
+ * @param steps    the accumulated processing time, in match steps, 
+ *                 for this matching operation.
+ * @return         TRUE to continue the matching operation.
+ *                 FALSE to terminate the matching operation.
+ * @draft ICU 4.0
+ */
+U_CDECL_BEGIN
+typedef UBool U_CALLCONV URegexMatchCallback (
+                   const void *context,
+                   int32_t     steps);
+U_CDECL_END
+
+/**
+ * Set a callback function for this URegularExpression.
+ * During matching operations the function will be called periodically,
+ * giving the application the opportunity to terminate a long-running
+ * match.
+ *
+ * @param   regexp      The compiled regular expression.
+ * @param   callback    A pointer to the user-supplied callback function.
+ * @param   context     User context pointer.  The value supplied at the
+ *                      time the callback function is set will be saved
+ *                      and passed to the callback each time that it is called.
+ * @param   status      A reference to a UErrorCode to receive any errors.
+ * @draft ICU 4.0
+ */
+U_DRAFT void U_EXPORT2
+uregex_setMatchCallback(URegularExpression      *regexp,
+                        URegexMatchCallback     *callback,
+                        const void              *context,
+                        UErrorCode              *status);
+
+
+/**
+ *  Get the callback function for this URegularExpression.
+ *
+ * @param   regexp      The compiled regular expression.
+ * @param   callback    Out paramater, receives a pointer to the user-supplied 
+ *                      callback function.
+ * @param   context     Out parameter, receives the user context pointer that
+ *                      was set when uregex_setMatchCallback() was called.
+ * @param   status      A reference to a UErrorCode to receive any errors.
+ * @draft ICU 4.0
+ */
+U_DRAFT void U_EXPORT2
+uregex_getMatchCallback(const URegularExpression    *regexp,
+                        URegexMatchCallback        **callback,
+                        const void                 **context,
+                        UErrorCode                  *status);
+
+
+
+#endif   /*  !UCONFIG_NO_REGULAR_EXPRESSIONS  */
+#endif   /*  UREGEX_H  */


[37/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_replicator/src/couch_replicator_sup.erl
----------------------------------------------------------------------
diff --git a/apps/couch_replicator/src/couch_replicator_sup.erl b/apps/couch_replicator/src/couch_replicator_sup.erl
deleted file mode 100644
index 905e2cf..0000000
--- a/apps/couch_replicator/src/couch_replicator_sup.erl
+++ /dev/null
@@ -1,59 +0,0 @@
-
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_replicator_sup).
-
--behaviour(supervisor).
-
-%% API
--export([start_link/0]).
-
-%% Supervisor callbacks
--export([init/1]).
-
-%% Helper macro for declaring children of supervisor
--define(CHILD(I, Type), {I, {I, start_link, []}, permanent, 5000, Type, [I]}).
-
-%% ===================================================================
-%% API functions
-%% ===================================================================
-
-start_link() ->
-    supervisor:start_link({local, ?MODULE}, ?MODULE, []).
-
-%% ===================================================================
-%% Supervisor callbacks
-%% ===================================================================
-
-init([]) ->
-    Children = [
-        {couch_replication_event,
-            {gen_event, start_link, [{local, couch_replication}]},
-            permanent,
-            brutal_kill,
-            worker,
-            dynamic},
-        {couch_replicator_job_sup,
-            {couch_replicator_job_sup, start_link, []},
-            permanent,
-            infinity,
-            supervisor,
-            [couch_replicator_job_sup]},
-        {couch_replicator_manager_sup,
-            {couch_replicator_manager_sup, start_link, []},
-            permanent,
-            infinity,
-            supervisor,
-            [couch_replicator_manager_sup]}
-    ],
-    {ok, { {one_for_one, 10, 3600}, Children} }.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_replicator/src/couch_replicator_utils.erl
----------------------------------------------------------------------
diff --git a/apps/couch_replicator/src/couch_replicator_utils.erl b/apps/couch_replicator/src/couch_replicator_utils.erl
deleted file mode 100644
index 0baddc2..0000000
--- a/apps/couch_replicator/src/couch_replicator_utils.erl
+++ /dev/null
@@ -1,396 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_replicator_utils).
-
--export([parse_rep_doc/2]).
--export([open_db/1, close_db/1]).
--export([start_db_compaction_notifier/2, stop_db_compaction_notifier/1]).
--export([replication_id/2]).
--export([sum_stats/2]).
-
--include_lib("couch/include/couch_db.hrl").
--include("couch_replicator_api_wrap.hrl").
--include("couch_replicator.hrl").
--include_lib("ibrowse/include/ibrowse.hrl").
-
--import(couch_util, [
-    get_value/2,
-    get_value/3
-]).
-
-
-parse_rep_doc({Props}, UserCtx) ->
-    ProxyParams = parse_proxy_params(get_value(<<"proxy">>, Props, <<>>)),
-    Options = make_options(Props),
-    case get_value(cancel, Options, false) andalso
-        (get_value(id, Options, nil) =/= nil) of
-    true ->
-        {ok, #rep{options = Options, user_ctx = UserCtx}};
-    false ->
-        Source = parse_rep_db(get_value(<<"source">>, Props), ProxyParams, Options),
-        Target = parse_rep_db(get_value(<<"target">>, Props), ProxyParams, Options),
-        Rep = #rep{
-            source = Source,
-            target = Target,
-            options = Options,
-            user_ctx = UserCtx,
-            doc_id = get_value(<<"_id">>, Props, null)
-        },
-        {ok, Rep#rep{id = replication_id(Rep)}}
-    end.
-
-
-replication_id(#rep{options = Options} = Rep) ->
-    BaseId = replication_id(Rep, ?REP_ID_VERSION),
-    {BaseId, maybe_append_options([continuous, create_target], Options)}.
-
-
-% Versioned clauses for generating replication IDs.
-% If a change is made to how replications are identified,
-% please add a new clause and increase ?REP_ID_VERSION.
-
-replication_id(#rep{user_ctx = UserCtx} = Rep, 3) ->
-    UUID = couch_server:get_uuid(),
-    Src = get_rep_endpoint(UserCtx, Rep#rep.source),
-    Tgt = get_rep_endpoint(UserCtx, Rep#rep.target),
-    maybe_append_filters([UUID, Src, Tgt], Rep);
-
-replication_id(#rep{user_ctx = UserCtx} = Rep, 2) ->
-    {ok, HostName} = inet:gethostname(),
-    Port = case (catch mochiweb_socket_server:get(couch_httpd, port)) of
-    P when is_number(P) ->
-        P;
-    _ ->
-        % On restart we might be called before the couch_httpd process is
-        % started.
-        % TODO: we might be under an SSL socket server only, or both under
-        % SSL and a non-SSL socket.
-        % ... mochiweb_socket_server:get(https, port)
-        list_to_integer(couch_config:get("httpd", "port", "5984"))
-    end,
-    Src = get_rep_endpoint(UserCtx, Rep#rep.source),
-    Tgt = get_rep_endpoint(UserCtx, Rep#rep.target),
-    maybe_append_filters([HostName, Port, Src, Tgt], Rep);
-
-replication_id(#rep{user_ctx = UserCtx} = Rep, 1) ->
-    {ok, HostName} = inet:gethostname(),
-    Src = get_rep_endpoint(UserCtx, Rep#rep.source),
-    Tgt = get_rep_endpoint(UserCtx, Rep#rep.target),
-    maybe_append_filters([HostName, Src, Tgt], Rep).
-
-
-maybe_append_filters(Base,
-        #rep{source = Source, user_ctx = UserCtx, options = Options}) ->
-    Base2 = Base ++
-        case get_value(filter, Options) of
-        undefined ->
-            case get_value(doc_ids, Options) of
-            undefined ->
-                [];
-            DocIds ->
-                [DocIds]
-            end;
-        Filter ->
-            [filter_code(Filter, Source, UserCtx),
-                get_value(query_params, Options, {[]})]
-        end,
-    couch_util:to_hex(couch_util:md5(term_to_binary(Base2))).
-
-
-filter_code(Filter, Source, UserCtx) ->
-    {DDocName, FilterName} =
-    case re:run(Filter, "(.*?)/(.*)", [{capture, [1, 2], binary}]) of
-    {match, [DDocName0, FilterName0]} ->
-        {DDocName0, FilterName0};
-    _ ->
-        throw({error, <<"Invalid filter. Must match `ddocname/filtername`.">>})
-    end,
-    Db = case (catch couch_replicator_api_wrap:db_open(Source, [{user_ctx, UserCtx}])) of
-    {ok, Db0} ->
-        Db0;
-    DbError ->
-        DbErrorMsg = io_lib:format("Could not open source database `~s`: ~s",
-           [couch_replicator_api_wrap:db_uri(Source), couch_util:to_binary(DbError)]),
-        throw({error, iolist_to_binary(DbErrorMsg)})
-    end,
-    try
-        Body = case (catch couch_replicator_api_wrap:open_doc(
-            Db, <<"_design/", DDocName/binary>>, [ejson_body])) of
-        {ok, #doc{body = Body0}} ->
-            Body0;
-        DocError ->
-            DocErrorMsg = io_lib:format(
-                "Couldn't open document `_design/~s` from source "
-                "database `~s`: ~s", [DDocName, couch_replicator_api_wrap:db_uri(Source),
-                    couch_util:to_binary(DocError)]),
-            throw({error, iolist_to_binary(DocErrorMsg)})
-        end,
-        Code = couch_util:get_nested_json_value(
-            Body, [<<"filters">>, FilterName]),
-        re:replace(Code, [$^, "\s*(.*?)\s*", $$], "\\1", [{return, binary}])
-    after
-        couch_replicator_api_wrap:db_close(Db)
-    end.
-
-
-maybe_append_options(Options, RepOptions) ->
-    lists:foldl(fun(Option, Acc) ->
-        Acc ++
-        case get_value(Option, RepOptions, false) of
-        true ->
-            "+" ++ atom_to_list(Option);
-        false ->
-            ""
-        end
-    end, [], Options).
-
-
-get_rep_endpoint(_UserCtx, #httpdb{url=Url, headers=Headers, oauth=OAuth}) ->
-    DefaultHeaders = (#httpdb{})#httpdb.headers,
-    case OAuth of
-    nil ->
-        {remote, Url, Headers -- DefaultHeaders};
-    #oauth{} ->
-        {remote, Url, Headers -- DefaultHeaders, OAuth}
-    end;
-get_rep_endpoint(UserCtx, <<DbName/binary>>) ->
-    {local, DbName, UserCtx}.
-
-
-parse_rep_db({Props}, ProxyParams, Options) ->
-    Url = maybe_add_trailing_slash(get_value(<<"url">>, Props)),
-    {AuthProps} = get_value(<<"auth">>, Props, {[]}),
-    {BinHeaders} = get_value(<<"headers">>, Props, {[]}),
-    Headers = lists:ukeysort(1, [{?b2l(K), ?b2l(V)} || {K, V} <- BinHeaders]),
-    DefaultHeaders = (#httpdb{})#httpdb.headers,
-    OAuth = case get_value(<<"oauth">>, AuthProps) of
-    undefined ->
-        nil;
-    {OauthProps} ->
-        #oauth{
-            consumer_key = ?b2l(get_value(<<"consumer_key">>, OauthProps)),
-            token = ?b2l(get_value(<<"token">>, OauthProps)),
-            token_secret = ?b2l(get_value(<<"token_secret">>, OauthProps)),
-            consumer_secret = ?b2l(get_value(<<"consumer_secret">>, OauthProps)),
-            signature_method =
-                case get_value(<<"signature_method">>, OauthProps) of
-                undefined ->        hmac_sha1;
-                <<"PLAINTEXT">> ->  plaintext;
-                <<"HMAC-SHA1">> ->  hmac_sha1;
-                <<"RSA-SHA1">> ->   rsa_sha1
-                end
-        }
-    end,
-    #httpdb{
-        url = Url,
-        oauth = OAuth,
-        headers = lists:ukeymerge(1, Headers, DefaultHeaders),
-        ibrowse_options = lists:keysort(1,
-            [{socket_options, get_value(socket_options, Options)} |
-                ProxyParams ++ ssl_params(Url)]),
-        timeout = get_value(connection_timeout, Options),
-        http_connections = get_value(http_connections, Options),
-        retries = get_value(retries, Options)
-    };
-parse_rep_db(<<"http://", _/binary>> = Url, ProxyParams, Options) ->
-    parse_rep_db({[{<<"url">>, Url}]}, ProxyParams, Options);
-parse_rep_db(<<"https://", _/binary>> = Url, ProxyParams, Options) ->
-    parse_rep_db({[{<<"url">>, Url}]}, ProxyParams, Options);
-parse_rep_db(<<DbName/binary>>, _ProxyParams, _Options) ->
-    DbName.
-
-
-maybe_add_trailing_slash(Url) when is_binary(Url) ->
-    maybe_add_trailing_slash(?b2l(Url));
-maybe_add_trailing_slash(Url) ->
-    case lists:last(Url) of
-    $/ ->
-        Url;
-    _ ->
-        Url ++ "/"
-    end.
-
-
-make_options(Props) ->
-    Options = lists:ukeysort(1, convert_options(Props)),
-    DefWorkers = couch_config:get("replicator", "worker_processes", "4"),
-    DefBatchSize = couch_config:get("replicator", "worker_batch_size", "500"),
-    DefConns = couch_config:get("replicator", "http_connections", "20"),
-    DefTimeout = couch_config:get("replicator", "connection_timeout", "30000"),
-    DefRetries = couch_config:get("replicator", "retries_per_request", "10"),
-    UseCheckpoints = couch_config:get("replicator", "use_checkpoints", "true"),
-    DefCheckpointInterval = couch_config:get("replicator", "checkpoint_interval", "5000"),
-    {ok, DefSocketOptions} = couch_util:parse_term(
-        couch_config:get("replicator", "socket_options",
-            "[{keepalive, true}, {nodelay, false}]")),
-    lists:ukeymerge(1, Options, lists:keysort(1, [
-        {connection_timeout, list_to_integer(DefTimeout)},
-        {retries, list_to_integer(DefRetries)},
-        {http_connections, list_to_integer(DefConns)},
-        {socket_options, DefSocketOptions},
-        {worker_batch_size, list_to_integer(DefBatchSize)},
-        {worker_processes, list_to_integer(DefWorkers)},
-        {use_checkpoints, list_to_existing_atom(UseCheckpoints)},
-        {checkpoint_interval, list_to_integer(DefCheckpointInterval)}
-    ])).
-
-
-convert_options([])->
-    [];
-convert_options([{<<"cancel">>, V} | R]) ->
-    [{cancel, V} | convert_options(R)];
-convert_options([{IdOpt, V} | R]) when IdOpt =:= <<"_local_id">>;
-        IdOpt =:= <<"replication_id">>; IdOpt =:= <<"id">> ->
-    Id = lists:splitwith(fun(X) -> X =/= $+ end, ?b2l(V)),
-    [{id, Id} | convert_options(R)];
-convert_options([{<<"create_target">>, V} | R]) ->
-    [{create_target, V} | convert_options(R)];
-convert_options([{<<"continuous">>, V} | R]) ->
-    [{continuous, V} | convert_options(R)];
-convert_options([{<<"filter">>, V} | R]) ->
-    [{filter, V} | convert_options(R)];
-convert_options([{<<"query_params">>, V} | R]) ->
-    [{query_params, V} | convert_options(R)];
-convert_options([{<<"doc_ids">>, null} | R]) ->
-    convert_options(R);
-convert_options([{<<"doc_ids">>, V} | R]) ->
-    % Ensure same behaviour as old replicator: accept a list of percent
-    % encoded doc IDs.
-    DocIds = [?l2b(couch_httpd:unquote(Id)) || Id <- V],
-    [{doc_ids, DocIds} | convert_options(R)];
-convert_options([{<<"worker_processes">>, V} | R]) ->
-    [{worker_processes, couch_util:to_integer(V)} | convert_options(R)];
-convert_options([{<<"worker_batch_size">>, V} | R]) ->
-    [{worker_batch_size, couch_util:to_integer(V)} | convert_options(R)];
-convert_options([{<<"http_connections">>, V} | R]) ->
-    [{http_connections, couch_util:to_integer(V)} | convert_options(R)];
-convert_options([{<<"connection_timeout">>, V} | R]) ->
-    [{connection_timeout, couch_util:to_integer(V)} | convert_options(R)];
-convert_options([{<<"retries_per_request">>, V} | R]) ->
-    [{retries, couch_util:to_integer(V)} | convert_options(R)];
-convert_options([{<<"socket_options">>, V} | R]) ->
-    {ok, SocketOptions} = couch_util:parse_term(V),
-    [{socket_options, SocketOptions} | convert_options(R)];
-convert_options([{<<"since_seq">>, V} | R]) ->
-    [{since_seq, V} | convert_options(R)];
-convert_options([{<<"use_checkpoints">>, V} | R]) ->
-    [{use_checkpoints, V} | convert_options(R)];
-convert_options([{<<"checkpoint_interval">>, V} | R]) ->
-    [{checkpoint_interval, couch_util:to_integer(V)} | convert_options(R)];
-convert_options([_ | R]) -> % skip unknown option
-    convert_options(R).
-
-
-parse_proxy_params(ProxyUrl) when is_binary(ProxyUrl) ->
-    parse_proxy_params(?b2l(ProxyUrl));
-parse_proxy_params([]) ->
-    [];
-parse_proxy_params(ProxyUrl) ->
-    #url{
-        host = Host,
-        port = Port,
-        username = User,
-        password = Passwd
-    } = ibrowse_lib:parse_url(ProxyUrl),
-    [{proxy_host, Host}, {proxy_port, Port}] ++
-        case is_list(User) andalso is_list(Passwd) of
-        false ->
-            [];
-        true ->
-            [{proxy_user, User}, {proxy_password, Passwd}]
-        end.
-
-
-ssl_params(Url) ->
-    case ibrowse_lib:parse_url(Url) of
-    #url{protocol = https} ->
-        Depth = list_to_integer(
-            couch_config:get("replicator", "ssl_certificate_max_depth", "3")
-        ),
-        VerifyCerts = couch_config:get("replicator", "verify_ssl_certificates"),
-        CertFile = couch_config:get("replicator", "cert_file", nil),
-        KeyFile = couch_config:get("replicator", "key_file", nil),
-        Password = couch_config:get("replicator", "password", nil),
-        SslOpts = [{depth, Depth} | ssl_verify_options(VerifyCerts =:= "true")],
-        SslOpts1 = case CertFile /= nil andalso KeyFile /= nil of
-            true ->
-                case Password of
-                    nil ->
-                        [{certfile, CertFile}, {keyfile, KeyFile}] ++ SslOpts;
-                    _ ->
-                        [{certfile, CertFile}, {keyfile, KeyFile},
-                            {password, Password}] ++ SslOpts
-                end;
-            false -> SslOpts
-        end,
-        [{is_ssl, true}, {ssl_options, SslOpts1}];
-    #url{protocol = http} ->
-        []
-    end.
-
-ssl_verify_options(Value) ->
-    ssl_verify_options(Value, erlang:system_info(otp_release)).
-
-ssl_verify_options(true, OTPVersion) when OTPVersion >= "R14" ->
-    CAFile = couch_config:get("replicator", "ssl_trusted_certificates_file"),
-    [{verify, verify_peer}, {cacertfile, CAFile}];
-ssl_verify_options(false, OTPVersion) when OTPVersion >= "R14" ->
-    [{verify, verify_none}];
-ssl_verify_options(true, _OTPVersion) ->
-    CAFile = couch_config:get("replicator", "ssl_trusted_certificates_file"),
-    [{verify, 2}, {cacertfile, CAFile}];
-ssl_verify_options(false, _OTPVersion) ->
-    [{verify, 0}].
-
-
-open_db(#db{name = Name, user_ctx = UserCtx, options = Options}) ->
-    {ok, Db} = couch_db:open(Name, [{user_ctx, UserCtx} | Options]),
-    Db;
-open_db(HttpDb) ->
-    HttpDb.
-
-
-close_db(#db{} = Db) ->
-    couch_db:close(Db);
-close_db(_HttpDb) ->
-    ok.
-
-
-start_db_compaction_notifier(#db{name = DbName}, Server) ->
-    {ok, Notifier} = couch_db_update_notifier:start_link(
-        fun({compacted, DbName1}) when DbName1 =:= DbName ->
-                ok = gen_server:cast(Server, {db_compacted, DbName});
-            (_) ->
-                ok
-        end),
-    Notifier;
-start_db_compaction_notifier(_, _) ->
-    nil.
-
-
-stop_db_compaction_notifier(nil) ->
-    ok;
-stop_db_compaction_notifier(Notifier) ->
-    couch_db_update_notifier:stop(Notifier).
-
-
-sum_stats(#rep_stats{} = S1, #rep_stats{} = S2) ->
-    #rep_stats{
-        missing_checked =
-            S1#rep_stats.missing_checked + S2#rep_stats.missing_checked,
-        missing_found = S1#rep_stats.missing_found + S2#rep_stats.missing_found,
-        docs_read = S1#rep_stats.docs_read + S2#rep_stats.docs_read,
-        docs_written = S1#rep_stats.docs_written + S2#rep_stats.docs_written,
-        doc_write_failures =
-            S1#rep_stats.doc_write_failures + S2#rep_stats.doc_write_failures
-    }.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_replicator/src/couch_replicator_worker.erl
----------------------------------------------------------------------
diff --git a/apps/couch_replicator/src/couch_replicator_worker.erl b/apps/couch_replicator/src/couch_replicator_worker.erl
deleted file mode 100644
index 0f65900..0000000
--- a/apps/couch_replicator/src/couch_replicator_worker.erl
+++ /dev/null
@@ -1,515 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_replicator_worker).
--behaviour(gen_server).
-
-% public API
--export([start_link/5]).
-
-% gen_server callbacks
--export([init/1, terminate/2, code_change/3]).
--export([handle_call/3, handle_cast/2, handle_info/2]).
-
--include_lib("couch/include/couch_db.hrl").
--include("couch_replicator_api_wrap.hrl").
--include("couch_replicator.hrl").
-
-% TODO: maybe make both buffer max sizes configurable
--define(DOC_BUFFER_BYTE_SIZE, 512 * 1024).   % for remote targets
--define(DOC_BUFFER_LEN, 10).                 % for local targets, # of documents
--define(MAX_BULK_ATT_SIZE, 64 * 1024).
--define(MAX_BULK_ATTS_PER_DOC, 8).
--define(STATS_DELAY, 10000000).              % 10 seconds (in microseconds)
-
--define(inc_stat(StatPos, Stats, Inc),
-    setelement(StatPos, Stats, element(StatPos, Stats) + Inc)).
-
--import(couch_replicator_utils, [
-    open_db/1,
-    close_db/1,
-    start_db_compaction_notifier/2,
-    stop_db_compaction_notifier/1
-]).
--import(couch_util, [
-    to_binary/1,
-    get_value/2,
-    get_value/3
-]).
-
-
--record(batch, {
-    docs = [],
-    size = 0
-}).
-
--record(state, {
-    cp,
-    loop,
-    max_parallel_conns,
-    source,
-    target,
-    readers = [],
-    writer = nil,
-    pending_fetch = nil,
-    flush_waiter = nil,
-    stats = #rep_stats{},
-    source_db_compaction_notifier = nil,
-    target_db_compaction_notifier = nil,
-    batch = #batch{}
-}).
-
-
-
-start_link(Cp, #db{} = Source, Target, ChangesManager, _MaxConns) ->
-    Pid = spawn_link(fun() ->
-        erlang:put(last_stats_report, now()),
-        queue_fetch_loop(Source, Target, Cp, Cp, ChangesManager)
-    end),
-    {ok, Pid};
-
-start_link(Cp, Source, Target, ChangesManager, MaxConns) ->
-    gen_server:start_link(
-        ?MODULE, {Cp, Source, Target, ChangesManager, MaxConns}, []).
-
-
-init({Cp, Source, Target, ChangesManager, MaxConns}) ->
-    process_flag(trap_exit, true),
-    Parent = self(),
-    LoopPid = spawn_link(fun() ->
-        queue_fetch_loop(Source, Target, Parent, Cp, ChangesManager)
-    end),
-    erlang:put(last_stats_report, now()),
-    State = #state{
-        cp = Cp,
-        max_parallel_conns = MaxConns,
-        loop = LoopPid,
-        source = open_db(Source),
-        target = open_db(Target),
-        source_db_compaction_notifier =
-            start_db_compaction_notifier(Source, self()),
-        target_db_compaction_notifier =
-            start_db_compaction_notifier(Target, self())
-    },
-    {ok, State}.
-
-
-handle_call({fetch_doc, {_Id, _Revs, _PAs} = Params}, {Pid, _} = From,
-    #state{loop = Pid, readers = Readers, pending_fetch = nil,
-        source = Src, target = Tgt, max_parallel_conns = MaxConns} = State) ->
-    case length(Readers) of
-    Size when Size < MaxConns ->
-        Reader = spawn_doc_reader(Src, Tgt, Params),
-        NewState = State#state{
-            readers = [Reader | Readers]
-        },
-        {reply, ok, NewState};
-    _ ->
-        NewState = State#state{
-            pending_fetch = {From, Params}
-        },
-        {noreply, NewState}
-    end;
-
-handle_call({batch_doc, Doc}, From, State) ->
-    gen_server:reply(From, ok),
-    {noreply, maybe_flush_docs(Doc, State)};
-
-handle_call({add_stats, IncStats}, From, #state{stats = Stats} = State) ->
-    gen_server:reply(From, ok),
-    NewStats = couch_replicator_utils:sum_stats(Stats, IncStats),
-    NewStats2 = maybe_report_stats(State#state.cp, NewStats),
-    {noreply, State#state{stats = NewStats2}};
-
-handle_call(flush, {Pid, _} = From,
-    #state{loop = Pid, writer = nil, flush_waiter = nil,
-        target = Target, batch = Batch} = State) ->
-    State2 = case State#state.readers of
-    [] ->
-        State#state{writer = spawn_writer(Target, Batch)};
-    _ ->
-        State
-    end,
-    {noreply, State2#state{flush_waiter = From}}.
-
-
-handle_cast({db_compacted, DbName},
-    #state{source = #db{name = DbName} = Source} = State) ->
-    {ok, NewSource} = couch_db:reopen(Source),
-    {noreply, State#state{source = NewSource}};
-
-handle_cast({db_compacted, DbName},
-    #state{target = #db{name = DbName} = Target} = State) ->
-    {ok, NewTarget} = couch_db:reopen(Target),
-    {noreply, State#state{target = NewTarget}};
-
-handle_cast(Msg, State) ->
-    {stop, {unexpected_async_call, Msg}, State}.
-
-
-handle_info({'EXIT', Pid, normal}, #state{loop = Pid} = State) ->
-    #state{
-        batch = #batch{docs = []}, readers = [], writer = nil,
-        pending_fetch = nil, flush_waiter = nil
-    } = State,
-    {stop, normal, State};
-
-handle_info({'EXIT', Pid, normal}, #state{writer = Pid} = State) ->
-    {noreply, after_full_flush(State)};
-
-handle_info({'EXIT', Pid, normal}, #state{writer = nil} = State) ->
-    #state{
-        readers = Readers, writer = Writer, batch = Batch,
-        source = Source, target = Target,
-        pending_fetch = Fetch, flush_waiter = FlushWaiter
-    } = State,
-    case Readers -- [Pid] of
-    Readers ->
-        {noreply, State};
-    Readers2 ->
-        State2 = case Fetch of
-        nil ->
-            case (FlushWaiter =/= nil) andalso (Writer =:= nil) andalso
-                (Readers2 =:= [])  of
-            true ->
-                State#state{
-                    readers = Readers2,
-                    writer = spawn_writer(Target, Batch)
-                };
-            false ->
-                State#state{readers = Readers2}
-            end;
-        {From, FetchParams} ->
-            Reader = spawn_doc_reader(Source, Target, FetchParams),
-            gen_server:reply(From, ok),
-            State#state{
-                readers = [Reader | Readers2],
-                pending_fetch = nil
-            }
-        end,
-        {noreply, State2}
-    end;
-
-handle_info({'EXIT', Pid, Reason}, State) ->
-   {stop, {process_died, Pid, Reason}, State}.
-
-
-terminate(_Reason, State) ->
-    close_db(State#state.source),
-    close_db(State#state.target),
-    stop_db_compaction_notifier(State#state.source_db_compaction_notifier),
-    stop_db_compaction_notifier(State#state.target_db_compaction_notifier).
-
-
-code_change(_OldVsn, State, _Extra) ->
-    {ok, State}.
-
-
-queue_fetch_loop(Source, Target, Parent, Cp, ChangesManager) ->
-    ChangesManager ! {get_changes, self()},
-    receive
-    {closed, ChangesManager} ->
-        ok;
-    {changes, ChangesManager, Changes, ReportSeq} ->
-        Target2 = open_db(Target),
-        {IdRevs, Stats0} = find_missing(Changes, Target2),
-        case Source of
-        #db{} ->
-            Source2 = open_db(Source),
-            Stats = local_process_batch(
-                IdRevs, Cp, Source2, Target2, #batch{}, Stats0),
-            close_db(Source2);
-        #httpdb{} ->
-            ok = gen_server:call(Parent, {add_stats, Stats0}, infinity),
-            remote_process_batch(IdRevs, Parent),
-            {ok, Stats} = gen_server:call(Parent, flush, infinity)
-        end,
-        close_db(Target2),
-        ok = gen_server:call(Cp, {report_seq_done, ReportSeq, Stats}, infinity),
-        erlang:put(last_stats_report, now()),
-        ?LOG_DEBUG("Worker reported completion of seq ~p", [ReportSeq]),
-        queue_fetch_loop(Source, Target, Parent, Cp, ChangesManager)
-    end.
-
-
-local_process_batch([], _Cp, _Src, _Tgt, #batch{docs = []}, Stats) ->
-    Stats;
-
-local_process_batch([], Cp, Source, Target, #batch{docs = Docs, size = Size}, Stats) ->
-    case Target of
-    #httpdb{} ->
-        ?LOG_DEBUG("Worker flushing doc batch of size ~p bytes", [Size]);
-    #db{} ->
-        ?LOG_DEBUG("Worker flushing doc batch of ~p docs", [Size])
-    end,
-    Stats2 = flush_docs(Target, Docs),
-    Stats3 = couch_replicator_utils:sum_stats(Stats, Stats2),
-    local_process_batch([], Cp, Source, Target, #batch{}, Stats3);
-
-local_process_batch([IdRevs | Rest], Cp, Source, Target, Batch, Stats) ->
-    {ok, {_, DocList, Stats2, _}} = fetch_doc(
-        Source, IdRevs, fun local_doc_handler/2, {Target, [], Stats, Cp}),
-    {Batch2, Stats3} = lists:foldl(
-        fun(Doc, {Batch0, Stats0}) ->
-            {Batch1, S} = maybe_flush_docs(Target, Batch0, Doc),
-            {Batch1, couch_replicator_utils:sum_stats(Stats0, S)}
-        end,
-        {Batch, Stats2}, DocList),
-    local_process_batch(Rest, Cp, Source, Target, Batch2, Stats3).
-
-
-remote_process_batch([], _Parent) ->
-    ok;
-
-remote_process_batch([{Id, Revs, PAs} | Rest], Parent) ->
-    % When the source is a remote database, we fetch a single document revision
-    % per HTTP request. This is mostly to facilitate retrying of HTTP requests
-    % due to network transient failures. It also helps not exceeding the maximum
-    % URL length allowed by proxies and Mochiweb.
-    lists:foreach(
-        fun(Rev) ->
-            ok = gen_server:call(Parent, {fetch_doc, {Id, [Rev], PAs}}, infinity)
-        end,
-        Revs),
-    remote_process_batch(Rest, Parent).
-
-
-spawn_doc_reader(Source, Target, FetchParams) ->
-    Parent = self(),
-    spawn_link(fun() ->
-        Source2 = open_db(Source),
-        fetch_doc(
-            Source2, FetchParams, fun remote_doc_handler/2, {Parent, Target}),
-        close_db(Source2)
-    end).
-
-
-fetch_doc(Source, {Id, Revs, PAs}, DocHandler, Acc) ->
-    try
-        couch_replicator_api_wrap:open_doc_revs(
-            Source, Id, Revs, [{atts_since, PAs}, latest], DocHandler, Acc)
-    catch
-    throw:{missing_stub, _} ->
-        ?LOG_ERROR("Retrying fetch and update of document `~s` due to out of "
-            "sync attachment stubs. Missing revisions are: ~s",
-            [Id, couch_doc:revs_to_strs(Revs)]),
-        couch_replicator_api_wrap:open_doc_revs(Source, Id, Revs, [latest], DocHandler, Acc)
-    end.
-
-
-local_doc_handler({ok, Doc}, {Target, DocList, Stats, Cp}) ->
-    Stats2 = ?inc_stat(#rep_stats.docs_read, Stats, 1),
-    case batch_doc(Doc) of
-    true ->
-        {ok, {Target, [Doc | DocList], Stats2, Cp}};
-    false ->
-        ?LOG_DEBUG("Worker flushing doc with attachments", []),
-        Target2 = open_db(Target),
-        Success = (flush_doc(Target2, Doc) =:= ok),
-        close_db(Target2),
-        Stats3 = case Success of
-        true ->
-            ?inc_stat(#rep_stats.docs_written, Stats2, 1);
-        false ->
-            ?inc_stat(#rep_stats.doc_write_failures, Stats2, 1)
-        end,
-        Stats4 = maybe_report_stats(Cp, Stats3),
-        {ok, {Target, DocList, Stats4, Cp}}
-    end;
-local_doc_handler(_, Acc) ->
-    {ok, Acc}.
-
-
-remote_doc_handler({ok, #doc{atts = []} = Doc}, {Parent, _} = Acc) ->
-    ok = gen_server:call(Parent, {batch_doc, Doc}, infinity),
-    {ok, Acc};
-remote_doc_handler({ok, Doc}, {Parent, Target} = Acc) ->
-    % Immediately flush documents with attachments received from a remote
-    % source. The data property of each attachment is a function that starts
-    % streaming the attachment data from the remote source, therefore it's
-    % convenient to call it ASAP to avoid ibrowse inactivity timeouts.
-    Stats = #rep_stats{docs_read = 1},
-    ?LOG_DEBUG("Worker flushing doc with attachments", []),
-    Target2 = open_db(Target),
-    Success = (flush_doc(Target2, Doc) =:= ok),
-    close_db(Target2),
-    {Result, Stats2} = case Success of
-    true ->
-        {{ok, Acc}, ?inc_stat(#rep_stats.docs_written, Stats, 1)};
-    false ->
-        {{skip, Acc}, ?inc_stat(#rep_stats.doc_write_failures, Stats, 1)}
-    end,
-    ok = gen_server:call(Parent, {add_stats, Stats2}, infinity),
-    Result;
-remote_doc_handler(_, Acc) ->
-    {ok, Acc}.
-
-
-spawn_writer(Target, #batch{docs = DocList, size = Size}) ->
-    case {Target, Size > 0} of
-    {#httpdb{}, true} ->
-        ?LOG_DEBUG("Worker flushing doc batch of size ~p bytes", [Size]);
-    {#db{}, true} ->
-        ?LOG_DEBUG("Worker flushing doc batch of ~p docs", [Size]);
-    _ ->
-        ok
-    end,
-    Parent = self(),
-    spawn_link(
-        fun() ->
-            Target2 = open_db(Target),
-            Stats = flush_docs(Target2, DocList),
-            close_db(Target2),
-            ok = gen_server:call(Parent, {add_stats, Stats}, infinity)
-        end).
-
-
-after_full_flush(#state{stats = Stats, flush_waiter = Waiter} = State) ->
-    gen_server:reply(Waiter, {ok, Stats}),
-    erlang:put(last_stats_report, now()),
-    State#state{
-        stats = #rep_stats{},
-        flush_waiter = nil,
-        writer = nil,
-        batch = #batch{}
-    }.
-
-
-maybe_flush_docs(Doc,State) ->
-    #state{
-        target = Target, batch = Batch,
-        stats = Stats, cp = Cp
-    } = State,
-    {Batch2, WStats} = maybe_flush_docs(Target, Batch, Doc),
-    Stats2 = couch_replicator_utils:sum_stats(Stats, WStats),
-    Stats3 = ?inc_stat(#rep_stats.docs_read, Stats2, 1),
-    Stats4 = maybe_report_stats(Cp, Stats3),
-    State#state{stats = Stats4, batch = Batch2}.
-
-
-maybe_flush_docs(#httpdb{} = Target, Batch, Doc) ->
-    #batch{docs = DocAcc, size = SizeAcc} = Batch,
-    case batch_doc(Doc) of
-    false ->
-        ?LOG_DEBUG("Worker flushing doc with attachments", []),
-        case flush_doc(Target, Doc) of
-        ok ->
-            {Batch, #rep_stats{docs_written = 1}};
-        _ ->
-            {Batch, #rep_stats{doc_write_failures = 1}}
-        end;
-    true ->
-        JsonDoc = ?JSON_ENCODE(couch_doc:to_json_obj(Doc, [revs, attachments])),
-        case SizeAcc + iolist_size(JsonDoc) of
-        SizeAcc2 when SizeAcc2 > ?DOC_BUFFER_BYTE_SIZE ->
-            ?LOG_DEBUG("Worker flushing doc batch of size ~p bytes", [SizeAcc2]),
-            Stats = flush_docs(Target, [JsonDoc | DocAcc]),
-            {#batch{}, Stats};
-        SizeAcc2 ->
-            {#batch{docs = [JsonDoc | DocAcc], size = SizeAcc2}, #rep_stats{}}
-        end
-    end;
-
-maybe_flush_docs(#db{} = Target, #batch{docs = DocAcc, size = SizeAcc}, Doc) ->
-    case SizeAcc + 1 of
-    SizeAcc2 when SizeAcc2 >= ?DOC_BUFFER_LEN ->
-        ?LOG_DEBUG("Worker flushing doc batch of ~p docs", [SizeAcc2]),
-        Stats = flush_docs(Target, [Doc | DocAcc]),
-        {#batch{}, Stats};
-    SizeAcc2 ->
-        {#batch{docs = [Doc | DocAcc], size = SizeAcc2}, #rep_stats{}}
-    end.
-
-
-batch_doc(#doc{atts = []}) ->
-    true;
-batch_doc(#doc{atts = Atts}) ->
-    (length(Atts) =< ?MAX_BULK_ATTS_PER_DOC) andalso
-        lists:all(
-            fun(#att{disk_len = L, data = Data}) ->
-                (L =< ?MAX_BULK_ATT_SIZE) andalso (Data =/= stub)
-            end, Atts).
-
-
-flush_docs(_Target, []) ->
-    #rep_stats{};
-
-flush_docs(Target, DocList) ->
-    {ok, Errors} = couch_replicator_api_wrap:update_docs(
-        Target, DocList, [delay_commit], replicated_changes),
-    DbUri = couch_replicator_api_wrap:db_uri(Target),
-    lists:foreach(
-        fun({Props}) ->
-            ?LOG_ERROR("Replicator: couldn't write document `~s`, revision `~s`,"
-                " to target database `~s`. Error: `~s`, reason: `~s`.",
-                [get_value(id, Props, ""), get_value(rev, Props, ""), DbUri,
-                    get_value(error, Props, ""), get_value(reason, Props, "")])
-        end, Errors),
-    #rep_stats{
-        docs_written = length(DocList) - length(Errors),
-        doc_write_failures = length(Errors)
-    }.
-
-flush_doc(Target, #doc{id = Id, revs = {Pos, [RevId | _]}} = Doc) ->
-    try couch_replicator_api_wrap:update_doc(Target, Doc, [], replicated_changes) of
-    {ok, _} ->
-        ok;
-    Error ->
-        ?LOG_ERROR("Replicator: error writing document `~s` to `~s`: ~s",
-            [Id, couch_replicator_api_wrap:db_uri(Target), couch_util:to_binary(Error)]),
-        Error
-    catch
-    throw:{missing_stub, _} = MissingStub ->
-        throw(MissingStub);
-    throw:{Error, Reason} ->
-        ?LOG_ERROR("Replicator: couldn't write document `~s`, revision `~s`,"
-            " to target database `~s`. Error: `~s`, reason: `~s`.",
-            [Id, couch_doc:rev_to_str({Pos, RevId}),
-                couch_replicator_api_wrap:db_uri(Target), to_binary(Error), to_binary(Reason)]),
-        {error, Error};
-    throw:Err ->
-        ?LOG_ERROR("Replicator: couldn't write document `~s`, revision `~s`,"
-            " to target database `~s`. Error: `~s`.",
-            [Id, couch_doc:rev_to_str({Pos, RevId}),
-                couch_replicator_api_wrap:db_uri(Target), to_binary(Err)]),
-        {error, Err}
-    end.
-
-
-find_missing(DocInfos, Target) ->
-    {IdRevs, AllRevsCount} = lists:foldr(
-        fun(#doc_info{id = Id, revs = RevsInfo}, {IdRevAcc, CountAcc}) ->
-            Revs = [Rev || #rev_info{rev = Rev} <- RevsInfo],
-            {[{Id, Revs} | IdRevAcc], CountAcc + length(Revs)}
-        end,
-        {[], 0}, DocInfos),
-    {ok, Missing} = couch_replicator_api_wrap:get_missing_revs(Target, IdRevs),
-    MissingRevsCount = lists:foldl(
-        fun({_Id, MissingRevs, _PAs}, Acc) -> Acc + length(MissingRevs) end,
-        0, Missing),
-    Stats = #rep_stats{
-        missing_checked = AllRevsCount,
-        missing_found = MissingRevsCount
-    },
-    {Missing, Stats}.
-
-
-maybe_report_stats(Cp, Stats) ->
-    Now = now(),
-    case timer:now_diff(erlang:get(last_stats_report), Now) >= ?STATS_DELAY of
-    true ->
-        ok = gen_server:call(Cp, {add_stats, Stats}, infinity),
-        erlang:put(last_stats_report, Now),
-        #rep_stats{};
-    false ->
-        Stats
-    end.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_replicator/test/01-load.t
----------------------------------------------------------------------
diff --git a/apps/couch_replicator/test/01-load.t b/apps/couch_replicator/test/01-load.t
deleted file mode 100644
index 8bd82dd..0000000
--- a/apps/couch_replicator/test/01-load.t
+++ /dev/null
@@ -1,37 +0,0 @@
-#!/usr/bin/env escript
-%% -*- erlang -*-
-
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
-% Test that we can load each module.
-
-main(_) ->
-    test_util:init_code_path(),
-    Modules = [
-        couch_replicator_api_wrap,
-        couch_replicator_httpc,
-        couch_replicator_httpd,
-        couch_replicator_manager,
-        couch_replicator_notifier,
-        couch_replicator,
-        couch_replicator_worker,
-        couch_replicator_utils,
-        couch_replicator_job_sup
-    ],
-
-    etap:plan(length(Modules)),
-    lists:foreach(
-        fun(Module) ->
-            etap:loaded_ok(Module, lists:concat(["Loaded: ", Module]))
-        end, Modules),
-    etap:end_tests().

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_replicator/test/02-httpc-pool.t
----------------------------------------------------------------------
diff --git a/apps/couch_replicator/test/02-httpc-pool.t b/apps/couch_replicator/test/02-httpc-pool.t
deleted file mode 100755
index a7bde6c..0000000
--- a/apps/couch_replicator/test/02-httpc-pool.t
+++ /dev/null
@@ -1,250 +0,0 @@
-#!/usr/bin/env escript
-%% -*- erlang -*-
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
-main(_) ->
-    test_util:init_code_path(),
-
-    etap:plan(55),
-    case (catch test()) of
-        ok ->
-            etap:end_tests();
-        Other ->
-            etap:diag(io_lib:format("Test died abnormally: ~p", [Other])),
-            etap:bail(Other)
-    end,
-    ok.
-
-
-test() ->
-    couch_server_sup:start_link(test_util:config_files()),
-    ibrowse:start(),
-
-    test_pool_full(),
-    test_worker_dead_pool_non_full(),
-    test_worker_dead_pool_full(),
-
-    couch_server_sup:stop(),
-    ok.
-
-
-test_pool_full() ->
-    Pool = spawn_pool(),
-    Client1 = spawn_client(Pool),
-    Client2 = spawn_client(Pool),
-    Client3 = spawn_client(Pool),
-
-    etap:diag("Check that we can spawn the max number of connections."),
-    etap:is(ping_client(Client1), ok, "Client 1 started ok."),
-    etap:is(ping_client(Client2), ok, "Client 2 started ok."),
-    etap:is(ping_client(Client3), ok, "Client 3 started ok."),
-
-    Worker1 = get_client_worker(Client1, "1"),
-    Worker2 = get_client_worker(Client2, "2"),
-    Worker3 = get_client_worker(Client3, "3"),
-    etap:is(is_process_alive(Worker1), true, "Client's 1 worker is alive."),
-    etap:is(is_process_alive(Worker2), true, "Client's 2 worker is alive."),
-    etap:is(is_process_alive(Worker3), true, "Client's 3 worker is alive."),
-
-    etap:isnt(Worker1, Worker2, "Clients 1 and 2 got different workers."),
-    etap:isnt(Worker2, Worker3, "Clients 2 and 3 got different workers."),
-    etap:isnt(Worker1, Worker3, "Clients 1 and 3 got different workers."),
-
-    etap:diag("Check that client 4 blocks waiting for a worker."),
-    Client4 = spawn_client(Pool),
-    etap:is(ping_client(Client4), timeout, "Client 4 blocked while waiting."),
-
-    etap:diag("Check that stopping a client gives up its worker."),
-    etap:is(stop_client(Client1), ok, "First client stopped."),
-
-    etap:diag("And check that our blocked client has been unblocked."),
-    etap:is(ping_client(Client4), ok, "Client 4 was unblocked."),
-
-    Worker4 = get_client_worker(Client4, "4"),
-    etap:is(is_process_alive(Worker4), true, "Client's 4 worker is alive."),
-    etap:is(Worker4, Worker1, "Client 4 got worker that client 1 got before."),
-
-    lists:foreach(fun(C) -> ok = stop_client(C) end, [Client2, Client3, Client4]),
-    stop_pool(Pool).
-
-
-test_worker_dead_pool_non_full() ->
-    Pool = spawn_pool(),
-    Client1 = spawn_client(Pool),
-
-    etap:is(ping_client(Client1), ok, "Client 1 started ok."),
-    Worker1 = get_client_worker(Client1, "1"),
-    etap:is(is_process_alive(Worker1), true, "Client's 1 worker is alive."),
-
-    etap:diag("Kill client's 1 worker."),
-    etap:is(kill_client_worker(Client1), ok, "Killed client's 1 worker."),
-    etap:is(is_process_alive(Worker1), false, "Client's 1 worker process is dead."),
-
-    etap:is(stop_client(Client1), ok, "First client stopped and released its worker."),
-
-    Client2 = spawn_client(Pool),
-    etap:is(ping_client(Client2), ok, "Client 2 started ok."),
-    Worker2 = get_client_worker(Client2, "2"),
-    etap:isnt(Worker2, Worker1, "Client 2 got a different worker from client 1"),
-    etap:is(is_process_alive(Worker2), true, "Client's 2 worker is alive."),
-
-    etap:is(stop_client(Client2), ok, "Second client stopped."),
-    stop_pool(Pool).
-
-
-test_worker_dead_pool_full() ->
-    Pool = spawn_pool(),
-    Client1 = spawn_client(Pool),
-    Client2 = spawn_client(Pool),
-    Client3 = spawn_client(Pool),
-
-    etap:diag("Check that we can spawn the max number of connections."),
-    etap:is(ping_client(Client1), ok, "Client 1 started ok."),
-    etap:is(ping_client(Client2), ok, "Client 2 started ok."),
-    etap:is(ping_client(Client3), ok, "Client 3 started ok."),
-
-    Worker1 = get_client_worker(Client1, "1"),
-    Worker2 = get_client_worker(Client2, "2"),
-    Worker3 = get_client_worker(Client3, "3"),
-    etap:is(is_process_alive(Worker1), true, "Client's 1 worker is alive."),
-    etap:is(is_process_alive(Worker2), true, "Client's 2 worker is alive."),
-    etap:is(is_process_alive(Worker3), true, "Client's 3 worker is alive."),
-
-    etap:isnt(Worker1, Worker2, "Clients 1 and 2 got different workers."),
-    etap:isnt(Worker2, Worker3, "Clients 2 and 3 got different workers."),
-    etap:isnt(Worker1, Worker3, "Clients 1 and 3 got different workers."),
-
-    etap:diag("Check that client 4 blocks waiting for a worker."),
-    Client4 = spawn_client(Pool),
-    etap:is(ping_client(Client4), timeout, "Client 4 blocked while waiting."),
-
-    etap:diag("Kill client's 1 worker."),
-    etap:is(kill_client_worker(Client1), ok, "Killed client's 1 worker."),
-    etap:is(is_process_alive(Worker1), false, "Client's 1 worker process is dead."),
-
-    etap:diag("Check client 4 got unblocked after first worker's death"),
-    etap:is(ping_client(Client4), ok, "Client 4 not blocked anymore."),
-
-    Worker4 = get_client_worker(Client4, "4"),
-    etap:is(is_process_alive(Worker4), true, "Client's 4 worker is alive."),
-    etap:isnt(Worker4, Worker1, "Client 4 got a worker different from client 1."),
-    etap:isnt(Worker4, Worker2, "Client 4 got a worker different from client 2."),
-    etap:isnt(Worker4, Worker3, "Client 4 got a worker different from client 3."),
-
-    etap:diag("Check that stopping client 1 is a noop."),
-    etap:is(stop_client(Client1), ok, "First client stopped."),
-
-    etap:is(is_process_alive(Worker2), true, "Client's 2 worker still alive."),
-    etap:is(is_process_alive(Worker3), true, "Client's 3 worker still alive."),
-    etap:is(is_process_alive(Worker4), true, "Client's 4 worker still alive."),
-
-    etap:diag("Check that client 5 blocks waiting for a worker."),
-    Client5 = spawn_client(Pool),
-    etap:is(ping_client(Client5), timeout, "Client 5 blocked while waiting."),
-
-    etap:diag("Check that stopping client 2 gives up its worker."),
-    etap:is(stop_client(Client2), ok, "Second client stopped."),
-
-    etap:diag("Now check that client 5 has been unblocked."),
-    etap:is(ping_client(Client5), ok, "Client 5 was unblocked."),
-
-    Worker5 = get_client_worker(Client5, "5"),
-    etap:is(is_process_alive(Worker5), true, "Client's 5 worker is alive."),
-    etap:isnt(Worker5, Worker1, "Client 5 got a worker different from client 1."),
-    etap:is(Worker5, Worker2, "Client 5 got same worker as client 2."),
-    etap:isnt(Worker5, Worker3, "Client 5 got a worker different from client 3."),
-    etap:isnt(Worker5, Worker4, "Client 5 got a worker different from client 4."),
-
-    etap:is(is_process_alive(Worker3), true, "Client's 3 worker still alive."),
-    etap:is(is_process_alive(Worker4), true, "Client's 4 worker still alive."),
-    etap:is(is_process_alive(Worker5), true, "Client's 5 worker still alive."),
-
-    lists:foreach(fun(C) -> ok = stop_client(C) end, [Client3, Client4, Client5]),
-    stop_pool(Pool).
-
-
-spawn_client(Pool) ->
-    Parent = self(),
-    Ref = make_ref(),
-    Pid = spawn(fun() ->
-        {ok, Worker} = couch_replicator_httpc_pool:get_worker(Pool),
-        loop(Parent, Ref, Worker, Pool)
-    end),
-    {Pid, Ref}.
-
-
-ping_client({Pid, Ref}) ->
-    Pid ! ping,
-    receive
-        {pong, Ref} ->
-            ok
-    after 3000 ->
-        timeout
-    end.
-
-
-get_client_worker({Pid, Ref}, ClientName) ->
-    Pid ! get_worker,
-    receive
-        {worker, Ref, Worker} ->
-            Worker
-    after 3000 ->
-        etap:bail("Timeout getting client " ++ ClientName ++ " worker.")
-    end.
-
-
-stop_client({Pid, Ref}) ->
-    Pid ! stop,
-    receive
-        {stop, Ref} ->
-            ok
-    after 3000 ->
-        timeout
-    end.
-
-
-kill_client_worker({Pid, Ref}) ->
-    Pid ! get_worker,
-    receive
-        {worker, Ref, Worker} ->
-            exit(Worker, kill),
-            ok
-    after 3000 ->
-        timeout
-    end.
-
-
-loop(Parent, Ref, Worker, Pool) ->
-    receive
-        ping ->
-            Parent ! {pong, Ref},
-            loop(Parent, Ref, Worker, Pool);
-        get_worker  ->
-            Parent ! {worker, Ref, Worker},
-            loop(Parent, Ref, Worker, Pool);
-        stop ->
-            couch_replicator_httpc_pool:release_worker(Pool, Worker),
-            Parent ! {stop, Ref}
-    end.
-
-
-spawn_pool() ->
-    Host = couch_config:get("httpd", "bind_address", "127.0.0.1"),
-    Port = couch_config:get("httpd", "port", "5984"),
-    {ok, Pool} = couch_replicator_httpc_pool:start_link(
-        "http://" ++ Host ++ ":5984", [{max_connections, 3}]),
-    Pool.
-
-
-stop_pool(Pool) ->
-    ok = couch_replicator_httpc_pool:stop(Pool).

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_replicator/test/03-replication-compact.t
----------------------------------------------------------------------
diff --git a/apps/couch_replicator/test/03-replication-compact.t b/apps/couch_replicator/test/03-replication-compact.t
deleted file mode 100755
index 7c4d38c..0000000
--- a/apps/couch_replicator/test/03-replication-compact.t
+++ /dev/null
@@ -1,488 +0,0 @@
-#!/usr/bin/env escript
-%% -*- erlang -*-
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
-% Verify that compacting databases that are being used as the source or
-% target of a replication doesn't affect the replication and that the
-% replication doesn't hold their reference counters forever.
-
--define(b2l(B), binary_to_list(B)).
-
--record(user_ctx, {
-    name = null,
-    roles = [],
-    handler
-}).
-
--record(db, {
-    main_pid = nil,
-    update_pid = nil,
-    compactor_pid = nil,
-    instance_start_time, % number of microsecs since jan 1 1970 as a binary string
-    fd,
-    updater_fd,
-    fd_ref_counter,
-    header = nil,
-    committed_update_seq,
-    fulldocinfo_by_id_btree,
-    docinfo_by_seq_btree,
-    local_docs_btree,
-    update_seq,
-    name,
-    filepath,
-    validate_doc_funs = [],
-    security = [],
-    security_ptr = nil,
-    user_ctx = #user_ctx{},
-    waiting_delayed_commit = nil,
-    revs_limit = 1000,
-    fsync_options = [],
-    options = [],
-    compression,
-    before_doc_update,
-    after_doc_read
-}).
-
--record(rep, {
-    id,
-    source,
-    target,
-    options,
-    user_ctx,
-    doc_id
-}).
-
-
-source_db_name() -> <<"couch_test_rep_db_a">>.
-target_db_name() -> <<"couch_test_rep_db_b">>.
-
-
-main(_) ->
-    test_util:init_code_path(),
-
-    etap:plan(376),
-    case (catch test()) of
-        ok ->
-            etap:end_tests();
-        Other ->
-            etap:diag(io_lib:format("Test died abnormally: ~p", [Other])),
-            etap:bail(Other)
-    end,
-    ok.
-
-
-test() ->
-    couch_server_sup:start_link(test_util:config_files()),
-    ibrowse:start(),
-
-    Pairs = [
-        {source_db_name(), target_db_name()},
-        {{remote, source_db_name()}, target_db_name()},
-        {source_db_name(), {remote, target_db_name()}},
-        {{remote, source_db_name()}, {remote, (target_db_name())}}
-    ],
-
-    lists:foreach(
-        fun({Source, Target}) ->
-            {ok, SourceDb} = create_db(source_db_name()),
-            etap:is(couch_db:is_idle(SourceDb), true,
-                "Source database is idle before starting replication"),
-
-            {ok, TargetDb} = create_db(target_db_name()),
-            etap:is(couch_db:is_idle(TargetDb), true,
-                "Target database is idle before starting replication"),
-
-            {ok, RepPid, RepId} = replicate(Source, Target),
-            check_active_tasks(RepPid, RepId, Source, Target),
-            {ok, DocsWritten} = populate_and_compact_test(
-                RepPid, SourceDb, TargetDb),
-
-            wait_target_in_sync(DocsWritten, TargetDb),
-            check_active_tasks(RepPid, RepId, Source, Target),
-            cancel_replication(RepId, RepPid),
-            compare_dbs(SourceDb, TargetDb),
-
-            delete_db(SourceDb),
-            delete_db(TargetDb),
-            couch_server_sup:stop(),
-            ok = timer:sleep(1000),
-            couch_server_sup:start_link(test_util:config_files())
-        end,
-        Pairs),
-
-    couch_server_sup:stop(),
-    ok.
-
-
-populate_and_compact_test(RepPid, SourceDb0, TargetDb0) ->
-    etap:is(is_process_alive(RepPid), true, "Replication process is alive"),
-    check_db_alive("source", SourceDb0),
-    check_db_alive("target", TargetDb0),
-
-    Writer = spawn_writer(SourceDb0),
-
-    lists:foldl(
-        fun(_, {SourceDb, TargetDb, DocCount}) ->
-            pause_writer(Writer),
-
-            compact_db("source", SourceDb),
-            etap:is(is_process_alive(RepPid), true,
-                "Replication process is alive after source database compaction"),
-            check_db_alive("source", SourceDb),
-            check_ref_counter("source", SourceDb),
-
-            compact_db("target", TargetDb),
-            etap:is(is_process_alive(RepPid), true,
-                "Replication process is alive after target database compaction"),
-            check_db_alive("target", TargetDb),
-            check_ref_counter("target", TargetDb),
-
-            {ok, SourceDb2} = reopen_db(SourceDb),
-            {ok, TargetDb2} = reopen_db(TargetDb),
-
-            resume_writer(Writer),
-            wait_writer(Writer, DocCount),
-
-            compact_db("source", SourceDb2),
-            etap:is(is_process_alive(RepPid), true,
-                "Replication process is alive after source database compaction"),
-            check_db_alive("source", SourceDb2),
-            pause_writer(Writer),
-            check_ref_counter("source", SourceDb2),
-            resume_writer(Writer),
-
-            compact_db("target", TargetDb2),
-            etap:is(is_process_alive(RepPid), true,
-                "Replication process is alive after target database compaction"),
-            check_db_alive("target", TargetDb2),
-            pause_writer(Writer),
-            check_ref_counter("target", TargetDb2),
-            resume_writer(Writer),
-
-            {ok, SourceDb3} = reopen_db(SourceDb2),
-            {ok, TargetDb3} = reopen_db(TargetDb2),
-            {SourceDb3, TargetDb3, DocCount + 50}
-        end,
-        {SourceDb0, TargetDb0, 50}, lists:seq(1, 5)),
-
-    DocsWritten = stop_writer(Writer),
-    {ok, DocsWritten}.
-
-
-check_db_alive(Type, #db{main_pid = Pid}) ->
-    etap:is(is_process_alive(Pid), true,
-        "Local " ++ Type ++ " database main pid is alive").
-
-
-compact_db(Type, #db{name = Name}) ->
-    {ok, Db} = couch_db:open_int(Name, []),
-    {ok, CompactPid} = couch_db:start_compact(Db),
-    MonRef = erlang:monitor(process, CompactPid),
-    receive
-    {'DOWN', MonRef, process, CompactPid, normal} ->
-        ok;
-    {'DOWN', MonRef, process, CompactPid, Reason} ->
-        etap:bail("Error compacting " ++ Type ++ " database " ++ ?b2l(Name) ++
-            ": " ++ couch_util:to_list(Reason))
-    after 30000 ->
-        etap:bail("Compaction for " ++ Type ++ " database " ++ ?b2l(Name) ++
-            " didn't finish")
-    end,
-    ok = couch_db:close(Db).
-
-
-check_ref_counter(Type, #db{name = Name, fd_ref_counter = OldRefCounter}) ->
-    MonRef = erlang:monitor(process, OldRefCounter),
-    receive
-    {'DOWN', MonRef, process, OldRefCounter, _} ->
-        etap:diag("Old " ++ Type ++ " database ref counter terminated")
-    after 30000 ->
-        etap:bail("Old " ++ Type ++ " database ref counter didn't terminate")
-    end,
-    {ok, #db{fd_ref_counter = NewRefCounter} = Db} = couch_db:open_int(Name, []),
-    ok = couch_db:close(Db),
-    etap:isnt(
-        NewRefCounter, OldRefCounter, Type ++ " database has new ref counter").
-
-
-reopen_db(#db{name = Name}) ->
-    {ok, Db} = couch_db:open_int(Name, []),
-    ok = couch_db:close(Db),
-    {ok, Db}.
-
-
-wait_target_in_sync(DocCount, #db{name = TargetName}) ->
-    wait_target_in_sync_loop(DocCount, TargetName, 300).
-
-
-wait_target_in_sync_loop(_DocCount, _TargetName, 0) ->
-    etap:bail("Could not get source and target databases in sync");
-wait_target_in_sync_loop(DocCount, TargetName, RetriesLeft) ->
-    {ok, Target} = couch_db:open_int(TargetName, []),
-    {ok, TargetInfo} = couch_db:get_db_info(Target),
-    ok = couch_db:close(Target),
-    TargetDocCount = couch_util:get_value(doc_count, TargetInfo),
-    case TargetDocCount == DocCount of
-    true ->
-        etap:diag("Source and target databases are in sync");
-    false ->
-        ok = timer:sleep(100),
-        wait_target_in_sync_loop(DocCount, TargetName, RetriesLeft - 1)
-    end.
-
-
-compare_dbs(#db{name = SourceName}, #db{name = TargetName}) ->
-    {ok, SourceDb} = couch_db:open_int(SourceName, []),
-    {ok, TargetDb} = couch_db:open_int(TargetName, []),
-    Fun = fun(FullDocInfo, _, Acc) ->
-        {ok, Doc} = couch_db:open_doc(SourceDb, FullDocInfo),
-        {Props} = DocJson = couch_doc:to_json_obj(Doc, [attachments]),
-        DocId = couch_util:get_value(<<"_id">>, Props),
-        DocTarget = case couch_db:open_doc(TargetDb, DocId) of
-        {ok, DocT} ->
-            DocT;
-        Error ->
-            etap:bail("Error opening document '" ++ ?b2l(DocId) ++
-                "' from target: " ++ couch_util:to_list(Error))
-        end,
-        DocTargetJson = couch_doc:to_json_obj(DocTarget, [attachments]),
-        case DocTargetJson of
-        DocJson ->
-            ok;
-        _ ->
-            etap:bail("Content from document '" ++ ?b2l(DocId) ++
-                "' differs in target database")
-        end,
-        {ok, Acc}
-    end,
-    {ok, _, _} = couch_db:enum_docs(SourceDb, Fun, [], []),
-    etap:diag("Target database has the same documents as the source database"),
-    ok = couch_db:close(SourceDb),
-    ok = couch_db:close(TargetDb).
-
-
-check_active_tasks(RepPid, {BaseId, Ext} = _RepId, Src, Tgt) ->
-    Source = case Src of
-    {remote, NameSrc} ->
-        <<(db_url(NameSrc))/binary, $/>>;
-    _ ->
-        Src
-    end,
-    Target = case Tgt of
-    {remote, NameTgt} ->
-        <<(db_url(NameTgt))/binary, $/>>;
-    _ ->
-        Tgt
-    end,
-    FullRepId = list_to_binary(BaseId ++ Ext),
-    Pid = list_to_binary(pid_to_list(RepPid)),
-    [RepTask] = couch_task_status:all(),
-    etap:is(couch_util:get_value(pid, RepTask), Pid,
-        "_active_tasks entry has correct pid property"),
-    etap:is(couch_util:get_value(replication_id, RepTask), FullRepId,
-        "_active_tasks entry has right replication id"),
-    etap:is(couch_util:get_value(continuous, RepTask), true,
-        "_active_tasks entry has continuous property set to true"),
-    etap:is(couch_util:get_value(source, RepTask), Source,
-        "_active_tasks entry has correct source property"),
-    etap:is(couch_util:get_value(target, RepTask), Target,
-        "_active_tasks entry has correct target property"),
-    etap:is(is_integer(couch_util:get_value(docs_read, RepTask)), true,
-        "_active_tasks entry has integer docs_read property"),
-    etap:is(is_integer(couch_util:get_value(docs_written, RepTask)), true,
-        "_active_tasks entry has integer docs_written property"),
-    etap:is(is_integer(couch_util:get_value(doc_write_failures, RepTask)), true,
-        "_active_tasks entry has integer doc_write_failures property"),
-    etap:is(is_integer(couch_util:get_value(revisions_checked, RepTask)), true,
-        "_active_tasks entry has integer revisions_checked property"),
-    etap:is(is_integer(couch_util:get_value(missing_revisions_found, RepTask)), true,
-        "_active_tasks entry has integer missing_revisions_found property"),
-    etap:is(is_integer(couch_util:get_value(checkpointed_source_seq, RepTask)), true,
-        "_active_tasks entry has integer checkpointed_source_seq property"),
-    etap:is(is_integer(couch_util:get_value(source_seq, RepTask)), true,
-        "_active_tasks entry has integer source_seq property"),
-    Progress = couch_util:get_value(progress, RepTask),
-    etap:is(is_integer(Progress), true,
-        "_active_tasks entry has an integer progress property"),
-    etap:is(Progress =< 100, true, "Progress is not greater than 100%").
-
-
-wait_writer(Pid, NumDocs) ->
-    case get_writer_num_docs_written(Pid) of
-    N when N >= NumDocs ->
-        ok;
-    _ ->
-        wait_writer(Pid, NumDocs)
-    end.
-
-
-spawn_writer(Db) ->
-    Parent = self(),
-    Pid = spawn(fun() -> writer_loop(Db, Parent, 0) end),
-    etap:diag("Started source database writer"),
-    Pid.
-
-
-pause_writer(Pid) ->
-    Ref = make_ref(),
-    Pid ! {pause, Ref},
-    receive
-    {paused, Ref} ->
-        ok
-    after 30000 ->
-        etap:bail("Failed to pause source database writer")
-    end.
-
-
-resume_writer(Pid) ->
-    Ref = make_ref(),
-    Pid ! {continue, Ref},
-    receive
-    {ok, Ref} ->
-        ok
-    after 30000 ->
-        etap:bail("Failed to unpause source database writer")
-    end.
-
-
-get_writer_num_docs_written(Pid) ->
-    Ref = make_ref(),
-    Pid ! {get_count, Ref},
-    receive
-    {count, Ref, Count} ->
-        Count
-    after 30000 ->
-        etap:bail("Timeout getting number of documents written from "
-            "source database writer")
-    end.
-
-
-stop_writer(Pid) ->
-    Ref = make_ref(),
-    Pid ! {stop, Ref},
-    receive
-    {stopped, Ref, DocsWritten} ->
-        MonRef = erlang:monitor(process, Pid),
-        receive
-        {'DOWN', MonRef, process, Pid, _Reason} ->
-            etap:diag("Stopped source database writer"),
-            DocsWritten
-        after 30000 ->
-            etap:bail("Timeout stopping source database writer")
-        end
-    after 30000 ->
-        etap:bail("Timeout stopping source database writer")
-    end.
-
-
-writer_loop(#db{name = DbName}, Parent, Counter) ->
-    maybe_pause(Parent, Counter),
-    Doc = couch_doc:from_json_obj({[
-        {<<"_id">>, list_to_binary(integer_to_list(Counter + 1))},
-        {<<"value">>, Counter + 1},
-        {<<"_attachments">>, {[
-            {<<"icon1.png">>, {[
-                {<<"data">>, base64:encode(att_data())},
-                {<<"content_type">>, <<"image/png">>}
-            ]}},
-            {<<"icon2.png">>, {[
-                {<<"data">>, base64:encode(iolist_to_binary(
-                    [att_data(), att_data()]))},
-                {<<"content_type">>, <<"image/png">>}
-            ]}}
-        ]}}
-    ]}),
-    maybe_pause(Parent, Counter),
-    {ok, Db} = couch_db:open_int(DbName, []),
-    {ok, _} = couch_db:update_doc(Db, Doc, []),
-    ok = couch_db:close(Db),
-    receive
-    {get_count, Ref} ->
-        Parent ! {count, Ref, Counter + 1},
-        writer_loop(Db, Parent, Counter + 1);
-    {stop, Ref} ->
-        Parent ! {stopped, Ref, Counter + 1}
-    after 0 ->
-        ok = timer:sleep(500),
-        writer_loop(Db, Parent, Counter + 1)
-    end.
-
-
-maybe_pause(Parent, Counter) ->
-    receive
-    {get_count, Ref} ->
-        Parent ! {count, Ref, Counter};
-    {pause, Ref} ->
-        Parent ! {paused, Ref},
-        receive {continue, Ref2} -> Parent ! {ok, Ref2} end
-    after 0 ->
-        ok
-    end.
-
-
-db_url(DbName) ->
-    iolist_to_binary([
-        "http://", couch_config:get("httpd", "bind_address", "127.0.0.1"),
-        ":", integer_to_list(mochiweb_socket_server:get(couch_httpd, port)),
-        "/", DbName
-    ]).
-
-
-create_db(DbName) ->
-    {ok, Db} = couch_db:create(
-        DbName,
-        [{user_ctx, #user_ctx{roles = [<<"_admin">>]}}, overwrite]),
-    couch_db:close(Db),
-    {ok, Db}.
-
-
-delete_db(#db{name = DbName, main_pid = Pid}) ->
-    ok = couch_server:delete(
-        DbName, [{user_ctx, #user_ctx{roles = [<<"_admin">>]}}]),
-    MonRef = erlang:monitor(process, Pid),
-    receive
-    {'DOWN', MonRef, process, Pid, _Reason} ->
-        ok
-    after 30000 ->
-        etap:bail("Timeout deleting database")
-    end.
-
-
-replicate({remote, Db}, Target) ->
-    replicate(db_url(Db), Target);
-
-replicate(Source, {remote, Db}) ->
-    replicate(Source, db_url(Db));
-
-replicate(Source, Target) ->
-    RepObject = {[
-        {<<"source">>, Source},
-        {<<"target">>, Target},
-        {<<"continuous">>, true}
-    ]},
-    {ok, Rep} = couch_replicator_utils:parse_rep_doc(
-        RepObject, #user_ctx{roles = [<<"_admin">>]}),
-    {ok, Pid} = couch_replicator:async_replicate(Rep),
-    {ok, Pid, Rep#rep.id}.
-
-
-cancel_replication(RepId, RepPid) ->
-    {ok, _} = couch_replicator:cancel_replication(RepId),
-    etap:is(is_process_alive(RepPid), false,
-        "Replication process is no longer alive after cancel").
-
-
-att_data() ->
-    {ok, Data} = file:read_file(
-        test_util:source_file("share/www/image/logo.png")),
-    Data.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_replicator/test/04-replication-large-atts.t
----------------------------------------------------------------------
diff --git a/apps/couch_replicator/test/04-replication-large-atts.t b/apps/couch_replicator/test/04-replication-large-atts.t
deleted file mode 100755
index a7063c7..0000000
--- a/apps/couch_replicator/test/04-replication-large-atts.t
+++ /dev/null
@@ -1,267 +0,0 @@
-#!/usr/bin/env escript
-%% -*- erlang -*-
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
-% Test replication of large attachments. Verify that both source and
-% target have the same attachment data and metadata.
-
--define(b2l(Bin), binary_to_list(Bin)).
-
--record(user_ctx, {
-    name = null,
-    roles = [],
-    handler
-}).
-
--record(doc, {
-    id = <<"">>,
-    revs = {0, []},
-    body = {[]},
-    atts = [],
-    deleted = false,
-    meta = []
-}).
-
--record(att, {
-    name,
-    type,
-    att_len,
-    disk_len,
-    md5= <<>>,
-    revpos=0,
-    data,
-    encoding=identity
-}).
-
-
-source_db_name() -> <<"couch_test_rep_db_a">>.
-target_db_name() -> <<"couch_test_rep_db_b">>.
-
-
-main(_) ->
-    test_util:init_code_path(),
-
-    etap:plan(1192),
-    case (catch test()) of
-        ok ->
-            etap:end_tests();
-        Other ->
-            etap:diag(io_lib:format("Test died abnormally: ~p", [Other])),
-            etap:bail(Other)
-    end,
-    ok.
-
-
-test() ->
-    couch_server_sup:start_link(test_util:config_files()),
-    application:start(ibrowse),
-    application:start(crypto),
-    couch_config:set("attachments", "compressible_types", "text/*", false),
-
-    Pairs = [
-        {source_db_name(), target_db_name()},
-        {{remote, source_db_name()}, target_db_name()},
-        {source_db_name(), {remote, target_db_name()}},
-        {{remote, source_db_name()}, {remote, (target_db_name())}}
-    ],
-
-    {ok, SourceDb} = create_db(source_db_name()),
-    etap:diag("Populating source database"),
-    populate_db(SourceDb, 11),
-    ok = couch_db:close(SourceDb),
-
-    lists:foreach(
-        fun({Source, Target}) ->
-            etap:diag("Creating target database"),
-            {ok, TargetDb} = create_db(target_db_name()),
-
-            ok = couch_db:close(TargetDb),
-            etap:diag("Triggering replication"),
-            replicate(Source, Target),
-            etap:diag("Replication finished, comparing source and target databases"),
-            compare_dbs(SourceDb, TargetDb),
-
-            etap:diag("Deleting target database"),
-            delete_db(TargetDb),
-            ok = timer:sleep(1000)
-        end,
-        Pairs),
-
-    delete_db(SourceDb),
-    couch_server_sup:stop(),
-    ok.
-
-
-populate_db(Db, DocCount) ->
-    Docs = lists:foldl(
-        fun(DocIdCounter, Acc) ->
-            Doc = #doc{
-                id = iolist_to_binary(["doc", integer_to_list(DocIdCounter)]),
-                body = {[]},
-                atts = [
-                    att(<<"att1">>, 2 * 1024 * 1024, <<"text/plain">>),
-                    att(<<"att2">>, round(6.6 * 1024 * 1024), <<"app/binary">>)
-                ]
-            },
-            [Doc | Acc]
-        end,
-        [], lists:seq(1, DocCount)),
-    {ok, _} = couch_db:update_docs(Db, Docs, []).
-
-
-att(Name, Size, Type) ->
-    #att{
-        name = Name,
-        type = Type,
-        att_len = Size,
-        data = fun(Count) -> crypto:rand_bytes(Count) end
-    }.
-
-
-compare_dbs(Source, Target) ->
-    {ok, SourceDb} = couch_db:open_int(couch_db:name(Source), []),
-    {ok, TargetDb} = couch_db:open_int(couch_db:name(Target), []),
-
-    Fun = fun(FullDocInfo, _, Acc) ->
-        {ok, DocSource} = couch_db:open_doc(SourceDb, FullDocInfo),
-        Id = DocSource#doc.id,
-
-        etap:diag("Verifying document " ++ ?b2l(Id)),
-
-        {ok, DocTarget} = couch_db:open_doc(TargetDb, Id),
-        etap:is(DocTarget#doc.body, DocSource#doc.body,
-            "Same body in source and target databases"),
-
-        #doc{atts = SourceAtts} = DocSource,
-        #doc{atts = TargetAtts} = DocTarget,
-        etap:is(
-            lists:sort([N || #att{name = N} <- SourceAtts]),
-            lists:sort([N || #att{name = N} <- TargetAtts]),
-            "Document has same number (and names) of attachments in "
-            "source and target databases"),
-
-        lists:foreach(
-            fun(#att{name = AttName} = Att) ->
-                etap:diag("Verifying attachment " ++ ?b2l(AttName)),
-
-                {ok, AttTarget} = find_att(TargetAtts, AttName),
-                SourceMd5 = att_md5(Att),
-                TargetMd5 = att_md5(AttTarget),
-                case AttName of
-                <<"att1">> ->
-                    etap:is(Att#att.encoding, gzip,
-                        "Attachment is gzip encoded in source database"),
-                    etap:is(AttTarget#att.encoding, gzip,
-                        "Attachment is gzip encoded in target database"),
-                    DecSourceMd5 = att_decoded_md5(Att),
-                    DecTargetMd5 = att_decoded_md5(AttTarget),
-                    etap:is(DecTargetMd5, DecSourceMd5,
-                        "Same identity content in source and target databases");
-                _ ->
-                    etap:is(Att#att.encoding, identity,
-                        "Attachment is not encoded in source database"),
-                    etap:is(AttTarget#att.encoding, identity,
-                        "Attachment is not encoded in target database")
-                end,
-                etap:is(TargetMd5, SourceMd5,
-                    "Same content in source and target databases"),
-                etap:is(is_integer(Att#att.disk_len), true,
-                    "#att.disk_len is an integer in source database"),
-                etap:is(is_integer(Att#att.att_len), true,
-                    "#att.att_len is an integer in source database"),
-                etap:is(is_integer(AttTarget#att.disk_len), true,
-                    "#att.disk_len is an integer in target database"),
-                etap:is(is_integer(AttTarget#att.att_len), true,
-                    "#att.att_len is an integer in target database"),
-                etap:is(Att#att.disk_len, AttTarget#att.disk_len,
-                    "Same identity length in source and target databases"),
-                etap:is(Att#att.att_len, AttTarget#att.att_len,
-                    "Same encoded length in source and target databases"),
-                etap:is(Att#att.type, AttTarget#att.type,
-                    "Same type in source and target databases"),
-                etap:is(Att#att.md5, SourceMd5, "Correct MD5 in source database"),
-                etap:is(AttTarget#att.md5, SourceMd5, "Correct MD5 in target database")
-            end,
-            SourceAtts),
-
-        {ok, Acc}
-    end,
-
-    {ok, _, _} = couch_db:enum_docs(SourceDb, Fun, [], []),
-    ok = couch_db:close(SourceDb),
-    ok = couch_db:close(TargetDb).
-
-
-find_att([], _Name) ->
-    nil;
-find_att([#att{name = Name} = Att | _], Name) ->
-    {ok, Att};
-find_att([_ | Rest], Name) ->
-    find_att(Rest, Name).
-
-
-att_md5(Att) ->
-    Md50 = couch_doc:att_foldl(
-        Att,
-        fun(Chunk, Acc) -> couch_util:md5_update(Acc, Chunk) end,
-        couch_util:md5_init()),
-    couch_util:md5_final(Md50).
-
-att_decoded_md5(Att) ->
-    Md50 = couch_doc:att_foldl_decode(
-        Att,
-        fun(Chunk, Acc) -> couch_util:md5_update(Acc, Chunk) end,
-        couch_util:md5_init()),
-    couch_util:md5_final(Md50).
-
-
-db_url(DbName) ->
-    iolist_to_binary([
-        "http://", couch_config:get("httpd", "bind_address", "127.0.0.1"),
-        ":", integer_to_list(mochiweb_socket_server:get(couch_httpd, port)),
-        "/", DbName
-    ]).
-
-
-create_db(DbName) ->
-    couch_db:create(
-        DbName,
-        [{user_ctx, #user_ctx{roles = [<<"_admin">>]}}, overwrite]).
-
-
-delete_db(Db) ->
-    ok = couch_server:delete(
-        couch_db:name(Db), [{user_ctx, #user_ctx{roles = [<<"_admin">>]}}]).
-
-
-replicate({remote, Db}, Target) ->
-    replicate(db_url(Db), Target);
-
-replicate(Source, {remote, Db}) ->
-    replicate(Source, db_url(Db));
-
-replicate(Source, Target) ->
-    RepObject = {[
-        {<<"source">>, Source},
-        {<<"target">>, Target}
-    ]},
-    {ok, Rep} = couch_replicator_utils:parse_rep_doc(
-        RepObject, #user_ctx{roles = [<<"_admin">>]}),
-    {ok, Pid} = couch_replicator:async_replicate(Rep),
-    MonRef = erlang:monitor(process, Pid),
-    receive
-    {'DOWN', MonRef, process, Pid, Reason} ->
-        etap:is(Reason, normal, "Replication finished successfully")
-    after 300000 ->
-        etap:bail("Timeout waiting for replication to finish")
-    end.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_replicator/test/05-replication-many-leaves.t
----------------------------------------------------------------------
diff --git a/apps/couch_replicator/test/05-replication-many-leaves.t b/apps/couch_replicator/test/05-replication-many-leaves.t
deleted file mode 100755
index 212ee99..0000000
--- a/apps/couch_replicator/test/05-replication-many-leaves.t
+++ /dev/null
@@ -1,294 +0,0 @@
-#!/usr/bin/env escript
-%% -*- erlang -*-
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
-% Test replication of documents with many leaf revisions.
-% Motivated by COUCHDB-1340 and other similar issues where a document
-% GET with a too long ?open_revs revision list doesn't work due to
-% maximum web server limits for the HTTP request path.
-
--record(user_ctx, {
-    name = null,
-    roles = [],
-    handler
-}).
-
--record(doc, {
-    id = <<"">>,
-    revs = {0, []},
-    body = {[]},
-    atts = [],
-    deleted = false,
-    meta = []
-}).
-
--record(att, {
-    name,
-    type,
-    att_len,
-    disk_len,
-    md5= <<>>,
-    revpos=0,
-    data,
-    encoding=identity
-}).
-
--define(b2l(B), binary_to_list(B)).
--define(l2b(L), list_to_binary(L)).
--define(i2l(I), integer_to_list(I)).
-
-
-source_db_name() -> <<"couch_test_rep_db_a">>.
-target_db_name() -> <<"couch_test_rep_db_b">>.
-
-doc_ids() ->
-    [<<"doc1">>, <<"doc2">>, <<"doc3">>].
-
-doc_num_conflicts(<<"doc1">>) -> 10;
-doc_num_conflicts(<<"doc2">>) -> 100;
-% a number > MaxURLlength (7000) / length(DocRevisionString)
-doc_num_conflicts(<<"doc3">>) -> 210.
-
-
-main(_) ->
-    test_util:init_code_path(),
-
-    etap:plan(56),
-    case (catch test()) of
-        ok ->
-            etap:end_tests();
-        Other ->
-            etap:diag(io_lib:format("Test died abnormally: ~p", [Other])),
-            etap:bail(Other)
-    end,
-    ok.
-
-
-test() ->
-    couch_server_sup:start_link(test_util:config_files()),
-    ibrowse:start(),
-    crypto:start(),
-    couch_config:set("replicator", "connection_timeout", "90000", false),
-
-    Pairs = [
-        {source_db_name(), target_db_name()},
-        {{remote, source_db_name()}, target_db_name()},
-        {source_db_name(), {remote, target_db_name()}},
-        {{remote, source_db_name()}, {remote, (target_db_name())}}
-    ],
-
-    lists:foreach(
-        fun({Source, Target}) ->
-            {ok, SourceDb} = create_db(source_db_name()),
-            etap:diag("Populating source database"),
-            {ok, DocRevs} = populate_db(SourceDb),
-            ok = couch_db:close(SourceDb),
-            etap:diag("Creating target database"),
-            {ok, TargetDb} = create_db(target_db_name()),
-
-            ok = couch_db:close(TargetDb),
-            etap:diag("Triggering replication"),
-            replicate(Source, Target),
-            etap:diag("Replication finished, comparing source and target databases"),
-            {ok, SourceDb2} = couch_db:open_int(source_db_name(), []),
-            {ok, TargetDb2} = couch_db:open_int(target_db_name(), []),
-            verify_target(SourceDb2, TargetDb2, DocRevs),
-            ok = couch_db:close(SourceDb2),
-            ok = couch_db:close(TargetDb2),
-
-            {ok, SourceDb3} = couch_db:open_int(source_db_name(), []),
-            {ok, DocRevs2} = add_attachments(SourceDb3, DocRevs, 2),
-            ok = couch_db:close(SourceDb3),
-            etap:diag("Triggering replication again"),
-            replicate(Source, Target),
-            etap:diag("Replication finished, comparing source and target databases"),
-            {ok, SourceDb4} = couch_db:open_int(source_db_name(), []),
-            {ok, TargetDb4} = couch_db:open_int(target_db_name(), []),
-            verify_target(SourceDb4, TargetDb4, DocRevs2),
-            ok = couch_db:close(SourceDb4),
-            ok = couch_db:close(TargetDb4),
-
-            etap:diag("Deleting source and target databases"),
-            delete_db(TargetDb),
-            delete_db(SourceDb),
-            ok = timer:sleep(1000)
-        end,
-        Pairs),
-
-    couch_server_sup:stop(),
-    ok.
-
-
-populate_db(Db) ->
-    DocRevsDict = lists:foldl(
-        fun(DocId, Acc) ->
-            Value = <<"0">>,
-            Doc = #doc{
-                id = DocId,
-                body = {[ {<<"value">>, Value} ]}
-            },
-            {ok, Rev} = couch_db:update_doc(Db, Doc, []),
-            {ok, DocRevs} = add_doc_siblings(Db, DocId, doc_num_conflicts(DocId)),
-            dict:store(DocId, [Rev | DocRevs], Acc)
-        end,
-        dict:new(), doc_ids()),
-    {ok, dict:to_list(DocRevsDict)}.
-
-
-add_doc_siblings(Db, DocId, NumLeaves) when NumLeaves > 0 ->
-    add_doc_siblings(Db, DocId, NumLeaves, [], []).
-
-
-add_doc_siblings(Db, _DocId, 0, AccDocs, AccRevs) ->
-    {ok, []} = couch_db:update_docs(Db, AccDocs, [], replicated_changes),
-    {ok, AccRevs};
-
-add_doc_siblings(Db, DocId, NumLeaves, AccDocs, AccRevs) ->
-    Value = list_to_binary(integer_to_list(NumLeaves)),
-    Rev = couch_util:md5(Value),
-    Doc = #doc{
-        id = DocId,
-        revs = {1, [Rev]},
-        body = {[ {<<"value">>, Value} ]}
-    },
-    add_doc_siblings(Db, DocId, NumLeaves - 1, [Doc | AccDocs], [{1, Rev} | AccRevs]).
-
-
-verify_target(_SourceDb, _TargetDb, []) ->
-    ok;
-
-verify_target(SourceDb, TargetDb, [{DocId, RevList} | Rest]) ->
-    {ok, Lookups} = couch_db:open_doc_revs(
-        TargetDb,
-        DocId,
-        RevList,
-        [conflicts, deleted_conflicts]),
-    Docs = [Doc || {ok, Doc} <- Lookups],
-    {ok, SourceLookups} = couch_db:open_doc_revs(
-        SourceDb,
-        DocId,
-        RevList,
-        [conflicts, deleted_conflicts]),
-    SourceDocs = [Doc || {ok, Doc} <- SourceLookups],
-    Total = doc_num_conflicts(DocId) + 1,
-    etap:is(
-        length(Docs),
-        Total,
-        "Target has " ++ ?i2l(Total) ++ " leaf revisions of document " ++ ?b2l(DocId)),
-    etap:diag("Verifying all revisions of document " ++ ?b2l(DocId)),
-    lists:foreach(
-        fun({#doc{id = Id, revs = Revs} = TgtDoc, #doc{id = Id, revs = Revs} = SrcDoc}) ->
-            SourceJson = couch_doc:to_json_obj(SrcDoc, [attachments]),
-            TargetJson = couch_doc:to_json_obj(TgtDoc, [attachments]),
-            case TargetJson of
-            SourceJson ->
-                ok;
-            _ ->
-                {Pos, [Rev | _]} = Revs,
-                etap:bail("Wrong value for revision " ++
-                    ?b2l(couch_doc:rev_to_str({Pos, Rev})) ++
-                    " of document " ++ ?b2l(DocId))
-            end
-        end,
-        lists:zip(Docs, SourceDocs)),
-    verify_target(SourceDb, TargetDb, Rest).
-
-
-add_attachments(Source, DocIdRevs, NumAtts) ->
-    add_attachments(Source, DocIdRevs, NumAtts, []).
-
-add_attachments(_SourceDb, [], _NumAtts, Acc) ->
-    {ok, Acc};
-
-add_attachments(SourceDb, [{DocId, RevList} | Rest], NumAtts, IdRevsAcc) ->
-    {ok, SourceLookups} = couch_db:open_doc_revs(
-        SourceDb,
-        DocId,
-        RevList,
-        []),
-    SourceDocs = [Doc || {ok, Doc} <- SourceLookups],
-    Total = doc_num_conflicts(DocId) + 1,
-    etap:is(
-        length(SourceDocs),
-        Total,
-        "Source still has " ++ ?i2l(Total) ++
-            " leaf revisions of document " ++ ?b2l(DocId)),
-    etap:diag("Adding " ++ ?i2l(NumAtts) ++
-        " attachments to each revision of the document " ++ ?b2l(DocId)),
-    NewDocs = lists:foldl(
-        fun(#doc{atts = Atts, revs = {Pos, [Rev | _]}} = Doc, Acc) ->
-            NewAtts = lists:foldl(
-                fun(I, AttAcc) ->
-                    AttData = crypto:rand_bytes(100),
-                    NewAtt = #att{
-                        name = iolist_to_binary(
-                            ["att_", ?i2l(I), "_", couch_doc:rev_to_str({Pos, Rev})]),
-                        type = <<"application/foobar">>,
-                        att_len = byte_size(AttData),
-                        data = AttData
-                    },
-                    [NewAtt | AttAcc]
-                end,
-                [], lists:seq(1, NumAtts)),
-            [Doc#doc{atts = Atts ++ NewAtts} | Acc]
-        end,
-        [], SourceDocs),
-    {ok, UpdateResults} = couch_db:update_docs(SourceDb, NewDocs, []),
-    NewRevs = [R || {ok, R} <- UpdateResults],
-    etap:is(
-        length(NewRevs),
-        length(NewDocs),
-        "Document revisions updated with " ++ ?i2l(NumAtts) ++ " attachments"),
-    add_attachments(SourceDb, Rest, NumAtts, [{DocId, NewRevs} | IdRevsAcc]).
-
-
-db_url(DbName) ->
-    iolist_to_binary([
-        "http://", couch_config:get("httpd", "bind_address", "127.0.0.1"),
-        ":", integer_to_list(mochiweb_socket_server:get(couch_httpd, port)),
-        "/", DbName
-    ]).
-
-
-create_db(DbName) ->
-    couch_db:create(
-        DbName,
-        [{user_ctx, #user_ctx{roles = [<<"_admin">>]}}, overwrite]).
-
-
-delete_db(Db) ->
-    ok = couch_server:delete(
-        couch_db:name(Db), [{user_ctx, #user_ctx{roles = [<<"_admin">>]}}]).
-
-
-replicate({remote, Db}, Target) ->
-    replicate(db_url(Db), Target);
-
-replicate(Source, {remote, Db}) ->
-    replicate(Source, db_url(Db));
-
-replicate(Source, Target) ->
-    RepObject = {[
-        {<<"source">>, Source},
-        {<<"target">>, Target}
-    ]},
-    {ok, Rep} = couch_replicator_utils:parse_rep_doc(
-        RepObject, #user_ctx{roles = [<<"_admin">>]}),
-    {ok, Pid} = couch_replicator:async_replicate(Rep),
-    MonRef = erlang:monitor(process, Pid),
-    receive
-    {'DOWN', MonRef, process, Pid, Reason} ->
-        etap:is(Reason, normal, "Replication finished successfully")
-    after 900000 ->
-        etap:bail("Timeout waiting for replication to finish")
-    end.


[40/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_mrview/src/couch_mrview_cleanup.erl
----------------------------------------------------------------------
diff --git a/apps/couch_mrview/src/couch_mrview_cleanup.erl b/apps/couch_mrview/src/couch_mrview_cleanup.erl
deleted file mode 100644
index 0593570..0000000
--- a/apps/couch_mrview/src/couch_mrview_cleanup.erl
+++ /dev/null
@@ -1,45 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%-include_lib("couch/include/couch_db.hrl").
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_mrview_cleanup).
-
--export([run/1]).
-
--include_lib("couch/include/couch_db.hrl").
--include_lib("couch_mrview/include/couch_mrview.hrl").
-
-run(Db) ->
-    RootDir = couch_index_util:root_dir(),
-    DbName = couch_db:name(Db),
-
-    DesignDocs = couch_db:get_design_docs(Db),
-    SigFiles = lists:foldl(fun(DDocInfo, SFAcc) ->
-        {ok, DDoc} = couch_db:open_doc_int(Db, DDocInfo, [ejson_body]),
-        {ok, InitState} = couch_mrview_util:ddoc_to_mrst(DbName, DDoc),
-        Sig = InitState#mrst.sig,
-        IFName = couch_mrview_util:index_file(DbName, Sig),
-        CFName = couch_mrview_util:compaction_file(DbName, Sig),
-        [IFName, CFName | SFAcc]
-    end, [], [DD || DD <- DesignDocs, DD#full_doc_info.deleted == false]),
-
-    IdxDir = couch_index_util:index_dir(mrview, DbName),
-    DiskFiles = filelib:wildcard(filename:join(IdxDir, "*")),
-
-    % We need to delete files that have no ddoc.
-    ToDelete = DiskFiles -- SigFiles,
-
-    lists:foreach(fun(FN) ->
-        ?LOG_DEBUG("Deleting stale view file: ~s", [FN]),
-        couch_file:delete(RootDir, FN, false)
-    end, ToDelete),
-
-    ok.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_mrview/src/couch_mrview_compactor.erl
----------------------------------------------------------------------
diff --git a/apps/couch_mrview/src/couch_mrview_compactor.erl b/apps/couch_mrview/src/couch_mrview_compactor.erl
deleted file mode 100644
index 4ab8dd1..0000000
--- a/apps/couch_mrview/src/couch_mrview_compactor.erl
+++ /dev/null
@@ -1,178 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_mrview_compactor).
-
--include_lib("couch/include/couch_db.hrl").
--include_lib("couch_mrview/include/couch_mrview.hrl").
-
--export([compact/3, swap_compacted/2]).
-
--record(acc, {
-   btree = nil,
-   last_id = nil,
-   kvs = [],
-   kvs_size = 0,
-   changes = 0,
-   total_changes
-}).
-
-
-compact(_Db, State, Opts) ->
-    case lists:member(recompact, Opts) of
-        false -> compact(State);
-        true -> recompact(State)
-    end.
-
-compact(State) ->
-    #mrst{
-        db_name=DbName,
-        idx_name=IdxName,
-        sig=Sig,
-        update_seq=Seq,
-        id_btree=IdBtree,
-        views=Views
-    } = State,
-
-    {EmptyState, NumDocIds} = couch_util:with_db(DbName, fun(Db) ->
-        CompactFName = couch_mrview_util:compaction_file(DbName, Sig),
-        {ok, Fd} = couch_mrview_util:open_file(CompactFName),
-        ESt = couch_mrview_util:reset_index(Db, Fd, State),
-
-        {ok, DbReduce} = couch_btree:full_reduce(Db#db.fulldocinfo_by_id_btree),
-        Count = element(1, DbReduce),
-
-        {ESt, Count}
-    end),
-
-    #mrst{
-        id_btree = EmptyIdBtree,
-        views = EmptyViews
-    } = EmptyState,
-
-    TotalChanges = lists:foldl(
-        fun(View, Acc) ->
-            {ok, Kvs} = couch_mrview_util:get_row_count(View),
-            Acc + Kvs
-        end,
-        NumDocIds, Views),
-    couch_task_status:add_task([
-        {type, view_compaction},
-        {database, DbName},
-        {design_document, IdxName},
-        {progress, 0}
-    ]),
-
-    BufferSize0 = couch_config:get(
-        "view_compaction", "keyvalue_buffer_size", "2097152"
-    ),
-    BufferSize = list_to_integer(BufferSize0),
-
-    FoldFun = fun({DocId, _} = KV, Acc) ->
-        #acc{btree = Bt, kvs = Kvs, kvs_size = KvsSize, last_id = LastId} = Acc,
-        if DocId =:= LastId ->
-            % COUCHDB-999 regression test
-            ?LOG_ERROR("Duplicate docid `~s` detected in view group `~s`"
-                ++ ", database `~s` - This view needs to be rebuilt.",
-                [DocId, IdxName, DbName]
-            ),
-            exit({view_duplicate_id, DocId});
-        true -> ok end,
-        KvsSize2 = KvsSize + ?term_size(KV),
-        case KvsSize2 >= BufferSize of
-            true ->
-                {ok, Bt2} = couch_btree:add(Bt, lists:reverse([KV | Kvs])),
-                Acc2 = update_task(Acc, 1 + length(Kvs)),
-                {ok, Acc2#acc{
-                    btree = Bt2, kvs = [], kvs_size = 0, last_id = DocId}};
-            _ ->
-                {ok, Acc#acc{
-                    kvs = [KV | Kvs], kvs_size = KvsSize2, last_id = DocId}}
-        end
-    end,
-
-    InitAcc = #acc{total_changes = TotalChanges, btree = EmptyIdBtree},
-    {ok, _, FinalAcc} = couch_btree:foldl(IdBtree, FoldFun, InitAcc),
-    #acc{btree = Bt3, kvs = Uncopied} = FinalAcc,
-    {ok, NewIdBtree} = couch_btree:add(Bt3, lists:reverse(Uncopied)),
-    FinalAcc2 = update_task(FinalAcc, length(Uncopied)),
-
-    {NewViews, _} = lists:mapfoldl(fun({View, EmptyView}, Acc) ->
-        compact_view(View, EmptyView, BufferSize, Acc)
-    end, FinalAcc2, lists:zip(Views, EmptyViews)),
-
-    unlink(EmptyState#mrst.fd),
-    {ok, EmptyState#mrst{
-        id_btree=NewIdBtree,
-        views=NewViews,
-        update_seq=Seq
-    }}.
-
-
-recompact(State) ->
-    link(State#mrst.fd),
-    {Pid, Ref} = erlang:spawn_monitor(fun() ->
-        couch_index_updater:update(couch_mrview_index, State)
-    end),
-    receive
-        {'DOWN', Ref, _, _, {updated, Pid, State2}} ->
-            unlink(State#mrst.fd),
-            {ok, State2}
-    end.
-
-
-%% @spec compact_view(View, EmptyView, Retry, Acc) -> {CompactView, NewAcc}
-compact_view(View, EmptyView, BufferSize, Acc0) ->
-    Fun = fun(KV, #acc{btree = Bt, kvs = Kvs, kvs_size = KvsSize} = Acc) ->
-        KvsSize2 = KvsSize + ?term_size(KV),
-        if KvsSize2 >= BufferSize ->
-            {ok, Bt2} = couch_btree:add(Bt, lists:reverse([KV | Kvs])),
-            Acc2 = update_task(Acc, 1 + length(Kvs)),
-            {ok, Acc2#acc{btree = Bt2, kvs = [], kvs_size = 0}};
-        true ->
-            {ok, Acc#acc{kvs = [KV | Kvs], kvs_size = KvsSize2}}
-        end
-    end,
-
-    InitAcc = Acc0#acc{kvs = [], kvs_size = 0, btree = EmptyView#mrview.btree},
-    {ok, _, FinalAcc} = couch_btree:foldl(View#mrview.btree, Fun, InitAcc),
-    #acc{btree = Bt3, kvs = Uncopied} = FinalAcc,
-    {ok, NewBt} = couch_btree:add(Bt3, lists:reverse(Uncopied)),
-    FinalAcc2 = update_task(FinalAcc, length(Uncopied)),
-    {EmptyView#mrview{btree=NewBt}, FinalAcc2}.
-
-
-update_task(#acc{changes = Changes, total_changes = Total} = Acc, ChangesInc) ->
-    Changes2 = Changes + ChangesInc,
-    couch_task_status:update([{progress, (Changes2 * 100) div Total}]),
-    Acc#acc{changes = Changes2}.
-
-
-swap_compacted(OldState, NewState) ->
-    #mrst{
-        sig=Sig,
-        db_name=DbName
-    } = NewState,
-
-    link(NewState#mrst.fd),
-
-    RootDir = couch_index_util:root_dir(),
-    IndexFName = couch_mrview_util:index_file(DbName, Sig),
-    CompactFName = couch_mrview_util:compaction_file(DbName, Sig),
-    ok = couch_file:delete(RootDir, IndexFName),
-    ok = file:rename(CompactFName, IndexFName),
-
-    unlink(OldState#mrst.fd),
-    couch_ref_counter:drop(OldState#mrst.refc),
-    {ok, NewRefCounter} = couch_ref_counter:start([NewState#mrst.fd]),
-
-    {ok, NewState#mrst{refc=NewRefCounter}}.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_mrview/src/couch_mrview_http.erl
----------------------------------------------------------------------
diff --git a/apps/couch_mrview/src/couch_mrview_http.erl b/apps/couch_mrview/src/couch_mrview_http.erl
deleted file mode 100644
index 22e0dc3..0000000
--- a/apps/couch_mrview/src/couch_mrview_http.erl
+++ /dev/null
@@ -1,409 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_mrview_http).
-
--export([
-    handle_all_docs_req/2,
-    handle_view_req/3,
-    handle_temp_view_req/2,
-    handle_info_req/3,
-    handle_compact_req/3,
-    handle_cleanup_req/2,
-    parse_qs/2
-]).
-
--include_lib("couch/include/couch_db.hrl").
--include_lib("couch_mrview/include/couch_mrview.hrl").
-
-
--record(vacc, {
-    db,
-    req,
-    resp,
-    prepend,
-    etag
-}).
-
-
-handle_all_docs_req(#httpd{method='GET'}=Req, Db) ->
-    all_docs_req(Req, Db, undefined);
-handle_all_docs_req(#httpd{method='POST'}=Req, Db) ->
-    Keys = get_view_keys(couch_httpd:json_body_obj(Req)),
-    all_docs_req(Req, Db, Keys);
-handle_all_docs_req(Req, _Db) ->
-    couch_httpd:send_method_not_allowed(Req, "GET,POST,HEAD").
-
-
-handle_view_req(#httpd{method='GET'}=Req, Db, DDoc) ->
-    [_, _, _, _, ViewName] = Req#httpd.path_parts,
-    couch_stats_collector:increment({httpd, view_reads}),
-    design_doc_view(Req, Db, DDoc, ViewName, undefined);
-handle_view_req(#httpd{method='POST'}=Req, Db, DDoc) ->
-    [_, _, _, _, ViewName] = Req#httpd.path_parts,
-    Keys = get_view_keys(couch_httpd:json_body_obj(Req)),
-    couch_stats_collector:increment({httpd, view_reads}),
-    design_doc_view(Req, Db, DDoc, ViewName, Keys);
-handle_view_req(Req, _Db, _DDoc) ->
-    couch_httpd:send_method_not_allowed(Req, "GET,POST,HEAD").
-
-
-handle_temp_view_req(#httpd{method='POST'}=Req, Db) ->
-    couch_httpd:validate_ctype(Req, "application/json"),
-    ok = couch_db:check_is_admin(Db),
-    {Body} = couch_httpd:json_body_obj(Req),
-    DDoc = couch_mrview_util:temp_view_to_ddoc({Body}),
-    Keys = get_view_keys({Body}),
-    couch_stats_collector:increment({httpd, temporary_view_reads}),
-    design_doc_view(Req, Db, DDoc, <<"temp">>, Keys);
-handle_temp_view_req(Req, _Db) ->
-    couch_httpd:send_method_not_allowed(Req, "POST").
-
-
-handle_info_req(#httpd{method='GET'}=Req, Db, DDoc) ->
-    [_, _, Name, _] = Req#httpd.path_parts,
-    {ok, Info} = couch_mrview:get_info(Db, DDoc),
-    couch_httpd:send_json(Req, 200, {[
-        {name, Name},
-        {view_index, {Info}}
-    ]});
-handle_info_req(Req, _Db, _DDoc) ->
-    couch_httpd:send_method_not_allowed(Req, "GET").
-
-
-handle_compact_req(#httpd{method='POST'}=Req, Db, DDoc) ->
-    ok = couch_db:check_is_admin(Db),
-    couch_httpd:validate_ctype(Req, "application/json"),
-    ok = couch_mrview:compact(Db, DDoc),
-    couch_httpd:send_json(Req, 202, {[{ok, true}]});
-handle_compact_req(Req, _Db, _DDoc) ->
-    couch_httpd:send_method_not_allowed(Req, "POST").
-
-
-handle_cleanup_req(#httpd{method='POST'}=Req, Db) ->
-    ok = couch_db:check_is_admin(Db),
-    couch_httpd:validate_ctype(Req, "application/json"),
-    ok = couch_mrview:cleanup(Db),
-    couch_httpd:send_json(Req, 202, {[{ok, true}]});
-handle_cleanup_req(Req, _Db) ->
-    couch_httpd:send_method_not_allowed(Req, "POST").
-
-
-all_docs_req(Req, Db, Keys) ->
-    case couch_db:is_system_db(Db) of
-    true ->
-        case (catch couch_db:check_is_admin(Db)) of
-        ok ->
-            do_all_docs_req(Req, Db, Keys);
-        _ ->
-            DbName = ?b2l(Db#db.name),
-            case couch_config:get("couch_httpd_auth",
-                                  "authentication_db",
-                                  "_users") of
-            DbName ->
-                UsersDbPublic = couch_config:get("couch_httpd_auth", "users_db_public", "false"),
-                PublicFields = couch_config:get("couch_httpd_auth", "public_fields"),
-                case {UsersDbPublic, PublicFields} of
-                {"true", PublicFields} when PublicFields =/= undefined ->
-                    do_all_docs_req(Req, Db, Keys);
-                {_, _} ->
-                    throw({forbidden, <<"Only admins can access _all_docs",
-                                        " of system databases.">>})
-                end;
-            _ ->
-                throw({forbidden, <<"Only admins can access _all_docs",
-                                    " of system databases.">>})
-            end
-        end;
-    false ->
-        do_all_docs_req(Req, Db, Keys)
-    end.
-
-do_all_docs_req(Req, Db, Keys) ->
-    Args0 = parse_qs(Req, Keys),
-    ETagFun = fun(Sig, Acc0) ->
-        ETag = couch_httpd:make_etag(Sig),
-        case couch_httpd:etag_match(Req, ETag) of
-            true -> throw({etag_match, ETag});
-            false -> {ok, Acc0#vacc{etag=ETag}}
-        end
-    end,
-    Args = Args0#mrargs{preflight_fun=ETagFun},
-    {ok, Resp} = couch_httpd:etag_maybe(Req, fun() ->
-        VAcc0 = #vacc{db=Db, req=Req},
-        DbName = ?b2l(Db#db.name),
-        UsersDbName = couch_config:get("couch_httpd_auth",
-                                         "authentication_db",
-                                         "_users"),
-        IsAdmin = is_admin(Db),
-        Callback = get_view_callback(DbName, UsersDbName, IsAdmin),
-        couch_mrview:query_all_docs(Db, Args, Callback, VAcc0)
-    end),
-    case is_record(Resp, vacc) of
-        true -> {ok, Resp#vacc.resp};
-        _ -> {ok, Resp}
-    end.
-
-is_admin(Db) ->
-    case catch couch_db:check_is_admin(Db) of
-    {unauthorized, _} ->
-        false;
-    ok ->
-        true
-    end.
-
-
-% admin users always get all fields
-get_view_callback(_, _, true) ->
-    fun view_cb/2;
-% if we are operating on the users db and we aren't
-% admin, filter the view
-get_view_callback(_DbName, _DbName, false) ->
-    fun filtered_view_cb/2;
-% non _users databases get all fields
-get_view_callback(_, _, _) ->
-    fun view_cb/2.
-
-
-design_doc_view(Req, Db, DDoc, ViewName, Keys) ->
-    Args0 = parse_qs(Req, Keys),
-    ETagFun = fun(Sig, Acc0) ->
-        ETag = couch_httpd:make_etag(Sig),
-        case couch_httpd:etag_match(Req, ETag) of
-            true -> throw({etag_match, ETag});
-            false -> {ok, Acc0#vacc{etag=ETag}}
-        end
-    end,
-    Args = Args0#mrargs{preflight_fun=ETagFun},
-    {ok, Resp} = couch_httpd:etag_maybe(Req, fun() ->
-        VAcc0 = #vacc{db=Db, req=Req},
-        couch_mrview:query_view(Db, DDoc, ViewName, Args, fun view_cb/2, VAcc0)
-    end),
-    case is_record(Resp, vacc) of
-        true -> {ok, Resp#vacc.resp};
-        _ -> {ok, Resp}
-    end.
-
-
-filtered_view_cb({row, Row0}, Acc) ->
-  Row1 = lists:map(fun({doc, null}) ->
-        {doc, null};
-    ({doc, Body}) ->
-        Doc = couch_users_db:strip_non_public_fields(#doc{body=Body}),
-        {doc, Doc#doc.body};
-    (KV) ->
-        KV
-    end, Row0),
-    view_cb({row, Row1}, Acc);
-filtered_view_cb(Obj, Acc) ->
-    view_cb(Obj, Acc).
-
-
-view_cb({meta, Meta}, #vacc{resp=undefined}=Acc) ->
-    Headers = [{"ETag", Acc#vacc.etag}],
-    {ok, Resp} = couch_httpd:start_json_response(Acc#vacc.req, 200, Headers),
-    % Map function starting
-    Parts = case couch_util:get_value(total, Meta) of
-        undefined -> [];
-        Total -> [io_lib:format("\"total_rows\":~p", [Total])]
-    end ++ case couch_util:get_value(offset, Meta) of
-        undefined -> [];
-        Offset -> [io_lib:format("\"offset\":~p", [Offset])]
-    end ++ case couch_util:get_value(update_seq, Meta) of
-        undefined -> [];
-        UpdateSeq -> [io_lib:format("\"update_seq\":~p", [UpdateSeq])]
-    end ++ ["\"rows\":["],
-    Chunk = lists:flatten("{" ++ string:join(Parts, ",") ++ "\r\n"),
-    couch_httpd:send_chunk(Resp, Chunk),
-    {ok, Acc#vacc{resp=Resp, prepend=""}};
-view_cb({row, Row}, #vacc{resp=undefined}=Acc) ->
-    % Reduce function starting
-    Headers = [{"ETag", Acc#vacc.etag}],
-    {ok, Resp} = couch_httpd:start_json_response(Acc#vacc.req, 200, Headers),
-    couch_httpd:send_chunk(Resp, ["{\"rows\":[\r\n", row_to_json(Row)]),
-    {ok, #vacc{resp=Resp, prepend=",\r\n"}};
-view_cb({row, Row}, Acc) ->
-    % Adding another row
-    couch_httpd:send_chunk(Acc#vacc.resp, [Acc#vacc.prepend, row_to_json(Row)]),
-    {ok, Acc#vacc{prepend=",\r\n"}};
-view_cb(complete, #vacc{resp=undefined}=Acc) ->
-    % Nothing in view
-    {ok, Resp} = couch_httpd:send_json(Acc#vacc.req, 200, {[{rows, []}]}),
-    {ok, Acc#vacc{resp=Resp}};
-view_cb(complete, Acc) ->
-    % Finish view output
-    couch_httpd:send_chunk(Acc#vacc.resp, "\r\n]}"),
-    couch_httpd:end_json_response(Acc#vacc.resp),
-    {ok, Acc}.
-
-
-row_to_json(Row) ->
-    Id = couch_util:get_value(id, Row),
-    row_to_json(Id, Row).
-
-
-row_to_json(error, Row) ->
-    % Special case for _all_docs request with KEYS to
-    % match prior behavior.
-    Key = couch_util:get_value(key, Row),
-    Val = couch_util:get_value(value, Row),
-    Obj = {[{key, Key}, {error, Val}]},
-    ?JSON_ENCODE(Obj);
-row_to_json(Id0, Row) ->
-    Id = case Id0 of
-        undefined -> [];
-        Id0 -> [{id, Id0}]
-    end,
-    Key = couch_util:get_value(key, Row, null),
-    Val = couch_util:get_value(value, Row),
-    Doc = case couch_util:get_value(doc, Row) of
-        undefined -> [];
-        Doc0 -> [{doc, Doc0}]
-    end,
-    Obj = {Id ++ [{key, Key}, {value, Val}] ++ Doc},
-    ?JSON_ENCODE(Obj).
-
-
-get_view_keys({Props}) ->
-    case couch_util:get_value(<<"keys">>, Props) of
-        undefined ->
-            ?LOG_DEBUG("POST with no keys member.", []),
-            undefined;
-        Keys when is_list(Keys) ->
-            Keys;
-        _ ->
-            throw({bad_request, "`keys` member must be a array."})
-    end.
-
-
-parse_qs(Req, Keys) ->
-    Args = #mrargs{keys=Keys},
-    lists:foldl(fun({K, V}, Acc) ->
-        parse_qs(K, V, Acc)
-    end, Args, couch_httpd:qs(Req)).
-
-
-parse_qs(Key, Val, Args) ->
-    case Key of
-        "" ->
-            Args;
-        "reduce" ->
-            Args#mrargs{reduce=parse_boolean(Val)};
-        "key" ->
-            JsonKey = ?JSON_DECODE(Val),
-            Args#mrargs{start_key=JsonKey, end_key=JsonKey};
-        "keys" ->
-            Args#mrargs{keys=?JSON_DECODE(Val)};
-        "startkey" ->
-            Args#mrargs{start_key=?JSON_DECODE(Val)};
-        "start_key" ->
-            Args#mrargs{start_key=?JSON_DECODE(Val)};
-        "startkey_docid" ->
-            Args#mrargs{start_key_docid=list_to_binary(Val)};
-        "start_key_doc_id" ->
-            Args#mrargs{start_key_docid=list_to_binary(Val)};
-        "endkey" ->
-            Args#mrargs{end_key=?JSON_DECODE(Val)};
-        "end_key" ->
-            Args#mrargs{end_key=?JSON_DECODE(Val)};
-        "endkey_docid" ->
-            Args#mrargs{end_key_docid=list_to_binary(Val)};
-        "end_key_doc_id" ->
-            Args#mrargs{end_key_docid=list_to_binary(Val)};
-        "limit" ->
-            Args#mrargs{limit=parse_pos_int(Val)};
-        "count" ->
-            throw({query_parse_error, <<"QS param `count` is not `limit`">>});
-        "stale" when Val == "ok" ->
-            Args#mrargs{stale=ok};
-        "stale" when Val == "update_after" ->
-            Args#mrargs{stale=update_after};
-        "stale" ->
-            throw({query_parse_error, <<"Invalid value for `stale`.">>});
-        "descending" ->
-            case parse_boolean(Val) of
-                true -> Args#mrargs{direction=rev};
-                _ -> Args#mrargs{direction=fwd}
-            end;
-        "skip" ->
-            Args#mrargs{skip=parse_pos_int(Val)};
-        "group" ->
-            case parse_boolean(Val) of
-                true -> Args#mrargs{group_level=exact};
-                _ -> Args#mrargs{group_level=0}
-            end;
-        "group_level" ->
-            Args#mrargs{group_level=parse_pos_int(Val)};
-        "inclusive_end" ->
-            Args#mrargs{inclusive_end=parse_boolean(Val)};
-        "include_docs" ->
-            Args#mrargs{include_docs=parse_boolean(Val)};
-        "attachments" ->
-            case parse_boolean(Val) of
-            true ->
-                Opts = Args#mrargs.doc_options,
-                Args#mrargs{doc_options=[attachments|Opts]};
-            false ->
-                Args
-            end;
-        "att_encoding_info" ->
-            case parse_boolean(Val) of
-            true ->
-                Opts = Args#mrargs.doc_options,
-                Args#mrargs{doc_options=[att_encoding_info|Opts]};
-            false ->
-                Args
-            end;
-        "update_seq" ->
-            Args#mrargs{update_seq=parse_boolean(Val)};
-        "conflicts" ->
-            Args#mrargs{conflicts=parse_boolean(Val)};
-        "list" ->
-            Args#mrargs{list=list_to_binary(Val)};
-        "callback" ->
-            Args#mrargs{callback=list_to_binary(Val)};
-        _ ->
-            BKey = list_to_binary(Key),
-            BVal = list_to_binary(Val),
-            Args#mrargs{extra=[{BKey, BVal} | Args#mrargs.extra]}
-    end.
-
-
-parse_boolean(Val) ->
-    case string:to_lower(Val) of
-    "true" -> true;
-    "false" -> false;
-    _ ->
-        Msg = io_lib:format("Invalid boolean parameter: ~p", [Val]),
-        throw({query_parse_error, ?l2b(Msg)})
-    end.
-
-
-parse_int(Val) ->
-    case (catch list_to_integer(Val)) of
-    IntVal when is_integer(IntVal) ->
-        IntVal;
-    _ ->
-        Msg = io_lib:format("Invalid value for integer: ~p", [Val]),
-        throw({query_parse_error, ?l2b(Msg)})
-    end.
-
-
-parse_pos_int(Val) ->
-    case parse_int(Val) of
-    IntVal when IntVal >= 0 ->
-        IntVal;
-    _ ->
-        Fmt = "Invalid value for positive integer: ~p",
-        Msg = io_lib:format(Fmt, [Val]),
-        throw({query_parse_error, ?l2b(Msg)})
-    end.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_mrview/src/couch_mrview_index.erl
----------------------------------------------------------------------
diff --git a/apps/couch_mrview/src/couch_mrview_index.erl b/apps/couch_mrview/src/couch_mrview_index.erl
deleted file mode 100644
index 7506f34..0000000
--- a/apps/couch_mrview/src/couch_mrview_index.erl
+++ /dev/null
@@ -1,162 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_mrview_index).
-
-
--export([get/2]).
--export([init/2, open/2, close/1, reset/1, delete/1]).
--export([start_update/3, purge/4, process_doc/3, finish_update/1, commit/1]).
--export([compact/3, swap_compacted/2]).
-
--include_lib("couch/include/couch_db.hrl").
--include_lib("couch_mrview/include/couch_mrview.hrl").
-
-
-get(Property, State) ->
-    case Property of
-        db_name ->
-            State#mrst.db_name;
-        idx_name ->
-            State#mrst.idx_name;
-        signature ->
-            State#mrst.sig;
-        update_seq ->
-            State#mrst.update_seq;
-        purge_seq ->
-            State#mrst.purge_seq;
-        update_options ->
-            Opts = State#mrst.design_opts,
-            IncDesign = couch_util:get_value(<<"include_design">>, Opts, false),
-            LocalSeq = couch_util:get_value(<<"local_seq">>, Opts, false),
-            if IncDesign -> [include_design]; true -> [] end
-                ++ if LocalSeq -> [local_seq]; true -> [] end;
-        info ->
-            #mrst{
-                fd = Fd,
-                sig = Sig,
-                id_btree = Btree,
-                language = Lang,
-                update_seq = UpdateSeq,
-                purge_seq = PurgeSeq,
-                views = Views
-            } = State,
-            {ok, Size} = couch_file:bytes(Fd),
-            {ok, DataSize} = couch_mrview_util:calculate_data_size(Btree,Views),
-            {ok, [
-                {signature, list_to_binary(couch_index_util:hexsig(Sig))},
-                {language, Lang},
-                {disk_size, Size},
-                {data_size, DataSize},
-                {update_seq, UpdateSeq},
-                {purge_seq, PurgeSeq}
-            ]};
-        Other ->
-            throw({unknown_index_property, Other})
-    end.
-
-
-init(Db, DDoc) ->
-    couch_mrview_util:ddoc_to_mrst(couch_db:name(Db), DDoc).
-
-
-open(Db, State) ->
-    #mrst{
-        db_name=DbName,
-        sig=Sig
-    } = State,
-    IndexFName = couch_mrview_util:index_file(DbName, Sig),
-
-    % If we are upgrading from <=1.2.x, we upgrade the view
-    % index file on the fly, avoiding an index reset.
-    %
-    % OldSig is `ok` if no upgrade happened.
-    %
-    % To remove suppport for 1.2.x auto-upgrades in the
-    % future, just remove the next line and the code
-    % between "upgrade code for <= 1.2.x" and
-    % "end upgrade code for <= 1.2.x" and the corresponding
-    % code in couch_mrview_util
-
-    OldSig = couch_mrview_util:maybe_update_index_file(State),
-
-    case couch_mrview_util:open_file(IndexFName) of
-        {ok, Fd} ->
-            case (catch couch_file:read_header(Fd)) of
-                % upgrade code for <= 1.2.x
-                {ok, {OldSig, Header}} ->
-                    % Matching view signatures.
-                    NewSt = couch_mrview_util:init_state(Db, Fd, State, Header),
-                    {ok, RefCounter} = couch_ref_counter:start([Fd]),
-                    {ok, NewSt#mrst{refc=RefCounter}};
-                % end of upgrade code for <= 1.2.x
-                {ok, {Sig, Header}} ->
-                    % Matching view signatures.
-                    NewSt = couch_mrview_util:init_state(Db, Fd, State, Header),
-                    {ok, RefCounter} = couch_ref_counter:start([Fd]),
-                    {ok, NewSt#mrst{refc=RefCounter}};
-                _ ->
-                    NewSt = couch_mrview_util:reset_index(Db, Fd, State),
-                    {ok, RefCounter} = couch_ref_counter:start([Fd]),
-                    {ok, NewSt#mrst{refc=RefCounter}}
-            end;
-        {error, Reason} = Error ->
-            ?LOG_ERROR("Failed to open view file '~s': ~s",
-                       [IndexFName, file:format_error(Reason)]),
-            Error
-    end.
-
-
-close(State) ->
-    couch_file:close(State#mrst.fd).
-
-
-delete(#mrst{db_name=DbName, sig=Sig}=State) ->
-    couch_file:close(State#mrst.fd),
-    catch couch_mrview_util:delete_files(DbName, Sig).
-
-
-reset(State) ->
-    couch_util:with_db(State#mrst.db_name, fun(Db) ->
-        NewState = couch_mrview_util:reset_index(Db, State#mrst.fd, State),
-        {ok, NewState}
-    end).
-
-
-start_update(PartialDest, State, NumChanges) ->
-    couch_mrview_updater:start_update(PartialDest, State, NumChanges).
-
-
-purge(Db, PurgeSeq, PurgedIdRevs, State) ->
-    couch_mrview_updater:purge(Db, PurgeSeq, PurgedIdRevs, State).
-
-
-process_doc(Doc, Seq, State) ->
-    couch_mrview_updater:process_doc(Doc, Seq, State).
-
-
-finish_update(State) ->
-    couch_mrview_updater:finish_update(State).
-
-
-commit(State) ->
-    Header = {State#mrst.sig, couch_mrview_util:make_header(State)},
-    couch_file:write_header(State#mrst.fd, Header).
-
-
-compact(Db, State, Opts) ->
-    couch_mrview_compactor:compact(Db, State, Opts).
-
-
-swap_compacted(OldState, NewState) ->
-    couch_mrview_compactor:swap_compacted(OldState, NewState).
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_mrview/src/couch_mrview_show.erl
----------------------------------------------------------------------
diff --git a/apps/couch_mrview/src/couch_mrview_show.erl b/apps/couch_mrview/src/couch_mrview_show.erl
deleted file mode 100644
index 4ab8e17..0000000
--- a/apps/couch_mrview/src/couch_mrview_show.erl
+++ /dev/null
@@ -1,368 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_mrview_show).
-
--export([
-    handle_doc_show_req/3,
-    handle_doc_update_req/3,
-    handle_view_list_req/3
-]).
-
--include_lib("couch/include/couch_db.hrl").
--include_lib("couch_mrview/include/couch_mrview.hrl").
-
--record(lacc, {
-    db,
-    req,
-    resp,
-    qserver,
-    lname,
-    etag,
-    code,
-    headers
-}).
-
-% /db/_design/foo/_show/bar/docid
-% show converts a json doc to a response of any content-type.
-% it looks up the doc an then passes it to the query server.
-% then it sends the response from the query server to the http client.
-
-maybe_open_doc(Db, DocId) ->
-    case catch couch_httpd_db:couch_doc_open(Db, DocId, nil, [conflicts]) of
-        #doc{} = Doc -> Doc;
-        {not_found, _} -> nil
-    end.
-
-handle_doc_show_req(#httpd{
-        path_parts=[_, _, _, _, ShowName, DocId]
-    }=Req, Db, DDoc) ->
-
-    % open the doc
-    Doc = maybe_open_doc(Db, DocId),
-
-    % we don't handle revs here b/c they are an internal api
-    % returns 404 if there is no doc with DocId
-    handle_doc_show(Req, Db, DDoc, ShowName, Doc, DocId);
-
-handle_doc_show_req(#httpd{
-        path_parts=[_, _, _, _, ShowName, DocId|Rest]
-    }=Req, Db, DDoc) ->
-
-    DocParts = [DocId|Rest],
-    DocId1 = ?l2b(string:join([?b2l(P)|| P <- DocParts], "/")),
-
-    % open the doc
-    Doc = maybe_open_doc(Db, DocId1),
-
-    % we don't handle revs here b/c they are an internal api
-    % pass 404 docs to the show function
-    handle_doc_show(Req, Db, DDoc, ShowName, Doc, DocId1);
-
-handle_doc_show_req(#httpd{
-        path_parts=[_, _, _, _, ShowName]
-    }=Req, Db, DDoc) ->
-    % with no docid the doc is nil
-    handle_doc_show(Req, Db, DDoc, ShowName, nil);
-
-handle_doc_show_req(Req, _Db, _DDoc) ->
-    couch_httpd:send_error(Req, 404, <<"show_error">>, <<"Invalid path.">>).
-
-handle_doc_show(Req, Db, DDoc, ShowName, Doc) ->
-    handle_doc_show(Req, Db, DDoc, ShowName, Doc, null).
-
-handle_doc_show(Req, Db, DDoc, ShowName, Doc, DocId) ->
-    % get responder for ddoc/showname
-    CurrentEtag = show_etag(Req, Doc, DDoc, []),
-    couch_httpd:etag_respond(Req, CurrentEtag, fun() ->
-        JsonReq = couch_httpd_external:json_req_obj(Req, Db, DocId),
-        JsonDoc = couch_query_servers:json_doc(Doc),
-        [<<"resp">>, ExternalResp] =
-            couch_query_servers:ddoc_prompt(DDoc, [<<"shows">>, ShowName],
-                [JsonDoc, JsonReq]),
-        JsonResp = apply_etag(ExternalResp, CurrentEtag),
-        couch_httpd_external:send_external_response(Req, JsonResp)
-    end).
-
-
-show_etag(#httpd{user_ctx=UserCtx}=Req, Doc, DDoc, More) ->
-    Accept = couch_httpd:header_value(Req, "Accept"),
-    DocPart = case Doc of
-        nil -> nil;
-        Doc -> couch_httpd:doc_etag(Doc)
-    end,
-    couch_httpd:make_etag({couch_httpd:doc_etag(DDoc), DocPart, Accept,
-        {UserCtx#user_ctx.name, UserCtx#user_ctx.roles}, More}).
-
-% updates a doc based on a request
-% handle_doc_update_req(#httpd{method = 'GET'}=Req, _Db, _DDoc) ->
-%     % anything but GET
-%     send_method_not_allowed(Req, "POST,PUT,DELETE,ETC");
-
-% This call is creating a new doc using an _update function to
-% modify the provided request body.
-% /db/_design/foo/_update/bar
-handle_doc_update_req(#httpd{
-        path_parts=[_, _, _, _, UpdateName]
-    }=Req, Db, DDoc) ->
-    send_doc_update_response(Req, Db, DDoc, UpdateName, nil, null);
-
-% /db/_design/foo/_update/bar/docid
-handle_doc_update_req(#httpd{
-        path_parts=[_, _, _, _, UpdateName | DocIdParts]
-    }=Req, Db, DDoc) ->
-    DocId = ?l2b(string:join([?b2l(P) || P <- DocIdParts], "/")),
-    Doc = maybe_open_doc(Db, DocId),
-    send_doc_update_response(Req, Db, DDoc, UpdateName, Doc, DocId);
-
-
-handle_doc_update_req(Req, _Db, _DDoc) ->
-    couch_httpd:send_error(Req, 404, <<"update_error">>, <<"Invalid path.">>).
-
-send_doc_update_response(Req, Db, DDoc, UpdateName, Doc, DocId) ->
-    JsonReq = couch_httpd_external:json_req_obj(Req, Db, DocId),
-    JsonDoc = couch_query_servers:json_doc(Doc),
-    Cmd = [<<"updates">>, UpdateName],
-    UpdateResp = couch_query_servers:ddoc_prompt(DDoc, Cmd, [JsonDoc, JsonReq]),
-    JsonResp = case UpdateResp of
-        [<<"up">>, {NewJsonDoc}, {JsonResp0}] ->
-            case couch_httpd:header_value(
-                    Req, "X-Couch-Full-Commit", "false") of
-                "true" ->
-                    Options = [full_commit, {user_ctx, Req#httpd.user_ctx}];
-                _ ->
-                    Options = [{user_ctx, Req#httpd.user_ctx}]
-            end,
-            NewDoc = couch_doc:from_json_obj({NewJsonDoc}),
-            couch_doc:validate_docid(NewDoc#doc.id),
-            {ok, NewRev} = couch_db:update_doc(Db, NewDoc, Options),
-            NewRevStr = couch_doc:rev_to_str(NewRev),
-            {[
-                {<<"code">>, 201},
-                {<<"headers">>, {[
-                    {<<"X-Couch-Update-NewRev">>, NewRevStr},
-                    {<<"X-Couch-Id">>, NewDoc#doc.id}
-                ]}}
-                | JsonResp0]};
-        [<<"up">>, _Other, {JsonResp0}] ->
-            {[{<<"code">>, 200} | JsonResp0]}
-    end,
-    % todo set location field
-    couch_httpd_external:send_external_response(Req, JsonResp).
-
-
-handle_view_list_req(#httpd{method=Method}=Req, Db, DDoc)
-    when Method =:= 'GET' orelse Method =:= 'OPTIONS' ->
-    case Req#httpd.path_parts of
-        [_, _, _DName, _, LName, VName] ->
-            % Same design doc for view and list
-            handle_view_list(Req, Db, DDoc, LName, DDoc, VName, undefined);
-        [_, _, _, _, LName, DName, VName] ->
-            % Different design docs for view and list
-            VDocId = <<"_design/", DName/binary>>,
-            {ok, VDDoc} = couch_db:open_doc(Db, VDocId, [ejson_body]),
-            handle_view_list(Req, Db, DDoc, LName, VDDoc, VName, undefined);
-        _ ->
-            couch_httpd:send_error(Req, 404, <<"list_error">>, <<"Bad path.">>)
-    end;
-handle_view_list_req(#httpd{method='POST'}=Req, Db, DDoc) ->
-    {Props} = couch_httpd:json_body_obj(Req),
-    Keys = proplists:get_value(<<"keys">>, Props),
-    case Req#httpd.path_parts of
-        [_, _, _DName, _, LName, VName] ->
-            handle_view_list(Req, Db, DDoc, LName, DDoc, VName, Keys);
-        [_, _, _, _, LName, DName, VName] ->
-            % Different design docs for view and list
-            VDocId = <<"_design/", DName/binary>>,
-            {ok, VDDoc} = couch_db:open_doc(Db, VDocId, [ejson_body]),
-            handle_view_list(Req, Db, DDoc, LName, VDDoc, VName, Keys);
-        _ ->
-            couch_httpd:send_error(Req, 404, <<"list_error">>, <<"Bad path.">>)
-    end;
-handle_view_list_req(Req, _Db, _DDoc) ->
-    couch_httpd:send_method_not_allowed(Req, "GET,POST,HEAD").
-
-
-handle_view_list(Req, Db, DDoc, LName, VDDoc, VName, Keys) ->
-    Args0 = couch_mrview_http:parse_qs(Req, Keys),
-    ETagFun = fun(BaseSig, Acc0) ->
-        UserCtx = Req#httpd.user_ctx,
-        Name = UserCtx#user_ctx.name,
-        Roles = UserCtx#user_ctx.roles,
-        Accept = couch_httpd:header_value(Req, "Accept"),
-        Parts = {couch_httpd:doc_etag(DDoc), Accept, {Name, Roles}},
-        ETag = couch_httpd:make_etag({BaseSig, Parts}),
-        case couch_httpd:etag_match(Req, ETag) of
-            true -> throw({etag_match, ETag});
-            false -> {ok, Acc0#lacc{etag=ETag}}
-        end
-    end,
-    Args = Args0#mrargs{preflight_fun=ETagFun},
-    couch_httpd:etag_maybe(Req, fun() ->
-        couch_query_servers:with_ddoc_proc(DDoc, fun(QServer) ->
-            Acc = #lacc{db=Db, req=Req, qserver=QServer, lname=LName},
-            case VName of
-              <<"_all_docs">> ->
-                couch_mrview:query_all_docs(Db, Args, fun list_cb/2, Acc);
-              _ ->
-                couch_mrview:query_view(Db, VDDoc, VName, Args, fun list_cb/2, Acc)
-            end
-        end)
-    end).
-
-
-list_cb({meta, Meta}, #lacc{code=undefined} = Acc) ->
-    MetaProps = case couch_util:get_value(total, Meta) of
-        undefined -> [];
-        Total -> [{total_rows, Total}]
-    end ++ case couch_util:get_value(offset, Meta) of
-        undefined -> [];
-        Offset -> [{offset, Offset}]
-    end ++ case couch_util:get_value(update_seq, Meta) of
-        undefined -> [];
-        UpdateSeq -> [{update_seq, UpdateSeq}]
-    end,
-    start_list_resp({MetaProps}, Acc);
-list_cb({row, Row}, #lacc{code=undefined} = Acc) ->
-    {ok, NewAcc} = start_list_resp({[]}, Acc),
-    send_list_row(Row, NewAcc);
-list_cb({row, Row}, Acc) ->
-    send_list_row(Row, Acc);
-list_cb(complete, Acc) ->
-    #lacc{qserver = {Proc, _}, resp = Resp0} = Acc,
-    if Resp0 =:= nil ->
-        {ok, #lacc{resp = Resp}} = start_list_resp({[]}, Acc);
-    true ->
-        Resp = Resp0
-    end,
-    case couch_query_servers:proc_prompt(Proc, [<<"list_end">>]) of
-        [<<"end">>, Data, Headers] ->
-            Acc2 = fixup_headers(Headers, Acc#lacc{resp=Resp}),
-            #lacc{resp = Resp2} = send_non_empty_chunk(Acc2, Data);
-        [<<"end">>, Data] ->
-            #lacc{resp = Resp2} = send_non_empty_chunk(Acc#lacc{resp=Resp}, Data)
-    end,
-    couch_httpd:last_chunk(Resp2),
-    {ok, Resp2}.
-
-start_list_resp(Head, Acc) ->
-    #lacc{db=Db, req=Req, qserver=QServer, lname=LName} = Acc,
-    JsonReq = couch_httpd_external:json_req_obj(Req, Db),
-
-    [<<"start">>,Chunk,JsonResp] = couch_query_servers:ddoc_proc_prompt(QServer,
-        [<<"lists">>, LName], [Head, JsonReq]),
-    Acc2 = send_non_empty_chunk(fixup_headers(JsonResp, Acc), Chunk),
-    {ok, Acc2}.
-
-fixup_headers(Headers, #lacc{etag=ETag} = Acc) ->
-    Headers2 = apply_etag(Headers, ETag),
-    #extern_resp_args{
-        code = Code,
-        ctype = CType,
-        headers = ExtHeaders
-    } = couch_httpd_external:parse_external_response(Headers2),
-    Headers3 = couch_httpd_external:default_or_content_type(CType, ExtHeaders),
-    Acc#lacc{code=Code, headers=Headers3}.
-
-send_list_row(Row, #lacc{qserver = {Proc, _}, resp = Resp} = Acc) ->
-    RowObj = case couch_util:get_value(id, Row) of
-        undefined -> [];
-        Id -> [{id, Id}]
-    end ++ case couch_util:get_value(key, Row) of
-        undefined -> [];
-        Key -> [{key, Key}]
-    end ++ case couch_util:get_value(value, Row) of
-        undefined -> [];
-        Val -> [{value, Val}]
-    end ++ case couch_util:get_value(doc, Row) of
-        undefined -> [];
-        Doc -> [{doc, Doc}]
-    end,
-    try couch_query_servers:proc_prompt(Proc, [<<"list_row">>, {RowObj}]) of
-    [<<"chunks">>, Chunk, Headers] ->
-        Acc2 = send_non_empty_chunk(fixup_headers(Headers, Acc), Chunk),
-        {ok, Acc2};
-    [<<"chunks">>, Chunk] ->
-        Acc2 = send_non_empty_chunk(Acc, Chunk),
-        {ok, Acc2};
-    [<<"end">>, Chunk, Headers] ->
-        Acc2 = send_non_empty_chunk(fixup_headers(Headers, Acc), Chunk),
-        #lacc{resp = Resp2} = Acc2,
-        couch_httpd:last_chunk(Resp2),
-        {stop, Acc2};
-    [<<"end">>, Chunk] ->
-        Acc2 = send_non_empty_chunk(Acc, Chunk),
-        #lacc{resp = Resp2} = Acc2,
-        couch_httpd:last_chunk(Resp2),
-        {stop, Acc2}
-    catch Error ->
-        case Resp of
-            undefined ->
-                {Code, _, _} = couch_httpd:error_info(Error),
-                #lacc{req=Req, headers=Headers} = Acc,
-                {ok, Resp2} = couch_httpd:start_chunked_response(Req, Code, Headers),
-                Acc2 = Acc#lacc{resp=Resp2, code=Code};
-            _ -> Resp2 = Resp, Acc2 = Acc
-        end,
-        couch_httpd:send_chunked_error(Resp2, Error),
-        {stop, Acc2}
-    end.
-
-send_non_empty_chunk(Acc, []) ->
-    Acc;
-send_non_empty_chunk(#lacc{resp=undefined} = Acc, Chunk) ->
-    #lacc{req=Req, code=Code, headers=Headers} = Acc,
-    {ok, Resp} = couch_httpd:start_chunked_response(Req, Code, Headers),
-    send_non_empty_chunk(Acc#lacc{resp = Resp}, Chunk);
-send_non_empty_chunk(#lacc{resp=Resp} = Acc, Chunk) ->
-    couch_httpd:send_chunk(Resp, Chunk),
-    Acc.
-
-
-apply_etag({ExternalResponse}, CurrentEtag) ->
-    % Here we embark on the delicate task of replacing or creating the
-    % headers on the JsonResponse object. We need to control the Etag and
-    % Vary headers. If the external function controls the Etag, we'd have to
-    % run it to check for a match, which sort of defeats the purpose.
-    case couch_util:get_value(<<"headers">>, ExternalResponse, nil) of
-    nil ->
-        % no JSON headers
-        % add our Etag and Vary headers to the response
-        {[{<<"headers">>, {[{<<"Etag">>, CurrentEtag}, {<<"Vary">>, <<"Accept">>}]}} | ExternalResponse]};
-    JsonHeaders ->
-        {[case Field of
-        {<<"headers">>, JsonHeaders} -> % add our headers
-            JsonHeadersEtagged = json_apply_field({<<"Etag">>, CurrentEtag}, JsonHeaders),
-            JsonHeadersVaried = json_apply_field({<<"Vary">>, <<"Accept">>}, JsonHeadersEtagged),
-            {<<"headers">>, JsonHeadersVaried};
-        _ -> % skip non-header fields
-            Field
-        end || Field <- ExternalResponse]}
-    end.
-
-
-% Maybe this is in the proplists API
-% todo move to couch_util
-json_apply_field(H, {L}) ->
-    json_apply_field(H, L, []).
-
-
-json_apply_field({Key, NewValue}, [{Key, _OldVal} | Headers], Acc) ->
-    % drop matching keys
-    json_apply_field({Key, NewValue}, Headers, Acc);
-json_apply_field({Key, NewValue}, [{OtherKey, OtherVal} | Headers], Acc) ->
-    % something else is next, leave it alone.
-    json_apply_field({Key, NewValue}, Headers, [{OtherKey, OtherVal} | Acc]);
-json_apply_field({Key, NewValue}, [], Acc) ->
-    % end of list, add ours
-    {[{Key, NewValue}|Acc]}.
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_mrview/src/couch_mrview_test_util.erl
----------------------------------------------------------------------
diff --git a/apps/couch_mrview/src/couch_mrview_test_util.erl b/apps/couch_mrview/src/couch_mrview_test_util.erl
deleted file mode 100644
index adc2675..0000000
--- a/apps/couch_mrview/src/couch_mrview_test_util.erl
+++ /dev/null
@@ -1,92 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_mrview_test_util).
-
--compile(export_all).
-
--include_lib("couch/include/couch_db.hrl").
-
--define(ADMIN, #user_ctx{roles=[<<"_admin">>]}).
-
-
-init_db(Name, Type) ->
-    init_db(Name, Type, 10).
-
-
-init_db(Name, Type, Count) ->
-    {ok, Db} = new_db(Name, Type),
-    Docs = make_docs(Count),
-    save_docs(Db, Docs).
-
-
-new_db(Name, Type) ->
-    couch_server:delete(Name, [{user_ctx, ?ADMIN}]),
-    {ok, Db} = couch_db:create(Name, [{user_ctx, ?ADMIN}]),
-    save_docs(Db, [ddoc(Type)]).
-
-
-save_docs(Db, Docs) ->
-    {ok, _} = couch_db:update_docs(Db, Docs, []),
-    couch_db:reopen(Db).
-
-
-make_docs(Count) ->
-    make_docs(Count, []).
-
-make_docs(Count, Acc) when Count =< 0 ->
-    Acc;
-make_docs(Count, Acc) ->
-    make_docs(Count-1, [doc(Count) | Acc]).
-
-
-ddoc(map) ->
-    couch_doc:from_json_obj({[
-        {<<"_id">>, <<"_design/bar">>},
-        {<<"views">>, {[
-            {<<"baz">>, {[
-                {<<"map">>, <<"function(doc) {emit(doc.val, doc.val);}">>}
-            ]}},
-            {<<"bing">>, {[
-                {<<"map">>, <<"function(doc) {}">>}
-            ]}},
-            {<<"zing">>, {[
-                {<<"map">>, <<
-                    "function(doc) {\n"
-                    "  if(doc.foo !== undefined)\n"
-                    "    emit(doc.foo, 0);\n"
-                    "}"
-                >>}
-            ]}}
-        ]}}
-    ]});
-ddoc(red) ->
-    couch_doc:from_json_obj({[
-        {<<"_id">>, <<"_design/bar">>},
-        {<<"views">>, {[
-            {<<"baz">>, {[
-                {<<"map">>, <<
-                    "function(doc) {\n"
-                    "  emit([doc.val % 2, doc.val], doc.val);\n"
-                    "}\n"
-                >>},
-                {<<"reduce">>, <<"function(keys, vals) {return sum(vals);}">>}
-            ]}}
-        ]}}
-    ]}).
-
-
-doc(Id) ->
-    couch_doc:from_json_obj({[
-        {<<"_id">>, list_to_binary(integer_to_list(Id))},
-        {<<"val">>, Id}
-    ]}).

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_mrview/src/couch_mrview_updater.erl
----------------------------------------------------------------------
diff --git a/apps/couch_mrview/src/couch_mrview_updater.erl b/apps/couch_mrview/src/couch_mrview_updater.erl
deleted file mode 100644
index 980b5cf..0000000
--- a/apps/couch_mrview/src/couch_mrview_updater.erl
+++ /dev/null
@@ -1,282 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_mrview_updater).
-
--export([start_update/3, purge/4, process_doc/3, finish_update/1]).
-
--include_lib("couch/include/couch_db.hrl").
--include_lib("couch_mrview/include/couch_mrview.hrl").
-
-
-start_update(Partial, State, NumChanges) ->
-    QueueOpts = [{max_size, 100000}, {max_items, 500}],
-    {ok, DocQueue} = couch_work_queue:new(QueueOpts),
-    {ok, WriteQueue} = couch_work_queue:new(QueueOpts),
-
-    InitState = State#mrst{
-        first_build=State#mrst.update_seq==0,
-        partial_resp_pid=Partial,
-        doc_acc=[],
-        doc_queue=DocQueue,
-        write_queue=WriteQueue
-    },
-
-    Self = self(),
-    MapFun = fun() ->
-        couch_task_status:add_task([
-            {type, indexer},
-            {database, State#mrst.db_name},
-            {design_document, State#mrst.idx_name},
-            {progress, 0},
-            {changes_done, 0},
-            {total_changes, NumChanges}
-        ]),
-        couch_task_status:set_update_frequency(500),
-        map_docs(Self, InitState)
-    end,
-    WriteFun = fun() -> write_results(Self, InitState) end,
-
-    spawn_link(MapFun),
-    spawn_link(WriteFun),
-
-    {ok, InitState}.
-
-
-purge(_Db, PurgeSeq, PurgedIdRevs, State) ->
-    #mrst{
-        id_btree=IdBtree,
-        views=Views
-    } = State,
-
-    Ids = [Id || {Id, _Revs} <- PurgedIdRevs],
-    {ok, Lookups, IdBtree2} = couch_btree:query_modify(IdBtree, Ids, [], Ids),
-
-    MakeDictFun = fun
-        ({ok, {DocId, ViewNumRowKeys}}, DictAcc) ->
-            FoldFun = fun({ViewNum, RowKey}, DictAcc2) ->
-                dict:append(ViewNum, {RowKey, DocId}, DictAcc2)
-            end,
-            lists:foldl(FoldFun, DictAcc, ViewNumRowKeys);
-        ({not_found, _}, DictAcc) ->
-            DictAcc
-    end,
-    KeysToRemove = lists:foldl(MakeDictFun, dict:new(), Lookups),
-
-    RemKeysFun = fun(#mrview{id_num=Num, btree=Btree}=View) ->
-        case dict:find(Num, KeysToRemove) of
-            {ok, RemKeys} ->
-                {ok, Btree2} = couch_btree:add_remove(Btree, [], RemKeys),
-                NewPurgeSeq = case Btree2 /= Btree of
-                    true -> PurgeSeq;
-                    _ -> View#mrview.purge_seq
-                end,
-                View#mrview{btree=Btree2, purge_seq=NewPurgeSeq};
-            error ->
-                View
-        end
-    end,
-
-    Views2 = lists:map(RemKeysFun, Views),
-    {ok, State#mrst{
-        id_btree=IdBtree2,
-        views=Views2,
-        purge_seq=PurgeSeq
-    }}.
-
-
-process_doc(Doc, Seq, #mrst{doc_acc=Acc}=State) when length(Acc) > 100 ->
-    couch_work_queue:queue(State#mrst.doc_queue, lists:reverse(Acc)),
-    process_doc(Doc, Seq, State#mrst{doc_acc=[]});
-process_doc(nil, Seq, #mrst{doc_acc=Acc}=State) ->
-    {ok, State#mrst{doc_acc=[{nil, Seq, nil} | Acc]}};
-process_doc(#doc{id=Id, deleted=true}, Seq, #mrst{doc_acc=Acc}=State) ->
-    {ok, State#mrst{doc_acc=[{Id, Seq, deleted} | Acc]}};
-process_doc(#doc{id=Id}=Doc, Seq, #mrst{doc_acc=Acc}=State) ->
-    {ok, State#mrst{doc_acc=[{Id, Seq, Doc} | Acc]}}.
-
-
-finish_update(#mrst{doc_acc=Acc}=State) ->
-    if Acc /= [] ->
-        couch_work_queue:queue(State#mrst.doc_queue, Acc);
-        true -> ok
-    end,
-    couch_work_queue:close(State#mrst.doc_queue),
-    receive
-        {new_state, NewState} ->
-            {ok, NewState#mrst{
-                first_build=undefined,
-                partial_resp_pid=undefined,
-                doc_acc=undefined,
-                doc_queue=undefined,
-                write_queue=undefined,
-                qserver=nil
-            }}
-    end.
-
-
-map_docs(Parent, State0) ->
-    case couch_work_queue:dequeue(State0#mrst.doc_queue) of
-        closed ->
-            couch_query_servers:stop_doc_map(State0#mrst.qserver),
-            couch_work_queue:close(State0#mrst.write_queue);
-        {ok, Dequeued} ->
-            % Run all the non deleted docs through the view engine and
-            % then pass the results on to the writer process.
-            State1 = case State0#mrst.qserver of
-                nil -> start_query_server(State0);
-                _ -> State0
-            end,
-            QServer = State1#mrst.qserver,
-            DocFun = fun
-                ({nil, Seq, _}, {SeqAcc, Results}) ->
-                    {erlang:max(Seq, SeqAcc), Results};
-                ({Id, Seq, deleted}, {SeqAcc, Results}) ->
-                    {erlang:max(Seq, SeqAcc), [{Id, []} | Results]};
-                ({Id, Seq, Doc}, {SeqAcc, Results}) ->
-                    {ok, Res} = couch_query_servers:map_doc_raw(QServer, Doc),
-                    {erlang:max(Seq, SeqAcc), [{Id, Res} | Results]}
-            end,
-            FoldFun = fun(Docs, Acc) ->
-                update_task(length(Docs)),
-                lists:foldl(DocFun, Acc, Docs)
-            end,
-            Results = lists:foldl(FoldFun, {0, []}, Dequeued),
-            couch_work_queue:queue(State1#mrst.write_queue, Results),
-            map_docs(Parent, State1)
-    end.
-
-
-write_results(Parent, State) ->
-    case couch_work_queue:dequeue(State#mrst.write_queue) of
-        closed ->
-            Parent ! {new_state, State};
-        {ok, Info} ->
-            EmptyKVs = [{V#mrview.id_num, []} || V <- State#mrst.views],
-            {Seq, ViewKVs, DocIdKeys} = merge_results(Info, 0, EmptyKVs, []),
-            NewState = write_kvs(State, Seq, ViewKVs, DocIdKeys),
-            send_partial(NewState#mrst.partial_resp_pid, NewState),
-            write_results(Parent, NewState)
-    end.
-
-
-start_query_server(State) ->
-    #mrst{
-        language=Language,
-        lib=Lib,
-        views=Views
-    } = State,
-    Defs = [View#mrview.def || View <- Views],
-    {ok, QServer} = couch_query_servers:start_doc_map(Language, Defs, Lib),
-    State#mrst{qserver=QServer}.
-
-
-merge_results([], SeqAcc, ViewKVs, DocIdKeys) ->
-    {SeqAcc, ViewKVs, DocIdKeys};
-merge_results([{Seq, Results} | Rest], SeqAcc, ViewKVs, DocIdKeys) ->
-    Fun = fun(RawResults, {VKV, DIK}) ->
-        merge_results(RawResults, VKV, DIK)
-    end,
-    {ViewKVs1, DocIdKeys1} = lists:foldl(Fun, {ViewKVs, DocIdKeys}, Results),
-    merge_results(Rest, erlang:max(Seq, SeqAcc), ViewKVs1, DocIdKeys1).
-
-
-merge_results({DocId, []}, ViewKVs, DocIdKeys) ->
-    {ViewKVs, [{DocId, []} | DocIdKeys]};
-merge_results({DocId, RawResults}, ViewKVs, DocIdKeys) ->
-    JsonResults = couch_query_servers:raw_to_ejson(RawResults),
-    Results = [[list_to_tuple(Res) || Res <- FunRs] || FunRs <- JsonResults],
-    {ViewKVs1, ViewIdKeys} = insert_results(DocId, Results, ViewKVs, [], []),
-    {ViewKVs1, [ViewIdKeys | DocIdKeys]}.
-
-
-insert_results(DocId, [], [], ViewKVs, ViewIdKeys) ->
-    {lists:reverse(ViewKVs), {DocId, ViewIdKeys}};
-insert_results(DocId, [KVs | RKVs], [{Id, VKVs} | RVKVs], VKVAcc, VIdKeys) ->
-    CombineDupesFun = fun
-        ({Key, Val}, {[{Key, {dups, Vals}} | Rest], IdKeys}) ->
-            {[{Key, {dups, [Val | Vals]}} | Rest], IdKeys};
-        ({Key, Val1}, {[{Key, Val2} | Rest], IdKeys}) ->
-            {[{Key, {dups, [Val1, Val2]}} | Rest], IdKeys};
-        ({Key, _}=KV, {Rest, IdKeys}) ->
-            {[KV | Rest], [{Id, Key} | IdKeys]}
-    end,
-    InitAcc = {[], VIdKeys},
-    {Duped, VIdKeys0} = lists:foldl(CombineDupesFun, InitAcc, lists:sort(KVs)),
-    FinalKVs = [{{Key, DocId}, Val} || {Key, Val} <- Duped] ++ VKVs,
-    insert_results(DocId, RKVs, RVKVs, [{Id, FinalKVs} | VKVAcc], VIdKeys0).
-
-
-write_kvs(State, UpdateSeq, ViewKVs, DocIdKeys) ->
-    #mrst{
-        id_btree=IdBtree,
-        first_build=FirstBuild
-    } = State,
-
-    {ok, ToRemove, IdBtree2} = update_id_btree(IdBtree, DocIdKeys, FirstBuild),
-    ToRemByView = collapse_rem_keys(ToRemove, dict:new()),
-
-    UpdateView = fun(#mrview{id_num=ViewId}=View, {ViewId, KVs}) ->
-        ToRem = couch_util:dict_find(ViewId, ToRemByView, []),
-        {ok, VBtree2} = couch_btree:add_remove(View#mrview.btree, KVs, ToRem),
-        NewUpdateSeq = case VBtree2 =/= View#mrview.btree of
-            true -> UpdateSeq;
-            _ -> View#mrview.update_seq
-        end,
-        View#mrview{btree=VBtree2, update_seq=NewUpdateSeq}
-    end,
-
-    State#mrst{
-        views=lists:zipwith(UpdateView, State#mrst.views, ViewKVs),
-        update_seq=UpdateSeq,
-        id_btree=IdBtree2
-    }.
-
-
-update_id_btree(Btree, DocIdKeys, true) ->
-    ToAdd = [{Id, DIKeys} || {Id, DIKeys} <- DocIdKeys, DIKeys /= []],
-    couch_btree:query_modify(Btree, [], ToAdd, []);
-update_id_btree(Btree, DocIdKeys, _) ->
-    ToFind = [Id || {Id, _} <- DocIdKeys],
-    ToAdd = [{Id, DIKeys} || {Id, DIKeys} <- DocIdKeys, DIKeys /= []],
-    ToRem = [Id || {Id, DIKeys} <- DocIdKeys, DIKeys == []],
-    couch_btree:query_modify(Btree, ToFind, ToAdd, ToRem).
-
-
-collapse_rem_keys([], Acc) ->
-    Acc;
-collapse_rem_keys([{ok, {DocId, ViewIdKeys}} | Rest], Acc) ->
-    NewAcc = lists:foldl(fun({ViewId, Key}, Acc2) ->
-        dict:append(ViewId, {Key, DocId}, Acc2)
-    end, Acc, ViewIdKeys),
-    collapse_rem_keys(Rest, NewAcc);
-collapse_rem_keys([{not_found, _} | Rest], Acc) ->
-    collapse_rem_keys(Rest, Acc).
-
-
-send_partial(Pid, State) when is_pid(Pid) ->
-    gen_server:cast(Pid, {new_state, State});
-send_partial(_, _) ->
-    ok.
-
-
-update_task(NumChanges) ->
-    [Changes, Total] = couch_task_status:get([changes_done, total_changes]),
-    Changes2 = Changes + NumChanges,
-    Progress = case Total of
-        0 ->
-            % updater restart after compaction finishes
-            0;
-        _ ->
-            (Changes2 * 100) div Total
-    end,
-    couch_task_status:update([{progress, Progress}, {changes_done, Changes2}]).

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_mrview/src/couch_mrview_util.erl
----------------------------------------------------------------------
diff --git a/apps/couch_mrview/src/couch_mrview_util.erl b/apps/couch_mrview/src/couch_mrview_util.erl
deleted file mode 100644
index f7946d1..0000000
--- a/apps/couch_mrview/src/couch_mrview_util.erl
+++ /dev/null
@@ -1,802 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_mrview_util).
-
--export([get_view/4]).
--export([ddoc_to_mrst/2, init_state/4, reset_index/3]).
--export([make_header/1]).
--export([index_file/2, compaction_file/2, open_file/1]).
--export([delete_files/2, delete_index_file/2, delete_compaction_file/2]).
--export([get_row_count/1, all_docs_reduce_to_count/1, reduce_to_count/1]).
--export([all_docs_key_opts/1, all_docs_key_opts/2, key_opts/1, key_opts/2]).
--export([fold/4, fold_reduce/4]).
--export([temp_view_to_ddoc/1]).
--export([calculate_data_size/2]).
--export([validate_args/1]).
--export([maybe_load_doc/3, maybe_load_doc/4]).
--export([maybe_update_index_file/1]).
-
--define(MOD, couch_mrview_index).
-
--include_lib("couch/include/couch_db.hrl").
--include_lib("couch_mrview/include/couch_mrview.hrl").
-
-
-get_view(Db, DDoc, ViewName, Args0) ->
-    ArgCheck = fun(InitState) ->
-        Args1 = set_view_type(Args0, ViewName, InitState#mrst.views),
-        {ok, validate_args(Args1)}
-    end,
-    {ok, Pid, Args2} = couch_index_server:get_index(?MOD, Db, DDoc, ArgCheck),
-    DbUpdateSeq = couch_util:with_db(Db, fun(WDb) ->
-        couch_db:get_update_seq(WDb)
-    end),
-    MinSeq = case Args2#mrargs.stale of
-        ok -> 0; update_after -> 0; _ -> DbUpdateSeq
-    end,
-    {ok, State} = case couch_index:get_state(Pid, MinSeq) of
-        {ok, _} = Resp -> Resp;
-        Error -> throw(Error)
-    end,
-    couch_ref_counter:add(State#mrst.refc),
-    if Args2#mrargs.stale == update_after ->
-        spawn(fun() -> catch couch_index:get_state(Pid, DbUpdateSeq) end);
-        true -> ok
-    end,
-    #mrst{language=Lang, views=Views} = State,
-    {Type, View, Args3} = extract_view(Lang, Args2, ViewName, Views),
-    check_range(Args3, view_cmp(View)),
-    Sig = view_sig(Db, State, View, Args3),
-    {ok, {Type, View}, Sig, Args3}.
-
-
-ddoc_to_mrst(DbName, #doc{id=Id, body={Fields}}) ->
-    MakeDict = fun({Name, {MRFuns}}, DictBySrcAcc) ->
-        case couch_util:get_value(<<"map">>, MRFuns) of
-            MapSrc when is_binary(MapSrc) ->
-                RedSrc = couch_util:get_value(<<"reduce">>, MRFuns, null),
-                {ViewOpts} = couch_util:get_value(<<"options">>, MRFuns, {[]}),
-                View = case dict:find({MapSrc, ViewOpts}, DictBySrcAcc) of
-                    {ok, View0} -> View0;
-                    error -> #mrview{def=MapSrc, options=ViewOpts}
-                end,
-                {MapNames, RedSrcs} = case RedSrc of
-                    null ->
-                        MNames = [Name | View#mrview.map_names],
-                        {MNames, View#mrview.reduce_funs};
-                    _ ->
-                        RedFuns = [{Name, RedSrc} | View#mrview.reduce_funs],
-                        {View#mrview.map_names, RedFuns}
-                end,
-                View2 = View#mrview{map_names=MapNames, reduce_funs=RedSrcs},
-                dict:store({MapSrc, ViewOpts}, View2, DictBySrcAcc);
-            undefined ->
-                DictBySrcAcc
-        end
-    end,
-    {RawViews} = couch_util:get_value(<<"views">>, Fields, {[]}),
-    BySrc = lists:foldl(MakeDict, dict:new(), RawViews),
-
-    NumViews = fun({_, View}, N) -> {View#mrview{id_num=N}, N+1} end,
-    {Views, _} = lists:mapfoldl(NumViews, 0, lists:sort(dict:to_list(BySrc))),
-
-    Language = couch_util:get_value(<<"language">>, Fields, <<"javascript">>),
-    {DesignOpts} = couch_util:get_value(<<"options">>, Fields, {[]}),
-    {RawViews} = couch_util:get_value(<<"views">>, Fields, {[]}),
-    Lib = couch_util:get_value(<<"lib">>, RawViews, {[]}),
-
-    IdxState = #mrst{
-        db_name=DbName,
-        idx_name=Id,
-        lib=Lib,
-        views=Views,
-        language=Language,
-        design_opts=DesignOpts
-    },
-    SigInfo = {Views, Language, DesignOpts, couch_index_util:sort_lib(Lib)},
-    {ok, IdxState#mrst{sig=couch_util:md5(term_to_binary(SigInfo))}}.
-
-
-set_view_type(_Args, _ViewName, []) ->
-    throw({not_found, missing_named_view});
-set_view_type(Args, ViewName, [View | Rest]) ->
-    RedNames = [N || {N, _} <- View#mrview.reduce_funs],
-    case lists:member(ViewName, RedNames) of
-        true ->
-            case Args#mrargs.reduce of
-                false -> Args#mrargs{view_type=map};
-                _ -> Args#mrargs{view_type=red}
-            end;
-        false ->
-            case lists:member(ViewName, View#mrview.map_names) of
-                true -> Args#mrargs{view_type=map};
-                false -> set_view_type(Args, ViewName, Rest)
-            end
-    end.
-
-
-extract_view(_Lang, _Args, _ViewName, []) ->
-    throw({not_found, missing_named_view});
-extract_view(Lang, #mrargs{view_type=map}=Args, Name, [View | Rest]) ->
-    Names = View#mrview.map_names ++ [N || {N, _} <- View#mrview.reduce_funs],
-    case lists:member(Name, Names) of
-        true -> {map, View, Args};
-        _ -> extract_view(Lang, Args, Name, Rest)
-    end;
-extract_view(Lang, #mrargs{view_type=red}=Args, Name, [View | Rest]) ->
-    RedNames = [N || {N, _} <- View#mrview.reduce_funs],
-    case lists:member(Name, RedNames) of
-        true -> {red, {index_of(Name, RedNames), Lang, View}, Args};
-        false -> extract_view(Lang, Args, Name, Rest)
-    end.
-
-
-view_sig(Db, State, View, #mrargs{include_docs=true}=Args) ->
-    BaseSig = view_sig(Db, State, View, Args#mrargs{include_docs=false}),
-    UpdateSeq = couch_db:get_update_seq(Db),
-    PurgeSeq = couch_db:get_purge_seq(Db),
-    Bin = term_to_binary({BaseSig, UpdateSeq, PurgeSeq}),
-    couch_index_util:hexsig(couch_util:md5(Bin));
-view_sig(Db, State, {_Nth, _Lang, View}, Args) ->
-    view_sig(Db, State, View, Args);
-view_sig(_Db, State, View, Args0) ->
-    Sig = State#mrst.sig,
-    UpdateSeq = View#mrview.update_seq,
-    PurgeSeq = View#mrview.purge_seq,
-    Args = Args0#mrargs{
-        preflight_fun=undefined,
-        extra=[]
-    },
-    Bin = term_to_binary({Sig, UpdateSeq, PurgeSeq, Args}),
-    couch_index_util:hexsig(couch_util:md5(Bin)).
-
-
-init_state(Db, Fd, #mrst{views=Views}=State, nil) ->
-    Header = #mrheader{
-        seq=0,
-        purge_seq=couch_db:get_purge_seq(Db),
-        id_btree_state=nil,
-        view_states=[{nil, 0, 0} || _ <- Views]
-    },
-    init_state(Db, Fd, State, Header);
-% read <= 1.2.x header record and transpile it to >=1.3.x
-% header record
-init_state(Db, Fd, State, #index_header{
-    seq=Seq,
-    purge_seq=PurgeSeq,
-    id_btree_state=IdBtreeState,
-    view_states=ViewStates}) ->
-    init_state(Db, Fd, State, #mrheader{
-        seq=Seq,
-        purge_seq=PurgeSeq,
-        id_btree_state=IdBtreeState,
-        view_states=ViewStates
-        });
-init_state(Db, Fd, State, Header) ->
-    #mrst{language=Lang, views=Views} = State,
-    #mrheader{
-        seq=Seq,
-        purge_seq=PurgeSeq,
-        id_btree_state=IdBtreeState,
-        view_states=ViewStates
-    } = Header,
-
-    StateUpdate = fun
-        ({_, _, _}=St) -> St;
-        (St) -> {St, 0, 0}
-    end,
-    ViewStates2 = lists:map(StateUpdate, ViewStates),
-
-    IdBtOpts = [{compression, couch_db:compression(Db)}],
-    {ok, IdBtree} = couch_btree:open(IdBtreeState, Fd, IdBtOpts),
-
-    OpenViewFun = fun(St, View) -> open_view(Db, Fd, Lang, St, View) end,
-    Views2 = lists:zipwith(OpenViewFun, ViewStates2, Views),
-
-    State#mrst{
-        fd=Fd,
-        update_seq=Seq,
-        purge_seq=PurgeSeq,
-        id_btree=IdBtree,
-        views=Views2
-    }.
-
-
-open_view(Db, Fd, Lang, {BTState, USeq, PSeq}, View) ->
-    FunSrcs = [FunSrc || {_Name, FunSrc} <- View#mrview.reduce_funs],
-    ReduceFun =
-        fun(reduce, KVs) ->
-            KVs2 = detuple_kvs(expand_dups(KVs, []), []),
-            {ok, Result} = couch_query_servers:reduce(Lang, FunSrcs, KVs2),
-            {length(KVs2), Result};
-        (rereduce, Reds) ->
-            Count = lists:sum([Count0 || {Count0, _} <- Reds]),
-            UsrReds = [UsrRedsList || {_, UsrRedsList} <- Reds],
-            {ok, Result} = couch_query_servers:rereduce(Lang, FunSrcs, UsrReds),
-            {Count, Result}
-        end,
-
-    Less = case couch_util:get_value(<<"collation">>, View#mrview.options) of
-        <<"raw">> -> fun(A, B) -> A < B end;
-        _ -> fun couch_ejson_compare:less_json_ids/2
-    end,
-
-    ViewBtOpts = [
-        {less, Less},
-        {reduce, ReduceFun},
-        {compression, couch_db:compression(Db)}
-    ],
-    {ok, Btree} = couch_btree:open(BTState, Fd, ViewBtOpts),
-    View#mrview{btree=Btree, update_seq=USeq, purge_seq=PSeq}.
-
-
-temp_view_to_ddoc({Props}) ->
-    Language = couch_util:get_value(<<"language">>, Props, <<"javascript">>),
-    Options = couch_util:get_value(<<"options">>, Props, {[]}),
-    View0 = [{<<"map">>, couch_util:get_value(<<"map">>, Props)}],
-    View1 = View0 ++ case couch_util:get_value(<<"reduce">>, Props) of
-        RedSrc when is_binary(RedSrc) -> [{<<"reduce">>, RedSrc}];
-        _ -> []
-    end,
-    DDoc = {[
-        {<<"_id">>, couch_uuids:random()},
-        {<<"language">>, Language},
-        {<<"options">>, Options},
-        {<<"views">>, {[
-            {<<"temp">>, {View1}}
-        ]}}
-    ]},
-    couch_doc:from_json_obj(DDoc).
-
-
-get_row_count(#mrview{btree=Bt}) ->
-    {ok, {Count, _Reds}} = couch_btree:full_reduce(Bt),
-    {ok, Count}.
-
-
-all_docs_reduce_to_count(Reductions) ->
-    Reduce = fun couch_db_updater:btree_by_id_reduce/2,
-    {Count, _, _} = couch_btree:final_reduce(Reduce, Reductions),
-    Count.
-
-reduce_to_count(nil) ->
-    0;
-reduce_to_count(Reductions) ->
-    Reduce = fun
-        (reduce, KVs) ->
-            Counts = [
-                case V of {dups, Vals} -> length(Vals); _ -> 1 end
-                || {_,V} <- KVs
-            ],
-            {lists:sum(Counts), []};
-        (rereduce, Reds) ->
-            {lists:sum([Count0 || {Count0, _} <- Reds]), []}
-    end,
-    {Count, _} = couch_btree:final_reduce(Reduce, Reductions),
-    Count.
-
-
-fold(#mrview{btree=Bt}, Fun, Acc, Opts) ->
-    WrapperFun = fun(KV, Reds, Acc2) ->
-        fold_fun(Fun, expand_dups([KV], []), Reds, Acc2)
-    end,
-    {ok, _LastRed, _Acc} = couch_btree:fold(Bt, WrapperFun, Acc, Opts).
-
-
-fold_fun(_Fun, [], _, Acc) ->
-    {ok, Acc};
-fold_fun(Fun, [KV|Rest], {KVReds, Reds}, Acc) ->
-    case Fun(KV, {KVReds, Reds}, Acc) of
-        {ok, Acc2} ->
-            fold_fun(Fun, Rest, {[KV|KVReds], Reds}, Acc2);
-        {stop, Acc2} ->
-            {stop, Acc2}
-    end.
-
-
-fold_reduce({NthRed, Lang, View}, Fun,  Acc, Options) ->
-    #mrview{
-        btree=Bt,
-        reduce_funs=RedFuns
-    } = View,
-    LPad = lists:duplicate(NthRed - 1, []),
-    RPad = lists:duplicate(length(RedFuns) - NthRed, []),
-    {_Name, FunSrc} = lists:nth(NthRed,RedFuns),
-
-    ReduceFun = fun
-        (reduce, KVs0) ->
-            KVs1 = detuple_kvs(expand_dups(KVs0, []), []),
-            {ok, Red} = couch_query_servers:reduce(Lang, [FunSrc], KVs1),
-            {0, LPad ++ Red ++ RPad};
-        (rereduce, Reds) ->
-            ExtractRed = fun({_, UReds0}) -> [lists:nth(NthRed, UReds0)] end,
-            UReds = lists:map(ExtractRed, Reds),
-            {ok, Red} = couch_query_servers:rereduce(Lang, [FunSrc], UReds),
-            {0, LPad ++ Red ++ RPad}
-    end,
-
-    WrapperFun = fun({GroupedKey, _}, PartialReds, Acc0) ->
-        {_, Reds} = couch_btree:final_reduce(ReduceFun, PartialReds),
-        Fun(GroupedKey, lists:nth(NthRed, Reds), Acc0)
-    end,
-
-    couch_btree:fold_reduce(Bt, WrapperFun, Acc, Options).
-
-
-validate_args(Args) ->
-    Reduce = Args#mrargs.reduce,
-    case Reduce == undefined orelse is_boolean(Reduce) of
-        true -> ok;
-        _ -> mrverror(<<"Invalid `reduce` value.">>)
-    end,
-
-    case {Args#mrargs.view_type, Reduce} of
-        {map, true} -> mrverror(<<"Reduce is invalid for map-only views.">>);
-        _ -> ok
-    end,
-
-    case {Args#mrargs.view_type, Args#mrargs.group_level, Args#mrargs.keys} of
-        {red, exact, _} -> ok;
-        {red, _, KeyList} when is_list(KeyList) ->
-            Msg = <<"Multi-key fetchs for reduce views must use `group=true`">>,
-            mrverror(Msg);
-        _ -> ok
-    end,
-
-    case Args#mrargs.keys of
-        Keys when is_list(Keys) -> ok;
-        undefined -> ok;
-        _ -> mrverror(<<"`keys` must be an array of strings.">>)
-    end,
-
-    case {Args#mrargs.keys, Args#mrargs.start_key} of
-        {undefined, _} -> ok;
-        {[], _} -> ok;
-        {[_|_], undefined} -> ok;
-        _ -> mrverror(<<"`start_key` is incompatible with `keys`">>)
-    end,
-
-    case Args#mrargs.start_key_docid of
-        undefined -> ok;
-        SKDocId0 when is_binary(SKDocId0) -> ok;
-        _ -> mrverror(<<"`start_key_docid` must be a string.">>)
-    end,
-
-    case {Args#mrargs.keys, Args#mrargs.end_key} of
-        {undefined, _} -> ok;
-        {[], _} -> ok;
-        {[_|_], undefined} -> ok;
-        _ -> mrverror(<<"`end_key` is incompatible with `keys`">>)
-    end,
-
-    case Args#mrargs.end_key_docid of
-        undefined -> ok;
-        EKDocId0 when is_binary(EKDocId0) -> ok;
-        _ -> mrverror(<<"`end_key_docid` must be a string.">>)
-    end,
-
-    case Args#mrargs.direction of
-        fwd -> ok;
-        rev -> ok;
-        _ -> mrverror(<<"Invalid direction.">>)
-    end,
-
-    case {Args#mrargs.limit >= 0, Args#mrargs.limit == undefined} of
-        {true, _} -> ok;
-        {_, true} -> ok;
-        _ -> mrverror(<<"`limit` must be a positive integer.">>)
-    end,
-
-    case Args#mrargs.skip < 0 of
-        true -> mrverror(<<"`skip` must be >= 0">>);
-        _ -> ok
-    end,
-
-    case {Args#mrargs.view_type, Args#mrargs.group_level} of
-        {red, exact} -> ok;
-        {_, 0} -> ok;
-        {red, Int} when is_integer(Int), Int >= 0 -> ok;
-        {red, _} -> mrverror(<<"`group_level` must be >= 0">>);
-        {map, _} -> mrverror(<<"Invalid use of grouping on a map view.">>)
-    end,
-
-    case Args#mrargs.stale of
-        ok -> ok;
-        update_after -> ok;
-        false -> ok;
-        _ -> mrverror(<<"Invalid value for `stale`.">>)
-    end,
-
-    case is_boolean(Args#mrargs.inclusive_end) of
-        true -> ok;
-        _ -> mrverror(<<"Invalid value for `inclusive_end`.">>)
-    end,
-
-    case {Args#mrargs.view_type, Args#mrargs.include_docs} of
-        {red, true} -> mrverror(<<"`include_docs` is invalid for reduce">>);
-        {_, ID} when is_boolean(ID) -> ok;
-        _ -> mrverror(<<"Invalid value for `include_docs`">>)
-    end,
-
-    case {Args#mrargs.view_type, Args#mrargs.conflicts} of
-        {_, undefined} -> ok;
-        {map, V} when is_boolean(V) -> ok;
-        {red, undefined} -> ok;
-        {map, _} -> mrverror(<<"Invalid value for `conflicts`.">>);
-        {red, _} -> mrverror(<<"`conflicts` is invalid for reduce views.">>)
-    end,
-
-    SKDocId = case {Args#mrargs.direction, Args#mrargs.start_key_docid} of
-        {fwd, undefined} -> <<>>;
-        {rev, undefined} -> <<255>>;
-        {_, SKDocId1} -> SKDocId1
-    end,
-
-    EKDocId = case {Args#mrargs.direction, Args#mrargs.end_key_docid} of
-        {fwd, undefined} -> <<255>>;
-        {rev, undefined} -> <<>>;
-        {_, EKDocId1} -> EKDocId1
-    end,
-
-    Args#mrargs{
-        start_key_docid=SKDocId,
-        end_key_docid=EKDocId
-    }.
-
-
-check_range(#mrargs{start_key=undefined}, _Cmp) ->
-    ok;
-check_range(#mrargs{end_key=undefined}, _Cmp) ->
-    ok;
-check_range(#mrargs{start_key=K, end_key=K}, _Cmp) ->
-    ok;
-check_range(Args, Cmp) ->
-    #mrargs{
-        direction=Dir,
-        start_key=SK,
-        start_key_docid=SKD,
-        end_key=EK,
-        end_key_docid=EKD
-    } = Args,
-    case {Dir, Cmp({SK, SKD}, {EK, EKD})} of
-        {fwd, false} ->
-            throw({query_parse_error,
-                <<"No rows can match your key range, reverse your ",
-                    "start_key and end_key or set descending=true">>});
-        {rev, true} ->
-            throw({query_parse_error,
-                <<"No rows can match your key range, reverse your ",
-                    "start_key and end_key or set descending=false">>});
-        _ -> ok
-    end.
-
-
-view_cmp({_Nth, _Lang, View}) ->
-    view_cmp(View);
-view_cmp(View) ->
-    fun(A, B) -> couch_btree:less(View#mrview.btree, A, B) end.
-
-
-make_header(State) ->
-    #mrst{
-        update_seq=Seq,
-        purge_seq=PurgeSeq,
-        id_btree=IdBtree,
-        views=Views
-    } = State,
-    ViewStates = [
-        {
-            couch_btree:get_state(V#mrview.btree),
-            V#mrview.update_seq,
-            V#mrview.purge_seq
-        }
-        ||
-        V <- Views
-    ],
-    #mrheader{
-        seq=Seq,
-        purge_seq=PurgeSeq,
-        id_btree_state=couch_btree:get_state(IdBtree),
-        view_states=ViewStates
-    }.
-
-
-index_file(DbName, Sig) ->
-    FileName = couch_index_util:hexsig(Sig) ++ ".view",
-    couch_index_util:index_file(mrview, DbName, FileName).
-
-
-compaction_file(DbName, Sig) ->
-    FileName = couch_index_util:hexsig(Sig) ++ ".compact.view",
-    couch_index_util:index_file(mrview, DbName, FileName).
-
-
-open_file(FName) ->
-    case couch_file:open(FName, [nologifmissing]) of
-        {ok, Fd} -> {ok, Fd};
-        {error, enoent} -> couch_file:open(FName, [create]);
-        Error -> Error
-    end.
-
-
-delete_files(DbName, Sig) ->
-    delete_index_file(DbName, Sig),
-    delete_compaction_file(DbName, Sig).
-
-
-delete_index_file(DbName, Sig) ->
-    delete_file(index_file(DbName, Sig)).
-
-
-delete_compaction_file(DbName, Sig) ->
-    delete_file(compaction_file(DbName, Sig)).
-
-
-delete_file(FName) ->
-    case filelib:is_file(FName) of
-        true ->
-            RootDir = couch_index_util:root_dir(),
-            couch_file:delete(RootDir, FName);
-        _ ->
-            ok
-    end.
-
-
-reset_index(Db, Fd, #mrst{sig=Sig}=State) ->
-    ok = couch_file:truncate(Fd, 0),
-    ok = couch_file:write_header(Fd, {Sig, nil}),
-    init_state(Db, Fd, reset_state(State), nil).
-
-
-reset_state(State) ->
-    State#mrst{
-        fd=nil,
-        qserver=nil,
-        update_seq=0,
-        id_btree=nil,
-        views=[View#mrview{btree=nil} || View <- State#mrst.views]
-    }.
-
-
-all_docs_key_opts(Args) ->
-    all_docs_key_opts(Args, []).
-
-
-all_docs_key_opts(#mrargs{keys=undefined}=Args, Extra) ->
-    all_docs_key_opts(Args#mrargs{keys=[]}, Extra);
-all_docs_key_opts(#mrargs{keys=[], direction=Dir}=Args, Extra) ->
-    [[{dir, Dir}] ++ ad_skey_opts(Args) ++ ad_ekey_opts(Args) ++ Extra];
-all_docs_key_opts(#mrargs{keys=Keys, direction=Dir}=Args, Extra) ->
-    lists:map(fun(K) ->
-        [{dir, Dir}]
-        ++ ad_skey_opts(Args#mrargs{start_key=K})
-        ++ ad_ekey_opts(Args#mrargs{end_key=K})
-        ++ Extra
-    end, Keys).
-
-
-ad_skey_opts(#mrargs{start_key=SKey}) when is_binary(SKey) ->
-    [{start_key, SKey}];
-ad_skey_opts(#mrargs{start_key_docid=SKeyDocId}) ->
-    [{start_key, SKeyDocId}].
-
-
-ad_ekey_opts(#mrargs{end_key=EKey}=Args) when is_binary(EKey) ->
-    Type = if Args#mrargs.inclusive_end -> end_key; true -> end_key_gt end,
-    [{Type, EKey}];
-ad_ekey_opts(#mrargs{end_key_docid=EKeyDocId}=Args) ->
-    Type = if Args#mrargs.inclusive_end -> end_key; true -> end_key_gt end,
-    [{Type, EKeyDocId}].
-
-
-key_opts(Args) ->
-    key_opts(Args, []).
-
-key_opts(#mrargs{keys=undefined, direction=Dir}=Args, Extra) ->
-    [[{dir, Dir}] ++ skey_opts(Args) ++ ekey_opts(Args) ++ Extra];
-key_opts(#mrargs{keys=Keys, direction=Dir}=Args, Extra) ->
-    lists:map(fun(K) ->
-        [{dir, Dir}]
-        ++ skey_opts(Args#mrargs{start_key=K})
-        ++ ekey_opts(Args#mrargs{end_key=K})
-        ++ Extra
-    end, Keys).
-
-
-skey_opts(#mrargs{start_key=undefined}) ->
-    [];
-skey_opts(#mrargs{start_key=SKey, start_key_docid=SKeyDocId}) ->
-    [{start_key, {SKey, SKeyDocId}}].
-
-
-ekey_opts(#mrargs{end_key=undefined}) ->
-    [];
-ekey_opts(#mrargs{end_key=EKey, end_key_docid=EKeyDocId}=Args) ->
-    case Args#mrargs.inclusive_end of
-        true -> [{end_key, {EKey, EKeyDocId}}];
-        false -> [{end_key_gt, {EKey, reverse_key_default(EKeyDocId)}}]
-    end.
-
-
-reverse_key_default(<<>>) -> <<255>>;
-reverse_key_default(<<255>>) -> <<>>;
-reverse_key_default(Key) -> Key.
-
-
-calculate_data_size(IdBt, Views) ->
-    SumFun = fun(#mrview{btree=Bt}, Acc) ->
-        sum_btree_sizes(Acc, couch_btree:size(Bt))
-    end,
-    Size = lists:foldl(SumFun, couch_btree:size(IdBt), Views),
-    {ok, Size}.
-
-
-sum_btree_sizes(nil, _) ->
-    null;
-sum_btree_sizes(_, nil) ->
-    null;
-sum_btree_sizes(Size1, Size2) ->
-    Size1 + Size2.
-
-
-detuple_kvs([], Acc) ->
-    lists:reverse(Acc);
-detuple_kvs([KV | Rest], Acc) ->
-    {{Key,Id},Value} = KV,
-    NKV = [[Key, Id], Value],
-    detuple_kvs(Rest, [NKV | Acc]).
-
-
-expand_dups([], Acc) ->
-    lists:reverse(Acc);
-expand_dups([{Key, {dups, Vals}} | Rest], Acc) ->
-    Expanded = [{Key, Val} || Val <- Vals],
-    expand_dups(Rest, Expanded ++ Acc);
-expand_dups([KV | Rest], Acc) ->
-    expand_dups(Rest, [KV | Acc]).
-
-
-maybe_load_doc(_Db, _DI, #mrargs{include_docs=false}) ->
-    [];
-maybe_load_doc(Db, #doc_info{}=DI, #mrargs{conflicts=true, doc_options=Opts}) ->
-    doc_row(couch_index_util:load_doc(Db, DI, [conflicts]), Opts);
-maybe_load_doc(Db, #doc_info{}=DI, #mrargs{doc_options=Opts}) ->
-    doc_row(couch_index_util:load_doc(Db, DI, []), Opts).
-
-
-maybe_load_doc(_Db, _Id, _Val, #mrargs{include_docs=false}) ->
-    [];
-maybe_load_doc(Db, Id, Val, #mrargs{conflicts=true, doc_options=Opts}) ->
-    doc_row(couch_index_util:load_doc(Db, docid_rev(Id, Val), [conflicts]), Opts);
-maybe_load_doc(Db, Id, Val, #mrargs{doc_options=Opts}) ->
-    doc_row(couch_index_util:load_doc(Db, docid_rev(Id, Val), []), Opts).
-
-
-doc_row(null, _Opts) ->
-    [{doc, null}];
-doc_row(Doc, Opts) ->
-    [{doc, couch_doc:to_json_obj(Doc, Opts)}].
-
-
-docid_rev(Id, {Props}) ->
-    DocId = couch_util:get_value(<<"_id">>, Props, Id),
-    Rev = case couch_util:get_value(<<"_rev">>, Props, nil) of
-        nil -> nil;
-        Rev0 -> couch_doc:parse_rev(Rev0)
-    end,
-    {DocId, Rev};
-docid_rev(Id, _) ->
-    {Id, nil}.
-
-
-index_of(Key, List) ->
-    index_of(Key, List, 1).
-
-
-index_of(_, [], _) ->
-    throw({error, missing_named_view});
-index_of(Key, [Key | _], Idx) ->
-    Idx;
-index_of(Key, [_ | Rest], Idx) ->
-    index_of(Key, Rest, Idx+1).
-
-
-mrverror(Mesg) ->
-    throw({query_parse_error, Mesg}).
-
-
-%% Updates 1.2.x or earlier view files to 1.3.x or later view files
-%% transparently, the first time the 1.2.x view file is opened by
-%% 1.3.x or later.
-%%
-%% Here's how it works:
-%%
-%% Before opening a view index,
-%% If no matching index file is found in the new location:
-%%  calculate the <= 1.2.x view signature
-%%  if a file with that signature lives in the old location
-%%    rename it to the new location with the new signature in the name.
-%% Then proceed to open the view index as usual.
-%% After opening, read its header.
-%%
-%% If the header matches the <= 1.2.x style #index_header record:
-%%   upgrade the header to the new #mrheader record
-%% The next time the view is used, the new header is used.
-%%
-%% If we crash after the rename, but before the header upgrade,
-%%   the header upgrade is done on the next view opening.
-%%
-%% If we crash between upgrading to the new header and writing
-%%   that header to disk, we start with the old header again,
-%%   do the upgrade and write to disk.
-
-maybe_update_index_file(State) ->
-    DbName = State#mrst.db_name,
-    NewIndexFile = index_file(DbName, State#mrst.sig),
-    % open in read-only mode so we don't create
-    % the file if it doesn't exist.
-    case file:open(NewIndexFile, [read, raw]) of
-    {ok, Fd_Read} ->
-        % the new index file exists, there is nothing to do here.
-        file:close(Fd_Read);
-    _Error ->
-        update_index_file(State)
-    end.
-
-update_index_file(State) ->
-    Sig = sig_vsn_12x(State),
-    DbName = State#mrst.db_name,
-    FileName = couch_index_util:hexsig(Sig) ++ ".view",
-    IndexFile = couch_index_util:index_file("", DbName, FileName),
-
-    % If we have an old index, rename it to the new position.
-    case file:read_file_info(IndexFile) of
-    {ok, _FileInfo} ->
-        % Crash if the rename fails for any reason.
-        % If the target exists, e.g. the next request will find the
-        % new file and we are good. We might need to catch this
-        % further up to avoid a full server crash.
-        ?LOG_INFO("Attempting to update legacy view index file.", []),
-        NewIndexFile = index_file(DbName, State#mrst.sig),
-        ok = filelib:ensure_dir(NewIndexFile),
-        ok = file:rename(IndexFile, NewIndexFile),
-        ?LOG_INFO("Successfully updated legacy view index file.", []),
-        Sig;
-    _ ->
-        % Ignore missing index file
-        ok
-    end.
-
-sig_vsn_12x(State) ->
-    ViewInfo = [old_view_format(V) || V <- State#mrst.views],
-    SigData = case State#mrst.lib of
-    {[]} ->
-        {ViewInfo, State#mrst.language, State#mrst.design_opts};
-    _ ->
-        {ViewInfo, State#mrst.language, State#mrst.design_opts,
-            couch_index_util:sort_lib(State#mrst.lib)}
-    end,
-    couch_util:md5(term_to_binary(SigData)).
-
-old_view_format(View) ->
-{
-    view,
-    View#mrview.id_num,
-    View#mrview.map_names,
-    View#mrview.def,
-    View#mrview.btree,
-    View#mrview.reduce_funs,
-    View#mrview.options
-}.
-
-%% End of <= 1.2.x upgrade code.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_mrview/test/01-load.t
----------------------------------------------------------------------
diff --git a/apps/couch_mrview/test/01-load.t b/apps/couch_mrview/test/01-load.t
deleted file mode 100644
index a57c1a7..0000000
--- a/apps/couch_mrview/test/01-load.t
+++ /dev/null
@@ -1,34 +0,0 @@
-#!/usr/bin/env escript
-%% -*- erlang -*-
-
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
-% Test that we can load each module.
-
-main(_) ->
-    test_util:init_code_path(),
-    Modules = [
-        couch_mrview,
-        couch_mrview_compactor,
-        couch_mrview_http,
-        couch_mrview_index,
-        couch_mrview_updater,
-        couch_mrview_util
-    ],
-
-    etap:plan(length(Modules)),
-    lists:foreach(
-        fun(Module) ->
-            etap:loaded_ok(Module, lists:concat(["Loaded: ", Module]))
-        end, Modules),
-    etap:end_tests().


[38/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_replicator/src/couch_replicator_api_wrap.erl
----------------------------------------------------------------------
diff --git a/apps/couch_replicator/src/couch_replicator_api_wrap.erl b/apps/couch_replicator/src/couch_replicator_api_wrap.erl
deleted file mode 100644
index 311025b..0000000
--- a/apps/couch_replicator/src/couch_replicator_api_wrap.erl
+++ /dev/null
@@ -1,877 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_replicator_api_wrap).
-
-% This module wraps the native erlang API, and allows for performing
-% operations on a remote vs. local databases via the same API.
-%
-% Notes:
-% Many options and apis aren't yet supported here, they are added as needed.
-
--include_lib("couch/include/couch_db.hrl").
--include("couch_replicator_api_wrap.hrl").
-
--export([
-    db_open/2,
-    db_open/3,
-    db_close/1,
-    get_db_info/1,
-    update_doc/3,
-    update_doc/4,
-    update_docs/3,
-    update_docs/4,
-    ensure_full_commit/1,
-    get_missing_revs/2,
-    open_doc/3,
-    open_doc_revs/6,
-    changes_since/5,
-    db_uri/1
-    ]).
-
--import(couch_replicator_httpc, [
-    send_req/3
-    ]).
-
--import(couch_util, [
-    encode_doc_id/1,
-    get_value/2,
-    get_value/3
-    ]).
-
--define(MAX_WAIT, 5 * 60 * 1000).
-
-db_uri(#httpdb{url = Url}) ->
-    couch_util:url_strip_password(Url);
-
-db_uri(#db{name = Name}) ->
-    db_uri(Name);
-
-db_uri(DbName) ->
-    ?b2l(DbName).
-
-
-db_open(Db, Options) ->
-    db_open(Db, Options, false).
-
-db_open(#httpdb{} = Db1, _Options, Create) ->
-    {ok, Db} = couch_replicator_httpc:setup(Db1),
-    case Create of
-    false ->
-        ok;
-    true ->
-        send_req(Db, [{method, put}], fun(_, _, _) -> ok end)
-    end,
-    send_req(Db, [{method, head}],
-        fun(200, _, _) ->
-            {ok, Db};
-        (401, _, _) ->
-            throw({unauthorized, ?l2b(db_uri(Db))});
-        (_, _, _) ->
-            throw({db_not_found, ?l2b(db_uri(Db))})
-        end);
-db_open(DbName, Options, Create) ->
-    try
-        case Create of
-        false ->
-            ok;
-        true ->
-            ok = couch_httpd:verify_is_server_admin(
-                get_value(user_ctx, Options)),
-            couch_db:create(DbName, Options)
-        end,
-        case couch_db:open(DbName, Options) of
-        {error, illegal_database_name, _} ->
-            throw({db_not_found, DbName});
-        {not_found, _Reason} ->
-            throw({db_not_found, DbName});
-        {ok, _Db} = Success ->
-            Success
-        end
-    catch
-    throw:{unauthorized, _} ->
-        throw({unauthorized, DbName})
-    end.
-
-db_close(#httpdb{httpc_pool = Pool}) ->
-    unlink(Pool),
-    ok = couch_replicator_httpc_pool:stop(Pool);
-db_close(DbName) ->
-    catch couch_db:close(DbName).
-
-
-get_db_info(#httpdb{} = Db) ->
-    send_req(Db, [],
-        fun(200, _, {Props}) ->
-            {ok, Props}
-        end);
-get_db_info(#db{name = DbName, user_ctx = UserCtx}) ->
-    {ok, Db} = couch_db:open(DbName, [{user_ctx, UserCtx}]),
-    {ok, Info} = couch_db:get_db_info(Db),
-    couch_db:close(Db),
-    {ok, [{couch_util:to_binary(K), V} || {K, V} <- Info]}.
-
-
-ensure_full_commit(#httpdb{} = Db) ->
-    send_req(
-        Db,
-        [{method, post}, {path, "_ensure_full_commit"},
-            {headers, [{"Content-Type", "application/json"}]}],
-        fun(201, _, {Props}) ->
-            {ok, get_value(<<"instance_start_time">>, Props)};
-        (_, _, {Props}) ->
-            {error, get_value(<<"error">>, Props)}
-        end);
-ensure_full_commit(Db) ->
-    couch_db:ensure_full_commit(Db).
-
-
-get_missing_revs(#httpdb{} = Db, IdRevs) ->
-    JsonBody = {[{Id, couch_doc:revs_to_strs(Revs)} || {Id, Revs} <- IdRevs]},
-    send_req(
-        Db,
-        [{method, post}, {path, "_revs_diff"}, {body, ?JSON_ENCODE(JsonBody)},
-            {headers, [{"Content-Type", "application/json"}]}],
-        fun(200, _, {Props}) ->
-            ConvertToNativeFun = fun({Id, {Result}}) ->
-                MissingRevs = couch_doc:parse_revs(
-                    get_value(<<"missing">>, Result)
-                ),
-                PossibleAncestors = couch_doc:parse_revs(
-                    get_value(<<"possible_ancestors">>, Result, [])
-                ),
-                {Id, MissingRevs, PossibleAncestors}
-            end,
-            {ok, lists:map(ConvertToNativeFun, Props)}
-        end);
-get_missing_revs(Db, IdRevs) ->
-    couch_db:get_missing_revs(Db, IdRevs).
-
-
-
-open_doc_revs(#httpdb{retries = 0} = HttpDb, Id, Revs, Options, _Fun, _Acc) ->
-    Path = encode_doc_id(Id),
-    QS = options_to_query_args(HttpDb, Path, [revs, {open_revs, Revs} | Options]),
-    Url = couch_util:url_strip_password(
-        couch_replicator_httpc:full_url(HttpDb, [{path,Path}, {qs,QS}])
-    ),
-    ?LOG_ERROR("Replication crashing because GET ~s failed", [Url]),
-    exit(kaboom);
-open_doc_revs(#httpdb{} = HttpDb, Id, Revs, Options, Fun, Acc) ->
-    Path = encode_doc_id(Id),
-    QS = options_to_query_args(HttpDb, Path, [revs, {open_revs, Revs} | Options]),
-    {Pid, Ref} = spawn_monitor(fun() ->
-        Self = self(),
-        Callback = fun(200, Headers, StreamDataFun) ->
-            remote_open_doc_revs_streamer_start(Self),
-            {<<"--">>, _, _} = couch_httpd:parse_multipart_request(
-                get_value("Content-Type", Headers),
-                StreamDataFun,
-                fun mp_parse_mixed/1
-            )
-        end,
-        Streamer = spawn_link(fun() ->
-            Params = [
-                {path, Path},
-                {qs, QS},
-                {ibrowse_options, [{stream_to, {self(), once}}]},
-                {headers, [{"Accept", "multipart/mixed"}]}
-            ],
-            % We're setting retries to 0 here to avoid the case where the
-            % Streamer retries the request and ends up jumbling together two
-            % different response bodies.  Retries are handled explicitly by
-            % open_doc_revs itself.
-            send_req(HttpDb#httpdb{retries = 0}, Params, Callback)
-        end),
-        % If this process dies normally we can leave
-        % the Streamer process hanging around keeping an
-        % HTTP connection open. This is a bit of a
-        % hammer approach to making sure it releases
-        % that connection back to the pool.
-        spawn(fun() ->
-            Ref = erlang:monitor(process, Self),
-            receive
-                {'DOWN', Ref, process, Self, normal} ->
-                    exit(Streamer, {streamer_parent_died, Self});
-                {'DOWN', Ref, process, Self, _} ->
-                    ok
-                end
-        end),
-        receive
-        {started_open_doc_revs, Ref} ->
-            Ret = receive_docs_loop(Streamer, Fun, Id, Revs, Ref, Acc),
-            exit({exit_ok, Ret})
-        end
-    end),
-    receive
-        {'DOWN', Ref, process, Pid, {exit_ok, Ret}} ->
-            Ret;
-        {'DOWN', Ref, process, Pid, {{nocatch, {missing_stub,_} = Stub}, _}} ->
-            throw(Stub);
-        {'DOWN', Ref, process, Pid, Else} ->
-            Url = couch_util:url_strip_password(
-                couch_replicator_httpc:full_url(HttpDb, [{path,Path}, {qs,QS}])
-            ),
-            #httpdb{retries = Retries, wait = Wait0} = HttpDb,
-            Wait = 2 * erlang:min(Wait0 * 2, ?MAX_WAIT),
-            ?LOG_INFO("Retrying GET to ~s in ~p seconds due to error ~p",
-                [Url, Wait / 1000, error_reason(Else)]
-            ),
-            ok = timer:sleep(Wait),
-            RetryDb = HttpDb#httpdb{
-                retries = Retries - 1,
-                wait = Wait
-            },
-            open_doc_revs(RetryDb, Id, Revs, Options, Fun, Acc)
-    end;
-open_doc_revs(Db, Id, Revs, Options, Fun, Acc) ->
-    {ok, Results} = couch_db:open_doc_revs(Db, Id, Revs, Options),
-    {ok, lists:foldl(fun(R, A) -> {_, A2} = Fun(R, A), A2 end, Acc, Results)}.
-
-error_reason({http_request_failed, "GET", _Url, {error, timeout}}) ->
-    timeout;
-error_reason({http_request_failed, "GET", _Url, {error, {_, req_timedout}}}) ->
-    req_timedout;
-error_reason({http_request_failed, "GET", _Url, Error}) ->
-    Error;
-error_reason(Else) ->
-    Else.
-
-open_doc(#httpdb{} = Db, Id, Options) ->
-    send_req(
-        Db,
-        [{path, encode_doc_id(Id)}, {qs, options_to_query_args(Options, [])}],
-        fun(200, _, Body) ->
-            {ok, couch_doc:from_json_obj(Body)};
-        (_, _, {Props}) ->
-            {error, get_value(<<"error">>, Props)}
-        end);
-open_doc(Db, Id, Options) ->
-    case couch_db:open_doc(Db, Id, Options) of
-    {ok, _} = Ok ->
-        Ok;
-    {not_found, _Reason} ->
-        {error, <<"not_found">>}
-    end.
-
-
-update_doc(Db, Doc, Options) ->
-    update_doc(Db, Doc, Options, interactive_edit).
-
-update_doc(#httpdb{} = HttpDb, #doc{id = DocId} = Doc, Options, Type) ->
-    QArgs = case Type of
-    replicated_changes ->
-        [{"new_edits", "false"}];
-    _ ->
-        []
-    end ++ options_to_query_args(Options, []),
-    Boundary = couch_uuids:random(),
-    JsonBytes = ?JSON_ENCODE(
-        couch_doc:to_json_obj(
-          Doc, [revs, attachments, follows, att_encoding_info | Options])),
-    {ContentType, Len} = couch_doc:len_doc_to_multi_part_stream(Boundary,
-        JsonBytes, Doc#doc.atts, true),
-    Headers = case lists:member(delay_commit, Options) of
-    true ->
-        [{"X-Couch-Full-Commit", "false"}];
-    false ->
-        []
-    end ++ [{"Content-Type", ?b2l(ContentType)}, {"Content-Length", Len}],
-    Body = {fun stream_doc/1, {JsonBytes, Doc#doc.atts, Boundary, Len}},
-    send_req(
-        % A crash here bubbles all the way back up to run_user_fun inside
-        % open_doc_revs, which will retry the whole thing.  That's the
-        % appropriate course of action, since we've already started streaming
-        % the response body from the GET request.
-        HttpDb#httpdb{retries = 0},
-        [{method, put}, {path, encode_doc_id(DocId)},
-            {qs, QArgs}, {headers, Headers}, {body, Body}],
-        fun(Code, _, {Props}) when Code =:= 200 orelse Code =:= 201 ->
-                {ok, couch_doc:parse_rev(get_value(<<"rev">>, Props))};
-            (409, _, _) ->
-                throw(conflict);
-            (Code, _, {Props}) ->
-                case {Code, get_value(<<"error">>, Props)} of
-                {401, <<"unauthorized">>} ->
-                    throw({unauthorized, get_value(<<"reason">>, Props)});
-                {403, <<"forbidden">>} ->
-                    throw({forbidden, get_value(<<"reason">>, Props)});
-                {412, <<"missing_stub">>} ->
-                    throw({missing_stub, get_value(<<"reason">>, Props)});
-                {_, Error} ->
-                    {error, Error}
-                end
-        end);
-update_doc(Db, Doc, Options, Type) ->
-    couch_db:update_doc(Db, Doc, Options, Type).
-
-
-update_docs(Db, DocList, Options) ->
-    update_docs(Db, DocList, Options, interactive_edit).
-
-update_docs(_Db, [], _Options, _UpdateType) ->
-    {ok, []};
-update_docs(#httpdb{} = HttpDb, DocList, Options, UpdateType) ->
-    FullCommit = atom_to_list(not lists:member(delay_commit, Options)),
-    Prefix = case UpdateType of
-    replicated_changes ->
-        <<"{\"new_edits\":false,\"docs\":[">>;
-    interactive_edit ->
-        <<"{\"docs\":[">>
-    end,
-    Suffix = <<"]}">>,
-    % Note: nginx and other servers don't like PUT/POST requests without
-    % a Content-Length header, so we can't do a chunked transfer encoding
-    % and JSON encode each doc only before sending it through the socket.
-    {Docs, Len} = lists:mapfoldl(
-        fun(#doc{} = Doc, Acc) ->
-            Json = ?JSON_ENCODE(couch_doc:to_json_obj(Doc, [revs, attachments])),
-            {Json, Acc + iolist_size(Json)};
-        (Doc, Acc) ->
-            {Doc, Acc + iolist_size(Doc)}
-        end,
-        byte_size(Prefix) + byte_size(Suffix) + length(DocList) - 1,
-        DocList),
-    BodyFun = fun(eof) ->
-            eof;
-        ([]) ->
-            {ok, Suffix, eof};
-        ([prefix | Rest]) ->
-            {ok, Prefix, Rest};
-        ([Doc]) ->
-            {ok, Doc, []};
-        ([Doc | RestDocs]) ->
-            {ok, [Doc, ","], RestDocs}
-    end,
-    Headers = [
-        {"Content-Length", Len},
-        {"Content-Type", "application/json"},
-        {"X-Couch-Full-Commit", FullCommit}
-    ],
-    send_req(
-        HttpDb,
-        [{method, post}, {path, "_bulk_docs"},
-            {body, {BodyFun, [prefix | Docs]}}, {headers, Headers}],
-        fun(201, _, Results) when is_list(Results) ->
-                {ok, bulk_results_to_errors(DocList, Results, remote)};
-           (417, _, Results) when is_list(Results) ->
-                {ok, bulk_results_to_errors(DocList, Results, remote)}
-        end);
-update_docs(Db, DocList, Options, UpdateType) ->
-    Result = couch_db:update_docs(Db, DocList, Options, UpdateType),
-    {ok, bulk_results_to_errors(DocList, Result, UpdateType)}.
-
-
-changes_since(#httpdb{headers = Headers1} = HttpDb, Style, StartSeq,
-    UserFun, Options) ->
-    HeartBeat = erlang:max(1000, HttpDb#httpdb.timeout div 3),
-    BaseQArgs = case get_value(continuous, Options, false) of
-    false ->
-        [{"feed", "normal"}];
-    true ->
-        [{"feed", "continuous"}]
-    end ++ [
-        {"style", atom_to_list(Style)}, {"since", ?JSON_ENCODE(StartSeq)},
-        {"heartbeat", integer_to_list(HeartBeat)}
-    ],
-    DocIds = get_value(doc_ids, Options),
-    {QArgs, Method, Body, Headers} = case DocIds of
-    undefined ->
-        QArgs1 = maybe_add_changes_filter_q_args(BaseQArgs, Options),
-        {QArgs1, get, [], Headers1};
-    _ when is_list(DocIds) ->
-        Headers2 = [{"Content-Type", "application/json"} | Headers1],
-        JsonDocIds = ?JSON_ENCODE({[{<<"doc_ids">>, DocIds}]}),
-        {[{"filter", "_doc_ids"} | BaseQArgs], post, JsonDocIds, Headers2}
-    end,
-    send_req(
-        HttpDb,
-        [{method, Method}, {path, "_changes"}, {qs, QArgs},
-            {headers, Headers}, {body, Body},
-            {ibrowse_options, [{stream_to, {self(), once}}]}],
-        fun(200, _, DataStreamFun) ->
-                parse_changes_feed(Options, UserFun, DataStreamFun);
-            (405, _, _) when is_list(DocIds) ->
-                % CouchDB versions < 1.1.0 don't have the builtin _changes feed
-                % filter "_doc_ids" neither support POST
-                send_req(HttpDb, [{method, get}, {path, "_changes"},
-                    {qs, BaseQArgs}, {headers, Headers1},
-                    {ibrowse_options, [{stream_to, {self(), once}}]}],
-                    fun(200, _, DataStreamFun2) ->
-                        UserFun2 = fun(#doc_info{id = Id} = DocInfo) ->
-                            case lists:member(Id, DocIds) of
-                            true ->
-                                UserFun(DocInfo);
-                            false ->
-                                ok
-                            end
-                        end,
-                        parse_changes_feed(Options, UserFun2, DataStreamFun2)
-                    end)
-        end);
-changes_since(Db, Style, StartSeq, UserFun, Options) ->
-    Filter = case get_value(doc_ids, Options) of
-    undefined ->
-        ?b2l(get_value(filter, Options, <<>>));
-    _DocIds ->
-        "_doc_ids"
-    end,
-    Args = #changes_args{
-        style = Style,
-        since = StartSeq,
-        filter = Filter,
-        feed = case get_value(continuous, Options, false) of
-            true ->
-                "continuous";
-            false ->
-                "normal"
-        end,
-        timeout = infinity
-    },
-    QueryParams = get_value(query_params, Options, {[]}),
-    Req = changes_json_req(Db, Filter, QueryParams, Options),
-    ChangesFeedFun = couch_changes:handle_changes(Args, {json_req, Req}, Db),
-    ChangesFeedFun(fun({change, Change, _}, _) ->
-            UserFun(json_to_doc_info(Change));
-        (_, _) ->
-            ok
-    end).
-
-
-% internal functions
-
-maybe_add_changes_filter_q_args(BaseQS, Options) ->
-    case get_value(filter, Options) of
-    undefined ->
-        BaseQS;
-    FilterName ->
-        {Params} = get_value(query_params, Options, {[]}),
-        [{"filter", ?b2l(FilterName)} | lists:foldl(
-            fun({K, V}, QSAcc) ->
-                Ks = couch_util:to_list(K),
-                case lists:keymember(Ks, 1, QSAcc) of
-                true ->
-                    QSAcc;
-                false ->
-                    [{Ks, couch_util:to_list(V)} | QSAcc]
-                end
-            end,
-            BaseQS, Params)]
-    end.
-
-parse_changes_feed(Options, UserFun, DataStreamFun) ->
-    case get_value(continuous, Options, false) of
-    true ->
-        continuous_changes(DataStreamFun, UserFun);
-    false ->
-        EventFun = fun(Ev) ->
-            changes_ev1(Ev, fun(DocInfo, _) -> UserFun(DocInfo) end, [])
-        end,
-        json_stream_parse:events(DataStreamFun, EventFun)
-    end.
-
-changes_json_req(_Db, "", _QueryParams, _Options) ->
-    {[]};
-changes_json_req(_Db, "_doc_ids", _QueryParams, Options) ->
-    {[{<<"doc_ids">>, get_value(doc_ids, Options)}]};
-changes_json_req(Db, FilterName, {QueryParams}, _Options) ->
-    {ok, Info} = couch_db:get_db_info(Db),
-    % simulate a request to db_name/_changes
-    {[
-        {<<"info">>, {Info}},
-        {<<"id">>, null},
-        {<<"method">>, 'GET'},
-        {<<"path">>, [couch_db:name(Db), <<"_changes">>]},
-        {<<"query">>, {[{<<"filter">>, FilterName} | QueryParams]}},
-        {<<"headers">>, []},
-        {<<"body">>, []},
-        {<<"peer">>, <<"replicator">>},
-        {<<"form">>, []},
-        {<<"cookie">>, []},
-        {<<"userCtx">>, couch_util:json_user_ctx(Db)}
-    ]}.
-
-
-options_to_query_args(HttpDb, Path, Options) ->
-    case lists:keytake(atts_since, 1, Options) of
-    false ->
-        options_to_query_args(Options, []);
-    {value, {atts_since, []}, Options2} ->
-        options_to_query_args(Options2, []);
-    {value, {atts_since, PAs}, Options2} ->
-        QueryArgs1 = options_to_query_args(Options2, []),
-        FullUrl = couch_replicator_httpc:full_url(
-            HttpDb, [{path, Path}, {qs, QueryArgs1}]),
-        RevList = atts_since_arg(
-            length("GET " ++ FullUrl ++ " HTTP/1.1\r\n") +
-            length("&atts_since=") + 6,  % +6 = % encoded [ and ]
-            PAs, []),
-        [{"atts_since", ?JSON_ENCODE(RevList)} | QueryArgs1]
-    end.
-
-
-options_to_query_args([], Acc) ->
-    lists:reverse(Acc);
-options_to_query_args([ejson_body | Rest], Acc) ->
-    options_to_query_args(Rest, Acc);
-options_to_query_args([delay_commit | Rest], Acc) ->
-    options_to_query_args(Rest, Acc);
-options_to_query_args([revs | Rest], Acc) ->
-    options_to_query_args(Rest, [{"revs", "true"} | Acc]);
-options_to_query_args([{open_revs, all} | Rest], Acc) ->
-    options_to_query_args(Rest, [{"open_revs", "all"} | Acc]);
-options_to_query_args([latest | Rest], Acc) ->
-    options_to_query_args(Rest, [{"latest", "true"} | Acc]);
-options_to_query_args([{open_revs, Revs} | Rest], Acc) ->
-    JsonRevs = ?b2l(?JSON_ENCODE(couch_doc:revs_to_strs(Revs))),
-    options_to_query_args(Rest, [{"open_revs", JsonRevs} | Acc]).
-
-
--define(MAX_URL_LEN, 7000).
-
-atts_since_arg(_UrlLen, [], Acc) ->
-    lists:reverse(Acc);
-atts_since_arg(UrlLen, [PA | Rest], Acc) ->
-    RevStr = couch_doc:rev_to_str(PA),
-    NewUrlLen = case Rest of
-    [] ->
-        % plus 2 double quotes (% encoded)
-        UrlLen + size(RevStr) + 6;
-    _ ->
-        % plus 2 double quotes and a comma (% encoded)
-        UrlLen + size(RevStr) + 9
-    end,
-    case NewUrlLen >= ?MAX_URL_LEN of
-    true ->
-        lists:reverse(Acc);
-    false ->
-        atts_since_arg(NewUrlLen, Rest, [RevStr | Acc])
-    end.
-
-
-% TODO: A less verbose, more elegant and automatic restart strategy for
-%       the exported open_doc_revs/6 function. The restart should be
-%       transparent to the caller like any other Couch API function exported
-%       by this module.
-receive_docs_loop(Streamer, Fun, Id, Revs, Ref, Acc) ->
-    try
-        % Left only for debugging purposes via an interactive or remote shell
-        erlang:put(open_doc_revs, {Id, Revs, Ref, Streamer}),
-        receive_docs(Streamer, Fun, Ref, Acc)
-    catch
-    error:{restart_open_doc_revs, NewRef} ->
-        receive_docs_loop(Streamer, Fun, Id, Revs, NewRef, Acc)
-    end.
-
-receive_docs(Streamer, UserFun, Ref, UserAcc) ->
-    Streamer ! {get_headers, Ref, self()},
-    receive
-    {started_open_doc_revs, NewRef} ->
-        restart_remote_open_doc_revs(Ref, NewRef);
-    {headers, Ref, Headers} ->
-        case get_value("content-type", Headers) of
-        {"multipart/related", _} = ContentType ->
-            case doc_from_multi_part_stream(
-                ContentType,
-                fun() -> receive_doc_data(Streamer, Ref) end,
-                Ref) of
-            {ok, Doc, Parser} ->
-                case run_user_fun(UserFun, {ok, Doc}, UserAcc, Ref) of
-                {ok, UserAcc2} ->
-                    ok;
-                {skip, UserAcc2} ->
-                    couch_doc:abort_multi_part_stream(Parser)
-                end,
-                receive_docs(Streamer, UserFun, Ref, UserAcc2)
-            end;
-        {"application/json", []} ->
-            Doc = couch_doc:from_json_obj(
-                    ?JSON_DECODE(receive_all(Streamer, Ref, []))),
-            {_, UserAcc2} = run_user_fun(UserFun, {ok, Doc}, UserAcc, Ref),
-            receive_docs(Streamer, UserFun, Ref, UserAcc2);
-        {"application/json", [{"error","true"}]} ->
-            {ErrorProps} = ?JSON_DECODE(receive_all(Streamer, Ref, [])),
-            Rev = get_value(<<"missing">>, ErrorProps),
-            Result = {{not_found, missing}, couch_doc:parse_rev(Rev)},
-            {_, UserAcc2} = run_user_fun(UserFun, Result, UserAcc, Ref),
-            receive_docs(Streamer, UserFun, Ref, UserAcc2)
-        end;
-    {done, Ref} ->
-        {ok, UserAcc}
-    end.
-
-
-run_user_fun(UserFun, Arg, UserAcc, OldRef) ->
-    {Pid, Ref} = spawn_monitor(fun() ->
-        try UserFun(Arg, UserAcc) of
-            Resp ->
-                exit({exit_ok, Resp})
-        catch
-            throw:Reason ->
-                exit({exit_throw, Reason});
-            error:Reason ->
-                exit({exit_error, Reason});
-            exit:Reason ->
-                exit({exit_exit, Reason})
-        end
-    end),
-    receive
-        {started_open_doc_revs, NewRef} ->
-            erlang:demonitor(Ref, [flush]),
-            exit(Pid, kill),
-            restart_remote_open_doc_revs(OldRef, NewRef);
-        {'DOWN', Ref, process, Pid, {exit_ok, Ret}} ->
-            Ret;
-        {'DOWN', Ref, process, Pid, {exit_throw, Reason}} ->
-            throw(Reason);
-        {'DOWN', Ref, process, Pid, {exit_error, Reason}} ->
-            erlang:error(Reason);
-        {'DOWN', Ref, process, Pid, {exit_exit, Reason}} ->
-            erlang:exit(Reason)
-    end.
-
-
-restart_remote_open_doc_revs(Ref, NewRef) ->
-    receive
-    {body_bytes, Ref, _} ->
-        restart_remote_open_doc_revs(Ref, NewRef);
-    {body_done, Ref} ->
-        restart_remote_open_doc_revs(Ref, NewRef);
-    {done, Ref} ->
-        restart_remote_open_doc_revs(Ref, NewRef);
-    {headers, Ref, _} ->
-        restart_remote_open_doc_revs(Ref, NewRef)
-    after 0 ->
-        erlang:error({restart_open_doc_revs, NewRef})
-    end.
-
-
-remote_open_doc_revs_streamer_start(Parent) ->
-    receive
-    {get_headers, _Ref, Parent} ->
-        remote_open_doc_revs_streamer_start(Parent);
-    {next_bytes, _Ref, Parent} ->
-        remote_open_doc_revs_streamer_start(Parent)
-    after 0 ->
-        Parent ! {started_open_doc_revs, make_ref()}
-    end.
-
-
-receive_all(Streamer, Ref, Acc) ->
-    Streamer ! {next_bytes, Ref, self()},
-    receive
-    {started_open_doc_revs, NewRef} ->
-        restart_remote_open_doc_revs(Ref, NewRef);
-    {body_bytes, Ref, Bytes} ->
-        receive_all(Streamer, Ref, [Bytes | Acc]);
-    {body_done, Ref} ->
-        lists:reverse(Acc)
-    end.
-
-
-mp_parse_mixed(eof) ->
-    receive {get_headers, Ref, From} ->
-        From ! {done, Ref}
-    end;
-mp_parse_mixed({headers, H}) ->
-    receive {get_headers, Ref, From} ->
-        From ! {headers, Ref, H}
-    end,
-    fun mp_parse_mixed/1;
-mp_parse_mixed({body, Bytes}) ->
-    receive {next_bytes, Ref, From} ->
-        From ! {body_bytes, Ref, Bytes}
-    end,
-    fun mp_parse_mixed/1;
-mp_parse_mixed(body_end) ->
-    receive {next_bytes, Ref, From} ->
-        From ! {body_done, Ref};
-    {get_headers, Ref, From} ->
-        self() ! {get_headers, Ref, From}
-    end,
-    fun mp_parse_mixed/1.
-
-
-receive_doc_data(Streamer, Ref) ->
-    Streamer ! {next_bytes, Ref, self()},
-    receive
-    {body_bytes, Ref, Bytes} ->
-        {Bytes, fun() -> receive_doc_data(Streamer, Ref) end};
-    {body_done, Ref} ->
-        {<<>>, fun() -> receive_doc_data(Streamer, Ref) end}
-    end.
-
-doc_from_multi_part_stream(ContentType, DataFun, Ref) ->
-    Self = self(),
-    Parser = spawn_link(fun() ->
-        {<<"--">>, _, _} = couch_httpd:parse_multipart_request(
-            ContentType, DataFun,
-            fun(Next) -> couch_doc:mp_parse_doc(Next, []) end),
-        unlink(Self)
-        end),
-    Parser ! {get_doc_bytes, Ref, self()},
-    receive
-    {started_open_doc_revs, NewRef} ->
-        unlink(Parser),
-        exit(Parser, kill),
-        restart_remote_open_doc_revs(Ref, NewRef);
-    {doc_bytes, Ref, DocBytes} ->
-        Doc = couch_doc:from_json_obj(?JSON_DECODE(DocBytes)),
-        ReadAttachmentDataFun = fun() ->
-            link(Parser),
-            Parser ! {get_bytes, Ref, self()},
-            receive
-            {started_open_doc_revs, NewRef} ->
-                unlink(Parser),
-                exit(Parser, kill),
-                receive {bytes, Ref, _} -> ok after 0 -> ok end,
-                restart_remote_open_doc_revs(Ref, NewRef);
-            {bytes, Ref, Bytes} ->
-                Bytes
-            end
-        end,
-        Atts2 = lists:map(
-            fun(#att{data = follows} = A) ->
-                A#att{data = ReadAttachmentDataFun};
-            (A) ->
-                A
-            end, Doc#doc.atts),
-        {ok, Doc#doc{atts = Atts2}, Parser}
-    end.
-
-
-changes_ev1(object_start, UserFun, UserAcc) ->
-    fun(Ev) -> changes_ev2(Ev, UserFun, UserAcc) end.
-
-changes_ev2({key, <<"results">>}, UserFun, UserAcc) ->
-    fun(Ev) -> changes_ev3(Ev, UserFun, UserAcc) end;
-changes_ev2(_, UserFun, UserAcc) ->
-    fun(Ev) -> changes_ev2(Ev, UserFun, UserAcc) end.
-
-changes_ev3(array_start, UserFun, UserAcc) ->
-    fun(Ev) -> changes_ev_loop(Ev, UserFun, UserAcc) end.
-
-changes_ev_loop(object_start, UserFun, UserAcc) ->
-    fun(Ev) ->
-        json_stream_parse:collect_object(Ev,
-            fun(Obj) ->
-                UserAcc2 = UserFun(json_to_doc_info(Obj), UserAcc),
-                fun(Ev2) -> changes_ev_loop(Ev2, UserFun, UserAcc2) end
-            end)
-    end;
-changes_ev_loop(array_end, _UserFun, _UserAcc) ->
-    fun(_Ev) -> changes_ev_done() end.
-
-changes_ev_done() ->
-    fun(_Ev) -> changes_ev_done() end.
-
-continuous_changes(DataFun, UserFun) ->
-    {DataFun2, _, Rest} = json_stream_parse:events(
-        DataFun,
-        fun(Ev) -> parse_changes_line(Ev, UserFun) end),
-    continuous_changes(fun() -> {Rest, DataFun2} end, UserFun).
-
-parse_changes_line(object_start, UserFun) ->
-    fun(Ev) ->
-        json_stream_parse:collect_object(Ev,
-            fun(Obj) -> UserFun(json_to_doc_info(Obj)) end)
-    end.
-
-json_to_doc_info({Props}) ->
-    RevsInfo = lists:map(
-        fun({Change}) ->
-            Rev = couch_doc:parse_rev(get_value(<<"rev">>, Change)),
-            Del = (true =:= get_value(<<"deleted">>, Change)),
-            #rev_info{rev=Rev, deleted=Del}
-        end, get_value(<<"changes">>, Props)),
-    #doc_info{
-        id = get_value(<<"id">>, Props),
-        high_seq = get_value(<<"seq">>, Props),
-        revs = RevsInfo
-    }.
-
-
-bulk_results_to_errors(Docs, {ok, Results}, interactive_edit) ->
-    lists:reverse(lists:foldl(
-        fun({_, {ok, _}}, Acc) ->
-            Acc;
-        ({#doc{id = Id, revs = {Pos, [RevId | _]}}, Error}, Acc) ->
-            {_, Error, Reason} = couch_httpd:error_info(Error),
-            [ {[{id, Id}, {rev, rev_to_str({Pos, RevId})},
-                {error, Error}, {reason, Reason}]} | Acc ]
-        end,
-        [], lists:zip(Docs, Results)));
-
-bulk_results_to_errors(Docs, {ok, Results}, replicated_changes) ->
-    bulk_results_to_errors(Docs, {aborted, Results}, interactive_edit);
-
-bulk_results_to_errors(_Docs, {aborted, Results}, interactive_edit) ->
-    lists:map(
-        fun({{Id, Rev}, Err}) ->
-            {_, Error, Reason} = couch_httpd:error_info(Err),
-            {[{id, Id}, {rev, rev_to_str(Rev)}, {error, Error}, {reason, Reason}]}
-        end,
-        Results);
-
-bulk_results_to_errors(_Docs, Results, remote) ->
-    lists:reverse(lists:foldl(
-        fun({Props}, Acc) ->
-            case get_value(<<"error">>, Props, get_value(error, Props)) of
-            undefined ->
-                Acc;
-            Error ->
-                Id = get_value(<<"id">>, Props, get_value(id, Props)),
-                Rev = get_value(<<"rev">>, Props, get_value(rev, Props)),
-                Reason = get_value(<<"reason">>, Props, get_value(reason, Props)),
-                [ {[{id, Id}, {rev, rev_to_str(Rev)},
-                    {error, Error}, {reason, Reason}]} | Acc ]
-            end
-        end,
-        [], Results)).
-
-
-rev_to_str({_Pos, _Id} = Rev) ->
-    couch_doc:rev_to_str(Rev);
-rev_to_str(Rev) ->
-    Rev.
-
-write_fun() ->
-    fun(Data) ->
-        receive {get_data, Ref, From} ->
-            From ! {data, Ref, Data}
-        end
-    end.
-
-stream_doc({JsonBytes, Atts, Boundary, Len}) ->
-    case erlang:erase({doc_streamer, Boundary}) of
-    Pid when is_pid(Pid) ->
-        unlink(Pid),
-        exit(Pid, kill);
-    _ ->
-        ok
-    end,
-    DocStreamer = spawn_link(
-        couch_doc,
-        doc_to_multi_part_stream,
-        [Boundary, JsonBytes, Atts, write_fun(), true]
-    ),
-    erlang:put({doc_streamer, Boundary}, DocStreamer),
-    {ok, <<>>, {Len, Boundary}};
-stream_doc({0, Id}) ->
-    erlang:erase({doc_streamer, Id}),
-    eof;
-stream_doc({LenLeft, Id}) when LenLeft > 0 ->
-    Ref = make_ref(),
-    erlang:get({doc_streamer, Id}) ! {get_data, Ref, self()},
-    receive {data, Ref, Data} ->
-        {ok, Data, {LenLeft - iolist_size(Data), Id}}
-    end.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_replicator/src/couch_replicator_api_wrap.hrl
----------------------------------------------------------------------
diff --git a/apps/couch_replicator/src/couch_replicator_api_wrap.hrl b/apps/couch_replicator/src/couch_replicator_api_wrap.hrl
deleted file mode 100644
index 1a6f27a..0000000
--- a/apps/couch_replicator/src/couch_replicator_api_wrap.hrl
+++ /dev/null
@@ -1,36 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
-
-
--record(httpdb, {
-    url,
-    oauth = nil,
-    headers = [
-        {"Accept", "application/json"},
-        {"User-Agent", "CouchDB/" ++ couch_server:get_version()}
-    ],
-    timeout,            % milliseconds
-    ibrowse_options = [],
-    retries = 10,
-    wait = 250,         % milliseconds
-    httpc_pool = nil,
-    http_connections
-}).
-
--record(oauth, {
-    consumer_key,
-    token,
-    token_secret,
-    consumer_secret,
-    signature_method
-}).

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_replicator/src/couch_replicator_app.erl
----------------------------------------------------------------------
diff --git a/apps/couch_replicator/src/couch_replicator_app.erl b/apps/couch_replicator/src/couch_replicator_app.erl
deleted file mode 100644
index 4083db6..0000000
--- a/apps/couch_replicator/src/couch_replicator_app.erl
+++ /dev/null
@@ -1,29 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_replicator_app).
-
--behaviour(application).
-
-%% Application callbacks
--export([start/2, stop/1]).
-
-%% ===================================================================
-%% Application callbacks
-%% ===================================================================
-
-start(_StartType, _StartArgs) ->
-    couch_util:start_app_deps(couch_replicator),
-    couch_replicator_sup:start_link().
-
-stop(_State) ->
-    ok.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_replicator/src/couch_replicator_httpc.erl
----------------------------------------------------------------------
diff --git a/apps/couch_replicator/src/couch_replicator_httpc.erl b/apps/couch_replicator/src/couch_replicator_httpc.erl
deleted file mode 100644
index c13bf18..0000000
--- a/apps/couch_replicator/src/couch_replicator_httpc.erl
+++ /dev/null
@@ -1,297 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_replicator_httpc).
-
--include_lib("couch/include/couch_db.hrl").
--include("couch_replicator_api_wrap.hrl").
--include_lib("ibrowse/include/ibrowse.hrl").
-
--export([setup/1]).
--export([send_req/3]).
--export([full_url/2]).
-
--import(couch_util, [
-    get_value/2,
-    get_value/3
-]).
-
--define(replace(L, K, V), lists:keystore(K, 1, L, {K, V})).
--define(MAX_WAIT, 5 * 60 * 1000).
-
-
-setup(#httpdb{httpc_pool = nil, url = Url, http_connections = MaxConns} = Db) ->
-    {ok, Pid} = couch_replicator_httpc_pool:start_link(Url, [{max_connections, MaxConns}]),
-    {ok, Db#httpdb{httpc_pool = Pid}}.
-
-
-send_req(HttpDb, Params1, Callback) ->
-    Params2 = ?replace(Params1, qs,
-        [{K, ?b2l(iolist_to_binary(V))} || {K, V} <- get_value(qs, Params1, [])]),
-    Params = ?replace(Params2, ibrowse_options,
-        lists:keysort(1, get_value(ibrowse_options, Params2, []))),
-    {Worker, Response} = send_ibrowse_req(HttpDb, Params),
-    process_response(Response, Worker, HttpDb, Params, Callback).
-
-
-send_ibrowse_req(#httpdb{headers = BaseHeaders} = HttpDb, Params) ->
-    Method = get_value(method, Params, get),
-    UserHeaders = lists:keysort(1, get_value(headers, Params, [])),
-    Headers1 = lists:ukeymerge(1, UserHeaders, BaseHeaders),
-    Headers2 = oauth_header(HttpDb, Params) ++ Headers1,
-    Url = full_url(HttpDb, Params),
-    Body = get_value(body, Params, []),
-    case get_value(path, Params) of
-    "_changes" ->
-        {ok, Worker} = ibrowse:spawn_link_worker_process(Url);
-    _ ->
-        {ok, Worker} = couch_replicator_httpc_pool:get_worker(HttpDb#httpdb.httpc_pool)
-    end,
-    IbrowseOptions = [
-        {response_format, binary}, {inactivity_timeout, HttpDb#httpdb.timeout} |
-        lists:ukeymerge(1, get_value(ibrowse_options, Params, []),
-            HttpDb#httpdb.ibrowse_options)
-    ],
-    Response = ibrowse:send_req_direct(
-        Worker, Url, Headers2, Method, Body, IbrowseOptions, infinity),
-    {Worker, Response}.
-
-
-process_response({error, sel_conn_closed}, _Worker, HttpDb, Params, Callback) ->
-    send_req(HttpDb, Params, Callback);
-
-process_response({error, {'EXIT', {normal, _}}}, _Worker, HttpDb, Params, Cb) ->
-    % ibrowse worker terminated because remote peer closed the socket
-    % -> not an error
-    send_req(HttpDb, Params, Cb);
-
-process_response({ibrowse_req_id, ReqId}, Worker, HttpDb, Params, Callback) ->
-    process_stream_response(ReqId, Worker, HttpDb, Params, Callback);
-
-process_response({ok, Code, Headers, Body}, Worker, HttpDb, Params, Callback) ->
-    release_worker(Worker, HttpDb),
-    case list_to_integer(Code) of
-    Ok when (Ok >= 200 andalso Ok < 300) ; (Ok >= 400 andalso Ok < 500) ->
-        EJson = case Body of
-        <<>> ->
-            null;
-        Json ->
-            ?JSON_DECODE(Json)
-        end,
-        Callback(Ok, Headers, EJson);
-    R when R =:= 301 ; R =:= 302 ; R =:= 303 ->
-        do_redirect(Worker, R, Headers, HttpDb, Params, Callback);
-    Error ->
-        maybe_retry({code, Error}, Worker, HttpDb, Params, Callback)
-    end;
-
-process_response(Error, Worker, HttpDb, Params, Callback) ->
-    maybe_retry(Error, Worker, HttpDb, Params, Callback).
-
-
-process_stream_response(ReqId, Worker, HttpDb, Params, Callback) ->
-    receive
-    {ibrowse_async_headers, ReqId, Code, Headers} ->
-        case list_to_integer(Code) of
-        Ok when (Ok >= 200 andalso Ok < 300) ; (Ok >= 400 andalso Ok < 500) ->
-            StreamDataFun = fun() ->
-                stream_data_self(HttpDb, Params, Worker, ReqId, Callback)
-            end,
-            ibrowse:stream_next(ReqId),
-            try
-                Ret = Callback(Ok, Headers, StreamDataFun),
-                release_worker(Worker, HttpDb),
-                clean_mailbox_req(ReqId),
-                Ret
-            catch throw:{maybe_retry_req, Err} ->
-                clean_mailbox_req(ReqId),
-                maybe_retry(Err, Worker, HttpDb, Params, Callback)
-            end;
-        R when R =:= 301 ; R =:= 302 ; R =:= 303 ->
-            do_redirect(Worker, R, Headers, HttpDb, Params, Callback);
-        Error ->
-            report_error(Worker, HttpDb, Params, {code, Error})
-        end;
-    {ibrowse_async_response, ReqId, {error, _} = Error} ->
-        maybe_retry(Error, Worker, HttpDb, Params, Callback)
-    after HttpDb#httpdb.timeout + 500 ->
-        % Note: ibrowse should always reply with timeouts, but this doesn't
-        % seem to be always true when there's a very high rate of requests
-        % and many open connections.
-        maybe_retry(timeout, Worker, HttpDb, Params, Callback)
-    end.
-
-
-clean_mailbox_req(ReqId) ->
-    receive
-    {ibrowse_async_response, ReqId, _} ->
-        clean_mailbox_req(ReqId);
-    {ibrowse_async_response_end, ReqId} ->
-        clean_mailbox_req(ReqId)
-    after 0 ->
-        ok
-    end.
-
-
-release_worker(Worker, #httpdb{httpc_pool = Pool}) ->
-    ok = couch_replicator_httpc_pool:release_worker(Pool, Worker).
-
-
-maybe_retry(Error, Worker, #httpdb{retries = 0} = HttpDb, Params, _Cb) ->
-    report_error(Worker, HttpDb, Params, {error, Error});
-
-maybe_retry(Error, Worker, #httpdb{retries = Retries, wait = Wait} = HttpDb,
-    Params, Cb) ->
-    release_worker(Worker, HttpDb),
-    Method = string:to_upper(atom_to_list(get_value(method, Params, get))),
-    Url = couch_util:url_strip_password(full_url(HttpDb, Params)),
-    ?LOG_INFO("Retrying ~s request to ~s in ~p seconds due to error ~s",
-        [Method, Url, Wait / 1000, error_cause(Error)]),
-    ok = timer:sleep(Wait),
-    Wait2 = erlang:min(Wait * 2, ?MAX_WAIT),
-    send_req(HttpDb#httpdb{retries = Retries - 1, wait = Wait2}, Params, Cb).
-
-
-report_error(Worker, HttpDb, Params, Error) ->
-    Method = string:to_upper(atom_to_list(get_value(method, Params, get))),
-    Url = couch_util:url_strip_password(full_url(HttpDb, Params)),
-    do_report_error(Url, Method, Error),
-    release_worker(Worker, HttpDb),
-    exit({http_request_failed, Method, Url, Error}).
-
-
-do_report_error(Url, Method, {code, Code}) ->
-    ?LOG_ERROR("Replicator, request ~s to ~p failed. The received "
-        "HTTP error code is ~p", [Method, Url, Code]);
-
-do_report_error(FullUrl, Method, Error) ->
-    ?LOG_ERROR("Replicator, request ~s to ~p failed due to error ~s",
-        [Method, FullUrl, error_cause(Error)]).
-
-
-error_cause({error, Cause}) ->
-    lists:flatten(io_lib:format("~p", [Cause]));
-error_cause(Cause) ->
-    lists:flatten(io_lib:format("~p", [Cause])).
-
-
-stream_data_self(#httpdb{timeout = T} = HttpDb, Params, Worker, ReqId, Cb) ->
-    case accumulate_messages(ReqId, [], T + 500) of
-    {Data, ibrowse_async_response} ->
-        ibrowse:stream_next(ReqId),
-        {Data, fun() -> stream_data_self(HttpDb, Params, Worker, ReqId, Cb) end};
-    {Data, ibrowse_async_response_end} ->
-        {Data, fun() -> throw({maybe_retry_req, more_data_expected}) end}
-    end.
-
-accumulate_messages(ReqId, Acc, Timeout) ->
-    receive
-    {ibrowse_async_response, ReqId, {error, Error}} ->
-        throw({maybe_retry_req, Error});
-    {ibrowse_async_response, ReqId, <<>>} ->
-        accumulate_messages(ReqId, Acc, Timeout);
-    {ibrowse_async_response, ReqId, Data} ->
-        accumulate_messages(ReqId, [Data | Acc], 0);
-    {ibrowse_async_response_end, ReqId} ->
-        {iolist_to_binary(lists:reverse(Acc)), ibrowse_async_response_end}
-    after Timeout ->
-        % Note: ibrowse should always reply with timeouts, but this doesn't
-        % seem to be always true when there's a very high rate of requests
-        % and many open connections.
-        if Acc =:= [] ->
-            throw({maybe_retry_req, timeout});
-        true ->
-            {iolist_to_binary(lists:reverse(Acc)), ibrowse_async_response}
-        end
-    end.
-
-
-full_url(#httpdb{url = BaseUrl}, Params) ->
-    Path = get_value(path, Params, []),
-    QueryArgs = get_value(qs, Params, []),
-    BaseUrl ++ Path ++ query_args_to_string(QueryArgs, []).
-
-
-query_args_to_string([], []) ->
-    "";
-query_args_to_string([], Acc) ->
-    "?" ++ string:join(lists:reverse(Acc), "&");
-query_args_to_string([{K, V} | Rest], Acc) ->
-    query_args_to_string(Rest, [K ++ "=" ++ couch_httpd:quote(V) | Acc]).
-
-
-oauth_header(#httpdb{oauth = nil}, _ConnParams) ->
-    [];
-oauth_header(#httpdb{url = BaseUrl, oauth = OAuth}, ConnParams) ->
-    Consumer = {
-        OAuth#oauth.consumer_key,
-        OAuth#oauth.consumer_secret,
-        OAuth#oauth.signature_method
-    },
-    Method = case get_value(method, ConnParams, get) of
-    get -> "GET";
-    post -> "POST";
-    put -> "PUT";
-    head -> "HEAD"
-    end,
-    QSL = get_value(qs, ConnParams, []),
-    OAuthParams = oauth:sign(Method,
-        BaseUrl ++ get_value(path, ConnParams, []),
-        QSL, Consumer, OAuth#oauth.token, OAuth#oauth.token_secret) -- QSL,
-    [{"Authorization",
-        "OAuth " ++ oauth:header_params_encode(OAuthParams)}].
-
-
-do_redirect(Worker, Code, Headers, #httpdb{url = Url} = HttpDb, Params, Cb) ->
-    release_worker(Worker, HttpDb),
-    RedirectUrl = redirect_url(Headers, Url),
-    {HttpDb2, Params2} = after_redirect(RedirectUrl, Code, HttpDb, Params),
-    send_req(HttpDb2, Params2, Cb).
-
-
-redirect_url(RespHeaders, OrigUrl) ->
-    MochiHeaders = mochiweb_headers:make(RespHeaders),
-    RedUrl = mochiweb_headers:get_value("Location", MochiHeaders),
-    #url{
-        host = Host,
-        host_type = HostType,
-        port = Port,
-        path = Path,  % includes query string
-        protocol = Proto
-    } = ibrowse_lib:parse_url(RedUrl),
-    #url{
-        username = User,
-        password = Passwd
-    } = ibrowse_lib:parse_url(OrigUrl),
-    Creds = case is_list(User) andalso is_list(Passwd) of
-    true ->
-        User ++ ":" ++ Passwd ++ "@";
-    false ->
-        []
-    end,
-    HostPart = case HostType of
-    ipv6_address ->
-        "[" ++ Host ++ "]";
-    _ ->
-        Host
-    end,
-    atom_to_list(Proto) ++ "://" ++ Creds ++ HostPart ++ ":" ++
-        integer_to_list(Port) ++ Path.
-
-after_redirect(RedirectUrl, 303, HttpDb, Params) ->
-    after_redirect(RedirectUrl, HttpDb, ?replace(Params, method, get));
-after_redirect(RedirectUrl, _Code, HttpDb, Params) ->
-    after_redirect(RedirectUrl, HttpDb, Params).
-
-after_redirect(RedirectUrl, HttpDb, Params) ->
-    Params2 = lists:keydelete(path, 1, lists:keydelete(qs, 1, Params)),
-    {HttpDb#httpdb{url = RedirectUrl}, Params2}.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_replicator/src/couch_replicator_httpc_pool.erl
----------------------------------------------------------------------
diff --git a/apps/couch_replicator/src/couch_replicator_httpc_pool.erl b/apps/couch_replicator/src/couch_replicator_httpc_pool.erl
deleted file mode 100644
index a82a2df..0000000
--- a/apps/couch_replicator/src/couch_replicator_httpc_pool.erl
+++ /dev/null
@@ -1,138 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_replicator_httpc_pool).
--behaviour(gen_server).
-
-% public API
--export([start_link/2, stop/1]).
--export([get_worker/1, release_worker/2]).
-
-% gen_server API
--export([init/1, handle_call/3, handle_info/2, handle_cast/2]).
--export([code_change/3, terminate/2]).
-
--include_lib("couch/include/couch_db.hrl").
-
--import(couch_util, [
-    get_value/2,
-    get_value/3
-]).
-
--record(state, {
-    url,
-    limit,                  % max # of workers allowed
-    free = [],              % free workers (connections)
-    busy = [],              % busy workers (connections)
-    waiting = queue:new()   % blocked clients waiting for a worker
-}).
-
-
-start_link(Url, Options) ->
-    gen_server:start_link(?MODULE, {Url, Options}, []).
-
-
-stop(Pool) ->
-    ok = gen_server:call(Pool, stop, infinity).
-
-
-get_worker(Pool) ->
-    {ok, _Worker} = gen_server:call(Pool, get_worker, infinity).
-
-
-release_worker(Pool, Worker) ->
-    ok = gen_server:cast(Pool, {release_worker, Worker}).
-
-
-init({Url, Options}) ->
-    process_flag(trap_exit, true),
-    State = #state{
-        url = Url,
-        limit = get_value(max_connections, Options)
-    },
-    {ok, State}.
-
-
-handle_call(get_worker, From, #state{waiting = Waiting} = State) ->
-    #state{url = Url, limit = Limit, busy = Busy, free = Free} = State,
-    case length(Busy) >= Limit of
-    true ->
-        {noreply, State#state{waiting = queue:in(From, Waiting)}};
-    false ->
-        case Free of
-        [] ->
-           {ok, Worker} = ibrowse:spawn_link_worker_process(Url),
-           Free2 = Free;
-        [Worker | Free2] ->
-           ok
-        end,
-        NewState = State#state{free = Free2, busy = [Worker | Busy]},
-        {reply, {ok, Worker}, NewState}
-    end;
-
-handle_call(stop, _From, State) ->
-    {stop, normal, ok, State}.
-
-
-handle_cast({release_worker, Worker}, #state{waiting = Waiting} = State) ->
-    case is_process_alive(Worker) andalso
-        lists:member(Worker, State#state.busy) of
-    true ->
-        case queue:out(Waiting) of
-        {empty, Waiting2} ->
-            Busy2 = State#state.busy -- [Worker],
-            Free2 = [Worker | State#state.free];
-        {{value, From}, Waiting2} ->
-            gen_server:reply(From, {ok, Worker}),
-            Busy2 = State#state.busy,
-            Free2 = State#state.free
-        end,
-        NewState = State#state{
-           busy = Busy2,
-           free = Free2,
-           waiting = Waiting2
-        },
-        {noreply, NewState};
-   false ->
-        {noreply, State}
-   end.
-
-
-handle_info({'EXIT', Pid, _Reason}, #state{busy = Busy, free = Free} = State) ->
-    case Free -- [Pid] of
-    Free ->
-        case Busy -- [Pid] of
-        Busy ->
-            {noreply, State};
-        Busy2 ->
-            case queue:out(State#state.waiting) of
-            {empty, _} ->
-                {noreply, State#state{busy = Busy2}};
-            {{value, From}, Waiting2} ->
-                {ok, Worker} = ibrowse:spawn_link_worker_process(State#state.url),
-                gen_server:reply(From, {ok, Worker}),
-                {noreply, State#state{busy = [Worker | Busy2], waiting = Waiting2}}
-            end
-        end;
-    Free2 ->
-        {noreply, State#state{free = Free2}}
-    end.
-
-
-code_change(_OldVsn, State, _Extra) ->
-    {ok, State}.
-
-
-terminate(_Reason, State) ->
-    lists:foreach(fun ibrowse_http_client:stop/1, State#state.free),
-    lists:foreach(fun ibrowse_http_client:stop/1, State#state.busy).
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_replicator/src/couch_replicator_httpd.erl
----------------------------------------------------------------------
diff --git a/apps/couch_replicator/src/couch_replicator_httpd.erl b/apps/couch_replicator/src/couch_replicator_httpd.erl
deleted file mode 100644
index 0a21d52..0000000
--- a/apps/couch_replicator/src/couch_replicator_httpd.erl
+++ /dev/null
@@ -1,66 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_replicator_httpd).
-
--include_lib("couch/include/couch_db.hrl").
-
--import(couch_httpd, [
-    send_json/2,
-    send_json/3,
-    send_method_not_allowed/2
-]).
-
--import(couch_util, [
-    to_binary/1
-]).
-
--export([handle_req/1]).
-
-
-handle_req(#httpd{method = 'POST', user_ctx = UserCtx} = Req) ->
-    couch_httpd:validate_ctype(Req, "application/json"),
-    RepDoc = {Props} = couch_httpd:json_body_obj(Req),
-    validate_rep_props(Props),
-    {ok, Rep} = couch_replicator_utils:parse_rep_doc(RepDoc, UserCtx),
-    case couch_replicator:replicate(Rep) of
-    {error, {Error, Reason}} ->
-        send_json(
-            Req, 500,
-            {[{error, to_binary(Error)}, {reason, to_binary(Reason)}]});
-    {error, not_found} ->
-        % Tried to cancel a replication that didn't exist.
-        send_json(Req, 404, {[{error, <<"not found">>}]});
-    {error, Reason} ->
-        send_json(Req, 500, {[{error, to_binary(Reason)}]});
-    {ok, {cancelled, RepId}} ->
-        send_json(Req, 200, {[{ok, true}, {<<"_local_id">>, RepId}]});
-    {ok, {continuous, RepId}} ->
-        send_json(Req, 202, {[{ok, true}, {<<"_local_id">>, RepId}]});
-    {ok, {HistoryResults}} ->
-        send_json(Req, {[{ok, true} | HistoryResults]})
-    end;
-
-handle_req(Req) ->
-    send_method_not_allowed(Req, "POST").
-
-validate_rep_props([]) ->
-    ok;
-validate_rep_props([{<<"query_params">>, {Params}}|Rest]) ->
-    lists:foreach(fun
-        ({_,V}) when is_binary(V) -> ok;
-        ({K,_}) -> throw({bad_request,
-            <<K/binary," value must be a string.">>})
-        end, Params),
-    validate_rep_props(Rest);
-validate_rep_props([_|Rest]) ->
-    validate_rep_props(Rest).

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_replicator/src/couch_replicator_job_sup.erl
----------------------------------------------------------------------
diff --git a/apps/couch_replicator/src/couch_replicator_job_sup.erl b/apps/couch_replicator/src/couch_replicator_job_sup.erl
deleted file mode 100644
index 484cc1a..0000000
--- a/apps/couch_replicator/src/couch_replicator_job_sup.erl
+++ /dev/null
@@ -1,31 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_replicator_job_sup).
--behaviour(supervisor).
--export([init/1, start_link/0]).
-
--include_lib("couch/include/couch_db.hrl").
-
-start_link() ->
-    supervisor:start_link({local,?MODULE}, ?MODULE, []).
-
-%%=============================================================================
-%% supervisor callbacks
-%%=============================================================================
-
-init([]) ->
-    {ok, {{one_for_one, 3, 10}, []}}.
-
-%%=============================================================================
-%% internal functions
-%%=============================================================================

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_replicator/src/couch_replicator_js_functions.hrl
----------------------------------------------------------------------
diff --git a/apps/couch_replicator/src/couch_replicator_js_functions.hrl b/apps/couch_replicator/src/couch_replicator_js_functions.hrl
deleted file mode 100644
index 3f1db7c..0000000
--- a/apps/couch_replicator/src/couch_replicator_js_functions.hrl
+++ /dev/null
@@ -1,151 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License.  You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--define(REP_DB_DOC_VALIDATE_FUN, <<"
-    function(newDoc, oldDoc, userCtx) {
-        function reportError(error_msg) {
-            log('Error writing document `' + newDoc._id +
-                '\\' to the replicator database: ' + error_msg);
-            throw({forbidden: error_msg});
-        }
-
-        function validateEndpoint(endpoint, fieldName) {
-            if ((typeof endpoint !== 'string') &&
-                ((typeof endpoint !== 'object') || (endpoint === null))) {
-
-                reportError('The `' + fieldName + '\\' property must exist' +
-                    ' and be either a string or an object.');
-            }
-
-            if (typeof endpoint === 'object') {
-                if ((typeof endpoint.url !== 'string') || !endpoint.url) {
-                    reportError('The url property must exist in the `' +
-                        fieldName + '\\' field and must be a non-empty string.');
-                }
-
-                if ((typeof endpoint.auth !== 'undefined') &&
-                    ((typeof endpoint.auth !== 'object') ||
-                        endpoint.auth === null)) {
-
-                    reportError('`' + fieldName +
-                        '.auth\\' must be a non-null object.');
-                }
-
-                if ((typeof endpoint.headers !== 'undefined') &&
-                    ((typeof endpoint.headers !== 'object') ||
-                        endpoint.headers === null)) {
-
-                    reportError('`' + fieldName +
-                        '.headers\\' must be a non-null object.');
-                }
-            }
-        }
-
-        var isReplicator = (userCtx.roles.indexOf('_replicator') >= 0);
-        var isAdmin = (userCtx.roles.indexOf('_admin') >= 0);
-
-        if (oldDoc && !newDoc._deleted && !isReplicator &&
-            (oldDoc._replication_state === 'triggered')) {
-            reportError('Only the replicator can edit replication documents ' +
-                'that are in the triggered state.');
-        }
-
-        if (!newDoc._deleted) {
-            validateEndpoint(newDoc.source, 'source');
-            validateEndpoint(newDoc.target, 'target');
-
-            if ((typeof newDoc.create_target !== 'undefined') &&
-                (typeof newDoc.create_target !== 'boolean')) {
-
-                reportError('The `create_target\\' field must be a boolean.');
-            }
-
-            if ((typeof newDoc.continuous !== 'undefined') &&
-                (typeof newDoc.continuous !== 'boolean')) {
-
-                reportError('The `continuous\\' field must be a boolean.');
-            }
-
-            if ((typeof newDoc.doc_ids !== 'undefined') &&
-                !isArray(newDoc.doc_ids)) {
-
-                reportError('The `doc_ids\\' field must be an array of strings.');
-            }
-
-            if ((typeof newDoc.filter !== 'undefined') &&
-                ((typeof newDoc.filter !== 'string') || !newDoc.filter)) {
-
-                reportError('The `filter\\' field must be a non-empty string.');
-            }
-
-            if ((typeof newDoc.query_params !== 'undefined') &&
-                ((typeof newDoc.query_params !== 'object') ||
-                    newDoc.query_params === null)) {
-
-                reportError('The `query_params\\' field must be an object.');
-            }
-
-            if (newDoc.user_ctx) {
-                var user_ctx = newDoc.user_ctx;
-
-                if ((typeof user_ctx !== 'object') || (user_ctx === null)) {
-                    reportError('The `user_ctx\\' property must be a ' +
-                        'non-null object.');
-                }
-
-                if (!(user_ctx.name === null ||
-                    (typeof user_ctx.name === 'undefined') ||
-                    ((typeof user_ctx.name === 'string') &&
-                        user_ctx.name.length > 0))) {
-
-                    reportError('The `user_ctx.name\\' property must be a ' +
-                        'non-empty string or null.');
-                }
-
-                if (!isAdmin && (user_ctx.name !== userCtx.name)) {
-                    reportError('The given `user_ctx.name\\' is not valid');
-                }
-
-                if (user_ctx.roles && !isArray(user_ctx.roles)) {
-                    reportError('The `user_ctx.roles\\' property must be ' +
-                        'an array of strings.');
-                }
-
-                if (!isAdmin && user_ctx.roles) {
-                    for (var i = 0; i < user_ctx.roles.length; i++) {
-                        var role = user_ctx.roles[i];
-
-                        if (typeof role !== 'string' || role.length === 0) {
-                            reportError('Roles must be non-empty strings.');
-                        }
-                        if (userCtx.roles.indexOf(role) === -1) {
-                            reportError('Invalid role (`' + role +
-                                '\\') in the `user_ctx\\'');
-                        }
-                    }
-                }
-            } else {
-                if (!isAdmin) {
-                    reportError('The `user_ctx\\' property is missing (it is ' +
-                       'optional for admins only).');
-                }
-            }
-        } else {
-            if (!isAdmin) {
-                if (!oldDoc.user_ctx || (oldDoc.user_ctx.name !== userCtx.name)) {
-                    reportError('Replication documents can only be deleted by ' +
-                        'admins or by the users who created them.');
-                }
-            }
-        }
-    }
-">>).

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_replicator/src/couch_replicator_manager.erl
----------------------------------------------------------------------
diff --git a/apps/couch_replicator/src/couch_replicator_manager.erl b/apps/couch_replicator/src/couch_replicator_manager.erl
deleted file mode 100644
index 8055727..0000000
--- a/apps/couch_replicator/src/couch_replicator_manager.erl
+++ /dev/null
@@ -1,709 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_replicator_manager).
--behaviour(gen_server).
-
-% public API
--export([replication_started/1, replication_completed/2, replication_error/2]).
-
--export([before_doc_update/2, after_doc_read/2]).
-
-% gen_server callbacks
--export([start_link/0, init/1, handle_call/3, handle_info/2, handle_cast/2]).
--export([code_change/3, terminate/2]).
-
--include_lib("couch/include/couch_db.hrl").
--include("couch_replicator.hrl").
--include("couch_replicator_js_functions.hrl").
-
--define(DOC_TO_REP, couch_rep_doc_id_to_rep_id).
--define(REP_TO_STATE, couch_rep_id_to_rep_state).
--define(INITIAL_WAIT, 2.5). % seconds
--define(MAX_WAIT, 600).     % seconds
--define(OWNER, <<"owner">>).
-
--define(replace(L, K, V), lists:keystore(K, 1, L, {K, V})).
-
--record(rep_state, {
-    rep,
-    starting,
-    retries_left,
-    max_retries,
-    wait = ?INITIAL_WAIT
-}).
-
--import(couch_util, [
-    get_value/2,
-    get_value/3,
-    to_binary/1
-]).
-
--record(state, {
-    changes_feed_loop = nil,
-    db_notifier = nil,
-    rep_db_name = nil,
-    rep_start_pids = [],
-    max_retries
-}).
-
-
-start_link() ->
-    gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
-
-
-replication_started(#rep{id = {BaseId, _} = RepId}) ->
-    case rep_state(RepId) of
-    nil ->
-        ok;
-    #rep_state{rep = #rep{doc_id = DocId}} ->
-        update_rep_doc(DocId, [
-            {<<"_replication_state">>, <<"triggered">>},
-            {<<"_replication_state_reason">>, undefined},
-            {<<"_replication_id">>, ?l2b(BaseId)},
-            {<<"_replication_stats">>, undefined}]),
-        ok = gen_server:call(?MODULE, {rep_started, RepId}, infinity),
-        ?LOG_INFO("Document `~s` triggered replication `~s`",
-            [DocId, pp_rep_id(RepId)])
-    end.
-
-
-replication_completed(#rep{id = RepId}, Stats) ->
-    case rep_state(RepId) of
-    nil ->
-        ok;
-    #rep_state{rep = #rep{doc_id = DocId}} ->
-        update_rep_doc(DocId, [
-            {<<"_replication_state">>, <<"completed">>},
-            {<<"_replication_state_reason">>, undefined},
-            {<<"_replication_stats">>, {Stats}}]),
-        ok = gen_server:call(?MODULE, {rep_complete, RepId}, infinity),
-        ?LOG_INFO("Replication `~s` finished (triggered by document `~s`)",
-            [pp_rep_id(RepId), DocId])
-    end.
-
-
-replication_error(#rep{id = {BaseId, _} = RepId}, Error) ->
-    case rep_state(RepId) of
-    nil ->
-        ok;
-    #rep_state{rep = #rep{doc_id = DocId}} ->
-        update_rep_doc(DocId, [
-            {<<"_replication_state">>, <<"error">>},
-            {<<"_replication_state_reason">>, to_binary(error_reason(Error))},
-            {<<"_replication_id">>, ?l2b(BaseId)}]),
-        ok = gen_server:call(?MODULE, {rep_error, RepId, Error}, infinity)
-    end.
-
-
-init(_) ->
-    process_flag(trap_exit, true),
-    ?DOC_TO_REP = ets:new(?DOC_TO_REP, [named_table, set, protected]),
-    ?REP_TO_STATE = ets:new(?REP_TO_STATE, [named_table, set, protected]),
-    Server = self(),
-    ok = couch_config:register(
-        fun("replicator", "db", NewName) ->
-            ok = gen_server:cast(Server, {rep_db_changed, ?l2b(NewName)});
-        ("replicator", "max_replication_retry_count", V) ->
-            ok = gen_server:cast(Server, {set_max_retries, retries_value(V)})
-        end
-    ),
-    {Loop, RepDbName} = changes_feed_loop(),
-    {ok, #state{
-        changes_feed_loop = Loop,
-        rep_db_name = RepDbName,
-        db_notifier = db_update_notifier(),
-        max_retries = retries_value(
-            couch_config:get("replicator", "max_replication_retry_count", "10"))
-    }}.
-
-
-handle_call({rep_db_update, {ChangeProps} = Change}, _From, State) ->
-    NewState = try
-        process_update(State, Change)
-    catch
-    _Tag:Error ->
-        {RepProps} = get_value(doc, ChangeProps),
-        DocId = get_value(<<"_id">>, RepProps),
-        rep_db_update_error(Error, DocId),
-        State
-    end,
-    {reply, ok, NewState};
-
-
-handle_call({rep_started, RepId}, _From, State) ->
-    case rep_state(RepId) of
-    nil ->
-        ok;
-    RepState ->
-        NewRepState = RepState#rep_state{
-            starting = false,
-            retries_left = State#state.max_retries,
-            max_retries = State#state.max_retries,
-            wait = ?INITIAL_WAIT
-        },
-        true = ets:insert(?REP_TO_STATE, {RepId, NewRepState})
-    end,
-    {reply, ok, State};
-
-handle_call({rep_complete, RepId}, _From, State) ->
-    true = ets:delete(?REP_TO_STATE, RepId),
-    {reply, ok, State};
-
-handle_call({rep_error, RepId, Error}, _From, State) ->
-    {reply, ok, replication_error(State, RepId, Error)};
-
-handle_call(Msg, From, State) ->
-    ?LOG_ERROR("Replication manager received unexpected call ~p from ~p",
-        [Msg, From]),
-    {stop, {error, {unexpected_call, Msg}}, State}.
-
-
-handle_cast({rep_db_changed, NewName}, #state{rep_db_name = NewName} = State) ->
-    {noreply, State};
-
-handle_cast({rep_db_changed, _NewName}, State) ->
-    {noreply, restart(State)};
-
-handle_cast({rep_db_created, NewName}, #state{rep_db_name = NewName} = State) ->
-    {noreply, State};
-
-handle_cast({rep_db_created, _NewName}, State) ->
-    {noreply, restart(State)};
-
-handle_cast({set_max_retries, MaxRetries}, State) ->
-    {noreply, State#state{max_retries = MaxRetries}};
-
-handle_cast(Msg, State) ->
-    ?LOG_ERROR("Replication manager received unexpected cast ~p", [Msg]),
-    {stop, {error, {unexpected_cast, Msg}}, State}.
-
-
-handle_info({'EXIT', From, normal}, #state{changes_feed_loop = From} = State) ->
-    % replicator DB deleted
-    {noreply, State#state{changes_feed_loop = nil, rep_db_name = nil}};
-
-handle_info({'EXIT', From, Reason}, #state{db_notifier = From} = State) ->
-    ?LOG_ERROR("Database update notifier died. Reason: ~p", [Reason]),
-    {stop, {db_update_notifier_died, Reason}, State};
-
-handle_info({'EXIT', From, normal}, #state{rep_start_pids = Pids} = State) ->
-    % one of the replication start processes terminated successfully
-    {noreply, State#state{rep_start_pids = Pids -- [From]}};
-
-handle_info({'DOWN', _Ref, _, _, _}, State) ->
-    % From a db monitor created by a replication process. Ignore.
-    {noreply, State};
-
-handle_info(Msg, State) ->
-    ?LOG_ERROR("Replication manager received unexpected message ~p", [Msg]),
-    {stop, {unexpected_msg, Msg}, State}.
-
-
-terminate(_Reason, State) ->
-    #state{
-        rep_start_pids = StartPids,
-        changes_feed_loop = Loop,
-        db_notifier = DbNotifier
-    } = State,
-    stop_all_replications(),
-    lists:foreach(
-        fun(Pid) ->
-            catch unlink(Pid),
-            catch exit(Pid, stop)
-        end,
-        [Loop | StartPids]),
-    true = ets:delete(?REP_TO_STATE),
-    true = ets:delete(?DOC_TO_REP),
-    couch_db_update_notifier:stop(DbNotifier).
-
-
-code_change(_OldVsn, State, _Extra) ->
-    {ok, State}.
-
-
-changes_feed_loop() ->
-    {ok, RepDb} = ensure_rep_db_exists(),
-    RepDbName = couch_db:name(RepDb),
-    couch_db:close(RepDb),
-    Server = self(),
-    Pid = spawn_link(
-        fun() ->
-            DbOpenOptions = [{user_ctx, RepDb#db.user_ctx}, sys_db],
-            {ok, Db} = couch_db:open_int(RepDbName, DbOpenOptions),
-            ChangesFeedFun = couch_changes:handle_changes(
-                #changes_args{
-                    include_docs = true,
-                    feed = "continuous",
-                    timeout = infinity
-                },
-                {json_req, null},
-                Db
-            ),
-            ChangesFeedFun(
-                fun({change, Change, _}, _) ->
-                    case has_valid_rep_id(Change) of
-                    true ->
-                        ok = gen_server:call(
-                            Server, {rep_db_update, Change}, infinity);
-                    false ->
-                        ok
-                    end;
-                (_, _) ->
-                    ok
-                end
-            )
-        end
-    ),
-    {Pid, RepDbName}.
-
-
-has_valid_rep_id({Change}) ->
-    has_valid_rep_id(get_value(<<"id">>, Change));
-has_valid_rep_id(<<?DESIGN_DOC_PREFIX, _Rest/binary>>) ->
-    false;
-has_valid_rep_id(_Else) ->
-    true.
-
-
-db_update_notifier() ->
-    Server = self(),
-    {ok, Notifier} = couch_db_update_notifier:start_link(
-        fun({created, DbName}) ->
-            case ?l2b(couch_config:get("replicator", "db", "_replicator")) of
-            DbName ->
-                ok = gen_server:cast(Server, {rep_db_created, DbName});
-            _ ->
-                ok
-            end;
-        (_) ->
-            % no need to handle the 'deleted' event - the changes feed loop
-            % dies when the database is deleted
-            ok
-        end
-    ),
-    Notifier.
-
-
-restart(#state{changes_feed_loop = Loop, rep_start_pids = StartPids} = State) ->
-    stop_all_replications(),
-    lists:foreach(
-        fun(Pid) ->
-            catch unlink(Pid),
-            catch exit(Pid, rep_db_changed)
-        end,
-        [Loop | StartPids]),
-    {NewLoop, NewRepDbName} = changes_feed_loop(),
-    State#state{
-        changes_feed_loop = NewLoop,
-        rep_db_name = NewRepDbName,
-        rep_start_pids = []
-    }.
-
-
-process_update(State, {Change}) ->
-    {RepProps} = JsonRepDoc = get_value(doc, Change),
-    DocId = get_value(<<"_id">>, RepProps),
-    case get_value(<<"deleted">>, Change, false) of
-    true ->
-        rep_doc_deleted(DocId),
-        State;
-    false ->
-        case get_value(<<"_replication_state">>, RepProps) of
-        undefined ->
-            maybe_start_replication(State, DocId, JsonRepDoc);
-        <<"triggered">> ->
-            maybe_start_replication(State, DocId, JsonRepDoc);
-        <<"completed">> ->
-            replication_complete(DocId),
-            State;
-        <<"error">> ->
-            case ets:lookup(?DOC_TO_REP, DocId) of
-            [] ->
-                maybe_start_replication(State, DocId, JsonRepDoc);
-            _ ->
-                State
-            end
-        end
-    end.
-
-
-rep_db_update_error(Error, DocId) ->
-    case Error of
-    {bad_rep_doc, Reason} ->
-        ok;
-    _ ->
-        Reason = to_binary(Error)
-    end,
-    ?LOG_ERROR("Replication manager, error processing document `~s`: ~s",
-        [DocId, Reason]),
-    update_rep_doc(DocId, [{<<"_replication_state">>, <<"error">>},
-                           {<<"_replication_state_reason">>, Reason}]).
-
-
-rep_user_ctx({RepDoc}) ->
-    case get_value(<<"user_ctx">>, RepDoc) of
-    undefined ->
-        #user_ctx{};
-    {UserCtx} ->
-        #user_ctx{
-            name = get_value(<<"name">>, UserCtx, null),
-            roles = get_value(<<"roles">>, UserCtx, [])
-        }
-    end.
-
-
-maybe_start_replication(State, DocId, RepDoc) ->
-    #rep{id = {BaseId, _} = RepId} = Rep = parse_rep_doc(RepDoc),
-    case rep_state(RepId) of
-    nil ->
-        RepState = #rep_state{
-            rep = Rep,
-            starting = true,
-            retries_left = State#state.max_retries,
-            max_retries = State#state.max_retries
-        },
-        true = ets:insert(?REP_TO_STATE, {RepId, RepState}),
-        true = ets:insert(?DOC_TO_REP, {DocId, RepId}),
-        ?LOG_INFO("Attempting to start replication `~s` (document `~s`).",
-            [pp_rep_id(RepId), DocId]),
-        Pid = spawn_link(fun() -> start_replication(Rep, 0) end),
-        State#state{rep_start_pids = [Pid | State#state.rep_start_pids]};
-    #rep_state{rep = #rep{doc_id = DocId}} ->
-        State;
-    #rep_state{starting = false, rep = #rep{doc_id = OtherDocId}} ->
-        ?LOG_INFO("The replication specified by the document `~s` was already"
-            " triggered by the document `~s`", [DocId, OtherDocId]),
-        maybe_tag_rep_doc(DocId, RepDoc, ?l2b(BaseId)),
-        State;
-    #rep_state{starting = true, rep = #rep{doc_id = OtherDocId}} ->
-        ?LOG_INFO("The replication specified by the document `~s` is already"
-            " being triggered by the document `~s`", [DocId, OtherDocId]),
-        maybe_tag_rep_doc(DocId, RepDoc, ?l2b(BaseId)),
-        State
-    end.
-
-
-parse_rep_doc(RepDoc) ->
-    {ok, Rep} = try
-        couch_replicator_utils:parse_rep_doc(RepDoc, rep_user_ctx(RepDoc))
-    catch
-    throw:{error, Reason} ->
-        throw({bad_rep_doc, Reason});
-    Tag:Err ->
-        throw({bad_rep_doc, to_binary({Tag, Err})})
-    end,
-    Rep.
-
-
-maybe_tag_rep_doc(DocId, {RepProps}, RepId) ->
-    case get_value(<<"_replication_id">>, RepProps) of
-    RepId ->
-        ok;
-    _ ->
-        update_rep_doc(DocId, [{<<"_replication_id">>, RepId}])
-    end.
-
-
-start_replication(Rep, Wait) ->
-    ok = timer:sleep(Wait * 1000),
-    case (catch couch_replicator:async_replicate(Rep)) of
-    {ok, _} ->
-        ok;
-    Error ->
-        replication_error(Rep, Error)
-    end.
-
-
-replication_complete(DocId) ->
-    case ets:lookup(?DOC_TO_REP, DocId) of
-    [{DocId, {BaseId, Ext} = RepId}] ->
-        case rep_state(RepId) of
-        nil ->
-            % Prior to OTP R14B02, temporary child specs remain in
-            % in the supervisor after a worker finishes - remove them.
-            % We want to be able to start the same replication but with
-            % eventually different values for parameters that don't
-            % contribute to its ID calculation.
-            case erlang:system_info(otp_release) < "R14B02" of
-            true ->
-                spawn(fun() ->
-                    _ = supervisor:delete_child(couch_replicator_job_sup, BaseId ++ Ext)
-                end);
-            false ->
-                ok
-            end;
-        #rep_state{} ->
-            ok
-        end,
-        true = ets:delete(?DOC_TO_REP, DocId);
-    _ ->
-        ok
-    end.
-
-
-rep_doc_deleted(DocId) ->
-    case ets:lookup(?DOC_TO_REP, DocId) of
-    [{DocId, RepId}] ->
-        couch_replicator:cancel_replication(RepId),
-        true = ets:delete(?REP_TO_STATE, RepId),
-        true = ets:delete(?DOC_TO_REP, DocId),
-        ?LOG_INFO("Stopped replication `~s` because replication document `~s`"
-            " was deleted", [pp_rep_id(RepId), DocId]);
-    [] ->
-        ok
-    end.
-
-
-replication_error(State, RepId, Error) ->
-    case rep_state(RepId) of
-    nil ->
-        State;
-    RepState ->
-        maybe_retry_replication(RepState, Error, State)
-    end.
-
-maybe_retry_replication(#rep_state{retries_left = 0} = RepState, Error, State) ->
-    #rep_state{
-        rep = #rep{id = RepId, doc_id = DocId},
-        max_retries = MaxRetries
-    } = RepState,
-    couch_replicator:cancel_replication(RepId),
-    true = ets:delete(?REP_TO_STATE, RepId),
-    true = ets:delete(?DOC_TO_REP, DocId),
-    ?LOG_ERROR("Error in replication `~s` (triggered by document `~s`): ~s"
-        "~nReached maximum retry attempts (~p).",
-        [pp_rep_id(RepId), DocId, to_binary(error_reason(Error)), MaxRetries]),
-    State;
-
-maybe_retry_replication(RepState, Error, State) ->
-    #rep_state{
-        rep = #rep{id = RepId, doc_id = DocId} = Rep
-    } = RepState,
-    #rep_state{wait = Wait} = NewRepState = state_after_error(RepState),
-    true = ets:insert(?REP_TO_STATE, {RepId, NewRepState}),
-    ?LOG_ERROR("Error in replication `~s` (triggered by document `~s`): ~s"
-        "~nRestarting replication in ~p seconds.",
-        [pp_rep_id(RepId), DocId, to_binary(error_reason(Error)), Wait]),
-    Pid = spawn_link(fun() -> start_replication(Rep, Wait) end),
-    State#state{rep_start_pids = [Pid | State#state.rep_start_pids]}.
-
-
-stop_all_replications() ->
-    ?LOG_INFO("Stopping all ongoing replications because the replicator"
-        " database was deleted or changed", []),
-    ets:foldl(
-        fun({_, RepId}, _) ->
-            couch_replicator:cancel_replication(RepId)
-        end,
-        ok, ?DOC_TO_REP),
-    true = ets:delete_all_objects(?REP_TO_STATE),
-    true = ets:delete_all_objects(?DOC_TO_REP).
-
-
-update_rep_doc(RepDocId, KVs) ->
-    {ok, RepDb} = ensure_rep_db_exists(),
-    try
-        case couch_db:open_doc(RepDb, RepDocId, [ejson_body]) of
-        {ok, LatestRepDoc} ->
-            update_rep_doc(RepDb, LatestRepDoc, KVs);
-        _ ->
-            ok
-        end
-    catch throw:conflict ->
-        % Shouldn't happen, as by default only the role _replicator can
-        % update replication documents.
-        ?LOG_ERROR("Conflict error when updating replication document `~s`."
-            " Retrying.", [RepDocId]),
-        ok = timer:sleep(5),
-        update_rep_doc(RepDocId, KVs)
-    after
-        couch_db:close(RepDb)
-    end.
-
-update_rep_doc(RepDb, #doc{body = {RepDocBody}} = RepDoc, KVs) ->
-    NewRepDocBody = lists:foldl(
-        fun({K, undefined}, Body) ->
-                lists:keydelete(K, 1, Body);
-            ({<<"_replication_state">> = K, State} = KV, Body) ->
-                case get_value(K, Body) of
-                State ->
-                    Body;
-                _ ->
-                    Body1 = lists:keystore(K, 1, Body, KV),
-                    lists:keystore(
-                        <<"_replication_state_time">>, 1, Body1,
-                        {<<"_replication_state_time">>, timestamp()})
-                end;
-            ({K, _V} = KV, Body) ->
-                lists:keystore(K, 1, Body, KV)
-        end,
-        RepDocBody, KVs),
-    case NewRepDocBody of
-    RepDocBody ->
-        ok;
-    _ ->
-        % Might not succeed - when the replication doc is deleted right
-        % before this update (not an error, ignore).
-        couch_db:update_doc(RepDb, RepDoc#doc{body = {NewRepDocBody}}, [])
-    end.
-
-
-% RFC3339 timestamps.
-% Note: doesn't include the time seconds fraction (RFC3339 says it's optional).
-timestamp() ->
-    {{Year, Month, Day}, {Hour, Min, Sec}} = calendar:now_to_local_time(now()),
-    UTime = erlang:universaltime(),
-    LocalTime = calendar:universal_time_to_local_time(UTime),
-    DiffSecs = calendar:datetime_to_gregorian_seconds(LocalTime) -
-        calendar:datetime_to_gregorian_seconds(UTime),
-    zone(DiffSecs div 3600, (DiffSecs rem 3600) div 60),
-    iolist_to_binary(
-        io_lib:format("~4..0w-~2..0w-~2..0wT~2..0w:~2..0w:~2..0w~s",
-            [Year, Month, Day, Hour, Min, Sec,
-                zone(DiffSecs div 3600, (DiffSecs rem 3600) div 60)])).
-
-zone(Hr, Min) when Hr >= 0, Min >= 0 ->
-    io_lib:format("+~2..0w:~2..0w", [Hr, Min]);
-zone(Hr, Min) ->
-    io_lib:format("-~2..0w:~2..0w", [abs(Hr), abs(Min)]).
-
-
-
-ensure_rep_db_exists() ->
-    DbName = ?l2b(couch_config:get("replicator", "db", "_replicator")),
-    UserCtx = #user_ctx{roles = [<<"_admin">>, <<"_replicator">>]},
-    case couch_db:open_int(DbName, [sys_db, {user_ctx, UserCtx}, nologifmissing]) of
-    {ok, Db} ->
-        Db;
-    _Error ->
-        {ok, Db} = couch_db:create(DbName, [sys_db, {user_ctx, UserCtx}])
-    end,
-    ensure_rep_ddoc_exists(Db, <<"_design/_replicator">>),
-    {ok, Db}.
-
-
-ensure_rep_ddoc_exists(RepDb, DDocID) ->
-    case couch_db:open_doc(RepDb, DDocID, []) of
-    {ok, _Doc} ->
-        ok;
-    _ ->
-        DDoc = couch_doc:from_json_obj({[
-            {<<"_id">>, DDocID},
-            {<<"language">>, <<"javascript">>},
-            {<<"validate_doc_update">>, ?REP_DB_DOC_VALIDATE_FUN}
-        ]}),
-        {ok, _Rev} = couch_db:update_doc(RepDb, DDoc, [])
-     end.
-
-
-% pretty-print replication id
-pp_rep_id(#rep{id = RepId}) ->
-    pp_rep_id(RepId);
-pp_rep_id({Base, Extension}) ->
-    Base ++ Extension.
-
-
-rep_state(RepId) ->
-    case ets:lookup(?REP_TO_STATE, RepId) of
-    [{RepId, RepState}] ->
-        RepState;
-    [] ->
-        nil
-    end.
-
-
-error_reason({error, {Error, Reason}})
-  when is_atom(Error), is_binary(Reason) ->
-    io_lib:format("~s: ~s", [Error, Reason]);
-error_reason({error, Reason}) ->
-    Reason;
-error_reason(Reason) ->
-    Reason.
-
-
-retries_value("infinity") ->
-    infinity;
-retries_value(Value) ->
-    list_to_integer(Value).
-
-
-state_after_error(#rep_state{retries_left = Left, wait = Wait} = State) ->
-    Wait2 = erlang:min(trunc(Wait * 2), ?MAX_WAIT),
-    case Left of
-    infinity ->
-        State#rep_state{wait = Wait2};
-    _ ->
-        State#rep_state{retries_left = Left - 1, wait = Wait2}
-    end.
-
-
-before_doc_update(#doc{id = <<?DESIGN_DOC_PREFIX, _/binary>>} = Doc, _Db) ->
-    Doc;
-before_doc_update(#doc{body = {Body}} = Doc, #db{user_ctx=UserCtx} = Db) ->
-    #user_ctx{roles = Roles, name = Name} = UserCtx,
-    case lists:member(<<"_replicator">>, Roles) of
-    true ->
-        Doc;
-    false ->
-        case couch_util:get_value(?OWNER, Body) of
-        undefined ->
-            Doc#doc{body = {?replace(Body, ?OWNER, Name)}};
-        Name ->
-            Doc;
-        Other ->
-            case (catch couch_db:check_is_admin(Db)) of
-            ok when Other =:= null ->
-                Doc#doc{body = {?replace(Body, ?OWNER, Name)}};
-            ok ->
-                Doc;
-            _ ->
-                throw({forbidden, <<"Can't update replication documents",
-                    " from other users.">>})
-            end
-        end
-    end.
-
-
-after_doc_read(#doc{id = <<?DESIGN_DOC_PREFIX, _/binary>>} = Doc, _Db) ->
-    Doc;
-after_doc_read(#doc{body = {Body}} = Doc, #db{user_ctx=UserCtx} = Db) ->
-    #user_ctx{name = Name} = UserCtx,
-    case (catch couch_db:check_is_admin(Db)) of
-    ok ->
-        Doc;
-    _ ->
-        case couch_util:get_value(?OWNER, Body) of
-        Name ->
-            Doc;
-        _Other ->
-            Source = strip_credentials(couch_util:get_value(<<"source">>, Body)),
-            Target = strip_credentials(couch_util:get_value(<<"target">>, Body)),
-            NewBody0 = ?replace(Body, <<"source">>, Source),
-            NewBody = ?replace(NewBody0, <<"target">>, Target),
-            #doc{revs = {Pos, [_ | Revs]}} = Doc,
-            NewDoc = Doc#doc{body = {NewBody}, revs = {Pos - 1, Revs}},
-            NewRevId = couch_db:new_revid(NewDoc),
-            NewDoc#doc{revs = {Pos, [NewRevId | Revs]}}
-        end
-    end.
-
-
-strip_credentials(undefined) ->
-    undefined;
-strip_credentials(Url) when is_binary(Url) ->
-    re:replace(Url,
-        "http(s)?://(?:[^:]+):[^@]+@(.*)$",
-        "http\\1://\\2",
-        [{return, binary}]);
-strip_credentials({Props}) ->
-    {lists:keydelete(<<"oauth">>, 1, Props)}.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_replicator/src/couch_replicator_manager_sup.erl
----------------------------------------------------------------------
diff --git a/apps/couch_replicator/src/couch_replicator_manager_sup.erl b/apps/couch_replicator/src/couch_replicator_manager_sup.erl
deleted file mode 100644
index f292546..0000000
--- a/apps/couch_replicator/src/couch_replicator_manager_sup.erl
+++ /dev/null
@@ -1,47 +0,0 @@
-
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_replicator_manager_sup).
-
--behaviour(supervisor).
-
-%% API
--export([start_link/0]).
-
-%% Supervisor callbacks
--export([init/1]).
-
-%% Helper macro for declaring children of supervisor
--define(CHILD(I, Type), {I, {I, start_link, []}, permanent, 5000, Type, [I]}).
-
-%% ===================================================================
-%% API functions
-%% ===================================================================
-
-start_link() ->
-    supervisor:start_link({local, ?MODULE}, ?MODULE, []).
-
-%% ===================================================================
-%% Supervisor callbacks
-%% ===================================================================
-
-init([]) ->
-    Children = [
-        {couch_replicator_manager,
-            {couch_replicator_manager, start_link, []},
-            permanent,
-            brutal_kill,
-            worker,
-            [couch_replicator_manager]}
-    ],
-    {ok, { {one_for_one, 10, 3600}, Children} }.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_replicator/src/couch_replicator_notifier.erl
----------------------------------------------------------------------
diff --git a/apps/couch_replicator/src/couch_replicator_notifier.erl b/apps/couch_replicator/src/couch_replicator_notifier.erl
deleted file mode 100644
index 39fd68b..0000000
--- a/apps/couch_replicator/src/couch_replicator_notifier.erl
+++ /dev/null
@@ -1,57 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_replicator_notifier).
-
--behaviour(gen_event).
-
-% public API
--export([start_link/1, stop/1, notify/1]).
-
-% gen_event callbacks
--export([init/1, terminate/2, code_change/3]).
--export([handle_event/2, handle_call/2, handle_info/2]).
-
--include_lib("couch/include/couch_db.hrl").
-
-start_link(FunAcc) ->
-    couch_event_sup:start_link(couch_replication,
-        {couch_replicator_notifier, make_ref()}, FunAcc).
-
-notify(Event) ->
-    gen_event:notify(couch_replication, Event).
-
-stop(Pid) ->
-    couch_event_sup:stop(Pid).
-
-
-init(FunAcc) ->
-    {ok, FunAcc}.
-
-terminate(_Reason, _State) ->
-    ok.
-
-handle_event(Event, Fun) when is_function(Fun, 1) ->
-    Fun(Event),
-    {ok, Fun};
-handle_event(Event, {Fun, Acc}) when is_function(Fun, 2) ->
-    Acc2 = Fun(Event, Acc),
-    {ok, {Fun, Acc2}}.
-
-handle_call(_Msg, State) ->
-    {reply, ok, State}.
-
-handle_info(_Msg, State) ->
-    {ok, State}.
-
-code_change(_OldVsn, State, _Extra) ->
-    {ok, State}.


[85/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/gregocal.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/gregocal.h b/src/apps/couch_collate/platform/osx/icu/unicode/gregocal.h
new file mode 100644
index 0000000..f2d1b0b
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/gregocal.h
@@ -0,0 +1,823 @@
+/*
+* Copyright (C) 1997-2006, International Business Machines Corporation and others.
+* All Rights Reserved.
+********************************************************************************
+*
+* File GREGOCAL.H
+*
+* Modification History:
+*
+*   Date        Name        Description
+*   04/22/97    aliu        Overhauled header.
+*    07/28/98    stephen        Sync with JDK 1.2
+*    09/04/98    stephen        Re-sync with JDK 8/31 putback
+*    09/14/98    stephen        Changed type of kOneDay, kOneWeek to double.
+*                            Fixed bug in roll()
+*   10/15/99    aliu        Fixed j31, incorrect WEEK_OF_YEAR computation.
+*                           Added documentation of WEEK_OF_YEAR computation.
+*   10/15/99    aliu        Fixed j32, cannot set date to Feb 29 2000 AD.
+*                           {JDK bug 4210209 4209272}
+*   11/07/2003  srl         Update, clean up documentation.
+********************************************************************************
+*/
+
+#ifndef GREGOCAL_H
+#define GREGOCAL_H
+
+#include "unicode/utypes.h"
+
+#if !UCONFIG_NO_FORMATTING
+
+#include "unicode/calendar.h"
+
+/**
+ * \file 
+ * \brief C++ API: Concrete class which provides the standard calendar.
+ */
+
+U_NAMESPACE_BEGIN
+
+/** 
+ * Concrete class which provides the standard calendar used by most of the world.
+ * <P>
+ * The standard (Gregorian) calendar has 2 eras, BC and AD.
+ * <P>
+ * This implementation handles a single discontinuity, which corresponds by default to
+ * the date the Gregorian calendar was originally instituted (October 15, 1582). Not all
+ * countries adopted the Gregorian calendar then, so this cutover date may be changed by
+ * the caller.
+ * <P>
+ * Prior to the institution of the Gregorian Calendar, New Year's Day was March 25. To
+ * avoid confusion, this Calendar always uses January 1. A manual adjustment may be made
+ * if desired for dates that are prior to the Gregorian changeover and which fall
+ * between January 1 and March 24.
+ *
+ * <p>Values calculated for the <code>WEEK_OF_YEAR</code> field range from 1 to
+ * 53.  Week 1 for a year is the first week that contains at least
+ * <code>getMinimalDaysInFirstWeek()</code> days from that year.  It thus
+ * depends on the values of <code>getMinimalDaysInFirstWeek()</code>,
+ * <code>getFirstDayOfWeek()</code>, and the day of the week of January 1.
+ * Weeks between week 1 of one year and week 1 of the following year are
+ * numbered sequentially from 2 to 52 or 53 (as needed).
+ *
+ * <p>For example, January 1, 1998 was a Thursday.  If
+ * <code>getFirstDayOfWeek()</code> is <code>MONDAY</code> and
+ * <code>getMinimalDaysInFirstWeek()</code> is 4 (these are the values
+ * reflecting ISO 8601 and many national standards), then week 1 of 1998 starts
+ * on December 29, 1997, and ends on January 4, 1998.  If, however,
+ * <code>getFirstDayOfWeek()</code> is <code>SUNDAY</code>, then week 1 of 1998
+ * starts on January 4, 1998, and ends on January 10, 1998; the first three days
+ * of 1998 then are part of week 53 of 1997.
+ *
+ * <p>Example for using GregorianCalendar:
+ * <pre>
+ * \code
+ *     // get the supported ids for GMT-08:00 (Pacific Standard Time)
+ *     UErrorCode success = U_ZERO_ERROR;
+ *     const StringEnumeration *ids = TimeZone::createEnumeration(-8 * 60 * 60 * 1000);
+ *     // if no ids were returned, something is wrong. get out.
+ *     if (ids == 0 || ids->count(success) == 0) {
+ *         return;
+ *     }
+ *
+ *     // begin output
+ *     cout << "Current Time" << endl;
+ *
+ *     // create a Pacific Standard Time time zone
+ *     SimpleTimeZone* pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids->unext(NULL, success)));
+ *
+ *     // set up rules for daylight savings time
+ *     pdt->setStartRule(Calendar::APRIL, 1, Calendar::SUNDAY, 2 * 60 * 60 * 1000);
+ *     pdt->setEndRule(Calendar::OCTOBER, -1, Calendar::SUNDAY, 2 * 60 * 60 * 1000);
+ *
+ *     // create a GregorianCalendar with the Pacific Daylight time zone
+ *     // and the current date and time
+ *     Calendar* calendar = new GregorianCalendar( pdt, success );
+ *
+ *     // print out a bunch of interesting things
+ *     cout << "ERA: " << calendar->get( Calendar::ERA, success ) << endl;
+ *     cout << "YEAR: " << calendar->get( Calendar::YEAR, success ) << endl;
+ *     cout << "MONTH: " << calendar->get( Calendar::MONTH, success ) << endl;
+ *     cout << "WEEK_OF_YEAR: " << calendar->get( Calendar::WEEK_OF_YEAR, success ) << endl;
+ *     cout << "WEEK_OF_MONTH: " << calendar->get( Calendar::WEEK_OF_MONTH, success ) << endl;
+ *     cout << "DATE: " << calendar->get( Calendar::DATE, success ) << endl;
+ *     cout << "DAY_OF_MONTH: " << calendar->get( Calendar::DAY_OF_MONTH, success ) << endl;
+ *     cout << "DAY_OF_YEAR: " << calendar->get( Calendar::DAY_OF_YEAR, success ) << endl;
+ *     cout << "DAY_OF_WEEK: " << calendar->get( Calendar::DAY_OF_WEEK, success ) << endl;
+ *     cout << "DAY_OF_WEEK_IN_MONTH: " << calendar->get( Calendar::DAY_OF_WEEK_IN_MONTH, success ) << endl;
+ *     cout << "AM_PM: " << calendar->get( Calendar::AM_PM, success ) << endl;
+ *     cout << "HOUR: " << calendar->get( Calendar::HOUR, success ) << endl;
+ *     cout << "HOUR_OF_DAY: " << calendar->get( Calendar::HOUR_OF_DAY, success ) << endl;
+ *     cout << "MINUTE: " << calendar->get( Calendar::MINUTE, success ) << endl;
+ *     cout << "SECOND: " << calendar->get( Calendar::SECOND, success ) << endl;
+ *     cout << "MILLISECOND: " << calendar->get( Calendar::MILLISECOND, success ) << endl;
+ *     cout << "ZONE_OFFSET: " << (calendar->get( Calendar::ZONE_OFFSET, success )/(60*60*1000)) << endl;
+ *     cout << "DST_OFFSET: " << (calendar->get( Calendar::DST_OFFSET, success )/(60*60*1000)) << endl;
+ *
+ *     cout << "Current Time, with hour reset to 3" << endl;
+ *     calendar->clear(Calendar::HOUR_OF_DAY); // so doesn't override
+ *     calendar->set(Calendar::HOUR, 3);
+ *     cout << "ERA: " << calendar->get( Calendar::ERA, success ) << endl;
+ *     cout << "YEAR: " << calendar->get( Calendar::YEAR, success ) << endl;
+ *     cout << "MONTH: " << calendar->get( Calendar::MONTH, success ) << endl;
+ *     cout << "WEEK_OF_YEAR: " << calendar->get( Calendar::WEEK_OF_YEAR, success ) << endl;
+ *     cout << "WEEK_OF_MONTH: " << calendar->get( Calendar::WEEK_OF_MONTH, success ) << endl;
+ *     cout << "DATE: " << calendar->get( Calendar::DATE, success ) << endl;
+ *     cout << "DAY_OF_MONTH: " << calendar->get( Calendar::DAY_OF_MONTH, success ) << endl;
+ *     cout << "DAY_OF_YEAR: " << calendar->get( Calendar::DAY_OF_YEAR, success ) << endl;
+ *     cout << "DAY_OF_WEEK: " << calendar->get( Calendar::DAY_OF_WEEK, success ) << endl;
+ *     cout << "DAY_OF_WEEK_IN_MONTH: " << calendar->get( Calendar::DAY_OF_WEEK_IN_MONTH, success ) << endl;
+ *     cout << "AM_PM: " << calendar->get( Calendar::AM_PM, success ) << endl;
+ *     cout << "HOUR: " << calendar->get( Calendar::HOUR, success ) << endl;
+ *     cout << "HOUR_OF_DAY: " << calendar->get( Calendar::HOUR_OF_DAY, success ) << endl;
+ *     cout << "MINUTE: " << calendar->get( Calendar::MINUTE, success ) << endl;
+ *     cout << "SECOND: " << calendar->get( Calendar::SECOND, success ) << endl;
+ *     cout << "MILLISECOND: " << calendar->get( Calendar::MILLISECOND, success ) << endl;
+ *     cout << "ZONE_OFFSET: " << (calendar->get( Calendar::ZONE_OFFSET, success )/(60*60*1000)) << endl; // in hours
+ *     cout << "DST_OFFSET: " << (calendar->get( Calendar::DST_OFFSET, success )/(60*60*1000)) << endl; // in hours
+ *
+ *     if (U_FAILURE(success)) {
+ *         cout << "An error occured. success=" << u_errorName(success) << endl;
+ *     }
+ *
+ *     delete ids;
+ *     delete calendar; // also deletes pdt
+ * \endcode
+ * </pre>
+ * @stable ICU 2.0
+ */
+class U_I18N_API GregorianCalendar: public Calendar {
+public:
+
+    /**
+     * Useful constants for GregorianCalendar and TimeZone.
+     * @stable ICU 2.0
+     */
+    enum EEras {
+        BC,
+        AD
+    };
+
+    /**
+     * Constructs a default GregorianCalendar using the current time in the default time
+     * zone with the default locale.
+     *
+     * @param success  Indicates the status of GregorianCalendar object construction.
+     *                 Returns U_ZERO_ERROR if constructed successfully.
+     * @stable ICU 2.0
+     */
+    GregorianCalendar(UErrorCode& success);
+
+    /**
+     * Constructs a GregorianCalendar based on the current time in the given time zone
+     * with the default locale. Clients are no longer responsible for deleting the given
+     * time zone object after it's adopted.
+     *
+     * @param zoneToAdopt     The given timezone.
+     * @param success  Indicates the status of GregorianCalendar object construction.
+     *                 Returns U_ZERO_ERROR if constructed successfully.
+     * @stable ICU 2.0
+     */
+    GregorianCalendar(TimeZone* zoneToAdopt, UErrorCode& success);
+
+    /**
+     * Constructs a GregorianCalendar based on the current time in the given time zone
+     * with the default locale.
+     *
+     * @param zone     The given timezone.
+     * @param success  Indicates the status of GregorianCalendar object construction.
+     *                 Returns U_ZERO_ERROR if constructed successfully.
+     * @stable ICU 2.0
+     */
+    GregorianCalendar(const TimeZone& zone, UErrorCode& success);
+
+    /**
+     * Constructs a GregorianCalendar based on the current time in the default time zone
+     * with the given locale.
+     *
+     * @param aLocale  The given locale.
+     * @param success  Indicates the status of GregorianCalendar object construction.
+     *                 Returns U_ZERO_ERROR if constructed successfully.
+     * @stable ICU 2.0
+     */
+    GregorianCalendar(const Locale& aLocale, UErrorCode& success);
+
+    /**
+     * Constructs a GregorianCalendar based on the current time in the given time zone
+     * with the given locale. Clients are no longer responsible for deleting the given
+     * time zone object after it's adopted.
+     *
+     * @param zoneToAdopt     The given timezone.
+     * @param aLocale  The given locale.
+     * @param success  Indicates the status of GregorianCalendar object construction.
+     *                 Returns U_ZERO_ERROR if constructed successfully.
+     * @stable ICU 2.0
+     */
+    GregorianCalendar(TimeZone* zoneToAdopt, const Locale& aLocale, UErrorCode& success);
+
+    /**
+     * Constructs a GregorianCalendar based on the current time in the given time zone
+     * with the given locale.
+     *
+     * @param zone     The given timezone.
+     * @param aLocale  The given locale.
+     * @param success  Indicates the status of GregorianCalendar object construction.
+     *                 Returns U_ZERO_ERROR if constructed successfully.
+     * @stable ICU 2.0
+     */
+    GregorianCalendar(const TimeZone& zone, const Locale& aLocale, UErrorCode& success);
+
+    /**
+     * Constructs a GregorianCalendar with the given AD date set in the default time
+     * zone with the default locale.
+     *
+     * @param year     The value used to set the YEAR time field in the calendar.
+     * @param month    The value used to set the MONTH time field in the calendar. Month
+     *                 value is 0-based. e.g., 0 for January.
+     * @param date     The value used to set the DATE time field in the calendar.
+     * @param success  Indicates the status of GregorianCalendar object construction.
+     *                 Returns U_ZERO_ERROR if constructed successfully.
+     * @stable ICU 2.0
+     */
+    GregorianCalendar(int32_t year, int32_t month, int32_t date, UErrorCode& success);
+
+    /**
+     * Constructs a GregorianCalendar with the given AD date and time set for the
+     * default time zone with the default locale.
+     *
+     * @param year     The value used to set the YEAR time field in the calendar.
+     * @param month    The value used to set the MONTH time field in the calendar. Month
+     *                 value is 0-based. e.g., 0 for January.
+     * @param date     The value used to set the DATE time field in the calendar.
+     * @param hour     The value used to set the HOUR_OF_DAY time field in the calendar.
+     * @param minute   The value used to set the MINUTE time field in the calendar.
+     * @param success  Indicates the status of GregorianCalendar object construction.
+     *                 Returns U_ZERO_ERROR if constructed successfully.
+     * @stable ICU 2.0
+     */
+    GregorianCalendar(int32_t year, int32_t month, int32_t date, int32_t hour, int32_t minute, UErrorCode& success);
+
+    /**
+     * Constructs a GregorianCalendar with the given AD date and time set for the
+     * default time zone with the default locale.
+     *
+     * @param year     The value used to set the YEAR time field in the calendar.
+     * @param month    The value used to set the MONTH time field in the calendar. Month
+     *                 value is 0-based. e.g., 0 for January.
+     * @param date     The value used to set the DATE time field in the calendar.
+     * @param hour     The value used to set the HOUR_OF_DAY time field in the calendar.
+     * @param minute   The value used to set the MINUTE time field in the calendar.
+     * @param second   The value used to set the SECOND time field in the calendar.
+     * @param success  Indicates the status of GregorianCalendar object construction.
+     *                 Returns U_ZERO_ERROR if constructed successfully.
+     * @stable ICU 2.0
+     */
+    GregorianCalendar(int32_t year, int32_t month, int32_t date, int32_t hour, int32_t minute, int32_t second, UErrorCode& success);
+
+    /**
+     * Destructor
+     * @stable ICU 2.0
+     */
+    virtual ~GregorianCalendar();
+
+    /**
+     * Copy constructor
+     * @param source    the object to be copied.
+     * @stable ICU 2.0
+     */
+    GregorianCalendar(const GregorianCalendar& source);
+
+    /**
+     * Default assignment operator
+     * @param right    the object to be copied.
+     * @stable ICU 2.0
+     */
+    GregorianCalendar& operator=(const GregorianCalendar& right);
+
+    /**
+     * Create and return a polymorphic copy of this calendar.
+     * @return    return a polymorphic copy of this calendar.
+     * @stable ICU 2.0
+     */
+    virtual Calendar* clone(void) const;
+
+    /**
+     * Sets the GregorianCalendar change date. This is the point when the switch from
+     * Julian dates to Gregorian dates occurred. Default is 00:00:00 local time, October
+     * 15, 1582. Previous to this time and date will be Julian dates.
+     *
+     * @param date     The given Gregorian cutover date.
+     * @param success  Output param set to success/failure code on exit.
+     * @stable ICU 2.0
+     */
+    void setGregorianChange(UDate date, UErrorCode& success);
+
+    /**
+     * Gets the Gregorian Calendar change date. This is the point when the switch from
+     * Julian dates to Gregorian dates occurred. Default is 00:00:00 local time, October
+     * 15, 1582. Previous to this time and date will be Julian dates.
+     *
+     * @return   The Gregorian cutover time for this calendar.
+     * @stable ICU 2.0
+     */
+    UDate getGregorianChange(void) const;
+
+    /**
+     * Return true if the given year is a leap year. Determination of whether a year is
+     * a leap year is actually very complicated. We do something crude and mostly
+     * correct here, but for a real determination you need a lot of contextual
+     * information. For example, in Sweden, the change from Julian to Gregorian happened
+     * in a complex way resulting in missed leap years and double leap years between
+     * 1700 and 1753. Another example is that after the start of the Julian calendar in
+     * 45 B.C., the leap years did not regularize until 8 A.D. This method ignores these
+     * quirks, and pays attention only to the Julian onset date and the Gregorian
+     * cutover (which can be changed).
+     *
+     * @param year  The given year.
+     * @return      True if the given year is a leap year; false otherwise.
+     * @stable ICU 2.0
+     */
+    UBool isLeapYear(int32_t year) const;
+
+    /**
+     * Returns TRUE if the given Calendar object is equivalent to this
+     * one.  Calendar override.
+     *
+     * @param other the Calendar to be compared with this Calendar   
+     * @stable ICU 2.4
+     */
+    virtual UBool isEquivalentTo(const Calendar& other) const;
+
+    /**
+     * (Overrides Calendar) Rolls up or down by the given amount in the specified field.
+     * For more information, see the documentation for Calendar::roll().
+     *
+     * @param field   The time field.
+     * @param amount  Indicates amount to roll.
+     * @param status  Output param set to success/failure code on exit. If any value
+     *                previously set in the time field is invalid, this will be set to
+     *                an error status.
+     * @deprecated ICU 2.6. Use roll(UCalendarDateFields field, int32_t amount, UErrorCode& status) instead.
+     */
+    virtual void roll(EDateFields field, int32_t amount, UErrorCode& status);
+
+    /**
+     * (Overrides Calendar) Rolls up or down by the given amount in the specified field.
+     * For more information, see the documentation for Calendar::roll().
+     *
+     * @param field   The time field.
+     * @param amount  Indicates amount to roll.
+     * @param status  Output param set to success/failure code on exit. If any value
+     *                previously set in the time field is invalid, this will be set to
+     *                an error status.
+     * @stable ICU 2.6.
+     */
+    virtual void roll(UCalendarDateFields field, int32_t amount, UErrorCode& status);
+
+    /**
+     * Return the minimum value that this field could have, given the current date.
+     * For the Gregorian calendar, this is the same as getMinimum() and getGreatestMinimum().
+     * @param field    the time field.
+     * @return         the minimum value that this field could have, given the current date.
+     * @deprecated ICU 2.6. Use getActualMinimum(UCalendarDateFields field) instead.
+     */
+    int32_t getActualMinimum(EDateFields field) const;
+
+    /**
+     * Return the minimum value that this field could have, given the current date.
+     * For the Gregorian calendar, this is the same as getMinimum() and getGreatestMinimum().
+     * @param field    the time field.
+     * @param status
+     * @return         the minimum value that this field could have, given the current date.
+     * @deprecated ICU 2.6. Use getActualMinimum(UCalendarDateFields field) instead. (Added to ICU 3.0 for signature consistency)
+     */
+    int32_t getActualMinimum(EDateFields field, UErrorCode& status) const;
+
+    /**
+     * Return the minimum value that this field could have, given the current date.
+     * For the Gregorian calendar, this is the same as getMinimum() and getGreatestMinimum().
+     * @param field    the time field.
+     * @param status   error result.
+     * @return         the minimum value that this field could have, given the current date.
+     * @stable ICU 3.0
+     */
+    int32_t getActualMinimum(UCalendarDateFields field, UErrorCode &status) const;
+
+    /**
+     * Return the maximum value that this field could have, given the current date.
+     * For example, with the date "Feb 3, 1997" and the DAY_OF_MONTH field, the actual
+     * maximum would be 28; for "Feb 3, 1996" it s 29.  Similarly for a Hebrew calendar,
+     * for some years the actual maximum for MONTH is 12, and for others 13.
+     * @param field    the time field.
+     * @return         the maximum value that this field could have, given the current date.
+     * @deprecated ICU 2.6. Use getActualMaximum(UCalendarDateFields field) instead.
+     */
+    int32_t getActualMaximum(EDateFields field) const;
+
+    /**
+     * Return the maximum value that this field could have, given the current date.
+     * For example, with the date "Feb 3, 1997" and the DAY_OF_MONTH field, the actual
+     * maximum would be 28; for "Feb 3, 1996" it s 29.  Similarly for a Hebrew calendar,
+     * for some years the actual maximum for MONTH is 12, and for others 13.
+     * @param field    the time field.
+     * @param status   returns any errors that may result from this function call.
+     * @return         the maximum value that this field could have, given the current date.
+     * @stable ICU 2.6
+     */
+    virtual int32_t getActualMaximum(UCalendarDateFields field, UErrorCode& status) const;
+
+    /**
+     * (Overrides Calendar) Return true if the current date for this Calendar is in
+     * Daylight Savings Time. Recognizes DST_OFFSET, if it is set.
+     *
+     * @param status Fill-in parameter which receives the status of this operation.
+     * @return   True if the current date for this Calendar is in Daylight Savings Time,
+     *           false, otherwise.
+     * @stable ICU 2.0
+     */
+    virtual UBool inDaylightTime(UErrorCode& status) const;
+
+public:
+
+    /**
+     * Override Calendar Returns a unique class ID POLYMORPHICALLY. Pure virtual
+     * override. This method is to implement a simple version of RTTI, since not all C++
+     * compilers support genuine RTTI. Polymorphic operator==() and clone() methods call
+     * this method.
+     *
+     * @return   The class ID for this object. All objects of a given class have the
+     *           same class ID. Objects of other classes have different class IDs.
+     * @stable ICU 2.0
+     */
+    virtual UClassID getDynamicClassID(void) const;
+
+    /**
+     * Return the class ID for this class. This is useful only for comparing to a return
+     * value from getDynamicClassID(). For example:
+     *
+     *      Base* polymorphic_pointer = createPolymorphicObject();
+     *      if (polymorphic_pointer->getDynamicClassID() ==
+     *          Derived::getStaticClassID()) ...
+     *
+     * @return   The class ID for all objects of this class.
+     * @stable ICU 2.0
+     */
+    static UClassID U_EXPORT2 getStaticClassID(void);
+
+    /**
+     * Get the calendar type, "gregorian", for use in DateFormatSymbols.
+     *
+     * @return calendar type
+     * @internal
+     */
+    virtual const char * getType() const;
+
+protected:
+
+    /**
+     * (Overrides Calendar) Converts GMT as milliseconds to time field values.
+     * @param status Fill-in parameter which receives the status of this operation.
+     * @stable ICU 2.0
+     */
+
+ private:
+    GregorianCalendar(); // default constructor not implemented
+
+ protected:
+    /**
+     * Return the ERA.  We need a special method for this because the
+     * default ERA is AD, but a zero (unset) ERA is BC.
+     * @return    the ERA.
+     * @internal
+     */
+    virtual int32_t internalGetEra() const;
+
+    /**
+     * Return the Julian day number of day before the first day of the
+     * given month in the given extended year.  Subclasses should override
+     * this method to implement their calendar system.
+     * @param eyear the extended year
+     * @param month the zero-based month, or 0 if useMonth is false
+     * @param useMonth if false, compute the day before the first day of
+     * the given year, otherwise, compute the day before the first day of
+     * the given month
+     * @return the Julian day number of the day before the first
+     * day of the given month and year
+     * @internal
+     */
+    virtual int32_t handleComputeMonthStart(int32_t eyear, int32_t month,
+                                                   UBool useMonth) const;
+
+    /**
+     * Subclasses may override this.  This method calls
+     * handleGetMonthLength() to obtain the calendar-specific month
+     * length.
+     * @param bestField which field to use to calculate the date 
+     * @return julian day specified by calendar fields.
+     * @internal
+     */
+    virtual int32_t handleComputeJulianDay(UCalendarDateFields bestField)  ;
+
+    /**
+     * Return the number of days in the given month of the given extended
+     * year of this calendar system.  Subclasses should override this
+     * method if they can provide a more correct or more efficient
+     * implementation than the default implementation in Calendar.
+     * @internal
+     */
+    virtual int32_t handleGetMonthLength(int32_t extendedYear, int32_t month) const;
+
+    /**
+     * Return the number of days in the given extended year of this
+     * calendar system.  Subclasses should override this method if they can
+     * provide a more correct or more efficient implementation than the
+     * default implementation in Calendar.
+     * @stable ICU 2.0
+     */
+    virtual int32_t handleGetYearLength(int32_t eyear) const;
+
+    /**
+     * return the length of the given month.
+     * @param month    the given month.
+     * @return    the length of the given month.
+     * @internal
+     */
+    virtual int32_t monthLength(int32_t month) const;
+
+    /**
+     * return the length of the month according to the given year.
+     * @param month    the given month.
+     * @param year     the given year.
+     * @return         the length of the month
+     * @internal
+     */
+    virtual int32_t monthLength(int32_t month, int32_t year) const;
+    
+    /**
+     * return the length of the given year.
+     * @param year    the given year.
+     * @return        the length of the given year.
+     * @internal
+     */
+    int32_t yearLength(int32_t year) const;
+    
+    /**
+     * return the length of the year field.
+     * @return    the length of the year field
+     * @internal
+     */
+    int32_t yearLength(void) const;
+
+    /**
+     * After adjustments such as add(MONTH), add(YEAR), we don't want the
+     * month to jump around.  E.g., we don't want Jan 31 + 1 month to go to Mar
+     * 3, we want it to go to Feb 28.  Adjustments which might run into this
+     * problem call this method to retain the proper month.
+     * @internal
+     */
+    void pinDayOfMonth(void);
+
+    /**
+     * Return the day number with respect to the epoch.  January 1, 1970 (Gregorian)
+     * is day zero.
+     * @param status Fill-in parameter which receives the status of this operation.
+     * @return       the day number with respect to the epoch.  
+     * @internal
+     */
+    virtual UDate getEpochDay(UErrorCode& status);
+
+    /**
+     * Subclass API for defining limits of different types.
+     * Subclasses must implement this method to return limits for the
+     * following fields:
+     *
+     * <pre>UCAL_ERA
+     * UCAL_YEAR
+     * UCAL_MONTH
+     * UCAL_WEEK_OF_YEAR
+     * UCAL_WEEK_OF_MONTH
+     * UCAL_DATE (DAY_OF_MONTH on Java)
+     * UCAL_DAY_OF_YEAR
+     * UCAL_DAY_OF_WEEK_IN_MONTH
+     * UCAL_YEAR_WOY
+     * UCAL_EXTENDED_YEAR</pre>
+     *
+     * @param field one of the above field numbers
+     * @param limitType one of <code>MINIMUM</code>, <code>GREATEST_MINIMUM</code>,
+     * <code>LEAST_MAXIMUM</code>, or <code>MAXIMUM</code>
+     * @internal
+     */
+    virtual int32_t handleGetLimit(UCalendarDateFields field, ELimitType limitType) const;
+
+    /**
+     * Return the extended year defined by the current fields.  This will
+     * use the UCAL_EXTENDED_YEAR field or the UCAL_YEAR and supra-year fields (such
+     * as UCAL_ERA) specific to the calendar system, depending on which set of
+     * fields is newer.
+     * @return the extended year
+     * @internal
+     */
+    virtual int32_t handleGetExtendedYear();
+
+    /** 
+     * Subclasses may override this to convert from week fields 
+     * (YEAR_WOY and WEEK_OF_YEAR) to an extended year in the case
+     * where YEAR, EXTENDED_YEAR are not set.
+     * The Gregorian implementation assumes a yearWoy in gregorian format, according to the current era.
+     * @return the extended year, UCAL_EXTENDED_YEAR
+     * @internal
+     */
+    virtual int32_t handleGetExtendedYearFromWeekFields(int32_t yearWoy, int32_t woy);
+
+
+    /**
+     * Subclasses may override this method to compute several fields
+     * specific to each calendar system.  These are:
+     *
+     * <ul><li>ERA
+     * <li>YEAR
+     * <li>MONTH
+     * <li>DAY_OF_MONTH
+     * <li>DAY_OF_YEAR
+     * <li>EXTENDED_YEAR</ul>
+     *
+     * <p>The GregorianCalendar implementation implements
+     * a calendar with the specified Julian/Gregorian cutover date.
+     * @internal
+     */
+    virtual void handleComputeFields(int32_t julianDay, UErrorCode &status);
+
+ private:
+    /**
+     * Compute the julian day number of the given year.
+     * @param isGregorian    if true, using Gregorian calendar, otherwise using Julian calendar
+     * @param year           the given year.
+     * @param isLeap         true if the year is a leap year.       
+     * @return 
+     */
+    static double computeJulianDayOfYear(UBool isGregorian, int32_t year,
+                                         UBool& isLeap);
+    
+    /**
+     * Validates the values of the set time fields.  True if they're all valid.
+     * @return    True if the set time fields are all valid.
+     */
+    UBool validateFields(void) const;
+
+    /**
+     * Validates the value of the given time field.  True if it's valid.
+     */
+    UBool boundsCheck(int32_t value, UCalendarDateFields field) const;
+
+    /**
+     * Return the pseudo-time-stamp for two fields, given their
+     * individual pseudo-time-stamps.  If either of the fields
+     * is unset, then the aggregate is unset.  Otherwise, the
+     * aggregate is the later of the two stamps.
+     * @param stamp_a    One given field.
+     * @param stamp_b    Another given field.
+     * @return the pseudo-time-stamp for two fields
+     */
+    int32_t aggregateStamp(int32_t stamp_a, int32_t stamp_b);
+
+    /**
+     * The point at which the Gregorian calendar rules are used, measured in
+     * milliseconds from the standard epoch.  Default is October 15, 1582
+     * (Gregorian) 00:00:00 UTC, that is, October 4, 1582 (Julian) is followed
+     * by October 15, 1582 (Gregorian).  This corresponds to Julian day number
+     * 2299161. This is measured from the standard epoch, not in Julian Days.
+     * @internal
+     */
+    UDate                fGregorianCutover;
+
+    /**
+     * Julian day number of the Gregorian cutover
+     */
+    int32_t             fCutoverJulianDay;
+
+    /**
+     * Midnight, local time (using this Calendar's TimeZone) at or before the
+     * gregorianCutover. This is a pure date value with no time of day or
+     * timezone component.
+     */
+    UDate                 fNormalizedGregorianCutover;// = gregorianCutover;
+
+    /**
+     * The year of the gregorianCutover, with 0 representing
+     * 1 BC, -1 representing 2 BC, etc.
+     */
+    int32_t fGregorianCutoverYear;// = 1582;
+
+    /**
+     * The year of the gregorianCutover, with 0 representing
+     * 1 BC, -1 representing 2 BC, etc.
+     */
+    int32_t fGregorianCutoverJulianDay;// = 2299161;
+
+    /**
+     * Converts time as milliseconds to Julian date. The Julian date used here is not a
+     * true Julian date, since it is measured from midnight, not noon.
+     *
+     * @param millis  The given milliseconds.
+     * @return        The Julian date number.
+     */
+    static double millisToJulianDay(UDate millis);
+
+    /**
+     * Converts Julian date to time as milliseconds. The Julian date used here is not a
+     * true Julian date, since it is measured from midnight, not noon.
+     *
+     * @param julian  The given Julian date number.
+     * @return        Time as milliseconds.
+     */
+    static UDate julianDayToMillis(double julian);
+
+    /**
+     * Used by handleComputeJulianDay() and handleComputeMonthStart().
+     * Temporary field indicating whether the calendar is currently Gregorian as opposed to Julian.
+     */
+    UBool fIsGregorian;
+
+    /**
+     * Used by handleComputeJulianDay() and handleComputeMonthStart().
+     * Temporary field indicating that the sense of the gregorian cutover should be inverted
+     * to handle certain calculations on and around the cutover date.
+     */
+    UBool fInvertGregorian;
+
+
+ public: // internal implementation
+
+    /**
+     * @internal 
+     * @return TRUE if this calendar has the notion of a default century
+     */
+    virtual UBool haveDefaultCentury() const;
+
+    /**
+     * @internal
+     * @return the start of the default century
+     */
+    virtual UDate defaultCenturyStart() const;
+
+    /**
+     * @internal 
+     * @return the beginning year of the default century
+     */
+    virtual int32_t defaultCenturyStartYear() const;
+
+ private:
+    /**
+     * The system maintains a static default century start date.  This is initialized
+     * the first time it is used.  Before then, it is set to SYSTEM_DEFAULT_CENTURY to
+     * indicate an uninitialized state.  Once the system default century date and year
+     * are set, they do not change.
+     */
+    static UDate         fgSystemDefaultCenturyStart;
+
+    /**
+     * See documentation for systemDefaultCenturyStart.
+     */
+    static int32_t          fgSystemDefaultCenturyStartYear;
+
+    /**
+     * Default value that indicates the defaultCenturyStartYear is unitialized
+     */
+    static const int32_t    fgSystemDefaultCenturyYear;
+
+    /**
+     * Default value that indicates the UDate of the beginning of the system default century
+     */
+    static const UDate        fgSystemDefaultCentury;
+
+    /**
+     * Returns the beginning date of the 100-year window that dates with 2-digit years
+     * are considered to fall within.
+     * @return    the beginning date of the 100-year window that dates with 2-digit years
+     *            are considered to fall within.
+     */
+    UDate         internalGetDefaultCenturyStart(void) const;
+
+    /**
+     * Returns the first year of the 100-year window that dates with 2-digit years
+     * are considered to fall within.
+     * @return    the first year of the 100-year window that dates with 2-digit years
+     *            are considered to fall within.
+     */
+    int32_t          internalGetDefaultCenturyStartYear(void) const;
+
+    /**
+     * Initializes the 100-year window that dates with 2-digit years are considered
+     * to fall within so that its start date is 80 years before the current time.
+     */
+    static void  initializeSystemDefaultCentury(void);
+
+};
+
+U_NAMESPACE_END
+
+#endif /* #if !UCONFIG_NO_FORMATTING */
+
+#endif // _GREGOCAL
+//eof
+

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/locid.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/locid.h b/src/apps/couch_collate/platform/osx/icu/unicode/locid.h
new file mode 100644
index 0000000..a3cc23b
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/locid.h
@@ -0,0 +1,765 @@
+/*
+******************************************************************************
+*
+*   Copyright (C) 1996-2006, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+*
+******************************************************************************
+*
+* File locid.h
+*
+* Created by: Helena Shih
+*
+* Modification History:
+*
+*   Date        Name        Description
+*   02/11/97    aliu        Changed gLocPath to fgLocPath and added methods to
+*                           get and set it.
+*   04/02/97    aliu        Made operator!= inline; fixed return value of getName().
+*   04/15/97    aliu        Cleanup for AIX/Win32.
+*   04/24/97    aliu        Numerous changes per code review.
+*   08/18/98    stephen     Added tokenizeString(),changed getDisplayName()
+*   09/08/98    stephen     Moved definition of kEmptyString for Mac Port
+*   11/09/99    weiv        Added const char * getName() const;
+*   04/12/00    srl         removing unicodestring api's and cached hash code
+*   08/10/01    grhoten     Change the static Locales to accessor functions
+******************************************************************************
+*/
+
+#ifndef LOCID_H
+#define LOCID_H
+
+#include "unicode/utypes.h"
+#include "unicode/uobject.h"
+#include "unicode/unistr.h"
+#include "unicode/putil.h"
+#include "unicode/uloc.h"
+#include "unicode/strenum.h"
+
+/**
+ * \file
+ * \brief C++ API: Locale ID object.
+ */
+
+/**
+ * A <code>Locale</code> object represents a specific geographical, political,
+ * or cultural region. An operation that requires a <code>Locale</code> to perform
+ * its task is called <em>locale-sensitive</em> and uses the <code>Locale</code>
+ * to tailor information for the user. For example, displaying a number
+ * is a locale-sensitive operation--the number should be formatted
+ * according to the customs/conventions of the user's native country,
+ * region, or culture.
+ *
+ * The Locale class is not suitable for subclassing.
+ *
+ * <P>
+ * You can create a <code>Locale</code> object using the constructor in
+ * this class:
+ * \htmlonly<blockquote>\endhtmlonly
+ * <pre>
+ *       Locale( const   char*  language,
+ *               const   char*  country,
+ *               const   char*  variant);
+ * </pre>
+ * \htmlonly</blockquote>\endhtmlonly
+ * The first argument to the constructors is a valid <STRONG>ISO
+ * Language Code.</STRONG> These codes are the lower-case two-letter
+ * codes as defined by ISO-639.
+ * You can find a full list of these codes at:
+ * <BR><a href ="http://www.loc.gov/standards/iso639-2/">
+ * http://www.loc.gov/standards/iso639-2/</a>
+ *
+ * <P>
+ * The second argument to the constructors is a valid <STRONG>ISO Country
+ * Code.</STRONG> These codes are the upper-case two-letter codes
+ * as defined by ISO-3166.
+ * You can find a full list of these codes at a number of sites, such as:
+ * <BR><a href="http://www.iso.org/iso/en/prods-services/iso3166ma/index.html">
+ * http://www.iso.org/iso/en/prods-services/iso3166ma/index.html</a>
+ *
+ * <P>
+ * The third constructor requires a third argument--the <STRONG>Variant.</STRONG>
+ * The Variant codes are vendor and browser-specific.
+ * For example, use REVISED for a langauge's revised script orthography, and POSIX for POSIX.
+ * Where there are two variants, separate them with an underscore, and
+ * put the most important one first. For
+ * example, a Traditional Spanish collation might be referenced, with
+ * "ES", "ES", "Traditional_POSIX".
+ *
+ * <P>
+ * Because a <code>Locale</code> object is just an identifier for a region,
+ * no validity check is performed when you construct a <code>Locale</code>.
+ * If you want to see whether particular resources are available for the
+ * <code>Locale</code> you construct, you must query those resources. For
+ * example, ask the <code>NumberFormat</code> for the locales it supports
+ * using its <code>getAvailableLocales</code> method.
+ * <BR><STRONG>Note:</STRONG> When you ask for a resource for a particular
+ * locale, you get back the best available match, not necessarily
+ * precisely what you asked for. For more information, look at
+ * <code>ResourceBundle</code>.
+ *
+ * <P>
+ * The <code>Locale</code> class provides a number of convenient constants
+ * that you can use to create <code>Locale</code> objects for commonly used
+ * locales. For example, the following refers to a <code>Locale</code> object
+ * for the United States:
+ * \htmlonly<blockquote>\endhtmlonly
+ * <pre>
+ *       Locale::getUS()
+ * </pre>
+ * \htmlonly</blockquote>\endhtmlonly
+ *
+ * <P>
+ * Once you've created a <code>Locale</code> you can query it for information about
+ * itself. Use <code>getCountry</code> to get the ISO Country Code and
+ * <code>getLanguage</code> to get the ISO Language Code. You can
+ * use <code>getDisplayCountry</code> to get the
+ * name of the country suitable for displaying to the user. Similarly,
+ * you can use <code>getDisplayLanguage</code> to get the name of
+ * the language suitable for displaying to the user. Interestingly,
+ * the <code>getDisplayXXX</code> methods are themselves locale-sensitive
+ * and have two versions: one that uses the default locale and one
+ * that takes a locale as an argument and displays the name or country in
+ * a language appropriate to that locale.
+ *
+ * <P>
+ * ICU provides a number of classes that perform locale-sensitive
+ * operations. For example, the <code>NumberFormat</code> class formats
+ * numbers, currency, or percentages in a locale-sensitive manner. Classes
+ * such as <code>NumberFormat</code> have a number of convenience methods
+ * for creating a default object of that type. For example, the
+ * <code>NumberFormat</code> class provides these three convenience methods
+ * for creating a default <code>NumberFormat</code> object:
+ * \htmlonly<blockquote>\endhtmlonly
+ * <pre>
+ *     UErrorCode success = U_ZERO_ERROR;
+ *     Locale myLocale;
+ *     NumberFormat *nf;
+ *
+ *     nf = NumberFormat::createInstance( success );          delete nf;
+ *     nf = NumberFormat::createCurrencyInstance( success );  delete nf;
+ *     nf = NumberFormat::createPercentInstance( success );   delete nf;
+ * </pre>
+ * \htmlonly</blockquote>\endhtmlonly
+ * Each of these methods has two variants; one with an explicit locale
+ * and one without; the latter using the default locale.
+ * \htmlonly<blockquote>\endhtmlonly
+ * <pre>
+ *     nf = NumberFormat::createInstance( myLocale, success );          delete nf;
+ *     nf = NumberFormat::createCurrencyInstance( myLocale, success );  delete nf;
+ *     nf = NumberFormat::createPercentInstance( myLocale, success );   delete nf;
+ * </pre>
+ * \htmlonly</blockquote>\endhtmlonly
+ * A <code>Locale</code> is the mechanism for identifying the kind of object
+ * (<code>NumberFormat</code>) that you would like to get. The locale is
+ * <STRONG>just</STRONG> a mechanism for identifying objects,
+ * <STRONG>not</STRONG> a container for the objects themselves.
+ *
+ * <P>
+ * Each class that performs locale-sensitive operations allows you
+ * to get all the available objects of that type. You can sift
+ * through these objects by language, country, or variant,
+ * and use the display names to present a menu to the user.
+ * For example, you can create a menu of all the collation objects
+ * suitable for a given language. Such classes implement these
+ * three class methods:
+ * \htmlonly<blockquote>\endhtmlonly
+ * <pre>
+ *       static Locale* getAvailableLocales(int32_t& numLocales)
+ *       static UnicodeString& getDisplayName(const Locale&  objectLocale,
+ *                                            const Locale&  displayLocale,
+ *                                            UnicodeString& displayName)
+ *       static UnicodeString& getDisplayName(const Locale&  objectLocale,
+ *                                            UnicodeString& displayName)
+ * </pre>
+ * \htmlonly</blockquote>\endhtmlonly
+ *
+ * @stable ICU 2.0
+ * @see ResourceBundle
+ */
+U_NAMESPACE_BEGIN
+class U_COMMON_API Locale : public UObject {
+public:
+    /** Useful constant for this language. @stable ICU 2.0 */
+    static const Locale &U_EXPORT2 getEnglish(void);
+    /** Useful constant for this language. @stable ICU 2.0 */
+    static const Locale &U_EXPORT2 getFrench(void);
+    /** Useful constant for this language. @stable ICU 2.0 */
+    static const Locale &U_EXPORT2 getGerman(void);
+    /** Useful constant for this language. @stable ICU 2.0 */
+    static const Locale &U_EXPORT2 getItalian(void);
+    /** Useful constant for this language. @stable ICU 2.0 */
+    static const Locale &U_EXPORT2 getJapanese(void);
+    /** Useful constant for this language. @stable ICU 2.0 */
+    static const Locale &U_EXPORT2 getKorean(void);
+    /** Useful constant for this language. @stable ICU 2.0 */
+    static const Locale &U_EXPORT2 getChinese(void);
+    /** Useful constant for this language. @stable ICU 2.0 */
+    static const Locale &U_EXPORT2 getSimplifiedChinese(void);
+    /** Useful constant for this language. @stable ICU 2.0 */
+    static const Locale &U_EXPORT2 getTraditionalChinese(void);
+
+    /** Useful constant for this country/region. @stable ICU 2.0 */
+    static const Locale &U_EXPORT2 getFrance(void);
+    /** Useful constant for this country/region. @stable ICU 2.0 */
+    static const Locale &U_EXPORT2 getGermany(void);
+    /** Useful constant for this country/region. @stable ICU 2.0 */
+    static const Locale &U_EXPORT2 getItaly(void);
+    /** Useful constant for this country/region. @stable ICU 2.0 */
+    static const Locale &U_EXPORT2 getJapan(void);
+    /** Useful constant for this country/region. @stable ICU 2.0 */
+    static const Locale &U_EXPORT2 getKorea(void);
+    /** Useful constant for this country/region. @stable ICU 2.0 */
+    static const Locale &U_EXPORT2 getChina(void);
+    /** Useful constant for this country/region. @stable ICU 2.0 */
+    static const Locale &U_EXPORT2 getPRC(void);
+    /** Useful constant for this country/region. @stable ICU 2.0 */
+    static const Locale &U_EXPORT2 getTaiwan(void);
+    /** Useful constant for this country/region. @stable ICU 2.0 */
+    static const Locale &U_EXPORT2 getUK(void);
+    /** Useful constant for this country/region. @stable ICU 2.0 */
+    static const Locale &U_EXPORT2 getUS(void);
+    /** Useful constant for this country/region. @stable ICU 2.0 */
+    static const Locale &U_EXPORT2 getCanada(void);
+    /** Useful constant for this country/region. @stable ICU 2.0 */
+    static const Locale &U_EXPORT2 getCanadaFrench(void);
+
+
+    /**
+     * Construct a default locale object, a Locale for the default locale ID.
+     *
+     * @see getDefault
+     * @see uloc_getDefault
+     * @stable ICU 2.0
+     */
+    Locale();
+
+    /**
+     * Construct a locale from language, country, variant.
+     * If an error occurs, then the constructed object will be "bogus"
+     * (isBogus() will return TRUE).
+     *
+     * @param language Lowercase two-letter or three-letter ISO-639 code.
+     *  This parameter can instead be an ICU style C locale (e.g. "en_US"),
+     *  but the other parameters must not be used.
+     *  This parameter can be NULL; if so,
+     *  the locale is initialized to match the current default locale.
+     *  (This is the same as using the default constructor.)
+     *  Please note: The Java Locale class does NOT accept the form
+     *  'new Locale("en_US")' but only 'new Locale("en","US")'
+     *
+     * @param country  Uppercase two-letter ISO-3166 code. (optional)
+     * @param variant  Uppercase vendor and browser specific code. See class
+     *                 description. (optional)
+     * @param keywordsAndValues A string consisting of keyword/values pairs, such as
+     *                 "collation=phonebook;currency=euro"
+     *
+     * @see getDefault
+     * @see uloc_getDefault
+     * @stable ICU 2.0
+     */
+    Locale( const   char * language,
+            const   char * country  = 0,
+            const   char * variant  = 0,
+            const   char * keywordsAndValues = 0);
+
+    /**
+     * Initializes a Locale object from another Locale object.
+     *
+     * @param other The Locale object being copied in.
+     * @stable ICU 2.0
+     */
+    Locale(const    Locale& other);
+
+
+    /**
+     * Destructor
+     * @stable ICU 2.0
+     */
+    virtual ~Locale() ;
+
+    /**
+     * Replaces the entire contents of *this with the specified value.
+     *
+     * @param other The Locale object being copied in.
+     * @return      *this
+     * @stable ICU 2.0
+     */
+    Locale& operator=(const Locale& other);
+
+    /**
+     * Checks if two locale keys are the same.
+     *
+     * @param other The locale key object to be compared with this.
+     * @return      True if the two locale keys are the same, false otherwise.
+     * @stable ICU 2.0
+     */
+    UBool   operator==(const    Locale&     other) const;
+
+    /**
+     * Checks if two locale keys are not the same.
+     *
+     * @param other The locale key object to be compared with this.
+     * @return      True if the two locale keys are not the same, false
+     *              otherwise.
+     * @stable ICU 2.0
+     */
+    UBool   operator!=(const    Locale&     other) const;
+
+    /**
+     * Clone this object.
+     * Clones can be used concurrently in multiple threads.
+     * If an error occurs, then NULL is returned.
+     * The caller must delete the clone.
+     *
+     * @return a clone of this object
+     *
+     * @see getDynamicClassID
+     * @stable ICU 2.8
+     */
+    Locale *clone() const;
+
+    /**
+     * Common methods of getting the current default Locale. Used for the
+     * presentation: menus, dialogs, etc. Generally set once when your applet or
+     * application is initialized, then never reset. (If you do reset the
+     * default locale, you probably want to reload your GUI, so that the change
+     * is reflected in your interface.)
+     *
+     * More advanced programs will allow users to use different locales for
+     * different fields, e.g. in a spreadsheet.
+     *
+     * Note that the initial setting will match the host system.
+     * @return a reference to the Locale object for the default locale ID
+     * @system
+     * @stable ICU 2.0
+     */
+    static const Locale& U_EXPORT2 getDefault(void);
+
+    /**
+     * Sets the default. Normally set once at the beginning of a process,
+     * then never reset.
+     * setDefault() only changes ICU's default locale ID, <strong>not</strong>
+     * the default locale ID of the runtime environment.
+     *
+     * @param newLocale Locale to set to.  If NULL, set to the value obtained
+     *                  from the runtime environement.
+     * @param success The error code.
+     * @system
+     * @stable ICU 2.0
+     */
+    static void U_EXPORT2 setDefault(const Locale& newLocale,
+                                     UErrorCode&   success);
+
+    /**
+     * Creates a locale which has had minimal canonicalization
+     * as per uloc_getName().
+     * @param name The name to create from.  If name is null,
+     *  the default Locale is used.
+     * @return new locale object
+     * @stable ICU 2.0
+     * @see uloc_getName
+     */
+    static Locale U_EXPORT2 createFromName(const char *name);
+
+    /**
+     * Creates a locale from the given string after canonicalizing
+     * the string by calling uloc_canonicalize().
+     * @param name the locale ID to create from.  Must not be NULL.
+     * @return a new locale object corresponding to the given name
+     * @stable ICU 3.0
+     * @see uloc_canonicalize
+     */
+    static Locale U_EXPORT2 createCanonical(const char* name);
+
+    /**
+     * Returns the locale's ISO-639 language code.
+     * @return      An alias to the code
+     * @stable ICU 2.0
+     */
+    inline const char *  getLanguage( ) const;
+
+    /**
+     * Returns the locale's ISO-15924 abbreviation script code.
+     * @return      An alias to the code
+     * @see uscript_getShortName
+     * @see uscript_getCode
+     * @stable ICU 2.8
+     */
+    inline const char *  getScript( ) const;
+
+    /**
+     * Returns the locale's ISO-3166 country code.
+     * @return      An alias to the code
+     * @stable ICU 2.0
+     */
+    inline const char *  getCountry( ) const;
+
+    /**
+     * Returns the locale's variant code.
+     * @return      An alias to the code
+     * @stable ICU 2.0
+     */
+    inline const char *  getVariant( ) const;
+
+    /**
+     * Returns the programmatic name of the entire locale, with the language,
+     * country and variant separated by underbars. If a field is missing, up
+     * to two leading underbars will occur. Example: "en", "de_DE", "en_US_WIN",
+     * "de__POSIX", "fr__MAC", "__MAC", "_MT", "_FR_EURO"
+     * @return      A pointer to "name".
+     * @stable ICU 2.0
+     */
+    inline const char * getName() const;
+
+    /**
+     * Returns the programmatic name of the entire locale as getName would return,
+     * but without keywords.
+     * @return      A pointer to "name".
+     * @see getName
+     * @stable ICU 2.8
+     */
+    const char * getBaseName() const;
+
+
+    /**
+     * Gets the list of keywords for the specified locale.
+     *
+     * @return pointer to StringEnumeration class. Client must dispose of it by calling delete.
+     * @param status Returns any error information while performing this operation.
+     * @stable ICU 2.8
+     */
+    StringEnumeration * createKeywords(UErrorCode &status) const;
+
+    /**
+     * Get the value for a keyword.
+     *
+     * @param keywordName name of the keyword for which we want the value. Case insensitive.
+     * @param status Returns any error information while performing this operation.
+     * @param buffer The buffer to receive the keyword value.
+     * @param bufferCapacity The capacity of receiving buffer
+     * @return the length of keyword value
+     *
+     * @stable ICU 2.8
+     */
+    int32_t getKeywordValue(const char* keywordName, char *buffer, int32_t bufferCapacity, UErrorCode &status) const;
+
+    /**
+     * returns the locale's three-letter language code, as specified
+     * in ISO draft standard ISO-639-2.
+     * @return      An alias to the code, or NULL
+     * @stable ICU 2.0
+     */
+    const char * getISO3Language() const;
+
+    /**
+     * Fills in "name" with the locale's three-letter ISO-3166 country code.
+     * @return      An alias to the code, or NULL
+     * @stable ICU 2.0
+     */
+    const char * getISO3Country() const;
+
+    /**
+     * Returns the Windows LCID value corresponding to this locale.
+     * This value is stored in the resource data for the locale as a one-to-four-digit
+     * hexadecimal number.  If the resource is missing, in the wrong format, or
+     * there is no Windows LCID value that corresponds to this locale, returns 0.
+     * @stable ICU 2.0
+     */
+    uint32_t        getLCID(void) const;
+
+    /**
+     * Fills in "dispLang" with the name of this locale's language in a format suitable for
+     * user display in the default locale.  For example, if the locale's language code is
+     * "fr" and the default locale's language code is "en", this function would set
+     * dispLang to "French".
+     * @param dispLang  Receives the language's display name.
+     * @return          A reference to "dispLang".
+     * @stable ICU 2.0
+     */
+    UnicodeString&  getDisplayLanguage(UnicodeString&   dispLang) const;
+
+    /**
+     * Fills in "dispLang" with the name of this locale's language in a format suitable for
+     * user display in the locale specified by "displayLocale".  For example, if the locale's
+     * language code is "en" and displayLocale's language code is "fr", this function would set
+     * dispLang to "Anglais".
+     * @param displayLocale  Specifies the locale to be used to display the name.  In other words,
+     *                  if the locale's language code is "en", passing Locale::getFrench() for
+     *                  displayLocale would result in "Anglais", while passing Locale::getGerman()
+     *                  for displayLocale would result in "Englisch".
+     * @param dispLang  Receives the language's display name.
+     * @return          A reference to "dispLang".
+     * @stable ICU 2.0
+     */
+    UnicodeString&  getDisplayLanguage( const   Locale&         displayLocale,
+                                                UnicodeString&  dispLang) const;
+
+    /**
+     * Fills in "dispScript" with the name of this locale's script in a format suitable
+     * for user display in the default locale.  For example, if the locale's script code
+     * is "LATN" and the default locale's language code is "en", this function would set
+     * dispScript to "Latin".
+     * @param dispScript    Receives the scripts's display name.
+     * @return              A reference to "dispScript".
+     * @stable ICU 2.8
+     */
+    UnicodeString&  getDisplayScript(          UnicodeString& dispScript) const;
+
+    /**
+     * Fills in "dispScript" with the name of this locale's country in a format suitable
+     * for user display in the locale specified by "displayLocale".  For example, if the locale's
+     * script code is "LATN" and displayLocale's language code is "en", this function would set
+     * dispScript to "Latin".
+     * @param displayLocale      Specifies the locale to be used to display the name.  In other
+     *                      words, if the locale's script code is "LATN", passing
+     *                      Locale::getFrench() for displayLocale would result in "", while
+     *                      passing Locale::getGerman() for displayLocale would result in
+     *                      "".
+     * @param dispScript    Receives the scripts's display name.
+     * @return              A reference to "dispScript".
+     * @stable ICU 2.8
+     */
+    UnicodeString&  getDisplayScript(  const   Locale&         displayLocale,
+                                               UnicodeString&  dispScript) const;
+
+    /**
+     * Fills in "dispCountry" with the name of this locale's country in a format suitable
+     * for user display in the default locale.  For example, if the locale's country code
+     * is "FR" and the default locale's language code is "en", this function would set
+     * dispCountry to "France".
+     * @param dispCountry   Receives the country's display name.
+     * @return              A reference to "dispCountry".
+     * @stable ICU 2.0
+     */
+    UnicodeString&  getDisplayCountry(          UnicodeString& dispCountry) const;
+
+    /**
+     * Fills in "dispCountry" with the name of this locale's country in a format suitable
+     * for user display in the locale specified by "displayLocale".  For example, if the locale's
+     * country code is "US" and displayLocale's language code is "fr", this function would set
+     * dispCountry to "&Eacute;tats-Unis".
+     * @param displayLocale      Specifies the locale to be used to display the name.  In other
+     *                      words, if the locale's country code is "US", passing
+     *                      Locale::getFrench() for displayLocale would result in "&Eacute;tats-Unis", while
+     *                      passing Locale::getGerman() for displayLocale would result in
+     *                      "Vereinigte Staaten".
+     * @param dispCountry   Receives the country's display name.
+     * @return              A reference to "dispCountry".
+     * @stable ICU 2.0
+     */
+    UnicodeString&  getDisplayCountry(  const   Locale&         displayLocale,
+                                                UnicodeString&  dispCountry) const;
+
+    /**
+     * Fills in "dispVar" with the name of this locale's variant code in a format suitable
+     * for user display in the default locale.
+     * @param dispVar   Receives the variant's name.
+     * @return          A reference to "dispVar".
+     * @stable ICU 2.0
+     */
+    UnicodeString&  getDisplayVariant(      UnicodeString& dispVar) const;
+
+    /**
+     * Fills in "dispVar" with the name of this locale's variant code in a format
+     * suitable for user display in the locale specified by "displayLocale".
+     * @param displayLocale  Specifies the locale to be used to display the name.
+     * @param dispVar   Receives the variant's display name.
+     * @return          A reference to "dispVar".
+     * @stable ICU 2.0
+     */
+    UnicodeString&  getDisplayVariant(  const   Locale&         displayLocale,
+                                                UnicodeString&  dispVar) const;
+
+    /**
+     * Fills in "name" with the name of this locale in a format suitable for user display
+     * in the default locale.  This function uses getDisplayLanguage(), getDisplayCountry(),
+     * and getDisplayVariant() to do its work, and outputs the display name in the format
+     * "language (country[,variant])".  For example, if the default locale is en_US, then
+     * fr_FR's display name would be "French (France)", and es_MX_Traditional's display name
+     * would be "Spanish (Mexico,Traditional)".
+     * @param name  Receives the locale's display name.
+     * @return      A reference to "name".
+     * @stable ICU 2.0
+     */
+    UnicodeString&  getDisplayName(         UnicodeString&  name) const;
+
+    /**
+     * Fills in "name" with the name of this locale in a format suitable for user display
+     * in the locale specfied by "displayLocale".  This function uses getDisplayLanguage(),
+     * getDisplayCountry(), and getDisplayVariant() to do its work, and outputs the display
+     * name in the format "language (country[,variant])".  For example, if displayLocale is
+     * fr_FR, then en_US's display name would be "Anglais (&Eacute;tats-Unis)", and no_NO_NY's
+     * display name would be "norv&eacute;gien (Norv&egrave;ge,NY)".
+     * @param displayLocale  Specifies the locale to be used to display the name.
+     * @param name      Receives the locale's display name.
+     * @return          A reference to "name".
+     * @stable ICU 2.0
+     */
+    UnicodeString&  getDisplayName( const   Locale&         displayLocale,
+                                            UnicodeString&  name) const;
+
+    /**
+     * Generates a hash code for the locale.
+     * @stable ICU 2.0
+     */
+    int32_t         hashCode(void) const;
+
+    /**
+     * Sets the locale to bogus
+     * A bogus locale represents a non-existing locale associated
+     * with services that can be instantiated from non-locale data
+     * in addition to locale (for example, collation can be
+     * instantiated from a locale and from a rule set).
+     * @stable ICU 2.1
+     */
+    void setToBogus();
+
+    /**
+     * Gets the bogus state. Locale object can be bogus if it doesn't exist
+     * @return FALSE if it is a real locale, TRUE if it is a bogus locale
+     * @stable ICU 2.1
+     */
+    UBool isBogus(void) const;
+
+    /**
+     * Returns a list of all installed locales.
+     * @param count Receives the number of locales in the list.
+     * @return      A pointer to an array of Locale objects.  This array is the list
+     *              of all locales with installed resource files.  The called does NOT
+     *              get ownership of this list, and must NOT delete it.
+     * @stable ICU 2.0
+     */
+    static const Locale* U_EXPORT2 getAvailableLocales(int32_t& count);
+
+    /**
+     * Gets a list of all available 2-letter country codes defined in ISO 639.  This is a
+     * pointer to an array of pointers to arrays of char.  All of these pointers are
+     * owned by ICU-- do not delete them, and do not write through them.  The array is
+     * terminated with a null pointer.
+     * @return a list of all available country codes
+     * @stable ICU 2.0
+     */
+    static const char* const* U_EXPORT2 getISOCountries();
+
+    /**
+     * Gets a list of all available language codes defined in ISO 639.  This is a pointer
+     * to an array of pointers to arrays of char.  All of these pointers are owned
+     * by ICU-- do not delete them, and do not write through them.  The array is
+     * terminated with a null pointer.
+     * @return a list of all available language codes
+     * @stable ICU 2.0
+     */
+    static const char* const* U_EXPORT2 getISOLanguages();
+
+    /**
+     * ICU "poor man's RTTI", returns a UClassID for this class.
+     *
+     * @stable ICU 2.2
+     */
+    static UClassID U_EXPORT2 getStaticClassID();
+
+    /**
+     * ICU "poor man's RTTI", returns a UClassID for the actual class.
+     *
+     * @stable ICU 2.2
+     */
+    virtual UClassID getDynamicClassID() const;
+
+protected: /* only protected for testing purposes. DO NOT USE. */
+    /**
+     * Set this from a single POSIX style locale string.
+     * @internal
+     */
+    void setFromPOSIXID(const char *posixID);
+
+private:
+    /**
+     * Initialize the locale object with a new name.
+     * Was deprecated - used in implementation - moved internal
+     *
+     * @param cLocaleID The new locale name.
+     */
+    Locale& init(const char* cLocaleID, UBool canonicalize);
+
+    /*
+     * Internal constructor to allow construction of a locale object with
+     *   NO side effects.   (Default constructor tries to get
+     *   the default locale.)
+     */
+    enum ELocaleType {
+        eBOGUS
+    };
+    Locale(ELocaleType);
+
+    /**
+     * Initialize the locale cache for commonly used locales
+     */
+    static Locale *getLocaleCache(void);
+
+    char language[ULOC_LANG_CAPACITY];
+    char script[ULOC_SCRIPT_CAPACITY];
+    char country[ULOC_COUNTRY_CAPACITY];
+    int32_t variantBegin;
+    char* fullName;
+    char fullNameBuffer[ULOC_FULLNAME_CAPACITY];
+    // name without keywords
+    char* baseName;
+    char baseNameBuffer[ULOC_FULLNAME_CAPACITY];
+
+    UBool fIsBogus;
+
+    static const Locale &getLocale(int locid);
+
+    /**
+     * A friend to allow the default locale to be set by either the C or C++ API.
+     * @internal
+     */
+    friend void locale_set_default_internal(const char *);
+};
+
+inline UBool
+Locale::operator!=(const    Locale&     other) const
+{
+    return !operator==(other);
+}
+
+inline const char *
+Locale::getCountry() const
+{
+    return country;
+}
+
+inline const char *
+Locale::getLanguage() const
+{
+    return language;
+}
+
+inline const char *
+Locale::getScript() const
+{
+    return script;
+}
+
+inline const char *
+Locale::getVariant() const
+{
+    return &fullName[variantBegin];
+}
+
+inline const char *
+Locale::getName() const
+{
+    return fullName;
+}
+
+inline UBool
+Locale::isBogus(void) const {
+    return fIsBogus;
+}
+
+U_NAMESPACE_END
+
+#endif
+

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/measfmt.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/measfmt.h b/src/apps/couch_collate/platform/osx/icu/unicode/measfmt.h
new file mode 100644
index 0000000..a5af55e
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/measfmt.h
@@ -0,0 +1,77 @@
+/*
+**********************************************************************
+* Copyright (c) 2004-2006, International Business Machines
+* Corporation and others.  All Rights Reserved.
+**********************************************************************
+* Author: Alan Liu
+* Created: April 20, 2004
+* Since: ICU 3.0
+**********************************************************************
+*/
+#ifndef MEASUREFORMAT_H
+#define MEASUREFORMAT_H
+
+#include "unicode/utypes.h"
+
+#if !UCONFIG_NO_FORMATTING
+
+#include "unicode/format.h"
+
+/**
+ * \file 
+ * \brief C++ API: Formatter for measure objects.
+ */
+
+U_NAMESPACE_BEGIN
+
+/**
+ * 
+ * A formatter for measure objects.  This is an abstract base class.
+ *
+ * <p>To format or parse a measure object, first create a formatter
+ * object using a MeasureFormat factory method.  Then use that
+ * object's format and parse methods.
+ *
+ * <p>This is an abstract class.
+ *
+ * @see Format
+ * @author Alan Liu
+ * @stable ICU 3.0
+ */
+class U_I18N_API MeasureFormat : public Format {
+
+ public:
+
+    /**
+     * Return a formatter for CurrencyAmount objects in the given
+     * locale.
+     * @param locale desired locale
+     * @param ec input-output error code
+     * @return a formatter object, or NULL upon error
+     * @stable ICU 3.0
+     */
+    static MeasureFormat* U_EXPORT2 createCurrencyFormat(const Locale& locale,
+                                               UErrorCode& ec);
+
+    /**
+     * Return a formatter for CurrencyAmount objects in the default
+     * locale.
+     * @param ec input-output error code
+     * @return a formatter object, or NULL upon error
+     * @stable ICU 3.0
+     */
+    static MeasureFormat* U_EXPORT2 createCurrencyFormat(UErrorCode& ec);
+
+ protected:
+
+    /**
+     * Default constructor.
+     * @stable ICU 3.0
+     */
+    MeasureFormat();
+};
+
+U_NAMESPACE_END
+
+#endif // #if !UCONFIG_NO_FORMATTING
+#endif // #ifndef MEASUREFORMAT_H

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/measunit.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/measunit.h b/src/apps/couch_collate/platform/osx/icu/unicode/measunit.h
new file mode 100644
index 0000000..9a210e6
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/measunit.h
@@ -0,0 +1,71 @@
+/*
+**********************************************************************
+* Copyright (c) 2004-2006, International Business Machines
+* Corporation and others.  All Rights Reserved.
+**********************************************************************
+* Author: Alan Liu
+* Created: April 26, 2004
+* Since: ICU 3.0
+**********************************************************************
+*/
+#ifndef __MEASUREUNIT_H__
+#define __MEASUREUNIT_H__
+
+#include "unicode/utypes.h"
+
+#if !UCONFIG_NO_FORMATTING
+
+#include "unicode/fmtable.h"
+
+/**
+ * \file 
+ * \brief C++ API: A unit for measuring a quantity.
+ */
+ 
+U_NAMESPACE_BEGIN
+
+/**
+ * A unit such as length, mass, volume, currency, etc.  A unit is
+ * coupled with a numeric amount to produce a Measure.
+ *
+ * <p>This is an abstract class.
+ *
+ * @author Alan Liu
+ * @stable ICU 3.0
+ */
+class U_I18N_API MeasureUnit: public UObject {
+ public:
+    /**
+     * Return a polymorphic clone of this object.  The result will
+     * have the same class as returned by getDynamicClassID().
+     * @stable ICU 3.0
+     */
+    virtual UObject* clone() const = 0;
+
+    /**
+     * Destructor
+     * @stable ICU 3.0
+     */
+    virtual ~MeasureUnit();
+    
+    /**
+     * Equality operator.  Return true if this object is equal
+     * to the given object.
+     * @stable ICU 3.0
+     */
+    virtual UBool operator==(const UObject& other) const = 0;
+
+ protected:
+    /**
+     * Default constructor.
+     * @stable ICU 3.0
+     */
+    MeasureUnit();
+};
+
+U_NAMESPACE_END
+
+// NOTE: There is no measunit.cpp. For implementation, see measure.cpp. [alan]
+
+#endif // !UCONFIG_NO_FORMATTING
+#endif // __MEASUREUNIT_H__

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/measure.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/measure.h b/src/apps/couch_collate/platform/osx/icu/unicode/measure.h
new file mode 100644
index 0000000..6b7a049
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/measure.h
@@ -0,0 +1,137 @@
+/*
+**********************************************************************
+* Copyright (c) 2004-2006, International Business Machines
+* Corporation and others.  All Rights Reserved.
+**********************************************************************
+* Author: Alan Liu
+* Created: April 26, 2004
+* Since: ICU 3.0
+**********************************************************************
+*/
+#ifndef __MEASURE_H__
+#define __MEASURE_H__
+
+#include "unicode/utypes.h"
+
+/**
+ * \file 
+ * \brief C++ API: MeasureUnit object.
+ */
+ 
+#if !UCONFIG_NO_FORMATTING
+
+#include "unicode/fmtable.h"
+
+U_NAMESPACE_BEGIN
+
+class MeasureUnit;
+
+/**
+ * An amount of a specified unit, consisting of a number and a Unit.
+ * For example, a length measure consists of a number and a length
+ * unit, such as feet or meters.  This is an abstract class.
+ * Subclasses specify a concrete Unit type.
+ *
+ * <p>Measure objects are parsed and formatted by subclasses of
+ * MeasureFormat.
+ *
+ * <p>Measure objects are immutable.
+ *
+ * <p>This is an abstract class.
+ *
+ * @author Alan Liu
+ * @stable ICU 3.0
+ */
+class U_I18N_API Measure: public UObject {
+ public:
+    /**
+     * Construct an object with the given numeric amount and the given
+     * unit.  After this call, the caller must not delete the given
+     * unit object.
+     * @param number a numeric object; amount.isNumeric() must be TRUE
+     * @param adoptedUnit the unit object, which must not be NULL
+     * @param ec input-output error code. If the amount or the unit
+     * is invalid, then this will be set to a failing value.
+     * @stable ICU 3.0
+     */
+    Measure(const Formattable& number, MeasureUnit* adoptedUnit,
+            UErrorCode& ec);
+
+    /**
+     * Copy constructor
+     * @stable ICU 3.0
+     */
+    Measure(const Measure& other);
+
+    /**
+     * Assignment operator
+     * @stable ICU 3.0
+     */
+    Measure& operator=(const Measure& other);
+
+    /**
+     * Return a polymorphic clone of this object.  The result will
+     * have the same class as returned by getDynamicClassID().
+     * @stable ICU 3.0
+     */
+    virtual UObject* clone() const = 0;
+
+    /**
+     * Destructor
+     * @stable ICU 3.0
+     */
+    virtual ~Measure();
+    
+    /**
+     * Equality operator.  Return true if this object is equal
+     * to the given object.
+     * @stable ICU 3.0
+     */
+    UBool operator==(const UObject& other) const;
+
+    /**
+     * Return a reference to the numeric value of this object.  The
+     * numeric value may be of any numeric type supported by
+     * Formattable.
+     * @stable ICU 3.0
+     */
+    inline const Formattable& getNumber() const;
+
+    /**
+     * Return a reference to the unit of this object.
+     * @stable ICU 3.0
+     */
+    inline const MeasureUnit& getUnit() const;
+
+ protected:
+    /**
+     * Default constructor.
+     * @stable ICU 3.0
+     */
+    Measure();
+
+ private:
+    /**
+     * The numeric value of this object, e.g. 2.54 or 100.
+     */
+    Formattable number;
+
+    /**
+     * The unit of this object, e.g., "millimeter" or "JPY".  This is
+     * owned by this object.
+     */
+    MeasureUnit* unit;
+};
+
+inline const Formattable& Measure::getNumber() const {
+    return number;
+}
+
+inline const MeasureUnit& Measure::getUnit() const {
+    return *unit;
+}
+
+U_NAMESPACE_END
+
+#endif // !UCONFIG_NO_FORMATTING
+#endif // __MEASURE_H__


[19/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/js/libs/ace/worker-json.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/js/libs/ace/worker-json.js b/apps/fauxton/assets/js/libs/ace/worker-json.js
deleted file mode 100644
index 607221f..0000000
--- a/apps/fauxton/assets/js/libs/ace/worker-json.js
+++ /dev/null
@@ -1,2271 +0,0 @@
-"no use strict";
-;(function(window) {
-if (typeof window.window != "undefined" && window.document) {
-    return;
-}
-
-window.console = function() {
-    var msgs = Array.prototype.slice.call(arguments, 0);
-    postMessage({type: "log", data: msgs});
-};
-window.console.error =
-window.console.warn = 
-window.console.log =
-window.console.trace = window.console;
-
-window.window = window;
-window.ace = window;
-
-window.normalizeModule = function(parentId, moduleName) {
-    if (moduleName.indexOf("!") !== -1) {
-        var chunks = moduleName.split("!");
-        return window.normalizeModule(parentId, chunks[0]) + "!" + window.normalizeModule(parentId, chunks[1]);
-    }
-    if (moduleName.charAt(0) == ".") {
-        var base = parentId.split("/").slice(0, -1).join("/");
-        moduleName = (base ? base + "/" : "") + moduleName;
-        
-        while(moduleName.indexOf(".") !== -1 && previous != moduleName) {
-            var previous = moduleName;
-            moduleName = moduleName.replace(/^\.\//, "").replace(/\/\.\//, "/").replace(/[^\/]+\/\.\.\//, "");
-        }
-    }
-    
-    return moduleName;
-};
-
-window.require = function(parentId, id) {
-    if (!id) {
-        id = parentId
-        parentId = null;
-    }
-    if (!id.charAt)
-        throw new Error("worker.js require() accepts only (parentId, id) as arguments");
-
-    id = window.normalizeModule(parentId, id);
-
-    var module = window.require.modules[id];
-    if (module) {
-        if (!module.initialized) {
-            module.initialized = true;
-            module.exports = module.factory().exports;
-        }
-        return module.exports;
-    }
-    
-    var chunks = id.split("/");
-    if (!window.require.tlns)
-        return console.log("unable to load " + id);
-    chunks[0] = window.require.tlns[chunks[0]] || chunks[0];
-    var path = chunks.join("/") + ".js";
-    
-    window.require.id = id;
-    importScripts(path);
-    return window.require(parentId, id);
-};
-window.require.modules = {};
-window.require.tlns = {};
-
-window.define = function(id, deps, factory) {
-    if (arguments.length == 2) {
-        factory = deps;
-        if (typeof id != "string") {
-            deps = id;
-            id = window.require.id;
-        }
-    } else if (arguments.length == 1) {
-        factory = id;
-        deps = []
-        id = window.require.id;
-    }
-
-    if (!deps.length)
-        deps = ['require', 'exports', 'module']
-
-    if (id.indexOf("text!") === 0) 
-        return;
-    
-    var req = function(childId) {
-        return window.require(id, childId);
-    };
-
-    window.require.modules[id] = {
-        exports: {},
-        factory: function() {
-            var module = this;
-            var returnExports = factory.apply(this, deps.map(function(dep) {
-              switch(dep) {
-                  case 'require': return req
-                  case 'exports': return module.exports
-                  case 'module':  return module
-                  default:        return req(dep)
-              }
-            }));
-            if (returnExports)
-                module.exports = returnExports;
-            return module;
-        }
-    };
-};
-window.define.amd = {}
-
-window.initBaseUrls  = function initBaseUrls(topLevelNamespaces) {
-    require.tlns = topLevelNamespaces;
-}
-
-window.initSender = function initSender() {
-
-    var EventEmitter = window.require("ace/lib/event_emitter").EventEmitter;
-    var oop = window.require("ace/lib/oop");
-    
-    var Sender = function() {};
-    
-    (function() {
-        
-        oop.implement(this, EventEmitter);
-                
-        this.callback = function(data, callbackId) {
-            postMessage({
-                type: "call",
-                id: callbackId,
-                data: data
-            });
-        };
-    
-        this.emit = function(name, data) {
-            postMessage({
-                type: "event",
-                name: name,
-                data: data
-            });
-        };
-        
-    }).call(Sender.prototype);
-    
-    return new Sender();
-}
-
-window.main = null;
-window.sender = null;
-
-window.onmessage = function(e) {
-    var msg = e.data;
-    if (msg.command) {
-        if (main[msg.command])
-            main[msg.command].apply(main, msg.args);
-        else
-            throw new Error("Unknown command:" + msg.command);
-    }
-    else if (msg.init) {        
-        initBaseUrls(msg.tlns);
-        require("ace/lib/es5-shim");
-        sender = initSender();
-        var clazz = require(msg.module)[msg.classname];
-        main = new clazz(sender);
-    } 
-    else if (msg.event && sender) {
-        sender._emit(msg.event, msg.data);
-    }
-};
-})(this);// https://github.com/kriskowal/es5-shim
-
-define('ace/lib/es5-shim', ['require', 'exports', 'module' ], function(require, exports, module) {
-
-function Empty() {}
-
-if (!Function.prototype.bind) {
-    Function.prototype.bind = function bind(that) { // .length is 1
-        var target = this;
-        if (typeof target != "function") {
-            throw new TypeError("Function.prototype.bind called on incompatible " + target);
-        }
-        var args = slice.call(arguments, 1); // for normal call
-        var bound = function () {
-
-            if (this instanceof bound) {
-
-                var result = target.apply(
-                    this,
-                    args.concat(slice.call(arguments))
-                );
-                if (Object(result) === result) {
-                    return result;
-                }
-                return this;
-
-            } else {
-                return target.apply(
-                    that,
-                    args.concat(slice.call(arguments))
-                );
-
-            }
-
-        };
-        if(target.prototype) {
-            Empty.prototype = target.prototype;
-            bound.prototype = new Empty();
-            Empty.prototype = null;
-        }
-        return bound;
-    };
-}
-var call = Function.prototype.call;
-var prototypeOfArray = Array.prototype;
-var prototypeOfObject = Object.prototype;
-var slice = prototypeOfArray.slice;
-var _toString = call.bind(prototypeOfObject.toString);
-var owns = call.bind(prototypeOfObject.hasOwnProperty);
-var defineGetter;
-var defineSetter;
-var lookupGetter;
-var lookupSetter;
-var supportsAccessors;
-if ((supportsAccessors = owns(prototypeOfObject, "__defineGetter__"))) {
-    defineGetter = call.bind(prototypeOfObject.__defineGetter__);
-    defineSetter = call.bind(prototypeOfObject.__defineSetter__);
-    lookupGetter = call.bind(prototypeOfObject.__lookupGetter__);
-    lookupSetter = call.bind(prototypeOfObject.__lookupSetter__);
-}
-if ([1,2].splice(0).length != 2) {
-    if(function() { // test IE < 9 to splice bug - see issue #138
-        function makeArray(l) {
-            var a = new Array(l+2);
-            a[0] = a[1] = 0;
-            return a;
-        }
-        var array = [], lengthBefore;
-        
-        array.splice.apply(array, makeArray(20));
-        array.splice.apply(array, makeArray(26));
-
-        lengthBefore = array.length; //46
-        array.splice(5, 0, "XXX"); // add one element
-
-        lengthBefore + 1 == array.length
-
-        if (lengthBefore + 1 == array.length) {
-            return true;// has right splice implementation without bugs
-        }
-    }()) {//IE 6/7
-        var array_splice = Array.prototype.splice;
-        Array.prototype.splice = function(start, deleteCount) {
-            if (!arguments.length) {
-                return [];
-            } else {
-                return array_splice.apply(this, [
-                    start === void 0 ? 0 : start,
-                    deleteCount === void 0 ? (this.length - start) : deleteCount
-                ].concat(slice.call(arguments, 2)))
-            }
-        };
-    } else {//IE8
-        Array.prototype.splice = function(pos, removeCount){
-            var length = this.length;
-            if (pos > 0) {
-                if (pos > length)
-                    pos = length;
-            } else if (pos == void 0) {
-                pos = 0;
-            } else if (pos < 0) {
-                pos = Math.max(length + pos, 0);
-            }
-
-            if (!(pos+removeCount < length))
-                removeCount = length - pos;
-
-            var removed = this.slice(pos, pos+removeCount);
-            var insert = slice.call(arguments, 2);
-            var add = insert.length;            
-            if (pos === length) {
-                if (add) {
-                    this.push.apply(this, insert);
-                }
-            } else {
-                var remove = Math.min(removeCount, length - pos);
-                var tailOldPos = pos + remove;
-                var tailNewPos = tailOldPos + add - remove;
-                var tailCount = length - tailOldPos;
-                var lengthAfterRemove = length - remove;
-
-                if (tailNewPos < tailOldPos) { // case A
-                    for (var i = 0; i < tailCount; ++i) {
-                        this[tailNewPos+i] = this[tailOldPos+i];
-                    }
-                } else if (tailNewPos > tailOldPos) { // case B
-                    for (i = tailCount; i--; ) {
-                        this[tailNewPos+i] = this[tailOldPos+i];
-                    }
-                } // else, add == remove (nothing to do)
-
-                if (add && pos === lengthAfterRemove) {
-                    this.length = lengthAfterRemove; // truncate array
-                    this.push.apply(this, insert);
-                } else {
-                    this.length = lengthAfterRemove + add; // reserves space
-                    for (i = 0; i < add; ++i) {
-                        this[pos+i] = insert[i];
-                    }
-                }
-            }
-            return removed;
-        };
-    }
-}
-if (!Array.isArray) {
-    Array.isArray = function isArray(obj) {
-        return _toString(obj) == "[object Array]";
-    };
-}
-var boxedString = Object("a"),
-    splitString = boxedString[0] != "a" || !(0 in boxedString);
-
-if (!Array.prototype.forEach) {
-    Array.prototype.forEach = function forEach(fun /*, thisp*/) {
-        var object = toObject(this),
-            self = splitString && _toString(this) == "[object String]" ?
-                this.split("") :
-                object,
-            thisp = arguments[1],
-            i = -1,
-            length = self.length >>> 0;
-        if (_toString(fun) != "[object Function]") {
-            throw new TypeError(); // TODO message
-        }
-
-        while (++i < length) {
-            if (i in self) {
-                fun.call(thisp, self[i], i, object);
-            }
-        }
-    };
-}
-if (!Array.prototype.map) {
-    Array.prototype.map = function map(fun /*, thisp*/) {
-        var object = toObject(this),
-            self = splitString && _toString(this) == "[object String]" ?
-                this.split("") :
-                object,
-            length = self.length >>> 0,
-            result = Array(length),
-            thisp = arguments[1];
-        if (_toString(fun) != "[object Function]") {
-            throw new TypeError(fun + " is not a function");
-        }
-
-        for (var i = 0; i < length; i++) {
-            if (i in self)
-                result[i] = fun.call(thisp, self[i], i, object);
-        }
-        return result;
-    };
-}
-if (!Array.prototype.filter) {
-    Array.prototype.filter = function filter(fun /*, thisp */) {
-        var object = toObject(this),
-            self = splitString && _toString(this) == "[object String]" ?
-                this.split("") :
-                    object,
-            length = self.length >>> 0,
-            result = [],
-            value,
-            thisp = arguments[1];
-        if (_toString(fun) != "[object Function]") {
-            throw new TypeError(fun + " is not a function");
-        }
-
-        for (var i = 0; i < length; i++) {
-            if (i in self) {
-                value = self[i];
-                if (fun.call(thisp, value, i, object)) {
-                    result.push(value);
-                }
-            }
-        }
-        return result;
-    };
-}
-if (!Array.prototype.every) {
-    Array.prototype.every = function every(fun /*, thisp */) {
-        var object = toObject(this),
-            self = splitString && _toString(this) == "[object String]" ?
-                this.split("") :
-                object,
-            length = self.length >>> 0,
-            thisp = arguments[1];
-        if (_toString(fun) != "[object Function]") {
-            throw new TypeError(fun + " is not a function");
-        }
-
-        for (var i = 0; i < length; i++) {
-            if (i in self && !fun.call(thisp, self[i], i, object)) {
-                return false;
-            }
-        }
-        return true;
-    };
-}
-if (!Array.prototype.some) {
-    Array.prototype.some = function some(fun /*, thisp */) {
-        var object = toObject(this),
-            self = splitString && _toString(this) == "[object String]" ?
-                this.split("") :
-                object,
-            length = self.length >>> 0,
-            thisp = arguments[1];
-        if (_toString(fun) != "[object Function]") {
-            throw new TypeError(fun + " is not a function");
-        }
-
-        for (var i = 0; i < length; i++) {
-            if (i in self && fun.call(thisp, self[i], i, object)) {
-                return true;
-            }
-        }
-        return false;
-    };
-}
-if (!Array.prototype.reduce) {
-    Array.prototype.reduce = function reduce(fun /*, initial*/) {
-        var object = toObject(this),
-            self = splitString && _toString(this) == "[object String]" ?
-                this.split("") :
-                object,
-            length = self.length >>> 0;
-        if (_toString(fun) != "[object Function]") {
-            throw new TypeError(fun + " is not a function");
-        }
-        if (!length && arguments.length == 1) {
-            throw new TypeError("reduce of empty array with no initial value");
-        }
-
-        var i = 0;
-        var result;
-        if (arguments.length >= 2) {
-            result = arguments[1];
-        } else {
-            do {
-                if (i in self) {
-                    result = self[i++];
-                    break;
-                }
-                if (++i >= length) {
-                    throw new TypeError("reduce of empty array with no initial value");
-                }
-            } while (true);
-        }
-
-        for (; i < length; i++) {
-            if (i in self) {
-                result = fun.call(void 0, result, self[i], i, object);
-            }
-        }
-
-        return result;
-    };
-}
-if (!Array.prototype.reduceRight) {
-    Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) {
-        var object = toObject(this),
-            self = splitString && _toString(this) == "[object String]" ?
-                this.split("") :
-                object,
-            length = self.length >>> 0;
-        if (_toString(fun) != "[object Function]") {
-            throw new TypeError(fun + " is not a function");
-        }
-        if (!length && arguments.length == 1) {
-            throw new TypeError("reduceRight of empty array with no initial value");
-        }
-
-        var result, i = length - 1;
-        if (arguments.length >= 2) {
-            result = arguments[1];
-        } else {
-            do {
-                if (i in self) {
-                    result = self[i--];
-                    break;
-                }
-                if (--i < 0) {
-                    throw new TypeError("reduceRight of empty array with no initial value");
-                }
-            } while (true);
-        }
-
-        do {
-            if (i in this) {
-                result = fun.call(void 0, result, self[i], i, object);
-            }
-        } while (i--);
-
-        return result;
-    };
-}
-if (!Array.prototype.indexOf || ([0, 1].indexOf(1, 2) != -1)) {
-    Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) {
-        var self = splitString && _toString(this) == "[object String]" ?
-                this.split("") :
-                toObject(this),
-            length = self.length >>> 0;
-
-        if (!length) {
-            return -1;
-        }
-
-        var i = 0;
-        if (arguments.length > 1) {
-            i = toInteger(arguments[1]);
-        }
-        i = i >= 0 ? i : Math.max(0, length + i);
-        for (; i < length; i++) {
-            if (i in self && self[i] === sought) {
-                return i;
-            }
-        }
-        return -1;
-    };
-}
-if (!Array.prototype.lastIndexOf || ([0, 1].lastIndexOf(0, -3) != -1)) {
-    Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) {
-        var self = splitString && _toString(this) == "[object String]" ?
-                this.split("") :
-                toObject(this),
-            length = self.length >>> 0;
-
-        if (!length) {
-            return -1;
-        }
-        var i = length - 1;
-        if (arguments.length > 1) {
-            i = Math.min(i, toInteger(arguments[1]));
-        }
-        i = i >= 0 ? i : length - Math.abs(i);
-        for (; i >= 0; i--) {
-            if (i in self && sought === self[i]) {
-                return i;
-            }
-        }
-        return -1;
-    };
-}
-if (!Object.getPrototypeOf) {
-    Object.getPrototypeOf = function getPrototypeOf(object) {
-        return object.__proto__ || (
-            object.constructor ?
-            object.constructor.prototype :
-            prototypeOfObject
-        );
-    };
-}
-if (!Object.getOwnPropertyDescriptor) {
-    var ERR_NON_OBJECT = "Object.getOwnPropertyDescriptor called on a " +
-                         "non-object: ";
-    Object.getOwnPropertyDescriptor = function getOwnPropertyDescriptor(object, property) {
-        if ((typeof object != "object" && typeof object != "function") || object === null)
-            throw new TypeError(ERR_NON_OBJECT + object);
-        if (!owns(object, property))
-            return;
-
-        var descriptor, getter, setter;
-        descriptor =  { enumerable: true, configurable: true };
-        if (supportsAccessors) {
-            var prototype = object.__proto__;
-            object.__proto__ = prototypeOfObject;
-
-            var getter = lookupGetter(object, property);
-            var setter = lookupSetter(object, property);
-            object.__proto__ = prototype;
-
-            if (getter || setter) {
-                if (getter) descriptor.get = getter;
-                if (setter) descriptor.set = setter;
-                return descriptor;
-            }
-        }
-        descriptor.value = object[property];
-        return descriptor;
-    };
-}
-if (!Object.getOwnPropertyNames) {
-    Object.getOwnPropertyNames = function getOwnPropertyNames(object) {
-        return Object.keys(object);
-    };
-}
-if (!Object.create) {
-    var createEmpty;
-    if (Object.prototype.__proto__ === null) {
-        createEmpty = function () {
-            return { "__proto__": null };
-        };
-    } else {
-        createEmpty = function () {
-            var empty = {};
-            for (var i in empty)
-                empty[i] = null;
-            empty.constructor =
-            empty.hasOwnProperty =
-            empty.propertyIsEnumerable =
-            empty.isPrototypeOf =
-            empty.toLocaleString =
-            empty.toString =
-            empty.valueOf =
-            empty.__proto__ = null;
-            return empty;
-        }
-    }
-
-    Object.create = function create(prototype, properties) {
-        var object;
-        if (prototype === null) {
-            object = createEmpty();
-        } else {
-            if (typeof prototype != "object")
-                throw new TypeError("typeof prototype["+(typeof prototype)+"] != 'object'");
-            var Type = function () {};
-            Type.prototype = prototype;
-            object = new Type();
-            object.__proto__ = prototype;
-        }
-        if (properties !== void 0)
-            Object.defineProperties(object, properties);
-        return object;
-    };
-}
-
-function doesDefinePropertyWork(object) {
-    try {
-        Object.defineProperty(object, "sentinel", {});
-        return "sentinel" in object;
-    } catch (exception) {
-    }
-}
-if (Object.defineProperty) {
-    var definePropertyWorksOnObject = doesDefinePropertyWork({});
-    var definePropertyWorksOnDom = typeof document == "undefined" ||
-        doesDefinePropertyWork(document.createElement("div"));
-    if (!definePropertyWorksOnObject || !definePropertyWorksOnDom) {
-        var definePropertyFallback = Object.defineProperty;
-    }
-}
-
-if (!Object.defineProperty || definePropertyFallback) {
-    var ERR_NON_OBJECT_DESCRIPTOR = "Property description must be an object: ";
-    var ERR_NON_OBJECT_TARGET = "Object.defineProperty called on non-object: "
-    var ERR_ACCESSORS_NOT_SUPPORTED = "getters & setters can not be defined " +
-                                      "on this javascript engine";
-
-    Object.defineProperty = function defineProperty(object, property, descriptor) {
-        if ((typeof object != "object" && typeof object != "function") || object === null)
-            throw new TypeError(ERR_NON_OBJECT_TARGET + object);
-        if ((typeof descriptor != "object" && typeof descriptor != "function") || descriptor === null)
-            throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR + descriptor);
-        if (definePropertyFallback) {
-            try {
-                return definePropertyFallback.call(Object, object, property, descriptor);
-            } catch (exception) {
-            }
-        }
-        if (owns(descriptor, "value")) {
-
-            if (supportsAccessors && (lookupGetter(object, property) ||
-                                      lookupSetter(object, property)))
-            {
-                var prototype = object.__proto__;
-                object.__proto__ = prototypeOfObject;
-                delete object[property];
-                object[property] = descriptor.value;
-                object.__proto__ = prototype;
-            } else {
-                object[property] = descriptor.value;
-            }
-        } else {
-            if (!supportsAccessors)
-                throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED);
-            if (owns(descriptor, "get"))
-                defineGetter(object, property, descriptor.get);
-            if (owns(descriptor, "set"))
-                defineSetter(object, property, descriptor.set);
-        }
-
-        return object;
-    };
-}
-if (!Object.defineProperties) {
-    Object.defineProperties = function defineProperties(object, properties) {
-        for (var property in properties) {
-            if (owns(properties, property))
-                Object.defineProperty(object, property, properties[property]);
-        }
-        return object;
-    };
-}
-if (!Object.seal) {
-    Object.seal = function seal(object) {
-        return object;
-    };
-}
-if (!Object.freeze) {
-    Object.freeze = function freeze(object) {
-        return object;
-    };
-}
-try {
-    Object.freeze(function () {});
-} catch (exception) {
-    Object.freeze = (function freeze(freezeObject) {
-        return function freeze(object) {
-            if (typeof object == "function") {
-                return object;
-            } else {
-                return freezeObject(object);
-            }
-        };
-    })(Object.freeze);
-}
-if (!Object.preventExtensions) {
-    Object.preventExtensions = function preventExtensions(object) {
-        return object;
-    };
-}
-if (!Object.isSealed) {
-    Object.isSealed = function isSealed(object) {
-        return false;
-    };
-}
-if (!Object.isFrozen) {
-    Object.isFrozen = function isFrozen(object) {
-        return false;
-    };
-}
-if (!Object.isExtensible) {
-    Object.isExtensible = function isExtensible(object) {
-        if (Object(object) === object) {
-            throw new TypeError(); // TODO message
-        }
-        var name = '';
-        while (owns(object, name)) {
-            name += '?';
-        }
-        object[name] = true;
-        var returnValue = owns(object, name);
-        delete object[name];
-        return returnValue;
-    };
-}
-if (!Object.keys) {
-    var hasDontEnumBug = true,
-        dontEnums = [
-            "toString",
-            "toLocaleString",
-            "valueOf",
-            "hasOwnProperty",
-            "isPrototypeOf",
-            "propertyIsEnumerable",
-            "constructor"
-        ],
-        dontEnumsLength = dontEnums.length;
-
-    for (var key in {"toString": null}) {
-        hasDontEnumBug = false;
-    }
-
-    Object.keys = function keys(object) {
-
-        if (
-            (typeof object != "object" && typeof object != "function") ||
-            object === null
-        ) {
-            throw new TypeError("Object.keys called on a non-object");
-        }
-
-        var keys = [];
-        for (var name in object) {
-            if (owns(object, name)) {
-                keys.push(name);
-            }
-        }
-
-        if (hasDontEnumBug) {
-            for (var i = 0, ii = dontEnumsLength; i < ii; i++) {
-                var dontEnum = dontEnums[i];
-                if (owns(object, dontEnum)) {
-                    keys.push(dontEnum);
-                }
-            }
-        }
-        return keys;
-    };
-
-}
-if (!Date.now) {
-    Date.now = function now() {
-        return new Date().getTime();
-    };
-}
-var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" +
-    "\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" +
-    "\u2029\uFEFF";
-if (!String.prototype.trim || ws.trim()) {
-    ws = "[" + ws + "]";
-    var trimBeginRegexp = new RegExp("^" + ws + ws + "*"),
-        trimEndRegexp = new RegExp(ws + ws + "*$");
-    String.prototype.trim = function trim() {
-        return String(this).replace(trimBeginRegexp, "").replace(trimEndRegexp, "");
-    };
-}
-
-function toInteger(n) {
-    n = +n;
-    if (n !== n) { // isNaN
-        n = 0;
-    } else if (n !== 0 && n !== (1/0) && n !== -(1/0)) {
-        n = (n > 0 || -1) * Math.floor(Math.abs(n));
-    }
-    return n;
-}
-
-function isPrimitive(input) {
-    var type = typeof input;
-    return (
-        input === null ||
-        type === "undefined" ||
-        type === "boolean" ||
-        type === "number" ||
-        type === "string"
-    );
-}
-
-function toPrimitive(input) {
-    var val, valueOf, toString;
-    if (isPrimitive(input)) {
-        return input;
-    }
-    valueOf = input.valueOf;
-    if (typeof valueOf === "function") {
-        val = valueOf.call(input);
-        if (isPrimitive(val)) {
-            return val;
-        }
-    }
-    toString = input.toString;
-    if (typeof toString === "function") {
-        val = toString.call(input);
-        if (isPrimitive(val)) {
-            return val;
-        }
-    }
-    throw new TypeError();
-}
-var toObject = function (o) {
-    if (o == null) { // this matches both null and undefined
-        throw new TypeError("can't convert "+o+" to object");
-    }
-    return Object(o);
-};
-
-});
-
-define('ace/mode/json_worker', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/worker/mirror', 'ace/mode/json/json_parse'], function(require, exports, module) {
-
-
-var oop = require("../lib/oop");
-var Mirror = require("../worker/mirror").Mirror;
-var parse = require("./json/json_parse");
-
-var JsonWorker = exports.JsonWorker = function(sender) {
-    Mirror.call(this, sender);
-    this.setTimeout(200);
-};
-
-oop.inherits(JsonWorker, Mirror);
-
-(function() {
-
-    this.onUpdate = function() {
-        var value = this.doc.getValue();
-
-        try {
-            var result = parse(value);
-        } catch (e) {
-            var pos = this.doc.indexToPosition(e.at-1);
-            this.sender.emit("error", {
-                row: pos.row,
-                column: pos.column,
-                text: e.message,
-                type: "error"
-            });
-            return;
-        }
-        this.sender.emit("ok");
-    };
-
-}).call(JsonWorker.prototype);
-
-});
-
-define('ace/lib/oop', ['require', 'exports', 'module' ], function(require, exports, module) {
-
-
-exports.inherits = (function() {
-    var tempCtor = function() {};
-    return function(ctor, superCtor) {
-        tempCtor.prototype = superCtor.prototype;
-        ctor.super_ = superCtor.prototype;
-        ctor.prototype = new tempCtor();
-        ctor.prototype.constructor = ctor;
-    };
-}());
-
-exports.mixin = function(obj, mixin) {
-    for (var key in mixin) {
-        obj[key] = mixin[key];
-    }
-    return obj;
-};
-
-exports.implement = function(proto, mixin) {
-    exports.mixin(proto, mixin);
-};
-
-});
-define('ace/worker/mirror', ['require', 'exports', 'module' , 'ace/document', 'ace/lib/lang'], function(require, exports, module) {
-
-
-var Document = require("../document").Document;
-var lang = require("../lib/lang");
-    
-var Mirror = exports.Mirror = function(sender) {
-    this.sender = sender;
-    var doc = this.doc = new Document("");
-    
-    var deferredUpdate = this.deferredUpdate = lang.delayedCall(this.onUpdate.bind(this));
-    
-    var _self = this;
-    sender.on("change", function(e) {
-        doc.applyDeltas(e.data);
-        deferredUpdate.schedule(_self.$timeout);
-    });
-};
-
-(function() {
-    
-    this.$timeout = 500;
-    
-    this.setTimeout = function(timeout) {
-        this.$timeout = timeout;
-    };
-    
-    this.setValue = function(value) {
-        this.doc.setValue(value);
-        this.deferredUpdate.schedule(this.$timeout);
-    };
-    
-    this.getValue = function(callbackId) {
-        this.sender.callback(this.doc.getValue(), callbackId);
-    };
-    
-    this.onUpdate = function() {
-    };
-    
-}).call(Mirror.prototype);
-
-});
-
-define('ace/document', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter', 'ace/range', 'ace/anchor'], function(require, exports, module) {
-
-
-var oop = require("./lib/oop");
-var EventEmitter = require("./lib/event_emitter").EventEmitter;
-var Range = require("./range").Range;
-var Anchor = require("./anchor").Anchor;
-
-var Document = function(text) {
-    this.$lines = [];
-    if (text.length == 0) {
-        this.$lines = [""];
-    } else if (Array.isArray(text)) {
-        this._insertLines(0, text);
-    } else {
-        this.insert({row: 0, column:0}, text);
-    }
-};
-
-(function() {
-
-    oop.implement(this, EventEmitter);
-    this.setValue = function(text) {
-        var len = this.getLength();
-        this.remove(new Range(0, 0, len, this.getLine(len-1).length));
-        this.insert({row: 0, column:0}, text);
-    };
-    this.getValue = function() {
-        return this.getAllLines().join(this.getNewLineCharacter());
-    };
-    this.createAnchor = function(row, column) {
-        return new Anchor(this, row, column);
-    };
-    if ("aaa".split(/a/).length == 0)
-        this.$split = function(text) {
-            return text.replace(/\r\n|\r/g, "\n").split("\n");
-        }
-    else
-        this.$split = function(text) {
-            return text.split(/\r\n|\r|\n/);
-        };
-
-
-    this.$detectNewLine = function(text) {
-        var match = text.match(/^.*?(\r\n|\r|\n)/m);
-        this.$autoNewLine = match ? match[1] : "\n";
-    };
-    this.getNewLineCharacter = function() {
-        switch (this.$newLineMode) {
-          case "windows":
-            return "\r\n";
-          case "unix":
-            return "\n";
-          default:
-            return this.$autoNewLine;
-        }
-    };
-
-    this.$autoNewLine = "\n";
-    this.$newLineMode = "auto";
-    this.setNewLineMode = function(newLineMode) {
-        if (this.$newLineMode === newLineMode)
-            return;
-
-        this.$newLineMode = newLineMode;
-    };
-    this.getNewLineMode = function() {
-        return this.$newLineMode;
-    };
-    this.isNewLine = function(text) {
-        return (text == "\r\n" || text == "\r" || text == "\n");
-    };
-    this.getLine = function(row) {
-        return this.$lines[row] || "";
-    };
-    this.getLines = function(firstRow, lastRow) {
-        return this.$lines.slice(firstRow, lastRow + 1);
-    };
-    this.getAllLines = function() {
-        return this.getLines(0, this.getLength());
-    };
-    this.getLength = function() {
-        return this.$lines.length;
-    };
-    this.getTextRange = function(range) {
-        if (range.start.row == range.end.row) {
-            return this.getLine(range.start.row)
-                .substring(range.start.column, range.end.column);
-        }
-        var lines = this.getLines(range.start.row, range.end.row);
-        lines[0] = (lines[0] || "").substring(range.start.column);
-        var l = lines.length - 1;
-        if (range.end.row - range.start.row == l)
-            lines[l] = lines[l].substring(0, range.end.column);
-        return lines.join(this.getNewLineCharacter());
-    };
-
-    this.$clipPosition = function(position) {
-        var length = this.getLength();
-        if (position.row >= length) {
-            position.row = Math.max(0, length - 1);
-            position.column = this.getLine(length-1).length;
-        } else if (position.row < 0)
-            position.row = 0;
-        return position;
-    };
-    this.insert = function(position, text) {
-        if (!text || text.length === 0)
-            return position;
-
-        position = this.$clipPosition(position);
-        if (this.getLength() <= 1)
-            this.$detectNewLine(text);
-
-        var lines = this.$split(text);
-        var firstLine = lines.splice(0, 1)[0];
-        var lastLine = lines.length == 0 ? null : lines.splice(lines.length - 1, 1)[0];
-
-        position = this.insertInLine(position, firstLine);
-        if (lastLine !== null) {
-            position = this.insertNewLine(position); // terminate first line
-            position = this._insertLines(position.row, lines);
-            position = this.insertInLine(position, lastLine || "");
-        }
-        return position;
-    };
-    this.insertLines = function(row, lines) {
-        if (row >= this.getLength())
-            return this.insert({row: row, column: 0}, "\n" + lines.join("\n"));
-        return this._insertLines(Math.max(row, 0), lines);
-    };
-    this._insertLines = function(row, lines) {
-        if (lines.length == 0)
-            return {row: row, column: 0};
-        if (lines.length > 0xFFFF) {
-            var end = this._insertLines(row, lines.slice(0xFFFF));
-            lines = lines.slice(0, 0xFFFF);
-        }
-
-        var args = [row, 0];
-        args.push.apply(args, lines);
-        this.$lines.splice.apply(this.$lines, args);
-
-        var range = new Range(row, 0, row + lines.length, 0);
-        var delta = {
-            action: "insertLines",
-            range: range,
-            lines: lines
-        };
-        this._emit("change", { data: delta });
-        return end || range.end;
-    };
-    this.insertNewLine = function(position) {
-        position = this.$clipPosition(position);
-        var line = this.$lines[position.row] || "";
-
-        this.$lines[position.row] = line.substring(0, position.column);
-        this.$lines.splice(position.row + 1, 0, line.substring(position.column, line.length));
-
-        var end = {
-            row : position.row + 1,
-            column : 0
-        };
-
-        var delta = {
-            action: "insertText",
-            range: Range.fromPoints(position, end),
-            text: this.getNewLineCharacter()
-        };
-        this._emit("change", { data: delta });
-
-        return end;
-    };
-    this.insertInLine = function(position, text) {
-        if (text.length == 0)
-            return position;
-
-        var line = this.$lines[position.row] || "";
-
-        this.$lines[position.row] = line.substring(0, position.column) + text
-                + line.substring(position.column);
-
-        var end = {
-            row : position.row,
-            column : position.column + text.length
-        };
-
-        var delta = {
-            action: "insertText",
-            range: Range.fromPoints(position, end),
-            text: text
-        };
-        this._emit("change", { data: delta });
-
-        return end;
-    };
-    this.remove = function(range) {
-        if (!range instanceof Range)
-            range = Range.fromPoints(range.start, range.end);
-        range.start = this.$clipPosition(range.start);
-        range.end = this.$clipPosition(range.end);
-
-        if (range.isEmpty())
-            return range.start;
-
-        var firstRow = range.start.row;
-        var lastRow = range.end.row;
-
-        if (range.isMultiLine()) {
-            var firstFullRow = range.start.column == 0 ? firstRow : firstRow + 1;
-            var lastFullRow = lastRow - 1;
-
-            if (range.end.column > 0)
-                this.removeInLine(lastRow, 0, range.end.column);
-
-            if (lastFullRow >= firstFullRow)
-                this._removeLines(firstFullRow, lastFullRow);
-
-            if (firstFullRow != firstRow) {
-                this.removeInLine(firstRow, range.start.column, this.getLine(firstRow).length);
-                this.removeNewLine(range.start.row);
-            }
-        }
-        else {
-            this.removeInLine(firstRow, range.start.column, range.end.column);
-        }
-        return range.start;
-    };
-    this.removeInLine = function(row, startColumn, endColumn) {
-        if (startColumn == endColumn)
-            return;
-
-        var range = new Range(row, startColumn, row, endColumn);
-        var line = this.getLine(row);
-        var removed = line.substring(startColumn, endColumn);
-        var newLine = line.substring(0, startColumn) + line.substring(endColumn, line.length);
-        this.$lines.splice(row, 1, newLine);
-
-        var delta = {
-            action: "removeText",
-            range: range,
-            text: removed
-        };
-        this._emit("change", { data: delta });
-        return range.start;
-    };
-    this.removeLines = function(firstRow, lastRow) {
-        if (firstRow < 0 || lastRow >= this.getLength())
-            return this.remove(new Range(firstRow, 0, lastRow + 1, 0));
-        return this._removeLines(firstRow, lastRow);
-    };
-
-    this._removeLines = function(firstRow, lastRow) {
-        var range = new Range(firstRow, 0, lastRow + 1, 0);
-        var removed = this.$lines.splice(firstRow, lastRow - firstRow + 1);
-
-        var delta = {
-            action: "removeLines",
-            range: range,
-            nl: this.getNewLineCharacter(),
-            lines: removed
-        };
-        this._emit("change", { data: delta });
-        return removed;
-    };
-    this.removeNewLine = function(row) {
-        var firstLine = this.getLine(row);
-        var secondLine = this.getLine(row+1);
-
-        var range = new Range(row, firstLine.length, row+1, 0);
-        var line = firstLine + secondLine;
-
-        this.$lines.splice(row, 2, line);
-
-        var delta = {
-            action: "removeText",
-            range: range,
-            text: this.getNewLineCharacter()
-        };
-        this._emit("change", { data: delta });
-    };
-    this.replace = function(range, text) {
-        if (!range instanceof Range)
-            range = Range.fromPoints(range.start, range.end);
-        if (text.length == 0 && range.isEmpty())
-            return range.start;
-        if (text == this.getTextRange(range))
-            return range.end;
-
-        this.remove(range);
-        if (text) {
-            var end = this.insert(range.start, text);
-        }
-        else {
-            end = range.start;
-        }
-
-        return end;
-    };
-    this.applyDeltas = function(deltas) {
-        for (var i=0; i<deltas.length; i++) {
-            var delta = deltas[i];
-            var range = Range.fromPoints(delta.range.start, delta.range.end);
-
-            if (delta.action == "insertLines")
-                this.insertLines(range.start.row, delta.lines);
-            else if (delta.action == "insertText")
-                this.insert(range.start, delta.text);
-            else if (delta.action == "removeLines")
-                this._removeLines(range.start.row, range.end.row - 1);
-            else if (delta.action == "removeText")
-                this.remove(range);
-        }
-    };
-    this.revertDeltas = function(deltas) {
-        for (var i=deltas.length-1; i>=0; i--) {
-            var delta = deltas[i];
-
-            var range = Range.fromPoints(delta.range.start, delta.range.end);
-
-            if (delta.action == "insertLines")
-                this._removeLines(range.start.row, range.end.row - 1);
-            else if (delta.action == "insertText")
-                this.remove(range);
-            else if (delta.action == "removeLines")
-                this._insertLines(range.start.row, delta.lines);
-            else if (delta.action == "removeText")
-                this.insert(range.start, delta.text);
-        }
-    };
-    this.indexToPosition = function(index, startRow) {
-        var lines = this.$lines || this.getAllLines();
-        var newlineLength = this.getNewLineCharacter().length;
-        for (var i = startRow || 0, l = lines.length; i < l; i++) {
-            index -= lines[i].length + newlineLength;
-            if (index < 0)
-                return {row: i, column: index + lines[i].length + newlineLength};
-        }
-        return {row: l-1, column: lines[l-1].length};
-    };
-    this.positionToIndex = function(pos, startRow) {
-        var lines = this.$lines || this.getAllLines();
-        var newlineLength = this.getNewLineCharacter().length;
-        var index = 0;
-        var row = Math.min(pos.row, lines.length);
-        for (var i = startRow || 0; i < row; ++i)
-            index += lines[i].length + newlineLength;
-
-        return index + pos.column;
-    };
-
-}).call(Document.prototype);
-
-exports.Document = Document;
-});
-
-define('ace/lib/event_emitter', ['require', 'exports', 'module' ], function(require, exports, module) {
-
-
-var EventEmitter = {};
-var stopPropagation = function() { this.propagationStopped = true; };
-var preventDefault = function() { this.defaultPrevented = true; };
-
-EventEmitter._emit =
-EventEmitter._dispatchEvent = function(eventName, e) {
-    this._eventRegistry || (this._eventRegistry = {});
-    this._defaultHandlers || (this._defaultHandlers = {});
-
-    var listeners = this._eventRegistry[eventName] || [];
-    var defaultHandler = this._defaultHandlers[eventName];
-    if (!listeners.length && !defaultHandler)
-        return;
-
-    if (typeof e != "object" || !e)
-        e = {};
-
-    if (!e.type)
-        e.type = eventName;
-    if (!e.stopPropagation)
-        e.stopPropagation = stopPropagation;
-    if (!e.preventDefault)
-        e.preventDefault = preventDefault;
-
-    listeners = listeners.slice();
-    for (var i=0; i<listeners.length; i++) {
-        listeners[i](e, this);
-        if (e.propagationStopped)
-            break;
-    }
-    
-    if (defaultHandler && !e.defaultPrevented)
-        return defaultHandler(e, this);
-};
-
-
-EventEmitter._signal = function(eventName, e) {
-    var listeners = (this._eventRegistry || {})[eventName];
-    if (!listeners)
-        return;
-    listeners = listeners.slice();
-    for (var i=0; i<listeners.length; i++)
-        listeners[i](e, this);
-};
-
-EventEmitter.once = function(eventName, callback) {
-    var _self = this;
-    callback && this.addEventListener(eventName, function newCallback() {
-        _self.removeEventListener(eventName, newCallback);
-        callback.apply(null, arguments);
-    });
-};
-
-
-EventEmitter.setDefaultHandler = function(eventName, callback) {
-    var handlers = this._defaultHandlers
-    if (!handlers)
-        handlers = this._defaultHandlers = {_disabled_: {}};
-    
-    if (handlers[eventName]) {
-        var old = handlers[eventName];
-        var disabled = handlers._disabled_[eventName];
-        if (!disabled)
-            handlers._disabled_[eventName] = disabled = [];
-        disabled.push(old);
-        var i = disabled.indexOf(callback);
-        if (i != -1) 
-            disabled.splice(i, 1);
-    }
-    handlers[eventName] = callback;
-};
-EventEmitter.removeDefaultHandler = function(eventName, callback) {
-    var handlers = this._defaultHandlers
-    if (!handlers)
-        return;
-    var disabled = handlers._disabled_[eventName];
-    
-    if (handlers[eventName] == callback) {
-        var old = handlers[eventName];
-        if (disabled)
-            this.setDefaultHandler(eventName, disabled.pop());
-    } else if (disabled) {
-        var i = disabled.indexOf(callback);
-        if (i != -1)
-            disabled.splice(i, 1);
-    }
-};
-
-EventEmitter.on =
-EventEmitter.addEventListener = function(eventName, callback, capturing) {
-    this._eventRegistry = this._eventRegistry || {};
-
-    var listeners = this._eventRegistry[eventName];
-    if (!listeners)
-        listeners = this._eventRegistry[eventName] = [];
-
-    if (listeners.indexOf(callback) == -1)
-        listeners[capturing ? "unshift" : "push"](callback);
-    return callback;
-};
-
-EventEmitter.off =
-EventEmitter.removeListener =
-EventEmitter.removeEventListener = function(eventName, callback) {
-    this._eventRegistry = this._eventRegistry || {};
-
-    var listeners = this._eventRegistry[eventName];
-    if (!listeners)
-        return;
-
-    var index = listeners.indexOf(callback);
-    if (index !== -1)
-        listeners.splice(index, 1);
-};
-
-EventEmitter.removeAllListeners = function(eventName) {
-    if (this._eventRegistry) this._eventRegistry[eventName] = [];
-};
-
-exports.EventEmitter = EventEmitter;
-
-});
-
-define('ace/range', ['require', 'exports', 'module' ], function(require, exports, module) {
-
-var comparePoints = function(p1, p2) {
-    return p1.row - p2.row || p1.column - p2.column;
-};
-var Range = function(startRow, startColumn, endRow, endColumn) {
-    this.start = {
-        row: startRow,
-        column: startColumn
-    };
-
-    this.end = {
-        row: endRow,
-        column: endColumn
-    };
-};
-
-(function() {
-    this.isEqual = function(range) {
-        return this.start.row === range.start.row &&
-            this.end.row === range.end.row &&
-            this.start.column === range.start.column &&
-            this.end.column === range.end.column;
-    };
-    this.toString = function() {
-        return ("Range: [" + this.start.row + "/" + this.start.column +
-            "] -> [" + this.end.row + "/" + this.end.column + "]");
-    };
-
-    this.contains = function(row, column) {
-        return this.compare(row, column) == 0;
-    };
-    this.compareRange = function(range) {
-        var cmp,
-            end = range.end,
-            start = range.start;
-
-        cmp = this.compare(end.row, end.column);
-        if (cmp == 1) {
-            cmp = this.compare(start.row, start.column);
-            if (cmp == 1) {
-                return 2;
-            } else if (cmp == 0) {
-                return 1;
-            } else {
-                return 0;
-            }
-        } else if (cmp == -1) {
-            return -2;
-        } else {
-            cmp = this.compare(start.row, start.column);
-            if (cmp == -1) {
-                return -1;
-            } else if (cmp == 1) {
-                return 42;
-            } else {
-                return 0;
-            }
-        }
-    };
-    this.comparePoint = function(p) {
-        return this.compare(p.row, p.column);
-    };
-    this.containsRange = function(range) {
-        return this.comparePoint(range.start) == 0 && this.comparePoint(range.end) == 0;
-    };
-    this.intersects = function(range) {
-        var cmp = this.compareRange(range);
-        return (cmp == -1 || cmp == 0 || cmp == 1);
-    };
-    this.isEnd = function(row, column) {
-        return this.end.row == row && this.end.column == column;
-    };
-    this.isStart = function(row, column) {
-        return this.start.row == row && this.start.column == column;
-    };
-    this.setStart = function(row, column) {
-        if (typeof row == "object") {
-            this.start.column = row.column;
-            this.start.row = row.row;
-        } else {
-            this.start.row = row;
-            this.start.column = column;
-        }
-    };
-    this.setEnd = function(row, column) {
-        if (typeof row == "object") {
-            this.end.column = row.column;
-            this.end.row = row.row;
-        } else {
-            this.end.row = row;
-            this.end.column = column;
-        }
-    };
-    this.inside = function(row, column) {
-        if (this.compare(row, column) == 0) {
-            if (this.isEnd(row, column) || this.isStart(row, column)) {
-                return false;
-            } else {
-                return true;
-            }
-        }
-        return false;
-    };
-    this.insideStart = function(row, column) {
-        if (this.compare(row, column) == 0) {
-            if (this.isEnd(row, column)) {
-                return false;
-            } else {
-                return true;
-            }
-        }
-        return false;
-    };
-    this.insideEnd = function(row, column) {
-        if (this.compare(row, column) == 0) {
-            if (this.isStart(row, column)) {
-                return false;
-            } else {
-                return true;
-            }
-        }
-        return false;
-    };
-    this.compare = function(row, column) {
-        if (!this.isMultiLine()) {
-            if (row === this.start.row) {
-                return column < this.start.column ? -1 : (column > this.end.column ? 1 : 0);
-            };
-        }
-
-        if (row < this.start.row)
-            return -1;
-
-        if (row > this.end.row)
-            return 1;
-
-        if (this.start.row === row)
-            return column >= this.start.column ? 0 : -1;
-
-        if (this.end.row === row)
-            return column <= this.end.column ? 0 : 1;
-
-        return 0;
-    };
-    this.compareStart = function(row, column) {
-        if (this.start.row == row && this.start.column == column) {
-            return -1;
-        } else {
-            return this.compare(row, column);
-        }
-    };
-    this.compareEnd = function(row, column) {
-        if (this.end.row == row && this.end.column == column) {
-            return 1;
-        } else {
-            return this.compare(row, column);
-        }
-    };
-    this.compareInside = function(row, column) {
-        if (this.end.row == row && this.end.column == column) {
-            return 1;
-        } else if (this.start.row == row && this.start.column == column) {
-            return -1;
-        } else {
-            return this.compare(row, column);
-        }
-    };
-    this.clipRows = function(firstRow, lastRow) {
-        if (this.end.row > lastRow)
-            var end = {row: lastRow + 1, column: 0};
-        else if (this.end.row < firstRow)
-            var end = {row: firstRow, column: 0};
-
-        if (this.start.row > lastRow)
-            var start = {row: lastRow + 1, column: 0};
-        else if (this.start.row < firstRow)
-            var start = {row: firstRow, column: 0};
-
-        return Range.fromPoints(start || this.start, end || this.end);
-    };
-    this.extend = function(row, column) {
-        var cmp = this.compare(row, column);
-
-        if (cmp == 0)
-            return this;
-        else if (cmp == -1)
-            var start = {row: row, column: column};
-        else
-            var end = {row: row, column: column};
-
-        return Range.fromPoints(start || this.start, end || this.end);
-    };
-
-    this.isEmpty = function() {
-        return (this.start.row === this.end.row && this.start.column === this.end.column);
-    };
-    this.isMultiLine = function() {
-        return (this.start.row !== this.end.row);
-    };
-    this.clone = function() {
-        return Range.fromPoints(this.start, this.end);
-    };
-    this.collapseRows = function() {
-        if (this.end.column == 0)
-            return new Range(this.start.row, 0, Math.max(this.start.row, this.end.row-1), 0)
-        else
-            return new Range(this.start.row, 0, this.end.row, 0)
-    };
-    this.toScreenRange = function(session) {
-        var screenPosStart = session.documentToScreenPosition(this.start);
-        var screenPosEnd = session.documentToScreenPosition(this.end);
-
-        return new Range(
-            screenPosStart.row, screenPosStart.column,
-            screenPosEnd.row, screenPosEnd.column
-        );
-    };
-    this.moveBy = function(row, column) {
-        this.start.row += row;
-        this.start.column += column;
-        this.end.row += row;
-        this.end.column += column;
-    };
-
-}).call(Range.prototype);
-Range.fromPoints = function(start, end) {
-    return new Range(start.row, start.column, end.row, end.column);
-};
-Range.comparePoints = comparePoints;
-
-Range.comparePoints = function(p1, p2) {
-    return p1.row - p2.row || p1.column - p2.column;
-};
-
-
-exports.Range = Range;
-});
-
-define('ace/anchor', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter'], function(require, exports, module) {
-
-
-var oop = require("./lib/oop");
-var EventEmitter = require("./lib/event_emitter").EventEmitter;
-
-var Anchor = exports.Anchor = function(doc, row, column) {
-    this.$onChange = this.onChange.bind(this);
-    this.attach(doc);
-    
-    if (typeof column == "undefined")
-        this.setPosition(row.row, row.column);
-    else
-        this.setPosition(row, column);
-};
-
-(function() {
-
-    oop.implement(this, EventEmitter);
-    this.getPosition = function() {
-        return this.$clipPositionToDocument(this.row, this.column);
-    };
-    this.getDocument = function() {
-        return this.document;
-    };
-    this.$insertRight = false;
-    this.onChange = function(e) {
-        var delta = e.data;
-        var range = delta.range;
-
-        if (range.start.row == range.end.row && range.start.row != this.row)
-            return;
-
-        if (range.start.row > this.row)
-            return;
-
-        if (range.start.row == this.row && range.start.column > this.column)
-            return;
-
-        var row = this.row;
-        var column = this.column;
-        var start = range.start;
-        var end = range.end;
-
-        if (delta.action === "insertText") {
-            if (start.row === row && start.column <= column) {
-                if (start.column === column && this.$insertRight) {
-                } else if (start.row === end.row) {
-                    column += end.column - start.column;
-                } else {
-                    column -= start.column;
-                    row += end.row - start.row;
-                }
-            } else if (start.row !== end.row && start.row < row) {
-                row += end.row - start.row;
-            }
-        } else if (delta.action === "insertLines") {
-            if (start.row <= row) {
-                row += end.row - start.row;
-            }
-        } else if (delta.action === "removeText") {
-            if (start.row === row && start.column < column) {
-                if (end.column >= column)
-                    column = start.column;
-                else
-                    column = Math.max(0, column - (end.column - start.column));
-
-            } else if (start.row !== end.row && start.row < row) {
-                if (end.row === row)
-                    column = Math.max(0, column - end.column) + start.column;
-                row -= (end.row - start.row);
-            } else if (end.row === row) {
-                row -= end.row - start.row;
-                column = Math.max(0, column - end.column) + start.column;
-            }
-        } else if (delta.action == "removeLines") {
-            if (start.row <= row) {
-                if (end.row <= row)
-                    row -= end.row - start.row;
-                else {
-                    row = start.row;
-                    column = 0;
-                }
-            }
-        }
-
-        this.setPosition(row, column, true);
-    };
-    this.setPosition = function(row, column, noClip) {
-        var pos;
-        if (noClip) {
-            pos = {
-                row: row,
-                column: column
-            };
-        } else {
-            pos = this.$clipPositionToDocument(row, column);
-        }
-
-        if (this.row == pos.row && this.column == pos.column)
-            return;
-
-        var old = {
-            row: this.row,
-            column: this.column
-        };
-
-        this.row = pos.row;
-        this.column = pos.column;
-        this._emit("change", {
-            old: old,
-            value: pos
-        });
-    };
-    this.detach = function() {
-        this.document.removeEventListener("change", this.$onChange);
-    };
-    this.attach = function(doc) {
-        this.document = doc || this.document;
-        this.document.on("change", this.$onChange);
-    };
-    this.$clipPositionToDocument = function(row, column) {
-        var pos = {};
-
-        if (row >= this.document.getLength()) {
-            pos.row = Math.max(0, this.document.getLength() - 1);
-            pos.column = this.document.getLine(pos.row).length;
-        }
-        else if (row < 0) {
-            pos.row = 0;
-            pos.column = 0;
-        }
-        else {
-            pos.row = row;
-            pos.column = Math.min(this.document.getLine(pos.row).length, Math.max(0, column));
-        }
-
-        if (column < 0)
-            pos.column = 0;
-
-        return pos;
-    };
-
-}).call(Anchor.prototype);
-
-});
-
-define('ace/lib/lang', ['require', 'exports', 'module' ], function(require, exports, module) {
-
-
-exports.stringReverse = function(string) {
-    return string.split("").reverse().join("");
-};
-
-exports.stringRepeat = function (string, count) {
-    var result = '';
-    while (count > 0) {
-        if (count & 1)
-            result += string;
-
-        if (count >>= 1)
-            string += string;
-    }
-    return result;
-};
-
-var trimBeginRegexp = /^\s\s*/;
-var trimEndRegexp = /\s\s*$/;
-
-exports.stringTrimLeft = function (string) {
-    return string.replace(trimBeginRegexp, '');
-};
-
-exports.stringTrimRight = function (string) {
-    return string.replace(trimEndRegexp, '');
-};
-
-exports.copyObject = function(obj) {
-    var copy = {};
-    for (var key in obj) {
-        copy[key] = obj[key];
-    }
-    return copy;
-};
-
-exports.copyArray = function(array){
-    var copy = [];
-    for (var i=0, l=array.length; i<l; i++) {
-        if (array[i] && typeof array[i] == "object")
-            copy[i] = this.copyObject( array[i] );
-        else 
-            copy[i] = array[i];
-    }
-    return copy;
-};
-
-exports.deepCopy = function (obj) {
-    if (typeof obj != "object") {
-        return obj;
-    }
-    
-    var copy = obj.constructor();
-    for (var key in obj) {
-        if (typeof obj[key] == "object") {
-            copy[key] = this.deepCopy(obj[key]);
-        } else {
-            copy[key] = obj[key];
-        }
-    }
-    return copy;
-};
-
-exports.arrayToMap = function(arr) {
-    var map = {};
-    for (var i=0; i<arr.length; i++) {
-        map[arr[i]] = 1;
-    }
-    return map;
-
-};
-
-exports.createMap = function(props) {
-    var map = Object.create(null);
-    for (var i in props) {
-        map[i] = props[i];
-    }
-    return map;
-};
-exports.arrayRemove = function(array, value) {
-  for (var i = 0; i <= array.length; i++) {
-    if (value === array[i]) {
-      array.splice(i, 1);
-    }
-  }
-};
-
-exports.escapeRegExp = function(str) {
-    return str.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1');
-};
-
-exports.escapeHTML = function(str) {
-    return str.replace(/&/g, "&#38;").replace(/"/g, "&#34;").replace(/'/g, "&#39;").replace(/</g, "&#60;");
-};
-
-exports.getMatchOffsets = function(string, regExp) {
-    var matches = [];
-
-    string.replace(regExp, function(str) {
-        matches.push({
-            offset: arguments[arguments.length-2],
-            length: str.length
-        });
-    });
-
-    return matches;
-};
-exports.deferredCall = function(fcn) {
-
-    var timer = null;
-    var callback = function() {
-        timer = null;
-        fcn();
-    };
-
-    var deferred = function(timeout) {
-        deferred.cancel();
-        timer = setTimeout(callback, timeout || 0);
-        return deferred;
-    };
-
-    deferred.schedule = deferred;
-
-    deferred.call = function() {
-        this.cancel();
-        fcn();
-        return deferred;
-    };
-
-    deferred.cancel = function() {
-        clearTimeout(timer);
-        timer = null;
-        return deferred;
-    };
-
-    return deferred;
-};
-
-
-exports.delayedCall = function(fcn, defaultTimeout) {
-    var timer = null;
-    var callback = function() {
-        timer = null;
-        fcn();
-    };
-
-    var _self = function(timeout) {
-        timer && clearTimeout(timer);
-        timer = setTimeout(callback, timeout || defaultTimeout);
-    };
-
-    _self.delay = _self;
-    _self.schedule = function(timeout) {
-        if (timer == null)
-            timer = setTimeout(callback, timeout || 0);
-    };
-
-    _self.call = function() {
-        this.cancel();
-        fcn();
-    };
-
-    _self.cancel = function() {
-        timer && clearTimeout(timer);
-        timer = null;
-    };
-
-    _self.isPending = function() {
-        return timer;
-    };
-
-    return _self;
-};
-});
-
-define('ace/mode/json/json_parse', ['require', 'exports', 'module' ], function(require, exports, module) {
-
-    var at,     // The index of the current character
-        ch,     // The current character
-        escapee = {
-            '"':  '"',
-            '\\': '\\',
-            '/':  '/',
-            b:    '\b',
-            f:    '\f',
-            n:    '\n',
-            r:    '\r',
-            t:    '\t'
-        },
-        text,
-
-        error = function (m) {
-
-            throw {
-                name:    'SyntaxError',
-                message: m,
-                at:      at,
-                text:    text
-            };
-        },
-
-        next = function (c) {
-
-            if (c && c !== ch) {
-                error("Expected '" + c + "' instead of '" + ch + "'");
-            }
-
-            ch = text.charAt(at);
-            at += 1;
-            return ch;
-        },
-
-        number = function () {
-
-            var number,
-                string = '';
-
-            if (ch === '-') {
-                string = '-';
-                next('-');
-            }
-            while (ch >= '0' && ch <= '9') {
-                string += ch;
-                next();
-            }
-            if (ch === '.') {
-                string += '.';
-                while (next() && ch >= '0' && ch <= '9') {
-                    string += ch;
-                }
-            }
-            if (ch === 'e' || ch === 'E') {
-                string += ch;
-                next();
-                if (ch === '-' || ch === '+') {
-                    string += ch;
-                    next();
-                }
-                while (ch >= '0' && ch <= '9') {
-                    string += ch;
-                    next();
-                }
-            }
-            number = +string;
-            if (isNaN(number)) {
-                error("Bad number");
-            } else {
-                return number;
-            }
-        },
-
-        string = function () {
-
-            var hex,
-                i,
-                string = '',
-                uffff;
-
-            if (ch === '"') {
-                while (next()) {
-                    if (ch === '"') {
-                        next();
-                        return string;
-                    } else if (ch === '\\') {
-                        next();
-                        if (ch === 'u') {
-                            uffff = 0;
-                            for (i = 0; i < 4; i += 1) {
-                                hex = parseInt(next(), 16);
-                                if (!isFinite(hex)) {
-                                    break;
-                                }
-                                uffff = uffff * 16 + hex;
-                            }
-                            string += String.fromCharCode(uffff);
-                        } else if (typeof escapee[ch] === 'string') {
-                            string += escapee[ch];
-                        } else {
-                            break;
-                        }
-                    } else {
-                        string += ch;
-                    }
-                }
-            }
-            error("Bad string");
-        },
-
-        white = function () {
-
-            while (ch && ch <= ' ') {
-                next();
-            }
-        },
-
-        word = function () {
-
-            switch (ch) {
-            case 't':
-                next('t');
-                next('r');
-                next('u');
-                next('e');
-                return true;
-            case 'f':
-                next('f');
-                next('a');
-                next('l');
-                next('s');
-                next('e');
-                return false;
-            case 'n':
-                next('n');
-                next('u');
-                next('l');
-                next('l');
-                return null;
-            }
-            error("Unexpected '" + ch + "'");
-        },
-
-        value,  // Place holder for the value function.
-
-        array = function () {
-
-            var array = [];
-
-            if (ch === '[') {
-                next('[');
-                white();
-                if (ch === ']') {
-                    next(']');
-                    return array;   // empty array
-                }
-                while (ch) {
-                    array.push(value());
-                    white();
-                    if (ch === ']') {
-                        next(']');
-                        return array;
-                    }
-                    next(',');
-                    white();
-                }
-            }
-            error("Bad array");
-        },
-
-        object = function () {
-
-            var key,
-                object = {};
-
-            if (ch === '{') {
-                next('{');
-                white();
-                if (ch === '}') {
-                    next('}');
-                    return object;   // empty object
-                }
-                while (ch) {
-                    key = string();
-                    white();
-                    next(':');
-                    if (Object.hasOwnProperty.call(object, key)) {
-                        error('Duplicate key "' + key + '"');
-                    }
-                    object[key] = value();
-                    white();
-                    if (ch === '}') {
-                        next('}');
-                        return object;
-                    }
-                    next(',');
-                    white();
-                }
-            }
-            error("Bad object");
-        };
-
-    value = function () {
-
-        white();
-        switch (ch) {
-        case '{':
-            return object();
-        case '[':
-            return array();
-        case '"':
-            return string();
-        case '-':
-            return number();
-        default:
-            return ch >= '0' && ch <= '9' ? number() : word();
-        }
-    };
-
-    return function (source, reviver) {
-        var result;
-
-        text = source;
-        at = 0;
-        ch = ' ';
-        result = value();
-        white();
-        if (ch) {
-            error("Syntax error");
-        }
-
-        return typeof reviver === 'function' ? function walk(holder, key) {
-            var k, v, value = holder[key];
-            if (value && typeof value === 'object') {
-                for (k in value) {
-                    if (Object.hasOwnProperty.call(value, k)) {
-                        v = walk(value, k);
-                        if (v !== undefined) {
-                            value[k] = v;
-                        } else {
-                            delete value[k];
-                        }
-                    }
-                }
-            }
-            return reviver.call(holder, key, value);
-        }({'': result}, '') : result;
-    };
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/js/libs/almond.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/js/libs/almond.js b/apps/fauxton/assets/js/libs/almond.js
deleted file mode 100644
index f530767..0000000
--- a/apps/fauxton/assets/js/libs/almond.js
+++ /dev/null
@@ -1,314 +0,0 @@
-/**
- * almond 0.1.1 Copyright (c) 2011, The Dojo Foundation All Rights Reserved.
- * Available via the MIT or new BSD license.
- * see: http://github.com/jrburke/almond for details
- */
-//Going sloppy to avoid 'use strict' string cost, but strict practices should
-//be followed.
-/*jslint sloppy: true */
-/*global setTimeout: false */
-
-var requirejs, require, define;
-(function (undef) {
-    var defined = {},
-        waiting = {},
-        config = {},
-        defining = {},
-        aps = [].slice,
-        main, req;
-
-    /**
-     * Given a relative module name, like ./something, normalize it to
-     * a real name that can be mapped to a path.
-     * @param {String} name the relative name
-     * @param {String} baseName a real name that the name arg is relative
-     * to.
-     * @returns {String} normalized name
-     */
-    function normalize(name, baseName) {
-        var baseParts = baseName && baseName.split("/"),
-            map = config.map,
-            starMap = (map && map['*']) || {},
-            nameParts, nameSegment, mapValue, foundMap, i, j, part;
-
-        //Adjust any relative paths.
-        if (name && name.charAt(0) === ".") {
-            //If have a base name, try to normalize against it,
-            //otherwise, assume it is a top-level require that will
-            //be relative to baseUrl in the end.
-            if (baseName) {
-                //Convert baseName to array, and lop off the last part,
-                //so that . matches that "directory" and not name of the baseName's
-                //module. For instance, baseName of "one/two/three", maps to
-                //"one/two/three.js", but we want the directory, "one/two" for
-                //this normalization.
-                baseParts = baseParts.slice(0, baseParts.length - 1);
-
-                name = baseParts.concat(name.split("/"));
-
-                //start trimDots
-                for (i = 0; (part = name[i]); i++) {
-                    if (part === ".") {
-                        name.splice(i, 1);
-                        i -= 1;
-                    } else if (part === "..") {
-                        if (i === 1 && (name[2] === '..' || name[0] === '..')) {
-                            //End of the line. Keep at least one non-dot
-                            //path segment at the front so it can be mapped
-                            //correctly to disk. Otherwise, there is likely
-                            //no path mapping for a path starting with '..'.
-                            //This can still fail, but catches the most reasonable
-                            //uses of ..
-                            return true;
-                        } else if (i > 0) {
-                            name.splice(i - 1, 2);
-                            i -= 2;
-                        }
-                    }
-                }
-                //end trimDots
-
-                name = name.join("/");
-            }
-        }
-
-        //Apply map config if available.
-        if ((baseParts || starMap) && map) {
-            nameParts = name.split('/');
-
-            for (i = nameParts.length; i > 0; i -= 1) {
-                nameSegment = nameParts.slice(0, i).join("/");
-
-                if (baseParts) {
-                    //Find the longest baseName segment match in the config.
-                    //So, do joins on the biggest to smallest lengths of baseParts.
-                    for (j = baseParts.length; j > 0; j -= 1) {
-                        mapValue = map[baseParts.slice(0, j).join('/')];
-
-                        //baseName segment has  config, find if it has one for
-                        //this name.
-                        if (mapValue) {
-                            mapValue = mapValue[nameSegment];
-                            if (mapValue) {
-                                //Match, update name to the new value.
-                                foundMap = mapValue;
-                                break;
-                            }
-                        }
-                    }
-                }
-
-                foundMap = foundMap || starMap[nameSegment];
-
-                if (foundMap) {
-                    nameParts.splice(0, i, foundMap);
-                    name = nameParts.join('/');
-                    break;
-                }
-            }
-        }
-
-        return name;
-    }
-
-    function makeRequire(relName, forceSync) {
-        return function () {
-            //A version of a require function that passes a moduleName
-            //value for items that may need to
-            //look up paths relative to the moduleName
-            return req.apply(undef, aps.call(arguments, 0).concat([relName, forceSync]));
-        };
-    }
-
-    function makeNormalize(relName) {
-        return function (name) {
-            return normalize(name, relName);
-        };
-    }
-
-    function makeLoad(depName) {
-        return function (value) {
-            defined[depName] = value;
-        };
-    }
-
-    function callDep(name) {
-        if (waiting.hasOwnProperty(name)) {
-            var args = waiting[name];
-            delete waiting[name];
-            defining[name] = true;
-            main.apply(undef, args);
-        }
-
-        if (!defined.hasOwnProperty(name)) {
-            throw new Error('No ' + name);
-        }
-        return defined[name];
-    }
-
-    /**
-     * Makes a name map, normalizing the name, and using a plugin
-     * for normalization if necessary. Grabs a ref to plugin
-     * too, as an optimization.
-     */
-    function makeMap(name, relName) {
-        var prefix, plugin,
-            index = name.indexOf('!');
-
-        if (index !== -1) {
-            prefix = normalize(name.slice(0, index), relName);
-            name = name.slice(index + 1);
-            plugin = callDep(prefix);
-
-            //Normalize according
-            if (plugin && plugin.normalize) {
-                name = plugin.normalize(name, makeNormalize(relName));
-            } else {
-                name = normalize(name, relName);
-            }
-        } else {
-            name = normalize(name, relName);
-        }
-
-        //Using ridiculous property names for space reasons
-        return {
-            f: prefix ? prefix + '!' + name : name, //fullName
-            n: name,
-            p: plugin
-        };
-    }
-
-    function makeConfig(name) {
-        return function () {
-            return (config && config.config && config.config[name]) || {};
-        };
-    }
-
-    main = function (name, deps, callback, relName) {
-        var args = [],
-            usingExports,
-            cjsModule, depName, ret, map, i;
-
-        //Use name if no relName
-        relName = relName || name;
-
-        //Call the callback to define the module, if necessary.
-        if (typeof callback === 'function') {
-
-            //Pull out the defined dependencies and pass the ordered
-            //values to the callback.
-            //Default to [require, exports, module] if no deps
-            deps = !deps.length && callback.length ? ['require', 'exports', 'module'] : deps;
-            for (i = 0; i < deps.length; i++) {
-                map = makeMap(deps[i], relName);
-                depName = map.f;
-
-                //Fast path CommonJS standard dependencies.
-                if (depName === "require") {
-                    args[i] = makeRequire(name);
-                } else if (depName === "exports") {
-                    //CommonJS module spec 1.1
-                    args[i] = defined[name] = {};
-                    usingExports = true;
-                } else if (depName === "module") {
-                    //CommonJS module spec 1.1
-                    cjsModule = args[i] = {
-                        id: name,
-                        uri: '',
-                        exports: defined[name],
-                        config: makeConfig(name)
-                    };
-                } else if (defined.hasOwnProperty(depName) || waiting.hasOwnProperty(depName)) {
-                    args[i] = callDep(depName);
-                } else if (map.p) {
-                    map.p.load(map.n, makeRequire(relName, true), makeLoad(depName), {});
-                    args[i] = defined[depName];
-                } else if (!defining[depName]) {
-                    throw new Error(name + ' missing ' + depName);
-                }
-            }
-
-            ret = callback.apply(defined[name], args);
-
-            if (name) {
-                //If setting exports via "module" is in play,
-                //favor that over return value and exports. After that,
-                //favor a non-undefined return value over exports use.
-                if (cjsModule && cjsModule.exports !== undef &&
-                    cjsModule.exports !== defined[name]) {
-                    defined[name] = cjsModule.exports;
-                } else if (ret !== undef || !usingExports) {
-                    //Use the return value from the function.
-                    defined[name] = ret;
-                }
-            }
-        } else if (name) {
-            //May just be an object definition for the module. Only
-            //worry about defining if have a module name.
-            defined[name] = callback;
-        }
-    };
-
-    requirejs = require = req = function (deps, callback, relName, forceSync) {
-        if (typeof deps === "string") {
-            //Just return the module wanted. In this scenario, the
-            //deps arg is the module name, and second arg (if passed)
-            //is just the relName.
-            //Normalize module name, if it contains . or ..
-            return callDep(makeMap(deps, callback).f);
-        } else if (!deps.splice) {
-            //deps is a config object, not an array.
-            config = deps;
-            if (callback.splice) {
-                //callback is an array, which means it is a dependency list.
-                //Adjust args if there are dependencies
-                deps = callback;
-                callback = relName;
-                relName = null;
-            } else {
-                deps = undef;
-            }
-        }
-
-        //Support require(['a'])
-        callback = callback || function () {};
-
-        //Simulate async callback;
-        if (forceSync) {
-            main(undef, deps, callback, relName);
-        } else {
-            setTimeout(function () {
-                main(undef, deps, callback, relName);
-            }, 15);
-        }
-
-        return req;
-    };
-
-    /**
-     * Just drops the config on the floor, but returns req in case
-     * the config return value is used.
-     */
-    req.config = function (cfg) {
-        config = cfg;
-        return req;
-    };
-
-    define = function (name, deps, callback) {
-
-        //This module may not have dependencies
-        if (!deps.splice) {
-            //deps is not an array, so probably means
-            //an object literal or factory function for
-            //the value. Adjust args.
-            callback = deps;
-            deps = [];
-        }
-
-        waiting[name] = [name, deps, callback];
-    };
-
-    define.amd = {
-        jQuery: true
-    };
-}());


[26/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/js/libs/ace/ext-chromevox.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/js/libs/ace/ext-chromevox.js b/apps/fauxton/assets/js/libs/ace/ext-chromevox.js
deleted file mode 100644
index 67258f7..0000000
--- a/apps/fauxton/assets/js/libs/ace/ext-chromevox.js
+++ /dev/null
@@ -1,537 +0,0 @@
-define('ace/ext/chromevox', ['require', 'exports', 'module' , 'ace/editor', 'ace/config'], function(require, exports, module) {
-var cvoxAce = {};
-cvoxAce.SpeechProperty;
-cvoxAce.Cursor;
-cvoxAce.Token;
-cvoxAce.Annotation;
-var CONSTANT_PROP = {
-  'rate': 0.8,
-  'pitch': 0.4,
-  'volume': 0.9
-};
-var DEFAULT_PROP = {
-  'rate': 1,
-  'pitch': 0.5,
-  'volume': 0.9
-};
-var ENTITY_PROP = {
-  'rate': 0.8,
-  'pitch': 0.8,
-  'volume': 0.9
-};
-var KEYWORD_PROP = {
-  'rate': 0.8,
-  'pitch': 0.3,
-  'volume': 0.9
-};
-var STORAGE_PROP = {
-  'rate': 0.8,
-  'pitch': 0.7,
-  'volume': 0.9
-};
-var VARIABLE_PROP = {
-  'rate': 0.8,
-  'pitch': 0.8,
-  'volume': 0.9
-};
-var DELETED_PROP = {
-  'punctuationEcho': 'none',
-  'relativePitch': -0.6
-};
-var ERROR_EARCON = 'ALERT_NONMODAL';
-var MODE_SWITCH_EARCON = 'ALERT_MODAL';
-var NO_MATCH_EARCON = 'INVALID_KEYPRESS';
-var INSERT_MODE_STATE = 'insertMode';
-var COMMAND_MODE_STATE = 'start';
-
-var REPLACE_LIST = [
-  {
-    substr: ';',
-    newSubstr: ' semicolon '
-  },
-  {
-    substr: ':',
-    newSubstr: ' colon '
-  }
-];
-var Command = {
-  SPEAK_ANNOT: 'annots',
-  SPEAK_ALL_ANNOTS: 'all_annots',
-  TOGGLE_LOCATION: 'toggle_location',
-  SPEAK_MODE: 'mode',
-  SPEAK_ROW_COL: 'row_col',
-  TOGGLE_DISPLACEMENT: 'toggle_displacement',
-  FOCUS_TEXT: 'focus_text'
-};
-var KEY_PREFIX = 'CONTROL + SHIFT ';
-cvoxAce.editor = null;
-var lastCursor = null;
-var annotTable = {};
-var shouldSpeakRowLocation = false;
-var shouldSpeakDisplacement = false;
-var changed = false;
-var vimState = null;
-var keyCodeToShortcutMap = {};
-var cmdToShortcutMap = {};
-var getKeyShortcutString = function(keyCode) {
-  return KEY_PREFIX + String.fromCharCode(keyCode);
-};
-var isVimMode = function() {
-  var keyboardHandler = cvoxAce.editor.keyBinding.getKeyboardHandler();
-  return keyboardHandler.$id === 'ace/keyboard/vim';
-};
-var getCurrentToken = function(cursor) {
-  return cvoxAce.editor.getSession().getTokenAt(cursor.row, cursor.column + 1);
-};
-var getCurrentLine = function(cursor) {
-  return cvoxAce.editor.getSession().getLine(cursor.row);
-};
-var onRowChange = function(currCursor) {
-  if (annotTable[currCursor.row]) {
-    cvox.Api.playEarcon(ERROR_EARCON);
-  }
-  if (shouldSpeakRowLocation) {
-    cvox.Api.stop();
-    speakChar(currCursor);
-    speakTokenQueue(getCurrentToken(currCursor));
-    speakLine(currCursor.row, 1);
-  } else {
-    speakLine(currCursor.row, 0);
-  }
-};
-var isWord = function(cursor) {
-  var line = getCurrentLine(cursor);
-  var lineSuffix = line.substr(cursor.column - 1);
-  if (cursor.column === 0) {
-    lineSuffix = ' ' + line;
-  }
-  var firstWordRegExp = /^\W(\w+)/;
-  var words = firstWordRegExp.exec(lineSuffix);
-  return words !== null;
-};
-var rules = {
-  'constant': {
-    prop: CONSTANT_PROP
-  },
-  'entity': {
-    prop: ENTITY_PROP
-  },
-  'keyword': {
-    prop: KEYWORD_PROP
-  },
-  'storage': {
-    prop: STORAGE_PROP
-  },
-  'variable': {
-    prop: VARIABLE_PROP
-  },
-  'meta': {
-    prop: DEFAULT_PROP,
-    replace: [
-      {
-        substr: '</',
-        newSubstr: ' closing tag '
-      },
-      {
-        substr: '/>',
-        newSubstr: ' close tag '
-      },
-      {
-        substr: '<',
-        newSubstr: ' tag start '
-      },
-      {
-        substr: '>',
-        newSubstr: ' tag end '
-      }
-    ]
-  }
-};
-var DEFAULT_RULE = {
-  prop: DEFAULT_RULE
-};
-var expand = function(value, replaceRules) {
-  var newValue = value;
-  for (var i = 0; i < replaceRules.length; i++) {
-    var replaceRule = replaceRules[i];
-    var regexp = new RegExp(replaceRule.substr, 'g');
-    newValue = newValue.replace(regexp, replaceRule.newSubstr);
-  }
-  return newValue;
-};
-var mergeTokens = function(tokens, start, end) {
-  var newToken = {};
-  newToken.value = '';
-  newToken.type = tokens[start].type;
-  for (var j = start; j < end; j++) {
-    newToken.value += tokens[j].value;
-  }
-  return newToken;
-};
-var mergeLikeTokens = function(tokens) {
-  if (tokens.length <= 1) {
-    return tokens;
-  }
-  var newTokens = [];
-  var lastLikeIndex = 0;
-  for (var i = 1; i < tokens.length; i++) {
-    var lastLikeToken = tokens[lastLikeIndex];
-    var currToken = tokens[i];
-    if (getTokenRule(lastLikeToken) !== getTokenRule(currToken)) {
-      newTokens.push(mergeTokens(tokens, lastLikeIndex, i));
-      lastLikeIndex = i;
-    }
-  }
-  newTokens.push(mergeTokens(tokens, lastLikeIndex, tokens.length));
-  return newTokens;
-};
-var isRowWhiteSpace = function(row) {
-  var line = cvoxAce.editor.getSession().getLine(row);
-  var whiteSpaceRegexp = /^\s*$/;
-  return whiteSpaceRegexp.exec(line) !== null;
-};
-var speakLine = function(row, queue) {
-  var tokens = cvoxAce.editor.getSession().getTokens(row);
-  if (tokens.length === 0 || isRowWhiteSpace(row)) {
-    cvox.Api.playEarcon('EDITABLE_TEXT');
-    return;
-  }
-  tokens = mergeLikeTokens(tokens);
-  var firstToken = tokens[0];
-  tokens = tokens.filter(function(token) {
-    return token !== firstToken;
-  });
-  speakToken_(firstToken, queue);
-  tokens.forEach(speakTokenQueue);
-};
-var speakTokenFlush = function(token) {
-  speakToken_(token, 0);
-};
-var speakTokenQueue = function(token) {
-  speakToken_(token, 1);
-};
-var getTokenRule = function(token) {
-  if (!token || !token.type) {
-    return;
-  }
-  var split = token.type.split('.');
-  if (split.length === 0) {
-    return;
-  }
-  var type = split[0];
-  var rule = rules[type];
-  if (!rule) {
-    return DEFAULT_RULE;
-  }
-  return rule;
-};
-var speakToken_ = function(token, queue) {
-  var rule = getTokenRule(token);
-  var value = expand(token.value, REPLACE_LIST);
-  if (rule.replace) {
-    value = expand(value, rule.replace);
-  }
-  cvox.Api.speak(value, queue, rule.prop);
-};
-var speakChar = function(cursor) {
-  var line = getCurrentLine(cursor);
-  cvox.Api.speak(line[cursor.column], 1);
-};
-var speakDisplacement = function(lastCursor, currCursor) {
-  var line = getCurrentLine(currCursor);
-  var displace = line.substring(lastCursor.column, currCursor.column);
-  displace = displace.replace(/ /g, ' space ');
-  cvox.Api.speak(displace);
-};
-var speakCharOrWordOrLine = function(lastCursor, currCursor) {
-  if (Math.abs(lastCursor.column - currCursor.column) !== 1) {
-    var currLineLength = getCurrentLine(currCursor).length;
-    if (currCursor.column === 0 || currCursor.column === currLineLength) {
-      speakLine(currCursor.row, 0);
-      return;
-    }
-    if (isWord(currCursor)) {
-      cvox.Api.stop();
-      speakTokenQueue(getCurrentToken(currCursor));
-      return;
-    }
-  }
-  speakChar(currCursor);
-};
-var onColumnChange = function(lastCursor, currCursor) {
-  if (!cvoxAce.editor.selection.isEmpty()) {
-    speakDisplacement(lastCursor, currCursor);
-    cvox.Api.speak('selected', 1);
-  }
-  else if (shouldSpeakDisplacement) {
-    speakDisplacement(lastCursor, currCursor);
-  } else {
-    speakCharOrWordOrLine(lastCursor, currCursor);
-  }
-};
-var onCursorChange = function(evt) {
-  if (changed) {
-    changed = false;
-    return;
-  }
-  var currCursor = cvoxAce.editor.selection.getCursor();
-  if (currCursor.row !== lastCursor.row) {
-    onRowChange(currCursor);
-  } else {
-    onColumnChange(lastCursor, currCursor);
-  }
-  lastCursor = currCursor;
-};
-var onSelectionChange = function(evt) {
-  if (cvoxAce.editor.selection.isEmpty()) {
-    cvox.Api.speak('unselected');
-  }
-};
-var onChange = function(evt) {
-  var data = evt.data;
-  switch (data.action) {
-  case 'removeText':
-    cvox.Api.speak(data.text, 0, DELETED_PROP);
-    changed = true;
-    break;
-  case 'insertText':
-    cvox.Api.speak(data.text, 0);
-    changed = true;
-    break;
-  }
-};
-var isNewAnnotation = function(annot) {
-  var row = annot.row;
-  var col = annot.column;
-  return !annotTable[row] || !annotTable[row][col];
-};
-var populateAnnotations = function(annotations) {
-  annotTable = {};
-  for (var i = 0; i < annotations.length; i++) {
-    var annotation = annotations[i];
-    var row = annotation.row;
-    var col = annotation.column;
-    if (!annotTable[row]) {
-      annotTable[row] = {};
-    }
-    annotTable[row][col] = annotation;
-  }
-};
-var onAnnotationChange = function(evt) {
-  var annotations = cvoxAce.editor.getSession().getAnnotations();
-  var newAnnotations = annotations.filter(isNewAnnotation);
-  if (newAnnotations.length > 0) {
-    cvox.Api.playEarcon(ERROR_EARCON);
-  }
-  populateAnnotations(annotations);
-};
-var speakAnnot = function(annot) {
-  var annotText = annot.type + ' ' + annot.text + ' on ' +
-      rowColToString(annot.row, annot.column);
-  annotText = annotText.replace(';', 'semicolon');
-  cvox.Api.speak(annotText, 1);
-};
-var speakAnnotsByRow = function(row) {
-  var annots = annotTable[row];
-  for (var col in annots) {
-    speakAnnot(annots[col]);
-  }
-};
-var rowColToString = function(row, col) {
-  return 'row ' + (row + 1) + ' column ' + (col + 1);
-};
-var speakCurrRowAndCol = function() {
-  cvox.Api.speak(rowColToString(lastCursor.row, lastCursor.column));
-};
-var speakAllAnnots = function() {
-  for (var row in annotTable) {
-    speakAnnotsByRow(row);
-  }
-};
-var speakMode = function() {
-  if (!isVimMode()) {
-    return;
-  }
-  switch (cvoxAce.editor.keyBinding.$data.state) {
-  case INSERT_MODE_STATE:
-    cvox.Api.speak('Insert mode');
-    break;
-  case COMMAND_MODE_STATE:
-    cvox.Api.speak('Command mode');
-    break;
-  }
-};
-var toggleSpeakRowLocation = function() {
-  shouldSpeakRowLocation = !shouldSpeakRowLocation;
-  if (shouldSpeakRowLocation) {
-    cvox.Api.speak('Speak location on row change enabled.');
-  } else {
-    cvox.Api.speak('Speak location on row change disabled.');
-  }
-};
-var toggleSpeakDisplacement = function() {
-  shouldSpeakDisplacement = !shouldSpeakDisplacement;
-  if (shouldSpeakDisplacement) {
-    cvox.Api.speak('Speak displacement on column changes.');
-  } else {
-    cvox.Api.speak('Speak current character or word on column changes.');
-  }
-};
-var onKeyDown = function(evt) {
-  if (evt.ctrlKey && evt.shiftKey) {
-    var shortcut = keyCodeToShortcutMap[evt.keyCode];
-    if (shortcut) {
-      shortcut.func();
-    }
-  }
-};
-var onChangeStatus = function(evt, editor) {
-  if (!isVimMode()) {
-    return;
-  }
-  var state = editor.keyBinding.$data.state;
-  if (state === vimState) {
-    return;
-  }
-  switch (state) {
-  case INSERT_MODE_STATE:
-    cvox.Api.playEarcon(MODE_SWITCH_EARCON);
-    cvox.Api.setKeyEcho(true);
-    break;
-  case COMMAND_MODE_STATE:
-    cvox.Api.playEarcon(MODE_SWITCH_EARCON);
-    cvox.Api.setKeyEcho(false);
-    break;
-  }
-  vimState = state;
-};
-var contextMenuHandler = function(evt) {
-  var cmd = evt.detail['customCommand'];
-  var shortcut = cmdToShortcutMap[cmd];
-  if (shortcut) {
-    shortcut.func();
-    cvoxAce.editor.focus();
-  }
-};
-var initContextMenu = function() {
-  var ACTIONS = SHORTCUTS.map(function(shortcut) {
-    return {
-      desc: shortcut.desc + getKeyShortcutString(shortcut.keyCode),
-      cmd: shortcut.cmd
-    };
-  });
-  var body = document.querySelector('body');
-  body.setAttribute('contextMenuActions', JSON.stringify(ACTIONS));
-  body.addEventListener('ATCustomEvent', contextMenuHandler, true);
-};
-var onFindSearchbox = function(evt) {
-  if (evt.match) {
-    speakLine(lastCursor.row, 0);
-  } else {
-    cvox.Api.playEarcon(NO_MATCH_EARCON);
-  }
-};
-var focus = function() {
-  cvoxAce.editor.focus();
-};
-var SHORTCUTS = [
-  {
-    keyCode: 49,
-    func: function() {
-      speakAnnotsByRow(lastCursor.row);
-    },
-    cmd: Command.SPEAK_ANNOT,
-    desc: 'Speak annotations on line'
-  },
-  {
-    keyCode: 50,
-    func: speakAllAnnots,
-    cmd: Command.SPEAK_ALL_ANNOTS,
-    desc: 'Speak all annotations'
-  },
-  {
-    keyCode: 51,
-    func: speakMode,
-    cmd: Command.SPEAK_MODE,
-    desc: 'Speak Vim mode'
-  },
-  {
-    keyCode: 52,
-    func: toggleSpeakRowLocation,
-    cmd: Command.TOGGLE_LOCATION,
-    desc: 'Toggle speak row location'
-  },
-  {
-    keyCode: 53,
-    func: speakCurrRowAndCol,
-    cmd: Command.SPEAK_ROW_COL,
-    desc: 'Speak row and column'
-  },
-  {
-    keyCode: 54,
-    func: toggleSpeakDisplacement,
-    cmd: Command.TOGGLE_DISPLACEMENT,
-    desc: 'Toggle speak displacement'
-  },
-  {
-    keyCode: 55,
-    func: focus,
-    cmd: Command.FOCUS_TEXT,
-    desc: 'Focus text'
-  }
-];
-var onFocus = function() {
-  cvoxAce.editor = editor;
-  editor.getSession().selection.on('changeCursor', onCursorChange);
-  editor.getSession().selection.on('changeSelection', onSelectionChange);
-  editor.getSession().on('change', onChange);
-  editor.getSession().on('changeAnnotation', onAnnotationChange);
-  editor.on('changeStatus', onChangeStatus);
-  editor.on('findSearchBox', onFindSearchbox);
-  editor.container.addEventListener('keydown', onKeyDown);
-
-  lastCursor = editor.selection.getCursor();
-};
-var init = function(editor) {
-  onFocus();
-  SHORTCUTS.forEach(function(shortcut) {
-    keyCodeToShortcutMap[shortcut.keyCode] = shortcut;
-    cmdToShortcutMap[shortcut.cmd] = shortcut;
-  });
-
-  editor.on('focus', onFocus);
-  if (isVimMode()) {
-    cvox.Api.setKeyEcho(false);
-  }
-  initContextMenu();
-};
-function cvoxApiExists() {
-  return (typeof(cvox) !== 'undefined') && cvox && cvox.Api;
-}
-var tries = 0;
-var MAX_TRIES = 15;
-function watchForCvoxLoad(editor) {
-  if (cvoxApiExists()) {
-    init(editor);
-  } else {
-    tries++;
-    if (tries >= MAX_TRIES) {
-      return;
-    }
-    window.setTimeout(watchForCvoxLoad, 500, editor);
-  }
-}
-
-var Editor = require('../editor').Editor;
-require('../config').defineOptions(Editor.prototype, 'editor', {
-  enableChromevoxEnhancements: {
-    set: function(val) {
-      if (val) {
-        watchForCvoxLoad(this);
-      }
-    },
-    value: true // turn it on by default or check for window.cvox
-  }
-});
-
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/js/libs/ace/ext-elastic_tabstops_lite.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/js/libs/ace/ext-elastic_tabstops_lite.js b/apps/fauxton/assets/js/libs/ace/ext-elastic_tabstops_lite.js
deleted file mode 100644
index 75abada..0000000
--- a/apps/fauxton/assets/js/libs/ace/ext-elastic_tabstops_lite.js
+++ /dev/null
@@ -1,301 +0,0 @@
-/* ***** BEGIN LICENSE BLOCK *****
- * Distributed under the BSD license:
- *
- * Copyright (c) 2012, Ajax.org B.V.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above copyright
- *       notice, this list of conditions and the following disclaimer in the
- *       documentation and/or other materials provided with the distribution.
- *     * Neither the name of Ajax.org B.V. nor the
- *       names of its contributors may be used to endorse or promote products
- *       derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * ***** END LICENSE BLOCK ***** */
-
-define('ace/ext/elastic_tabstops_lite', ['require', 'exports', 'module' , 'ace/editor', 'ace/config'], function(require, exports, module) {
-
-
-var ElasticTabstopsLite = function(editor) {
-    this.$editor = editor;
-    var self = this;
-    var changedRows = [];
-    var recordChanges = false;
-    this.onAfterExec = function() {
-        recordChanges = false;
-        self.processRows(changedRows);
-        changedRows = [];
-    };
-    this.onExec = function() {
-        recordChanges = true;
-    };
-    this.onChange = function(e) {
-        var range = e.data.range
-        if (recordChanges) {
-            if (changedRows.indexOf(range.start.row) == -1)
-                changedRows.push(range.start.row);
-            if (range.end.row != range.start.row)
-                changedRows.push(range.end.row);
-        }
-    };
-};
-
-(function() {
-    this.processRows = function(rows) {
-        this.$inChange = true;
-        var checkedRows = [];
-
-        for (var r = 0, rowCount = rows.length; r < rowCount; r++) {
-            var row = rows[r];
-
-            if (checkedRows.indexOf(row) > -1)
-                continue;
-
-            var cellWidthObj = this.$findCellWidthsForBlock(row);
-            var cellWidths = this.$setBlockCellWidthsToMax(cellWidthObj.cellWidths);
-            var rowIndex = cellWidthObj.firstRow;
-
-            for (var w = 0, l = cellWidths.length; w < l; w++) {
-                var widths = cellWidths[w];
-                checkedRows.push(rowIndex);
-                this.$adjustRow(rowIndex, widths);
-                rowIndex++;
-            }
-        }
-        this.$inChange = false;
-    };
-
-    this.$findCellWidthsForBlock = function(row) {
-        var cellWidths = [], widths;
-        var rowIter = row;
-        while (rowIter >= 0) {
-            widths = this.$cellWidthsForRow(rowIter);
-            if (widths.length == 0)
-                break;
-
-            cellWidths.unshift(widths);
-            rowIter--;
-        }
-        var firstRow = rowIter + 1;
-        rowIter = row;
-        var numRows = this.$editor.session.getLength();
-
-        while (rowIter < numRows - 1) {
-            rowIter++;
-
-            widths = this.$cellWidthsForRow(rowIter);
-            if (widths.length == 0)
-                break;
-
-            cellWidths.push(widths);
-        }
-
-        return { cellWidths: cellWidths, firstRow: firstRow };
-    };
-
-    this.$cellWidthsForRow = function(row) {
-        var selectionColumns = this.$selectionColumnsForRow(row);
-
-        var tabs = [-1].concat(this.$tabsForRow(row));
-        var widths = tabs.map(function(el) { return 0; } ).slice(1);
-        var line = this.$editor.session.getLine(row);
-
-        for (var i = 0, len = tabs.length - 1; i < len; i++) {
-            var leftEdge = tabs[i]+1;
-            var rightEdge = tabs[i+1];
-
-            var rightmostSelection = this.$rightmostSelectionInCell(selectionColumns, rightEdge);
-            var cell = line.substring(leftEdge, rightEdge);
-            widths[i] = Math.max(cell.replace(/\s+$/g,'').length, rightmostSelection - leftEdge);
-        }
-
-        return widths;
-    };
-
-    this.$selectionColumnsForRow = function(row) {
-        var selections = [], cursor = this.$editor.getCursorPosition();
-        if (this.$editor.session.getSelection().isEmpty()) {
-            if (row == cursor.row)
-                selections.push(cursor.column);
-        }
-
-        return selections;
-    };
-
-    this.$setBlockCellWidthsToMax = function(cellWidths) {
-        var startingNewBlock = true, blockStartRow, blockEndRow, maxWidth;
-        var columnInfo = this.$izip_longest(cellWidths);
-
-        for (var c = 0, l = columnInfo.length; c < l; c++) {
-            var column = columnInfo[c];
-            if (!column.push) {
-                console.error(column);
-                continue;
-            }
-            column.push(NaN);
-
-            for (var r = 0, s = column.length; r < s; r++) {
-                var width = column[r];
-                if (startingNewBlock) {
-                    blockStartRow = r;
-                    maxWidth = 0;
-                    startingNewBlock = false;
-                }
-                if (isNaN(width)) {
-                    blockEndRow = r;
-
-                    for (var j = blockStartRow; j < blockEndRow; j++) {
-                        cellWidths[j][c] = maxWidth;
-                    }
-                    startingNewBlock = true;
-                }
-
-                maxWidth = Math.max(maxWidth, width);
-            }
-        }
-
-        return cellWidths;
-    };
-
-    this.$rightmostSelectionInCell = function(selectionColumns, cellRightEdge) {
-        var rightmost = 0;
-
-        if (selectionColumns.length) {
-            var lengths = [];
-            for (var s = 0, length = selectionColumns.length; s < length; s++) {
-                if (selectionColumns[s] <= cellRightEdge)
-                    lengths.push(s);
-                else
-                    lengths.push(0);
-            }
-            rightmost = Math.max.apply(Math, lengths);
-        }
-
-        return rightmost;
-    };
-
-    this.$tabsForRow = function(row) {
-        var rowTabs = [], line = this.$editor.session.getLine(row),
-            re = /\t/g, match;
-
-        while ((match = re.exec(line)) != null) {
-            rowTabs.push(match.index);
-        }
-
-        return rowTabs;
-    };
-
-    this.$adjustRow = function(row, widths) {
-        var rowTabs = this.$tabsForRow(row);
-
-        if (rowTabs.length == 0)
-            return;
-
-        var bias = 0, location = -1;
-        var expandedSet = this.$izip(widths, rowTabs);
-
-        for (var i = 0, l = expandedSet.length; i < l; i++) {
-            var w = expandedSet[i][0], it = expandedSet[i][1];
-            location += 1 + w;
-            it += bias;
-            var difference = location - it;
-
-            if (difference == 0)
-                continue;
-
-            var partialLine = this.$editor.session.getLine(row).substr(0, it );
-            var strippedPartialLine = partialLine.replace(/\s*$/g, "");
-            var ispaces = partialLine.length - strippedPartialLine.length;
-
-            if (difference > 0) {
-                this.$editor.session.getDocument().insertInLine({row: row, column: it + 1}, Array(difference + 1).join(" ") + "\t");
-                this.$editor.session.getDocument().removeInLine(row, it, it + 1);
-
-                bias += difference;
-            }
-
-            if (difference < 0 && ispaces >= -difference) {
-                this.$editor.session.getDocument().removeInLine(row, it + difference, it);
-                bias += difference;
-            }
-        }
-    };
-    this.$izip_longest = function(iterables) {
-        if (!iterables[0])
-            return [];
-        var longest = iterables[0].length;
-        var iterablesLength = iterables.length;
-
-        for (var i = 1; i < iterablesLength; i++) {
-            var iLength = iterables[i].length;
-            if (iLength > longest)
-                longest = iLength;
-        }
-
-        var expandedSet = [];
-
-        for (var l = 0; l < longest; l++) {
-            var set = [];
-            for (var i = 0; i < iterablesLength; i++) {
-                if (iterables[i][l] === "")
-                    set.push(NaN);
-                else
-                    set.push(iterables[i][l]);
-            }
-
-            expandedSet.push(set);
-        }
-
-
-        return expandedSet;
-    };
-    this.$izip = function(widths, tabs) {
-        var size = widths.length >= tabs.length ? tabs.length : widths.length;
-
-        var expandedSet = [];
-        for (var i = 0; i < size; i++) {
-            var set = [ widths[i], tabs[i] ];
-            expandedSet.push(set);
-        }
-        return expandedSet;
-    };
-
-}).call(ElasticTabstopsLite.prototype);
-
-exports.ElasticTabstopsLite = ElasticTabstopsLite;
-
-var Editor = require("../editor").Editor;
-require("../config").defineOptions(Editor.prototype, "editor", {
-    useElasticTabstops: {
-        set: function(val) {
-            if (val) {
-                if (!this.elasticTabstops)
-                    this.elasticTabstops = new ElasticTabstopsLite(this);
-                this.commands.on("afterExec", this.elasticTabstops.onAfterExec);
-                this.commands.on("exec", this.elasticTabstops.onExec);
-                this.on("change", this.elasticTabstops.onChange);
-            } else if (this.elasticTabstops) {
-                this.commands.removeListener("afterExec", this.elasticTabstops.onAfterExec);
-                this.commands.removeListener("exec", this.elasticTabstops.onExec);
-                this.removeListener("change", this.elasticTabstops.onChange);
-            }
-        }
-    }
-});
-
-});
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/js/libs/ace/ext-emmet.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/js/libs/ace/ext-emmet.js b/apps/fauxton/assets/js/libs/ace/ext-emmet.js
deleted file mode 100644
index a6228a7..0000000
--- a/apps/fauxton/assets/js/libs/ace/ext-emmet.js
+++ /dev/null
@@ -1,1096 +0,0 @@
-/* ***** BEGIN LICENSE BLOCK *****
- * Distributed under the BSD license:
- *
- * Copyright (c) 2010, Ajax.org B.V.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above copyright
- *       notice, this list of conditions and the following disclaimer in the
- *       documentation and/or other materials provided with the distribution.
- *     * Neither the name of Ajax.org B.V. nor the
- *       names of its contributors may be used to endorse or promote products
- *       derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * ***** END LICENSE BLOCK ***** */
-
-define('ace/ext/emmet', ['require', 'exports', 'module' , 'ace/keyboard/hash_handler', 'ace/editor', 'ace/snippets', 'ace/range', 'ace/config'], function(require, exports, module) {
-
-var HashHandler = require("ace/keyboard/hash_handler").HashHandler;
-var Editor = require("ace/editor").Editor;
-var snippetManager = require("ace/snippets").snippetManager;
-var Range = require("ace/range").Range;
-var emmet;
-
-Editor.prototype.indexToPosition = function(index) {
-    return this.session.doc.indexToPosition(index);
-};
-
-Editor.prototype.positionToIndex = function(pos) {
-    return this.session.doc.positionToIndex(pos);
-};
-function AceEmmetEditor() {}
-
-AceEmmetEditor.prototype = {
-    setupContext: function(editor) {
-        this.ace = editor;
-        this.indentation = editor.session.getTabString();
-        if (!emmet)
-            emmet = window.emmet;
-        emmet.require("resources").setVariable("indentation", this.indentation);
-        this.$syntax = null;
-        this.$syntax = this.getSyntax();
-    },
-    getSelectionRange: function() {
-        var range = this.ace.getSelectionRange();
-        return {
-            start: this.ace.positionToIndex(range.start),
-            end: this.ace.positionToIndex(range.end)
-        };
-    },
-    createSelection: function(start, end) {
-        this.ace.selection.setRange({
-            start: this.ace.indexToPosition(start),
-            end: this.ace.indexToPosition(end)
-        });
-    },
-    getCurrentLineRange: function() {
-        var row = this.ace.getCursorPosition().row;
-        var lineLength = this.ace.session.getLine(row).length;
-        var index = this.ace.positionToIndex({row: row, column: 0});
-        return {
-            start: index,
-            end: index + lineLength
-        };
-    },
-    getCaretPos: function(){
-        var pos = this.ace.getCursorPosition();
-        return this.ace.positionToIndex(pos);
-    },
-    setCaretPos: function(index){
-        var pos = this.ace.indexToPosition(index);
-        this.ace.clearSelection();
-        this.ace.selection.moveCursorToPosition(pos);
-    },
-    getCurrentLine: function() {
-        var row = this.ace.getCursorPosition().row;
-        return this.ace.session.getLine(row);
-    },
-    replaceContent: function(value, start, end, noIndent) {
-        if (end == null)
-            end = start == null ? this.getContent().length : start;
-        if (start == null)
-            start = 0;        
-        
-        var editor = this.ace;
-        var range = Range.fromPoints(editor.indexToPosition(start), editor.indexToPosition(end));
-        editor.session.remove(range);
-        
-        range.end = range.start;
-        
-        value = this.$updateTabstops(value);
-        snippetManager.insertSnippet(editor, value)
-    },
-    getContent: function(){
-        return this.ace.getValue();
-    },
-    getSyntax: function() {
-        if (this.$syntax)
-            return this.$syntax;
-        var syntax = this.ace.session.$modeId.split("/").pop();
-        if (syntax == "html" || syntax == "php") {
-            var cursor = this.ace.getCursorPosition();
-            var state = this.ace.session.getState(cursor.row);
-            if (typeof state != "string")
-                state = state[0];
-            if (state) {
-                state = state.split("-");
-                if (state.length > 1)
-                    syntax = state[0];
-                else if (syntax == "php")
-                    syntax = "html";
-            }
-        }
-        return syntax;
-    },
-    getProfileName: function() {
-        switch(this.getSyntax()) {
-          case "css": return "css";
-          case "xml":
-          case "xsl":
-            return "xml";
-          case "html":
-            var profile = emmet.require("resources").getVariable("profile");
-            if (!profile)
-                profile = this.ace.session.getLines(0,2).join("").search(/<!DOCTYPE[^>]+XHTML/i) != -1 ? "xhtml": "html";
-            return profile;
-        }
-        return "xhtml";
-    },
-    prompt: function(title) {
-        return prompt(title);
-    },
-    getSelection: function() {
-        return this.ace.session.getTextRange();
-    },
-    getFilePath: function() {
-        return "";
-    },
-    $updateTabstops: function(value) {
-        var base = 1000;
-        var zeroBase = 0;
-        var lastZero = null;
-        var range = emmet.require('range');
-        var ts = emmet.require('tabStops');
-        var settings = emmet.require('resources').getVocabulary("user");
-        var tabstopOptions = {
-            tabstop: function(data) {
-                var group = parseInt(data.group, 10);
-                var isZero = group === 0;
-                if (isZero)
-                    group = ++zeroBase;
-                else
-                    group += base;
-
-                var placeholder = data.placeholder;
-                if (placeholder) {
-                    placeholder = ts.processText(placeholder, tabstopOptions);
-                }
-
-                var result = '${' + group + (placeholder ? ':' + placeholder : '') + '}';
-
-                if (isZero) {
-                    lastZero = range.create(data.start, result);
-                }
-
-                return result
-            },
-            escape: function(ch) {
-                if (ch == '$') return '\\$';
-                if (ch == '\\') return '\\\\';
-                return ch;
-            }
-        };
-
-        value = ts.processText(value, tabstopOptions);
-
-        if (settings.variables['insert_final_tabstop'] && !/\$\{0\}$/.test(value)) {
-            value += '${0}';
-        } else if (lastZero) {
-            value = emmet.require('utils').replaceSubstring(value, '${0}', lastZero);
-        }
-        
-        return value;
-    }
-};
-
-
-var keymap = {
-    expand_abbreviation: {"mac": "ctrl+alt+e", "win": "alt+e"},
-    match_pair_outward: {"mac": "ctrl+d", "win": "ctrl+,"},
-    match_pair_inward: {"mac": "ctrl+j", "win": "ctrl+shift+0"},
-    matching_pair: {"mac": "ctrl+alt+j", "win": "alt+j"},
-    next_edit_point: "alt+right",
-    prev_edit_point: "alt+left",
-    toggle_comment: {"mac": "command+/", "win": "ctrl+/"},
-    split_join_tag: {"mac": "shift+command+'", "win": "shift+ctrl+`"},
-    remove_tag: {"mac": "command+'", "win": "shift+ctrl+;"},
-    evaluate_math_expression: {"mac": "shift+command+y", "win": "shift+ctrl+y"},
-    increment_number_by_1: "ctrl+up",
-    decrement_number_by_1: "ctrl+down",
-    increment_number_by_01: "alt+up",
-    decrement_number_by_01: "alt+down",
-    increment_number_by_10: {"mac": "alt+command+up", "win": "shift+alt+up"},
-    decrement_number_by_10: {"mac": "alt+command+down", "win": "shift+alt+down"},
-    select_next_item: {"mac": "shift+command+.", "win": "shift+ctrl+."},
-    select_previous_item: {"mac": "shift+command+,", "win": "shift+ctrl+,"},
-    reflect_css_value: {"mac": "shift+command+r", "win": "shift+ctrl+r"},
-
-    encode_decode_data_url: {"mac": "shift+ctrl+d", "win": "ctrl+'"},
-    expand_abbreviation_with_tab: "Tab",
-    wrap_with_abbreviation: {"mac": "shift+ctrl+a", "win": "shift+ctrl+a"}
-};
-
-var editorProxy = new AceEmmetEditor();
-exports.commands = new HashHandler();
-exports.runEmmetCommand = function(editor) {
-    editorProxy.setupContext(editor);
-    if (editorProxy.getSyntax() == "php")
-        return false;
-    var actions = emmet.require("actions");
-
-    if (this.action == "expand_abbreviation_with_tab") {
-        if (!editor.selection.isEmpty())
-            return false;
-    }
-    
-    if (this.action == "wrap_with_abbreviation") {
-        return setTimeout(function() {
-            actions.run("wrap_with_abbreviation", editorProxy);
-        }, 0);
-    }
-    
-    try {
-        var result = actions.run(this.action, editorProxy);
-    } catch(e) {
-        editor._signal("changeStatus", typeof e == "string" ? e : e.message);
-        console.log(e);
-    }
-    return result;
-};
-
-for (var command in keymap) {
-    exports.commands.addCommand({
-        name: "emmet:" + command,
-        action: command,
-        bindKey: keymap[command],
-        exec: exports.runEmmetCommand,
-        multiSelectAction: "forEach"
-    });
-}
-
-var onChangeMode = function(e, target) {
-    var editor = target;
-    if (!editor)
-        return;
-    var modeId = editor.session.$modeId;
-    var enabled = modeId && /css|less|scss|sass|stylus|html|php/.test(modeId);
-    if (e.enableEmmet === false)
-        enabled = false;
-    if (enabled)
-        editor.keyBinding.addKeyboardHandler(exports.commands);
-    else
-        editor.keyBinding.removeKeyboardHandler(exports.commands);
-};
-
-
-exports.AceEmmetEditor = AceEmmetEditor;
-require("ace/config").defineOptions(Editor.prototype, "editor", {
-    enableEmmet: {
-        set: function(val) {
-            this[val ? "on" : "removeListener"]("changeMode", onChangeMode);
-            onChangeMode({enableEmmet: !!val}, this);
-        },
-        value: true
-    }
-});
-
-
-exports.setCore = function(e) {emmet = e;};
-});
-
-define('ace/snippets', ['require', 'exports', 'module' , 'ace/lib/lang', 'ace/range', 'ace/keyboard/hash_handler', 'ace/tokenizer', 'ace/lib/dom'], function(require, exports, module) {
-
-var lang = require("./lib/lang")
-var Range = require("./range").Range
-var HashHandler = require("./keyboard/hash_handler").HashHandler;
-var Tokenizer = require("./tokenizer").Tokenizer;
-var comparePoints = Range.comparePoints;
-
-var SnippetManager = function() {
-    this.snippetMap = {};
-    this.snippetNameMap = {};
-};
-
-(function() {
-    this.getTokenizer = function() {
-        function TabstopToken(str, _, stack) {
-            str = str.substr(1);
-            if (/^\d+$/.test(str) && !stack.inFormatString)
-                return [{tabstopId: parseInt(str, 10)}];
-            return [{text: str}]
-        }
-        function escape(ch) {
-            return "(?:[^\\\\" + ch + "]|\\\\.)";
-        }
-        SnippetManager.$tokenizer = new Tokenizer({
-            start: [
-                {regex: /:/, onMatch: function(val, state, stack) {
-                    if (stack.length && stack[0].expectIf) {
-                        stack[0].expectIf = false;
-                        stack[0].elseBranch = stack[0];
-                        return [stack[0]];
-                    }
-                    return ":";
-                }},
-                {regex: /\\./, onMatch: function(val, state, stack) {
-                    var ch = val[1];
-                    if (ch == "}" && stack.length) {
-                        val = ch;
-                    }else if ("`$\\".indexOf(ch) != -1) {
-                        val = ch;
-                    } else if (stack.inFormatString) {
-                        if (ch == "n")
-                            val = "\n";
-                        else if (ch == "t")
-                            val = "\n";
-                        else if ("ulULE".indexOf(ch) != -1) {
-                            val = {changeCase: ch, local: ch > "a"};
-                        }
-                    }
-
-                    return [val];
-                }},
-                {regex: /}/, onMatch: function(val, state, stack) {
-                    return [stack.length ? stack.shift() : val];
-                }},
-                {regex: /\$(?:\d+|\w+)/, onMatch: TabstopToken},
-                {regex: /\$\{[\dA-Z_a-z]+/, onMatch: function(str, state, stack) {
-                    var t = TabstopToken(str.substr(1), state, stack);
-                    stack.unshift(t[0]);
-                    return t;
-                }, next: "snippetVar"},
-                {regex: /\n/, token: "newline", merge: false}
-            ],
-            snippetVar: [
-                {regex: "\\|" + escape("\\|") + "*\\|", onMatch: function(val, state, stack) {
-                    stack[0].choices = val.slice(1, -1).split(",");
-                }, next: "start"},
-                {regex: "/(" + escape("/") + "+)/(?:(" + escape("/") + "*)/)(\\w*):?",
-                 onMatch: function(val, state, stack) {
-                    var ts = stack[0];
-                    ts.fmtString = val;
-
-                    val = this.splitRegex.exec(val);
-                    ts.guard = val[1];
-                    ts.fmt = val[2];
-                    ts.flag = val[3];
-                    return "";
-                }, next: "start"},
-                {regex: "`" + escape("`") + "*`", onMatch: function(val, state, stack) {
-                    stack[0].code = val.splice(1, -1);
-                    return "";
-                }, next: "start"},
-                {regex: "\\?", onMatch: function(val, state, stack) {
-                    if (stack[0])
-                        stack[0].expectIf = true;
-                }, next: "start"},
-                {regex: "([^:}\\\\]|\\\\.)*:?", token: "", next: "start"}
-            ],
-            formatString: [
-                {regex: "/(" + escape("/") + "+)/", token: "regex"},
-                {regex: "", onMatch: function(val, state, stack) {
-                    stack.inFormatString = true;
-                }, next: "start"}
-            ]
-        });
-        SnippetManager.prototype.getTokenizer = function() {
-            return SnippetManager.$tokenizer;
-        }
-        return SnippetManager.$tokenizer;
-    };
-
-    this.tokenizeTmSnippet = function(str, startState) {
-        return this.getTokenizer().getLineTokens(str, startState).tokens.map(function(x) {
-            return x.value || x;
-        });
-    };
-
-    this.$getDefaultValue = function(editor, name) {
-        if (/^[A-Z]\d+$/.test(name)) {
-            var i = name.substr(1);
-            return (this.variables[name[0] + "__"] || {})[i];
-        }
-        if (/^\d+$/.test(name)) {
-            return (this.variables.__ || {})[name];
-        }
-        name = name.replace(/^TM_/, "");
-
-        if (!editor)
-            return;
-        var s = editor.session;
-        switch(name) {
-            case "CURRENT_WORD":
-                var r = s.getWordRange();
-            case "SELECTION":
-            case "SELECTED_TEXT":
-                return s.getTextRange(r);
-            case "CURRENT_LINE":
-                return s.getLine(editor.getCursorPosition().row);
-            case "PREV_LINE": // not possible in textmate
-                return s.getLine(editor.getCursorPosition().row - 1);
-            case "LINE_INDEX":
-                return editor.getCursorPosition().column;
-            case "LINE_NUMBER":
-                return editor.getCursorPosition().row + 1;
-            case "SOFT_TABS":
-                return s.getUseSoftTabs() ? "YES" : "NO";
-            case "TAB_SIZE":
-                return s.getTabSize();
-            case "FILENAME":
-            case "FILEPATH":
-                return "ace.ajax.org";
-            case "FULLNAME":
-                return "Ace";
-        }
-    };
-    this.variables = {};
-    this.getVariableValue = function(editor, varName) {
-        if (this.variables.hasOwnProperty(varName))
-            return this.variables[varName](editor, varName) || "";
-        return this.$getDefaultValue(editor, varName) || "";
-    };
-    this.tmStrFormat = function(str, ch, editor) {
-        var flag = ch.flag || "";
-        var re = ch.guard;
-        re = new RegExp(re, flag.replace(/[^gi]/, ""));
-        var fmtTokens = this.tokenizeTmSnippet(ch.fmt, "formatString");
-        var _self = this;
-        var formatted = str.replace(re, function() {
-            _self.variables.__ = arguments;
-            var fmtParts = _self.resolveVariables(fmtTokens, editor);
-            var gChangeCase = "E";
-            for (var i  = 0; i < fmtParts.length; i++) {
-                var ch = fmtParts[i];
-                if (typeof ch == "object") {
-                    fmtParts[i] = "";
-                    if (ch.changeCase && ch.local) {
-                        var next = fmtParts[i + 1];
-                        if (next && typeof next == "string") {
-                            if (ch.changeCase == "u")
-                                fmtParts[i] = next[0].toUpperCase();
-                            else
-                                fmtParts[i] = next[0].toLowerCase();
-                            fmtParts[i + 1] = next.substr(1);
-                        }
-                    } else if (ch.changeCase) {
-                        gChangeCase = ch.changeCase;
-                    }
-                } else if (gChangeCase == "U") {
-                    fmtParts[i] = ch.toUpperCase();
-                } else if (gChangeCase == "L") {
-                    fmtParts[i] = ch.toLowerCase();
-                }
-            }
-            return fmtParts.join("");
-        });
-        this.variables.__ = null;
-        return formatted;
-    };
-
-    this.resolveVariables = function(snippet, editor) {
-        var result = [];
-        for (var i = 0; i < snippet.length; i++) {
-            var ch = snippet[i];
-            if (typeof ch == "string") {
-                result.push(ch);
-            } else if (typeof ch != "object") {
-                continue;
-            } else if (ch.skip) {
-                gotoNext(ch);
-            } else if (ch.processed < i) {
-                continue;
-            } else if (ch.text) {
-                var value = this.getVariableValue(editor, ch.text);
-                if (value && ch.fmtString)
-                    value = this.tmStrFormat(value, ch);
-                ch.processed = i;
-                if (ch.expectIf == null) {
-                    if (value) {
-                        result.push(value);
-                        gotoNext(ch);
-                    }
-                } else {
-                    if (value) {
-                        ch.skip = ch.elseBranch;
-                    } else
-                        gotoNext(ch);
-                }
-            } else if (ch.tabstopId != null) {
-                result.push(ch);
-            } else if (ch.changeCase != null) {
-                result.push(ch);
-            }
-        }
-        function gotoNext(ch) {
-            var i1 = snippet.indexOf(ch, i + 1);
-            if (i1 != -1)
-                i = i1;
-        }
-        return result;
-    };
-
-    this.insertSnippet = function(editor, snippetText) {
-        var cursor = editor.getCursorPosition();
-        var line = editor.session.getLine(cursor.row);
-        var indentString = line.match(/^\s*/)[0];
-        var tabString = editor.session.getTabString();
-
-        var tokens = this.tokenizeTmSnippet(snippetText);
-        tokens = this.resolveVariables(tokens, editor);
-        tokens = tokens.map(function(x) {
-            if (x == "\n")
-                return x + indentString;
-            if (typeof x == "string")
-                return x.replace(/\t/g, tabString);
-            return x;
-        });
-        var tabstops = [];
-        tokens.forEach(function(p, i) {
-            if (typeof p != "object")
-                return;
-            var id = p.tabstopId;
-            var ts = tabstops[id];
-            if (!ts) {
-                ts = tabstops[id] = [];
-                ts.index = id;
-                ts.value = "";
-            }
-            if (ts.indexOf(p) !== -1)
-                return;
-            ts.push(p);
-            var i1 = tokens.indexOf(p, i + 1);
-            if (i1 === -1)
-                return;
-
-            var value = tokens.slice(i + 1, i1);
-            var isNested = value.some(function(t) {return typeof t === "object"});          
-            if (isNested && !ts.value) {
-                ts.value = value;
-            } else if (value.length && (!ts.value || typeof ts.value !== "string")) {
-                ts.value = value.join("");
-            }
-        });
-        tabstops.forEach(function(ts) {ts.length = 0});
-        var expanding = {};
-        function copyValue(val) {
-            var copy = []
-            for (var i = 0; i < val.length; i++) {
-                var p = val[i];
-                if (typeof p == "object") {
-                    if (expanding[p.tabstopId])
-                        continue;
-                    var j = val.lastIndexOf(p, i - 1);
-                    p = copy[j] || {tabstopId: p.tabstopId};
-                }
-                copy[i] = p;
-            }
-            return copy;
-        }
-        for (var i = 0; i < tokens.length; i++) {
-            var p = tokens[i];
-            if (typeof p != "object")
-                continue;
-            var id = p.tabstopId;
-            var i1 = tokens.indexOf(p, i + 1);
-            if (expanding[id] == p) { 
-                expanding[id] = null;
-                continue;
-            }
-            
-            var ts = tabstops[id];
-            var arg = typeof ts.value == "string" ? [ts.value] : copyValue(ts.value);
-            arg.unshift(i + 1, Math.max(0, i1 - i));
-            arg.push(p);
-            expanding[id] = p;
-            tokens.splice.apply(tokens, arg);
-
-            if (ts.indexOf(p) === -1)
-                ts.push(p);
-        };
-        var row = 0, column = 0;
-        var text = "";
-        tokens.forEach(function(t) {
-            if (typeof t === "string") {
-                if (t[0] === "\n"){
-                    column = t.length - 1;
-                    row ++;
-                } else
-                    column += t.length;
-                text += t;
-            } else {
-                if (!t.start)
-                    t.start = {row: row, column: column};
-                else
-                    t.end = {row: row, column: column};
-            }
-        });
-        var range = editor.getSelectionRange();
-        var end = editor.session.replace(range, text);
-
-        var tabstopManager = new TabstopManager(editor);
-        tabstopManager.addTabstops(tabstops, range.start, end);
-        tabstopManager.tabNext();
-    };
-
-    this.$getScope = function(editor) {
-        var scope = editor.session.$mode.$id || "";
-        scope = scope.split("/").pop();
-        if (scope === "html" || scope === "php") {
-            if (scope === "php") 
-                scope = "html";
-            var c = editor.getCursorPosition()
-            var state = editor.session.getState(c.row);
-            if (typeof state === "object") {
-                state = state[0];
-            }
-            if (state.substring) {
-                if (state.substring(0, 3) == "js-")
-                    scope = "javascript";
-                else if (state.substring(0, 4) == "css-")
-                    scope = "css";
-                else if (state.substring(0, 4) == "php-")
-                    scope = "php";
-            }
-        }
-        
-        return scope;
-    };
-
-    this.expandWithTab = function(editor) {
-        var cursor = editor.getCursorPosition();
-        var line = editor.session.getLine(cursor.row);
-        var before = line.substring(0, cursor.column);
-        var after = line.substr(cursor.column);
-
-        var scope = this.$getScope(editor);
-        var snippetMap = this.snippetMap;
-        var snippet;
-        [scope, "_"].some(function(scope) {
-            var snippets = snippetMap[scope];
-            if (snippets)
-                snippet = this.findMatchingSnippet(snippets, before, after);
-            return !!snippet;
-        }, this);
-        if (!snippet)
-            return false;
-
-        editor.session.doc.removeInLine(cursor.row,
-            cursor.column - snippet.replaceBefore.length,
-            cursor.column + snippet.replaceAfter.length
-        );
-
-        this.variables.M__ = snippet.matchBefore;
-        this.variables.T__ = snippet.matchAfter;
-        this.insertSnippet(editor, snippet.content);
-
-        this.variables.M__ = this.variables.T__ = null;
-        return true;
-    };
-
-    this.findMatchingSnippet = function(snippetList, before, after) {
-        for (var i = snippetList.length; i--;) {
-            var s = snippetList[i];
-            if (s.startRe && !s.startRe.test(before))
-                continue;
-            if (s.endRe && !s.endRe.test(after))
-                continue;
-            if (!s.startRe && !s.endRe)
-                continue;
-
-            s.matchBefore = s.startRe ? s.startRe.exec(before) : [""];
-            s.matchAfter = s.endRe ? s.endRe.exec(after) : [""];
-            s.replaceBefore = s.triggerRe ? s.triggerRe.exec(before)[0] : "";
-            s.replaceAfter = s.endTriggerRe ? s.endTriggerRe.exec(after)[0] : "";
-            return s;
-        }
-    };
-
-    this.snippetMap = {};
-    this.snippetNameMap = {};
-    this.register = function(snippets, scope) {
-        var snippetMap = this.snippetMap;
-        var snippetNameMap = this.snippetNameMap;
-        var self = this;
-        function wrapRegexp(src) {
-            if (src && !/^\^?\(.*\)\$?$|^\\b$/.test(src))
-                src = "(?:" + src + ")"
-
-            return src || "";
-        }
-        function guardedRegexp(re, guard, opening) {
-            re = wrapRegexp(re);
-            guard = wrapRegexp(guard);
-            if (opening) {
-                re = guard + re;
-                if (re && re[re.length - 1] != "$")
-                    re = re + "$";
-            } else {
-                re = re + guard;
-                if (re && re[0] != "^")
-                    re = "^" + re;
-            }
-            return new RegExp(re);
-        }
-
-        function addSnippet(s) {
-            if (!s.scope)
-                s.scope = scope || "_";
-            scope = s.scope
-            if (!snippetMap[scope]) {
-                snippetMap[scope] = [];
-                snippetNameMap[scope] = {};
-            }
-
-            var map = snippetNameMap[scope];
-            if (s.name) {
-                var old = map[s.name];
-                if (old)
-                    self.unregister(old);
-                map[s.name] = s;
-            }
-            snippetMap[scope].push(s);
-
-            if (s.tabTrigger && !s.trigger) {
-                if (!s.guard && /^\w/.test(s.tabTrigger))
-                    s.guard = "\\b";
-                s.trigger = lang.escapeRegExp(s.tabTrigger);
-            }
-
-            s.startRe = guardedRegexp(s.trigger, s.guard, true);
-            s.triggerRe = new RegExp(s.trigger, "", true);
-
-            s.endRe = guardedRegexp(s.endTrigger, s.endGuard, true);
-            s.endTriggerRe = new RegExp(s.endTrigger, "", true);
-        };
-
-        if (snippets.content)
-            addSnippet(snippets);
-        else if (Array.isArray(snippets))
-            snippets.forEach(addSnippet);
-    };
-    this.unregister = function(snippets, scope) {
-        var snippetMap = this.snippetMap;
-        var snippetNameMap = this.snippetNameMap;
-
-        function removeSnippet(s) {
-            var nameMap = snippetNameMap[s.scope||scope];
-            if (nameMap && nameMap[s.name]) {
-                delete nameMap[s.name];
-                var map = snippetMap[s.scope||scope];
-                var i = map && map.indexOf(s);
-                if (i >= 0)
-                    map.splice(i, 1);
-            }
-        }
-        if (snippets.content)
-            removeSnippet(snippets);
-        else if (Array.isArray(snippets))
-            snippets.forEach(removeSnippet);
-    };
-    this.parseSnippetFile = function(str) {
-        str = str.replace(/\r/g, "");
-        var list = [], snippet = {};
-        var re = /^#.*|^({[\s\S]*})\s*$|^(\S+) (.*)$|^((?:\n*\t.*)+)/gm;
-        var m;
-        while (m = re.exec(str)) {
-            if (m[1]) {
-                try {
-                    snippet = JSON.parse(m[1])
-                    list.push(snippet);
-                } catch (e) {}
-            } if (m[4]) {
-                snippet.content = m[4].replace(/^\t/gm, "");
-                list.push(snippet);
-                snippet = {};
-            } else {
-                var key = m[2], val = m[3];
-                if (key == "regex") {
-                    var guardRe = /\/((?:[^\/\\]|\\.)*)|$/g;
-                    snippet.guard = guardRe.exec(val)[1];
-                    snippet.trigger = guardRe.exec(val)[1];
-                    snippet.endTrigger = guardRe.exec(val)[1];
-                    snippet.endGuard = guardRe.exec(val)[1];
-                } else if (key == "snippet") {
-                    snippet.tabTrigger = val.match(/^\S*/)[0];
-                    if (!snippet.name)
-                        snippet.name = val;
-                } else {
-                    snippet[key] = val;
-                }
-            }
-        }
-        return list;
-    };
-    this.getSnippetByName = function(name, editor) {
-        var scope = editor && this.$getScope(editor);
-        var snippetMap = this.snippetNameMap;
-        var snippet;
-        [scope, "_"].some(function(scope) {
-            var snippets = snippetMap[scope];
-            if (snippets)
-                snippet = snippets[name];
-            return !!snippet;
-        }, this);
-        return snippet;
-    };
-
-}).call(SnippetManager.prototype);
-
-
-var TabstopManager = function(editor) {
-    if (editor.tabstopManager)
-        return editor.tabstopManager;
-    editor.tabstopManager = this;
-    this.$onChange = this.onChange.bind(this);
-    this.$onChangeSelection = lang.delayedCall(this.onChangeSelection.bind(this)).schedule;
-    this.$onChangeSession = this.onChangeSession.bind(this);
-    this.$onAfterExec = this.onAfterExec.bind(this);
-    this.attach(editor);
-};
-(function() {
-    this.attach = function(editor) {
-        this.index = -1;
-        this.ranges = [];
-        this.tabstops = [];
-        this.selectedTabstop = null;
-
-        this.editor = editor;
-        this.editor.on("change", this.$onChange);
-        this.editor.on("changeSelection", this.$onChangeSelection);
-        this.editor.on("changeSession", this.$onChangeSession);
-        this.editor.commands.on("afterExec", this.$onAfterExec);
-        this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler);
-    };
-    this.detach = function() {
-        this.tabstops.forEach(this.removeTabstopMarkers, this);
-        this.ranges = null;
-        this.tabstops = null;
-        this.selectedTabstop = null;
-        this.editor.removeListener("change", this.$onChange);
-        this.editor.removeListener("changeSelection", this.$onChangeSelection);
-        this.editor.removeListener("changeSession", this.$onChangeSession);
-        this.editor.commands.removeListener("afterExec", this.$onAfterExec);
-        this.editor.keyBinding.removeKeyboardHandler(this.keyboardHandler);
-        this.editor.tabstopManager = null;
-        this.editor = null;
-    };
-
-    this.onChange = function(e) {
-        var changeRange = e.data.range;
-        var isRemove = e.data.action[0] == "r";
-        var start = changeRange.start;
-        var end = changeRange.end;
-        var startRow = start.row;
-        var endRow = end.row;
-        var lineDif = endRow - startRow;
-        var colDiff = end.column - start.column;
-
-        if (isRemove) {
-            lineDif = -lineDif;
-            colDiff = -colDiff;
-        }
-        if (!this.$inChange && isRemove) {
-            var ts = this.selectedTabstop;
-            var changedOutside = !ts.some(function(r) {
-                return comparePoints(r.start, start) <= 0 && comparePoints(r.end, end) >= 0;
-            });
-            if (changedOutside)
-                return this.detach();
-        }
-        var ranges = this.ranges;
-        for (var i = 0; i < ranges.length; i++) {
-            var r = ranges[i];
-            if (r.end.row < start.row)
-                continue;
-
-            if (comparePoints(start, r.start) < 0 && comparePoints(end, r.end) > 0) {
-                this.removeRange(r);
-                i--;
-                continue;
-            }
-
-            if (r.start.row == startRow && r.start.column > start.column)
-                r.start.column += colDiff;
-            if (r.end.row == startRow && r.end.column >= start.column)
-                r.end.column += colDiff;
-            if (r.start.row >= startRow)
-                r.start.row += lineDif;
-            if (r.end.row >= startRow)
-                r.end.row += lineDif;
-
-            if (comparePoints(r.start, r.end) > 0)
-                this.removeRange(r);
-        }
-        if (!ranges.length)
-            this.detach();
-    };
-    this.updateLinkedFields = function() {
-        var ts = this.selectedTabstop;
-        if (!ts.hasLinkedRanges)
-            return;
-        this.$inChange = true;
-        var session = this.editor.session;
-        var text = session.getTextRange(ts.firstNonLinked);
-        for (var i = ts.length; i--;) {
-            var range = ts[i];
-            if (!range.linked)
-                continue;
-            var fmt = exports.snippetManager.tmStrFormat(text, range.original)
-            session.replace(range, fmt);
-        }
-        this.$inChange = false;
-    };
-    this.onAfterExec = function(e) {
-        if (e.command && !e.command.readOnly)
-            this.updateLinkedFields();
-    };
-    this.onChangeSelection = function() {
-        if (!this.editor)
-            return
-        var lead = this.editor.selection.lead;
-        var anchor = this.editor.selection.anchor;
-        var isEmpty = this.editor.selection.isEmpty();
-        for (var i = this.ranges.length; i--;) {
-            if (this.ranges[i].linked)
-                continue;
-            var containsLead = this.ranges[i].contains(lead.row, lead.column);
-            var containsAnchor = isEmpty || this.ranges[i].contains(anchor.row, anchor.column);
-            if (containsLead && containsAnchor)
-                return;
-        }
-        this.detach();
-    };
-    this.onChangeSession = function() {
-        this.detach();
-    };
-    this.tabNext = function(dir) {
-        var max = this.tabstops.length - 1;
-        var index = this.index + (dir || 1);
-        index = Math.min(Math.max(index, 0), max);
-        this.selectTabstop(index);
-        if (index == max)
-            this.detach();
-    };
-    this.selectTabstop = function(index) {
-        var ts = this.tabstops[this.index];
-        if (ts)
-            this.addTabstopMarkers(ts);
-        this.index = index;
-        ts = this.tabstops[this.index];
-        if (!ts || !ts.length)
-            return;
-        
-        this.selectedTabstop = ts;
-        if (!this.editor.inVirtualSelectionMode) {        
-            var sel = this.editor.multiSelect;
-            sel.toSingleRange(ts.firstNonLinked.clone());
-            for (var i = ts.length; i--;) {
-                if (ts.hasLinkedRanges && ts[i].linked)
-                    continue;
-                sel.addRange(ts[i].clone(), true);
-            }
-        } else {
-            this.editor.selection.setRange(ts.firstNonLinked);
-        }
-        
-        this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler);
-    };
-    this.addTabstops = function(tabstops, start, end) {
-        if (!tabstops[0]) {
-            var p = Range.fromPoints(end, end);
-            moveRelative(p.start, start);
-            moveRelative(p.end, start);
-            tabstops[0] = [p];
-            tabstops[0].index = 0;
-        }
-
-        var i = this.index;
-        var arg = [i, 0];
-        var ranges = this.ranges;
-        var editor = this.editor;
-        tabstops.forEach(function(ts) {
-            for (var i = ts.length; i--;) {
-                var p = ts[i];
-                var range = Range.fromPoints(p.start, p.end || p.start);
-                movePoint(range.start, start);
-                movePoint(range.end, start);
-                range.original = p;
-                range.tabstop = ts;
-                ranges.push(range);
-                ts[i] = range;
-                if (p.fmtString) {
-                    range.linked = true;
-                    ts.hasLinkedRanges = true;
-                } else if (!ts.firstNonLinked)
-                    ts.firstNonLinked = range;
-            }
-            if (!ts.firstNonLinked)
-                ts.hasLinkedRanges = false;
-            arg.push(ts);
-            this.addTabstopMarkers(ts);
-        }, this);
-        arg.push(arg.splice(2, 1)[0]);
-        this.tabstops.splice.apply(this.tabstops, arg);
-    };
-
-    this.addTabstopMarkers = function(ts) {
-        var session = this.editor.session;
-        ts.forEach(function(range) {
-            if  (!range.markerId)
-                range.markerId = session.addMarker(range, "ace_snippet-marker", "text");
-        });
-    };
-    this.removeTabstopMarkers = function(ts) {
-        var session = this.editor.session;
-        ts.forEach(function(range) {
-            session.removeMarker(range.markerId);
-            range.markerId = null;
-        });
-    };
-    this.removeRange = function(range) {
-        var i = range.tabstop.indexOf(range);
-        range.tabstop.splice(i, 1);
-        i = this.ranges.indexOf(range);
-        this.ranges.splice(i, 1);
-        this.editor.session.removeMarker(range.markerId);
-    };
-
-    this.keyboardHandler = new HashHandler();
-    this.keyboardHandler.bindKeys({
-        "Tab": function(ed) {
-            ed.tabstopManager.tabNext(1);
-        },
-        "Shift-Tab": function(ed) {
-            ed.tabstopManager.tabNext(-1);
-        },
-        "Esc": function(ed) {
-            ed.tabstopManager.detach();
-        },
-        "Return": function(ed) {
-            return false;
-        }
-    });
-}).call(TabstopManager.prototype);
-
-
-var movePoint = function(point, diff) {
-    if (point.row == 0)
-        point.column += diff.column;
-    point.row += diff.row;
-};
-
-var moveRelative = function(point, start) {
-    if (point.row == start.row)
-        point.column -= start.column;
-    point.row -= start.row;
-};
-
-
-require("./lib/dom").importCssString("\
-.ace_snippet-marker {\
-    -moz-box-sizing: border-box;\
-    box-sizing: border-box;\
-    background: rgba(194, 193, 208, 0.09);\
-    border: 1px dotted rgba(211, 208, 235, 0.62);\
-    position: absolute;\
-}");
-
-exports.snippetManager = new SnippetManager();
-
-
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/js/libs/ace/ext-keybinding_menu.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/js/libs/ace/ext-keybinding_menu.js b/apps/fauxton/assets/js/libs/ace/ext-keybinding_menu.js
deleted file mode 100644
index fac6eae..0000000
--- a/apps/fauxton/assets/js/libs/ace/ext-keybinding_menu.js
+++ /dev/null
@@ -1,207 +0,0 @@
-/* ***** BEGIN LICENSE BLOCK *****
- * Distributed under the BSD license:
- *
- * Copyright (c) 2013 Matthew Christopher Kastor-Inare III, Atropa Inc. Intl
- * All rights reserved.
- *
- * Contributed to Ajax.org under the BSD license.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above copyright
- *       notice, this list of conditions and the following disclaimer in the
- *       documentation and/or other materials provided with the distribution.
- *     * Neither the name of Ajax.org B.V. nor the
- *       names of its contributors may be used to endorse or promote products
- *       derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * ***** END LICENSE BLOCK ***** */
-
-define('ace/ext/keybinding_menu', ['require', 'exports', 'module' , 'ace/editor', 'ace/ext/menu_tools/overlay_page', 'ace/ext/menu_tools/get_editor_keyboard_shortcuts'], function(require, exports, module) {
-    
-    var Editor = require("ace/editor").Editor;
-    function showKeyboardShortcuts (editor) {
-        if(!document.getElementById('kbshortcutmenu')) {
-            var overlayPage = require('./menu_tools/overlay_page').overlayPage;
-            var getEditorKeybordShortcuts = require('./menu_tools/get_editor_keyboard_shortcuts').getEditorKeybordShortcuts;
-            var kb = getEditorKeybordShortcuts(editor);
-            var el = document.createElement('div');
-            var commands = kb.reduce(function(previous, current) {
-                return previous + '<div class="ace_optionsMenuEntry"><span class="ace_optionsMenuCommand">' 
-                    + current.command + '</span> : '
-                    + '<span class="ace_optionsMenuKey">' + current.key + '</span></div>';
-            }, '');
-
-            el.id = 'kbshortcutmenu';
-            el.innerHTML = '<h1>Keyboard Shortcuts</h1>' + commands + '</div>';
-            overlayPage(editor, el, '0', '0', '0', null);
-        }
-    };
-    module.exports.init = function(editor) {
-        Editor.prototype.showKeyboardShortcuts = function() {
-            showKeyboardShortcuts(this);
-        };
-        editor.commands.addCommands([{
-            name: "showKeyboardShortcuts",
-            bindKey: {win: "Ctrl-Alt-h", mac: "Command-Alt-h"},
-            exec: function(editor, line) {
-                editor.showKeyboardShortcuts();
-            }
-        }]);
-    };
-
-});
-
-define('ace/ext/menu_tools/overlay_page', ['require', 'exports', 'module' , 'ace/lib/dom'], function(require, exports, module) {
-
-var dom = require("../../lib/dom");
-var cssText = "#ace_settingsmenu, #kbshortcutmenu {\
-background-color: #F7F7F7;\
-color: black;\
-box-shadow: -5px 4px 5px rgba(126, 126, 126, 0.55);\
-padding: 1em 0.5em 2em 1em;\
-overflow: auto;\
-position: absolute;\
-margin: 0;\
-bottom: 0;\
-right: 0;\
-top: 0;\
-z-index: 9991;\
-cursor: default;\
-}\
-.ace_dark #ace_settingsmenu, .ace_dark #kbshortcutmenu {\
-box-shadow: -20px 10px 25px rgba(126, 126, 126, 0.25);\
-background-color: rgba(255, 255, 255, 0.6);\
-color: black;\
-}\
-.ace_optionsMenuEntry:hover {\
-background-color: rgba(100, 100, 100, 0.1);\
--webkit-transition: all 0.5s;\
-transition: all 0.3s\
-}\
-.ace_closeButton {\
-background: rgba(245, 146, 146, 0.5);\
-border: 1px solid #F48A8A;\
-border-radius: 50%;\
-padding: 7px;\
-position: absolute;\
-right: -8px;\
-top: -8px;\
-z-index: 1000;\
-}\
-.ace_closeButton{\
-background: rgba(245, 146, 146, 0.9);\
-}\
-.ace_optionsMenuKey {\
-color: darkslateblue;\
-font-weight: bold;\
-}\
-.ace_optionsMenuCommand {\
-color: darkcyan;\
-font-weight: normal;\
-}";
-dom.importCssString(cssText);
-module.exports.overlayPage = function overlayPage(editor, contentElement, top, right, bottom, left) {
-    top = top ? 'top: ' + top + ';' : '';
-    bottom = bottom ? 'bottom: ' + bottom + ';' : '';
-    right = right ? 'right: ' + right + ';' : '';
-    left = left ? 'left: ' + left + ';' : '';
-
-    var closer = document.createElement('div');
-    var contentContainer = document.createElement('div');
-
-    function documentEscListener(e) {
-        if (e.keyCode === 27) {
-            closer.click();
-        }
-    }
-
-    closer.style.cssText = 'margin: 0; padding: 0; ' +
-        'position: fixed; top:0; bottom:0; left:0; right:0;' +
-        'z-index: 9990; ' +
-        'background-color: rgba(0, 0, 0, 0.3);';
-    closer.addEventListener('click', function() {
-        document.removeEventListener('keydown', documentEscListener);
-        closer.parentNode.removeChild(closer);
-        editor.focus();
-        closer = null;
-    });
-    document.addEventListener('keydown', documentEscListener);
-
-    contentContainer.style.cssText = top + right + bottom + left;
-    contentContainer.addEventListener('click', function(e) {
-        e.stopPropagation();
-    });
-
-    var wrapper = dom.createElement("div");
-    wrapper.style.position = "relative";
-    
-    var closeButton = dom.createElement("div");
-    closeButton.className = "ace_closeButton";
-    closeButton.addEventListener('click', function() {
-        closer.click();
-    });
-    
-    wrapper.appendChild(closeButton);
-    contentContainer.appendChild(wrapper);
-    
-    contentContainer.appendChild(contentElement);
-    closer.appendChild(contentContainer);
-    document.body.appendChild(closer);
-    editor.blur();
-};
-
-});
-
-define('ace/ext/menu_tools/get_editor_keyboard_shortcuts', ['require', 'exports', 'module' , 'ace/lib/keys'], function(require, exports, module) {
-
-var keys = require("../../lib/keys");
-module.exports.getEditorKeybordShortcuts = function(editor) {
-    var KEY_MODS = keys.KEY_MODS;
-    var keybindings = [];
-    var commandMap = {};
-    editor.keyBinding.$handlers.forEach(function(handler) {
-        var ckb = handler.commandKeyBinding;
-        for (var i in ckb) {
-            var modifier = parseInt(i);
-            if (modifier == -1) {
-                modifier = "";
-            } else if(isNaN(modifier)) {
-                modifier = i;
-            } else {
-                modifier = "" +
-                    (modifier & KEY_MODS.command ? "Cmd-"   : "") +
-                    (modifier & KEY_MODS.ctrl    ? "Ctrl-"  : "") +
-                    (modifier & KEY_MODS.alt     ? "Alt-"   : "") +
-                    (modifier & KEY_MODS.shift   ? "Shift-" : "");
-            }
-            for (var key in ckb[i]) {
-                var command = ckb[i][key]
-                if (typeof command != "string")
-                    command  = command.name
-                if (commandMap[command]) {
-                    commandMap[command].key += "|" + modifier + key;
-                } else {
-                    commandMap[command] = {key: modifier+key, command: command};
-                    keybindings.push(commandMap[command]);
-                }
-            }
-        }
-    });
-    return keybindings;
-};
-
-});
\ No newline at end of file


[55/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/utext.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/utext.h b/src/apps/couch_collate/platform/osx/icu/unicode/utext.h
new file mode 100644
index 0000000..866b850
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/utext.h
@@ -0,0 +1,1562 @@
+/*
+*******************************************************************************
+*
+*   Copyright (C) 2004-2008, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+*
+*******************************************************************************
+*   file name:  utext.h
+*   encoding:   US-ASCII
+*   tab size:   8 (not used)
+*   indentation:4
+*
+*   created on: 2004oct06
+*   created by: Markus W. Scherer
+*/
+
+#ifndef __UTEXT_H__
+#define __UTEXT_H__
+
+/**
+ * \file
+ * \brief C API: Abstract Unicode Text API
+ *
+ * The Text Access API provides a means to allow text that is stored in alternative
+ * formats to work with ICU services.  ICU normally operates on text that is
+ * stored in UTF-16 format, in (UChar *) arrays for the C APIs or as type
+ * UnicodeString for C++ APIs.
+ *
+ * ICU Text Access allows other formats, such as UTF-8 or non-contiguous
+ * UTF-16 strings, to be placed in a UText wrapper and then passed to ICU services.
+ *
+ * There are three general classes of usage for UText:
+ *
+ *     Application Level Use.  This is the simplest usage - applications would
+ *     use one of the utext_open() functions on their input text, and pass
+ *     the resulting UText to the desired ICU service.
+ *
+ *     Second is usage in ICU Services, such as break iteration, that will need to
+ *     operate on input presented to them as a UText.  These implementations
+ *     will need to use the iteration and related UText functions to gain
+ *     access to the actual text.
+ *
+ *     The third class of UText users are "text providers."  These are the
+ *     UText implementations for the various text storage formats.  An application
+ *     or system with a unique text storage format can implement a set of
+ *     UText provider functions for that format, which will then allow
+ *     ICU services to operate on that format.
+ *
+ *
+ * <em>Iterating over text</em>
+ *
+ * Here is sample code for a forward iteration over the contents of a UText
+ *
+ * \code
+ *    UChar32  c;
+ *    UText    *ut = whatever();
+ *
+ *    for (c=utext_next32From(ut, 0); c>=0; c=utext_next32(ut)) {
+ *       // do whatever with the codepoint c here.
+ *    }
+ * \endcode
+ *
+ * And here is similar code to iterate in the reverse direction, from the end
+ * of the text towards the beginning.
+ *
+ * \code
+ *    UChar32  c;
+ *    UText    *ut = whatever();
+ *    int      textLength = utext_nativeLength(ut);
+ *    for (c=utext_previous32From(ut, textLength); c>=0; c=utext_previous32(ut)) {
+ *       // do whatever with the codepoint c here.
+ *    }
+ * \endcode
+ *
+ * <em>Characters and Indexing</em>
+ *
+ * Indexing into text by UText functions is nearly always in terms of the native
+ * indexing of the underlying text storage.  The storage format could be UTF-8
+ * or UTF-32, for example.  When coding to the UText access API, no assumptions
+ * can be made regarding the size of characters, or how far an index
+ * may move when iterating between characters.
+ *
+ * All indices supplied to UText functions are pinned to the length of the
+ * text.  An out-of-bounds index is not considered to be an error, but is
+ * adjusted to be in the range  0 <= index <= length of input text.
+ *
+ *
+ * When an index position is returned from a UText function, it will be
+ * a native index to the underlying text.  In the case of multi-unit characters,
+ * it will  always refer to the first position of the character,
+ * never to the interior.  This is essentially the same thing as saying that
+ * a returned index will always point to a boundary between characters.
+ *
+ * When a native index is supplied to a UText function, all indices that
+ * refer to any part of a multi-unit character representation are considered
+ * to be equivalent.  In the case of multi-unit characters, an incoming index
+ * will be logically normalized to refer to the start of the character.
+ * 
+ * It is possible to test whether a native index is on a code point boundary
+ * by doing a utext_setNativeIndex() followed by a utext_getNativeIndex().
+ * If the index is returned unchanged, it was on a code point boundary.  If
+ * an adjusted index is returned, the original index referred to the
+ * interior of a character.
+ *
+ * <em>Conventions for calling UText functions</em>
+ *
+ * Most UText access functions have as their first parameter a (UText *) pointer,
+ * which specifies the UText to be used.  Unless otherwise noted, the
+ * pointer must refer to a valid, open UText.  Attempting to
+ * use a closed UText or passing a NULL pointer is a programming error and
+ * will produce undefined results or NULL pointer exceptions.
+ * 
+ * The UText_Open family of functions can either open an existing (closed)
+ * UText, or heap allocate a new UText.  Here is sample code for creating
+ * a stack-allocated UText.
+ *
+ * \code
+ *    char     *s = whatever();  // A utf-8 string 
+ *    U_ErrorCode status = U_ZERO_ERROR;
+ *    UText    ut = UTEXT_INITIALIZER;
+ *    utext_openUTF8(ut, s, -1, &status);
+ *    if (U_FAILURE(status)) {
+ *        // error handling
+ *    } else {
+ *        // work with the UText
+ *    }
+ * \endcode
+ *
+ * Any existing UText passed to an open function _must_ have been initialized, 
+ * either by the UTEXT_INITIALIZER, or by having been originally heap-allocated
+ * by an open function.  Passing NULL will cause the open function to
+ * heap-allocate and fully initialize a new UText.
+ *
+ */
+
+
+
+#include "unicode/utypes.h"
+#ifdef XP_CPLUSPLUS
+#include "unicode/rep.h"
+#include "unicode/unistr.h"
+#include "unicode/chariter.h"
+#endif
+
+
+U_CDECL_BEGIN
+
+struct UText;
+typedef struct UText UText; /**< C typedef for struct UText. @stable ICU 3.6 */
+
+
+/***************************************************************************************
+ *
+ *   C Functions for creating UText wrappers around various kinds of text strings.
+ *
+ ****************************************************************************************/
+
+
+/**
+  * Close function for UText instances.
+  * Cleans up, releases any resources being held by an open UText.
+  * <p>
+  *   If the UText was originally allocated by one of the utext_open functions,
+  *   the storage associated with the utext will also be freed.
+  *   If the UText storage originated with the application, as it would with
+  *   a local or static instance, the storage will not be deleted.
+  *
+  *   An open UText can be reset to refer to new string by using one of the utext_open()
+  *   functions without first closing the UText.  
+  *
+  * @param ut  The UText to be closed.
+  * @return    NULL if the UText struct was deleted by the close.  If the UText struct
+  *            was originally provided by the caller to the open function, it is
+  *            returned by this function, and may be safely used again in
+  *            a subsequent utext_open.
+  *
+  * @stable ICU 3.4
+  */
+U_STABLE UText * U_EXPORT2
+utext_close(UText *ut);
+
+
+/**
+ * Open a read-only UText implementation for UTF-8 strings.
+ * 
+ * \htmlonly
+ * Any invalid UTF-8 in the input will be handled in this way:
+ * a sequence of bytes that has the form of a truncated, but otherwise valid,
+ * UTF-8 sequence will be replaced by a single unicode replacement character, \uFFFD. 
+ * Any other illegal bytes will each be replaced by a \uFFFD.
+ * \endhtmlonly
+ * 
+ * @param ut     Pointer to a UText struct.  If NULL, a new UText will be created.
+ *               If non-NULL, must refer to an initialized UText struct, which will then
+ *               be reset to reference the specified UTF-8 string.
+ * @param s      A UTF-8 string.  Must not be NULL.
+ * @param length The length of the UTF-8 string in bytes, or -1 if the string is
+ *               zero terminated.
+ * @param status Errors are returned here.
+ * @return       A pointer to the UText.  If a pre-allocated UText was provided, it
+ *               will always be used and returned.
+ * @stable ICU 3.4
+ */
+U_STABLE UText * U_EXPORT2
+utext_openUTF8(UText *ut, const char *s, int64_t length, UErrorCode *status);
+
+
+/**
+ * Open a read-only UText for UChar * string.
+ * 
+ * @param ut     Pointer to a UText struct.  If NULL, a new UText will be created.
+ *               If non-NULL, must refer to an initialized UText struct, which will then
+ *               be reset to reference the specified UChar string.
+ * @param s      A UChar (UTF-16) string
+ * @param length The number of UChars in the input string, or -1 if the string is
+ *               zero terminated.
+ * @param status Errors are returned here.
+ * @return       A pointer to the UText.  If a pre-allocated UText was provided, it
+ *               will always be used and returned.
+ * @stable ICU 3.4
+ */
+U_STABLE UText * U_EXPORT2
+utext_openUChars(UText *ut, const UChar *s, int64_t length, UErrorCode *status);
+
+
+#ifdef XP_CPLUSPLUS
+/**
+ * Open a writable UText for a non-const UnicodeString. 
+ * 
+ * @param ut      Pointer to a UText struct.  If NULL, a new UText will be created.
+ *                 If non-NULL, must refer to an initialized UText struct, which will then
+ *                 be reset to reference the specified input string.
+ * @param s       A UnicodeString.
+ * @param status Errors are returned here.
+ * @return        Pointer to the UText.  If a UText was supplied as input, this
+ *                 will always be used and returned.
+ * @stable ICU 3.4
+ */
+U_STABLE UText * U_EXPORT2
+utext_openUnicodeString(UText *ut, U_NAMESPACE_QUALIFIER UnicodeString *s, UErrorCode *status);
+
+
+/**
+ * Open a UText for a const UnicodeString.   The resulting UText will not be writable.
+ * 
+ * @param ut    Pointer to a UText struct.  If NULL, a new UText will be created.
+ *               If non-NULL, must refer to an initialized UText struct, which will then
+ *               be reset to reference the specified input string.
+ * @param s      A const UnicodeString to be wrapped.
+ * @param status Errors are returned here.
+ * @return       Pointer to the UText.  If a UText was supplied as input, this
+ *               will always be used and returned.
+ * @stable ICU 3.4
+ */
+U_STABLE UText * U_EXPORT2
+utext_openConstUnicodeString(UText *ut, const U_NAMESPACE_QUALIFIER UnicodeString *s, UErrorCode *status);
+
+
+/**
+ * Open a writable UText implementation for an ICU Replaceable object.
+ * @param ut    Pointer to a UText struct.  If NULL, a new UText will be created.
+ *               If non-NULL, must refer to an already existing UText, which will then
+ *               be reset to reference the specified replaceable text.
+ * @param rep    A Replaceable text object.
+ * @param status Errors are returned here.
+ * @return       Pointer to the UText.  If a UText was supplied as input, this
+ *               will always be used and returned.
+ * @see Replaceable
+ * @stable ICU 3.4
+ */
+U_STABLE UText * U_EXPORT2
+utext_openReplaceable(UText *ut, U_NAMESPACE_QUALIFIER Replaceable *rep, UErrorCode *status);
+
+/**
+ * Open a  UText implementation over an ICU CharacterIterator.
+ * @param ut    Pointer to a UText struct.  If NULL, a new UText will be created.
+ *               If non-NULL, must refer to an already existing UText, which will then
+ *               be reset to reference the specified replaceable text.
+ * @param ci     A Character Iterator.
+ * @param status Errors are returned here.
+ * @return       Pointer to the UText.  If a UText was supplied as input, this
+ *               will always be used and returned.
+ * @see Replaceable
+ * @stable ICU 3.4
+ */
+U_STABLE UText * U_EXPORT2
+utext_openCharacterIterator(UText *ut, U_NAMESPACE_QUALIFIER CharacterIterator *ic, UErrorCode *status);
+
+#endif
+
+
+/**
+  *  Clone a UText.  This is much like opening a UText where the source text is itself
+  *  another UText.
+  *
+  *  A deep clone will copy both the UText data structures and the underlying text.
+  *  The original and cloned UText will operate completely independently; modifications
+  *  made to the text in one will not affect the other.  Text providers are not
+  *  required to support deep clones.  The user of clone() must check the status return
+  *  and be prepared to handle failures.
+  *
+  *  The standard UText implementations for UTF8, UChar *, UnicodeString and
+  *  Replaceable all support deep cloning.
+  *
+  *  The UText returned from a deep clone will be writable, assuming that the text
+  *  provider is able to support writing, even if the source UText had been made
+  *  non-writable by means of UText_freeze().
+  *
+  *  A shallow clone replicates only the UText data structures; it does not make
+  *  a copy of the underlying text.  Shallow clones can be used as an efficient way to 
+  *  have multiple iterators active in a single text string that is not being
+  *  modified.
+  *
+  *  A shallow clone operation will not fail, barring truly exceptional conditions such
+  *  as memory allocation failures.
+  *
+  *  Shallow UText clones should be avoided if the UText functions that modify the
+  *  text are expected to be used, either on the original or the cloned UText.
+  *  Any such modifications  can cause unpredictable behavior.  Read Only
+  *  shallow clones provide some protection against errors of this type by
+  *  disabling text modification via the cloned UText.
+  *
+  *  A shallow clone made with the readOnly parameter == FALSE will preserve the 
+  *  utext_isWritable() state of the source object.  Note, however, that
+  *  write operations must be avoided while more than one UText exists that refer
+  *  to the same underlying text.
+  *
+  *  A UText and its clone may be safely concurrently accessed by separate threads.
+  *  This is true for read access only with shallow clones, and for both read and
+  *  write access with deep clones.
+  *  It is the responsibility of the Text Provider to ensure that this thread safety
+  *  constraint is met.
+  *
+  *  @param dest   A UText struct to be filled in with the result of the clone operation,
+  *                or NULL if the clone function should heap-allocate a new UText struct.
+  *                If non-NULL, must refer to an already existing UText, which will then
+  *                be reset to become the clone.
+  *  @param src    The UText to be cloned.
+  *  @param deep   TRUE to request a deep clone, FALSE for a shallow clone.
+  *  @param readOnly TRUE to request that the cloned UText have read only access to the 
+  *                underlying text.  
+
+  *  @param status Errors are returned here.  For deep clones, U_UNSUPPORTED_ERROR
+  *                will be returned if the text provider is unable to clone the
+  *                original text.
+  *  @return       The newly created clone, or NULL if the clone operation failed.
+  *  @stable ICU 3.4
+  */
+U_STABLE UText * U_EXPORT2
+utext_clone(UText *dest, const UText *src, UBool deep, UBool readOnly, UErrorCode *status);
+
+
+/**
+  *  Compare two UText objects for equality.
+  *  UTexts are equal if they are iterating over the same text, and
+  *    have the same iteration position within the text.
+  *    If either or both of the parameters are NULL, the comparison is FALSE.
+  *
+  *  @param a   The first of the two UTexts to compare.
+  *  @param b   The other UText to be compared.
+  *  @return    TRUE if the two UTexts are equal.
+  *  @stable ICU 3.6
+  */
+U_STABLE UBool U_EXPORT2
+utext_equals(const UText *a, const UText *b);
+
+
+/*****************************************************************************
+ *
+ *   Functions to work with the text represeted by a UText wrapper
+ *
+ *****************************************************************************/
+
+/**
+  * Get the length of the text.  Depending on the characteristics
+  * of the underlying text representation, this may be expensive.  
+  * @see  utext_isLengthExpensive()
+  *
+  *
+  * @param ut  the text to be accessed.
+  * @return the length of the text, expressed in native units.
+  *
+  * @stable ICU 3.4
+  */
+U_STABLE int64_t U_EXPORT2
+utext_nativeLength(UText *ut);
+
+/**
+ *  Return TRUE if calculating the length of the text could be expensive.
+ *  Finding the length of NUL terminated strings is considered to be expensive.
+ *
+ *  Note that the value of this function may change
+ *  as the result of other operations on a UText.
+ *  Once the length of a string has been discovered, it will no longer
+ *  be expensive to report it.
+ *
+ * @param ut the text to be accessed.
+ * @return TRUE if determining the length of the text could be time consuming.
+ * @stable ICU 3.4
+ */
+U_STABLE UBool U_EXPORT2
+utext_isLengthExpensive(const UText *ut);
+
+/**
+ * Returns the code point at the requested index,
+ * or U_SENTINEL (-1) if it is out of bounds.
+ *
+ * If the specified index points to the interior of a multi-unit
+ * character - one of the trail bytes of a UTF-8 sequence, for example -
+ * the complete code point will be returned.
+ *
+ * The iteration position will be set to the start of the returned code point.
+ *
+ * This function is roughly equivalent to the the sequence
+ *    utext_setNativeIndex(index);
+ *    utext_current32();
+ * (There is a subtle difference if the index is out of bounds by being less than zero - 
+ * utext_setNativeIndex(negative value) sets the index to zero, after which utext_current()
+ * will return the char at zero.  utext_char32At(negative index), on the other hand, will
+ * return the U_SENTINEL value of -1.)
+ * 
+ * @param ut the text to be accessed
+ * @param nativeIndex the native index of the character to be accessed.  If the index points
+ *        to other than the first unit of a multi-unit character, it will be adjusted
+ *        to the start of the character.
+ * @return the code point at the specified index.
+ * @stable ICU 3.4
+ */
+U_STABLE UChar32 U_EXPORT2
+utext_char32At(UText *ut, int64_t nativeIndex);
+
+
+/**
+ *
+ * Get the code point at the current iteration position,
+ * or U_SENTINEL (-1) if the iteration has reached the end of
+ * the input text.
+ *
+ * @param ut the text to be accessed.
+ * @return the Unicode code point at the current iterator position.
+ * @stable ICU 3.4
+ */
+U_STABLE UChar32 U_EXPORT2
+utext_current32(UText *ut);
+
+
+/**
+ * Get the code point at the current iteration position of the UText, and
+ * advance the position to the first index following the character.
+ *
+ * If the position is at the end of the text (the index following
+ * the last character, which is also the length of the text), 
+ * return U_SENTINEL (-1) and do not advance the index. 
+ *
+ * This is a post-increment operation.
+ *
+ * An inline macro version of this function, UTEXT_NEXT32(), 
+ * is available for performance critical use.
+ *
+ * @param ut the text to be accessed.
+ * @return the Unicode code point at the iteration position.
+ * @see UTEXT_NEXT32
+ * @stable ICU 3.4
+ */
+U_STABLE UChar32 U_EXPORT2
+utext_next32(UText *ut);
+
+
+/**
+ *  Move the iterator position to the character (code point) whose
+ *  index precedes the current position, and return that character.
+ *  This is a pre-decrement operation.
+ *
+ *  If the initial position is at the start of the text (index of 0) 
+ *  return U_SENTINEL (-1), and leave the position unchanged.
+ *
+ *  An inline macro version of this function, UTEXT_PREVIOUS32(), 
+ *  is available for performance critical use.
+ *
+ *  @param ut the text to be accessed.
+ *  @return the previous UChar32 code point, or U_SENTINEL (-1) 
+ *          if the iteration has reached the start of the text.
+ *  @see UTEXT_PREVIOUS32
+ *  @stable ICU 3.4
+ */
+U_STABLE UChar32 U_EXPORT2
+utext_previous32(UText *ut);
+
+
+/**
+  * Set the iteration index and return the code point at that index. 
+  * Leave the iteration index at the start of the following code point.
+  *
+  * This function is the most efficient and convenient way to
+  * begin a forward iteration.  The results are identical to the those
+  * from the sequence
+  * \code
+  *    utext_setIndex();
+  *    utext_next32();
+  * \endcode
+  *
+  *  @param ut the text to be accessed.
+  *  @param nativeIndex Iteration index, in the native units of the text provider.
+  *  @return Code point which starts at or before index,
+  *         or U_SENTINEL (-1) if it is out of bounds.
+  * @stable ICU 3.4
+  */
+U_STABLE UChar32 U_EXPORT2
+utext_next32From(UText *ut, int64_t nativeIndex);
+
+
+
+/**
+  * Set the iteration index, and return the code point preceding the
+  * one specified by the initial index.  Leave the iteration position
+  * at the start of the returned code point.
+  *
+  * This function is the most efficient and convenient way to
+  * begin a backwards iteration.
+  *
+  * @param ut the text to be accessed.
+  * @param nativeIndex Iteration index in the native units of the text provider.
+  * @return Code point preceding the one at the initial index,
+  *         or U_SENTINEL (-1) if it is out of bounds.
+  *
+  * @stable ICU 3.4
+  */
+U_STABLE UChar32 U_EXPORT2
+utext_previous32From(UText *ut, int64_t nativeIndex);
+
+/**
+  * Get the current iterator position, which can range from 0 to 
+  * the length of the text.
+  * The position is a native index into the input text, in whatever format it
+  * may have (possibly UTF-8 for example), and may not always be the same as
+  * the corresponding UChar (UTF-16) index.
+  * The returned position will always be aligned to a code point boundary. 
+  *
+  * @param ut the text to be accessed.
+  * @return the current index position, in the native units of the text provider.
+  * @stable ICU 3.4
+  */
+U_STABLE int64_t U_EXPORT2
+utext_getNativeIndex(const UText *ut);
+
+/**
+ * Set the current iteration position to the nearest code point
+ * boundary at or preceding the specified index.
+ * The index is in the native units of the original input text.
+ * If the index is out of range, it will be pinned to be within
+ * the range of the input text.
+ * <p>
+ * It will usually be more efficient to begin an iteration
+ * using the functions utext_next32From() or utext_previous32From()
+ * rather than setIndex().
+ * <p>
+ * Moving the index position to an adjacent character is best done
+ * with utext_next32(), utext_previous32() or utext_moveIndex32().
+ * Attempting to do direct arithmetic on the index position is
+ * complicated by the fact that the size (in native units) of a
+ * character depends on the underlying representation of the character
+ * (UTF-8, UTF-16, UTF-32, arbitrary codepage), and is not
+ * easily knowable.
+ *
+ * @param ut the text to be accessed.
+ * @param nativeIndex the native unit index of the new iteration position.
+ * @stable ICU 3.4
+ */
+U_STABLE void U_EXPORT2
+utext_setNativeIndex(UText *ut, int64_t nativeIndex);
+
+/**
+ * Move the iterator postion by delta code points.  The number of code points
+ * is a signed number; a negative delta will move the iterator backwards,
+ * towards the start of the text.
+ * <p>
+ * The index is moved by <code>delta</code> code points
+ * forward or backward, but no further backward than to 0 and
+ * no further forward than to utext_nativeLength().
+ * The resulting index value will be in between 0 and length, inclusive.
+ *
+ * @param ut the text to be accessed.
+ * @param delta the signed number of code points to move the iteration position.
+ * @return TRUE if the position could be moved the requested number of positions while
+ *              staying within the range [0 - text length].
+ * @stable ICU 3.4
+ */
+U_STABLE UBool U_EXPORT2
+utext_moveIndex32(UText *ut, int32_t delta);
+
+/**
+ * Get the native index of the character preceeding the current position.
+ * If the iteration position is already at the start of the text, zero
+ * is returned.
+ * The value returned is the same as that obtained from the following sequence,
+ * but without the side effect of changing the iteration position.
+ *   
+ * \code
+ *    UText  *ut = whatever;
+ *      ...
+ *    utext_previous(ut)
+ *    utext_getNativeIndex(ut);
+ * \endcode
+ *
+ * This function is most useful during forwards iteration, where it will get the
+ *   native index of the character most recently returned from utext_next().
+ *
+ * @param ut the text to be accessed
+ * @return the native index of the character preceeding the current index position,
+ *         or zero if the current position is at the start of the text.
+ * @stable ICU 3.6
+ */
+U_STABLE int64_t U_EXPORT2
+utext_getPreviousNativeIndex(UText *ut); 
+
+
+/**
+ *
+ * Extract text from a UText into a UChar buffer.  The range of text to be extracted
+ * is specified in the native indices of the UText provider.  These may not necessarily
+ * be UTF-16 indices.
+ * <p>
+ * The size (number of 16 bit UChars) of the data to be extracted is returned.  The
+ * full number of UChars is returned, even when the extracted text is truncated
+ * because the specified buffer size is too small.
+ * <p>
+ * The extracted string will (if you are a user) / must (if you are a text provider)
+ * be NUL-terminated if there is sufficient space in the destination buffer.  This
+ * terminating NUL is not included in the returned length.
+ * <p>
+ * The iteration index is left at the position following the last extracted character.
+ *
+ * @param  ut    the UText from which to extract data.
+ * @param  nativeStart the native index of the first character to extract.\
+ *               If the specified index is out of range,
+ *               it will be pinned to to be within 0 <= index <= textLength
+ * @param  nativeLimit the native string index of the position following the last
+ *               character to extract.  If the specified index is out of range,
+ *               it will be pinned to to be within 0 <= index <= textLength.
+ *               nativeLimit must be >= nativeStart.
+ * @param  dest  the UChar (UTF-16) buffer into which the extracted text is placed
+ * @param  destCapacity  The size, in UChars, of the destination buffer.  May be zero
+ *               for precomputing the required size.
+ * @param  status receives any error status.
+ *         U_BUFFER_OVERFLOW_ERROR: the extracted text was truncated because the 
+ *         buffer was too small.  Returns number of UChars for preflighting.
+ * @return Number of UChars in the data to be extracted.  Does not include a trailing NUL.
+ *
+ * @stable ICU 3.4
+ */
+U_STABLE int32_t U_EXPORT2
+utext_extract(UText *ut,
+             int64_t nativeStart, int64_t nativeLimit,
+             UChar *dest, int32_t destCapacity,
+             UErrorCode *status);
+
+
+/************************************************************************************
+ *
+ *  #define inline versions of selected performance-critical text access functions
+ *          Caution:  do not use auto increment++ or decrement-- expressions
+ *                    as parameters to these macros.
+ *
+ *          For most use, where there is no extreme performance constraint, the
+ *          normal, non-inline functions are a better choice.  The resulting code
+ *          will be smaller, and, if the need ever arises, easier to debug.
+ *
+ *          These are implemented as #defines rather than real functions
+ *          because there is no fully portable way to do inline functions in plain C.
+ *
+ ************************************************************************************/
+
+/**
+ * inline version of utext_next32(), for performance-critical situations.
+ *
+ * Get the code point at the current iteration position of the UText, and
+ * advance the position to the first index following the character.
+ * This is a post-increment operation.
+ * Returns U_SENTINEL (-1) if the position is at the end of the
+ * text.
+ *
+ * @stable ICU 3.4
+ */
+#define UTEXT_NEXT32(ut)  \
+    ((ut)->chunkOffset < (ut)->chunkLength && ((ut)->chunkContents)[(ut)->chunkOffset]<0xd800 ? \
+    ((ut)->chunkContents)[((ut)->chunkOffset)++] : utext_next32(ut))
+
+/**
+ * inline version of utext_previous32(), for performance-critical situations.
+ *
+ *  Move the iterator position to the character (code point) whose
+ *  index precedes the current position, and return that character.
+ *  This is a pre-decrement operation.
+ *  Returns U_SENTINEL (-1) if the position is at the start of the  text.
+ *
+ * @stable ICU 3.4
+ */
+#define UTEXT_PREVIOUS32(ut)  \
+    ((ut)->chunkOffset > 0 && \
+     (ut)->chunkContents[(ut)->chunkOffset-1] < 0xd800 ? \
+          (ut)->chunkContents[--((ut)->chunkOffset)]  :  utext_previous32(ut))
+
+/**
+  *  inline version of utext_getNativeIndex(), for performance-critical situations.
+  *
+  * Get the current iterator position, which can range from 0 to 
+  * the length of the text.
+  * The position is a native index into the input text, in whatever format it
+  * may have (possibly UTF-8 for example), and may not always be the same as
+  * the corresponding UChar (UTF-16) index.
+  * The returned position will always be aligned to a code point boundary. 
+  *
+  * @stable ICU 3.6
+  */
+#define UTEXT_GETNATIVEINDEX(ut)                       \
+    ((ut)->chunkOffset <= (ut)->nativeIndexingLimit?   \
+        (ut)->chunkNativeStart+(ut)->chunkOffset :     \
+        (ut)->pFuncs->mapOffsetToNative(ut))    
+
+/**
+  *  inline version of utext_setNativeIndex(), for performance-critical situations.
+  *
+  * Set the current iteration position to the nearest code point
+  * boundary at or preceding the specified index.
+  * The index is in the native units of the original input text.
+  * If the index is out of range, it will be pinned to be within
+  * the range of the input text.
+  *
+  * @stable ICU 4.0
+  */
+#define UTEXT_SETNATIVEINDEX(ut, ix)                       \
+    { int64_t __offset = (ix) - (ut)->chunkNativeStart; \
+      if (__offset>=0 && __offset<=(int64_t)(ut)->nativeIndexingLimit) { \
+          (ut)->chunkOffset=(int32_t)__offset; \
+      } else { \
+          utext_setNativeIndex((ut), (ix)); } }
+
+
+
+/************************************************************************************
+ *
+ *   Functions related to writing or modifying the text.
+ *   These will work only with modifiable UTexts.  Attempting to
+ *   modify a read-only UText will return an error status.
+ *
+ ************************************************************************************/
+
+
+/**
+ *  Return TRUE if the text can be written (modified) with utext_replace() or
+ *  utext_copy().  For the text to be writable, the text provider must
+ *  be of a type that supports writing and the UText must not be frozen.
+ *
+ *  Attempting to modify text when utext_isWriteable() is FALSE will fail -
+ *  the text will not be modified, and an error will be returned from the function
+ *  that attempted the modification.
+ *
+ * @param  ut   the UText to be tested.
+ * @return TRUE if the text is modifiable.
+ *
+ * @see    utext_freeze()
+ * @see    utext_replace()
+ * @see    utext_copy()
+ * @stable ICU 3.4
+ *
+ */
+U_STABLE UBool U_EXPORT2
+utext_isWritable(const UText *ut);
+
+
+/**
+  * Test whether there is meta data associated with the text.
+  * @see Replaceable::hasMetaData()
+  *
+  * @param ut The UText to be tested
+  * @return TRUE if the underlying text includes meta data.
+  * @stable ICU 3.4
+  */
+U_STABLE UBool U_EXPORT2
+utext_hasMetaData(const UText *ut);
+
+
+/**
+ * Replace a range of the original text with a replacement text.
+ *
+ * Leaves the current iteration position at the position following the
+ *  newly inserted replacement text.
+ *
+ * This function is only available on UText types that support writing,
+ * that is, ones where utext_isWritable() returns TRUE.
+ *
+ * When using this function, there should be only a single UText opened onto the
+ * underlying native text string.  Behavior after a replace operation
+ * on a UText is undefined for any other additional UTexts that refer to the
+ * modified string.
+ *
+ * @param ut               the UText representing the text to be operated on.
+ * @param nativeStart      the native index of the start of the region to be replaced
+ * @param nativeLimit      the native index of the character following the region to be replaced.
+ * @param replacementText  pointer to the replacement text
+ * @param replacementLength length of the replacement text, or -1 if the text is NUL terminated.
+ * @param status           receives any error status.  Possible errors include
+ *                         U_NO_WRITE_PERMISSION
+ *
+ * @return The signed number of (native) storage units by which
+ *         the length of the text expanded or contracted.
+ *
+ * @stable ICU 3.4
+ */
+U_STABLE int32_t U_EXPORT2
+utext_replace(UText *ut,
+             int64_t nativeStart, int64_t nativeLimit,
+             const UChar *replacementText, int32_t replacementLength,
+             UErrorCode *status);
+
+
+
+/**
+ *
+ * Copy or move a substring from one position to another within the text,
+ * while retaining any metadata associated with the text.
+ * This function is used to duplicate or reorder substrings.
+ * The destination index must not overlap the source range.
+ *
+ * The text to be copied or moved is inserted at destIndex;
+ * it does not replace or overwrite any existing text.
+ *
+ * The iteration position is left following the newly inserted text
+ * at the destination position.
+ *
+ * This function is only available on UText types that support writing,
+ * that is, ones where utext_isWritable() returns TRUE.
+ *
+ * When using this function, there should be only a single UText opened onto the
+ * underlying native text string.  Behavior after a copy operation
+ * on a UText is undefined in any other additional UTexts that refer to the
+ * modified string.
+ *
+ * @param ut           The UText representing the text to be operated on.
+ * @param nativeStart  The native index of the start of the region to be copied or moved
+ * @param nativeLimit  The native index of the character position following the region
+ *                     to be copied.
+ * @param destIndex    The native destination index to which the source substring is
+ *                     copied or moved.
+ * @param move         If TRUE, then the substring is moved, not copied/duplicated.
+ * @param status       receives any error status.  Possible errors include U_NO_WRITE_PERMISSION
+ *                       
+ * @stable ICU 3.4
+ */
+U_STABLE void U_EXPORT2
+utext_copy(UText *ut,
+          int64_t nativeStart, int64_t nativeLimit,
+          int64_t destIndex,
+          UBool move,
+          UErrorCode *status);
+
+
+/**
+  *  <p>
+  *  Freeze a UText.  This prevents any modification to the underlying text itself
+  *  by means of functions operating on this UText.
+  *  </p>
+  *  <p>
+  *  Once frozen, a UText can not be unfrozen.  The intent is to ensure
+  *  that a the text underlying a frozen UText wrapper cannot be modified via that UText.
+  *  </p>
+  *  <p>
+  *  Caution:  freezing a UText will disable changes made via the specific
+  *   frozen UText wrapper only; it will not have any effect on the ability to
+  *   directly modify the text by bypassing the UText.  Any such backdoor modifications
+  *   are always an error while UText access is occuring because the underlying
+  *   text can get out of sync with UText's buffering.
+  *  </p>
+  *
+  *  @param ut  The UText to be frozen.
+  *  @see   utext_isWritable()
+  *  @stable ICU 3.6
+  */
+U_STABLE void U_EXPORT2
+utext_freeze(UText *ut);
+
+
+/**
+ * UText provider properties (bit field indexes).
+ *
+ * @see UText
+ * @stable ICU 3.4
+ */
+enum {
+    /**
+     * It is potentially time consuming for the provider to determine the length of the text.
+     * @stable ICU 3.4
+     */
+    UTEXT_PROVIDER_LENGTH_IS_EXPENSIVE = 1,
+    /**
+     * Text chunks remain valid and usable until the text object is modified or
+     * deleted, not just until the next time the access() function is called
+     * (which is the default).
+     * @stable ICU 3.4
+     */
+    UTEXT_PROVIDER_STABLE_CHUNKS = 2,
+    /**
+     * The provider supports modifying the text via the replace() and copy()
+     * functions.
+     * @see Replaceable
+     * @stable ICU 3.4
+     */
+    UTEXT_PROVIDER_WRITABLE = 3,
+    /**
+     * There is meta data associated with the text.
+     * @see Replaceable::hasMetaData()
+     * @stable ICU 3.4
+     */ 
+    UTEXT_PROVIDER_HAS_META_DATA = 4,
+    /**
+     * Text provider owns the text storage.
+     *  Generally occurs as the result of a deep clone of the UText.
+     *  When closing the UText, the associated text must
+     *  also be closed/deleted/freed/ whatever is appropriate.
+     * @stable ICU 3.6
+     */
+     UTEXT_PROVIDER_OWNS_TEXT = 5
+};
+
+/**
+  * Function type declaration for UText.clone().
+  *
+  *  clone a UText.  Much like opening a UText where the source text is itself
+  *  another UText.
+  *
+  *  A deep clone will copy both the UText data structures and the underlying text.
+  *  The original and cloned UText will operate completely independently; modifications
+  *  made to the text in one will not effect the other.  Text providers are not
+  *  required to support deep clones.  The user of clone() must check the status return
+  *  and be prepared to handle failures.
+  *
+  *  A shallow clone replicates only the UText data structures; it does not make
+  *  a copy of the underlying text.  Shallow clones can be used as an efficient way to 
+  *  have multiple iterators active in a single text string that is not being
+  *  modified.
+  *
+  *  A shallow clone operation must not fail except for truly exceptional conditions such
+  *  as memory allocation failures.
+  *
+  *  A UText and its clone may be safely concurrently accessed by separate threads.
+  *  This is true for both shallow and deep clones.
+  *  It is the responsibility of the Text Provider to ensure that this thread safety
+  *  constraint is met.
+
+  *
+  *  @param dest   A UText struct to be filled in with the result of the clone operation,
+  *                or NULL if the clone function should heap-allocate a new UText struct.
+  *  @param src    The UText to be cloned.
+  *  @param deep   TRUE to request a deep clone, FALSE for a shallow clone.
+  *  @param status Errors are returned here.  For deep clones, U_UNSUPPORTED_ERROR
+  *                should be returned if the text provider is unable to clone the
+  *                original text.
+  *  @return       The newly created clone, or NULL if the clone operation failed.
+  *
+  * @stable ICU 3.4
+  */
+typedef UText * U_CALLCONV
+UTextClone(UText *dest, const UText *src, UBool deep, UErrorCode *status);
+
+
+/**
+ * Function type declaration for UText.nativeLength().
+ *
+ * @param ut the UText to get the length of.
+ * @return the length, in the native units of the original text string.
+ * @see UText
+ * @stable ICU 3.4
+ */
+typedef int64_t U_CALLCONV
+UTextNativeLength(UText *ut);
+
+/**
+ * Function type declaration for UText.access().  Get the description of the text chunk
+ *  containing the text at a requested native index.  The UText's iteration
+ *  position will be left at the requested index.  If the index is out
+ *  of bounds, the iteration position will be left at the start or end
+ *  of the string, as appropriate.
+ *
+ *  Chunks must begin and end on code point boundaries.  A single code point
+ *  comprised of multiple storage units must never span a chunk boundary.
+ *
+ *
+ * @param ut          the UText being accessed.
+ * @param nativeIndex Requested index of the text to be accessed.
+ * @param forward     If TRUE, then the returned chunk must contain text
+ *                    starting from the index, so that start<=index<limit.
+ *                    If FALSE, then the returned chunk must contain text
+ *                    before the index, so that start<index<=limit.
+ * @return            True if the requested index could be accessed.  The chunk
+ *                    will contain the requested text.
+ *                    False value if a chunk cannot be accessed
+ *                    (the requested index is out of bounds).
+ *
+ * @see UText
+ * @stable ICU 3.4
+ */
+typedef UBool U_CALLCONV
+UTextAccess(UText *ut, int64_t nativeIndex, UBool forward);
+
+/**
+ * Function type declaration for UText.extract().
+ *
+ * Extract text from a UText into a UChar buffer.  The range of text to be extracted
+ * is specified in the native indices of the UText provider.  These may not necessarily
+ * be UTF-16 indices.
+ * <p>
+ * The size (number of 16 bit UChars) in the data to be extracted is returned.  The
+ * full amount is returned, even when the specified buffer size is smaller.
+ * <p>
+ * The extracted string will (if you are a user) / must (if you are a text provider)
+ * be NUL-terminated if there is sufficient space in the destination buffer.
+ *
+ * @param  ut            the UText from which to extract data.
+ * @param  nativeStart   the native index of the first characer to extract.
+ * @param  nativeLimit   the native string index of the position following the last
+ *                       character to extract.
+ * @param  dest          the UChar (UTF-16) buffer into which the extracted text is placed
+ * @param  destCapacity  The size, in UChars, of the destination buffer.  May be zero
+ *                       for precomputing the required size.
+ * @param  status        receives any error status.
+ *                       If U_BUFFER_OVERFLOW_ERROR: Returns number of UChars for
+ *                       preflighting.
+ * @return Number of UChars in the data.  Does not include a trailing NUL.
+ *
+ * @stable ICU 3.4
+ */
+typedef int32_t U_CALLCONV
+UTextExtract(UText *ut,
+             int64_t nativeStart, int64_t nativeLimit,
+             UChar *dest, int32_t destCapacity,
+             UErrorCode *status);
+
+/**
+ * Function type declaration for UText.replace().
+ *
+ * Replace a range of the original text with a replacement text.
+ *
+ * Leaves the current iteration position at the position following the
+ *  newly inserted replacement text.
+ *
+ * This function need only be implemented on UText types that support writing.
+ *
+ * When using this function, there should be only a single UText opened onto the
+ * underlying native text string.  The function is responsible for updating the
+ * text chunk within the UText to reflect the updated iteration position,
+ * taking into account any changes to the underlying string's structure caused
+ * by the replace operation.
+ *
+ * @param ut               the UText representing the text to be operated on.
+ * @param nativeStart      the index of the start of the region to be replaced
+ * @param nativeLimit      the index of the character following the region to be replaced.
+ * @param replacementText  pointer to the replacement text
+ * @param replacmentLength length of the replacement text in UChars, or -1 if the text is NUL terminated.
+ * @param status           receives any error status.  Possible errors include
+ *                         U_NO_WRITE_PERMISSION
+ *
+ * @return The signed number of (native) storage units by which
+ *         the length of the text expanded or contracted.
+ *
+ * @stable ICU 3.4
+ */
+typedef int32_t U_CALLCONV
+UTextReplace(UText *ut,
+             int64_t nativeStart, int64_t nativeLimit,
+             const UChar *replacementText, int32_t replacmentLength,
+             UErrorCode *status);
+
+/**
+ * Function type declaration for UText.copy().
+ *
+ * Copy or move a substring from one position to another within the text,
+ * while retaining any metadata associated with the text.
+ * This function is used to duplicate or reorder substrings.
+ * The destination index must not overlap the source range.
+ *
+ * The text to be copied or moved is inserted at destIndex;
+ * it does not replace or overwrite any existing text.
+ *
+ * This function need only be implemented for UText types that support writing.
+ *
+ * When using this function, there should be only a single UText opened onto the
+ * underlying native text string.  The function is responsible for updating the
+ * text chunk within the UText to reflect the updated iteration position,
+ * taking into account any changes to the underlying string's structure caused
+ * by the replace operation.
+ *
+ * @param ut           The UText representing the text to be operated on.
+ * @param nativeStart  The index of the start of the region to be copied or moved
+ * @param nativeLimit  The index of the character following the region to be replaced.
+ * @param nativeDest   The destination index to which the source substring is copied or moved.
+ * @param move         If TRUE, then the substring is moved, not copied/duplicated.
+ * @param status       receives any error status.  Possible errors include U_NO_WRITE_PERMISSION
+ *
+ * @stable ICU 3.4
+ */
+typedef void U_CALLCONV
+UTextCopy(UText *ut,
+          int64_t nativeStart, int64_t nativeLimit,
+          int64_t nativeDest,
+          UBool move,
+          UErrorCode *status);
+
+/**
+ * Function type declaration for UText.mapOffsetToNative().
+ * Map from the current UChar offset within the current text chunk to
+ *  the corresponding native index in the original source text.
+ *
+ * This is required only for text providers that do not use native UTF-16 indexes.
+ *
+ * @param ut     the UText.
+ * @return Absolute (native) index corresponding to chunkOffset in the current chunk.
+ *         The returned native index should always be to a code point boundary.
+ *
+ * @stable ICU 3.4
+ */
+typedef int64_t U_CALLCONV
+UTextMapOffsetToNative(const UText *ut);
+
+/**
+ * Function type declaration for UText.mapIndexToUTF16().
+ * Map from a native index to a UChar offset within a text chunk.
+ * Behavior is undefined if the native index does not fall within the
+ *   current chunk.
+ *
+ * This function is required only for text providers that do not use native UTF-16 indexes.
+ *
+ * @param ut          The UText containing the text chunk.
+ * @param nativeIndex Absolute (native) text index, chunk->start<=index<=chunk->limit.
+ * @return            Chunk-relative UTF-16 offset corresponding to the specified native
+ *                    index.
+ *
+ * @stable ICU 3.4
+ */
+typedef int32_t U_CALLCONV
+UTextMapNativeIndexToUTF16(const UText *ut, int64_t nativeIndex);
+
+
+/**
+ * Function type declaration for UText.utextClose().
+ *
+ * A Text Provider close function is only required for provider types that make
+ *  allocations in their open function (or other functions) that must be 
+ *  cleaned when the UText is closed.
+ *
+ * The allocation of the UText struct itself and any "extra" storage
+ * associated with the UText is handled by the common UText implementation
+ * and does not require provider specific cleanup in a close function.
+ *
+ * Most UText provider implementations do not need to implement this function.
+ *
+ * @param ut A UText object to be closed.
+ *
+ * @stable ICU 3.4
+ */
+typedef void U_CALLCONV
+UTextClose(UText *ut);
+
+
+/**
+  *   (public)  Function dispatch table for UText.
+  *             Conceptually very much like a C++ Virtual Function Table.
+  *             This struct defines the organization of the table.
+  *             Each text provider implementation must provide an
+  *              actual table that is initialized with the appropriate functions
+  *              for the type of text being handled.
+  *   @stable ICU 3.6
+  */
+struct UTextFuncs {
+    /**
+     *   (public)  Function table size, sizeof(UTextFuncs)
+     *             Intended for use should the table grow to accomodate added
+     *             functions in the future, to allow tests for older format
+     *             function tables that do not contain the extensions.
+     *
+     *             Fields are placed for optimal alignment on
+     *             32/64/128-bit-pointer machines, by normally grouping together
+     *             4 32-bit fields,
+     *             4 pointers,
+     *             2 64-bit fields
+     *             in sequence.
+     *   @stable ICU 3.6
+     */
+    int32_t       tableSize;
+
+    /**
+      *   (private)  Alignment padding.
+      *              Do not use, reserved for use by the UText framework only.
+      *   @internal
+      */
+    int32_t       reserved1, /** @internal */ reserved2, /** @internal */ reserved3;
+
+
+    /**
+     * (public) Function pointer for UTextClone
+     *
+     * @see UTextClone
+     * @stable ICU 3.6
+     */
+    UTextClone *clone;
+
+    /**
+     * (public) function pointer for UTextLength
+     * May be expensive to compute!
+     *
+     * @see UTextLength
+     * @stable ICU 3.6
+     */
+    UTextNativeLength *nativeLength;
+
+    /**
+     * (public) Function pointer for UTextAccess.
+     *
+     * @see UTextAccess
+     * @stable ICU 3.6
+     */
+    UTextAccess *access;
+
+    /**
+     * (public) Function pointer for UTextExtract.
+     *
+     * @see UTextExtract
+     * @stable ICU 3.6
+     */
+    UTextExtract *extract;
+
+    /**
+     * (public) Function pointer for UTextReplace.
+     *
+     * @see UTextReplace
+     * @stable ICU 3.6
+     */
+    UTextReplace *replace;
+
+    /**
+     * (public) Function pointer for UTextCopy.
+     *
+     * @see UTextCopy
+     * @stable ICU 3.6
+     */
+    UTextCopy *copy;
+
+    /**
+     * (public) Function pointer for UTextMapOffsetToNative.
+     *
+     * @see UTextMapOffsetToNative
+     * @stable ICU 3.6
+     */
+    UTextMapOffsetToNative *mapOffsetToNative;
+
+    /**
+     * (public) Function pointer for UTextMapNativeIndexToUTF16.
+     *
+     * @see UTextMapNativeIndexToUTF16
+     * @stable ICU 3.6
+     */
+    UTextMapNativeIndexToUTF16 *mapNativeIndexToUTF16;
+
+    /**
+     * (public) Function pointer for UTextClose.
+      *
+      * @see UTextClose
+      * @stable ICU 3.6
+      */
+    UTextClose  *close;
+
+    /**
+      * (private)  Spare function pointer
+      * @internal
+      */
+
+    UTextClose  *spare1;
+    /**
+      * (private)  Spare function pointer
+      * @internal
+      */
+    UTextClose  *spare2;
+
+    /**
+      * (private)  Spare function pointer
+      * @internal
+      */
+    UTextClose  *spare3;
+
+};
+/**
+ * Function dispatch table for UText
+ * @see UTextFuncs
+ */
+typedef struct UTextFuncs UTextFuncs;
+
+ /**
+  *   UText struct.  Provides the interface between the generic UText access code
+  *                  and the UText provider code that works on specific kinds of
+  *                  text  (UTF-8, noncontiguous UTF-16, whatever.)
+  *
+  *                  Applications that are using predefined types of text providers
+  *                  to pass text data to ICU services will have no need to view the
+  *                  internals of the UText structs that they open.
+  *
+  * @stable ICU 3.6
+  */
+struct UText {
+    /**
+     *     (private)  Magic.  Used to help detect when UText functions are handed
+     *                        invalid or unitialized UText structs.
+     *                        utext_openXYZ() functions take an initialized,
+     *                        but not necessarily open, UText struct as an
+     *                        optional fill-in parameter.  This magic field
+     *                        is used to check for that initialization.
+     *                        Text provider close functions must NOT clear
+     *                        the magic field because that would prevent
+     *                        reuse of the UText struct.
+     * @internal
+     */
+    uint32_t       magic;
+
+
+    /**
+     *     (private)  Flags for managing the allocation and freeing of
+     *                memory associated with this UText.
+     * @internal
+     */
+    int32_t        flags;
+
+
+    /**
+      *  Text provider properties.  This set of flags is maintainted by the
+      *                             text provider implementation.
+      *  @stable ICU 3.4
+      */
+    int32_t         providerProperties;
+
+    /**
+     * (public) sizeOfStruct=sizeof(UText)
+     * Allows possible backward compatible extension.
+     *
+     * @stable ICU 3.4
+     */
+    int32_t         sizeOfStruct;
+    
+    /* ------ 16 byte alignment boundary -----------  */
+    
+
+    /**
+      *  (protected) Native index of the first character position following
+      *              the current chunk.
+      *  @stable ICU 3.6
+      */
+    int64_t         chunkNativeLimit;
+
+    /**
+     *   (protected)  Size in bytes of the extra space (pExtra).
+     *  @stable ICU 3.4
+     */
+    int32_t        extraSize;
+
+    /**
+      *    (protected) The highest chunk offset where native indexing and
+      *    chunk (UTF-16) indexing correspond.  For UTF-16 sources, value
+      *    will be equal to chunkLength.
+      *
+      *    @stable ICU 3.6
+      */
+    int32_t         nativeIndexingLimit;
+
+    /* ---- 16 byte alignment boundary------ */
+    
+    /**
+     *  (protected) Native index of the first character in the text chunk.
+     *  @stable ICU 3.6
+     */
+    int64_t         chunkNativeStart;
+
+    /**
+     *  (protected) Current iteration position within the text chunk (UTF-16 buffer).
+     *  This is the index to the character that will be returned by utext_next32().
+     *  @stable ICU 3.6
+     */
+    int32_t         chunkOffset;
+
+    /**
+     *  (protected) Length the text chunk (UTF-16 buffer), in UChars.
+     *  @stable ICU 3.6
+     */
+    int32_t         chunkLength;
+
+    /* ---- 16  byte alignment boundary-- */
+    
+
+    /**
+     *  (protected)  pointer to a chunk of text in UTF-16 format.
+     *  May refer either to original storage of the source of the text, or
+     *  if conversion was required, to a buffer owned by the UText.
+     *  @stable ICU 3.6
+     */
+    const UChar    *chunkContents;
+
+     /**
+      * (public)     Pointer to Dispatch table for accessing functions for this UText.
+      * @stable ICU 3.6
+      */
+    const UTextFuncs     *pFuncs;
+
+    /**
+     *  (protected)  Pointer to additional space requested by the
+     *               text provider during the utext_open operation.
+     * @stable ICU 3.4
+     */
+    void          *pExtra;
+
+    /**
+     * (protected) Pointer to string or text-containin object or similar.
+     * This is the source of the text that this UText is wrapping, in a format
+     *  that is known to the text provider functions.
+     * @stable ICU 3.4
+     */
+    const void   *context;
+
+    /* --- 16 byte alignment boundary--- */
+
+    /**
+     * (protected) Pointer fields available for use by the text provider.
+     * Not used by UText common code.
+     * @stable ICU 3.6
+     */
+    const void     *p; 
+    /**
+     * (protected) Pointer fields available for use by the text provider.
+     * Not used by UText common code.
+     * @stable ICU 3.6
+     */
+    const void     *q;
+     /**
+     * (protected) Pointer fields available for use by the text provider.
+     * Not used by UText common code.
+     * @stable ICU 3.6
+      */
+    const void     *r;
+
+    /**
+      *  Private field reserved for future use by the UText framework
+      *     itself.  This is not to be touched by the text providers.
+      * @internal ICU 3.4
+      */
+    void           *privP;
+
+
+    /* --- 16 byte alignment boundary--- */
+    
+
+    /**
+      * (protected) Integer field reserved for use by the text provider.
+      * Not used by the UText framework, or by the client (user) of the UText.
+      * @stable ICU 3.4
+      */
+    int64_t         a;
+
+    /**
+      * (protected) Integer field reserved for use by the text provider.
+      * Not used by the UText framework, or by the client (user) of the UText.
+      * @stable ICU 3.4
+      */
+    int32_t         b;
+
+    /**
+      * (protected) Integer field reserved for use by the text provider.
+      * Not used by the UText framework, or by the client (user) of the UText.
+      * @stable ICU 3.4
+      */
+    int32_t         c;
+
+    /*  ---- 16 byte alignment boundary---- */
+
+
+    /**
+      *  Private field reserved for future use by the UText framework
+      *     itself.  This is not to be touched by the text providers.
+      * @internal ICU 3.4
+      */
+    int64_t         privA;
+    /**
+      *  Private field reserved for future use by the UText framework
+      *     itself.  This is not to be touched by the text providers.
+      * @internal ICU 3.4
+      */
+    int32_t         privB;
+    /**
+      *  Private field reserved for future use by the UText framework
+      *     itself.  This is not to be touched by the text providers.
+      * @internal ICU 3.4
+      */
+    int32_t         privC;
+};
+
+
+/**
+ *  Common function for use by Text Provider implementations to allocate and/or initialize
+ *  a new UText struct.  To be called in the implementation of utext_open() functions.
+ *  If the supplied UText parameter is null, a new UText struct will be allocated on the heap.
+ *  If the supplied UText is already open, the provider's close function will be called
+ *  so that the struct can be reused by the open that is in progress.
+ *
+ * @param ut   pointer to a UText struct to be re-used, or null if a new UText
+ *             should be allocated.
+ * @param extraSpace The amount of additional space to be allocated as part
+ *             of this UText, for use by types of providers that require
+ *             additional storage.
+ * @param status Errors are returned here.
+ * @return pointer to the UText, allocated if necessary, with extra space set up if requested.
+ * @stable ICU 3.4
+ */
+U_STABLE UText * U_EXPORT2
+utext_setup(UText *ut, int32_t extraSpace, UErrorCode *status);
+
+/**
+  * @internal
+  *  Value used to help identify correctly initialized UText structs.
+  *  Note:  must be publicly visible so that UTEXT_INITIALIZER can access it.
+  */
+enum {
+    UTEXT_MAGIC = 0x345ad82c
+};
+
+/**
+ * initializer to be used with local (stack) instances of a UText
+ *  struct.  UText structs must be initialized before passing
+ *  them to one of the utext_open functions.
+ *
+ * @stable ICU 3.6
+ */
+#define UTEXT_INITIALIZER {                                        \
+                  UTEXT_MAGIC,          /* magic                */ \
+                  0,                    /* flags                */ \
+                  0,                    /* providerProps        */ \
+                  sizeof(UText),        /* sizeOfStruct         */ \
+                  0,                    /* chunkNativeLimit     */ \
+                  0,                    /* extraSize            */ \
+                  0,                    /* nativeIndexingLimit  */ \
+                  0,                    /* chunkNativeStart     */ \
+                  0,                    /* chunkOffset          */ \
+                  0,                    /* chunkLength          */ \
+                  NULL,                 /* chunkContents        */ \
+                  NULL,                 /* pFuncs               */ \
+                  NULL,                 /* pExtra               */ \
+                  NULL,                 /* context              */ \
+                  NULL, NULL, NULL,     /* p, q, r              */ \
+                  NULL,                 /* privP                */ \
+                  0, 0, 0,              /* a, b, c              */ \
+                  0, 0, 0               /* privA,B,C,           */ \
+                  }
+
+
+U_CDECL_END
+
+
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/utf.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/utf.h b/src/apps/couch_collate/platform/osx/icu/unicode/utf.h
new file mode 100644
index 0000000..1682283
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/utf.h
@@ -0,0 +1,227 @@
+/*
+*******************************************************************************
+*
+*   Copyright (C) 1999-2007, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+*
+*******************************************************************************
+*   file name:  utf.h
+*   encoding:   US-ASCII
+*   tab size:   8 (not used)
+*   indentation:4
+*
+*   created on: 1999sep09
+*   created by: Markus W. Scherer
+*/
+
+/**
+ * \file
+ * \brief C API: Code point macros
+ *
+ * This file defines macros for checking whether a code point is
+ * a surrogate or a non-character etc.
+ *
+ * The UChar and UChar32 data types for Unicode code units and code points
+ * are defined in umachines.h because they can be machine-dependent.
+ *
+ * utf.h is included by utypes.h and itself includes utf8.h and utf16.h after some
+ * common definitions. Those files define macros for efficiently getting code points
+ * in and out of UTF-8/16 strings.
+ * utf16.h macros have "U16_" prefixes.
+ * utf8.h defines similar macros with "U8_" prefixes for UTF-8 string handling.
+ *
+ * ICU processes 16-bit Unicode strings.
+ * Most of the time, such strings are well-formed UTF-16.
+ * Single, unpaired surrogates must be handled as well, and are treated in ICU
+ * like regular code points where possible.
+ * (Pairs of surrogate code points are indistinguishable from supplementary
+ * code points encoded as pairs of supplementary code units.)
+ *
+ * In fact, almost all Unicode code points in normal text (>99%)
+ * are on the BMP (<=U+ffff) and even <=U+d7ff.
+ * ICU functions handle supplementary code points (U+10000..U+10ffff)
+ * but are optimized for the much more frequently occurring BMP code points.
+ *
+ * utf.h defines UChar to be an unsigned 16-bit integer. If this matches wchar_t, then
+ * UChar is defined to be exactly wchar_t, otherwise uint16_t.
+ *
+ * UChar32 is defined to be a signed 32-bit integer (int32_t), large enough for a 21-bit
+ * Unicode code point (Unicode scalar value, 0..0x10ffff).
+ * Before ICU 2.4, the definition of UChar32 was similarly platform-dependent as
+ * the definition of UChar. For details see the documentation for UChar32 itself.
+ *
+ * utf.h also defines a small number of C macros for single Unicode code points.
+ * These are simple checks for surrogates and non-characters.
+ * For actual Unicode character properties see uchar.h.
+ *
+ * By default, string operations must be done with error checking in case
+ * a string is not well-formed UTF-16.
+ * The macros will detect if a surrogate code unit is unpaired
+ * (lead unit without trail unit or vice versa) and just return the unit itself
+ * as the code point.
+ * (It is an accidental property of Unicode and UTF-16 that all
+ * malformed sequences can be expressed unambiguously with a distinct subrange
+ * of Unicode code points.)
+ *
+ * The regular "safe" macros require that the initial, passed-in string index
+ * is within bounds. They only check the index when they read more than one
+ * code unit. This is usually done with code similar to the following loop:
+ * <pre>while(i<length) {
+ *   U16_NEXT(s, i, length, c);
+ *   // use c
+ * }</pre>
+ *
+ * When it is safe to assume that text is well-formed UTF-16
+ * (does not contain single, unpaired surrogates), then one can use
+ * U16_..._UNSAFE macros.
+ * These do not check for proper code unit sequences or truncated text and may
+ * yield wrong results or even cause a crash if they are used with "malformed"
+ * text.
+ * In practice, U16_..._UNSAFE macros will produce slightly less code but
+ * should not be faster because the processing is only different when a
+ * surrogate code unit is detected, which will be rare.
+ *
+ * Similarly for UTF-8, there are "safe" macros without a suffix,
+ * and U8_..._UNSAFE versions.
+ * The performance differences are much larger here because UTF-8 provides so
+ * many opportunities for malformed sequences.
+ * The unsafe UTF-8 macros are entirely implemented inside the macro definitions
+ * and are fast, while the safe UTF-8 macros call functions for all but the
+ * trivial (ASCII) cases.
+ * (ICU 3.6 optimizes U8_NEXT() and U8_APPEND() to handle most other common
+ * characters inline as well.)
+ *
+ * Unlike with UTF-16, malformed sequences cannot be expressed with distinct
+ * code point values (0..U+10ffff). They are indicated with negative values instead.
+ *
+ * For more information see the ICU User Guide Strings chapter
+ * (http://icu-project.org/userguide/strings.html).
+ *
+ * <em>Usage:</em>
+ * ICU coding guidelines for if() statements should be followed when using these macros.
+ * Compound statements (curly braces {}) must be used  for if-else-while... 
+ * bodies and all macro statements should be terminated with semicolon.
+ *
+ * @stable ICU 2.4
+ */
+
+#ifndef __UTF_H__
+#define __UTF_H__
+
+#include "unicode/utypes.h"
+/* include the utfXX.h after the following definitions */
+
+/* single-code point definitions -------------------------------------------- */
+
+/**
+ * This value is intended for sentinel values for APIs that
+ * (take or) return single code points (UChar32).
+ * It is outside of the Unicode code point range 0..0x10ffff.
+ * 
+ * For example, a "done" or "error" value in a new API
+ * could be indicated with U_SENTINEL.
+ *
+ * ICU APIs designed before ICU 2.4 usually define service-specific "done"
+ * values, mostly 0xffff.
+ * Those may need to be distinguished from
+ * actual U+ffff text contents by calling functions like
+ * CharacterIterator::hasNext() or UnicodeString::length().
+ *
+ * @return -1
+ * @see UChar32
+ * @stable ICU 2.4
+ */
+#define U_SENTINEL (-1)
+
+/**
+ * Is this code point a Unicode noncharacter?
+ * @param c 32-bit code point
+ * @return TRUE or FALSE
+ * @stable ICU 2.4
+ */
+#define U_IS_UNICODE_NONCHAR(c) \
+    ((c)>=0xfdd0 && \
+     ((uint32_t)(c)<=0xfdef || ((c)&0xfffe)==0xfffe) && \
+     (uint32_t)(c)<=0x10ffff)
+
+/**
+ * Is c a Unicode code point value (0..U+10ffff)
+ * that can be assigned a character?
+ *
+ * Code points that are not characters include:
+ * - single surrogate code points (U+d800..U+dfff, 2048 code points)
+ * - the last two code points on each plane (U+__fffe and U+__ffff, 34 code points)
+ * - U+fdd0..U+fdef (new with Unicode 3.1, 32 code points)
+ * - the highest Unicode code point value is U+10ffff
+ *
+ * This means that all code points below U+d800 are character code points,
+ * and that boundary is tested first for performance.
+ *
+ * @param c 32-bit code point
+ * @return TRUE or FALSE
+ * @stable ICU 2.4
+ */
+#define U_IS_UNICODE_CHAR(c) \
+    ((uint32_t)(c)<0xd800 || \
+        ((uint32_t)(c)>0xdfff && \
+         (uint32_t)(c)<=0x10ffff && \
+         !U_IS_UNICODE_NONCHAR(c)))
+
+/**
+ * Is this code point a BMP code point (U+0000..U+ffff)?
+ * @param c 32-bit code point
+ * @return TRUE or FALSE
+ * @stable ICU 2.8
+ */
+#define U_IS_BMP(c) ((uint32_t)(c)<=0xffff)
+
+/**
+ * Is this code point a supplementary code point (U+10000..U+10ffff)?
+ * @param c 32-bit code point
+ * @return TRUE or FALSE
+ * @stable ICU 2.8
+ */
+#define U_IS_SUPPLEMENTARY(c) ((uint32_t)((c)-0x10000)<=0xfffff)
+ 
+/**
+ * Is this code point a lead surrogate (U+d800..U+dbff)?
+ * @param c 32-bit code point
+ * @return TRUE or FALSE
+ * @stable ICU 2.4
+ */
+#define U_IS_LEAD(c) (((c)&0xfffffc00)==0xd800)
+
+/**
+ * Is this code point a trail surrogate (U+dc00..U+dfff)?
+ * @param c 32-bit code point
+ * @return TRUE or FALSE
+ * @stable ICU 2.4
+ */
+#define U_IS_TRAIL(c) (((c)&0xfffffc00)==0xdc00)
+
+/**
+ * Is this code point a surrogate (U+d800..U+dfff)?
+ * @param c 32-bit code point
+ * @return TRUE or FALSE
+ * @stable ICU 2.4
+ */
+#define U_IS_SURROGATE(c) (((c)&0xfffff800)==0xd800)
+
+/**
+ * Assuming c is a surrogate code point (U_IS_SURROGATE(c)),
+ * is it a lead surrogate?
+ * @param c 32-bit code point
+ * @return TRUE or FALSE
+ * @stable ICU 2.4
+ */
+#define U_IS_SURROGATE_LEAD(c) (((c)&0x400)==0)
+
+/* include the utfXX.h ------------------------------------------------------ */
+
+#include "unicode/utf8.h"
+#include "unicode/utf16.h"
+
+/* utf_old.h contains deprecated, pre-ICU 2.4 definitions */
+#include "unicode/utf_old.h"
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/utf16.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/utf16.h b/src/apps/couch_collate/platform/osx/icu/unicode/utf16.h
new file mode 100644
index 0000000..719bc04
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/utf16.h
@@ -0,0 +1,605 @@
+/*
+*******************************************************************************
+*
+*   Copyright (C) 1999-2007, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+*
+*******************************************************************************
+*   file name:  utf16.h
+*   encoding:   US-ASCII
+*   tab size:   8 (not used)
+*   indentation:4
+*
+*   created on: 1999sep09
+*   created by: Markus W. Scherer
+*/
+
+/**
+ * \file
+ * \brief C API: 16-bit Unicode handling macros
+ * 
+ * This file defines macros to deal with 16-bit Unicode (UTF-16) code units and strings.
+ * utf16.h is included by utf.h after unicode/umachine.h
+ * and some common definitions.
+ *
+ * For more information see utf.h and the ICU User Guide Strings chapter
+ * (http://icu-project.org/userguide/strings.html).
+ *
+ * <em>Usage:</em>
+ * ICU coding guidelines for if() statements should be followed when using these macros.
+ * Compound statements (curly braces {}) must be used  for if-else-while... 
+ * bodies and all macro statements should be terminated with semicolon.
+ */
+
+#ifndef __UTF16_H__
+#define __UTF16_H__
+
+/* utf.h must be included first. */
+#ifndef __UTF_H__
+#   include "unicode/utf.h"
+#endif
+
+/* single-code point definitions -------------------------------------------- */
+
+/**
+ * Does this code unit alone encode a code point (BMP, not a surrogate)?
+ * @param c 16-bit code unit
+ * @return TRUE or FALSE
+ * @stable ICU 2.4
+ */
+#define U16_IS_SINGLE(c) !U_IS_SURROGATE(c)
+
+/**
+ * Is this code unit a lead surrogate (U+d800..U+dbff)?
+ * @param c 16-bit code unit
+ * @return TRUE or FALSE
+ * @stable ICU 2.4
+ */
+#define U16_IS_LEAD(c) (((c)&0xfffffc00)==0xd800)
+
+/**
+ * Is this code unit a trail surrogate (U+dc00..U+dfff)?
+ * @param c 16-bit code unit
+ * @return TRUE or FALSE
+ * @stable ICU 2.4
+ */
+#define U16_IS_TRAIL(c) (((c)&0xfffffc00)==0xdc00)
+
+/**
+ * Is this code unit a surrogate (U+d800..U+dfff)?
+ * @param c 16-bit code unit
+ * @return TRUE or FALSE
+ * @stable ICU 2.4
+ */
+#define U16_IS_SURROGATE(c) U_IS_SURROGATE(c)
+
+/**
+ * Assuming c is a surrogate code point (U16_IS_SURROGATE(c)),
+ * is it a lead surrogate?
+ * @param c 16-bit code unit
+ * @return TRUE or FALSE
+ * @stable ICU 2.4
+ */
+#define U16_IS_SURROGATE_LEAD(c) (((c)&0x400)==0)
+
+/**
+ * Helper constant for U16_GET_SUPPLEMENTARY.
+ * @internal
+ */
+#define U16_SURROGATE_OFFSET ((0xd800<<10UL)+0xdc00-0x10000)
+
+/**
+ * Get a supplementary code point value (U+10000..U+10ffff)
+ * from its lead and trail surrogates.
+ * The result is undefined if the input values are not
+ * lead and trail surrogates.
+ *
+ * @param lead lead surrogate (U+d800..U+dbff)
+ * @param trail trail surrogate (U+dc00..U+dfff)
+ * @return supplementary code point (U+10000..U+10ffff)
+ * @stable ICU 2.4
+ */
+#define U16_GET_SUPPLEMENTARY(lead, trail) \
+    (((UChar32)(lead)<<10UL)+(UChar32)(trail)-U16_SURROGATE_OFFSET)
+
+
+/**
+ * Get the lead surrogate (0xd800..0xdbff) for a
+ * supplementary code point (0x10000..0x10ffff).
+ * @param supplementary 32-bit code point (U+10000..U+10ffff)
+ * @return lead surrogate (U+d800..U+dbff) for supplementary
+ * @stable ICU 2.4
+ */
+#define U16_LEAD(supplementary) (UChar)(((supplementary)>>10)+0xd7c0)
+
+/**
+ * Get the trail surrogate (0xdc00..0xdfff) for a
+ * supplementary code point (0x10000..0x10ffff).
+ * @param supplementary 32-bit code point (U+10000..U+10ffff)
+ * @return trail surrogate (U+dc00..U+dfff) for supplementary
+ * @stable ICU 2.4
+ */
+#define U16_TRAIL(supplementary) (UChar)(((supplementary)&0x3ff)|0xdc00)
+
+/**
+ * How many 16-bit code units are used to encode this Unicode code point? (1 or 2)
+ * The result is not defined if c is not a Unicode code point (U+0000..U+10ffff).
+ * @param c 32-bit code point
+ * @return 1 or 2
+ * @stable ICU 2.4
+ */
+#define U16_LENGTH(c) ((uint32_t)(c)<=0xffff ? 1 : 2)
+
+/**
+ * The maximum number of 16-bit code units per Unicode code point (U+0000..U+10ffff).
+ * @return 2
+ * @stable ICU 2.4
+ */
+#define U16_MAX_LENGTH 2
+
+/**
+ * Get a code point from a string at a random-access offset,
+ * without changing the offset.
+ * "Unsafe" macro, assumes well-formed UTF-16.
+ *
+ * The offset may point to either the lead or trail surrogate unit
+ * for a supplementary code point, in which case the macro will read
+ * the adjacent matching surrogate as well.
+ * The result is undefined if the offset points to a single, unpaired surrogate.
+ * Iteration through a string is more efficient with U16_NEXT_UNSAFE or U16_NEXT.
+ *
+ * @param s const UChar * string
+ * @param i string offset
+ * @param c output UChar32 variable
+ * @see U16_GET
+ * @stable ICU 2.4
+ */
+#define U16_GET_UNSAFE(s, i, c) { \
+    (c)=(s)[i]; \
+    if(U16_IS_SURROGATE(c)) { \
+        if(U16_IS_SURROGATE_LEAD(c)) { \
+            (c)=U16_GET_SUPPLEMENTARY((c), (s)[(i)+1]); \
+        } else { \
+            (c)=U16_GET_SUPPLEMENTARY((s)[(i)-1], (c)); \
+        } \
+    } \
+}
+
+/**
+ * Get a code point from a string at a random-access offset,
+ * without changing the offset.
+ * "Safe" macro, handles unpaired surrogates and checks for string boundaries.
+ *
+ * The offset may point to either the lead or trail surrogate unit
+ * for a supplementary code point, in which case the macro will read
+ * the adjacent matching surrogate as well.
+ * If the offset points to a single, unpaired surrogate, then that itself
+ * will be returned as the code point.
+ * Iteration through a string is more efficient with U16_NEXT_UNSAFE or U16_NEXT.
+ *
+ * @param s const UChar * string
+ * @param start starting string offset (usually 0)
+ * @param i string offset, must be start<=i<length
+ * @param length string length
+ * @param c output UChar32 variable
+ * @see U16_GET_UNSAFE
+ * @stable ICU 2.4
+ */
+#define U16_GET(s, start, i, length, c) { \
+    (c)=(s)[i]; \
+    if(U16_IS_SURROGATE(c)) { \
+        uint16_t __c2; \
+        if(U16_IS_SURROGATE_LEAD(c)) { \
+            if((i)+1<(length) && U16_IS_TRAIL(__c2=(s)[(i)+1])) { \
+                (c)=U16_GET_SUPPLEMENTARY((c), __c2); \
+            } \
+        } else { \
+            if((i)-1>=(start) && U16_IS_LEAD(__c2=(s)[(i)-1])) { \
+                (c)=U16_GET_SUPPLEMENTARY(__c2, (c)); \
+            } \
+        } \
+    } \
+}
+
+/* definitions with forward iteration --------------------------------------- */
+
+/**
+ * Get a code point from a string at a code point boundary offset,
+ * and advance the offset to the next code point boundary.
+ * (Post-incrementing forward iteration.)
+ * "Unsafe" macro, assumes well-formed UTF-16.
+ *
+ * The offset may point to the lead surrogate unit
+ * for a supplementary code point, in which case the macro will read
+ * the following trail surrogate as well.
+ * If the offset points to a trail surrogate, then that itself
+ * will be returned as the code point.
+ * The result is undefined if the offset points to a single, unpaired lead surrogate.
+ *
+ * @param s const UChar * string
+ * @param i string offset
+ * @param c output UChar32 variable
+ * @see U16_NEXT
+ * @stable ICU 2.4
+ */
+#define U16_NEXT_UNSAFE(s, i, c) { \
+    (c)=(s)[(i)++]; \
+    if(U16_IS_LEAD(c)) { \
+        (c)=U16_GET_SUPPLEMENTARY((c), (s)[(i)++]); \
+    } \
+}
+
+/**
+ * Get a code point from a string at a code point boundary offset,
+ * and advance the offset to the next code point boundary.
+ * (Post-incrementing forward iteration.)
+ * "Safe" macro, handles unpaired surrogates and checks for string boundaries.
+ *
+ * The offset may point to the lead surrogate unit
+ * for a supplementary code point, in which case the macro will read
+ * the following trail surrogate as well.
+ * If the offset points to a trail surrogate or
+ * to a single, unpaired lead surrogate, then that itself
+ * will be returned as the code point.
+ *
+ * @param s const UChar * string
+ * @param i string offset, must be i<length
+ * @param length string length
+ * @param c output UChar32 variable
+ * @see U16_NEXT_UNSAFE
+ * @stable ICU 2.4
+ */
+#define U16_NEXT(s, i, length, c) { \
+    (c)=(s)[(i)++]; \
+    if(U16_IS_LEAD(c)) { \
+        uint16_t __c2; \
+        if((i)<(length) && U16_IS_TRAIL(__c2=(s)[(i)])) { \
+            ++(i); \
+            (c)=U16_GET_SUPPLEMENTARY((c), __c2); \
+        } \
+    } \
+}
+
+/**
+ * Append a code point to a string, overwriting 1 or 2 code units.
+ * The offset points to the current end of the string contents
+ * and is advanced (post-increment).
+ * "Unsafe" macro, assumes a valid code point and sufficient space in the string.
+ * Otherwise, the result is undefined.
+ *
+ * @param s const UChar * string buffer
+ * @param i string offset
+ * @param c code point to append
+ * @see U16_APPEND
+ * @stable ICU 2.4
+ */
+#define U16_APPEND_UNSAFE(s, i, c) { \
+    if((uint32_t)(c)<=0xffff) { \
+        (s)[(i)++]=(uint16_t)(c); \
+    } else { \
+        (s)[(i)++]=(uint16_t)(((c)>>10)+0xd7c0); \
+        (s)[(i)++]=(uint16_t)(((c)&0x3ff)|0xdc00); \
+    } \
+}
+
+/**
+ * Append a code point to a string, overwriting 1 or 2 code units.
+ * The offset points to the current end of the string contents
+ * and is advanced (post-increment).
+ * "Safe" macro, checks for a valid code point.
+ * If a surrogate pair is written, checks for sufficient space in the string.
+ * If the code point is not valid or a trail surrogate does not fit,
+ * then isError is set to TRUE.
+ *
+ * @param s const UChar * string buffer
+ * @param i string offset, must be i<capacity
+ * @param capacity size of the string buffer
+ * @param c code point to append
+ * @param isError output UBool set to TRUE if an error occurs, otherwise not modified
+ * @see U16_APPEND_UNSAFE
+ * @stable ICU 2.4
+ */
+#define U16_APPEND(s, i, capacity, c, isError) { \
+    if((uint32_t)(c)<=0xffff) { \
+        (s)[(i)++]=(uint16_t)(c); \
+    } else if((uint32_t)(c)<=0x10ffff && (i)+1<(capacity)) { \
+        (s)[(i)++]=(uint16_t)(((c)>>10)+0xd7c0); \
+        (s)[(i)++]=(uint16_t)(((c)&0x3ff)|0xdc00); \
+    } else /* c>0x10ffff or not enough space */ { \
+        (isError)=TRUE; \
+    } \
+}
+
+/**
+ * Advance the string offset from one code point boundary to the next.
+ * (Post-incrementing iteration.)
+ * "Unsafe" macro, assumes well-formed UTF-16.
+ *
+ * @param s const UChar * string
+ * @param i string offset
+ * @see U16_FWD_1
+ * @stable ICU 2.4
+ */
+#define U16_FWD_1_UNSAFE(s, i) { \
+    if(U16_IS_LEAD((s)[(i)++])) { \
+        ++(i); \
+    } \
+}
+
+/**
+ * Advance the string offset from one code point boundary to the next.
+ * (Post-incrementing iteration.)
+ * "Safe" macro, handles unpaired surrogates and checks for string boundaries.
+ *
+ * @param s const UChar * string
+ * @param i string offset, must be i<length
+ * @param length string length
+ * @see U16_FWD_1_UNSAFE
+ * @stable ICU 2.4
+ */
+#define U16_FWD_1(s, i, length) { \
+    if(U16_IS_LEAD((s)[(i)++]) && (i)<(length) && U16_IS_TRAIL((s)[i])) { \
+        ++(i); \
+    } \
+}
+
+/**
+ * Advance the string offset from one code point boundary to the n-th next one,
+ * i.e., move forward by n code points.
+ * (Post-incrementing iteration.)
+ * "Unsafe" macro, assumes well-formed UTF-16.
+ *
+ * @param s const UChar * string
+ * @param i string offset
+ * @param n number of code points to skip
+ * @see U16_FWD_N
+ * @stable ICU 2.4
+ */
+#define U16_FWD_N_UNSAFE(s, i, n) { \
+    int32_t __N=(n); \
+    while(__N>0) { \
+        U16_FWD_1_UNSAFE(s, i); \
+        --__N; \
+    } \
+}
+
+/**
+ * Advance the string offset from one code point boundary to the n-th next one,
+ * i.e., move forward by n code points.
+ * (Post-incrementing iteration.)
+ * "Safe" macro, handles unpaired surrogates and checks for string boundaries.
+ *
+ * @param s const UChar * string
+ * @param i string offset, must be i<length
+ * @param length string length
+ * @param n number of code points to skip
+ * @see U16_FWD_N_UNSAFE
+ * @stable ICU 2.4
+ */
+#define U16_FWD_N(s, i, length, n) { \
+    int32_t __N=(n); \
+    while(__N>0 && (i)<(length)) { \
+        U16_FWD_1(s, i, length); \
+        --__N; \
+    } \
+}
+
+/**
+ * Adjust a random-access offset to a code point boundary
+ * at the start of a code point.
+ * If the offset points to the trail surrogate of a surrogate pair,
+ * then the offset is decremented.
+ * Otherwise, it is not modified.
+ * "Unsafe" macro, assumes well-formed UTF-16.
+ *
+ * @param s const UChar * string
+ * @param i string offset
+ * @see U16_SET_CP_START
+ * @stable ICU 2.4
+ */
+#define U16_SET_CP_START_UNSAFE(s, i) { \
+    if(U16_IS_TRAIL((s)[i])) { \
+        --(i); \
+    } \
+}
+
+/**
+ * Adjust a random-access offset to a code point boundary
+ * at the start of a code point.
+ * If the offset points to the trail surrogate of a surrogate pair,
+ * then the offset is decremented.
+ * Otherwise, it is not modified.
+ * "Safe" macro, handles unpaired surrogates and checks for string boundaries.
+ *
+ * @param s const UChar * string
+ * @param start starting string offset (usually 0)
+ * @param i string offset, must be start<=i
+ * @see U16_SET_CP_START_UNSAFE
+ * @stable ICU 2.4
+ */
+#define U16_SET_CP_START(s, start, i) { \
+    if(U16_IS_TRAIL((s)[i]) && (i)>(start) && U16_IS_LEAD((s)[(i)-1])) { \
+        --(i); \
+    } \
+}
+
+/* definitions with backward iteration -------------------------------------- */
+
+/**
+ * Move the string offset from one code point boundary to the previous one
+ * and get the code point between them.
+ * (Pre-decrementing backward iteration.)
+ * "Unsafe" macro, assumes well-formed UTF-16.
+ *
+ * The input offset may be the same as the string length.
+ * If the offset is behind a trail surrogate unit
+ * for a supplementary code point, then the macro will read
+ * the preceding lead surrogate as well.
+ * If the offset is behind a lead surrogate, then that itself
+ * will be returned as the code point.
+ * The result is undefined if the offset is behind a single, unpaired trail surrogate.
+ *
+ * @param s const UChar * string
+ * @param i string offset
+ * @param c output UChar32 variable
+ * @see U16_PREV
+ * @stable ICU 2.4
+ */
+#define U16_PREV_UNSAFE(s, i, c) { \
+    (c)=(s)[--(i)]; \
+    if(U16_IS_TRAIL(c)) { \
+        (c)=U16_GET_SUPPLEMENTARY((s)[--(i)], (c)); \
+    } \
+}
+
+/**
+ * Move the string offset from one code point boundary to the previous one
+ * and get the code point between them.
+ * (Pre-decrementing backward iteration.)
+ * "Safe" macro, handles unpaired surrogates and checks for string boundaries.
+ *
+ * The input offset may be the same as the string length.
+ * If the offset is behind a trail surrogate unit
+ * for a supplementary code point, then the macro will read
+ * the preceding lead surrogate as well.
+ * If the offset is behind a lead surrogate or behind a single, unpaired
+ * trail surrogate, then that itself
+ * will be returned as the code point.
+ *
+ * @param s const UChar * string
+ * @param start starting string offset (usually 0)
+ * @param i string offset, must be start<i
+ * @param c output UChar32 variable
+ * @see U16_PREV_UNSAFE
+ * @stable ICU 2.4
+ */
+#define U16_PREV(s, start, i, c) { \
+    (c)=(s)[--(i)]; \
+    if(U16_IS_TRAIL(c)) { \
+        uint16_t __c2; \
+        if((i)>(start) && U16_IS_LEAD(__c2=(s)[(i)-1])) { \
+            --(i); \
+            (c)=U16_GET_SUPPLEMENTARY(__c2, (c)); \
+        } \
+    } \
+}
+
+/**
+ * Move the string offset from one code point boundary to the previous one.
+ * (Pre-decrementing backward iteration.)
+ * The input offset may be the same as the string length.
+ * "Unsafe" macro, assumes well-formed UTF-16.
+ *
+ * @param s const UChar * string
+ * @param i string offset
+ * @see U16_BACK_1
+ * @stable ICU 2.4
+ */
+#define U16_BACK_1_UNSAFE(s, i) { \
+    if(U16_IS_TRAIL((s)[--(i)])) { \
+        --(i); \
+    } \
+}
+
+/**
+ * Move the string offset from one code point boundary to the previous one.
+ * (Pre-decrementing backward iteration.)
+ * The input offset may be the same as the string length.
+ * "Safe" macro, handles unpaired surrogates and checks for string boundaries.
+ *
+ * @param s const UChar * string
+ * @param start starting string offset (usually 0)
+ * @param i string offset, must be start<i
+ * @see U16_BACK_1_UNSAFE
+ * @stable ICU 2.4
+ */
+#define U16_BACK_1(s, start, i) { \
+    if(U16_IS_TRAIL((s)[--(i)]) && (i)>(start) && U16_IS_LEAD((s)[(i)-1])) { \
+        --(i); \
+    } \
+}
+
+/**
+ * Move the string offset from one code point boundary to the n-th one before it,
+ * i.e., move backward by n code points.
+ * (Pre-decrementing backward iteration.)
+ * The input offset may be the same as the string length.
+ * "Unsafe" macro, assumes well-formed UTF-16.
+ *
+ * @param s const UChar * string
+ * @param i string offset
+ * @param n number of code points to skip
+ * @see U16_BACK_N
+ * @stable ICU 2.4
+ */
+#define U16_BACK_N_UNSAFE(s, i, n) { \
+    int32_t __N=(n); \
+    while(__N>0) { \
+        U16_BACK_1_UNSAFE(s, i); \
+        --__N; \
+    } \
+}
+
+/**
+ * Move the string offset from one code point boundary to the n-th one before it,
+ * i.e., move backward by n code points.
+ * (Pre-decrementing backward iteration.)
+ * The input offset may be the same as the string length.
+ * "Safe" macro, handles unpaired surrogates and checks for string boundaries.
+ *
+ * @param s const UChar * string
+ * @param start start of string
+ * @param i string offset, must be start<i
+ * @param n number of code points to skip
+ * @see U16_BACK_N_UNSAFE
+ * @stable ICU 2.4
+ */
+#define U16_BACK_N(s, start, i, n) { \
+    int32_t __N=(n); \
+    while(__N>0 && (i)>(start)) { \
+        U16_BACK_1(s, start, i); \
+        --__N; \
+    } \
+}
+
+/**
+ * Adjust a random-access offset to a code point boundary after a code point.
+ * If the offset is behind the lead surrogate of a surrogate pair,
+ * then the offset is incremented.
+ * Otherwise, it is not modified.
+ * The input offset may be the same as the string length.
+ * "Unsafe" macro, assumes well-formed UTF-16.
+ *
+ * @param s const UChar * string
+ * @param i string offset
+ * @see U16_SET_CP_LIMIT
+ * @stable ICU 2.4
+ */
+#define U16_SET_CP_LIMIT_UNSAFE(s, i) { \
+    if(U16_IS_LEAD((s)[(i)-1])) { \
+        ++(i); \
+    } \
+}
+
+/**
+ * Adjust a random-access offset to a code point boundary after a code point.
+ * If the offset is behind the lead surrogate of a surrogate pair,
+ * then the offset is incremented.
+ * Otherwise, it is not modified.
+ * The input offset may be the same as the string length.
+ * "Safe" macro, handles unpaired surrogates and checks for string boundaries.
+ *
+ * @param s const UChar * string
+ * @param start starting string offset (usually 0)
+ * @param i string offset, start<=i<=length
+ * @param length string length
+ * @see U16_SET_CP_LIMIT_UNSAFE
+ * @stable ICU 2.4
+ */
+#define U16_SET_CP_LIMIT(s, start, i, length) { \
+    if((start)<(i) && (i)<(length) && U16_IS_LEAD((s)[(i)-1]) && U16_IS_TRAIL((s)[i])) { \
+        ++(i); \
+    } \
+}
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/utf32.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/utf32.h b/src/apps/couch_collate/platform/osx/icu/unicode/utf32.h
new file mode 100644
index 0000000..bf63e69
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/utf32.h
@@ -0,0 +1,23 @@
+/*
+*******************************************************************************
+*
+*   Copyright (C) 1999-2001, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+*
+*******************************************************************************
+*   file name:  utf32.h
+*   encoding:   US-ASCII
+*   tab size:   8 (not used)
+*   indentation:4
+*
+*   created on: 1999sep20
+*   created by: Markus W. Scherer
+*/
+/**
+ * \file
+ * \brief C API: UTF-32 macros
+ *
+ * This file is obsolete and its contents moved to utf_old.h.
+ * See utf_old.h and Jitterbug 2150 and its discussion on the ICU mailing list
+ * in September 2002.
+ */


[34/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/permissions/views.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/permissions/views.js b/apps/fauxton/app/addons/permissions/views.js
deleted file mode 100644
index eb5a378..0000000
--- a/apps/fauxton/app/addons/permissions/views.js
+++ /dev/null
@@ -1,200 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-       "app",
-       "api",
-       "addons/permissions/resources"
-],
-function (app, FauxtonAPI, Permissions ) {
-  var events = {};
-  Permissions.events = _.extend(events, Backbone.Events);
-
-  Permissions.Permissions = FauxtonAPI.View.extend({
-    template: "addons/permissions/templates/permissions",
-
-    initialize: function (options) {
-      this.database = options.database;
-      this.listenTo(Permissions.events, 'itemRemoved', this.itemRemoved);
-    },
-
-    itemRemoved: function (event) {
-      this.model.set({
-        admins: this.adminsView.items(),
-        members: this.membersView.items()
-      });
-
-      this.model.save().then(function () {
-        FauxtonAPI.addNotification({
-          msg: 'Database permissions has been updated.'
-        });
-        }, function (xhr) {
-        FauxtonAPI.addNotification({
-          msg: 'Could not update permissions - reason: ' + xhr.responseText,
-          type: 'error'
-        });
-      });
-    },
-
-    beforeRender: function () {
-      this.adminsView = this.insertView('#sections', new Permissions.PermissionSection({
-        model: this.model,
-        section: 'admins',
-        help: 'Database admins can update design documents and edit the admin and member lists.'
-      }));
-
-      this.membersView = this.insertView('#sections', new Permissions.PermissionSection({
-        model: this.model,
-        section: 'members',
-        help: 'Database members can access the database. If no members are defined, the database is public.'
-      }));
-    },
-
-    serialize: function () {
-      return {
-        databaseName: this.database.id,
-      };
-    }
-  });
-
-  Permissions.PermissionSection = FauxtonAPI.View.extend({
-    template: "addons/permissions/templates/section",
-    initialize: function (options) {
-      this.section = options.section;
-      this.help = options.help;
-    },
-
-    events: {
-      "submit .permission-item-form": "addItem",
-      'click button.close': "removeItem"
-    },
-
-    beforeRender: function () {
-      var section = this.model.get(this.section);
-      
-      this.nameViews = [];
-      this.roleViews = [];
-
-      _.each(section.names, function (name) {
-        var nameView = this.insertView('#'+this.section+'-items-names', new Permissions.PermissionItem({
-          item: name,
-        }));
-        this.nameViews.push(nameView);
-      }, this);
-
-      _.each(section.roles, function (role) {
-        var roleView = this.insertView('#'+this.section+'-items-roles', new Permissions.PermissionItem({
-          item: role,
-        }));
-        this.roleViews.push(roleView);
-      }, this);
-    },
-
-    getItemFromView: function (viewList) {
-      return _.map(viewList, function (view) {
-        return view.item;
-      });
-    },
-
-    discardRemovedViews: function () {
-      this.nameViews = _.filter(this.nameViews, function (view) {
-        return !view.removed; 
-      });
-
-      this.roleViews = _.filter(this.roleViews, function (view) {
-        return !view.removed; 
-      });
-    },
-
-    items: function () {
-      this.discardRemovedViews();
-
-      return  {
-        names: this.getItemFromView(this.nameViews),
-        roles: this.getItemFromView(this.roleViews)
-      };
-    },
-
-    addItem: function (event) {
-      event.preventDefault();
-      var $item = this.$(event.currentTarget).find('.item'),
-          value = $item.val(),
-          section = $item.data('section'),
-          type = $item.data('type'),
-          that = this;
-
-      var resp = this.model.addItem(value, type, section);
-
-      if (resp && resp.error) {
-        return FauxtonAPI.addNotification({
-          msg: resp.msg,
-          type: 'error'
-        });
-      }
-
-      this.model.save().then(function () {
-        that.render();
-        FauxtonAPI.addNotification({
-          msg: 'Database permissions has been updated.'
-        });
-      }, function (xhr) {
-        FauxtonAPI.addNotification({
-          msg: 'Could not update permissions - reason: ' + xhr.responseText,
-          type: 'error'
-        });
-      });
-    },
-
-    serialize: function () {
-      return {
-        section: this.section,
-        help: this.help
-      };
-    }
-
-  });
-
-  Permissions.PermissionItem = FauxtonAPI.View.extend({
-    tagName: "li",
-    template: "addons/permissions/templates/item",
-    initialize: function (options) {
-      this.item = options.item;
-      this.viewsList = options.viewsList;
-    },
-
-    events: {
-      'click .close': "removeItem"
-    },
-
-    removeItem: function (event) {
-      var that = this;
-      event.preventDefault();
-      
-      this.removed = true;
-      Permissions.events.trigger('itemRemoved');
-
-      this.$el.hide('fast', function () {
-        that.remove();
-      });
-    },
-
-
-    serialize: function () {
-      return {
-        item: this.item
-      };
-    }
-
-  });
-
-  return Permissions;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/plugins/base.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/plugins/base.js b/apps/fauxton/app/addons/plugins/base.js
deleted file mode 100644
index 0798fbd..0000000
--- a/apps/fauxton/app/addons/plugins/base.js
+++ /dev/null
@@ -1,24 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-  "app",
-  "api",
-  "addons/plugins/routes"
-],
-
-function(app, FauxtonAPI, plugins) {
-  plugins.initialize = function() {
-    //FauxtonAPI.addHeaderLink({title: "Plugins", href: "#_plugins", icon: "fonticon-plugins", className: 'plugins'});
-  };
-  return plugins;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/plugins/resources.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/plugins/resources.js b/apps/fauxton/app/addons/plugins/resources.js
deleted file mode 100644
index d00fada..0000000
--- a/apps/fauxton/app/addons/plugins/resources.js
+++ /dev/null
@@ -1,26 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-  "app",
-  "api"
-],
-
-function (app, FauxtonAPI) {
-  var plugins = FauxtonAPI.addon();
-
-  plugins.Hello = FauxtonAPI.View.extend({
-    template: "addons/plugins/templates/plugins"
-  });
-
-  return plugins;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/plugins/routes.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/plugins/routes.js b/apps/fauxton/app/addons/plugins/routes.js
deleted file mode 100644
index 24d47f0..0000000
--- a/apps/fauxton/app/addons/plugins/routes.js
+++ /dev/null
@@ -1,47 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-  "app",
-  "api",
-  "addons/plugins/resources"
-],
-function(app, FauxtonAPI, plugins) {
-      var  PluginsRouteObject = FauxtonAPI.RouteObject.extend({
-        layout: "one_pane",
-
-        crumbs: [
-          {"name": "Plugins","link": "_plugins"}
-        ],
-
-        routes: {
-           "_plugins": "pluginsRoute"
-        },
-
-        selectedHeader: "Plugins",
-
-        roles: ["_admin"],
-
-        apiUrl:'plugins',
-
-        initialize: function () {
-            //put common views used on all your routes here (eg:  sidebars )
-        },
-
-        pluginsRoute: function () {
-          this.setView("#dashboard-content", new plugins.Hello({}));
-        }
-      });
-
-      plugins.RouteObjects = [PluginsRouteObject];
-  return plugins;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/plugins/templates/plugins.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/plugins/templates/plugins.html b/apps/fauxton/app/addons/plugins/templates/plugins.html
deleted file mode 100644
index 3002247..0000000
--- a/apps/fauxton/app/addons/plugins/templates/plugins.html
+++ /dev/null
@@ -1,102 +0,0 @@
-<!--
-
-Licensed under the Apache License, Version 2.0 (the "License"); you may not use
-this file except in compliance with the License. You may obtain a copy of the
-License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software distributed
-under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
-CONDITIONS OF ANY KIND, either express or implied. See the License for the
-specific language governing permissions and limitations under the License.
-
--->
-    <div id="content">
-      <div class="row">
-        <h2>GeoCouch</h2>
-        <p>Version: <strong>couchdb1.2.x_v0.3.0-11-g66e6219</strong></p>
-        <p>Author: Volker Mische</p>
-        <p>
-          Available Erlang Versions:
-          <ul>
-            <li>CouchDB 1.4.0-XXX R15B01</li>
-          </ul>
-        </p>
-        <p>
-          <button href="#" class="install-plugin" data-url="http://people.apache.org/~jan" data-checksums='{"1.4.0": {"R15B03":"D5QPhrJTAifM42DXqAj4RxzfEtI="}}' data-name="geocouch" data-version="couchdb1.2.x_v0.3.0-16-g66e6219">Install GeoCouch Now</button>
-        </p>
-      </div>
-      <div class="row">
-        <h2>CouchPerUser</h2>
-        <p>Version: <strong>1.0.0</strong></p>
-        <p>Author: Bob Ippolito</p>
-        <p>
-          Available Erlang Versions:
-          <ul>
-            <li>CouchDB 1.4.0-XXX R15B01</li>
-          </ul>
-        </p>
-        <p>
-          <button href="#" class="install-plugin" data-url="http://people.apache.org/~jan" data-checksums='{"1.4.0": {"R15B03":"Aj3mjC6M75NA62q5/xkP0tl8Hws="}}' data-name="couchperuser" data-version="1.0.0">Install CouchPerUser Now</button>
-        </p>
-      </div>
-    </div>
-  </div></body>
-  <script>
-    $('.install-plugin').each(function() {
-      var button = $(this);
-      var name = button.data('name');
-      var version = button.data('version');
-      $.get("/_config/plugins/" + name + "/", function(body, textStatus) {
-        body = JSON.parse(body);
-        if(body == version) {
-          button.html('Already Installed. Click to Uninstall');
-          button.data('delete', true);
-        } else {
-          button.html('Other Version Installed: ' + body);
-          button.attr('disabled', true);
-        }
-      });
-    });
-
-    $('.install-plugin').click(function(event) {
-      var button = $(this);
-      var delete_plugin = button.data('delete') || false;
-      var plugin_spec = JSON.stringify({
-        name: button.data('name'),
-        url: button.data('url'),
-        version: button.data('version'),
-        checksums: button.data('checksums'),
-        "delete": delete_plugin
-      });
-      var url = '/_plugins'
-      $.ajax({
-        url: url,
-        type: 'POST',
-        data: plugin_spec,
-        contentType: 'application/json', // what we send to the server
-        dataType: 'json', // expected from the server
-        processData: false, // keep our precious JSON
-        success: function(data, textStatus, jqXhr) {
-          if(textStatus == "success") {
-            var action = delete_plugin ? 'Uninstalled' : 'Installed';
-            button.html('Sucessfully ' + action);
-            button.attr('disabled', true);
-          } else {
-            button.html(textStatus);
-          }
-        },
-        beforeSend: function(xhr) {
-          xhr.setRequestHeader('Accept', 'application/json');
-        },
-      });
-    });
-  </script>
-  <style type="text/css">
-  .row {
-    background-color: #FFF;
-    padding:1em;
-    margin-bottom:1em;
-  }
-  </style>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/replication/assets/less/replication.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/replication/assets/less/replication.less b/apps/fauxton/app/addons/replication/assets/less/replication.less
deleted file mode 100644
index a301966..0000000
--- a/apps/fauxton/app/addons/replication/assets/less/replication.less
+++ /dev/null
@@ -1,196 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-
-@brown: #3A2C2B;
-@red: #E33F3B;
-@darkRed: #AF2D24;
-@linkRed: #DA4F49;
-@greyBrown: #A59D9D;
-@fontGrey: #808080;
-@secondarySidebar: #E4DFDC;
-
-
-form#replication {
-	position: relative;
-	max-width: none;
-	width: auto;
-
-	.form_set{
-		width: 350px;
-		display: inline-block;
-		border: 1px solid @greyBrown;
-		padding: 15px 10px 0;
-		margin-bottom: 20px;
-		&.middle{
-			width: 100px;
-			border: none;
-			position: relative;
-			height: 100px;
-			margin: 0;
-		}
-		input, select {
-			margin: 0 0 16px 5px;
-			height: 40px;
-			width: 318px;
-		}
-		.btn-group{
-			margin: 0 0 16px 5px;
-			.btn {
-				padding: 10px 57px;
-			}
-		}
-		&.local{
-			.local_option{
-				display: block;
-			}
-			.remote_option{
-				display: none;
-			}
-			.local-btn{
-				background-color: @red;
-				color: #fff;
-			}
-			.remote-btn{
-				background-color: #f5f5f5;
-				color: @fontGrey;
-			}
-		}
-		.local_option{
-			display: none;
-		}
-		.remote-btn{
-			background-color: @red;
-			color: #fff;
-		}
-	}
-
-
-	.options {
-		position: relative;
-		&:after{
-			content: '';
-			display: block;
-			position: absolute;
-			right: -16px;
-			top: 9px;
-			width: 0; 
-			height: 0; 
-			border-left: 5px solid transparent;
-			border-right: 5px solid transparent;
-			border-bottom: 5px solid black;
-			border-top: none;
-		}
-		&.off {
-			&:after{
-			content: '';
-			display: block;
-			position: absolute;
-			right: -16px;
-			top: 9px;
-			width: 0; 
-			height: 0; 
-			border-left: 5px solid transparent;
-			border-right: 5px solid transparent;
-			border-bottom: none;
-			border-top: 5px solid black;
-			}
-		}
-	}
-	.control-group{
-		label{
-			float: left;
-			min-height: 30px;
-			vertical-align: top;
-			padding-right: 5px;
-			min-width: 130px;
-			padding-left: 0px;
-		}
-		input[type=radio],
-		input[type=checkbox]{
-			margin: 0 0 2px 0;
-		}
-	}
-
-	.circle{
-		z-index: 0;
-		position: absolute;
-		top: 20px;
-		left: 15px;
-
-		&:after {
-			width: 70px;
-			height: 70px;
-			content: '';
-			display: block;
-			position: relative;
-			margin: 0 auto;
-			border: 1px solid @greyBrown;
-			-webkit-border-radius: 40px;
-			-moz-border-radius: 40px;
-			border-radius:40px;
-		}
-	}
-	.swap {
-		text-decoration: none;
-		z-index: 30;
-		cursor: pointer;
-		position: absolute;
-		font-size: 40px;
-		width: 27px;
-		height: 12px;
-		top: 31px;
-		left: 30px;
-		&:hover {
-			color: @greyBrown;
-		}
-	}
-
-}
-#replicationStatus{
-	&.showHeader{
-		li.header{
-			display: block;
-			border: none;
-		}
-		ul {
-			border:1px solid @greyBrown;
-		}
-	}
-	li.header{
-		display: none;
-	}
-	ul{
-		margin: 0;
-		li{
-			.progress,
-			p{
-				margin: 0px;
-				vertical-align: bottom;
-				&.break {
-					-ms-word-break: break-all;
-					word-break: break-all;
-
-					/* Non standard for webkit */
-					word-break: break-word;
-					-webkit-hyphens: auto;
-					-moz-hyphens: auto;
-					hyphens: auto;
-				}
-			}
-			padding: 10px 10px;
-			margin: 0;
-			list-style: none;
-			border-top: 1px solid @greyBrown;
-		}
-	}
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/replication/base.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/replication/base.js b/apps/fauxton/app/addons/replication/base.js
deleted file mode 100644
index 93965c1..0000000
--- a/apps/fauxton/app/addons/replication/base.js
+++ /dev/null
@@ -1,24 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-  "app",
-  "api",
-  "addons/replication/route"
-],
-
-function(app, FauxtonAPI, replication) {
-	replication.initialize = function() {
-    FauxtonAPI.addHeaderLink({title: "Replication", href: "#/replication", icon: "fonticon-replicate",});
-  };
-  return replication;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/replication/resources.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/replication/resources.js b/apps/fauxton/app/addons/replication/resources.js
deleted file mode 100644
index 14f255a..0000000
--- a/apps/fauxton/app/addons/replication/resources.js
+++ /dev/null
@@ -1,69 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-  "app",
-  "api",
-  'addons/activetasks/resources'
-],
-
-function (app, FauxtonAPI, ActiveTasks) {
-  var Replication = {};
-
-  //these are probably dupes from the database modules. I'm going to keep them seperate for now.
-  Replication.DBModel = Backbone.Model.extend({
-    label: function () {
-      //for autocomplete
-        return this.get("name");
-    }
-  });
-
-  Replication.DBList = Backbone.Collection.extend({
-    model: Replication.DBModel,
-    url: function() {
-      return app.host + "/_all_dbs";
-    },
-    parse: function(resp) {
-      // TODO: pagination!
-      return _.map(resp, function(database) {
-        return {
-          id: database,
-          name: database
-        };
-      });
-    }
-  });
-
-  Replication.Task = Backbone.Model.extend({});
-
-  Replication.Tasks = Backbone.Collection.extend({
-    model: Replication.Task,
-    url: function () {
-      return app.host + '/_active_tasks';
-    },
-    parse: function(resp){
-      //only want replication tasks to return
-      return _.filter(resp, function(task){
-        return task.type === "replication";
-      });
-    }
-  });
-
-  Replication.Replicate = Backbone.Model.extend({
-    documentation: "replication_doc",
-    url: function(){
-      return app.host + "/_replicate";
-    }
-  });
-
-  return Replication;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/replication/route.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/replication/route.js b/apps/fauxton/app/addons/replication/route.js
deleted file mode 100644
index 17368f8..0000000
--- a/apps/fauxton/app/addons/replication/route.js
+++ /dev/null
@@ -1,50 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-  "app",
-  "api",
-  "addons/replication/resources",
-  "addons/replication/views"
-],
-function(app, FauxtonAPI, Replication, Views) {
-  var  RepRouteObject = FauxtonAPI.RouteObject.extend({
-    layout: "one_pane",
-    roles: ["_admin"],
-    routes: {
-      "replication": "defaultView",
-      "replication/:dbname": "defaultView"
-    },
-    selectedHeader: "Replication",
-    apiUrl: function() {
-      return [this.replication.url(), this.replication.documentation];
-    },
-    crumbs: [
-      {"name": "Replicate changes from: ", "link": "replication"}
-    ],
-    defaultView: function(dbname){
-			this.databases = new Replication.DBList({});
-      this.tasks = new Replication.Tasks({id: "ReplicationTasks"});
-      this.replication = new Replication.Replicate({});
-			this.setView("#dashboard-content", new Views.ReplicationForm({
-        selectedDB: dbname ||"",
-				collection: this.databases,
-        status:  this.tasks
-			}));  
-    }
-  });
-
-
-	Replication.RouteObjects = [RepRouteObject];
-
-  return Replication;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/replication/templates/form.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/replication/templates/form.html b/apps/fauxton/app/addons/replication/templates/form.html
deleted file mode 100644
index 32a87dc..0000000
--- a/apps/fauxton/app/addons/replication/templates/form.html
+++ /dev/null
@@ -1,74 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<form id="replication" class="form-horizontal">
-		<div class="from form_set  local">
-			<div class="btn-group">
-			  <button class="btn local-btn" type="button" value="local">Local</button>
-			  <button class="btn remote-btn" type="button" value="remote">Remote</button>
-			</div>
-
-			<div class="from_local local_option">
-				<select id="from_name" name="source">
-					<% _.each( databases, function( db, i ){ %>
-					   <option value="<%=db.name%>" <% if(selectedDB == db.name){%>selected<%}%> ><%=db.name%></option>
-					<% }); %>
-				</select>
-			</div>
-			<div class="from_to_remote remote_option">
-				<input type="text" id="from_url" name="source" size="30" value="http://">
-			</div>
-		</div>
-
-		<div class="form_set middle">
-			<span class="circle "></span>
-				<a href="#" title="Switch Target and Source" class="swap">
-					<span class="fonticon-swap-arrows"></span>
-				</a>
-			</span>
-		</div>
-
-		<div class="to form_set local">
-			<div class="btn-group">
-			  <button class="btn local-btn" type="button" value="local">Local</button>
-			  <button class="btn remote-btn" type="button" value="remote">Remote</button>
-			</div>
-			<div class="to_local local_option">
-				<input type="text" id="to_name" name="target" size="30" placeholder="database name">
-			</div>
-
-			<div class="to_remote remote_option">
-				<input type="text" id="to_url" name="target" size="30" value="http://">
-			</div>
-		</div>
-
-
-	<div class="actions">
-		<div class="control-group">
-			<label for="continuous">
-				<input type="checkbox" name="continuous" value="true" id="continuous">
-				Continuous
-			</label>
-
-			<label for="createTarget">
-				<input type="checkbox" name="create_target" value="true" id="createTarget">
-				Create Target <a href="<%=getDocUrl('replication_doc')%>" target="_blank"><i class="icon-question-sign" rel="tooltip" title="Create the target database"></i></a>
-			</label>
-		</div>
-
-		<button class="btn btn-success btn-large save" type="submit">Replicate</button>
-	</div>
-</form>
-
-<div id="replicationStatus"></div>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/replication/templates/progress.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/replication/templates/progress.html b/apps/fauxton/app/addons/replication/templates/progress.html
deleted file mode 100644
index 1e6ef90..0000000
--- a/apps/fauxton/app/addons/replication/templates/progress.html
+++ /dev/null
@@ -1,22 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-<p class="span6 break">Replicating <strong><%=source%></strong> to <strong><%=target%></strong></p>
-
-<div class="span4 progress progress-striped active">
-  <div class="bar" style="width: <%=progress || 0%>%;"><%=progress || "0"%>%</div>
-</div>
-
-<span class="span1">
-	<button class="cancel btn btn-danger btn-large delete" data-source="<%=source%>"  data-rep-id="<%=repid%>" data-continuous="<%=continuous%>" data-target="<%=target%>">Cancel</a>
-</span>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/replication/tests/replicationSpec.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/replication/tests/replicationSpec.js b/apps/fauxton/app/addons/replication/tests/replicationSpec.js
deleted file mode 100644
index 788b082..0000000
--- a/apps/fauxton/app/addons/replication/tests/replicationSpec.js
+++ /dev/null
@@ -1,28 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-define([
-       'addons/replication/base',
-       'chai'
-], function (Replication, chai) {
-  var expect = chai.expect;
-
-  describe('Replication Addon', function(){
-
-    describe('Replication DBList Collection', function () {
-      var rep;
-
-      beforeEach(function () {
-        rep = new rep.DBList(["foo","bar","baz","bo"]);
-      });
-    });
-  });
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/replication/views.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/replication/views.js b/apps/fauxton/app/addons/replication/views.js
deleted file mode 100644
index f4b96fd..0000000
--- a/apps/fauxton/app/addons/replication/views.js
+++ /dev/null
@@ -1,295 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-       "app",
-       "api",
-       "modules/fauxton/components",
-       "addons/replication/resources"
-],
-function(app, FauxtonAPI, Components, replication) {
-  var View = {},
-  Events ={},
-  pollingInfo ={
-    rate: 5,
-    intervalId: null
-  };
-
-  _.extend(Events, Backbone.Events);
-
-  // NOTES: http://wiki.apache.org/couchdb/Replication
-
-  // Replication form view is huge
-  // -----------------------------------
-  // afterRender: autocomplete on the target input field
-  // beforeRender:  add the status table
-  // disableFields:  disable non active fields on submit 
-  // enableFields:  enable field when radio btns are clicked
-  // establish:  get the DB list for autocomplete
-  // formValidation:  make sure fields aren't empty
-  // showProgress:  make a call to active_tasks model and show only replication types.  Poll every 5 seconds. (make this it's own view)
-  // startReplication:  saves to the model, starts replication
-  // submit:  form submit handler
-  // swapFields:  change to and from target
-  // toggleAdvancedOptions:  toggle advanced
-
-  View.ReplicationForm = FauxtonAPI.View.extend({
-    template: "addons/replication/templates/form",
-    events:  {
-      "submit #replication": "validate",
-      "click .btn-group .btn": "showFields",
-      "click .swap": "swapFields",
-      "click .options": "toggleAdvancedOptions"
-    },
-    initialize: function(options){
-      this.status = options.status;
-      this.selectedDB = options.selectedDB;
-      this.newRepModel = new replication.Replicate({});
-    },
-    afterRender: function(){
-      this.dbSearchTypeahead = new Components.DbSearchTypeahead({
-        dbLimit: 30,
-        el: "input#to_name"
-      });
-
-      this.dbSearchTypeahead.render();
-
-    },
-
-    beforeRender:  function(){
-      this.insertView("#replicationStatus", new View.ReplicationList({
-        collection: this.status
-      }));
-    },
-    cleanup: function(){
-      clearInterval(pollingInfo.intervalId);
-    },
-    enableFields: function(){
-      this.$el.find('input','select').attr('disabled',false);
-    },
-    disableFields: function(){
-      this.$el.find('input:hidden','select:hidden').attr('disabled',true);
-    },
-    showFields: function(e){
-      var $currentTarget = this.$(e.currentTarget),
-      targetVal = $currentTarget.val();
-
-      if (targetVal === "local"){
-        $currentTarget.parents('.form_set').addClass('local');
-      }else{
-        $currentTarget.parents('.form_set').removeClass('local');
-      }
-    },
-    establish: function(){
-      return [ this.collection.fetch(), this.status.fetch()];
-    },
-    validate: function(e){
-      e.preventDefault();
-      var notification;
-      if (this.formValidation()){
-        notification = FauxtonAPI.addNotification({
-          msg: "Please enter every field.",
-          type: "error",
-          clear: true
-        });
-      }else if (this.$('input#to_name').is(':visible') && !this.$('input[name=create_target]').is(':checked')){
-        var alreadyExists = this.collection.where({"name":this.$('input#to_name').val()});
-        if (alreadyExists.length === 0){
-          notification = FauxtonAPI.addNotification({
-            msg: "This database doesn't exist. Check create target if you want to create it.",
-            type: "error",
-            clear: true
-          });
-        }
-      }else{
-        this.submit(e);
-      }
-    },
-    formValidation: function(e){
-      var $remote = this.$el.find('input:visible'),
-      error = false;
-      for(var i=0; i<$remote.length; i++){
-        if ($remote[i].value =="http://" || $remote[i].value ===""){
-          error = true;
-        }
-      }
-      return error;
-    },
-    serialize: function(){
-      return {
-        databases:  this.collection.toJSON(),
-        selectedDB: this.selectedDB
-      };
-    },
-    startReplication: function(json){
-      var that = this;
-      this.newRepModel.save(json,{
-        success: function(resp){
-          var notification = FauxtonAPI.addNotification({
-            msg: "Replication from "+resp.get('source')+" to "+ resp.get('target')+" has begun.",
-            type: "success",
-            clear: true
-          });
-          that.updateButtonText(false);
-          Events.trigger('update:tasks');
-        },
-        error: function(model, xhr, options){
-          var errorMessage = JSON.parse(xhr.responseText);
-          var notification = FauxtonAPI.addNotification({
-            msg: errorMessage.reason,
-            type: "error",
-            clear: true
-          });
-          that.updateButtonText(false);
-        }
-      });
-      this.enableFields();
-    },		
-    updateButtonText: function(wait){
-      var $button = this.$('#replication button[type=submit]');
-      if(wait){
-        $button.text('Starting replication...').attr('disabled', true);
-      } else {
-        $button.text('Replication').attr('disabled', false);
-      }
-    },
-    submit: function(e){
-      this.disableFields(); 
-      var formJSON = {};
-      _.map(this.$(e.currentTarget).serializeArray(), function(formData){
-        if(formData.value !== ''){
-          formJSON[formData.name] = (formData.value ==="true"? true: formData.value.replace(/\s/g, '').toLowerCase());
-        }
-      });
-
-      this.updateButtonText(true);
-      this.startReplication(formJSON);
-    },	
-    swapFields: function(e){
-      e.preventDefault();
-      //WALL O' VARIABLES
-      var $fromSelect = this.$('#from_name'),
-          $toSelect = this.$('#to_name'),
-          $toInput = this.$('#to_url'),
-          $fromInput = this.$('#from_url'),
-          fromSelectVal = $fromSelect.val(),
-          fromInputVal = $fromInput.val(),
-          toSelectVal = $toSelect.val(),
-          toInputVal = $toInput.val();
-
-      $fromSelect.val(toSelectVal);
-      $toSelect.val(fromSelectVal);
-
-      $fromInput.val(toInputVal);
-      $toInput.val(fromInputVal);
-    }
-  });
-
-
-  View.ReplicationList = FauxtonAPI.View.extend({
-    tagName: "ul",
-    initialize:  function(){
-      Events.bind('update:tasks', this.establish, this);
-      this.listenTo(this.collection, "reset", this.render);
-      this.$el.prepend("<li class='header'><h4>Active Replication Tasks</h4></li>");
-    },
-    establish: function(){
-      return [this.collection.fetch({reset: true})];
-    },
-    setPolling: function(){
-      var that = this;
-      this.cleanup();
-      pollingInfo.intervalId = setInterval(function() {
-        that.establish();
-      }, pollingInfo.rate*1000);
-    },
-    cleanup: function(){
-      clearInterval(pollingInfo.intervalId);
-    },
-    beforeRender:  function(){
-      this.collection.forEach(function(item) {
-        this.insertView(new View.replicationItem({ 
-          model: item
-        }));
-      }, this);
-    },
-    showHeader: function(){
-      if (this.collection.length > 0){
-        this.$el.parent().addClass('showHeader');
-      } else {
-        this.$el.parent().removeClass('showHeader');
-      }
-    },
-    afterRender: function(){
-      this.showHeader();
-      this.setPolling();
-    }
-  });
-
-  //make this a table row item.
-  View.replicationItem = FauxtonAPI.View.extend({
-    tagName: "li",
-    className: "row",
-    template: "addons/replication/templates/progress",
-    events: {
-      "click .cancel": "cancelReplication"
-    },
-    initialize: function(){
-      this.newRepModel = new replication.Replicate({});
-    },
-    establish: function(){
-      return [this.model.fetch()];
-    },
-    cancelReplication: function(e){
-      //need to pass "cancel": true with source & target
-      var $currentTarget = this.$(e.currentTarget),
-      repID = $currentTarget.attr('data-rep-id');
-      this.newRepModel.save({
-        "replication_id": repID,
-        "cancel": true
-      },
-      {
-        success: function(model, xhr, options){
-          var notification = FauxtonAPI.addNotification({
-            msg: "Replication stopped.",
-            type: "success",
-            clear: true
-          });
-        },
-        error: function(model, xhr, options){
-          var errorMessage = JSON.parse(xhr.responseText);
-          var notification = FauxtonAPI.addNotification({
-            msg: errorMessage.reason,
-            type: "error",
-            clear: true
-          });
-        }
-      });
-    },
-    afterRender: function(){
-      if (this.model.get('continuous')){
-        this.$el.addClass('continuous');
-      }
-    },
-    serialize: function(){
-      return {
-        progress:  this.model.get('progress'),
-        target: this.model.get('target'),
-        source: this.model.get('source'),
-        continuous: this.model.get('continuous'),
-        repid: this.model.get('replication_id')
-      };
-    }
-  });
-
-  return View;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/stats/assets/less/stats.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/stats/assets/less/stats.less b/apps/fauxton/app/addons/stats/assets/less/stats.less
deleted file mode 100644
index cfa7679..0000000
--- a/apps/fauxton/app/addons/stats/assets/less/stats.less
+++ /dev/null
@@ -1,19 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-.datatypes {
-  border: #d3d3d3 1px solid;
-  -webkit-border-radius: 5px;
-  -moz-border-radius: 5px;
-  border-radius: 5px;
-  padding: 15px;
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/stats/base.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/stats/base.js b/apps/fauxton/app/addons/stats/base.js
deleted file mode 100644
index 1b44b8b..0000000
--- a/apps/fauxton/app/addons/stats/base.js
+++ /dev/null
@@ -1,26 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-  "app",
-  "api",
-  "addons/stats/routes"
-],
-
-function(app, FauxtonAPI, Stats) {
-
-  Stats.initialize = function() {
-    FauxtonAPI.addHeaderLink({title: "Statistics", href: "#stats", icon: "fonticon-stats", className: 'stats'});
-  };
-
-  return Stats;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/stats/resources.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/stats/resources.js b/apps/fauxton/app/addons/stats/resources.js
deleted file mode 100644
index a761e6b..0000000
--- a/apps/fauxton/app/addons/stats/resources.js
+++ /dev/null
@@ -1,38 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-       "app",
-       "api",
-       "backbone",
-       "lodash",
-       "modules/fauxton/base"
-],
-
-function (app, FauxtonAPI, backbone, _, Fauxton) {
-  var Stats = new FauxtonAPI.addon();
-
-  Stats.Collection = Backbone.Collection.extend({
-    model: Backbone.Model,
-    documentation: "stats",
-    url: app.host+"/_stats",
-    parse: function(resp) {
-      return _.flatten(_.map(resp, function(doc, key) {
-        return _.map(doc, function(v, k){
-          return _.extend({id: k, type: key}, v);
-        });
-      }), true);
-    }
-  });
-
-  return Stats;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/stats/routes.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/stats/routes.js b/apps/fauxton/app/addons/stats/routes.js
deleted file mode 100644
index 971c111..0000000
--- a/apps/fauxton/app/addons/stats/routes.js
+++ /dev/null
@@ -1,63 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-       "app",
-       "api",
-       "addons/stats/views"
-],
-
-function(app, FauxtonAPI, Stats) {
-
-  var StatsRouteObject = FauxtonAPI.RouteObject.extend({
-    layout: "with_sidebar",
-
-    routes: {
-      "stats":"showStats",
-      "_stats": "showStats"
-    },
-    
-    
-    crumbs: [
-      {"name": "Statistics", "link": "_stats"}
-    ],
-
-    selectedHeader: "Statistics",
-
-    initialize: function () {
-      this.stats = new Stats.Collection();
-
-      this.setView("#sidebar-content", new Views.StatSelect({
-        collection: this.stats
-      }));
-
-    },
-
-    showStats: function () {
-      this.setView("#dashboard-content", new Views.Statistics({
-        collection: this.stats
-      }));
-    },
-
-    establish: function() {
-      return [this.stats.fetch()];
-    },
-
-    apiUrl: function(){
-      return [ this.stats.url, this.stats.documentation]; 
-    }
-  });
-
-  Stats.RouteObjects = [StatsRouteObject];
-
-  return Stats;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/stats/templates/by_method.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/stats/templates/by_method.html b/apps/fauxton/app/addons/stats/templates/by_method.html
deleted file mode 100644
index 099d737..0000000
--- a/apps/fauxton/app/addons/stats/templates/by_method.html
+++ /dev/null
@@ -1,16 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<h2>By Method <small>GET, POST, PUT, DELETE</small></h2>
-<div id="httpd_request_methods"></div>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/stats/templates/pie_table.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/stats/templates/pie_table.html b/apps/fauxton/app/addons/stats/templates/pie_table.html
deleted file mode 100644
index c8e89cd..0000000
--- a/apps/fauxton/app/addons/stats/templates/pie_table.html
+++ /dev/null
@@ -1,54 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<div class="row-fluid">
-    <h2>  <%= datatype %> </h2>
-</div>
-
-<div class="row-fluid">
-  <div>
-    <table class="table table-condensed table-striped">
-      <thead>
-        <tr>
-          <th> Description </th>
-          <th> current </th>
-          <th>  sum </th>
-          <th>  mean </th>
-          <th>  stddev </th>
-          <th>  min </th>
-          <th>  max </th>
-        </tr>
-      </thead>
-      <% _.each (statistics, function (stat_line) {
-        if (stat_line.get("sum")){
-       %>
-      <tr>
-        <td><%= stat_line.get("description") %></td>
-        <td><%= stat_line.get("current") %></td>
-        <td><%= stat_line.get("sum") %></td>
-        <td><%= stat_line.get("mean") %></td>
-        <td><%= stat_line.get("stddev") %></td>
-        <td><%= stat_line.get("min") %></td>
-        <td><%= stat_line.get("max") %></td>
-      </tr>
-      <% }}) %>
-    </table>
-  </div>
-
-  <div class="span5" style="height:430px;min-width: 430px">
-    <center>
-      <svg id="<%= datatype %>_graph"></svg>
-    </center>
-  </div>
-</div>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/stats/templates/stats.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/stats/templates/stats.html b/apps/fauxton/app/addons/stats/templates/stats.html
deleted file mode 100644
index ae7ce14..0000000
--- a/apps/fauxton/app/addons/stats/templates/stats.html
+++ /dev/null
@@ -1,16 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<div class="datatypes">
-</div>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/stats/templates/statselect.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/stats/templates/statselect.html b/apps/fauxton/app/addons/stats/templates/statselect.html
deleted file mode 100644
index ef1133c..0000000
--- a/apps/fauxton/app/addons/stats/templates/statselect.html
+++ /dev/null
@@ -1,22 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-
-<% _.each(datatypes, function (datatype) { %>
-<li> 
-<a href="#stats" class="datatype-select" data-type-select="<%= datatype %>"> 
-  <%= datatype %>
-  <i class="icon-chevron-right" style="float:right"></i>
-</a>
-</li>
-<% }); %>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/stats/views.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/stats/views.js b/apps/fauxton/app/addons/stats/views.js
deleted file mode 100644
index 9dd9cbc..0000000
--- a/apps/fauxton/app/addons/stats/views.js
+++ /dev/null
@@ -1,171 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-  "app",
-
-  "api",
-  'addons/stats/resources',
-  "d3",
-  "nv.d3"
-
-],
-
-function(app, FauxtonAPI,Stats) {
-  Views = {};
-
-  datatypeEventer = {};
-  _.extend(datatypeEventer, Backbone.Events);
-
-  Views.Legend = FauxtonAPI.View.extend({
-    tagName: 'ul',
-    template: "addons/stats/templates/legend",
-
-    serialize: function () {
-      return {
-        legend_items: this.collection.toJSON()
-      };
-    }
-  });
-
-  Views.Pie = FauxtonAPI.View.extend({
-    className: "datatype-section",
-    template: 'addons/stats/templates/pie_table',
-
-    initialize: function(args){
-      this.datatype = args.datatype;
-    },
-
-    serialize: function() {
-      return {
-        statistics: this.collection.where({type: this.datatype}),
-        datatype: this.datatype
-      };
-    },
-
-    afterRender: function(){
-        var collection = this.collection,
-            chartelem = "#" + this.datatype + '_graph',
-            series = _.map(this.collection.where({type: this.datatype}),
-          function(d, counter){
-            // TODO: x should be a counter
-            var point = {
-              y: d.get("sum") || 0,
-              key: d.id
-            };
-            return point;
-          }
-        );
-
-        series = _.filter(series, function(d){return d.y > 0;});
-        series = _.sortBy(series, function(d){return -d.y;});
-
-        nv.addGraph(function() {
-            var width = 550,
-                height = 400;
-
-            var chart = nv.models.pieChart()
-                .x(function(d) { return d.key; })
-                .y(function(d) { return d.y; })
-                .showLabels(true)
-                .showLegend(false)
-                .values(function(d) { return d; })
-                .color(d3.scale.category10().range())
-                .width(width)
-                .height(height);
-
-              d3.select(chartelem)
-                  .datum([series])
-                .transition().duration(300)
-                  .attr('width', width)
-                  .attr('height', height)
-                  .call(chart);
-
-            return chart;
-        });
-
-      this.$el.addClass(this.datatype + '_section');
-    }
-  });
-
-  Views.StatSelect = FauxtonAPI.View.extend({
-    className: 'nav nav-tabs nav-stacked',
-    tagName: 'ul',
-
-    template: "addons/stats/templates/statselect",
-
-    initialize: function (options) {
-      this.rows = [];
-    },
-
-    events: {
-      'click .datatype-select': "datatype_selected"
-    },
-
-    serialize: function () {
-      return {
-        datatypes: _.uniq(this.collection.pluck("type"))
-      };
-    },
-
-    afterRender: function () {
-      this.$('.datatype-select').first().addClass('active');
-    },
-
-    datatype_selected: function (event) {
-      var $target = $(event.currentTarget);
-
-      event.preventDefault();
-      event.stopPropagation();
-      this.$('.datatype-select').removeClass('active');
-      $target.addClass('active');
-      datatypeEventer.trigger('datatype-select', $target.attr('data-type-select'));
-    }
-  });
-
-  Views.Statistics = FauxtonAPI.View.extend({
-    template: "addons/stats/templates/stats",
-
-    initialize: function (options) {
-      this.rows = [];
-      datatypeEventer.on('datatype-select', this.display_datatype, this);
-    },
-
-    serialize: function () {
-      return {
-        datatypes: _.uniq(this.collection.pluck("type"))
-      };
-    },
-
-    beforeRender: function () {
-      _.each(_.uniq(this.collection.pluck("type")), function(datatype) {
-        this.rows[datatype] = this.insertView(".datatypes", new Views.Pie({
-          collection: this.collection,
-          datatype: datatype
-        }));
-      }, this);
-    },
-
-    afterRender: function () {
-      this.$('.datatype-section').hide().first().toggle();
-    },
-
-    display_datatype: function (datatype) {
-      this.$('.datatype-section').hide();
-      this.$('.' + datatype + '_section').show();
-    }
-  });
-
-  Stats.Views = Views;
-
-  return Stats;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/verifyinstall/assets/less/verifyinstall.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/verifyinstall/assets/less/verifyinstall.less b/apps/fauxton/app/addons/verifyinstall/assets/less/verifyinstall.less
deleted file mode 100644
index e084cb3..0000000
--- a/apps/fauxton/app/addons/verifyinstall/assets/less/verifyinstall.less
+++ /dev/null
@@ -1,16 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-#start {
-  margin-bottom: 20px;
-}
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/verifyinstall/base.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/verifyinstall/base.js b/apps/fauxton/app/addons/verifyinstall/base.js
deleted file mode 100644
index d17c353..0000000
--- a/apps/fauxton/app/addons/verifyinstall/base.js
+++ /dev/null
@@ -1,31 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-  "app",
-  "api",
-  "addons/verifyinstall/routes"
-],
-
-function(app, FauxtonAPI, VerifyInstall) {
-  VerifyInstall.initialize = function () {
-    FauxtonAPI.addHeaderLink({
-        title: "Verify", 
-        href: "#verifyinstall",
-        icon: "fonticon-circle-check",
-        bottomNav: true,
-      });
-  };
-
-
-  return VerifyInstall;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/verifyinstall/resources.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/verifyinstall/resources.js b/apps/fauxton/app/addons/verifyinstall/resources.js
deleted file mode 100644
index 5d83f9a..0000000
--- a/apps/fauxton/app/addons/verifyinstall/resources.js
+++ /dev/null
@@ -1,181 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-  "app",
-  "api",
-  "modules/databases/resources",
-  "modules/documents/resources"
-],
-
-function (app, FauxtonAPI, Databases, Documents) {
-  var Verifyinstall = FauxtonAPI.addon();
-
-  var db = new Databases.Model({
-    id: 'verifytestdb',
-    name: 'verifytestdb'
-  });
-
-  var dbReplicate = new Databases.Model({
-    id: 'verifytestdb_replicate',
-    name: 'verifytestdb_replicate'
-  });
-
-  var doc, viewDoc;
-
-  Verifyinstall.testProcess = {
-
-    saveDoc: function () {
-      doc = new Documents.Doc({_id: 'test_doc_1', a: 1}, {
-        database: db
-      });
-
-      return doc.save();
-    },
-
-    destroyDoc: function () {
-     return doc.destroy();
-    },
-
-    updateDoc: function () {
-      doc.set({b: "hello"});
-      return doc.save(); 
-    },
-
-    saveDB: function () {
-      return db.save();
-    },
-
-    setupDB: function (db) {
-      var deferred = FauxtonAPI.Deferred();
-      db.fetch()
-      .then(function () {
-        return db.destroy();
-      }, function (xhr) {
-        deferred.resolve();
-      })
-      .then(function () {
-        deferred.resolve();
-      }, function (xhr, error, reason) {
-        if (reason === "Unauthorized") {
-          deferred.reject(xhr, error, reason);
-        }
-      });
-
-      return deferred;
-    },
-
-    setup: function () {
-      return FauxtonAPI.when([
-        this.setupDB(db), 
-        this.setupDB(dbReplicate)
-      ]);
-    },
-
-    testView: function () {
-      var deferred = FauxtonAPI.Deferred();
-      var promise = $.get(viewDoc.url() + '/_view/testview');
-
-      promise.then(function (resp) { 
-        var row = JSON.parse(resp).rows[0];
-        if (row.value === 6) {
-          return deferred.resolve();
-        }
-        var reason = {
-            reason: 'Values expect 6, got ' + row.value
-          };
-
-        deferred.reject({responseText: JSON.stringify(reason)});
-      }, deferred.reject);
-
-      return deferred;
-    },
-
-    setupView: function () {
-      var doc1 = new Documents.Doc({_id: 'test_doc10', a: 1}, {
-        database: db
-      });
-
-      var doc2 = new Documents.Doc({_id: 'test_doc_20', a: 2}, {
-        database: db
-      });
-
-      var doc3 = new Documents.Doc({_id: 'test_doc_30', a: 3}, {
-        database: db
-      });
-
-      viewDoc = new Documents.Doc({
-        _id: '_design/view_check',
-        views: {
-          'testview': { 
-            map:'function (doc) { emit(doc._id, doc.a); }',
-            reduce: '_sum'
-          }
-        } 
-      },{
-        database: db,
-      });
-
-      return FauxtonAPI.when([doc1.save(),doc2.save(), doc3.save(), viewDoc.save()]);
-    },
-
-    setupReplicate: function () {
-      return $.ajax({
-        url: '/_replicate',
-        contentType: 'application/json',
-        type: 'POST',
-        dataType: 'json',
-        processData: false,
-        data: JSON.stringify({
-          create_target: true,
-          source: 'verifytestdb',
-          target: 'verifytestdb_replicate'
-        }),
-      });
-    },
-
-    testReplicate: function () {
-      var deferred = FauxtonAPI.Deferred();
-      /*var dbReplicate = new Databases.Model({
-          id: 'verifytestdb_replicate',
-          name: 'verifytestdb_replicate'
-        });*/
-
-      var promise = dbReplicate.fetch();
-
-      promise.then(function () {
-        var docCount = dbReplicate.get('doc_count');
-        if ( docCount === 4) {
-          deferred.resolve();
-          return;
-        }
-
-        var reason = {
-          reason: 'Replication Failed, expected 4 docs got ' + docCount
-        };
-
-        deferred.reject({responseText: JSON.stringify(reason)});
-      }, deferred.reject);
-
-      return deferred;
-    },
-
-    removeDBs: function () {
-      dbReplicate.destroy();
-      db.destroy();
-
-    }
-  };
-
-
-  return Verifyinstall;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/verifyinstall/routes.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/verifyinstall/routes.js b/apps/fauxton/app/addons/verifyinstall/routes.js
deleted file mode 100644
index e5024ba..0000000
--- a/apps/fauxton/app/addons/verifyinstall/routes.js
+++ /dev/null
@@ -1,37 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-  "app",
-  "api",
-  "addons/verifyinstall/views"
-],
-function(app, FauxtonAPI, VerifyInstall) {
-
-  var VerifyRouteObject = FauxtonAPI.RouteObject.extend({
-    layout: 'one_pane',
-
-    routes: {
-      'verifyinstall': "verifyInstall"
-    },
-    selectedHeader: "Verify",
-
-    verifyInstall: function () {
-      this.setView('#dashboard-content', new VerifyInstall.Main({}));
-    },
-
-    crumbs: [{name: 'Verify Couchdb Installation', link: '#'}]
-  });
-
-  VerifyInstall.RouteObjects = [VerifyRouteObject];
-  return VerifyInstall;
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/verifyinstall/templates/main.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/verifyinstall/templates/main.html b/apps/fauxton/app/addons/verifyinstall/templates/main.html
deleted file mode 100644
index fa41907..0000000
--- a/apps/fauxton/app/addons/verifyinstall/templates/main.html
+++ /dev/null
@@ -1,50 +0,0 @@
-<!--
-Licensed under the Apache License, Version 2.0 (the "License"); you may not
-use this file except in compliance with the License. You may obtain a copy of
-the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-License for the specific language governing permissions and limitations under
-the License.
--->
-<button id="start" class="btn btn-large btn-success"> Verify Installation </button>
-<div id="error"> </div>
-
-<table id="test-score" class="table table-striped table-bordered" >
-  <thead>
-    <tr>
-      <th> Test </th>
-      <th> Status </th>
-    </tr>
-  </thead>
-  <tbody>
-    <tr>
-      <td> Create Database </td>
-      <td id="create-database" class="status">  </td>
-    </tr>
-    <tr>
-      <td> Create Document </td>
-      <td id="create-document" class="status">  </td>
-    </tr>
-    <tr>
-      <td> Update Document </td>
-      <td id="update-document" class="status">  </td>
-    </tr>
-    <tr>
-      <td> Delete Document </td>
-      <td id="delete-document" class="status">  </td>
-    </tr>
-    <tr>
-      <td> Create View </td>
-      <td id="create-view" class="status">  </td>
-    </tr>
-    <tr>
-      <td> Replication </td>
-      <td id="replicate" class="status">  </td>
-    </tr>
-  </tbody>
-</table>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/addons/verifyinstall/views.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/addons/verifyinstall/views.js b/apps/fauxton/app/addons/verifyinstall/views.js
deleted file mode 100644
index eb6dac4..0000000
--- a/apps/fauxton/app/addons/verifyinstall/views.js
+++ /dev/null
@@ -1,127 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-  "app",
-  "api",
-  "addons/verifyinstall/resources",
-],
-function(app, FauxtonAPI, VerifyInstall) {
-
-  VerifyInstall.Main = FauxtonAPI.View.extend({
-    template: 'addons/verifyinstall/templates/main',
-
-    events: {
-      "click #start": "startTest"
-    },
-
-    initialize: function (options) {
-      _.bindAll(this);
-    },
-
-    setPass: function (id) {
-      this.$('#' + id).html('&#10003;');
-    },
-
-    setError: function (id, msg) {
-      this.$('#' + id).html('&#x2717;');
-      FauxtonAPI.addNotification({
-        msg: 'Error: ' + msg,
-        type: 'error',
-        selector: '#error'
-      });
-    },
-
-    complete: function () {
-      FauxtonAPI.addNotification({
-        msg: 'Success! You Couchdb install is working. Time to Relax',
-        type: 'success',
-        selector: '#error'
-      });
-    },
-
-    enableButton: function () {
-      this.$('#start').removeAttr('disabled').text('Verify Installation');
-    },
-
-    disableButton: function () {
-      this.$('#start').attr('disabled','disabled').text('Verifying');
-    },
-
-    formatError: function (id) {
-      var enableButton = this.enableButton,
-          setError = this.setError;
-
-      return function (xhr, error, reason) {
-        enableButton();
-
-        if (!xhr) { return; }
-
-        setError(id, JSON.parse(xhr.responseText).reason);
-      };
-    },
-
-    
-    startTest: function () {
-      this.disableButton();
-      this.$('.status').text('');
-
-      var testProcess = VerifyInstall.testProcess,
-          setPass = this.setPass,
-          complete = this.complete,
-          setError = this.setError,
-          formatError = this.formatError;
-
-      testProcess.setup()
-      .then(function () {
-        return testProcess.saveDB();
-      }, formatError('create-database'))
-      .then(function () {
-        setPass('create-database');
-        return testProcess.saveDoc();
-      }, formatError('create-document'))
-      .then(function () {
-        setPass('create-document');
-        return testProcess.updateDoc();
-      }, formatError('update-document'))
-      .then(function () {
-        setPass('update-document');
-        return testProcess.destroyDoc();
-      }, formatError('delete-document'))
-      .then(function () {
-        setPass('delete-document');
-        return testProcess.setupView();
-      }, formatError('create-view'))
-      .then(function () {
-        return testProcess.testView();
-      }, formatError('create-view'))
-      .then(function () {
-        setPass('create-view');
-        return testProcess.setupReplicate();
-      }, formatError('create-view'))
-      .then(function () {
-        return testProcess.testReplicate();
-      }, formatError('replicate'))
-      .then(function () {
-          setPass('replicate');
-          complete();
-          testProcess.removeDBs();
-      }, formatError('replicate'));
-
-      this.enableButton();
-    }
-  });
-
-
-  return VerifyInstall;
-
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/app/api.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/app/api.js b/apps/fauxton/app/api.js
deleted file mode 100644
index 5ad032a..0000000
--- a/apps/fauxton/app/api.js
+++ /dev/null
@@ -1,558 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-       "app",
-
-       // Modules
-       "modules/fauxton/base",
-       "spin"
-],
-
-function(app, Fauxton) {
-  var FauxtonAPI = app.module();
-
-  FauxtonAPI.moduleExtensions = {
-    Routes: {
-    }
-  };
-
-  FauxtonAPI.addonExtensions = {
-    initialize: function() {}
-  };
-
-  // List of JSHINT errors to ignore
-  // Gets around problem of anonymous functions not being a valid statement
-  FauxtonAPI.excludedViewErrors = [
-    "Missing name in function declaration.",
-    "['{a}'] is better written in dot notation."
-  ];
-
-  FauxtonAPI.isIgnorableError = function(msg) {
-    return _.contains(FauxtonAPI.excludedViewErrors, msg);
-  };
-
-  FauxtonAPI.View = Backbone.View.extend({
-    // This should return an array of promises, an empty array, or null
-    establish: function() {
-      return null;
-    },
-
-    loaderClassname: 'loader',
-
-    disableLoader: false,
-
-    forceRender: function () {
-      this.hasRendered = false;
-    }
-  });
-
-  FauxtonAPI.navigate = function(url, _opts) {
-    var options = _.extend({trigger: true}, _opts );
-    app.router.navigate(url,options);
-  };
-
-  FauxtonAPI.beforeUnload = function () {
-    app.router.beforeUnload.apply(app.router, arguments);
-  };
-
-  FauxtonAPI.removeBeforeUnload = function () {
-    app.router.removeBeforeUnload.apply(app.router, arguments);
-  };
-
-  FauxtonAPI.addHeaderLink = function(link) {
-    app.masterLayout.navBar.addLink(link);
-  };
-
-  FauxtonAPI.removeHeaderLink = function(link) {
-    app.masterLayout.navBar.removeLink(link);
-  };
-
-  FauxtonAPI.Deferred = function() {
-    return $.Deferred();
-  };
-
-  FauxtonAPI.when = function (deferreds) {
-    if (deferreds instanceof Array) {
-      return $.when.apply(null, deferreds);
-    }
-
-    return $.when(deferreds);
-  };
-
-  FauxtonAPI.addRoute = function(route) {
-    app.router.route(route.route, route.name, route.callback);
-  };
-
-  FauxtonAPI.triggerRouteEvent = function (routeEvent, args) {
-    app.router.triggerRouteEvent("route:"+routeEvent, args);
-  };
-
-  FauxtonAPI.module = function(extra) {
-    return app.module(_.extend(FauxtonAPI.moduleExtensions, extra));
-  };
-
-  FauxtonAPI.addon = function(extra) {
-    return FauxtonAPI.module(FauxtonAPI.addonExtensions, extra);
-  };
-
-  FauxtonAPI.addNotification = function(options) {
-    options = _.extend({
-      msg: "Notification Event Triggered!",
-      type: "info",
-      selector: "#global-notifications"
-    }, options);
-    var view = new Fauxton.Notification(options);
-
-    return view.renderNotification();
-  };
-
-  FauxtonAPI.UUID = Backbone.Model.extend({
-    initialize: function(options) {
-      options = _.extend({count: 1}, options);
-      this.count = options.count;
-    },
-
-    url: function() {
-      return app.host + "/_uuids?count=" + this.count;
-    },
-
-    next: function() {
-      return this.get("uuids").pop();
-    }
-  });
-
-  FauxtonAPI.Session = Backbone.Model.extend({
-    url: '/_session',
-
-    user: function () {
-      var userCtx = this.get('userCtx');
-
-      if (!userCtx || !userCtx.name) { return null; }
-
-      return {
-        name: userCtx.name,
-        roles: userCtx.roles
-      };
-    },
-
-    fetchOnce: function (opt) {
-      var options = _.extend({}, opt);
-
-      if (!this._deferred || this._deferred.state() === "rejected" || options.forceFetch ) {
-        this._deferred = this.fetch();
-      }
-
-      return this._deferred;
-    },
-
-    fetchUser: function (opt) {
-      var that = this,
-      currentUser = this.user();
-
-      return this.fetchOnce(opt).then(function () {
-        var user = that.user();
-
-        // Notify anyone listening on these events that either a user has changed
-        // or current user is the same
-        if (currentUser !== user) {
-          that.trigger('session:userChanged');
-        } else {
-          that.trigger('session:userFetched');
-        }
-
-        // this will return the user as a value to all function that calls done on this
-        // eg. session.fetchUser().done(user) { .. do something with user ..}
-        return user; 
-      });
-    }
-  });
-
-  FauxtonAPI.setSession = function (newSession) {
-    app.session = FauxtonAPI.session = newSession;
-    return FauxtonAPI.session.fetchUser();
-  };
-
-  FauxtonAPI.setSession(new FauxtonAPI.Session());
-
-  // This is not exposed externally as it should not need to be accessed or overridden
-  var Auth = function (options) {
-    this._options = options;
-    this.initialize.apply(this, arguments);
-  };
-
-  // Piggy-back on Backbone's self-propagating extend function,
-  Auth.extend = Backbone.Model.extend;
-
-  _.extend(Auth.prototype, Backbone.Events, {
-    authDeniedCb: function() {},
-
-    initialize: function() {
-      var that = this;
-    },
-
-    authHandlerCb : function (roles) {
-      var deferred = $.Deferred();
-      deferred.resolve();
-      return deferred;
-    },
-
-    registerAuth: function (authHandlerCb) {
-      this.authHandlerCb = authHandlerCb;
-    },
-
-    registerAuthDenied: function (authDeniedCb) {
-      this.authDeniedCb = authDeniedCb;
-    },
-
-    checkAccess: function (roles) {
-      var requiredRoles = roles || [],
-      that = this;
-
-      return FauxtonAPI.session.fetchUser().then(function (user) {
-        return FauxtonAPI.when(that.authHandlerCb(FauxtonAPI.session, requiredRoles));
-      });
-    }
-  });
-
-  FauxtonAPI.auth = new Auth();
-
-  FauxtonAPI.RouteObject = function(options) {
-    this._options = options;
-
-    this._configure(options || {});
-    this.initialize.apply(this, arguments);
-    this.addEvents();
-  };
-
-  var broadcaster = {};
-  _.extend(broadcaster, Backbone.Events);
-
-  FauxtonAPI.RouteObject.on = function (eventName, fn) {
-    broadcaster.on(eventName, fn); 
-  };
-  
-  /* How Route Object events work
-   To listen to a specific route objects events:
-
-   myRouteObject = FauxtonAPI.RouteObject.extend({
-    events: {
-      "beforeRender": "beforeRenderEvent"
-    },
-
-    beforeRenderEvent: function (view, selector) {
-      console.log('Hey, beforeRenderEvent triggered',arguments);
-    },
-   });
-
-    It is also possible to listen to events triggered from all Routeobjects. 
-    This is great for more general things like adding loaders, hooks.
-
-    FauxtonAPI.RouteObject.on('beforeRender', function (routeObject, view, selector) {
-      console.log('hey, this will trigger when any routeobject renders a view');
-    });
-
-   Current Events to subscribe to:
-    * beforeFullRender -- before a full render is being done
-    * beforeEstablish -- before the routeobject calls establish
-    * AfterEstablish -- after the routeobject has run establish
-    * beforeRender -- before a view is rendered
-    * afterRender -- a view is finished being rendered
-    * renderComplete -- all rendering is complete
-    
-  */
-
-  // Piggy-back on Backbone's self-propagating extend function
-  FauxtonAPI.RouteObject.extend = Backbone.Model.extend;
-
-  var routeObjectOptions = ["views", "routes", "events", "roles", "crumbs", "layout", "apiUrl", "establish"];
-
-  _.extend(FauxtonAPI.RouteObject.prototype, Backbone.Events, {
-    // Should these be default vals or empty funcs?
-    views: {},
-    routes: {},
-    events: {},
-    crumbs: [],
-    layout: "with_sidebar",
-    apiUrl: null,
-    disableLoader: false,
-    loaderClassname: 'loader',
-    renderedState: false,
-    establish: function() {},
-    route: function() {},
-    roles: [],
-    initialize: function() {}
-  }, {
-
-    renderWith: function(route, masterLayout, args) {
-      var routeObject = this,
-          triggerBroadcast = _.bind(this.triggerBroadcast, this);
-
-      // Only want to redo the template if its a full render
-      if (!this.renderedState) {
-        masterLayout.setTemplate(this.layout);
-        triggerBroadcast('beforeFullRender');
-        $('#primary-navbar li').removeClass('active');
-
-        if (this.selectedHeader) {
-          app.selectedHeader = this.selectedHeader;
-          $('#primary-navbar li[data-nav-name="' + this.selectedHeader + '"]').addClass('active');
-        }
-      }
-
-      masterLayout.clearBreadcrumbs();
-      var crumbs = this.get('crumbs');
-
-      if (crumbs.length) {
-        masterLayout.setBreadcrumbs(new Fauxton.Breadcrumbs({
-          crumbs: crumbs
-        }));
-      }
-
-      triggerBroadcast('beforeEstablish');
-      FauxtonAPI.when(this.establish()).then(function(resp) {
-        triggerBroadcast('afterEstablish');
-        _.each(routeObject.getViews(), function(view, selector) {
-          if(view.hasRendered) { 
-            triggerBroadcast('viewHasRendered', view, selector);
-            return;
-          }
-
-          triggerBroadcast('beforeRender', view, selector);
-          FauxtonAPI.when(view.establish()).then(function(resp) {
-            masterLayout.setView(selector, view);
-
-            masterLayout.renderView(selector);
-            triggerBroadcast('afterRender', view, selector);
-            }, function(resp) {
-              view.establishError = {
-                error: true,
-                reason: resp
-              };
-
-              if (resp) { 
-                var errorText = JSON.parse(resp.responseText).reason;
-                FauxtonAPI.addNotification({
-                  msg: 'An Error occurred: ' + errorText,
-                  type: 'error',
-                  clear: true
-                });
-              }
-
-              masterLayout.renderView(selector);
-          });
-
-        });
-      }.bind(this), function (resp) {
-          if (!resp) { return; }
-          FauxtonAPI.addNotification({
-                msg: 'An Error occurred' + JSON.parse(resp.responseText).reason,
-                type: 'error',
-                clear: true
-          });
-      });
-
-      if (this.get('apiUrl')){
-        masterLayout.apiBar.update(this.get('apiUrl'));
-      } else {
-        masterLayout.apiBar.hide();
-      }
-
-      // Track that we've done a full initial render
-      this.renderedState = true;
-      triggerBroadcast('renderComplete');
-    },
-
-    triggerBroadcast: function (eventName) {
-      var args = Array.prototype.slice.call(arguments);
-      this.trigger.apply(this, args);
-
-      args.splice(0,1, eventName, this);
-      broadcaster.trigger.apply(broadcaster, args);
-    },
-
-    get: function(key) {
-      return _.isFunction(this[key]) ? this[key]() : this[key];
-    },
-
-    addEvents: function(events) {
-      events = events || this.get('events');
-      _.each(events, function(method, event) {
-        if (!_.isFunction(method) && !_.isFunction(this[method])) {
-          throw new Error("Invalid method: "+method);
-        }
-        method = _.isFunction(method) ? method : this[method];
-
-        this.on(event, method);
-      }, this);
-    },
-
-    _configure: function(options) {
-      _.each(_.intersection(_.keys(options), routeObjectOptions), function(key) {
-        this[key] = options[key];
-      }, this);
-    },
-
-    getView: function(selector) {
-      return this.views[selector];
-    },
-
-    setView: function(selector, view) {
-      this.views[selector] = view;
-      return view;
-    },
-
-    getViews: function() {
-      return this.views;
-    },
-
-    removeViews: function () {
-      _.each(this.views, function (view, selector) {
-        view.remove();
-        delete this.views[selector];
-      }, this);
-    },
-
-    getRouteUrls: function () {
-      return _.keys(this.get('routes'));
-    },
-
-    hasRoute: function (route) {
-      if (this.get('routes')[route]) {
-        return true;
-      }
-      return false;
-    },
-
-    routeCallback: function (route, args) {
-      var routes = this.get('routes'),
-      routeObj = routes[route],
-      routeCallback;
-
-      if (typeof routeObj === 'object') {
-        routeCallback = this[routeObj.route];
-      } else {
-        routeCallback = this[routeObj];
-      }
-
-      routeCallback.apply(this, args);
-    },
-
-    getRouteRoles: function (routeUrl) {
-      var route = this.get('routes')[routeUrl];
-
-      if ((typeof route === 'object') && route.roles) {
-        return route.roles; 
-      }
-
-      return this.roles;
-    }
-
-  });
-
-  // We could look at moving the spinner code out to its own module
-  var routeObjectSpinner;
-  FauxtonAPI.RouteObject.on('beforeEstablish', function (routeObject) {
-    if (!routeObject.disableLoader){ 
-      var opts = {
-        lines: 16, // The number of lines to draw
-        length: 8, // The length of each line
-        width: 4, // The line thickness
-        radius: 12, // The radius of the inner circle
-        color: '#333', // #rbg or #rrggbb
-        speed: 1, // Rounds per second
-        trail: 10, // Afterglow percentage
-        shadow: false // Whether to render a shadow
-     };
-
-     if (!$('.spinner').length) {
-       $('<div class="spinner"></div>')
-        .appendTo('#app-container');
-     }
-
-     routeObjectSpinner = new Spinner(opts).spin();
-     $('.spinner').append(routeObjectSpinner.el);
-   }
-  });
-
-  var removeRouteObjectSpinner = function () {
-    if (routeObjectSpinner) {
-      routeObjectSpinner.stop();
-      $('.spinner').remove();
-    }
-  };
-
-  var removeViewSpinner = function () {
-    if (viewSpinner){
-      viewSpinner.stop();
-      $('.spinner').remove();
-    }
-  };
-
-  var viewSpinner;
-  FauxtonAPI.RouteObject.on('beforeRender', function (routeObject, view, selector) {
-    removeRouteObjectSpinner();
-
-    if (!view.disableLoader){ 
-      var opts = {
-        lines: 16, // The number of lines to draw
-        length: 8, // The length of each line
-        width: 4, // The line thickness
-        radius: 12, // The radius of the inner circle
-        color: '#333', // #rbg or #rrggbb
-        speed: 1, // Rounds per second
-        trail: 10, // Afterglow percentage
-        shadow: false // Whether to render a shadow
-      };
-
-      viewSpinner = new Spinner(opts).spin();
-      $('<div class="spinner"></div>')
-        .appendTo(selector)
-        .append(viewSpinner.el);
-    }
-  });
-
-  FauxtonAPI.RouteObject.on('afterRender', function (routeObject, view, selector) {
-    removeViewSpinner();
-  });
-
-  FauxtonAPI.RouteObject.on('viewHasRendered', function () {
-    removeViewSpinner();
-    removeRouteObjectSpinner();
-  });
-
-  var extensions = _.extend({}, Backbone.Events);
-  // Can look at a remove function later.
-  FauxtonAPI.registerExtension = function (name, view) {
-    if (!extensions[name]) {
-      extensions[name] = [];
-    }
-
-    extensions.trigger('add:' + name, view);
-    extensions[name].push(view);
-  };
-
-  FauxtonAPI.getExtensions = function (name) {
-    var views = extensions[name];
-
-    if (!views) {
-      views = [];
-    }
-
-    return views;
-  };
-
-  FauxtonAPI.extensions = extensions;
-
-  app.fauxtonAPI = FauxtonAPI;
-  return app.fauxtonAPI;
-});


[44/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_httpd_proxy.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_httpd_proxy.erl b/apps/couch/src/couch_httpd_proxy.erl
deleted file mode 100644
index 6a4557c..0000000
--- a/apps/couch/src/couch_httpd_proxy.erl
+++ /dev/null
@@ -1,426 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
--module(couch_httpd_proxy).
-
--export([handle_proxy_req/2]).
-
--include("couch_db.hrl").
--include_lib("ibrowse/include/ibrowse.hrl").
-
--define(TIMEOUT, infinity).
--define(PKT_SIZE, 4096).
-
-
-handle_proxy_req(Req, ProxyDest) ->
-    Method = get_method(Req),
-    Url = get_url(Req, ProxyDest),
-    Version = get_version(Req),
-    Headers = get_headers(Req),
-    Body = get_body(Req),
-    Options = [
-        {http_vsn, Version},
-        {headers_as_is, true},
-        {response_format, binary},
-        {stream_to, {self(), once}}
-    ],
-    case ibrowse:send_req(Url, Headers, Method, Body, Options, ?TIMEOUT) of
-        {ibrowse_req_id, ReqId} ->
-            stream_response(Req, ProxyDest, ReqId);
-        {error, Reason} ->
-            throw({error, Reason})
-    end.
-
-
-get_method(#httpd{mochi_req=MochiReq}) ->
-    case MochiReq:get(method) of
-        Method when is_atom(Method) ->
-            list_to_atom(string:to_lower(atom_to_list(Method)));
-        Method when is_list(Method) ->
-            list_to_atom(string:to_lower(Method));
-        Method when is_binary(Method) ->
-            list_to_atom(string:to_lower(?b2l(Method)))
-    end.
-
-
-get_url(Req, ProxyDest) when is_binary(ProxyDest) ->
-    get_url(Req, ?b2l(ProxyDest));
-get_url(#httpd{mochi_req=MochiReq}=Req, ProxyDest) ->
-    BaseUrl = case mochiweb_util:partition(ProxyDest, "/") of
-        {[], "/", _} -> couch_httpd:absolute_uri(Req, ProxyDest);
-        _ -> ProxyDest
-    end,
-    ProxyPrefix = "/" ++ ?b2l(hd(Req#httpd.path_parts)),
-    RequestedPath = MochiReq:get(raw_path),
-    case mochiweb_util:partition(RequestedPath, ProxyPrefix) of
-        {[], ProxyPrefix, []} ->
-            BaseUrl;
-        {[], ProxyPrefix, [$/ | DestPath]} ->
-            remove_trailing_slash(BaseUrl) ++ "/" ++ DestPath;
-        {[], ProxyPrefix, DestPath} ->
-            remove_trailing_slash(BaseUrl) ++ "/" ++ DestPath;
-        _Else ->
-            throw({invalid_url_path, {ProxyPrefix, RequestedPath}})
-    end.
-
-get_version(#httpd{mochi_req=MochiReq}) ->
-    MochiReq:get(version).
-
-
-get_headers(#httpd{mochi_req=MochiReq}) ->
-    to_ibrowse_headers(mochiweb_headers:to_list(MochiReq:get(headers)), []).
-
-to_ibrowse_headers([], Acc) ->
-    lists:reverse(Acc);
-to_ibrowse_headers([{K, V} | Rest], Acc) when is_atom(K) ->
-    to_ibrowse_headers([{atom_to_list(K), V} | Rest], Acc);
-to_ibrowse_headers([{K, V} | Rest], Acc) when is_list(K) ->
-    case string:to_lower(K) of
-        "content-length" ->
-            to_ibrowse_headers(Rest, [{content_length, V} | Acc]);
-        % This appears to make ibrowse too smart.
-        %"transfer-encoding" ->
-        %    to_ibrowse_headers(Rest, [{transfer_encoding, V} | Acc]);
-        _ ->
-            to_ibrowse_headers(Rest, [{K, V} | Acc])
-    end.
-
-get_body(#httpd{method='GET'}) ->
-    fun() -> eof end;
-get_body(#httpd{method='HEAD'}) ->
-    fun() -> eof end;
-get_body(#httpd{method='DELETE'}) ->
-    fun() -> eof end;
-get_body(#httpd{mochi_req=MochiReq}) ->
-    case MochiReq:get(body_length) of
-        undefined ->
-            <<>>;
-        {unknown_transfer_encoding, Unknown} ->
-            exit({unknown_transfer_encoding, Unknown});
-        chunked ->
-            {fun stream_chunked_body/1, {init, MochiReq, 0}};
-        0 ->
-            <<>>;
-        Length when is_integer(Length) andalso Length > 0 ->
-            {fun stream_length_body/1, {init, MochiReq, Length}};
-        Length ->
-            exit({invalid_body_length, Length})
-    end.
-
-
-remove_trailing_slash(Url) ->
-    rem_slash(lists:reverse(Url)).
-
-rem_slash([]) ->
-    [];
-rem_slash([$\s | RevUrl]) ->
-    rem_slash(RevUrl);
-rem_slash([$\t | RevUrl]) ->
-    rem_slash(RevUrl);
-rem_slash([$\r | RevUrl]) ->
-    rem_slash(RevUrl);
-rem_slash([$\n | RevUrl]) ->
-    rem_slash(RevUrl);
-rem_slash([$/ | RevUrl]) ->
-    rem_slash(RevUrl);
-rem_slash(RevUrl) ->
-    lists:reverse(RevUrl).
-
-
-stream_chunked_body({init, MReq, 0}) ->
-    % First chunk, do expect-continue dance.
-    init_body_stream(MReq),
-    stream_chunked_body({stream, MReq, 0, [], ?PKT_SIZE});
-stream_chunked_body({stream, MReq, 0, Buf, BRem}) ->
-    % Finished a chunk, get next length. If next length
-    % is 0, its time to try and read trailers.
-    {CRem, Data} = read_chunk_length(MReq),
-    case CRem of
-        0 ->
-            BodyData = lists:reverse(Buf, Data),
-            {ok, BodyData, {trailers, MReq, [], ?PKT_SIZE}};
-        _ ->
-            stream_chunked_body(
-                {stream, MReq, CRem, [Data | Buf], BRem-size(Data)}
-            )
-    end;
-stream_chunked_body({stream, MReq, CRem, Buf, BRem}) when BRem =< 0 ->
-    % Time to empty our buffers to the upstream socket.
-    BodyData = lists:reverse(Buf),
-    {ok, BodyData, {stream, MReq, CRem, [], ?PKT_SIZE}};
-stream_chunked_body({stream, MReq, CRem, Buf, BRem}) ->
-    % Buffer some more data from the client.
-    Length = lists:min([CRem, BRem]),
-    Socket = MReq:get(socket),
-    NewState = case mochiweb_socket:recv(Socket, Length, ?TIMEOUT) of
-        {ok, Data} when size(Data) == CRem ->
-            case mochiweb_socket:recv(Socket, 2, ?TIMEOUT) of
-                {ok, <<"\r\n">>} ->
-                    {stream, MReq, 0, [<<"\r\n">>, Data | Buf], BRem-Length-2};
-                _ ->
-                    exit(normal)
-            end;
-        {ok, Data} ->
-            {stream, MReq, CRem-Length, [Data | Buf], BRem-Length};
-        _ ->
-            exit(normal)
-    end,
-    stream_chunked_body(NewState);
-stream_chunked_body({trailers, MReq, Buf, BRem}) when BRem =< 0 ->
-    % Empty our buffers and send data upstream.
-    BodyData = lists:reverse(Buf),
-    {ok, BodyData, {trailers, MReq, [], ?PKT_SIZE}};
-stream_chunked_body({trailers, MReq, Buf, BRem}) ->
-    % Read another trailer into the buffer or stop on an
-    % empty line.
-    Socket = MReq:get(socket),
-    mochiweb_socket:setopts(Socket, [{packet, line}]),
-    case mochiweb_socket:recv(Socket, 0, ?TIMEOUT) of
-        {ok, <<"\r\n">>} ->
-            mochiweb_socket:setopts(Socket, [{packet, raw}]),
-            BodyData = lists:reverse(Buf, <<"\r\n">>),
-            {ok, BodyData, eof};
-        {ok, Footer} ->
-            mochiweb_socket:setopts(Socket, [{packet, raw}]),
-            NewState = {trailers, MReq, [Footer | Buf], BRem-size(Footer)},
-            stream_chunked_body(NewState);
-        _ ->
-            exit(normal)
-    end;
-stream_chunked_body(eof) ->
-    % Tell ibrowse we're done sending data.
-    eof.
-
-
-stream_length_body({init, MochiReq, Length}) ->
-    % Do the expect-continue dance
-    init_body_stream(MochiReq),
-    stream_length_body({stream, MochiReq, Length});
-stream_length_body({stream, _MochiReq, 0}) ->
-    % Finished streaming.
-    eof;
-stream_length_body({stream, MochiReq, Length}) ->
-    BufLen = lists:min([Length, ?PKT_SIZE]),
-    case MochiReq:recv(BufLen) of
-        <<>> -> eof;
-        Bin -> {ok, Bin, {stream, MochiReq, Length-BufLen}}
-    end.
-
-
-init_body_stream(MochiReq) ->
-    Expect = case MochiReq:get_header_value("expect") of
-        undefined ->
-            undefined;
-        Value when is_list(Value) ->
-            string:to_lower(Value)
-    end,
-    case Expect of
-        "100-continue" ->
-            MochiReq:start_raw_response({100, gb_trees:empty()});
-        _Else ->
-            ok
-    end.
-
-
-read_chunk_length(MochiReq) ->
-    Socket = MochiReq:get(socket),
-    mochiweb_socket:setopts(Socket, [{packet, line}]),
-    case mochiweb_socket:recv(Socket, 0, ?TIMEOUT) of
-        {ok, Header} ->
-            mochiweb_socket:setopts(Socket, [{packet, raw}]),
-            Splitter = fun(C) ->
-                C =/= $\r andalso C =/= $\n andalso C =/= $\s
-            end,
-            {Hex, _Rest} = lists:splitwith(Splitter, ?b2l(Header)),
-            {mochihex:to_int(Hex), Header};
-        _ ->
-            exit(normal)
-    end.
-
-
-stream_response(Req, ProxyDest, ReqId) ->
-    receive
-        {ibrowse_async_headers, ReqId, "100", _} ->
-            % ibrowse doesn't handle 100 Continue responses which
-            % means we have to discard them so the proxy client
-            % doesn't get confused.
-            ibrowse:stream_next(ReqId),
-            stream_response(Req, ProxyDest, ReqId);
-        {ibrowse_async_headers, ReqId, Status, Headers} ->
-            {Source, Dest} = get_urls(Req, ProxyDest),
-            FixedHeaders = fix_headers(Source, Dest, Headers, []),
-            case body_length(FixedHeaders) of
-                chunked ->
-                    {ok, Resp} = couch_httpd:start_chunked_response(
-                        Req, list_to_integer(Status), FixedHeaders
-                    ),
-                    ibrowse:stream_next(ReqId),
-                    stream_chunked_response(Req, ReqId, Resp),
-                    {ok, Resp};
-                Length when is_integer(Length) ->
-                    {ok, Resp} = couch_httpd:start_response_length(
-                        Req, list_to_integer(Status), FixedHeaders, Length
-                    ),
-                    ibrowse:stream_next(ReqId),
-                    stream_length_response(Req, ReqId, Resp),
-                    {ok, Resp};
-                _ ->
-                    {ok, Resp} = couch_httpd:start_response(
-                        Req, list_to_integer(Status), FixedHeaders
-                    ),
-                    ibrowse:stream_next(ReqId),
-                    stream_length_response(Req, ReqId, Resp),
-                    % XXX: MochiWeb apparently doesn't look at the
-                    % response to see if it must force close the
-                    % connection. So we help it out here.
-                    erlang:put(mochiweb_request_force_close, true),
-                    {ok, Resp}
-            end
-    end.
-
-
-stream_chunked_response(Req, ReqId, Resp) ->
-    receive
-        {ibrowse_async_response, ReqId, {error, Reason}} ->
-            throw({error, Reason});
-        {ibrowse_async_response, ReqId, Chunk} ->
-            couch_httpd:send_chunk(Resp, Chunk),
-            ibrowse:stream_next(ReqId),
-            stream_chunked_response(Req, ReqId, Resp);
-        {ibrowse_async_response_end, ReqId} ->
-            couch_httpd:last_chunk(Resp)
-    end.
-
-
-stream_length_response(Req, ReqId, Resp) ->
-    receive
-        {ibrowse_async_response, ReqId, {error, Reason}} ->
-            throw({error, Reason});
-        {ibrowse_async_response, ReqId, Chunk} ->
-            couch_httpd:send(Resp, Chunk),
-            ibrowse:stream_next(ReqId),
-            stream_length_response(Req, ReqId, Resp);
-        {ibrowse_async_response_end, ReqId} ->
-            ok
-    end.
-
-
-get_urls(Req, ProxyDest) ->
-    SourceUrl = couch_httpd:absolute_uri(Req, "/" ++ hd(Req#httpd.path_parts)),
-    Source = parse_url(?b2l(iolist_to_binary(SourceUrl))),
-    case (catch parse_url(ProxyDest)) of
-        Dest when is_record(Dest, url) ->
-            {Source, Dest};
-        _ ->
-            DestUrl = couch_httpd:absolute_uri(Req, ProxyDest),
-            {Source, parse_url(DestUrl)}
-    end.
-
-
-fix_headers(_, _, [], Acc) ->
-    lists:reverse(Acc);
-fix_headers(Source, Dest, [{K, V} | Rest], Acc) ->
-    Fixed = case string:to_lower(K) of
-        "location" -> rewrite_location(Source, Dest, V);
-        "content-location" -> rewrite_location(Source, Dest, V);
-        "uri" -> rewrite_location(Source, Dest, V);
-        "destination" -> rewrite_location(Source, Dest, V);
-        "set-cookie" -> rewrite_cookie(Source, Dest, V);
-        _ -> V
-    end,
-    fix_headers(Source, Dest, Rest, [{K, Fixed} | Acc]).
-
-
-rewrite_location(Source, #url{host=Host, port=Port, protocol=Proto}, Url) ->
-    case (catch parse_url(Url)) of
-        #url{host=Host, port=Port, protocol=Proto} = Location ->
-            DestLoc = #url{
-                protocol=Source#url.protocol,
-                host=Source#url.host,
-                port=Source#url.port,
-                path=join_url_path(Source#url.path, Location#url.path)
-            },
-            url_to_url(DestLoc);
-        #url{} ->
-            Url;
-        _ ->
-            url_to_url(Source#url{path=join_url_path(Source#url.path, Url)})
-    end.
-
-
-rewrite_cookie(_Source, _Dest, Cookie) ->
-    Cookie.
-
-
-parse_url(Url) when is_binary(Url) ->
-    ibrowse_lib:parse_url(?b2l(Url));
-parse_url(Url) when is_list(Url) ->
-    ibrowse_lib:parse_url(?b2l(iolist_to_binary(Url))).
-
-
-join_url_path(Src, Dst) ->
-    Src2 = case lists:reverse(Src) of
-        "/" ++ RestSrc -> lists:reverse(RestSrc);
-        _ -> Src
-    end,
-    Dst2 = case Dst of
-        "/" ++ RestDst -> RestDst;
-        _ -> Dst
-    end,
-    Src2 ++ "/" ++ Dst2.
-
-
-url_to_url(#url{host=Host, port=Port, path=Path, protocol=Proto} = Url) ->
-    LPort = case {Proto, Port} of
-        {http, 80} -> "";
-        {https, 443} -> "";
-        _ -> ":" ++ integer_to_list(Port)
-    end,
-    LPath = case Path of
-        "/" ++ _RestPath -> Path;
-        _ -> "/" ++ Path
-    end,
-    HostPart = case Url#url.host_type of
-        ipv6_address ->
-            "[" ++ Host ++ "]";
-        _ ->
-            Host
-    end,
-    atom_to_list(Proto) ++ "://" ++ HostPart ++ LPort ++ LPath.
-
-
-body_length(Headers) ->
-    case is_chunked(Headers) of
-        true -> chunked;
-        _ -> content_length(Headers)
-    end.
-
-
-is_chunked([]) ->
-    false;
-is_chunked([{K, V} | Rest]) ->
-    case string:to_lower(K) of
-        "transfer-encoding" ->
-            string:to_lower(V) == "chunked";
-        _ ->
-            is_chunked(Rest)
-    end.
-
-content_length([]) ->
-    undefined;
-content_length([{K, V} | Rest]) ->
-    case string:to_lower(K) of
-        "content-length" ->
-            list_to_integer(V);
-        _ ->
-            content_length(Rest)
-    end.
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_httpd_rewrite.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_httpd_rewrite.erl b/apps/couch/src/couch_httpd_rewrite.erl
deleted file mode 100644
index 1187397..0000000
--- a/apps/couch/src/couch_httpd_rewrite.erl
+++ /dev/null
@@ -1,484 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-% http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-%
-% bind_path is based on bind method from Webmachine
-
-
-%% @doc Module for URL rewriting by pattern matching.
-
--module(couch_httpd_rewrite).
--export([handle_rewrite_req/3]).
--include("couch_db.hrl").
-
--define(SEPARATOR, $\/).
--define(MATCH_ALL, {bind, <<"*">>}).
-
-
-%% doc The http rewrite handler. All rewriting is done from
-%% /dbname/_design/ddocname/_rewrite by default.
-%%
-%% each rules should be in rewrites member of the design doc.
-%% Ex of a complete rule :
-%%
-%%  {
-%%      ....
-%%      "rewrites": [
-%%      {
-%%          "from": "",
-%%          "to": "index.html",
-%%          "method": "GET",
-%%          "query": {}
-%%      }
-%%      ]
-%%  }
-%%
-%%  from: is the path rule used to bind current uri to the rule. It
-%% use pattern matching for that.
-%%
-%%  to: rule to rewrite an url. It can contain variables depending on binding
-%% variables discovered during pattern matching and query args (url args and from
-%% the query member.)
-%%
-%%  method: method to bind the request method to the rule. by default "*"
-%%  query: query args you want to define they can contain dynamic variable
-%% by binding the key to the bindings
-%%
-%%
-%% to and from are path with  patterns. pattern can be string starting with ":" or
-%% "*". ex:
-%% /somepath/:var/*
-%%
-%% This path is converted in erlang list by splitting "/". Each var are
-%% converted in atom. "*" is converted to '*' atom. The pattern matching is done
-%% by splitting "/" in request url in a list of token. A string pattern will
-%% match equal token. The star atom ('*' in single quotes) will match any number
-%% of tokens, but may only be present as the last pathtern in a pathspec. If all
-%% tokens are matched and all pathterms are used, then the pathspec matches. It works
-%% like webmachine. Each identified token will be reused in to rule and in query
-%%
-%% The pattern matching is done by first matching the request method to a rule. by
-%% default all methods match a rule. (method is equal to "*" by default). Then
-%% It will try to match the path to one rule. If no rule match, then a 404 error
-%% is displayed.
-%%
-%% Once a rule is found we rewrite the request url using the "to" and
-%% "query" members. The identified token are matched to the rule and
-%% will replace var. if '*' is found in the rule it will contain the remaining
-%% part if it exists.
-%%
-%% Examples:
-%%
-%% Dispatch rule            URL             TO                  Tokens
-%%
-%% {"from": "/a/b",         /a/b?k=v        /some/b?k=v         var =:= b
-%% "to": "/some/"}                                              k = v
-%%
-%% {"from": "/a/b",         /a/b            /some/b?var=b       var =:= b
-%% "to": "/some/:var"}
-%%
-%% {"from": "/a",           /a              /some
-%% "to": "/some/*"}
-%%
-%% {"from": "/a/*",         /a/b/c          /some/b/c
-%% "to": "/some/*"}
-%%
-%% {"from": "/a",           /a              /some
-%% "to": "/some/*"}
-%%
-%% {"from": "/a/:foo/*",    /a/b/c          /some/b/c?foo=b     foo =:= b
-%% "to": "/some/:foo/*"}
-%%
-%% {"from": "/a/:foo",     /a/b             /some/?k=b&foo=b    foo =:= b
-%% "to": "/some",
-%%  "query": {
-%%      "k": ":foo"
-%%  }}
-%%
-%% {"from": "/a",           /a?foo=b        /some/b             foo =:= b
-%% "to": "/some/:foo",
-%%  }}
-
-
-
-handle_rewrite_req(#httpd{
-        path_parts=[DbName, <<"_design">>, DesignName, _Rewrite|PathParts],
-        method=Method,
-        mochi_req=MochiReq}=Req, _Db, DDoc) ->
-
-    % we are in a design handler
-    DesignId = <<"_design/", DesignName/binary>>,
-    Prefix = <<"/", (?l2b(couch_util:url_encode(DbName)))/binary, "/", DesignId/binary>>,
-    QueryList = lists:map(fun decode_query_value/1, couch_httpd:qs(Req)),
-
-    RewritesSoFar = erlang:get(?REWRITE_COUNT),
-    MaxRewrites = list_to_integer(couch_config:get("httpd", "rewrite_limit", "100")),
-    case RewritesSoFar >= MaxRewrites of
-        true ->
-            throw({bad_request, <<"Exceeded rewrite recursion limit">>});
-        false ->
-            erlang:put(?REWRITE_COUNT, RewritesSoFar + 1)
-    end,
-
-    #doc{body={Props}} = DDoc,
-
-    % get rules from ddoc
-    case couch_util:get_value(<<"rewrites">>, Props) of
-        undefined ->
-            couch_httpd:send_error(Req, 404, <<"rewrite_error">>,
-                <<"Invalid path.">>);
-        Bin when is_binary(Bin) ->
-            couch_httpd:send_error(Req, 400, <<"rewrite_error">>,
-                <<"Rewrite rules are a String. They must be a JSON Array.">>);
-        Rules ->
-            % create dispatch list from rules
-            DispatchList =  [make_rule(Rule) || {Rule} <- Rules],
-            Method1 = couch_util:to_binary(Method),
-
-            %% get raw path by matching url to a rule.
-            RawPath = case try_bind_path(DispatchList, Method1, 
-                    PathParts, QueryList) of
-                no_dispatch_path ->
-                    throw(not_found);
-                {NewPathParts, Bindings} ->
-                    Parts = [quote_plus(X) || X <- NewPathParts],
-
-                    % build new path, reencode query args, eventually convert
-                    % them to json
-                    Bindings1 = maybe_encode_bindings(Bindings),
-                    Path = binary_to_list(
-                        iolist_to_binary([
-                                string:join(Parts, [?SEPARATOR]),
-                                [["?", mochiweb_util:urlencode(Bindings1)] 
-                                    || Bindings1 =/= [] ]
-                            ])),
-                    
-                    % if path is relative detect it and rewrite path
-                    case mochiweb_util:safe_relative_path(Path) of
-                        undefined ->
-                            ?b2l(Prefix) ++ "/" ++ Path;
-                        P1 ->
-                            ?b2l(Prefix) ++ "/" ++ P1
-                    end
-
-                end,
-
-            % normalize final path (fix levels "." and "..")
-            RawPath1 = ?b2l(iolist_to_binary(normalize_path(RawPath))),
-
-            % In order to do OAuth correctly, we have to save the
-            % requested path. We use default so chained rewriting
-            % wont replace the original header.
-            Headers = mochiweb_headers:default("x-couchdb-requested-path",
-                                             MochiReq:get(raw_path),
-                                             MochiReq:get(headers)),
-
-            ?LOG_DEBUG("rewrite to ~p ~n", [RawPath1]),
-
-            % build a new mochiweb request
-            MochiReq1 = mochiweb_request:new(MochiReq:get(socket),
-                                             MochiReq:get(method),
-                                             RawPath1,
-                                             MochiReq:get(version),
-                                             Headers),
-
-            % cleanup, It force mochiweb to reparse raw uri.
-            MochiReq1:cleanup(),
-
-            #httpd{
-                db_url_handlers = DbUrlHandlers,
-                design_url_handlers = DesignUrlHandlers,
-                default_fun = DefaultFun,
-                url_handlers = UrlHandlers,
-                user_ctx = UserCtx,
-               auth = Auth
-            } = Req,
-
-            erlang:put(pre_rewrite_auth, Auth),
-            erlang:put(pre_rewrite_user_ctx, UserCtx),
-            couch_httpd:handle_request_int(MochiReq1, DefaultFun,
-                    UrlHandlers, DbUrlHandlers, DesignUrlHandlers)
-        end.
-
-quote_plus({bind, X}) ->
-    mochiweb_util:quote_plus(X);
-quote_plus(X) ->
-    mochiweb_util:quote_plus(X).
-
-%% @doc Try to find a rule matching current url. If none is found
-%% 404 error not_found is raised
-try_bind_path([], _Method, _PathParts, _QueryList) ->
-    no_dispatch_path;
-try_bind_path([Dispatch|Rest], Method, PathParts, QueryList) ->
-    [{PathParts1, Method1}, RedirectPath, QueryArgs, Formats] = Dispatch,
-    case bind_method(Method1, Method) of
-        true ->
-            case bind_path(PathParts1, PathParts, []) of
-                {ok, Remaining, Bindings} ->
-                    Bindings1 = Bindings ++ QueryList,
-                    % we parse query args from the rule and fill
-                    % it eventually with bindings vars
-                    QueryArgs1 = make_query_list(QueryArgs, Bindings1,
-                        Formats, []),
-                    % remove params in QueryLists1 that are already in
-                    % QueryArgs1
-                    Bindings2 = lists:foldl(fun({K, V}, Acc) ->
-                        K1 = to_binding(K),
-                        KV = case couch_util:get_value(K1, QueryArgs1) of
-                            undefined -> [{K1, V}];
-                            _V1 -> []
-                        end,
-                        Acc ++ KV
-                    end, [], Bindings1),
-
-                    FinalBindings = Bindings2 ++ QueryArgs1,
-                    NewPathParts = make_new_path(RedirectPath, FinalBindings,
-                                    Remaining, []),
-                    {NewPathParts, FinalBindings};
-                fail ->
-                    try_bind_path(Rest, Method, PathParts, QueryList)
-            end;
-        false ->
-            try_bind_path(Rest, Method, PathParts, QueryList)
-    end.
-
-%% rewriting dynamically the quey list given as query member in
-%% rewrites. Each value is replaced by one binding or an argument
-%% passed in url.
-make_query_list([], _Bindings, _Formats, Acc) ->
-    Acc;
-make_query_list([{Key, {Value}}|Rest], Bindings, Formats, Acc) ->
-    Value1 = {Value},
-    make_query_list(Rest, Bindings, Formats, [{to_binding(Key), Value1}|Acc]);
-make_query_list([{Key, Value}|Rest], Bindings, Formats, Acc) when is_binary(Value) ->
-    Value1 = replace_var(Value, Bindings, Formats),
-    make_query_list(Rest, Bindings, Formats, [{to_binding(Key), Value1}|Acc]);
-make_query_list([{Key, Value}|Rest], Bindings, Formats, Acc) when is_list(Value) ->
-    Value1 = replace_var(Value, Bindings, Formats),
-    make_query_list(Rest, Bindings, Formats, [{to_binding(Key), Value1}|Acc]);
-make_query_list([{Key, Value}|Rest], Bindings, Formats, Acc) ->
-    make_query_list(Rest, Bindings, Formats, [{to_binding(Key), Value}|Acc]).
-
-replace_var(<<"*">>=Value, Bindings, Formats) ->
-    get_var(Value, Bindings, Value, Formats);
-replace_var(<<":", Var/binary>> = Value, Bindings, Formats) ->
-    get_var(Var, Bindings, Value, Formats);
-replace_var(Value, _Bindings, _Formats) when is_binary(Value) ->
-    Value;
-replace_var(Value, Bindings, Formats) when is_list(Value) ->
-    lists:reverse(lists:foldl(fun
-                (<<":", Var/binary>>=Value1, Acc) ->
-                    [get_var(Var, Bindings, Value1, Formats)|Acc];
-                (Value1, Acc) ->
-                    [Value1|Acc]
-            end, [], Value));
-replace_var(Value, _Bindings, _Formats) ->
-    Value.
-                    
-maybe_json(Key, Value) ->
-    case lists:member(Key, [<<"key">>, <<"startkey">>, <<"start_key">>,
-                <<"endkey">>, <<"end_key">>, <<"keys">>]) of
-        true ->
-            ?JSON_ENCODE(Value);
-        false ->
-            Value
-    end.
-
-get_var(VarName, Props, Default, Formats) ->
-    VarName1 = to_binding(VarName),
-    Val = couch_util:get_value(VarName1, Props, Default),
-    maybe_format(VarName, Val, Formats).
-
-maybe_format(VarName, Value, Formats) ->
-    case couch_util:get_value(VarName, Formats) of
-        undefined ->
-             Value;
-        Format ->
-            format(Format, Value)
-    end.
-
-format(<<"int">>, Value) when is_integer(Value) ->
-    Value;
-format(<<"int">>, Value) when is_binary(Value) ->
-    format(<<"int">>, ?b2l(Value));
-format(<<"int">>, Value) when is_list(Value) ->
-    case (catch list_to_integer(Value)) of
-        IntVal when is_integer(IntVal) ->
-            IntVal;
-        _ ->
-            Value
-    end;
-format(<<"bool">>, Value) when is_binary(Value) ->
-    format(<<"bool">>, ?b2l(Value));
-format(<<"bool">>, Value) when is_list(Value) ->
-    case string:to_lower(Value) of
-        "true" -> true;
-        "false" -> false;
-        _ -> Value
-    end;
-format(_Format, Value) ->
-   Value. 
-
-%% doc: build new patch from bindings. bindings are query args
-%% (+ dynamic query rewritten if needed) and bindings found in
-%% bind_path step.
-make_new_path([], _Bindings, _Remaining, Acc) ->
-    lists:reverse(Acc);
-make_new_path([?MATCH_ALL], _Bindings, Remaining, Acc) ->
-    Acc1 = lists:reverse(Acc) ++ Remaining,
-    Acc1;
-make_new_path([?MATCH_ALL|_Rest], _Bindings, Remaining, Acc) ->
-    Acc1 = lists:reverse(Acc) ++ Remaining,
-    Acc1;
-make_new_path([{bind, P}|Rest], Bindings, Remaining, Acc) ->
-    P2 = case couch_util:get_value({bind, P}, Bindings) of
-        undefined -> << "undefined">>;
-        P1 -> 
-            iolist_to_binary(P1)
-    end,
-    make_new_path(Rest, Bindings, Remaining, [P2|Acc]);
-make_new_path([P|Rest], Bindings, Remaining, Acc) ->
-    make_new_path(Rest, Bindings, Remaining, [P|Acc]).
-
-
-%% @doc If method of the query fith the rule method. If the
-%% method rule is '*', which is the default, all
-%% request method will bind. It allows us to make rules
-%% depending on HTTP method.
-bind_method(?MATCH_ALL, _Method ) ->
-    true;
-bind_method({bind, Method}, Method) ->
-    true;
-bind_method(_, _) ->
-    false.
-
-
-%% @doc bind path. Using the rule from we try to bind variables given
-%% to the current url by pattern matching
-bind_path([], [], Bindings) ->
-    {ok, [], Bindings};
-bind_path([?MATCH_ALL], [Match|_RestMatch]=Rest, Bindings) ->
-    {ok, Rest, [{?MATCH_ALL, Match}|Bindings]};
-bind_path(_, [], _) ->
-    fail;
-bind_path([{bind, Token}|RestToken],[Match|RestMatch],Bindings) ->
-    bind_path(RestToken, RestMatch, [{{bind, Token}, Match}|Bindings]);
-bind_path([Token|RestToken], [Token|RestMatch], Bindings) ->
-    bind_path(RestToken, RestMatch, Bindings);
-bind_path(_, _, _) ->
-    fail.
-
-
-%% normalize path.
-normalize_path(Path)  ->
-    "/" ++ string:join(normalize_path1(string:tokens(Path,
-                "/"), []), [?SEPARATOR]).
-
-
-normalize_path1([], Acc) ->
-    lists:reverse(Acc);
-normalize_path1([".."|Rest], Acc) ->
-    Acc1 = case Acc of
-        [] -> [".."|Acc];
-        [T|_] when T =:= ".." -> [".."|Acc];
-        [_|R] -> R
-    end,
-    normalize_path1(Rest, Acc1);
-normalize_path1(["."|Rest], Acc) ->
-    normalize_path1(Rest, Acc);
-normalize_path1([Path|Rest], Acc) ->
-    normalize_path1(Rest, [Path|Acc]).
-
-
-%% @doc transform json rule in erlang for pattern matching
-make_rule(Rule) ->
-    Method = case couch_util:get_value(<<"method">>, Rule) of
-        undefined -> ?MATCH_ALL;
-        M -> to_binding(M)
-    end,
-    QueryArgs = case couch_util:get_value(<<"query">>, Rule) of
-        undefined -> [];
-        {Args} -> Args
-        end,
-    FromParts  = case couch_util:get_value(<<"from">>, Rule) of
-        undefined -> [?MATCH_ALL];
-        From ->
-            parse_path(From)
-        end,
-    ToParts  = case couch_util:get_value(<<"to">>, Rule) of
-        undefined ->
-            throw({error, invalid_rewrite_target});
-        To ->
-            parse_path(To)
-        end,
-    Formats = case couch_util:get_value(<<"formats">>, Rule) of
-        undefined -> [];
-        {Fmts} -> Fmts
-    end,
-    [{FromParts, Method}, ToParts, QueryArgs, Formats].
-
-parse_path(Path) ->
-    {ok, SlashRE} = re:compile(<<"\\/">>),
-    path_to_list(re:split(Path, SlashRE), [], 0).
-
-%% @doc convert a path rule (from or to) to an erlang list
-%% * and path variable starting by ":" are converted
-%% in erlang atom.
-path_to_list([], Acc, _DotDotCount) ->
-    lists:reverse(Acc);
-path_to_list([<<>>|R], Acc, DotDotCount) ->
-    path_to_list(R, Acc, DotDotCount);
-path_to_list([<<"*">>|R], Acc, DotDotCount) ->
-    path_to_list(R, [?MATCH_ALL|Acc], DotDotCount);
-path_to_list([<<"..">>|R], Acc, DotDotCount) when DotDotCount == 2 ->
-    case couch_config:get("httpd", "secure_rewrites", "true") of
-    "false" ->
-        path_to_list(R, [<<"..">>|Acc], DotDotCount+1);
-    _Else ->
-        ?LOG_INFO("insecure_rewrite_rule ~p blocked", [lists:reverse(Acc) ++ [<<"..">>] ++ R]),
-        throw({insecure_rewrite_rule, "too many ../.. segments"})
-    end;
-path_to_list([<<"..">>|R], Acc, DotDotCount) ->
-    path_to_list(R, [<<"..">>|Acc], DotDotCount+1);
-path_to_list([P|R], Acc, DotDotCount) ->
-    P1 = case P of
-        <<":", Var/binary>> ->
-            to_binding(Var);
-        _ -> P
-    end,
-    path_to_list(R, [P1|Acc], DotDotCount).
-
-maybe_encode_bindings([]) ->
-    [];
-maybe_encode_bindings(Props) -> 
-    lists:foldl(fun 
-            ({{bind, <<"*">>}, _V}, Acc) ->
-                Acc;
-            ({{bind, K}, V}, Acc) ->
-                V1 = iolist_to_binary(maybe_json(K, V)),
-                [{K, V1}|Acc]
-        end, [], Props).
-                
-decode_query_value({K,V}) ->
-    case lists:member(K, ["key", "startkey", "start_key",
-                "endkey", "end_key", "keys"]) of
-        true ->
-            {to_binding(K), ?JSON_DECODE(V)};
-        false ->
-            {to_binding(K), ?l2b(V)}
-    end.
-
-to_binding({bind, V}) ->
-    {bind, V};
-to_binding(V) when is_list(V) ->
-    to_binding(?l2b(V));
-to_binding(V) ->
-    {bind, V}.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_httpd_stats_handlers.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_httpd_stats_handlers.erl b/apps/couch/src/couch_httpd_stats_handlers.erl
deleted file mode 100644
index d6973f6..0000000
--- a/apps/couch/src/couch_httpd_stats_handlers.erl
+++ /dev/null
@@ -1,56 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_httpd_stats_handlers).
--include("couch_db.hrl").
-
--export([handle_stats_req/1]).
--import(couch_httpd, [
-    send_json/2, send_json/3, send_json/4, send_method_not_allowed/2,
-    start_json_response/2, send_chunk/2, end_json_response/1,
-    start_chunked_response/3, send_error/4
-]).
-
-handle_stats_req(#httpd{method='GET', path_parts=[_]}=Req) ->
-    flush(Req),
-    send_json(Req, couch_stats_aggregator:all(range(Req)));
-
-handle_stats_req(#httpd{method='GET', path_parts=[_, _Mod]}) ->
-    throw({bad_request, <<"Stat names must have exactly two parts.">>});
-
-handle_stats_req(#httpd{method='GET', path_parts=[_, Mod, Key]}=Req) ->
-    flush(Req),
-    Stats = couch_stats_aggregator:get_json({list_to_atom(binary_to_list(Mod)),
-        list_to_atom(binary_to_list(Key))}, range(Req)),
-    send_json(Req, {[{Mod, {[{Key, Stats}]}}]});
-
-handle_stats_req(#httpd{method='GET', path_parts=[_, _Mod, _Key | _Extra]}) ->
-    throw({bad_request, <<"Stat names must have exactly two parts.">>});
-
-handle_stats_req(Req) ->
-    send_method_not_allowed(Req, "GET").
-
-range(Req) ->
-    case couch_util:get_value("range", couch_httpd:qs(Req)) of
-        undefined ->
-            0;
-        Value ->
-            list_to_integer(Value)
-    end.
-
-flush(Req) ->
-    case couch_util:get_value("flush", couch_httpd:qs(Req)) of
-        "true" ->
-            couch_stats_aggregator:collect_sample();
-        _Else ->
-            ok
-    end.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_httpd_vhost.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_httpd_vhost.erl b/apps/couch/src/couch_httpd_vhost.erl
deleted file mode 100644
index 4c3ebfe..0000000
--- a/apps/couch/src/couch_httpd_vhost.erl
+++ /dev/null
@@ -1,383 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_httpd_vhost).
--behaviour(gen_server).
-
--export([start_link/0, config_change/2, reload/0, get_state/0, dispatch_host/1]).
--export([urlsplit_netloc/2, redirect_to_vhost/2]).
--export([host/1, split_host_port/1]).
-
--export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-
--include("couch_db.hrl").
-
--define(SEPARATOR, $\/).
--define(MATCH_ALL, {bind, '*'}).
-
--record(vhosts_state, {
-        vhosts,
-        vhost_globals,
-        vhosts_fun}).
-
-%% doc the vhost manager.
-%% This gen_server keep state of vhosts added to the ini and try to
-%% match the Host header (or forwarded) against rules built against
-%% vhost list.
-%%
-%% Declaration of vhosts take place in the configuration file :
-%%
-%% [vhosts]
-%% example.com = /example
-%% *.example.com = /example
-%%
-%% The first line will rewrite the rquest to display the content of the
-%% example database. This rule works only if the Host header is
-%% 'example.com' and won't work for CNAMEs. Second rule on the other hand
-%% match all CNAMES to example db. So www.example.com or db.example.com
-%% will work.
-%%
-%% The wildcard ('*') should always be the last in the cnames:
-%%
-%%      "*.db.example.com = /"  will match all cname on top of db
-%% examples to the root of the machine.
-%%
-%%
-%% Rewriting Hosts to path
-%% -----------------------
-%%
-%% Like in the _rewrite handler you could match some variable and use
-%them to create the target path. Some examples:
-%%
-%%    [vhosts]
-%%    *.example.com = /*
-%%    :dbname.example.com = /:dbname
-%%    :ddocname.:dbname.example.com = /:dbname/_design/:ddocname/_rewrite
-%%
-%% First rule pass wildcard as dbname, second do the same but use a
-%% variable name and the third one allows you to use any app with
-%% @ddocname in any db with @dbname .
-%%
-%% You could also change the default function to handle request by
-%% changing the setting `redirect_vhost_handler` in `httpd` section of
-%% the Ini:
-%%
-%%    [httpd]
-%%    redirect_vhost_handler = {Module, Fun}
-%%
-%% The function take 2 args : the mochiweb request object and the target
-%%% path.
-
-start_link() ->
-    gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
-
-%% @doc reload vhosts rules
-reload() ->
-    gen_server:call(?MODULE, reload).
-
-get_state() ->
-    gen_server:call(?MODULE, get_state).
-
-%% @doc Try to find a rule matching current Host heade. some rule is
-%% found it rewrite the Mochiweb Request else it return current Request.
-dispatch_host(MochiReq) ->
-    #vhosts_state{
-        vhost_globals = VHostGlobals,
-        vhosts = VHosts,
-        vhosts_fun=Fun} = get_state(),
-
-    {"/" ++ VPath, Query, Fragment} = mochiweb_util:urlsplit_path(MochiReq:get(raw_path)),
-    VPathParts =  string:tokens(VPath, "/"),
-
-    VHost = host(MochiReq),
-    {VHostParts, VhostPort} = split_host_port(VHost),
-    FinalMochiReq = case try_bind_vhost(VHosts, lists:reverse(VHostParts),
-            VhostPort, VPathParts) of
-        no_vhost_matched -> MochiReq;
-        {VhostTarget, NewPath} ->
-            case vhost_global(VHostGlobals, MochiReq) of
-                true ->
-                    MochiReq;
-                _Else ->
-                    NewPath1 = mochiweb_util:urlunsplit_path({NewPath, Query,
-                                          Fragment}),
-                    MochiReq1 = mochiweb_request:new(MochiReq:get(socket),
-                                      MochiReq:get(method),
-                                      NewPath1,
-                                      MochiReq:get(version),
-                                      MochiReq:get(headers)),
-                    Fun(MochiReq1, VhostTarget)
-            end
-    end,
-    FinalMochiReq.
-
-append_path("/"=_Target, "/"=_Path) ->
-    "/";
-append_path(Target, Path) ->
-    Target ++ Path.
-
-% default redirect vhost handler
-redirect_to_vhost(MochiReq, VhostTarget) ->
-    Path = MochiReq:get(raw_path),
-    Target = append_path(VhostTarget, Path),
-
-    ?LOG_DEBUG("Vhost Target: '~p'~n", [Target]),
-
-    Headers = mochiweb_headers:enter("x-couchdb-vhost-path", Path,
-        MochiReq:get(headers)),
-
-    % build a new mochiweb request
-    MochiReq1 = mochiweb_request:new(MochiReq:get(socket),
-                                      MochiReq:get(method),
-                                      Target,
-                                      MochiReq:get(version),
-                                      Headers),
-    % cleanup, It force mochiweb to reparse raw uri.
-    MochiReq1:cleanup(),
-    MochiReq1.
-
-%% if so, then it will not be rewritten, but will run as a normal couchdb request.
-%* normally you'd use this for _uuids _utils and a few of the others you want to
-%% keep available on vhosts. You can also use it to make databases 'global'.
-vhost_global( VhostGlobals, MochiReq) ->
-    RawUri = MochiReq:get(raw_path),
-    {"/" ++ Path, _, _} = mochiweb_util:urlsplit_path(RawUri),
-
-    Front = case couch_httpd:partition(Path) of
-    {"", "", ""} ->
-        "/"; % Special case the root url handler
-    {FirstPart, _, _} ->
-        FirstPart
-    end,
-    [true] == [true||V <- VhostGlobals, V == Front].
-
-%% bind host
-%% first it try to bind the port then the hostname.
-try_bind_vhost([], _HostParts, _Port, _PathParts) ->
-    no_vhost_matched;
-try_bind_vhost([VhostSpec|Rest], HostParts, Port, PathParts) ->
-    {{VHostParts, VPort, VPath}, Path} = VhostSpec,
-    case bind_port(VPort, Port) of
-        ok ->
-            case bind_vhost(lists:reverse(VHostParts), HostParts, []) of
-                {ok, Bindings, Remainings} ->
-                    case bind_path(VPath, PathParts) of
-                        {ok, PathParts1} ->
-                            Path1 = make_target(Path, Bindings, Remainings, []),
-                            {make_path(Path1), make_path(PathParts1)};
-                        fail ->
-                            try_bind_vhost(Rest, HostParts, Port,
-                                PathParts)
-                    end;
-                fail -> try_bind_vhost(Rest, HostParts, Port, PathParts)
-            end;
-        fail ->  try_bind_vhost(Rest, HostParts, Port, PathParts)
-    end.
-
-%% doc: build new patch from bindings. bindings are query args
-%% (+ dynamic query rewritten if needed) and bindings found in
-%% bind_path step.
-%% TODO: merge code with rewrite. But we need to make sure we are
-%% in string here.
-make_target([], _Bindings, _Remaining, Acc) ->
-    lists:reverse(Acc);
-make_target([?MATCH_ALL], _Bindings, Remaining, Acc) ->
-    Acc1 = lists:reverse(Acc) ++ Remaining,
-    Acc1;
-make_target([?MATCH_ALL|_Rest], _Bindings, Remaining, Acc) ->
-    Acc1 = lists:reverse(Acc) ++ Remaining,
-    Acc1;
-make_target([{bind, P}|Rest], Bindings, Remaining, Acc) ->
-    P2 = case couch_util:get_value({bind, P}, Bindings) of
-        undefined ->  "undefined";
-        P1 -> P1
-    end,
-    make_target(Rest, Bindings, Remaining, [P2|Acc]);
-make_target([P|Rest], Bindings, Remaining, Acc) ->
-    make_target(Rest, Bindings, Remaining, [P|Acc]).
-
-%% bind port
-bind_port(Port, Port) -> ok;
-bind_port('*', _) -> ok;
-bind_port(_,_) -> fail.
-
-%% bind bhost
-bind_vhost([],[], Bindings) -> {ok, Bindings, []};
-bind_vhost([?MATCH_ALL], [], _Bindings) -> fail;
-bind_vhost([?MATCH_ALL], Rest, Bindings) -> {ok, Bindings, Rest};
-bind_vhost([], _HostParts, _Bindings) -> fail;
-bind_vhost([{bind, Token}|Rest], [Match|RestHost], Bindings) ->
-    bind_vhost(Rest, RestHost, [{{bind, Token}, Match}|Bindings]);
-bind_vhost([Cname|Rest], [Cname|RestHost], Bindings) ->
-    bind_vhost(Rest, RestHost, Bindings);
-bind_vhost(_, _, _) -> fail.
-
-%% bind path
-bind_path([], PathParts) ->
-    {ok, PathParts};
-bind_path(_VPathParts, []) ->
-    fail;
-bind_path([Path|VRest],[Path|Rest]) ->
-   bind_path(VRest, Rest);
-bind_path(_, _) ->
-    fail.
-
-% utilities
-
-
-%% create vhost list from ini
-
-host(MochiReq) ->
-    XHost = couch_config:get("httpd", "x_forwarded_host",
-                             "X-Forwarded-Host"),
-    case MochiReq:get_header_value(XHost) of
-        undefined ->
-            case MochiReq:get_header_value("Host") of
-                undefined -> [];
-                Value1 -> Value1
-            end;
-        Value -> Value
-    end.
-
-make_vhosts() ->
-    Vhosts = lists:foldl(fun
-                ({_, ""}, Acc) ->
-                    Acc;
-                ({Vhost, Path}, Acc) ->
-                    [{parse_vhost(Vhost), split_path(Path)}|Acc]
-            end, [], couch_config:get("vhosts")),
-
-    lists:reverse(lists:usort(Vhosts)).
-
-
-parse_vhost(Vhost) ->
-    case urlsplit_netloc(Vhost, []) of
-        {[], Path} ->
-            {make_spec("*", []), '*', Path};
-        {HostPort, []} ->
-            {H, P} = split_host_port(HostPort),
-            H1 = make_spec(H, []),
-            {H1, P, []};
-        {HostPort, Path} ->
-            {H, P} = split_host_port(HostPort),
-            H1 = make_spec(H, []),
-            {H1, P, string:tokens(Path, "/")}
-    end.
-
-
-split_host_port(HostAsString) ->
-    case string:rchr(HostAsString, $:) of
-        0 ->
-            {split_host(HostAsString), '*'};
-        N ->
-            HostPart = string:substr(HostAsString, 1, N-1),
-            case (catch erlang:list_to_integer(string:substr(HostAsString,
-                            N+1, length(HostAsString)))) of
-                {'EXIT', _} ->
-                    {split_host(HostAsString), '*'};
-                Port ->
-                    {split_host(HostPart), Port}
-            end
-    end.
-
-split_host(HostAsString) ->
-    string:tokens(HostAsString, "\.").
-
-split_path(Path) ->
-    make_spec(string:tokens(Path, "/"), []).
-
-
-make_spec([], Acc) ->
-    lists:reverse(Acc);
-make_spec([""|R], Acc) ->
-    make_spec(R, Acc);
-make_spec(["*"|R], Acc) ->
-    make_spec(R, [?MATCH_ALL|Acc]);
-make_spec([P|R], Acc) ->
-    P1 = parse_var(P),
-    make_spec(R, [P1|Acc]).
-
-
-parse_var(P) ->
-    case P of
-        ":" ++ Var ->
-            {bind, Var};
-        _ -> P
-    end.
-
-
-% mochiweb doesn't export it.
-urlsplit_netloc("", Acc) ->
-    {lists:reverse(Acc), ""};
-urlsplit_netloc(Rest=[C | _], Acc) when C =:= $/; C =:= $?; C =:= $# ->
-    {lists:reverse(Acc), Rest};
-urlsplit_netloc([C | Rest], Acc) ->
-    urlsplit_netloc(Rest, [C | Acc]).
-
-make_path(Parts) ->
-     "/" ++ string:join(Parts,[?SEPARATOR]).
-
-init(_) ->
-    ok = couch_config:register(fun ?MODULE:config_change/2),
-
-    %% load configuration
-    {VHostGlobals, VHosts, Fun} = load_conf(),
-    State = #vhosts_state{
-        vhost_globals=VHostGlobals,
-        vhosts=VHosts,
-        vhosts_fun=Fun},
-    {ok, State}.
-
-handle_call(reload, _From, _State) ->
-    {VHostGlobals, VHosts, Fun} = load_conf(),
-    {reply, ok, #vhosts_state{
-            vhost_globals=VHostGlobals,
-            vhosts=VHosts,
-            vhosts_fun=Fun}};
-handle_call(get_state, _From, State) ->
-    {reply, State, State};
-handle_call(_Msg, _From, State) ->
-    {noreply, State}.
-
-handle_cast(_Msg, State) ->
-    {noreply, State}.
-
-handle_info(_Info, State) ->
-    {noreply, State}.
-
-terminate(_Reason, _State) ->
-    ok.
-
-code_change(_OldVsn, State, _Extra) ->
-    {ok, State}.
-
-config_change("httpd", "vhost_global_handlers") ->
-    ?MODULE:reload();
-config_change("httpd", "redirect_vhost_handler") ->
-    ?MODULE:reload();
-config_change("vhosts", _) ->
-    ?MODULE:reload().
-
-load_conf() ->
-    %% get vhost globals
-    VHostGlobals = re:split(couch_config:get("httpd",
-            "vhost_global_handlers",""), "\\s*,\\s*",[{return, list}]),
-
-    %% build vhosts matching rules
-    VHosts = make_vhosts(),
-
-    %% build vhosts handler fun
-    DefaultVHostFun = "{couch_httpd_vhost, redirect_to_vhost}",
-    Fun = couch_httpd:make_arity_2_fun(couch_config:get("httpd",
-            "redirect_vhost_handler", DefaultVHostFun)),
-
-    {VHostGlobals, VHosts, Fun}.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_js_functions.hrl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_js_functions.hrl b/apps/couch/src/couch_js_functions.hrl
deleted file mode 100644
index a48feae..0000000
--- a/apps/couch/src/couch_js_functions.hrl
+++ /dev/null
@@ -1,170 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License.  You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--define(AUTH_DB_DOC_VALIDATE_FUNCTION, <<"
-    function(newDoc, oldDoc, userCtx, secObj) {
-        if (newDoc._deleted === true) {
-            // allow deletes by admins and matching users
-            // without checking the other fields
-            if ((userCtx.roles.indexOf('_admin') !== -1) ||
-                (userCtx.name == oldDoc.name)) {
-                return;
-            } else {
-                throw({forbidden: 'Only admins may delete other user docs.'});
-            }
-        }
-
-        if ((oldDoc && oldDoc.type !== 'user') || newDoc.type !== 'user') {
-            throw({forbidden : 'doc.type must be user'});
-        } // we only allow user docs for now
-
-        if (!newDoc.name) {
-            throw({forbidden: 'doc.name is required'});
-        }
-
-        if (!newDoc.roles) {
-            throw({forbidden: 'doc.roles must exist'});
-        }
-
-        if (!isArray(newDoc.roles)) {
-            throw({forbidden: 'doc.roles must be an array'});
-        }
-
-        for (var idx = 0; idx < newDoc.roles.length; idx++) {
-            if (typeof newDoc.roles[idx] !== 'string') {
-                throw({forbidden: 'doc.roles can only contain strings'});
-            }
-        }
-
-        if (newDoc._id !== ('org.couchdb.user:' + newDoc.name)) {
-            throw({
-                forbidden: 'Doc ID must be of the form org.couchdb.user:name'
-            });
-        }
-
-        if (oldDoc) { // validate all updates
-            if (oldDoc.name !== newDoc.name) {
-                throw({forbidden: 'Usernames can not be changed.'});
-            }
-        }
-
-        if (newDoc.password_sha && !newDoc.salt) {
-            throw({
-                forbidden: 'Users with password_sha must have a salt.' +
-                    'See /_utils/script/couch.js for example code.'
-            });
-        }
-
-        if (newDoc.password_scheme === \"pbkdf2\") {
-            if (typeof(newDoc.iterations) !== \"number\") {
-               throw({forbidden: \"iterations must be a number.\"});
-            }
-            if (typeof(newDoc.derived_key) !== \"string\") {
-               throw({forbidden: \"derived_key must be a string.\"});
-            }
-        }
-
-        var is_server_or_database_admin = function(userCtx, secObj) {
-            // see if the user is a server admin
-            if(userCtx.roles.indexOf('_admin') !== -1) {
-                return true; // a server admin
-            }
-
-            // see if the user a database admin specified by name
-            if(secObj && secObj.admins && secObj.admins.names) {
-                if(secObj.admins.names.indexOf(userCtx.name) !== -1) {
-                    return true; // database admin
-                }
-            }
-
-            // see if the user a database admin specified by role
-            if(secObj && secObj.admins && secObj.admins.roles) {
-                var db_roles = secObj.admins.roles;
-                for(var idx = 0; idx < userCtx.roles.length; idx++) {
-                    var user_role = userCtx.roles[idx];
-                    if(db_roles.indexOf(user_role) !== -1) {
-                        return true; // role matches!
-                    }
-                }
-            }
-
-            return false; // default to no admin
-        }
-
-        if (!is_server_or_database_admin(userCtx, secObj)) {
-            if (oldDoc) { // validate non-admin updates
-                if (userCtx.name !== newDoc.name) {
-                    throw({
-                        forbidden: 'You may only update your own user document.'
-                    });
-                }
-                // validate role updates
-                var oldRoles = oldDoc.roles.sort();
-                var newRoles = newDoc.roles.sort();
-
-                if (oldRoles.length !== newRoles.length) {
-                    throw({forbidden: 'Only _admin may edit roles'});
-                }
-
-                for (var i = 0; i < oldRoles.length; i++) {
-                    if (oldRoles[i] !== newRoles[i]) {
-                        throw({forbidden: 'Only _admin may edit roles'});
-                    }
-                }
-            } else if (newDoc.roles.length > 0) {
-                throw({forbidden: 'Only _admin may set roles'});
-            }
-        }
-
-        // no system roles in users db
-        for (var i = 0; i < newDoc.roles.length; i++) {
-            if (newDoc.roles[i][0] === '_') {
-                throw({
-                    forbidden:
-                    'No system roles (starting with underscore) in users db.'
-                });
-            }
-        }
-
-        // no system names as names
-        if (newDoc.name[0] === '_') {
-            throw({forbidden: 'Username may not start with underscore.'});
-        }
-
-        var badUserNameChars = [':'];
-
-        for (var i = 0; i < badUserNameChars.length; i++) {
-            if (newDoc.name.indexOf(badUserNameChars[i]) >= 0) {
-                throw({forbidden: 'Character `' + badUserNameChars[i] +
-                        '` is not allowed in usernames.'});
-            }
-        }
-    }
-">>).
-
-
--define(OAUTH_MAP_FUN, <<"
-    function(doc) {
-        if (doc.type === 'user' && doc.oauth && doc.oauth.consumer_keys) {
-            for (var consumer_key in doc.oauth.consumer_keys) {
-                for (var token in doc.oauth.tokens) {
-                    var obj = {
-                        'consumer_secret': doc.oauth.consumer_keys[consumer_key],
-                        'token_secret': doc.oauth.tokens[token],
-                        'username': doc.name
-                    };
-                    emit([consumer_key, token], obj);
-                }
-            }
-        }
-    }
-">>).

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_key_tree.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_key_tree.erl b/apps/couch/src/couch_key_tree.erl
deleted file mode 100644
index ce45ab8..0000000
--- a/apps/couch/src/couch_key_tree.erl
+++ /dev/null
@@ -1,422 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
-%% @doc Data structure used to represent document edit histories.
-
-%% A key tree is used to represent the edit history of a document. Each node of
-%% the tree represents a particular version. Relations between nodes represent
-%% the order that these edits were applied. For instance, a set of three edits
-%% would produce a tree of versions A->B->C indicating that edit C was based on
-%% version B which was in turn based on A. In a world without replication (and
-%% no ability to disable MVCC checks), all histories would be forced to be
-%% linear lists of edits due to constraints imposed by MVCC (ie, new edits must
-%% be based on the current version). However, we have replication, so we must
-%% deal with not so easy cases, which lead to trees.
-%%
-%% Consider a document in state A. This doc is replicated to a second node. We
-%% then edit the document on each node leaving it in two different states, B
-%% and C. We now have two key trees, A->B and A->C. When we go to replicate a
-%% second time, the key tree must combine these two trees which gives us
-%% A->(B|C). This is how conflicts are introduced. In terms of the key tree, we
-%% say that we have two leaves (B and C) that are not deleted. The presense of
-%% the multiple leaves indicate conflict. To remove a conflict, one of the
-%% edits (B or C) can be deleted, which results in, A->(B|C->D) where D is an
-%% edit that is specially marked with the a deleted=true flag.
-%%
-%% What makes this a bit more complicated is that there is a limit to the
-%% number of revisions kept, specified in couch_db.hrl (default is 1000). When
-%% this limit is exceeded only the last 1000 are kept. This comes in to play
-%% when branches are merged. The comparison has to begin at the same place in
-%% the branches. A revision id is of the form N-XXXXXXX where N is the current
-%% revision. So each path will have a start number, calculated in
-%% couch_doc:to_path using the formula N - length(RevIds) + 1 So, .eg. if a doc
-%% was edit 1003 times this start number would be 4, indicating that 3
-%% revisions were truncated.
-%%
-%% This comes into play in @see merge_at/3 which recursively walks down one
-%% tree or the other until they begin at the same revision.
-
--module(couch_key_tree).
-
--export([merge/3, find_missing/2, get_key_leafs/2, get_full_key_paths/2, get/2]).
--export([get_all_leafs/1, count_leafs/1, remove_leafs/2, get_all_leafs_full/1, stem/2]).
--export([map/2, mapfold/3, map_leafs/2, fold/3]).
-
--include("couch_db.hrl").
-
-%% @doc Merge a path with a list of paths and stem to the given length.
--spec merge([path()], path(), pos_integer()) -> {[path()],
-    conflicts | no_conflicts}.
-merge(Paths, Path, Depth) ->
-    {Merged, Conflicts} = merge(Paths, Path),
-    {stem(Merged, Depth), Conflicts}.
-
-%% @doc Merge a path with an existing list of paths, returning a new list of
-%% paths. A return of conflicts indicates a new conflict was discovered in this
-%% merge. Conflicts may already exist in the original list of paths.
--spec merge([path()], path()) -> {[path()], conflicts | no_conflicts}.
-merge(Paths, Path) ->
-    {ok, Merged, HasConflicts} = merge_one(Paths, Path, [], false),
-    if HasConflicts ->
-        Conflicts = conflicts;
-    (length(Merged) =/= length(Paths)) and (length(Merged) =/= 1) ->
-        Conflicts = conflicts;
-    true ->
-        Conflicts = no_conflicts
-    end,
-    {lists:sort(Merged), Conflicts}.
-
--spec merge_one(Original::[path()], Inserted::path(), [path()], boolean()) ->
-    {ok, Merged::[path()], NewConflicts::boolean()}.
-merge_one([], Insert, OutAcc, ConflictsAcc) ->
-    {ok, [Insert | OutAcc], ConflictsAcc};
-merge_one([{Start, Tree}|Rest], {StartInsert, TreeInsert}, Acc, HasConflicts) ->
-    case merge_at([Tree], StartInsert - Start, [TreeInsert]) of
-    {ok, [Merged], Conflicts} ->
-        MergedStart = lists:min([Start, StartInsert]),
-        {ok, Rest ++ [{MergedStart, Merged} | Acc], Conflicts or HasConflicts};
-    no ->
-        AccOut = [{Start, Tree} | Acc],
-        merge_one(Rest, {StartInsert, TreeInsert}, AccOut, HasConflicts)
-    end.
-
--spec merge_at(tree(), Place::integer(), tree()) ->
-    {ok, Merged::tree(), HasConflicts::boolean()} | no.
-merge_at(_Ours, _Place, []) ->
-    no;
-merge_at([], _Place, _Insert) ->
-    no;
-merge_at([{Key, Value, SubTree}|Sibs], Place, InsertTree) when Place > 0 ->
-    % inserted starts later than committed, need to drill into committed subtree
-    case merge_at(SubTree, Place - 1, InsertTree) of
-    {ok, Merged, Conflicts} ->
-        {ok, [{Key, Value, Merged} | Sibs], Conflicts};
-    no ->
-        % first branch didn't merge, move to next branch
-        case merge_at(Sibs, Place, InsertTree) of
-        {ok, Merged, Conflicts} ->
-            {ok, [{Key, Value, SubTree} | Merged], Conflicts};
-        no ->
-            no
-        end
-    end;
-merge_at(OurTree, Place, [{Key, Value, SubTree}]) when Place < 0 ->
-    % inserted starts earlier than committed, need to drill into insert subtree
-    case merge_at(OurTree, Place + 1, SubTree) of
-    {ok, Merged, Conflicts} ->
-        {ok, [{Key, Value, Merged}], Conflicts};
-    no ->
-        no
-    end;
-merge_at([{Key, V1, SubTree}|Sibs], 0, [{Key, V2, InsertSubTree}]) ->
-    {Merged, Conflicts} = merge_simple(SubTree, InsertSubTree),
-    {ok, [{Key, value_pref(V1, V2), Merged} | Sibs], Conflicts};
-merge_at([{OurKey, _, _} | _], 0, [{Key, _, _}]) when OurKey > Key ->
-    % siblings keys are ordered, no point in continuing
-    no;
-merge_at([Tree | Sibs], 0, InsertTree) ->
-    case merge_at(Sibs, 0, InsertTree) of
-    {ok, Merged, Conflicts} ->
-        {ok, [Tree | Merged], Conflicts};
-    no ->
-        no
-    end.
-
-% key tree functions
-
--spec merge_simple(tree(), tree()) -> {Merged::tree(), NewConflicts::boolean()}.
-merge_simple([], B) ->
-    {B, false};
-merge_simple(A, []) ->
-    {A, false};
-merge_simple([{Key, V1, SubA} | NextA], [{Key, V2, SubB} | NextB]) ->
-    {MergedSubTree, Conflict1} = merge_simple(SubA, SubB),
-    {MergedNextTree, Conflict2} = merge_simple(NextA, NextB),
-    Value = value_pref(V1, V2),
-    {[{Key, Value, MergedSubTree} | MergedNextTree], Conflict1 or Conflict2};
-merge_simple([{A, _, _} = Tree | Next], [{B, _, _} | _] = Insert) when A < B ->
-    {Merged, Conflict} = merge_simple(Next, Insert),
-    % if Merged has more branches than the input we added a new conflict
-    {[Tree | Merged], Conflict orelse (length(Merged) > length(Next))};
-merge_simple(Ours, [Tree | Next]) ->
-    {Merged, Conflict} = merge_simple(Ours, Next),
-    {[Tree | Merged], Conflict orelse (length(Merged) > length(Next))}.
-
-find_missing(_Tree, []) ->
-    [];
-find_missing([], SeachKeys) ->
-    SeachKeys;
-find_missing([{Start, {Key, Value, SubTree}} | RestTree], SeachKeys) ->
-    PossibleKeys = [{KeyPos, KeyValue} || {KeyPos, KeyValue} <- SeachKeys, KeyPos >= Start],
-    ImpossibleKeys = [{KeyPos, KeyValue} || {KeyPos, KeyValue} <- SeachKeys, KeyPos < Start],
-    Missing = find_missing_simple(Start, [{Key, Value, SubTree}], PossibleKeys),
-    find_missing(RestTree, ImpossibleKeys ++ Missing).
-
-find_missing_simple(_Pos, _Tree, []) ->
-    [];
-find_missing_simple(_Pos, [], SeachKeys) ->
-    SeachKeys;
-find_missing_simple(Pos, [{Key, _, SubTree} | RestTree], SeachKeys) ->
-    PossibleKeys = [{KeyPos, KeyValue} || {KeyPos, KeyValue} <- SeachKeys, KeyPos >= Pos],
-    ImpossibleKeys = [{KeyPos, KeyValue} || {KeyPos, KeyValue} <- SeachKeys, KeyPos < Pos],
-
-    SrcKeys2 = PossibleKeys -- [{Pos, Key}],
-    SrcKeys3 = find_missing_simple(Pos + 1, SubTree, SrcKeys2),
-    ImpossibleKeys ++ find_missing_simple(Pos, RestTree, SrcKeys3).
-
-
-filter_leafs([], _Keys, FilteredAcc, RemovedKeysAcc) ->
-    {FilteredAcc, RemovedKeysAcc};
-filter_leafs([{Pos, [{LeafKey, _}|_]} = Path |Rest], Keys, FilteredAcc, RemovedKeysAcc) ->
-    FilteredKeys = lists:delete({Pos, LeafKey}, Keys),
-    if FilteredKeys == Keys ->
-        % this leaf is not a key we are looking to remove
-        filter_leafs(Rest, Keys, [Path | FilteredAcc], RemovedKeysAcc);
-    true ->
-        % this did match a key, remove both the node and the input key
-        filter_leafs(Rest, FilteredKeys, FilteredAcc, [{Pos, LeafKey} | RemovedKeysAcc])
-    end.
-
-% Removes any branches from the tree whose leaf node(s) are in the Keys
-remove_leafs(Trees, Keys) ->
-    % flatten each branch in a tree into a tree path
-    Paths = get_all_leafs_full(Trees),
-
-    % filter out any that are in the keys list.
-    {FilteredPaths, RemovedKeys} = filter_leafs(Paths, Keys, [], []),
-
-    SortedPaths = lists:sort(
-        [{Pos + 1 - length(Path), Path} || {Pos, Path} <- FilteredPaths]
-    ),
-
-    % convert paths back to trees
-    NewTree = lists:foldl(
-        fun({StartPos, Path},TreeAcc) ->
-            [SingleTree] = lists:foldl(
-                fun({K,V},NewTreeAcc) -> [{K,V,NewTreeAcc}] end, [], Path),
-            {NewTrees, _} = merge(TreeAcc, {StartPos, SingleTree}),
-            NewTrees
-        end, [], SortedPaths),
-    {NewTree, RemovedKeys}.
-
-
-% get the leafs in the tree matching the keys. The matching key nodes can be
-% leafs or an inner nodes. If an inner node, then the leafs for that node
-% are returned.
-get_key_leafs(Tree, Keys) ->
-    get_key_leafs(Tree, Keys, []).
-
-get_key_leafs(_, [], Acc) ->
-    {Acc, []};
-get_key_leafs([], Keys, Acc) ->
-    {Acc, Keys};
-get_key_leafs([{Pos, Tree}|Rest], Keys, Acc) ->
-    {Gotten, RemainingKeys} = get_key_leafs_simple(Pos, [Tree], Keys, []),
-    get_key_leafs(Rest, RemainingKeys, Gotten ++ Acc).
-
-get_key_leafs_simple(_Pos, _Tree, [], _KeyPathAcc) ->
-    {[], []};
-get_key_leafs_simple(_Pos, [], KeysToGet, _KeyPathAcc) ->
-    {[], KeysToGet};
-get_key_leafs_simple(Pos, [{Key, _Value, SubTree}=Tree | RestTree], KeysToGet, KeyPathAcc) ->
-    case lists:delete({Pos, Key}, KeysToGet) of
-    KeysToGet -> % same list, key not found
-        {LeafsFound, KeysToGet2} = get_key_leafs_simple(Pos + 1, SubTree, KeysToGet, [Key | KeyPathAcc]),
-        {RestLeafsFound, KeysRemaining} = get_key_leafs_simple(Pos, RestTree, KeysToGet2, KeyPathAcc),
-        {LeafsFound ++ RestLeafsFound, KeysRemaining};
-    KeysToGet2 ->
-        LeafsFound = get_all_leafs_simple(Pos, [Tree], KeyPathAcc),
-        LeafKeysFound = [{LeafPos, LeafRev} || {_, {LeafPos, [LeafRev|_]}}
-            <- LeafsFound],
-        KeysToGet3 = KeysToGet2 -- LeafKeysFound,
-        {RestLeafsFound, KeysRemaining} = get_key_leafs_simple(Pos, RestTree, KeysToGet3, KeyPathAcc),
-        {LeafsFound ++ RestLeafsFound, KeysRemaining}
-    end.
-
-get(Tree, KeysToGet) ->
-    {KeyPaths, KeysNotFound} = get_full_key_paths(Tree, KeysToGet),
-    FixedResults = [ {Value, {Pos, [Key0 || {Key0, _} <- Path]}} || {Pos, [{_Key, Value}|_]=Path} <- KeyPaths],
-    {FixedResults, KeysNotFound}.
-
-get_full_key_paths(Tree, Keys) ->
-    get_full_key_paths(Tree, Keys, []).
-
-get_full_key_paths(_, [], Acc) ->
-    {Acc, []};
-get_full_key_paths([], Keys, Acc) ->
-    {Acc, Keys};
-get_full_key_paths([{Pos, Tree}|Rest], Keys, Acc) ->
-    {Gotten, RemainingKeys} = get_full_key_paths(Pos, [Tree], Keys, []),
-    get_full_key_paths(Rest, RemainingKeys, Gotten ++ Acc).
-
-
-get_full_key_paths(_Pos, _Tree, [], _KeyPathAcc) ->
-    {[], []};
-get_full_key_paths(_Pos, [], KeysToGet, _KeyPathAcc) ->
-    {[], KeysToGet};
-get_full_key_paths(Pos, [{KeyId, Value, SubTree} | RestTree], KeysToGet, KeyPathAcc) ->
-    KeysToGet2 = KeysToGet -- [{Pos, KeyId}],
-    CurrentNodeResult =
-    case length(KeysToGet2) =:= length(KeysToGet) of
-    true -> % not in the key list.
-        [];
-    false -> % this node is the key list. return it
-        [{Pos, [{KeyId, Value} | KeyPathAcc]}]
-    end,
-    {KeysGotten, KeysRemaining} = get_full_key_paths(Pos + 1, SubTree, KeysToGet2, [{KeyId, Value} | KeyPathAcc]),
-    {KeysGotten2, KeysRemaining2} = get_full_key_paths(Pos, RestTree, KeysRemaining, KeyPathAcc),
-    {CurrentNodeResult ++ KeysGotten ++ KeysGotten2, KeysRemaining2}.
-
-get_all_leafs_full(Tree) ->
-    get_all_leafs_full(Tree, []).
-
-get_all_leafs_full([], Acc) ->
-    Acc;
-get_all_leafs_full([{Pos, Tree} | Rest], Acc) ->
-    get_all_leafs_full(Rest, get_all_leafs_full_simple(Pos, [Tree], []) ++ Acc).
-
-get_all_leafs_full_simple(_Pos, [], _KeyPathAcc) ->
-    [];
-get_all_leafs_full_simple(Pos, [{KeyId, Value, []} | RestTree], KeyPathAcc) ->
-    [{Pos, [{KeyId, Value} | KeyPathAcc]} | get_all_leafs_full_simple(Pos, RestTree, KeyPathAcc)];
-get_all_leafs_full_simple(Pos, [{KeyId, Value, SubTree} | RestTree], KeyPathAcc) ->
-    get_all_leafs_full_simple(Pos + 1, SubTree, [{KeyId, Value} | KeyPathAcc]) ++ get_all_leafs_full_simple(Pos, RestTree, KeyPathAcc).
-
-get_all_leafs(Trees) ->
-    get_all_leafs(Trees, []).
-
-get_all_leafs([], Acc) ->
-    Acc;
-get_all_leafs([{Pos, Tree}|Rest], Acc) ->
-    get_all_leafs(Rest, get_all_leafs_simple(Pos, [Tree], []) ++ Acc).
-
-get_all_leafs_simple(_Pos, [], _KeyPathAcc) ->
-    [];
-get_all_leafs_simple(Pos, [{KeyId, Value, []} | RestTree], KeyPathAcc) ->
-    [{Value, {Pos, [KeyId | KeyPathAcc]}} | get_all_leafs_simple(Pos, RestTree, KeyPathAcc)];
-get_all_leafs_simple(Pos, [{KeyId, _Value, SubTree} | RestTree], KeyPathAcc) ->
-    get_all_leafs_simple(Pos + 1, SubTree, [KeyId | KeyPathAcc]) ++ get_all_leafs_simple(Pos, RestTree, KeyPathAcc).
-
-
-count_leafs([]) ->
-    0;
-count_leafs([{_Pos,Tree}|Rest]) ->
-    count_leafs_simple([Tree]) + count_leafs(Rest).
-
-count_leafs_simple([]) ->
-    0;
-count_leafs_simple([{_Key, _Value, []} | RestTree]) ->
-    1 + count_leafs_simple(RestTree);
-count_leafs_simple([{_Key, _Value, SubTree} | RestTree]) ->
-    count_leafs_simple(SubTree) + count_leafs_simple(RestTree).
-
-
-fold(_Fun, Acc, []) ->
-    Acc;
-fold(Fun, Acc0, [{Pos, Tree}|Rest]) ->
-    Acc1 = fold_simple(Fun, Acc0, Pos, [Tree]),
-    fold(Fun, Acc1, Rest).
-
-fold_simple(_Fun, Acc, _Pos, []) ->
-    Acc;
-fold_simple(Fun, Acc0, Pos, [{Key, Value, SubTree} | RestTree]) ->
-    Type = if SubTree == [] -> leaf; true -> branch end,
-    Acc1 = Fun({Pos, Key}, Value, Type, Acc0),
-    Acc2 = fold_simple(Fun, Acc1, Pos+1, SubTree),
-    fold_simple(Fun, Acc2, Pos, RestTree).
-
-
-map(_Fun, []) ->
-    [];
-map(Fun, [{Pos, Tree}|Rest]) ->
-    case erlang:fun_info(Fun, arity) of
-    {arity, 2} ->
-        [NewTree] = map_simple(fun(A,B,_C) -> Fun(A,B) end, Pos, [Tree]),
-        [{Pos, NewTree} | map(Fun, Rest)];
-    {arity, 3} ->
-        [NewTree] = map_simple(Fun, Pos, [Tree]),
-        [{Pos, NewTree} | map(Fun, Rest)]
-    end.
-
-map_simple(_Fun, _Pos, []) ->
-    [];
-map_simple(Fun, Pos, [{Key, Value, SubTree} | RestTree]) ->
-    Value2 = Fun({Pos, Key}, Value,
-            if SubTree == [] -> leaf; true -> branch end),
-    [{Key, Value2, map_simple(Fun, Pos + 1, SubTree)} | map_simple(Fun, Pos, RestTree)].
-
-
-mapfold(_Fun, Acc, []) ->
-    {[], Acc};
-mapfold(Fun, Acc, [{Pos, Tree} | Rest]) ->
-    {[NewTree], Acc2} = mapfold_simple(Fun, Acc, Pos, [Tree]),
-    {Rest2, Acc3} = mapfold(Fun, Acc2, Rest),
-    {[{Pos, NewTree} | Rest2], Acc3}.
-
-mapfold_simple(_Fun, Acc, _Pos, []) ->
-    {[], Acc};
-mapfold_simple(Fun, Acc, Pos, [{Key, Value, SubTree} | RestTree]) ->
-    {Value2, Acc2} = Fun({Pos, Key}, Value,
-            if SubTree == [] -> leaf; true -> branch end, Acc),
-    {SubTree2, Acc3} = mapfold_simple(Fun, Acc2, Pos + 1, SubTree),
-    {RestTree2, Acc4} = mapfold_simple(Fun, Acc3, Pos, RestTree),
-    {[{Key, Value2, SubTree2} | RestTree2], Acc4}.
-
-
-map_leafs(_Fun, []) ->
-    [];
-map_leafs(Fun, [{Pos, Tree}|Rest]) ->
-    [NewTree] = map_leafs_simple(Fun, Pos, [Tree]),
-    [{Pos, NewTree} | map_leafs(Fun, Rest)].
-
-map_leafs_simple(_Fun, _Pos, []) ->
-    [];
-map_leafs_simple(Fun, Pos, [{Key, Value, []} | RestTree]) ->
-    Value2 = Fun({Pos, Key}, Value),
-    [{Key, Value2, []} | map_leafs_simple(Fun, Pos, RestTree)];
-map_leafs_simple(Fun, Pos, [{Key, Value, SubTree} | RestTree]) ->
-    [{Key, Value, map_leafs_simple(Fun, Pos + 1, SubTree)} | map_leafs_simple(Fun, Pos, RestTree)].
-
-
-stem(Trees, Limit) ->
-    % flatten each branch in a tree into a tree path, sort by starting rev #
-    Paths = lists:sort(lists:map(fun({Pos, Path}) ->
-        StemmedPath = lists:sublist(Path, Limit),
-        {Pos + 1 - length(StemmedPath), StemmedPath}
-    end, get_all_leafs_full(Trees))),
-
-    % convert paths back to trees
-    lists:foldl(
-        fun({StartPos, Path},TreeAcc) ->
-            [SingleTree] = lists:foldl(
-                fun({K,V},NewTreeAcc) -> [{K,V,NewTreeAcc}] end, [], Path),
-            {NewTrees, _} = merge(TreeAcc, {StartPos, SingleTree}),
-            NewTrees
-        end, [], Paths).
-
-
-value_pref(Tuple, _) when is_tuple(Tuple),
-        (tuple_size(Tuple) == 3 orelse tuple_size(Tuple) == 4) ->
-    Tuple;
-value_pref(_, Tuple) when is_tuple(Tuple),
-        (tuple_size(Tuple) == 3 orelse tuple_size(Tuple) == 4) ->
-    Tuple;
-value_pref(?REV_MISSING, Other) ->
-    Other;
-value_pref(Other, ?REV_MISSING) ->
-    Other;
-value_pref(Last, _) ->
-    Last.
-
-
-% Tests moved to test/etap/06?-*.t
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_log.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_log.erl b/apps/couch/src/couch_log.erl
deleted file mode 100644
index cd4bbbb..0000000
--- a/apps/couch/src/couch_log.erl
+++ /dev/null
@@ -1,254 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_log).
--behaviour(gen_event).
-
-% public API
--export([start_link/0, stop/0]).
--export([debug/2, info/2, warn/2, error/2]).
--export([debug_on/0, info_on/0, warn_on/0, get_level/0, get_level_integer/0, set_level/1]).
--export([debug_on/1, info_on/1, warn_on/1, get_level/1, get_level_integer/1, set_level/2]).
--export([read/2]).
-
-% gen_event callbacks
--export([init/1, handle_event/2, terminate/2, code_change/3]).
--export([handle_info/2, handle_call/2]).
-
--define(LEVEL_ERROR, 4).
--define(LEVEL_WARN, 3).
--define(LEVEL_INFO, 2).
--define(LEVEL_DEBUG, 1).
-
--record(state, {
-    fd,
-    level,
-    sasl
-}).
-
-debug(Format, Args) ->
-    {ConsoleMsg, FileMsg} = get_log_messages(self(), debug, Format, Args),
-    gen_event:sync_notify(error_logger, {couch_debug, ConsoleMsg, FileMsg}).
-
-info(Format, Args) ->
-    {ConsoleMsg, FileMsg} = get_log_messages(self(), info, Format, Args),
-    gen_event:sync_notify(error_logger, {couch_info, ConsoleMsg, FileMsg}).
-
-warn(Format, Args) ->
-    {ConsoleMsg, FileMsg} = get_log_messages(self(), warn, Format, Args),
-    gen_event:sync_notify(error_logger, {couch_warn, ConsoleMsg, FileMsg}).
-
-error(Format, Args) ->
-    {ConsoleMsg, FileMsg} = get_log_messages(self(), error, Format, Args),
-    gen_event:sync_notify(error_logger, {couch_error, ConsoleMsg, FileMsg}).
-
-
-level_integer(error)    -> ?LEVEL_ERROR;
-level_integer(warn)     -> ?LEVEL_WARN;
-level_integer(info)     -> ?LEVEL_INFO;
-level_integer(debug)    -> ?LEVEL_DEBUG;
-level_integer(_Else)    -> ?LEVEL_ERROR. % anything else default to ERROR level
-
-level_atom(?LEVEL_ERROR) -> error;
-level_atom(?LEVEL_WARN) -> warn;
-level_atom(?LEVEL_INFO) -> info;
-level_atom(?LEVEL_DEBUG) -> debug.
-
-
-start_link() ->
-    couch_event_sup:start_link({local, couch_log}, error_logger, couch_log, []).
-
-stop() ->
-    couch_event_sup:stop(couch_log).
-
-init([]) ->
-    % read config and register for configuration changes
-
-    % just stop if one of the config settings change. couch_server_sup
-    % will restart us and then we will pick up the new settings.
-    ok = couch_config:register(
-        fun("log", "file") ->
-            ?MODULE:stop();
-        ("log", "level") ->
-            ?MODULE:stop();
-        ("log", "include_sasl") ->
-            ?MODULE:stop();
-        ("log_level_by_module", _) ->
-            ?MODULE:stop()
-        end),
-
-    Filename = couch_config:get("log", "file", "couchdb.log"),
-    Level = level_integer(list_to_atom(couch_config:get("log", "level", "info"))),
-    Sasl = couch_config:get("log", "include_sasl", "true") =:= "true",
-    LevelByModule = couch_config:get("log_level_by_module"),
-
-    case ets:info(?MODULE) of
-    undefined -> ets:new(?MODULE, [named_table]);
-    _ -> ok
-    end,
-    ets:insert(?MODULE, {level, Level}),
-    lists:foreach(fun({Module, ModuleLevel}) ->
-        ModuleLevelInteger = level_integer(list_to_atom(ModuleLevel)),
-        ets:insert(?MODULE, {Module, ModuleLevelInteger})
-    end, LevelByModule),
-
-
-    case file:open(Filename, [append]) of
-    {ok, Fd} ->
-        {ok, #state{fd = Fd, level = Level, sasl = Sasl}};
-    {error, Reason} ->
-        ReasonStr = file:format_error(Reason),
-        io:format("Error opening log file ~s: ~s", [Filename, ReasonStr]),
-        {stop, {error, ReasonStr, Filename}}
-    end.
-
-debug_on() ->
-    get_level_integer() =< ?LEVEL_DEBUG.
-
-info_on() ->
-    get_level_integer() =< ?LEVEL_INFO.
-
-warn_on() ->
-    get_level_integer() =< ?LEVEL_WARN.
-
-debug_on(Module) ->
-    get_level_integer(Module) =< ?LEVEL_DEBUG.
-
-info_on(Module) ->
-    get_level_integer(Module) =< ?LEVEL_INFO.
-
-warn_on(Module) ->
-    get_level_integer(Module) =< ?LEVEL_WARN.
-
-set_level(LevelAtom) ->
-    set_level_integer(level_integer(LevelAtom)).
-
-set_level(Module, LevelAtom) ->
-    set_level_integer(Module, level_integer(LevelAtom)).
-
-get_level() ->
-    level_atom(get_level_integer()).
-
-get_level(Module) ->
-    level_atom(get_level_integer(Module)).
-
-get_level_integer() ->
-    try
-        ets:lookup_element(?MODULE, level, 2)
-    catch error:badarg ->
-        ?LEVEL_ERROR
-    end.
-
-get_level_integer(Module0) ->
-    Module = atom_to_list(Module0),
-    try
-        [{_Module, Level}] = ets:lookup(?MODULE, Module),
-        Level
-    catch error:_ ->
-        get_level_integer()
-    end.
-
-set_level_integer(Int) ->
-    gen_event:call(error_logger, couch_log, {set_level_integer, Int}).
-
-set_level_integer(Module, Int) ->
-    gen_event:call(error_logger, couch_log, {set_level_integer, Module, Int}).
-
-handle_event({couch_error, ConMsg, FileMsg}, State) ->
-    log(State, ConMsg, FileMsg),
-    {ok, State};
-handle_event({couch_warn, ConMsg, FileMsg}, State) ->
-    log(State, ConMsg, FileMsg),
-    {ok, State};
-handle_event({couch_info, ConMsg, FileMsg}, State) ->
-    log(State, ConMsg, FileMsg),
-    {ok, State};
-handle_event({couch_debug, ConMsg, FileMsg}, State) ->
-    log(State, ConMsg, FileMsg),
-    {ok, State};
-handle_event({error_report, _, {Pid, _, _}}=Event, #state{sasl = true} = St) ->
-    {ConMsg, FileMsg} = get_log_messages(Pid, error, "~p", [Event]),
-    log(St, ConMsg, FileMsg),
-    {ok, St};
-handle_event({error, _, {Pid, Format, Args}}, #state{sasl = true} = State) ->
-    {ConMsg, FileMsg} = get_log_messages(Pid, error, Format, Args),
-    log(State, ConMsg, FileMsg),
-    {ok, State};
-handle_event(_Event, State) ->
-    {ok, State}.
-
-handle_call({set_level_integer, NewLevel}, State) ->
-    ets:insert(?MODULE, {level, NewLevel}),
-    {ok, ok, State#state{level = NewLevel}};
-
-handle_call({set_level_integer, Module, NewLevel}, State) ->
-    ets:insert(?MODULE, {Module, NewLevel}),
-    {ok, ok, State#state{level = NewLevel}}.
-
-handle_info(_Info, State) ->
-    {ok, State}.
-
-code_change(_OldVsn, State, _Extra) ->
-    {ok, State}.
-
-terminate(_Arg, #state{fd = Fd}) ->
-    file:close(Fd).
-
-log(#state{fd = Fd}, ConsoleMsg, FileMsg) ->
-    ok = io:put_chars(ConsoleMsg),
-    ok = io:put_chars(Fd, FileMsg).
-
-get_log_messages(Pid, Level, Format, Args) ->
-    ConsoleMsg = unicode:characters_to_binary(io_lib:format(
-        "[~s] [~p] " ++ Format ++ "~n", [Level, Pid | Args])),
-    FileMsg = ["[", couch_util:rfc1123_date(), "] ", ConsoleMsg],
-    {ConsoleMsg, iolist_to_binary(FileMsg)}.
-
-
-% Read Bytes bytes from the end of log file, jumping Offset bytes towards
-% the beginning of the file first.
-%
-%  Log File    FilePos
-%  ----------
-% |          |  10
-% |          |  20
-% |          |  30
-% |          |  40
-% |          |  50
-% |          |  60
-% |          |  70 -- Bytes = 20  --
-% |          |  80                 | Chunk
-% |          |  90 -- Offset = 10 --
-% |__________| 100
-
-read(Bytes, Offset) ->
-    LogFileName = couch_config:get("log", "file"),
-    LogFileSize = filelib:file_size(LogFileName),
-    MaxChunkSize = list_to_integer(
-        couch_config:get("httpd", "log_max_chunk_size", "1000000")),
-    case Bytes > MaxChunkSize of
-    true ->
-        throw({bad_request, "'bytes' cannot exceed " ++
-            integer_to_list(MaxChunkSize)});
-    false ->
-        ok
-    end,
-
-    {ok, Fd} = file:open(LogFileName, [read]),
-    Start = lists:max([LogFileSize - Bytes - Offset, 0]),
-
-    % TODO: truncate chopped first line
-    % TODO: make streaming
-
-    {ok, Chunk} = file:pread(Fd, Start, Bytes),
-    ok = file:close(Fd),
-    Chunk.


[30/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/css/nv.d3.css
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/css/nv.d3.css b/apps/fauxton/assets/css/nv.d3.css
deleted file mode 100644
index 28ccd05..0000000
--- a/apps/fauxton/assets/css/nv.d3.css
+++ /dev/null
@@ -1,656 +0,0 @@
-
-/********************
- * HTML CSS
- */
-
-
-.chartWrap {
-  margin: 0;
-  padding: 0;
-  overflow: hidden;
-}
-
-
-/********************
- * TOOLTIP CSS
- */
-
-.nvtooltip {
-  position: absolute;
-  background-color: rgba(255,255,255,1);
-  padding: 10px;
-  border: 1px solid #ddd;
-  z-index: 10000;
-
-  font-family: Arial;
-  font-size: 13px;
-
-  transition: opacity 500ms linear;
-  -moz-transition: opacity 500ms linear;
-  -webkit-transition: opacity 500ms linear;
-
-  transition-delay: 500ms;
-  -moz-transition-delay: 500ms;
-  -webkit-transition-delay: 500ms;
-
-  -moz-box-shadow: 4px 4px 8px rgba(0,0,0,.5);
-  -webkit-box-shadow: 4px 4px 8px rgba(0,0,0,.5);
-  box-shadow: 4px 4px 8px rgba(0,0,0,.5);
-
-  -moz-border-radius: 10px;
-  border-radius: 10px;
-
-  pointer-events: none;
-
-  -webkit-touch-callout: none;
-  -webkit-user-select: none;
-  -khtml-user-select: none;
-  -moz-user-select: none;
-  -ms-user-select: none;
-  user-select: none;
-}
-
-.nvtooltip h3 {
-  margin: 0;
-  padding: 0;
-  text-align: center;
-}
-
-.nvtooltip p {
-  margin: 0;
-  padding: 0;
-  text-align: center;
-}
-
-.nvtooltip span {
-  display: inline-block;
-  margin: 2px 0;
-}
-
-.nvtooltip-pending-removal {
-  position: absolute;
-  pointer-events: none;
-}
-
-
-/********************
- * SVG CSS
- */
-
-
-svg {
-  -webkit-touch-callout: none;
-  -webkit-user-select: none;
-  -khtml-user-select: none;
-  -moz-user-select: none;
-  -ms-user-select: none;
-  user-select: none;
-  /* Trying to get SVG to act like a greedy block in all browsers */
-  display: block;
-  width:100%;
-  height:100%;
-}
-
-
-svg text {
-  font: normal 12px Arial;
-}
-
-svg .title {
- font: bold 14px Arial;
-}
-
-.nvd3 .nv-background {
-  fill: white;
-  fill-opacity: 0;
-  /*
-  pointer-events: none;
-  */
-}
-
-.nvd3.nv-noData {
-  font-size: 18px;
-  font-weight: bolf;
-}
-
-
-/**********
-*  Brush
-*/
-
-.nv-brush .extent {
-  fill-opacity: .125;
-  shape-rendering: crispEdges;
-}
-
-
-
-/**********
-*  Legend
-*/
-
-.nvd3 .nv-legend .nv-series {
-  cursor: pointer;
-}
-
-.nvd3 .nv-legend .disabled circle {
-  fill-opacity: 0;
-}
-
-
-
-/**********
-*  Axes
-*/
-
-.nvd3 .nv-axis path {
-  fill: none;
-  stroke: #000;
-  stroke-opacity: .75;
-  shape-rendering: crispEdges;
-}
-
-.nvd3 .nv-axis path.domain {
-  stroke-opacity: .75;
-}
-
-.nvd3 .nv-axis.nv-x path.domain {
-  stroke-opacity: 0;
-}
-
-.nvd3 .nv-axis line {
-  fill: none;
-  stroke: #000;
-  stroke-opacity: .25;
-  shape-rendering: crispEdges;
-}
-
-.nvd3 .nv-axis line.zero {
-  stroke-opacity: .75;
-}
-
-.nvd3 .nv-axis .nv-axisMaxMin text {
-  font-weight: bold;
-}
-
-.nvd3 .x  .nv-axis .nv-axisMaxMin text,
-.nvd3 .x2 .nv-axis .nv-axisMaxMin text,
-.nvd3 .x3 .nv-axis .nv-axisMaxMin text {
-  text-anchor: middle
-}
-
-
-
-/**********
-*  Brush
-*/
-
-.nv-brush .resize path {
-  fill: #eee;
-  stroke: #666;
-}
-
-
-
-/**********
-*  Bars
-*/
-
-.nvd3 .nv-bars .negative rect {
-    zfill: brown;
-}
-
-.nvd3 .nv-bars rect {
-  zfill: steelblue;
-  fill-opacity: .75;
-
-  transition: fill-opacity 250ms linear;
-  -moz-transition: fill-opacity 250ms linear;
-  -webkit-transition: fill-opacity 250ms linear;
-}
-
-.nvd3 .nv-bars rect:hover {
-  fill-opacity: 1;
-}
-
-.nvd3 .nv-bars .hover rect {
-  fill: lightblue;
-}
-
-.nvd3 .nv-bars text {
-  fill: rgba(0,0,0,0);
-}
-
-.nvd3 .nv-bars .hover text {
-  fill: rgba(0,0,0,1);
-}
-
-
-/**********
-*  Bars
-*/
-
-.nvd3 .nv-multibar .nv-groups rect,
-.nvd3 .nv-multibarHorizontal .nv-groups rect,
-.nvd3 .nv-discretebar .nv-groups rect {
-  stroke-opacity: 0;
-
-  transition: fill-opacity 250ms linear;
-  -moz-transition: fill-opacity 250ms linear;
-  -webkit-transition: fill-opacity 250ms linear;
-}
-
-.nvd3 .nv-multibar .nv-groups rect:hover,
-.nvd3 .nv-multibarHorizontal .nv-groups rect:hover,
-.nvd3 .nv-discretebar .nv-groups rect:hover {
-  fill-opacity: 1;
-}
-
-.nvd3 .nv-discretebar .nv-groups text,
-.nvd3 .nv-multibarHorizontal .nv-groups text {
-  font-weight: bold;
-  fill: rgba(0,0,0,1);
-  stroke: rgba(0,0,0,0);
-}
-
-/***********
-*  Pie Chart
-*/
-
-.nvd3.nv-pie path {
-  stroke-opacity: 0;
-
-  transition: fill-opacity 250ms linear, stroke-width 250ms linear, stroke-opacity 250ms linear;
-  -moz-transition: fill-opacity 250ms linear, stroke-width 250ms linear, stroke-opacity 250ms linear;
-  -webkit-transition: fill-opacity 250ms linear, stroke-width 250ms linear, stroke-opacity 250ms linear;
-
-}
-
-.nvd3.nv-pie .nv-slice text {
-  stroke: #000;
-  stroke-width: 0;
-}
-
-.nvd3.nv-pie path {
-  stroke: #fff;
-  stroke-width: 1px;
-  stroke-opacity: 1;
-}
-
-.nvd3.nv-pie .hover path {
-  fill-opacity: .7;
-/*
-  stroke-width: 6px;
-  stroke-opacity: 1;
-*/
-}
-
-.nvd3.nv-pie .nv-label rect {
-  fill-opacity: 0;
-  stroke-opacity: 0;
-}
-
-/**********
-* Lines
-*/
-
-.nvd3 .nv-groups path.nv-line {
-  fill: none;
-  stroke-width: 2.5px;
-  /*
-  stroke-linecap: round;
-  shape-rendering: geometricPrecision;
-
-  transition: stroke-width 250ms linear;
-  -moz-transition: stroke-width 250ms linear;
-  -webkit-transition: stroke-width 250ms linear;
-
-  transition-delay: 250ms
-  -moz-transition-delay: 250ms;
-  -webkit-transition-delay: 250ms;
-  */
-}
-
-.nvd3 .nv-groups path.nv-area {
-  stroke: none;
-  /*
-  stroke-linecap: round;
-  shape-rendering: geometricPrecision;
-
-  stroke-width: 2.5px;
-  transition: stroke-width 250ms linear;
-  -moz-transition: stroke-width 250ms linear;
-  -webkit-transition: stroke-width 250ms linear;
-
-  transition-delay: 250ms
-  -moz-transition-delay: 250ms;
-  -webkit-transition-delay: 250ms;
-  */
-}
-
-.nvd3 .nv-line.hover path {
-  stroke-width: 6px;
-}
-
-/*
-.nvd3.scatter .groups .point {
-  fill-opacity: 0.1;
-  stroke-opacity: 0.1;
-}
-  */
-
-.nvd3.nv-line .nvd3.nv-scatter .nv-groups .nv-point {
-  fill-opacity: 0;
-  stroke-opacity: 0;
-}
-
-.nvd3.nv-scatter.nv-single-point .nv-groups .nv-point {
-  fill-opacity: .5 !important;
-  stroke-opacity: .5 !important;
-}
-
-
-.nvd3 .nv-groups .nv-point {
-  transition: stroke-width 250ms linear, stroke-opacity 250ms linear;
-  -moz-transition: stroke-width 250ms linear, stroke-opacity 250ms linear;
-  -webkit-transition: stroke-width 250ms linear, stroke-opacity 250ms linear;
-}
-
-.nvd3.nv-scatter .nv-groups .nv-point.hover,
-.nvd3 .nv-groups .nv-point.hover {
-  stroke-width: 20px;
-  fill-opacity: .5 !important;
-  stroke-opacity: .5 !important;
-}
-
-
-.nvd3 .nv-point-paths path {
-  stroke: #aaa;
-  stroke-opacity: 0;
-  fill: #eee;
-  fill-opacity: 0;
-}
-
-
-
-.nvd3 .nv-indexLine {
-  cursor: ew-resize;
-}
-
-
-/**********
-* Distribution
-*/
-
-.nvd3 .nv-distribution {
-  pointer-events: none;
-}
-
-
-
-/**********
-*  Scatter
-*/
-
-/* **Attempting to remove this for useVoronoi(false), need to see if it's required anywhere
-.nvd3 .nv-groups .nv-point {
-  pointer-events: none;
-}
-*/
-
-.nvd3 .nv-groups .nv-point.hover {
-  stroke-width: 20px;
-  stroke-opacity: .5;
-}
-
-.nvd3 .nv-scatter .nv-point.hover {
-  fill-opacity: 1;
-}
-
-/*
-.nv-group.hover .nv-point {
-  fill-opacity: 1;
-}
-*/
-
-
-/**********
-*  Stacked Area
-*/
-
-.nvd3.nv-stackedarea path.nv-area {
-  fill-opacity: .7;
-  /*
-  stroke-opacity: .65;
-  fill-opacity: 1;
-  */
-  stroke-opacity: 0;
-
-  transition: fill-opacity 250ms linear, stroke-opacity 250ms linear;
-  -moz-transition: fill-opacity 250ms linear, stroke-opacity 250ms linear;
-  -webkit-transition: fill-opacity 250ms linear, stroke-opacity 250ms linear;
-
-  /*
-  transition-delay: 500ms;
-  -moz-transition-delay: 500ms;
-  -webkit-transition-delay: 500ms;
-  */
-
-}
-
-.nvd3.nv-stackedarea path.nv-area.hover {
-  fill-opacity: .9;
-  /*
-  stroke-opacity: .85;
-  */
-}
-/*
-.d3stackedarea .groups path {
-  stroke-opacity: 0;
-}
-  */
-
-
-
-.nvd3.nv-stackedarea .nv-groups .nv-point {
-  stroke-opacity: 0;
-  fill-opacity: 0;
-}
-
-.nvd3.nv-stackedarea .nv-groups .nv-point.hover {
-  stroke-width: 20px;
-  stroke-opacity: .75;
-  fill-opacity: 1;
-}
-
-
-
-/**********
-*  Line Plus Bar
-*/
-
-.nvd3.nv-linePlusBar .nv-bar rect {
-  fill-opacity: .75;
-}
-
-.nvd3.nv-linePlusBar .nv-bar rect:hover {
-  fill-opacity: 1;
-}
-
-
-/**********
-*  Bullet
-*/
-
-.nvd3.nv-bullet { font: 10px sans-serif; }
-.nvd3.nv-bullet .nv-measure { fill-opacity: .8; }
-.nvd3.nv-bullet .nv-measure:hover { fill-opacity: 1; }
-.nvd3.nv-bullet .nv-marker { stroke: #000; stroke-width: 2px; }
-.nvd3.nv-bullet .nv-markerTriangle { stroke: #000; fill: #fff; stroke-width: 1.5px; }
-.nvd3.nv-bullet .nv-tick line { stroke: #666; stroke-width: .5px; }
-.nvd3.nv-bullet .nv-range.nv-s0 { fill: #eee; }
-.nvd3.nv-bullet .nv-range.nv-s1 { fill: #ddd; }
-.nvd3.nv-bullet .nv-range.nv-s2 { fill: #ccc; }
-.nvd3.nv-bullet .nv-title { font-size: 14px; font-weight: bold; }
-.nvd3.nv-bullet .nv-subtitle { fill: #999; }
-
-
-.nvd3.nv-bullet .nv-range {
-  fill: #999;
-  fill-opacity: .4;
-}
-.nvd3.nv-bullet .nv-range:hover {
-  fill-opacity: .7;
-}
-
-
-
-/**********
-* Sparkline
-*/
-
-.nvd3.nv-sparkline path {
-  fill: none;
-}
-
-.nvd3.nv-sparklineplus g.nv-hoverValue {
-  pointer-events: none;
-}
-
-.nvd3.nv-sparklineplus .nv-hoverValue line {
-  stroke: #333;
-  stroke-width: 1.5px;
- }
-
-.nvd3.nv-sparklineplus,
-.nvd3.nv-sparklineplus g {
-  pointer-events: all;
-}
-
-.nvd3 .nv-hoverArea {
-  fill-opacity: 0;
-  stroke-opacity: 0;
-}
-
-.nvd3.nv-sparklineplus .nv-xValue,
-.nvd3.nv-sparklineplus .nv-yValue {
-  /*
-  stroke: #666;
-  */
-  stroke-width: 0;
-  font-size: .9em;
-  font-weight: normal;
-}
-
-.nvd3.nv-sparklineplus .nv-yValue {
-  stroke: #f66;
-}
-
-.nvd3.nv-sparklineplus .nv-maxValue {
-  stroke: #2ca02c;
-  fill: #2ca02c;
-}
-
-.nvd3.nv-sparklineplus .nv-minValue {
-  stroke: #d62728;
-  fill: #d62728;
-}
-
-.nvd3.nv-sparklineplus .nv-currentValue {
-  /*
-  stroke: #444;
-  fill: #000;
-  */
-  font-weight: bold;
-  font-size: 1.1em;
-}
-
-/**********
-* historical stock
-*/
-
-.nvd3.nv-ohlcBar .nv-ticks .nv-tick {
-  stroke-width: 2px;
-}
-
-.nvd3.nv-ohlcBar .nv-ticks .nv-tick.hover {
-  stroke-width: 4px;
-}
-
-.nvd3.nv-ohlcBar .nv-ticks .nv-tick.positive {
- stroke: #2ca02c;
-}
-
-.nvd3.nv-ohlcBar .nv-ticks .nv-tick.negative {
- stroke: #d62728;
-}
-
-.nvd3.nv-historicalStockChart .nv-axis .nv-axislabel {
-  font-weight: bold;
-}
-
-.nvd3.nv-historicalStockChart .nv-dragTarget {
-  fill-opacity: 0;
-  stroke: none;
-  cursor: move;
-}
-
-.nvd3 .nv-brush .extent {
-  /*
-  cursor: ew-resize !important;
-  */
-  fill-opacity: 0 !important;
-}
-
-.nvd3 .nv-brushBackground rect {
-  stroke: #000;
-  stroke-width: .4;
-  fill: #fff;
-  fill-opacity: .7;
-}
-
-
-
-/**********
-* Indented Tree
-*/
-
-
-/**
- * TODO: the following 3 selectors are based on classes used in the example.  I should either make them standard and leave them here, or move to a CSS file not included in the library
- */
-.nvd3.nv-indentedtree .name {
-  margin-left: 5px;
-}
-
-.nvd3.nv-indentedtree .clickable {
-  color: #08C;
-  cursor: pointer;
-}
-
-.nvd3.nv-indentedtree span.clickable:hover {
-  color: #005580;
-  text-decoration: underline;
-}
-
-
-.nvd3.nv-indentedtree .nv-childrenCount {
-  display: inline-block;
-  margin-left: 5px;
-}
-
-.nvd3.nv-indentedtree .nv-treeicon {
-  cursor: pointer;
-  /*
-  cursor: n-resize;
-  */
-}
-
-.nvd3.nv-indentedtree .nv-treeicon.nv-folded {
-  cursor: pointer;
-  /*
-  cursor: s-resize;
-  */
-}
-
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/img/FontAwesome.otf
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/img/FontAwesome.otf b/apps/fauxton/assets/img/FontAwesome.otf
deleted file mode 100644
index 7012545..0000000
Binary files a/apps/fauxton/assets/img/FontAwesome.otf and /dev/null differ

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/img/couchdb-site.png
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/img/couchdb-site.png b/apps/fauxton/assets/img/couchdb-site.png
deleted file mode 100644
index a9b3a99..0000000
Binary files a/apps/fauxton/assets/img/couchdb-site.png and /dev/null differ

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/img/couchdblogo.png
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/img/couchdblogo.png b/apps/fauxton/assets/img/couchdblogo.png
deleted file mode 100644
index cbe991c..0000000
Binary files a/apps/fauxton/assets/img/couchdblogo.png and /dev/null differ

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/img/fontawesome-webfont.eot
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/img/fontawesome-webfont.eot b/apps/fauxton/assets/img/fontawesome-webfont.eot
deleted file mode 100755
index 0662cb9..0000000
Binary files a/apps/fauxton/assets/img/fontawesome-webfont.eot and /dev/null differ


[66/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/udata.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/udata.h b/src/apps/couch_collate/platform/osx/icu/unicode/udata.h
new file mode 100644
index 0000000..84046d5
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/udata.h
@@ -0,0 +1,389 @@
+/*
+******************************************************************************
+*
+*   Copyright (C) 1999-2008, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+*
+******************************************************************************
+*   file name:  udata.h
+*   encoding:   US-ASCII
+*   tab size:   8 (not used)
+*   indentation:4
+*
+*   created on: 1999oct25
+*   created by: Markus W. Scherer
+*/
+
+#ifndef __UDATA_H__
+#define __UDATA_H__
+
+#include "unicode/utypes.h"
+
+U_CDECL_BEGIN
+
+/**
+ * \file
+ * \brief C API: Data loading interface
+ *
+ * <h2>Information about data loading interface</h2>
+ *
+ * This API is used to find and efficiently load data for ICU and applications
+ * using ICU. It provides an abstract interface that specifies a data type and
+ * name to find and load the data. Normally this API is used by other ICU APIs
+ * to load required data out of the ICU data library, but it can be used to
+ * load data out of other places.
+ *
+ * See the User Guide Data Management chapter.
+ */
+ 
+#ifndef U_HIDE_INTERNAL_API
+/**
+ * Character used to separate package names from tree names 
+ * @internal ICU 3.0
+ */
+#define U_TREE_SEPARATOR '-'
+
+/**
+ * String used to separate package names from tree names 
+ * @internal ICU 3.0
+ */
+#define U_TREE_SEPARATOR_STRING "-"
+
+/**
+ * Character used to separate parts of entry names
+ * @internal ICU 3.0
+ */
+#define U_TREE_ENTRY_SEP_CHAR '/'
+
+/**
+ * String used to separate parts of entry names
+ * @internal ICU 3.0
+ */
+#define U_TREE_ENTRY_SEP_STRING "/"
+
+/**
+ * Alias for standard ICU data 
+ * @internal ICU 3.0
+ */
+#define U_ICUDATA_ALIAS "ICUDATA"
+
+#endif /* U_HIDE_INTERNAL_API */
+
+/**
+ * UDataInfo contains the properties about the requested data.
+ * This is meta data.
+ *
+ * <p>This structure may grow in the future, indicated by the
+ * <code>size</code> field.</p>
+ *
+ * <p>The platform data property fields help determine if a data
+ * file can be efficiently used on a given machine.
+ * The particular fields are of importance only if the data
+ * is affected by the properties - if there is integer data
+ * with word sizes > 1 byte, char* text, or UChar* text.</p>
+ *
+ * <p>The implementation for the <code>udata_open[Choice]()</code>
+ * functions may reject data based on the value in <code>isBigEndian</code>.
+ * No other field is used by the <code>udata</code> API implementation.</p>
+ *
+ * <p>The <code>dataFormat</code> may be used to identify
+ * the kind of data, e.g. a converter table.</p>
+ *
+ * <p>The <code>formatVersion</code> field should be used to
+ * make sure that the format can be interpreted.
+ * I may be a good idea to check only for the one or two highest
+ * of the version elements to allow the data memory to
+ * get more or somewhat rearranged contents, for as long
+ * as the using code can still interpret the older contents.</p>
+ *
+ * <p>The <code>dataVersion</code> field is intended to be a
+ * common place to store the source version of the data;
+ * for data from the Unicode character database, this could
+ * reflect the Unicode version.</p>
+ * @stable ICU 2.0
+ */
+typedef struct {
+    /** sizeof(UDataInfo)
+     *  @stable ICU 2.0 */
+    uint16_t size;
+
+    /** unused, set to 0 
+     *  @stable ICU 2.0*/
+    uint16_t reservedWord;
+
+    /* platform data properties */
+    /** 0 for little-endian machine, 1 for big-endian
+     *  @stable ICU 2.0 */
+    uint8_t isBigEndian;
+
+    /** see U_CHARSET_FAMILY values in utypes.h 
+     *  @stable ICU 2.0*/
+    uint8_t charsetFamily;
+
+    /** sizeof(UChar), one of { 1, 2, 4 } 
+     *  @stable ICU 2.0*/
+    uint8_t sizeofUChar;
+
+    /** unused, set to 0 
+     *  @stable ICU 2.0*/
+    uint8_t reservedByte;
+
+    /** data format identifier 
+     *  @stable ICU 2.0*/
+    uint8_t dataFormat[4];
+
+    /** versions: [0] major [1] minor [2] milli [3] micro 
+     *  @stable ICU 2.0*/
+    uint8_t formatVersion[4];
+
+    /** versions: [0] major [1] minor [2] milli [3] micro 
+     *  @stable ICU 2.0*/
+    uint8_t dataVersion[4];
+} UDataInfo;
+
+/* API for reading data -----------------------------------------------------*/
+
+/**
+ * Forward declaration of the data memory type.
+ * @stable ICU 2.0
+ */
+typedef struct UDataMemory UDataMemory;
+
+/**
+ * Callback function for udata_openChoice().
+ * @param context parameter passed into <code>udata_openChoice()</code>.
+ * @param type The type of the data as passed into <code>udata_openChoice()</code>.
+ *             It may be <code>NULL</code>.
+ * @param name The name of the data as passed into <code>udata_openChoice()</code>.
+ * @param pInfo A pointer to the <code>UDataInfo</code> structure
+ *              of data that has been loaded and will be returned
+ *              by <code>udata_openChoice()</code> if this function
+ *              returns <code>TRUE</code>.
+ * @return TRUE if the current data memory is acceptable
+ * @stable ICU 2.0
+ */
+typedef UBool U_CALLCONV
+UDataMemoryIsAcceptable(void *context,
+                        const char *type, const char *name,
+                        const UDataInfo *pInfo);
+
+
+/**
+ * Convenience function.
+ * This function works the same as <code>udata_openChoice</code>
+ * except that any data that matches the type and name
+ * is assumed to be acceptable.
+ * @param path Specifies an absolute path and/or a basename for the
+ *             finding of the data in the file system.
+ *             <code>NULL</code> for ICU data.
+ * @param type A string that specifies the type of data to be loaded.
+ *             For example, resource bundles are loaded with type "res",
+ *             conversion tables with type "cnv".
+ *             This may be <code>NULL</code> or empty.
+ * @param name A string that specifies the name of the data.
+ * @param pErrorCode An ICU UErrorCode parameter. It must not be <code>NULL</code>.
+ * @return A pointer (handle) to a data memory object, or <code>NULL</code>
+ *         if an error occurs. Call <code>udata_getMemory()</code>
+ *         to get a pointer to the actual data.
+ *
+ * @see udata_openChoice
+ * @stable ICU 2.0
+ */
+U_STABLE UDataMemory * U_EXPORT2
+udata_open(const char *path, const char *type, const char *name,
+           UErrorCode *pErrorCode);
+
+/**
+ * Data loading function.
+ * This function is used to find and load efficiently data for
+ * ICU and applications using ICU.
+ * It provides an abstract interface that allows to specify a data
+ * type and name to find and load the data.
+ *
+ * <p>The implementation depends on platform properties and user preferences
+ * and may involve loading shared libraries (DLLs), mapping
+ * files into memory, or fopen()/fread() files.
+ * It may also involve using static memory or database queries etc.
+ * Several or all data items may be combined into one entity
+ * (DLL, memory-mappable file).</p>
+ *
+ * <p>The data is always preceded by a header that includes
+ * a <code>UDataInfo</code> structure.
+ * The caller's <code>isAcceptable()</code> function is called to make
+ * sure that the data is useful. It may be called several times if it
+ * rejects the data and there is more than one location with data
+ * matching the type and name.</p>
+ *
+ * <p>If <code>path==NULL</code>, then ICU data is loaded.
+ * Otherwise, it is separated into a basename and a basename-less directory string.
+ * The basename is used as the data package name, and the directory is
+ * logically prepended to the ICU data directory string.</p>
+ *
+ * <p>For details about ICU data loading see the User Guide
+ * Data Management chapter. (http://icu-project.org/userguide/icudata.html)</p>
+ *
+ * @param path Specifies an absolute path and/or a basename for the
+ *             finding of the data in the file system.
+ *             <code>NULL</code> for ICU data.
+ * @param type A string that specifies the type of data to be loaded.
+ *             For example, resource bundles are loaded with type "res",
+ *             conversion tables with type "cnv".
+ *             This may be <code>NULL</code> or empty.
+ * @param name A string that specifies the name of the data.
+ * @param isAcceptable This function is called to verify that loaded data
+ *                     is useful for the client code. If it returns FALSE
+ *                     for all data items, then <code>udata_openChoice()</code>
+ *                     will return with an error.
+ * @param context Arbitrary parameter to be passed into isAcceptable.
+ * @param pErrorCode An ICU UErrorCode parameter. It must not be <code>NULL</code>.
+ * @return A pointer (handle) to a data memory object, or <code>NULL</code>
+ *         if an error occurs. Call <code>udata_getMemory()</code>
+ *         to get a pointer to the actual data.
+ * @stable ICU 2.0
+ */
+U_STABLE UDataMemory * U_EXPORT2
+udata_openChoice(const char *path, const char *type, const char *name,
+                 UDataMemoryIsAcceptable *isAcceptable, void *context,
+                 UErrorCode *pErrorCode);
+
+/**
+ * Close the data memory.
+ * This function must be called to allow the system to
+ * release resources associated with this data memory.
+ * @param pData The pointer to data memory object
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2
+udata_close(UDataMemory *pData);
+
+/**
+ * Get the pointer to the actual data inside the data memory.
+ * The data is read-only.
+ * @param pData The pointer to data memory object
+ * @stable ICU 2.0
+ */
+U_STABLE const void * U_EXPORT2
+udata_getMemory(UDataMemory *pData);
+
+/**
+ * Get the information from the data memory header.
+ * This allows to get access to the header containing
+ * platform data properties etc. which is not part of
+ * the data itself and can therefore not be accessed
+ * via the pointer that <code>udata_getMemory()</code> returns.
+ *
+ * @param pData pointer to the data memory object
+ * @param pInfo pointer to a UDataInfo object;
+ *              its <code>size</code> field must be set correctly,
+ *              typically to <code>sizeof(UDataInfo)</code>.
+ *
+ * <code>*pInfo</code> will be filled with the UDataInfo structure
+ * in the data memory object. If this structure is smaller than
+ * <code>pInfo->size</code>, then the <code>size</code> will be
+ * adjusted and only part of the structure will be filled.
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2
+udata_getInfo(UDataMemory *pData, UDataInfo *pInfo);
+
+/**
+ * This function bypasses the normal ICU data loading process and
+ * allows you to force ICU's system data to come out of a user-specified
+ * area in memory.
+ *
+ * The format of this data is that of the icu common data file, as is
+ * generated by the pkgdata tool with mode=common or mode=dll.
+ * You can read in a whole common mode file and pass the address to the start of the
+ * data, or (with the appropriate link options) pass in the pointer to
+ * the data that has been loaded from a dll by the operating system,
+ * as shown in this code:
+ *
+ *       extern const  char U_IMPORT U_ICUDATA_ENTRY_POINT []; 
+ *        // U_ICUDATA_ENTRY_POINT is same as entry point specified to pkgdata tool
+ *       UErrorCode  status = U_ZERO_ERROR;
+ *
+ *       udata_setCommonData(&U_ICUDATA_ENTRY_POINT, &status);
+ *
+ * Warning: ICU must NOT have even attempted to access its data yet
+ * when this call is made, or U_USING_DEFAULT_WARNING code will
+ * be returned. Be careful of UnicodeStrings in static initialization which
+ * may attempt to load a converter (use the UNICODE_STRING(x) macro instead).
+ *
+ * Also note that it is important that the declaration be as above. The entry point
+ * must not be declared as an extern void*.
+ *
+ * This function has no effect on application (non ICU) data.  See udata_setAppData()
+ * for similar functionality for application data.
+ *
+ * @param data pointer to ICU common data
+ * @param err outgoing error status <code>U_USING_DEFAULT_WARNING, U_UNSUPPORTED_ERROR</code>
+ * @stable ICU 2.0
+ */
+
+U_STABLE void U_EXPORT2
+udata_setCommonData(const void *data, UErrorCode *err);
+
+
+/**
+ * This function bypasses the normal ICU data loading process for application-specific
+ * data and allows you to force the it to come out of a user-specified
+ * pointer.
+ *
+ * The format of this data is that of the icu common data file, like 'icudt26l.dat'
+ * or the corresponding shared library (DLL) file.
+ * The application must read in or otherwise construct an image of the data and then
+ * pass the address of it to this function.
+ *
+ *
+ * Warning:  setAppData will set a U_USING_DEFAULT_WARNING code if
+ *           data with the specifed path that has already been opened, or
+ *           if setAppData with the same path has already been called.
+ *           Any such calls to setAppData will have no effect.
+ *
+ *
+ * @param packageName the package name by which the application will refer
+ *             to (open) this data
+ * @param data pointer to the data
+ * @param err outgoing error status <code>U_USING_DEFAULT_WARNING, U_UNSUPPORTED_ERROR</code>
+ * @see udata_setCommonData
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2
+udata_setAppData(const char *packageName, const void *data, UErrorCode *err);
+
+/**
+ * Possible settings for udata_setFileAccess()
+ * @see udata_setFileAccess
+ * @stable ICU 3.4
+ */
+typedef enum UDataFileAccess {
+    /** ICU looks for data in single files first, then in packages. (default) */
+    UDATA_FILES_FIRST,
+    /** ICU only loads data from packages, not from single files. */
+    UDATA_ONLY_PACKAGES,
+    /** ICU loads data from packages first, and only from single files
+        if the data cannot be found in a package. */
+    UDATA_PACKAGES_FIRST,
+    /** ICU does not access the file system for data loading. */
+    UDATA_NO_FILES,
+    /** An alias for the default access mode. */
+    UDATA_DEFAULT_ACCESS = UDATA_FILES_FIRST,
+    UDATA_FILE_ACCESS_COUNT
+} UDataFileAccess;
+
+/**
+ * This function may be called to control how ICU loads data. It must be called
+ * before any ICU data is loaded, including application data loaded with ures/ResourceBundle or
+ * udata APIs. It should be called before u_init.  This function is not multithread safe.  
+ * The results of calling it while other threads are loading data are undefined.
+ * @param access The type of file access to be used
+ * @param status Error code.
+ * @see UDataFileAccess
+ * @stable ICU 3.4 
+ */
+U_STABLE void U_EXPORT2
+udata_setFileAccess(UDataFileAccess access, UErrorCode *status);
+
+U_CDECL_END
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/udatpg.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/udatpg.h b/src/apps/couch_collate/platform/osx/icu/unicode/udatpg.h
new file mode 100644
index 0000000..206637f
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/udatpg.h
@@ -0,0 +1,471 @@
+/*
+*******************************************************************************
+*
+*   Copyright (C) 2007-2008, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+*
+*******************************************************************************
+*   file name:  udatpg.h
+*   encoding:   US-ASCII
+*   tab size:   8 (not used)
+*   indentation:4
+*
+*   created on: 2007jul30
+*   created by: Markus W. Scherer
+*/
+
+#ifndef __UDATPG_H__
+#define __UDATPG_H__
+
+#include "unicode/utypes.h"
+#include "unicode/uenum.h"
+
+/**
+ * \file
+ * \brief C API: Wrapper for DateTimePatternGenerator (unicode/dtptngen.h).
+ *
+ * UDateTimePatternGenerator provides flexible generation of date format patterns, 
+ * like "yy-MM-dd". The user can build up the generator by adding successive 
+ * patterns. Once that is done, a query can be made using a "skeleton", which is 
+ * a pattern which just includes the desired fields and lengths. The generator 
+ * will return the "best fit" pattern corresponding to that skeleton.
+ * <p>The main method people will use is udatpg_getBestPattern, since normally
+ * UDateTimePatternGenerator is pre-built with data from a particular locale. 
+ * However, generators can be built directly from other data as well.
+ * <p><i>Issue: may be useful to also have a function that returns the list of 
+ * fields in a pattern, in order, since we have that internally.
+ * That would be useful for getting the UI order of field elements.</i>
+ */
+
+/**
+ * Opaque type for a date/time pattern generator object.
+ * @stable ICU 4.0
+ */
+typedef void *UDateTimePatternGenerator;
+
+/**
+ * Field number constants for udatpg_getAppendItemFormats() and similar functions.
+ * These constants are separate from UDateFormatField despite semantic overlap
+ * because some fields are merged for the date/time pattern generator.
+ * @stable ICU 4.0
+ */
+typedef enum UDateTimePatternField {
+    /** @stable ICU 4.0 */
+    UDATPG_ERA_FIELD,
+    /** @stable ICU 4.0 */
+    UDATPG_YEAR_FIELD,
+    /** @stable ICU 4.0 */
+    UDATPG_QUARTER_FIELD,
+    /** @stable ICU 4.0 */
+    UDATPG_MONTH_FIELD,
+    /** @stable ICU 4.0 */
+    UDATPG_WEEK_OF_YEAR_FIELD,
+    /** @stable ICU 4.0 */
+    UDATPG_WEEK_OF_MONTH_FIELD,
+    /** @stable ICU 4.0 */
+    UDATPG_WEEKDAY_FIELD,
+    /** @stable ICU 4.0 */
+    UDATPG_DAY_OF_YEAR_FIELD,
+    /** @stable ICU 4.0 */
+    UDATPG_DAY_OF_WEEK_IN_MONTH_FIELD,
+    /** @stable ICU 4.0 */
+    UDATPG_DAY_FIELD,
+    /** @stable ICU 4.0 */
+    UDATPG_DAYPERIOD_FIELD,
+    /** @stable ICU 4.0 */
+    UDATPG_HOUR_FIELD,
+    /** @stable ICU 4.0 */
+    UDATPG_MINUTE_FIELD,
+    /** @stable ICU 4.0 */
+    UDATPG_SECOND_FIELD,
+    /** @stable ICU 4.0 */
+    UDATPG_FRACTIONAL_SECOND_FIELD,
+    /** @stable ICU 4.0 */
+    UDATPG_ZONE_FIELD,
+    /** @stable ICU 4.0 */
+    UDATPG_FIELD_COUNT
+} UDateTimePatternField;
+
+/**
+ * Status return values from udatpg_addPattern().
+ * @stable ICU 4.0
+ */
+typedef enum UDateTimePatternConflict {
+    /** @stable ICU 4.0 */
+    UDATPG_NO_CONFLICT,
+    /** @stable ICU 4.0 */
+    UDATPG_BASE_CONFLICT,
+    /** @stable ICU 4.0 */
+    UDATPG_CONFLICT,
+    /** @stable ICU 4.0 */
+    UDATPG_CONFLICT_COUNT
+} UDateTimePatternConflict;
+
+/**
+  * Open a generator according to a given locale.
+  * @param locale
+  * @param pErrorCode a pointer to the UErrorCode which must not indicate a
+  *                   failure before the function call.
+  * @return a pointer to UDateTimePatternGenerator.
+  * @stable ICU 4.0
+  */
+U_DRAFT UDateTimePatternGenerator * U_EXPORT2
+udatpg_open(const char *locale, UErrorCode *pErrorCode);
+
+/**
+  * Open an empty generator, to be constructed with udatpg_addPattern(...) etc.
+  * @param pErrorCode a pointer to the UErrorCode which must not indicate a
+  *                   failure before the function call.
+  * @return a pointer to UDateTimePatternGenerator.
+  * @stable ICU 4.0
+  */
+U_DRAFT UDateTimePatternGenerator * U_EXPORT2
+udatpg_openEmpty(UErrorCode *pErrorCode);
+
+/**
+  * Close a generator.
+  * @param dtpg a pointer to UDateTimePatternGenerator.
+  * @stable ICU 4.0
+  */
+U_DRAFT void U_EXPORT2
+udatpg_close(UDateTimePatternGenerator *dtpg);
+
+/**
+  * Create a copy pf a generator.
+  * @param dtpg a pointer to UDateTimePatternGenerator to be copied.
+  * @param pErrorCode a pointer to the UErrorCode which must not indicate a
+  *                   failure before the function call.
+  * @return a pointer to a new UDateTimePatternGenerator.
+  * @stable ICU 4.0
+ */
+U_DRAFT UDateTimePatternGenerator * U_EXPORT2
+udatpg_clone(const UDateTimePatternGenerator *dtpg, UErrorCode *pErrorCode);
+
+/**
+ * Get the best pattern matching the input skeleton. It is guaranteed to
+ * have all of the fields in the skeleton.
+ * 
+ * Note that this function uses a non-const UDateTimePatternGenerator:
+ * It uses a stateful pattern parser which is set up for each generator object,
+ * rather than creating one for each function call.
+ * Consecutive calls to this function do not affect each other,
+ * but this function cannot be used concurrently on a single generator object.
+ * 
+ * @param dtpg a pointer to UDateTimePatternGenerator.
+ * @param skeleton
+ *            The skeleton is a pattern containing only the variable fields.
+ *            For example, "MMMdd" and "mmhh" are skeletons.
+ * @param length the length of skeleton
+ * @param bestPattern
+ *            The best pattern found from the given skeleton.
+ * @param capacity the capacity of bestPattern.
+ * @param pErrorCode a pointer to the UErrorCode which must not indicate a
+ *                   failure before the function call.
+ * @return the length of bestPattern.
+ * @stable ICU 4.0
+ */
+U_DRAFT int32_t U_EXPORT2
+udatpg_getBestPattern(UDateTimePatternGenerator *dtpg,
+                      const UChar *skeleton, int32_t length,
+                      UChar *bestPattern, int32_t capacity,
+                      UErrorCode *pErrorCode);
+
+/**
+  * Get a unique skeleton from a given pattern. For example,
+  * both "MMM-dd" and "dd/MMM" produce the skeleton "MMMdd".
+  * 
+  * Note that this function uses a non-const UDateTimePatternGenerator:
+  * It uses a stateful pattern parser which is set up for each generator object,
+  * rather than creating one for each function call.
+  * Consecutive calls to this function do not affect each other,
+  * but this function cannot be used concurrently on a single generator object.
+  *
+  * @param dtpg     a pointer to UDateTimePatternGenerator.
+  * @param pattern  input pattern, such as "dd/MMM".
+  * @param length   the length of pattern.
+  * @param skeleton such as "MMMdd"
+  * @param capacity the capacity of skeleton.
+  * @param pErrorCode a pointer to the UErrorCode which must not indicate a
+  *                  failure before the function call.
+  * @return the length of skeleton.
+  * @stable ICU 4.0
+  */
+U_DRAFT int32_t U_EXPORT2
+udatpg_getSkeleton(UDateTimePatternGenerator *dtpg,
+                   const UChar *pattern, int32_t length,
+                   UChar *skeleton, int32_t capacity,
+                   UErrorCode *pErrorCode);
+
+/**
+ * Get a unique base skeleton from a given pattern. This is the same
+ * as the skeleton, except that differences in length are minimized so
+ * as to only preserve the difference between string and numeric form. So
+ * for example, both "MMM-dd" and "d/MMM" produce the skeleton "MMMd"
+ * (notice the single d).
+ *
+ * Note that this function uses a non-const UDateTimePatternGenerator:
+ * It uses a stateful pattern parser which is set up for each generator object,
+ * rather than creating one for each function call.
+ * Consecutive calls to this function do not affect each other,
+ * but this function cannot be used concurrently on a single generator object.
+ *
+ * @param dtpg     a pointer to UDateTimePatternGenerator.
+ * @param pattern  input pattern, such as "dd/MMM".
+ * @param length   the length of pattern.
+ * @param baseSkeleton such as "Md"
+ * @param capacity the capacity of base skeleton.
+ * @param pErrorCode a pointer to the UErrorCode which must not indicate a
+ *                  failure before the function call.
+ * @return the length of baseSkeleton.
+ * @stable ICU 4.0
+ */
+U_DRAFT int32_t U_EXPORT2
+udatpg_getBaseSkeleton(UDateTimePatternGenerator *dtpg,
+                       const UChar *pattern, int32_t length,
+                       UChar *baseSkeleton, int32_t capacity,
+                       UErrorCode *pErrorCode);
+
+/**
+ * Adds a pattern to the generator. If the pattern has the same skeleton as
+ * an existing pattern, and the override parameter is set, then the previous
+ * value is overriden. Otherwise, the previous value is retained. In either
+ * case, the conflicting status is set and previous vale is stored in 
+ * conflicting pattern.
+ * <p>
+ * Note that single-field patterns (like "MMM") are automatically added, and
+ * don't need to be added explicitly!
+ *
+ * @param dtpg     a pointer to UDateTimePatternGenerator.
+ * @param pattern  input pattern, such as "dd/MMM"
+ * @param patternLength the length of pattern.
+ * @param override  When existing values are to be overridden use true, 
+ *                  otherwise use false.
+ * @param conflictingPattern  Previous pattern with the same skeleton.
+ * @param capacity the capacity of conflictingPattern.
+ * @param pLength a pointer to the length of conflictingPattern.
+ * @param pErrorCode a pointer to the UErrorCode which must not indicate a
+ *                  failure before the function call.
+ * @return conflicting status. The value could be UDATPG_NO_CONFLICT, 
+ *                  UDATPG_BASE_CONFLICT or UDATPG_CONFLICT.
+ * @stable ICU 4.0
+ */
+U_DRAFT UDateTimePatternConflict U_EXPORT2
+udatpg_addPattern(UDateTimePatternGenerator *dtpg,
+                  const UChar *pattern, int32_t patternLength,
+                  UBool override,
+                  UChar *conflictingPattern, int32_t capacity, int32_t *pLength,
+                  UErrorCode *pErrorCode);
+
+/**
+  * An AppendItem format is a pattern used to append a field if there is no
+  * good match. For example, suppose that the input skeleton is "GyyyyMMMd",
+  * and there is no matching pattern internally, but there is a pattern
+  * matching "yyyyMMMd", say "d-MM-yyyy". Then that pattern is used, plus the
+  * G. The way these two are conjoined is by using the AppendItemFormat for G
+  * (era). So if that value is, say "{0}, {1}" then the final resulting
+  * pattern is "d-MM-yyyy, G".
+  * <p>
+  * There are actually three available variables: {0} is the pattern so far,
+  * {1} is the element we are adding, and {2} is the name of the element.
+  * <p>
+  * This reflects the way that the CLDR data is organized.
+  *
+  * @param dtpg   a pointer to UDateTimePatternGenerator.
+  * @param field  UDateTimePatternField, such as UDATPG_ERA_FIELD
+  * @param value  pattern, such as "{0}, {1}"
+  * @param length the length of value.
+  * @stable ICU 4.0
+  */
+U_DRAFT void U_EXPORT2
+udatpg_setAppendItemFormat(UDateTimePatternGenerator *dtpg,
+                           UDateTimePatternField field,
+                           const UChar *value, int32_t length);
+
+/**
+ * Getter corresponding to setAppendItemFormat. Values below 0 or at or
+ * above UDATPG_FIELD_COUNT are illegal arguments.
+ *
+ * @param dtpg   A pointer to UDateTimePatternGenerator.
+ * @param field  UDateTimePatternField, such as UDATPG_ERA_FIELD
+ * @param pLength A pointer that will receive the length of appendItemFormat.
+ * @return appendItemFormat for field.
+ * @stable ICU 4.0
+ */
+U_DRAFT const UChar * U_EXPORT2
+udatpg_getAppendItemFormat(const UDateTimePatternGenerator *dtpg,
+                           UDateTimePatternField field,
+                           int32_t *pLength);
+
+/**
+   * Set the name of field, eg "era" in English for ERA. These are only
+   * used if the corresponding AppendItemFormat is used, and if it contains a
+   * {2} variable.
+   * <p>
+   * This reflects the way that the CLDR data is organized.
+   *
+   * @param dtpg   a pointer to UDateTimePatternGenerator.
+   * @param field  UDateTimePatternField
+   * @param value  name for the field.
+   * @param length the length of value.
+   * @stable ICU 4.0
+   */
+U_DRAFT void U_EXPORT2
+udatpg_setAppendItemName(UDateTimePatternGenerator *dtpg,
+                         UDateTimePatternField field,
+                         const UChar *value, int32_t length);
+
+/**
+ * Getter corresponding to setAppendItemNames. Values below 0 or at or above
+ * UDATPG_FIELD_COUNT are illegal arguments.
+ *
+ * @param dtpg   a pointer to UDateTimePatternGenerator.
+ * @param field  UDateTimePatternField, such as UDATPG_ERA_FIELD
+ * @param pLength A pointer that will receive the length of the name for field.
+ * @return name for field
+ * @stable ICU 4.0
+ */
+U_DRAFT const UChar * U_EXPORT2
+udatpg_getAppendItemName(const UDateTimePatternGenerator *dtpg,
+                         UDateTimePatternField field,
+                         int32_t *pLength);
+
+/**
+ * The date time format is a message format pattern used to compose date and
+ * time patterns. The default value is "{0} {1}", where {0} will be replaced
+ * by the date pattern and {1} will be replaced by the time pattern.
+ * <p>
+ * This is used when the input skeleton contains both date and time fields,
+ * but there is not a close match among the added patterns. For example,
+ * suppose that this object was created by adding "dd-MMM" and "hh:mm", and
+ * its datetimeFormat is the default "{0} {1}". Then if the input skeleton
+ * is "MMMdhmm", there is not an exact match, so the input skeleton is
+ * broken up into two components "MMMd" and "hmm". There are close matches
+ * for those two skeletons, so the result is put together with this pattern,
+ * resulting in "d-MMM h:mm".
+ *
+ * @param dtpg a pointer to UDateTimePatternGenerator.
+ * @param dtFormat
+ *            message format pattern, here {0} will be replaced by the date
+ *            pattern and {1} will be replaced by the time pattern.
+ * @param length the length of dtFormat.
+ * @stable ICU 4.0
+ */
+U_DRAFT void U_EXPORT2
+udatpg_setDateTimeFormat(const UDateTimePatternGenerator *dtpg,
+                         const UChar *dtFormat, int32_t length);
+
+/**
+ * Getter corresponding to setDateTimeFormat.
+ * @param dtpg   a pointer to UDateTimePatternGenerator.
+ * @param pLength A pointer that will receive the length of the format
+ * @return dateTimeFormat.
+ * @stable ICU 4.0
+ */
+U_DRAFT const UChar * U_EXPORT2
+udatpg_getDateTimeFormat(const UDateTimePatternGenerator *dtpg,
+                         int32_t *pLength);
+
+/**
+ * The decimal value is used in formatting fractions of seconds. If the
+ * skeleton contains fractional seconds, then this is used with the
+ * fractional seconds. For example, suppose that the input pattern is
+ * "hhmmssSSSS", and the best matching pattern internally is "H:mm:ss", and
+ * the decimal string is ",". Then the resulting pattern is modified to be
+ * "H:mm:ss,SSSS"
+ *
+ * @param dtpg a pointer to UDateTimePatternGenerator.
+ * @param decimal
+ * @param length the length of decimal.
+ * @stable ICU 4.0
+ */
+U_DRAFT void U_EXPORT2
+udatpg_setDecimal(UDateTimePatternGenerator *dtpg,
+                  const UChar *decimal, int32_t length);
+
+/**
+ * Getter corresponding to setDecimal.
+ * 
+ * @param dtpg a pointer to UDateTimePatternGenerator.
+ * @param pLength A pointer that will receive the length of the decimal string.
+ * @return corresponding to the decimal point.
+ * @stable ICU 4.0
+ */
+U_DRAFT const UChar * U_EXPORT2
+udatpg_getDecimal(const UDateTimePatternGenerator *dtpg,
+                  int32_t *pLength);
+
+/**
+ * Adjusts the field types (width and subtype) of a pattern to match what is
+ * in a skeleton. That is, if you supply a pattern like "d-M H:m", and a
+ * skeleton of "MMMMddhhmm", then the input pattern is adjusted to be
+ * "dd-MMMM hh:mm". This is used internally to get the best match for the
+ * input skeleton, but can also be used externally.
+ *
+ * Note that this function uses a non-const UDateTimePatternGenerator:
+ * It uses a stateful pattern parser which is set up for each generator object,
+ * rather than creating one for each function call.
+ * Consecutive calls to this function do not affect each other,
+ * but this function cannot be used concurrently on a single generator object.
+ *
+ * @param dtpg a pointer to UDateTimePatternGenerator.
+ * @param pattern Input pattern
+ * @param patternLength the length of input pattern.
+ * @param skeleton
+ * @param skeletonLength the length of input skeleton.
+ * @param dest  pattern adjusted to match the skeleton fields widths and subtypes.
+ * @param destCapacity the capacity of dest.
+ * @param pErrorCode a pointer to the UErrorCode which must not indicate a
+ *                  failure before the function call.
+ * @return the length of dest.
+ * @stable ICU 4.0
+ */
+U_DRAFT int32_t U_EXPORT2
+udatpg_replaceFieldTypes(UDateTimePatternGenerator *dtpg,
+                         const UChar *pattern, int32_t patternLength,
+                         const UChar *skeleton, int32_t skeletonLength,
+                         UChar *dest, int32_t destCapacity,
+                         UErrorCode *pErrorCode);
+
+/**
+ * Return a UEnumeration list of all the skeletons in canonical form.
+ * Call udatpg_getPatternForSkeleton() to get the corresponding pattern.
+ * 
+ * @param dtpg a pointer to UDateTimePatternGenerator.
+ * @param pErrorCode a pointer to the UErrorCode which must not indicate a
+ *                  failure before the function call
+ * @return a UEnumeration list of all the skeletons
+ *         The caller must close the object.
+ * @stable ICU 4.0
+ */
+U_DRAFT UEnumeration * U_EXPORT2
+udatpg_openSkeletons(const UDateTimePatternGenerator *dtpg, UErrorCode *pErrorCode);
+
+/**
+ * Return a UEnumeration list of all the base skeletons in canonical form.
+ *
+ * @param dtpg a pointer to UDateTimePatternGenerator.
+ * @param pErrorCode a pointer to the UErrorCode which must not indicate a
+ *             failure before the function call.
+ * @return a UEnumeration list of all the base skeletons
+ *             The caller must close the object.
+ * @stable ICU 4.0
+ */
+U_DRAFT UEnumeration * U_EXPORT2
+udatpg_openBaseSkeletons(const UDateTimePatternGenerator *dtpg, UErrorCode *pErrorCode);
+
+/**
+ * Get the pattern corresponding to a given skeleton.
+ * 
+ * @param dtpg a pointer to UDateTimePatternGenerator.
+ * @param skeleton 
+ * @param skeletonLength pointer to the length of skeleton.
+ * @param pLength pointer to the length of return pattern.
+ * @return pattern corresponding to a given skeleton.
+ * @stable ICU 4.0
+ */
+U_DRAFT const UChar * U_EXPORT2
+udatpg_getPatternForSkeleton(const UDateTimePatternGenerator *dtpg,
+                             const UChar *skeleton, int32_t skeletonLength,
+                             int32_t *pLength);
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/udeprctd.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/udeprctd.h b/src/apps/couch_collate/platform/osx/icu/unicode/udeprctd.h
new file mode 100644
index 0000000..9bf45f3
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/udeprctd.h
@@ -0,0 +1,50 @@
+/*
+*******************************************************************************
+*   Copyright (C) 2004-2008, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+*******************************************************************************
+*
+*   file name:  
+*   encoding:   US-ASCII
+*   tab size:   8 (not used)
+*   indentation:4
+*
+*   Created by: genheaders.pl, a perl script written by Ram Viswanadha
+*
+*  Contains data for commenting out APIs.
+*  Gets included by umachine.h
+*
+*  THIS FILE IS MACHINE-GENERATED, DON'T PLAY WITH IT IF YOU DON'T KNOW WHAT
+*  YOU ARE DOING, OTHERWISE VERY BAD THINGS WILL HAPPEN!
+*/
+
+#ifndef UDEPRCTD_H
+#define UDEPRCTD_H
+
+#ifdef U_HIDE_DEPRECATED_API
+
+#    if U_DISABLE_RENAMING
+#        define ucol_getContractions ucol_getContractions_DEPRECATED_API_DO_NOT_USE
+#        define ucol_getLocale ucol_getLocale_DEPRECATED_API_DO_NOT_USE
+#        define ures_countArrayItems ures_countArrayItems_DEPRECATED_API_DO_NOT_USE
+#        define ures_getLocale ures_getLocale_DEPRECATED_API_DO_NOT_USE
+#        define ures_getVersionNumber ures_getVersionNumber_DEPRECATED_API_DO_NOT_USE
+#        define utrans_getAvailableID utrans_getAvailableID_DEPRECATED_API_DO_NOT_USE
+#        define utrans_getID utrans_getID_DEPRECATED_API_DO_NOT_USE
+#        define utrans_open utrans_open_DEPRECATED_API_DO_NOT_USE
+#        define utrans_unregister utrans_unregister_DEPRECATED_API_DO_NOT_USE
+#    else
+#        define ucol_getContractions_4_0 ucol_getContractions_DEPRECATED_API_DO_NOT_USE
+#        define ucol_getLocale_4_0 ucol_getLocale_DEPRECATED_API_DO_NOT_USE
+#        define ures_countArrayItems_4_0 ures_countArrayItems_DEPRECATED_API_DO_NOT_USE
+#        define ures_getLocale_4_0 ures_getLocale_DEPRECATED_API_DO_NOT_USE
+#        define ures_getVersionNumber_4_0 ures_getVersionNumber_DEPRECATED_API_DO_NOT_USE
+#        define utrans_getAvailableID_4_0 utrans_getAvailableID_DEPRECATED_API_DO_NOT_USE
+#        define utrans_getID_4_0 utrans_getID_DEPRECATED_API_DO_NOT_USE
+#        define utrans_open_4_0 utrans_open_DEPRECATED_API_DO_NOT_USE
+#        define utrans_unregister_4_0 utrans_unregister_DEPRECATED_API_DO_NOT_USE
+#    endif /* U_DISABLE_RENAMING */
+
+#endif /* U_HIDE_DEPRECATED_API */
+#endif /* UDEPRCTD_H */
+

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/udraft.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/udraft.h b/src/apps/couch_collate/platform/osx/icu/unicode/udraft.h
new file mode 100644
index 0000000..5426adf
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/udraft.h
@@ -0,0 +1,166 @@
+/*
+*******************************************************************************
+*   Copyright (C) 2004-2008, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+*******************************************************************************
+*
+*   file name:  
+*   encoding:   US-ASCII
+*   tab size:   8 (not used)
+*   indentation:4
+*
+*   Created by: genheaders.pl, a perl script written by Ram Viswanadha
+*
+*  Contains data for commenting out APIs.
+*  Gets included by umachine.h
+*
+*  THIS FILE IS MACHINE-GENERATED, DON'T PLAY WITH IT IF YOU DON'T KNOW WHAT
+*  YOU ARE DOING, OTHERWISE VERY BAD THINGS WILL HAPPEN!
+*/
+
+#ifndef UDRAFT_H
+#define UDRAFT_H
+
+#ifdef U_HIDE_DRAFT_API
+
+#    if U_DISABLE_RENAMING
+#        define afkLanguageCode afkLanguageCode_DRAFT_API_DO_NOT_USE
+#        define armiScriptCode armiScriptCode_DRAFT_API_DO_NOT_USE
+#        define u_fclose u_fclose_DRAFT_API_DO_NOT_USE
+#        define u_feof u_feof_DRAFT_API_DO_NOT_USE
+#        define u_fflush u_fflush_DRAFT_API_DO_NOT_USE
+#        define u_fgetConverter u_fgetConverter_DRAFT_API_DO_NOT_USE
+#        define u_fgetc u_fgetc_DRAFT_API_DO_NOT_USE
+#        define u_fgetcodepage u_fgetcodepage_DRAFT_API_DO_NOT_USE
+#        define u_fgetcx u_fgetcx_DRAFT_API_DO_NOT_USE
+#        define u_fgetfile u_fgetfile_DRAFT_API_DO_NOT_USE
+#        define u_fgetlocale u_fgetlocale_DRAFT_API_DO_NOT_USE
+#        define u_fgets u_fgets_DRAFT_API_DO_NOT_USE
+#        define u_file_read u_file_read_DRAFT_API_DO_NOT_USE
+#        define u_file_write u_file_write_DRAFT_API_DO_NOT_USE
+#        define u_finit u_finit_DRAFT_API_DO_NOT_USE
+#        define u_fopen u_fopen_DRAFT_API_DO_NOT_USE
+#        define u_fprintf u_fprintf_DRAFT_API_DO_NOT_USE
+#        define u_fprintf_u u_fprintf_u_DRAFT_API_DO_NOT_USE
+#        define u_fputc u_fputc_DRAFT_API_DO_NOT_USE
+#        define u_fputs u_fputs_DRAFT_API_DO_NOT_USE
+#        define u_frewind u_frewind_DRAFT_API_DO_NOT_USE
+#        define u_fscanf u_fscanf_DRAFT_API_DO_NOT_USE
+#        define u_fscanf_u u_fscanf_u_DRAFT_API_DO_NOT_USE
+#        define u_fsetcodepage u_fsetcodepage_DRAFT_API_DO_NOT_USE
+#        define u_fsetlocale u_fsetlocale_DRAFT_API_DO_NOT_USE
+#        define u_fsettransliterator u_fsettransliterator_DRAFT_API_DO_NOT_USE
+#        define u_fstropen u_fstropen_DRAFT_API_DO_NOT_USE
+#        define u_fungetc u_fungetc_DRAFT_API_DO_NOT_USE
+#        define u_snprintf u_snprintf_DRAFT_API_DO_NOT_USE
+#        define u_snprintf_u u_snprintf_u_DRAFT_API_DO_NOT_USE
+#        define u_sprintf u_sprintf_DRAFT_API_DO_NOT_USE
+#        define u_sprintf_u u_sprintf_u_DRAFT_API_DO_NOT_USE
+#        define u_sscanf u_sscanf_DRAFT_API_DO_NOT_USE
+#        define u_sscanf_u u_sscanf_u_DRAFT_API_DO_NOT_USE
+#        define u_vfprintf u_vfprintf_DRAFT_API_DO_NOT_USE
+#        define u_vfprintf_u u_vfprintf_u_DRAFT_API_DO_NOT_USE
+#        define u_vfscanf u_vfscanf_DRAFT_API_DO_NOT_USE
+#        define u_vfscanf_u u_vfscanf_u_DRAFT_API_DO_NOT_USE
+#        define u_vsnprintf u_vsnprintf_DRAFT_API_DO_NOT_USE
+#        define u_vsnprintf_u u_vsnprintf_u_DRAFT_API_DO_NOT_USE
+#        define u_vsprintf u_vsprintf_DRAFT_API_DO_NOT_USE
+#        define u_vsprintf_u u_vsprintf_u_DRAFT_API_DO_NOT_USE
+#        define u_vsscanf u_vsscanf_DRAFT_API_DO_NOT_USE
+#        define u_vsscanf_u u_vsscanf_u_DRAFT_API_DO_NOT_USE
+#        define ucal_clone ucal_clone_DRAFT_API_DO_NOT_USE
+#        define ucal_getCanonicalTimeZoneID ucal_getCanonicalTimeZoneID_DRAFT_API_DO_NOT_USE
+#        define ucurr_countCurrencies ucurr_countCurrencies_DRAFT_API_DO_NOT_USE
+#        define ucurr_forLocaleAndDate ucurr_forLocaleAndDate_DRAFT_API_DO_NOT_USE
+#        define uloc_addLikelySubtags uloc_addLikelySubtags_DRAFT_API_DO_NOT_USE
+#        define uloc_getCharacterOrientation uloc_getCharacterOrientation_DRAFT_API_DO_NOT_USE
+#        define uloc_getLineOrientation uloc_getLineOrientation_DRAFT_API_DO_NOT_USE
+#        define uloc_minimizeSubtags uloc_minimizeSubtags_DRAFT_API_DO_NOT_USE
+#        define uregex_getMatchCallback uregex_getMatchCallback_DRAFT_API_DO_NOT_USE
+#        define uregex_getStackLimit uregex_getStackLimit_DRAFT_API_DO_NOT_USE
+#        define uregex_getTimeLimit uregex_getTimeLimit_DRAFT_API_DO_NOT_USE
+#        define uregex_hasAnchoringBounds uregex_hasAnchoringBounds_DRAFT_API_DO_NOT_USE
+#        define uregex_hasTransparentBounds uregex_hasTransparentBounds_DRAFT_API_DO_NOT_USE
+#        define uregex_hitEnd uregex_hitEnd_DRAFT_API_DO_NOT_USE
+#        define uregex_regionEnd uregex_regionEnd_DRAFT_API_DO_NOT_USE
+#        define uregex_regionStart uregex_regionStart_DRAFT_API_DO_NOT_USE
+#        define uregex_requireEnd uregex_requireEnd_DRAFT_API_DO_NOT_USE
+#        define uregex_setMatchCallback uregex_setMatchCallback_DRAFT_API_DO_NOT_USE
+#        define uregex_setRegion uregex_setRegion_DRAFT_API_DO_NOT_USE
+#        define uregex_setStackLimit uregex_setStackLimit_DRAFT_API_DO_NOT_USE
+#        define uregex_setTimeLimit uregex_setTimeLimit_DRAFT_API_DO_NOT_USE
+#        define uregex_useAnchoringBounds uregex_useAnchoringBounds_DRAFT_API_DO_NOT_USE
+#        define uregex_useTransparentBounds uregex_useTransparentBounds_DRAFT_API_DO_NOT_USE
+#    else
+#        define afkLanguageCode_4_0 afkLanguageCode_DRAFT_API_DO_NOT_USE
+#        define armiScriptCode_4_0 armiScriptCode_DRAFT_API_DO_NOT_USE
+#        define u_fclose_4_0 u_fclose_DRAFT_API_DO_NOT_USE
+#        define u_feof_4_0 u_feof_DRAFT_API_DO_NOT_USE
+#        define u_fflush_4_0 u_fflush_DRAFT_API_DO_NOT_USE
+#        define u_fgetConverter_4_0 u_fgetConverter_DRAFT_API_DO_NOT_USE
+#        define u_fgetc_4_0 u_fgetc_DRAFT_API_DO_NOT_USE
+#        define u_fgetcodepage_4_0 u_fgetcodepage_DRAFT_API_DO_NOT_USE
+#        define u_fgetcx_4_0 u_fgetcx_DRAFT_API_DO_NOT_USE
+#        define u_fgetfile_4_0 u_fgetfile_DRAFT_API_DO_NOT_USE
+#        define u_fgetlocale_4_0 u_fgetlocale_DRAFT_API_DO_NOT_USE
+#        define u_fgets_4_0 u_fgets_DRAFT_API_DO_NOT_USE
+#        define u_file_read_4_0 u_file_read_DRAFT_API_DO_NOT_USE
+#        define u_file_write_4_0 u_file_write_DRAFT_API_DO_NOT_USE
+#        define u_finit_4_0 u_finit_DRAFT_API_DO_NOT_USE
+#        define u_fopen_4_0 u_fopen_DRAFT_API_DO_NOT_USE
+#        define u_fprintf_4_0 u_fprintf_DRAFT_API_DO_NOT_USE
+#        define u_fprintf_u_4_0 u_fprintf_u_DRAFT_API_DO_NOT_USE
+#        define u_fputc_4_0 u_fputc_DRAFT_API_DO_NOT_USE
+#        define u_fputs_4_0 u_fputs_DRAFT_API_DO_NOT_USE
+#        define u_frewind_4_0 u_frewind_DRAFT_API_DO_NOT_USE
+#        define u_fscanf_4_0 u_fscanf_DRAFT_API_DO_NOT_USE
+#        define u_fscanf_u_4_0 u_fscanf_u_DRAFT_API_DO_NOT_USE
+#        define u_fsetcodepage_4_0 u_fsetcodepage_DRAFT_API_DO_NOT_USE
+#        define u_fsetlocale_4_0 u_fsetlocale_DRAFT_API_DO_NOT_USE
+#        define u_fsettransliterator_4_0 u_fsettransliterator_DRAFT_API_DO_NOT_USE
+#        define u_fstropen_4_0 u_fstropen_DRAFT_API_DO_NOT_USE
+#        define u_fungetc_4_0 u_fungetc_DRAFT_API_DO_NOT_USE
+#        define u_snprintf_4_0 u_snprintf_DRAFT_API_DO_NOT_USE
+#        define u_snprintf_u_4_0 u_snprintf_u_DRAFT_API_DO_NOT_USE
+#        define u_sprintf_4_0 u_sprintf_DRAFT_API_DO_NOT_USE
+#        define u_sprintf_u_4_0 u_sprintf_u_DRAFT_API_DO_NOT_USE
+#        define u_sscanf_4_0 u_sscanf_DRAFT_API_DO_NOT_USE
+#        define u_sscanf_u_4_0 u_sscanf_u_DRAFT_API_DO_NOT_USE
+#        define u_vfprintf_4_0 u_vfprintf_DRAFT_API_DO_NOT_USE
+#        define u_vfprintf_u_4_0 u_vfprintf_u_DRAFT_API_DO_NOT_USE
+#        define u_vfscanf_4_0 u_vfscanf_DRAFT_API_DO_NOT_USE
+#        define u_vfscanf_u_4_0 u_vfscanf_u_DRAFT_API_DO_NOT_USE
+#        define u_vsnprintf_4_0 u_vsnprintf_DRAFT_API_DO_NOT_USE
+#        define u_vsnprintf_u_4_0 u_vsnprintf_u_DRAFT_API_DO_NOT_USE
+#        define u_vsprintf_4_0 u_vsprintf_DRAFT_API_DO_NOT_USE
+#        define u_vsprintf_u_4_0 u_vsprintf_u_DRAFT_API_DO_NOT_USE
+#        define u_vsscanf_4_0 u_vsscanf_DRAFT_API_DO_NOT_USE
+#        define u_vsscanf_u_4_0 u_vsscanf_u_DRAFT_API_DO_NOT_USE
+#        define ucal_clone_4_0 ucal_clone_DRAFT_API_DO_NOT_USE
+#        define ucal_getCanonicalTimeZoneID_4_0 ucal_getCanonicalTimeZoneID_DRAFT_API_DO_NOT_USE
+#        define ucurr_countCurrencies_4_0 ucurr_countCurrencies_DRAFT_API_DO_NOT_USE
+#        define ucurr_forLocaleAndDate_4_0 ucurr_forLocaleAndDate_DRAFT_API_DO_NOT_USE
+#        define uloc_addLikelySubtags_4_0 uloc_addLikelySubtags_DRAFT_API_DO_NOT_USE
+#        define uloc_getCharacterOrientation_4_0 uloc_getCharacterOrientation_DRAFT_API_DO_NOT_USE
+#        define uloc_getLineOrientation_4_0 uloc_getLineOrientation_DRAFT_API_DO_NOT_USE
+#        define uloc_minimizeSubtags_4_0 uloc_minimizeSubtags_DRAFT_API_DO_NOT_USE
+#        define uregex_getMatchCallback_4_0 uregex_getMatchCallback_DRAFT_API_DO_NOT_USE
+#        define uregex_getStackLimit_4_0 uregex_getStackLimit_DRAFT_API_DO_NOT_USE
+#        define uregex_getTimeLimit_4_0 uregex_getTimeLimit_DRAFT_API_DO_NOT_USE
+#        define uregex_hasAnchoringBounds_4_0 uregex_hasAnchoringBounds_DRAFT_API_DO_NOT_USE
+#        define uregex_hasTransparentBounds_4_0 uregex_hasTransparentBounds_DRAFT_API_DO_NOT_USE
+#        define uregex_hitEnd_4_0 uregex_hitEnd_DRAFT_API_DO_NOT_USE
+#        define uregex_regionEnd_4_0 uregex_regionEnd_DRAFT_API_DO_NOT_USE
+#        define uregex_regionStart_4_0 uregex_regionStart_DRAFT_API_DO_NOT_USE
+#        define uregex_requireEnd_4_0 uregex_requireEnd_DRAFT_API_DO_NOT_USE
+#        define uregex_setMatchCallback_4_0 uregex_setMatchCallback_DRAFT_API_DO_NOT_USE
+#        define uregex_setRegion_4_0 uregex_setRegion_DRAFT_API_DO_NOT_USE
+#        define uregex_setStackLimit_4_0 uregex_setStackLimit_DRAFT_API_DO_NOT_USE
+#        define uregex_setTimeLimit_4_0 uregex_setTimeLimit_DRAFT_API_DO_NOT_USE
+#        define uregex_useAnchoringBounds_4_0 uregex_useAnchoringBounds_DRAFT_API_DO_NOT_USE
+#        define uregex_useTransparentBounds_4_0 uregex_useTransparentBounds_DRAFT_API_DO_NOT_USE
+#    endif /* U_DISABLE_RENAMING */
+
+#endif /* U_HIDE_DRAFT_API */
+#endif /* UDRAFT_H */
+

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/uenum.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/uenum.h b/src/apps/couch_collate/platform/osx/icu/unicode/uenum.h
new file mode 100644
index 0000000..ff9b299
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/uenum.h
@@ -0,0 +1,134 @@
+/*
+*******************************************************************************
+*
+*   Copyright (C) 2002-2005, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+*
+*******************************************************************************
+*   file name:  uenum.h
+*   encoding:   US-ASCII
+*   tab size:   8 (not used)
+*   indentation:2
+*
+*   created on: 2002jul08
+*   created by: Vladimir Weinstein
+*/
+
+#ifndef __UENUM_H
+#define __UENUM_H
+
+#include "unicode/utypes.h"
+
+/**
+ * \file
+ * \brief C API: String Enumeration 
+ */
+ 
+/**
+ * An enumeration object.
+ * For usage in C programs.
+ * @stable ICU 2.2
+ */
+struct UEnumeration;
+/** structure representing an enumeration object instance @stable ICU 2.2 */
+typedef struct UEnumeration UEnumeration;
+
+/**
+ * Disposes of resources in use by the iterator.  If en is NULL,
+ * does nothing.  After this call, any char* or UChar* pointer
+ * returned by uenum_unext() or uenum_next() is invalid.
+ * @param en UEnumeration structure pointer
+ * @stable ICU 2.2
+ */
+U_STABLE void U_EXPORT2
+uenum_close(UEnumeration* en);
+
+/**
+ * Returns the number of elements that the iterator traverses.  If
+ * the iterator is out-of-sync with its service, status is set to
+ * U_ENUM_OUT_OF_SYNC_ERROR.
+ * This is a convenience function. It can end up being very
+ * expensive as all the items might have to be pre-fetched (depending
+ * on the type of data being traversed). Use with caution and only 
+ * when necessary.
+ * @param en UEnumeration structure pointer
+ * @param status error code, can be U_ENUM_OUT_OF_SYNC_ERROR if the
+ *               iterator is out of sync.
+ * @return number of elements in the iterator
+ * @stable ICU 2.2
+ */
+U_STABLE int32_t U_EXPORT2
+uenum_count(UEnumeration* en, UErrorCode* status);
+
+/**
+ * Returns the next element in the iterator's list.  If there are
+ * no more elements, returns NULL.  If the iterator is out-of-sync
+ * with its service, status is set to U_ENUM_OUT_OF_SYNC_ERROR and
+ * NULL is returned.  If the native service string is a char* string,
+ * it is converted to UChar* with the invariant converter.
+ * The result is terminated by (UChar)0.
+ * @param en the iterator object
+ * @param resultLength pointer to receive the length of the result
+ *                     (not including the terminating \\0).
+ *                     If the pointer is NULL it is ignored.
+ * @param status the error code, set to U_ENUM_OUT_OF_SYNC_ERROR if
+ *               the iterator is out of sync with its service.
+ * @return a pointer to the string.  The string will be
+ *         zero-terminated.  The return pointer is owned by this iterator
+ *         and must not be deleted by the caller.  The pointer is valid
+ *         until the next call to any uenum_... method, including
+ *         uenum_next() or uenum_unext().  When all strings have been
+ *         traversed, returns NULL.
+ * @stable ICU 2.2
+ */
+U_STABLE const UChar* U_EXPORT2
+uenum_unext(UEnumeration* en,
+            int32_t* resultLength,
+            UErrorCode* status);
+
+/**
+ * Returns the next element in the iterator's list.  If there are
+ * no more elements, returns NULL.  If the iterator is out-of-sync
+ * with its service, status is set to U_ENUM_OUT_OF_SYNC_ERROR and
+ * NULL is returned.  If the native service string is a UChar*
+ * string, it is converted to char* with the invariant converter.
+ * The result is terminated by (char)0.  If the conversion fails
+ * (because a character cannot be converted) then status is set to
+ * U_INVARIANT_CONVERSION_ERROR and the return value is undefined
+ * (but non-NULL).
+ * @param en the iterator object
+ * @param resultLength pointer to receive the length of the result
+ *                     (not including the terminating \\0).
+ *                     If the pointer is NULL it is ignored.
+ * @param status the error code, set to U_ENUM_OUT_OF_SYNC_ERROR if
+ *               the iterator is out of sync with its service.  Set to
+ *               U_INVARIANT_CONVERSION_ERROR if the underlying native string is
+ *               UChar* and conversion to char* with the invariant converter
+ *               fails. This error pertains only to current string, so iteration
+ *               might be able to continue successfully.
+ * @return a pointer to the string.  The string will be
+ *         zero-terminated.  The return pointer is owned by this iterator
+ *         and must not be deleted by the caller.  The pointer is valid
+ *         until the next call to any uenum_... method, including
+ *         uenum_next() or uenum_unext().  When all strings have been
+ *         traversed, returns NULL.
+ * @stable ICU 2.2
+ */
+U_STABLE const char* U_EXPORT2
+uenum_next(UEnumeration* en,
+           int32_t* resultLength,
+           UErrorCode* status);
+
+/**
+ * Resets the iterator to the current list of service IDs.  This
+ * re-establishes sync with the service and rewinds the iterator
+ * to start at the first element.
+ * @param en the iterator object
+ * @param status the error code, set to U_ENUM_OUT_OF_SYNC_ERROR if
+ *               the iterator is out of sync with its service.  
+ * @stable ICU 2.2
+ */
+U_STABLE void U_EXPORT2
+uenum_reset(UEnumeration* en, UErrorCode* status);
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/uidna.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/uidna.h b/src/apps/couch_collate/platform/osx/icu/unicode/uidna.h
new file mode 100644
index 0000000..52aa6e9
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/uidna.h
@@ -0,0 +1,312 @@
+/*
+ *******************************************************************************
+ *
+ *   Copyright (C) 2003-2007, International Business Machines
+ *   Corporation and others.  All Rights Reserved.
+ *
+ *******************************************************************************
+ *   file name:  uidna.h
+ *   encoding:   US-ASCII
+ *   tab size:   8 (not used)
+ *   indentation:4
+ *
+ *   created on: 2003feb1
+ *   created by: Ram Viswanadha
+ */
+
+#ifndef __UIDNA_H__
+#define __UIDNA_H__
+
+#include "unicode/utypes.h"
+
+#if !UCONFIG_NO_IDNA
+
+#include "unicode/parseerr.h"
+  
+/**
+ * \file
+ * \brief C API: Internationalized Domain Names in Applications Tranformation
+ *
+ * UIDNA API implements the IDNA protocol as defined in the IDNA RFC 
+ * (http://www.ietf.org/rfc/rfc3490.txt).
+ * The RFC defines 2 operations: ToASCII and ToUnicode. Domain labels 
+ * containing non-ASCII code points are required to be processed by
+ * ToASCII operation before passing it to resolver libraries. Domain names
+ * that are obtained from resolver libraries are required to be processed by
+ * ToUnicode operation before displaying the domain name to the user.
+ * IDNA requires that implementations process input strings with Nameprep
+ * (http://www.ietf.org/rfc/rfc3491.txt), 
+ * which is a profile of Stringprep (http://www.ietf.org/rfc/rfc3454.txt), 
+ * and then with Punycode (http://www.ietf.org/rfc/rfc3492.txt). 
+ * Implementations of IDNA MUST fully implement Nameprep and Punycode; 
+ * neither Nameprep nor Punycode are optional.
+ * The input and output of ToASCII and ToUnicode operations are Unicode 
+ * and are designed to be chainable, i.e., applying ToASCII or ToUnicode operations
+ * multiple times to an input string will yield the same result as applying the operation
+ * once.
+ * ToUnicode(ToUnicode(ToUnicode...(ToUnicode(string)))) == ToUnicode(string) 
+ * ToASCII(ToASCII(ToASCII...(ToASCII(string))) == ToASCII(string).
+ *
+ */
+
+/** 
+ * Option to prohibit processing of unassigned codepoints in the input and
+ * do not check if the input conforms to STD-3 ASCII rules.
+ * 
+ * @see  uidna_toASCII uidna_toUnicode
+ * @stable ICU 2.6
+ */
+#define UIDNA_DEFAULT          0x0000
+/** 
+ * Option to allow processing of unassigned codepoints in the input
+ * 
+ * @see  uidna_toASCII uidna_toUnicode
+ * @stable ICU 2.6
+ */
+#define UIDNA_ALLOW_UNASSIGNED 0x0001
+/** 
+ * Option to check if input conforms to STD-3 ASCII rules
+ * 
+ * @see  uidna_toASCII uidna_toUnicode
+ * @stable ICU 2.6
+ */
+#define UIDNA_USE_STD3_RULES   0x0002
+
+/**
+ * This function implements the ToASCII operation as defined in the IDNA RFC.
+ * This operation is done on <b>single labels</b> before sending it to something that expects
+ * ASCII names. A label is an individual part of a domain name. Labels are usually
+ * separated by dots; e.g." "www.example.com" is composed of 3 labels 
+ * "www","example", and "com".
+ *
+ *
+ * @param src               Input UChar array containing label in Unicode.
+ * @param srcLength         Number of UChars in src, or -1 if NUL-terminated.
+ * @param dest              Output UChar array with ASCII (ACE encoded) label.
+ * @param destCapacity      Size of dest.
+ * @param options           A bit set of options:
+ *
+ *  - UIDNA_DEFAULT             Use default options, i.e., do not process unassigned code points
+ *                              and do not use STD3 ASCII rules
+ *                              If unassigned code points are found the operation fails with 
+ *                              U_UNASSIGNED_ERROR error code.
+ *
+ *  - UIDNA_ALLOW_UNASSIGNED    Unassigned values can be converted to ASCII for query operations
+ *                              If this option is set, the unassigned code points are in the input 
+ *                              are treated as normal Unicode code points.
+ *                          
+ *  - UIDNA_USE_STD3_RULES      Use STD3 ASCII rules for host name syntax restrictions
+ *                              If this option is set and the input does not satisfy STD3 rules,  
+ *                              the operation will fail with U_IDNA_STD3_ASCII_RULES_ERROR
+ *
+ * @param parseError        Pointer to UParseError struct to receive information on position 
+ *                          of error if an error is encountered. Can be NULL.
+ * @param status            ICU in/out error code parameter.
+ *                          U_INVALID_CHAR_FOUND if src contains
+ *                          unmatched single surrogates.
+ *                          U_INDEX_OUTOFBOUNDS_ERROR if src contains
+ *                          too many code points.
+ *                          U_BUFFER_OVERFLOW_ERROR if destCapacity is not enough
+ * @return The length of the result string, if successful - or in case of a buffer overflow,
+ *         in which case it will be greater than destCapacity.
+ * @stable ICU 2.6
+ */
+U_STABLE int32_t U_EXPORT2
+uidna_toASCII(const UChar* src, int32_t srcLength, 
+              UChar* dest, int32_t destCapacity,
+              int32_t options,
+              UParseError* parseError,
+              UErrorCode* status);
+
+
+/**
+ * This function implements the ToUnicode operation as defined in the IDNA RFC.
+ * This operation is done on <b>single labels</b> before sending it to something that expects
+ * Unicode names. A label is an individual part of a domain name. Labels are usually
+ * separated by dots; for e.g." "www.example.com" is composed of 3 labels 
+ * "www","example", and "com".
+ *
+ * @param src               Input UChar array containing ASCII (ACE encoded) label.
+ * @param srcLength         Number of UChars in src, or -1 if NUL-terminated.
+ * @param dest Output       Converted UChar array containing Unicode equivalent of label.
+ * @param destCapacity      Size of dest.
+ * @param options           A bit set of options:
+ *  
+ *  - UIDNA_DEFAULT             Use default options, i.e., do not process unassigned code points
+ *                              and do not use STD3 ASCII rules
+ *                              If unassigned code points are found the operation fails with 
+ *                              U_UNASSIGNED_ERROR error code.
+ *
+ *  - UIDNA_ALLOW_UNASSIGNED      Unassigned values can be converted to ASCII for query operations
+ *                              If this option is set, the unassigned code points are in the input 
+ *                              are treated as normal Unicode code points. <b> Note: </b> This option is 
+ *                              required on toUnicode operation because the RFC mandates 
+ *                              verification of decoded ACE input by applying toASCII and comparing
+ *                              its output with source
+ *
+ *                          
+ *                          
+ *  - UIDNA_USE_STD3_RULES      Use STD3 ASCII rules for host name syntax restrictions
+ *                              If this option is set and the input does not satisfy STD3 rules,  
+ *                              the operation will fail with U_IDNA_STD3_ASCII_RULES_ERROR
+ *
+ * @param parseError        Pointer to UParseError struct to receive information on position 
+ *                          of error if an error is encountered. Can be NULL.
+ * @param status            ICU in/out error code parameter.
+ *                          U_INVALID_CHAR_FOUND if src contains
+ *                          unmatched single surrogates.
+ *                          U_INDEX_OUTOFBOUNDS_ERROR if src contains
+ *                          too many code points.
+ *                          U_BUFFER_OVERFLOW_ERROR if destCapacity is not enough
+ * @return The length of the result string, if successful - or in case of a buffer overflow,
+ *         in which case it will be greater than destCapacity.
+ * @stable ICU 2.6
+ */
+U_STABLE int32_t U_EXPORT2
+uidna_toUnicode(const UChar* src, int32_t srcLength,
+                UChar* dest, int32_t destCapacity,
+                int32_t options,
+                UParseError* parseError,
+                UErrorCode* status);
+
+
+/**
+ * Convenience function that implements the IDNToASCII operation as defined in the IDNA RFC.
+ * This operation is done on complete domain names, e.g: "www.example.com". 
+ * It is important to note that this operation can fail. If it fails, then the input 
+ * domain name cannot be used as an Internationalized Domain Name and the application
+ * should have methods defined to deal with the failure.
+ * 
+ * <b>Note:</b> IDNA RFC specifies that a conformant application should divide a domain name
+ * into separate labels, decide whether to apply allowUnassigned and useSTD3ASCIIRules on each, 
+ * and then convert. This function does not offer that level of granularity. The options once  
+ * set will apply to all labels in the domain name
+ *
+ * @param src               Input UChar array containing IDN in Unicode.
+ * @param srcLength         Number of UChars in src, or -1 if NUL-terminated.
+ * @param dest              Output UChar array with ASCII (ACE encoded) IDN.
+ * @param destCapacity      Size of dest.
+ * @param options           A bit set of options:
+ *  
+ *  - UIDNA_DEFAULT             Use default options, i.e., do not process unassigned code points
+ *                              and do not use STD3 ASCII rules
+ *                              If unassigned code points are found the operation fails with 
+ *                              U_UNASSIGNED_CODE_POINT_FOUND error code.
+ *
+ *  - UIDNA_ALLOW_UNASSIGNED    Unassigned values can be converted to ASCII for query operations
+ *                              If this option is set, the unassigned code points are in the input 
+ *                              are treated as normal Unicode code points.
+ *                          
+ *  - UIDNA_USE_STD3_RULES      Use STD3 ASCII rules for host name syntax restrictions
+ *                              If this option is set and the input does not satisfy STD3 rules,  
+ *                              the operation will fail with U_IDNA_STD3_ASCII_RULES_ERROR
+ * 
+ * @param parseError        Pointer to UParseError struct to receive information on position 
+ *                          of error if an error is encountered. Can be NULL.
+ * @param status            ICU in/out error code parameter.
+ *                          U_INVALID_CHAR_FOUND if src contains
+ *                          unmatched single surrogates.
+ *                          U_INDEX_OUTOFBOUNDS_ERROR if src contains
+ *                          too many code points.
+ *                          U_BUFFER_OVERFLOW_ERROR if destCapacity is not enough
+ * @return The length of the result string, if successful - or in case of a buffer overflow,
+ *         in which case it will be greater than destCapacity.
+ * @stable ICU 2.6
+ */
+U_STABLE int32_t U_EXPORT2
+uidna_IDNToASCII(  const UChar* src, int32_t srcLength,
+                   UChar* dest, int32_t destCapacity,
+                   int32_t options,
+                   UParseError* parseError,
+                   UErrorCode* status);
+
+/**
+ * Convenience function that implements the IDNToUnicode operation as defined in the IDNA RFC.
+ * This operation is done on complete domain names, e.g: "www.example.com". 
+ *
+ * <b>Note:</b> IDNA RFC specifies that a conformant application should divide a domain name
+ * into separate labels, decide whether to apply allowUnassigned and useSTD3ASCIIRules on each, 
+ * and then convert. This function does not offer that level of granularity. The options once  
+ * set will apply to all labels in the domain name
+ *
+ * @param src               Input UChar array containing IDN in ASCII (ACE encoded) form.
+ * @param srcLength         Number of UChars in src, or -1 if NUL-terminated.
+ * @param dest Output       UChar array containing Unicode equivalent of source IDN.
+ * @param destCapacity      Size of dest.
+ * @param options           A bit set of options:
+ *  
+ *  - UIDNA_DEFAULT             Use default options, i.e., do not process unassigned code points
+ *                              and do not use STD3 ASCII rules
+ *                              If unassigned code points are found the operation fails with 
+ *                              U_UNASSIGNED_CODE_POINT_FOUND error code.
+ *
+ *  - UIDNA_ALLOW_UNASSIGNED    Unassigned values can be converted to ASCII for query operations
+ *                              If this option is set, the unassigned code points are in the input 
+ *                              are treated as normal Unicode code points.
+ *                          
+ *  - UIDNA_USE_STD3_RULES      Use STD3 ASCII rules for host name syntax restrictions
+ *                              If this option is set and the input does not satisfy STD3 rules,  
+ *                              the operation will fail with U_IDNA_STD3_ASCII_RULES_ERROR
+ *
+ * @param parseError        Pointer to UParseError struct to receive information on position 
+ *                          of error if an error is encountered. Can be NULL.
+ * @param status            ICU in/out error code parameter.
+ *                          U_INVALID_CHAR_FOUND if src contains
+ *                          unmatched single surrogates.
+ *                          U_INDEX_OUTOFBOUNDS_ERROR if src contains
+ *                          too many code points.
+ *                          U_BUFFER_OVERFLOW_ERROR if destCapacity is not enough
+ * @return The length of the result string, if successful - or in case of a buffer overflow,
+ *         in which case it will be greater than destCapacity.
+ * @stable ICU 2.6
+ */
+U_STABLE int32_t U_EXPORT2
+uidna_IDNToUnicode(  const UChar* src, int32_t srcLength,
+                     UChar* dest, int32_t destCapacity,
+                     int32_t options,
+                     UParseError* parseError,
+                     UErrorCode* status);
+
+/**
+ * Compare two IDN strings for equivalence.
+ * This function splits the domain names into labels and compares them.
+ * According to IDN RFC, whenever two labels are compared, they are 
+ * considered equal if and only if their ASCII forms (obtained by 
+ * applying toASCII) match using an case-insensitive ASCII comparison.
+ * Two domain names are considered a match if and only if all labels 
+ * match regardless of whether label separators match.
+ *
+ * @param s1                First source string.
+ * @param length1           Length of first source string, or -1 if NUL-terminated.
+ *
+ * @param s2                Second source string.
+ * @param length2           Length of second source string, or -1 if NUL-terminated.
+ * @param options           A bit set of options:
+ *  
+ *  - UIDNA_DEFAULT             Use default options, i.e., do not process unassigned code points
+ *                              and do not use STD3 ASCII rules
+ *                              If unassigned code points are found the operation fails with 
+ *                              U_UNASSIGNED_CODE_POINT_FOUND error code.
+ *
+ *  - UIDNA_ALLOW_UNASSIGNED    Unassigned values can be converted to ASCII for query operations
+ *                              If this option is set, the unassigned code points are in the input 
+ *                              are treated as normal Unicode code points.
+ *                          
+ *  - UIDNA_USE_STD3_RULES      Use STD3 ASCII rules for host name syntax restrictions
+ *                              If this option is set and the input does not satisfy STD3 rules,  
+ *                              the operation will fail with U_IDNA_STD3_ASCII_RULES_ERROR
+ *
+ * @param status            ICU error code in/out parameter.
+ *                          Must fulfill U_SUCCESS before the function call.
+ * @return <0 or 0 or >0 as usual for string comparisons
+ * @stable ICU 2.6
+ */
+U_STABLE int32_t U_EXPORT2
+uidna_compare(  const UChar *s1, int32_t length1,
+                const UChar *s2, int32_t length2,
+                int32_t options,
+                UErrorCode* status);
+
+#endif /* #if !UCONFIG_NO_IDNA */
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/uintrnal.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/uintrnal.h b/src/apps/couch_collate/platform/osx/icu/unicode/uintrnal.h
new file mode 100644
index 0000000..6a01f6b
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/uintrnal.h
@@ -0,0 +1,180 @@
+/*
+*******************************************************************************
+*   Copyright (C) 2004-2008, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+*******************************************************************************
+*
+*   file name:  
+*   encoding:   US-ASCII
+*   tab size:   8 (not used)
+*   indentation:4
+*
+*   Created by: genheaders.pl, a perl script written by Ram Viswanadha
+*
+*  Contains data for commenting out APIs.
+*  Gets included by umachine.h
+*
+*  THIS FILE IS MACHINE-GENERATED, DON'T PLAY WITH IT IF YOU DON'T KNOW WHAT
+*  YOU ARE DOING, OTHERWISE VERY BAD THINGS WILL HAPPEN!
+*/
+
+#ifndef UINTRNAL_H
+#define UINTRNAL_H
+
+#ifdef U_HIDE_INTERNAL_API
+
+#    if U_DISABLE_RENAMING
+#        define RegexPatternDump RegexPatternDump_INTERNAL_API_DO_NOT_USE
+#        define pl_addFontRun pl_addFontRun_INTERNAL_API_DO_NOT_USE
+#        define pl_addLocaleRun pl_addLocaleRun_INTERNAL_API_DO_NOT_USE
+#        define pl_addValueRun pl_addValueRun_INTERNAL_API_DO_NOT_USE
+#        define pl_close pl_close_INTERNAL_API_DO_NOT_USE
+#        define pl_closeFontRuns pl_closeFontRuns_INTERNAL_API_DO_NOT_USE
+#        define pl_closeLine pl_closeLine_INTERNAL_API_DO_NOT_USE
+#        define pl_closeLocaleRuns pl_closeLocaleRuns_INTERNAL_API_DO_NOT_USE
+#        define pl_closeValueRuns pl_closeValueRuns_INTERNAL_API_DO_NOT_USE
+#        define pl_countLineRuns pl_countLineRuns_INTERNAL_API_DO_NOT_USE
+#        define pl_create pl_create_INTERNAL_API_DO_NOT_USE
+#        define pl_getAscent pl_getAscent_INTERNAL_API_DO_NOT_USE
+#        define pl_getDescent pl_getDescent_INTERNAL_API_DO_NOT_USE
+#        define pl_getFontRunCount pl_getFontRunCount_INTERNAL_API_DO_NOT_USE
+#        define pl_getFontRunFont pl_getFontRunFont_INTERNAL_API_DO_NOT_USE
+#        define pl_getFontRunLastLimit pl_getFontRunLastLimit_INTERNAL_API_DO_NOT_USE
+#        define pl_getFontRunLimit pl_getFontRunLimit_INTERNAL_API_DO_NOT_USE
+#        define pl_getLeading pl_getLeading_INTERNAL_API_DO_NOT_USE
+#        define pl_getLineAscent pl_getLineAscent_INTERNAL_API_DO_NOT_USE
+#        define pl_getLineDescent pl_getLineDescent_INTERNAL_API_DO_NOT_USE
+#        define pl_getLineLeading pl_getLineLeading_INTERNAL_API_DO_NOT_USE
+#        define pl_getLineVisualRun pl_getLineVisualRun_INTERNAL_API_DO_NOT_USE
+#        define pl_getLineWidth pl_getLineWidth_INTERNAL_API_DO_NOT_USE
+#        define pl_getLocaleRunCount pl_getLocaleRunCount_INTERNAL_API_DO_NOT_USE
+#        define pl_getLocaleRunLastLimit pl_getLocaleRunLastLimit_INTERNAL_API_DO_NOT_USE
+#        define pl_getLocaleRunLimit pl_getLocaleRunLimit_INTERNAL_API_DO_NOT_USE
+#        define pl_getLocaleRunLocale pl_getLocaleRunLocale_INTERNAL_API_DO_NOT_USE
+#        define pl_getParagraphLevel pl_getParagraphLevel_INTERNAL_API_DO_NOT_USE
+#        define pl_getTextDirection pl_getTextDirection_INTERNAL_API_DO_NOT_USE
+#        define pl_getValueRunCount pl_getValueRunCount_INTERNAL_API_DO_NOT_USE
+#        define pl_getValueRunLastLimit pl_getValueRunLastLimit_INTERNAL_API_DO_NOT_USE
+#        define pl_getValueRunLimit pl_getValueRunLimit_INTERNAL_API_DO_NOT_USE
+#        define pl_getValueRunValue pl_getValueRunValue_INTERNAL_API_DO_NOT_USE
+#        define pl_getVisualRunAscent pl_getVisualRunAscent_INTERNAL_API_DO_NOT_USE
+#        define pl_getVisualRunDescent pl_getVisualRunDescent_INTERNAL_API_DO_NOT_USE
+#        define pl_getVisualRunDirection pl_getVisualRunDirection_INTERNAL_API_DO_NOT_USE
+#        define pl_getVisualRunFont pl_getVisualRunFont_INTERNAL_API_DO_NOT_USE
+#        define pl_getVisualRunGlyphCount pl_getVisualRunGlyphCount_INTERNAL_API_DO_NOT_USE
+#        define pl_getVisualRunGlyphToCharMap pl_getVisualRunGlyphToCharMap_INTERNAL_API_DO_NOT_USE
+#        define pl_getVisualRunGlyphs pl_getVisualRunGlyphs_INTERNAL_API_DO_NOT_USE
+#        define pl_getVisualRunLeading pl_getVisualRunLeading_INTERNAL_API_DO_NOT_USE
+#        define pl_getVisualRunPositions pl_getVisualRunPositions_INTERNAL_API_DO_NOT_USE
+#        define pl_isComplex pl_isComplex_INTERNAL_API_DO_NOT_USE
+#        define pl_line pl_line_INTERNAL_API_DO_NOT_USE
+#        define pl_nextLine pl_nextLine_INTERNAL_API_DO_NOT_USE
+#        define pl_openEmptyFontRuns pl_openEmptyFontRuns_INTERNAL_API_DO_NOT_USE
+#        define pl_openEmptyLocaleRuns pl_openEmptyLocaleRuns_INTERNAL_API_DO_NOT_USE
+#        define pl_openEmptyValueRuns pl_openEmptyValueRuns_INTERNAL_API_DO_NOT_USE
+#        define pl_openFontRuns pl_openFontRuns_INTERNAL_API_DO_NOT_USE
+#        define pl_openLocaleRuns pl_openLocaleRuns_INTERNAL_API_DO_NOT_USE
+#        define pl_openValueRuns pl_openValueRuns_INTERNAL_API_DO_NOT_USE
+#        define pl_paragraph pl_paragraph_INTERNAL_API_DO_NOT_USE
+#        define pl_reflow pl_reflow_INTERNAL_API_DO_NOT_USE
+#        define pl_resetFontRuns pl_resetFontRuns_INTERNAL_API_DO_NOT_USE
+#        define pl_resetLocaleRuns pl_resetLocaleRuns_INTERNAL_API_DO_NOT_USE
+#        define pl_resetValueRuns pl_resetValueRuns_INTERNAL_API_DO_NOT_USE
+#        define pl_visualRun pl_visualRun_INTERNAL_API_DO_NOT_USE
+#        define ucol_equals ucol_equals_INTERNAL_API_DO_NOT_USE
+#        define ucol_forgetUCA ucol_forgetUCA_INTERNAL_API_DO_NOT_USE
+#        define ucol_getAttributeOrDefault ucol_getAttributeOrDefault_INTERNAL_API_DO_NOT_USE
+#        define ucol_getUnsafeSet ucol_getUnsafeSet_INTERNAL_API_DO_NOT_USE
+#        define ucol_nextProcessed ucol_nextProcessed_INTERNAL_API_DO_NOT_USE
+#        define ucol_prepareShortStringOpen ucol_prepareShortStringOpen_INTERNAL_API_DO_NOT_USE
+#        define ucol_previousProcessed ucol_previousProcessed_INTERNAL_API_DO_NOT_USE
+#        define uprv_getDefaultCodepage uprv_getDefaultCodepage_INTERNAL_API_DO_NOT_USE
+#        define uprv_getDefaultLocaleID uprv_getDefaultLocaleID_INTERNAL_API_DO_NOT_USE
+#        define ures_openFillIn ures_openFillIn_INTERNAL_API_DO_NOT_USE
+#        define usearch_search usearch_search_INTERNAL_API_DO_NOT_USE
+#        define usearch_searchBackwards usearch_searchBackwards_INTERNAL_API_DO_NOT_USE
+#        define utf8_appendCharSafeBody utf8_appendCharSafeBody_INTERNAL_API_DO_NOT_USE
+#        define utf8_back1SafeBody utf8_back1SafeBody_INTERNAL_API_DO_NOT_USE
+#        define utf8_countTrailBytes utf8_countTrailBytes_INTERNAL_API_DO_NOT_USE
+#        define utf8_nextCharSafeBody utf8_nextCharSafeBody_INTERNAL_API_DO_NOT_USE
+#        define utf8_prevCharSafeBody utf8_prevCharSafeBody_INTERNAL_API_DO_NOT_USE
+#    else
+#        define RegexPatternDump_4_0 RegexPatternDump_INTERNAL_API_DO_NOT_USE
+#        define pl_addFontRun_4_0 pl_addFontRun_INTERNAL_API_DO_NOT_USE
+#        define pl_addLocaleRun_4_0 pl_addLocaleRun_INTERNAL_API_DO_NOT_USE
+#        define pl_addValueRun_4_0 pl_addValueRun_INTERNAL_API_DO_NOT_USE
+#        define pl_closeFontRuns_4_0 pl_closeFontRuns_INTERNAL_API_DO_NOT_USE
+#        define pl_closeLine_4_0 pl_closeLine_INTERNAL_API_DO_NOT_USE
+#        define pl_closeLocaleRuns_4_0 pl_closeLocaleRuns_INTERNAL_API_DO_NOT_USE
+#        define pl_closeValueRuns_4_0 pl_closeValueRuns_INTERNAL_API_DO_NOT_USE
+#        define pl_close_4_0 pl_close_INTERNAL_API_DO_NOT_USE
+#        define pl_countLineRuns_4_0 pl_countLineRuns_INTERNAL_API_DO_NOT_USE
+#        define pl_create_4_0 pl_create_INTERNAL_API_DO_NOT_USE
+#        define pl_getAscent_4_0 pl_getAscent_INTERNAL_API_DO_NOT_USE
+#        define pl_getDescent_4_0 pl_getDescent_INTERNAL_API_DO_NOT_USE
+#        define pl_getFontRunCount_4_0 pl_getFontRunCount_INTERNAL_API_DO_NOT_USE
+#        define pl_getFontRunFont_4_0 pl_getFontRunFont_INTERNAL_API_DO_NOT_USE
+#        define pl_getFontRunLastLimit_4_0 pl_getFontRunLastLimit_INTERNAL_API_DO_NOT_USE
+#        define pl_getFontRunLimit_4_0 pl_getFontRunLimit_INTERNAL_API_DO_NOT_USE
+#        define pl_getLeading_4_0 pl_getLeading_INTERNAL_API_DO_NOT_USE
+#        define pl_getLineAscent_4_0 pl_getLineAscent_INTERNAL_API_DO_NOT_USE
+#        define pl_getLineDescent_4_0 pl_getLineDescent_INTERNAL_API_DO_NOT_USE
+#        define pl_getLineLeading_4_0 pl_getLineLeading_INTERNAL_API_DO_NOT_USE
+#        define pl_getLineVisualRun_4_0 pl_getLineVisualRun_INTERNAL_API_DO_NOT_USE
+#        define pl_getLineWidth_4_0 pl_getLineWidth_INTERNAL_API_DO_NOT_USE
+#        define pl_getLocaleRunCount_4_0 pl_getLocaleRunCount_INTERNAL_API_DO_NOT_USE
+#        define pl_getLocaleRunLastLimit_4_0 pl_getLocaleRunLastLimit_INTERNAL_API_DO_NOT_USE
+#        define pl_getLocaleRunLimit_4_0 pl_getLocaleRunLimit_INTERNAL_API_DO_NOT_USE
+#        define pl_getLocaleRunLocale_4_0 pl_getLocaleRunLocale_INTERNAL_API_DO_NOT_USE
+#        define pl_getParagraphLevel_4_0 pl_getParagraphLevel_INTERNAL_API_DO_NOT_USE
+#        define pl_getTextDirection_4_0 pl_getTextDirection_INTERNAL_API_DO_NOT_USE
+#        define pl_getValueRunCount_4_0 pl_getValueRunCount_INTERNAL_API_DO_NOT_USE
+#        define pl_getValueRunLastLimit_4_0 pl_getValueRunLastLimit_INTERNAL_API_DO_NOT_USE
+#        define pl_getValueRunLimit_4_0 pl_getValueRunLimit_INTERNAL_API_DO_NOT_USE
+#        define pl_getValueRunValue_4_0 pl_getValueRunValue_INTERNAL_API_DO_NOT_USE
+#        define pl_getVisualRunAscent_4_0 pl_getVisualRunAscent_INTERNAL_API_DO_NOT_USE
+#        define pl_getVisualRunDescent_4_0 pl_getVisualRunDescent_INTERNAL_API_DO_NOT_USE
+#        define pl_getVisualRunDirection_4_0 pl_getVisualRunDirection_INTERNAL_API_DO_NOT_USE
+#        define pl_getVisualRunFont_4_0 pl_getVisualRunFont_INTERNAL_API_DO_NOT_USE
+#        define pl_getVisualRunGlyphCount_4_0 pl_getVisualRunGlyphCount_INTERNAL_API_DO_NOT_USE
+#        define pl_getVisualRunGlyphToCharMap_4_0 pl_getVisualRunGlyphToCharMap_INTERNAL_API_DO_NOT_USE
+#        define pl_getVisualRunGlyphs_4_0 pl_getVisualRunGlyphs_INTERNAL_API_DO_NOT_USE
+#        define pl_getVisualRunLeading_4_0 pl_getVisualRunLeading_INTERNAL_API_DO_NOT_USE
+#        define pl_getVisualRunPositions_4_0 pl_getVisualRunPositions_INTERNAL_API_DO_NOT_USE
+#        define pl_isComplex_4_0 pl_isComplex_INTERNAL_API_DO_NOT_USE
+#        define pl_line_4_0 pl_line_INTERNAL_API_DO_NOT_USE
+#        define pl_nextLine_4_0 pl_nextLine_INTERNAL_API_DO_NOT_USE
+#        define pl_openEmptyFontRuns_4_0 pl_openEmptyFontRuns_INTERNAL_API_DO_NOT_USE
+#        define pl_openEmptyLocaleRuns_4_0 pl_openEmptyLocaleRuns_INTERNAL_API_DO_NOT_USE
+#        define pl_openEmptyValueRuns_4_0 pl_openEmptyValueRuns_INTERNAL_API_DO_NOT_USE
+#        define pl_openFontRuns_4_0 pl_openFontRuns_INTERNAL_API_DO_NOT_USE
+#        define pl_openLocaleRuns_4_0 pl_openLocaleRuns_INTERNAL_API_DO_NOT_USE
+#        define pl_openValueRuns_4_0 pl_openValueRuns_INTERNAL_API_DO_NOT_USE
+#        define pl_paragraph_4_0 pl_paragraph_INTERNAL_API_DO_NOT_USE
+#        define pl_reflow_4_0 pl_reflow_INTERNAL_API_DO_NOT_USE
+#        define pl_resetFontRuns_4_0 pl_resetFontRuns_INTERNAL_API_DO_NOT_USE
+#        define pl_resetLocaleRuns_4_0 pl_resetLocaleRuns_INTERNAL_API_DO_NOT_USE
+#        define pl_resetValueRuns_4_0 pl_resetValueRuns_INTERNAL_API_DO_NOT_USE
+#        define pl_visualRun_4_0 pl_visualRun_INTERNAL_API_DO_NOT_USE
+#        define ucol_equals_4_0 ucol_equals_INTERNAL_API_DO_NOT_USE
+#        define ucol_forgetUCA_4_0 ucol_forgetUCA_INTERNAL_API_DO_NOT_USE
+#        define ucol_getAttributeOrDefault_4_0 ucol_getAttributeOrDefault_INTERNAL_API_DO_NOT_USE
+#        define ucol_getUnsafeSet_4_0 ucol_getUnsafeSet_INTERNAL_API_DO_NOT_USE
+#        define ucol_nextProcessed_4_0 ucol_nextProcessed_INTERNAL_API_DO_NOT_USE
+#        define ucol_prepareShortStringOpen_4_0 ucol_prepareShortStringOpen_INTERNAL_API_DO_NOT_USE
+#        define ucol_previousProcessed_4_0 ucol_previousProcessed_INTERNAL_API_DO_NOT_USE
+#        define uprv_getDefaultCodepage_4_0 uprv_getDefaultCodepage_INTERNAL_API_DO_NOT_USE
+#        define uprv_getDefaultLocaleID_4_0 uprv_getDefaultLocaleID_INTERNAL_API_DO_NOT_USE
+#        define ures_openFillIn_4_0 ures_openFillIn_INTERNAL_API_DO_NOT_USE
+#        define usearch_searchBackwards_4_0 usearch_searchBackwards_INTERNAL_API_DO_NOT_USE
+#        define usearch_search_4_0 usearch_search_INTERNAL_API_DO_NOT_USE
+#        define utf8_appendCharSafeBody_4_0 utf8_appendCharSafeBody_INTERNAL_API_DO_NOT_USE
+#        define utf8_back1SafeBody_4_0 utf8_back1SafeBody_INTERNAL_API_DO_NOT_USE
+#        define utf8_countTrailBytes_4_0 utf8_countTrailBytes_INTERNAL_API_DO_NOT_USE
+#        define utf8_nextCharSafeBody_4_0 utf8_nextCharSafeBody_INTERNAL_API_DO_NOT_USE
+#        define utf8_prevCharSafeBody_4_0 utf8_prevCharSafeBody_INTERNAL_API_DO_NOT_USE
+#    endif /* U_DISABLE_RENAMING */
+
+#endif /* U_HIDE_INTERNAL_API */
+#endif /* UINTRNAL_H */
+


[77/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/stsearch.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/stsearch.h b/src/apps/couch_collate/platform/osx/icu/unicode/stsearch.h
new file mode 100644
index 0000000..8499752
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/stsearch.h
@@ -0,0 +1,518 @@
+/*
+**********************************************************************
+*   Copyright (C) 2001-2008 IBM and others. All rights reserved.
+**********************************************************************
+*   Date        Name        Description
+*  03/22/2000   helena      Creation.
+**********************************************************************
+*/
+
+#ifndef STSEARCH_H
+#define STSEARCH_H
+
+#include "unicode/utypes.h"
+
+/**
+ * \file 
+ * \brief C++ API: Service for searching text based on RuleBasedCollator.
+ */
+ 
+#if !UCONFIG_NO_COLLATION && !UCONFIG_NO_BREAK_ITERATION
+
+#include "unicode/tblcoll.h"
+#include "unicode/coleitr.h"
+#include "unicode/search.h"
+
+U_NAMESPACE_BEGIN
+
+/** 
+ *
+ * <tt>StringSearch</tt> is a <tt>SearchIterator</tt> that provides
+ * language-sensitive text searching based on the comparison rules defined
+ * in a {@link RuleBasedCollator} object.
+ * StringSearch ensures that language eccentricity can be 
+ * handled, e.g. for the German collator, characters &szlig; and SS will be matched 
+ * if case is chosen to be ignored.
+ * See the <a href="http://source.icu-project.org/repos/icu/icuhtml/trunk/design/collation/ICU_collation_design.htm">
+ * "ICU Collation Design Document"</a> for more information.
+ * <p> 
+ * The algorithm implemented is a modified form of the Boyer Moore's search.
+ * For more information  see 
+ * <a href="http://icu-project.org/docs/papers/efficient_text_searching_in_java.html">
+ * "Efficient Text Searching in Java"</a>, published in <i>Java Report</i> 
+ * in February, 1999, for further information on the algorithm.
+ * <p>
+ * There are 2 match options for selection:<br>
+ * Let S' be the sub-string of a text string S between the offsets start and 
+ * end <start, end>.
+ * <br>
+ * A pattern string P matches a text string S at the offsets <start, end> 
+ * if
+ * <pre> 
+ * option 1. Some canonical equivalent of P matches some canonical equivalent 
+ *           of S'
+ * option 2. P matches S' and if P starts or ends with a combining mark, 
+ *           there exists no non-ignorable combining mark before or after S? 
+ *           in S respectively. 
+ * </pre>
+ * Option 2. will be the default.
+ * <p>
+ * This search has APIs similar to that of other text iteration mechanisms 
+ * such as the break iterators in <tt>BreakIterator</tt>. Using these 
+ * APIs, it is easy to scan through text looking for all occurances of 
+ * a given pattern. This search iterator allows changing of direction by 
+ * calling a <tt>reset</tt> followed by a <tt>next</tt> or <tt>previous</tt>. 
+ * Though a direction change can occur without calling <tt>reset</tt> first,  
+ * this operation comes with some speed penalty.
+ * Match results in the forward direction will match the result matches in 
+ * the backwards direction in the reverse order
+ * <p>
+ * <tt>SearchIterator</tt> provides APIs to specify the starting position 
+ * within the text string to be searched, e.g. <tt>setOffset</tt>,
+ * <tt>preceding</tt> and <tt>following</tt>. Since the 
+ * starting position will be set as it is specified, please take note that 
+ * there are some danger points which the search may render incorrect 
+ * results:
+ * <ul>
+ * <li> The midst of a substring that requires normalization.
+ * <li> If the following match is to be found, the position should not be the
+ *      second character which requires to be swapped with the preceding 
+ *      character. Vice versa, if the preceding match is to be found, 
+ *      position to search from should not be the first character which 
+ *      requires to be swapped with the next character. E.g certain Thai and
+ *      Lao characters require swapping.
+ * <li> If a following pattern match is to be found, any position within a 
+ *      contracting sequence except the first will fail. Vice versa if a 
+ *      preceding pattern match is to be found, a invalid starting point 
+ *      would be any character within a contracting sequence except the last.
+ * </ul>
+ * <p>
+ * A breakiterator can be used if only matches at logical breaks are desired.
+ * Using a breakiterator will only give you results that exactly matches the
+ * boundaries given by the breakiterator. For instance the pattern "e" will
+ * not be found in the string "\u00e9" if a character break iterator is used.
+ * <p>
+ * Options are provided to handle overlapping matches. 
+ * E.g. In English, overlapping matches produces the result 0 and 2 
+ * for the pattern "abab" in the text "ababab", where else mutually 
+ * exclusive matches only produce the result of 0.
+ * <p>
+ * Though collator attributes will be taken into consideration while 
+ * performing matches, there are no APIs here for setting and getting the 
+ * attributes. These attributes can be set by getting the collator
+ * from <tt>getCollator</tt> and using the APIs in <tt>coll.h</tt>.
+ * Lastly to update StringSearch to the new collator attributes, 
+ * reset() has to be called.
+ * <p> 
+ * Restriction: <br>
+ * Currently there are no composite characters that consists of a
+ * character with combining class > 0 before a character with combining 
+ * class == 0. However, if such a character exists in the future,  
+ * StringSearch does not guarantee the results for option 1.
+ * <p>
+ * Consult the <tt>SearchIterator</tt> documentation for information on
+ * and examples of how to use instances of this class to implement text
+ * searching.
+ * <pre><code>
+ * UnicodeString target("The quick brown fox jumps over the lazy dog.");
+ * UnicodeString pattern("fox");
+ *
+ * UErrorCode      error = U_ZERO_ERROR;
+ * StringSearch iter(pattern, target, Locale::getUS(), NULL, status);
+ * for (int pos = iter.first(error);
+ *      pos != USEARCH_DONE; 
+ *      pos = iter.next(error))
+ * {
+ *     printf("Found match at %d pos, length is %d\n", pos, 
+ *                                             iter.getMatchLength());
+ * }
+ * </code></pre>
+ * <p>
+ * Note, StringSearch is not to be subclassed.
+ * </p>
+ * @see SearchIterator
+ * @see RuleBasedCollator
+ * @since ICU 2.0
+ */
+
+class U_I18N_API StringSearch : public SearchIterator
+{
+public:
+
+    // public constructors and destructors --------------------------------
+
+    /**
+     * Creating a <tt>StringSearch</tt> instance using the argument locale 
+     * language rule set. A collator will be created in the process, which 
+     * will be owned by this instance and will be deleted during 
+     * destruction
+     * @param pattern The text for which this object will search.
+     * @param text    The text in which to search for the pattern.
+     * @param locale  A locale which defines the language-sensitive 
+     *                comparison rules used to determine whether text in the 
+     *                pattern and target matches. 
+     * @param breakiter A <tt>BreakIterator</tt> object used to constrain 
+     *                the matches that are found. Matches whose start and end 
+     *                indices in the target text are not boundaries as 
+     *                determined by the <tt>BreakIterator</tt> are 
+     *                ignored. If this behavior is not desired, 
+     *                <tt>NULL</tt> can be passed in instead.
+     * @param status  for errors if any. If pattern or text is NULL, or if
+     *               either the length of pattern or text is 0 then an 
+     *               U_ILLEGAL_ARGUMENT_ERROR is returned.
+     * @stable ICU 2.0
+     */
+    StringSearch(const UnicodeString &pattern, const UnicodeString &text,
+                 const Locale        &locale,       
+                       BreakIterator *breakiter,
+                       UErrorCode    &status);
+
+    /**
+     * Creating a <tt>StringSearch</tt> instance using the argument collator 
+     * language rule set. Note, user retains the ownership of this collator, 
+     * it does not get destroyed during this instance's destruction.
+     * @param pattern The text for which this object will search.
+     * @param text    The text in which to search for the pattern.
+     * @param coll    A <tt>RuleBasedCollator</tt> object which defines 
+     *                the language-sensitive comparison rules used to 
+     *                determine whether text in the pattern and target 
+     *                matches. User is responsible for the clearing of this
+     *                object.
+     * @param breakiter A <tt>BreakIterator</tt> object used to constrain 
+     *                the matches that are found. Matches whose start and end 
+     *                indices in the target text are not boundaries as 
+     *                determined by the <tt>BreakIterator</tt> are 
+     *                ignored. If this behavior is not desired, 
+     *                <tt>NULL</tt> can be passed in instead.
+     * @param status for errors if any. If either the length of pattern or 
+     *               text is 0 then an U_ILLEGAL_ARGUMENT_ERROR is returned.
+     * @stable ICU 2.0
+     */
+    StringSearch(const UnicodeString     &pattern, 
+                 const UnicodeString     &text,
+                       RuleBasedCollator *coll,       
+                       BreakIterator     *breakiter,
+                       UErrorCode        &status);
+
+    /**
+     * Creating a <tt>StringSearch</tt> instance using the argument locale 
+     * language rule set. A collator will be created in the process, which 
+     * will be owned by this instance and will be deleted during 
+     * destruction
+     * <p>
+     * Note: No parsing of the text within the <tt>CharacterIterator</tt> 
+     * will be done during searching for this version. The block of text 
+     * in <tt>CharacterIterator</tt> will be used as it is.
+     * @param pattern The text for which this object will search.
+     * @param text    The text iterator in which to search for the pattern.
+     * @param locale  A locale which defines the language-sensitive 
+     *                comparison rules used to determine whether text in the 
+     *                pattern and target matches. User is responsible for 
+     *                the clearing of this object.
+     * @param breakiter A <tt>BreakIterator</tt> object used to constrain 
+     *                the matches that are found. Matches whose start and end 
+     *                indices in the target text are not boundaries as 
+     *                determined by the <tt>BreakIterator</tt> are 
+     *                ignored. If this behavior is not desired, 
+     *                <tt>NULL</tt> can be passed in instead.
+     * @param status for errors if any. If either the length of pattern or 
+     *               text is 0 then an U_ILLEGAL_ARGUMENT_ERROR is returned.
+     * @stable ICU 2.0
+     */
+    StringSearch(const UnicodeString &pattern, CharacterIterator &text,
+                 const Locale        &locale, 
+                       BreakIterator *breakiter,
+                       UErrorCode    &status);
+
+    /**
+     * Creating a <tt>StringSearch</tt> instance using the argument collator 
+     * language rule set. Note, user retains the ownership of this collator, 
+     * it does not get destroyed during this instance's destruction.
+     * <p>
+     * Note: No parsing of the text within the <tt>CharacterIterator</tt> 
+     * will be done during searching for this version. The block of text 
+     * in <tt>CharacterIterator</tt> will be used as it is.
+     * @param pattern The text for which this object will search.
+     * @param text    The text in which to search for the pattern.
+     * @param coll    A <tt>RuleBasedCollator</tt> object which defines 
+     *                the language-sensitive comparison rules used to 
+     *                determine whether text in the pattern and target 
+     *                matches. User is responsible for the clearing of this
+     *                object.
+     * @param breakiter A <tt>BreakIterator</tt> object used to constrain 
+     *                the matches that are found. Matches whose start and end 
+     *                indices in the target text are not boundaries as 
+     *                determined by the <tt>BreakIterator</tt> are 
+     *                ignored. If this behavior is not desired, 
+     *                <tt>NULL</tt> can be passed in instead.
+     * @param status for errors if any. If either the length of pattern or 
+     *               text is 0 then an U_ILLEGAL_ARGUMENT_ERROR is returned.
+     * @stable ICU 2.0
+     */
+    StringSearch(const UnicodeString     &pattern, CharacterIterator &text,
+                       RuleBasedCollator *coll, 
+                       BreakIterator     *breakiter,
+                       UErrorCode        &status);
+
+    /**
+     * Copy constructor that creates a StringSearch instance with the same 
+     * behavior, and iterating over the same text.
+     * @param that StringSearch instance to be copied.
+     * @stable ICU 2.0
+     */
+    StringSearch(const StringSearch &that);
+
+    /**
+    * Destructor. Cleans up the search iterator data struct.
+    * If a collator is created in the constructor, it will be destroyed here.
+    * @stable ICU 2.0
+    */
+    virtual ~StringSearch(void);
+
+    /**
+     * Clone this object.
+     * Clones can be used concurrently in multiple threads.
+     * If an error occurs, then NULL is returned.
+     * The caller must delete the clone.
+     *
+     * @return a clone of this object
+     *
+     * @see getDynamicClassID
+     * @stable ICU 2.8
+     */
+    StringSearch *clone() const;
+
+    // operator overloading ---------------------------------------------
+
+    /**
+     * Assignment operator. Sets this iterator to have the same behavior,
+     * and iterate over the same text, as the one passed in.
+     * @param that instance to be copied.
+     * @stable ICU 2.0
+     */
+    StringSearch & operator=(const StringSearch &that);
+
+    /**
+     * Equality operator. 
+     * @param that instance to be compared.
+     * @return TRUE if both instances have the same attributes, 
+     *         breakiterators, collators and iterate over the same text 
+     *         while looking for the same pattern.
+     * @stable ICU 2.0
+     */
+    virtual UBool operator==(const SearchIterator &that) const;
+
+    // public get and set methods ----------------------------------------
+
+    /**
+     * Sets the index to point to the given position, and clears any state 
+     * that's affected.
+     * <p>
+     * This method takes the argument index and sets the position in the text 
+     * string accordingly without checking if the index is pointing to a 
+     * valid starting point to begin searching. 
+     * @param position within the text to be set. If position is less
+     *          than or greater than the text range for searching, 
+     *          an U_INDEX_OUTOFBOUNDS_ERROR will be returned
+     * @param status for errors if it occurs
+     * @stable ICU 2.0
+     */
+    virtual void setOffset(int32_t position, UErrorCode &status);
+
+    /**
+     * Return the current index in the text being searched.
+     * If the iteration has gone past the end of the text
+     * (or past the beginning for a backwards search), USEARCH_DONE
+     * is returned.
+     * @return current index in the text being searched.
+     * @stable ICU 2.0
+     */
+    virtual int32_t getOffset(void) const;
+
+    /**
+     * Set the target text to be searched.
+     * Text iteration will hence begin at the start of the text string. 
+     * This method is 
+     * useful if you want to re-use an iterator to search for the same 
+     * pattern within a different body of text.
+     * @param text text string to be searched
+     * @param status for errors if any. If the text length is 0 then an 
+     *        U_ILLEGAL_ARGUMENT_ERROR is returned.
+     * @stable ICU 2.0
+     */
+    virtual void setText(const UnicodeString &text, UErrorCode &status);
+    
+    /**
+     * Set the target text to be searched.
+     * Text iteration will hence begin at the start of the text string. 
+     * This method is 
+     * useful if you want to re-use an iterator to search for the same 
+     * pattern within a different body of text.
+     * Note: No parsing of the text within the <tt>CharacterIterator</tt> 
+     * will be done during searching for this version. The block of text 
+     * in <tt>CharacterIterator</tt> will be used as it is.
+     * @param text text string to be searched
+     * @param status for errors if any. If the text length is 0 then an 
+     *        U_ILLEGAL_ARGUMENT_ERROR is returned.
+     * @stable ICU 2.0
+     */
+    virtual void setText(CharacterIterator &text, UErrorCode &status);
+
+    /**
+     * Gets the collator used for the language rules.
+     * <p>
+     * Caller may modify but <b>must not</b> delete the <tt>RuleBasedCollator</tt>!
+     * Modifications to this collator will affect the original collator passed in to 
+     * the <tt>StringSearch></tt> constructor or to setCollator, if any.
+     * @return collator used for string search
+     * @stable ICU 2.0
+     */
+    RuleBasedCollator * getCollator() const;
+    
+    /**
+     * Sets the collator used for the language rules. User retains the 
+     * ownership of this collator, thus the responsibility of deletion lies 
+     * with the user. This method causes internal data such as Boyer-Moore 
+     * shift tables to be recalculated, but the iterator's position is 
+     * unchanged.
+     * @param coll    collator 
+     * @param status  for errors if any
+     * @stable ICU 2.0
+     */
+    void setCollator(RuleBasedCollator *coll, UErrorCode &status);
+    
+    /**
+     * Sets the pattern used for matching.
+     * Internal data like the Boyer Moore table will be recalculated, but 
+     * the iterator's position is unchanged.
+     * @param pattern search pattern to be found
+     * @param status for errors if any. If the pattern length is 0 then an 
+     *               U_ILLEGAL_ARGUMENT_ERROR is returned.
+     * @stable ICU 2.0
+     */
+    void setPattern(const UnicodeString &pattern, UErrorCode &status);
+    
+    /**
+     * Gets the search pattern.
+     * @return pattern used for matching
+     * @stable ICU 2.0
+     */
+    const UnicodeString & getPattern() const;
+
+    // public methods ----------------------------------------------------
+
+    /** 
+     * Reset the iteration.
+     * Search will begin at the start of the text string if a forward 
+     * iteration is initiated before a backwards iteration. Otherwise if 
+     * a backwards iteration is initiated before a forwards iteration, the 
+     * search will begin at the end of the text string.
+     * @stable ICU 2.0
+     */
+    virtual void reset();
+
+    /**
+     * Returns a copy of StringSearch with the same behavior, and 
+     * iterating over the same text, as this one. Note that all data will be
+     * replicated, except for the user-specified collator and the
+     * breakiterator.
+     * @return cloned object
+     * @stable ICU 2.0
+     */
+    virtual SearchIterator * safeClone(void) const;
+    
+    /**
+     * ICU "poor man's RTTI", returns a UClassID for the actual class.
+     *
+     * @stable ICU 2.2
+     */
+    virtual UClassID getDynamicClassID() const;
+
+    /**
+     * ICU "poor man's RTTI", returns a UClassID for this class.
+     *
+     * @stable ICU 2.2
+     */
+    static UClassID U_EXPORT2 getStaticClassID();
+
+protected:
+
+    // protected method -------------------------------------------------
+
+    /**
+     * Search forward for matching text, starting at a given location.
+     * Clients should not call this method directly; instead they should 
+     * call {@link SearchIterator#next }.
+     * <p>
+     * If a match is found, this method returns the index at which the match
+     * starts and calls {@link SearchIterator#setMatchLength } with the number 
+     * of characters in the target text that make up the match. If no match 
+     * is found, the method returns <tt>USEARCH_DONE</tt>.
+     * <p>
+     * The <tt>StringSearch</tt> is adjusted so that its current index 
+     * (as returned by {@link #getOffset }) is the match position if one was 
+     * found.
+     * If a match is not found, <tt>USEARCH_DONE</tt> will be returned and
+     * the <tt>StringSearch</tt> will be adjusted to the index USEARCH_DONE.
+     * @param position The index in the target text at which the search 
+     *                 starts
+     * @param status for errors if any occurs
+     * @return The index at which the matched text in the target starts, or 
+     *         USEARCH_DONE if no match was found.
+     * @stable ICU 2.0
+     */
+    virtual int32_t handleNext(int32_t position, UErrorCode &status);
+
+    /**
+     * Search backward for matching text, starting at a given location.
+     * Clients should not call this method directly; instead they should call
+     * <tt>SearchIterator.previous()</tt>, which this method overrides.
+     * <p>
+     * If a match is found, this method returns the index at which the match
+     * starts and calls {@link SearchIterator#setMatchLength } with the number 
+     * of characters in the target text that make up the match. If no match 
+     * is found, the method returns <tt>USEARCH_DONE</tt>.
+     * <p>
+     * The <tt>StringSearch</tt> is adjusted so that its current index 
+     * (as returned by {@link #getOffset }) is the match position if one was 
+     * found.
+     * If a match is not found, <tt>USEARCH_DONE</tt> will be returned and
+     * the <tt>StringSearch</tt> will be adjusted to the index USEARCH_DONE.
+     * @param position The index in the target text at which the search 
+     *                 starts.
+     * @param status for errors if any occurs
+     * @return The index at which the matched text in the target starts, or 
+     *         USEARCH_DONE if no match was found.
+     * @stable ICU 2.0
+     */
+    virtual int32_t handlePrev(int32_t position, UErrorCode &status);
+    
+private :
+    StringSearch(); // default constructor not implemented
+
+    // private data members ----------------------------------------------
+
+    /**
+    * RuleBasedCollator, contains exactly the same UCollator * in m_strsrch_
+    * @stable ICU 2.0
+    */
+    RuleBasedCollator  m_collator_;
+    /**
+    * Pattern text
+    * @stable ICU 2.0
+    */
+    UnicodeString      m_pattern_;
+    /**
+    * String search struct data
+    * @stable ICU 2.0
+    */
+    UStringSearch     *m_strsrch_;
+
+};
+
+U_NAMESPACE_END
+
+#endif /* #if !UCONFIG_NO_COLLATION */
+
+#endif
+

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/symtable.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/symtable.h b/src/apps/couch_collate/platform/osx/icu/unicode/symtable.h
new file mode 100644
index 0000000..428f8bf
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/symtable.h
@@ -0,0 +1,112 @@
+/*
+**********************************************************************
+*   Copyright (c) 2000-2005, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+**********************************************************************
+*   Date        Name        Description
+*   02/04/00    aliu        Creation.
+**********************************************************************
+*/
+#ifndef SYMTABLE_H
+#define SYMTABLE_H
+
+#include "unicode/utypes.h"
+#include "unicode/uobject.h"
+
+/**
+ * \file 
+ * \brief C++ API: An interface that defines both lookup protocol and parsing of
+ * symbolic names.
+ */
+ 
+U_NAMESPACE_BEGIN
+
+class ParsePosition;
+class UnicodeFunctor;
+class UnicodeSet;
+class UnicodeString;
+
+/**
+ * An interface that defines both lookup protocol and parsing of
+ * symbolic names.
+ *
+ * <p>A symbol table maintains two kinds of mappings.  The first is
+ * between symbolic names and their values.  For example, if the
+ * variable with the name "start" is set to the value "alpha"
+ * (perhaps, though not necessarily, through an expression such as
+ * "$start=alpha"), then the call lookup("start") will return the
+ * char[] array ['a', 'l', 'p', 'h', 'a'].
+ *
+ * <p>The second kind of mapping is between character values and
+ * UnicodeMatcher objects.  This is used by RuleBasedTransliterator,
+ * which uses characters in the private use area to represent objects
+ * such as UnicodeSets.  If U+E015 is mapped to the UnicodeSet [a-z],
+ * then lookupMatcher(0xE015) will return the UnicodeSet [a-z].
+ *
+ * <p>Finally, a symbol table defines parsing behavior for symbolic
+ * names.  All symbolic names start with the SYMBOL_REF character.
+ * When a parser encounters this character, it calls parseReference()
+ * with the position immediately following the SYMBOL_REF.  The symbol
+ * table parses the name, if there is one, and returns it.
+ *
+ * @stable ICU 2.8
+ */
+class U_COMMON_API SymbolTable /* not : public UObject because this is an interface/mixin class */ {
+public:
+
+    /**
+     * The character preceding a symbol reference name.
+     * @stable ICU 2.8
+     */
+    enum { SYMBOL_REF = 0x0024 /*$*/ };
+
+    /**
+     * Destructor.
+     * @stable ICU 2.8
+     */
+    virtual ~SymbolTable();
+
+    /**
+     * Lookup the characters associated with this string and return it.
+     * Return <tt>NULL</tt> if no such name exists.  The resultant
+     * string may have length zero.
+     * @param s the symbolic name to lookup
+     * @return a string containing the name's value, or <tt>NULL</tt> if
+     * there is no mapping for s.
+     * @stable ICU 2.8
+     */
+    virtual const UnicodeString* lookup(const UnicodeString& s) const = 0;
+
+    /**
+     * Lookup the UnicodeMatcher associated with the given character, and
+     * return it.  Return <tt>NULL</tt> if not found.
+     * @param ch a 32-bit code point from 0 to 0x10FFFF inclusive.
+     * @return the UnicodeMatcher object represented by the given
+     * character, or NULL if there is no mapping for ch.
+     * @stable ICU 2.8
+     */
+    virtual const UnicodeFunctor* lookupMatcher(UChar32 ch) const = 0;
+
+    /**
+     * Parse a symbol reference name from the given string, starting
+     * at the given position.  If no valid symbol reference name is
+     * found, return the empty string and leave pos unchanged.  That is, if the
+     * character at pos cannot start a name, or if pos is at or after
+     * text.length(), then return an empty string.  This indicates an
+     * isolated SYMBOL_REF character.
+     * @param text the text to parse for the name
+     * @param pos on entry, the index of the first character to parse.
+     * This is the character following the SYMBOL_REF character.  On
+     * exit, the index after the last parsed character.  If the parse
+     * failed, pos is unchanged on exit.
+     * @param limit the index after the last character to be parsed.
+     * @return the parsed name, or an empty string if there is no
+     * valid symbolic name at the given position.
+     * @stable ICU 2.8
+     */
+    virtual UnicodeString parseReference(const UnicodeString& text,
+                                         ParsePosition& pos, int32_t limit) const = 0;
+};
+U_NAMESPACE_END
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/tblcoll.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/tblcoll.h b/src/apps/couch_collate/platform/osx/icu/unicode/tblcoll.h
new file mode 100644
index 0000000..2fdd63b
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/tblcoll.h
@@ -0,0 +1,926 @@
+/*
+******************************************************************************
+* Copyright (C) 1996-2008, International Business Machines Corporation and
+* others. All Rights Reserved.
+******************************************************************************
+*/
+
+/**
+ * \file 
+ * \brief C++ API: RuleBasedCollator class provides the simple implementation of Collator.
+ */
+
+/**
+* File tblcoll.h
+*
+* Created by: Helena Shih
+*
+* Modification History:
+*
+*  Date        Name        Description
+*  2/5/97      aliu        Added streamIn and streamOut methods.  Added
+*                          constructor which reads RuleBasedCollator object from
+*                          a binary file.  Added writeToFile method which streams
+*                          RuleBasedCollator out to a binary file.  The streamIn
+*                          and streamOut methods use istream and ostream objects
+*                          in binary mode.
+*  2/12/97     aliu        Modified to use TableCollationData sub-object to
+*                          hold invariant data.
+*  2/13/97     aliu        Moved several methods into this class from Collation.
+*                          Added a private RuleBasedCollator(Locale&) constructor,
+*                          to be used by Collator::createDefault().  General
+*                          clean up.
+*  2/20/97     helena      Added clone, operator==, operator!=, operator=, and copy
+*                          constructor and getDynamicClassID.
+*  3/5/97      aliu        Modified constructFromFile() to add parameter
+*                          specifying whether or not binary loading is to be
+*                          attempted.  This is required for dynamic rule loading.
+* 05/07/97     helena      Added memory allocation error detection.
+*  6/17/97     helena      Added IDENTICAL strength for compare, changed getRules to
+*                          use MergeCollation::getPattern.
+*  6/20/97     helena      Java class name change.
+*  8/18/97     helena      Added internal API documentation.
+* 09/03/97     helena      Added createCollationKeyValues().
+* 02/10/98     damiba      Added compare with "length" parameter
+* 08/05/98     erm         Synched with 1.2 version of RuleBasedCollator.java
+* 04/23/99     stephen     Removed EDecompositionMode, merged with
+*                          Normalizer::EMode
+* 06/14/99     stephen     Removed kResourceBundleSuffix
+* 11/02/99     helena      Collator performance enhancements.  Eliminates the
+*                          UnicodeString construction and special case for NO_OP.
+* 11/23/99     srl         More performance enhancements. Updates to NormalizerIterator
+*                          internal state management.
+* 12/15/99     aliu        Update to support Thai collation.  Move NormalizerIterator
+*                          to implementation file.
+* 01/29/01     synwee      Modified into a C++ wrapper which calls C API
+*                          (ucol.h)
+*/
+
+#ifndef TBLCOLL_H
+#define TBLCOLL_H
+
+#include "unicode/utypes.h"
+
+ 
+#if !UCONFIG_NO_COLLATION
+
+#include "unicode/coll.h"
+#include "unicode/ucol.h"
+#include "unicode/sortkey.h"
+#include "unicode/normlzr.h"
+
+U_NAMESPACE_BEGIN
+
+/**
+* @stable ICU 2.0
+*/
+class StringSearch;
+/**
+* @stable ICU 2.0
+*/
+class CollationElementIterator;
+
+/**
+ * The RuleBasedCollator class provides the simple implementation of
+ * Collator, using data-driven tables. The user can create a customized
+ * table-based collation.
+ * <P>
+ * <em>Important: </em>The ICU collation service has been reimplemented 
+ * in order to achieve better performance and UCA compliance. 
+ * For details, see the 
+ * <a href="http://source.icu-project.org/repos/icu/icuhtml/trunk/design/collation/ICU_collation_design.htm">
+ * collation design document</a>.
+ * <p>
+ * RuleBasedCollator is a thin C++ wrapper over the C implementation.
+ * <p>
+ * For more information about the collation service see 
+ * <a href="http://icu-project.org/userguide/Collate_Intro.html">the users guide</a>.
+ * <p>
+ * Collation service provides correct sorting orders for most locales supported in ICU. 
+ * If specific data for a locale is not available, the orders eventually falls back
+ * to the <a href="http://www.unicode.org/unicode/reports/tr10/">UCA sort order</a>. 
+ * <p>
+ * Sort ordering may be customized by providing your own set of rules. For more on
+ * this subject see the <a href="http://icu-project.org/userguide/Collate_Customization.html">
+ * Collation customization</a> section of the users guide.
+ * <p>
+ * Note, RuleBasedCollator is not to be subclassed.
+ * @see        Collator
+ * @version    2.0 11/15/2001
+ */
+class U_I18N_API RuleBasedCollator : public Collator
+{
+public:
+
+  // constructor -------------------------------------------------------------
+
+    /**
+     * RuleBasedCollator constructor. This takes the table rules and builds a
+     * collation table out of them. Please see RuleBasedCollator class
+     * description for more details on the collation rule syntax.
+     * @param rules the collation rules to build the collation table from.
+     * @param status reporting a success or an error.
+     * @see Locale
+     * @stable ICU 2.0
+     */
+    RuleBasedCollator(const UnicodeString& rules, UErrorCode& status);
+
+    /**
+     * RuleBasedCollator constructor. This takes the table rules and builds a
+     * collation table out of them. Please see RuleBasedCollator class
+     * description for more details on the collation rule syntax.
+     * @param rules the collation rules to build the collation table from.
+     * @param collationStrength default strength for comparison
+     * @param status reporting a success or an error.
+     * @see Locale
+     * @stable ICU 2.0
+     */
+    RuleBasedCollator(const UnicodeString& rules,
+                       ECollationStrength collationStrength,
+                       UErrorCode& status);
+
+    /**
+     * RuleBasedCollator constructor. This takes the table rules and builds a
+     * collation table out of them. Please see RuleBasedCollator class
+     * description for more details on the collation rule syntax.
+     * @param rules the collation rules to build the collation table from.
+     * @param decompositionMode the normalisation mode
+     * @param status reporting a success or an error.
+     * @see Locale
+     * @stable ICU 2.0
+     */
+    RuleBasedCollator(const UnicodeString& rules,
+                    UColAttributeValue decompositionMode,
+                    UErrorCode& status);
+
+    /**
+     * RuleBasedCollator constructor. This takes the table rules and builds a
+     * collation table out of them. Please see RuleBasedCollator class
+     * description for more details on the collation rule syntax.
+     * @param rules the collation rules to build the collation table from.
+     * @param collationStrength default strength for comparison
+     * @param decompositionMode the normalisation mode
+     * @param status reporting a success or an error.
+     * @see Locale
+     * @stable ICU 2.0
+     */
+    RuleBasedCollator(const UnicodeString& rules,
+                    ECollationStrength collationStrength,
+                    UColAttributeValue decompositionMode,
+                    UErrorCode& status);
+
+    /**
+     * Copy constructor.
+     * @param other the RuleBasedCollator object to be copied
+     * @see Locale
+     * @stable ICU 2.0
+     */
+    RuleBasedCollator(const RuleBasedCollator& other);
+
+
+    /** Opens a collator from a collator binary image created using
+    *  cloneBinary. Binary image used in instantiation of the 
+    *  collator remains owned by the user and should stay around for 
+    *  the lifetime of the collator. The API also takes a base collator
+    *  which usualy should be UCA.
+    *  @param bin binary image owned by the user and required through the
+    *             lifetime of the collator
+    *  @param length size of the image. If negative, the API will try to
+    *                figure out the length of the image
+    *  @param base fallback collator, usually UCA. Base is required to be
+    *              present through the lifetime of the collator. Currently 
+    *              it cannot be NULL.
+    *  @param status for catching errors
+    *  @return newly created collator
+    *  @see cloneBinary
+    *  @stable ICU 3.4
+    */
+    RuleBasedCollator(const uint8_t *bin, int32_t length, 
+                    const RuleBasedCollator *base, 
+                    UErrorCode &status);
+    // destructor --------------------------------------------------------------
+
+    /**
+     * Destructor.
+     * @stable ICU 2.0
+     */
+    virtual ~RuleBasedCollator();
+
+    // public methods ----------------------------------------------------------
+
+    /**
+     * Assignment operator.
+     * @param other other RuleBasedCollator object to compare with.
+     * @stable ICU 2.0
+     */
+    RuleBasedCollator& operator=(const RuleBasedCollator& other);
+
+    /**
+     * Returns true if argument is the same as this object.
+     * @param other Collator object to be compared.
+     * @return true if arguments is the same as this object.
+     * @stable ICU 2.0
+     */
+    virtual UBool operator==(const Collator& other) const;
+
+    /**
+     * Returns true if argument is not the same as this object.
+     * @param other Collator object to be compared
+     * @return returns true if argument is not the same as this object.
+     * @stable ICU 2.0
+     */
+    virtual UBool operator!=(const Collator& other) const;
+
+    /**
+     * Makes a deep copy of the object.
+     * The caller owns the returned object.
+     * @return the cloned object.
+     * @stable ICU 2.0
+     */
+    virtual Collator* clone(void) const;
+
+    /**
+     * Creates a collation element iterator for the source string. The caller of
+     * this method is responsible for the memory management of the return
+     * pointer.
+     * @param source the string over which the CollationElementIterator will
+     *        iterate.
+     * @return the collation element iterator of the source string using this as
+     *         the based Collator.
+     * @stable ICU 2.2
+     */
+    virtual CollationElementIterator* createCollationElementIterator(
+                                           const UnicodeString& source) const;
+
+    /**
+     * Creates a collation element iterator for the source. The caller of this
+     * method is responsible for the memory management of the returned pointer.
+     * @param source the CharacterIterator which produces the characters over
+     *        which the CollationElementItgerator will iterate.
+     * @return the collation element iterator of the source using this as the
+     *         based Collator.
+     * @stable ICU 2.2
+     */
+    virtual CollationElementIterator* createCollationElementIterator(
+                                         const CharacterIterator& source) const;
+
+    /**
+     * Compares a range of character data stored in two different strings based
+     * on the collation rules. Returns information about whether a string is
+     * less than, greater than or equal to another string in a language.
+     * This can be overriden in a subclass.
+     * @param source the source string.
+     * @param target the target string to be compared with the source string.
+     * @return the comparison result. GREATER if the source string is greater
+     *         than the target string, LESS if the source is less than the
+     *         target. Otherwise, returns EQUAL.
+     * @deprecated ICU 2.6 Use overload with UErrorCode&
+     */
+    virtual EComparisonResult compare(const UnicodeString& source,
+                                      const UnicodeString& target) const;
+
+
+    /**
+    * The comparison function compares the character data stored in two
+    * different strings. Returns information about whether a string is less 
+    * than, greater than or equal to another string.
+    * @param source the source string to be compared with.
+    * @param target the string that is to be compared with the source string.
+    * @param status possible error code
+    * @return Returns an enum value. UCOL_GREATER if source is greater
+    * than target; UCOL_EQUAL if source is equal to target; UCOL_LESS if source is less
+    * than target
+    * @stable ICU 2.6
+    **/
+    virtual UCollationResult compare(const UnicodeString& source,
+                                      const UnicodeString& target,
+                                      UErrorCode &status) const;
+
+    /**
+     * Compares a range of character data stored in two different strings based
+     * on the collation rules up to the specified length. Returns information
+     * about whether a string is less than, greater than or equal to another
+     * string in a language. This can be overriden in a subclass.
+     * @param source the source string.
+     * @param target the target string to be compared with the source string.
+     * @param length compares up to the specified length
+     * @return the comparison result. GREATER if the source string is greater
+     *         than the target string, LESS if the source is less than the
+     *         target. Otherwise, returns EQUAL.
+     * @deprecated ICU 2.6 Use overload with UErrorCode&
+     */
+    virtual EComparisonResult compare(const UnicodeString& source,
+                                      const UnicodeString&  target,
+                                      int32_t length) const;
+
+    /**
+    * Does the same thing as compare but limits the comparison to a specified 
+    * length
+    * @param source the source string to be compared with.
+    * @param target the string that is to be compared with the source string.
+    * @param length the length the comparison is limited to
+    * @param status possible error code
+    * @return Returns an enum value. UCOL_GREATER if source (up to the specified 
+    *         length) is greater than target; UCOL_EQUAL if source (up to specified 
+    *         length) is equal to target; UCOL_LESS if source (up to the specified 
+    *         length) is less  than target.
+    * @stable ICU 2.6
+    */
+    virtual UCollationResult compare(const UnicodeString& source,
+                                      const UnicodeString& target,
+                                      int32_t length,
+                                      UErrorCode &status) const;
+
+    /**
+     * The comparison function compares the character data stored in two
+     * different string arrays. Returns information about whether a string array
+     * is less than, greater than or equal to another string array.
+     * <p>Example of use:
+     * <pre>
+     * .       UChar ABC[] = {0x41, 0x42, 0x43, 0};  // = "ABC"
+     * .       UChar abc[] = {0x61, 0x62, 0x63, 0};  // = "abc"
+     * .       UErrorCode status = U_ZERO_ERROR;
+     * .       Collator *myCollation =
+     * .                         Collator::createInstance(Locale::US, status);
+     * .       if (U_FAILURE(status)) return;
+     * .       myCollation->setStrength(Collator::PRIMARY);
+     * .       // result would be Collator::EQUAL ("abc" == "ABC")
+     * .       // (no primary difference between "abc" and "ABC")
+     * .       Collator::EComparisonResult result =
+     * .                             myCollation->compare(abc, 3, ABC, 3);
+     * .       myCollation->setStrength(Collator::TERTIARY);
+     * .       // result would be Collator::LESS ("abc" &lt;&lt;&lt; "ABC")
+     * .       // (with tertiary difference between "abc" and "ABC")
+     * .       result =  myCollation->compare(abc, 3, ABC, 3);
+     * </pre>
+     * @param source the source string array to be compared with.
+     * @param sourceLength the length of the source string array. If this value
+     *        is equal to -1, the string array is null-terminated.
+     * @param target the string that is to be compared with the source string.
+     * @param targetLength the length of the target string array. If this value
+     *        is equal to -1, the string array is null-terminated.
+     * @return Returns a byte value. GREATER if source is greater than target;
+     *         EQUAL if source is equal to target; LESS if source is less than
+     *         target
+     * @deprecated ICU 2.6 Use overload with UErrorCode&
+     */
+    virtual EComparisonResult compare(const UChar* source, int32_t sourceLength,
+                                      const UChar* target, int32_t targetLength)
+                                      const;
+
+    /**
+    * The comparison function compares the character data stored in two
+    * different string arrays. Returns information about whether a string array 
+    * is less than, greater than or equal to another string array.
+    * @param source the source string array to be compared with.
+    * @param sourceLength the length of the source string array.  If this value
+    *        is equal to -1, the string array is null-terminated.
+    * @param target the string that is to be compared with the source string.
+    * @param targetLength the length of the target string array.  If this value
+    *        is equal to -1, the string array is null-terminated.
+    * @param status possible error code
+    * @return Returns an enum value. UCOL_GREATER if source is greater
+    * than target; UCOL_EQUAL if source is equal to target; UCOL_LESS if source is less
+    * than target
+    * @stable ICU 2.6
+    */
+    virtual UCollationResult compare(const UChar* source, int32_t sourceLength,
+                                      const UChar* target, int32_t targetLength,
+                                      UErrorCode &status) const;
+
+    /**
+    * Transforms a specified region of the string into a series of characters
+    * that can be compared with CollationKey.compare. Use a CollationKey when
+    * you need to do repeated comparisions on the same string. For a single
+    * comparison the compare method will be faster.
+    * @param source the source string.
+    * @param key the transformed key of the source string.
+    * @param status the error code status.
+    * @return the transformed key.
+    * @see CollationKey
+    * @deprecated ICU 2.8 Use getSortKey(...) instead
+    */
+    virtual CollationKey& getCollationKey(const UnicodeString& source,
+                                          CollationKey& key,
+                                          UErrorCode& status) const;
+
+    /**
+    * Transforms a specified region of the string into a series of characters
+    * that can be compared with CollationKey.compare. Use a CollationKey when
+    * you need to do repeated comparisions on the same string. For a single
+    * comparison the compare method will be faster.
+    * @param source the source string.
+    * @param sourceLength the length of the source string.
+    * @param key the transformed key of the source string.
+    * @param status the error code status.
+    * @return the transformed key.
+    * @see CollationKey
+    * @deprecated ICU 2.8 Use getSortKey(...) instead
+    */
+    virtual CollationKey& getCollationKey(const UChar *source,
+                                          int32_t sourceLength,
+                                          CollationKey& key,
+                                          UErrorCode& status) const;
+
+    /**
+     * Generates the hash code for the rule-based collation object.
+     * @return the hash code.
+     * @stable ICU 2.0
+     */
+    virtual int32_t hashCode(void) const;
+
+    /**
+    * Gets the locale of the Collator
+    * @param type can be either requested, valid or actual locale. For more
+    *             information see the definition of ULocDataLocaleType in
+    *             uloc.h
+    * @param status the error code status.
+    * @return locale where the collation data lives. If the collator
+    *         was instantiated from rules, locale is empty.
+    * @deprecated ICU 2.8 likely to change in ICU 3.0, based on feedback
+    */
+    virtual const Locale getLocale(ULocDataLocaleType type, UErrorCode& status) const;
+
+    /**
+     * Gets the table-based rules for the collation object.
+     * @return returns the collation rules that the table collation object was
+     *         created from.
+     * @stable ICU 2.0
+     */
+    const UnicodeString& getRules(void) const;
+
+    /**
+     * Gets the version information for a Collator.
+     * @param info the version # information, the result will be filled in
+     * @stable ICU 2.0
+     */
+    virtual void getVersion(UVersionInfo info) const;
+
+    /**
+     * Return the maximum length of any expansion sequences that end with the
+     * specified comparison order.
+     * @param order a collation order returned by previous or next.
+     * @return maximum size of the expansion sequences ending with the collation
+     *         element or 1 if collation element does not occur at the end of
+     *         any expansion sequence
+     * @see CollationElementIterator#getMaxExpansion
+     * @stable ICU 2.0
+     */
+    int32_t getMaxExpansion(int32_t order) const;
+
+    /**
+     * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This
+     * method is to implement a simple version of RTTI, since not all C++
+     * compilers support genuine RTTI. Polymorphic operator==() and clone()
+     * methods call this method.
+     * @return The class ID for this object. All objects of a given class have
+     *         the same class ID. Objects of other classes have different class
+     *         IDs.
+     * @stable ICU 2.0
+     */
+    virtual UClassID getDynamicClassID(void) const;
+
+    /**
+     * Returns the class ID for this class. This is useful only for comparing to
+     * a return value from getDynamicClassID(). For example:
+     * <pre>
+     * Base* polymorphic_pointer = createPolymorphicObject();
+     * if (polymorphic_pointer->getDynamicClassID() ==
+     *                                          Derived::getStaticClassID()) ...
+     * </pre>
+     * @return The class ID for all objects of this class.
+     * @stable ICU 2.0
+     */
+    static UClassID U_EXPORT2 getStaticClassID(void);
+
+    /**
+     * Returns the binary format of the class's rules. The format is that of
+     * .col files.
+     * @param length Returns the length of the data, in bytes
+     * @param status the error code status.
+     * @return memory, owned by the caller, of size 'length' bytes.
+     * @stable ICU 2.2
+     */
+    uint8_t *cloneRuleData(int32_t &length, UErrorCode &status);
+
+
+    /** Creates a binary image of a collator. This binary image can be stored and 
+    *  later used to instantiate a collator using ucol_openBinary.
+    *  This API supports preflighting.
+    *  @param buffer a fill-in buffer to receive the binary image
+    *  @param capacity capacity of the destination buffer
+    *  @param status for catching errors
+    *  @return size of the image
+    *  @see ucol_openBinary
+    *  @stable ICU 3.4
+    */
+    int32_t cloneBinary(uint8_t *buffer, int32_t capacity, UErrorCode &status);
+
+    /**
+     * Returns current rules. Delta defines whether full rules are returned or
+     * just the tailoring.
+     * @param delta one of UCOL_TAILORING_ONLY, UCOL_FULL_RULES.
+     * @param buffer UnicodeString to store the result rules
+     * @stable ICU 2.2
+     */
+    void getRules(UColRuleOption delta, UnicodeString &buffer);
+
+    /**
+     * Universal attribute setter
+     * @param attr attribute type
+     * @param value attribute value
+     * @param status to indicate whether the operation went on smoothly or there were errors
+     * @stable ICU 2.2
+     */
+    virtual void setAttribute(UColAttribute attr, UColAttributeValue value,
+                              UErrorCode &status);
+
+    /**
+     * Universal attribute getter.
+     * @param attr attribute type
+     * @param status to indicate whether the operation went on smoothly or there were errors
+     * @return attribute value
+     * @stable ICU 2.2
+     */
+    virtual UColAttributeValue getAttribute(UColAttribute attr,
+                                            UErrorCode &status);
+
+    /**
+     * Sets the variable top to a collation element value of a string supplied.
+     * @param varTop one or more (if contraction) UChars to which the variable top should be set
+     * @param len length of variable top string. If -1 it is considered to be zero terminated.
+     * @param status error code. If error code is set, the return value is undefined. Errors set by this function are: <br>
+     *    U_CE_NOT_FOUND_ERROR if more than one character was passed and there is no such a contraction<br>
+     *    U_PRIMARY_TOO_LONG_ERROR if the primary for the variable top has more than two bytes
+     * @return a 32 bit value containing the value of the variable top in upper 16 bits. Lower 16 bits are undefined
+     * @stable ICU 2.0
+     */
+    virtual uint32_t setVariableTop(const UChar *varTop, int32_t len, UErrorCode &status);
+
+    /**
+     * Sets the variable top to a collation element value of a string supplied.
+     * @param varTop an UnicodeString size 1 or more (if contraction) of UChars to which the variable top should be set
+     * @param status error code. If error code is set, the return value is undefined. Errors set by this function are: <br>
+     *    U_CE_NOT_FOUND_ERROR if more than one character was passed and there is no such a contraction<br>
+     *    U_PRIMARY_TOO_LONG_ERROR if the primary for the variable top has more than two bytes
+     * @return a 32 bit value containing the value of the variable top in upper 16 bits. Lower 16 bits are undefined
+     * @stable ICU 2.0
+     */
+    virtual uint32_t setVariableTop(const UnicodeString varTop, UErrorCode &status);
+
+    /**
+     * Sets the variable top to a collation element value supplied. Variable top is set to the upper 16 bits.
+     * Lower 16 bits are ignored.
+     * @param varTop CE value, as returned by setVariableTop or ucol)getVariableTop
+     * @param status error code (not changed by function)
+     * @stable ICU 2.0
+     */
+    virtual void setVariableTop(const uint32_t varTop, UErrorCode &status);
+
+    /**
+     * Gets the variable top value of a Collator.
+     * Lower 16 bits are undefined and should be ignored.
+     * @param status error code (not changed by function). If error code is set, the return value is undefined.
+     * @stable ICU 2.0
+     */
+    virtual uint32_t getVariableTop(UErrorCode &status) const;
+
+    /**
+     * Get an UnicodeSet that contains all the characters and sequences tailored in 
+     * this collator.
+     * @param status      error code of the operation
+     * @return a pointer to a UnicodeSet object containing all the 
+     *         code points and sequences that may sort differently than
+     *         in the UCA. The object must be disposed of by using delete
+     * @stable ICU 2.4
+     */
+    virtual UnicodeSet *getTailoredSet(UErrorCode &status) const;
+
+    /**
+     * Thread safe cloning operation.
+     * @return pointer to the new clone, user should remove it.
+     * @stable ICU 2.2
+     */
+    virtual Collator* safeClone(void);
+
+    /**
+     * Get the sort key as an array of bytes from an UnicodeString.
+     * @param source string to be processed.
+     * @param result buffer to store result in. If NULL, number of bytes needed
+     *        will be returned.
+     * @param resultLength length of the result buffer. If if not enough the
+     *        buffer will be filled to capacity.
+     * @return Number of bytes needed for storing the sort key
+     * @stable ICU 2.0
+     */
+    virtual int32_t getSortKey(const UnicodeString& source, uint8_t *result,
+                               int32_t resultLength) const;
+
+    /**
+     * Get the sort key as an array of bytes from an UChar buffer.
+     * @param source string to be processed.
+     * @param sourceLength length of string to be processed. If -1, the string
+     *        is 0 terminated and length will be decided by the function.
+     * @param result buffer to store result in. If NULL, number of bytes needed
+     *        will be returned.
+     * @param resultLength length of the result buffer. If if not enough the
+     *        buffer will be filled to capacity.
+     * @return Number of bytes needed for storing the sort key
+     * @stable ICU 2.2
+     */
+    virtual int32_t getSortKey(const UChar *source, int32_t sourceLength,
+                               uint8_t *result, int32_t resultLength) const;
+
+    /**
+    * Determines the minimum strength that will be use in comparison or
+    * transformation.
+    * <p>E.g. with strength == SECONDARY, the tertiary difference is ignored
+    * <p>E.g. with strength == PRIMARY, the secondary and tertiary difference
+    * are ignored.
+    * @return the current comparison level.
+    * @see RuleBasedCollator#setStrength
+    * @deprecated ICU 2.6 Use getAttribute(UCOL_STRENGTH...) instead
+    */
+    virtual ECollationStrength getStrength(void) const;
+
+    /**
+    * Sets the minimum strength to be used in comparison or transformation.
+    * @see RuleBasedCollator#getStrength
+    * @param newStrength the new comparison level.
+    * @deprecated ICU 2.6 Use setAttribute(UCOL_STRENGTH...) instead
+    */
+    virtual void setStrength(ECollationStrength newStrength);
+
+private:
+
+    // private static constants -----------------------------------------------
+
+    enum {
+        /* need look up in .commit() */
+        CHARINDEX = 0x70000000,
+        /* Expand index follows */
+        EXPANDCHARINDEX = 0x7E000000,
+        /* contract indexes follows */
+        CONTRACTCHARINDEX = 0x7F000000,
+        /* unmapped character values */
+        UNMAPPED = 0xFFFFFFFF,
+        /* primary strength increment */
+        PRIMARYORDERINCREMENT = 0x00010000,
+        /* secondary strength increment */
+        SECONDARYORDERINCREMENT = 0x00000100,
+        /* tertiary strength increment */
+        TERTIARYORDERINCREMENT = 0x00000001,
+        /* mask off anything but primary order */
+        PRIMARYORDERMASK = 0xffff0000,
+        /* mask off anything but secondary order */
+        SECONDARYORDERMASK = 0x0000ff00,
+        /* mask off anything but tertiary order */
+        TERTIARYORDERMASK = 0x000000ff,
+        /* mask off ignorable char order */
+        IGNORABLEMASK = 0x0000ffff,
+        /* use only the primary difference */
+        PRIMARYDIFFERENCEONLY = 0xffff0000,
+        /* use only the primary and secondary difference */
+        SECONDARYDIFFERENCEONLY = 0xffffff00,
+        /* primary order shift */
+        PRIMARYORDERSHIFT = 16,
+        /* secondary order shift */
+        SECONDARYORDERSHIFT = 8,
+        /* starting value for collation elements */
+        COLELEMENTSTART = 0x02020202,
+        /* testing mask for primary low element */
+        PRIMARYLOWZEROMASK = 0x00FF0000,
+        /* reseting value for secondaries and tertiaries */
+        RESETSECONDARYTERTIARY = 0x00000202,
+        /* reseting value for tertiaries */
+        RESETTERTIARY = 0x00000002,
+
+        PRIMIGNORABLE = 0x0202
+    };
+
+    // private data members ---------------------------------------------------
+
+    UBool dataIsOwned;
+
+    UBool isWriteThroughAlias;
+
+    /**
+    * c struct for collation. All initialisation for it has to be done through
+    * setUCollator().
+    */
+    UCollator *ucollator;
+
+    /**
+    * Rule UnicodeString
+    */
+    UnicodeString urulestring;
+
+    // friend classes --------------------------------------------------------
+
+    /**
+    * Used to iterate over collation elements in a character source.
+    */
+    friend class CollationElementIterator;
+
+    /**
+    * Collator ONLY needs access to RuleBasedCollator(const Locale&,
+    *                                                       UErrorCode&)
+    */
+    friend class Collator;
+
+    /**
+    * Searching over collation elements in a character source
+    */
+    friend class StringSearch;
+
+    // private constructors --------------------------------------------------
+
+    /**
+     * Default constructor
+     */
+    RuleBasedCollator();
+
+    /**
+     * RuleBasedCollator constructor. This constructor takes a locale. The
+     * only caller of this class should be Collator::createInstance(). If
+     * createInstance() happens to know that the requested locale's collation is
+     * implemented as a RuleBasedCollator, it can then call this constructor.
+     * OTHERWISE IT SHOULDN'T, since this constructor ALWAYS RETURNS A VALID
+     * COLLATION TABLE. It does this by falling back to defaults.
+     * @param desiredLocale locale used
+     * @param status error code status
+     */
+    RuleBasedCollator(const Locale& desiredLocale, UErrorCode& status);
+
+    /**
+     * common constructor implementation
+     *
+     * @param rules the collation rules to build the collation table from.
+     * @param collationStrength default strength for comparison
+     * @param decompositionMode the normalisation mode
+     * @param status reporting a success or an error.
+     */
+    void
+    construct(const UnicodeString& rules,
+              UColAttributeValue collationStrength,
+              UColAttributeValue decompositionMode,
+              UErrorCode& status);
+
+    // private methods -------------------------------------------------------
+
+    /**
+    * Creates the c struct for ucollator
+    * @param locale desired locale
+    * @param status error status
+    */
+    void setUCollator(const Locale& locale, UErrorCode& status);
+
+    /**
+    * Creates the c struct for ucollator
+    * @param locale desired locale name
+    * @param status error status
+    */
+    void setUCollator(const char* locale, UErrorCode& status);
+
+    /**
+    * Creates the c struct for ucollator. This used internally by StringSearch.
+    * Hence the responsibility of cleaning up the ucollator is not done by
+    * this RuleBasedCollator. The isDataOwned flag is set to FALSE.
+    * @param collator new ucollator data
+    * @param rules corresponding collation rules
+    */
+    void setUCollator(UCollator *collator);
+
+public:
+    /**
+    * Get UCollator data struct. Used only by StringSearch & intltest.
+    * @return UCollator data struct
+    * @internal
+    */
+    const UCollator * getUCollator();
+
+protected:
+   /**
+    * Used internally by registraton to define the requested and valid locales.
+    * @param requestedLocale the requsted locale
+    * @param validLocale the valid locale
+    * @param actualLocale the actual locale
+    * @internal
+    */
+    virtual void setLocales(const Locale& requestedLocale, const Locale& validLocale, const Locale& actualLocale);
+
+private:
+
+    // if not owned and not a write through alias, copy the ucollator
+    void checkOwned(void);
+
+    // utility to init rule string used by checkOwned and construct
+    void setRuleStringFromCollator();
+
+    /**
+    * Converts C's UCollationResult to EComparisonResult
+    * @param result member of the enum UComparisonResult
+    * @return EComparisonResult equivalent of UCollationResult
+    * @deprecated ICU 2.6. We will not need it.
+    */
+    Collator::EComparisonResult getEComparisonResult(
+                                            const UCollationResult &result) const;
+
+    /**
+    * Converts C's UCollationStrength to ECollationStrength
+    * @param strength member of the enum UCollationStrength
+    * @return ECollationStrength equivalent of UCollationStrength
+    */
+    Collator::ECollationStrength getECollationStrength(
+                                        const UCollationStrength &strength) const;
+
+    /**
+    * Converts C++'s ECollationStrength to UCollationStrength
+    * @param strength member of the enum ECollationStrength
+    * @return UCollationStrength equivalent of ECollationStrength
+    */
+    UCollationStrength getUCollationStrength(
+      const Collator::ECollationStrength &strength) const;
+};
+
+// inline method implementation ---------------------------------------------
+
+inline void RuleBasedCollator::setUCollator(const Locale &locale,
+                                               UErrorCode &status)
+{
+    setUCollator(locale.getName(), status);
+}
+
+
+inline void RuleBasedCollator::setUCollator(UCollator     *collator)
+{
+
+    if (ucollator && dataIsOwned) {
+        ucol_close(ucollator);
+    }
+    ucollator   = collator;
+    dataIsOwned = FALSE;
+    isWriteThroughAlias = TRUE;
+    setRuleStringFromCollator();
+}
+
+inline const UCollator * RuleBasedCollator::getUCollator()
+{
+    return ucollator;
+}
+
+inline Collator::EComparisonResult RuleBasedCollator::getEComparisonResult(
+                                           const UCollationResult &result) const
+{
+    switch (result)
+    {
+    case UCOL_LESS :
+        return Collator::LESS;
+    case UCOL_EQUAL :
+        return Collator::EQUAL;
+    default :
+        return Collator::GREATER;
+    }
+}
+
+inline Collator::ECollationStrength RuleBasedCollator::getECollationStrength(
+                                       const UCollationStrength &strength) const
+{
+    switch (strength)
+    {
+    case UCOL_PRIMARY :
+        return Collator::PRIMARY;
+    case UCOL_SECONDARY :
+        return Collator::SECONDARY;
+    case UCOL_TERTIARY :
+        return Collator::TERTIARY;
+    case UCOL_QUATERNARY :
+        return Collator::QUATERNARY;
+    default :
+        return Collator::IDENTICAL;
+    }
+}
+
+inline UCollationStrength RuleBasedCollator::getUCollationStrength(
+                             const Collator::ECollationStrength &strength) const
+{
+    switch (strength)
+    {
+    case Collator::PRIMARY :
+        return UCOL_PRIMARY;
+    case Collator::SECONDARY :
+        return UCOL_SECONDARY;
+    case Collator::TERTIARY :
+        return UCOL_TERTIARY;
+    case Collator::QUATERNARY :
+        return UCOL_QUATERNARY;
+    default :
+        return UCOL_IDENTICAL;
+    }
+}
+
+U_NAMESPACE_END
+
+#endif /* #if !UCONFIG_NO_COLLATION */
+
+#endif


[29/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/img/fontawesome-webfont.svg
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/img/fontawesome-webfont.svg b/apps/fauxton/assets/img/fontawesome-webfont.svg
deleted file mode 100755
index 2edb4ec..0000000
--- a/apps/fauxton/assets/img/fontawesome-webfont.svg
+++ /dev/null
@@ -1,399 +0,0 @@
-<?xml version="1.0" standalone="no"?>
-<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" >
-<svg xmlns="http://www.w3.org/2000/svg">
-<metadata></metadata>
-<defs>
-<font id="fontawesomeregular" horiz-adv-x="1536" >
-<font-face units-per-em="1792" ascent="1536" descent="-256" />
-<missing-glyph horiz-adv-x="448" />
-<glyph unicode=" "  horiz-adv-x="448" />
-<glyph unicode="&#x09;" horiz-adv-x="448" />
-<glyph unicode="&#xa0;" horiz-adv-x="448" />
-<glyph unicode="&#xa8;" horiz-adv-x="1792" />
-<glyph unicode="&#xa9;" horiz-adv-x="1792" />
-<glyph unicode="&#xae;" horiz-adv-x="1792" />
-<glyph unicode="&#xb4;" horiz-adv-x="1792" />
-<glyph unicode="&#xc6;" horiz-adv-x="1792" />
-<glyph unicode="&#x2000;" horiz-adv-x="768" />
-<glyph unicode="&#x2001;" />
-<glyph unicode="&#x2002;" horiz-adv-x="768" />
-<glyph unicode="&#x2003;" />
-<glyph unicode="&#x2004;" horiz-adv-x="512" />
-<glyph unicode="&#x2005;" horiz-adv-x="384" />
-<glyph unicode="&#x2006;" horiz-adv-x="256" />
-<glyph unicode="&#x2007;" horiz-adv-x="256" />
-<glyph unicode="&#x2008;" horiz-adv-x="192" />
-<glyph unicode="&#x2009;" horiz-adv-x="307" />
-<glyph unicode="&#x200a;" horiz-adv-x="85" />
-<glyph unicode="&#x202f;" horiz-adv-x="307" />
-<glyph unicode="&#x205f;" horiz-adv-x="384" />
-<glyph unicode="&#x2122;" horiz-adv-x="1792" />
-<glyph unicode="&#x221e;" horiz-adv-x="1792" />
-<glyph unicode="&#x2260;" horiz-adv-x="1792" />
-<glyph unicode="&#xe000;" horiz-adv-x="500" d="M0 0z" />
-<glyph unicode="&#xf000;" horiz-adv-x="1792" d="M1699 1350q0 -35 -43 -78l-632 -632v-768h320q26 0 45 -19t19 -45t-19 -45t-45 -19h-896q-26 0 -45 19t-19 45t19 45t45 19h320v768l-632 632q-43 43 -43 78q0 23 18 36.5t38 17.5t43 4h1408q23 0 43 -4t38 -17.5t18 -36.5z" />
-<glyph unicode="&#xf001;" d="M1536 1312v-1120q0 -50 -34 -89t-86 -60.5t-103.5 -32t-96.5 -10.5t-96.5 10.5t-103.5 32t-86 60.5t-34 89t34 89t86 60.5t103.5 32t96.5 10.5q105 0 192 -39v537l-768 -237v-709q0 -50 -34 -89t-86 -60.5t-103.5 -32t-96.5 -10.5t-96.5 10.5t-103.5 32t-86 60.5t-34 89 t34 89t86 60.5t103.5 32t96.5 10.5q105 0 192 -39v967q0 31 19 56.5t49 35.5l832 256q12 4 28 4q40 0 68 -28t28 -68z" />
-<glyph unicode="&#xf002;" horiz-adv-x="1664" d="M1152 704q0 185 -131.5 316.5t-316.5 131.5t-316.5 -131.5t-131.5 -316.5t131.5 -316.5t316.5 -131.5t316.5 131.5t131.5 316.5zM1664 -128q0 -52 -38 -90t-90 -38q-54 0 -90 38l-343 342q-179 -124 -399 -124q-143 0 -273.5 55.5t-225 150t-150 225t-55.5 273.5 t55.5 273.5t150 225t225 150t273.5 55.5t273.5 -55.5t225 -150t150 -225t55.5 -273.5q0 -220 -124 -399l343 -343q37 -37 37 -90z" />
-<glyph unicode="&#xf003;" horiz-adv-x="1792" d="M1664 32v768q-32 -36 -69 -66q-268 -206 -426 -338q-51 -43 -83 -67t-86.5 -48.5t-102.5 -24.5h-1h-1q-48 0 -102.5 24.5t-86.5 48.5t-83 67q-158 132 -426 338q-37 30 -69 66v-768q0 -13 9.5 -22.5t22.5 -9.5h1472q13 0 22.5 9.5t9.5 22.5zM1664 1083v11v13.5t-0.5 13 t-3 12.5t-5.5 9t-9 7.5t-14 2.5h-1472q-13 0 -22.5 -9.5t-9.5 -22.5q0 -168 147 -284q193 -152 401 -317q6 -5 35 -29.5t46 -37.5t44.5 -31.5t50.5 -27.5t43 -9h1h1q20 0 43 9t50.5 27.5t44.5 31.5t46 37.5t35 29.5q208 165 401 317q54 43 100.5 115.5t46.5 131.5z M1792 1120v-1088q0 -66 -47 -113t-113 -47h-1472q-66 0 -113 47t-47 113v1088q0 66 47 113t113 47h1472q66 0 113 -47t47 -113z" />
-<glyph unicode="&#xf004;" horiz-adv-x="1792" d="M896 -128q-26 0 -44 18l-624 602q-10 8 -27.5 26t-55.5 65.5t-68 97.5t-53.5 121t-23.5 138q0 220 127 344t351 124q62 0 126.5 -21.5t120 -58t95.5 -68.5t76 -68q36 36 76 68t95.5 68.5t120 58t126.5 21.5q224 0 351 -124t127 -344q0 -221 -229 -450l-623 -600 q-18 -18 -44 -18z" />
-<glyph unicode="&#xf005;" horiz-adv-x="1664" d="M1664 889q0 -22 -26 -48l-363 -354l86 -500q1 -7 1 -20q0 -21 -10.5 -35.5t-30.5 -14.5q-19 0 -40 12l-449 236l-449 -236q-22 -12 -40 -12q-21 0 -31.5 14.5t-10.5 35.5q0 6 2 20l86 500l-364 354q-25 27 -25 48q0 37 56 46l502 73l225 455q19 41 49 41t49 -41l225 -455 l502 -73q56 -9 56 -46z" />
-<glyph unicode="&#xf006;" horiz-adv-x="1664" d="M1137 532l306 297l-422 62l-189 382l-189 -382l-422 -62l306 -297l-73 -421l378 199l377 -199zM1664 889q0 -22 -26 -48l-363 -354l86 -500q1 -7 1 -20q0 -50 -41 -50q-19 0 -40 12l-449 236l-449 -236q-22 -12 -40 -12q-21 0 -31.5 14.5t-10.5 35.5q0 6 2 20l86 500 l-364 354q-25 27 -25 48q0 37 56 46l502 73l225 455q19 41 49 41t49 -41l225 -455l502 -73q56 -9 56 -46z" />
-<glyph unicode="&#xf007;" horiz-adv-x="1408" d="M1408 131q0 -120 -73 -189.5t-194 -69.5h-874q-121 0 -194 69.5t-73 189.5q0 53 3.5 103.5t14 109t26.5 108.5t43 97.5t62 81t85.5 53.5t111.5 20q9 0 42 -21.5t74.5 -48t108 -48t133.5 -21.5t133.5 21.5t108 48t74.5 48t42 21.5q61 0 111.5 -20t85.5 -53.5t62 -81 t43 -97.5t26.5 -108.5t14 -109t3.5 -103.5zM1088 1024q0 -159 -112.5 -271.5t-271.5 -112.5t-271.5 112.5t-112.5 271.5t112.5 271.5t271.5 112.5t271.5 -112.5t112.5 -271.5z" />
-<glyph unicode="&#xf008;" horiz-adv-x="1920" d="M384 -64v128q0 26 -19 45t-45 19h-128q-26 0 -45 -19t-19 -45v-128q0 -26 19 -45t45 -19h128q26 0 45 19t19 45zM384 320v128q0 26 -19 45t-45 19h-128q-26 0 -45 -19t-19 -45v-128q0 -26 19 -45t45 -19h128q26 0 45 19t19 45zM384 704v128q0 26 -19 45t-45 19h-128 q-26 0 -45 -19t-19 -45v-128q0 -26 19 -45t45 -19h128q26 0 45 19t19 45zM1408 -64v512q0 26 -19 45t-45 19h-768q-26 0 -45 -19t-19 -45v-512q0 -26 19 -45t45 -19h768q26 0 45 19t19 45zM384 1088v128q0 26 -19 45t-45 19h-128q-26 0 -45 -19t-19 -45v-128q0 -26 19 -45 t45 -19h128q26 0 45 19t19 45zM1792 -64v128q0 26 -19 45t-45 19h-128q-26 0 -45 -19t-19 -45v-128q0 -26 19 -45t45 -19h128q26 0 45 19t19 45zM1408 704v512q0 26 -19 45t-45 19h-768q-26 0 -45 -19t-19 -45v-512q0 -26 19 -45t45 -19h768q26 0 45 19t19 45zM1792 320v128 q0 26 -19 45t-45 19h-128q-26 0 -45 -19t-19 -45v-128q0 -26 19 -45t45 -19h128q26 0 45 19t19 45zM1792 704v128q0 26 -19 45t-45 19h-128q-26 0 -45 -19t-19 -45v-128q0 -26 19 -45t45 -19h128q26 0 45 19t1
 9 45zM1792 1088v128q0 26 -19 45t-45 19h-128q-26 0 -45 -19 t-19 -45v-128q0 -26 19 -45t45 -19h128q26 0 45 19t19 45zM1920 1248v-1344q0 -66 -47 -113t-113 -47h-1600q-66 0 -113 47t-47 113v1344q0 66 47 113t113 47h1600q66 0 113 -47t47 -113z" />
-<glyph unicode="&#xf009;" horiz-adv-x="1664" d="M768 512v-384q0 -52 -38 -90t-90 -38h-512q-52 0 -90 38t-38 90v384q0 52 38 90t90 38h512q52 0 90 -38t38 -90zM768 1280v-384q0 -52 -38 -90t-90 -38h-512q-52 0 -90 38t-38 90v384q0 52 38 90t90 38h512q52 0 90 -38t38 -90zM1664 512v-384q0 -52 -38 -90t-90 -38 h-512q-52 0 -90 38t-38 90v384q0 52 38 90t90 38h512q52 0 90 -38t38 -90zM1664 1280v-384q0 -52 -38 -90t-90 -38h-512q-52 0 -90 38t-38 90v384q0 52 38 90t90 38h512q52 0 90 -38t38 -90z" />
-<glyph unicode="&#xf00a;" horiz-adv-x="1792" d="M512 288v-192q0 -40 -28 -68t-68 -28h-320q-40 0 -68 28t-28 68v192q0 40 28 68t68 28h320q40 0 68 -28t28 -68zM512 800v-192q0 -40 -28 -68t-68 -28h-320q-40 0 -68 28t-28 68v192q0 40 28 68t68 28h320q40 0 68 -28t28 -68zM1152 288v-192q0 -40 -28 -68t-68 -28h-320 q-40 0 -68 28t-28 68v192q0 40 28 68t68 28h320q40 0 68 -28t28 -68zM512 1312v-192q0 -40 -28 -68t-68 -28h-320q-40 0 -68 28t-28 68v192q0 40 28 68t68 28h320q40 0 68 -28t28 -68zM1152 800v-192q0 -40 -28 -68t-68 -28h-320q-40 0 -68 28t-28 68v192q0 40 28 68t68 28 h320q40 0 68 -28t28 -68zM1792 288v-192q0 -40 -28 -68t-68 -28h-320q-40 0 -68 28t-28 68v192q0 40 28 68t68 28h320q40 0 68 -28t28 -68zM1152 1312v-192q0 -40 -28 -68t-68 -28h-320q-40 0 -68 28t-28 68v192q0 40 28 68t68 28h320q40 0 68 -28t28 -68zM1792 800v-192 q0 -40 -28 -68t-68 -28h-320q-40 0 -68 28t-28 68v192q0 40 28 68t68 28h320q40 0 68 -28t28 -68zM1792 1312v-192q0 -40 -28 -68t-68 -28h-320q-40 0 -68 28t-28 68v192q0 40 28 68t68 28h320q40 0 68 -28
 t28 -68z" />
-<glyph unicode="&#xf00b;" horiz-adv-x="1792" d="M512 288v-192q0 -40 -28 -68t-68 -28h-320q-40 0 -68 28t-28 68v192q0 40 28 68t68 28h320q40 0 68 -28t28 -68zM512 800v-192q0 -40 -28 -68t-68 -28h-320q-40 0 -68 28t-28 68v192q0 40 28 68t68 28h320q40 0 68 -28t28 -68zM1792 288v-192q0 -40 -28 -68t-68 -28h-960 q-40 0 -68 28t-28 68v192q0 40 28 68t68 28h960q40 0 68 -28t28 -68zM512 1312v-192q0 -40 -28 -68t-68 -28h-320q-40 0 -68 28t-28 68v192q0 40 28 68t68 28h320q40 0 68 -28t28 -68zM1792 800v-192q0 -40 -28 -68t-68 -28h-960q-40 0 -68 28t-28 68v192q0 40 28 68t68 28 h960q40 0 68 -28t28 -68zM1792 1312v-192q0 -40 -28 -68t-68 -28h-960q-40 0 -68 28t-28 68v192q0 40 28 68t68 28h960q40 0 68 -28t28 -68z" />
-<glyph unicode="&#xf00c;" horiz-adv-x="1792" d="M1671 970q0 -40 -28 -68l-724 -724l-136 -136q-28 -28 -68 -28t-68 28l-136 136l-362 362q-28 28 -28 68t28 68l136 136q28 28 68 28t68 -28l294 -295l656 657q28 28 68 28t68 -28l136 -136q28 -28 28 -68z" />
-<glyph unicode="&#xf00d;" horiz-adv-x="1408" d="M1298 214q0 -40 -28 -68l-136 -136q-28 -28 -68 -28t-68 28l-294 294l-294 -294q-28 -28 -68 -28t-68 28l-136 136q-28 28 -28 68t28 68l294 294l-294 294q-28 28 -28 68t28 68l136 136q28 28 68 28t68 -28l294 -294l294 294q28 28 68 28t68 -28l136 -136q28 -28 28 -68 t-28 -68l-294 -294l294 -294q28 -28 28 -68z" />
-<glyph unicode="&#xf00e;" horiz-adv-x="1664" d="M1024 736v-64q0 -13 -9.5 -22.5t-22.5 -9.5h-224v-224q0 -13 -9.5 -22.5t-22.5 -9.5h-64q-13 0 -22.5 9.5t-9.5 22.5v224h-224q-13 0 -22.5 9.5t-9.5 22.5v64q0 13 9.5 22.5t22.5 9.5h224v224q0 13 9.5 22.5t22.5 9.5h64q13 0 22.5 -9.5t9.5 -22.5v-224h224 q13 0 22.5 -9.5t9.5 -22.5zM1152 704q0 185 -131.5 316.5t-316.5 131.5t-316.5 -131.5t-131.5 -316.5t131.5 -316.5t316.5 -131.5t316.5 131.5t131.5 316.5zM1664 -128q0 -53 -37.5 -90.5t-90.5 -37.5q-54 0 -90 38l-343 342q-179 -124 -399 -124q-143 0 -273.5 55.5 t-225 150t-150 225t-55.5 273.5t55.5 273.5t150 225t225 150t273.5 55.5t273.5 -55.5t225 -150t150 -225t55.5 -273.5q0 -220 -124 -399l343 -343q37 -37 37 -90z" />
-<glyph unicode="&#xf010;" horiz-adv-x="1664" d="M1024 736v-64q0 -13 -9.5 -22.5t-22.5 -9.5h-576q-13 0 -22.5 9.5t-9.5 22.5v64q0 13 9.5 22.5t22.5 9.5h576q13 0 22.5 -9.5t9.5 -22.5zM1152 704q0 185 -131.5 316.5t-316.5 131.5t-316.5 -131.5t-131.5 -316.5t131.5 -316.5t316.5 -131.5t316.5 131.5t131.5 316.5z M1664 -128q0 -53 -37.5 -90.5t-90.5 -37.5q-54 0 -90 38l-343 342q-179 -124 -399 -124q-143 0 -273.5 55.5t-225 150t-150 225t-55.5 273.5t55.5 273.5t150 225t225 150t273.5 55.5t273.5 -55.5t225 -150t150 -225t55.5 -273.5q0 -220 -124 -399l343 -343q37 -37 37 -90z " />
-<glyph unicode="&#xf011;" d="M1536 640q0 -156 -61 -298t-164 -245t-245 -164t-298 -61t-298 61t-245 164t-164 245t-61 298q0 182 80.5 343t226.5 270q43 32 95.5 25t83.5 -50q32 -42 24.5 -94.5t-49.5 -84.5q-98 -74 -151.5 -181t-53.5 -228q0 -104 40.5 -198.5t109.5 -163.5t163.5 -109.5 t198.5 -40.5t198.5 40.5t163.5 109.5t109.5 163.5t40.5 198.5q0 121 -53.5 228t-151.5 181q-42 32 -49.5 84.5t24.5 94.5q31 43 84 50t95 -25q146 -109 226.5 -270t80.5 -343zM896 1408v-640q0 -52 -38 -90t-90 -38t-90 38t-38 90v640q0 52 38 90t90 38t90 -38t38 -90z" />
-<glyph unicode="&#xf012;" horiz-adv-x="1792" d="M256 96v-192q0 -14 -9 -23t-23 -9h-192q-14 0 -23 9t-9 23v192q0 14 9 23t23 9h192q14 0 23 -9t9 -23zM640 224v-320q0 -14 -9 -23t-23 -9h-192q-14 0 -23 9t-9 23v320q0 14 9 23t23 9h192q14 0 23 -9t9 -23zM1024 480v-576q0 -14 -9 -23t-23 -9h-192q-14 0 -23 9t-9 23 v576q0 14 9 23t23 9h192q14 0 23 -9t9 -23zM1408 864v-960q0 -14 -9 -23t-23 -9h-192q-14 0 -23 9t-9 23v960q0 14 9 23t23 9h192q14 0 23 -9t9 -23zM1792 1376v-1472q0 -14 -9 -23t-23 -9h-192q-14 0 -23 9t-9 23v1472q0 14 9 23t23 9h192q14 0 23 -9t9 -23z" />
-<glyph unicode="&#xf013;" d="M1024 640q0 106 -75 181t-181 75t-181 -75t-75 -181t75 -181t181 -75t181 75t75 181zM1536 749v-222q0 -12 -8 -23t-20 -13l-185 -28q-19 -54 -39 -91q35 -50 107 -138q10 -12 10 -25t-9 -23q-27 -37 -99 -108t-94 -71q-12 0 -26 9l-138 108q-44 -23 -91 -38 q-16 -136 -29 -186q-7 -28 -36 -28h-222q-14 0 -24.5 8.5t-11.5 21.5l-28 184q-49 16 -90 37l-141 -107q-10 -9 -25 -9q-14 0 -25 11q-126 114 -165 168q-7 10 -7 23q0 12 8 23q15 21 51 66.5t54 70.5q-27 50 -41 99l-183 27q-13 2 -21 12.5t-8 23.5v222q0 12 8 23t19 13 l186 28q14 46 39 92q-40 57 -107 138q-10 12 -10 24q0 10 9 23q26 36 98.5 107.5t94.5 71.5q13 0 26 -10l138 -107q44 23 91 38q16 136 29 186q7 28 36 28h222q14 0 24.5 -8.5t11.5 -21.5l28 -184q49 -16 90 -37l142 107q9 9 24 9q13 0 25 -10q129 -119 165 -170q7 -8 7 -22 q0 -12 -8 -23q-15 -21 -51 -66.5t-54 -70.5q26 -50 41 -98l183 -28q13 -2 21 -12.5t8 -23.5z" />
-<glyph unicode="&#xf014;" horiz-adv-x="1408" d="M512 800v-576q0 -14 -9 -23t-23 -9h-64q-14 0 -23 9t-9 23v576q0 14 9 23t23 9h64q14 0 23 -9t9 -23zM768 800v-576q0 -14 -9 -23t-23 -9h-64q-14 0 -23 9t-9 23v576q0 14 9 23t23 9h64q14 0 23 -9t9 -23zM1024 800v-576q0 -14 -9 -23t-23 -9h-64q-14 0 -23 9t-9 23v576 q0 14 9 23t23 9h64q14 0 23 -9t9 -23zM1152 76v948h-896v-948q0 -22 7 -40.5t14.5 -27t10.5 -8.5h832q3 0 10.5 8.5t14.5 27t7 40.5zM480 1152h448l-48 117q-7 9 -17 11h-317q-10 -2 -17 -11zM1408 1120v-64q0 -14 -9 -23t-23 -9h-96v-948q0 -83 -47 -143.5t-113 -60.5h-832 q-66 0 -113 58.5t-47 141.5v952h-96q-14 0 -23 9t-9 23v64q0 14 9 23t23 9h309l70 167q15 37 54 63t79 26h320q40 0 79 -26t54 -63l70 -167h309q14 0 23 -9t9 -23z" />
-<glyph unicode="&#xf015;" horiz-adv-x="1664" d="M1408 544v-480q0 -26 -19 -45t-45 -19h-384v384h-256v-384h-384q-26 0 -45 19t-19 45v480q0 1 0.5 3t0.5 3l575 474l575 -474q1 -2 1 -6zM1631 613l-62 -74q-8 -9 -21 -11h-3q-13 0 -21 7l-692 577l-692 -577q-12 -8 -24 -7q-13 2 -21 11l-62 74q-8 10 -7 23.5t11 21.5 l719 599q32 26 76 26t76 -26l244 -204v195q0 14 9 23t23 9h192q14 0 23 -9t9 -23v-408l219 -182q10 -8 11 -21.5t-7 -23.5z" />
-<glyph unicode="&#xf016;" horiz-adv-x="1280" d="M128 0h1024v768h-416q-40 0 -68 28t-28 68v416h-512v-1280zM768 896h376q-10 29 -22 41l-313 313q-12 12 -41 22v-376zM1280 864v-896q0 -40 -28 -68t-68 -28h-1088q-40 0 -68 28t-28 68v1344q0 40 28 68t68 28h640q40 0 88 -20t76 -48l312 -312q28 -28 48 -76t20 -88z " />
-<glyph unicode="&#xf017;" d="M896 992v-448q0 -14 -9 -23t-23 -9h-320q-14 0 -23 9t-9 23v64q0 14 9 23t23 9h224v352q0 14 9 23t23 9h64q14 0 23 -9t9 -23zM1312 640q0 148 -73 273t-198 198t-273 73t-273 -73t-198 -198t-73 -273t73 -273t198 -198t273 -73t273 73t198 198t73 273zM1536 640 q0 -209 -103 -385.5t-279.5 -279.5t-385.5 -103t-385.5 103t-279.5 279.5t-103 385.5t103 385.5t279.5 279.5t385.5 103t385.5 -103t279.5 -279.5t103 -385.5z" />
-<glyph unicode="&#xf018;" horiz-adv-x="1920" d="M1111 540v4l-24 320q-1 13 -11 22.5t-23 9.5h-186q-13 0 -23 -9.5t-11 -22.5l-24 -320v-4q-1 -12 8 -20t21 -8h244q12 0 21 8t8 20zM1870 73q0 -73 -46 -73h-704q13 0 22 9.5t8 22.5l-20 256q-1 13 -11 22.5t-23 9.5h-272q-13 0 -23 -9.5t-11 -22.5l-20 -256 q-1 -13 8 -22.5t22 -9.5h-704q-46 0 -46 73q0 54 26 116l417 1044q8 19 26 33t38 14h339q-13 0 -23 -9.5t-11 -22.5l-15 -192q-1 -14 8 -23t22 -9h166q13 0 22 9t8 23l-15 192q-1 13 -11 22.5t-23 9.5h339q20 0 38 -14t26 -33l417 -1044q26 -62 26 -116z" />
-<glyph unicode="&#xf019;" horiz-adv-x="1664" d="M1280 192q0 26 -19 45t-45 19t-45 -19t-19 -45t19 -45t45 -19t45 19t19 45zM1536 192q0 26 -19 45t-45 19t-45 -19t-19 -45t19 -45t45 -19t45 19t19 45zM1664 416v-320q0 -40 -28 -68t-68 -28h-1472q-40 0 -68 28t-28 68v320q0 40 28 68t68 28h465l135 -136 q58 -56 136 -56t136 56l136 136h464q40 0 68 -28t28 -68zM1339 985q17 -41 -14 -70l-448 -448q-18 -19 -45 -19t-45 19l-448 448q-31 29 -14 70q17 39 59 39h256v448q0 26 19 45t45 19h256q26 0 45 -19t19 -45v-448h256q42 0 59 -39z" />
-<glyph unicode="&#xf01a;" d="M1120 608q0 -12 -10 -24l-319 -319q-11 -9 -23 -9t-23 9l-320 320q-15 16 -7 35q8 20 30 20h192v352q0 14 9 23t23 9h192q14 0 23 -9t9 -23v-352h192q14 0 23 -9t9 -23zM768 1184q-148 0 -273 -73t-198 -198t-73 -273t73 -273t198 -198t273 -73t273 73t198 198t73 273 t-73 273t-198 198t-273 73zM1536 640q0 -209 -103 -385.5t-279.5 -279.5t-385.5 -103t-385.5 103t-279.5 279.5t-103 385.5t103 385.5t279.5 279.5t385.5 103t385.5 -103t279.5 -279.5t103 -385.5z" />
-<glyph unicode="&#xf01b;" d="M1118 660q-8 -20 -30 -20h-192v-352q0 -14 -9 -23t-23 -9h-192q-14 0 -23 9t-9 23v352h-192q-14 0 -23 9t-9 23q0 12 10 24l319 319q11 9 23 9t23 -9l320 -320q15 -16 7 -35zM768 1184q-148 0 -273 -73t-198 -198t-73 -273t73 -273t198 -198t273 -73t273 73t198 198 t73 273t-73 273t-198 198t-273 73zM1536 640q0 -209 -103 -385.5t-279.5 -279.5t-385.5 -103t-385.5 103t-279.5 279.5t-103 385.5t103 385.5t279.5 279.5t385.5 103t385.5 -103t279.5 -279.5t103 -385.5z" />
-<glyph unicode="&#xf01c;" d="M1023 576h316q-1 3 -2.5 8t-2.5 8l-212 496h-708l-212 -496q-1 -2 -2.5 -8t-2.5 -8h316l95 -192h320zM1536 546v-482q0 -26 -19 -45t-45 -19h-1408q-26 0 -45 19t-19 45v482q0 62 25 123l238 552q10 25 36.5 42t52.5 17h832q26 0 52.5 -17t36.5 -42l238 -552 q25 -61 25 -123z" />
-<glyph unicode="&#xf01d;" d="M1184 640q0 -37 -32 -55l-544 -320q-15 -9 -32 -9q-16 0 -32 8q-32 19 -32 56v640q0 37 32 56q33 18 64 -1l544 -320q32 -18 32 -55zM1312 640q0 148 -73 273t-198 198t-273 73t-273 -73t-198 -198t-73 -273t73 -273t198 -198t273 -73t273 73t198 198t73 273zM1536 640 q0 -209 -103 -385.5t-279.5 -279.5t-385.5 -103t-385.5 103t-279.5 279.5t-103 385.5t103 385.5t279.5 279.5t385.5 103t385.5 -103t279.5 -279.5t103 -385.5z" />
-<glyph unicode="&#xf01e;" d="M1536 1280v-448q0 -26 -19 -45t-45 -19h-448q-42 0 -59 40q-17 39 14 69l138 138q-148 137 -349 137q-104 0 -198.5 -40.5t-163.5 -109.5t-109.5 -163.5t-40.5 -198.5t40.5 -198.5t109.5 -163.5t163.5 -109.5t198.5 -40.5q119 0 225 52t179 147q7 10 23 12q14 0 25 -9 l137 -138q9 -8 9.5 -20.5t-7.5 -22.5q-109 -132 -264 -204.5t-327 -72.5q-156 0 -298 61t-245 164t-164 245t-61 298t61 298t164 245t245 164t298 61q147 0 284.5 -55.5t244.5 -156.5l130 129q29 31 70 14q39 -17 39 -59z" />
-<glyph unicode="&#xf021;" d="M1511 480q0 -5 -1 -7q-64 -268 -268 -434.5t-478 -166.5q-146 0 -282.5 55t-243.5 157l-129 -129q-19 -19 -45 -19t-45 19t-19 45v448q0 26 19 45t45 19h448q26 0 45 -19t19 -45t-19 -45l-137 -137q71 -66 161 -102t187 -36q134 0 250 65t186 179q11 17 53 117 q8 23 30 23h192q13 0 22.5 -9.5t9.5 -22.5zM1536 1280v-448q0 -26 -19 -45t-45 -19h-448q-26 0 -45 19t-19 45t19 45l138 138q-148 137 -349 137q-134 0 -250 -65t-186 -179q-11 -17 -53 -117q-8 -23 -30 -23h-199q-13 0 -22.5 9.5t-9.5 22.5v7q65 268 270 434.5t480 166.5 q146 0 284 -55.5t245 -156.5l130 129q19 19 45 19t45 -19t19 -45z" />
-<glyph unicode="&#xf022;" horiz-adv-x="1792" d="M384 352v-64q0 -13 -9.5 -22.5t-22.5 -9.5h-64q-13 0 -22.5 9.5t-9.5 22.5v64q0 13 9.5 22.5t22.5 9.5h64q13 0 22.5 -9.5t9.5 -22.5zM384 608v-64q0 -13 -9.5 -22.5t-22.5 -9.5h-64q-13 0 -22.5 9.5t-9.5 22.5v64q0 13 9.5 22.5t22.5 9.5h64q13 0 22.5 -9.5t9.5 -22.5z M384 864v-64q0 -13 -9.5 -22.5t-22.5 -9.5h-64q-13 0 -22.5 9.5t-9.5 22.5v64q0 13 9.5 22.5t22.5 9.5h64q13 0 22.5 -9.5t9.5 -22.5zM1536 352v-64q0 -13 -9.5 -22.5t-22.5 -9.5h-960q-13 0 -22.5 9.5t-9.5 22.5v64q0 13 9.5 22.5t22.5 9.5h960q13 0 22.5 -9.5t9.5 -22.5z M1536 608v-64q0 -13 -9.5 -22.5t-22.5 -9.5h-960q-13 0 -22.5 9.5t-9.5 22.5v64q0 13 9.5 22.5t22.5 9.5h960q13 0 22.5 -9.5t9.5 -22.5zM1536 864v-64q0 -13 -9.5 -22.5t-22.5 -9.5h-960q-13 0 -22.5 9.5t-9.5 22.5v64q0 13 9.5 22.5t22.5 9.5h960q13 0 22.5 -9.5 t9.5 -22.5zM1664 160v832q0 13 -9.5 22.5t-22.5 9.5h-1472q-13 0 -22.5 -9.5t-9.5 -22.5v-832q0 -13 9.5 -22.5t22.5 -9.5h1472q13 0 22.5 9.5t9.5 22.5zM1792 1248v-1088q0 -66 -47 -113t-113 -47h-1472q-66 0 -1
 13 47t-47 113v1088q0 66 47 113t113 47h1472q66 0 113 -47 t47 -113z" />
-<glyph unicode="&#xf023;" horiz-adv-x="1152" d="M320 768h512v192q0 106 -75 181t-181 75t-181 -75t-75 -181v-192zM1152 672v-576q0 -40 -28 -68t-68 -28h-960q-40 0 -68 28t-28 68v576q0 40 28 68t68 28h32v192q0 184 132 316t316 132t316 -132t132 -316v-192h32q40 0 68 -28t28 -68z" />
-<glyph unicode="&#xf024;" horiz-adv-x="1792" d="M320 1280q0 -72 -64 -110v-1266q0 -13 -9.5 -22.5t-22.5 -9.5h-64q-13 0 -22.5 9.5t-9.5 22.5v1266q-64 38 -64 110q0 53 37.5 90.5t90.5 37.5t90.5 -37.5t37.5 -90.5zM1792 1216v-763q0 -25 -12.5 -38.5t-39.5 -27.5q-215 -116 -369 -116q-61 0 -123.5 22t-108.5 48 t-115.5 48t-142.5 22q-192 0 -464 -146q-17 -9 -33 -9q-26 0 -45 19t-19 45v742q0 32 31 55q21 14 79 43q236 120 421 120q107 0 200 -29t219 -88q38 -19 88 -19q54 0 117.5 21t110 47t88 47t54.5 21q26 0 45 -19t19 -45z" />
-<glyph unicode="&#xf025;" horiz-adv-x="1664" d="M1664 650q0 -166 -60 -314l-20 -49l-185 -33q-22 -83 -90.5 -136.5t-156.5 -53.5v-32q0 -14 -9 -23t-23 -9h-64q-14 0 -23 9t-9 23v576q0 14 9 23t23 9h64q14 0 23 -9t9 -23v-32q71 0 130 -35.5t93 -95.5l68 12q29 95 29 193q0 148 -88 279t-236.5 209t-315.5 78 t-315.5 -78t-236.5 -209t-88 -279q0 -98 29 -193l68 -12q34 60 93 95.5t130 35.5v32q0 14 9 23t23 9h64q14 0 23 -9t9 -23v-576q0 -14 -9 -23t-23 -9h-64q-14 0 -23 9t-9 23v32q-88 0 -156.5 53.5t-90.5 136.5l-185 33l-20 49q-60 148 -60 314q0 151 67 291t179 242.5 t266 163.5t320 61t320 -61t266 -163.5t179 -242.5t67 -291z" />
-<glyph unicode="&#xf026;" horiz-adv-x="768" d="M768 1184v-1088q0 -26 -19 -45t-45 -19t-45 19l-333 333h-262q-26 0 -45 19t-19 45v384q0 26 19 45t45 19h262l333 333q19 19 45 19t45 -19t19 -45z" />
-<glyph unicode="&#xf027;" horiz-adv-x="1152" d="M768 1184v-1088q0 -26 -19 -45t-45 -19t-45 19l-333 333h-262q-26 0 -45 19t-19 45v384q0 26 19 45t45 19h262l333 333q19 19 45 19t45 -19t19 -45zM1152 640q0 -76 -42.5 -141.5t-112.5 -93.5q-10 -5 -25 -5q-26 0 -45 18.5t-19 45.5q0 21 12 35.5t29 25t34 23t29 35.5 t12 57t-12 57t-29 35.5t-34 23t-29 25t-12 35.5q0 27 19 45.5t45 18.5q15 0 25 -5q70 -27 112.5 -93t42.5 -142z" />
-<glyph unicode="&#xf028;" horiz-adv-x="1664" d="M768 1184v-1088q0 -26 -19 -45t-45 -19t-45 19l-333 333h-262q-26 0 -45 19t-19 45v384q0 26 19 45t45 19h262l333 333q19 19 45 19t45 -19t19 -45zM1152 640q0 -76 -42.5 -141.5t-112.5 -93.5q-10 -5 -25 -5q-26 0 -45 18.5t-19 45.5q0 21 12 35.5t29 25t34 23t29 35.5 t12 57t-12 57t-29 35.5t-34 23t-29 25t-12 35.5q0 27 19 45.5t45 18.5q15 0 25 -5q70 -27 112.5 -93t42.5 -142zM1408 640q0 -153 -85 -282.5t-225 -188.5q-13 -5 -25 -5q-27 0 -46 19t-19 45q0 39 39 59q56 29 76 44q74 54 115.5 135.5t41.5 173.5t-41.5 173.5 t-115.5 135.5q-20 15 -76 44q-39 20 -39 59q0 26 19 45t45 19q13 0 26 -5q140 -59 225 -188.5t85 -282.5zM1664 640q0 -230 -127 -422.5t-338 -283.5q-13 -5 -26 -5q-26 0 -45 19t-19 45q0 36 39 59q7 4 22.5 10.5t22.5 10.5q46 25 82 51q123 91 192 227t69 289t-69 289 t-192 227q-36 26 -82 51q-7 4 -22.5 10.5t-22.5 10.5q-39 23 -39 59q0 26 19 45t45 19q13 0 26 -5q211 -91 338 -283.5t127 -422.5z" />
-<glyph unicode="&#xf029;" horiz-adv-x="1408" d="M384 384v-128h-128v128h128zM384 1152v-128h-128v128h128zM1152 1152v-128h-128v128h128zM128 129h384v383h-384v-383zM128 896h384v384h-384v-384zM896 896h384v384h-384v-384zM640 640v-640h-640v640h640zM1152 128v-128h-128v128h128zM1408 128v-128h-128v128h128z M1408 640v-384h-384v128h-128v-384h-128v640h384v-128h128v128h128zM640 1408v-640h-640v640h640zM1408 1408v-640h-640v640h640z" />
-<glyph unicode="&#xf02a;" horiz-adv-x="1792" d="M63 0h-63v1408h63v-1408zM126 1h-32v1407h32v-1407zM220 1h-31v1407h31v-1407zM377 1h-31v1407h31v-1407zM534 1h-62v1407h62v-1407zM660 1h-31v1407h31v-1407zM723 1h-31v1407h31v-1407zM786 1h-31v1407h31v-1407zM943 1h-63v1407h63v-1407zM1100 1h-63v1407h63v-1407z M1226 1h-63v1407h63v-1407zM1352 1h-63v1407h63v-1407zM1446 1h-63v1407h63v-1407zM1635 1h-94v1407h94v-1407zM1698 1h-32v1407h32v-1407zM1792 0h-63v1408h63v-1408z" />
-<glyph unicode="&#xf02b;" d="M448 1088q0 53 -37.5 90.5t-90.5 37.5t-90.5 -37.5t-37.5 -90.5t37.5 -90.5t90.5 -37.5t90.5 37.5t37.5 90.5zM1515 512q0 -53 -37 -90l-491 -492q-39 -37 -91 -37q-53 0 -90 37l-715 716q-38 37 -64.5 101t-26.5 117v416q0 52 38 90t90 38h416q53 0 117 -26.5t102 -64.5 l715 -714q37 -39 37 -91z" />
-<glyph unicode="&#xf02c;" horiz-adv-x="1920" d="M448 1088q0 53 -37.5 90.5t-90.5 37.5t-90.5 -37.5t-37.5 -90.5t37.5 -90.5t90.5 -37.5t90.5 37.5t37.5 90.5zM1515 512q0 -53 -37 -90l-491 -492q-39 -37 -91 -37q-53 0 -90 37l-715 716q-38 37 -64.5 101t-26.5 117v416q0 52 38 90t90 38h416q53 0 117 -26.5t102 -64.5 l715 -714q37 -39 37 -91zM1899 512q0 -53 -37 -90l-491 -492q-39 -37 -91 -37q-36 0 -59 14t-53 45l470 470q37 37 37 90q0 52 -37 91l-715 714q-38 38 -102 64.5t-117 26.5h224q53 0 117 -26.5t102 -64.5l715 -714q37 -39 37 -91z" />
-<glyph unicode="&#xf02d;" horiz-adv-x="1664" d="M1639 1058q40 -57 18 -129l-275 -906q-19 -64 -76.5 -107.5t-122.5 -43.5h-923q-77 0 -148.5 53.5t-99.5 131.5q-24 67 -2 127q0 4 3 27t4 37q1 8 -3 21.5t-3 19.5q2 11 8 21t16.5 23.5t16.5 23.5q23 38 45 91.5t30 91.5q3 10 0.5 30t-0.5 28q3 11 17 28t17 23 q21 36 42 92t25 90q1 9 -2.5 32t0.5 28q4 13 22 30.5t22 22.5q19 26 42.5 84.5t27.5 96.5q1 8 -3 25.5t-2 26.5q2 8 9 18t18 23t17 21q8 12 16.5 30.5t15 35t16 36t19.5 32t26.5 23.5t36 11.5t47.5 -5.5l-1 -3q38 9 51 9h761q74 0 114 -56t18 -130l-274 -906 q-36 -119 -71.5 -153.5t-128.5 -34.5h-869q-27 0 -38 -15q-11 -16 -1 -43q24 -70 144 -70h923q29 0 56 15.5t35 41.5l300 987q7 22 5 57q38 -15 59 -43zM575 1056q-4 -13 2 -22.5t20 -9.5h608q13 0 25.5 9.5t16.5 22.5l21 64q4 13 -2 22.5t-20 9.5h-608q-13 0 -25.5 -9.5 t-16.5 -22.5zM492 800q-4 -13 2 -22.5t20 -9.5h608q13 0 25.5 9.5t16.5 22.5l21 64q4 13 -2 22.5t-20 9.5h-608q-13 0 -25.5 -9.5t-16.5 -22.5z" />
-<glyph unicode="&#xf02e;" horiz-adv-x="1280" d="M1164 1408q23 0 44 -9q33 -13 52.5 -41t19.5 -62v-1289q0 -34 -19.5 -62t-52.5 -41q-19 -8 -44 -8q-48 0 -83 32l-441 424l-441 -424q-36 -33 -83 -33q-23 0 -44 9q-33 13 -52.5 41t-19.5 62v1289q0 34 19.5 62t52.5 41q21 9 44 9h1048z" />
-<glyph unicode="&#xf02f;" horiz-adv-x="1664" d="M384 0h896v256h-896v-256zM384 640h896v384h-160q-40 0 -68 28t-28 68v160h-640v-640zM1536 576q0 26 -19 45t-45 19t-45 -19t-19 -45t19 -45t45 -19t45 19t19 45zM1664 576v-416q0 -13 -9.5 -22.5t-22.5 -9.5h-224v-160q0 -40 -28 -68t-68 -28h-960q-40 0 -68 28t-28 68 v160h-224q-13 0 -22.5 9.5t-9.5 22.5v416q0 79 56.5 135.5t135.5 56.5h64v544q0 40 28 68t68 28h672q40 0 88 -20t76 -48l152 -152q28 -28 48 -76t20 -88v-256h64q79 0 135.5 -56.5t56.5 -135.5z" />
-<glyph unicode="&#xf030;" horiz-adv-x="1920" d="M960 864q119 0 203.5 -84.5t84.5 -203.5t-84.5 -203.5t-203.5 -84.5t-203.5 84.5t-84.5 203.5t84.5 203.5t203.5 84.5zM1664 1280q106 0 181 -75t75 -181v-896q0 -106 -75 -181t-181 -75h-1408q-106 0 -181 75t-75 181v896q0 106 75 181t181 75h224l51 136 q19 49 69.5 84.5t103.5 35.5h512q53 0 103.5 -35.5t69.5 -84.5l51 -136h224zM960 128q185 0 316.5 131.5t131.5 316.5t-131.5 316.5t-316.5 131.5t-316.5 -131.5t-131.5 -316.5t131.5 -316.5t316.5 -131.5z" />
-<glyph unicode="&#xf031;" horiz-adv-x="1664" d="M725 977l-170 -450q73 -1 153.5 -2t119 -1.5t52.5 -0.5l29 2q-32 95 -92 241q-53 132 -92 211zM21 -128h-21l2 79q22 7 80 18q89 16 110 31q20 16 48 68l237 616l280 724h75h53l11 -21l205 -480q103 -242 124 -297q39 -102 96 -235q26 -58 65 -164q24 -67 65 -149 q22 -49 35 -57q22 -19 69 -23q47 -6 103 -27q6 -39 6 -57q0 -14 -1 -26q-80 0 -192 8q-93 8 -189 8q-79 0 -135 -2l-200 -11l-58 -2q0 45 4 78l131 28q56 13 68 23q12 12 12 27t-6 32l-47 114l-92 228l-450 2q-29 -65 -104 -274q-23 -64 -23 -84q0 -31 17 -43 q26 -21 103 -32q3 0 13.5 -2t30 -5t40.5 -6q1 -28 1 -58q0 -17 -2 -27q-66 0 -349 20l-48 -8q-81 -14 -167 -14z" />
-<glyph unicode="&#xf032;" horiz-adv-x="1408" d="M555 15q76 -32 140 -32q131 0 216 41t122 113q38 70 38 181q0 114 -41 180q-58 94 -141 126q-80 32 -247 32q-74 0 -101 -10v-144l-1 -173l3 -270q0 -15 12 -44zM541 761q43 -7 109 -7q175 0 264 65t89 224q0 112 -85 187q-84 75 -255 75q-52 0 -130 -13q0 -44 2 -77 q7 -122 6 -279l-1 -98q0 -43 1 -77zM0 -128l2 94q45 9 68 12q77 12 123 31q17 27 21 51q9 66 9 194l-2 497q-5 256 -9 404q-1 87 -11 109q-1 4 -12 12q-18 12 -69 15q-30 2 -114 13l-4 83l260 6l380 13l45 1q5 0 14 0.5t14 0.5q1 0 21.5 -0.5t40.5 -0.5h74q88 0 191 -27 q43 -13 96 -39q57 -29 102 -76q44 -47 65 -104t21 -122q0 -70 -32 -128t-95 -105q-26 -20 -150 -77q177 -41 267 -146q92 -106 92 -236q0 -76 -29 -161q-21 -62 -71 -117q-66 -72 -140 -108q-73 -36 -203 -60q-82 -15 -198 -11l-197 4q-84 2 -298 -11q-33 -3 -272 -11z" />
-<glyph unicode="&#xf033;" horiz-adv-x="1024" d="M0 -126l17 85q4 1 77 20q76 19 116 39q29 37 41 101l27 139l56 268l12 64q8 44 17 84.5t16 67t12.5 46.5t9 30.5t3.5 11.5l29 157l16 63l22 135l8 50v38q-41 22 -144 28q-28 2 -38 4l19 103l317 -14q39 -2 73 -2q66 0 214 9q33 2 68 4.5t36 2.5q-2 -19 -6 -38 q-7 -29 -13 -51q-55 -19 -109 -31q-64 -16 -101 -31q-12 -31 -24 -88q-9 -44 -13 -82q-44 -199 -66 -306l-61 -311l-38 -158l-43 -235l-12 -45q-2 -7 1 -27q64 -15 119 -21q36 -5 66 -10q-1 -29 -7 -58q-7 -31 -9 -41q-18 0 -23 -1q-24 -2 -42 -2q-9 0 -28 3q-19 4 -145 17 l-198 2q-41 1 -174 -11q-74 -7 -98 -9z" />
-<glyph unicode="&#xf034;" horiz-adv-x="1792" d="M81 1407l54 -27q20 -5 211 -5h130l19 3l115 1l215 -1h293l34 -2q14 -1 28 7t21 16l7 8l42 1q15 0 28 -1v-104.5t1 -131.5l1 -100l-1 -58q0 -32 -4 -51q-39 -15 -68 -18q-25 43 -54 128q-8 24 -15.5 62.5t-11.5 65.5t-6 29q-13 15 -27 19q-7 2 -42.5 2t-103.5 -1t-111 -1 q-34 0 -67 -5q-10 -97 -8 -136l1 -152v-332l3 -359l-1 -147q-1 -46 11 -85q49 -25 89 -32q2 0 18 -5t44 -13t43 -12q30 -8 50 -18q5 -45 5 -50q0 -10 -3 -29q-14 -1 -34 -1q-110 0 -187 10q-72 8 -238 8q-88 0 -233 -14q-48 -4 -70 -4q-2 22 -2 26l-1 26v9q21 33 79 49 q139 38 159 50q9 21 12 56q8 192 6 433l-5 428q-1 62 -0.5 118.5t0.5 102.5t-2 57t-6 15q-6 5 -14 6q-38 6 -148 6q-43 0 -100 -13.5t-73 -24.5q-13 -9 -22 -33t-22 -75t-24 -84q-6 -19 -19.5 -32t-20.5 -13q-44 27 -56 44v297v86zM1744 128q33 0 42 -18.5t-11 -44.5 l-126 -162q-20 -26 -49 -26t-49 26l-126 162q-20 26 -11 44.5t42 18.5h80v1024h-80q-33 0 -42 18.5t11 44.5l126 162q20 26 49 26t49 -26l126 -162q20 -26 11 -44.5t-42 -18.5h-80v-1024h80z" />
-<glyph unicode="&#xf035;" d="M81 1407l54 -27q20 -5 211 -5h130l19 3l115 1l446 -1h318l34 -2q14 -1 28 7t21 16l7 8l42 1q15 0 28 -1v-104.5t1 -131.5l1 -100l-1 -58q0 -32 -4 -51q-39 -15 -68 -18q-25 43 -54 128q-8 24 -15.5 62.5t-11.5 65.5t-6 29q-13 15 -27 19q-7 2 -58.5 2t-138.5 -1t-128 -1 q-94 0 -127 -5q-10 -97 -8 -136l1 -152v52l3 -359l-1 -147q-1 -46 11 -85q49 -25 89 -32q2 0 18 -5t44 -13t43 -12q30 -8 50 -18q5 -45 5 -50q0 -10 -3 -29q-14 -1 -34 -1q-110 0 -187 10q-72 8 -238 8q-82 0 -233 -13q-45 -5 -70 -5q-2 22 -2 26l-1 26v9q21 33 79 49 q139 38 159 50q9 21 12 56q6 137 6 433l-5 44q0 265 -2 278q-2 11 -6 15q-6 5 -14 6q-38 6 -148 6q-50 0 -168.5 -14t-132.5 -24q-13 -9 -22 -33t-22 -75t-24 -84q-6 -19 -19.5 -32t-20.5 -13q-44 27 -56 44v297v86zM1505 113q26 -20 26 -49t-26 -49l-162 -126 q-26 -20 -44.5 -11t-18.5 42v80h-1024v-80q0 -33 -18.5 -42t-44.5 11l-162 126q-26 20 -26 49t26 49l162 126q26 20 44.5 11t18.5 -42v-80h1024v80q0 33 18.5 42t44.5 -11z" />
-<glyph unicode="&#xf036;" horiz-adv-x="1792" d="M1792 192v-128q0 -26 -19 -45t-45 -19h-1664q-26 0 -45 19t-19 45v128q0 26 19 45t45 19h1664q26 0 45 -19t19 -45zM1408 576v-128q0 -26 -19 -45t-45 -19h-1280q-26 0 -45 19t-19 45v128q0 26 19 45t45 19h1280q26 0 45 -19t19 -45zM1664 960v-128q0 -26 -19 -45 t-45 -19h-1536q-26 0 -45 19t-19 45v128q0 26 19 45t45 19h1536q26 0 45 -19t19 -45zM1280 1344v-128q0 -26 -19 -45t-45 -19h-1152q-26 0 -45 19t-19 45v128q0 26 19 45t45 19h1152q26 0 45 -19t19 -45z" />
-<glyph unicode="&#xf037;" horiz-adv-x="1792" d="M1792 192v-128q0 -26 -19 -45t-45 -19h-1664q-26 0 -45 19t-19 45v128q0 26 19 45t45 19h1664q26 0 45 -19t19 -45zM1408 576v-128q0 -26 -19 -45t-45 -19h-896q-26 0 -45 19t-19 45v128q0 26 19 45t45 19h896q26 0 45 -19t19 -45zM1664 960v-128q0 -26 -19 -45t-45 -19 h-1408q-26 0 -45 19t-19 45v128q0 26 19 45t45 19h1408q26 0 45 -19t19 -45zM1280 1344v-128q0 -26 -19 -45t-45 -19h-640q-26 0 -45 19t-19 45v128q0 26 19 45t45 19h640q26 0 45 -19t19 -45z" />
-<glyph unicode="&#xf038;" horiz-adv-x="1792" d="M1792 192v-128q0 -26 -19 -45t-45 -19h-1664q-26 0 -45 19t-19 45v128q0 26 19 45t45 19h1664q26 0 45 -19t19 -45zM1792 576v-128q0 -26 -19 -45t-45 -19h-1280q-26 0 -45 19t-19 45v128q0 26 19 45t45 19h1280q26 0 45 -19t19 -45zM1792 960v-128q0 -26 -19 -45 t-45 -19h-1536q-26 0 -45 19t-19 45v128q0 26 19 45t45 19h1536q26 0 45 -19t19 -45zM1792 1344v-128q0 -26 -19 -45t-45 -19h-1152q-26 0 -45 19t-19 45v128q0 26 19 45t45 19h1152q26 0 45 -19t19 -45z" />
-<glyph unicode="&#xf039;" horiz-adv-x="1792" d="M1792 192v-128q0 -26 -19 -45t-45 -19h-1664q-26 0 -45 19t-19 45v128q0 26 19 45t45 19h1664q26 0 45 -19t19 -45zM1792 576v-128q0 -26 -19 -45t-45 -19h-1664q-26 0 -45 19t-19 45v128q0 26 19 45t45 19h1664q26 0 45 -19t19 -45zM1792 960v-128q0 -26 -19 -45 t-45 -19h-1664q-26 0 -45 19t-19 45v128q0 26 19 45t45 19h1664q26 0 45 -19t19 -45zM1792 1344v-128q0 -26 -19 -45t-45 -19h-1664q-26 0 -45 19t-19 45v128q0 26 19 45t45 19h1664q26 0 45 -19t19 -45z" />
-<glyph unicode="&#xf03a;" horiz-adv-x="1792" d="M256 224v-192q0 -13 -9.5 -22.5t-22.5 -9.5h-192q-13 0 -22.5 9.5t-9.5 22.5v192q0 13 9.5 22.5t22.5 9.5h192q13 0 22.5 -9.5t9.5 -22.5zM256 608v-192q0 -13 -9.5 -22.5t-22.5 -9.5h-192q-13 0 -22.5 9.5t-9.5 22.5v192q0 13 9.5 22.5t22.5 9.5h192q13 0 22.5 -9.5 t9.5 -22.5zM256 992v-192q0 -13 -9.5 -22.5t-22.5 -9.5h-192q-13 0 -22.5 9.5t-9.5 22.5v192q0 13 9.5 22.5t22.5 9.5h192q13 0 22.5 -9.5t9.5 -22.5zM1792 224v-192q0 -13 -9.5 -22.5t-22.5 -9.5h-1344q-13 0 -22.5 9.5t-9.5 22.5v192q0 13 9.5 22.5t22.5 9.5h1344 q13 0 22.5 -9.5t9.5 -22.5zM256 1376v-192q0 -13 -9.5 -22.5t-22.5 -9.5h-192q-13 0 -22.5 9.5t-9.5 22.5v192q0 13 9.5 22.5t22.5 9.5h192q13 0 22.5 -9.5t9.5 -22.5zM1792 608v-192q0 -13 -9.5 -22.5t-22.5 -9.5h-1344q-13 0 -22.5 9.5t-9.5 22.5v192q0 13 9.5 22.5 t22.5 9.5h1344q13 0 22.5 -9.5t9.5 -22.5zM1792 992v-192q0 -13 -9.5 -22.5t-22.5 -9.5h-1344q-13 0 -22.5 9.5t-9.5 22.5v192q0 13 9.5 22.5t22.5 9.5h1344q13 0 22.5 -9.5t9.5 -22.5zM1792 1376v-192q0 -13 -9.5 -22.5t
 -22.5 -9.5h-1344q-13 0 -22.5 9.5t-9.5 22.5v192 q0 13 9.5 22.5t22.5 9.5h1344q13 0 22.5 -9.5t9.5 -22.5z" />
-<glyph unicode="&#xf03b;" horiz-adv-x="1792" d="M384 992v-576q0 -13 -9.5 -22.5t-22.5 -9.5q-14 0 -23 9l-288 288q-9 9 -9 23t9 23l288 288q9 9 23 9q13 0 22.5 -9.5t9.5 -22.5zM1792 224v-192q0 -13 -9.5 -22.5t-22.5 -9.5h-1728q-13 0 -22.5 9.5t-9.5 22.5v192q0 13 9.5 22.5t22.5 9.5h1728q13 0 22.5 -9.5 t9.5 -22.5zM1792 608v-192q0 -13 -9.5 -22.5t-22.5 -9.5h-1088q-13 0 -22.5 9.5t-9.5 22.5v192q0 13 9.5 22.5t22.5 9.5h1088q13 0 22.5 -9.5t9.5 -22.5zM1792 992v-192q0 -13 -9.5 -22.5t-22.5 -9.5h-1088q-13 0 -22.5 9.5t-9.5 22.5v192q0 13 9.5 22.5t22.5 9.5h1088 q13 0 22.5 -9.5t9.5 -22.5zM1792 1376v-192q0 -13 -9.5 -22.5t-22.5 -9.5h-1728q-13 0 -22.5 9.5t-9.5 22.5v192q0 13 9.5 22.5t22.5 9.5h1728q13 0 22.5 -9.5t9.5 -22.5z" />
-<glyph unicode="&#xf03c;" horiz-adv-x="1792" d="M352 704q0 -14 -9 -23l-288 -288q-9 -9 -23 -9q-13 0 -22.5 9.5t-9.5 22.5v576q0 13 9.5 22.5t22.5 9.5q14 0 23 -9l288 -288q9 -9 9 -23zM1792 224v-192q0 -13 -9.5 -22.5t-22.5 -9.5h-1728q-13 0 -22.5 9.5t-9.5 22.5v192q0 13 9.5 22.5t22.5 9.5h1728q13 0 22.5 -9.5 t9.5 -22.5zM1792 608v-192q0 -13 -9.5 -22.5t-22.5 -9.5h-1088q-13 0 -22.5 9.5t-9.5 22.5v192q0 13 9.5 22.5t22.5 9.5h1088q13 0 22.5 -9.5t9.5 -22.5zM1792 992v-192q0 -13 -9.5 -22.5t-22.5 -9.5h-1088q-13 0 -22.5 9.5t-9.5 22.5v192q0 13 9.5 22.5t22.5 9.5h1088 q13 0 22.5 -9.5t9.5 -22.5zM1792 1376v-192q0 -13 -9.5 -22.5t-22.5 -9.5h-1728q-13 0 -22.5 9.5t-9.5 22.5v192q0 13 9.5 22.5t22.5 9.5h1728q13 0 22.5 -9.5t9.5 -22.5z" />
-<glyph unicode="&#xf03d;" horiz-adv-x="1792" d="M1792 1184v-1088q0 -42 -39 -59q-13 -5 -25 -5q-27 0 -45 19l-403 403v-166q0 -119 -84.5 -203.5t-203.5 -84.5h-704q-119 0 -203.5 84.5t-84.5 203.5v704q0 119 84.5 203.5t203.5 84.5h704q119 0 203.5 -84.5t84.5 -203.5v-165l403 402q18 19 45 19q12 0 25 -5 q39 -17 39 -59z" />
-<glyph unicode="&#xf03e;" horiz-adv-x="1920" d="M640 960q0 -80 -56 -136t-136 -56t-136 56t-56 136t56 136t136 56t136 -56t56 -136zM1664 576v-448h-1408v192l320 320l160 -160l512 512zM1760 1280h-1600q-13 0 -22.5 -9.5t-9.5 -22.5v-1216q0 -13 9.5 -22.5t22.5 -9.5h1600q13 0 22.5 9.5t9.5 22.5v1216 q0 13 -9.5 22.5t-22.5 9.5zM1920 1248v-1216q0 -66 -47 -113t-113 -47h-1600q-66 0 -113 47t-47 113v1216q0 66 47 113t113 47h1600q66 0 113 -47t47 -113z" />
-<glyph unicode="&#xf040;" d="M363 0l91 91l-235 235l-91 -91v-107h128v-128h107zM886 928q0 22 -22 22q-10 0 -17 -7l-542 -542q-7 -7 -7 -17q0 -22 22 -22q10 0 17 7l542 542q7 7 7 17zM832 1120l416 -416l-832 -832h-416v416zM1515 1024q0 -53 -37 -90l-166 -166l-416 416l166 165q36 38 90 38 q53 0 91 -38l235 -234q37 -39 37 -91z" />
-<glyph unicode="&#xf041;" horiz-adv-x="1024" d="M768 896q0 106 -75 181t-181 75t-181 -75t-75 -181t75 -181t181 -75t181 75t75 181zM1024 896q0 -109 -33 -179l-364 -774q-16 -33 -47.5 -52t-67.5 -19t-67.5 19t-46.5 52l-365 774q-33 70 -33 179q0 212 150 362t362 150t362 -150t150 -362z" />
-<glyph unicode="&#xf042;" d="M768 96v1088q-148 0 -273 -73t-198 -198t-73 -273t73 -273t198 -198t273 -73zM1536 640q0 -209 -103 -385.5t-279.5 -279.5t-385.5 -103t-385.5 103t-279.5 279.5t-103 385.5t103 385.5t279.5 279.5t385.5 103t385.5 -103t279.5 -279.5t103 -385.5z" />
-<glyph unicode="&#xf043;" horiz-adv-x="1024" d="M512 384q0 36 -20 69q-1 1 -15.5 22.5t-25.5 38t-25 44t-21 50.5q-4 16 -21 16t-21 -16q-7 -23 -21 -50.5t-25 -44t-25.5 -38t-15.5 -22.5q-20 -33 -20 -69q0 -53 37.5 -90.5t90.5 -37.5t90.5 37.5t37.5 90.5zM1024 512q0 -212 -150 -362t-362 -150t-362 150t-150 362 q0 145 81 275q6 9 62.5 90.5t101 151t99.5 178t83 201.5q9 30 34 47t51 17t51.5 -17t33.5 -47q28 -93 83 -201.5t99.5 -178t101 -151t62.5 -90.5q81 -127 81 -275z" />
-<glyph unicode="&#xf044;" horiz-adv-x="1792" d="M888 352l116 116l-152 152l-116 -116v-56h96v-96h56zM1328 1072q-16 16 -33 -1l-350 -350q-17 -17 -1 -33t33 1l350 350q17 17 1 33zM1408 478v-190q0 -119 -84.5 -203.5t-203.5 -84.5h-832q-119 0 -203.5 84.5t-84.5 203.5v832q0 119 84.5 203.5t203.5 84.5h832 q63 0 117 -25q15 -7 18 -23q3 -17 -9 -29l-49 -49q-14 -14 -32 -8q-23 6 -45 6h-832q-66 0 -113 -47t-47 -113v-832q0 -66 47 -113t113 -47h832q66 0 113 47t47 113v126q0 13 9 22l64 64q15 15 35 7t20 -29zM1312 1216l288 -288l-672 -672h-288v288zM1756 1084l-92 -92 l-288 288l92 92q28 28 68 28t68 -28l152 -152q28 -28 28 -68t-28 -68z" />
-<glyph unicode="&#xf045;" horiz-adv-x="1664" d="M1408 547v-259q0 -119 -84.5 -203.5t-203.5 -84.5h-832q-119 0 -203.5 84.5t-84.5 203.5v832q0 119 84.5 203.5t203.5 84.5h255v0q13 0 22.5 -9.5t9.5 -22.5q0 -27 -26 -32q-77 -26 -133 -60q-10 -4 -16 -4h-112q-66 0 -113 -47t-47 -113v-832q0 -66 47 -113t113 -47h832 q66 0 113 47t47 113v214q0 19 18 29q28 13 54 37q16 16 35 8q21 -9 21 -29zM1645 1043l-384 -384q-18 -19 -45 -19q-12 0 -25 5q-39 17 -39 59v192h-160q-323 0 -438 -131q-119 -137 -74 -473q3 -23 -20 -34q-8 -2 -12 -2q-16 0 -26 13q-10 14 -21 31t-39.5 68.5t-49.5 99.5 t-38.5 114t-17.5 122q0 49 3.5 91t14 90t28 88t47 81.5t68.5 74t94.5 61.5t124.5 48.5t159.5 30.5t196.5 11h160v192q0 42 39 59q13 5 25 5q26 0 45 -19l384 -384q19 -19 19 -45t-19 -45z" />
-<glyph unicode="&#xf046;" horiz-adv-x="1664" d="M1408 606v-318q0 -119 -84.5 -203.5t-203.5 -84.5h-832q-119 0 -203.5 84.5t-84.5 203.5v832q0 119 84.5 203.5t203.5 84.5h832q63 0 117 -25q15 -7 18 -23q3 -17 -9 -29l-49 -49q-10 -10 -23 -10q-3 0 -9 2q-23 6 -45 6h-832q-66 0 -113 -47t-47 -113v-832 q0 -66 47 -113t113 -47h832q66 0 113 47t47 113v254q0 13 9 22l64 64q10 10 23 10q6 0 12 -3q20 -8 20 -29zM1639 1095l-814 -814q-24 -24 -57 -24t-57 24l-430 430q-24 24 -24 57t24 57l110 110q24 24 57 24t57 -24l263 -263l647 647q24 24 57 24t57 -24l110 -110 q24 -24 24 -57t-24 -57z" />
-<glyph unicode="&#xf047;" horiz-adv-x="1792" d="M1792 640q0 -26 -19 -45l-256 -256q-19 -19 -45 -19t-45 19t-19 45v128h-384v-384h128q26 0 45 -19t19 -45t-19 -45l-256 -256q-19 -19 -45 -19t-45 19l-256 256q-19 19 -19 45t19 45t45 19h128v384h-384v-128q0 -26 -19 -45t-45 -19t-45 19l-256 256q-19 19 -19 45 t19 45l256 256q19 19 45 19t45 -19t19 -45v-128h384v384h-128q-26 0 -45 19t-19 45t19 45l256 256q19 19 45 19t45 -19l256 -256q19 -19 19 -45t-19 -45t-45 -19h-128v-384h384v128q0 26 19 45t45 19t45 -19l256 -256q19 -19 19 -45z" />
-<glyph unicode="&#xf048;" horiz-adv-x="1024" d="M979 1395q19 19 32 13t13 -32v-1472q0 -26 -13 -32t-32 13l-710 710q-9 9 -13 19v-678q0 -26 -19 -45t-45 -19h-128q-26 0 -45 19t-19 45v1408q0 26 19 45t45 19h128q26 0 45 -19t19 -45v-678q4 11 13 19z" />
-<glyph unicode="&#xf049;" horiz-adv-x="1792" d="M1747 1395q19 19 32 13t13 -32v-1472q0 -26 -13 -32t-32 13l-710 710q-9 9 -13 19v-710q0 -26 -13 -32t-32 13l-710 710q-9 9 -13 19v-678q0 -26 -19 -45t-45 -19h-128q-26 0 -45 19t-19 45v1408q0 26 19 45t45 19h128q26 0 45 -19t19 -45v-678q4 11 13 19l710 710 q19 19 32 13t13 -32v-710q4 11 13 19z" />
-<glyph unicode="&#xf04a;" horiz-adv-x="1664" d="M1619 1395q19 19 32 13t13 -32v-1472q0 -26 -13 -32t-32 13l-710 710q-8 9 -13 19v-710q0 -26 -13 -32t-32 13l-710 710q-19 19 -19 45t19 45l710 710q19 19 32 13t13 -32v-710q5 11 13 19z" />
-<glyph unicode="&#xf04b;" horiz-adv-x="1408" d="M1384 609l-1328 -738q-23 -13 -39.5 -3t-16.5 36v1472q0 26 16.5 36t39.5 -3l1328 -738q23 -13 23 -31t-23 -31z" />
-<glyph unicode="&#xf04c;" d="M1536 1344v-1408q0 -26 -19 -45t-45 -19h-512q-26 0 -45 19t-19 45v1408q0 26 19 45t45 19h512q26 0 45 -19t19 -45zM640 1344v-1408q0 -26 -19 -45t-45 -19h-512q-26 0 -45 19t-19 45v1408q0 26 19 45t45 19h512q26 0 45 -19t19 -45z" />
-<glyph unicode="&#xf04d;" d="M1536 1344v-1408q0 -26 -19 -45t-45 -19h-1408q-26 0 -45 19t-19 45v1408q0 26 19 45t45 19h1408q26 0 45 -19t19 -45z" />
-<glyph unicode="&#xf04e;" horiz-adv-x="1664" d="M45 -115q-19 -19 -32 -13t-13 32v1472q0 26 13 32t32 -13l710 -710q8 -8 13 -19v710q0 26 13 32t32 -13l710 -710q19 -19 19 -45t-19 -45l-710 -710q-19 -19 -32 -13t-13 32v710q-5 -10 -13 -19z" />
-<glyph unicode="&#xf050;" horiz-adv-x="1792" d="M45 -115q-19 -19 -32 -13t-13 32v1472q0 26 13 32t32 -13l710 -710q8 -8 13 -19v710q0 26 13 32t32 -13l710 -710q8 -8 13 -19v678q0 26 19 45t45 19h128q26 0 45 -19t19 -45v-1408q0 -26 -19 -45t-45 -19h-128q-26 0 -45 19t-19 45v678q-5 -10 -13 -19l-710 -710 q-19 -19 -32 -13t-13 32v710q-5 -10 -13 -19z" />
-<glyph unicode="&#xf051;" horiz-adv-x="1024" d="M45 -115q-19 -19 -32 -13t-13 32v1472q0 26 13 32t32 -13l710 -710q8 -8 13 -19v678q0 26 19 45t45 19h128q26 0 45 -19t19 -45v-1408q0 -26 -19 -45t-45 -19h-128q-26 0 -45 19t-19 45v678q-5 -10 -13 -19z" />
-<glyph unicode="&#xf052;" horiz-adv-x="1538" d="M14 557l710 710q19 19 45 19t45 -19l710 -710q19 -19 13 -32t-32 -13h-1472q-26 0 -32 13t13 32zM1473 0h-1408q-26 0 -45 19t-19 45v256q0 26 19 45t45 19h1408q26 0 45 -19t19 -45v-256q0 -26 -19 -45t-45 -19z" />
-<glyph unicode="&#xf053;" horiz-adv-x="1152" d="M742 -37l-652 651q-37 37 -37 90.5t37 90.5l652 651q37 37 90.5 37t90.5 -37l75 -75q37 -37 37 -90.5t-37 -90.5l-486 -486l486 -485q37 -38 37 -91t-37 -90l-75 -75q-37 -37 -90.5 -37t-90.5 37z" />
-<glyph unicode="&#xf054;" horiz-adv-x="1152" d="M1099 704q0 -52 -37 -91l-652 -651q-37 -37 -90 -37t-90 37l-76 75q-37 39 -37 91q0 53 37 90l486 486l-486 485q-37 39 -37 91q0 53 37 90l76 75q36 38 90 38t90 -38l652 -651q37 -37 37 -90z" />
-<glyph unicode="&#xf055;" d="M1216 576v128q0 26 -19 45t-45 19h-256v256q0 26 -19 45t-45 19h-128q-26 0 -45 -19t-19 -45v-256h-256q-26 0 -45 -19t-19 -45v-128q0 -26 19 -45t45 -19h256v-256q0 -26 19 -45t45 -19h128q26 0 45 19t19 45v256h256q26 0 45 19t19 45zM1536 640q0 -209 -103 -385.5 t-279.5 -279.5t-385.5 -103t-385.5 103t-279.5 279.5t-103 385.5t103 385.5t279.5 279.5t385.5 103t385.5 -103t279.5 -279.5t103 -385.5z" />
-<glyph unicode="&#xf056;" d="M1216 576v128q0 26 -19 45t-45 19h-768q-26 0 -45 -19t-19 -45v-128q0 -26 19 -45t45 -19h768q26 0 45 19t19 45zM1536 640q0 -209 -103 -385.5t-279.5 -279.5t-385.5 -103t-385.5 103t-279.5 279.5t-103 385.5t103 385.5t279.5 279.5t385.5 103t385.5 -103t279.5 -279.5 t103 -385.5z" />
-<glyph unicode="&#xf057;" d="M1149 414q0 26 -19 45l-181 181l181 181q19 19 19 45q0 27 -19 46l-90 90q-19 19 -46 19q-26 0 -45 -19l-181 -181l-181 181q-19 19 -45 19q-27 0 -46 -19l-90 -90q-19 -19 -19 -46q0 -26 19 -45l181 -181l-181 -181q-19 -19 -19 -45q0 -27 19 -46l90 -90q19 -19 46 -19 q26 0 45 19l181 181l181 -181q19 -19 45 -19q27 0 46 19l90 90q19 19 19 46zM1536 640q0 -209 -103 -385.5t-279.5 -279.5t-385.5 -103t-385.5 103t-279.5 279.5t-103 385.5t103 385.5t279.5 279.5t385.5 103t385.5 -103t279.5 -279.5t103 -385.5z" />
-<glyph unicode="&#xf058;" d="M1284 802q0 28 -18 46l-91 90q-19 19 -45 19t-45 -19l-408 -407l-226 226q-19 19 -45 19t-45 -19l-91 -90q-18 -18 -18 -46q0 -27 18 -45l362 -362q19 -19 45 -19q27 0 46 19l543 543q18 18 18 45zM1536 640q0 -209 -103 -385.5t-279.5 -279.5t-385.5 -103t-385.5 103 t-279.5 279.5t-103 385.5t103 385.5t279.5 279.5t385.5 103t385.5 -103t279.5 -279.5t103 -385.5z" />
-<glyph unicode="&#xf059;" d="M896 160v192q0 14 -9 23t-23 9h-192q-14 0 -23 -9t-9 -23v-192q0 -14 9 -23t23 -9h192q14 0 23 9t9 23zM1152 832q0 88 -55.5 163t-138.5 116t-170 41q-243 0 -371 -213q-15 -24 8 -42l132 -100q7 -6 19 -6q16 0 25 12q53 68 86 92q34 24 86 24q48 0 85.5 -26t37.5 -59 q0 -38 -20 -61t-68 -45q-63 -28 -115.5 -86.5t-52.5 -125.5v-36q0 -14 9 -23t23 -9h192q14 0 23 9t9 23q0 19 21.5 49.5t54.5 49.5q32 18 49 28.5t46 35t44.5 48t28 60.5t12.5 81zM1536 640q0 -209 -103 -385.5t-279.5 -279.5t-385.5 -103t-385.5 103t-279.5 279.5 t-103 385.5t103 385.5t279.5 279.5t385.5 103t385.5 -103t279.5 -279.5t103 -385.5z" />
-<glyph unicode="&#xf05a;" d="M1024 160v160q0 14 -9 23t-23 9h-96v512q0 14 -9 23t-23 9h-320q-14 0 -23 -9t-9 -23v-160q0 -14 9 -23t23 -9h96v-320h-96q-14 0 -23 -9t-9 -23v-160q0 -14 9 -23t23 -9h448q14 0 23 9t9 23zM896 1056v160q0 14 -9 23t-23 9h-192q-14 0 -23 -9t-9 -23v-160q0 -14 9 -23 t23 -9h192q14 0 23 9t9 23zM1536 640q0 -209 -103 -385.5t-279.5 -279.5t-385.5 -103t-385.5 103t-279.5 279.5t-103 385.5t103 385.5t279.5 279.5t385.5 103t385.5 -103t279.5 -279.5t103 -385.5z" />
-<glyph unicode="&#xf05b;" d="M1197 512h-109q-26 0 -45 19t-19 45v128q0 26 19 45t45 19h109q-32 108 -112.5 188.5t-188.5 112.5v-109q0 -26 -19 -45t-45 -19h-128q-26 0 -45 19t-19 45v109q-108 -32 -188.5 -112.5t-112.5 -188.5h109q26 0 45 -19t19 -45v-128q0 -26 -19 -45t-45 -19h-109 q32 -108 112.5 -188.5t188.5 -112.5v109q0 26 19 45t45 19h128q26 0 45 -19t19 -45v-109q108 32 188.5 112.5t112.5 188.5zM1536 704v-128q0 -26 -19 -45t-45 -19h-143q-37 -161 -154.5 -278.5t-278.5 -154.5v-143q0 -26 -19 -45t-45 -19h-128q-26 0 -45 19t-19 45v143 q-161 37 -278.5 154.5t-154.5 278.5h-143q-26 0 -45 19t-19 45v128q0 26 19 45t45 19h143q37 161 154.5 278.5t278.5 154.5v143q0 26 19 45t45 19h128q26 0 45 -19t19 -45v-143q161 -37 278.5 -154.5t154.5 -278.5h143q26 0 45 -19t19 -45z" />
-<glyph unicode="&#xf05c;" d="M1097 457l-146 -146q-10 -10 -23 -10t-23 10l-137 137l-137 -137q-10 -10 -23 -10t-23 10l-146 146q-10 10 -10 23t10 23l137 137l-137 137q-10 10 -10 23t10 23l146 146q10 10 23 10t23 -10l137 -137l137 137q10 10 23 10t23 -10l146 -146q10 -10 10 -23t-10 -23 l-137 -137l137 -137q10 -10 10 -23t-10 -23zM1312 640q0 148 -73 273t-198 198t-273 73t-273 -73t-198 -198t-73 -273t73 -273t198 -198t273 -73t273 73t198 198t73 273zM1536 640q0 -209 -103 -385.5t-279.5 -279.5t-385.5 -103t-385.5 103t-279.5 279.5t-103 385.5 t103 385.5t279.5 279.5t385.5 103t385.5 -103t279.5 -279.5t103 -385.5z" />
-<glyph unicode="&#xf05d;" d="M1171 723l-422 -422q-19 -19 -45 -19t-45 19l-294 294q-19 19 -19 45t19 45l102 102q19 19 45 19t45 -19l147 -147l275 275q19 19 45 19t45 -19l102 -102q19 -19 19 -45t-19 -45zM1312 640q0 148 -73 273t-198 198t-273 73t-273 -73t-198 -198t-73 -273t73 -273t198 -198 t273 -73t273 73t198 198t73 273zM1536 640q0 -209 -103 -385.5t-279.5 -279.5t-385.5 -103t-385.5 103t-279.5 279.5t-103 385.5t103 385.5t279.5 279.5t385.5 103t385.5 -103t279.5 -279.5t103 -385.5z" />
-<glyph unicode="&#xf05e;" d="M1312 643q0 161 -87 295l-754 -753q137 -89 297 -89q111 0 211.5 43.5t173.5 116.5t116 174.5t43 212.5zM313 344l755 754q-135 91 -300 91q-148 0 -273 -73t-198 -199t-73 -274q0 -162 89 -299zM1536 643q0 -157 -61 -300t-163.5 -246t-245 -164t-298.5 -61t-298.5 61 t-245 164t-163.5 246t-61 300t61 299.5t163.5 245.5t245 164t298.5 61t298.5 -61t245 -164t163.5 -245.5t61 -299.5z" />
-<glyph unicode="&#xf060;" d="M1536 640v-128q0 -53 -32.5 -90.5t-84.5 -37.5h-704l293 -294q38 -36 38 -90t-38 -90l-75 -76q-37 -37 -90 -37q-52 0 -91 37l-651 652q-37 37 -37 90q0 52 37 91l651 650q38 38 91 38q52 0 90 -38l75 -74q38 -38 38 -91t-38 -91l-293 -293h704q52 0 84.5 -37.5 t32.5 -90.5z" />
-<glyph unicode="&#xf061;" d="M1472 576q0 -54 -37 -91l-651 -651q-39 -37 -91 -37q-51 0 -90 37l-75 75q-38 38 -38 91t38 91l293 293h-704q-52 0 -84.5 37.5t-32.5 90.5v128q0 53 32.5 90.5t84.5 37.5h704l-293 294q-38 36 -38 90t38 90l75 75q38 38 90 38q53 0 91 -38l651 -651q37 -35 37 -90z" />
-<glyph unicode="&#xf062;" horiz-adv-x="1664" d="M1611 565q0 -51 -37 -90l-75 -75q-38 -38 -91 -38q-54 0 -90 38l-294 293v-704q0 -52 -37.5 -84.5t-90.5 -32.5h-128q-53 0 -90.5 32.5t-37.5 84.5v704l-294 -293q-36 -38 -90 -38t-90 38l-75 75q-38 38 -38 90q0 53 38 91l651 651q35 37 90 37q54 0 91 -37l651 -651 q37 -39 37 -91z" />
-<glyph unicode="&#xf063;" horiz-adv-x="1664" d="M1611 704q0 -53 -37 -90l-651 -652q-39 -37 -91 -37q-53 0 -90 37l-651 652q-38 36 -38 90q0 53 38 91l74 75q39 37 91 37q53 0 90 -37l294 -294v704q0 52 38 90t90 38h128q52 0 90 -38t38 -90v-704l294 294q37 37 90 37q52 0 91 -37l75 -75q37 -39 37 -91z" />
-<glyph unicode="&#xf064;" horiz-adv-x="1792" d="M1792 896q0 -26 -19 -45l-512 -512q-19 -19 -45 -19t-45 19t-19 45v256h-224q-98 0 -175.5 -6t-154 -21.5t-133 -42.5t-105.5 -69.5t-80 -101t-48.5 -138.5t-17.5 -181q0 -55 5 -123q0 -6 2.5 -23.5t2.5 -26.5q0 -15 -8.5 -25t-23.5 -10q-16 0 -28 17q-7 9 -13 22 t-13.5 30t-10.5 24q-127 285 -127 451q0 199 53 333q162 403 875 403h224v256q0 26 19 45t45 19t45 -19l512 -512q19 -19 19 -45z" />
-<glyph unicode="&#xf065;" d="M755 480q0 -13 -10 -23l-332 -332l144 -144q19 -19 19 -45t-19 -45t-45 -19h-448q-26 0 -45 19t-19 45v448q0 26 19 45t45 19t45 -19l144 -144l332 332q10 10 23 10t23 -10l114 -114q10 -10 10 -23zM1536 1344v-448q0 -26 -19 -45t-45 -19t-45 19l-144 144l-332 -332 q-10 -10 -23 -10t-23 10l-114 114q-10 10 -10 23t10 23l332 332l-144 144q-19 19 -19 45t19 45t45 19h448q26 0 45 -19t19 -45z" />
-<glyph unicode="&#xf066;" d="M768 576v-448q0 -26 -19 -45t-45 -19t-45 19l-144 144l-332 -332q-10 -10 -23 -10t-23 10l-114 114q-10 10 -10 23t10 23l332 332l-144 144q-19 19 -19 45t19 45t45 19h448q26 0 45 -19t19 -45zM1523 1248q0 -13 -10 -23l-332 -332l144 -144q19 -19 19 -45t-19 -45 t-45 -19h-448q-26 0 -45 19t-19 45v448q0 26 19 45t45 19t45 -19l144 -144l332 332q10 10 23 10t23 -10l114 -114q10 -10 10 -23z" />
-<glyph unicode="&#xf067;" horiz-adv-x="1408" d="M1408 800v-192q0 -40 -28 -68t-68 -28h-416v-416q0 -40 -28 -68t-68 -28h-192q-40 0 -68 28t-28 68v416h-416q-40 0 -68 28t-28 68v192q0 40 28 68t68 28h416v416q0 40 28 68t68 28h192q40 0 68 -28t28 -68v-416h416q40 0 68 -28t28 -68z" />
-<glyph unicode="&#xf068;" horiz-adv-x="1408" d="M1408 800v-192q0 -40 -28 -68t-68 -28h-1216q-40 0 -68 28t-28 68v192q0 40 28 68t68 28h1216q40 0 68 -28t28 -68z" />
-<glyph unicode="&#xf069;" horiz-adv-x="1664" d="M1482 486q46 -26 59.5 -77.5t-12.5 -97.5l-64 -110q-26 -46 -77.5 -59.5t-97.5 12.5l-266 153v-307q0 -52 -38 -90t-90 -38h-128q-52 0 -90 38t-38 90v307l-266 -153q-46 -26 -97.5 -12.5t-77.5 59.5l-64 110q-26 46 -12.5 97.5t59.5 77.5l266 154l-266 154 q-46 26 -59.5 77.5t12.5 97.5l64 110q26 46 77.5 59.5t97.5 -12.5l266 -153v307q0 52 38 90t90 38h128q52 0 90 -38t38 -90v-307l266 153q46 26 97.5 12.5t77.5 -59.5l64 -110q26 -46 12.5 -97.5t-59.5 -77.5l-266 -154z" />
-<glyph unicode="&#xf06a;" d="M768 1408q209 0 385.5 -103t279.5 -279.5t103 -385.5t-103 -385.5t-279.5 -279.5t-385.5 -103t-385.5 103t-279.5 279.5t-103 385.5t103 385.5t279.5 279.5t385.5 103zM896 161v190q0 14 -9 23.5t-22 9.5h-192q-13 0 -23 -10t-10 -23v-190q0 -13 10 -23t23 -10h192 q13 0 22 9.5t9 23.5zM894 505l18 621q0 12 -10 18q-10 8 -24 8h-220q-14 0 -24 -8q-10 -6 -10 -18l17 -621q0 -10 10 -17.5t24 -7.5h185q14 0 23.5 7.5t10.5 17.5z" />
-<glyph unicode="&#xf06b;" d="M928 180v56v468v192h-320v-192v-468v-56q0 -25 18 -38.5t46 -13.5h192q28 0 46 13.5t18 38.5zM472 1024h195l-126 161q-26 31 -69 31q-40 0 -68 -28t-28 -68t28 -68t68 -28zM1160 1120q0 40 -28 68t-68 28q-43 0 -69 -31l-125 -161h194q40 0 68 28t28 68zM1536 864v-320 q0 -14 -9 -23t-23 -9h-96v-416q0 -40 -28 -68t-68 -28h-1088q-40 0 -68 28t-28 68v416h-96q-14 0 -23 9t-9 23v320q0 14 9 23t23 9h440q-93 0 -158.5 65.5t-65.5 158.5t65.5 158.5t158.5 65.5q107 0 168 -77l128 -165l128 165q61 77 168 77q93 0 158.5 -65.5t65.5 -158.5 t-65.5 -158.5t-158.5 -65.5h440q14 0 23 -9t9 -23z" />
-<glyph unicode="&#xf06c;" horiz-adv-x="1792" d="M1280 832q0 26 -19 45t-45 19q-172 0 -318 -49.5t-259.5 -134t-235.5 -219.5q-19 -21 -19 -45q0 -26 19 -45t45 -19q24 0 45 19q27 24 74 71t67 66q137 124 268.5 176t313.5 52q26 0 45 19t19 45zM1792 1030q0 -95 -20 -193q-46 -224 -184.5 -383t-357.5 -268 q-214 -108 -438 -108q-148 0 -286 47q-15 5 -88 42t-96 37q-16 0 -39.5 -32t-45 -70t-52.5 -70t-60 -32q-30 0 -51 11t-31 24t-27 42q-2 4 -6 11t-5.5 10t-3 9.5t-1.5 13.5q0 35 31 73.5t68 65.5t68 56t31 48q0 4 -14 38t-16 44q-9 51 -9 104q0 115 43.5 220t119 184.5 t170.5 139t204 95.5q55 18 145 25.5t179.5 9t178.5 6t163.5 24t113.5 56.5l29.5 29.5t29.5 28t27 20t36.5 16t43.5 4.5q39 0 70.5 -46t47.5 -112t24 -124t8 -96z" />
-<glyph unicode="&#xf06d;" horiz-adv-x="1408" d="M1408 -160v-64q0 -13 -9.5 -22.5t-22.5 -9.5h-1344q-13 0 -22.5 9.5t-9.5 22.5v64q0 13 9.5 22.5t22.5 9.5h1344q13 0 22.5 -9.5t9.5 -22.5zM1152 896q0 -78 -24.5 -144t-64 -112.5t-87.5 -88t-96 -77.5t-87.5 -72t-64 -81.5t-24.5 -96.5q0 -96 67 -224l-4 1l1 -1 q-90 41 -160 83t-138.5 100t-113.5 122.5t-72.5 150.5t-27.5 184q0 78 24.5 144t64 112.5t87.5 88t96 77.5t87.5 72t64 81.5t24.5 96.5q0 94 -66 224l3 -1l-1 1q90 -41 160 -83t138.5 -100t113.5 -122.5t72.5 -150.5t27.5 -184z" />
-<glyph unicode="&#xf06e;" horiz-adv-x="1792" d="M1664 576q-152 236 -381 353q61 -104 61 -225q0 -185 -131.5 -316.5t-316.5 -131.5t-316.5 131.5t-131.5 316.5q0 121 61 225q-229 -117 -381 -353q133 -205 333.5 -326.5t434.5 -121.5t434.5 121.5t333.5 326.5zM944 960q0 20 -14 34t-34 14q-125 0 -214.5 -89.5 t-89.5 -214.5q0 -20 14 -34t34 -14t34 14t14 34q0 86 61 147t147 61q20 0 34 14t14 34zM1792 576q0 -34 -20 -69q-140 -230 -376.5 -368.5t-499.5 -138.5t-499.5 139t-376.5 368q-20 35 -20 69t20 69q140 229 376.5 368t499.5 139t499.5 -139t376.5 -368q20 -35 20 -69z" />
-<glyph unicode="&#xf070;" horiz-adv-x="1792" d="M555 201l78 141q-87 63 -136 159t-49 203q0 121 61 225q-229 -117 -381 -353q167 -258 427 -375zM944 960q0 20 -14 34t-34 14q-125 0 -214.5 -89.5t-89.5 -214.5q0 -20 14 -34t34 -14t34 14t14 34q0 86 61 147t147 61q20 0 34 14t14 34zM1307 1151q0 -7 -1 -9 q-105 -188 -315 -566t-316 -567l-49 -89q-10 -16 -28 -16q-12 0 -134 70q-16 10 -16 28q0 12 44 87q-143 65 -263.5 173t-208.5 245q-20 31 -20 69t20 69q153 235 380 371t496 136q89 0 180 -17l54 97q10 16 28 16q5 0 18 -6t31 -15.5t33 -18.5t31.5 -18.5t19.5 -11.5 q16 -10 16 -27zM1344 704q0 -139 -79 -253.5t-209 -164.5l280 502q8 -45 8 -84zM1792 576q0 -35 -20 -69q-39 -64 -109 -145q-150 -172 -347.5 -267t-419.5 -95l74 132q212 18 392.5 137t301.5 307q-115 179 -282 294l63 112q95 -64 182.5 -153t144.5 -184q20 -34 20 -69z " />
-<glyph unicode="&#xf071;" horiz-adv-x="1792" d="M1024 161v190q0 14 -9.5 23.5t-22.5 9.5h-192q-13 0 -22.5 -9.5t-9.5 -23.5v-190q0 -14 9.5 -23.5t22.5 -9.5h192q13 0 22.5 9.5t9.5 23.5zM1022 535l18 459q0 12 -10 19q-13 11 -24 11h-220q-11 0 -24 -11q-10 -7 -10 -21l17 -457q0 -10 10 -16.5t24 -6.5h185 q14 0 23.5 6.5t10.5 16.5zM1008 1469l768 -1408q35 -63 -2 -126q-17 -29 -46.5 -46t-63.5 -17h-1536q-34 0 -63.5 17t-46.5 46q-37 63 -2 126l768 1408q17 31 47 49t65 18t65 -18t47 -49z" />
-<glyph unicode="&#xf072;" horiz-adv-x="1408" d="M1376 1376q44 -52 12 -148t-108 -172l-161 -161l160 -696q5 -19 -12 -33l-128 -96q-7 -6 -19 -6q-4 0 -7 1q-15 3 -21 16l-279 508l-259 -259l53 -194q5 -17 -8 -31l-96 -96q-9 -9 -23 -9h-2q-15 2 -24 13l-189 252l-252 189q-11 7 -13 23q-1 13 9 25l96 97q9 9 23 9 q6 0 8 -1l194 -53l259 259l-508 279q-14 8 -17 24q-2 16 9 27l128 128q14 13 30 8l665 -159l160 160q76 76 172 108t148 -12z" />
-<glyph unicode="&#xf073;" horiz-adv-x="1664" d="M128 -128h288v288h-288v-288zM480 -128h320v288h-320v-288zM128 224h288v320h-288v-320zM480 224h320v320h-320v-320zM128 608h288v288h-288v-288zM864 -128h320v288h-320v-288zM480 608h320v288h-320v-288zM1248 -128h288v288h-288v-288zM864 224h320v320h-320v-320z M512 1088v288q0 13 -9.5 22.5t-22.5 9.5h-64q-13 0 -22.5 -9.5t-9.5 -22.5v-288q0 -13 9.5 -22.5t22.5 -9.5h64q13 0 22.5 9.5t9.5 22.5zM1248 224h288v320h-288v-320zM864 608h320v288h-320v-288zM1248 608h288v288h-288v-288zM1280 1088v288q0 13 -9.5 22.5t-22.5 9.5h-64 q-13 0 -22.5 -9.5t-9.5 -22.5v-288q0 -13 9.5 -22.5t22.5 -9.5h64q13 0 22.5 9.5t9.5 22.5zM1664 1152v-1280q0 -52 -38 -90t-90 -38h-1408q-52 0 -90 38t-38 90v1280q0 52 38 90t90 38h128v96q0 66 47 113t113 47h64q66 0 113 -47t47 -113v-96h384v96q0 66 47 113t113 47 h64q66 0 113 -47t47 -113v-96h128q52 0 90 -38t38 -90z" />
-<glyph unicode="&#xf074;" horiz-adv-x="1792" d="M666 1055q-60 -92 -137 -273q-22 45 -37 72.5t-40.5 63.5t-51 56.5t-63 35t-81.5 14.5h-224q-14 0 -23 9t-9 23v192q0 14 9 23t23 9h224q250 0 410 -225zM1792 256q0 -14 -9 -23l-320 -320q-9 -9 -23 -9q-13 0 -22.5 9.5t-9.5 22.5v192q-32 0 -85 -0.5t-81 -1t-73 1 t-71 5t-64 10.5t-63 18.5t-58 28.5t-59 40t-55 53.5t-56 69.5q59 93 136 273q22 -45 37 -72.5t40.5 -63.5t51 -56.5t63 -35t81.5 -14.5h256v192q0 14 9 23t23 9q12 0 24 -10l319 -319q9 -9 9 -23zM1792 1152q0 -14 -9 -23l-320 -320q-9 -9 -23 -9q-13 0 -22.5 9.5t-9.5 22.5 v192h-256q-48 0 -87 -15t-69 -45t-51 -61.5t-45 -77.5q-32 -62 -78 -171q-29 -66 -49.5 -111t-54 -105t-64 -100t-74 -83t-90 -68.5t-106.5 -42t-128 -16.5h-224q-14 0 -23 9t-9 23v192q0 14 9 23t23 9h224q48 0 87 15t69 45t51 61.5t45 77.5q32 62 78 171q29 66 49.5 111 t54 105t64 100t74 83t90 68.5t106.5 42t128 16.5h256v192q0 14 9 23t23 9q12 0 24 -10l319 -319q9 -9 9 -23z" />
-<glyph unicode="&#xf075;" horiz-adv-x="1792" d="M1792 640q0 -174 -120 -321.5t-326 -233t-450 -85.5q-70 0 -145 8q-198 -175 -460 -242q-49 -14 -114 -22q-17 -2 -30.5 9t-17.5 29v1q-3 4 -0.5 12t2 10t4.5 9.5l6 9t7 8.5t8 9q7 8 31 34.5t34.5 38t31 39.5t32.5 51t27 59t26 76q-157 89 -247.5 220t-90.5 281 q0 130 71 248.5t191 204.5t286 136.5t348 50.5q244 0 450 -85.5t326 -233t120 -321.5z" />
-<glyph unicode="&#xf076;" d="M1536 704v-128q0 -201 -98.5 -362t-274 -251.5t-395.5 -90.5t-395.5 90.5t-274 251.5t-98.5 362v128q0 26 19 45t45 19h384q26 0 45 -19t19 -45v-128q0 -52 23.5 -90t53.5 -57t71 -30t64 -13t44 -2t44 2t64 13t71 30t53.5 57t23.5 90v128q0 26 19 45t45 19h384 q26 0 45 -19t19 -45zM512 1344v-384q0 -26 -19 -45t-45 -19h-384q-26 0 -45 19t-19 45v384q0 26 19 45t45 19h384q26 0 45 -19t19 -45zM1536 1344v-384q0 -26 -19 -45t-45 -19h-384q-26 0 -45 19t-19 45v384q0 26 19 45t45 19h384q26 0 45 -19t19 -45z" />
-<glyph unicode="&#xf077;" horiz-adv-x="1664" d="M1611 320q0 -53 -37 -90l-75 -75q-38 -38 -91 -38q-54 0 -90 38l-486 485l-486 -485q-36 -38 -90 -38t-90 38l-75 75q-38 36 -38 90q0 53 38 91l651 651q37 37 90 37q52 0 91 -37l650 -651q38 -38 38 -91z" />
-<glyph unicode="&#xf078;" horiz-adv-x="1664" d="M1611 832q0 -53 -37 -90l-651 -651q-38 -38 -91 -38q-54 0 -90 38l-651 651q-38 36 -38 90q0 53 38 91l74 75q39 37 91 37q53 0 90 -37l486 -486l486 486q37 37 90 37q52 0 91 -37l75 -75q37 -39 37 -91z" />
-<glyph unicode="&#xf079;" horiz-adv-x="1920" d="M1280 32q0 -13 -9.5 -22.5t-22.5 -9.5h-960q-8 0 -13.5 2t-9 7t-5.5 8t-3 11.5t-1 11.5v13v11v160v416h-192q-26 0 -45 19t-19 45q0 24 15 41l320 384q19 22 49 22t49 -22l320 -384q15 -17 15 -41q0 -26 -19 -45t-45 -19h-192v-384h576q16 0 25 -11l160 -192q7 -11 7 -21 zM1920 448q0 -24 -15 -41l-320 -384q-20 -23 -49 -23t-49 23l-320 384q-15 17 -15 41q0 26 19 45t45 19h192v384h-576q-16 0 -25 12l-160 192q-7 9 -7 20q0 13 9.5 22.5t22.5 9.5h960q8 0 13.5 -2t9 -7t5.5 -8t3 -11.5t1 -11.5v-13v-11v-160v-416h192q26 0 45 -19t19 -45z " />
-<glyph unicode="&#xf07a;" horiz-adv-x="1664" d="M640 0q0 -53 -37.5 -90.5t-90.5 -37.5t-90.5 37.5t-37.5 90.5t37.5 90.5t90.5 37.5t90.5 -37.5t37.5 -90.5zM1536 0q0 -53 -37.5 -90.5t-90.5 -37.5t-90.5 37.5t-37.5 90.5t37.5 90.5t90.5 37.5t90.5 -37.5t37.5 -90.5zM1664 1088v-512q0 -24 -16 -42.5t-41 -21.5 l-1044 -122q1 -7 4.5 -21.5t6 -26.5t2.5 -22q0 -16 -24 -64h920q26 0 45 -19t19 -45t-19 -45t-45 -19h-1024q-26 0 -45 19t-19 45q0 14 11 39.5t29.5 59.5t20.5 38l-177 823h-204q-26 0 -45 19t-19 45t19 45t45 19h256q16 0 28.5 -6.5t20 -15.5t13 -24.5t7.5 -26.5 t5.5 -29.5t4.5 -25.5h1201q26 0 45 -19t19 -45z" />
-<glyph unicode="&#xf07b;" horiz-adv-x="1664" d="M1664 928v-704q0 -92 -66 -158t-158 -66h-1216q-92 0 -158 66t-66 158v960q0 92 66 158t158 66h320q92 0 158 -66t66 -158v-32h672q92 0 158 -66t66 -158z" />
-<glyph unicode="&#xf07c;" horiz-adv-x="1920" d="M1879 584q0 -31 -31 -66l-336 -396q-43 -51 -120.5 -86.5t-143.5 -35.5h-1088q-34 0 -60.5 13t-26.5 43q0 31 31 66l336 396q43 51 120.5 86.5t143.5 35.5h1088q34 0 60.5 -13t26.5 -43zM1536 928v-160h-832q-94 0 -197 -47.5t-164 -119.5l-337 -396l-5 -6q0 4 -0.5 12.5 t-0.5 12.5v960q0 92 66 158t158 66h320q92 0 158 -66t66 -158v-32h544q92 0 158 -66t66 -158z" />
-<glyph unicode="&#xf07d;" horiz-adv-x="768" d="M704 1216q0 -26 -19 -45t-45 -19h-128v-1024h128q26 0 45 -19t19 -45t-19 -45l-256 -256q-19 -19 -45 -19t-45 19l-256 256q-19 19 -19 45t19 45t45 19h128v1024h-128q-26 0 -45 19t-19 45t19 45l256 256q19 19 45 19t45 -19l256 -256q19 -19 19 -45z" />
-<glyph unicode="&#xf07e;" horiz-adv-x="1792" d="M1792 640q0 -26 -19 -45l-256 -256q-19 -19 -45 -19t-45 19t-19 45v128h-1024v-128q0 -26 -19 -45t-45 -19t-45 19l-256 256q-19 19 -19 45t19 45l256 256q19 19 45 19t45 -19t19 -45v-128h1024v128q0 26 19 45t45 19t45 -19l256 -256q19 -19 19 -45z" />
-<glyph unicode="&#xf080;" horiz-adv-x="1920" d="M512 512v-384h-256v384h256zM896 1024v-896h-256v896h256zM1280 768v-640h-256v640h256zM1664 1152v-1024h-256v1024h256zM1792 32v1216q0 13 -9.5 22.5t-22.5 9.5h-1600q-13 0 -22.5 -9.5t-9.5 -22.5v-1216q0 -13 9.5 -22.5t22.5 -9.5h1600q13 0 22.5 9.5t9.5 22.5z M1920 1248v-1216q0 -66 -47 -113t-113 -47h-1600q-66 0 -113 47t-47 113v1216q0 66 47 113t113 47h1600q66 0 113 -47t47 -113z" />
-<glyph unicode="&#xf081;" d="M1280 926q-56 -25 -121 -34q68 40 93 117q-65 -38 -134 -51q-61 66 -153 66q-87 0 -148.5 -61.5t-61.5 -148.5q0 -29 5 -48q-129 7 -242 65t-192 155q-29 -50 -29 -106q0 -114 91 -175q-47 1 -100 26v-2q0 -75 50 -133.5t123 -72.5q-29 -8 -51 -8q-13 0 -39 4 q21 -63 74.5 -104t121.5 -42q-116 -90 -261 -90q-26 0 -50 3q148 -94 322 -94q112 0 210 35.5t168 95t120.5 137t75 162t24.5 168.5q0 18 -1 27q63 45 105 109zM1536 1120v-960q0 -119 -84.5 -203.5t-203.5 -84.5h-960q-119 0 -203.5 84.5t-84.5 203.5v960q0 119 84.5 203.5 t203.5 84.5h960q119 0 203.5 -84.5t84.5 -203.5z" />
-<glyph unicode="&#xf082;" d="M1307 618l23 219h-198v109q0 49 15.5 68.5t71.5 19.5h110v219h-175q-152 0 -218 -72t-66 -213v-131h-131v-219h131v-635h262v635h175zM1536 1120v-960q0 -119 -84.5 -203.5t-203.5 -84.5h-960q-119 0 -203.5 84.5t-84.5 203.5v960q0 119 84.5 203.5t203.5 84.5h960 q119 0 203.5 -84.5t84.5 -203.5z" />
-<glyph unicode="&#xf083;" horiz-adv-x="1792" d="M928 704q0 14 -9 23t-23 9q-66 0 -113 -47t-47 -113q0 -14 9 -23t23 -9t23 9t9 23q0 40 28 68t68 28q14 0 23 9t9 23zM1152 574q0 -106 -75 -181t-181 -75t-181 75t-75 181t75 181t181 75t181 -75t75 -181zM128 0h1536v128h-1536v-128zM1280 574q0 159 -112.5 271.5 t-271.5 112.5t-271.5 -112.5t-112.5 -271.5t112.5 -271.5t271.5 -112.5t271.5 112.5t112.5 271.5zM256 1216h384v128h-384v-128zM128 1024h1536v118v138h-828l-64 -128h-644v-128zM1792 1280v-1280q0 -53 -37.5 -90.5t-90.5 -37.5h-1536q-53 0 -90.5 37.5t-37.5 90.5v1280 q0 53 37.5 90.5t90.5 37.5h1536q53 0 90.5 -37.5t37.5 -90.5z" />
-<glyph unicode="&#xf084;" horiz-adv-x="1792" d="M832 1024q0 80 -56 136t-136 56t-136 -56t-56 -136q0 -42 19 -83q-41 19 -83 19q-80 0 -136 -56t-56 -136t56 -136t136 -56t136 56t56 136q0 42 -19 83q41 -19 83 -19q80 0 136 56t56 136zM1683 320q0 -17 -49 -66t-66 -49q-9 0 -28.5 16t-36.5 33t-38.5 40t-24.5 26 l-96 -96l220 -220q28 -28 28 -68q0 -42 -39 -81t-81 -39q-40 0 -68 28l-671 671q-176 -131 -365 -131q-163 0 -265.5 102.5t-102.5 265.5q0 160 95 313t248 248t313 95q163 0 265.5 -102.5t102.5 -265.5q0 -189 -131 -365l355 -355l96 96q-3 3 -26 24.5t-40 38.5t-33 36.5 t-16 28.5q0 17 49 66t66 49q13 0 23 -10q6 -6 46 -44.5t82 -79.5t86.5 -86t73 -78t28.5 -41z" />
-<glyph unicode="&#xf085;" horiz-adv-x="1920" d="M896 640q0 106 -75 181t-181 75t-181 -75t-75 -181t75 -181t181 -75t181 75t75 181zM1664 128q0 52 -38 90t-90 38t-90 -38t-38 -90q0 -53 37.5 -90.5t90.5 -37.5t90.5 37.5t37.5 90.5zM1664 1152q0 52 -38 90t-90 38t-90 -38t-38 -90q0 -53 37.5 -90.5t90.5 -37.5 t90.5 37.5t37.5 90.5zM1280 731v-185q0 -10 -7 -19.5t-16 -10.5l-155 -24q-11 -35 -32 -76q34 -48 90 -115q7 -10 7 -20q0 -12 -7 -19q-23 -30 -82.5 -89.5t-78.5 -59.5q-11 0 -21 7l-115 90q-37 -19 -77 -31q-11 -108 -23 -155q-7 -24 -30 -24h-186q-11 0 -20 7.5t-10 17.5 l-23 153q-34 10 -75 31l-118 -89q-7 -7 -20 -7q-11 0 -21 8q-144 133 -144 160q0 9 7 19q10 14 41 53t47 61q-23 44 -35 82l-152 24q-10 1 -17 9.5t-7 19.5v185q0 10 7 19.5t16 10.5l155 24q11 35 32 76q-34 48 -90 115q-7 11 -7 20q0 12 7 20q22 30 82 89t79 59q11 0 21 -7 l115 -90q34 18 77 32q11 108 23 154q7 24 30 24h186q11 0 20 -7.5t10 -17.5l23 -153q34 -10 75 -31l118 89q8 7 20 7q11 0 21 -8q144 -133 144 -160q0 -9 -7 -19q-12 -16 -42 -54t-45 -60q23 -48 34 -82l152 
 -23q10 -2 17 -10.5t7 -19.5zM1920 198v-140q0 -16 -149 -31 q-12 -27 -30 -52q51 -113 51 -138q0 -4 -4 -7q-122 -71 -124 -71q-8 0 -46 47t-52 68q-20 -2 -30 -2t-30 2q-14 -21 -52 -68t-46 -47q-2 0 -124 71q-4 3 -4 7q0 25 51 138q-18 25 -30 52q-149 15 -149 31v140q0 16 149 31q13 29 30 52q-51 113 -51 138q0 4 4 7q4 2 35 20 t59 34t30 16q8 0 46 -46.5t52 -67.5q20 2 30 2t30 -2q51 71 92 112l6 2q4 0 124 -70q4 -3 4 -7q0 -25 -51 -138q17 -23 30 -52q149 -15 149 -31zM1920 1222v-140q0 -16 -149 -31q-12 -27 -30 -52q51 -113 51 -138q0 -4 -4 -7q-122 -71 -124 -71q-8 0 -46 47t-52 68 q-20 -2 -30 -2t-30 2q-14 -21 -52 -68t-46 -47q-2 0 -124 71q-4 3 -4 7q0 25 51 138q-18 25 -30 52q-149 15 -149 31v140q0 16 149 31q13 29 30 52q-51 113 -51 138q0 4 4 7q4 2 35 20t59 34t30 16q8 0 46 -46.5t52 -67.5q20 2 30 2t30 -2q51 71 92 112l6 2q4 0 124 -70 q4 -3 4 -7q0 -25 -51 -138q17 -23 30 -52q149 -15 149 -31z" />
-<glyph unicode="&#xf086;" horiz-adv-x="1792" d="M1408 768q0 -139 -94 -257t-256.5 -186.5t-353.5 -68.5q-86 0 -176 16q-124 -88 -278 -128q-36 -9 -86 -16h-3q-11 0 -20.5 8t-11.5 21q-1 3 -1 6.5t0.5 6.5t2 6l2.5 5t3.5 5.5t4 5t4.5 5t4 4.5q5 6 23 25t26 29.5t22.5 29t25 38.5t20.5 44q-124 72 -195 177t-71 224 q0 139 94 257t256.5 186.5t353.5 68.5t353.5 -68.5t256.5 -186.5t94 -257zM1792 512q0 -120 -71 -224.5t-195 -176.5q10 -24 20.5 -44t25 -38.5t22.5 -29t26 -29.5t23 -25q1 -1 4 -4.5t4.5 -5t4 -5t3.5 -5.5l2.5 -5t2 -6t0.5 -6.5t-1 -6.5q-3 -14 -13 -22t-22 -7 q-50 7 -86 16q-154 40 -278 128q-90 -16 -176 -16q-271 0 -472 132q58 -4 88 -4q161 0 309 45t264 129q125 92 192 212t67 254q0 77 -23 152q129 -71 204 -178t75 -230z" />
-<glyph unicode="&#xf087;" d="M256 192q0 26 -19 45t-45 19t-45 -19t-19 -45t19 -45t45 -19t45 19t19 45zM1408 768q0 51 -39 89.5t-89 38.5h-352q0 58 48 159.5t48 160.5q0 98 -32 145t-128 47q-26 -26 -38 -85t-30.5 -125.5t-59.5 -109.5q-22 -23 -77 -91q-4 -5 -23 -30t-31.5 -41t-34.5 -42.5 t-40 -44t-38.5 -35.5t-40 -27t-35.5 -9h-32v-640h32q13 0 31.5 -3t33 -6.5t38 -11t35 -11.5t35.5 -12.5t29 -10.5q211 -73 342 -73h121q192 0 192 167q0 26 -5 56q30 16 47.5 52.5t17.5 73.5t-18 69q53 50 53 119q0 25 -10 55.5t-25 47.5q32 1 53.5 47t21.5 81zM1536 769 q0 -89 -49 -163q9 -33 9 -69q0 -77 -38 -144q3 -21 3 -43q0 -101 -60 -178q1 -139 -85 -219.5t-227 -80.5h-36h-93q-96 0 -189.5 22.5t-216.5 65.5q-116 40 -138 40h-288q-53 0 -90.5 37.5t-37.5 90.5v640q0 53 37.5 90.5t90.5 37.5h274q36 24 137 155q58 75 107 128 q24 25 35.5 85.5t30.5 126.5t62 108q39 37 90 37q84 0 151 -32.5t102 -101.5t35 -186q0 -93 -48 -192h176q104 0 180 -76t76 -179z" />
-<glyph unicode="&#xf088;" d="M256 1088q0 26 -19 45t-45 19t-45 -19t-19 -45t19 -45t45 -19t45 19t19 45zM1408 512q0 35 -21.5 81t-53.5 47q15 17 25 47.5t10 55.5q0 69 -53 119q18 32 18 69t-17.5 73.5t-47.5 52.5q5 30 5 56q0 85 -49 126t-136 41h-128q-131 0 -342 -73q-5 -2 -29 -10.5 t-35.5 -12.5t-35 -11.5t-38 -11t-33 -6.5t-31.5 -3h-32v-640h32q16 0 35.5 -9t40 -27t38.5 -35.5t40 -44t34.5 -42.5t31.5 -41t23 -30q55 -68 77 -91q41 -43 59.5 -109.5t30.5 -125.5t38 -85q96 0 128 47t32 145q0 59 -48 160.5t-48 159.5h352q50 0 89 38.5t39 89.5z M1536 511q0 -103 -76 -179t-180 -76h-176q48 -99 48 -192q0 -118 -35 -186q-35 -69 -102 -101.5t-151 -32.5q-51 0 -90 37q-34 33 -54 82t-25.5 90.5t-17.5 84.5t-31 64q-48 50 -107 127q-101 131 -137 155h-274q-53 0 -90.5 37.5t-37.5 90.5v640q0 53 37.5 90.5t90.5 37.5 h288q22 0 138 40q128 44 223 66t200 22h112q140 0 226.5 -79t85.5 -216v-5q60 -77 60 -178q0 -22 -3 -43q38 -67 38 -144q0 -36 -9 -69q49 -74 49 -163z" />
-<glyph unicode="&#xf089;" horiz-adv-x="896" d="M832 1504v-1339l-449 -236q-22 -12 -40 -12q-21 0 -31.5 14.5t-10.5 35.5q0 6 2 20l86 500l-364 354q-25 27 -25 48q0 37 56 46l502 73l225 455q19 41 49 41z" />
-<glyph unicode="&#xf08a;" horiz-adv-x="1792" d="M1664 940q0 81 -21.5 143t-55 98.5t-81.5 59.5t-94 31t-98 8t-112 -25.5t-110.5 -64t-86.5 -72t-60 -61.5q-18 -22 -49 -22t-49 22q-24 28 -60 61.5t-86.5 72t-110.5 64t-112 25.5t-98 -8t-94 -31t-81.5 -59.5t-55 -98.5t-21.5 -143q0 -168 187 -355l581 -560l580 559 q188 188 188 356zM1792 940q0 -221 -229 -450l-623 -600q-18 -18 -44 -18t-44 18l-624 602q-10 8 -27.5 26t-55.5 65.5t-68 97.5t-53.5 121t-23.5 138q0 220 127 344t351 124q62 0 126.5 -21.5t120 -58t95.5 -68.5t76 -68q36 36 76 68t95.5 68.5t120 58t126.5 21.5 q224 0 351 -124t127 -344z" />
-<glyph unicode="&#xf08b;" horiz-adv-x="1664" d="M640 96q0 -4 1 -20t0.5 -26.5t-3 -23.5t-10 -19.5t-20.5 -6.5h-320q-119 0 -203.5 84.5t-84.5 203.5v704q0 119 84.5 203.5t203.5 84.5h320q13 0 22.5 -9.5t9.5 -22.5q0 -4 1 -20t0.5 -26.5t-3 -23.5t-10 -19.5t-20.5 -6.5h-320q-66 0 -113 -47t-47 -113v-704 q0 -66 47 -113t113 -47h288h11h13t11.5 -1t11.5 -3t8 -5.5t7 -9t2 -13.5zM1568 640q0 -26 -19 -45l-544 -544q-19 -19 -45 -19t-45 19t-19 45v288h-448q-26 0 -45 19t-19 45v384q0 26 19 45t45 19h448v288q0 26 19 45t45 19t45 -19l544 -544q19 -19 19 -45z" />
-<glyph unicode="&#xf08c;" d="M237 122h231v694h-231v-694zM483 1030q-1 52 -36 86t-93 34t-94.5 -34t-36.5 -86q0 -51 35.5 -85.5t92.5 -34.5h1q59 0 95 34.5t36 85.5zM1068 122h231v398q0 154 -73 233t-193 79q-136 0 -209 -117h2v101h-231q3 -66 0 -694h231v388q0 38 7 56q15 35 45 59.5t74 24.5 q116 0 116 -157v-371zM1536 1120v-960q0 -119 -84.5 -203.5t-203.5 -84.5h-960q-119 0 -203.5 84.5t-84.5 203.5v960q0 119 84.5 203.5t203.5 84.5h960q119 0 203.5 -84.5t84.5 -203.5z" />
-<glyph unicode="&#xf08d;" horiz-adv-x="1152" d="M480 672v448q0 14 -9 23t-23 9t-23 -9t-9 -23v-448q0 -14 9 -23t23 -9t23 9t9 23zM1152 320q0 -26 -19 -45t-45 -19h-429l-51 -483q-2 -12 -10.5 -20.5t-20.5 -8.5h-1q-27 0 -32 27l-76 485h-404q-26 0 -45 19t-19 45q0 123 78.5 221.5t177.5 98.5v512q-52 0 -90 38 t-38 90t38 90t90 38h640q52 0 90 -38t38 -90t-38 -90t-90 -38v-512q99 0 177.5 -98.5t78.5 -221.5z" />
-<glyph unicode="&#xf08e;" horiz-adv-x="1792" d="M1408 608v-320q0 -119 -84.5 -203.5t-203.5 -84.5h-832q-119 0 -203.5 84.5t-84.5 203.5v832q0 119 84.5 203.5t203.5 84.5h704q14 0 23 -9t9 -23v-64q0 -14 -9 -23t-23 -9h-704q-66 0 -113 -47t-47 -113v-832q0 -66 47 -113t113 -47h832q66 0 113 47t47 113v320 q0 14 9 23t23 9h64q14 0 23 -9t9 -23zM1792 1472v-512q0 -26 -19 -45t-45 -19t-45 19l-176 176l-652 -652q-10 -10 -23 -10t-23 10l-114 114q-10 10 -10 23t10 23l652 652l-176 176q-19 19 -19 45t19 45t45 19h512q26 0 45 -19t19 -45z" />
-<glyph unicode="&#xf090;" d="M1184 640q0 -26 -19 -45l-544 -544q-19 -19 -45 -19t-45 19t-19 45v288h-448q-26 0 -45 19t-19 45v384q0 26 19 45t45 19h448v288q0 26 19 45t45 19t45 -19l544 -544q19 -19 19 -45zM1536 992v-704q0 -119 -84.5 -203.5t-203.5 -84.5h-320q-13 0 -22.5 9.5t-9.5 22.5 q0 4 -1 20t-0.5 26.5t3 23.5t10 19.5t20.5 6.5h320q66 0 113 47t47 113v704q0 66 -47 113t-113 47h-288h-11h-13t-11.5 1t-11.5 3t-8 5.5t-7 9t-2 13.5q0 4 -1 20t-0.5 26.5t3 23.5t10 19.5t20.5 6.5h320q119 0 203.5 -84.5t84.5 -203.5z" />
-<glyph unicode="&#xf091;" horiz-adv-x="1664" d="M458 653q-74 162 -74 371h-256v-96q0 -78 94.5 -162t235.5 -113zM1536 928v96h-256q0 -209 -74 -371q141 29 235.5 113t94.5 162zM1664 1056v-128q0 -71 -41.5 -143t-112 -130t-173 -97.5t-215.5 -44.5q-42 -54 -95 -95q-38 -34 -52.5 -72.5t-14.5 -89.5q0 -54 30.5 -91 t97.5 -37q75 0 133.5 -45.5t58.5 -114.5v-64q0 -14 -9 -23t-23 -9h-832q-14 0 -23 9t-9 23v64q0 69 58.5 114.5t133.5 45.5q67 0 97.5 37t30.5 91q0 51 -14.5 89.5t-52.5 72.5q-53 41 -95 95q-113 5 -215.5 44.5t-173 97.5t-112 130t-41.5 143v128q0 40 28 68t68 28h288v96 q0 66 47 113t113 47h576q66 0 113 -47t47 -113v-96h288q40 0 68 -28t28 -68z" />
-<glyph unicode="&#xf092;" d="M394 184q-8 -9 -20 3q-13 11 -4 19q8 9 20 -3q12 -11 4 -19zM352 245q9 -12 0 -19q-8 -6 -17 7t0 18q9 7 17 -6zM291 305q-5 -7 -13 -2q-10 5 -7 12q3 5 13 2q10 -5 7 -12zM322 271q-6 -7 -16 3q-9 11 -2 16q6 6 16 -3q9 -11 2 -16zM451 159q-4 -12 -19 -6q-17 4 -13 15 t19 7q16 -5 13 -16zM514 154q0 -11 -16 -11q-17 -2 -17 11q0 11 16 11q17 2 17 -11zM572 164q2 -10 -14 -14t-18 8t14 15q16 2 18 -9zM1536 1120v-960q0 -119 -84.5 -203.5t-203.5 -84.5h-224q-16 0 -24.5 1t-19.5 5t-16 14.5t-5 27.5v239q0 97 -52 142q57 6 102.5 18t94 39 t81 66.5t53 105t20.5 150.5q0 121 -79 206q37 91 -8 204q-28 9 -81 -11t-92 -44l-38 -24q-93 26 -192 26t-192 -26q-16 11 -42.5 27t-83.5 38.5t-86 13.5q-44 -113 -7 -204q-79 -85 -79 -206q0 -85 20.5 -150t52.5 -105t80.5 -67t94 -39t102.5 -18q-40 -36 -49 -103 q-21 -10 -45 -15t-57 -5t-65.5 21.5t-55.5 62.5q-19 32 -48.5 52t-49.5 24l-20 3q-21 0 -29 -4.5t-5 -11.5t9 -14t13 -12l7 -5q22 -10 43.5 -38t31.5 -51l10 -23q13 -38 44 -61.5t67 -30t69.5 -7t55.5 3.5l23 4q0 -38 0.5 -103t0.5 
 -68q0 -22 -11 -33.5t-22 -13t-33 -1.5 h-224q-119 0 -203.5 84.5t-84.5 203.5v960q0 119 84.5 203.5t203.5 84.5h960q119 0 203.5 -84.5t84.5 -203.5z" />
-<glyph unicode="&#xf093;" horiz-adv-x="1664" d="M1280 64q0 26 -19 45t-45 19t-45 -19t-19 -45t19 -45t45 -19t45 19t19 45zM1536 64q0 26 -19 45t-45 19t-45 -19t-19 -45t19 -45t45 -19t45 19t19 45zM1664 288v-320q0 -40 -28 -68t-68 -28h-1472q-40 0 -68 28t-28 68v320q0 40 28 68t68 28h427q21 -56 70.5 -92 t110.5 -36h256q61 0 110.5 36t70.5 92h427q40 0 68 -28t28 -68zM1339 936q-17 -40 -59 -40h-256v-448q0 -26 -19 -45t-45 -19h-256q-26 0 -45 19t-19 45v448h-256q-42 0 -59 40q-17 39 14 69l448 448q18 19 45 19t45 -19l448 -448q31 -30 14 -69z" />
-<glyph unicode="&#xf094;" d="M1407 710q0 44 -7 113.5t-18 96.5q-12 30 -17 44t-9 36.5t-4 48.5q0 23 5 68.5t5 67.5q0 37 -10 55q-4 1 -13 1q-19 0 -58 -4.5t-59 -4.5q-60 0 -176 24t-175 24q-43 0 -94.5 -11.5t-85 -23.5t-89.5 -34q-137 -54 -202 -103q-96 -73 -159.5 -189.5t-88 -236t-24.5 -248.5 q0 -40 12.5 -120t12.5 -121q0 -23 -11 -66.5t-11 -65.5t12 -36.5t34 -14.5q24 0 72.5 11t73.5 11q57 0 169.5 -15.5t169.5 -15.5q181 0 284 36q129 45 235.5 152.5t166 245.5t59.5 275zM1535 712q0 -165 -70 -327.5t-196 -288t-281 -180.5q-124 -44 -326 -44 q-57 0 -170 14.5t-169 14.5q-24 0 -72.5 -14.5t-73.5 -14.5q-73 0 -123.5 55.5t-50.5 128.5q0 24 11 68t11 67q0 40 -12.5 120.5t-12.5 121.5q0 111 18 217.5t54.5 209.5t100.5 194t150 156q78 59 232 120q194 78 316 78q60 0 175.5 -24t173.5 -24q19 0 57 5t58 5 q81 0 118 -50.5t37 -134.5q0 -23 -5 -68t-5 -68q0 -10 1 -18.5t3 -17t4 -13.5t6.5 -16t6.5 -17q16 -40 25 -118.5t9 -136.5z" />
-<glyph unicode="&#xf095;" horiz-adv-x="1408" d="M1408 296q0 -27 -10 -70.5t-21 -68.5q-21 -50 -122 -106q-94 -51 -186 -51q-27 0 -52.5 3.5t-57.5 12.5t-47.5 14.5t-55.5 20.5t-49 18q-98 35 -175 83q-128 79 -264.5 215.5t-215.5 264.5q-48 77 -83 175q-3 9 -18 49t-20.5 55.5t-14.5 47.5t-12.5 57.5t-3.5 52.5 q0 92 51 186q56 101 106 122q25 11 68.5 21t70.5 10q14 0 21 -3q18 -6 53 -76q11 -19 30 -54t35 -63.5t31 -53.5q3 -4 17.5 -25t21.5 -35.5t7 -28.5q0 -20 -28.5 -50t-62 -55t-62 -53t-28.5 -46q0 -9 5 -22.5t8.5 -20.5t14 -24t11.5 -19q76 -137 174 -235t235 -174 q2 -1 19 -11.5t24 -14t20.5 -8.5t22.5 -5q18 0 46 28.5t53 62t55 62t50 28.5q14 0 28.5 -7t35.5 -21.5t25 -17.5q25 -15 53.5 -31t63.5 -35t54 -30q70 -35 76 -53q3 -7 3 -21z" />
-<glyph unicode="&#xf096;" horiz-adv-x="1408" d="M1120 1280h-832q-66 0 -113 -47t-47 -113v-832q0 -66 47 -113t113 -47h832q66 0 113 47t47 113v832q0 66 -47 113t-113 47zM1408 1120v-832q0 -119 -84.5 -203.5t-203.5 -84.5h-832q-119 0 -203.5 84.5t-84.5 203.5v832q0 119 84.5 203.5t203.5 84.5h832 q119 0 203.5 -84.5t84.5 -203.5z" />
-<glyph unicode="&#xf097;" horiz-adv-x="1280" d="M1152 1280h-1024v-1242l423 406l89 85l89 -85l423 -406v1242zM1164 1408q23 0 44 -9q33 -13 52.5 -41t19.5 -62v-1289q0 -34 -19.5 -62t-52.5 -41q-19 -8 -44 -8q-48 0 -83 32l-441 424l-441 -424q-36 -33 -83 -33q-23 0 -44 9q-33 13 -52.5 41t-19.5 62v1289 q0 34 19.5 62t52.5 41q21 9 44 9h1048z" />
-<glyph unicode="&#xf098;" d="M1280 343q0 11 -2 16q-3 8 -38.5 29.5t-88.5 49.5l-53 29q-5 3 -19 13t-25 15t-21 5q-18 0 -47 -32.5t-57 -65.5t-44 -33q-7 0 -16.5 3.5t-15.5 6.5t-17 9.5t-14 8.5q-99 55 -170.5 126.5t-126.5 170.5q-2 3 -8.5 14t-9.5 17t-6.5 15.5t-3.5 16.5q0 13 20.5 33.5t45 38.5 t45 39.5t20.5 36.5q0 10 -5 21t-15 25t-13 19q-3 6 -15 28.5t-25 45.5t-26.5 47.5t-25 40.5t-16.5 18t-16 2q-48 0 -101 -22q-46 -21 -80 -94.5t-34 -130.5q0 -16 2.5 -34t5 -30.5t9 -33t10 -29.5t12.5 -33t11 -30q60 -164 216.5 -320.5t320.5 -216.5q6 -2 30 -11t33 -12.5 t29.5 -10t33 -9t30.5 -5t34 -2.5q57 0 130.5 34t94.5 80q22 53 22 101zM1536 1120v-960q0 -119 -84.5 -203.5t-203.5 -84.5h-960q-119 0 -203.5 84.5t-84.5 203.5v960q0 119 84.5 203.5t203.5 84.5h960q119 0 203.5 -84.5t84.5 -203.5z" />
-<glyph unicode="&#xf099;" horiz-adv-x="1664" d="M1620 1128q-67 -98 -162 -167q1 -14 1 -42q0 -130 -38 -259.5t-115.5 -248.5t-184.5 -210.5t-258 -146t-323 -54.5q-271 0 -496 145q35 -4 78 -4q225 0 401 138q-105 2 -188 64.5t-114 159.5q33 -5 61 -5q43 0 85 11q-112 23 -185.5 111.5t-73.5 205.5v4q68 -38 146 -41 q-66 44 -105 115t-39 154q0 88 44 163q121 -149 294.5 -238.5t371.5 -99.5q-8 38 -8 74q0 134 94.5 228.5t228.5 94.5q140 0 236 -102q109 21 205 78q-37 -115 -142 -178q93 10 186 50z" />
-<glyph unicode="&#xf09a;" horiz-adv-x="768" d="M511 980h257l-30 -284h-227v-824h-341v824h-170v284h170v171q0 182 86 275.5t283 93.5h227v-284h-142q-39 0 -62.5 -6.5t-34 -23.5t-13.5 -34.5t-3 -49.5v-142z" />
-<glyph unicode="&#xf09b;" d="M1536 640q0 -251 -146.5 -451.5t-378.5 -277.5q-27 -5 -39.5 7t-12.5 30v211q0 97 -52 142q57 6 102.5 18t94 39t81 66.5t53 105t20.5 150.5q0 121 -79 206q37 91 -8 204q-28 9 -81 -11t-92 -44l-38 -24q-93 26 -192 26t-192 -26q-16 11 -42.5 27t-83.5 38.5t-86 13.5 q-44 -113 -7 -204q-79 -85 -79 -206q0 -85 20.5 -150t52.5 -105t80.5 -67t94 -39t102.5 -18q-40 -36 -49 -103q-21 -10 -45 -15t-57 -5t-65.5 21.5t-55.5 62.5q-19 32 -48.5 52t-49.5 24l-20 3q-21 0 -29 -4.5t-5 -11.5t9 -14t13 -12l7 -5q22 -10 43.5 -38t31.5 -51l10 -23 q13 -38 44 -61.5t67 -30t69.5 -7t55.5 3.5l23 4q0 -38 0.5 -89t0.5 -54q0 -18 -13 -30t-40 -7q-232 77 -378.5 277.5t-146.5 451.5q0 209 103 385.5t279.5 279.5t385.5 103t385.5 -103t279.5 -279.5t103 -385.5z" />
-<glyph unicode="&#xf09c;" horiz-adv-x="1664" d="M1664 960v-256q0 -26 -19 -45t-45 -19h-64q-26 0 -45 19t-19 45v256q0 106 -75 181t-181 75t-181 -75t-75 -181v-192h96q40 0 68 -28t28 -68v-576q0 -40 -28 -68t-68 -28h-960q-40 0 -68 28t-28 68v576q0 40 28 68t68 28h672v192q0 185 131.5 316.5t316.5 131.5 t316.5 -131.5t131.5 -316.5z" />
-<glyph unicode="&#xf09d;" horiz-adv-x="1920" d="M1760 1408q66 0 113 -47t47 -113v-1216q0 -66 -47 -113t-113 -47h-1600q-66 0 -113 47t-47 113v1216q0 66 47 113t113 47h1600zM160 1280q-13 0 -22.5 -9.5t-9.5 -22.5v-224h1664v224q0 13 -9.5 22.5t-22.5 9.5h-1600zM1760 0q13 0 22.5 9.5t9.5 22.5v608h-1664v-608 q0 -13 9.5 -22.5t22.5 -9.5h1600zM256 128v128h256v-128h-256zM640 128v128h384v-128h-384z" />
-<glyph unicode="&#xf09e;" horiz-adv-x="1408" d="M384 192q0 -80 -56 -136t-136 -56t-136 56t-56 136t56 136t136 56t136 -56t56 -136zM896 69q2 -28 -17 -48q-18 -21 -47 -21h-135q-25 0 -43 16.5t-20 41.5q-22 229 -184.5 391.5t-391.5 184.5q-25 2 -41.5 20t-16.5 43v135q0 29 21 47q17 17 43 17h5q160 -13 306 -80.5 t259 -181.5q114 -113 181.5 -259t80.5 -306zM1408 67q2 -27 -18 -47q-18 -20 -46 -20h-143q-26 0 -44.5 17.5t-19.5 42.5q-12 215 -101 408.5t-231.5 336t-336 231.5t-408.5 102q-25 1 -42.5 19.5t-17.5 43.5v143q0 28 20 46q18 18 44 18h3q262 -13 501.5 -120t425.5 -294 q187 -186 294 -425.5t120 -501.5z" />
-<glyph unicode="&#xf0a0;" d="M1040 320q0 -33 -23.5 -56.5t-56.5 -23.5t-56.5 23.5t-23.5 56.5t23.5 56.5t56.5 23.5t56.5 -23.5t23.5 -56.5zM1296 320q0 -33 -23.5 -56.5t-56.5 -23.5t-56.5 23.5t-23.5 56.5t23.5 56.5t56.5 23.5t56.5 -23.5t23.5 -56.5zM1408 160v320q0 13 -9.5 22.5t-22.5 9.5 h-1216q-13 0 -22.5 -9.5t-9.5 -22.5v-320q0 -13 9.5 -22.5t22.5 -9.5h1216q13 0 22.5 9.5t9.5 22.5zM178 640h1180l-157 482q-4 13 -16 21.5t-26 8.5h-782q-14 0 -26 -8.5t-16 -21.5zM1536 480v-320q0 -66 -47 -113t-113 -47h-1216q-66 0 -113 47t-47 113v320q0 25 16 75 l197 606q17 53 63 86t101 33h782q55 0 101 -33t63 -86l197 -606q16 -50 16 -75z" />
-<glyph unicode="&#xf0a1;" horiz-adv-x="1792" d="M1664 896q53 0 90.5 -37.5t37.5 -90.5t-37.5 -90.5t-90.5 -37.5v-384q0 -52 -38 -90t-90 -38q-417 347 -812 380q-58 -19 -91 -66t-31 -100.5t40 -92.5q-20 -33 -23 -65.5t6 -58t33.5 -55t48 -50t61.5 -50.5q-29 -58 -111.5 -83t-168.5 -11.5t-132 55.5q-7 23 -29.5 87.5 t-32 94.5t-23 89t-15 101t3.5 98.5t22 110.5h-122q-66 0 -113 47t-47 113v192q0 66 47 113t113 47h480q435 0 896 384q52 0 90 -38t38 -90v-384zM1536 292v954q-394 -302 -768 -343v-270q377 -42 768 -341z" />
-<glyph unicode="&#xf0a2;" horiz-adv-x="1664" d="M848 -160q0 16 -16 16q-59 0 -101.5 42.5t-42.5 101.5q0 16 -16 16t-16 -16q0 -73 51.5 -124.5t124.5 -51.5q16 0 16 16zM183 128h1298q-164 181 -246.5 411.5t-82.5 484.5q0 256 -320 256t-320 -256q0 -254 -82.5 -484.5t-246.5 -411.5zM1664 128q0 -52 -38 -90t-90 -38 h-448q0 -106 -75 -181t-181 -75t-181 75t-75 181h-448q-52 0 -90 38t-38 90q190 161 287 397.5t97 498.5q0 165 96 262t264 117q-8 18 -8 37q0 40 28 68t68 28t68 -28t28 -68q0 -19 -8 -37q168 -20 264 -117t96 -262q0 -262 97 -498.5t287 -397.5z" />
-<glyph unicode="&#xf0a3;" d="M1376 640l138 -135q30 -28 20 -70q-12 -41 -52 -51l-188 -48l53 -186q12 -41 -19 -70q-29 -31 -70 -19l-186 53l-48 -188q-10 -40 -51 -52q-12 -2 -19 -2q-31 0 -51 22l-135 138l-135 -138q-28 -30 -70 -20q-41 11 -51 52l-48 188l-186 -53q-41 -12 -70 19q-31 29 -19 70 l53 186l-188 48q-40 10 -52 51q-10 42 20 70l138 135l-138 135q-30 28 -20 70q12 41 52 51l188 48l-53 186q-12 41 19 70q29 31 70 19l186 -53l48 188q10 41 51 51q41 12 70 -19l135 -139l135 139q29 30 70 19q41 -10 51 -51l48 -188l186 53q41 12 70 -19q31 -29 19 -70 l-53 -186l188 -48q40 -10 52 -51q10 -42 -20 -70z" />
-<glyph unicode="&#xf0a4;" horiz-adv-x="1792" d="M256 192q0 26 -19 45t-45 19t-45 -19t-19 -45t19 -45t45 -19t45 19t19 45zM1664 768q0 51 -39 89.5t-89 38.5h-576q0 20 15 48.5t33 55t33 68t15 84.5q0 67 -44.5 97.5t-115.5 30.5q-24 0 -90 -139q-24 -44 -37 -65q-40 -64 -112 -145q-71 -81 -101 -106 q-69 -57 -140 -57h-32v-640h32q72 0 167 -32t193.5 -64t179.5 -32q189 0 189 167q0 26 -5 56q30 16 47.5 52.5t17.5 73.5t-18 69q53 50 53 119q0 25 -10 55.5t-25 47.5h331q52 0 90 38t38 90zM1792 769q0 -105 -75.5 -181t-180.5 -76h-169q-4 -62 -37 -119q3 -21 3 -43 q0 -101 -60 -178q1 -139 -85 -219.5t-227 -80.5q-133 0 -322 69q-164 59 -223 59h-288q-53 0 -90.5 37.5t-37.5 90.5v640q0 53 37.5 90.5t90.5 37.5h288q10 0 21.5 4.5t23.5 14t22.5 18t24 22.5t20.5 21.5t19 21.5t14 17q65 74 100 129q13 21 33 62t37 72t40.5 63t55 49.5 t69.5 17.5q125 0 206.5 -67t81.5 -189q0 -68 -22 -128h374q104 0 180 -76t76 -179z" />
-<glyph unicode="&#xf0a5;" horiz-adv-x="1792" d="M1376 128h32v640h-32q-35 0 -67.5 12t-62.5 37t-50 46t-49 54q-2 3 -3.5 4.5t-4 4.5t-4.5 5q-72 81 -112 145q-14 22 -38 68q-1 3 -10.5 22.5t-18.5 36t-20 35.5t-21.5 30.5t-18.5 11.5q-71 0 -115.5 -30.5t-44.5 -97.5q0 -43 15 -84.5t33 -68t33 -55t15 -48.5h-576 q-50 0 -89 -38.5t-39 -89.5q0 -52 38 -90t90 -38h331q-15 -17 -25 -47.5t-10 -55.5q0 -69 53 -119q-18 -32 -18 -69t17.5 -73.5t47.5 -52.5q-4 -24 -4 -56q0 -85 48.5 -126t135.5 -41q84 0 183 32t194 64t167 32zM1664 192q0 26 -19 45t-45 19t-45 -19t-19 -45t19 -45 t45 -19t45 19t19 45zM1792 768v-640q0 -53 -37.5 -90.5t-90.5 -37.5h-288q-59 0 -223 -59q-190 -69 -317 -69q-142 0 -230 77.5t-87 217.5l1 5q-61 76 -61 178q0 22 3 43q-33 57 -37 119h-169q-105 0 -180.5 76t-75.5 181q0 103 76 179t180 76h374q-22 60 -22 128 q0 122 81.5 189t206.5 67q38 0 69.5 -17.5t55 -49.5t40.5 -63t37 -72t33 -62q35 -55 100 -129q2 -3 14 -17t19 -21.5t20.5 -21.5t24 -22.5t22.5 -18t23.5 -14t21.5 -4.5h288q53 0 90.5 -37.5t37.5 -90.5z" />
-<glyph unicode="&#xf0a6;" d="M1280 -64q0 26 -19 45t-45 19t-45 -19t-19 -45t19 -45t45 -19t45 19t19 45zM1408 700q0 189 -167 189q-26 0 -56 -5q-16 30 -52.5 47.5t-73.5 17.5t-69 -18q-50 53 -119 53q-25 0 -55.5 -10t-47.5 -25v331q0 52 -38 90t-90 38q-51 0 -89.5 -39t-38.5 -89v-576 q-20 0 -48.5 15t-55 33t-68 33t-84.5 15q-67 0 -97.5 -44.5t-30.5 -115.5q0 -24 139 -90q44 -24 65 -37q64 -40 145 -112q81 -71 106 -101q57 -69 57 -140v-32h640v32q0 72 32 167t64 193.5t32 179.5zM1536 705q0 -133 -69 -322q-59 -164 -59 -223v-288q0 -53 -37.5 -90.5 t-90.5 -37.5h-640q-53 0 -90.5 37.5t-37.5 90.5v288q0 10 -4.5 21.5t-14 23.5t-18 22.5t-22.5 24t-21.5 20.5t-21.5 19t-17 14q-74 65 -129 100q-21 13 -62 33t-72 37t-63 40.5t-49.5 55t-17.5 69.5q0 125 67 206.5t189 81.5q68 0 128 -22v374q0 104 76 180t179 76 q105 0 181 -75.5t76 -180.5v-169q62 -4 119 -37q21 3 43 3q101 0 178 -60q139 1 219.5 -85t80.5 -227z" />
-<glyph unicode="&#xf0a7;" d="M1408 576q0 84 -32 183t-64 194t-32 167v32h-640v-32q0 -35 -12 -67.5t-37 -62.5t-46 -50t-54 -49q-9 -8 -14 -12q-81 -72 -145 -112q-22 -14 -68 -38q-3 -1 -22.5 -10.5t-36 -18.5t-35.5 -20t-30.5 -21.5t-11.5 -18.5q0 -71 30.5 -115.5t97.5 -44.5q43 0 84.5 15t68 33 t55 33t48.5 15v-576q0 -50 38.5 -89t89.5 -39q52 0 90 38t38 90v331q46 -35 103 -35q69 0 119 53q32 -18 69 -18t73.5 17.5t52.5 47.5q24 -4 56 -4q85 0 126 48.5t41 135.5zM1280 1344q0 26 -19 45t-45 19t-45 -19t-19 -45t19 -45t45 -19t45 19t19 45zM1536 580 q0 -142 -77.5 -230t-217.5 -87l-5 1q-76 -61 -178 -61q-22 0 -43 3q-54 -30 -119 -37v-169q0 -105 -76 -180.5t-181 -75.5q-103 0 -179 76t-76 180v374q-54 -22 -128 -22q-121 0 -188.5 81.5t-67.5 206.5q0 38 17.5 69.5t49.5 55t63 40.5t72 37t62 33q55 35 129 100 q3 2 17 14t21.5 19t21.5 20.5t22.5 24t18 22.5t14 23.5t4.5 21.5v288q0 53 37.5 90.5t90.5 37.5h640q53 0 90.5 -37.5t37.5 -90.5v-288q0 -59 59 -223q69 -190 69 -317z" />
-<glyph unicode="&#xf0a8;" d="M1280 576v128q0 26 -19 45t-45 19h-502l189 189q19 19 19 45t-19 45l-91 91q-18 18 -45 18t-45 -18l-362 -362l-91 -91q-18 -18 -18 -45t18 -45l91 -91l362 -362q18 -18 45 -18t45 18l91 91q18 18 18 45t-18 45l-189 189h502q26 0 45 19t19 45zM1536 640 q0 -209 -103 -385.5t-279.5 -279.5t-385.5 -103t-385.5 103t-279.5 279.5t-103 385.5t103 385.5t279.5 279.5t385.5 103t385.5 -103t279.5 -279.5t103 -385.5z" />
-<glyph unicode="&#xf0a9;" d="M1285 640q0 27 -18 45l-91 91l-362 362q-18 18 -45 18t-45 -18l-91 -91q-18 -18 -18 -45t18 -45l189 -189h-502q-26 0 -45 -19t-19 -45v-128q0 -26 19 -45t45 -19h502l-189 -189q-19 -19 -19 -45t19 -45l91 -91q18 -18 45 -18t45 18l362 362l91 91q18 18 18 45zM1536 640 q0 -209 -103 -385.5t-279.5 -279.5t-385.5 -103t-385.5 103t-279.5 279.5t-103 385.5t103 385.5t279.5 279.5t385.5 103t385.5 -103t279.5 -279.5t103 -385.5z" />
-<glyph unicode="&#xf0aa;" d="M1284 641q0 27 -18 45l-362 362l-91 91q-18 18 -45 18t-45 -18l-91 -91l-362 -362q-18 -18 -18 -45t18 -45l91 -91q18 -18 45 -18t45 18l189 189v-502q0 -26 19 -45t45 -19h128q26 0 45 19t19 45v502l189 -189q19 -19 45 -19t45 19l91 91q18 18 18 45zM1536 640 q0 -209 -103 -385.5t-279.5 -279.5t-385.5 -103t-385.5 103t-279.5 279.5t-103 385.5t103 385.5t279.5 279.5t385.5 103t385.5 -103t279.5 -279.5t103 -385.5z" />
-<glyph unicode="&#xf0ab;" d="M1284 639q0 27 -18 45l-91 91q-18 18 -45 18t-45 -18l-189 -189v502q0 26 -19 45t-45 19h-128q-26 0 -45 -19t-19 -45v-502l-189 189q-19 19 -45 19t-45 -19l-91 -91q-18 -18 -18 -45t18 -45l362 -362l91 -91q18 -18 45 -18t45 18l91 91l362 362q18 18 18 45zM1536 640 q0 -209 -103 -385.5t-279.5 -279.5t-385.5 -103t-385.5 103t-279.5 279.5t-103 385.5t103 385.5t279.5 279.5t385.5 103t385.5 -103t279.5 -279.5t103 -385.5z" />
-<glyph unicode="&#xf0ac;" d="M768 1408q209 0 385.5 -103t279.5 -279.5t103 -385.5t-103 -385.5t-279.5 -279.5t-385.5 -103t-385.5 103t-279.5 279.5t-103 385.5t103 385.5t279.5 279.5t385.5 103zM1042 887q-2 -1 -9.5 -9.5t-13.5 -9.5q2 0 4.5 5t5 11t3.5 7q6 7 22 15q14 6 52 12q34 8 51 -11 q-2 2 9.5 13t14.5 12q3 2 15 4.5t15 7.5l2 22q-12 -1 -17.5 7t-6.5 21q0 -2 -6 -8q0 7 -4.5 8t-11.5 -1t-9 -1q-10 3 -15 7.5t-8 16.5t-4 15q-2 5 -9.5 10.5t-9.5 10.5q-1 2 -2.5 5.5t-3 6.5t-4 5.5t-5.5 2.5t-7 -5t-7.5 -10t-4.5 -5q-3 2 -6 1.5t-4.5 -1t-4.5 -3t-5 -3.5 q-3 -2 -8.5 -3t-8.5 -2q15 5 -1 11q-10 4 -16 3q9 4 7.5 12t-8.5 14h5q-1 4 -8.5 8.5t-17.5 8.5t-13 6q-8 5 -34 9.5t-33 0.5q-5 -6 -4.5 -10.5t4 -14t3.5 -12.5q1 -6 -5.5 -13t-6.5 -12q0 -7 14 -15.5t10 -21.5q-3 -8 -16 -16t-16 -12q-5 -8 -1.5 -18.5t10.5 -16.5 q2 -2 1.5 -4t-3.5 -4.5t-5.5 -4t-6.5 -3.5l-3 -2q-11 -5 -20.5 6t-13.5 26q-7 25 -16 30q-23 8 -29 -1q-5 13 -41 26q-25 9 -58 4q6 1 0 15q-7 15 -19 12q3 6 4 17.5t1 13.5q3 13 12 23q1 1 7 8.5t9.5 13.5t0.5 6q35 -4 50 11q5 5 11.5 17
 t10.5 17q9 6 14 5.5t14.5 -5.5 t14.5 -5q14 -1 15.5 11t-7.5 20q12 -1 3 17q-5 7 -8 9q-12 4 -27 -5q-8 -4 2 -8q-1 1 -9.5 -10.5t-16.5 -17.5t-16 5q-1 1 -5.5 13.5t-9.5 13.5q-8 0 -16 -15q3 8 -11 15t-24 8q19 12 -8 27q-7 4 -20.5 5t-19.5 -4q-5 -7 -5.5 -11.5t5 -8t10.5 -5.5t11.5 -4t8.5 -3 q14 -10 8 -14q-2 -1 -8.5 -3.5t-11.5 -4.5t-6 -4q-3 -4 0 -14t-2 -14q-5 5 -9 17.5t-7 16.5q7 -9 -25 -6l-10 1q-4 0 -16 -2t-20.5 -1t-13.5 8q-4 8 0 20q1 4 4 2q-4 3 -11 9.5t-10 8.5q-46 -15 -94 -41q6 -1 12 1q5 2 13 6.5t10 5.5q34 14 42 7l5 5q14 -16 20 -25 q-7 4 -30 1q-20 -6 -22 -12q7 -12 5 -18q-4 3 -11.5 10t-14.5 11t-15 5q-16 0 -22 -1q-146 -80 -235 -222q7 -7 12 -8q4 -1 5 -9t2.5 -11t11.5 3q9 -8 3 -19q1 1 44 -27q19 -17 21 -21q3 -11 -10 -18q-1 2 -9 9t-9 4q-3 -5 0.5 -18.5t10.5 -12.5q-7 0 -9.5 -16t-2.5 -35.5 t-1 -23.5l2 -1q-3 -12 5.5 -34.5t21.5 -19.5q-13 -3 20 -43q6 -8 8 -9q3 -2 12 -7.5t15 -10t10 -10.5q4 -5 10 -22.5t14 -23.5q-2 -6 9.5 -20t10.5 -23q-1 0 -2.5 -1t-2.5 -1q3 -7 15.5 -14t15.5 -13q1 -3 2 -10t3 -11t8 -2q2 20 -24 62q-1
 5 25 -17 29q-3 5 -5.5 15.5 t-4.5 14.5q2 0 6 -1.5t8.5 -3.5t7.5 -4t2 -3q-3 -7 2 -17.5t12 -18.5t17 -19t12 -13q6 -6 14 -19.5t0 -13.5q9 0 20 -10t17 -20q5 -8 8 -26t5 -24q2 -7 8.5 -13.5t12.5 -9.5l16 -8t13 -7q5 -2 18.5 -10.5t21.5 -11.5q10 -4 16 -4t14.5 2.5t13.5 3.5q15 2 29 -15t21 -21 q36 -19 55 -11q-2 -1 0.5 -7.5t8 -15.5t9 -14.5t5.5 -8.5q5 -6 18 -15t18 -15q6 4 7 9q-3 -8 7 -20t18 -10q14 3 14 32q-31 -15 -49 18q0 1 -2.5 5.5t-4 8.5t-2.5 8.5t0 7.5t5 3q9 0 10 3.5t-2 12.5t-4 13q-1 8 -11 20t-12 15q-5 -9 -16 -8t-16 9q0 -1 -1.5 -5.5t-1.5 -6.5 q-13 0 -15 1q1 3 2.5 17.5t3.5 22.5q1 4 5.5 12t7.5 14.5t4 12.5t-4.5 9.5t-17.5 2.5q-19 -1 -26 -20q-1 -3 -3 -10.5t-5 -11.5t-9 -7q-7 -3 -24 -2t-24 5q-13 8 -22.5 29t-9.5 37q0 10 2.5 26.5t3 25t-5.5 24.5q3 2 9 9.5t10 10.5q2 1 4.5 1.5t4.5 0t4 1.5t3 6q-1 1 -4 3 q-3 3 -4 3q7 -3 28.5 1.5t27.5 -1.5q15 -11 22 2q0 1 -2.5 9.5t-0.5 13.5q5 -27 29 -9q3 -3 15.5 -5t17.5 -5q3 -2 7 -5.5t5.5 -4.5t5 0.5t8.5 6.5q10 -14 12 -24q11 -40 19 -44q7 -3 11 -2t4.5 9.5t0 14t-1.5 12.5l-1 8v18l-1 8q
 -15 3 -18.5 12t1.5 18.5t15 18.5q1 1 8 3.5 t15.5 6.5t12.5 8q21 19 15 35q7 0 11 9q-1 0 -5 3t-7.5 5t-4.5 2q9 5 2 16q5 3 7.5 11t7.5 10q9 -12 21 -2q7 8 1 16q5 7 20.5 10.5t18.5 9.5q7 -2 8 2t1 12t3 12q4 5 15 9t13 5l17 11q3 4 0 4q18 -2 31 11q10 11 -6 20q3 6 -3 9.5t-15 5.5q3 1 11.5 0.5t10.5 1.5 q15 10 -7 16q-17 5 -43 -12zM879 10q206 36 351 189q-3 3 -12.5 4.5t-12.5 3.5q-18 7 -24 8q1 7 -2.5 13t-8 9t-12.5 8t-11 7q-2 2 -7 6t-7 5.5t-7.5 4.5t-8.5 2t-10 -1l-3 -1q-3 -1 -5.5 -2.5t-5.5 -3t-4 -3t0 -2.5q-21 17 -36 22q-5 1 -11 5.5t-10.5 7t-10 1.5t-11.5 -7 q-5 -5 -6 -15t-2 -13q-7 5 0 17.5t2 18.5q-3 6 -10.5 4.5t-12 -4.5t-11.5 -8.5t-9 -6.5t-8.5 -5.5t-8.5 -7.5q-3 -4 -6 -12t-5 -11q-2 4 -11.5 6.5t-9.5 5.5q2 -10 4 -35t5 -38q7 -31 -12 -48q-27 -25 -29 -40q-4 -22 12 -26q0 -7 -8 -20.5t-7 -21.5q0 -6 2 -16z" />
-<glyph unicode="&#xf0ad;" horiz-adv-x="1664" d="M384 64q0 26 -19 45t-45 1

<TRUNCATED>
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/img/fontawesome-webfont.ttf
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/img/fontawesome-webfont.ttf b/apps/fauxton/assets/img/fontawesome-webfont.ttf
deleted file mode 100755
index d365924..0000000
Binary files a/apps/fauxton/assets/img/fontawesome-webfont.ttf and /dev/null differ


[17/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/js/libs/bootstrap.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/js/libs/bootstrap.js b/apps/fauxton/assets/js/libs/bootstrap.js
deleted file mode 100644
index 96fed13..0000000
--- a/apps/fauxton/assets/js/libs/bootstrap.js
+++ /dev/null
@@ -1,2291 +0,0 @@
-/* ===================================================
- * bootstrap-transition.js v2.3.2
- * http://twitter.github.com/bootstrap/javascript.html#transitions
- * ===================================================
- * Copyright 2012 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ========================================================== */
-
-
-!function ($) {
-
-  "use strict"; // jshint ;_;
-
-
-  /* CSS TRANSITION SUPPORT (http://www.modernizr.com/)
-   * ======================================================= */
-
-  $(function () {
-
-    $.support.transition = (function () {
-
-      var transitionEnd = (function () {
-
-        var el = document.createElement('bootstrap')
-          , transEndEventNames = {
-               'WebkitTransition' : 'webkitTransitionEnd'
-            ,  'MozTransition'    : 'transitionend'
-            ,  'OTransition'      : 'oTransitionEnd otransitionend'
-            ,  'transition'       : 'transitionend'
-            }
-          , name
-
-        for (name in transEndEventNames){
-          if (el.style[name] !== undefined) {
-            return transEndEventNames[name]
-          }
-        }
-
-      }())
-
-      return transitionEnd && {
-        end: transitionEnd
-      }
-
-    })()
-
-  })
-
-}(window.jQuery);
-/* =========================================================
- * bootstrap-modal.js v2.3.2
- * http://twitter.github.com/bootstrap/javascript.html#modals
- * =========================================================
- * Copyright 2012 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ========================================================= */
-
-
-!function ($) {
-
-  "use strict"; // jshint ;_;
-
-
- /* MODAL CLASS DEFINITION
-  * ====================== */
-
-  var Modal = function (element, options) {
-    this.options = options
-    this.$element = $(element)
-      .delegate('[data-dismiss="modal"]', 'click.dismiss.modal', $.proxy(this.hide, this))
-    this.options.remote && this.$element.find('.modal-body').load(this.options.remote)
-  }
-
-  Modal.prototype = {
-
-      constructor: Modal
-
-    , toggle: function () {
-        return this[!this.isShown ? 'show' : 'hide']()
-      }
-
-    , show: function () {
-        var that = this
-          , e = $.Event('show')
-
-        this.$element.trigger(e)
-
-        if (this.isShown || e.isDefaultPrevented()) return
-
-        this.isShown = true
-
-        this.escape()
-
-        this.backdrop(function () {
-          var transition = $.support.transition && that.$element.hasClass('fade')
-
-          if (!that.$element.parent().length) {
-            that.$element.appendTo(document.body) //don't move modals dom position
-          }
-
-          that.$element.show()
-
-          if (transition) {
-            that.$element[0].offsetWidth // force reflow
-          }
-
-          that.$element
-            .addClass('in')
-            .attr('aria-hidden', false)
-
-          that.enforceFocus()
-
-          transition ?
-            that.$element.one($.support.transition.end, function () { that.$element.focus().trigger('shown') }) :
-            that.$element.focus().trigger('shown')
-
-        })
-      }
-
-    , hide: function (e) {
-        e && e.preventDefault()
-
-        var that = this
-
-        e = $.Event('hide')
-
-        this.$element.trigger(e)
-
-        if (!this.isShown || e.isDefaultPrevented()) return
-
-        this.isShown = false
-
-        this.escape()
-
-        $(document).off('focusin.modal')
-
-        this.$element
-          .removeClass('in')
-          .attr('aria-hidden', true)
-
-        $.support.transition && this.$element.hasClass('fade') ?
-          this.hideWithTransition() :
-          this.hideModal()
-      }
-
-    , enforceFocus: function () {
-        var that = this
-        $(document).on('focusin.modal', function (e) {
-          if (that.$element[0] !== e.target && !that.$element.has(e.target).length) {
-            that.$element.focus()
-          }
-        })
-      }
-
-    , escape: function () {
-        var that = this
-        if (this.isShown && this.options.keyboard) {
-          this.$element.on('keyup.dismiss.modal', function ( e ) {
-            e.which == 27 && that.hide()
-          })
-        } else if (!this.isShown) {
-          this.$element.off('keyup.dismiss.modal')
-        }
-      }
-
-    , hideWithTransition: function () {
-        var that = this
-          , timeout = setTimeout(function () {
-              that.$element.off($.support.transition.end)
-              that.hideModal()
-            }, 500)
-
-        this.$element.one($.support.transition.end, function () {
-          clearTimeout(timeout)
-          that.hideModal()
-        })
-      }
-
-    , hideModal: function () {
-        var that = this
-        this.$element.hide()
-        this.backdrop(function () {
-          that.removeBackdrop()
-          that.$element.trigger('hidden')
-        })
-      }
-
-    , removeBackdrop: function () {
-        this.$backdrop && this.$backdrop.remove()
-        this.$backdrop = null
-      }
-
-    , backdrop: function (callback) {
-        var that = this
-          , animate = this.$element.hasClass('fade') ? 'fade' : ''
-
-        if (this.isShown && this.options.backdrop) {
-          var doAnimate = $.support.transition && animate
-
-          this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />')
-            .appendTo(document.body)
-
-          this.$backdrop.click(
-            this.options.backdrop == 'static' ?
-              $.proxy(this.$element[0].focus, this.$element[0])
-            : $.proxy(this.hide, this)
-          )
-
-          if (doAnimate) this.$backdrop[0].offsetWidth // force reflow
-
-          this.$backdrop.addClass('in')
-
-          if (!callback) return
-
-          doAnimate ?
-            this.$backdrop.one($.support.transition.end, callback) :
-            callback()
-
-        } else if (!this.isShown && this.$backdrop) {
-          this.$backdrop.removeClass('in')
-
-          $.support.transition && this.$element.hasClass('fade')?
-            this.$backdrop.one($.support.transition.end, callback) :
-            callback()
-
-        } else if (callback) {
-          callback()
-        }
-      }
-  }
-
-
- /* MODAL PLUGIN DEFINITION
-  * ======================= */
-
-  var old = $.fn.modal
-
-  $.fn.modal = function (option) {
-    return this.each(function () {
-      var $this = $(this)
-        , data = $this.data('modal')
-        , options = $.extend({}, $.fn.modal.defaults, $this.data(), typeof option == 'object' && option)
-      if (!data) $this.data('modal', (data = new Modal(this, options)))
-      if (typeof option == 'string') data[option]()
-      else if (options.show) data.show()
-    })
-  }
-
-  $.fn.modal.defaults = {
-      backdrop: true
-    , keyboard: true
-    , show: true
-  }
-
-  $.fn.modal.Constructor = Modal
-
-
- /* MODAL NO CONFLICT
-  * ================= */
-
-  $.fn.modal.noConflict = function () {
-    $.fn.modal = old
-    return this
-  }
-
-
- /* MODAL DATA-API
-  * ============== */
-
-  $(document).on('click.modal.data-api', '[data-toggle="modal"]', function (e) {
-    var $this = $(this)
-      , href = $this.attr('href')
-      , $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7
-      , option = $target.data('modal') ? 'toggle' : $.extend({ remote:!/#/.test(href) && href }, $target.data(), $this.data())
-
-    e.preventDefault()
-
-    $target
-      .modal(option)
-      .one('hide', function () {
-        $this.focus()
-      })
-  })
-
-}(window.jQuery);
-
-/* ============================================================
- * bootstrap-dropdown.js v2.3.2
- * http://twitter.github.com/bootstrap/javascript.html#dropdowns
- * ============================================================
- * Copyright 2012 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============================================================ */
-
-
-!function ($) {
-
-  "use strict"; // jshint ;_;
-
-
- /* DROPDOWN CLASS DEFINITION
-  * ========================= */
-
-  var toggle = '[data-toggle=dropdown]'
-    , Dropdown = function (element) {
-        var $el = $(element).on('click.dropdown.data-api', this.toggle)
-        $('html').on('click.dropdown.data-api', function () {
-          $el.parent().removeClass('open')
-        })
-      }
-
-  Dropdown.prototype = {
-
-    constructor: Dropdown
-
-  , toggle: function (e) {
-      var $this = $(this)
-        , $parent
-        , isActive
-
-      if ($this.is('.disabled, :disabled')) return
-
-      $parent = getParent($this)
-
-      isActive = $parent.hasClass('open')
-
-      clearMenus()
-
-      if (!isActive) {
-        if ('ontouchstart' in document.documentElement) {
-          // if mobile we we use a backdrop because click events don't delegate
-          $('<div class="dropdown-backdrop"/>').insertBefore($(this)).on('click', clearMenus)
-        }
-        $parent.toggleClass('open')
-      }
-
-      $this.focus()
-
-      return false
-    }
-
-  , keydown: function (e) {
-      var $this
-        , $items
-        , $active
-        , $parent
-        , isActive
-        , index
-
-      if (!/(38|40|27)/.test(e.keyCode)) return
-
-      $this = $(this)
-
-      e.preventDefault()
-      e.stopPropagation()
-
-      if ($this.is('.disabled, :disabled')) return
-
-      $parent = getParent($this)
-
-      isActive = $parent.hasClass('open')
-
-      if (!isActive || (isActive && e.keyCode == 27)) {
-        if (e.which == 27) $parent.find(toggle).focus()
-        return $this.click()
-      }
-
-      $items = $('[role=menu] li:not(.divider):visible a', $parent)
-
-      if (!$items.length) return
-
-      index = $items.index($items.filter(':focus'))
-
-      if (e.keyCode == 38 && index > 0) index--                                        // up
-      if (e.keyCode == 40 && index < $items.length - 1) index++                        // down
-      if (!~index) index = 0
-
-      $items
-        .eq(index)
-        .focus()
-    }
-
-  }
-
-  function clearMenus() {
-    $('.dropdown-backdrop').remove()
-    $(toggle).each(function () {
-      getParent($(this)).removeClass('open')
-    })
-  }
-
-  function getParent($this) {
-    var selector = $this.attr('data-target')
-      , $parent
-
-    if (!selector) {
-      selector = $this.attr('href')
-      selector = selector && /#/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
-    }
-
-    $parent = selector && $(selector)
-
-    if (!$parent || !$parent.length) $parent = $this.parent()
-
-    return $parent
-  }
-
-
-  /* DROPDOWN PLUGIN DEFINITION
-   * ========================== */
-
-  var old = $.fn.dropdown
-
-  $.fn.dropdown = function (option) {
-    return this.each(function () {
-      var $this = $(this)
-        , data = $this.data('dropdown')
-      if (!data) $this.data('dropdown', (data = new Dropdown(this)))
-      if (typeof option == 'string') data[option].call($this)
-    })
-  }
-
-  $.fn.dropdown.Constructor = Dropdown
-
-
- /* DROPDOWN NO CONFLICT
-  * ==================== */
-
-  $.fn.dropdown.noConflict = function () {
-    $.fn.dropdown = old
-    return this
-  }
-
-
-  /* APPLY TO STANDARD DROPDOWN ELEMENTS
-   * =================================== */
-
-  $(document)
-    .on('click.dropdown.data-api', clearMenus)
-    .on('click.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })
-    .on('click.dropdown.data-api'  , toggle, Dropdown.prototype.toggle)
-    .on('keydown.dropdown.data-api', toggle + ', [role=menu]' , Dropdown.prototype.keydown)
-
-}(window.jQuery);
-
-/* =============================================================
- * bootstrap-scrollspy.js v2.3.2
- * http://twitter.github.com/bootstrap/javascript.html#scrollspy
- * =============================================================
- * Copyright 2012 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============================================================== */
-
-
-!function ($) {
-
-  "use strict"; // jshint ;_;
-
-
- /* SCROLLSPY CLASS DEFINITION
-  * ========================== */
-
-  function ScrollSpy(element, options) {
-    var process = $.proxy(this.process, this)
-      , $element = $(element).is('body') ? $(window) : $(element)
-      , href
-    this.options = $.extend({}, $.fn.scrollspy.defaults, options)
-    this.$scrollElement = $element.on('scroll.scroll-spy.data-api', process)
-    this.selector = (this.options.target
-      || ((href = $(element).attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7
-      || '') + ' .nav li > a'
-    this.$body = $('body')
-    this.refresh()
-    this.process()
-  }
-
-  ScrollSpy.prototype = {
-
-      constructor: ScrollSpy
-
-    , refresh: function () {
-        var self = this
-          , $targets
-
-        this.offsets = $([])
-        this.targets = $([])
-
-        $targets = this.$body
-          .find(this.selector)
-          .map(function () {
-            var $el = $(this)
-              , href = $el.data('target') || $el.attr('href')
-              , $href = /^#\w/.test(href) && $(href)
-            return ( $href
-              && $href.length
-              && [[ $href.position().top + (!$.isWindow(self.$scrollElement.get(0)) && self.$scrollElement.scrollTop()), href ]] ) || null
-          })
-          .sort(function (a, b) { return a[0] - b[0] })
-          .each(function () {
-            self.offsets.push(this[0])
-            self.targets.push(this[1])
-          })
-      }
-
-    , process: function () {
-        var scrollTop = this.$scrollElement.scrollTop() + this.options.offset
-          , scrollHeight = this.$scrollElement[0].scrollHeight || this.$body[0].scrollHeight
-          , maxScroll = scrollHeight - this.$scrollElement.height()
-          , offsets = this.offsets
-          , targets = this.targets
-          , activeTarget = this.activeTarget
-          , i
-
-        if (scrollTop >= maxScroll) {
-          return activeTarget != (i = targets.last()[0])
-            && this.activate ( i )
-        }
-
-        for (i = offsets.length; i--;) {
-          activeTarget != targets[i]
-            && scrollTop >= offsets[i]
-            && (!offsets[i + 1] || scrollTop <= offsets[i + 1])
-            && this.activate( targets[i] )
-        }
-      }
-
-    , activate: function (target) {
-        var active
-          , selector
-
-        this.activeTarget = target
-
-        $(this.selector)
-          .parent('.active')
-          .removeClass('active')
-
-        selector = this.selector
-          + '[data-target="' + target + '"],'
-          + this.selector + '[href="' + target + '"]'
-
-        active = $(selector)
-          .parent('li')
-          .addClass('active')
-
-        if (active.parent('.dropdown-menu').length)  {
-          active = active.closest('li.dropdown').addClass('active')
-        }
-
-        active.trigger('activate')
-      }
-
-  }
-
-
- /* SCROLLSPY PLUGIN DEFINITION
-  * =========================== */
-
-  var old = $.fn.scrollspy
-
-  $.fn.scrollspy = function (option) {
-    return this.each(function () {
-      var $this = $(this)
-        , data = $this.data('scrollspy')
-        , options = typeof option == 'object' && option
-      if (!data) $this.data('scrollspy', (data = new ScrollSpy(this, options)))
-      if (typeof option == 'string') data[option]()
-    })
-  }
-
-  $.fn.scrollspy.Constructor = ScrollSpy
-
-  $.fn.scrollspy.defaults = {
-    offset: 10
-  }
-
-
- /* SCROLLSPY NO CONFLICT
-  * ===================== */
-
-  $.fn.scrollspy.noConflict = function () {
-    $.fn.scrollspy = old
-    return this
-  }
-
-
- /* SCROLLSPY DATA-API
-  * ================== */
-
-  $(window).on('load', function () {
-    $('[data-spy="scroll"]').each(function () {
-      var $spy = $(this)
-      $spy.scrollspy($spy.data())
-    })
-  })
-
-}(window.jQuery);
-/* ========================================================
- * bootstrap-tab.js v2.3.2
- * http://twitter.github.com/bootstrap/javascript.html#tabs
- * ========================================================
- * Copyright 2012 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ======================================================== */
-
-
-!function ($) {
-
-  "use strict"; // jshint ;_;
-
-
- /* TAB CLASS DEFINITION
-  * ==================== */
-
-  var Tab = function (element) {
-    this.element = $(element)
-  }
-
-  Tab.prototype = {
-
-    constructor: Tab
-
-  , show: function () {
-      var $this = this.element
-        , $ul = $this.closest('ul:not(.dropdown-menu)')
-        , selector = $this.attr('data-target')
-        , previous
-        , $target
-        , e
-
-      if (!selector) {
-        selector = $this.attr('href')
-        selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
-      }
-
-      if ( $this.parent('li').hasClass('active') ) return
-
-      previous = $ul.find('.active:last a')[0]
-
-      e = $.Event('show', {
-        relatedTarget: previous
-      })
-
-      $this.trigger(e)
-
-      if (e.isDefaultPrevented()) return
-
-      $target = $(selector)
-
-      this.activate($this.parent('li'), $ul)
-      this.activate($target, $target.parent(), function () {
-        $this.trigger({
-          type: 'shown'
-        , relatedTarget: previous
-        })
-      })
-    }
-
-  , activate: function ( element, container, callback) {
-      var $active = container.find('> .active')
-        , transition = callback
-            && $.support.transition
-            && $active.hasClass('fade')
-
-      function next() {
-        $active
-          .removeClass('active')
-          .find('> .dropdown-menu > .active')
-          .removeClass('active')
-
-        element.addClass('active')
-
-        if (transition) {
-          element[0].offsetWidth // reflow for transition
-          element.addClass('in')
-        } else {
-          element.removeClass('fade')
-        }
-
-        if ( element.parent('.dropdown-menu') ) {
-          element.closest('li.dropdown').addClass('active')
-        }
-
-        callback && callback()
-      }
-
-      transition ?
-        $active.one($.support.transition.end, next) :
-        next()
-
-      $active.removeClass('in')
-    }
-  }
-
-
- /* TAB PLUGIN DEFINITION
-  * ===================== */
-
-  var old = $.fn.tab
-
-  $.fn.tab = function ( option ) {
-    return this.each(function () {
-      var $this = $(this)
-        , data = $this.data('tab')
-      if (!data) $this.data('tab', (data = new Tab(this)))
-      if (typeof option == 'string') data[option]()
-    })
-  }
-
-  $.fn.tab.Constructor = Tab
-
-
- /* TAB NO CONFLICT
-  * =============== */
-
-  $.fn.tab.noConflict = function () {
-    $.fn.tab = old
-    return this
-  }
-
-
- /* TAB DATA-API
-  * ============ */
-
-  $(document).on('click.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) {
-    e.preventDefault()
-    $(this).tab('show')
-  })
-
-}(window.jQuery);
-/* ===========================================================
- * bootstrap-tooltip.js v2.3.2
- * http://twitter.github.com/bootstrap/javascript.html#tooltips
- * Inspired by the original jQuery.tipsy by Jason Frame
- * ===========================================================
- * Copyright 2012 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ========================================================== */
-
-
-!function ($) {
-
-  "use strict"; // jshint ;_;
-
-
- /* TOOLTIP PUBLIC CLASS DEFINITION
-  * =============================== */
-
-  var Tooltip = function (element, options) {
-    this.init('tooltip', element, options)
-  }
-
-  Tooltip.prototype = {
-
-    constructor: Tooltip
-
-  , init: function (type, element, options) {
-      var eventIn
-        , eventOut
-        , triggers
-        , trigger
-        , i
-
-      this.type = type
-      this.$element = $(element)
-      this.options = this.getOptions(options)
-      this.enabled = true
-
-      triggers = this.options.trigger.split(' ')
-
-      for (i = triggers.length; i--;) {
-        trigger = triggers[i]
-        if (trigger == 'click') {
-          this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
-        } else if (trigger != 'manual') {
-          eventIn = trigger == 'hover' ? 'mouseenter' : 'focus'
-          eventOut = trigger == 'hover' ? 'mouseleave' : 'blur'
-          this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
-          this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
-        }
-      }
-
-      this.options.selector ?
-        (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) :
-        this.fixTitle()
-    }
-
-  , getOptions: function (options) {
-      options = $.extend({}, $.fn[this.type].defaults, this.$element.data(), options)
-
-      if (options.delay && typeof options.delay == 'number') {
-        options.delay = {
-          show: options.delay
-        , hide: options.delay
-        }
-      }
-
-      return options
-    }
-
-  , enter: function (e) {
-      var defaults = $.fn[this.type].defaults
-        , options = {}
-        , self
-
-      this._options && $.each(this._options, function (key, value) {
-        if (defaults[key] != value) options[key] = value
-      }, this)
-
-      self = $(e.currentTarget)[this.type](options).data(this.type)
-
-      if (!self.options.delay || !self.options.delay.show) return self.show()
-
-      clearTimeout(this.timeout)
-      self.hoverState = 'in'
-      this.timeout = setTimeout(function() {
-        if (self.hoverState == 'in') self.show()
-      }, self.options.delay.show)
-    }
-
-  , leave: function (e) {
-      var self = $(e.currentTarget)[this.type](this._options).data(this.type)
-
-      if (this.timeout) clearTimeout(this.timeout)
-      if (!self.options.delay || !self.options.delay.hide) return self.hide()
-
-      self.hoverState = 'out'
-      this.timeout = setTimeout(function() {
-        if (self.hoverState == 'out') self.hide()
-      }, self.options.delay.hide)
-    }
-
-  , show: function () {
-      var $tip
-        , pos
-        , actualWidth
-        , actualHeight
-        , placement
-        , tp
-        , e = $.Event('show')
-
-      if (this.hasContent() && this.enabled) {
-        this.$element.trigger(e)
-        if (e.isDefaultPrevented()) return
-        $tip = this.tip()
-        this.setContent()
-
-        if (this.options.animation) {
-          $tip.addClass('fade')
-        }
-
-        placement = typeof this.options.placement == 'function' ?
-          this.options.placement.call(this, $tip[0], this.$element[0]) :
-          this.options.placement
-
-        $tip
-          .detach()
-          .css({ top: 0, left: 0, display: 'block' })
-
-        this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)
-
-        pos = this.getPosition()
-
-        actualWidth = $tip[0].offsetWidth
-        actualHeight = $tip[0].offsetHeight
-
-        switch (placement) {
-          case 'bottom':
-            tp = {top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2}
-            break
-          case 'top':
-            tp = {top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2}
-            break
-          case 'left':
-            tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth}
-            break
-          case 'right':
-            tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width}
-            break
-        }
-
-        this.applyPlacement(tp, placement)
-        this.$element.trigger('shown')
-      }
-    }
-
-  , applyPlacement: function(offset, placement){
-      var $tip = this.tip()
-        , width = $tip[0].offsetWidth
-        , height = $tip[0].offsetHeight
-        , actualWidth
-        , actualHeight
-        , delta
-        , replace
-
-      $tip
-        .offset(offset)
-        .addClass(placement)
-        .addClass('in')
-
-      actualWidth = $tip[0].offsetWidth
-      actualHeight = $tip[0].offsetHeight
-
-      if (placement == 'top' && actualHeight != height) {
-        offset.top = offset.top + height - actualHeight
-        replace = true
-      }
-
-      if (placement == 'bottom' || placement == 'top') {
-        delta = 0
-
-        if (offset.left < 0){
-          delta = offset.left * -2
-          offset.left = 0
-          $tip.offset(offset)
-          actualWidth = $tip[0].offsetWidth
-          actualHeight = $tip[0].offsetHeight
-        }
-
-        this.replaceArrow(delta - width + actualWidth, actualWidth, 'left')
-      } else {
-        this.replaceArrow(actualHeight - height, actualHeight, 'top')
-      }
-
-      if (replace) $tip.offset(offset)
-    }
-
-  , replaceArrow: function(delta, dimension, position){
-      this
-        .arrow()
-        .css(position, delta ? (50 * (1 - delta / dimension) + "%") : '')
-    }
-
-  , setContent: function () {
-      var $tip = this.tip()
-        , title = this.getTitle()
-
-      $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
-      $tip.removeClass('fade in top bottom left right')
-    }
-
-  , hide: function () {
-      var that = this
-        , $tip = this.tip()
-        , e = $.Event('hide')
-
-      this.$element.trigger(e)
-      if (e.isDefaultPrevented()) return
-
-      $tip.removeClass('in')
-
-      function removeWithAnimation() {
-        var timeout = setTimeout(function () {
-          $tip.off($.support.transition.end).detach()
-        }, 500)
-
-        $tip.one($.support.transition.end, function () {
-          clearTimeout(timeout)
-          $tip.detach()
-        })
-      }
-
-      $.support.transition && this.$tip.hasClass('fade') ?
-        removeWithAnimation() :
-        $tip.detach()
-
-      this.$element.trigger('hidden')
-
-      return this
-    }
-
-  , fixTitle: function () {
-      var $e = this.$element
-      if ($e.attr('title') || typeof($e.attr('data-original-title')) != 'string') {
-        $e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
-      }
-    }
-
-  , hasContent: function () {
-      return this.getTitle()
-    }
-
-  , getPosition: function () {
-      var el = this.$element[0]
-      return $.extend({}, (typeof el.getBoundingClientRect == 'function') ? el.getBoundingClientRect() : {
-        width: el.offsetWidth
-      , height: el.offsetHeight
-      }, this.$element.offset())
-    }
-
-  , getTitle: function () {
-      var title
-        , $e = this.$element
-        , o = this.options
-
-      title = $e.attr('data-original-title')
-        || (typeof o.title == 'function' ? o.title.call($e[0]) :  o.title)
-
-      return title
-    }
-
-  , tip: function () {
-      return this.$tip = this.$tip || $(this.options.template)
-    }
-
-  , arrow: function(){
-      return this.$arrow = this.$arrow || this.tip().find(".tooltip-arrow")
-    }
-
-  , validate: function () {
-      if (!this.$element[0].parentNode) {
-        this.hide()
-        this.$element = null
-        this.options = null
-      }
-    }
-
-  , enable: function () {
-      this.enabled = true
-    }
-
-  , disable: function () {
-      this.enabled = false
-    }
-
-  , toggleEnabled: function () {
-      this.enabled = !this.enabled
-    }
-
-  , toggle: function (e) {
-      var self = e ? $(e.currentTarget)[this.type](this._options).data(this.type) : this
-      self.tip().hasClass('in') ? self.hide() : self.show()
-    }
-
-  , destroy: function () {
-      this.hide().$element.off('.' + this.type).removeData(this.type)
-    }
-
-  }
-
-
- /* TOOLTIP PLUGIN DEFINITION
-  * ========================= */
-
-  var old = $.fn.tooltip
-
-  $.fn.tooltip = function ( option ) {
-    return this.each(function () {
-      var $this = $(this)
-        , data = $this.data('tooltip')
-        , options = typeof option == 'object' && option
-      if (!data) $this.data('tooltip', (data = new Tooltip(this, options)))
-      if (typeof option == 'string') data[option]()
-    })
-  }
-
-  $.fn.tooltip.Constructor = Tooltip
-
-  $.fn.tooltip.defaults = {
-    animation: true
-  , placement: 'top'
-  , selector: false
-  , template: '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>'
-  , trigger: 'hover focus'
-  , title: ''
-  , delay: 0
-  , html: false
-  , container: false
-  }
-
-
- /* TOOLTIP NO CONFLICT
-  * =================== */
-
-  $.fn.tooltip.noConflict = function () {
-    $.fn.tooltip = old
-    return this
-  }
-
-}(window.jQuery);
-
-/* ===========================================================
- * bootstrap-popover.js v2.3.2
- * http://twitter.github.com/bootstrap/javascript.html#popovers
- * ===========================================================
- * Copyright 2012 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * =========================================================== */
-
-
-!function ($) {
-
-  "use strict"; // jshint ;_;
-
-
- /* POPOVER PUBLIC CLASS DEFINITION
-  * =============================== */
-
-  var Popover = function (element, options) {
-    this.init('popover', element, options)
-  }
-
-
-  /* NOTE: POPOVER EXTENDS BOOTSTRAP-TOOLTIP.js
-     ========================================== */
-
-  Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype, {
-
-    constructor: Popover
-
-  , setContent: function () {
-      var $tip = this.tip()
-        , title = this.getTitle()
-        , content = this.getContent()
-
-      $tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title)
-      $tip.find('.popover-content')[this.options.html ? 'html' : 'text'](content)
-
-      $tip.removeClass('fade top bottom left right in')
-    }
-
-  , hasContent: function () {
-      return this.getTitle() || this.getContent()
-    }
-
-  , getContent: function () {
-      var content
-        , $e = this.$element
-        , o = this.options
-
-      content = (typeof o.content == 'function' ? o.content.call($e[0]) :  o.content)
-        || $e.attr('data-content')
-
-      return content
-    }
-
-  , tip: function () {
-      if (!this.$tip) {
-        this.$tip = $(this.options.template)
-      }
-      return this.$tip
-    }
-
-  , destroy: function () {
-      this.hide().$element.off('.' + this.type).removeData(this.type)
-    }
-
-  })
-
-
- /* POPOVER PLUGIN DEFINITION
-  * ======================= */
-
-  var old = $.fn.popover
-
-  $.fn.popover = function (option) {
-    return this.each(function () {
-      var $this = $(this)
-        , data = $this.data('popover')
-        , options = typeof option == 'object' && option
-      if (!data) $this.data('popover', (data = new Popover(this, options)))
-      if (typeof option == 'string') data[option]()
-    })
-  }
-
-  $.fn.popover.Constructor = Popover
-
-  $.fn.popover.defaults = $.extend({} , $.fn.tooltip.defaults, {
-    placement: 'right'
-  , trigger: 'click'
-  , content: ''
-  , template: '<div class="popover"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
-  })
-
-
- /* POPOVER NO CONFLICT
-  * =================== */
-
-  $.fn.popover.noConflict = function () {
-    $.fn.popover = old
-    return this
-  }
-
-}(window.jQuery);
-
-/* ==========================================================
- * bootstrap-affix.js v2.3.2
- * http://twitter.github.com/bootstrap/javascript.html#affix
- * ==========================================================
- * Copyright 2012 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ========================================================== */
-
-
-!function ($) {
-
-  "use strict"; // jshint ;_;
-
-
- /* AFFIX CLASS DEFINITION
-  * ====================== */
-
-  var Affix = function (element, options) {
-    this.options = $.extend({}, $.fn.affix.defaults, options)
-    this.$window = $(window)
-      .on('scroll.affix.data-api', $.proxy(this.checkPosition, this))
-      .on('click.affix.data-api',  $.proxy(function () { setTimeout($.proxy(this.checkPosition, this), 1) }, this))
-    this.$element = $(element)
-    this.checkPosition()
-  }
-
-  Affix.prototype.checkPosition = function () {
-    if (!this.$element.is(':visible')) return
-
-    var scrollHeight = $(document).height()
-      , scrollTop = this.$window.scrollTop()
-      , position = this.$element.offset()
-      , offset = this.options.offset
-      , offsetBottom = offset.bottom
-      , offsetTop = offset.top
-      , reset = 'affix affix-top affix-bottom'
-      , affix
-
-    if (typeof offset != 'object') offsetBottom = offsetTop = offset
-    if (typeof offsetTop == 'function') offsetTop = offset.top()
-    if (typeof offsetBottom == 'function') offsetBottom = offset.bottom()
-
-    affix = this.unpin != null && (scrollTop + this.unpin <= position.top) ?
-      false    : offsetBottom != null && (position.top + this.$element.height() >= scrollHeight - offsetBottom) ?
-      'bottom' : offsetTop != null && scrollTop <= offsetTop ?
-      'top'    : false
-
-    if (this.affixed === affix) return
-
-    this.affixed = affix
-    this.unpin = affix == 'bottom' ? position.top - scrollTop : null
-
-    this.$element.removeClass(reset).addClass('affix' + (affix ? '-' + affix : ''))
-  }
-
-
- /* AFFIX PLUGIN DEFINITION
-  * ======================= */
-
-  var old = $.fn.affix
-
-  $.fn.affix = function (option) {
-    return this.each(function () {
-      var $this = $(this)
-        , data = $this.data('affix')
-        , options = typeof option == 'object' && option
-      if (!data) $this.data('affix', (data = new Affix(this, options)))
-      if (typeof option == 'string') data[option]()
-    })
-  }
-
-  $.fn.affix.Constructor = Affix
-
-  $.fn.affix.defaults = {
-    offset: 0
-  }
-
-
- /* AFFIX NO CONFLICT
-  * ================= */
-
-  $.fn.affix.noConflict = function () {
-    $.fn.affix = old
-    return this
-  }
-
-
- /* AFFIX DATA-API
-  * ============== */
-
-  $(window).on('load', function () {
-    $('[data-spy="affix"]').each(function () {
-      var $spy = $(this)
-        , data = $spy.data()
-
-      data.offset = data.offset || {}
-
-      data.offsetBottom && (data.offset.bottom = data.offsetBottom)
-      data.offsetTop && (data.offset.top = data.offsetTop)
-
-      $spy.affix(data)
-    })
-  })
-
-
-}(window.jQuery);
-/* ==========================================================
- * bootstrap-alert.js v2.3.2
- * http://twitter.github.com/bootstrap/javascript.html#alerts
- * ==========================================================
- * Copyright 2012 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ========================================================== */
-
-
-!function ($) {
-
-  "use strict"; // jshint ;_;
-
-
- /* ALERT CLASS DEFINITION
-  * ====================== */
-
-  var dismiss = '[data-dismiss="alert"]'
-    , Alert = function (el) {
-        $(el).on('click', dismiss, this.close)
-      }
-
-  Alert.prototype.close = function (e) {
-    var $this = $(this)
-      , selector = $this.attr('data-target')
-      , $parent
-
-    if (!selector) {
-      selector = $this.attr('href')
-      selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
-    }
-
-    $parent = $(selector)
-
-    e && e.preventDefault()
-
-    $parent.length || ($parent = $this.hasClass('alert') ? $this : $this.parent())
-
-    $parent.trigger(e = $.Event('close'))
-
-    if (e.isDefaultPrevented()) return
-
-    $parent.removeClass('in')
-
-    function removeElement() {
-      $parent
-        .trigger('closed')
-        .remove()
-    }
-
-    $.support.transition && $parent.hasClass('fade') ?
-      $parent.on($.support.transition.end, removeElement) :
-      removeElement()
-  }
-
-
- /* ALERT PLUGIN DEFINITION
-  * ======================= */
-
-  var old = $.fn.alert
-
-  $.fn.alert = function (option) {
-    return this.each(function () {
-      var $this = $(this)
-        , data = $this.data('alert')
-      if (!data) $this.data('alert', (data = new Alert(this)))
-      if (typeof option == 'string') data[option].call($this)
-    })
-  }
-
-  $.fn.alert.Constructor = Alert
-
-
- /* ALERT NO CONFLICT
-  * ================= */
-
-  $.fn.alert.noConflict = function () {
-    $.fn.alert = old
-    return this
-  }
-
-
- /* ALERT DATA-API
-  * ============== */
-
-  $(document).on('click.alert.data-api', dismiss, Alert.prototype.close)
-
-}(window.jQuery);
-/* ============================================================
- * bootstrap-button.js v2.3.2
- * http://twitter.github.com/bootstrap/javascript.html#buttons
- * ============================================================
- * Copyright 2012 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============================================================ */
-
-
-!function ($) {
-
-  "use strict"; // jshint ;_;
-
-
- /* BUTTON PUBLIC CLASS DEFINITION
-  * ============================== */
-
-  var Button = function (element, options) {
-    this.$element = $(element)
-    this.options = $.extend({}, $.fn.button.defaults, options)
-  }
-
-  Button.prototype.setState = function (state) {
-    var d = 'disabled'
-      , $el = this.$element
-      , data = $el.data()
-      , val = $el.is('input') ? 'val' : 'html'
-
-    state = state + 'Text'
-    data.resetText || $el.data('resetText', $el[val]())
-
-    $el[val](data[state] || this.options[state])
-
-    // push to event loop to allow forms to submit
-    setTimeout(function () {
-      state == 'loadingText' ?
-        $el.addClass(d).attr(d, d) :
-        $el.removeClass(d).removeAttr(d)
-    }, 0)
-  }
-
-  Button.prototype.toggle = function () {
-    var $parent = this.$element.closest('[data-toggle="buttons-radio"]')
-
-    $parent && $parent
-      .find('.active')
-      .removeClass('active')
-
-    this.$element.toggleClass('active')
-  }
-
-
- /* BUTTON PLUGIN DEFINITION
-  * ======================== */
-
-  var old = $.fn.button
-
-  $.fn.button = function (option) {
-    return this.each(function () {
-      var $this = $(this)
-        , data = $this.data('button')
-        , options = typeof option == 'object' && option
-      if (!data) $this.data('button', (data = new Button(this, options)))
-      if (option == 'toggle') data.toggle()
-      else if (option) data.setState(option)
-    })
-  }
-
-  $.fn.button.defaults = {
-    loadingText: 'loading...'
-  }
-
-  $.fn.button.Constructor = Button
-
-
- /* BUTTON NO CONFLICT
-  * ================== */
-
-  $.fn.button.noConflict = function () {
-    $.fn.button = old
-    return this
-  }
-
-
- /* BUTTON DATA-API
-  * =============== */
-
-  $(document).on('click.button.data-api', '[data-toggle^=button]', function (e) {
-    var $btn = $(e.target)
-    if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn')
-    $btn.button('toggle')
-  })
-
-}(window.jQuery);
-/* =============================================================
- * bootstrap-collapse.js v2.3.2
- * http://twitter.github.com/bootstrap/javascript.html#collapse
- * =============================================================
- * Copyright 2012 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============================================================ */
-
-
-!function ($) {
-
-  "use strict"; // jshint ;_;
-
-
- /* COLLAPSE PUBLIC CLASS DEFINITION
-  * ================================ */
-
-  var Collapse = function (element, options) {
-    this.$element = $(element)
-    this.options = $.extend({}, $.fn.collapse.defaults, options)
-
-    if (this.options.parent) {
-      this.$parent = $(this.options.parent)
-    }
-
-    this.options.toggle && this.toggle()
-  }
-
-  Collapse.prototype = {
-
-    constructor: Collapse
-
-  , dimension: function () {
-      var hasWidth = this.$element.hasClass('width')
-      return hasWidth ? 'width' : 'height'
-    }
-
-  , show: function () {
-      var dimension
-        , scroll
-        , actives
-        , hasData
-
-      if (this.transitioning || this.$element.hasClass('in')) return
-
-      dimension = this.dimension()
-      scroll = $.camelCase(['scroll', dimension].join('-'))
-      actives = this.$parent && this.$parent.find('> .accordion-group > .in')
-
-      if (actives && actives.length) {
-        hasData = actives.data('collapse')
-        if (hasData && hasData.transitioning) return
-        actives.collapse('hide')
-        hasData || actives.data('collapse', null)
-      }
-
-      this.$element[dimension](0)
-      this.transition('addClass', $.Event('show'), 'shown')
-      $.support.transition && this.$element[dimension](this.$element[0][scroll])
-    }
-
-  , hide: function () {
-      var dimension
-      if (this.transitioning || !this.$element.hasClass('in')) return
-      dimension = this.dimension()
-      this.reset(this.$element[dimension]())
-      this.transition('removeClass', $.Event('hide'), 'hidden')
-      this.$element[dimension](0)
-    }
-
-  , reset: function (size) {
-      var dimension = this.dimension()
-
-      this.$element
-        .removeClass('collapse')
-        [dimension](size || 'auto')
-        [0].offsetWidth
-
-      this.$element[size !== null ? 'addClass' : 'removeClass']('collapse')
-
-      return this
-    }
-
-  , transition: function (method, startEvent, completeEvent) {
-      var that = this
-        , complete = function () {
-            if (startEvent.type == 'show') that.reset()
-            that.transitioning = 0
-            that.$element.trigger(completeEvent)
-          }
-
-      this.$element.trigger(startEvent)
-
-      if (startEvent.isDefaultPrevented()) return
-
-      this.transitioning = 1
-
-      this.$element[method]('in')
-
-      $.support.transition && this.$element.hasClass('collapse') ?
-        this.$element.one($.support.transition.end, complete) :
-        complete()
-    }
-
-  , toggle: function () {
-      this[this.$element.hasClass('in') ? 'hide' : 'show']()
-    }
-
-  }
-
-
- /* COLLAPSE PLUGIN DEFINITION
-  * ========================== */
-
-  var old = $.fn.collapse
-
-  $.fn.collapse = function (option) {
-    return this.each(function () {
-      var $this = $(this)
-        , data = $this.data('collapse')
-        , options = $.extend({}, $.fn.collapse.defaults, $this.data(), typeof option == 'object' && option)
-      if (!data) $this.data('collapse', (data = new Collapse(this, options)))
-      if (typeof option == 'string') data[option]()
-    })
-  }
-
-  $.fn.collapse.defaults = {
-    toggle: true
-  }
-
-  $.fn.collapse.Constructor = Collapse
-
-
- /* COLLAPSE NO CONFLICT
-  * ==================== */
-
-  $.fn.collapse.noConflict = function () {
-    $.fn.collapse = old
-    return this
-  }
-
-
- /* COLLAPSE DATA-API
-  * ================= */
-
-  $(document).on('click.collapse.data-api', '[data-toggle=collapse]', function (e) {
-    var $this = $(this), href
-      , target = $this.attr('data-target')
-        || e.preventDefault()
-        || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7
-      , option = $(target).data('collapse') ? 'toggle' : $this.data()
-    $this[$(target).hasClass('in') ? 'addClass' : 'removeClass']('collapsed')
-    $(target).collapse(option)
-  })
-
-}(window.jQuery);
-/* ==========================================================
- * bootstrap-carousel.js v2.3.2
- * http://twitter.github.com/bootstrap/javascript.html#carousel
- * ==========================================================
- * Copyright 2012 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ========================================================== */
-
-
-!function ($) {
-
-  "use strict"; // jshint ;_;
-
-
- /* CAROUSEL CLASS DEFINITION
-  * ========================= */
-
-  var Carousel = function (element, options) {
-    this.$element = $(element)
-    this.$indicators = this.$element.find('.carousel-indicators')
-    this.options = options
-    this.options.pause == 'hover' && this.$element
-      .on('mouseenter', $.proxy(this.pause, this))
-      .on('mouseleave', $.proxy(this.cycle, this))
-  }
-
-  Carousel.prototype = {
-
-    cycle: function (e) {
-      if (!e) this.paused = false
-      if (this.interval) clearInterval(this.interval);
-      this.options.interval
-        && !this.paused
-        && (this.interval = setInterval($.proxy(this.next, this), this.options.interval))
-      return this
-    }
-
-  , getActiveIndex: function () {
-      this.$active = this.$element.find('.item.active')
-      this.$items = this.$active.parent().children()
-      return this.$items.index(this.$active)
-    }
-
-  , to: function (pos) {
-      var activeIndex = this.getActiveIndex()
-        , that = this
-
-      if (pos > (this.$items.length - 1) || pos < 0) return
-
-      if (this.sliding) {
-        return this.$element.one('slid', function () {
-          that.to(pos)
-        })
-      }
-
-      if (activeIndex == pos) {
-        return this.pause().cycle()
-      }
-
-      return this.slide(pos > activeIndex ? 'next' : 'prev', $(this.$items[pos]))
-    }
-
-  , pause: function (e) {
-      if (!e) this.paused = true
-      if (this.$element.find('.next, .prev').length && $.support.transition.end) {
-        this.$element.trigger($.support.transition.end)
-        this.cycle(true)
-      }
-      clearInterval(this.interval)
-      this.interval = null
-      return this
-    }
-
-  , next: function () {
-      if (this.sliding) return
-      return this.slide('next')
-    }
-
-  , prev: function () {
-      if (this.sliding) return
-      return this.slide('prev')
-    }
-
-  , slide: function (type, next) {
-      var $active = this.$element.find('.item.active')
-        , $next = next || $active[type]()
-        , isCycling = this.interval
-        , direction = type == 'next' ? 'left' : 'right'
-        , fallback  = type == 'next' ? 'first' : 'last'
-        , that = this
-        , e
-
-      this.sliding = true
-
-      isCycling && this.pause()
-
-      $next = $next.length ? $next : this.$element.find('.item')[fallback]()
-
-      e = $.Event('slide', {
-        relatedTarget: $next[0]
-      , direction: direction
-      })
-
-      if ($next.hasClass('active')) return
-
-      if (this.$indicators.length) {
-        this.$indicators.find('.active').removeClass('active')
-        this.$element.one('slid', function () {
-          var $nextIndicator = $(that.$indicators.children()[that.getActiveIndex()])
-          $nextIndicator && $nextIndicator.addClass('active')
-        })
-      }
-
-      if ($.support.transition && this.$element.hasClass('slide')) {
-        this.$element.trigger(e)
-        if (e.isDefaultPrevented()) return
-        $next.addClass(type)
-        $next[0].offsetWidth // force reflow
-        $active.addClass(direction)
-        $next.addClass(direction)
-        this.$element.one($.support.transition.end, function () {
-          $next.removeClass([type, direction].join(' ')).addClass('active')
-          $active.removeClass(['active', direction].join(' '))
-          that.sliding = false
-          setTimeout(function () { that.$element.trigger('slid') }, 0)
-        })
-      } else {
-        this.$element.trigger(e)
-        if (e.isDefaultPrevented()) return
-        $active.removeClass('active')
-        $next.addClass('active')
-        this.sliding = false
-        this.$element.trigger('slid')
-      }
-
-      isCycling && this.cycle()
-
-      return this
-    }
-
-  }
-
-
- /* CAROUSEL PLUGIN DEFINITION
-  * ========================== */
-
-  var old = $.fn.carousel
-
-  $.fn.carousel = function (option) {
-    return this.each(function () {
-      var $this = $(this)
-        , data = $this.data('carousel')
-        , options = $.extend({}, $.fn.carousel.defaults, typeof option == 'object' && option)
-        , action = typeof option == 'string' ? option : options.slide
-      if (!data) $this.data('carousel', (data = new Carousel(this, options)))
-      if (typeof option == 'number') data.to(option)
-      else if (action) data[action]()
-      else if (options.interval) data.pause().cycle()
-    })
-  }
-
-  $.fn.carousel.defaults = {
-    interval: 5000
-  , pause: 'hover'
-  }
-
-  $.fn.carousel.Constructor = Carousel
-
-
- /* CAROUSEL NO CONFLICT
-  * ==================== */
-
-  $.fn.carousel.noConflict = function () {
-    $.fn.carousel = old
-    return this
-  }
-
- /* CAROUSEL DATA-API
-  * ================= */
-
-  $(document).on('click.carousel.data-api', '[data-slide], [data-slide-to]', function (e) {
-    var $this = $(this), href
-      , $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7
-      , options = $.extend({}, $target.data(), $this.data())
-      , slideIndex
-
-    $target.carousel(options)
-
-    if (slideIndex = $this.attr('data-slide-to')) {
-      $target.data('carousel').pause().to(slideIndex).cycle()
-    }
-
-    e.preventDefault()
-  })
-
-}(window.jQuery);
-/* =============================================================
- * bootstrap-typeahead.js v2.3.2
- * http://twitter.github.com/bootstrap/javascript.html#typeahead
- * =============================================================
- * Copyright 2012 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============================================================ */
-
-
-!function($){
-
-  "use strict"; // jshint ;_;
-
-
- /* TYPEAHEAD PUBLIC CLASS DEFINITION
-  * ================================= */
-
-  var Typeahead = function (element, options) {
-    this.$element = $(element)
-    this.options = $.extend({}, $.fn.typeahead.defaults, options)
-    this.matcher = this.options.matcher || this.matcher
-    this.sorter = this.options.sorter || this.sorter
-    this.highlighter = this.options.highlighter || this.highlighter
-    this.updater = this.options.updater || this.updater
-    this.source = this.options.source
-    this.$menu = $(this.options.menu)
-    this.shown = false
-    this.listen()
-  }
-
-  Typeahead.prototype = {
-
-    constructor: Typeahead
-
-  , select: function () {
-      var val = this.$menu.find('.active').attr('data-value')
-      this.$element
-        .val(this.updater(val))
-        .change()
-      return this.hide()
-    }
-
-  , updater: function (item) {
-      return item
-    }
-
-  , show: function () {
-      var pos = $.extend({}, this.$element.position(), {
-        height: this.$element[0].offsetHeight
-      })
-
-      this.$menu
-        .insertAfter(this.$element)
-        .css({
-          top: pos.top + pos.height
-        , left: pos.left
-        })
-        .show()
-
-      this.shown = true
-      return this
-    }
-
-  , hide: function () {
-      this.$menu.hide()
-      this.shown = false
-      return this
-    }
-
-  , lookup: function (event) {
-      var items
-
-      this.query = this.$element.val()
-
-      if (!this.query || this.query.length < this.options.minLength) {
-        return this.shown ? this.hide() : this
-      }
-
-      items = $.isFunction(this.source) ? this.source(this.query, $.proxy(this.process, this)) : this.source
-
-      return items ? this.process(items) : this
-    }
-
-  , process: function (items) {
-      var that = this
-
-      items = $.grep(items, function (item) {
-        return that.matcher(item)
-      })
-
-      items = this.sorter(items)
-
-      if (!items.length) {
-        return this.shown ? this.hide() : this
-      }
-
-      return this.render(items.slice(0, this.options.items)).show()
-    }
-
-  , matcher: function (item) {
-      return ~item.toLowerCase().indexOf(this.query.toLowerCase())
-    }
-
-  , sorter: function (items) {
-      var beginswith = []
-        , caseSensitive = []
-        , caseInsensitive = []
-        , item
-
-      while (item = items.shift()) {
-        if (!item.toLowerCase().indexOf(this.query.toLowerCase())) beginswith.push(item)
-        else if (~item.indexOf(this.query)) caseSensitive.push(item)
-        else caseInsensitive.push(item)
-      }
-
-      return beginswith.concat(caseSensitive, caseInsensitive)
-    }
-
-  , highlighter: function (item) {
-      var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&')
-      return item.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
-        return '<strong>' + match + '</strong>'
-      })
-    }
-
-  , render: function (items) {
-      var that = this
-
-      items = $(items).map(function (i, item) {
-        i = $(that.options.item).attr('data-value', item)
-        i.find('a').html(that.highlighter(item))
-        return i[0]
-      })
-
-      items.first().addClass('active')
-      this.$menu.html(items)
-      return this
-    }
-
-  , next: function (event) {
-      var active = this.$menu.find('.active').removeClass('active')
-        , next = active.next()
-
-      if (!next.length) {
-        next = $(this.$menu.find('li')[0])
-      }
-
-      next.addClass('active')
-    }
-
-  , prev: function (event) {
-      var active = this.$menu.find('.active').removeClass('active')
-        , prev = active.prev()
-
-      if (!prev.length) {
-        prev = this.$menu.find('li').last()
-      }
-
-      prev.addClass('active')
-    }
-
-  , listen: function () {
-      this.$element
-        .on('focus',    $.proxy(this.focus, this))
-        .on('blur',     $.proxy(this.blur, this))
-        .on('keypress', $.proxy(this.keypress, this))
-        .on('keyup',    $.proxy(this.keyup, this))
-
-      if (this.eventSupported('keydown')) {
-        this.$element.on('keydown', $.proxy(this.keydown, this))
-      }
-
-      this.$menu
-        .on('click', $.proxy(this.click, this))
-        .on('mouseenter', 'li', $.proxy(this.mouseenter, this))
-        .on('mouseleave', 'li', $.proxy(this.mouseleave, this))
-    }
-
-  , eventSupported: function(eventName) {
-      var isSupported = eventName in this.$element
-      if (!isSupported) {
-        this.$element.setAttribute(eventName, 'return;')
-        isSupported = typeof this.$element[eventName] === 'function'
-      }
-      return isSupported
-    }
-
-  , move: function (e) {
-      if (!this.shown) return
-
-      switch(e.keyCode) {
-        case 9: // tab
-        case 13: // enter
-        case 27: // escape
-          e.preventDefault()
-          break
-
-        case 38: // up arrow
-          e.preventDefault()
-          this.prev()
-          break
-
-        case 40: // down arrow
-          e.preventDefault()
-          this.next()
-          break
-      }
-
-      e.stopPropagation()
-    }
-
-  , keydown: function (e) {
-      this.suppressKeyPressRepeat = ~$.inArray(e.keyCode, [40,38,9,13,27])
-      this.move(e)
-    }
-
-  , keypress: function (e) {
-      if (this.suppressKeyPressRepeat) return
-      this.move(e)
-    }
-
-  , keyup: function (e) {
-      switch(e.keyCode) {
-        case 40: // down arrow
-        case 38: // up arrow
-        case 16: // shift
-        case 17: // ctrl
-        case 18: // alt
-          break
-
-        case 9: // tab
-        case 13: // enter
-          if (!this.shown) return
-          this.select()
-          break
-
-        case 27: // escape
-          if (!this.shown) return
-          this.hide()
-          break
-
-        default:
-          this.lookup()
-      }
-
-      e.stopPropagation()
-      e.preventDefault()
-  }
-
-  , focus: function (e) {
-      this.focused = true
-    }
-
-  , blur: function (e) {
-      this.focused = false
-      if (!this.mousedover && this.shown) this.hide()
-    }
-
-  , click: function (e) {
-      e.stopPropagation()
-      e.preventDefault()
-      this.select()
-      this.$element.focus()
-    }
-
-  , mouseenter: function (e) {
-      this.mousedover = true
-      this.$menu.find('.active').removeClass('active')
-      $(e.currentTarget).addClass('active')
-    }
-
-  , mouseleave: function (e) {
-      this.mousedover = false
-      if (!this.focused && this.shown) this.hide()
-    }
-
-  }
-
-
-  /* TYPEAHEAD PLUGIN DEFINITION
-   * =========================== */
-
-  var old = $.fn.typeahead
-
-  $.fn.typeahead = function (option) {
-    return this.each(function () {
-      var $this = $(this)
-        , data = $this.data('typeahead')
-        , options = typeof option == 'object' && option
-      if (!data) $this.data('typeahead', (data = new Typeahead(this, options)))
-      if (typeof option == 'string') data[option]()
-    })
-  }
-
-  $.fn.typeahead.defaults = {
-    source: []
-  , items: 8
-  , menu: '<ul class="typeahead dropdown-menu"></ul>'
-  , item: '<li><a href="#"></a></li>'
-  , minLength: 1
-  }
-
-  $.fn.typeahead.Constructor = Typeahead
-
-
- /* TYPEAHEAD NO CONFLICT
-  * =================== */
-
-  $.fn.typeahead.noConflict = function () {
-    $.fn.typeahead = old
-    return this
-  }
-
-
- /* TYPEAHEAD DATA-API
-  * ================== */
-
-  $(document).on('focus.typeahead.data-api', '[data-provide="typeahead"]', function (e) {
-    var $this = $(this)
-    if ($this.data('typeahead')) return
-    $this.typeahead($this.data())
-  })
-
-}(window.jQuery);


[22/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/js/libs/ace/mode-jsoniq.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/js/libs/ace/mode-jsoniq.js b/apps/fauxton/assets/js/libs/ace/mode-jsoniq.js
deleted file mode 100644
index 8233635..0000000
--- a/apps/fauxton/assets/js/libs/ace/mode-jsoniq.js
+++ /dev/null
@@ -1,2714 +0,0 @@
-/* ***** BEGIN LICENSE BLOCK *****
- * Distributed under the BSD license:
- *
- * Copyright (c) 2010, Ajax.org B.V.
- * All rights reserved.
- * 
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above copyright
- *       notice, this list of conditions and the following disclaimer in the
- *       documentation and/or other materials provided with the distribution.
- *     * Neither the name of Ajax.org B.V. nor the
- *       names of its contributors may be used to endorse or promote products
- *       derived from this software without specific prior written permission.
- * 
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * ***** END LICENSE BLOCK ***** */
-define('ace/mode/jsoniq', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/mode/xquery/JSONiqLexer', 'ace/range', 'ace/mode/behaviour/xquery', 'ace/mode/folding/cstyle'], function(require, exports, module) {
-
-
-var oop = require("../lib/oop");
-var TextMode = require("./text").Mode;
-var JSONiqLexer = require("./xquery/JSONiqLexer").JSONiqLexer;
-var Range = require("../range").Range;
-var XQueryBehaviour = require("./behaviour/xquery").XQueryBehaviour;
-var CStyleFoldMode = require("./folding/cstyle").FoldMode;
-
-
-var Mode = function() {
-    this.$tokenizer   = new JSONiqLexer();
-    this.$behaviour   = new XQueryBehaviour();
-    this.foldingRules = new CStyleFoldMode();
-};
-
-oop.inherits(Mode, TextMode);
-
-(function() {
-
-    this.getNextLineIndent = function(state, line, tab) {
-        var indent = this.$getIndent(line);
-        var match = line.match(/\s*(?:then|else|return|[{\(]|<\w+>)\s*$/);
-        if (match)
-            indent += tab;
-        return indent;
-    };
-    
-    this.checkOutdent = function(state, line, input) {
-        if (! /^\s+$/.test(line))
-            return false;
-
-        return /^\s*[\}\)]/.test(input);
-    };
-    
-    this.autoOutdent = function(state, doc, row) {
-        var line = doc.getLine(row);
-        var match = line.match(/^(\s*[\}\)])/);
-
-        if (!match) return 0;
-
-        var column = match[1].length;
-        var openBracePos = doc.findMatchingBracket({row: row, column: column});
-
-        if (!openBracePos || openBracePos.row == row) return 0;
-
-        var indent = this.$getIndent(doc.getLine(openBracePos.row));
-        doc.replace(new Range(row, 0, row, column-1), indent);
-    };
-
-    this.toggleCommentLines = function(state, doc, startRow, endRow) {
-        var i, line;
-        var outdent = true;
-        var re = /^\s*\(:(.*):\)/;
-
-        for (i=startRow; i<= endRow; i++) {
-            if (!re.test(doc.getLine(i))) {
-                outdent = false;
-                break;
-            }
-        }
-
-        var range = new Range(0, 0, 0, 0);
-        for (i=startRow; i<= endRow; i++) {
-            line = doc.getLine(i);
-            range.start.row  = i;
-            range.end.row    = i;
-            range.end.column = line.length;
-
-            doc.replace(range, outdent ? line.match(re)[1] : "(:" + line + ":)");
-        }
-    };
-}).call(Mode.prototype);
-
-exports.Mode = Mode;
-});
- 
-define('ace/mode/xquery/JSONiqLexer', ['require', 'exports', 'module' , 'ace/mode/xquery/JSONiqTokenizer'], function(require, exports, module) {
-  
-  var JSONiqTokenizer = require("./JSONiqTokenizer").JSONiqTokenizer;
-  
-  var TokenHandler = function(code) {
-      
-    var input = code;
-    
-    this.tokens = [];
- 
-    this.reset = function(code) {
-      input = input;
-      this.tokens = [];
-    };
-    
-    this.startNonterminal = function(name, begin) {};
-
-    this.endNonterminal = function(name, end) {};
-
-    this.terminal = function(name, begin, end) {
-      this.tokens.push({
-        name: name,
-        value: input.substring(begin, end)
-      });
-    };
-
-    this.whitespace = function(begin, end) {
-      this.tokens.push({
-        name: "WS",
-        value: input.substring(begin, end)
-      });
-    };
-  };
-    var keys = "NaN|after|allowing|ancestor|ancestor-or-self|and|append|array|as|ascending|at|attribute|base-uri|before|boundary-space|break|by|case|cast|castable|catch|child|collation|comment|constraint|construction|contains|context|continue|copy|copy-namespaces|count|decimal-format|decimal-separator|declare|default|delete|descendant|descendant-or-self|descending|digit|div|document|document-node|element|else|empty|empty-sequence|encoding|end|eq|every|except|exit|external|false|first|following|following-sibling|for|from|ft-option|function|ge|greatest|group|grouping-separator|gt|idiv|if|import|in|index|infinity|insert|instance|integrity|intersect|into|is|item|json|json-item|jsoniq|last|lax|le|least|let|loop|lt|minus-sign|mod|modify|module|namespace|namespace-node|ne|next|node|nodes|not|null|object|of|only|option|or|order|ordered|ordering|paragraphs|parent|pattern-separator|per-mille|percent|preceding|preceding-sibling|previous|processing-instruction|rename|replace|return|returning|re
 validation|satisfies|schema|schema-attribute|schema-element|score|select|self|sentences|sliding|some|stable|start|strict|switch|text|then|times|to|treat|true|try|tumbling|type|typeswitch|union|unordered|updating|validate|value|variable|version|when|where|while|window|with|words|xquery|zero-digit".split("|");
-    var keywords = keys.map(
-      function(val) { return { name: "'" + val + "'", token: "keyword" }; }
-    );
-    
-    var ncnames = keys.map(
-      function(val) { return { name: "'" + val + "'", token: "text", next: function(stack){ stack.pop(); } }; }
-    );
-
-    var cdata = "constant.language";
-    var number = "constant";
-    var xmlcomment = "comment";
-    var pi = "xml-pe";
-    var pragma = "constant.buildin";
-    
-    var Rules = {
-      start: [
-        { name: "'(#'", token: pragma, next: function(stack){ stack.push("Pragma"); } },
-        { name: "'(:'", token: "comment", next: function(stack){ stack.push("Comment"); } },
-        { name: "'(:~'", token: "comment.doc", next: function(stack){ stack.push("CommentDoc"); } },
-        { name: "'<!--'", token: xmlcomment, next: function(stack){ stack.push("XMLComment"); } },
-        { name: "'<?'", token: pi, next: function(stack) { stack.push("PI"); } },
-        { name: "''''", token: "string", next: function(stack){ stack.push("AposString"); } },
-        { name: "'\"'", token: "string", next: function(stack){ stack.push("QuotString"); } },
-        { name: "Annotation", token: "support.function" },
-        { name: "ModuleDecl", token: "keyword", next: function(stack){ stack.push("Prefix"); } },
-        { name: "OptionDecl", token: "keyword", next: function(stack){ stack.push("_EQName"); } },
-        { name: "AttrTest", token: "support.type" },
-        { name: "Variable",  token: "variable" },
-        { name: "'<![CDATA['", token: cdata, next: function(stack){ stack.push("CData"); } },
-        { name: "IntegerLiteral", token: number },
-        { name: "DecimalLiteral", token: number },
-        { name: "DoubleLiteral", token: number },
-        { name: "Operator", token: "keyword.operator" },
-        { name: "EQName", token: function(val) { return keys.indexOf(val) !== -1 ? "keyword" : "support.function"; } },
-        { name: "'('", token:"lparen" },
-        { name: "')'", token:"rparen" },
-        { name: "Tag", token: "meta.tag", next: function(stack){ stack.push("StartTag"); } },
-        { name: "'}'", token: "text", next: function(stack){ if(stack.length > 1) stack.pop();  } },
-        { name: "'{'", token: "text", next: function(stack){ stack.push("start"); } } //, next: function(stack){ if(stack.length > 1) { stack.pop(); } } }
-      ].concat(keywords),
-      _EQName: [
-        { name: "EQName", token: "text", next: function(stack) { stack.pop(); } }
-      ].concat(ncnames),
-      Prefix: [
-        { name: "NCName", token: "text", next: function(stack) { stack.pop(); } }
-      ].concat(ncnames),
-      StartTag: [
-        { name: "'>'", token: "meta.tag", next: function(stack){ stack.push("TagContent"); } },
-        { name: "QName", token: "entity.other.attribute-name" },
-        { name: "'='", token: "text" },
-        { name: "''''", token: "string", next: function(stack){ stack.push("AposAttr"); } },
-        { name: "'\"'", token: "string", next: function(stack){ stack.push("QuotAttr"); } },
-        { name: "'/>'", token: "meta.tag.r", next: function(stack){ stack.pop(); } }
-      ],
-      TagContent: [
-        { name: "ElementContentChar", token: "text" },
-        { name: "'<![CDATA['", token: cdata, next: function(stack){ stack.push("CData"); } },
-        { name: "'<!--'", token: xmlcomment, next: function(stack){ stack.push("XMLComment"); } },
-        { name: "Tag", token: "meta.tag", next: function(stack){ stack.push("StartTag"); } },
-        { name: "PredefinedEntityRef", token: "constant.language.escape" },
-        { name: "CharRef", token: "constant.language.escape" },
-        { name: "'{{'", token: "text" },
-        { name: "'}}'", token: "text" },
-        { name: "'{'", token: "text", next: function(stack){ stack.push("start"); } },
-        { name: "EndTag", token: "meta.tag", next: function(stack){ stack.pop(); stack.pop(); } }
-      ],
-      AposAttr: [
-        { name: "''''", token: "string", next: function(stack){ stack.pop(); } },
-        { name: "EscapeApos", token: "constant.language.escape" },
-        { name: "AposAttrContentChar", token: "string" },
-        { name: "PredefinedEntityRef", token: "constant.language.escape" },
-        { name: "CharRef", token: "constant.language.escape" },
-        { name: "'{{'", token: "string" },
-        { name: "'}}'", token: "string" },
-        { name: "'{'", token: "text", next: function(stack){ stack.push("start"); } }
-      ],
-      QuotAttr: [
-        { name: "'\"'", token: "string", next: function(stack){ stack.pop(); } },
-        { name: "EscapeQuot", token: "constant.language.escape" },
-        { name: "QuotAttrContentChar", token: "string" },
-        { name: "PredefinedEntityRef", token: "constant.language.escape" },
-        { name: "CharRef", token: "constant.language.escape" },
-        { name: "'{{'", token: "string" },
-        { name: "'}}'", token: "string" },
-        { name: "'{'", token: "text", next: function(stack){ stack.push("start"); } }
-      ],
-      Pragma: [
-        { name: "PragmaContents", token: pragma },
-        { name: "'#'", token: pragma },
-        { name: "'#)'", token: pragma, next: function(stack){ stack.pop(); } }
-      ],
-      Comment: [
-        { name: "CommentContents", token: "comment" },
-        { name: "'(:'", token: "comment", next: function(stack){ stack.push("Comment"); } },
-        { name: "':)'", token: "comment", next: function(stack){ stack.pop(); } }
-      ],
-      CommentDoc: [
-        { name: "DocCommentContents", token: "comment.doc" },
-        { name: "DocTag", token: "comment.doc.tag" },
-        { name: "'(:'", token: "comment.doc", next: function(stack){ stack.push("CommentDoc"); } },
-        { name: "':)'", token: "comment.doc", next: function(stack){ stack.pop(); } }
-      ],
-      XMLComment: [
-        { name: "DirCommentContents", token: xmlcomment },
-        { name: "'-->'", token: xmlcomment, next: function(stack){ stack.pop(); } }
-      ],
-      CData: [
-        { name: "CDataSectionContents", token: cdata },
-        { name: "']]>'", token: cdata, next: function(stack){ stack.pop(); } }
-      ],
-      PI: [
-        { name: "DirPIContents", token: pi },
-        { name: "'?'", token: pi },
-        { name: "'?>'", token: pi, next: function(stack){ stack.pop(); } }
-      ],
-      AposString: [
-        { name: "''''", token: "string", next: function(stack){ stack.pop(); } },
-        { name: "PredefinedEntityRef", token: "constant.language.escape" },
-        { name: "CharRef", token: "constant.language.escape" },
-        { name: "EscapeApos", token: "constant.language.escape" },
-        { name: "AposChar", token: "string" }
-      ],
-      QuotString: [
-        { name: "'\"'", token: "string", next: function(stack){ stack.pop(); } },
-        { name: "PredefinedEntityRef", token: "constant.language.escape" },
-        { name: "CharRef", token: "constant.language.escape" },
-        { name: "EscapeQuot", token: "constant.language.escape" },
-        { name: "QuotChar", token: "string" }
-      ]
-    };
-    
-exports.JSONiqLexer = function() {
-  
-  this.tokens = [];
-  
-  this.getLineTokens = function(line, state, row) {
-    state = (state === "start" || !state) ? '["start"]' : state;
-    var stack = JSON.parse(state);
-    var h = new TokenHandler(line);
-    var tokenizer = new JSONiqTokenizer(line, h);
-    var tokens = [];
-    
-    while(true) {
-      var currentState = stack[stack.length - 1];
-      try {
-        
-        h.tokens = [];
-        tokenizer["parse_" + currentState]();
-        var info = null;
-        
-        if(h.tokens.length > 1 && h.tokens[0].name === "WS") {
-          tokens.push({
-            type: "text",
-            value: h.tokens[0].value
-          });
-          h.tokens.splice(0, 1);
-        }
-        
-        var token = h.tokens[0];
-        var rules  = Rules[currentState];
-        for(var k = 0; k < rules.length; k++) {
-          var rule = Rules[currentState][k];
-          if((typeof(rule.name) === "function" && rule.name(token)) || rule.name === token.name) {
-            info = rule;
-            break;
-          }
-        }
-        
-        if(token.name === "EOF") { break; }
-        if(token.value === "") { throw "Encountered empty string lexical rule."; }
-        
-        tokens.push({
-          type: info === null ? "text" : (typeof(info.token) === "function" ? info.token(token.value) : info.token),
-          value: token.value
-        });
-        
-        if(info && info.next) {
-          info.next(stack);    
-        }
-      
-      } catch(e) {
-        if(e instanceof tokenizer.ParseException) {
-          var index = 0;
-          for(var i=0; i < tokens.length; i++) {
-            index += tokens[i].value.length;
-          }
-          tokens.push({ type: "text", value: line.substring(index) });
-          return {
-            tokens: tokens,
-            state: JSON.stringify(["start"])
-          };
-        } else {
-          throw e;
-        }  
-      }
-    }
-   
-    
-    if(this.tokens[row] !== undefined) {
-      var cachedLine = this.lines[row];
-      var begin = sharedStart([line, cachedLine]);
-      var diff = cachedLine.length - line.length;
-      var idx = 0;
-      var col = 0;
-      for(var i = 0; i < tokens.length; i++) {
-        var token = tokens[i];
-        for(var j = 0; j < this.tokens[row].length; j++) {
-          var semanticToken = this.tokens[row][j];
-          if(
-             ((col + token.value.length) <= begin.length && semanticToken.sc === col && semanticToken.ec === (col + token.value.length)) ||
-             (semanticToken.sc === (col + diff) && semanticToken.ec === (col + token.value.length + diff))
-            ) {
-            idx = i;
-            tokens[i].type = semanticToken.type;
-          }
-        }
-        col += token.value.length;
-      }
-    }
-
-    return {
-      tokens: tokens,
-      state: JSON.stringify(stack)
-    };
-  };
-  
-  function sharedStart(A) {
-    var tem1, tem2, s, A = A.slice(0).sort();
-    tem1 = A[0];
-    s = tem1.length;
-    tem2 = A.pop();
-    while(s && tem2.indexOf(tem1) == -1) {
-        tem1 = tem1.substring(0, --s);
-    }
-    return tem1;
-  }
-};
-});
-
-                                                            define('ace/mode/xquery/JSONiqTokenizer', ['require', 'exports', 'module' ], function(require, exports, module) {
-                                                            var JSONiqTokenizer = exports.JSONiqTokenizer = function JSONiqTokenizer(string, parsingEventHandler)
-                                                            {
-                                                              init(string, parsingEventHandler);
-  var self = this;
-
-  this.ParseException = function(b, e, s, o, x)
-  {
-    var
-      begin = b,
-      end = e,
-      state = s,
-      offending = o,
-      expected = x;
-
-    this.getBegin = function() {return begin;};
-    this.getEnd = function() {return end;};
-    this.getState = function() {return state;};
-    this.getExpected = function() {return expected;};
-    this.getOffending = function() {return offending;};
-
-    this.getMessage = function()
-    {
-      return offending < 0 ? "lexical analysis failed" : "syntax error";
-    };
-  };
-
-  function init(string, parsingEventHandler)
-  {
-    eventHandler = parsingEventHandler;
-    input = string;
-    size = string.length;
-    reset(0, 0, 0);
-  }
-
-  this.getInput = function()
-  {
-    return input;
-  };
-
-  function reset(l, b, e)
-  {
-            b0 = b; e0 = b;
-    l1 = l; b1 = b; e1 = e;
-    end = e;
-    eventHandler.reset(input);
-  }
-
-  this.getOffendingToken = function(e)
-  {
-    var o = e.getOffending();
-    return o >= 0 ? JSONiqTokenizer.TOKEN[o] : null;
-  };
-
-  this.getExpectedTokenSet = function(e)
-  {
-    var expected;
-    if (e.getExpected() < 0)
-    {
-      expected = JSONiqTokenizer.getTokenSet(- e.getState());
-    }
-    else
-    {
-      expected = [JSONiqTokenizer.TOKEN[e.getExpected()]];
-    }
-    return expected;
-  };
-
-  this.getErrorMessage = function(e)
-  {
-    var tokenSet = this.getExpectedTokenSet(e);
-    var found = this.getOffendingToken(e);
-    var prefix = input.substring(0, e.getBegin());
-    var lines = prefix.split("\n");
-    var line = lines.length;
-    var column = lines[line - 1].length + 1;
-    var size = e.getEnd() - e.getBegin();
-    return e.getMessage()
-         + (found == null ? "" : ", found " + found)
-         + "\nwhile expecting "
-         + (tokenSet.length == 1 ? tokenSet[0] : ("[" + tokenSet.join(", ") + "]"))
-         + "\n"
-         + (size == 0 || found != null ? "" : "after successfully scanning " + size + " characters beginning ")
-         + "at line " + line + ", column " + column + ":\n..."
-         + input.substring(e.getBegin(), Math.min(input.length, e.getBegin() + 64))
-         + "...";
-  };
-
-  this.parse_start = function()
-  {
-    eventHandler.startNonterminal("start", e0);
-    lookahead1W(14);                // ModuleDecl | Annotation | OptionDecl | Operator | Variable | Tag | AttrTest |
-    switch (l1)
-    {
-    case 55:                        // '<![CDATA['
-      shift(55);                    // '<![CDATA['
-      break;
-    case 54:                        // '<!--'
-      shift(54);                    // '<!--'
-      break;
-    case 56:                        // '<?'
-      shift(56);                    // '<?'
-      break;
-    case 40:                        // '(#'
-      shift(40);                    // '(#'
-      break;
-    case 42:                        // '(:~'
-      shift(42);                    // '(:~'
-      break;
-    case 41:                        // '(:'
-      shift(41);                    // '(:'
-      break;
-    case 35:                        // '"'
-      shift(35);                    // '"'
-      break;
-    case 38:                        // "'"
-      shift(38);                    // "'"
-      break;
-    case 274:                       // '}'
-      shift(274);                   // '}'
-      break;
-    case 271:                       // '{'
-      shift(271);                   // '{'
-      break;
-    case 39:                        // '('
-      shift(39);                    // '('
-      break;
-    case 43:                        // ')'
-      shift(43);                    // ')'
-      break;
-    case 49:                        // '/'
-      shift(49);                    // '/'
-      break;
-    case 62:                        // '['
-      shift(62);                    // '['
-      break;
-    case 63:                        // ']'
-      shift(63);                    // ']'
-      break;
-    case 46:                        // ','
-      shift(46);                    // ','
-      break;
-    case 48:                        // '.'
-      shift(48);                    // '.'
-      break;
-    case 53:                        // ';'
-      shift(53);                    // ';'
-      break;
-    case 51:                        // ':'
-      shift(51);                    // ':'
-      break;
-    case 34:                        // '!'
-      shift(34);                    // '!'
-      break;
-    case 273:                       // '|'
-      shift(273);                   // '|'
-      break;
-    case 2:                         // Annotation
-      shift(2);                     // Annotation
-      break;
-    case 1:                         // ModuleDecl
-      shift(1);                     // ModuleDecl
-      break;
-    case 3:                         // OptionDecl
-      shift(3);                     // OptionDecl
-      break;
-    case 12:                        // AttrTest
-      shift(12);                    // AttrTest
-      break;
-    case 13:                        // Wildcard
-      shift(13);                    // Wildcard
-      break;
-    case 15:                        // IntegerLiteral
-      shift(15);                    // IntegerLiteral
-      break;
-    case 16:                        // DecimalLiteral
-      shift(16);                    // DecimalLiteral
-      break;
-    case 17:                        // DoubleLiteral
-      shift(17);                    // DoubleLiteral
-      break;
-    case 5:                         // Variable
-      shift(5);                     // Variable
-      break;
-    case 6:                         // Tag
-      shift(6);                     // Tag
-      break;
-    case 4:                         // Operator
-      shift(4);                     // Operator
-      break;
-    case 33:                        // EOF
-      shift(33);                    // EOF
-      break;
-    default:
-      parse_EQName();
-    }
-    eventHandler.endNonterminal("start", e0);
-  };
-
-  this.parse_StartTag = function()
-  {
-    eventHandler.startNonterminal("StartTag", e0);
-    lookahead1W(8);                 // QName | S^WS | EOF | '"' | "'" | '/>' | '=' | '>'
-    switch (l1)
-    {
-    case 58:                        // '>'
-      shift(58);                    // '>'
-      break;
-    case 50:                        // '/>'
-      shift(50);                    // '/>'
-      break;
-    case 27:                        // QName
-      shift(27);                    // QName
-      break;
-    case 57:                        // '='
-      shift(57);                    // '='
-      break;
-    case 35:                        // '"'
-      shift(35);                    // '"'
-      break;
-    case 38:                        // "'"
-      shift(38);                    // "'"
-      break;
-    default:
-      shift(33);                    // EOF
-    }
-    eventHandler.endNonterminal("StartTag", e0);
-  };
-
-  this.parse_TagContent = function()
-  {
-    eventHandler.startNonterminal("TagContent", e0);
-    lookahead1(11);                 // Tag | EndTag | PredefinedEntityRef | ElementContentChar | CharRef | EOF |
-    switch (l1)
-    {
-    case 23:                        // ElementContentChar
-      shift(23);                    // ElementContentChar
-      break;
-    case 6:                         // Tag
-      shift(6);                     // Tag
-      break;
-    case 7:                         // EndTag
-      shift(7);                     // EndTag
-      break;
-    case 55:                        // '<![CDATA['
-      shift(55);                    // '<![CDATA['
-      break;
-    case 54:                        // '<!--'
-      shift(54);                    // '<!--'
-      break;
-    case 18:                        // PredefinedEntityRef
-      shift(18);                    // PredefinedEntityRef
-      break;
-    case 29:                        // CharRef
-      shift(29);                    // CharRef
-      break;
-    case 272:                       // '{{'
-      shift(272);                   // '{{'
-      break;
-    case 275:                       // '}}'
-      shift(275);                   // '}}'
-      break;
-    case 271:                       // '{'
-      shift(271);                   // '{'
-      break;
-    default:
-      shift(33);                    // EOF
-    }
-    eventHandler.endNonterminal("TagContent", e0);
-  };
-
-  this.parse_AposAttr = function()
-  {
-    eventHandler.startNonterminal("AposAttr", e0);
-    lookahead1(10);                 // PredefinedEntityRef | EscapeApos | AposAttrContentChar | CharRef | EOF | "'" |
-    switch (l1)
-    {
-    case 20:                        // EscapeApos
-      shift(20);                    // EscapeApos
-      break;
-    case 25:                        // AposAttrContentChar
-      shift(25);                    // AposAttrContentChar
-      break;
-    case 18:                        // PredefinedEntityRef
-      shift(18);                    // PredefinedEntityRef
-      break;
-    case 29:                        // CharRef
-      shift(29);                    // CharRef
-      break;
-    case 272:                       // '{{'
-      shift(272);                   // '{{'
-      break;
-    case 275:                       // '}}'
-      shift(275);                   // '}}'
-      break;
-    case 271:                       // '{'
-      shift(271);                   // '{'
-      break;
-    case 38:                        // "'"
-      shift(38);                    // "'"
-      break;
-    default:
-      shift(33);                    // EOF
-    }
-    eventHandler.endNonterminal("AposAttr", e0);
-  };
-
-  this.parse_QuotAttr = function()
-  {
-    eventHandler.startNonterminal("QuotAttr", e0);
-    lookahead1(9);                  // PredefinedEntityRef | EscapeQuot | QuotAttrContentChar | CharRef | EOF | '"' |
-    switch (l1)
-    {
-    case 19:                        // EscapeQuot
-      shift(19);                    // EscapeQuot
-      break;
-    case 24:                        // QuotAttrContentChar
-      shift(24);                    // QuotAttrContentChar
-      break;
-    case 18:                        // PredefinedEntityRef
-      shift(18);                    // PredefinedEntityRef
-      break;
-    case 29:                        // CharRef
-      shift(29);                    // CharRef
-      break;
-    case 272:                       // '{{'
-      shift(272);                   // '{{'
-      break;
-    case 275:                       // '}}'
-      shift(275);                   // '}}'
-      break;
-    case 271:                       // '{'
-      shift(271);                   // '{'
-      break;
-    case 35:                        // '"'
-      shift(35);                    // '"'
-      break;
-    default:
-      shift(33);                    // EOF
-    }
-    eventHandler.endNonterminal("QuotAttr", e0);
-  };
-
-  this.parse_CData = function()
-  {
-    eventHandler.startNonterminal("CData", e0);
-    lookahead1(1);                  // CDataSectionContents | EOF | ']]>'
-    switch (l1)
-    {
-    case 11:                        // CDataSectionContents
-      shift(11);                    // CDataSectionContents
-      break;
-    case 64:                        // ']]>'
-      shift(64);                    // ']]>'
-      break;
-    default:
-      shift(33);                    // EOF
-    }
-    eventHandler.endNonterminal("CData", e0);
-  };
-
-  this.parse_XMLComment = function()
-  {
-    eventHandler.startNonterminal("XMLComment", e0);
-    lookahead1(0);                  // DirCommentContents | EOF | '-->'
-    switch (l1)
-    {
-    case 9:                         // DirCommentContents
-      shift(9);                     // DirCommentContents
-      break;
-    case 47:                        // '-->'
-      shift(47);                    // '-->'
-      break;
-    default:
-      shift(33);                    // EOF
-    }
-    eventHandler.endNonterminal("XMLComment", e0);
-  };
-
-  this.parse_PI = function()
-  {
-    eventHandler.startNonterminal("PI", e0);
-    lookahead1(3);                  // DirPIContents | EOF | '?' | '?>'
-    switch (l1)
-    {
-    case 10:                        // DirPIContents
-      shift(10);                    // DirPIContents
-      break;
-    case 59:                        // '?'
-      shift(59);                    // '?'
-      break;
-    case 60:                        // '?>'
-      shift(60);                    // '?>'
-      break;
-    default:
-      shift(33);                    // EOF
-    }
-    eventHandler.endNonterminal("PI", e0);
-  };
-
-  this.parse_Pragma = function()
-  {
-    eventHandler.startNonterminal("Pragma", e0);
-    lookahead1(2);                  // PragmaContents | EOF | '#' | '#)'
-    switch (l1)
-    {
-    case 8:                         // PragmaContents
-      shift(8);                     // PragmaContents
-      break;
-    case 36:                        // '#'
-      shift(36);                    // '#'
-      break;
-    case 37:                        // '#)'
-      shift(37);                    // '#)'
-      break;
-    default:
-      shift(33);                    // EOF
-    }
-    eventHandler.endNonterminal("Pragma", e0);
-  };
-
-  this.parse_Comment = function()
-  {
-    eventHandler.startNonterminal("Comment", e0);
-    lookahead1(4);                  // CommentContents | EOF | '(:' | ':)'
-    switch (l1)
-    {
-    case 52:                        // ':)'
-      shift(52);                    // ':)'
-      break;
-    case 41:                        // '(:'
-      shift(41);                    // '(:'
-      break;
-    case 30:                        // CommentContents
-      shift(30);                    // CommentContents
-      break;
-    default:
-      shift(33);                    // EOF
-    }
-    eventHandler.endNonterminal("Comment", e0);
-  };
-
-  this.parse_CommentDoc = function()
-  {
-    eventHandler.startNonterminal("CommentDoc", e0);
-    lookahead1(5);                  // DocTag | DocCommentContents | EOF | '(:' | ':)'
-    switch (l1)
-    {
-    case 31:                        // DocTag
-      shift(31);                    // DocTag
-      break;
-    case 32:                        // DocCommentContents
-      shift(32);                    // DocCommentContents
-      break;
-    case 52:                        // ':)'
-      shift(52);                    // ':)'
-      break;
-    case 41:                        // '(:'
-      shift(41);                    // '(:'
-      break;
-    default:
-      shift(33);                    // EOF
-    }
-    eventHandler.endNonterminal("CommentDoc", e0);
-  };
-
-  this.parse_QuotString = function()
-  {
-    eventHandler.startNonterminal("QuotString", e0);
-    lookahead1(6);                  // PredefinedEntityRef | EscapeQuot | QuotChar | CharRef | EOF | '"'
-    switch (l1)
-    {
-    case 18:                        // PredefinedEntityRef
-      shift(18);                    // PredefinedEntityRef
-      break;
-    case 29:                        // CharRef
-      shift(29);                    // CharRef
-      break;
-    case 19:                        // EscapeQuot
-      shift(19);                    // EscapeQuot
-      break;
-    case 21:                        // QuotChar
-      shift(21);                    // QuotChar
-      break;
-    case 35:                        // '"'
-      shift(35);                    // '"'
-      break;
-    default:
-      shift(33);                    // EOF
-    }
-    eventHandler.endNonterminal("QuotString", e0);
-  };
-
-  this.parse_AposString = function()
-  {
-    eventHandler.startNonterminal("AposString", e0);
-    lookahead1(7);                  // PredefinedEntityRef | EscapeApos | AposChar | CharRef | EOF | "'"
-    switch (l1)
-    {
-    case 18:                        // PredefinedEntityRef
-      shift(18);                    // PredefinedEntityRef
-      break;
-    case 29:                        // CharRef
-      shift(29);                    // CharRef
-      break;
-    case 20:                        // EscapeApos
-      shift(20);                    // EscapeApos
-      break;
-    case 22:                        // AposChar
-      shift(22);                    // AposChar
-      break;
-    case 38:                        // "'"
-      shift(38);                    // "'"
-      break;
-    default:
-      shift(33);                    // EOF
-    }
-    eventHandler.endNonterminal("AposString", e0);
-  };
-
-  this.parse_Prefix = function()
-  {
-    eventHandler.startNonterminal("Prefix", e0);
-    lookahead1W(13);                // NCName^Token | S^WS | 'after' | 'allowing' | 'ancestor' | 'ancestor-or-self' |
-    whitespace();
-    parse_NCName();
-    eventHandler.endNonterminal("Prefix", e0);
-  };
-
-  this.parse__EQName = function()
-  {
-    eventHandler.startNonterminal("_EQName", e0);
-    lookahead1W(12);                // EQName^Token | S^WS | 'after' | 'allowing' | 'ancestor' | 'ancestor-or-self' |
-    whitespace();
-    parse_EQName();
-    eventHandler.endNonterminal("_EQName", e0);
-  };
-
-  function parse_EQName()
-  {
-    eventHandler.startNonterminal("EQName", e0);
-    switch (l1)
-    {
-    case 77:                        // 'attribute'
-      shift(77);                    // 'attribute'
-      break;
-    case 91:                        // 'comment'
-      shift(91);                    // 'comment'
-      break;
-    case 115:                       // 'document-node'
-      shift(115);                   // 'document-node'
-      break;
-    case 116:                       // 'element'
-      shift(116);                   // 'element'
-      break;
-    case 119:                       // 'empty-sequence'
-      shift(119);                   // 'empty-sequence'
-      break;
-    case 140:                       // 'function'
-      shift(140);                   // 'function'
-      break;
-    case 147:                       // 'if'
-      shift(147);                   // 'if'
-      break;
-    case 160:                       // 'item'
-      shift(160);                   // 'item'
-      break;
-    case 180:                       // 'namespace-node'
-      shift(180);                   // 'namespace-node'
-      break;
-    case 186:                       // 'node'
-      shift(186);                   // 'node'
-      break;
-    case 211:                       // 'processing-instruction'
-      shift(211);                   // 'processing-instruction'
-      break;
-    case 221:                       // 'schema-attribute'
-      shift(221);                   // 'schema-attribute'
-      break;
-    case 222:                       // 'schema-element'
-      shift(222);                   // 'schema-element'
-      break;
-    case 238:                       // 'switch'
-      shift(238);                   // 'switch'
-      break;
-    case 239:                       // 'text'
-      shift(239);                   // 'text'
-      break;
-    case 248:                       // 'typeswitch'
-      shift(248);                   // 'typeswitch'
-      break;
-    default:
-      parse_FunctionName();
-    }
-    eventHandler.endNonterminal("EQName", e0);
-  }
-
-  function parse_FunctionName()
-  {
-    eventHandler.startNonterminal("FunctionName", e0);
-    switch (l1)
-    {
-    case 14:                        // EQName^Token
-      shift(14);                    // EQName^Token
-      break;
-    case 65:                        // 'after'
-      shift(65);                    // 'after'
-      break;
-    case 68:                        // 'ancestor'
-      shift(68);                    // 'ancestor'
-      break;
-    case 69:                        // 'ancestor-or-self'
-      shift(69);                    // 'ancestor-or-self'
-      break;
-    case 70:                        // 'and'
-      shift(70);                    // 'and'
-      break;
-    case 74:                        // 'as'
-      shift(74);                    // 'as'
-      break;
-    case 75:                        // 'ascending'
-      shift(75);                    // 'ascending'
-      break;
-    case 79:                        // 'before'
-      shift(79);                    // 'before'
-      break;
-    case 83:                        // 'case'
-      shift(83);                    // 'case'
-      break;
-    case 84:                        // 'cast'
-      shift(84);                    // 'cast'
-      break;
-    case 85:                        // 'castable'
-      shift(85);                    // 'castable'
-      break;
-    case 88:                        // 'child'
-      shift(88);                    // 'child'
-      break;
-    case 89:                        // 'collation'
-      shift(89);                    // 'collation'
-      break;
-    case 98:                        // 'copy'
-      shift(98);                    // 'copy'
-      break;
-    case 100:                       // 'count'
-      shift(100);                   // 'count'
-      break;
-    case 103:                       // 'declare'
-      shift(103);                   // 'declare'
-      break;
-    case 104:                       // 'default'
-      shift(104);                   // 'default'
-      break;
-    case 105:                       // 'delete'
-      shift(105);                   // 'delete'
-      break;
-    case 106:                       // 'descendant'
-      shift(106);                   // 'descendant'
-      break;
-    case 107:                       // 'descendant-or-self'
-      shift(107);                   // 'descendant-or-self'
-      break;
-    case 108:                       // 'descending'
-      shift(108);                   // 'descending'
-      break;
-    case 113:                       // 'div'
-      shift(113);                   // 'div'
-      break;
-    case 114:                       // 'document'
-      shift(114);                   // 'document'
-      break;
-    case 117:                       // 'else'
-      shift(117);                   // 'else'
-      break;
-    case 118:                       // 'empty'
-      shift(118);                   // 'empty'
-      break;
-    case 121:                       // 'end'
-      shift(121);                   // 'end'
-      break;
-    case 123:                       // 'eq'
-      shift(123);                   // 'eq'
-      break;
-    case 124:                       // 'every'
-      shift(124);                   // 'every'
-      break;
-    case 126:                       // 'except'
-      shift(126);                   // 'except'
-      break;
-    case 129:                       // 'first'
-      shift(129);                   // 'first'
-      break;
-    case 130:                       // 'following'
-      shift(130);                   // 'following'
-      break;
-    case 131:                       // 'following-sibling'
-      shift(131);                   // 'following-sibling'
-      break;
-    case 132:                       // 'for'
-      shift(132);                   // 'for'
-      break;
-    case 141:                       // 'ge'
-      shift(141);                   // 'ge'
-      break;
-    case 143:                       // 'group'
-      shift(143);                   // 'group'
-      break;
-    case 145:                       // 'gt'
-      shift(145);                   // 'gt'
-      break;
-    case 146:                       // 'idiv'
-      shift(146);                   // 'idiv'
-      break;
-    case 148:                       // 'import'
-      shift(148);                   // 'import'
-      break;
-    case 154:                       // 'insert'
-      shift(154);                   // 'insert'
-      break;
-    case 155:                       // 'instance'
-      shift(155);                   // 'instance'
-      break;
-    case 157:                       // 'intersect'
-      shift(157);                   // 'intersect'
-      break;
-    case 158:                       // 'into'
-      shift(158);                   // 'into'
-      break;
-    case 159:                       // 'is'
-      shift(159);                   // 'is'
-      break;
-    case 165:                       // 'last'
-      shift(165);                   // 'last'
-      break;
-    case 167:                       // 'le'
-      shift(167);                   // 'le'
-      break;
-    case 169:                       // 'let'
-      shift(169);                   // 'let'
-      break;
-    case 173:                       // 'lt'
-      shift(173);                   // 'lt'
-      break;
-    case 175:                       // 'mod'
-      shift(175);                   // 'mod'
-      break;
-    case 176:                       // 'modify'
-      shift(176);                   // 'modify'
-      break;
-    case 177:                       // 'module'
-      shift(177);                   // 'module'
-      break;
-    case 179:                       // 'namespace'
-      shift(179);                   // 'namespace'
-      break;
-    case 181:                       // 'ne'
-      shift(181);                   // 'ne'
-      break;
-    case 193:                       // 'only'
-      shift(193);                   // 'only'
-      break;
-    case 195:                       // 'or'
-      shift(195);                   // 'or'
-      break;
-    case 196:                       // 'order'
-      shift(196);                   // 'order'
-      break;
-    case 197:                       // 'ordered'
-      shift(197);                   // 'ordered'
-      break;
-    case 201:                       // 'parent'
-      shift(201);                   // 'parent'
-      break;
-    case 207:                       // 'preceding'
-      shift(207);                   // 'preceding'
-      break;
-    case 208:                       // 'preceding-sibling'
-      shift(208);                   // 'preceding-sibling'
-      break;
-    case 213:                       // 'rename'
-      shift(213);                   // 'rename'
-      break;
-    case 214:                       // 'replace'
-      shift(214);                   // 'replace'
-      break;
-    case 215:                       // 'return'
-      shift(215);                   // 'return'
-      break;
-    case 219:                       // 'satisfies'
-      shift(219);                   // 'satisfies'
-      break;
-    case 224:                       // 'self'
-      shift(224);                   // 'self'
-      break;
-    case 230:                       // 'some'
-      shift(230);                   // 'some'
-      break;
-    case 231:                       // 'stable'
-      shift(231);                   // 'stable'
-      break;
-    case 232:                       // 'start'
-      shift(232);                   // 'start'
-      break;
-    case 243:                       // 'to'
-      shift(243);                   // 'to'
-      break;
-    case 244:                       // 'treat'
-      shift(244);                   // 'treat'
-      break;
-    case 245:                       // 'try'
-      shift(245);                   // 'try'
-      break;
-    case 249:                       // 'union'
-      shift(249);                   // 'union'
-      break;
-    case 251:                       // 'unordered'
-      shift(251);                   // 'unordered'
-      break;
-    case 255:                       // 'validate'
-      shift(255);                   // 'validate'
-      break;
-    case 261:                       // 'where'
-      shift(261);                   // 'where'
-      break;
-    case 265:                       // 'with'
-      shift(265);                   // 'with'
-      break;
-    case 269:                       // 'xquery'
-      shift(269);                   // 'xquery'
-      break;
-    case 67:                        // 'allowing'
-      shift(67);                    // 'allowing'
-      break;
-    case 76:                        // 'at'
-      shift(76);                    // 'at'
-      break;
-    case 78:                        // 'base-uri'
-      shift(78);                    // 'base-uri'
-      break;
-    case 80:                        // 'boundary-space'
-      shift(80);                    // 'boundary-space'
-      break;
-    case 81:                        // 'break'
-      shift(81);                    // 'break'
-      break;
-    case 86:                        // 'catch'
-      shift(86);                    // 'catch'
-      break;
-    case 93:                        // 'construction'
-      shift(93);                    // 'construction'
-      break;
-    case 96:                        // 'context'
-      shift(96);                    // 'context'
-      break;
-    case 97:                        // 'continue'
-      shift(97);                    // 'continue'
-      break;
-    case 99:                        // 'copy-namespaces'
-      shift(99);                    // 'copy-namespaces'
-      break;
-    case 101:                       // 'decimal-format'
-      shift(101);                   // 'decimal-format'
-      break;
-    case 120:                       // 'encoding'
-      shift(120);                   // 'encoding'
-      break;
-    case 127:                       // 'exit'
-      shift(127);                   // 'exit'
-      break;
-    case 128:                       // 'external'
-      shift(128);                   // 'external'
-      break;
-    case 136:                       // 'ft-option'
-      shift(136);                   // 'ft-option'
-      break;
-    case 149:                       // 'in'
-      shift(149);                   // 'in'
-      break;
-    case 150:                       // 'index'
-      shift(150);                   // 'index'
-      break;
-    case 156:                       // 'integrity'
-      shift(156);                   // 'integrity'
-      break;
-    case 166:                       // 'lax'
-      shift(166);                   // 'lax'
-      break;
-    case 187:                       // 'nodes'
-      shift(187);                   // 'nodes'
-      break;
-    case 194:                       // 'option'
-      shift(194);                   // 'option'
-      break;
-    case 198:                       // 'ordering'
-      shift(198);                   // 'ordering'
-      break;
-    case 217:                       // 'revalidation'
-      shift(217);                   // 'revalidation'
-      break;
-    case 220:                       // 'schema'
-      shift(220);                   // 'schema'
-      break;
-    case 223:                       // 'score'
-      shift(223);                   // 'score'
-      break;
-    case 229:                       // 'sliding'
-      shift(229);                   // 'sliding'
-      break;
-    case 235:                       // 'strict'
-      shift(235);                   // 'strict'
-      break;
-    case 246:                       // 'tumbling'
-      shift(246);                   // 'tumbling'
-      break;
-    case 247:                       // 'type'
-      shift(247);                   // 'type'
-      break;
-    case 252:                       // 'updating'
-      shift(252);                   // 'updating'
-      break;
-    case 256:                       // 'value'
-      shift(256);                   // 'value'
-      break;
-    case 257:                       // 'variable'
-      shift(257);                   // 'variable'
-      break;
-    case 258:                       // 'version'
-      shift(258);                   // 'version'
-      break;
-    case 262:                       // 'while'
-      shift(262);                   // 'while'
-      break;
-    case 92:                        // 'constraint'
-      shift(92);                    // 'constraint'
-      break;
-    case 171:                       // 'loop'
-      shift(171);                   // 'loop'
-      break;
-    default:
-      shift(216);                   // 'returning'
-    }
-    eventHandler.endNonterminal("FunctionName", e0);
-  }
-
-  function parse_NCName()
-  {
-    eventHandler.startNonterminal("NCName", e0);
-    switch (l1)
-    {
-    case 26:                        // NCName^Token
-      shift(26);                    // NCName^Token
-      break;
-    case 65:                        // 'after'
-      shift(65);                    // 'after'
-      break;
-    case 70:                        // 'and'
-      shift(70);                    // 'and'
-      break;
-    case 74:                        // 'as'
-      shift(74);                    // 'as'
-      break;
-    case 75:                        // 'ascending'
-      shift(75);                    // 'ascending'
-      break;
-    case 79:                        // 'before'
-      shift(79);                    // 'before'
-      break;
-    case 83:                        // 'case'
-      shift(83);                    // 'case'
-      break;
-    case 84:                        // 'cast'
-      shift(84);                    // 'cast'
-      break;
-    case 85:                        // 'castable'
-      shift(85);                    // 'castable'
-      break;
-    case 89:                        // 'collation'
-      shift(89);                    // 'collation'
-      break;
-    case 100:                       // 'count'
-      shift(100);                   // 'count'
-      break;
-    case 104:                       // 'default'
-      shift(104);                   // 'default'
-      break;
-    case 108:                       // 'descending'
-      shift(108);                   // 'descending'
-      break;
-    case 113:                       // 'div'
-      shift(113);                   // 'div'
-      break;
-    case 117:                       // 'else'
-      shift(117);                   // 'else'
-      break;
-    case 118:                       // 'empty'
-      shift(118);                   // 'empty'
-      break;
-    case 121:                       // 'end'
-      shift(121);                   // 'end'
-      break;
-    case 123:                       // 'eq'
-      shift(123);                   // 'eq'
-      break;
-    case 126:                       // 'except'
-      shift(126);                   // 'except'
-      break;
-    case 132:                       // 'for'
-      shift(132);                   // 'for'
-      break;
-    case 141:                       // 'ge'
-      shift(141);                   // 'ge'
-      break;
-    case 143:                       // 'group'
-      shift(143);                   // 'group'
-      break;
-    case 145:                       // 'gt'
-      shift(145);                   // 'gt'
-      break;
-    case 146:                       // 'idiv'
-      shift(146);                   // 'idiv'
-      break;
-    case 155:                       // 'instance'
-      shift(155);                   // 'instance'
-      break;
-    case 157:                       // 'intersect'
-      shift(157);                   // 'intersect'
-      break;
-    case 158:                       // 'into'
-      shift(158);                   // 'into'
-      break;
-    case 159:                       // 'is'
-      shift(159);                   // 'is'
-      break;
-    case 167:                       // 'le'
-      shift(167);                   // 'le'
-      break;
-    case 169:                       // 'let'
-      shift(169);                   // 'let'
-      break;
-    case 173:                       // 'lt'
-      shift(173);                   // 'lt'
-      break;
-    case 175:                       // 'mod'
-      shift(175);                   // 'mod'
-      break;
-    case 176:                       // 'modify'
-      shift(176);                   // 'modify'
-      break;
-    case 181:                       // 'ne'
-      shift(181);                   // 'ne'
-      break;
-    case 193:                       // 'only'
-      shift(193);                   // 'only'
-      break;
-    case 195:                       // 'or'
-      shift(195);                   // 'or'
-      break;
-    case 196:                       // 'order'
-      shift(196);                   // 'order'
-      break;
-    case 215:                       // 'return'
-      shift(215);                   // 'return'
-      break;
-    case 219:                       // 'satisfies'
-      shift(219);                   // 'satisfies'
-      break;
-    case 231:                       // 'stable'
-      shift(231);                   // 'stable'
-      break;
-    case 232:                       // 'start'
-      shift(232);                   // 'start'
-      break;
-    case 243:                       // 'to'
-      shift(243);                   // 'to'
-      break;
-    case 244:                       // 'treat'
-      shift(244);                   // 'treat'
-      break;
-    case 249:                       // 'union'
-      shift(249);                   // 'union'
-      break;
-    case 261:                       // 'where'
-      shift(261);                   // 'where'
-      break;
-    case 265:                       // 'with'
-      shift(265);                   // 'with'
-      break;
-    case 68:                        // 'ancestor'
-      shift(68);                    // 'ancestor'
-      break;
-    case 69:                        // 'ancestor-or-self'
-      shift(69);                    // 'ancestor-or-self'
-      break;
-    case 77:                        // 'attribute'
-      shift(77);                    // 'attribute'
-      break;
-    case 88:                        // 'child'
-      shift(88);                    // 'child'
-      break;
-    case 91:                        // 'comment'
-      shift(91);                    // 'comment'
-      break;
-    case 98:                        // 'copy'
-      shift(98);                    // 'copy'
-      break;
-    case 103:                       // 'declare'
-      shift(103);                   // 'declare'
-      break;
-    case 105:                       // 'delete'
-      shift(105);                   // 'delete'
-      break;
-    case 106:                       // 'descendant'
-      shift(106);                   // 'descendant'
-      break;
-    case 107:                       // 'descendant-or-self'
-      shift(107);                   // 'descendant-or-self'
-      break;
-    case 114:                       // 'document'
-      shift(114);                   // 'document'
-      break;
-    case 115:                       // 'document-node'
-      shift(115);                   // 'document-node'
-      break;
-    case 116:                       // 'element'
-      shift(116);                   // 'element'
-      break;
-    case 119:                       // 'empty-sequence'
-      shift(119);                   // 'empty-sequence'
-      break;
-    case 124:                       // 'every'
-      shift(124);                   // 'every'
-      break;
-    case 129:                       // 'first'
-      shift(129);                   // 'first'
-      break;
-    case 130:                       // 'following'
-      shift(130);                   // 'following'
-      break;
-    case 131:                       // 'following-sibling'
-      shift(131);                   // 'following-sibling'
-      break;
-    case 140:                       // 'function'
-      shift(140);                   // 'function'
-      break;
-    case 147:                       // 'if'
-      shift(147);                   // 'if'
-      break;
-    case 148:                       // 'import'
-      shift(148);                   // 'import'
-      break;
-    case 154:                       // 'insert'
-      shift(154);                   // 'insert'
-      break;
-    case 160:                       // 'item'
-      shift(160);                   // 'item'
-      break;
-    case 165:                       // 'last'
-      shift(165);                   // 'last'
-      break;
-    case 177:                       // 'module'
-      shift(177);                   // 'module'
-      break;
-    case 179:                       // 'namespace'
-      shift(179);                   // 'namespace'
-      break;
-    case 180:                       // 'namespace-node'
-      shift(180);                   // 'namespace-node'
-      break;
-    case 186:                       // 'node'
-      shift(186);                   // 'node'
-      break;
-    case 197:                       // 'ordered'
-      shift(197);                   // 'ordered'
-      break;
-    case 201:                       // 'parent'
-      shift(201);                   // 'parent'
-      break;
-    case 207:                       // 'preceding'
-      shift(207);                   // 'preceding'
-      break;
-    case 208:                       // 'preceding-sibling'
-      shift(208);                   // 'preceding-sibling'
-      break;
-    case 211:                       // 'processing-instruction'
-      shift(211);                   // 'processing-instruction'
-      break;
-    case 213:                       // 'rename'
-      shift(213);                   // 'rename'
-      break;
-    case 214:                       // 'replace'
-      shift(214);                   // 'replace'
-      break;
-    case 221:                       // 'schema-attribute'
-      shift(221);                   // 'schema-attribute'
-      break;
-    case 222:                       // 'schema-element'
-      shift(222);                   // 'schema-element'
-      break;
-    case 224:                       // 'self'
-      shift(224);                   // 'self'
-      break;
-    case 230:                       // 'some'
-      shift(230);                   // 'some'
-      break;
-    case 238:                       // 'switch'
-      shift(238);                   // 'switch'
-      break;
-    case 239:                       // 'text'
-      shift(239);                   // 'text'
-      break;
-    case 245:                       // 'try'
-      shift(245);                   // 'try'
-      break;
-    case 248:                       // 'typeswitch'
-      shift(248);                   // 'typeswitch'
-      break;
-    case 251:                       // 'unordered'
-      shift(251);                   // 'unordered'
-      break;
-    case 255:                       // 'validate'
-      shift(255);                   // 'validate'
-      break;
-    case 257:                       // 'variable'
-      shift(257);                   // 'variable'
-      break;
-    case 269:                       // 'xquery'
-      shift(269);                   // 'xquery'
-      break;
-    case 67:                        // 'allowing'
-      shift(67);                    // 'allowing'
-      break;
-    case 76:                        // 'at'
-      shift(76);                    // 'at'
-      break;
-    case 78:                        // 'base-uri'
-      shift(78);                    // 'base-uri'
-      break;
-    case 80:                        // 'boundary-space'
-      shift(80);                    // 'boundary-space'
-      break;
-    case 81:                        // 'break'
-      shift(81);                    // 'break'
-      break;
-    case 86:                        // 'catch'
-      shift(86);                    // 'catch'
-      break;
-    case 93:                        // 'construction'
-      shift(93);                    // 'construction'
-      break;
-    case 96:                        // 'context'
-      shift(96);                    // 'context'
-      break;
-    case 97:                        // 'continue'
-      shift(97);                    // 'continue'
-      break;
-    case 99:                        // 'copy-namespaces'
-      shift(99);                    // 'copy-namespaces'
-      break;
-    case 101:                       // 'decimal-format'
-      shift(101);                   // 'decimal-format'
-      break;
-    case 120:                       // 'encoding'
-      shift(120);                   // 'encoding'
-      break;
-    case 127:                       // 'exit'
-      shift(127);                   // 'exit'
-      break;
-    case 128:                       // 'external'
-      shift(128);                   // 'external'
-      break;
-    case 136:                       // 'ft-option'
-      shift(136);                   // 'ft-option'
-      break;
-    case 149:                       // 'in'
-      shift(149);                   // 'in'
-      break;
-    case 150:                       // 'index'
-      shift(150);                   // 'index'
-      break;
-    case 156:                       // 'integrity'
-      shift(156);                   // 'integrity'
-      break;
-    case 166:                       // 'lax'
-      shift(166);                   // 'lax'
-      break;
-    case 187:                       // 'nodes'
-      shift(187);                   // 'nodes'
-      break;
-    case 194:                       // 'option'
-      shift(194);                   // 'option'
-      break;
-    case 198:                       // 'ordering'
-      shift(198);                   // 'ordering'
-      break;
-    case 217:                       // 'revalidation'
-      shift(217);                   // 'revalidation'
-      break;
-    case 220:                       // 'schema'
-      shift(220);                   // 'schema'
-      break;
-    case 223:                       // 'score'
-      shift(223);                   // 'score'
-      break;
-    case 229:                       // 'sliding'
-      shift(229);                   // 'sliding'
-      break;
-    case 235:                       // 'strict'
-      shift(235);                   // 'strict'
-      break;
-    case 246:                       // 'tumbling'
-      shift(246);                   // 'tumbling'
-      break;
-    case 247:                       // 'type'
-      shift(247);                   // 'type'
-      break;
-    case 252:                       // 'updating'
-      shift(252);                   // 'updating'
-      break;
-    case 256:                       // 'value'
-      shift(256);                   // 'value'
-      break;
-    case 258:                       // 'version'
-      shift(258);                   // 'version'
-      break;
-    case 262:                       // 'while'
-      shift(262);                   // 'while'
-      break;
-    case 92:                        // 'constraint'
-      shift(92);                    // 'constraint'
-      break;
-    case 171:                       // 'loop'
-      shift(171);                   // 'loop'
-      break;
-    default:
-      shift(216);                   // 'returning'
-    }
-    eventHandler.endNonterminal("NCName", e0);
-  }
-
-  function shift(t)
-  {
-    if (l1 == t)
-    {
-      whitespace();
-      eventHandler.terminal(JSONiqTokenizer.TOKEN[l1], b1, e1 > size ? size : e1);
-      b0 = b1; e0 = e1; l1 = 0;
-    }
-    else
-    {
-      error(b1, e1, 0, l1, t);
-    }
-  }
-
-  function whitespace()
-  {
-    if (e0 != b1)
-    {
-      b0 = e0;
-      e0 = b1;
-      eventHandler.whitespace(b0, e0);
-    }
-  }
-
-  function matchW(set)
-  {
-    var code;
-    for (;;)
-    {
-      code = match(set);
-      if (code != 28)               // S^WS
-      {
-        break;
-      }
-    }
-    return code;
-  }
-
-  function lookahead1W(set)
-  {
-    if (l1 == 0)
-    {
-      l1 = matchW(set);
-      b1 = begin;
-      e1 = end;
-    }
-  }
-
-  function lookahead1(set)
-  {
-    if (l1 == 0)
-    {
-      l1 = match(set);
-      b1 = begin;
-      e1 = end;
-    }
-  }
-
-  function error(b, e, s, l, t)
-  {
-    throw new self.ParseException(b, e, s, l, t);
-  }
-
-  var lk, b0, e0;
-  var l1, b1, e1;
-  var eventHandler;
-
-  var input;
-  var size;
-  var begin;
-  var end;
-
-  function match(tokenSetId)
-  {
-    var nonbmp = false;
-    begin = end;
-    var current = end;
-    var result = JSONiqTokenizer.INITIAL[tokenSetId];
-    var state = 0;
-
-    for (var code = result & 4095; code != 0; )
-    {
-      var charclass;
-      var c0 = current < size ? input.charCodeAt(current) : 0;
-      ++current;
-      if (c0 < 0x80)
-      {
-        charclass = JSONiqTokenizer.MAP0[c0];
-      }
-      else if (c0 < 0xd800)
-      {
-        var c1 = c0 >> 4;
-        charclass = JSONiqTokenizer.MAP1[(c0 & 15) + JSONiqTokenizer.MAP1[(c1 & 31) + JSONiqTokenizer.MAP1[c1 >> 5]]];
-      }
-      else
-      {
-        if (c0 < 0xdc00)
-        {
-          var c1 = current < size ? input.charCodeAt(current) : 0;
-          if (c1 >= 0xdc00 && c1 < 0xe000)
-          {
-            ++current;
-            c0 = ((c0 & 0x3ff) << 10) + (c1 & 0x3ff) + 0x10000;
-            nonbmp = true;
-          }
-        }
-        var lo = 0, hi = 5;
-        for (var m = 3; ; m = (hi + lo) >> 1)
-        {
-          if (JSONiqTokenizer.MAP2[m] > c0) hi = m - 1;
-          else if (JSONiqTokenizer.MAP2[6 + m] < c0) lo = m + 1;
-          else {charclass = JSONiqTokenizer.MAP2[12 + m]; break;}
-          if (lo > hi) {charclass = 0; break;}
-        }
-      }
-
-      state = code;
-      var i0 = (charclass << 12) + code - 1;
-      code = JSONiqTokenizer.TRANSITION[(i0 & 15) + JSONiqTokenizer.TRANSITION[i0 >> 4]];
-
-      if (code > 4095)
-      {
-        result = code;
-        code &= 4095;
-        end = current;
-      }
-    }
-
-    result >>= 12;
-    if (result == 0)
-    {
-      end = current - 1;
-      var c1 = end < size ? input.charCodeAt(end) : 0;
-      if (c1 >= 0xdc00 && c1 < 0xe000) --end;
-      return error(begin, end, state, -1, -1);
-    }
-
-    if (nonbmp)
-    {
-      for (var i = result >> 9; i > 0; --i)
-      {
-        --end;
-        var c1 = end < size ? input.charCodeAt(end) : 0;
-        if (c1 >= 0xdc00 && c1 < 0xe000) --end;
-      }
-    }
-    else
-    {
-      end -= result >> 9;
-    }
-
-    return (result & 511) - 1;
-  }
-}
-
-JSONiqTokenizer.getTokenSet = function(tokenSetId)
-{
-  var set = [];
-  var s = tokenSetId < 0 ? - tokenSetId : INITIAL[tokenSetId] & 4095;
-  for (var i = 0; i < 276; i += 32)
-  {
-    var j = i;
-    var i0 = (i >> 5) * 2062 + s - 1;
-    var i1 = i0 >> 2;
-    var i2 = i1 >> 2;
-    var f = JSONiqTokenizer.EXPECTED[(i0 & 3) + JSONiqTokenizer.EXPECTED[(i1 & 3) + JSONiqTokenizer.EXPECTED[(i2 & 3) + JSONiqTokenizer.EXPECTED[i2 >> 2]]]];
-    for ( ; f != 0; f >>>= 1, ++j)
-    {
-      if ((f & 1) != 0)
-      {
-        set.push(JSONiqTokenizer.TOKEN[j]);
-      }
-    }
-  }
-  return set;
-};
-
-JSONiqTokenizer.MAP0 =
-[ 66, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 27, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 32, 31, 31, 33, 31, 31, 31, 31, 31, 31, 34, 35, 36, 35, 31, 35, 37, 38, 39, 40, 41, 42, 43, 44, 45, 31, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 31, 61, 62, 63, 64, 35
-];
-
-JSONiqTokenizer.MAP1 =
-[ 108, 124, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 156, 181, 181, 181, 181, 181, 214, 215, 213, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 247, 261, 277, 293, 309, 347, 363, 379, 416, 416, 416, 408, 331, 323, 331, 323, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 433, 433, 433, 433, 433, 433, 433, 316, 331, 331, 331, 331, 331, 331, 331, 331, 394, 416, 416, 417, 415, 416, 416, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 416, 416, 416, 416, 416, 416, 416, 416, 416, 416, 416, 416, 416, 416, 416, 416, 416, 416, 
 416, 416, 416, 416, 416, 416, 416, 416, 416, 416, 416, 416, 416, 416, 330, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 416, 66, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 27, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 35, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 32, 31, 31, 33, 31, 31, 31, 31, 31, 31, 34, 35, 36, 35, 31, 35, 37, 38, 39, 40, 41, 42, 43, 44, 45, 31, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 31, 61, 62, 63, 64, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 31, 31, 35, 35, 35, 35, 35, 35, 35, 65, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65
 , 65, 65, 65
-];
-
-JSONiqTokenizer.MAP2 =
-[ 57344, 63744, 64976, 65008, 65536, 983040, 63743, 64975, 65007, 65533, 983039, 1114111, 35, 31, 35, 31, 31, 35
-];
-
-JSONiqTokenizer.INITIAL =
-[ 1, 2, 36867, 45060, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
-];
-
-JSONiqTokenizer.TRANSITION =
-[ 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 1
 7590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 22874, 18847, 17152, 19027, 19252, 17687, 19027, 17173, 30771, 36436, 17330, 17349, 18940, 17189, 17208, 17281, 17675, 17991, 17308, 17327, 17346, 18937, 17365, 21855, 18660, 18676, 19025, 17265, 2200
 8, 17292, 17421, 21157, 17192, 21217, 21848, 17311, 18669, 19018, 19027, 17447, 17470, 17497, 17520, 17251, 36410, 17824, 20322, 20663, 20490, 17543, 17559, 17585, 21862, 17504, 17527, 17258, 36417, 18199, 21915, 17611, 36466, 18259, 17633, 17661, 18368, 17703, 17730, 17772, 33538, 21921, 17617, 36472, 18265, 36530, 17477, 19171, 17902, 17934, 17744, 17795, 17874, 17590, 21595, 17481, 17890, 17922, 18742, 17960, 36550, 17714, 17976, 18021, 18738, 18065, 36544, 18632, 18081, 18098, 18114, 18159, 18185, 18215, 18094, 18251, 18292, 18281, 18308, 18005, 18338, 18354, 18384, 17849, 36402, 19251, 17838, 17163, 30650, 18400, 17858, 32918, 17756, 18816, 18429, 18445, 18143, 17393, 18500, 18516, 18546, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 
 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 18590, 21686, 17152, 19027, 19252, 17687, 19027, 28677, 30771, 36436, 17330, 17349, 18940, 17189, 17208, 17281, 17675, 17991, 17308, 17327, 17346, 18937, 17365, 21855, 18660, 18676, 19025, 17265, 22008, 17292, 17421, 21157, 17192, 21217, 21848, 17311, 18669, 19018, 19027, 17447, 17470, 17497, 17520, 17251, 36410, 17824, 20322, 20663, 20490, 17543, 17559, 17585, 21862, 17504, 17527, 17258, 36417, 181
 99, 21915, 17611, 36466, 18259, 17633, 17661, 18368, 17703, 17730, 17772, 33538, 21921, 17617, 36472, 18265, 36530, 17477, 19171, 17902, 17934, 17744, 17795, 17874, 17590, 21595, 17481, 17890, 17922, 18742, 17960, 36550, 17714, 17976, 18021, 18738, 18065, 36544, 18632, 18081, 18098, 18114, 18159, 18185, 18215, 18094, 18251, 18292, 18281, 18308, 18005, 18338, 18354, 18384, 17849, 36402, 19251, 17838, 17163, 30650, 18400, 17858, 32918, 17756, 18816, 18429, 18445, 18143, 17393, 18500, 18516, 18546, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590,
  17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 20083, 18847, 18648, 19027, 19252, 21242, 19027, 17173, 30771, 36436, 17330, 17349, 18940, 17189, 17208, 17281, 17675, 17991, 17308, 17327, 17346, 18937, 18460, 21855, 18660, 18676, 19025, 17265, 22008, 17292, 17421, 21157, 17192, 21217, 21848, 17311, 18669, 19018, 19027, 17447, 32909, 17497, 17520, 17251, 36410, 17824, 20322, 20663, 20490, 17543, 17559, 17585, 21862, 17504, 17527, 17258, 36417, 21890, 21915, 17611, 36466, 18259, 17633, 17661, 18368, 17703, 17730, 17772, 33538, 21921, 17617, 36472, 18265, 36530, 17477, 19171, 17902, 17934, 17744, 17795, 17874, 17590, 21595, 17481, 19175, 17906, 18
 742, 17960, 36550, 17714, 17976, 18021, 18738, 18692, 18413, 18632, 18081, 18098, 18114, 18159, 18185, 18717, 18094, 18251, 18292, 18281, 18308, 18005, 18338, 18354, 18384, 17849, 36402, 19251, 17838, 17163, 30650, 18400, 17858, 32918, 17645, 18816, 18429, 18445, 18530, 17393, 18758, 18516, 18546, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590
 , 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 18774, 18789, 18805, 19027, 19252, 17687, 19027, 17173, 30771, 36436, 17330, 17349, 18940, 17189, 17208, 17281, 17675, 17991, 17308, 17327, 17346, 18937, 18460, 21855, 18660, 18676, 19025, 17265, 22008, 17292, 17421, 21157, 17192, 21217, 21848, 17311, 18669, 19018, 19027, 17447, 32909, 17497, 17520, 17251, 36410, 17824, 20322, 20663, 20490, 17543, 17559, 17585, 21862, 17504, 17527, 17258, 36417, 21890, 21915, 17611, 36466, 18259, 17633, 17661, 18368, 17703, 17730, 17772, 33538, 21921, 17617, 36472, 18265, 36530, 17477, 19171, 17902, 17934, 17744, 17795, 17874, 17590, 21595, 17481, 19175, 17906, 18742, 17960, 36550, 17714, 17976, 18021, 18738, 18692, 18413, 18632, 18081, 18098, 18114, 18159, 18185, 18717, 18094, 18251, 18292, 18281, 18308, 18005, 18338, 18354, 18384, 17849, 36402, 19251, 17838, 1
 7163, 30650, 18400, 17858, 32918, 17645, 18816, 18429, 18445, 18530, 17393, 18758, 18516, 18546, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 18832, 2288
 9, 18925, 19027, 19252, 17569, 19027, 17173, 30771, 36436, 17330, 17349, 18940, 17189, 17208, 17281, 17675, 17991, 17308, 17327, 17346, 18937, 18956, 21855, 18660, 18676, 19025, 17265, 22008, 17292, 17421, 21157, 17192, 21217, 19073, 17311, 18669, 19018, 19027, 17447, 32909, 17497, 17520, 17251, 36410, 17824, 20322, 20663, 20490, 17543, 17559, 18972, 21862, 17504, 17527, 17258, 36417, 21890, 21915, 17611, 36466, 18259, 17633, 17661, 18368, 17703, 17730, 17772, 33538, 21921, 17617, 36472, 18265, 36530, 17477, 19171, 17902, 17934, 17744, 17795, 17874, 17590, 21595, 17481, 19175, 17906, 18742, 17960, 36550, 17714, 17976, 18021, 18738, 18692, 18413, 18632, 18081, 18098, 18114, 18159, 18185, 18717, 18094, 18251, 18292, 18281, 18308, 18005, 18338, 18354, 18384, 17849, 36402, 19251, 17838, 17163, 30650, 18400, 17858, 32918, 17645, 18816, 18429, 18445, 18530, 17393, 18758, 18516, 18546, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 
 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 21818, 18847, 19006, 19027, 19252, 17687, 19027, 17173, 30771, 36436, 17330, 17349, 18940, 17189, 17208, 17281, 17675, 17991, 17308, 17327, 17346, 18937, 18460, 21855, 18660, 18676, 19025, 17265, 22008, 17292, 174
 21, 21157, 17192, 21217, 21848, 17311, 18669, 19018, 19027, 17447, 32909, 17497, 17520, 17251, 36410, 17824, 20322, 20663, 20490, 17543, 17559, 17585, 21862, 17504, 17527, 17258, 36417, 21890, 21915, 17611, 36466, 18259, 17633, 17661, 18368, 17703, 17730, 17772, 33538, 21921, 17617, 36472, 18265, 36530, 17477, 19171, 17902, 17934, 17744, 17795, 17874, 17590, 21595, 17481, 19175, 17906, 18742, 17960, 36550, 17714, 17976, 18021, 18738, 18692, 18413, 18632, 18081, 18098, 18114, 18159, 18185, 18717, 18094, 18251, 18292, 18281, 18308, 18005, 18338, 18354, 18384, 17849, 36402, 19251, 17838, 17163, 30650, 18400, 17858, 32918, 17645, 18816, 18429, 18445, 18530, 17393, 18758, 18516, 18546, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590,
  17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 21671, 18847, 19006, 19027, 19252, 17687, 19027, 17173, 30771, 36436, 17330, 17349, 18940, 17189, 17208, 17281, 17675, 17991, 17308, 17327, 17346, 18937, 18460, 21855, 18660, 18676, 19025, 17265, 22008, 17292, 17421, 21157, 17192, 21217, 21848, 17311, 18669, 19018, 19027, 17447, 32909, 17497, 17520, 17251, 36410, 17824, 20322, 20663, 20490, 17543, 17559, 17585, 21862, 17504, 17527, 17258, 36417, 21890, 21915, 17
 611, 36466, 18259, 17633, 17661, 18368, 17703, 17730, 17772, 33538, 21921, 17617, 36472, 18265, 36530, 17477, 19171, 17902, 17934, 17744, 17795, 17874, 17590, 21595, 17481, 19175, 17906, 18742, 17960, 36550, 17714, 17976, 18021, 18738, 18692, 18413, 18632, 18081, 18098, 18114, 18159, 18185, 18717, 18094, 18251, 18292, 18281, 18308, 18005, 18338, 18354, 18384, 17849, 36402, 19251, 17838, 17163, 30650, 18400, 17858, 32918, 17645, 18816, 18429, 18445, 18530, 17393, 18758, 18516, 18546, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590
 , 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 22395, 20098, 18731, 19027, 19252, 17687, 19027, 17173, 23525, 36436, 17330, 17349, 18940, 17189, 17208, 17281, 17675, 18129, 17308, 17327, 17346, 18937, 18460, 21855, 18660, 18676, 19025, 17265, 22008, 17292, 17421, 21157, 17192, 20746, 19130, 17311, 18669, 19018, 19027, 17447, 32909, 17497, 17520, 17251, 36410, 17824, 20322, 20663, 20490, 17543, 17559, 17585, 21862, 17504, 17527, 17258, 36417, 21890, 21915, 17611, 36466, 18259, 17633, 17661, 18368, 17703, 17730, 17772, 33538, 21921, 17617, 36472, 18265, 36530, 17477, 19171, 17902, 17934, 17744, 17795, 17874, 17590, 21595, 17481, 19175, 17906, 18742, 17960, 3
 6550, 17714, 17976, 18021, 18738, 18692, 18413, 18632, 18081, 18098, 18114, 18159, 18185, 18717, 18094, 18251, 18292, 18281, 18308, 18005, 18338, 18354, 18384, 17849, 36402, 19251, 17838, 17163, 30650, 18400, 17858, 32918, 17645, 18816, 18429, 18445, 18530, 17393, 18758, 18516, 18546, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 1759
 0, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 19043, 18847, 18620, 19027, 19252, 17687, 19027, 17173, 30771, 36436, 17330, 17349, 18940, 17189, 17208, 17281, 17675, 17991, 17308, 17327, 17346, 18937, 18460, 21855, 18660, 18676, 19025, 17265, 22008, 17292, 17421, 21157, 17192, 21217, 21848, 17311, 18669, 19018, 19027, 17447, 32909, 17497, 17520, 17251, 36410, 17824, 20322, 20663, 20490, 17543, 17559, 17585, 21862, 17504, 17527, 17258, 36417, 21890, 21915, 17611, 36466, 18259, 17633, 17661, 18368, 17703, 17730, 17772, 33538, 21921, 17617, 36472, 18265, 36530, 17477, 19171, 17902, 17934, 17744, 17795, 17874, 17590, 21595, 17481, 19175, 17906, 18742, 17960, 36550, 17714, 17976, 18021, 18738, 18692, 18413, 18632, 18081, 18098, 18114, 18159, 18185, 18717, 18094, 18251, 18292, 18281, 18308, 18005, 18338, 18354, 18384, 17849, 36402, 19251, 17838, 17163, 30650, 
 18400, 17858, 32918, 17645, 18816, 18429, 18445, 18530, 17393, 18758, 18516, 18546, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 17590, 19100, 22410, 19006, 190
 27, 19252, 17687, 19027, 19084, 30771, 36436, 17330, 17349, 18940, 17189, 17208, 17281, 17675, 17991, 17308, 17327, 17346, 18937, 18460, 21855, 18660, 18676, 19025, 17265, 22008, 17292, 17421, 21157, 17192, 21217, 21848, 17311, 18669, 19018, 19027, 17447, 32909,

<TRUNCATED>

[95/96] [abbrv] git commit: updated refs/heads/1994-merge-rcouch to 9605700

Posted by be...@apache.org.
support static build

This change backport the static build from rcouch.

A static build of spidermonkey is the default. To build with the
libraries installed you can pass the parameter `libs=shared` to the
make.

By default couch_collate is using ICU installed on the system except if
you pass the option `icu=static` to the Make.

At anytime you can override the compilation environnement with the
following variables:

JS_CFLAGS
JS_LIBS
ICU_CFLAGS
ICU_LDFLAGS


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/79f67b6a
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/79f67b6a
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/79f67b6a

Branch: refs/heads/1994-merge-rcouch
Commit: 79f67b6a6993c880c05c6a8a28ba4527c01b4020
Parents: 941a823
Author: Benoit Chesneau <be...@apache.org>
Authored: Wed Jan 8 23:15:49 2014 +0100
Committer: Benoit Chesneau <bc...@gmail.com>
Committed: Thu Jan 9 00:59:38 2014 +0100

----------------------------------------------------------------------
 .gitignore                                      |    7 +
 Makefile                                        |   27 +-
 bootstrap                                       |    2 +-
 rebar.config                                    |    1 -
 src/apps/couch/build_spidermonkey.sh            |  251 ++
 src/apps/couch/patches/js/patch-configure       | 3508 +++++++++++++++
 src/apps/couch/patches/js/patch-configure_in    |   56 +
 src/apps/couch/patches/js/patch-jscntxt_h       |   10 +
 src/apps/couch/patches/js/patch-jsprf_cpp       |   11 +
 src/apps/couch/rebar.config.script              |   95 +-
 src/apps/couch_collate/build_icu.sh             |  191 +
 .../patches/icu/common-uloc_c.patch             |   26 +
 .../icu/layout_LookupProcessor_cpp.patch        |   13 +
 .../icu/source_config_Makefile_inc_in.patch     |   12 +
 .../patches/icu/source_icudefs_mk_in.patch      |   19 +
 .../platform/osx/icu/unicode/basictz.h          |  210 +
 .../platform/osx/icu/unicode/brkiter.h          |  557 +++
 .../platform/osx/icu/unicode/calendar.h         | 2170 +++++++++
 .../platform/osx/icu/unicode/caniter.h          |  201 +
 .../platform/osx/icu/unicode/chariter.h         |  716 +++
 .../platform/osx/icu/unicode/choicfmt.h         |  746 +++
 .../platform/osx/icu/unicode/coleitr.h          |  400 ++
 .../platform/osx/icu/unicode/coll.h             | 1035 +++++
 .../platform/osx/icu/unicode/curramt.h          |  130 +
 .../platform/osx/icu/unicode/currunit.h         |  117 +
 .../platform/osx/icu/unicode/datefmt.h          |  700 +++
 .../platform/osx/icu/unicode/dbbi.h             |   41 +
 .../platform/osx/icu/unicode/dcfmtsym.h         |  370 ++
 .../platform/osx/icu/unicode/decimfmt.h         | 1901 ++++++++
 .../platform/osx/icu/unicode/docmain.h          |  202 +
 .../platform/osx/icu/unicode/dtfmtsym.h         |  721 +++
 .../platform/osx/icu/unicode/dtintrv.h          |  159 +
 .../platform/osx/icu/unicode/dtitvfmt.h         |  949 ++++
 .../platform/osx/icu/unicode/dtitvinf.h         |  528 +++
 .../platform/osx/icu/unicode/dtptngen.h         |  423 ++
 .../platform/osx/icu/unicode/dtrule.h           |  250 ++
 .../platform/osx/icu/unicode/fieldpos.h         |  291 ++
 .../platform/osx/icu/unicode/fmtable.h          |  591 +++
 .../platform/osx/icu/unicode/format.h           |  296 ++
 .../platform/osx/icu/unicode/gregocal.h         |  823 ++++
 .../platform/osx/icu/unicode/locid.h            |  765 ++++
 .../platform/osx/icu/unicode/measfmt.h          |   77 +
 .../platform/osx/icu/unicode/measunit.h         |   71 +
 .../platform/osx/icu/unicode/measure.h          |  137 +
 .../platform/osx/icu/unicode/msgfmt.h           |  940 ++++
 .../platform/osx/icu/unicode/normlzr.h          |  823 ++++
 .../platform/osx/icu/unicode/numfmt.h           |  886 ++++
 .../platform/osx/icu/unicode/parseerr.h         |   92 +
 .../platform/osx/icu/unicode/parsepos.h         |  230 +
 .../platform/osx/icu/unicode/platform.h         |  316 ++
 .../platform/osx/icu/unicode/plurfmt.h          |  541 +++
 .../platform/osx/icu/unicode/plurrule.h         |  291 ++
 .../platform/osx/icu/unicode/ppalmos.h          |  273 ++
 .../platform/osx/icu/unicode/putil.h            |  184 +
 .../platform/osx/icu/unicode/pwin32.h           |  311 ++
 .../platform/osx/icu/unicode/rbbi.h             |  722 +++
 .../platform/osx/icu/unicode/rbnf.h             | 1049 +++++
 .../platform/osx/icu/unicode/rbtz.h             |  361 ++
 .../platform/osx/icu/unicode/regex.h            | 1232 +++++
 .../platform/osx/icu/unicode/rep.h              |  259 ++
 .../platform/osx/icu/unicode/resbund.h          |  485 ++
 .../platform/osx/icu/unicode/schriter.h         |  187 +
 .../platform/osx/icu/unicode/search.h           |  569 +++
 .../platform/osx/icu/unicode/simpletz.h         |  927 ++++
 .../platform/osx/icu/unicode/smpdtfmt.h         |  975 ++++
 .../platform/osx/icu/unicode/sortkey.h          |  324 ++
 .../platform/osx/icu/unicode/strenum.h          |  271 ++
 .../platform/osx/icu/unicode/stsearch.h         |  518 +++
 .../platform/osx/icu/unicode/symtable.h         |  112 +
 .../platform/osx/icu/unicode/tblcoll.h          |  926 ++++
 .../platform/osx/icu/unicode/timezone.h         |  803 ++++
 .../platform/osx/icu/unicode/translit.h         | 1323 ++++++
 .../platform/osx/icu/unicode/tzrule.h           |  828 ++++
 .../platform/osx/icu/unicode/tztrans.h          |  195 +
 .../platform/osx/icu/unicode/ubidi.h            | 2013 +++++++++
 .../platform/osx/icu/unicode/ubrk.h             |  482 ++
 .../platform/osx/icu/unicode/ucal.h             | 1161 +++++
 .../platform/osx/icu/unicode/ucasemap.h         |  391 ++
 .../platform/osx/icu/unicode/ucat.h             |  158 +
 .../platform/osx/icu/unicode/uchar.h            | 3062 +++++++++++++
 .../platform/osx/icu/unicode/uchriter.h         |  381 ++
 .../platform/osx/icu/unicode/uclean.h           |  267 ++
 .../platform/osx/icu/unicode/ucnv.h             | 1967 ++++++++
 .../platform/osx/icu/unicode/ucnv_cb.h          |  162 +
 .../platform/osx/icu/unicode/ucnv_err.h         |  463 ++
 .../platform/osx/icu/unicode/ucol.h             | 1132 +++++
 .../platform/osx/icu/unicode/ucoleitr.h         |  315 ++
 .../platform/osx/icu/unicode/uconfig.h          |  228 +
 .../platform/osx/icu/unicode/ucsdet.h           |  349 ++
 .../platform/osx/icu/unicode/ucurr.h            |  270 ++
 .../platform/osx/icu/unicode/udat.h             |  962 ++++
 .../platform/osx/icu/unicode/udata.h            |  389 ++
 .../platform/osx/icu/unicode/udatpg.h           |  471 ++
 .../platform/osx/icu/unicode/udeprctd.h         |   50 +
 .../platform/osx/icu/unicode/udraft.h           |  166 +
 .../platform/osx/icu/unicode/uenum.h            |  134 +
 .../platform/osx/icu/unicode/uidna.h            |  312 ++
 .../platform/osx/icu/unicode/uintrnal.h         |  180 +
 .../platform/osx/icu/unicode/uiter.h            |  707 +++
 .../platform/osx/icu/unicode/uloc.h             | 1046 +++++
 .../platform/osx/icu/unicode/ulocdata.h         |  192 +
 .../platform/osx/icu/unicode/umachine.h         |  338 ++
 .../platform/osx/icu/unicode/umisc.h            |   60 +
 .../platform/osx/icu/unicode/umsg.h             |  647 +++
 .../platform/osx/icu/unicode/unifilt.h          |  127 +
 .../platform/osx/icu/unicode/unifunct.h         |  125 +
 .../platform/osx/icu/unicode/unimatch.h         |  163 +
 .../platform/osx/icu/unicode/unirepl.h          |   97 +
 .../platform/osx/icu/unicode/uniset.h           | 1566 +++++++
 .../platform/osx/icu/unicode/unistr.h           | 4230 ++++++++++++++++++
 .../platform/osx/icu/unicode/unorm.h            |  576 +++
 .../platform/osx/icu/unicode/unum.h             |  869 ++++
 .../platform/osx/icu/unicode/uobject.h          |  308 ++
 .../platform/osx/icu/unicode/uobslete.h         |   32 +
 .../platform/osx/icu/unicode/urbtok.h           |  126 +
 .../platform/osx/icu/unicode/uregex.h           |  989 ++++
 .../platform/osx/icu/unicode/urename.h          | 1775 ++++++++
 .../platform/osx/icu/unicode/urep.h             |  155 +
 .../platform/osx/icu/unicode/ures.h             |  871 ++++
 .../platform/osx/icu/unicode/uscript.h          |  254 ++
 .../platform/osx/icu/unicode/usearch.h          |  766 ++++
 .../platform/osx/icu/unicode/uset.h             | 1052 +++++
 .../platform/osx/icu/unicode/usetiter.h         |  318 ++
 .../platform/osx/icu/unicode/ushape.h           |  263 ++
 .../platform/osx/icu/unicode/usprep.h           |  156 +
 .../platform/osx/icu/unicode/ustring.h          | 1479 ++++++
 .../platform/osx/icu/unicode/usystem.h          |   46 +
 .../platform/osx/icu/unicode/utext.h            | 1562 +++++++
 .../platform/osx/icu/unicode/utf.h              |  227 +
 .../platform/osx/icu/unicode/utf16.h            |  605 +++
 .../platform/osx/icu/unicode/utf32.h            |   23 +
 .../platform/osx/icu/unicode/utf8.h             |  652 +++
 .../platform/osx/icu/unicode/utf_old.h          | 1171 +++++
 .../platform/osx/icu/unicode/utmscale.h         |  481 ++
 .../platform/osx/icu/unicode/utrace.h           |  358 ++
 .../platform/osx/icu/unicode/utrans.h           |  583 +++
 .../platform/osx/icu/unicode/utypes.h           |  801 ++++
 .../platform/osx/icu/unicode/uversion.h         |  275 ++
 .../platform/osx/icu/unicode/vtzone.h           |  443 ++
 src/apps/couch_collate/rebar.config.script      |   66 +-
 src/support/build_js.escript                    |    0
 141 files changed, 78760 insertions(+), 44 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/.gitignore
----------------------------------------------------------------------
diff --git a/.gitignore b/.gitignore
index bf1f2e9..fc9b019 100644
--- a/.gitignore
+++ b/.gitignore
@@ -148,6 +148,8 @@ support/rebar/.test
 src/apps/couch_collate/ebin
 src/apps/couch_collate/priv
 src/apps/couch_collate/c_src/*.o
+src/apps/couch_collate/.libs
+src/apps/couch_collate/.dists
 
 src/apps/couch/ebin
 src/apps/couch_replicator/ebin
@@ -163,3 +165,8 @@ src/apps/couch/c_src/couch_js/config.h
 src/apps/couch/priv/couchjs
 src/apps/couch/c_src/spawnkillable/*.o
 src/apps/couch/priv/couchspawnkillable
+src/apps/couch/.libs
+src/apps/couch/.dists
+
+src/share/server/main-coffee.js
+src/share/server/main.js

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/Makefile
----------------------------------------------------------------------
diff --git a/Makefile b/Makefile
index 0c36ffc..2b09f43 100644
--- a/Makefile
+++ b/Makefile
@@ -1,30 +1,45 @@
 BASE_DIR = $(shell pwd)
 ERLANG_BIN = $(shell dirname $(shell which erl))
+GIT_BIN = $(shell dirname $(shell which git))
 REBAR ?= $(BASE_DIR)/rebar
 OVERLAY_VARS ?=
 
 $(if $(ERLANG_BIN),,$(warning "Warning: No Erlang found in your path, this will probably not work"))
 
+$(if $(GIT_BIN),,$(warning "Warning: No Git found in your path, this will probably not work"))
+
+
 .PHONY: rel deps
 
+COUCHDB_STATIC=1
+ifeq ($(libs), shared)
+	COUCHDB_STATIC=0
+endif
+export COUCHDB_STATIC
+
+USE_STATIC_ICU=0
+ifeq ($(icu), static)
+	USE_STATIC_ICU=1
+endif
+export USE_STATIC_ICU
+
 all: deps compile
 
 compile:
-	./rebar compile
+	@./rebar compile
 
 deps:
-	./rebar get-deps
+	@./rebar get-deps
 
 clean:
-	./rebar clean
+	@./rebar clean
 
 distclean: clean relclean
 
 generate:
-	./rebar generate $(OVERLAY_VARS)
+	@./rebar generate $(OVERLAY_VARS)
 
 rel: deps compile generate
 
 relclean:
-	rm -rf rel/apache-couchdb
-
+	@rm -rf rel/apache-couchdb

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/bootstrap
----------------------------------------------------------------------
diff --git a/bootstrap b/bootstrap
index 4e2a42f..38db553 100755
--- a/bootstrap
+++ b/bootstrap
@@ -65,7 +65,7 @@ fi
 sed "s/%revision%/$REVISION/" < pkg.vars.config.in > pkg.vars.config
 
 # build rebar
-export SUPPORT_DIR=$CURRENT/support
+export SUPPORT_DIR=$CURRENT/src/support
 ESCRIPT=`find_program escript`
 ERLC=`find_program erlc`
 

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/rebar.config
----------------------------------------------------------------------
diff --git a/rebar.config b/rebar.config
index f33cca6..8950111 100644
--- a/rebar.config
+++ b/rebar.config
@@ -33,7 +33,6 @@
     {jiffy, ".*", {git, "git://github.com/refuge/jiffy.git", "master"}}
 ]}.
 
-{lib_dirs, ["src/apps", "src/deps"]}.
 
 {deps_dir, ["src/deps"]}.
 

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch/build_spidermonkey.sh
----------------------------------------------------------------------
diff --git a/src/apps/couch/build_spidermonkey.sh b/src/apps/couch/build_spidermonkey.sh
new file mode 100755
index 0000000..95a15dd
--- /dev/null
+++ b/src/apps/couch/build_spidermonkey.sh
@@ -0,0 +1,251 @@
+#!/bin/sh
+
+CORE_TOP=`pwd`
+export CORE_TOP
+
+CURLBIN=`which curl`
+if ! test -n "CURLBIN"; then
+    display_error "Error: curl is required. Add it to 'PATH'"
+    exit 1
+fi
+
+GUNZIP=`which gunzip`
+UNZIP=`which unzip`
+TAR=`which tar`
+GNUMAKE=`which gmake 2>/dev/null || which make`
+PATCHES=$CORE_TOP/patches
+STATICLIBS=$CORE_TOP/.libs
+DISTDIR=$CORE_TOP/.dists
+
+# nspr sources
+NSPR_VER=4.8.8
+NSPR_DISTNAME=nspr-$NSPR_VER.tar.gz
+NSPR_SITE=http://dl.refuge.io
+
+# spidermonkey js sources
+JS_VER=185-1.0.0
+JS_REALVER=1.8.5
+JS_DISTNAME=js$JS_VER.tar.gz
+JS_SITE=http://dl.refuge.io
+JSDIR=$STATICLIBS/js-$JS_REALVER
+JS_LIBDIR=$STATICLIBS/js/lib
+JS_INCDIR=$STATICLIBS/js/include
+
+
+[ "$MACHINE" ] || MACHINE=`(uname -m) 2>/dev/null` || MACHINE="unknown"
+[ "$RELEASE" ] || RELEASE=`(uname -r) 2>/dev/null` || RELEASE="unknown"
+[ "$SYSTEM" ] || SYSTEM=`(uname -s) 2>/dev/null`  || SYSTEM="unknown"
+[ "$BUILD" ] || VERSION=`(uname -v) 2>/dev/null` || VERSION="unknown"
+
+
+CFLAGS="-g -O2 -Wall"
+LDFLAGS="-lstdc++"
+ARCH=
+ISA64=
+GNUMAKE=make
+CC=gcc
+CXX=g++
+PATCH=patch
+case "$SYSTEM" in
+    Linux)
+        ARCH=`arch 2>/dev/null`
+        ;;
+    FreeBSD|OpenBSD|NetBSD)
+        ARCH=`(uname -p) 2>/dev/null`
+        GNUMAKE=gmake
+        ;;
+    Darwin)
+        ARCH=`(uname -p) 2>/dev/null`
+        ISA64=`(sysctl -n hw.optional.x86_64) 2>/dev/null`
+        ;;
+    Solaris)
+        ARCH=`(uname -p) 2>/dev/null`
+        GNUMAKE=gmake
+        PATCH=gpatch
+        ;;
+    *)
+        ARCH="unknown"
+        ;;
+esac
+
+
+# TODO: add mirror & signature validation support
+fetch()
+{
+    TARGET=$DISTDIR/$1
+    if ! test -f $TARGET; then
+        echo "==> Fetch $1 to $TARGET"
+        $CURLBIN --progress-bar -L $2/$1 -o $TARGET
+    fi
+}
+
+build_nspr()
+{
+    NSPR_CONFIGURE_ENV=""
+    case "$SYSTEM" in
+        Linux)
+            ARCH=`arch 2>/dev/null`
+            if [ "$ARCH" = "x86_64" ]; then
+                NSPR_CONFIGURE_ENV="--enable-64bit"
+            fi
+            CFLAGS="$CFLAGS -lpthread"
+            ;;
+        FreeBSD|OpenBSD|NetBSD)
+            ARCH=`(uname -p) 2>/dev/null`
+            if [ "$ARCH" = "x86_64" ] || [ "$ARCH" = "amd64" ]; then
+                NSPR_CONFIGURE_ENV+=--enable-64bit
+            fi
+            ;;
+        Darwin)
+            if [ "$ISA64" = "1" ]; then
+                NSPR_CONFIGURE_ENV+=--enable-64bit
+            fi
+            ;;
+    esac
+
+    fetch $NSPR_DISTNAME $NSPR_SITE
+
+    # clean the build
+    rm -rf $STATICLIBS/nspr*
+
+    echo "==> build nspr"
+    cd $STATICLIBS
+    $GUNZIP -c $DISTDIR/$NSPR_DISTNAME | $TAR xf -
+
+    cd $STATICLIBS/nspr-$NSPR_VER/mozilla/nsprpub
+    ./configure --disable-debug --enable-optimize \
+        --prefix=$STATICLIBS/nsprpub $NSPR_CONFIGURE_ENV
+
+    $GNUMAKE all
+    $GNUMAKE install
+}
+
+build_js()
+{
+
+    fetch $JS_DISTNAME $JS_SITE
+
+    # clean the build
+    rm -rf $STATICLIBS/js*
+
+    mkdir -p $JS_LIBDIR
+    mkdir -p $JS_INCDIR
+
+    cd $STATICLIBS
+    $GUNZIP -c $DISTDIR/$JS_DISTNAME | $TAR -xf -
+
+    echo "==> build js"
+    cd $JSDIR/js/src
+    $PATCH -p0 -i $PATCHES/js/patch-jsprf_cpp || echo "skipping patch"
+    $PATCH -p0 -i $PATCHES/js/patch-configure || echo "skipping patch"
+
+    env CFLAGS="$CFLAGS" LDFLAGS="$LDFLAGS" \
+        CPPFLAGS="-DXP_UNIX -DJS_C_STRINGS_ARE_UTF8" \
+        ./configure --prefix=$STATICLIBS/js \
+				    --disable-debug \
+					--enable-optimize \
+					--enable-static \
+					--disable-shared-js \
+					--disable-tests \
+					--with-system-nspr \
+					--with-nspr-prefix=$STATICLIBS/nsprpub && \
+        $GNUMAKE all || exit 1
+
+    mkdir -p $JS_INCDIR/js
+    cp $JSDIR/js/src/*.h $JS_INCDIR
+    cp $JSDIR/js/src/*.tbl $JS_INCDIR
+    cp $JSDIR/js/src/libjs_static.a $JS_LIBDIR
+}
+
+
+do_setup()
+{
+    echo "==> spidermonkey (compile)"
+    mkdir -p $DISTDIR
+    mkdir -p $STATICLIBS
+}
+
+do_builddeps()
+{
+    if [ ! -f $STATICLIBS/nsprpub/lib/libnspr4.a ]; then
+        build_nspr
+    fi
+
+    if [ ! -f $STATICLIBS/js/lib/libjs_static.a ]; then
+        build_js
+    fi
+}
+
+
+clean()
+{
+    rm -rf $STATICLIBS
+    rm -rf $DISTDIR
+}
+
+
+
+usage()
+{
+    cat << EOF
+Usage: $basename [command] [OPTIONS]
+
+The $basename command compile Mozilla Spidermonkey and ICU statically
+for couch_core.
+
+Commands:
+
+    all:        build couch_core static libs
+    clean:      clean static libs
+    -?:         display usage
+
+Report bugs at <https://github.com/refuge/couch_core>.
+EOF
+}
+
+
+if [ ! "x$COUCHDB_STATIC" = "x1" ]; then
+    exit 0
+fi
+
+if [ "x$1" = "x" ]; then
+    do_setup
+    do_builddeps
+	exit 0
+fi
+
+case "$1" in
+    all)
+        shift 1
+        do_setup
+        do_builddeps
+        ;;
+    clean)
+        shift 1
+        clean
+        ;;
+    js)
+        shift 1
+        do_setup
+        build_js
+        ;;
+    nspr)
+        shift 1
+        do_setup
+        build_nspr
+        ;;
+    help|--help|-h|-?)
+        usage
+        exit 0
+        ;;
+    *)
+        echo $basename: ERROR Unknown command $arg 1>&2
+        echo 1>&2
+        usage 1>&2
+        echo "### $basename: Exitting." 1>&2
+        exit 1;
+        ;;
+esac
+
+
+exit 0


[65/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/uiter.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/uiter.h b/src/apps/couch_collate/platform/osx/icu/unicode/uiter.h
new file mode 100644
index 0000000..9409f01
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/uiter.h
@@ -0,0 +1,707 @@
+/*
+*******************************************************************************
+*
+*   Copyright (C) 2002-2006, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+*
+*******************************************************************************
+*   file name:  uiter.h
+*   encoding:   US-ASCII
+*   tab size:   8 (not used)
+*   indentation:4
+*
+*   created on: 2002jan18
+*   created by: Markus W. Scherer
+*/
+
+#ifndef __UITER_H__
+#define __UITER_H__
+
+/**
+ * \file
+ * \brief C API: Unicode Character Iteration
+ *
+ * @see UCharIterator
+ */
+
+#include "unicode/utypes.h"
+
+#ifdef XP_CPLUSPLUS
+    U_NAMESPACE_BEGIN
+
+    class CharacterIterator;
+    class Replaceable;
+
+    U_NAMESPACE_END
+#endif
+
+U_CDECL_BEGIN
+
+struct UCharIterator;
+typedef struct UCharIterator UCharIterator; /**< C typedef for struct UCharIterator. @stable ICU 2.1 */
+
+/**
+ * Origin constants for UCharIterator.getIndex() and UCharIterator.move().
+ * @see UCharIteratorMove
+ * @see UCharIterator
+ * @stable ICU 2.1
+ */
+typedef enum UCharIteratorOrigin {
+    UITER_START, UITER_CURRENT, UITER_LIMIT, UITER_ZERO, UITER_LENGTH
+} UCharIteratorOrigin;
+
+/** Constants for UCharIterator. @stable ICU 2.6 */
+enum {
+    /**
+     * Constant value that may be returned by UCharIteratorMove
+     * indicating that the final UTF-16 index is not known, but that the move succeeded.
+     * This can occur when moving relative to limit or length, or
+     * when moving relative to the current index after a setState()
+     * when the current UTF-16 index is not known.
+     *
+     * It would be very inefficient to have to count from the beginning of the text
+     * just to get the current/limit/length index after moving relative to it.
+     * The actual index can be determined with getIndex(UITER_CURRENT)
+     * which will count the UChars if necessary.
+     *
+     * @stable ICU 2.6
+     */
+    UITER_UNKNOWN_INDEX=-2
+};
+
+
+/**
+ * Constant for UCharIterator getState() indicating an error or
+ * an unknown state.
+ * Returned by uiter_getState()/UCharIteratorGetState
+ * when an error occurs.
+ * Also, some UCharIterator implementations may not be able to return
+ * a valid state for each position. This will be clearly documented
+ * for each such iterator (none of the public ones here).
+ *
+ * @stable ICU 2.6
+ */
+#define UITER_NO_STATE ((uint32_t)0xffffffff)
+
+/**
+ * Function type declaration for UCharIterator.getIndex().
+ *
+ * Gets the current position, or the start or limit of the
+ * iteration range.
+ *
+ * This function may perform slowly for UITER_CURRENT after setState() was called,
+ * or for UITER_LENGTH, because an iterator implementation may have to count
+ * UChars if the underlying storage is not UTF-16.
+ *
+ * @param iter the UCharIterator structure ("this pointer")
+ * @param origin get the 0, start, limit, length, or current index
+ * @return the requested index, or U_SENTINEL in an error condition
+ *
+ * @see UCharIteratorOrigin
+ * @see UCharIterator
+ * @stable ICU 2.1
+ */
+typedef int32_t U_CALLCONV
+UCharIteratorGetIndex(UCharIterator *iter, UCharIteratorOrigin origin);
+
+/**
+ * Function type declaration for UCharIterator.move().
+ *
+ * Use iter->move(iter, index, UITER_ZERO) like CharacterIterator::setIndex(index).
+ *
+ * Moves the current position relative to the start or limit of the
+ * iteration range, or relative to the current position itself.
+ * The movement is expressed in numbers of code units forward
+ * or backward by specifying a positive or negative delta.
+ * Out of bounds movement will be pinned to the start or limit.
+ *
+ * This function may perform slowly for moving relative to UITER_LENGTH
+ * because an iterator implementation may have to count the rest of the
+ * UChars if the native storage is not UTF-16.
+ *
+ * When moving relative to the limit or length, or
+ * relative to the current position after setState() was called,
+ * move() may return UITER_UNKNOWN_INDEX (-2) to avoid an inefficient
+ * determination of the actual UTF-16 index.
+ * The actual index can be determined with getIndex(UITER_CURRENT)
+ * which will count the UChars if necessary.
+ * See UITER_UNKNOWN_INDEX for details.
+ *
+ * @param iter the UCharIterator structure ("this pointer")
+ * @param delta can be positive, zero, or negative
+ * @param origin move relative to the 0, start, limit, length, or current index
+ * @return the new index, or U_SENTINEL on an error condition,
+ *         or UITER_UNKNOWN_INDEX when the index is not known.
+ *
+ * @see UCharIteratorOrigin
+ * @see UCharIterator
+ * @see UITER_UNKNOWN_INDEX
+ * @stable ICU 2.1
+ */
+typedef int32_t U_CALLCONV
+UCharIteratorMove(UCharIterator *iter, int32_t delta, UCharIteratorOrigin origin);
+
+/**
+ * Function type declaration for UCharIterator.hasNext().
+ *
+ * Check if current() and next() can still
+ * return another code unit.
+ *
+ * @param iter the UCharIterator structure ("this pointer")
+ * @return boolean value for whether current() and next() can still return another code unit
+ *
+ * @see UCharIterator
+ * @stable ICU 2.1
+ */
+typedef UBool U_CALLCONV
+UCharIteratorHasNext(UCharIterator *iter);
+
+/**
+ * Function type declaration for UCharIterator.hasPrevious().
+ *
+ * Check if previous() can still return another code unit.
+ *
+ * @param iter the UCharIterator structure ("this pointer")
+ * @return boolean value for whether previous() can still return another code unit
+ *
+ * @see UCharIterator
+ * @stable ICU 2.1
+ */
+typedef UBool U_CALLCONV
+UCharIteratorHasPrevious(UCharIterator *iter);
+ 
+/**
+ * Function type declaration for UCharIterator.current().
+ *
+ * Return the code unit at the current position,
+ * or U_SENTINEL if there is none (index is at the limit).
+ *
+ * @param iter the UCharIterator structure ("this pointer")
+ * @return the current code unit
+ *
+ * @see UCharIterator
+ * @stable ICU 2.1
+ */
+typedef UChar32 U_CALLCONV
+UCharIteratorCurrent(UCharIterator *iter);
+
+/**
+ * Function type declaration for UCharIterator.next().
+ *
+ * Return the code unit at the current index and increment
+ * the index (post-increment, like s[i++]),
+ * or return U_SENTINEL if there is none (index is at the limit).
+ *
+ * @param iter the UCharIterator structure ("this pointer")
+ * @return the current code unit (and post-increment the current index)
+ *
+ * @see UCharIterator
+ * @stable ICU 2.1
+ */
+typedef UChar32 U_CALLCONV
+UCharIteratorNext(UCharIterator *iter);
+
+/**
+ * Function type declaration for UCharIterator.previous().
+ *
+ * Decrement the index and return the code unit from there
+ * (pre-decrement, like s[--i]),
+ * or return U_SENTINEL if there is none (index is at the start).
+ *
+ * @param iter the UCharIterator structure ("this pointer")
+ * @return the previous code unit (after pre-decrementing the current index)
+ *
+ * @see UCharIterator
+ * @stable ICU 2.1
+ */
+typedef UChar32 U_CALLCONV
+UCharIteratorPrevious(UCharIterator *iter);
+
+/**
+ * Function type declaration for UCharIterator.reservedFn().
+ * Reserved for future use.
+ *
+ * @param iter the UCharIterator structure ("this pointer")
+ * @param something some integer argument
+ * @return some integer
+ *
+ * @see UCharIterator
+ * @stable ICU 2.1
+ */
+typedef int32_t U_CALLCONV
+UCharIteratorReserved(UCharIterator *iter, int32_t something);
+
+/**
+ * Function type declaration for UCharIterator.getState().
+ *
+ * Get the "state" of the iterator in the form of a single 32-bit word.
+ * It is recommended that the state value be calculated to be as small as
+ * is feasible. For strings with limited lengths, fewer than 32 bits may
+ * be sufficient.
+ *
+ * This is used together with setState()/UCharIteratorSetState
+ * to save and restore the iterator position more efficiently than with
+ * getIndex()/move().
+ *
+ * The iterator state is defined as a uint32_t value because it is designed
+ * for use in ucol_nextSortKeyPart() which provides 32 bits to store the state
+ * of the character iterator.
+ *
+ * With some UCharIterator implementations (e.g., UTF-8),
+ * getting and setting the UTF-16 index with existing functions
+ * (getIndex(UITER_CURRENT) followed by move(pos, UITER_ZERO)) is possible but
+ * relatively slow because the iterator has to "walk" from a known index
+ * to the requested one.
+ * This takes more time the farther it needs to go.
+ *
+ * An opaque state value allows an iterator implementation to provide
+ * an internal index (UTF-8: the source byte array index) for
+ * fast, constant-time restoration.
+ *
+ * After calling setState(), a getIndex(UITER_CURRENT) may be slow because
+ * the UTF-16 index may not be restored as well, but the iterator can deliver
+ * the correct text contents and move relative to the current position
+ * without performance degradation.
+ *
+ * Some UCharIterator implementations may not be able to return
+ * a valid state for each position, in which case they return UITER_NO_STATE instead.
+ * This will be clearly documented for each such iterator (none of the public ones here).
+ *
+ * @param iter the UCharIterator structure ("this pointer")
+ * @return the state word
+ *
+ * @see UCharIterator
+ * @see UCharIteratorSetState
+ * @see UITER_NO_STATE
+ * @stable ICU 2.6
+ */
+typedef uint32_t U_CALLCONV
+UCharIteratorGetState(const UCharIterator *iter);
+
+/**
+ * Function type declaration for UCharIterator.setState().
+ *
+ * Restore the "state" of the iterator using a state word from a getState() call.
+ * The iterator object need not be the same one as for which getState() was called,
+ * but it must be of the same type (set up using the same uiter_setXYZ function)
+ * and it must iterate over the same string
+ * (binary identical regardless of memory address).
+ * For more about the state word see UCharIteratorGetState.
+ *
+ * After calling setState(), a getIndex(UITER_CURRENT) may be slow because
+ * the UTF-16 index may not be restored as well, but the iterator can deliver
+ * the correct text contents and move relative to the current position
+ * without performance degradation.
+ *
+ * @param iter the UCharIterator structure ("this pointer")
+ * @param state the state word from a getState() call
+ *              on a same-type, same-string iterator
+ * @param pErrorCode Must be a valid pointer to an error code value,
+ *                   which must not indicate a failure before the function call.
+ *
+ * @see UCharIterator
+ * @see UCharIteratorGetState
+ * @stable ICU 2.6
+ */
+typedef void U_CALLCONV
+UCharIteratorSetState(UCharIterator *iter, uint32_t state, UErrorCode *pErrorCode);
+
+
+/**
+ * C API for code unit iteration.
+ * This can be used as a C wrapper around
+ * CharacterIterator, Replaceable, or implemented using simple strings, etc.
+ *
+ * There are two roles for using UCharIterator:
+ *
+ * A "provider" sets the necessary function pointers and controls the "protected"
+ * fields of the UCharIterator structure. A "provider" passes a UCharIterator
+ * into C APIs that need a UCharIterator as an abstract, flexible string interface.
+ *
+ * Implementations of such C APIs are "callers" of UCharIterator functions;
+ * they only use the "public" function pointers and never access the "protected"
+ * fields directly.
+ *
+ * The current() and next() functions only check the current index against the
+ * limit, and previous() only checks the current index against the start,
+ * to see if the iterator already reached the end of the iteration range.
+ *
+ * The assumption - in all iterators - is that the index is moved via the API,
+ * which means it won't go out of bounds, or the index is modified by
+ * user code that knows enough about the iterator implementation to set valid
+ * index values.
+ *
+ * UCharIterator functions return code unit values 0..0xffff,
+ * or U_SENTINEL if the iteration bounds are reached.
+ *
+ * @stable ICU 2.1
+ */
+struct UCharIterator {
+    /**
+     * (protected) Pointer to string or wrapped object or similar.
+     * Not used by caller.
+     * @stable ICU 2.1
+     */
+    const void *context;
+
+    /**
+     * (protected) Length of string or similar.
+     * Not used by caller.
+     * @stable ICU 2.1
+     */
+    int32_t length;
+
+    /**
+     * (protected) Start index or similar.
+     * Not used by caller.
+     * @stable ICU 2.1
+     */
+    int32_t start;
+
+    /**
+     * (protected) Current index or similar.
+     * Not used by caller.
+     * @stable ICU 2.1
+     */
+    int32_t index;
+
+    /**
+     * (protected) Limit index or similar.
+     * Not used by caller.
+     * @stable ICU 2.1
+     */
+    int32_t limit;
+
+    /**
+     * (protected) Used by UTF-8 iterators and possibly others.
+     * @stable ICU 2.1
+     */
+    int32_t reservedField;
+
+    /**
+     * (public) Returns the current position or the
+     * start or limit index of the iteration range.
+     *
+     * @see UCharIteratorGetIndex
+     * @stable ICU 2.1
+     */
+    UCharIteratorGetIndex *getIndex;
+
+    /**
+     * (public) Moves the current position relative to the start or limit of the
+     * iteration range, or relative to the current position itself.
+     * The movement is expressed in numbers of code units forward
+     * or backward by specifying a positive or negative delta.
+     *
+     * @see UCharIteratorMove
+     * @stable ICU 2.1
+     */
+    UCharIteratorMove *move;
+
+    /**
+     * (public) Check if current() and next() can still
+     * return another code unit.
+     *
+     * @see UCharIteratorHasNext
+     * @stable ICU 2.1
+     */
+    UCharIteratorHasNext *hasNext;
+
+    /**
+     * (public) Check if previous() can still return another code unit.
+     *
+     * @see UCharIteratorHasPrevious
+     * @stable ICU 2.1
+     */
+    UCharIteratorHasPrevious *hasPrevious;
+
+    /**
+     * (public) Return the code unit at the current position,
+     * or U_SENTINEL if there is none (index is at the limit).
+     *
+     * @see UCharIteratorCurrent
+     * @stable ICU 2.1
+     */
+    UCharIteratorCurrent *current;
+
+    /**
+     * (public) Return the code unit at the current index and increment
+     * the index (post-increment, like s[i++]),
+     * or return U_SENTINEL if there is none (index is at the limit).
+     *
+     * @see UCharIteratorNext
+     * @stable ICU 2.1
+     */
+    UCharIteratorNext *next;
+
+    /**
+     * (public) Decrement the index and return the code unit from there
+     * (pre-decrement, like s[--i]),
+     * or return U_SENTINEL if there is none (index is at the start).
+     *
+     * @see UCharIteratorPrevious
+     * @stable ICU 2.1
+     */
+    UCharIteratorPrevious *previous;
+
+    /**
+     * (public) Reserved for future use. Currently NULL.
+     *
+     * @see UCharIteratorReserved
+     * @stable ICU 2.1
+     */
+    UCharIteratorReserved *reservedFn;
+
+    /**
+     * (public) Return the state of the iterator, to be restored later with setState().
+     * This function pointer is NULL if the iterator does not implement it.
+     *
+     * @see UCharIteratorGet
+     * @stable ICU 2.6
+     */
+    UCharIteratorGetState *getState;
+
+    /**
+     * (public) Restore the iterator state from the state word from a call
+     * to getState().
+     * This function pointer is NULL if the iterator does not implement it.
+     *
+     * @see UCharIteratorSet
+     * @stable ICU 2.6
+     */
+    UCharIteratorSetState *setState;
+};
+
+/**
+ * Helper function for UCharIterator to get the code point
+ * at the current index.
+ *
+ * Return the code point that includes the code unit at the current position,
+ * or U_SENTINEL if there is none (index is at the limit).
+ * If the current code unit is a lead or trail surrogate,
+ * then the following or preceding surrogate is used to form
+ * the code point value.
+ *
+ * @param iter the UCharIterator structure ("this pointer")
+ * @return the current code point
+ *
+ * @see UCharIterator
+ * @see U16_GET
+ * @see UnicodeString::char32At()
+ * @stable ICU 2.1
+ */
+U_STABLE UChar32 U_EXPORT2
+uiter_current32(UCharIterator *iter);
+
+/**
+ * Helper function for UCharIterator to get the next code point.
+ *
+ * Return the code point at the current index and increment
+ * the index (post-increment, like s[i++]),
+ * or return U_SENTINEL if there is none (index is at the limit).
+ *
+ * @param iter the UCharIterator structure ("this pointer")
+ * @return the current code point (and post-increment the current index)
+ *
+ * @see UCharIterator
+ * @see U16_NEXT
+ * @stable ICU 2.1
+ */
+U_STABLE UChar32 U_EXPORT2
+uiter_next32(UCharIterator *iter);
+
+/**
+ * Helper function for UCharIterator to get the previous code point.
+ *
+ * Decrement the index and return the code point from there
+ * (pre-decrement, like s[--i]),
+ * or return U_SENTINEL if there is none (index is at the start).
+ *
+ * @param iter the UCharIterator structure ("this pointer")
+ * @return the previous code point (after pre-decrementing the current index)
+ *
+ * @see UCharIterator
+ * @see U16_PREV
+ * @stable ICU 2.1
+ */
+U_STABLE UChar32 U_EXPORT2
+uiter_previous32(UCharIterator *iter);
+
+/**
+ * Get the "state" of the iterator in the form of a single 32-bit word.
+ * This is a convenience function that calls iter->getState(iter)
+ * if iter->getState is not NULL;
+ * if it is NULL or any other error occurs, then UITER_NO_STATE is returned.
+ *
+ * Some UCharIterator implementations may not be able to return
+ * a valid state for each position, in which case they return UITER_NO_STATE instead.
+ * This will be clearly documented for each such iterator (none of the public ones here).
+ *
+ * @param iter the UCharIterator structure ("this pointer")
+ * @return the state word
+ *
+ * @see UCharIterator
+ * @see UCharIteratorGetState
+ * @see UITER_NO_STATE
+ * @stable ICU 2.6
+ */
+U_STABLE uint32_t U_EXPORT2
+uiter_getState(const UCharIterator *iter);
+
+/**
+ * Restore the "state" of the iterator using a state word from a getState() call.
+ * This is a convenience function that calls iter->setState(iter, state, pErrorCode)
+ * if iter->setState is not NULL; if it is NULL, then U_UNSUPPORTED_ERROR is set.
+ *
+ * @param iter the UCharIterator structure ("this pointer")
+ * @param state the state word from a getState() call
+ *              on a same-type, same-string iterator
+ * @param pErrorCode Must be a valid pointer to an error code value,
+ *                   which must not indicate a failure before the function call.
+ *
+ * @see UCharIterator
+ * @see UCharIteratorSetState
+ * @stable ICU 2.6
+ */
+U_STABLE void U_EXPORT2
+uiter_setState(UCharIterator *iter, uint32_t state, UErrorCode *pErrorCode);
+
+/**
+ * Set up a UCharIterator to iterate over a string.
+ *
+ * Sets the UCharIterator function pointers for iteration over the string s
+ * with iteration boundaries start=index=0 and length=limit=string length.
+ * The "provider" may set the start, index, and limit values at any time
+ * within the range 0..length.
+ * The length field will be ignored.
+ *
+ * The string pointer s is set into UCharIterator.context without copying
+ * or reallocating the string contents.
+ *
+ * getState() simply returns the current index.
+ * move() will always return the final index.
+ *
+ * @param iter UCharIterator structure to be set for iteration
+ * @param s String to iterate over
+ * @param length Length of s, or -1 if NUL-terminated
+ *
+ * @see UCharIterator
+ * @stable ICU 2.1
+ */
+U_STABLE void U_EXPORT2
+uiter_setString(UCharIterator *iter, const UChar *s, int32_t length);
+
+/**
+ * Set up a UCharIterator to iterate over a UTF-16BE string
+ * (byte vector with a big-endian pair of bytes per UChar).
+ *
+ * Everything works just like with a normal UChar iterator (uiter_setString),
+ * except that UChars are assembled from byte pairs,
+ * and that the length argument here indicates an even number of bytes.
+ *
+ * getState() simply returns the current index.
+ * move() will always return the final index.
+ *
+ * @param iter UCharIterator structure to be set for iteration
+ * @param s UTF-16BE string to iterate over
+ * @param length Length of s as an even number of bytes, or -1 if NUL-terminated
+ *               (NUL means pair of 0 bytes at even index from s)
+ *
+ * @see UCharIterator
+ * @see uiter_setString
+ * @stable ICU 2.6
+ */
+U_STABLE void U_EXPORT2
+uiter_setUTF16BE(UCharIterator *iter, const char *s, int32_t length);
+
+/**
+ * Set up a UCharIterator to iterate over a UTF-8 string.
+ *
+ * Sets the UCharIterator function pointers for iteration over the UTF-8 string s
+ * with UTF-8 iteration boundaries 0 and length.
+ * The implementation counts the UTF-16 index on the fly and
+ * lazily evaluates the UTF-16 length of the text.
+ *
+ * The start field is used as the UTF-8 offset, the limit field as the UTF-8 length.
+ * When the reservedField is not 0, then it contains a supplementary code point
+ * and the UTF-16 index is between the two corresponding surrogates.
+ * At that point, the UTF-8 index is behind that code point.
+ *
+ * The UTF-8 string pointer s is set into UCharIterator.context without copying
+ * or reallocating the string contents.
+ *
+ * getState() returns a state value consisting of
+ * - the current UTF-8 source byte index (bits 31..1)
+ * - a flag (bit 0) that indicates whether the UChar position is in the middle
+ *   of a surrogate pair
+ *   (from a 4-byte UTF-8 sequence for the corresponding supplementary code point)
+ *
+ * getState() cannot also encode the UTF-16 index in the state value.
+ * move(relative to limit or length), or
+ * move(relative to current) after setState(), may return UITER_UNKNOWN_INDEX.
+ *
+ * @param iter UCharIterator structure to be set for iteration
+ * @param s UTF-8 string to iterate over
+ * @param length Length of s in bytes, or -1 if NUL-terminated
+ *
+ * @see UCharIterator
+ * @stable ICU 2.6
+ */
+U_STABLE void U_EXPORT2
+uiter_setUTF8(UCharIterator *iter, const char *s, int32_t length);
+
+#ifdef XP_CPLUSPLUS
+
+/**
+ * Set up a UCharIterator to wrap around a C++ CharacterIterator.
+ *
+ * Sets the UCharIterator function pointers for iteration using the
+ * CharacterIterator charIter.
+ *
+ * The CharacterIterator pointer charIter is set into UCharIterator.context
+ * without copying or cloning the CharacterIterator object.
+ * The other "protected" UCharIterator fields are set to 0 and will be ignored.
+ * The iteration index and boundaries are controlled by the CharacterIterator.
+ *
+ * getState() simply returns the current index.
+ * move() will always return the final index.
+ *
+ * @param iter UCharIterator structure to be set for iteration
+ * @param charIter CharacterIterator to wrap
+ *
+ * @see UCharIterator
+ * @stable ICU 2.1
+ */
+U_STABLE void U_EXPORT2
+uiter_setCharacterIterator(UCharIterator *iter, U_NAMESPACE_QUALIFIER CharacterIterator *charIter);
+
+/**
+ * Set up a UCharIterator to iterate over a C++ Replaceable.
+ *
+ * Sets the UCharIterator function pointers for iteration over the
+ * Replaceable rep with iteration boundaries start=index=0 and
+ * length=limit=rep->length().
+ * The "provider" may set the start, index, and limit values at any time
+ * within the range 0..length=rep->length().
+ * The length field will be ignored.
+ *
+ * The Replaceable pointer rep is set into UCharIterator.context without copying
+ * or cloning/reallocating the Replaceable object.
+ *
+ * getState() simply returns the current index.
+ * move() will always return the final index.
+ *
+ * @param iter UCharIterator structure to be set for iteration
+ * @param rep Replaceable to iterate over
+ *
+ * @see UCharIterator
+ * @stable ICU 2.1
+ */
+U_STABLE void U_EXPORT2
+uiter_setReplaceable(UCharIterator *iter, const U_NAMESPACE_QUALIFIER Replaceable *rep);
+
+#endif
+
+U_CDECL_END
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/uloc.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/uloc.h b/src/apps/couch_collate/platform/osx/icu/unicode/uloc.h
new file mode 100644
index 0000000..29c479a
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/uloc.h
@@ -0,0 +1,1046 @@
+/*
+**********************************************************************
+*   Copyright (C) 1997-2008, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+**********************************************************************
+*
+* File ULOC.H
+*
+* Modification History:
+*
+*   Date        Name        Description
+*   04/01/97    aliu        Creation.
+*   08/22/98    stephen     JDK 1.2 sync.
+*   12/08/98    rtg         New C API for Locale
+*   03/30/99    damiba      overhaul
+*   03/31/99    helena      Javadoc for uloc functions.
+*   04/15/99    Madhu       Updated Javadoc
+********************************************************************************
+*/
+
+#ifndef ULOC_H
+#define ULOC_H
+
+#include "unicode/utypes.h"
+#include "unicode/uenum.h"
+
+/**    
+ * \file
+ * \brief  C API: Locale 
+ *
+ * <h2> ULoc C API for Locale </h2>
+ * A <code>Locale</code> represents a specific geographical, political,
+ * or cultural region. An operation that requires a <code>Locale</code> to perform
+ * its task is called <em>locale-sensitive</em> and uses the <code>Locale</code>
+ * to tailor information for the user. For example, displaying a number
+ * is a locale-sensitive operation--the number should be formatted
+ * according to the customs/conventions of the user's native country,
+ * region, or culture.  In the C APIs, a locales is simply a const char string.
+ *
+ * <P>
+ * You create a <code>Locale</code> with one of the three options listed below.
+ * Each of the component is separated by '_' in the locale string.
+ * \htmlonly<blockquote>\endhtmlonly
+ * <pre>
+ * \code
+ *       newLanguage
+ * 
+ *       newLanguage + newCountry
+ * 
+ *       newLanguage + newCountry + newVariant
+ * \endcode
+ * </pre>
+ * \htmlonly</blockquote>\endhtmlonly
+ * The first option is a valid <STRONG>ISO
+ * Language Code.</STRONG> These codes are the lower-case two-letter
+ * codes as defined by ISO-639.
+ * You can find a full list of these codes at a number of sites, such as:
+ * <BR><a href ="http://www.ics.uci.edu/pub/ietf/http/related/iso639.txt">
+ * http://www.ics.uci.edu/pub/ietf/http/related/iso639.txt</a>
+ *
+ * <P>
+ * The second option includes an additonal <STRONG>ISO Country
+ * Code.</STRONG> These codes are the upper-case two-letter codes
+ * as defined by ISO-3166.
+ * You can find a full list of these codes at a number of sites, such as:
+ * <BR><a href="http://www.chemie.fu-berlin.de/diverse/doc/ISO_3166.html">
+ * http://www.chemie.fu-berlin.de/diverse/doc/ISO_3166.html</a>
+ *
+ * <P>
+ * The third option requires another additonal information--the 
+ * <STRONG>Variant.</STRONG>
+ * The Variant codes are vendor and browser-specific.
+ * For example, use WIN for Windows, MAC for Macintosh, and POSIX for POSIX.
+ * Where there are two variants, separate them with an underscore, and
+ * put the most important one first. For
+ * example, a Traditional Spanish collation might be referenced, with
+ * "ES", "ES", "Traditional_WIN".
+ *
+ * <P>
+ * Because a <code>Locale</code> is just an identifier for a region,
+ * no validity check is performed when you specify a <code>Locale</code>.
+ * If you want to see whether particular resources are available for the
+ * <code>Locale</code> you asked for, you must query those resources. For
+ * example, ask the <code>UNumberFormat</code> for the locales it supports
+ * using its <code>getAvailable</code> method.
+ * <BR><STRONG>Note:</STRONG> When you ask for a resource for a particular
+ * locale, you get back the best available match, not necessarily
+ * precisely what you asked for. For more information, look at
+ * <code>UResourceBundle</code>.
+ *
+ * <P>
+ * The <code>Locale</code> provides a number of convenient constants
+ * that you can use to specify the commonly used
+ * locales. For example, the following refers to a locale
+ * for the United States:
+ * \htmlonly<blockquote>\endhtmlonly
+ * <pre>
+ * \code
+ *       ULOC_US
+ * \endcode
+ * </pre>
+ * \htmlonly</blockquote>\endhtmlonly
+ *
+ * <P>
+ * Once you've specified a locale you can query it for information about
+ * itself. Use <code>uloc_getCountry</code> to get the ISO Country Code and
+ * <code>uloc_getLanguage</code> to get the ISO Language Code. You can
+ * use <code>uloc_getDisplayCountry</code> to get the
+ * name of the country suitable for displaying to the user. Similarly,
+ * you can use <code>uloc_getDisplayLanguage</code> to get the name of
+ * the language suitable for displaying to the user. Interestingly,
+ * the <code>uloc_getDisplayXXX</code> methods are themselves locale-sensitive
+ * and have two versions: one that uses the default locale and one
+ * that takes a locale as an argument and displays the name or country in
+ * a language appropriate to that locale.
+ *
+ * <P>
+ * The ICU provides a number of services that perform locale-sensitive
+ * operations. For example, the <code>unum_xxx</code> functions format
+ * numbers, currency, or percentages in a locale-sensitive manner. 
+ * </P>
+ * \htmlonly<blockquote>\endhtmlonly
+ * <pre>
+ * \code
+ *     UErrorCode success = U_ZERO_ERROR;
+ *     UNumberFormat *nf;
+ *     const char* myLocale = "fr_FR";
+ * 
+ *     nf = unum_open( UNUM_DEFAULT, NULL, success );          
+ *     unum_close(nf);
+ *     nf = unum_open( UNUM_CURRENCY, NULL, success );
+ *     unum_close(nf);
+ *     nf = unum_open( UNUM_PERCENT, NULL, success );   
+ *     unum_close(nf);
+ * \endcode
+ * </pre>
+ * \htmlonly</blockquote>\endhtmlonly
+ * Each of these methods has two variants; one with an explicit locale
+ * and one without; the latter using the default locale.
+ * \htmlonly<blockquote>\endhtmlonly
+ * <pre>
+ * \code 
+ * 
+ *     nf = unum_open( UNUM_DEFAULT, myLocale, success );          
+ *     unum_close(nf);
+ *     nf = unum_open( UNUM_CURRENCY, myLocale, success );
+ *     unum_close(nf);
+ *     nf = unum_open( UNUM_PERCENT, myLocale, success );   
+ *     unum_close(nf);
+ * \endcode
+ * </pre>
+ * \htmlonly</blockquote>\endhtmlonly
+ * A <code>Locale</code> is the mechanism for identifying the kind of services
+ * (<code>UNumberFormat</code>) that you would like to get. The locale is
+ * <STRONG>just</STRONG> a mechanism for identifying these services.
+ *
+ * <P>
+ * Each international serivce that performs locale-sensitive operations 
+ * allows you
+ * to get all the available objects of that type. You can sift
+ * through these objects by language, country, or variant,
+ * and use the display names to present a menu to the user.
+ * For example, you can create a menu of all the collation objects
+ * suitable for a given language. Such classes implement these
+ * three class methods:
+ * \htmlonly<blockquote>\endhtmlonly
+ * <pre>
+ * \code
+ *       const char* uloc_getAvailable(int32_t index);
+ *       int32_t uloc_countAvailable();
+ *       int32_t
+ *       uloc_getDisplayName(const char* localeID,
+ *                 const char* inLocaleID, 
+ *                 UChar* result,
+ *                 int32_t maxResultSize,
+ *                  UErrorCode* err);
+ * 
+ * \endcode
+ * </pre>
+ * \htmlonly</blockquote>\endhtmlonly
+ * <P>
+ * Concerning POSIX/RFC1766 Locale IDs, 
+ *  the getLanguage/getCountry/getVariant/getName functions do understand
+ * the POSIX type form of  language_COUNTRY.ENCODING\@VARIANT
+ * and if there is not an ICU-stype variant, uloc_getVariant() for example
+ * will return the one listed after the \@at sign. As well, the hyphen
+ * "-" is recognized as a country/variant separator similarly to RFC1766.
+ * So for example, "en-us" will be interpreted as en_US.  
+ * As a result, uloc_getName() is far from a no-op, and will have the
+ * effect of converting POSIX/RFC1766 IDs into ICU form, although it does
+ * NOT map any of the actual codes (i.e. russian->ru) in any way.
+ * Applications should call uloc_getName() at the point where a locale ID
+ * is coming from an external source (user entry, OS, web browser)
+ * and pass the resulting string to other ICU functions.  For example,
+ * don't use de-de\@EURO as an argument to resourcebundle.
+ *
+ * @see UResourceBundle
+ */
+
+/** Useful constant for this language. @stable ICU 2.0 */
+#define ULOC_CHINESE            "zh"
+/** Useful constant for this language. @stable ICU 2.0 */
+#define ULOC_ENGLISH            "en"
+/** Useful constant for this language. @stable ICU 2.0 */
+#define ULOC_FRENCH             "fr"
+/** Useful constant for this language. @stable ICU 2.0 */
+#define ULOC_GERMAN             "de"
+/** Useful constant for this language. @stable ICU 2.0 */
+#define ULOC_ITALIAN            "it"
+/** Useful constant for this language. @stable ICU 2.0 */
+#define ULOC_JAPANESE           "ja"
+/** Useful constant for this language. @stable ICU 2.0 */
+#define ULOC_KOREAN             "ko"
+/** Useful constant for this language. @stable ICU 2.0 */
+#define ULOC_SIMPLIFIED_CHINESE "zh_CN"
+/** Useful constant for this language. @stable ICU 2.0 */
+#define ULOC_TRADITIONAL_CHINESE "zh_TW"
+
+/** Useful constant for this country/region. @stable ICU 2.0 */
+#define ULOC_CANADA         "en_CA"
+/** Useful constant for this country/region. @stable ICU 2.0 */
+#define ULOC_CANADA_FRENCH  "fr_CA"
+/** Useful constant for this country/region. @stable ICU 2.0 */
+#define ULOC_CHINA          "zh_CN"
+/** Useful constant for this country/region. @stable ICU 2.0 */
+#define ULOC_PRC            "zh_CN"
+/** Useful constant for this country/region. @stable ICU 2.0 */
+#define ULOC_FRANCE         "fr_FR"
+/** Useful constant for this country/region. @stable ICU 2.0 */
+#define ULOC_GERMANY        "de_DE"
+/** Useful constant for this country/region. @stable ICU 2.0 */
+#define ULOC_ITALY          "it_IT"
+/** Useful constant for this country/region. @stable ICU 2.0 */
+#define ULOC_JAPAN          "ja_JP"
+/** Useful constant for this country/region. @stable ICU 2.0 */
+#define ULOC_KOREA          "ko_KR"
+/** Useful constant for this country/region. @stable ICU 2.0 */
+#define ULOC_TAIWAN         "zh_TW"
+/** Useful constant for this country/region. @stable ICU 2.0 */
+#define ULOC_UK             "en_GB"
+/** Useful constant for this country/region. @stable ICU 2.0 */
+#define ULOC_US             "en_US"
+
+/**
+ * Useful constant for the maximum size of the language part of a locale ID.
+ * (including the terminating NULL).
+ * @stable ICU 2.0
+ */
+#define ULOC_LANG_CAPACITY 12
+
+/**
+ * Useful constant for the maximum size of the country part of a locale ID
+ * (including the terminating NULL).
+ * @stable ICU 2.0
+ */
+#define ULOC_COUNTRY_CAPACITY 4
+/**
+ * Useful constant for the maximum size of the whole locale ID
+ * (including the terminating NULL).
+ * @stable ICU 2.0
+ */
+#define ULOC_FULLNAME_CAPACITY 56
+
+/**
+ * Useful constant for the maximum size of the script part of a locale ID
+ * (including the terminating NULL).
+ * @stable ICU 2.8
+ */
+#define ULOC_SCRIPT_CAPACITY 6
+
+/**
+ * Useful constant for the maximum size of keywords in a locale
+ * @stable ICU 2.8
+ */
+#define ULOC_KEYWORDS_CAPACITY 50
+
+/**
+ * Useful constant for the maximum SIZE of keywords in a locale
+ * @stable ICU 2.8
+ */
+#define ULOC_KEYWORD_AND_VALUES_CAPACITY 100
+
+/**
+ * Character separating keywords from the locale string
+ * different for EBCDIC - TODO
+ * @stable ICU 2.8
+ */
+#define ULOC_KEYWORD_SEPARATOR '@'
+/**
+ * Character for assigning value to a keyword
+ * @stable ICU 2.8
+ */
+#define ULOC_KEYWORD_ASSIGN '='
+/**
+ * Character separating keywords
+ * @stable ICU 2.8
+ */
+#define ULOC_KEYWORD_ITEM_SEPARATOR ';'
+
+/**
+ * Constants for *_getLocale()
+ * Allow user to select whether she wants information on 
+ * requested, valid or actual locale.
+ * For example, a collator for "en_US_CALIFORNIA" was
+ * requested. In the current state of ICU (2.0), 
+ * the requested locale is "en_US_CALIFORNIA",
+ * the valid locale is "en_US" (most specific locale supported by ICU)
+ * and the actual locale is "root" (the collation data comes unmodified 
+ * from the UCA)
+ * The locale is considered supported by ICU if there is a core ICU bundle 
+ * for that locale (although it may be empty).
+ * @stable ICU 2.1
+ */
+typedef enum {
+  /** This is locale the data actually comes from 
+   * @stable ICU 2.1
+   */
+  ULOC_ACTUAL_LOCALE    = 0,
+  /** This is the most specific locale supported by ICU 
+   * @stable ICU 2.1
+   */
+  ULOC_VALID_LOCALE    = 1,
+
+#ifndef U_HIDE_DEPRECATED_API
+  /** This is the requested locale
+   *  @deprecated ICU 2.8 
+   */
+  ULOC_REQUESTED_LOCALE = 2,
+#endif /* U_HIDE_DEPRECATED_API */
+
+  ULOC_DATA_LOCALE_TYPE_LIMIT = 3
+} ULocDataLocaleType ;
+
+
+/**
+ * Gets ICU's default locale.  
+ * The returned string is a snapshot in time, and will remain valid
+ *   and unchanged even when uloc_setDefault() is called.
+ *   The returned storage is owned by ICU, and must not be altered or deleted
+ *   by the caller.
+ *  
+ * @return the ICU default locale
+ * @system
+ * @stable ICU 2.0
+ */
+U_STABLE const char* U_EXPORT2
+uloc_getDefault(void);
+
+/**
+ * Sets ICU's default locale.  
+ *    By default (without calling this function), ICU's default locale will be based
+ *    on information obtained from the underlying system environment.
+ *    <p>
+ *    Changes to ICU's default locale do not propagate back to the
+ *    system environment.
+ *    <p>
+ *    Changes to ICU's default locale to not affect any ICU services that
+ *    may already be open based on the previous default locale value.
+ *
+ * @param localeID the new ICU default locale. A value of NULL will try to get
+ *                 the system's default locale.
+ * @param status the error information if the setting of default locale fails
+ * @system
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2
+uloc_setDefault(const char* localeID,
+        UErrorCode*       status);
+
+/**
+ * Gets the language code for the specified locale.
+ *
+ * @param localeID the locale to get the ISO language code with
+ * @param language the language code for localeID
+ * @param languageCapacity the size of the language buffer to store the  
+ * language code with
+ * @param err error information if retrieving the language code failed
+ * @return the actual buffer size needed for the language code.  If it's greater 
+ * than languageCapacity, the returned language code will be truncated.  
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+uloc_getLanguage(const char*    localeID,
+         char* language,
+         int32_t languageCapacity,
+         UErrorCode* err);
+
+/**
+ * Gets the script code for the specified locale.
+ *
+ * @param localeID the locale to get the ISO language code with
+ * @param script the language code for localeID
+ * @param scriptCapacity the size of the language buffer to store the  
+ * language code with
+ * @param err error information if retrieving the language code failed
+ * @return the actual buffer size needed for the language code.  If it's greater 
+ * than scriptCapacity, the returned language code will be truncated.  
+ * @stable ICU 2.8
+ */
+U_STABLE int32_t U_EXPORT2
+uloc_getScript(const char*    localeID,
+         char* script,
+         int32_t scriptCapacity,
+         UErrorCode* err);
+
+/**
+ * Gets the  country code for the specified locale.
+ *
+ * @param localeID the locale to get the country code with
+ * @param country the country code for localeID
+ * @param countryCapacity the size of the country buffer to store the  
+ * country code with
+ * @param err error information if retrieving the country code failed
+ * @return the actual buffer size needed for the country code.  If it's greater 
+ * than countryCapacity, the returned country code will be truncated.  
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+uloc_getCountry(const char*    localeID,
+        char* country,
+        int32_t countryCapacity,
+        UErrorCode* err);
+
+/**
+ * Gets the variant code for the specified locale.
+ *
+ * @param localeID the locale to get the variant code with
+ * @param variant the variant code for localeID
+ * @param variantCapacity the size of the variant buffer to store the 
+ * variant code with
+ * @param err error information if retrieving the variant code failed
+ * @return the actual buffer size needed for the variant code.  If it's greater 
+ * than variantCapacity, the returned variant code will be truncated.  
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+uloc_getVariant(const char*    localeID,
+        char* variant,
+        int32_t variantCapacity,
+        UErrorCode* err);
+
+
+/**
+ * Gets the full name for the specified locale.
+ * Note: This has the effect of 'canonicalizing' the ICU locale ID to
+ * a certain extent. Upper and lower case are set as needed.
+ * It does NOT map aliased names in any way.
+ * See the top of this header file.
+ * This API supports preflighting.
+ *
+ * @param localeID the locale to get the full name with
+ * @param name fill in buffer for the name without keywords.
+ * @param nameCapacity capacity of the fill in buffer.
+ * @param err error information if retrieving the full name failed
+ * @return the actual buffer size needed for the full name.  If it's greater 
+ * than nameCapacity, the returned full name will be truncated.  
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+uloc_getName(const char*    localeID,
+         char* name,
+         int32_t nameCapacity,
+         UErrorCode* err);
+
+/**
+ * Gets the full name for the specified locale.
+ * Note: This has the effect of 'canonicalizing' the string to
+ * a certain extent. Upper and lower case are set as needed,
+ * and if the components were in 'POSIX' format they are changed to
+ * ICU format.  It does NOT map aliased names in any way.
+ * See the top of this header file.
+ *
+ * @param localeID the locale to get the full name with
+ * @param name the full name for localeID
+ * @param nameCapacity the size of the name buffer to store the 
+ * full name with
+ * @param err error information if retrieving the full name failed
+ * @return the actual buffer size needed for the full name.  If it's greater 
+ * than nameCapacity, the returned full name will be truncated.  
+ * @stable ICU 2.8
+ */
+U_STABLE int32_t U_EXPORT2
+uloc_canonicalize(const char*    localeID,
+         char* name,
+         int32_t nameCapacity,
+         UErrorCode* err);
+
+/**
+ * Gets the ISO language code for the specified locale.
+ *
+ * @param localeID the locale to get the ISO language code with
+ * @return language the ISO language code for localeID
+ * @stable ICU 2.0
+ */
+U_STABLE const char* U_EXPORT2
+uloc_getISO3Language(const char* localeID);
+
+
+/**
+ * Gets the ISO country code for the specified locale.
+ *
+ * @param localeID the locale to get the ISO country code with
+ * @return country the ISO country code for localeID
+ * @stable ICU 2.0
+ */
+U_STABLE const char* U_EXPORT2
+uloc_getISO3Country(const char* localeID);
+
+/**
+ * Gets the Win32 LCID value for the specified locale.
+ * If the ICU locale is not recognized by Windows, 0 will be returned.
+ *
+ * @param localeID the locale to get the Win32 LCID value with
+ * @return country the Win32 LCID for localeID
+ * @stable ICU 2.0
+ */
+U_STABLE uint32_t U_EXPORT2
+uloc_getLCID(const char* localeID);
+
+/**
+ * Gets the language name suitable for display for the specified locale.
+ *
+ * @param locale the locale to get the ISO language code with
+ * @param displayLocale Specifies the locale to be used to display the name.  In other words,
+ *                 if the locale's language code is "en", passing Locale::getFrench() for
+ *                 inLocale would result in "Anglais", while passing Locale::getGerman()
+ *                 for inLocale would result in "Englisch".
+ * @param language the displayable language code for localeID
+ * @param languageCapacity the size of the language buffer to store the  
+ * displayable language code with
+ * @param status error information if retrieving the displayable language code failed
+ * @return the actual buffer size needed for the displayable language code.  If it's greater 
+ * than languageCapacity, the returned language code will be truncated.  
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+uloc_getDisplayLanguage(const char* locale,
+            const char* displayLocale,
+            UChar* language,
+            int32_t languageCapacity,
+            UErrorCode* status);
+
+/**
+ * Gets the script name suitable for display for the specified locale.
+ *
+ * @param locale the locale to get the displayable script code with. NULL may be used to specify the default.
+ * @param displayLocale Specifies the locale to be used to display the name.  In other words,
+ *                 if the locale's language code is "en", passing Locale::getFrench() for
+ *                 inLocale would result in "", while passing Locale::getGerman()
+ *                 for inLocale would result in "". NULL may be used to specify the default.
+ * @param script the displayable country code for localeID
+ * @param scriptCapacity the size of the script buffer to store the  
+ * displayable script code with
+ * @param status error information if retrieving the displayable script code failed
+ * @return the actual buffer size needed for the displayable script code.  If it's greater 
+ * than scriptCapacity, the returned displayable script code will be truncated.  
+ * @stable ICU 2.8
+ */
+U_STABLE int32_t U_EXPORT2
+uloc_getDisplayScript(const char* locale,
+            const char* displayLocale,
+            UChar* script,
+            int32_t scriptCapacity,
+            UErrorCode* status);
+
+/**
+ * Gets the country name suitable for display for the specified locale.
+ *
+ * @param locale the locale to get the displayable country code with. NULL may be used to specify the default.
+ * @param displayLocale Specifies the locale to be used to display the name.  In other words,
+ *                 if the locale's language code is "en", passing Locale::getFrench() for
+ *                 inLocale would result in "Anglais", while passing Locale::getGerman()
+ *                 for inLocale would result in "Englisch". NULL may be used to specify the default.
+ * @param country the displayable country code for localeID
+ * @param countryCapacity the size of the country buffer to store the  
+ * displayable country code with
+ * @param status error information if retrieving the displayable country code failed
+ * @return the actual buffer size needed for the displayable country code.  If it's greater 
+ * than countryCapacity, the returned displayable country code will be truncated.  
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+uloc_getDisplayCountry(const char* locale,
+                       const char* displayLocale,
+                       UChar* country,
+                       int32_t countryCapacity,
+                       UErrorCode* status);
+
+
+/**
+ * Gets the variant name suitable for display for the specified locale.
+ *
+ * @param locale the locale to get the displayable variant code with. NULL may be used to specify the default.
+ * @param displayLocale Specifies the locale to be used to display the name.  In other words,
+ *                 if the locale's language code is "en", passing Locale::getFrench() for
+ *                 inLocale would result in "Anglais", while passing Locale::getGerman()
+ *                 for inLocale would result in "Englisch". NULL may be used to specify the default.
+ * @param variant the displayable variant code for localeID
+ * @param variantCapacity the size of the variant buffer to store the 
+ * displayable variant code with
+ * @param status error information if retrieving the displayable variant code failed
+ * @return the actual buffer size needed for the displayable variant code.  If it's greater 
+ * than variantCapacity, the returned displayable variant code will be truncated.  
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+uloc_getDisplayVariant(const char* locale,
+                       const char* displayLocale,
+                       UChar* variant,
+                       int32_t variantCapacity,
+                       UErrorCode* status);
+
+/**
+ * Gets the keyword name suitable for display for the specified locale.
+ * E.g: for the locale string de_DE\@collation=PHONEBOOK, this API gets the display 
+ * string for the keyword collation. 
+ * Usage:
+ * <code>
+ *    UErrorCode status = U_ZERO_ERROR;
+ *    const char* keyword =NULL;
+ *    int32_t keywordLen = 0;
+ *    int32_t keywordCount = 0;
+ *    UChar displayKeyword[256];
+ *    int32_t displayKeywordLen = 0;
+ *    UEnumeration* keywordEnum = uloc_openKeywords("de_DE@collation=PHONEBOOK;calendar=TRADITIONAL", &status);
+ *    for(keywordCount = uenum_count(keywordEnum, &status); keywordCount > 0 ; keywordCount--){
+ *          if(U_FAILURE(status)){
+ *              ...something went wrong so handle the error...
+ *              break;
+ *          }
+ *          // the uenum_next returns NUL terminated string
+ *          keyword = uenum_next(keywordEnum, &keywordLen, &status);
+ *          displayKeywordLen = uloc_getDisplayKeyword(keyword, "en_US", displayKeyword, 256);
+ *          ... do something interesting .....
+ *    }
+ *    uenum_close(keywordEnum);
+ * </code>
+ * @param keyword           The keyword whose display string needs to be returned.
+ * @param displayLocale     Specifies the locale to be used to display the name.  In other words,
+ *                          if the locale's language code is "en", passing Locale::getFrench() for
+ *                          inLocale would result in "Anglais", while passing Locale::getGerman()
+ *                          for inLocale would result in "Englisch". NULL may be used to specify the default.
+ * @param dest              the buffer to which the displayable keyword should be written.
+ * @param destCapacity      The size of the buffer (number of UChars). If it is 0, then
+ *                          dest may be NULL and the function will only return the length of the 
+ *                          result without writing any of the result string (pre-flighting).
+ * @param status            error information if retrieving the displayable string failed. 
+ *                          Should not be NULL and should not indicate failure on entry.
+ * @return the actual buffer size needed for the displayable variant code.  
+ * @see #uloc_openKeywords
+ * @stable ICU 2.8
+ */
+U_STABLE int32_t U_EXPORT2
+uloc_getDisplayKeyword(const char* keyword,
+                       const char* displayLocale,
+                       UChar* dest,
+                       int32_t destCapacity,
+                       UErrorCode* status);
+/**
+ * Gets the value of the keyword suitable for display for the specified locale.
+ * E.g: for the locale string de_DE\@collation=PHONEBOOK, this API gets the display 
+ * string for PHONEBOOK, in the display locale, when "collation" is specified as the keyword.
+ *
+ * @param locale            The locale to get the displayable variant code with. NULL may be used to specify the default.
+ * @param keyword           The keyword for whose value should be used.
+ * @param displayLocale     Specifies the locale to be used to display the name.  In other words,
+ *                          if the locale's language code is "en", passing Locale::getFrench() for
+ *                          inLocale would result in "Anglais", while passing Locale::getGerman()
+ *                          for inLocale would result in "Englisch". NULL may be used to specify the default.
+ * @param dest              the buffer to which the displayable keyword should be written.
+ * @param destCapacity      The size of the buffer (number of UChars). If it is 0, then
+ *                          dest may be NULL and the function will only return the length of the 
+ *                          result without writing any of the result string (pre-flighting).
+ * @param status            error information if retrieving the displayable string failed. 
+ *                          Should not be NULL and must not indicate failure on entry.
+ * @return the actual buffer size needed for the displayable variant code.  
+ * @stable ICU 2.8
+ */
+U_STABLE int32_t U_EXPORT2
+uloc_getDisplayKeywordValue(   const char* locale,
+                               const char* keyword,
+                               const char* displayLocale,
+                               UChar* dest,
+                               int32_t destCapacity,
+                               UErrorCode* status);
+/**
+ * Gets the full name suitable for display for the specified locale.
+ *
+ * @param localeID the locale to get the displayable name with. NULL may be used to specify the default.
+ * @param inLocaleID Specifies the locale to be used to display the name.  In other words,
+ *                   if the locale's language code is "en", passing Locale::getFrench() for
+ *                   inLocale would result in "Anglais", while passing Locale::getGerman()
+ *                   for inLocale would result in "Englisch". NULL may be used to specify the default.
+ * @param result the displayable name for localeID
+ * @param maxResultSize the size of the name buffer to store the 
+ * displayable full name with
+ * @param err error information if retrieving the displayable name failed
+ * @return the actual buffer size needed for the displayable name.  If it's greater 
+ * than maxResultSize, the returned displayable name will be truncated.  
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+uloc_getDisplayName(const char* localeID,
+            const char* inLocaleID,
+            UChar* result,
+            int32_t maxResultSize,
+            UErrorCode* err);
+
+
+/**
+ * Gets the specified locale from a list of all available locales.  
+ * The return value is a pointer to an item of 
+ * a locale name array.  Both this array and the pointers
+ * it contains are owned by ICU and should not be deleted or written through
+ * by the caller.  The locale name is terminated by a null pointer.
+ * @param n the specific locale name index of the available locale list
+ * @return a specified locale name of all available locales
+ * @stable ICU 2.0
+ */
+U_STABLE const char* U_EXPORT2
+uloc_getAvailable(int32_t n);
+
+/**
+ * Gets the size of the all available locale list.
+ *
+ * @return the size of the locale list
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2 uloc_countAvailable(void);
+
+/**
+ *
+ * Gets a list of all available language codes defined in ISO 639.  This is a pointer
+ * to an array of pointers to arrays of char.  All of these pointers are owned
+ * by ICU-- do not delete them, and do not write through them.  The array is
+ * terminated with a null pointer.
+ * @return a list of all available language codes
+ * @stable ICU 2.0
+ */
+U_STABLE const char* const* U_EXPORT2
+uloc_getISOLanguages(void);
+
+/**
+ *
+ * Gets a list of all available 2-letter country codes defined in ISO 639.  This is a
+ * pointer to an array of pointers to arrays of char.  All of these pointers are
+ * owned by ICU-- do not delete them, and do not write through them.  The array is
+ * terminated with a null pointer.
+ * @return a list of all available country codes
+ * @stable ICU 2.0
+ */
+U_STABLE const char* const* U_EXPORT2
+uloc_getISOCountries(void);
+
+/**
+ * Truncate the locale ID string to get the parent locale ID.
+ * Copies the part of the string before the last underscore.
+ * The parent locale ID will be an empty string if there is no
+ * underscore, or if there is only one underscore at localeID[0].
+ *
+ * @param localeID Input locale ID string.
+ * @param parent   Output string buffer for the parent locale ID.
+ * @param parentCapacity Size of the output buffer.
+ * @param err A UErrorCode value.
+ * @return The length of the parent locale ID.
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+uloc_getParent(const char*    localeID,
+                 char* parent,
+                 int32_t parentCapacity,
+                 UErrorCode* err);
+
+
+
+
+/**
+ * Gets the full name for the specified locale.
+ * Note: This has the effect of 'canonicalizing' the string to
+ * a certain extent. Upper and lower case are set as needed,
+ * and if the components were in 'POSIX' format they are changed to
+ * ICU format.  It does NOT map aliased names in any way.
+ * See the top of this header file.
+ * This API strips off the keyword part, so "de_DE\@collation=phonebook" 
+ * will become "de_DE". 
+ * This API supports preflighting.
+ *
+ * @param localeID the locale to get the full name with
+ * @param name fill in buffer for the name without keywords.
+ * @param nameCapacity capacity of the fill in buffer.
+ * @param err error information if retrieving the full name failed
+ * @return the actual buffer size needed for the full name.  If it's greater 
+ * than nameCapacity, the returned full name will be truncated.  
+ * @stable ICU 2.8
+ */
+U_STABLE int32_t U_EXPORT2
+uloc_getBaseName(const char*    localeID,
+         char* name,
+         int32_t nameCapacity,
+         UErrorCode* err);
+
+/**
+ * Gets an enumeration of keywords for the specified locale. Enumeration
+ * must get disposed of by the client using uenum_close function.
+ *
+ * @param localeID the locale to get the variant code with
+ * @param status error information if retrieving the keywords failed
+ * @return enumeration of keywords or NULL if there are no keywords.
+ * @stable ICU 2.8
+ */
+U_STABLE UEnumeration* U_EXPORT2
+uloc_openKeywords(const char* localeID,
+                        UErrorCode* status);
+
+/**
+ * Get the value for a keyword. Locale name does not need to be normalized.
+ * 
+ * @param localeID locale name containing the keyword ("de_DE@currency=EURO;collation=PHONEBOOK")
+ * @param keywordName name of the keyword for which we want the value. Case insensitive.
+ * @param buffer receiving buffer
+ * @param bufferCapacity capacity of receiving buffer
+ * @param status containing error code - buffer not big enough.
+ * @return the length of keyword value
+ * @stable ICU 2.8
+ */
+U_STABLE int32_t U_EXPORT2
+uloc_getKeywordValue(const char* localeID,
+                     const char* keywordName,
+                     char* buffer, int32_t bufferCapacity,
+                     UErrorCode* status);
+
+
+/**
+ * Set the value of the specified keyword.
+ * NOTE: Unlike almost every other ICU function which takes a
+ * buffer, this function will NOT truncate the output text. If a
+ * BUFFER_OVERFLOW_ERROR is received, it means that the original
+ * buffer is untouched. This is done to prevent incorrect or possibly
+ * even malformed locales from being generated and used.
+ * 
+ * @param keywordName name of the keyword to be set. Case insensitive.
+ * @param keywordValue value of the keyword to be set. If 0-length or
+ *  NULL, will result in the keyword being removed. No error is given if 
+ *  that keyword does not exist.
+ * @param buffer input buffer containing locale to be modified.
+ * @param bufferCapacity capacity of receiving buffer
+ * @param status containing error code - buffer not big enough.
+ * @return the length needed for the buffer
+ * @see uloc_getKeywordValue
+ * @stable ICU 3.2
+ */
+U_STABLE int32_t U_EXPORT2
+uloc_setKeywordValue(const char* keywordName,
+                     const char* keywordValue,
+                     char* buffer, int32_t bufferCapacity,
+                     UErrorCode* status);
+
+/**
+ * enums for the  return value for the character and line orientation
+ * functions.
+ * @draft ICU 4.0
+ */
+typedef enum {
+  ULOC_LAYOUT_LTR   = 0,  /* left-to-right. */
+  ULOC_LAYOUT_RTL    = 1,  /* right-to-left. */
+  ULOC_LAYOUT_TTB    = 2,  /* top-to-bottom. */
+  ULOC_LAYOUT_BTT    = 3,   /* bottom-to-top. */
+  ULOC_LAYOUT_UNKNOWN
+} ULayoutType;
+
+/**
+ * Get the layout character orientation for the specified locale.
+ * 
+ * @param localeId locale name
+ * @param status Error status
+ * @return an enum indicating the layout orientation for characters.
+ * @draft ICU 4.0
+ */
+U_DRAFT ULayoutType U_EXPORT2
+uloc_getCharacterOrientation(const char* localeId,
+                             UErrorCode *status);
+
+/**
+ * Get the layout line orientation for the specified locale.
+ * 
+ * @param localeId locale name
+ * @param status Error status
+ * @return an enum indicating the layout orientation for lines.
+ * @draft ICU 4.0
+ */
+U_DRAFT ULayoutType U_EXPORT2
+uloc_getLineOrientation(const char* localeId,
+                        UErrorCode *status);
+
+/**
+ * enums for the 'outResult' parameter return value
+ * @see uloc_acceptLanguageFromHTTP
+ * @see uloc_acceptLanguage
+ * @stable ICU 3.2
+ */
+typedef enum {
+  ULOC_ACCEPT_FAILED   = 0,  /* No exact match was found. */
+  ULOC_ACCEPT_VALID    = 1,  /* An exact match was found. */
+  ULOC_ACCEPT_FALLBACK = 2   /* A fallback was found, for example, 
+                                Accept list contained 'ja_JP'
+                                which matched available locale 'ja'. */
+} UAcceptResult;
+
+
+/**
+ * Based on a HTTP header from a web browser and a list of available locales,
+ * determine an acceptable locale for the user.
+ * @param result - buffer to accept the result locale
+ * @param resultAvailable the size of the result buffer.
+ * @param outResult - An out parameter that contains the fallback status
+ * @param httpAcceptLanguage - "Accept-Language:" header as per HTTP.
+ * @param availableLocales - list of available locales to match
+ * @param status Error status, may be BUFFER_OVERFLOW_ERROR
+ * @return length needed for the locale.
+ * @stable ICU 3.2
+ */
+U_STABLE int32_t U_EXPORT2
+uloc_acceptLanguageFromHTTP(char *result, int32_t resultAvailable,
+                            UAcceptResult *outResult,
+                            const char *httpAcceptLanguage,
+                            UEnumeration* availableLocales,
+                            UErrorCode *status);
+
+/**
+ * Based on a list of available locales,
+ * determine an acceptable locale for the user.
+ * @param result - buffer to accept the result locale
+ * @param resultAvailable the size of the result buffer.
+ * @param outResult - An out parameter that contains the fallback status
+ * @param acceptList - list of acceptable languages
+ * @param acceptListCount - count of acceptList items
+ * @param availableLocales - list of available locales to match
+ * @param status Error status, may be BUFFER_OVERFLOW_ERROR
+ * @return length needed for the locale.
+ * @stable ICU 3.2
+ */
+U_STABLE int32_t U_EXPORT2
+uloc_acceptLanguage(char *result, int32_t resultAvailable, 
+                    UAcceptResult *outResult, const char **acceptList,
+                    int32_t acceptListCount,
+                    UEnumeration* availableLocales,
+                    UErrorCode *status);
+
+
+/**
+ * Gets the ICU locale ID for the specified Win32 LCID value.
+ *
+ * @param hostID the Win32 LCID to translate
+ * @param locale the output buffer for the ICU locale ID, which will be NUL-terminated
+ *  if there is room.
+ * @param localeCapacity the size of the output buffer
+ * @param status an error is returned if the LCID is unrecognized or the output buffer
+ *  is too small
+ * @return actual the actual size of the locale ID, not including NUL-termination 
+ * @stable ICU 4.0
+ */
+U_DRAFT int32_t U_EXPORT2
+uloc_getLocaleForLCID(uint32_t hostID, char *locale, int32_t localeCapacity,
+                    UErrorCode *status);
+
+
+/**
+ * Add the likely subtags for a provided locale ID, per the algorithm described
+ * in the following CLDR technical report:
+ *
+ *   http://www.unicode.org/reports/tr35/#Likely_Subtags
+ *
+ * If localeID is already in the maximal form, or there is no data available
+ * for maximization, it will be copied to the output buffer.  For example,
+ * "und-Zzzz" cannot be maximized, since there is no reasonable maximization.
+ *
+ * Examples:
+ *
+ * "en" maximizes to "en_Latn_US"
+ *
+ * "de" maximizes to "de_Latn_US"
+ *
+ * "sr" maximizes to "sr_Cyrl_RS"
+ *
+ * "sh" maximizes to "sr_Latn_RS" (Note this will not reverse.)
+ *
+ * "zh_Hani" maximizes to "zh_Hans_CN" (Note this will not reverse.)
+ *
+ * @param localeID The locale to maximize
+ * @param maximizedLocaleID The maximized locale
+ * @param maximizedLocaleIDCapacity The capacity of the maximizedLocaleID buffer
+ * @param err Error information if maximizing the locale failed.  If the length
+ * of the localeID and the null-terminator is greater than the maximum allowed size,
+ * or the localeId is not well-formed, the error code is U_ILLEGAL_ARGUMENT_ERROR.
+ * @return The actual buffer size needed for the maximized locale.  If it's
+ * greater than maximizedLocaleIDCapacity, the returned ID will be truncated.
+ * On error, the return value is -1.
+ * @draft ICU 4.0
+ */
+U_DRAFT int32_t U_EXPORT2
+uloc_addLikelySubtags(const char*    localeID,
+         char* maximizedLocaleID,
+         int32_t maximizedLocaleIDCapacity,
+         UErrorCode* err);
+
+
+/**
+ * Minimize the subtags for a provided locale ID, per the algorithm described
+ * in the following CLDR technical report:
+ *
+ *   http://www.unicode.org/reports/tr35/#Likely_Subtags
+ *
+ * If localeID is already in the minimal form, or there is no data available
+ * for minimization, it will be copied to the output buffer.  Since the
+ * minimization algorithm relies on proper maximization, see the comments
+ * for uloc_addLikelySubtags for reasons why there might not be any data.
+ *
+ * Examples:
+ *
+ * "en_Latn_US" minimizes to "en"
+ *
+ * "de_Latn_US" minimizes to "de"
+ *
+ * "sr_Cyrl_RS" minimizes to "sr"
+ *
+ * "zh_Hant_TW" minimizes to "zh_TW" (The region is preferred to the
+ * script, and minimizing to "zh" would imply "zh_Hans_CN".)
+ *
+ * @param localeID The locale to minimize
+ * @param minimizedLocaleID The minimized locale
+ * @param minimizedLocaleIDCapacity The capacity of the minimizedLocaleID buffer
+ * @param err Error information if minimizing the locale failed.  If the length
+ * of the localeID and the null-terminator is greater than the maximum allowed size,
+ * or the localeId is not well-formed, the error code is U_ILLEGAL_ARGUMENT_ERROR.
+ * @return The actual buffer size needed for the minimized locale.  If it's
+ * greater than minimizedLocaleIDCapacity, the returned ID will be truncated.
+ * On error, the return value is -1.
+ * @draft ICU 4.0
+ */
+U_DRAFT int32_t U_EXPORT2
+uloc_minimizeSubtags(const char*    localeID,
+         char* minimizedLocaleID,
+         int32_t minimizedLocaleIDCapacity,
+         UErrorCode* err);
+
+#endif /*_ULOC*/

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/ulocdata.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/ulocdata.h b/src/apps/couch_collate/platform/osx/icu/unicode/ulocdata.h
new file mode 100644
index 0000000..4a69994
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/ulocdata.h
@@ -0,0 +1,192 @@
+/*
+******************************************************************************
+*                                                                            *
+* Copyright (C) 2003-2007, International Business Machines                   *
+*                Corporation and others. All Rights Reserved.                *
+*                                                                            *
+******************************************************************************
+*   file name:  ulocdata.h
+*   encoding:   US-ASCII
+*   tab size:   8 (not used)
+*   indentation:4
+*
+*   created on: 2003Oct21
+*   created by: Ram Viswanadha
+*/
+
+#ifndef __ULOCDATA_H__
+#define __ULOCDATA_H__
+
+#include "unicode/ures.h"
+#include "unicode/uloc.h"
+#include "unicode/uset.h"
+
+/**
+ * \file
+ * \brief C API: Provides access to locale data. 
+ */
+
+/** Forward declaration of the ULocaleData structure. @stable ICU 3.6 */
+struct ULocaleData;
+
+/** A locale data object. @stable ICU 3.6 */
+typedef struct ULocaleData ULocaleData;
+
+
+
+/** The possible types of exemplar character sets.
+  * @stable ICU 3.4
+  */
+typedef enum ULocaleDataExemplarSetType  {
+     ULOCDATA_ES_STANDARD=0,      /* Basic set */
+     ULOCDATA_ES_AUXILIARY=1,     /* Auxiliary set */
+     ULOCDATA_ES_COUNT=2
+} ULocaleDataExemplarSetType;
+
+/** The possible types of delimiters.
+  * @stable ICU 3.4
+  */
+typedef enum ULocaleDataDelimiterType {
+    ULOCDATA_QUOTATION_START = 0,     /* Quotation start */
+     ULOCDATA_QUOTATION_END = 1,       /* Quotation end */
+     ULOCDATA_ALT_QUOTATION_START = 2, /* Alternate quotation start */
+     ULOCDATA_ALT_QUOTATION_END = 3,   /* Alternate quotation end */
+     ULOCDATA_DELIMITER_COUNT = 4
+} ULocaleDataDelimiterType;
+
+/**
+ * Opens a locale data object for the given locale
+ *
+ * @param localeID  Specifies the locale associated with this locale
+ *                  data object.
+ * @param status    Pointer to error status code.
+ * @stable ICU 3.4
+ */
+U_STABLE ULocaleData* U_EXPORT2 
+ulocdata_open(const char *localeID, UErrorCode *status);
+
+/**
+ * Closes a locale data object.
+ *
+ * @param uld       The locale data object to close
+ * @stable ICU 3.4
+ */
+U_STABLE void U_EXPORT2 
+ulocdata_close(ULocaleData *uld);
+
+/**
+ * Sets the "no Substitute" attribute of the locale data
+ * object.  If true, then any methods associated with the
+ * locale data object will return null when there is no
+ * data available for that method, given the locale ID
+ * supplied to ulocdata_open().
+ *
+ * @param uld       The locale data object to set.
+ * @param setting   Value of the "no substitute" attribute.
+ * @stable ICU 3.4
+ */
+U_STABLE void U_EXPORT2 
+ulocdata_setNoSubstitute(ULocaleData *uld, UBool setting);
+
+/**
+ * Retrieves the current "no Substitute" value of the locale data
+ * object.  If true, then any methods associated with the
+ * locale data object will return null when there is no
+ * data available for that method, given the locale ID
+ * supplied to ulocdata_open().
+ *
+ * @param uld       Pointer to the The locale data object to set.
+ * @return UBool    Value of the "no substitute" attribute.
+ * @stable ICU 3.4
+ */
+U_STABLE UBool U_EXPORT2 
+ulocdata_getNoSubstitute(ULocaleData *uld);
+
+/**
+ * Returns the set of exemplar characters for a locale.
+ *
+ * @param uld       Pointer to the locale data object from which the 
+ *                  exemplar character set is to be retrieved.
+ * @param fillIn    Pointer to a USet object to receive the 
+ *                  exemplar character set for the given locale.  Previous
+ *                  contents of fillIn are lost.  <em>If fillIn is NULL,
+ *                  then a new USet is created and returned.  The caller
+ *                  owns the result and must dispose of it by calling
+ *                  uset_close.</em>
+ * @param options   Bitmask for options to apply to the exemplar pattern.
+ *                  Specify zero to retrieve the exemplar set as it is
+ *                  defined in the locale data.  Specify
+ *                  USET_CASE_INSENSITIVE to retrieve a case-folded
+ *                  exemplar set.  See uset_applyPattern for a complete
+ *                  list of valid options.  The USET_IGNORE_SPACE bit is
+ *                  always set, regardless of the value of 'options'.
+ * @param extype    Specifies the type of exemplar set to be retrieved.
+ * @param status    Pointer to an input-output error code value;
+ *                  must not be NULL.
+ * @return USet*    Either fillIn, or if fillIn is NULL, a pointer to
+ *                  a newly-allocated USet that the user must close.
+ * @stable ICU 3.4
+ */
+U_STABLE USet* U_EXPORT2 
+ulocdata_getExemplarSet(ULocaleData *uld, USet *fillIn, 
+                        uint32_t options, ULocaleDataExemplarSetType extype, UErrorCode *status);
+
+/**
+ * Returns one of the delimiter strings associated with a locale.
+ *
+ * @param uld           Pointer to the locale data object from which the 
+ *                      delimiter string is to be retrieved.
+ * @param type          the type of delimiter to be retrieved.
+ * @param result        A pointer to a buffer to receive the result.
+ * @param resultLength  The maximum size of result.
+ * @param status        Pointer to an error code value
+ * @return int32_t      The total buffer size needed; if greater than resultLength,
+ *                      the output was truncated.
+ * @stable ICU 3.4
+ */
+U_STABLE int32_t U_EXPORT2 
+ulocdata_getDelimiter(ULocaleData *uld, ULocaleDataDelimiterType type, UChar *result, int32_t resultLength, UErrorCode *status);
+
+/**
+ * Enumeration for representing the measurement systems.
+ * @stable ICU 2.8
+ */
+typedef enum UMeasurementSystem {
+    UMS_SI,     /** Measurement system specified by SI otherwise known as Metric system. */
+    UMS_US,     /** Measurement system followed in the United States of America. */ 
+    UMS_LIMIT
+} UMeasurementSystem;
+
+/**
+ * Returns the measurement system used in the locale specified by the localeID.
+ * Please note that this API will change in ICU 3.6 and will use an ulocdata object.
+ *
+ * @param localeID      The id of the locale for which the measurement system to be retrieved.
+ * @param status        Must be a valid pointer to an error code value,
+ *                      which must not indicate a failure before the function call.
+ * @return UMeasurementSystem the measurement system used in the locale.
+ * @stable ICU 2.8
+ */
+U_STABLE UMeasurementSystem U_EXPORT2
+ulocdata_getMeasurementSystem(const char *localeID, UErrorCode *status);
+
+/**
+ * Returns the element gives the normal business letter size, and customary units. 
+ * The units for the numbers are always in <em>milli-meters</em>.
+ * For US since 8.5 and 11 do not yeild an integral value when converted to milli-meters,
+ * the values are rounded off.
+ * So for A4 size paper the height and width are 297 mm and 210 mm repectively, 
+ * and for US letter size the height and width are 279 mm and 216 mm respectively.
+ * Please note that this API will change in ICU 3.6 and will use an ulocdata object.
+ *
+ * @param localeID      The id of the locale for which the paper size information to be retrieved.
+ * @param height        A pointer to int to recieve the height information.
+ * @param width         A pointer to int to recieve the width information.
+ * @param status        Must be a valid pointer to an error code value,
+ *                      which must not indicate a failure before the function call.
+ * @stable ICU 2.8
+ */
+U_STABLE void U_EXPORT2
+ulocdata_getPaperSize(const char *localeID, int32_t *height, int32_t *width, UErrorCode *status);
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/umachine.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/umachine.h b/src/apps/couch_collate/platform/osx/icu/unicode/umachine.h
new file mode 100644
index 0000000..083f9cf
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/umachine.h
@@ -0,0 +1,338 @@
+/*
+******************************************************************************
+*
+*   Copyright (C) 1999-2006, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+*
+******************************************************************************
+*   file name:  umachine.h
+*   encoding:   US-ASCII
+*   tab size:   8 (not used)
+*   indentation:4
+*
+*   created on: 1999sep13
+*   created by: Markus W. Scherer
+*
+*   This file defines basic types and constants for utf.h to be
+*   platform-independent. umachine.h and utf.h are included into
+*   utypes.h to provide all the general definitions for ICU.
+*   All of these definitions used to be in utypes.h before
+*   the UTF-handling macros made this unmaintainable.
+*/
+
+#ifndef __UMACHINE_H__
+#define __UMACHINE_H__
+
+
+/**
+ * \file
+ * \brief Basic types and constants for UTF 
+ * 
+ * <h2> Basic types and constants for UTF </h2>
+ *   This file defines basic types and constants for utf.h to be
+ *   platform-independent. umachine.h and utf.h are included into
+ *   utypes.h to provide all the general definitions for ICU.
+ *   All of these definitions used to be in utypes.h before
+ *   the UTF-handling macros made this unmaintainable.
+ * 
+ */
+/*==========================================================================*/
+/* Include platform-dependent definitions                                   */
+/* which are contained in the platform-specific file platform.h             */
+/*==========================================================================*/
+
+#if defined(U_PALMOS)
+#   include "unicode/ppalmos.h"
+#elif defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64)
+#   include "unicode/pwin32.h"
+#else
+#   include "unicode/platform.h"
+#endif
+
+/*
+ * ANSI C headers:
+ * stddef.h defines wchar_t
+ */
+#include <stddef.h>
+
+/*==========================================================================*/
+/* XP_CPLUSPLUS is a cross-platform symbol which should be defined when     */
+/* using C++.  It should not be defined when compiling under C.             */
+/*==========================================================================*/
+
+#ifdef __cplusplus
+#   ifndef XP_CPLUSPLUS
+#       define XP_CPLUSPLUS
+#   endif
+#else
+#   undef XP_CPLUSPLUS
+#endif
+
+/*==========================================================================*/
+/* For C wrappers, we use the symbol U_STABLE.                                */
+/* This works properly if the includer is C or C++.                         */
+/* Functions are declared   U_STABLE return-type U_EXPORT2 function-name()... */
+/*==========================================================================*/
+
+/**
+ * \def U_CFUNC
+ * This is used in a declaration of a library private ICU C function.
+ * @stable ICU 2.4
+ */
+
+/**
+ * \def U_CDECL_BEGIN
+ * This is used to begin a declaration of a library private ICU C API.
+ * @stable ICU 2.4
+ */
+
+/**
+ * \def U_CDECL_END
+ * This is used to end a declaration of a library private ICU C API 
+ * @stable ICU 2.4
+ */
+
+#ifdef XP_CPLUSPLUS
+#   define U_CFUNC extern "C"
+#   define U_CDECL_BEGIN extern "C" {
+#   define U_CDECL_END   }
+#else
+#   define U_CFUNC extern
+#   define U_CDECL_BEGIN
+#   define U_CDECL_END
+#endif
+
+/** This is used to declare a function as a public ICU C API @stable ICU 2.0*/
+#define U_CAPI U_CFUNC U_EXPORT
+#define U_STABLE U_CAPI
+#define U_DRAFT  U_CAPI
+#define U_DEPRECATED U_CAPI
+#define U_OBSOLETE U_CAPI
+#define U_INTERNAL U_CAPI
+
+/*==========================================================================*/
+/* limits for int32_t etc., like in POSIX inttypes.h                        */
+/*==========================================================================*/
+
+#ifndef INT8_MIN
+/** The smallest value an 8 bit signed integer can hold @stable ICU 2.0 */
+#   define INT8_MIN        ((int8_t)(-128))
+#endif
+#ifndef INT16_MIN
+/** The smallest value a 16 bit signed integer can hold @stable ICU 2.0 */
+#   define INT16_MIN       ((int16_t)(-32767-1))
+#endif
+#ifndef INT32_MIN
+/** The smallest value a 32 bit signed integer can hold @stable ICU 2.0 */
+#   define INT32_MIN       ((int32_t)(-2147483647-1))
+#endif
+
+#ifndef INT8_MAX
+/** The largest value an 8 bit signed integer can hold @stable ICU 2.0 */
+#   define INT8_MAX        ((int8_t)(127))
+#endif
+#ifndef INT16_MAX
+/** The largest value a 16 bit signed integer can hold @stable ICU 2.0 */
+#   define INT16_MAX       ((int16_t)(32767))
+#endif
+#ifndef INT32_MAX
+/** The largest value a 32 bit signed integer can hold @stable ICU 2.0 */
+#   define INT32_MAX       ((int32_t)(2147483647))
+#endif
+
+#ifndef UINT8_MAX
+/** The largest value an 8 bit unsigned integer can hold @stable ICU 2.0 */
+#   define UINT8_MAX       ((uint8_t)(255U))
+#endif
+#ifndef UINT16_MAX
+/** The largest value a 16 bit unsigned integer can hold @stable ICU 2.0 */
+#   define UINT16_MAX      ((uint16_t)(65535U))
+#endif
+#ifndef UINT32_MAX
+/** The largest value a 32 bit unsigned integer can hold @stable ICU 2.0 */
+#   define UINT32_MAX      ((uint32_t)(4294967295U))
+#endif
+
+#if defined(U_INT64_T_UNAVAILABLE)
+# error int64_t is required for decimal format and rule-based number format.
+#else
+# ifndef INT64_C
+/**
+ * Provides a platform independent way to specify a signed 64-bit integer constant.
+ * note: may be wrong for some 64 bit platforms - ensure your compiler provides INT64_C
+ * @stable ICU 2.8
+ */
+#   define INT64_C(c) c ## LL
+# endif
+# ifndef UINT64_C
+/**
+ * Provides a platform independent way to specify an unsigned 64-bit integer constant.
+ * note: may be wrong for some 64 bit platforms - ensure your compiler provides UINT64_C
+ * @stable ICU 2.8
+ */
+#   define UINT64_C(c) c ## ULL
+# endif
+# ifndef U_INT64_MIN
+/** The smallest value a 64 bit signed integer can hold @stable ICU 2.8 */
+#     define U_INT64_MIN       ((int64_t)(INT64_C(-9223372036854775807)-1))
+# endif
+# ifndef U_INT64_MAX
+/** The largest value a 64 bit signed integer can hold @stable ICU 2.8 */
+#     define U_INT64_MAX       ((int64_t)(INT64_C(9223372036854775807)))
+# endif
+# ifndef U_UINT64_MAX
+/** The largest value a 64 bit unsigned integer can hold @stable ICU 2.8 */
+#     define U_UINT64_MAX      ((uint64_t)(UINT64_C(18446744073709551615)))
+# endif
+#endif
+
+/*==========================================================================*/
+/* Boolean data type                                                        */
+/*==========================================================================*/
+
+/** The ICU boolean type @stable ICU 2.0 */
+typedef int8_t UBool;
+
+#ifndef TRUE
+/** The TRUE value of a UBool @stable ICU 2.0 */
+#   define TRUE  1
+#endif
+#ifndef FALSE
+/** The FALSE value of a UBool @stable ICU 2.0 */
+#   define FALSE 0
+#endif
+
+
+/*==========================================================================*/
+/* Unicode data types                                                       */
+/*==========================================================================*/
+
+/* wchar_t-related definitions -------------------------------------------- */
+
+/**
+ * \def U_HAVE_WCHAR_H
+ * Indicates whether <wchar.h> is available (1) or not (0). Set to 1 by default.
+ *
+ * @stable ICU 2.0
+ */
+#ifndef U_HAVE_WCHAR_H
+#   define U_HAVE_WCHAR_H 1
+#endif
+
+/**
+ * \def U_SIZEOF_WCHAR_T
+ * U_SIZEOF_WCHAR_T==sizeof(wchar_t) (0 means it is not defined or autoconf could not set it)
+ *
+ * @stable ICU 2.0
+ */
+#if U_SIZEOF_WCHAR_T==0
+#   undef U_SIZEOF_WCHAR_T
+#   define U_SIZEOF_WCHAR_T 4
+#endif
+
+/*
+ * \def U_WCHAR_IS_UTF16
+ * Defined if wchar_t uses UTF-16.
+ *
+ * @stable ICU 2.0
+ */
+/*
+ * \def U_WCHAR_IS_UTF32
+ * Defined if wchar_t uses UTF-32.
+ *
+ * @stable ICU 2.0
+ */
+#if !defined(U_WCHAR_IS_UTF16) && !defined(U_WCHAR_IS_UTF32)
+#   ifdef __STDC_ISO_10646__ 
+#       if (U_SIZEOF_WCHAR_T==2)
+#           define U_WCHAR_IS_UTF16
+#       elif (U_SIZEOF_WCHAR_T==4)
+#           define  U_WCHAR_IS_UTF32
+#       endif
+#   elif defined __UCS2__
+#       if (__OS390__ || __OS400__) && (U_SIZEOF_WCHAR_T==2)
+#           define U_WCHAR_IS_UTF16
+#       endif
+#   elif defined __UCS4__
+#       if (U_SIZEOF_WCHAR_T==4)
+#           define U_WCHAR_IS_UTF32
+#       endif
+#   elif defined(U_WINDOWS)
+#       define U_WCHAR_IS_UTF16    
+#   endif
+#endif
+
+/* UChar and UChar32 definitions -------------------------------------------- */
+
+/** Number of bytes in a UChar. @stable ICU 2.0 */
+#define U_SIZEOF_UCHAR 2
+
+/**
+ * \var UChar
+ * Define UChar to be wchar_t if that is 16 bits wide; always assumed to be unsigned.
+ * If wchar_t is not 16 bits wide, then define UChar to be uint16_t.
+ * This makes the definition of UChar platform-dependent
+ * but allows direct string type compatibility with platforms with
+ * 16-bit wchar_t types.
+ *
+ * @stable ICU 2.0
+ */
+
+/* Define UChar to be compatible with wchar_t if possible. */
+#if U_SIZEOF_WCHAR_T==2
+    typedef wchar_t UChar;
+#else
+    typedef uint16_t UChar;
+#endif
+
+/**
+ * Define UChar32 as a type for single Unicode code points.
+ * UChar32 is a signed 32-bit integer (same as int32_t).
+ *
+ * The Unicode code point range is 0..0x10ffff.
+ * All other values (negative or >=0x110000) are illegal as Unicode code points.
+ * They may be used as sentinel values to indicate "done", "error"
+ * or similar non-code point conditions.
+ *
+ * Before ICU 2.4 (Jitterbug 2146), UChar32 was defined
+ * to be wchar_t if that is 32 bits wide (wchar_t may be signed or unsigned)
+ * or else to be uint32_t.
+ * That is, the definition of UChar32 was platform-dependent.
+ *
+ * @see U_SENTINEL
+ * @stable ICU 2.4
+ */
+typedef int32_t UChar32;
+
+/*==========================================================================*/
+/* U_INLINE and U_ALIGN_CODE   Set default values if these are not already  */
+/*                             defined.  Definitions normally are in        */
+/*                             platform.h or the corresponding file for     */
+/*                             the OS in use.                               */
+/*==========================================================================*/
+
+#ifndef U_HIDE_INTERNAL_API
+
+/**
+ * \def U_ALIGN_CODE
+ * This is used to align code fragments to a specific byte boundary.
+ * This is useful for getting consistent performance test results.
+ * @internal
+ */
+#ifndef U_ALIGN_CODE
+#   define U_ALIGN_CODE(n)
+#endif
+
+#endif /* U_HIDE_INTERNAL_API */
+
+#ifndef U_INLINE
+#   ifdef XP_CPLUSPLUS
+#       define U_INLINE inline
+#   else
+#       define U_INLINE
+#   endif
+#endif
+
+#include "unicode/urename.h"
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/umisc.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/umisc.h b/src/apps/couch_collate/platform/osx/icu/unicode/umisc.h
new file mode 100644
index 0000000..d85451f
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/umisc.h
@@ -0,0 +1,60 @@
+/*
+**********************************************************************
+*   Copyright (C) 1999-2006, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+**********************************************************************
+*   file name:  umisc.h
+*   encoding:   US-ASCII
+*   tab size:   8 (not used)
+*   indentation:4
+*
+*   created on: 1999oct15
+*   created by: Markus W. Scherer
+*/
+
+#ifndef UMISC_H
+#define UMISC_H
+
+#include "unicode/utypes.h"
+
+/**
+ * \file
+ * \brief  C API:misc definitions 
+ *
+ *  This file contains miscellaneous definitions for the C APIs. 
+ */
+
+U_CDECL_BEGIN
+
+/** A struct representing a range of text containing a specific field 
+ *  @stable ICU 2.0
+ */
+typedef struct UFieldPosition {
+  /**
+   * The field 
+   * @stable ICU 2.0
+   */
+  int32_t field;
+  /**
+   * The start of the text range containing field 
+   * @stable ICU 2.0
+   */
+  int32_t beginIndex;
+  /** 
+   * The limit of the text range containing field 
+   * @stable ICU 2.0
+   */
+  int32_t endIndex;
+} UFieldPosition;
+
+#if !UCONFIG_NO_SERVICE
+/**
+ * Opaque type returned by registerInstance, registerFactory and unregister for service registration.
+ * @stable ICU 2.6
+ */
+typedef const void* URegistryKey;
+#endif
+
+U_CDECL_END
+
+#endif


[75/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/translit.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/translit.h b/src/apps/couch_collate/platform/osx/icu/unicode/translit.h
new file mode 100644
index 0000000..bfff344
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/translit.h
@@ -0,0 +1,1323 @@
+/*
+**********************************************************************
+* Copyright (C) 1999-2008, International Business Machines
+* Corporation and others. All Rights Reserved.
+**********************************************************************
+*   Date        Name        Description
+*   11/17/99    aliu        Creation.
+**********************************************************************
+*/
+#ifndef TRANSLIT_H
+#define TRANSLIT_H
+
+#include "unicode/utypes.h"
+
+/**
+ * \file 
+ * \brief C++ API: Tranforms text from one format to another.
+ */
+ 
+#if !UCONFIG_NO_TRANSLITERATION
+
+#include "unicode/uobject.h"
+#include "unicode/unistr.h"
+#include "unicode/parseerr.h"
+#include "unicode/utrans.h" // UTransPosition, UTransDirection
+#include "unicode/strenum.h"
+
+U_NAMESPACE_BEGIN
+
+class UnicodeFilter;
+class UnicodeSet;
+class CompoundTransliterator;
+class TransliteratorParser;
+class NormalizationTransliterator;
+class TransliteratorIDParser;
+
+/**
+ *
+ * <code>Transliterator</code> is an abstract class that
+ * transliterates text from one format to another.  The most common
+ * kind of transliterator is a script, or alphabet, transliterator.
+ * For example, a Russian to Latin transliterator changes Russian text
+ * written in Cyrillic characters to phonetically equivalent Latin
+ * characters.  It does not <em>translate</em> Russian to English!
+ * Transliteration, unlike translation, operates on characters, without
+ * reference to the meanings of words and sentences.
+ *
+ * <p>Although script conversion is its most common use, a
+ * transliterator can actually perform a more general class of tasks.
+ * In fact, <code>Transliterator</code> defines a very general API
+ * which specifies only that a segment of the input text is replaced
+ * by new text.  The particulars of this conversion are determined
+ * entirely by subclasses of <code>Transliterator</code>.
+ *
+ * <p><b>Transliterators are stateless</b>
+ *
+ * <p><code>Transliterator</code> objects are <em>stateless</em>; they
+ * retain no information between calls to
+ * <code>transliterate()</code>.  (However, this does <em>not</em>
+ * mean that threads may share transliterators without synchronizing
+ * them.  Transliterators are not immutable, so they must be
+ * synchronized when shared between threads.)  This might seem to
+ * limit the complexity of the transliteration operation.  In
+ * practice, subclasses perform complex transliterations by delaying
+ * the replacement of text until it is known that no other
+ * replacements are possible.  In other words, although the
+ * <code>Transliterator</code> objects are stateless, the source text
+ * itself embodies all the needed information, and delayed operation
+ * allows arbitrary complexity.
+ *
+ * <p><b>Batch transliteration</b>
+ *
+ * <p>The simplest way to perform transliteration is all at once, on a
+ * string of existing text.  This is referred to as <em>batch</em>
+ * transliteration.  For example, given a string <code>input</code>
+ * and a transliterator <code>t</code>, the call
+ *
+ * \htmlonly<blockquote>\endhtmlonly<code>String result = t.transliterate(input);
+ * </code>\htmlonly</blockquote>\endhtmlonly
+ *
+ * will transliterate it and return the result.  Other methods allow
+ * the client to specify a substring to be transliterated and to use
+ * {@link Replaceable } objects instead of strings, in order to
+ * preserve out-of-band information (such as text styles).
+ *
+ * <p><b>Keyboard transliteration</b>
+ *
+ * <p>Somewhat more involved is <em>keyboard</em>, or incremental
+ * transliteration.  This is the transliteration of text that is
+ * arriving from some source (typically the user's keyboard) one
+ * character at a time, or in some other piecemeal fashion.
+ *
+ * <p>In keyboard transliteration, a <code>Replaceable</code> buffer
+ * stores the text.  As text is inserted, as much as possible is
+ * transliterated on the fly.  This means a GUI that displays the
+ * contents of the buffer may show text being modified as each new
+ * character arrives.
+ *
+ * <p>Consider the simple <code>RuleBasedTransliterator</code>:
+ *
+ * \htmlonly<blockquote>\endhtmlonly<code>
+ * th&gt;{theta}<br>
+ * t&gt;{tau}
+ * </code>\htmlonly</blockquote>\endhtmlonly
+ *
+ * When the user types 't', nothing will happen, since the
+ * transliterator is waiting to see if the next character is 'h'.  To
+ * remedy this, we introduce the notion of a cursor, marked by a '|'
+ * in the output string:
+ *
+ * \htmlonly<blockquote>\endhtmlonly<code>
+ * t&gt;|{tau}<br>
+ * {tau}h&gt;{theta}
+ * </code>\htmlonly</blockquote>\endhtmlonly
+ *
+ * Now when the user types 't', tau appears, and if the next character
+ * is 'h', the tau changes to a theta.  This is accomplished by
+ * maintaining a cursor position (independent of the insertion point,
+ * and invisible in the GUI) across calls to
+ * <code>transliterate()</code>.  Typically, the cursor will
+ * be coincident with the insertion point, but in a case like the one
+ * above, it will precede the insertion point.
+ *
+ * <p>Keyboard transliteration methods maintain a set of three indices
+ * that are updated with each call to
+ * <code>transliterate()</code>, including the cursor, start,
+ * and limit.  Since these indices are changed by the method, they are
+ * passed in an <code>int[]</code> array. The <code>START</code> index
+ * marks the beginning of the substring that the transliterator will
+ * look at.  It is advanced as text becomes committed (but it is not
+ * the committed index; that's the <code>CURSOR</code>).  The
+ * <code>CURSOR</code> index, described above, marks the point at
+ * which the transliterator last stopped, either because it reached
+ * the end, or because it required more characters to disambiguate
+ * between possible inputs.  The <code>CURSOR</code> can also be
+ * explicitly set by rules in a <code>RuleBasedTransliterator</code>.
+ * Any characters before the <code>CURSOR</code> index are frozen;
+ * future keyboard transliteration calls within this input sequence
+ * will not change them.  New text is inserted at the
+ * <code>LIMIT</code> index, which marks the end of the substring that
+ * the transliterator looks at.
+ *
+ * <p>Because keyboard transliteration assumes that more characters
+ * are to arrive, it is conservative in its operation.  It only
+ * transliterates when it can do so unambiguously.  Otherwise it waits
+ * for more characters to arrive.  When the client code knows that no
+ * more characters are forthcoming, perhaps because the user has
+ * performed some input termination operation, then it should call
+ * <code>finishTransliteration()</code> to complete any
+ * pending transliterations.
+ *
+ * <p><b>Inverses</b>
+ *
+ * <p>Pairs of transliterators may be inverses of one another.  For
+ * example, if transliterator <b>A</b> transliterates characters by
+ * incrementing their Unicode value (so "abc" -> "def"), and
+ * transliterator <b>B</b> decrements character values, then <b>A</b>
+ * is an inverse of <b>B</b> and vice versa.  If we compose <b>A</b>
+ * with <b>B</b> in a compound transliterator, the result is the
+ * indentity transliterator, that is, a transliterator that does not
+ * change its input text.
+ *
+ * The <code>Transliterator</code> method <code>getInverse()</code>
+ * returns a transliterator's inverse, if one exists, or
+ * <code>null</code> otherwise.  However, the result of
+ * <code>getInverse()</code> usually will <em>not</em> be a true
+ * mathematical inverse.  This is because true inverse transliterators
+ * are difficult to formulate.  For example, consider two
+ * transliterators: <b>AB</b>, which transliterates the character 'A'
+ * to 'B', and <b>BA</b>, which transliterates 'B' to 'A'.  It might
+ * seem that these are exact inverses, since
+ *
+ * \htmlonly<blockquote>\endhtmlonly"A" x <b>AB</b> -> "B"<br>
+ * "B" x <b>BA</b> -> "A"\htmlonly</blockquote>\endhtmlonly
+ *
+ * where 'x' represents transliteration.  However,
+ *
+ * \htmlonly<blockquote>\endhtmlonly"ABCD" x <b>AB</b> -> "BBCD"<br>
+ * "BBCD" x <b>BA</b> -> "AACD"\htmlonly</blockquote>\endhtmlonly
+ *
+ * so <b>AB</b> composed with <b>BA</b> is not the
+ * identity. Nonetheless, <b>BA</b> may be usefully considered to be
+ * <b>AB</b>'s inverse, and it is on this basis that
+ * <b>AB</b><code>.getInverse()</code> could legitimately return
+ * <b>BA</b>.
+ *
+ * <p><b>IDs and display names</b>
+ *
+ * <p>A transliterator is designated by a short identifier string or
+ * <em>ID</em>.  IDs follow the format <em>source-destination</em>,
+ * where <em>source</em> describes the entity being replaced, and
+ * <em>destination</em> describes the entity replacing
+ * <em>source</em>.  The entities may be the names of scripts,
+ * particular sequences of characters, or whatever else it is that the
+ * transliterator converts to or from.  For example, a transliterator
+ * from Russian to Latin might be named "Russian-Latin".  A
+ * transliterator from keyboard escape sequences to Latin-1 characters
+ * might be named "KeyboardEscape-Latin1".  By convention, system
+ * entity names are in English, with the initial letters of words
+ * capitalized; user entity names may follow any format so long as
+ * they do not contain dashes.
+ *
+ * <p>In addition to programmatic IDs, transliterator objects have
+ * display names for presentation in user interfaces, returned by
+ * {@link #getDisplayName }.
+ *
+ * <p><b>Factory methods and registration</b>
+ *
+ * <p>In general, client code should use the factory method
+ * {@link #createInstance } to obtain an instance of a
+ * transliterator given its ID.  Valid IDs may be enumerated using
+ * <code>getAvailableIDs()</code>.  Since transliterators are mutable,
+ * multiple calls to {@link #createInstance } with the same ID will
+ * return distinct objects.
+ *
+ * <p>In addition to the system transliterators registered at startup,
+ * user transliterators may be registered by calling
+ * <code>registerInstance()</code> at run time.  A registered instance
+ * acts a template; future calls to {@link #createInstance } with the ID
+ * of the registered object return clones of that object.  Thus any
+ * object passed to <tt>registerInstance()</tt> must implement
+ * <tt>clone()</tt> propertly.  To register a transliterator subclass
+ * without instantiating it (until it is needed), users may call
+ * {@link #registerFactory }.  In this case, the objects are
+ * instantiated by invoking the zero-argument public constructor of
+ * the class.
+ *
+ * <p><b>Subclassing</b>
+ *
+ * Subclasses must implement the abstract method
+ * <code>handleTransliterate()</code>.  <p>Subclasses should override
+ * the <code>transliterate()</code> method taking a
+ * <code>Replaceable</code> and the <code>transliterate()</code>
+ * method taking a <code>String</code> and <code>StringBuffer</code>
+ * if the performance of these methods can be improved over the
+ * performance obtained by the default implementations in this class.
+ *
+ * @author Alan Liu
+ * @stable ICU 2.0
+ */
+class U_I18N_API Transliterator : public UObject {
+
+private:
+
+    /**
+     * Programmatic name, e.g., "Latin-Arabic".
+     */
+    UnicodeString ID;
+
+    /**
+     * This transliterator's filter.  Any character for which
+     * <tt>filter.contains()</tt> returns <tt>false</tt> will not be
+     * altered by this transliterator.  If <tt>filter</tt> is
+     * <tt>null</tt> then no filtering is applied.
+     */
+    UnicodeFilter* filter;
+
+    int32_t maximumContextLength;
+
+ public:
+
+    /**
+     * A context integer or pointer for a factory function, passed by
+     * value.
+     * @stable ICU 2.4
+     */
+    union Token {
+        /**
+         * This token, interpreted as a 32-bit integer.
+         * @stable ICU 2.4
+         */
+        int32_t integer;
+        /**
+         * This token, interpreted as a native pointer.
+         * @stable ICU 2.4
+         */
+        void*   pointer;
+    };
+
+    /**
+     * Return a token containing an integer.
+     * @return a token containing an integer.
+     * @internal
+     */
+    inline static Token integerToken(int32_t);
+
+    /**
+     * Return a token containing a pointer.
+     * @return a token containing a pointer.
+     * @internal
+     */
+    inline static Token pointerToken(void*);
+
+    /**
+     * A function that creates and returns a Transliterator.  When
+     * invoked, it will be passed the ID string that is being
+     * instantiated, together with the context pointer that was passed
+     * in when the factory function was first registered.  Many
+     * factory functions will ignore both parameters, however,
+     * functions that are registered to more than one ID may use the
+     * ID or the context parameter to parameterize the transliterator
+     * they create.
+     * @param ID      the string identifier for this transliterator
+     * @param context a context pointer that will be stored and
+     *                later passed to the factory function when an ID matching
+     *                the registration ID is being instantiated with this factory.
+     * @stable ICU 2.4
+     */
+    typedef Transliterator* (U_EXPORT2 *Factory)(const UnicodeString& ID, Token context);
+
+protected:
+
+    /**
+     * Default constructor.
+     * @param ID the string identifier for this transliterator
+     * @param adoptedFilter the filter.  Any character for which
+     * <tt>filter.contains()</tt> returns <tt>false</tt> will not be
+     * altered by this transliterator.  If <tt>filter</tt> is
+     * <tt>null</tt> then no filtering is applied.
+     * @stable ICU 2.4
+     */
+    Transliterator(const UnicodeString& ID, UnicodeFilter* adoptedFilter);
+
+    /**
+     * Copy constructor.
+     * @stable ICU 2.4
+     */
+    Transliterator(const Transliterator&);
+
+    /**
+     * Assignment operator.
+     * @stable ICU 2.4
+     */
+    Transliterator& operator=(const Transliterator&);
+
+    /**
+     * Create a transliterator from a basic ID.  This is an ID
+     * containing only the forward direction source, target, and
+     * variant.
+     * @param id a basic ID of the form S-T or S-T/V.
+     * @param canon canonical ID to assign to the object, or
+     * NULL to leave the ID unchanged
+     * @return a newly created Transliterator or null if the ID is
+     * invalid.
+     * @stable ICU 2.4
+     */
+    static Transliterator* createBasicInstance(const UnicodeString& id,
+                                               const UnicodeString* canon);
+
+    friend class TransliteratorParser; // for parseID()
+    friend class TransliteratorIDParser; // for createBasicInstance()
+    friend class TransliteratorAlias; // for setID()
+
+public:
+
+    /**
+     * Destructor.
+     * @stable ICU 2.0
+     */
+    virtual ~Transliterator();
+
+    /**
+     * Implements Cloneable.
+     * All subclasses are encouraged to implement this method if it is
+     * possible and reasonable to do so.  Subclasses that are to be
+     * registered with the system using <tt>registerInstance()</tt>
+     * are required to implement this method.  If a subclass does not
+     * implement clone() properly and is registered with the system
+     * using registerInstance(), then the default clone() implementation
+     * will return null, and calls to createInstance() will fail.
+     *
+     * @return a copy of the object.
+     * @see #registerInstance
+     * @stable ICU 2.0
+     */
+    virtual Transliterator* clone() const;
+
+    /**
+     * Transliterates a segment of a string, with optional filtering.
+     *
+     * @param text the string to be transliterated
+     * @param start the beginning index, inclusive; <code>0 <= start
+     * <= limit</code>.
+     * @param limit the ending index, exclusive; <code>start <= limit
+     * <= text.length()</code>.
+     * @return The new limit index.  The text previously occupying <code>[start,
+     * limit)</code> has been transliterated, possibly to a string of a different
+     * length, at <code>[start, </code><em>new-limit</em><code>)</code>, where
+     * <em>new-limit</em> is the return value. If the input offsets are out of bounds,
+     * the returned value is -1 and the input string remains unchanged.
+     * @stable ICU 2.0
+     */
+    virtual int32_t transliterate(Replaceable& text,
+                                  int32_t start, int32_t limit) const;
+
+    /**
+     * Transliterates an entire string in place. Convenience method.
+     * @param text the string to be transliterated
+     * @stable ICU 2.0
+     */
+    virtual void transliterate(Replaceable& text) const;
+
+    /**
+     * Transliterates the portion of the text buffer that can be
+     * transliterated unambiguosly after new text has been inserted,
+     * typically as a result of a keyboard event.  The new text in
+     * <code>insertion</code> will be inserted into <code>text</code>
+     * at <code>index.limit</code>, advancing
+     * <code>index.limit</code> by <code>insertion.length()</code>.
+     * Then the transliterator will try to transliterate characters of
+     * <code>text</code> between <code>index.cursor</code> and
+     * <code>index.limit</code>.  Characters before
+     * <code>index.cursor</code> will not be changed.
+     *
+     * <p>Upon return, values in <code>index</code> will be updated.
+     * <code>index.start</code> will be advanced to the first
+     * character that future calls to this method will read.
+     * <code>index.cursor</code> and <code>index.limit</code> will
+     * be adjusted to delimit the range of text that future calls to
+     * this method may change.
+     *
+     * <p>Typical usage of this method begins with an initial call
+     * with <code>index.start</code> and <code>index.limit</code>
+     * set to indicate the portion of <code>text</code> to be
+     * transliterated, and <code>index.cursor == index.start</code>.
+     * Thereafter, <code>index</code> can be used without
+     * modification in future calls, provided that all changes to
+     * <code>text</code> are made via this method.
+     *
+     * <p>This method assumes that future calls may be made that will
+     * insert new text into the buffer.  As a result, it only performs
+     * unambiguous transliterations.  After the last call to this
+     * method, there may be untransliterated text that is waiting for
+     * more input to resolve an ambiguity.  In order to perform these
+     * pending transliterations, clients should call {@link
+     * #finishTransliteration } after the last call to this
+     * method has been made.
+     *
+     * @param text the buffer holding transliterated and untransliterated text
+     * @param index an array of three integers.
+     *
+     * <ul><li><code>index.start</code>: the beginning index,
+     * inclusive; <code>0 <= index.start <= index.limit</code>.
+     *
+     * <li><code>index.limit</code>: the ending index, exclusive;
+     * <code>index.start <= index.limit <= text.length()</code>.
+     * <code>insertion</code> is inserted at
+     * <code>index.limit</code>.
+     *
+     * <li><code>index.cursor</code>: the next character to be
+     * considered for transliteration; <code>index.start <=
+     * index.cursor <= index.limit</code>.  Characters before
+     * <code>index.cursor</code> will not be changed by future calls
+     * to this method.</ul>
+     *
+     * @param insertion text to be inserted and possibly
+     * transliterated into the translation buffer at
+     * <code>index.limit</code>.  If <code>null</code> then no text
+     * is inserted.
+     * @param status    Output param to filled in with a success or an error.
+     * @see #handleTransliterate
+     * @exception IllegalArgumentException if <code>index</code>
+     * is invalid
+     * @see UTransPosition
+     * @stable ICU 2.0
+     */
+    virtual void transliterate(Replaceable& text, UTransPosition& index,
+                               const UnicodeString& insertion,
+                               UErrorCode& status) const;
+
+    /**
+     * Transliterates the portion of the text buffer that can be
+     * transliterated unambiguosly after a new character has been
+     * inserted, typically as a result of a keyboard event.  This is a
+     * convenience method; see {@link
+     * #transliterate(Replaceable&, UTransPosition&, const UnicodeString&, UErrorCode&) const}
+     * for details.
+     * @param text the buffer holding transliterated and
+     * untransliterated text
+     * @param index an array of three integers.  See {@link
+     * #transliterate(Replaceable&, UTransPosition&, const UnicodeString&, UErrorCode&) const }.
+     * @param insertion text to be inserted and possibly
+     * transliterated into the translation buffer at
+     * <code>index.limit</code>.
+     * @param status    Output param to filled in with a success or an error.
+     * @see #transliterate(Replaceable&, UTransPosition&, const UnicodeString&, UErrorCode&) const
+     * @stable ICU 2.0
+     */
+    virtual void transliterate(Replaceable& text, UTransPosition& index,
+                               UChar32 insertion,
+                               UErrorCode& status) const;
+
+    /**
+     * Transliterates the portion of the text buffer that can be
+     * transliterated unambiguosly.  This is a convenience method; see
+     * {@link
+     * #transliterate(Replaceable&, UTransPosition&, const UnicodeString&, UErrorCode&) const }
+     * for details.
+     * @param text the buffer holding transliterated and
+     * untransliterated text
+     * @param index an array of three integers.  See {@link
+     * #transliterate(Replaceable&, UTransPosition&, const UnicodeString&, UErrorCode&) const }.
+     * @param status    Output param to filled in with a success or an error.
+     * @see #transliterate(Replaceable, int[], String)
+     * @stable ICU 2.0
+     */
+    virtual void transliterate(Replaceable& text, UTransPosition& index,
+                               UErrorCode& status) const;
+
+    /**
+     * Finishes any pending transliterations that were waiting for
+     * more characters.  Clients should call this method as the last
+     * call after a sequence of one or more calls to
+     * <code>transliterate()</code>.
+     * @param text the buffer holding transliterated and
+     * untransliterated text.
+     * @param index the array of indices previously passed to {@link
+     * #transliterate }
+     * @stable ICU 2.0
+     */
+    virtual void finishTransliteration(Replaceable& text,
+                                       UTransPosition& index) const;
+
+private:
+
+    /**
+     * This internal method does incremental transliteration.  If the
+     * 'insertion' is non-null then we append it to 'text' before
+     * proceeding.  This method calls through to the pure virtual
+     * framework method handleTransliterate() to do the actual
+     * work.
+     * @param text the buffer holding transliterated and
+     * untransliterated text
+     * @param index an array of three integers.  See {@link
+     * #transliterate(Replaceable, int[], String)}.
+     * @param insertion text to be inserted and possibly
+     * transliterated into the translation buffer at
+     * <code>index.limit</code>.
+     * @param status    Output param to filled in with a success or an error.
+     */
+    void _transliterate(Replaceable& text,
+                        UTransPosition& index,
+                        const UnicodeString* insertion,
+                        UErrorCode &status) const;
+
+protected:
+
+    /**
+     * Abstract method that concrete subclasses define to implement
+     * their transliteration algorithm.  This method handles both
+     * incremental and non-incremental transliteration.  Let
+     * <code>originalStart</code> refer to the value of
+     * <code>pos.start</code> upon entry.
+     *
+     * <ul>
+     *  <li>If <code>incremental</code> is false, then this method
+     *  should transliterate all characters between
+     *  <code>pos.start</code> and <code>pos.limit</code>. Upon return
+     *  <code>pos.start</code> must == <code> pos.limit</code>.</li>
+     *
+     *  <li>If <code>incremental</code> is true, then this method
+     *  should transliterate all characters between
+     *  <code>pos.start</code> and <code>pos.limit</code> that can be
+     *  unambiguously transliterated, regardless of future insertions
+     *  of text at <code>pos.limit</code>.  Upon return,
+     *  <code>pos.start</code> should be in the range
+     *  [<code>originalStart</code>, <code>pos.limit</code>).
+     *  <code>pos.start</code> should be positioned such that
+     *  characters [<code>originalStart</code>, <code>
+     *  pos.start</code>) will not be changed in the future by this
+     *  transliterator and characters [<code>pos.start</code>,
+     *  <code>pos.limit</code>) are unchanged.</li>
+     * </ul>
+     *
+     * <p>Implementations of this method should also obey the
+     * following invariants:</p>
+     *
+     * <ul>
+     *  <li> <code>pos.limit</code> and <code>pos.contextLimit</code>
+     *  should be updated to reflect changes in length of the text
+     *  between <code>pos.start</code> and <code>pos.limit</code>. The
+     *  difference <code> pos.contextLimit - pos.limit</code> should
+     *  not change.</li>
+     *
+     *  <li><code>pos.contextStart</code> should not change.</li>
+     *
+     *  <li>Upon return, neither <code>pos.start</code> nor
+     *  <code>pos.limit</code> should be less than
+     *  <code>originalStart</code>.</li>
+     *
+     *  <li>Text before <code>originalStart</code> and text after
+     *  <code>pos.limit</code> should not change.</li>
+     *
+     *  <li>Text before <code>pos.contextStart</code> and text after
+     *  <code> pos.contextLimit</code> should be ignored.</li>
+     * </ul>
+     *
+     * <p>Subclasses may safely assume that all characters in
+     * [<code>pos.start</code>, <code>pos.limit</code>) are filtered.
+     * In other words, the filter has already been applied by the time
+     * this method is called.  See
+     * <code>filteredTransliterate()</code>.
+     *
+     * <p>This method is <b>not</b> for public consumption.  Calling
+     * this method directly will transliterate
+     * [<code>pos.start</code>, <code>pos.limit</code>) without
+     * applying the filter. End user code should call <code>
+     * transliterate()</code> instead of this method. Subclass code
+     * and wrapping transliterators should call
+     * <code>filteredTransliterate()</code> instead of this method.<p>
+     *
+     * @param text the buffer holding transliterated and
+     * untransliterated text
+     *
+     * @param pos the indices indicating the start, limit, context
+     * start, and context limit of the text.
+     *
+     * @param incremental if true, assume more text may be inserted at
+     * <code>pos.limit</code> and act accordingly.  Otherwise,
+     * transliterate all text between <code>pos.start</code> and
+     * <code>pos.limit</code> and move <code>pos.start</code> up to
+     * <code>pos.limit</code>.
+     *
+     * @see #transliterate
+     * @stable ICU 2.4
+     */
+    virtual void handleTransliterate(Replaceable& text,
+                                     UTransPosition& pos,
+                                     UBool incremental) const = 0;
+
+public:
+    /**
+     * Transliterate a substring of text, as specified by index, taking filters
+     * into account.  This method is for subclasses that need to delegate to
+     * another transliterator, such as CompoundTransliterator.
+     * @param text the text to be transliterated
+     * @param index the position indices
+     * @param incremental if TRUE, then assume more characters may be inserted
+     * at index.limit, and postpone processing to accomodate future incoming
+     * characters
+     * @stable ICU 2.4
+     */
+    virtual void filteredTransliterate(Replaceable& text,
+                                       UTransPosition& index,
+                                       UBool incremental) const;
+
+private:
+
+    /**
+     * Top-level transliteration method, handling filtering, incremental and
+     * non-incremental transliteration, and rollback.  All transliteration
+     * public API methods eventually call this method with a rollback argument
+     * of TRUE.  Other entities may call this method but rollback should be
+     * FALSE.
+     *
+     * <p>If this transliterator has a filter, break up the input text into runs
+     * of unfiltered characters.  Pass each run to
+     * <subclass>.handleTransliterate().
+     *
+     * <p>In incremental mode, if rollback is TRUE, perform a special
+     * incremental procedure in which several passes are made over the input
+     * text, adding one character at a time, and committing successful
+     * transliterations as they occur.  Unsuccessful transliterations are rolled
+     * back and retried with additional characters to give correct results.
+     *
+     * @param text the text to be transliterated
+     * @param index the position indices
+     * @param incremental if TRUE, then assume more characters may be inserted
+     * at index.limit, and postpone processing to accomodate future incoming
+     * characters
+     * @param rollback if TRUE and if incremental is TRUE, then perform special
+     * incremental processing, as described above, and undo partial
+     * transliterations where necessary.  If incremental is FALSE then this
+     * parameter is ignored.
+     */
+    virtual void filteredTransliterate(Replaceable& text,
+                                       UTransPosition& index,
+                                       UBool incremental,
+                                       UBool rollback) const;
+
+public:
+
+    /**
+     * Returns the length of the longest context required by this transliterator.
+     * This is <em>preceding</em> context.  The default implementation supplied
+     * by <code>Transliterator</code> returns zero; subclasses
+     * that use preceding context should override this method to return the
+     * correct value.  For example, if a transliterator translates "ddd" (where
+     * d is any digit) to "555" when preceded by "(ddd)", then the preceding
+     * context length is 5, the length of "(ddd)".
+     *
+     * @return The maximum number of preceding context characters this
+     * transliterator needs to examine
+     * @stable ICU 2.0
+     */
+    int32_t getMaximumContextLength(void) const;
+
+protected:
+
+    /**
+     * Method for subclasses to use to set the maximum context length.
+     * @param maxContextLength the new value to be set.
+     * @see #getMaximumContextLength
+     * @stable ICU 2.4
+     */
+    void setMaximumContextLength(int32_t maxContextLength);
+
+public:
+
+    /**
+     * Returns a programmatic identifier for this transliterator.
+     * If this identifier is passed to <code>createInstance()</code>, it
+     * will return this object, if it has been registered.
+     * @return a programmatic identifier for this transliterator.
+     * @see #registerInstance
+     * @see #registerFactory
+     * @see #getAvailableIDs
+     * @stable ICU 2.0
+     */
+    virtual const UnicodeString& getID(void) const;
+
+    /**
+     * Returns a name for this transliterator that is appropriate for
+     * display to the user in the default locale.  See {@link
+     * #getDisplayName } for details.
+     * @param ID     the string identifier for this transliterator
+     * @param result Output param to receive the display name
+     * @return       A reference to 'result'.
+     * @stable ICU 2.0
+     */
+    static UnicodeString& U_EXPORT2 getDisplayName(const UnicodeString& ID,
+                                         UnicodeString& result);
+
+    /**
+     * Returns a name for this transliterator that is appropriate for
+     * display to the user in the given locale.  This name is taken
+     * from the locale resource data in the standard manner of the
+     * <code>java.text</code> package.
+     *
+     * <p>If no localized names exist in the system resource bundles,
+     * a name is synthesized using a localized
+     * <code>MessageFormat</code> pattern from the resource data.  The
+     * arguments to this pattern are an integer followed by one or two
+     * strings.  The integer is the number of strings, either 1 or 2.
+     * The strings are formed by splitting the ID for this
+     * transliterator at the first '-'.  If there is no '-', then the
+     * entire ID forms the only string.
+     * @param ID       the string identifier for this transliterator
+     * @param inLocale the Locale in which the display name should be
+     *                 localized.
+     * @param result   Output param to receive the display name
+     * @return         A reference to 'result'.
+     * @stable ICU 2.0
+     */
+    static UnicodeString& U_EXPORT2 getDisplayName(const UnicodeString& ID,
+                                         const Locale& inLocale,
+                                         UnicodeString& result);
+
+    /**
+     * Returns the filter used by this transliterator, or <tt>NULL</tt>
+     * if this transliterator uses no filter.
+     * @return the filter used by this transliterator, or <tt>NULL</tt>
+     *         if this transliterator uses no filter.
+     * @stable ICU 2.0
+     */
+    const UnicodeFilter* getFilter(void) const;
+
+    /**
+     * Returns the filter used by this transliterator, or <tt>NULL</tt> if this
+     * transliterator uses no filter.  The caller must eventually delete the
+     * result.  After this call, this transliterator's filter is set to
+     * <tt>NULL</tt>.
+     * @return the filter used by this transliterator, or <tt>NULL</tt> if this
+     *         transliterator uses no filter.
+     * @stable ICU 2.4
+     */
+    UnicodeFilter* orphanFilter(void);
+
+    /**
+     * Changes the filter used by this transliterator.  If the filter
+     * is set to <tt>null</tt> then no filtering will occur.
+     *
+     * <p>Callers must take care if a transliterator is in use by
+     * multiple threads.  The filter should not be changed by one
+     * thread while another thread may be transliterating.
+     * @param adoptedFilter the new filter to be adopted.
+     * @stable ICU 2.0
+     */
+    void adoptFilter(UnicodeFilter* adoptedFilter);
+
+    /**
+     * Returns this transliterator's inverse.  See the class
+     * documentation for details.  This implementation simply inverts
+     * the two entities in the ID and attempts to retrieve the
+     * resulting transliterator.  That is, if <code>getID()</code>
+     * returns "A-B", then this method will return the result of
+     * <code>createInstance("B-A")</code>, or <code>null</code> if that
+     * call fails.
+     *
+     * <p>Subclasses with knowledge of their inverse may wish to
+     * override this method.
+     *
+     * @param status Output param to filled in with a success or an error.
+     * @return a transliterator that is an inverse, not necessarily
+     * exact, of this transliterator, or <code>null</code> if no such
+     * transliterator is registered.
+     * @see #registerInstance
+     * @stable ICU 2.0
+     */
+    Transliterator* createInverse(UErrorCode& status) const;
+
+    /**
+     * Returns a <code>Transliterator</code> object given its ID.
+     * The ID must be either a system transliterator ID or a ID registered
+     * using <code>registerInstance()</code>.
+     *
+     * @param ID a valid ID, as enumerated by <code>getAvailableIDs()</code>
+     * @param dir        either FORWARD or REVERSE.
+     * @param parseError Struct to recieve information on position
+     *                   of error if an error is encountered
+     * @param status     Output param to filled in with a success or an error.
+     * @return A <code>Transliterator</code> object with the given ID
+     * @see #registerInstance
+     * @see #getAvailableIDs
+     * @see #getID
+     * @stable ICU 2.0
+     */
+    static Transliterator* U_EXPORT2 createInstance(const UnicodeString& ID,
+                                          UTransDirection dir,
+                                          UParseError& parseError,
+                                          UErrorCode& status);
+
+    /**
+     * Returns a <code>Transliterator</code> object given its ID.
+     * The ID must be either a system transliterator ID or a ID registered
+     * using <code>registerInstance()</code>.
+     * @param ID a valid ID, as enumerated by <code>getAvailableIDs()</code>
+     * @param dir        either FORWARD or REVERSE.
+     * @param status     Output param to filled in with a success or an error.
+     * @return A <code>Transliterator</code> object with the given ID
+     * @stable ICU 2.0
+     */
+    static Transliterator* U_EXPORT2 createInstance(const UnicodeString& ID,
+                                          UTransDirection dir,
+                                          UErrorCode& status);
+
+    /**
+     * Returns a <code>Transliterator</code> object constructed from
+     * the given rule string.  This will be a RuleBasedTransliterator,
+     * if the rule string contains only rules, or a
+     * CompoundTransliterator, if it contains ID blocks, or a
+     * NullTransliterator, if it contains ID blocks which parse as
+     * empty for the given direction.
+     * @param ID            the id for the transliterator.
+     * @param rules         rules, separated by ';'
+     * @param dir           either FORWARD or REVERSE.
+     * @param parseError    Struct to recieve information on position
+     *                      of error if an error is encountered
+     * @param status        Output param set to success/failure code.
+     * @stable ICU 2.0
+     */
+    static Transliterator* U_EXPORT2 createFromRules(const UnicodeString& ID,
+                                           const UnicodeString& rules,
+                                           UTransDirection dir,
+                                           UParseError& parseError,
+                                           UErrorCode& status);
+
+    /**
+     * Create a rule string that can be passed to createFromRules()
+     * to recreate this transliterator.
+     * @param result the string to receive the rules.  Previous
+     * contents will be deleted.
+     * @param escapeUnprintable if TRUE then convert unprintable
+     * character to their hex escape representations, \\uxxxx or
+     * \\Uxxxxxxxx.  Unprintable characters are those other than
+     * U+000A, U+0020..U+007E.
+     * @stable ICU 2.0
+     */
+    virtual UnicodeString& toRules(UnicodeString& result,
+                                   UBool escapeUnprintable) const;
+
+    /**
+     * Return the number of elements that make up this transliterator.
+     * For example, if the transliterator "NFD;Jamo-Latin;Latin-Greek"
+     * were created, the return value of this method would be 3.
+     *
+     * <p>If this transliterator is not composed of other
+     * transliterators, then this method returns 1.
+     * @return the number of transliterators that compose this
+     * transliterator, or 1 if this transliterator is not composed of
+     * multiple transliterators
+     * @stable ICU 3.0
+     */
+    int32_t countElements() const;
+
+    /**
+     * Return an element that makes up this transliterator.  For
+     * example, if the transliterator "NFD;Jamo-Latin;Latin-Greek"
+     * were created, the return value of this method would be one
+     * of the three transliterator objects that make up that
+     * transliterator: [NFD, Jamo-Latin, Latin-Greek].
+     *
+     * <p>If this transliterator is not composed of other
+     * transliterators, then this method will return a reference to
+     * this transliterator when given the index 0.
+     * @param index a value from 0..countElements()-1 indicating the
+     * transliterator to return
+     * @param ec input-output error code
+     * @return one of the transliterators that makes up this
+     * transliterator, if this transliterator is made up of multiple
+     * transliterators, otherwise a reference to this object if given
+     * an index of 0
+     * @stable ICU 3.0
+     */
+    const Transliterator& getElement(int32_t index, UErrorCode& ec) const;
+
+    /**
+     * Returns the set of all characters that may be modified in the
+     * input text by this Transliterator.  This incorporates this
+     * object's current filter; if the filter is changed, the return
+     * value of this function will change.  The default implementation
+     * returns an empty set.  Some subclasses may override {@link
+     * #handleGetSourceSet } to return a more precise result.  The
+     * return result is approximate in any case and is intended for
+     * use by tests, tools, or utilities.
+     * @param result receives result set; previous contents lost
+     * @return a reference to result
+     * @see #getTargetSet
+     * @see #handleGetSourceSet
+     * @stable ICU 2.4
+     */
+    UnicodeSet& getSourceSet(UnicodeSet& result) const;
+
+    /**
+     * Framework method that returns the set of all characters that
+     * may be modified in the input text by this Transliterator,
+     * ignoring the effect of this object's filter.  The base class
+     * implementation returns the empty set.  Subclasses that wish to
+     * implement this should override this method.
+     * @return the set of characters that this transliterator may
+     * modify.  The set may be modified, so subclasses should return a
+     * newly-created object.
+     * @param result receives result set; previous contents lost
+     * @see #getSourceSet
+     * @see #getTargetSet
+     * @stable ICU 2.4
+     */
+    virtual void handleGetSourceSet(UnicodeSet& result) const;
+
+    /**
+     * Returns the set of all characters that may be generated as
+     * replacement text by this transliterator.  The default
+     * implementation returns the empty set.  Some subclasses may
+     * override this method to return a more precise result.  The
+     * return result is approximate in any case and is intended for
+     * use by tests, tools, or utilities requiring such
+     * meta-information.
+     * @param result receives result set; previous contents lost
+     * @return a reference to result
+     * @see #getTargetSet
+     * @stable ICU 2.4
+     */
+    virtual UnicodeSet& getTargetSet(UnicodeSet& result) const;
+
+public:
+
+    /**
+     * Registers a factory function that creates transliterators of
+     * a given ID.
+     * @param id the ID being registered
+     * @param factory a function pointer that will be copied and
+     * called later when the given ID is passed to createInstance()
+     * @param context a context pointer that will be stored and
+     * later passed to the factory function when an ID matching
+     * the registration ID is being instantiated with this factory.
+     * @stable ICU 2.0
+     */
+    static void U_EXPORT2 registerFactory(const UnicodeString& id,
+                                Factory factory,
+                                Token context);
+
+    /**
+     * Registers an instance <tt>obj</tt> of a subclass of
+     * <code>Transliterator</code> with the system.  When
+     * <tt>createInstance()</tt> is called with an ID string that is
+     * equal to <tt>obj->getID()</tt>, then <tt>obj->clone()</tt> is
+     * returned.
+     *
+     * After this call the Transliterator class owns the adoptedObj
+     * and will delete it.
+     *
+     * @param adoptedObj an instance of subclass of
+     * <code>Transliterator</code> that defines <tt>clone()</tt>
+     * @see #createInstance
+     * @see #registerFactory
+     * @see #unregister
+     * @stable ICU 2.0
+     */
+    static void U_EXPORT2 registerInstance(Transliterator* adoptedObj);
+
+    /**
+     * Registers an ID string as an alias of another ID string.
+     * That is, after calling this function, <tt>createInstance(aliasID)</tt>
+     * will return the same thing as <tt>createInstance(realID)</tt>.
+     * This is generally used to create shorter, more mnemonic aliases
+     * for long compound IDs.
+     *
+     * @param aliasID The new ID being registered.
+     * @param realID The ID that the new ID is to be an alias for.
+     * This can be a compound ID and can include filters and should
+     * refer to transliterators that have already been registered with
+     * the framework, although this isn't checked.
+     * @stable ICU 3.6
+     */
+     static void U_EXPORT2 registerAlias(const UnicodeString& aliasID,
+                                         const UnicodeString& realID);
+
+protected:
+
+    /**
+     * @internal
+     * @param id the ID being registered
+     * @param factory a function pointer that will be copied and
+     * called later when the given ID is passed to createInstance()
+     * @param context a context pointer that will be stored and
+     * later passed to the factory function when an ID matching
+     * the registration ID is being instantiated with this factory.
+     */
+    static void _registerFactory(const UnicodeString& id,
+                                 Factory factory,
+                                 Token context);
+
+    /**
+     * @internal
+     */
+    static void _registerInstance(Transliterator* adoptedObj);
+
+    /**
+     * @internal
+     */
+    static void _registerAlias(const UnicodeString& aliasID, const UnicodeString& realID);
+
+    /**
+     * Register two targets as being inverses of one another.  For
+     * example, calling registerSpecialInverse("NFC", "NFD", true) causes
+     * Transliterator to form the following inverse relationships:
+     *
+     * <pre>NFC => NFD
+     * Any-NFC => Any-NFD
+     * NFD => NFC
+     * Any-NFD => Any-NFC</pre>
+     *
+     * (Without the special inverse registration, the inverse of NFC
+     * would be NFC-Any.)  Note that NFD is shorthand for Any-NFD, but
+     * that the presence or absence of "Any-" is preserved.
+     *
+     * <p>The relationship is symmetrical; registering (a, b) is
+     * equivalent to registering (b, a).
+     *
+     * <p>The relevant IDs must still be registered separately as
+     * factories or classes.
+     *
+     * <p>Only the targets are specified.  Special inverses always
+     * have the form Any-Target1 <=> Any-Target2.  The target should
+     * have canonical casing (the casing desired to be produced when
+     * an inverse is formed) and should contain no whitespace or other
+     * extraneous characters.
+     *
+     * @param target the target against which to register the inverse
+     * @param inverseTarget the inverse of target, that is
+     * Any-target.getInverse() => Any-inverseTarget
+     * @param bidirectional if true, register the reverse relation
+     * as well, that is, Any-inverseTarget.getInverse() => Any-target
+     * @internal
+     */
+    static void _registerSpecialInverse(const UnicodeString& target,
+                                        const UnicodeString& inverseTarget,
+                                        UBool bidirectional);
+
+public:
+
+    /**
+     * Unregisters a transliterator or class.  This may be either
+     * a system transliterator or a user transliterator or class.
+     * Any attempt to construct an unregistered transliterator based
+     * on its ID will fail.
+     *
+     * @param ID the ID of the transliterator or class
+     * @return the <code>Object</code> that was registered with
+     * <code>ID</code>, or <code>null</code> if none was
+     * @see #registerInstance
+     * @see #registerFactory
+     * @stable ICU 2.0
+     */
+    static void U_EXPORT2 unregister(const UnicodeString& ID);
+
+public:
+
+    /**
+     * Return a StringEnumeration over the IDs available at the time of the
+     * call, including user-registered IDs.
+     * @param ec input-output error code
+     * @return a newly-created StringEnumeration over the transliterators
+     * available at the time of the call. The caller should delete this object
+     * when done using it.
+     * @stable ICU 3.0
+     */
+    static StringEnumeration* U_EXPORT2 getAvailableIDs(UErrorCode& ec);
+
+    /**
+     * Return the number of registered source specifiers.
+     * @return the number of registered source specifiers.
+     * @stable ICU 2.0
+     */
+    static int32_t U_EXPORT2 countAvailableSources(void);
+
+    /**
+     * Return a registered source specifier.
+     * @param index which specifier to return, from 0 to n-1, where
+     * n = countAvailableSources()
+     * @param result fill-in paramter to receive the source specifier.
+     * If index is out of range, result will be empty.
+     * @return reference to result
+     * @stable ICU 2.0
+     */
+    static UnicodeString& U_EXPORT2 getAvailableSource(int32_t index,
+                                             UnicodeString& result);
+
+    /**
+     * Return the number of registered target specifiers for a given
+     * source specifier.
+     * @param source the given source specifier.
+     * @return the number of registered target specifiers for a given
+     *         source specifier.
+     * @stable ICU 2.0
+     */
+    static int32_t U_EXPORT2 countAvailableTargets(const UnicodeString& source);
+
+    /**
+     * Return a registered target specifier for a given source.
+     * @param index which specifier to return, from 0 to n-1, where
+     * n = countAvailableTargets(source)
+     * @param source the source specifier
+     * @param result fill-in paramter to receive the target specifier.
+     * If source is invalid or if index is out of range, result will
+     * be empty.
+     * @return reference to result
+     * @stable ICU 2.0
+     */
+    static UnicodeString& U_EXPORT2 getAvailableTarget(int32_t index,
+                                             const UnicodeString& source,
+                                             UnicodeString& result);
+
+    /**
+     * Return the number of registered variant specifiers for a given
+     * source-target pair.
+     * @param source    the source specifiers.
+     * @param target    the target specifiers.
+     * @stable ICU 2.0
+     */
+    static int32_t U_EXPORT2 countAvailableVariants(const UnicodeString& source,
+                                          const UnicodeString& target);
+
+    /**
+     * Return a registered variant specifier for a given source-target
+     * pair.
+     * @param index which specifier to return, from 0 to n-1, where
+     * n = countAvailableVariants(source, target)
+     * @param source the source specifier
+     * @param target the target specifier
+     * @param result fill-in paramter to receive the variant
+     * specifier.  If source is invalid or if target is invalid or if
+     * index is out of range, result will be empty.
+     * @return reference to result
+     * @stable ICU 2.0
+     */
+    static UnicodeString& U_EXPORT2 getAvailableVariant(int32_t index,
+                                              const UnicodeString& source,
+                                              const UnicodeString& target,
+                                              UnicodeString& result);
+
+protected:
+
+    /**
+     * Non-mutexed internal method
+     * @internal
+     */
+    static int32_t _countAvailableSources(void);
+
+    /**
+     * Non-mutexed internal method
+     * @internal
+     */
+    static UnicodeString& _getAvailableSource(int32_t index,
+                                              UnicodeString& result);
+
+    /**
+     * Non-mutexed internal method
+     * @internal
+     */
+    static int32_t _countAvailableTargets(const UnicodeString& source);
+
+    /**
+     * Non-mutexed internal method
+     * @internal
+     */
+    static UnicodeString& _getAvailableTarget(int32_t index,
+                                              const UnicodeString& source,
+                                              UnicodeString& result);
+
+    /**
+     * Non-mutexed internal method
+     * @internal
+     */
+    static int32_t _countAvailableVariants(const UnicodeString& source,
+                                           const UnicodeString& target);
+
+    /**
+     * Non-mutexed internal method
+     * @internal
+     */
+    static UnicodeString& _getAvailableVariant(int32_t index,
+                                               const UnicodeString& source,
+                                               const UnicodeString& target,
+                                               UnicodeString& result);
+
+protected:
+
+    /**
+     * Set the ID of this transliterators.  Subclasses shouldn't do
+     * this, unless the underlying script behavior has changed.
+     * @param id the new id t to be set.
+     * @stable ICU 2.4
+     */
+    void setID(const UnicodeString& id);
+
+public:
+
+    /**
+     * Return the class ID for this class.  This is useful only for
+     * comparing to a return value from getDynamicClassID().
+     * Note that Transliterator is an abstract base class, and therefor
+     * no fully constructed object will  have a dynamic
+     * UCLassID that equals the UClassID returned from
+     * TRansliterator::getStaticClassID().
+     * @return       The class ID for class Transliterator.
+     * @stable ICU 2.0
+     */
+    static UClassID U_EXPORT2 getStaticClassID(void);
+
+    /**
+     * Returns a unique class ID <b>polymorphically</b>.  This method
+     * is to implement a simple version of RTTI, since not all C++
+     * compilers support genuine RTTI.  Polymorphic operator==() and
+     * clone() methods call this method.
+     *
+     * <p>Concrete subclasses of Transliterator must use the
+     *    UOBJECT_DEFINE_RTTI_IMPLEMENTATION macro from
+     *    uobject.h to provide the RTTI functions.
+     *
+     * @return The class ID for this object. All objects of a given
+     * class have the same class ID.  Objects of other classes have
+     * different class IDs.
+     * @stable ICU 2.0
+     */
+    virtual UClassID getDynamicClassID(void) const = 0;
+
+private:
+    static UBool initializeRegistry(UErrorCode &status);
+
+public:
+    /**
+     * Return the number of IDs currently registered with the system.
+     * To retrieve the actual IDs, call getAvailableID(i) with
+     * i from 0 to countAvailableIDs() - 1.
+     * @return the number of IDs currently registered with the system.
+     * @obsolete ICU 3.4 use getAvailableIDs() instead
+     */
+    static int32_t U_EXPORT2 countAvailableIDs(void);
+
+    /**
+     * Return the index-th available ID.  index must be between 0
+     * and countAvailableIDs() - 1, inclusive.  If index is out of
+     * range, the result of getAvailableID(0) is returned.
+     * @param index the given ID index.
+     * @return      the index-th available ID.  index must be between 0
+     *              and countAvailableIDs() - 1, inclusive.  If index is out of
+     *              range, the result of getAvailableID(0) is returned.
+     * @obsolete ICU 3.4 use getAvailableIDs() instead; this function
+     * is not thread safe, since it returns a reference to storage that
+     * may become invalid if another thread calls unregister
+     */
+    static const UnicodeString& U_EXPORT2 getAvailableID(int32_t index);
+};
+
+inline int32_t Transliterator::getMaximumContextLength(void) const {
+    return maximumContextLength;
+}
+
+inline void Transliterator::setID(const UnicodeString& id) {
+    ID = id;
+    // NUL-terminate the ID string, which is a non-aliased copy.
+    ID.append((UChar)0);
+    ID.truncate(ID.length()-1);
+}
+
+inline Transliterator::Token Transliterator::integerToken(int32_t i) {
+    Token t;
+    t.integer = i;
+    return t;
+}
+
+inline Transliterator::Token Transliterator::pointerToken(void* p) {
+    Token t;
+    t.pointer = p;
+    return t;
+}
+
+U_NAMESPACE_END
+
+#endif /* #if !UCONFIG_NO_TRANSLITERATION */
+
+#endif


[64/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/umsg.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/umsg.h b/src/apps/couch_collate/platform/osx/icu/unicode/umsg.h
new file mode 100644
index 0000000..32ed063
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/umsg.h
@@ -0,0 +1,647 @@
+/*
+*******************************************************************************
+* Copyright (C) 1996-2006, International Business Machines Corporation
+* and others. All Rights Reserved.
+*******************************************************************************
+*
+*   file name:  umsg.h
+*   encoding:   US-ASCII
+*   tab size:   8 (not used)
+*   indentation:4
+*
+*   Change history:
+*
+*   08/5/2001  Ram         Added C wrappers for C++ API.
+*                          
+*
+*/
+
+#ifndef UMSG_H
+#define UMSG_H
+
+#include "unicode/utypes.h"
+
+#if !UCONFIG_NO_FORMATTING
+
+#include "unicode/uloc.h"
+#include "unicode/parseerr.h"
+#include <stdarg.h>
+/**
+ * \file
+ * \brief C API: MessageFormat
+ *
+ * <h2>Message Format C API </h2>
+ *
+ * Provides means to produce concatenated messages in language-neutral way.
+ * Use this for all concatenations that show up to end users.
+ * <P>
+ * Takes a set of objects, formats them, then inserts the formatted
+ * strings into the pattern at the appropriate places.
+ * <P>
+ * Here are some examples of usage:
+ * Example 1:
+ * <pre>
+ * \code
+ *     UChar *result, *tzID, *str;
+ *     UChar pattern[100];
+ *     int32_t resultLengthOut, resultlength;
+ *     UCalendar *cal;
+ *     UDate d1;
+ *     UDateFormat *def1;
+ *     UErrorCode status = U_ZERO_ERROR;
+ *
+ *     str=(UChar*)malloc(sizeof(UChar) * (strlen("disturbance in force") +1));
+ *     u_uastrcpy(str, "disturbance in force");
+ *     tzID=(UChar*)malloc(sizeof(UChar) * 4);
+ *     u_uastrcpy(tzID, "PST");
+ *     cal=ucal_open(tzID, u_strlen(tzID), "en_US", UCAL_TRADITIONAL, &status);
+ *     ucal_setDateTime(cal, 1999, UCAL_MARCH, 18, 0, 0, 0, &status);
+ *     d1=ucal_getMillis(cal, &status);
+ *     u_uastrcpy(pattern, "On {0, date, long}, there was a {1} on planet {2,number,integer}");
+ *     resultlength=0;
+ *     resultLengthOut=u_formatMessage( "en_US", pattern, u_strlen(pattern), NULL, resultlength, &status, d1, str, 7);
+ *     if(status==U_BUFFER_OVERFLOW_ERROR){
+ *         status=U_ZERO_ERROR;
+ *         resultlength=resultLengthOut+1;
+ *         result=(UChar*)realloc(result, sizeof(UChar) * resultlength);
+ *         u_formatMessage( "en_US", pattern, u_strlen(pattern), result, resultlength, &status, d1, str, 7);
+ *     }
+ *     printf("%s\n", austrdup(result) );//austrdup( a function used to convert UChar* to char*)
+ *     //output>: "On March 18, 1999, there was a disturbance in force on planet 7
+ * \endcode
+ * </pre>
+ * Typically, the message format will come from resources, and the
+ * arguments will be dynamically set at runtime.
+ * <P>
+ * Example 2:
+ * <pre>
+ * \code
+ *     UChar* str;
+ *     UErrorCode status = U_ZERO_ERROR;
+ *     UChar *result;
+ *     UChar pattern[100];
+ *     int32_t resultlength, resultLengthOut, i;
+ *     double testArgs= { 100.0, 1.0, 0.0};
+ *
+ *     str=(UChar*)malloc(sizeof(UChar) * 10);
+ *     u_uastrcpy(str, "MyDisk");
+ *     u_uastrcpy(pattern, "The disk {1} contains {0,choice,0#no files|1#one file|1<{0,number,integer} files}");
+ *     for(i=0; i<3; i++){
+ *       resultlength=0;
+ *       resultLengthOut=u_formatMessage( "en_US", pattern, u_strlen(pattern), NULL, resultlength, &status, testArgs[i], str);
+ *       if(status==U_BUFFER_OVERFLOW_ERROR){
+ *         status=U_ZERO_ERROR;
+ *         resultlength=resultLengthOut+1;
+ *         result=(UChar*)malloc(sizeof(UChar) * resultlength);
+ *         u_formatMessage( "en_US", pattern, u_strlen(pattern), result, resultlength, &status, testArgs[i], str);
+ *       }
+ *       printf("%s\n", austrdup(result) );  //austrdup( a function used to convert UChar* to char*)
+ *       free(result);
+ *     }
+ *     // output, with different testArgs:
+ *     // output: The disk "MyDisk" contains 100 files.
+ *     // output: The disk "MyDisk" contains one file.
+ *     // output: The disk "MyDisk" contains no files.
+ * \endcode
+ *  </pre>
+ *
+ *  The pattern is of the following form.  Legend:
+ *  <pre>
+ * \code
+ *       {optional item}
+ *       (group that may be repeated)*
+ * \endcode
+ *  </pre>
+ *  Do not confuse optional items with items inside quotes braces, such
+ *  as this: "{".  Quoted braces are literals.
+ *  <pre>
+ * \code
+ *       messageFormatPattern := string ( "{" messageFormatElement "}" string )*
+ *
+ *       messageFormatElement := argument { "," elementFormat }
+ *
+ *       elementFormat := "time" { "," datetimeStyle }
+ *                      | "date" { "," datetimeStyle }
+ *                      | "number" { "," numberStyle }
+ *                      | "choice" "," choiceStyle
+ *
+ *       datetimeStyle := "short"
+ *                      | "medium"
+ *                      | "long"
+ *                      | "full"
+ *                      | dateFormatPattern
+ *
+ *       numberStyle :=   "currency"
+ *                      | "percent"
+ *                      | "integer"
+ *                      | numberFormatPattern
+ *
+ *       choiceStyle :=   choiceFormatPattern
+ * \endcode
+ * </pre>
+ * If there is no elementFormat, then the argument must be a string,
+ * which is substituted. If there is no dateTimeStyle or numberStyle,
+ * then the default format is used (e.g.  NumberFormat.getInstance(),
+ * DateFormat.getDefaultTime() or DateFormat.getDefaultDate(). For
+ * a ChoiceFormat, the pattern must always be specified, since there
+ * is no default.
+ * <P>
+ * In strings, single quotes can be used to quote the "{" sign if
+ * necessary. A real single quote is represented by ''.  Inside a
+ * messageFormatElement, quotes are [not] removed. For example,
+ * {1,number,$'#',##} will produce a number format with the pound-sign
+ * quoted, with a result such as: "$#31,45".
+ * <P>
+ * If a pattern is used, then unquoted braces in the pattern, if any,
+ * must match: that is, "ab {0} de" and "ab '}' de" are ok, but "ab
+ * {0'}' de" and "ab } de" are not.
+ * <p>
+ * <dl><dt><b>Warning:</b><dd>The rules for using quotes within message
+ * format patterns unfortunately have shown to be somewhat confusing.
+ * In particular, it isn't always obvious to localizers whether single
+ * quotes need to be doubled or not. Make sure to inform localizers about
+ * the rules, and tell them (for example, by using comments in resource
+ * bundle source files) which strings will be processed by MessageFormat.
+ * Note that localizers may need to use single quotes in translated
+ * strings where the original version doesn't have them.
+ * <br>Note also that the simplest way to avoid the problem is to
+ * use the real apostrophe (single quote) character U+2019 (') for
+ * human-readable text, and to use the ASCII apostrophe (U+0027 ' )
+ * only in program syntax, like quoting in MessageFormat.
+ * See the annotations for U+0027 Apostrophe in The Unicode Standard.</p>
+ * </dl>
+ * <P>
+ * The argument is a number from 0 to 9, which corresponds to the
+ * arguments presented in an array to be formatted.
+ * <P>
+ * It is ok to have unused arguments in the array.  With missing
+ * arguments or arguments that are not of the right class for the
+ * specified format, a failing UErrorCode result is set.
+ * <P>
+
+ * <P>
+ * [Note:] As we see above, the string produced by a choice Format in
+ * MessageFormat is treated specially; occurances of '{' are used to
+ * indicated subformats.
+ * <P>
+ * [Note:] Formats are numbered by order of variable in the string.
+ * This is [not] the same as the argument numbering!
+ * <pre>
+ * \code
+ *    For example: with "abc{2}def{3}ghi{0}...",
+ *
+ *    format0 affects the first variable {2}
+ *    format1 affects the second variable {3}
+ *    format2 affects the second variable {0}
+ * \endcode
+ * </pre>
+ * and so on.
+ */
+
+/**
+ * Format a message for a locale.
+ * This function may perform re-ordering of the arguments depending on the
+ * locale. For all numeric arguments, double is assumed unless the type is
+ * explicitly integer.  All choice format arguments must be of type double.
+ * @param locale The locale for which the message will be formatted
+ * @param pattern The pattern specifying the message's format
+ * @param patternLength The length of pattern
+ * @param result A pointer to a buffer to receive the formatted message.
+ * @param resultLength The maximum size of result.
+ * @param status A pointer to an UErrorCode to receive any errors
+ * @param ... A variable-length argument list containing the arguments specified
+ * in pattern.
+ * @return The total buffer size needed; if greater than resultLength, the
+ * output was truncated.
+ * @see u_parseMessage
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2 
+u_formatMessage(const char  *locale,
+                 const UChar *pattern,
+                int32_t     patternLength,
+                UChar       *result,
+                int32_t     resultLength,
+                UErrorCode  *status,
+                ...);
+
+/**
+ * Format a message for a locale.
+ * This function may perform re-ordering of the arguments depending on the
+ * locale. For all numeric arguments, double is assumed unless the type is
+ * explicitly integer.  All choice format arguments must be of type double.
+ * @param locale The locale for which the message will be formatted
+ * @param pattern The pattern specifying the message's format
+ * @param patternLength The length of pattern
+ * @param result A pointer to a buffer to receive the formatted message.
+ * @param resultLength The maximum size of result.
+ * @param ap A variable-length argument list containing the arguments specified
+ * @param status A pointer to an UErrorCode to receive any errors
+ * in pattern.
+ * @return The total buffer size needed; if greater than resultLength, the
+ * output was truncated.
+ * @see u_parseMessage
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2 
+u_vformatMessage(   const char  *locale,
+                    const UChar *pattern,
+                    int32_t     patternLength,
+                    UChar       *result,
+                    int32_t     resultLength,
+                    va_list     ap,
+                    UErrorCode  *status);
+
+/**
+ * Parse a message.
+ * For numeric arguments, this function will always use doubles.  Integer types
+ * should not be passed.
+ * This function is not able to parse all output from {@link #u_formatMessage }.
+ * @param locale The locale for which the message is formatted
+ * @param pattern The pattern specifying the message's format
+ * @param patternLength The length of pattern
+ * @param source The text to parse.
+ * @param sourceLength The length of source, or -1 if null-terminated.
+ * @param status A pointer to an UErrorCode to receive any errors
+ * @param ... A variable-length argument list containing the arguments
+ * specified in pattern.
+ * @see u_formatMessage
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+u_parseMessage( const char   *locale,
+                const UChar  *pattern,
+                int32_t      patternLength,
+                const UChar  *source,
+                int32_t      sourceLength,
+                UErrorCode   *status,
+                ...);
+
+/**
+ * Parse a message.
+ * For numeric arguments, this function will always use doubles.  Integer types
+ * should not be passed.
+ * This function is not able to parse all output from {@link #u_formatMessage }.
+ * @param locale The locale for which the message is formatted
+ * @param pattern The pattern specifying the message's format
+ * @param patternLength The length of pattern
+ * @param source The text to parse.
+ * @param sourceLength The length of source, or -1 if null-terminated.
+ * @param ap A variable-length argument list containing the arguments
+ * @param status A pointer to an UErrorCode to receive any errors
+ * specified in pattern.
+ * @see u_formatMessage
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+u_vparseMessage(const char  *locale,
+                const UChar *pattern,
+                int32_t     patternLength,
+                const UChar *source,
+                int32_t     sourceLength,
+                va_list     ap,
+                UErrorCode  *status);
+
+/**
+ * Format a message for a locale.
+ * This function may perform re-ordering of the arguments depending on the
+ * locale. For all numeric arguments, double is assumed unless the type is
+ * explicitly integer.  All choice format arguments must be of type double.
+ * @param locale The locale for which the message will be formatted
+ * @param pattern The pattern specifying the message's format
+ * @param patternLength The length of pattern
+ * @param result A pointer to a buffer to receive the formatted message.
+ * @param resultLength The maximum size of result.
+ * @param status A pointer to an UErrorCode to receive any errors
+ * @param ... A variable-length argument list containing the arguments specified
+ * in pattern.
+ * @param parseError  A pointer to UParseError to receive information about errors
+ *                     occurred during parsing.
+ * @return The total buffer size needed; if greater than resultLength, the
+ * output was truncated.
+ * @see u_parseMessage
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2 
+u_formatMessageWithError(   const char    *locale,
+                            const UChar   *pattern,
+                            int32_t       patternLength,
+                            UChar         *result,
+                            int32_t       resultLength,
+                            UParseError   *parseError,
+                            UErrorCode    *status,
+                            ...);
+
+/**
+ * Format a message for a locale.
+ * This function may perform re-ordering of the arguments depending on the
+ * locale. For all numeric arguments, double is assumed unless the type is
+ * explicitly integer.  All choice format arguments must be of type double.
+ * @param locale The locale for which the message will be formatted
+ * @param pattern The pattern specifying the message's format
+ * @param patternLength The length of pattern
+ * @param result A pointer to a buffer to receive the formatted message.
+ * @param resultLength The maximum size of result.
+ * @param parseError  A pointer to UParseError to receive information about errors
+ *                    occurred during parsing.
+ * @param ap A variable-length argument list containing the arguments specified
+ * @param status A pointer to an UErrorCode to receive any errors
+ * in pattern.
+ * @return The total buffer size needed; if greater than resultLength, the
+ * output was truncated.
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2 
+u_vformatMessageWithError(  const char   *locale,
+                            const UChar  *pattern,
+                            int32_t      patternLength,
+                            UChar        *result,
+                            int32_t      resultLength,
+                            UParseError* parseError,
+                            va_list      ap,
+                            UErrorCode   *status);
+
+/**
+ * Parse a message.
+ * For numeric arguments, this function will always use doubles.  Integer types
+ * should not be passed.
+ * This function is not able to parse all output from {@link #u_formatMessage }.
+ * @param locale The locale for which the message is formatted
+ * @param pattern The pattern specifying the message's format
+ * @param patternLength The length of pattern
+ * @param source The text to parse.
+ * @param sourceLength The length of source, or -1 if null-terminated.
+ * @param parseError  A pointer to UParseError to receive information about errors
+ *                     occurred during parsing.
+ * @param status A pointer to an UErrorCode to receive any errors
+ * @param ... A variable-length argument list containing the arguments
+ * specified in pattern.
+ * @see u_formatMessage
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+u_parseMessageWithError(const char  *locale,
+                        const UChar *pattern,
+                        int32_t     patternLength,
+                        const UChar *source,
+                        int32_t     sourceLength,
+                        UParseError *parseError,
+                        UErrorCode  *status,
+                        ...);
+
+/**
+ * Parse a message.
+ * For numeric arguments, this function will always use doubles.  Integer types
+ * should not be passed.
+ * This function is not able to parse all output from {@link #u_formatMessage }.
+ * @param locale The locale for which the message is formatted
+ * @param pattern The pattern specifying the message's format
+ * @param patternLength The length of pattern
+ * @param source The text to parse.
+ * @param sourceLength The length of source, or -1 if null-terminated.
+ * @param ap A variable-length argument list containing the arguments
+ * @param parseError  A pointer to UParseError to receive information about errors
+ *                     occurred during parsing.
+ * @param status A pointer to an UErrorCode to receive any errors
+ * specified in pattern.
+ * @see u_formatMessage
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+u_vparseMessageWithError(const char  *locale,
+                         const UChar *pattern,
+                         int32_t     patternLength,
+                         const UChar *source,
+                         int32_t     sourceLength,
+                         va_list     ap,
+                         UParseError *parseError,
+                         UErrorCode* status);
+
+/*----------------------- New experimental API --------------------------- */
+/** 
+ * The message format object
+ * @stable ICU 2.0
+ */
+typedef void* UMessageFormat;
+
+
+/**
+ * Open a message formatter with given pattern and for the given locale.
+ * @param pattern       A pattern specifying the format to use.
+ * @param patternLength Length of the pattern to use
+ * @param locale        The locale for which the messages are formatted.
+ * @param parseError    A pointer to UParseError struct to receive any errors 
+ *                      occured during parsing. Can be NULL.
+ * @param status        A pointer to an UErrorCode to receive any errors.
+ * @return              A pointer to a UMessageFormat to use for formatting 
+ *                      messages, or 0 if an error occurred. 
+ * @stable ICU 2.0
+ */
+U_STABLE UMessageFormat* U_EXPORT2 
+umsg_open(  const UChar     *pattern,
+            int32_t         patternLength,
+            const  char     *locale,
+            UParseError     *parseError,
+            UErrorCode      *status);
+
+/**
+ * Close a UMessageFormat.
+ * Once closed, a UMessageFormat may no longer be used.
+ * @param format The formatter to close.
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+umsg_close(UMessageFormat* format);
+
+/**
+ * Open a copy of a UMessageFormat.
+ * This function performs a deep copy.
+ * @param fmt The formatter to copy
+ * @param status A pointer to an UErrorCode to receive any errors.
+ * @return A pointer to a UDateFormat identical to fmt.
+ * @stable ICU 2.0
+ */
+U_STABLE UMessageFormat U_EXPORT2 
+umsg_clone(const UMessageFormat *fmt,
+           UErrorCode *status);
+
+/**
+ * Sets the locale. This locale is used for fetching default number or date
+ * format information.
+ * @param fmt The formatter to set
+ * @param locale The locale the formatter should use.
+ * @stable ICU 2.0
+ */
+U_STABLE void  U_EXPORT2 
+umsg_setLocale(UMessageFormat *fmt,
+               const char* locale);
+
+/**
+ * Gets the locale. This locale is used for fetching default number or date
+ * format information.
+ * @param fmt The formatter to querry
+ * @return the locale.
+ * @stable ICU 2.0
+ */
+U_STABLE const char*  U_EXPORT2 
+umsg_getLocale(const UMessageFormat *fmt);
+
+/**
+ * Sets the pattern.
+ * @param fmt           The formatter to use
+ * @param pattern       The pattern to be applied.
+ * @param patternLength Length of the pattern to use
+ * @param parseError    Struct to receive information on position 
+ *                      of error if an error is encountered.Can be NULL.
+ * @param status        Output param set to success/failure code on
+ *                      exit. If the pattern is invalid, this will be
+ *                      set to a failure result.
+ * @stable ICU 2.0
+ */
+U_STABLE void  U_EXPORT2 
+umsg_applyPattern( UMessageFormat *fmt,
+                   const UChar* pattern,
+                   int32_t patternLength,
+                   UParseError* parseError,
+                   UErrorCode* status);
+
+/**
+ * Gets the pattern.
+ * @param fmt          The formatter to use
+ * @param result       A pointer to a buffer to receive the pattern.
+ * @param resultLength The maximum size of result.
+ * @param status       Output param set to success/failure code on
+ *                     exit. If the pattern is invalid, this will be
+ *                     set to a failure result.  
+ * @return the pattern of the format
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t  U_EXPORT2 
+umsg_toPattern(const UMessageFormat *fmt,
+               UChar* result, 
+               int32_t resultLength,
+               UErrorCode* status);
+
+/**
+ * Format a message for a locale.
+ * This function may perform re-ordering of the arguments depending on the
+ * locale. For all numeric arguments, double is assumed unless the type is
+ * explicitly integer.  All choice format arguments must be of type double.
+ * @param fmt           The formatter to use
+ * @param result        A pointer to a buffer to receive the formatted message.
+ * @param resultLength  The maximum size of result.
+ * @param status        A pointer to an UErrorCode to receive any errors
+ * @param ...           A variable-length argument list containing the arguments 
+ *                      specified in pattern.
+ * @return              The total buffer size needed; if greater than resultLength, 
+ *                      the output was truncated.
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2 
+umsg_format(    const UMessageFormat *fmt,
+                UChar          *result,
+                int32_t        resultLength,
+                UErrorCode     *status,
+                ...);
+
+/**
+ * Format a message for a locale.
+ * This function may perform re-ordering of the arguments depending on the
+ * locale. For all numeric arguments, double is assumed unless the type is
+ * explicitly integer.  All choice format arguments must be of type double.
+ * @param fmt          The formatter to use 
+ * @param result       A pointer to a buffer to receive the formatted message.
+ * @param resultLength The maximum size of result.
+ * @param ap           A variable-length argument list containing the arguments 
+ * @param status       A pointer to an UErrorCode to receive any errors
+ *                     specified in pattern.
+ * @return             The total buffer size needed; if greater than resultLength, 
+ *                     the output was truncated.
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2 
+umsg_vformat(   const UMessageFormat *fmt,
+                UChar          *result,
+                int32_t        resultLength,
+                va_list        ap,
+                UErrorCode     *status);
+
+/**
+ * Parse a message.
+ * For numeric arguments, this function will always use doubles.  Integer types
+ * should not be passed.
+ * This function is not able to parse all output from {@link #umsg_format }.
+ * @param fmt           The formatter to use 
+ * @param source        The text to parse.
+ * @param sourceLength  The length of source, or -1 if null-terminated.
+ * @param count         Output param to receive number of elements returned.
+ * @param status        A pointer to an UErrorCode to receive any errors
+ * @param ...           A variable-length argument list containing the arguments
+ *                      specified in pattern.
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+umsg_parse( const UMessageFormat *fmt,
+            const UChar    *source,
+            int32_t        sourceLength,
+            int32_t        *count,
+            UErrorCode     *status,
+            ...);
+
+/**
+ * Parse a message.
+ * For numeric arguments, this function will always use doubles.  Integer types
+ * should not be passed.
+ * This function is not able to parse all output from {@link #umsg_format }.
+ * @param fmt           The formatter to use 
+ * @param source        The text to parse.
+ * @param sourceLength  The length of source, or -1 if null-terminated.
+ * @param count         Output param to receive number of elements returned.
+ * @param ap            A variable-length argument list containing the arguments
+ * @param status        A pointer to an UErrorCode to receive any errors
+ *                      specified in pattern.
+ * @see u_formatMessage
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+umsg_vparse(const UMessageFormat *fmt,
+            const UChar    *source,
+            int32_t        sourceLength,
+            int32_t        *count,
+            va_list        ap,
+            UErrorCode     *status);
+
+
+/**
+ * Convert an 'apostrophe-friendly' pattern into a standard
+ * pattern.  Standard patterns treat all apostrophes as
+ * quotes, which is problematic in some languages, e.g. 
+ * French, where apostrophe is commonly used.  This utility
+ * assumes that only an unpaired apostrophe immediately before
+ * a brace is a true quote.  Other unpaired apostrophes are paired,
+ * and the resulting standard pattern string is returned.
+ *
+ * <p><b>Note</b> it is not guaranteed that the returned pattern
+ * is indeed a valid pattern.  The only effect is to convert
+ * between patterns having different quoting semantics.
+ *
+ * @param pattern the 'apostrophe-friendly' patttern to convert
+ * @param patternLength the length of pattern, or -1 if unknown and pattern is null-terminated
+ * @param dest the buffer for the result, or NULL if preflight only
+ * @param destCapacity the length of the buffer, or 0 if preflighting
+ * @param ec the error code
+ * @return the length of the resulting text, not including trailing null
+ *        if buffer has room for the trailing null, it is provided, otherwise
+ *        not
+ * @stable ICU 3.4
+ */
+U_STABLE int32_t U_EXPORT2 
+umsg_autoQuoteApostrophe(const UChar* pattern, 
+                         int32_t patternLength,
+                         UChar* dest,
+                         int32_t destCapacity,
+                         UErrorCode* ec);
+
+#endif /* #if !UCONFIG_NO_FORMATTING */
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/unifilt.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/unifilt.h b/src/apps/couch_collate/platform/osx/icu/unicode/unifilt.h
new file mode 100644
index 0000000..5bf1ba4
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/unifilt.h
@@ -0,0 +1,127 @@
+/*
+**********************************************************************
+* Copyright (C) 1999-2006, International Business Machines Corporation and others.
+* All Rights Reserved.
+**********************************************************************
+*   Date        Name        Description
+*   11/17/99    aliu        Creation.
+**********************************************************************
+*/
+#ifndef UNIFILT_H
+#define UNIFILT_H
+
+#include "unicode/unifunct.h"
+#include "unicode/unimatch.h"
+
+/**
+ * \file 
+ * \brief C++ API: Unicode Filter
+ */
+
+U_NAMESPACE_BEGIN
+
+/**
+ * U_ETHER is used to represent character values for positions outside
+ * a range.  For example, transliterator uses this to represent
+ * characters outside the range contextStart..contextLimit-1.  This
+ * allows explicit matching by rules and UnicodeSets of text outside a
+ * defined range.
+ * @stable ICU 3.0
+ */
+#define U_ETHER ((UChar)0xFFFF)
+
+/**
+ *
+ * <code>UnicodeFilter</code> defines a protocol for selecting a
+ * subset of the full range (U+0000 to U+10FFFF) of Unicode characters.
+ * Currently, filters are used in conjunction with classes like {@link
+ * Transliterator} to only process selected characters through a
+ * transformation.
+ *
+ * <p>Note: UnicodeFilter currently stubs out two pure virtual methods
+ * of its base class, UnicodeMatcher.  These methods are toPattern()
+ * and matchesIndexValue().  This is done so that filter classes that
+ * are not actually used as matchers -- specifically, those in the
+ * UnicodeFilterLogic component, and those in tests -- can continue to
+ * work without defining these methods.  As long as a filter is not
+ * used in an RBT during real transliteration, these methods will not
+ * be called.  However, this breaks the UnicodeMatcher base class
+ * protocol, and it is not a correct solution.
+ *
+ * <p>In the future we may revisit the UnicodeMatcher / UnicodeFilter
+ * hierarchy and either redesign it, or simply remove the stubs in
+ * UnicodeFilter and force subclasses to implement the full
+ * UnicodeMatcher protocol.
+ *
+ * @see UnicodeFilterLogic
+ * @stable ICU 2.0
+ */
+class U_COMMON_API UnicodeFilter : public UnicodeFunctor, public UnicodeMatcher {
+
+public:
+    /**
+     * Destructor
+     * @stable ICU 2.0
+     */
+    virtual ~UnicodeFilter();
+
+    /**
+     * Returns <tt>true</tt> for characters that are in the selected
+     * subset.  In other words, if a character is <b>to be
+     * filtered</b>, then <tt>contains()</tt> returns
+     * <b><tt>false</tt></b>.
+     * @stable ICU 2.0
+     */
+    virtual UBool contains(UChar32 c) const = 0;
+
+    /**
+     * UnicodeFunctor API.  Cast 'this' to a UnicodeMatcher* pointer
+     * and return the pointer.
+     * @stable ICU 2.4
+     */
+    virtual UnicodeMatcher* toMatcher() const;
+
+    /**
+     * Implement UnicodeMatcher API.
+     * @stable ICU 2.4
+     */
+    virtual UMatchDegree matches(const Replaceable& text,
+                                 int32_t& offset,
+                                 int32_t limit,
+                                 UBool incremental);
+
+    /**
+     * UnicodeFunctor API.  Nothing to do.
+     * @stable ICU 2.4
+     */
+    virtual void setData(const TransliterationRuleData*);
+
+    /**
+     * ICU "poor man's RTTI", returns a UClassID for the actual class.
+     *
+     * @stable ICU 2.2
+     */
+    virtual UClassID getDynamicClassID() const = 0;
+
+    /**
+     * ICU "poor man's RTTI", returns a UClassID for this class.
+     *
+     * @stable ICU 2.2
+     */
+    static UClassID U_EXPORT2 getStaticClassID();
+
+protected:
+
+    /*
+     * Since this class has pure virtual functions,
+     * a constructor can't be used.
+     * @stable ICU 2.0
+     */
+/*    UnicodeFilter();*/
+};
+
+/*inline UnicodeFilter::UnicodeFilter() {}*/
+
+U_NAMESPACE_END
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/unifunct.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/unifunct.h b/src/apps/couch_collate/platform/osx/icu/unicode/unifunct.h
new file mode 100644
index 0000000..3aa7b03
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/unifunct.h
@@ -0,0 +1,125 @@
+/*
+**********************************************************************
+*   Copyright (c) 2002-2005, International Business Machines Corporation
+*   and others.  All Rights Reserved.
+**********************************************************************
+*   Date        Name        Description
+*   01/14/2002  aliu        Creation.
+**********************************************************************
+*/
+#ifndef UNIFUNCT_H
+#define UNIFUNCT_H
+
+#include "unicode/utypes.h"
+#include "unicode/uobject.h"
+
+/**
+ * \file 
+ * \brief C++ API: Unicode Functor
+ */
+ 
+U_NAMESPACE_BEGIN
+
+class UnicodeMatcher;
+class UnicodeReplacer;
+class TransliterationRuleData;
+
+/**
+ * <code>UnicodeFunctor</code> is an abstract base class for objects
+ * that perform match and/or replace operations on Unicode strings.
+ * @author Alan Liu
+ * @stable ICU 2.4
+ */
+class U_COMMON_API UnicodeFunctor : public UObject {
+
+public:
+
+    /**
+     * Destructor
+     * @stable ICU 2.4
+     */
+    virtual ~UnicodeFunctor();
+
+    /**
+     * Return a copy of this object.  All UnicodeFunctor objects
+     * have to support cloning in order to allow classes using
+     * UnicodeFunctor to implement cloning.
+     * @stable ICU 2.4
+     */
+    virtual UnicodeFunctor* clone() const = 0;
+
+    /**
+     * Cast 'this' to a UnicodeMatcher* pointer and return the
+     * pointer, or null if this is not a UnicodeMatcher*.  Subclasses
+     * that mix in UnicodeMatcher as a base class must override this.
+     * This protocol is required because a pointer to a UnicodeFunctor
+     * cannot be cast to a pointer to a UnicodeMatcher, since
+     * UnicodeMatcher is a mixin that does not derive from
+     * UnicodeFunctor.
+     * @stable ICU 2.4
+     */
+    virtual UnicodeMatcher* toMatcher() const;
+
+    /**
+     * Cast 'this' to a UnicodeReplacer* pointer and return the
+     * pointer, or null if this is not a UnicodeReplacer*.  Subclasses
+     * that mix in UnicodeReplacer as a base class must override this.
+     * This protocol is required because a pointer to a UnicodeFunctor
+     * cannot be cast to a pointer to a UnicodeReplacer, since
+     * UnicodeReplacer is a mixin that does not derive from
+     * UnicodeFunctor.
+     * @stable ICU 2.4
+     */
+    virtual UnicodeReplacer* toReplacer() const;
+
+    /**
+     * Return the class ID for this class.  This is useful only for
+     * comparing to a return value from getDynamicClassID().
+     * @return          The class ID for all objects of this class.
+     * @stable ICU 2.0
+     */
+    static UClassID U_EXPORT2 getStaticClassID(void);
+
+    /**
+     * Returns a unique class ID <b>polymorphically</b>.  This method
+     * is to implement a simple version of RTTI, since not all C++
+     * compilers support genuine RTTI.  Polymorphic operator==() and
+     * clone() methods call this method.
+     *
+     * <p>Concrete subclasses of UnicodeFunctor should use the macro
+     *    UOBJECT_DEFINE_RTTI_IMPLEMENTATION from uobject.h to
+     *    provide definitios getStaticClassID and getDynamicClassID.
+     *
+     * @return The class ID for this object. All objects of a given
+     * class have the same class ID.  Objects of other classes have
+     * different class IDs.
+     * @stable ICU 2.4
+     */
+    virtual UClassID getDynamicClassID(void) const = 0;
+
+    /**
+     * Set the data object associated with this functor.  The data
+     * object provides context for functor-to-standin mapping.  This
+     * method is required when assigning a functor to a different data
+     * object.  This function MAY GO AWAY later if the architecture is
+     * changed to pass data object pointers through the API.
+     * @internal ICU 2.1
+     */
+    virtual void setData(const TransliterationRuleData*) = 0;
+
+protected:
+
+    /**
+     * Since this class has pure virtual functions,
+     * a constructor can't be used.
+     * @stable ICU 2.0
+     */
+    /*UnicodeFunctor();*/
+
+};
+
+/*inline UnicodeFunctor::UnicodeFunctor() {}*/
+
+U_NAMESPACE_END
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/unimatch.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/unimatch.h b/src/apps/couch_collate/platform/osx/icu/unicode/unimatch.h
new file mode 100644
index 0000000..0dbb14e
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/unimatch.h
@@ -0,0 +1,163 @@
+/*
+* Copyright (C) 2001-2005, International Business Machines Corporation and others. All Rights Reserved.
+**********************************************************************
+*   Date        Name        Description
+*   07/18/01    aliu        Creation.
+**********************************************************************
+*/
+#ifndef UNIMATCH_H
+#define UNIMATCH_H
+
+#include "unicode/utypes.h"
+
+/**
+ * \file 
+ * \brief C++ API: Unicode Matcher
+ */
+
+
+U_NAMESPACE_BEGIN
+
+class Replaceable;
+class UnicodeString;
+class UnicodeSet;
+
+/**
+ * Constants returned by <code>UnicodeMatcher::matches()</code>
+ * indicating the degree of match.
+ * @stable ICU 2.4
+ */
+enum UMatchDegree {
+    /**
+     * Constant returned by <code>matches()</code> indicating a
+     * mismatch between the text and this matcher.  The text contains
+     * a character which does not match, or the text does not contain
+     * all desired characters for a non-incremental match.
+     * @stable ICU 2.4
+     */
+    U_MISMATCH,
+    
+    /**
+     * Constant returned by <code>matches()</code> indicating a
+     * partial match between the text and this matcher.  This value is
+     * only returned for incremental match operations.  All characters
+     * of the text match, but more characters are required for a
+     * complete match.  Alternatively, for variable-length matchers,
+     * all characters of the text match, and if more characters were
+     * supplied at limit, they might also match.
+     * @stable ICU 2.4
+     */
+    U_PARTIAL_MATCH,
+    
+    /**
+     * Constant returned by <code>matches()</code> indicating a
+     * complete match between the text and this matcher.  For an
+     * incremental variable-length match, this value is returned if
+     * the given text matches, and it is known that additional
+     * characters would not alter the extent of the match.
+     * @stable ICU 2.4
+     */
+    U_MATCH
+};
+
+/**
+ * <code>UnicodeMatcher</code> defines a protocol for objects that can
+ * match a range of characters in a Replaceable string.
+ * @stable ICU 2.4
+ */
+class U_COMMON_API UnicodeMatcher /* not : public UObject because this is an interface/mixin class */ {
+
+public:
+    /**
+     * Destructor.
+     * @stable ICU 2.4
+     */
+    virtual ~UnicodeMatcher();
+
+    /**
+     * Return a UMatchDegree value indicating the degree of match for
+     * the given text at the given offset.  Zero, one, or more
+     * characters may be matched.
+     *
+     * Matching in the forward direction is indicated by limit >
+     * offset.  Characters from offset forwards to limit-1 will be
+     * considered for matching.
+     * 
+     * Matching in the reverse direction is indicated by limit <
+     * offset.  Characters from offset backwards to limit+1 will be
+     * considered for matching.
+     *
+     * If limit == offset then the only match possible is a zero
+     * character match (which subclasses may implement if desired).
+     *
+     * As a side effect, advance the offset parameter to the limit of
+     * the matched substring.  In the forward direction, this will be
+     * the index of the last matched character plus one.  In the
+     * reverse direction, this will be the index of the last matched
+     * character minus one.
+     *
+     * <p>Note:  This method is not const because some classes may
+     * modify their state as the result of a match.
+     *
+     * @param text the text to be matched
+     * @param offset on input, the index into text at which to begin
+     * matching.  On output, the limit of the matched text.  The
+     * number of matched characters is the output value of offset
+     * minus the input value.  Offset should always point to the
+     * HIGH SURROGATE (leading code unit) of a pair of surrogates,
+     * both on entry and upon return.
+     * @param limit the limit index of text to be matched.  Greater
+     * than offset for a forward direction match, less than offset for
+     * a backward direction match.  The last character to be
+     * considered for matching will be text.charAt(limit-1) in the
+     * forward direction or text.charAt(limit+1) in the backward
+     * direction.
+     * @param incremental if TRUE, then assume further characters may
+     * be inserted at limit and check for partial matching.  Otherwise
+     * assume the text as given is complete.
+     * @return a match degree value indicating a full match, a partial
+     * match, or a mismatch.  If incremental is FALSE then
+     * U_PARTIAL_MATCH should never be returned.
+     * @stable ICU 2.4
+     */
+    virtual UMatchDegree matches(const Replaceable& text,
+                                 int32_t& offset,
+                                 int32_t limit,
+                                 UBool incremental) = 0;
+
+    /**
+     * Returns a string representation of this matcher.  If the result of
+     * calling this function is passed to the appropriate parser, it
+     * will produce another matcher that is equal to this one.
+     * @param result the string to receive the pattern.  Previous
+     * contents will be deleted.
+     * @param escapeUnprintable if TRUE then convert unprintable
+     * character to their hex escape representations, \\uxxxx or
+     * \\Uxxxxxxxx.  Unprintable characters are those other than
+     * U+000A, U+0020..U+007E.
+     * @stable ICU 2.4
+     */
+    virtual UnicodeString& toPattern(UnicodeString& result,
+                                     UBool escapeUnprintable = FALSE) const = 0;
+
+    /**
+     * Returns TRUE if this matcher will match a character c, where c
+     * & 0xFF == v, at offset, in the forward direction (with limit >
+     * offset).  This is used by <tt>RuleBasedTransliterator</tt> for
+     * indexing.
+     * @stable ICU 2.4
+     */
+    virtual UBool matchesIndexValue(uint8_t v) const = 0;
+
+    /**
+     * Union the set of all characters that may be matched by this object
+     * into the given set.
+     * @param toUnionTo the set into which to union the source characters
+     * @stable ICU 2.4
+     */
+    virtual void addMatchSetTo(UnicodeSet& toUnionTo) const = 0;
+};
+
+U_NAMESPACE_END
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/unirepl.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/unirepl.h b/src/apps/couch_collate/platform/osx/icu/unicode/unirepl.h
new file mode 100644
index 0000000..6b7746b
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/unirepl.h
@@ -0,0 +1,97 @@
+/*
+**********************************************************************
+*   Copyright (c) 2002-2005, International Business Machines Corporation
+*   and others.  All Rights Reserved.
+**********************************************************************
+*   Date        Name        Description
+*   01/14/2002  aliu        Creation.
+**********************************************************************
+*/
+#ifndef UNIREPL_H
+#define UNIREPL_H
+
+#include "unicode/utypes.h"
+
+/**
+ * \file 
+ * \brief C++ API: UnicodeReplacer
+ */
+
+U_NAMESPACE_BEGIN
+
+class Replaceable;
+class UnicodeString;
+class UnicodeSet;
+
+/**
+ * <code>UnicodeReplacer</code> defines a protocol for objects that
+ * replace a range of characters in a Replaceable string with output
+ * text.  The replacement is done via the Replaceable API so as to
+ * preserve out-of-band data.
+ *
+ * <p>This is a mixin class.
+ * @author Alan Liu
+ * @stable ICU 2.4
+ */
+class U_I18N_API UnicodeReplacer /* not : public UObject because this is an interface/mixin class */ {
+
+ public:
+
+    /**
+     * Destructor.
+     * @stable ICU 2.4
+     */
+    virtual ~UnicodeReplacer();
+
+    /**
+     * Replace characters in 'text' from 'start' to 'limit' with the
+     * output text of this object.  Update the 'cursor' parameter to
+     * give the cursor position and return the length of the
+     * replacement text.
+     *
+     * @param text the text to be matched
+     * @param start inclusive start index of text to be replaced
+     * @param limit exclusive end index of text to be replaced;
+     * must be greater than or equal to start
+     * @param cursor output parameter for the cursor position.
+     * Not all replacer objects will update this, but in a complete
+     * tree of replacer objects, representing the entire output side
+     * of a transliteration rule, at least one must update it.
+     * @return the number of 16-bit code units in the text replacing
+     * the characters at offsets start..(limit-1) in text
+     * @stable ICU 2.4
+     */
+    virtual int32_t replace(Replaceable& text,
+                            int32_t start,
+                            int32_t limit,
+                            int32_t& cursor) = 0;
+
+    /**
+     * Returns a string representation of this replacer.  If the
+     * result of calling this function is passed to the appropriate
+     * parser, typically TransliteratorParser, it will produce another
+     * replacer that is equal to this one.
+     * @param result the string to receive the pattern.  Previous
+     * contents will be deleted.
+     * @param escapeUnprintable if TRUE then convert unprintable
+     * character to their hex escape representations, \\uxxxx or
+     * \\Uxxxxxxxx.  Unprintable characters are defined by
+     * Utility.isUnprintable().
+     * @return a reference to 'result'.
+     * @stable ICU 2.4
+     */
+    virtual UnicodeString& toReplacerPattern(UnicodeString& result,
+                                             UBool escapeUnprintable) const = 0;
+
+    /**
+     * Union the set of all characters that may output by this object
+     * into the given set.
+     * @param toUnionTo the set into which to union the output characters
+     * @stable ICU 2.4
+     */
+    virtual void addReplacementSetTo(UnicodeSet& toUnionTo) const = 0;
+};
+
+U_NAMESPACE_END
+
+#endif


[45/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_httpd_db.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_httpd_db.erl b/apps/couch/src/couch_httpd_db.erl
deleted file mode 100644
index 0a7c17c..0000000
--- a/apps/couch/src/couch_httpd_db.erl
+++ /dev/null
@@ -1,1226 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_httpd_db).
--include("couch_db.hrl").
-
--export([handle_request/1, handle_compact_req/2, handle_design_req/2,
-    db_req/2, couch_doc_open/4,handle_changes_req/2,
-    update_doc_result_to_json/1, update_doc_result_to_json/2,
-    handle_design_info_req/3]).
-
--import(couch_httpd,
-    [send_json/2,send_json/3,send_json/4,send_method_not_allowed/2,
-    start_json_response/2,send_chunk/2,last_chunk/1,end_json_response/1,
-    start_chunked_response/3, absolute_uri/2, send/2,
-    start_response_length/4, send_error/4]).
-
--record(doc_query_args, {
-    options = [],
-    rev = nil,
-    open_revs = [],
-    update_type = interactive_edit,
-    atts_since = nil
-}).
-
-% Database request handlers
-handle_request(#httpd{path_parts=[DbName|RestParts],method=Method,
-        db_url_handlers=DbUrlHandlers}=Req)->
-    case {Method, RestParts} of
-    {'PUT', []} ->
-        create_db_req(Req, DbName);
-    {'DELETE', []} ->
-        % if we get ?rev=... the user is using a faulty script where the
-        % document id is empty by accident. Let them recover safely.
-        case couch_httpd:qs_value(Req, "rev", false) of
-            false -> delete_db_req(Req, DbName);
-            _Rev -> throw({bad_request,
-                "You tried to DELETE a database with a ?=rev parameter. "
-                ++ "Did you mean to DELETE a document instead?"})
-        end;
-    {_, []} ->
-        do_db_req(Req, fun db_req/2);
-    {_, [SecondPart|_]} ->
-        Handler = couch_util:dict_find(SecondPart, DbUrlHandlers, fun db_req/2),
-        do_db_req(Req, Handler)
-    end.
-
-handle_changes_req(#httpd{method='POST'}=Req, Db) ->
-    couch_httpd:validate_ctype(Req, "application/json"),
-    handle_changes_req1(Req, Db);
-handle_changes_req(#httpd{method='GET'}=Req, Db) ->
-    handle_changes_req1(Req, Db);
-handle_changes_req(#httpd{path_parts=[_,<<"_changes">>]}=Req, _Db) ->
-    send_method_not_allowed(Req, "GET,HEAD,POST").
-
-handle_changes_req1(Req, #db{name=DbName}=Db) ->
-    AuthDbName = ?l2b(couch_config:get("couch_httpd_auth", "authentication_db")),
-    case AuthDbName of
-    DbName ->
-        % in the authentication database, _changes is admin-only.
-        ok = couch_db:check_is_admin(Db);
-    _Else ->
-        % on other databases, _changes is free for all.
-        ok
-    end,
-    handle_changes_req2(Req, Db).
-
-handle_changes_req2(Req, Db) ->
-    MakeCallback = fun(Resp) ->
-        fun({change, {ChangeProp}=Change, _}, "eventsource") ->
-            Seq = proplists:get_value(<<"seq">>, ChangeProp),
-            send_chunk(Resp, ["data: ", ?JSON_ENCODE(Change),
-                              "\n", "id: ", ?JSON_ENCODE(Seq),
-                              "\n\n"]);
-        ({change, Change, _}, "continuous") ->
-            send_chunk(Resp, [?JSON_ENCODE(Change) | "\n"]);
-        ({change, Change, Prepend}, _) ->
-            send_chunk(Resp, [Prepend, ?JSON_ENCODE(Change)]);
-        (start, "eventsource") ->
-            ok;
-        (start, "continuous") ->
-            ok;
-        (start, _) ->
-            send_chunk(Resp, "{\"results\":[\n");
-        ({stop, _EndSeq}, "eventsource") ->
-            end_json_response(Resp);
-        ({stop, EndSeq}, "continuous") ->
-            send_chunk(
-                Resp,
-                [?JSON_ENCODE({[{<<"last_seq">>, EndSeq}]}) | "\n"]
-            ),
-            end_json_response(Resp);
-        ({stop, EndSeq}, _) ->
-            send_chunk(
-                Resp,
-                io_lib:format("\n],\n\"last_seq\":~w}\n", [EndSeq])
-            ),
-            end_json_response(Resp);
-        (timeout, _) ->
-            send_chunk(Resp, "\n")
-        end
-    end,
-    ChangesArgs = parse_changes_query(Req, Db),
-    ChangesFun = couch_changes:handle_changes(ChangesArgs, Req, Db),
-    WrapperFun = case ChangesArgs#changes_args.feed of
-    "normal" ->
-        {ok, Info} = couch_db:get_db_info(Db),
-        CurrentEtag = couch_httpd:make_etag(Info),
-        fun(FeedChangesFun) ->
-            couch_httpd:etag_respond(
-                Req,
-                CurrentEtag,
-                fun() ->
-                    {ok, Resp} = couch_httpd:start_json_response(
-                         Req, 200, [{"ETag", CurrentEtag}]
-                    ),
-                    FeedChangesFun(MakeCallback(Resp))
-                end
-            )
-        end;
-    "eventsource" ->
-        Headers = [
-            {"Content-Type", "text/event-stream"},
-            {"Cache-Control", "no-cache"}
-        ],
-        {ok, Resp} = couch_httpd:start_chunked_response(Req, 200, Headers),
-        fun(FeedChangesFun) ->
-            FeedChangesFun(MakeCallback(Resp))
-        end;
-    _ ->
-        % "longpoll" or "continuous"
-        {ok, Resp} = couch_httpd:start_json_response(Req, 200),
-        fun(FeedChangesFun) ->
-            FeedChangesFun(MakeCallback(Resp))
-        end
-    end,
-    couch_stats_collector:increment(
-        {httpd, clients_requesting_changes}
-    ),
-    try
-        WrapperFun(ChangesFun)
-    after
-    couch_stats_collector:decrement(
-        {httpd, clients_requesting_changes}
-    )
-    end.
-
-handle_compact_req(#httpd{method='POST'}=Req, Db) ->
-    case Req#httpd.path_parts of
-        [_DbName, <<"_compact">>] ->
-            ok = couch_db:check_is_admin(Db),
-            couch_httpd:validate_ctype(Req, "application/json"),
-            {ok, _} = couch_db:start_compact(Db),
-            send_json(Req, 202, {[{ok, true}]});
-        [_DbName, <<"_compact">>, DesignName | _] ->
-            DesignId = <<"_design/", DesignName/binary>>,
-            DDoc = couch_httpd_db:couch_doc_open(
-                Db, DesignId, nil, [ejson_body]
-            ),
-            couch_mrview_http:handle_compact_req(Req, Db, DDoc)
-    end;
-
-handle_compact_req(Req, _Db) ->
-    send_method_not_allowed(Req, "POST").
-
-
-handle_design_req(#httpd{
-        path_parts=[_DbName, _Design, DesignName, <<"_",_/binary>> = Action | _Rest],
-        design_url_handlers = DesignUrlHandlers
-    }=Req, Db) ->
-    case couch_db:is_system_db(Db) of
-    true ->
-        case (catch couch_db:check_is_admin(Db)) of
-        ok -> ok;
-        _ ->
-            throw({forbidden, <<"Only admins can access design document",
-                " actions for system databases.">>})
-        end;
-    false -> ok
-    end,
-
-    % load ddoc
-    DesignId = <<"_design/", DesignName/binary>>,
-    DDoc = couch_httpd_db:couch_doc_open(Db, DesignId, nil, [ejson_body]),
-    Handler = couch_util:dict_find(Action, DesignUrlHandlers, fun(_, _, _) ->
-        throw({not_found, <<"missing handler: ", Action/binary>>})
-    end),
-    Handler(Req, Db, DDoc);
-
-handle_design_req(Req, Db) ->
-    db_req(Req, Db).
-
-handle_design_info_req(#httpd{
-            method='GET',
-            path_parts=[_DbName, _Design, DesignName, _]
-        }=Req, Db, _DDoc) ->
-    DesignId = <<"_design/", DesignName/binary>>,
-    DDoc = couch_httpd_db:couch_doc_open(Db, DesignId, nil, [ejson_body]),
-    couch_mrview_http:handle_info_req(Req, Db, DDoc).
-
-create_db_req(#httpd{user_ctx=UserCtx}=Req, DbName) ->
-    ok = couch_httpd:verify_is_server_admin(Req),
-    case couch_server:create(DbName, [{user_ctx, UserCtx}]) of
-    {ok, Db} ->
-        couch_db:close(Db),
-        DbUrl = absolute_uri(Req, "/" ++ couch_util:url_encode(DbName)),
-        send_json(Req, 201, [{"Location", DbUrl}], {[{ok, true}]});
-    Error ->
-        throw(Error)
-    end.
-
-delete_db_req(#httpd{user_ctx=UserCtx}=Req, DbName) ->
-    ok = couch_httpd:verify_is_server_admin(Req),
-    case couch_server:delete(DbName, [{user_ctx, UserCtx}]) of
-    ok ->
-        send_json(Req, 200, {[{ok, true}]});
-    Error ->
-        throw(Error)
-    end.
-
-do_db_req(#httpd{user_ctx=UserCtx,path_parts=[DbName|_]}=Req, Fun) ->
-    case couch_db:open(DbName, [{user_ctx, UserCtx}]) of
-    {ok, Db} ->
-        try
-            Fun(Req, Db)
-        after
-            catch couch_db:close(Db)
-        end;
-    Error ->
-        throw(Error)
-    end.
-
-db_req(#httpd{method='GET',path_parts=[_DbName]}=Req, Db) ->
-    {ok, DbInfo} = couch_db:get_db_info(Db),
-    send_json(Req, {DbInfo});
-
-db_req(#httpd{method='POST',path_parts=[_DbName]}=Req, Db) ->
-    couch_httpd:validate_ctype(Req, "application/json"),
-    Doc = couch_doc:from_json_obj(couch_httpd:json_body(Req)),
-    validate_attachment_names(Doc),
-    Doc2 = case Doc#doc.id of
-        <<"">> ->
-            Doc#doc{id=couch_uuids:new(), revs={0, []}};
-        _ ->
-            Doc
-    end,
-    DocId = Doc2#doc.id,
-    update_doc(Req, Db, DocId, Doc2);
-
-db_req(#httpd{path_parts=[_DbName]}=Req, _Db) ->
-    send_method_not_allowed(Req, "DELETE,GET,HEAD,POST");
-
-db_req(#httpd{method='POST',path_parts=[_,<<"_ensure_full_commit">>]}=Req, Db) ->
-    couch_httpd:validate_ctype(Req, "application/json"),
-    UpdateSeq = couch_db:get_update_seq(Db),
-    CommittedSeq = couch_db:get_committed_update_seq(Db),
-    {ok, StartTime} =
-    case couch_httpd:qs_value(Req, "seq") of
-    undefined ->
-        couch_db:ensure_full_commit(Db);
-    RequiredStr ->
-        RequiredSeq = list_to_integer(RequiredStr),
-        if RequiredSeq > UpdateSeq ->
-            throw({bad_request,
-                "can't do a full commit ahead of current update_seq"});
-        RequiredSeq > CommittedSeq ->
-            couch_db:ensure_full_commit(Db);
-        true ->
-            {ok, Db#db.instance_start_time}
-        end
-    end,
-    send_json(Req, 201, {[
-        {ok, true},
-        {instance_start_time, StartTime}
-    ]});
-
-db_req(#httpd{path_parts=[_,<<"_ensure_full_commit">>]}=Req, _Db) ->
-    send_method_not_allowed(Req, "POST");
-
-db_req(#httpd{method='POST',path_parts=[_,<<"_bulk_docs">>]}=Req, Db) ->
-    couch_stats_collector:increment({httpd, bulk_requests}),
-    couch_httpd:validate_ctype(Req, "application/json"),
-    {JsonProps} = couch_httpd:json_body_obj(Req),
-    case couch_util:get_value(<<"docs">>, JsonProps) of
-    undefined ->
-        send_error(Req, 400, <<"bad_request">>, <<"Missing JSON list of 'docs'">>);
-    DocsArray ->
-        case couch_httpd:header_value(Req, "X-Couch-Full-Commit") of
-        "true" ->
-            Options = [full_commit];
-        "false" ->
-            Options = [delay_commit];
-        _ ->
-            Options = []
-        end,
-        case couch_util:get_value(<<"new_edits">>, JsonProps, true) of
-        true ->
-            Docs = lists:map(
-                fun({ObjProps} = JsonObj) ->
-                    Doc = couch_doc:from_json_obj(JsonObj),
-                    validate_attachment_names(Doc),
-                    Id = case Doc#doc.id of
-                        <<>> -> couch_uuids:new();
-                        Id0 -> Id0
-                    end,
-                    case couch_util:get_value(<<"_rev">>, ObjProps) of
-                    undefined ->
-                       Revs = {0, []};
-                    Rev  ->
-                        {Pos, RevId} = couch_doc:parse_rev(Rev),
-                        Revs = {Pos, [RevId]}
-                    end,
-                    Doc#doc{id=Id,revs=Revs}
-                end,
-                DocsArray),
-            Options2 =
-            case couch_util:get_value(<<"all_or_nothing">>, JsonProps) of
-            true  -> [all_or_nothing|Options];
-            _ -> Options
-            end,
-            case couch_db:update_docs(Db, Docs, Options2) of
-            {ok, Results} ->
-                % output the results
-                DocResults = lists:zipwith(fun update_doc_result_to_json/2,
-                    Docs, Results),
-                send_json(Req, 201, DocResults);
-            {aborted, Errors} ->
-                ErrorsJson =
-                    lists:map(fun update_doc_result_to_json/1, Errors),
-                send_json(Req, 417, ErrorsJson)
-            end;
-        false ->
-            Docs = lists:map(fun(JsonObj) ->
-                    Doc = couch_doc:from_json_obj(JsonObj),
-                    validate_attachment_names(Doc),
-                    Doc
-                end, DocsArray),
-            {ok, Errors} = couch_db:update_docs(Db, Docs, Options, replicated_changes),
-            ErrorsJson =
-                lists:map(fun update_doc_result_to_json/1, Errors),
-            send_json(Req, 201, ErrorsJson)
-        end
-    end;
-db_req(#httpd{path_parts=[_,<<"_bulk_docs">>]}=Req, _Db) ->
-    send_method_not_allowed(Req, "POST");
-
-db_req(#httpd{method='POST',path_parts=[_,<<"_purge">>]}=Req, Db) ->
-    couch_httpd:validate_ctype(Req, "application/json"),
-    {IdsRevs} = couch_httpd:json_body_obj(Req),
-    IdsRevs2 = [{Id, couch_doc:parse_revs(Revs)} || {Id, Revs} <- IdsRevs],
-
-    case couch_db:purge_docs(Db, IdsRevs2) of
-    {ok, PurgeSeq, PurgedIdsRevs} ->
-        PurgedIdsRevs2 = [{Id, couch_doc:revs_to_strs(Revs)} || {Id, Revs} <- PurgedIdsRevs],
-        send_json(Req, 200, {[{<<"purge_seq">>, PurgeSeq}, {<<"purged">>, {PurgedIdsRevs2}}]});
-    Error ->
-        throw(Error)
-    end;
-
-db_req(#httpd{path_parts=[_,<<"_purge">>]}=Req, _Db) ->
-    send_method_not_allowed(Req, "POST");
-
-db_req(#httpd{method='POST',path_parts=[_,<<"_missing_revs">>]}=Req, Db) ->
-    {JsonDocIdRevs} = couch_httpd:json_body_obj(Req),
-    JsonDocIdRevs2 = [{Id, [couch_doc:parse_rev(RevStr) || RevStr <- RevStrs]} || {Id, RevStrs} <- JsonDocIdRevs],
-    {ok, Results} = couch_db:get_missing_revs(Db, JsonDocIdRevs2),
-    Results2 = [{Id, couch_doc:revs_to_strs(Revs)} || {Id, Revs, _} <- Results],
-    send_json(Req, {[
-        {missing_revs, {Results2}}
-    ]});
-
-db_req(#httpd{path_parts=[_,<<"_missing_revs">>]}=Req, _Db) ->
-    send_method_not_allowed(Req, "POST");
-
-db_req(#httpd{method='POST',path_parts=[_,<<"_revs_diff">>]}=Req, Db) ->
-    {JsonDocIdRevs} = couch_httpd:json_body_obj(Req),
-    JsonDocIdRevs2 =
-        [{Id, couch_doc:parse_revs(RevStrs)} || {Id, RevStrs} <- JsonDocIdRevs],
-    {ok, Results} = couch_db:get_missing_revs(Db, JsonDocIdRevs2),
-    Results2 =
-    lists:map(fun({Id, MissingRevs, PossibleAncestors}) ->
-        {Id,
-            {[{missing, couch_doc:revs_to_strs(MissingRevs)}] ++
-                if PossibleAncestors == [] ->
-                    [];
-                true ->
-                    [{possible_ancestors,
-                        couch_doc:revs_to_strs(PossibleAncestors)}]
-                end}}
-    end, Results),
-    send_json(Req, {Results2});
-
-db_req(#httpd{path_parts=[_,<<"_revs_diff">>]}=Req, _Db) ->
-    send_method_not_allowed(Req, "POST");
-
-db_req(#httpd{method='PUT',path_parts=[_,<<"_security">>]}=Req, Db) ->
-    SecObj = couch_httpd:json_body(Req),
-    ok = couch_db:set_security(Db, SecObj),
-    send_json(Req, {[{<<"ok">>, true}]});
-
-db_req(#httpd{method='GET',path_parts=[_,<<"_security">>]}=Req, Db) ->
-    send_json(Req, couch_db:get_security(Db));
-
-db_req(#httpd{path_parts=[_,<<"_security">>]}=Req, _Db) ->
-    send_method_not_allowed(Req, "PUT,GET");
-
-db_req(#httpd{method='PUT',path_parts=[_,<<"_revs_limit">>]}=Req,
-        Db) ->
-    Limit = couch_httpd:json_body(Req),
-   case is_integer(Limit) of
-   true ->
-       ok = couch_db:set_revs_limit(Db, Limit),
-       send_json(Req, {[{<<"ok">>, true}]});
-   false ->
-       throw({bad_request, <<"Rev limit has to be an integer">>})
-   end;
-
-db_req(#httpd{method='GET',path_parts=[_,<<"_revs_limit">>]}=Req, Db) ->
-    send_json(Req, couch_db:get_revs_limit(Db));
-
-db_req(#httpd{path_parts=[_,<<"_revs_limit">>]}=Req, _Db) ->
-    send_method_not_allowed(Req, "PUT,GET");
-
-% Special case to enable using an unencoded slash in the URL of design docs,
-% as slashes in document IDs must otherwise be URL encoded.
-db_req(#httpd{method='GET',mochi_req=MochiReq, path_parts=[DbName,<<"_design/",_/binary>>|_]}=Req, _Db) ->
-    PathFront = "/" ++ couch_httpd:quote(binary_to_list(DbName)) ++ "/",
-    [_|PathTail] = re:split(MochiReq:get(raw_path), "_design%2F",
-        [{return, list}]),
-    couch_httpd:send_redirect(Req, PathFront ++ "_design/" ++
-        mochiweb_util:join(PathTail, "_design%2F"));
-
-db_req(#httpd{path_parts=[_DbName,<<"_design">>,Name]}=Req, Db) ->
-    db_doc_req(Req, Db, <<"_design/",Name/binary>>);
-
-db_req(#httpd{path_parts=[_DbName,<<"_design">>,Name|FileNameParts]}=Req, Db) ->
-    db_attachment_req(Req, Db, <<"_design/",Name/binary>>, FileNameParts);
-
-
-% Special case to allow for accessing local documents without %2F
-% encoding the docid. Throws out requests that don't have the second
-% path part or that specify an attachment name.
-db_req(#httpd{path_parts=[_DbName, <<"_local">>]}, _Db) ->
-    throw({bad_request, <<"Invalid _local document id.">>});
-
-db_req(#httpd{path_parts=[_DbName, <<"_local/">>]}, _Db) ->
-    throw({bad_request, <<"Invalid _local document id.">>});
-
-db_req(#httpd{path_parts=[_DbName, <<"_local">>, Name]}=Req, Db) ->
-    db_doc_req(Req, Db, <<"_local/", Name/binary>>);
-
-db_req(#httpd{path_parts=[_DbName, <<"_local">> | _Rest]}, _Db) ->
-    throw({bad_request, <<"_local documents do not accept attachments.">>});
-
-db_req(#httpd{path_parts=[_, DocId]}=Req, Db) ->
-    db_doc_req(Req, Db, DocId);
-
-db_req(#httpd{path_parts=[_, DocId | FileNameParts]}=Req, Db) ->
-    db_attachment_req(Req, Db, DocId, FileNameParts).
-
-db_doc_req(#httpd{method='DELETE'}=Req, Db, DocId) ->
-    % check for the existence of the doc to handle the 404 case.
-    couch_doc_open(Db, DocId, nil, []),
-    case couch_httpd:qs_value(Req, "rev") of
-    undefined ->
-        update_doc(Req, Db, DocId,
-                couch_doc_from_req(Req, DocId, {[{<<"_deleted">>,true}]}));
-    Rev ->
-        update_doc(Req, Db, DocId,
-                couch_doc_from_req(Req, DocId,
-                    {[{<<"_rev">>, ?l2b(Rev)},{<<"_deleted">>,true}]}))
-    end;
-
-db_doc_req(#httpd{method = 'GET', mochi_req = MochiReq} = Req, Db, DocId) ->
-    #doc_query_args{
-        rev = Rev,
-        open_revs = Revs,
-        options = Options1,
-        atts_since = AttsSince
-    } = parse_doc_query(Req),
-    Options = case AttsSince of
-    nil ->
-        Options1;
-    RevList when is_list(RevList) ->
-        [{atts_since, RevList}, attachments | Options1]
-    end,
-    case Revs of
-    [] ->
-        Doc = couch_doc_open(Db, DocId, Rev, Options),
-        send_doc(Req, Doc, Options);
-    _ ->
-        {ok, Results} = couch_db:open_doc_revs(Db, DocId, Revs, Options),
-        case MochiReq:accepts_content_type("multipart/mixed") of
-        false ->
-            {ok, Resp} = start_json_response(Req, 200),
-            send_chunk(Resp, "["),
-            % We loop through the docs. The first time through the separator
-            % is whitespace, then a comma on subsequent iterations.
-            lists:foldl(
-                fun(Result, AccSeparator) ->
-                    case Result of
-                    {ok, Doc} ->
-                        JsonDoc = couch_doc:to_json_obj(Doc, Options),
-                        Json = ?JSON_ENCODE({[{ok, JsonDoc}]}),
-                        send_chunk(Resp, AccSeparator ++ Json);
-                    {{not_found, missing}, RevId} ->
-                        RevStr = couch_doc:rev_to_str(RevId),
-                        Json = ?JSON_ENCODE({[{"missing", RevStr}]}),
-                        send_chunk(Resp, AccSeparator ++ Json)
-                    end,
-                    "," % AccSeparator now has a comma
-                end,
-                "", Results),
-            send_chunk(Resp, "]"),
-            end_json_response(Resp);
-        true ->
-            send_docs_multipart(Req, Results, Options)
-        end
-    end;
-
-
-db_doc_req(#httpd{method='POST'}=Req, Db, DocId) ->
-    couch_httpd:validate_referer(Req),
-    couch_doc:validate_docid(DocId),
-    couch_httpd:validate_ctype(Req, "multipart/form-data"),
-    Form = couch_httpd:parse_form(Req),
-    case couch_util:get_value("_doc", Form) of
-    undefined ->
-        Rev = couch_doc:parse_rev(couch_util:get_value("_rev", Form)),
-        {ok, [{ok, Doc}]} = couch_db:open_doc_revs(Db, DocId, [Rev], []);
-    Json ->
-        Doc = couch_doc_from_req(Req, DocId, ?JSON_DECODE(Json))
-    end,
-    UpdatedAtts = [
-        #att{name=validate_attachment_name(Name),
-            type=list_to_binary(ContentType),
-            data=Content} ||
-        {Name, {ContentType, _}, Content} <-
-        proplists:get_all_values("_attachments", Form)
-    ],
-    #doc{atts=OldAtts} = Doc,
-    OldAtts2 = lists:flatmap(
-        fun(#att{name=OldName}=Att) ->
-            case [1 || A <- UpdatedAtts, A#att.name == OldName] of
-            [] -> [Att]; % the attachment wasn't in the UpdatedAtts, return it
-            _ -> [] % the attachment was in the UpdatedAtts, drop it
-            end
-        end, OldAtts),
-    NewDoc = Doc#doc{
-        atts = UpdatedAtts ++ OldAtts2
-    },
-    update_doc(Req, Db, DocId, NewDoc);
-
-db_doc_req(#httpd{method='PUT'}=Req, Db, DocId) ->
-    couch_doc:validate_docid(DocId),
-
-    case couch_util:to_list(couch_httpd:header_value(Req, "Content-Type")) of
-    ("multipart/related;" ++ _) = ContentType ->
-        {ok, Doc0, WaitFun, Parser} = couch_doc:doc_from_multi_part_stream(
-            ContentType, fun() -> receive_request_data(Req) end),
-        Doc = couch_doc_from_req(Req, DocId, Doc0),
-        try
-            Result = update_doc(Req, Db, DocId, Doc),
-            WaitFun(),
-            Result
-        catch throw:Err ->
-            % Document rejected by a validate_doc_update function.
-            couch_doc:abort_multi_part_stream(Parser),
-            throw(Err)
-        end;
-    _Else ->
-        Body = couch_httpd:json_body(Req),
-        Doc = couch_doc_from_req(Req, DocId, Body),
-        update_doc(Req, Db, DocId, Doc)
-    end;
-
-db_doc_req(#httpd{method='COPY'}=Req, Db, SourceDocId) ->
-    SourceRev =
-    case extract_header_rev(Req, couch_httpd:qs_value(Req, "rev")) of
-        missing_rev -> nil;
-        Rev -> Rev
-    end,
-    {TargetDocId, TargetRevs} = parse_copy_destination_header(Req),
-    % open old doc
-    Doc = couch_doc_open(Db, SourceDocId, SourceRev, []),
-    % save new doc
-    update_doc(Req, Db, TargetDocId, Doc#doc{id=TargetDocId, revs=TargetRevs});
-
-db_doc_req(Req, _Db, _DocId) ->
-    send_method_not_allowed(Req, "DELETE,GET,HEAD,POST,PUT,COPY").
-
-
-send_doc(Req, Doc, Options) ->
-    case Doc#doc.meta of
-    [] ->
-        DiskEtag = couch_httpd:doc_etag(Doc),
-        % output etag only when we have no meta
-        couch_httpd:etag_respond(Req, DiskEtag, fun() ->
-            send_doc_efficiently(Req, Doc, [{"ETag", DiskEtag}], Options)
-        end);
-    _ ->
-        send_doc_efficiently(Req, Doc, [], Options)
-    end.
-
-
-send_doc_efficiently(Req, #doc{atts=[]}=Doc, Headers, Options) ->
-        send_json(Req, 200, Headers, couch_doc:to_json_obj(Doc, Options));
-send_doc_efficiently(#httpd{mochi_req = MochiReq} = Req,
-    #doc{atts = Atts} = Doc, Headers, Options) ->
-    case lists:member(attachments, Options) of
-    true ->
-        case MochiReq:accepts_content_type("multipart/related") of
-        false ->
-            send_json(Req, 200, Headers, couch_doc:to_json_obj(Doc, Options));
-        true ->
-            Boundary = couch_uuids:random(),
-            JsonBytes = ?JSON_ENCODE(couch_doc:to_json_obj(Doc,
-                    [attachments, follows, att_encoding_info | Options])),
-            {ContentType, Len} = couch_doc:len_doc_to_multi_part_stream(
-                    Boundary,JsonBytes, Atts, true),
-            CType = {"Content-Type", ?b2l(ContentType)},
-            {ok, Resp} = start_response_length(Req, 200, [CType|Headers], Len),
-            couch_doc:doc_to_multi_part_stream(Boundary,JsonBytes,Atts,
-                    fun(Data) -> couch_httpd:send(Resp, Data) end, true)
-        end;
-    false ->
-        send_json(Req, 200, Headers, couch_doc:to_json_obj(Doc, Options))
-    end.
-
-send_docs_multipart(Req, Results, Options1) ->
-    OuterBoundary = couch_uuids:random(),
-    InnerBoundary = couch_uuids:random(),
-    Options = [attachments, follows, att_encoding_info | Options1],
-    CType = {"Content-Type",
-        "multipart/mixed; boundary=\"" ++ ?b2l(OuterBoundary) ++ "\""},
-    {ok, Resp} = start_chunked_response(Req, 200, [CType]),
-    couch_httpd:send_chunk(Resp, <<"--", OuterBoundary/binary>>),
-    lists:foreach(
-        fun({ok, #doc{atts=Atts}=Doc}) ->
-            JsonBytes = ?JSON_ENCODE(couch_doc:to_json_obj(Doc, Options)),
-            {ContentType, _Len} = couch_doc:len_doc_to_multi_part_stream(
-                    InnerBoundary, JsonBytes, Atts, true),
-            couch_httpd:send_chunk(Resp, <<"\r\nContent-Type: ",
-                    ContentType/binary, "\r\n\r\n">>),
-            couch_doc:doc_to_multi_part_stream(InnerBoundary, JsonBytes, Atts,
-                    fun(Data) -> couch_httpd:send_chunk(Resp, Data)
-                    end, true),
-             couch_httpd:send_chunk(Resp, <<"\r\n--", OuterBoundary/binary>>);
-        ({{not_found, missing}, RevId}) ->
-             RevStr = couch_doc:rev_to_str(RevId),
-             Json = ?JSON_ENCODE({[{"missing", RevStr}]}),
-             couch_httpd:send_chunk(Resp,
-                [<<"\r\nContent-Type: application/json; error=\"true\"\r\n\r\n">>,
-                Json,
-                <<"\r\n--", OuterBoundary/binary>>])
-         end, Results),
-    couch_httpd:send_chunk(Resp, <<"--">>),
-    couch_httpd:last_chunk(Resp).
-
-send_ranges_multipart(Req, ContentType, Len, Att, Ranges) ->
-    Boundary = couch_uuids:random(),
-    CType = {"Content-Type",
-        "multipart/byteranges; boundary=\"" ++ ?b2l(Boundary) ++ "\""},
-    {ok, Resp} = start_chunked_response(Req, 206, [CType]),
-    couch_httpd:send_chunk(Resp, <<"--", Boundary/binary>>),
-    lists:foreach(fun({From, To}) ->
-        ContentRange = ?l2b(make_content_range(From, To, Len)),
-        couch_httpd:send_chunk(Resp,
-            <<"\r\nContent-Type: ", ContentType/binary, "\r\n",
-            "Content-Range: ", ContentRange/binary, "\r\n",
-           "\r\n">>),
-        couch_doc:range_att_foldl(Att, From, To + 1,
-            fun(Seg, _) -> send_chunk(Resp, Seg) end, {ok, Resp}),
-        couch_httpd:send_chunk(Resp, <<"\r\n--", Boundary/binary>>)
-    end, Ranges),
-    couch_httpd:send_chunk(Resp, <<"--">>),
-    couch_httpd:last_chunk(Resp),
-    {ok, Resp}.
-
-receive_request_data(Req) ->
-    receive_request_data(Req, couch_httpd:body_length(Req)).
-
-receive_request_data(Req, LenLeft) when LenLeft > 0 ->
-    Len = erlang:min(4096, LenLeft),
-    Data = couch_httpd:recv(Req, Len),
-    {Data, fun() -> receive_request_data(Req, LenLeft - iolist_size(Data)) end};
-receive_request_data(_Req, _) ->
-    throw(<<"expected more data">>).
-
-make_content_range(From, To, Len) ->
-    io_lib:format("bytes ~B-~B/~B", [From, To, Len]).
-
-update_doc_result_to_json({{Id, Rev}, Error}) ->
-        {_Code, Err, Msg} = couch_httpd:error_info(Error),
-        {[{id, Id}, {rev, couch_doc:rev_to_str(Rev)},
-            {error, Err}, {reason, Msg}]}.
-
-update_doc_result_to_json(#doc{id=DocId}, Result) ->
-    update_doc_result_to_json(DocId, Result);
-update_doc_result_to_json(DocId, {ok, NewRev}) ->
-    {[{ok, true}, {id, DocId}, {rev, couch_doc:rev_to_str(NewRev)}]};
-update_doc_result_to_json(DocId, Error) ->
-    {_Code, ErrorStr, Reason} = couch_httpd:error_info(Error),
-    {[{id, DocId}, {error, ErrorStr}, {reason, Reason}]}.
-
-
-update_doc(Req, Db, DocId, #doc{deleted=false}=Doc) ->
-    Loc = absolute_uri(Req, "/" ++ ?b2l(Db#db.name) ++ "/" ++ ?b2l(DocId)),
-    update_doc(Req, Db, DocId, Doc, [{"Location", Loc}]);
-update_doc(Req, Db, DocId, Doc) ->
-    update_doc(Req, Db, DocId, Doc, []).
-
-update_doc(Req, Db, DocId, Doc, Headers) ->
-    #doc_query_args{
-        update_type = UpdateType
-    } = parse_doc_query(Req),
-    update_doc(Req, Db, DocId, Doc, Headers, UpdateType).
-
-update_doc(Req, Db, DocId, #doc{deleted=Deleted}=Doc, Headers, UpdateType) ->
-    case couch_httpd:header_value(Req, "X-Couch-Full-Commit") of
-    "true" ->
-        Options = [full_commit];
-    "false" ->
-        Options = [delay_commit];
-    _ ->
-        Options = []
-    end,
-    case couch_httpd:qs_value(Req, "batch") of
-    "ok" ->
-        % async batching
-        spawn(fun() ->
-                case catch(couch_db:update_doc(Db, Doc, Options, UpdateType)) of
-                {ok, _} -> ok;
-                Error ->
-                    ?LOG_INFO("Batch doc error (~s): ~p",[DocId, Error])
-                end
-            end),
-        send_json(Req, 202, Headers, {[
-            {ok, true},
-            {id, DocId}
-        ]});
-    _Normal ->
-        % normal
-        {ok, NewRev} = couch_db:update_doc(Db, Doc, Options, UpdateType),
-        NewRevStr = couch_doc:rev_to_str(NewRev),
-        ResponseHeaders = [{"ETag", <<"\"", NewRevStr/binary, "\"">>}] ++ Headers,
-        send_json(Req,
-            if Deleted orelse Req#httpd.method == 'DELETE' -> 200;
-            true -> 201 end,
-            ResponseHeaders, {[
-                {ok, true},
-                {id, DocId},
-                {rev, NewRevStr}]})
-    end.
-
-couch_doc_from_req(Req, DocId, #doc{revs=Revs}=Doc) ->
-    validate_attachment_names(Doc),
-    Rev = case couch_httpd:qs_value(Req, "rev") of
-    undefined ->
-        undefined;
-    QSRev ->
-        couch_doc:parse_rev(QSRev)
-    end,
-    Revs2 =
-    case Revs of
-    {Start, [RevId|_]} ->
-        if Rev /= undefined andalso Rev /= {Start, RevId} ->
-            throw({bad_request, "Document rev from request body and query "
-                   "string have different values"});
-        true ->
-            case extract_header_rev(Req, {Start, RevId}) of
-            missing_rev -> {0, []};
-            _ -> Revs
-            end
-        end;
-    _ ->
-        case extract_header_rev(Req, Rev) of
-        missing_rev -> {0, []};
-        {Pos, RevId2} -> {Pos, [RevId2]}
-        end
-    end,
-    Doc#doc{id=DocId, revs=Revs2};
-couch_doc_from_req(Req, DocId, Json) ->
-    couch_doc_from_req(Req, DocId, couch_doc:from_json_obj(Json)).
-
-% Useful for debugging
-% couch_doc_open(Db, DocId) ->
-%   couch_doc_open(Db, DocId, nil, []).
-
-couch_doc_open(Db, DocId, Rev, Options) ->
-    case Rev of
-    nil -> % open most recent rev
-        case couch_db:open_doc(Db, DocId, Options) of
-        {ok, Doc} ->
-            Doc;
-         Error ->
-             throw(Error)
-         end;
-  _ -> % open a specific rev (deletions come back as stubs)
-      case couch_db:open_doc_revs(Db, DocId, [Rev], Options) of
-          {ok, [{ok, Doc}]} ->
-              Doc;
-          {ok, [{{not_found, missing}, Rev}]} ->
-              throw(not_found);
-          {ok, [Else]} ->
-              throw(Else)
-      end
-  end.
-
-% Attachment request handlers
-
-db_attachment_req(#httpd{method='GET',mochi_req=MochiReq}=Req, Db, DocId, FileNameParts) ->
-    FileName = list_to_binary(mochiweb_util:join(lists:map(fun binary_to_list/1, FileNameParts),"/")),
-    #doc_query_args{
-        rev=Rev,
-        options=Options
-    } = parse_doc_query(Req),
-    #doc{
-        atts=Atts
-    } = Doc = couch_doc_open(Db, DocId, Rev, Options),
-    case [A || A <- Atts, A#att.name == FileName] of
-    [] ->
-        throw({not_found, "Document is missing attachment"});
-    [#att{type=Type, encoding=Enc, disk_len=DiskLen, att_len=AttLen}=Att] ->
-        Etag = case Att#att.md5 of
-            <<>> -> couch_httpd:doc_etag(Doc);
-            Md5 -> "\"" ++ ?b2l(base64:encode(Md5)) ++ "\""
-        end,
-        ReqAcceptsAttEnc = lists:member(
-           atom_to_list(Enc),
-           couch_httpd:accepted_encodings(Req)
-        ),
-        Len = case {Enc, ReqAcceptsAttEnc} of
-        {identity, _} ->
-            % stored and served in identity form
-            DiskLen;
-        {_, false} when DiskLen =/= AttLen ->
-            % Stored encoded, but client doesn't accept the encoding we used,
-            % so we need to decode on the fly.  DiskLen is the identity length
-            % of the attachment.
-            DiskLen;
-        {_, true} ->
-            % Stored and served encoded.  AttLen is the encoded length.
-            AttLen;
-        _ ->
-            % We received an encoded attachment and stored it as such, so we
-            % don't know the identity length.  The client doesn't accept the
-            % encoding, and since we cannot serve a correct Content-Length
-            % header we'll fall back to a chunked response.
-            undefined
-        end,
-        Headers = [
-            {"ETag", Etag},
-            {"Cache-Control", "must-revalidate"},
-            {"Content-Type", binary_to_list(Type)}
-        ] ++ case ReqAcceptsAttEnc of
-        true when Enc =/= identity ->
-            % RFC 2616 says that the 'identify' encoding should not be used in
-            % the Content-Encoding header
-            [{"Content-Encoding", atom_to_list(Enc)}];
-        _ ->
-            []
-        end ++ case Enc of
-            identity ->
-                [{"Accept-Ranges", "bytes"}];
-            _ ->
-                [{"Accept-Ranges", "none"}]
-        end,
-        AttFun = case ReqAcceptsAttEnc of
-        false ->
-            fun couch_doc:att_foldl_decode/3;
-        true ->
-            fun couch_doc:att_foldl/3
-        end,
-        couch_httpd:etag_respond(
-            Req,
-            Etag,
-            fun() ->
-                case Len of
-                undefined ->
-                    {ok, Resp} = start_chunked_response(Req, 200, Headers),
-                    AttFun(Att, fun(Seg, _) -> send_chunk(Resp, Seg) end, {ok, Resp}),
-                    last_chunk(Resp);
-                _ ->
-                    Ranges = parse_ranges(MochiReq:get(range), Len),
-                    case {Enc, Ranges} of
-                        {identity, [{From, To}]} ->
-                            Headers1 = [{"Content-Range", make_content_range(From, To, Len)}]
-                                ++ Headers,
-                            {ok, Resp} = start_response_length(Req, 206, Headers1, To - From + 1),
-                            couch_doc:range_att_foldl(Att, From, To + 1,
-                                fun(Seg, _) -> send(Resp, Seg) end, {ok, Resp});
-                        {identity, Ranges} when is_list(Ranges) andalso length(Ranges) < 10 ->
-                            send_ranges_multipart(Req, Type, Len, Att, Ranges);
-                        _ ->
-                            Headers1 = Headers ++
-                                if Enc =:= identity orelse ReqAcceptsAttEnc =:= true ->
-                                    [{"Content-MD5", base64:encode(Att#att.md5)}];
-                                true ->
-                                    []
-                            end,
-                            {ok, Resp} = start_response_length(Req, 200, Headers1, Len),
-                            AttFun(Att, fun(Seg, _) -> send(Resp, Seg) end, {ok, Resp})
-                    end
-                end
-            end
-        )
-    end;
-
-
-db_attachment_req(#httpd{method=Method,mochi_req=MochiReq}=Req, Db, DocId, FileNameParts)
-        when (Method == 'PUT') or (Method == 'DELETE') ->
-    FileName = validate_attachment_name(
-                    mochiweb_util:join(
-                        lists:map(fun binary_to_list/1,
-                            FileNameParts),"/")),
-
-    NewAtt = case Method of
-        'DELETE' ->
-            [];
-        _ ->
-            [#att{
-                name = FileName,
-                type = case couch_httpd:header_value(Req,"Content-Type") of
-                    undefined ->
-                        % We could throw an error here or guess by the FileName.
-                        % Currently, just giving it a default.
-                        <<"application/octet-stream">>;
-                    CType ->
-                        list_to_binary(CType)
-                    end,
-                data = case couch_httpd:body_length(Req) of
-                    undefined ->
-                        <<"">>;
-                    {unknown_transfer_encoding, Unknown} ->
-                        exit({unknown_transfer_encoding, Unknown});
-                    chunked ->
-                        fun(MaxChunkSize, ChunkFun, InitState) ->
-                            couch_httpd:recv_chunked(Req, MaxChunkSize,
-                                ChunkFun, InitState)
-                        end;
-                    0 ->
-                        <<"">>;
-                    Length when is_integer(Length) ->
-                        Expect = case couch_httpd:header_value(Req, "expect") of
-                                     undefined ->
-                                         undefined;
-                                     Value when is_list(Value) ->
-                                         string:to_lower(Value)
-                                 end,
-                        case Expect of
-                            "100-continue" ->
-                                MochiReq:start_raw_response({100, gb_trees:empty()});
-                            _Else ->
-                                ok
-                        end,
-
-
-                        fun(Size) -> couch_httpd:recv(Req, Size) end
-                    end,
-                att_len = case couch_httpd:header_value(Req,"Content-Length") of
-                    undefined ->
-                        undefined;
-                    Length ->
-                        list_to_integer(Length)
-                    end,
-                md5 = get_md5_header(Req),
-                encoding = case string:to_lower(string:strip(
-                    couch_httpd:header_value(Req,"Content-Encoding","identity")
-                )) of
-                "identity" ->
-                   identity;
-                "gzip" ->
-                   gzip;
-                _ ->
-                   throw({
-                       bad_ctype,
-                       "Only gzip and identity content-encodings are supported"
-                   })
-                end
-            }]
-    end,
-
-    Doc = case extract_header_rev(Req, couch_httpd:qs_value(Req, "rev")) of
-        missing_rev -> % make the new doc
-            couch_doc:validate_docid(DocId),
-            #doc{id=DocId};
-        Rev ->
-            case couch_db:open_doc_revs(Db, DocId, [Rev], []) of
-                {ok, [{ok, Doc0}]} -> Doc0;
-                {ok, [{{not_found, missing}, Rev}]} -> throw(conflict);
-                {ok, [Error]} -> throw(Error)
-            end
-    end,
-
-    #doc{atts=Atts} = Doc,
-    DocEdited = Doc#doc{
-        atts = NewAtt ++ [A || A <- Atts, A#att.name /= FileName]
-    },
-
-    Headers = case Method of
-    'DELETE' ->
-        [];
-    _ ->
-        [{"Location", absolute_uri(Req, "/" ++
-            ?b2l(Db#db.name) ++ "/" ++
-            ?b2l(DocId) ++ "/" ++
-            ?b2l(FileName)
-        )}]
-    end,
-    update_doc(Req, Db, DocId, DocEdited, Headers);
-
-db_attachment_req(Req, _Db, _DocId, _FileNameParts) ->
-    send_method_not_allowed(Req, "DELETE,GET,HEAD,PUT").
-
-parse_ranges(undefined, _Len) ->
-    undefined;
-parse_ranges(fail, _Len) ->
-    undefined;
-parse_ranges(Ranges, Len) ->
-    parse_ranges(Ranges, Len, []).
-
-parse_ranges([], _Len, Acc) ->
-    lists:reverse(Acc);
-parse_ranges([{0, none}|_], _Len, _Acc) ->
-    undefined;
-parse_ranges([{From, To}|_], _Len, _Acc) when is_integer(From) andalso is_integer(To) andalso To < From ->
-    throw(requested_range_not_satisfiable);
-parse_ranges([{From, To}|Rest], Len, Acc) when is_integer(To) andalso To >= Len ->
-    parse_ranges([{From, Len-1}] ++ Rest, Len, Acc);
-parse_ranges([{none, To}|Rest], Len, Acc) ->
-    parse_ranges([{Len - To, Len - 1}] ++ Rest, Len, Acc);
-parse_ranges([{From, none}|Rest], Len, Acc) ->
-    parse_ranges([{From, Len - 1}] ++ Rest, Len, Acc);
-parse_ranges([{From,To}|Rest], Len, Acc) ->
-    parse_ranges(Rest, Len, [{From, To}] ++ Acc).
-
-get_md5_header(Req) ->
-    ContentMD5 = couch_httpd:header_value(Req, "Content-MD5"),
-    Length = couch_httpd:body_length(Req),
-    Trailer = couch_httpd:header_value(Req, "Trailer"),
-    case {ContentMD5, Length, Trailer} of
-        _ when is_list(ContentMD5) orelse is_binary(ContentMD5) ->
-            base64:decode(ContentMD5);
-        {_, chunked, undefined} ->
-            <<>>;
-        {_, chunked, _} ->
-            case re:run(Trailer, "\\bContent-MD5\\b", [caseless]) of
-                {match, _} ->
-                    md5_in_footer;
-                _ ->
-                    <<>>
-            end;
-        _ ->
-            <<>>
-    end.
-
-parse_doc_query(Req) ->
-    lists:foldl(fun({Key,Value}, Args) ->
-        case {Key, Value} of
-        {"attachments", "true"} ->
-            Options = [attachments | Args#doc_query_args.options],
-            Args#doc_query_args{options=Options};
-        {"meta", "true"} ->
-            Options = [revs_info, conflicts, deleted_conflicts | Args#doc_query_args.options],
-            Args#doc_query_args{options=Options};
-        {"revs", "true"} ->
-            Options = [revs | Args#doc_query_args.options],
-            Args#doc_query_args{options=Options};
-        {"local_seq", "true"} ->
-            Options = [local_seq | Args#doc_query_args.options],
-            Args#doc_query_args{options=Options};
-        {"revs_info", "true"} ->
-            Options = [revs_info | Args#doc_query_args.options],
-            Args#doc_query_args{options=Options};
-        {"conflicts", "true"} ->
-            Options = [conflicts | Args#doc_query_args.options],
-            Args#doc_query_args{options=Options};
-        {"deleted_conflicts", "true"} ->
-            Options = [deleted_conflicts | Args#doc_query_args.options],
-            Args#doc_query_args{options=Options};
-        {"rev", Rev} ->
-            Args#doc_query_args{rev=couch_doc:parse_rev(Rev)};
-        {"open_revs", "all"} ->
-            Args#doc_query_args{open_revs=all};
-        {"open_revs", RevsJsonStr} ->
-            JsonArray = ?JSON_DECODE(RevsJsonStr),
-            Args#doc_query_args{open_revs=couch_doc:parse_revs(JsonArray)};
-        {"latest", "true"} ->
-            Options = [latest | Args#doc_query_args.options],
-            Args#doc_query_args{options=Options};
-        {"atts_since", RevsJsonStr} ->
-            JsonArray = ?JSON_DECODE(RevsJsonStr),
-            Args#doc_query_args{atts_since = couch_doc:parse_revs(JsonArray)};
-        {"new_edits", "false"} ->
-            Args#doc_query_args{update_type=replicated_changes};
-        {"new_edits", "true"} ->
-            Args#doc_query_args{update_type=interactive_edit};
-        {"att_encoding_info", "true"} ->
-            Options = [att_encoding_info | Args#doc_query_args.options],
-            Args#doc_query_args{options=Options};
-        _Else -> % unknown key value pair, ignore.
-            Args
-        end
-    end, #doc_query_args{}, couch_httpd:qs(Req)).
-
-parse_changes_query(Req, Db) ->
-    ChangesArgs = lists:foldl(fun({Key, Value}, Args) ->
-        case {string:to_lower(Key), Value} of
-        {"feed", _} ->
-            Args#changes_args{feed=Value};
-        {"descending", "true"} ->
-            Args#changes_args{dir=rev};
-        {"since", "now"} ->
-            UpdateSeq = couch_util:with_db(Db#db.name, fun(WDb) ->
-                                        couch_db:get_update_seq(WDb)
-                                end),
-            Args#changes_args{since=UpdateSeq};
-        {"since", _} ->
-            Args#changes_args{since=list_to_integer(Value)};
-        {"last-event-id", _} ->
-            Args#changes_args{since=list_to_integer(Value)};
-        {"limit", _} ->
-            Args#changes_args{limit=list_to_integer(Value)};
-        {"style", _} ->
-            Args#changes_args{style=list_to_existing_atom(Value)};
-        {"heartbeat", "true"} ->
-            Args#changes_args{heartbeat=true};
-        {"heartbeat", _} ->
-            Args#changes_args{heartbeat=list_to_integer(Value)};
-        {"timeout", _} ->
-            Args#changes_args{timeout=list_to_integer(Value)};
-        {"include_docs", "true"} ->
-            Args#changes_args{include_docs=true};
-        {"attachments", "true"} ->
-            Opts = Args#changes_args.doc_options,
-            Args#changes_args{doc_options=[attachments|Opts]};
-        {"att_encoding_info", "true"} ->
-            Opts = Args#changes_args.doc_options,
-            Args#changes_args{doc_options=[att_encoding_info|Opts]};
-        {"conflicts", "true"} ->
-            Args#changes_args{conflicts=true};
-        {"filter", _} ->
-            Args#changes_args{filter=Value};
-        _Else -> % unknown key value pair, ignore.
-            Args
-        end
-    end, #changes_args{}, couch_httpd:qs(Req)),
-    %% if it's an EventSource request with a Last-event-ID header
-    %% that should override the `since` query string, since it's
-    %% probably the browser reconnecting.
-    case ChangesArgs#changes_args.feed of
-        "eventsource" ->
-            case couch_httpd:header_value(Req, "last-event-id") of
-                undefined ->
-                    ChangesArgs;
-                Value ->
-                    ChangesArgs#changes_args{since=list_to_integer(Value)}
-            end;
-        _ ->
-            ChangesArgs
-    end.
-
-extract_header_rev(Req, ExplicitRev) when is_binary(ExplicitRev) or is_list(ExplicitRev)->
-    extract_header_rev(Req, couch_doc:parse_rev(ExplicitRev));
-extract_header_rev(Req, ExplicitRev) ->
-    Etag = case couch_httpd:header_value(Req, "If-Match") of
-        undefined -> undefined;
-        Value -> couch_doc:parse_rev(string:strip(Value, both, $"))
-    end,
-    case {ExplicitRev, Etag} of
-    {undefined, undefined} -> missing_rev;
-    {_, undefined} -> ExplicitRev;
-    {undefined, _} -> Etag;
-    _ when ExplicitRev == Etag -> Etag;
-    _ ->
-        throw({bad_request, "Document rev and etag have different values"})
-    end.
-
-
-parse_copy_destination_header(Req) ->
-    case couch_httpd:header_value(Req, "Destination") of
-    undefined ->
-        throw({bad_request, "Destination header is mandatory for COPY."});
-    Destination ->
-        case re:run(Destination, "^https?://", [{capture, none}]) of
-        match ->
-            throw({bad_request, "Destination URL must be relative."});
-        nomatch ->
-            % see if ?rev=revid got appended to the Destination header
-            case re:run(Destination, "\\?", [{capture, none}]) of
-            nomatch ->
-                {list_to_binary(Destination), {0, []}};
-            match ->
-                [DocId, RevQs] = re:split(Destination, "\\?", [{return, list}]),
-                [_RevQueryKey, Rev] = re:split(RevQs, "=", [{return, list}]),
-                {Pos, RevId} = couch_doc:parse_rev(Rev),
-                {list_to_binary(DocId), {Pos, [RevId]}}
-            end
-        end
-    end.
-
-validate_attachment_names(Doc) ->
-    lists:foreach(fun(#att{name=Name}) ->
-        validate_attachment_name(Name)
-    end, Doc#doc.atts).
-
-validate_attachment_name(Name) when is_list(Name) ->
-    validate_attachment_name(list_to_binary(Name));
-validate_attachment_name(<<"_",_/binary>>) ->
-    throw({bad_request, <<"Attachment name can't start with '_'">>});
-validate_attachment_name(Name) ->
-    case couch_util:validate_utf8(Name) of
-        true -> Name;
-        false -> throw({bad_request, <<"Attachment name is not UTF-8 encoded">>})
-    end.
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_httpd_external.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_httpd_external.erl b/apps/couch/src/couch_httpd_external.erl
deleted file mode 100644
index 2036d25..0000000
--- a/apps/couch/src/couch_httpd_external.erl
+++ /dev/null
@@ -1,177 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_httpd_external).
-
--export([handle_external_req/2, handle_external_req/3]).
--export([send_external_response/2, json_req_obj/2, json_req_obj/3]).
--export([default_or_content_type/2, parse_external_response/1]).
-
--import(couch_httpd,[send_error/4]).
-
--include("couch_db.hrl").
-
-% handle_external_req/2
-% for the old type of config usage:
-% _external = {couch_httpd_external, handle_external_req}
-% with urls like
-% /db/_external/action/design/name
-handle_external_req(#httpd{
-                        path_parts=[_DbName, _External, UrlName | _Path]
-                    }=HttpReq, Db) ->
-    process_external_req(HttpReq, Db, UrlName);
-handle_external_req(#httpd{path_parts=[_, _]}=Req, _Db) ->
-    send_error(Req, 404, <<"external_server_error">>, <<"No server name specified.">>);
-handle_external_req(Req, _) ->
-    send_error(Req, 404, <<"external_server_error">>, <<"Broken assumption">>).
-
-% handle_external_req/3
-% for this type of config usage:
-% _action = {couch_httpd_external, handle_external_req, <<"action">>}
-% with urls like
-% /db/_action/design/name
-handle_external_req(HttpReq, Db, Name) ->
-    process_external_req(HttpReq, Db, Name).
-
-process_external_req(HttpReq, Db, Name) ->
-
-    Response = couch_external_manager:execute(binary_to_list(Name),
-        json_req_obj(HttpReq, Db)),
-
-    case Response of
-    {unknown_external_server, Msg} ->
-        send_error(HttpReq, 404, <<"external_server_error">>, Msg);
-    _ ->
-        send_external_response(HttpReq, Response)
-    end.
-json_req_obj(Req, Db) -> json_req_obj(Req, Db, null).
-json_req_obj(#httpd{mochi_req=Req,
-               method=Method,
-               requested_path_parts=RequestedPath,
-               path_parts=Path,
-               req_body=ReqBody
-            }, Db, DocId) ->
-    Body = case ReqBody of
-        undefined ->
-            MaxSize = list_to_integer(
-                couch_config:get("couchdb", "max_document_size", "4294967296")),
-            Req:recv_body(MaxSize);
-        Else -> Else
-    end,
-    ParsedForm = case Req:get_primary_header_value("content-type") of
-        "application/x-www-form-urlencoded" ++ _ ->
-            case Body of
-            undefined -> [];
-            _ -> mochiweb_util:parse_qs(Body)
-            end;
-        _ ->
-            []
-    end,
-    Headers = Req:get(headers),
-    Hlist = mochiweb_headers:to_list(Headers),
-    {ok, Info} = couch_db:get_db_info(Db),
-    
-% add headers...
-    {[{<<"info">>, {Info}},
-        {<<"id">>, DocId},
-        {<<"uuid">>, couch_uuids:new()},
-        {<<"method">>, Method},
-        {<<"requested_path">>, RequestedPath},
-        {<<"path">>, Path},
-        {<<"raw_path">>, ?l2b(Req:get(raw_path))},
-        {<<"query">>, json_query_keys(to_json_terms(Req:parse_qs()))},
-        {<<"headers">>, to_json_terms(Hlist)},
-        {<<"body">>, Body},
-        {<<"peer">>, ?l2b(Req:get(peer))},
-        {<<"form">>, to_json_terms(ParsedForm)},
-        {<<"cookie">>, to_json_terms(Req:parse_cookie())},
-        {<<"userCtx">>, couch_util:json_user_ctx(Db)},
-        {<<"secObj">>, couch_db:get_security(Db)}]}.
-
-to_json_terms(Data) ->
-    to_json_terms(Data, []).
-
-to_json_terms([], Acc) ->
-    {lists:reverse(Acc)};
-to_json_terms([{Key, Value} | Rest], Acc) when is_atom(Key) ->
-    to_json_terms(Rest, [{list_to_binary(atom_to_list(Key)), list_to_binary(Value)} | Acc]);
-to_json_terms([{Key, Value} | Rest], Acc) ->
-    to_json_terms(Rest, [{list_to_binary(Key), list_to_binary(Value)} | Acc]).
-
-json_query_keys({Json}) ->
-    json_query_keys(Json, []).
-json_query_keys([], Acc) ->
-    {lists:reverse(Acc)};
-json_query_keys([{<<"startkey">>, Value} | Rest], Acc) ->
-    json_query_keys(Rest, [{<<"startkey">>, ?JSON_DECODE(Value)}|Acc]);
-json_query_keys([{<<"endkey">>, Value} | Rest], Acc) ->
-    json_query_keys(Rest, [{<<"endkey">>, ?JSON_DECODE(Value)}|Acc]);
-json_query_keys([{<<"key">>, Value} | Rest], Acc) ->
-    json_query_keys(Rest, [{<<"key">>, ?JSON_DECODE(Value)}|Acc]);
-json_query_keys([Term | Rest], Acc) ->
-    json_query_keys(Rest, [Term|Acc]).
-
-send_external_response(Req, Response) ->
-    #extern_resp_args{
-        code = Code,
-        data = Data,
-        ctype = CType,
-        headers = Headers,
-        json = Json
-    } = parse_external_response(Response),
-    Headers1 = default_or_content_type(CType, Headers),
-    case Json of
-    nil ->
-        couch_httpd:send_response(Req, Code, Headers1, Data);
-    Json ->
-        couch_httpd:send_json(Req, Code, Headers1, Json)
-    end.
-
-parse_external_response({Response}) ->
-    lists:foldl(fun({Key,Value}, Args) ->
-        case {Key, Value} of
-            {"", _} ->
-                Args;
-            {<<"code">>, Value} ->
-                Args#extern_resp_args{code=Value};
-            {<<"stop">>, true} ->
-                Args#extern_resp_args{stop=true};
-            {<<"json">>, Value} ->
-                Args#extern_resp_args{
-                    json=Value,
-                    ctype="application/json"};
-            {<<"body">>, Value} ->
-                Args#extern_resp_args{data=Value, ctype="text/html; charset=utf-8"};
-            {<<"base64">>, Value} ->
-                Args#extern_resp_args{
-                    data=base64:decode(Value),
-                    ctype="application/binary"
-                };
-            {<<"headers">>, {Headers}} ->
-                NewHeaders = lists:map(fun({Header, HVal}) ->
-                    {binary_to_list(Header), binary_to_list(HVal)}
-                end, Headers),
-                Args#extern_resp_args{headers=NewHeaders};
-            _ -> % unknown key
-                Msg = lists:flatten(io_lib:format("Invalid data from external server: ~p", [{Key, Value}])),
-                throw({external_response_error, Msg})
-            end
-        end, #extern_resp_args{}, Response).
-
-default_or_content_type(DefaultContentType, Headers) ->
-    IsContentType = fun({X, _}) -> string:to_lower(X) == "content-type" end,
-    case lists:any(IsContentType, Headers) of
-    false ->
-        [{"Content-Type", DefaultContentType} | Headers];
-    true ->
-        Headers
-    end.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_httpd_misc_handlers.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_httpd_misc_handlers.erl b/apps/couch/src/couch_httpd_misc_handlers.erl
deleted file mode 100644
index 96a05c6..0000000
--- a/apps/couch/src/couch_httpd_misc_handlers.erl
+++ /dev/null
@@ -1,318 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_httpd_misc_handlers).
-
--export([handle_welcome_req/2,handle_favicon_req/2,handle_utils_dir_req/2,
-    handle_all_dbs_req/1,handle_restart_req/1,
-    handle_uuids_req/1,handle_config_req/1,handle_log_req/1,
-    handle_task_status_req/1, handle_file_req/2]).
-
--export([increment_update_seq_req/2]).
-
-
--include("couch_db.hrl").
-
--import(couch_httpd,
-    [send_json/2,send_json/3,send_json/4,send_method_not_allowed/2,
-    start_json_response/2,send_chunk/2,last_chunk/1,end_json_response/1,
-    start_chunked_response/3, send_error/4]).
-
-% httpd global handlers
-
-handle_welcome_req(#httpd{method='GET'}=Req, WelcomeMessage) ->
-    send_json(Req, {[
-        {couchdb, WelcomeMessage},
-        {uuid, couch_server:get_uuid()},
-        {version, list_to_binary(couch_server:get_version())}
-        ] ++ case couch_config:get("vendor") of
-        [] ->
-            [];
-        Properties ->
-            [{vendor, {[{?l2b(K), ?l2b(V)} || {K, V} <- Properties]}}]
-        end
-    });
-handle_welcome_req(Req, _) ->
-    send_method_not_allowed(Req, "GET,HEAD").
-
-handle_favicon_req(#httpd{method='GET'}=Req, DocumentRoot) ->
-    {{Year,Month,Day},Time} = erlang:universaltime(),
-    OneYearFromNow = {{Year+1,Month,Day},Time},
-    CachingHeaders = [
-        %favicon should expire a year from now
-        {"Cache-Control", "public, max-age=31536000"},
-        {"Expires", couch_util:rfc1123_date(OneYearFromNow)}
-    ],
-    couch_httpd:serve_file(Req, "favicon.ico", DocumentRoot, CachingHeaders);
-
-handle_favicon_req(Req, _) ->
-    send_method_not_allowed(Req, "GET,HEAD").
-
-handle_file_req(#httpd{method='GET'}=Req, Document) ->
-    couch_httpd:serve_file(Req, filename:basename(Document), filename:dirname(Document));
-
-handle_file_req(Req, _) ->
-    send_method_not_allowed(Req, "GET,HEAD").
-
-handle_utils_dir_req(#httpd{method='GET'}=Req, DocumentRoot) ->
-    "/" ++ UrlPath = couch_httpd:path(Req),
-    case couch_httpd:partition(UrlPath) of
-    {_ActionKey, "/", RelativePath} ->
-        % GET /_utils/path or GET /_utils/
-        CachingHeaders =
-                [{"Cache-Control", "private, must-revalidate"}],
-        couch_httpd:serve_file(Req, RelativePath, DocumentRoot, CachingHeaders);
-    {_ActionKey, "", _RelativePath} ->
-        % GET /_utils
-        RedirectPath = couch_httpd:path(Req) ++ "/",
-        couch_httpd:send_redirect(Req, RedirectPath)
-    end;
-handle_utils_dir_req(Req, _) ->
-    send_method_not_allowed(Req, "GET,HEAD").
-
-handle_all_dbs_req(#httpd{method='GET'}=Req) ->
-    {ok, DbNames} = couch_server:all_databases(),
-    send_json(Req, DbNames);
-handle_all_dbs_req(Req) ->
-    send_method_not_allowed(Req, "GET,HEAD").
-
-
-handle_task_status_req(#httpd{method='GET'}=Req) ->
-    ok = couch_httpd:verify_is_server_admin(Req),
-    % convert the list of prop lists to a list of json objects
-    send_json(Req, [{Props} || Props <- couch_task_status:all()]);
-handle_task_status_req(Req) ->
-    send_method_not_allowed(Req, "GET,HEAD").
-
-
-handle_restart_req(#httpd{method='POST'}=Req) ->
-    couch_httpd:validate_ctype(Req, "application/json"),
-    ok = couch_httpd:verify_is_server_admin(Req),
-    Result = send_json(Req, 202, {[{ok, true}]}),
-    couch_server_sup:restart_core_server(),
-    Result;
-handle_restart_req(Req) ->
-    send_method_not_allowed(Req, "POST").
-
-
-handle_uuids_req(#httpd{method='GET'}=Req) ->
-    Count = list_to_integer(couch_httpd:qs_value(Req, "count", "1")),
-    UUIDs = [couch_uuids:new() || _ <- lists:seq(1, Count)],
-    Etag = couch_httpd:make_etag(UUIDs),
-    couch_httpd:etag_respond(Req, Etag, fun() ->
-        CacheBustingHeaders = [
-            {"Date", couch_util:rfc1123_date()},
-            {"Cache-Control", "no-cache"},
-            % Past date, ON PURPOSE!
-            {"Expires", "Fri, 01 Jan 1990 00:00:00 GMT"},
-            {"Pragma", "no-cache"},
-            {"ETag", Etag}
-        ],
-        send_json(Req, 200, CacheBustingHeaders, {[{<<"uuids">>, UUIDs}]})
-    end);
-handle_uuids_req(Req) ->
-    send_method_not_allowed(Req, "GET").
-
-
-% Config request handler
-
-
-% GET /_config/
-% GET /_config
-handle_config_req(#httpd{method='GET', path_parts=[_]}=Req) ->
-    ok = couch_httpd:verify_is_server_admin(Req),
-    Grouped = lists:foldl(fun({{Section, Key}, Value}, Acc) ->
-        case dict:is_key(Section, Acc) of
-        true ->
-            dict:append(Section, {list_to_binary(Key), list_to_binary(Value)}, Acc);
-        false ->
-            dict:store(Section, [{list_to_binary(Key), list_to_binary(Value)}], Acc)
-        end
-    end, dict:new(), couch_config:all()),
-    KVs = dict:fold(fun(Section, Values, Acc) ->
-        [{list_to_binary(Section), {Values}} | Acc]
-    end, [], Grouped),
-    send_json(Req, 200, {KVs});
-% GET /_config/Section
-handle_config_req(#httpd{method='GET', path_parts=[_,Section]}=Req) ->
-    ok = couch_httpd:verify_is_server_admin(Req),
-    KVs = [{list_to_binary(Key), list_to_binary(Value)}
-            || {Key, Value} <- couch_config:get(Section)],
-    send_json(Req, 200, {KVs});
-% GET /_config/Section/Key
-handle_config_req(#httpd{method='GET', path_parts=[_, Section, Key]}=Req) ->
-    ok = couch_httpd:verify_is_server_admin(Req),
-    case couch_config:get(Section, Key, null) of
-    null ->
-        throw({not_found, unknown_config_value});
-    Value ->
-        send_json(Req, 200, list_to_binary(Value))
-    end;
-% PUT or DELETE /_config/Section/Key
-handle_config_req(#httpd{method=Method, path_parts=[_, Section, Key]}=Req)
-      when (Method == 'PUT') or (Method == 'DELETE') ->
-    ok = couch_httpd:verify_is_server_admin(Req),
-    Persist = couch_httpd:header_value(Req, "X-Couch-Persist") /= "false",
-    case couch_config:get(<<"httpd">>, <<"config_whitelist">>, null) of
-        null ->
-            % No whitelist; allow all changes.
-            handle_approved_config_req(Req, Persist);
-        WhitelistValue ->
-            % Provide a failsafe to protect against inadvertently locking
-            % onesself out of the config by supplying a syntactically-incorrect
-            % Erlang term. To intentionally lock down the whitelist, supply a
-            % well-formed list which does not include the whitelist config
-            % variable itself.
-            FallbackWhitelist = [{<<"httpd">>, <<"config_whitelist">>}],
-
-            Whitelist = case couch_util:parse_term(WhitelistValue) of
-                {ok, Value} when is_list(Value) ->
-                    Value;
-                {ok, _NonListValue} ->
-                    FallbackWhitelist;
-                {error, _} ->
-                    [{WhitelistSection, WhitelistKey}] = FallbackWhitelist,
-                    ?LOG_ERROR("Only whitelisting ~s/~s due to error parsing: ~p",
-                               [WhitelistSection, WhitelistKey, WhitelistValue]),
-                    FallbackWhitelist
-            end,
-
-            IsRequestedKeyVal = fun(Element) ->
-                case Element of
-                    {A, B} ->
-                        % For readability, tuples may be used instead of binaries
-                        % in the whitelist.
-                        case {couch_util:to_binary(A), couch_util:to_binary(B)} of
-                            {Section, Key} ->
-                                true;
-                            {Section, <<"*">>} ->
-                                true;
-                            _Else ->
-                                false
-                        end;
-                    _Else ->
-                        false
-                end
-            end,
-
-            case lists:any(IsRequestedKeyVal, Whitelist) of
-                true ->
-                    % Allow modifying this whitelisted variable.
-                    handle_approved_config_req(Req, Persist);
-                _NotWhitelisted ->
-                    % Disallow modifying this non-whitelisted variable.
-                    send_error(Req, 400, <<"modification_not_allowed">>,
-                               ?l2b("This config variable is read-only"))
-            end
-    end;
-handle_config_req(Req) ->
-    send_method_not_allowed(Req, "GET,PUT,DELETE").
-
-% PUT /_config/Section/Key
-% "value"
-handle_approved_config_req(Req, Persist) ->
-    Query = couch_httpd:qs(Req),
-    UseRawValue = case lists:keyfind("raw", 1, Query) of
-    false            -> false; % Not specified
-    {"raw", ""}      -> false; % Specified with no value, i.e. "?raw" and "?raw="
-    {"raw", "false"} -> false;
-    {"raw", "true"}  -> true;
-    {"raw", InvalidValue} -> InvalidValue
-    end,
-    handle_approved_config_req(Req, Persist, UseRawValue).
-
-handle_approved_config_req(#httpd{method='PUT', path_parts=[_, Section, Key]}=Req,
-                           Persist, UseRawValue)
-        when UseRawValue =:= false orelse UseRawValue =:= true ->
-    RawValue = couch_httpd:json_body(Req),
-    Value = case UseRawValue of
-    true ->
-        % Client requests no change to the provided value.
-        RawValue;
-    false ->
-        % Pre-process the value as necessary.
-        case Section of
-        <<"admins">> ->
-            couch_passwords:hash_admin_password(RawValue);
-        _ ->
-            RawValue
-        end
-    end,
-
-    OldValue = couch_config:get(Section, Key, ""),
-    case couch_config:set(Section, Key, ?b2l(Value), Persist) of
-    ok ->
-        send_json(Req, 200, list_to_binary(OldValue));
-    Error ->
-        throw(Error)
-    end;
-
-handle_approved_config_req(#httpd{method='PUT'}=Req, _Persist, UseRawValue) ->
-    Err = io_lib:format("Bad value for 'raw' option: ~s", [UseRawValue]),
-    send_json(Req, 400, {[{error, ?l2b(Err)}]});
-
-% DELETE /_config/Section/Key
-handle_approved_config_req(#httpd{method='DELETE',path_parts=[_,Section,Key]}=Req,
-                           Persist, _UseRawValue) ->
-    case couch_config:get(Section, Key, null) of
-    null ->
-        throw({not_found, unknown_config_value});
-    OldValue ->
-        couch_config:delete(Section, Key, Persist),
-        send_json(Req, 200, list_to_binary(OldValue))
-    end.
-
-
-% httpd db handlers
-
-increment_update_seq_req(#httpd{method='POST'}=Req, Db) ->
-    couch_httpd:validate_ctype(Req, "application/json"),
-    {ok, NewSeq} = couch_db:increment_update_seq(Db),
-    send_json(Req, {[{ok, true},
-        {update_seq, NewSeq}
-    ]});
-increment_update_seq_req(Req, _Db) ->
-    send_method_not_allowed(Req, "POST").
-
-% httpd log handlers
-
-handle_log_req(#httpd{method='GET'}=Req) ->
-    ok = couch_httpd:verify_is_server_admin(Req),
-    Bytes = list_to_integer(couch_httpd:qs_value(Req, "bytes", "1000")),
-    Offset = list_to_integer(couch_httpd:qs_value(Req, "offset", "0")),
-    Chunk = couch_log:read(Bytes, Offset),
-    {ok, Resp} = start_chunked_response(Req, 200, [
-        % send a plaintext response
-        {"Content-Type", "text/plain; charset=utf-8"},
-        {"Content-Length", integer_to_list(length(Chunk))}
-    ]),
-    send_chunk(Resp, Chunk),
-    last_chunk(Resp);
-handle_log_req(#httpd{method='POST'}=Req) ->
-    {PostBody} = couch_httpd:json_body_obj(Req),
-    Level = couch_util:get_value(<<"level">>, PostBody),
-    Message = ?b2l(couch_util:get_value(<<"message">>, PostBody)),
-    case Level of
-    <<"debug">> ->
-        ?LOG_DEBUG(Message, []),
-        send_json(Req, 200, {[{ok, true}]});
-    <<"info">> ->
-        ?LOG_INFO(Message, []),
-        send_json(Req, 200, {[{ok, true}]});
-    <<"error">> ->
-        ?LOG_ERROR(Message, []),
-        send_json(Req, 200, {[{ok, true}]});
-    _ ->
-        send_json(Req, 400, {[{error, ?l2b(io_lib:format("Unrecognized log level '~s'", [Level]))}]})
-    end;
-handle_log_req(Req) ->
-    send_method_not_allowed(Req, "GET,POST").

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_httpd_oauth.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_httpd_oauth.erl b/apps/couch/src/couch_httpd_oauth.erl
deleted file mode 100644
index 2094c08..0000000
--- a/apps/couch/src/couch_httpd_oauth.erl
+++ /dev/null
@@ -1,387 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License.  You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_httpd_oauth).
-
--include("couch_db.hrl").
--include("couch_js_functions.hrl").
-
--export([oauth_authentication_handler/1, handle_oauth_req/1]).
-
--define(OAUTH_DDOC_ID, <<"_design/oauth">>).
--define(OAUTH_VIEW_NAME, <<"oauth_credentials">>).
-
--record(callback_params, {
-    consumer,
-    token,
-    token_secret,
-    url,
-    signature,
-    params,
-    username
-}).
-
-% OAuth auth handler using per-node user db
-oauth_authentication_handler(Req) ->
-    serve_oauth(Req, fun oauth_auth_callback/2, true).
-
-
-oauth_auth_callback(Req, #callback_params{token_secret = undefined}) ->
-    couch_httpd:send_error(
-         Req, 400, <<"invalid_token">>, <<"Invalid OAuth token.">>);
-
-oauth_auth_callback(#httpd{mochi_req = MochiReq} = Req, CbParams) ->
-    Method = atom_to_list(MochiReq:get(method)),
-    #callback_params{
-        consumer = Consumer,
-        token_secret = TokenSecret,
-        url = Url,
-        signature = Sig,
-        params = Params,
-        username = User
-    } = CbParams,
-    case oauth:verify(Sig, Method, Url, Params, Consumer, TokenSecret) of
-    true ->
-        set_user_ctx(Req, User);
-    false ->
-        ?LOG_DEBUG("OAuth handler: signature verification failed for user `~p`~n"
-            "Received signature is `~p`~n"
-            "HTTP method is `~p`~n"
-            "URL is `~p`~n"
-            "Parameters are `~p`~n"
-            "Consumer is `~p`, token secret is `~p`~n"
-            "Expected signature was `~p`~n",
-            [User, Sig, Method, Url, Params, Consumer, TokenSecret,
-                oauth:signature(Method, Url, Params, Consumer, TokenSecret)]),
-        Req
-    end.
-
-
-% Look up the consumer key and get the roles to give the consumer
-set_user_ctx(_Req, undefined) ->
-    throw({bad_request, unknown_oauth_token});
-set_user_ctx(Req, Name) ->
-    case couch_auth_cache:get_user_creds(Name) of
-        nil ->
-            ?LOG_DEBUG("OAuth handler: user `~p` credentials not found", [Name]),
-            Req;
-        User ->
-            Roles = couch_util:get_value(<<"roles">>, User, []),
-            Req#httpd{user_ctx=#user_ctx{name=Name, roles=Roles}}
-    end.
-
-% OAuth request_token
-handle_oauth_req(#httpd{path_parts=[_OAuth, <<"request_token">>], method=Method}=Req1) ->
-    serve_oauth(Req1, fun(Req, CbParams) ->
-        #callback_params{
-            consumer = Consumer,
-            token_secret = TokenSecret,
-            url = Url,
-            signature = Sig,
-            params = Params
-        } = CbParams,
-        case oauth:verify(
-            Sig, atom_to_list(Method), Url, Params, Consumer, TokenSecret) of
-        true ->
-            ok(Req, <<"oauth_token=requestkey&oauth_token_secret=requestsecret">>);
-        false ->
-            invalid_signature(Req)
-        end
-    end, false);
-handle_oauth_req(#httpd{path_parts=[_OAuth, <<"authorize">>]}=Req) ->
-    {ok, serve_oauth_authorize(Req)};
-handle_oauth_req(#httpd{path_parts=[_OAuth, <<"access_token">>], method='GET'}=Req1) ->
-    serve_oauth(Req1, fun(Req, CbParams) ->
-        #callback_params{
-            consumer = Consumer,
-            token = Token,
-            url = Url,
-            signature = Sig,
-            params = Params
-        } = CbParams,
-        case Token of
-        "requestkey" ->
-            case oauth:verify(
-                Sig, "GET", Url, Params, Consumer, "requestsecret") of
-            true ->
-                ok(Req,
-                    <<"oauth_token=accesskey&oauth_token_secret=accesssecret">>);
-            false ->
-                invalid_signature(Req)
-            end;
-        _ ->
-            couch_httpd:send_error(
-                Req, 400, <<"invalid_token">>, <<"Invalid OAuth token.">>)
-        end
-    end, false);
-handle_oauth_req(#httpd{path_parts=[_OAuth, <<"access_token">>]}=Req) ->
-    couch_httpd:send_method_not_allowed(Req, "GET").
-
-invalid_signature(Req) ->
-    couch_httpd:send_error(Req, 400, <<"invalid_signature">>, <<"Invalid signature value.">>).
-
-% This needs to be protected i.e. force user to login using HTTP Basic Auth or form-based login.
-serve_oauth_authorize(#httpd{method=Method}=Req1) ->
-    case Method of
-        'GET' ->
-            % Confirm with the User that they want to authenticate the Consumer
-            serve_oauth(Req1, fun(Req, CbParams) ->
-                #callback_params{
-                    consumer = Consumer,
-                    token_secret = TokenSecret,
-                    url = Url,
-                    signature = Sig,
-                    params = Params
-                } = CbParams,
-                case oauth:verify(
-                    Sig, "GET", Url, Params, Consumer, TokenSecret) of
-                true ->
-                    ok(Req, <<"oauth_token=requestkey&",
-                        "oauth_token_secret=requestsecret">>);
-                false ->
-                    invalid_signature(Req)
-                end
-            end, false);
-        'POST' ->
-            % If the User has confirmed, we direct the User back to the Consumer with a verification code
-            serve_oauth(Req1, fun(Req, CbParams) ->
-                #callback_params{
-                    consumer = Consumer,
-                    token_secret = TokenSecret,
-                    url = Url,
-                    signature = Sig,
-                    params = Params
-                } = CbParams,
-                case oauth:verify(
-                    Sig, "POST", Url, Params, Consumer, TokenSecret) of
-                true ->
-                    %redirect(oauth_callback, oauth_token, oauth_verifier),
-                    ok(Req, <<"oauth_token=requestkey&",
-                        "oauth_token_secret=requestsecret">>);
-                false ->
-                    invalid_signature(Req)
-                end
-            end, false);
-        _ ->
-            couch_httpd:send_method_not_allowed(Req1, "GET,POST")
-    end.
-
-serve_oauth(#httpd{mochi_req=MochiReq}=Req, Fun, FailSilently) ->
-    % 1. In the HTTP Authorization header as defined in OAuth HTTP Authorization Scheme.
-    % 2. As the HTTP POST request body with a content-type of application/x-www-form-urlencoded.
-    % 3. Added to the URLs in the query part (as defined by [RFC3986] section 3).
-    AuthHeader = case MochiReq:get_header_value("authorization") of
-        undefined ->
-            "";
-        Else ->
-            [Head | Tail] = re:split(Else, "\\s", [{parts, 2}, {return, list}]),
-            case [string:to_lower(Head) | Tail] of
-                ["oauth", Rest] -> Rest;
-                _ -> ""
-            end
-    end,
-    HeaderParams = oauth:header_params_decode(AuthHeader),
-    %Realm = couch_util:get_value("realm", HeaderParams),
-
-    % get requested path
-    RequestedPath = case MochiReq:get_header_value("x-couchdb-requested-path") of
-        undefined ->
-            case MochiReq:get_header_value("x-couchdb-vhost-path") of
-                undefined ->
-                    MochiReq:get(raw_path);
-                VHostPath ->
-                    VHostPath
-            end;
-        RequestedPath0 ->
-           RequestedPath0
-    end,
-    {_, QueryString, _} = mochiweb_util:urlsplit_path(RequestedPath),
-
-    Params = proplists:delete("realm", HeaderParams) ++ mochiweb_util:parse_qs(QueryString),
-
-    ?LOG_DEBUG("OAuth Params: ~p", [Params]),
-    case couch_util:get_value("oauth_version", Params, "1.0") of
-        "1.0" ->
-            case couch_util:get_value("oauth_consumer_key", Params, undefined) of
-                undefined ->
-                    case FailSilently of
-                        true -> Req;
-                        false -> couch_httpd:send_error(Req, 400, <<"invalid_consumer">>, <<"Invalid consumer.">>)
-                    end;
-                ConsumerKey ->
-                    Url = couch_httpd:absolute_uri(Req, RequestedPath),
-                    case get_callback_params(ConsumerKey, Params, Url) of
-                        {ok, CallbackParams} ->
-                            Fun(Req, CallbackParams);
-                        invalid_consumer_token_pair ->
-                            couch_httpd:send_error(
-                                Req, 400,
-                                <<"invalid_consumer_token_pair">>,
-                                <<"Invalid consumer and token pair.">>);
-                        {error, {Error, Reason}} ->
-                            couch_httpd:send_error(Req, 400, Error, Reason)
-                    end
-            end;
-        _ ->
-            couch_httpd:send_error(Req, 400, <<"invalid_oauth_version">>, <<"Invalid OAuth version.">>)
-    end.
-
-
-get_callback_params(ConsumerKey, Params, Url) ->
-    Token = couch_util:get_value("oauth_token", Params),
-    SigMethod = sig_method(Params),
-    CbParams0 = #callback_params{
-        token = Token,
-        signature = couch_util:get_value("oauth_signature", Params),
-        params = proplists:delete("oauth_signature", Params),
-        url = Url
-    },
-    case oauth_credentials_info(Token, ConsumerKey) of
-    nil ->
-        invalid_consumer_token_pair;
-    {error, _} = Err ->
-        Err;
-    {OauthCreds} ->
-        User = couch_util:get_value(<<"username">>, OauthCreds, []),
-        ConsumerSecret = ?b2l(couch_util:get_value(
-            <<"consumer_secret">>, OauthCreds, <<>>)),
-        TokenSecret = ?b2l(couch_util:get_value(
-            <<"token_secret">>, OauthCreds, <<>>)),
-        case (User =:= []) orelse (ConsumerSecret =:= []) orelse
-            (TokenSecret =:= []) of
-        true ->
-            invalid_consumer_token_pair;
-        false ->
-            CbParams = CbParams0#callback_params{
-                consumer = {ConsumerKey, ConsumerSecret, SigMethod},
-                token_secret = TokenSecret,
-                username = User
-            },
-            ?LOG_DEBUG("Got OAuth credentials, for ConsumerKey `~p` and "
-                "Token `~p`, from the views, User: `~p`, "
-                "ConsumerSecret: `~p`, TokenSecret: `~p`",
-                [ConsumerKey, Token, User, ConsumerSecret, TokenSecret]),
-            {ok, CbParams}
-        end
-    end.
-
-
-sig_method(Params) ->
-    sig_method_1(couch_util:get_value("oauth_signature_method", Params)).
-sig_method_1("PLAINTEXT") ->
-    plaintext;
-% sig_method_1("RSA-SHA1") ->
-%    rsa_sha1;
-sig_method_1("HMAC-SHA1") ->
-    hmac_sha1;
-sig_method_1(_) ->
-    undefined.
-
-
-ok(#httpd{mochi_req=MochiReq}, Body) ->
-    {ok, MochiReq:respond({200, [], Body})}.
-
-
-oauth_credentials_info(Token, ConsumerKey) ->
-    case use_auth_db() of
-    {ok, Db} ->
-        Result = case query_oauth_view(Db, [?l2b(ConsumerKey), ?l2b(Token)]) of
-        [] ->
-            nil;
-        [Creds] ->
-            Creds;
-        [_ | _] ->
-            Reason = iolist_to_binary(
-                io_lib:format("Found multiple OAuth credentials for the pair "
-                    " (consumer_key: `~p`, token: `~p`)", [ConsumerKey, Token])),
-            {error, {<<"oauth_token_consumer_key_pair">>, Reason}}
-        end,
-        couch_db:close(Db),
-        Result;
-    nil ->
-        {
-            case couch_config:get("oauth_consumer_secrets", ConsumerKey) of
-            undefined -> [];
-            ConsumerSecret -> [{<<"consumer_secret">>, ?l2b(ConsumerSecret)}]
-            end
-            ++
-            case couch_config:get("oauth_token_secrets", Token) of
-            undefined -> [];
-            TokenSecret -> [{<<"token_secret">>, ?l2b(TokenSecret)}]
-            end
-            ++
-            case couch_config:get("oauth_token_users", Token) of
-            undefined -> [];
-            User -> [{<<"username">>, ?l2b(User)}]
-            end
-        }
-    end.
-
-
-use_auth_db() ->
-    case couch_config:get("couch_httpd_oauth", "use_users_db", "false") of
-    "false" ->
-        nil;
-    "true" ->
-        AuthDb = open_auth_db(),
-        {ok, _AuthDb2} = ensure_oauth_views_exist(AuthDb)
-    end.
-
-
-open_auth_db() ->
-    DbName = ?l2b(couch_config:get("couch_httpd_auth", "authentication_db")),
-    DbOptions = [{user_ctx, #user_ctx{roles = [<<"_admin">>]}}],
-    {ok, AuthDb} = couch_db:open_int(DbName, DbOptions),
-    AuthDb.
-
-
-ensure_oauth_views_exist(AuthDb) ->
-    case couch_db:open_doc(AuthDb, ?OAUTH_DDOC_ID, []) of
-    {ok, _DDoc} ->
-        {ok, AuthDb};
-    _ ->
-        {ok, DDoc} = get_oauth_ddoc(),
-        {ok, _Rev} = couch_db:update_doc(AuthDb, DDoc, []),
-        {ok, _AuthDb2} = couch_db:reopen(AuthDb)
-    end.
-
-
-get_oauth_ddoc() ->
-    Json = {[
-        {<<"_id">>, ?OAUTH_DDOC_ID},
-        {<<"language">>, <<"javascript">>},
-        {<<"views">>,
-            {[
-                {?OAUTH_VIEW_NAME,
-                    {[
-                        {<<"map">>, ?OAUTH_MAP_FUN}
-                    ]}
-                }
-            ]}
-        }
-    ]},
-    {ok, couch_doc:from_json_obj(Json)}.
-
-
-query_oauth_view(Db, Key) ->
-    ViewOptions = [
-        {start_key, Key},
-        {end_key, Key}
-    ],
-    Callback = fun({row, Row}, Acc) ->
-            {ok, [couch_util:get_value(value, Row) | Acc]};
-        (_, Acc) ->
-            {ok, Acc}
-    end,
-    {ok, Result} = couch_mrview:query_view(
-        Db, ?OAUTH_DDOC_ID, ?OAUTH_VIEW_NAME, ViewOptions, Callback, []),
-    Result.


[09/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/font-awesome/icons.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/font-awesome/icons.less b/apps/fauxton/assets/less/bootstrap/font-awesome/icons.less
deleted file mode 100644
index 476d201..0000000
--- a/apps/fauxton/assets/less/bootstrap/font-awesome/icons.less
+++ /dev/null
@@ -1,381 +0,0 @@
-/* Font Awesome uses the Unicode Private Use Area (PUA) to ensure screen
-   readers do not read off random characters that represent icons */
-
-.icon-glass:before { content: @glass; }
-.icon-music:before { content: @music; }
-.icon-search:before { content: @search; }
-.icon-envelope-alt:before { content: @envelope-alt; }
-.icon-heart:before { content: @heart; }
-.icon-star:before { content: @star; }
-.icon-star-empty:before { content: @star-empty; }
-.icon-user:before { content: @user; }
-.icon-film:before { content: @film; }
-.icon-th-large:before { content: @th-large; }
-.icon-th:before { content: @th; }
-.icon-th-list:before { content: @th-list; }
-.icon-ok:before { content: @ok; }
-.icon-remove:before { content: @remove; }
-.icon-zoom-in:before { content: @zoom-in; }
-.icon-zoom-out:before { content: @zoom-out; }
-.icon-power-off:before,
-.icon-off:before { content: @off; }
-.icon-signal:before { content: @signal; }
-.icon-gear:before,
-.icon-cog:before { content: @cog; }
-.icon-trash:before { content: @trash; }
-.icon-home:before { content: @home; }
-.icon-file-alt:before { content: @file-alt; }
-.icon-time:before { content: @time; }
-.icon-road:before { content: @road; }
-.icon-download-alt:before { content: @download-alt; }
-.icon-download:before { content: @download; }
-.icon-upload:before { content: @upload; }
-.icon-inbox:before { content: @inbox; }
-.icon-play-circle:before { content: @play-circle; }
-.icon-rotate-right:before,
-.icon-repeat:before { content: @repeat; }
-.icon-refresh:before { content: @refresh; }
-.icon-list-alt:before { content: @list-alt; }
-.icon-lock:before { content: @lock; }
-.icon-flag:before { content: @flag; }
-.icon-headphones:before { content: @headphones; }
-.icon-volume-off:before { content: @volume-off; }
-.icon-volume-down:before { content: @volume-down; }
-.icon-volume-up:before { content: @volume-up; }
-.icon-qrcode:before { content: @qrcode; }
-.icon-barcode:before { content: @barcode; }
-.icon-tag:before { content: @tag; }
-.icon-tags:before { content: @tags; }
-.icon-book:before { content: @book; }
-.icon-bookmark:before { content: @bookmark; }
-.icon-print:before { content: @print; }
-.icon-camera:before { content: @camera; }
-.icon-font:before { content: @font; }
-.icon-bold:before { content: @bold; }
-.icon-italic:before { content: @italic; }
-.icon-text-height:before { content: @text-height; }
-.icon-text-width:before { content: @text-width; }
-.icon-align-left:before { content: @align-left; }
-.icon-align-center:before { content: @align-center; }
-.icon-align-right:before { content: @align-right; }
-.icon-align-justify:before { content: @align-justify; }
-.icon-list:before { content: @list; }
-.icon-indent-left:before { content: @indent-left; }
-.icon-indent-right:before { content: @indent-right; }
-.icon-facetime-video:before { content: @facetime-video; }
-.icon-picture:before { content: @picture; }
-.icon-pencil:before { content: @pencil; }
-.icon-map-marker:before { content: @map-marker; }
-.icon-adjust:before { content: @adjust; }
-.icon-tint:before { content: @tint; }
-.icon-edit:before { content: @edit; }
-.icon-share:before { content: @share; }
-.icon-check:before { content: @check; }
-.icon-move:before { content: @move; }
-.icon-step-backward:before { content: @step-backward; }
-.icon-fast-backward:before { content: @fast-backward; }
-.icon-backward:before { content: @backward; }
-.icon-play:before { content: @play; }
-.icon-pause:before { content: @pause; }
-.icon-stop:before { content: @stop; }
-.icon-forward:before { content: @forward; }
-.icon-fast-forward:before { content: @fast-forward; }
-.icon-step-forward:before { content: @step-forward; }
-.icon-eject:before { content: @eject; }
-.icon-chevron-left:before { content: @chevron-left; }
-.icon-chevron-right:before { content: @chevron-right; }
-.icon-plus-sign:before { content: @plus-sign; }
-.icon-minus-sign:before { content: @minus-sign; }
-.icon-remove-sign:before { content: @remove-sign; }
-.icon-ok-sign:before { content: @ok-sign; }
-.icon-question-sign:before { content: @question-sign; }
-.icon-info-sign:before { content: @info-sign; }
-.icon-screenshot:before { content: @screenshot; }
-.icon-remove-circle:before { content: @remove-circle; }
-.icon-ok-circle:before { content: @ok-circle; }
-.icon-ban-circle:before { content: @ban-circle; }
-.icon-arrow-left:before { content: @arrow-left; }
-.icon-arrow-right:before { content: @arrow-right; }
-.icon-arrow-up:before { content: @arrow-up; }
-.icon-arrow-down:before { content: @arrow-down; }
-.icon-mail-forward:before,
-.icon-share-alt:before { content: @share-alt; }
-.icon-resize-full:before { content: @resize-full; }
-.icon-resize-small:before { content: @resize-small; }
-.icon-plus:before { content: @plus; }
-.icon-minus:before { content: @minus; }
-.icon-asterisk:before { content: @asterisk; }
-.icon-exclamation-sign:before { content: @exclamation-sign; }
-.icon-gift:before { content: @gift; }
-.icon-leaf:before { content: @leaf; }
-.icon-fire:before { content: @fire; }
-.icon-eye-open:before { content: @eye-open; }
-.icon-eye-close:before { content: @eye-close; }
-.icon-warning-sign:before { content: @warning-sign; }
-.icon-plane:before { content: @plane; }
-.icon-calendar:before { content: @calendar; }
-.icon-random:before { content: @random; }
-.icon-comment:before { content: @comment; }
-.icon-magnet:before { content: @magnet; }
-.icon-chevron-up:before { content: @chevron-up; }
-.icon-chevron-down:before { content: @chevron-down; }
-.icon-retweet:before { content: @retweet; }
-.icon-shopping-cart:before { content: @shopping-cart; }
-.icon-folder-close:before { content: @folder-close; }
-.icon-folder-open:before { content: @folder-open; }
-.icon-resize-vertical:before { content: @resize-vertical; }
-.icon-resize-horizontal:before { content: @resize-horizontal; }
-.icon-bar-chart:before { content: @bar-chart; }
-.icon-twitter-sign:before { content: @twitter-sign; }
-.icon-facebook-sign:before { content: @facebook-sign; }
-.icon-camera-retro:before { content: @camera-retro; }
-.icon-key:before { content: @key; }
-.icon-gears:before,
-.icon-cogs:before { content: @cogs; }
-.icon-comments:before { content: @comments; }
-.icon-thumbs-up-alt:before { content: @thumbs-up-alt; }
-.icon-thumbs-down-alt:before { content: @thumbs-down-alt; }
-.icon-star-half:before { content: @star-half; }
-.icon-heart-empty:before { content: @heart-empty; }
-.icon-signout:before { content: @signout; }
-.icon-linkedin-sign:before { content: @linkedin-sign; }
-.icon-pushpin:before { content: @pushpin; }
-.icon-external-link:before { content: @external-link; }
-.icon-signin:before { content: @signin; }
-.icon-trophy:before { content: @trophy; }
-.icon-github-sign:before { content: @github-sign; }
-.icon-upload-alt:before { content: @upload-alt; }
-.icon-lemon:before { content: @lemon; }
-.icon-phone:before { content: @phone; }
-.icon-unchecked:before,
-.icon-check-empty:before { content: @check-empty; }
-.icon-bookmark-empty:before { content: @bookmark-empty; }
-.icon-phone-sign:before { content: @phone-sign; }
-.icon-twitter:before { content: @twitter; }
-.icon-facebook:before { content: @facebook; }
-.icon-github:before { content: @github; }
-.icon-unlock:before { content: @unlock; }
-.icon-credit-card:before { content: @credit-card; }
-.icon-rss:before { content: @rss; }
-.icon-hdd:before { content: @hdd; }
-.icon-bullhorn:before { content: @bullhorn; }
-.icon-bell:before { content: @bell; }
-.icon-certificate:before { content: @certificate; }
-.icon-hand-right:before { content: @hand-right; }
-.icon-hand-left:before { content: @hand-left; }
-.icon-hand-up:before { content: @hand-up; }
-.icon-hand-down:before { content: @hand-down; }
-.icon-circle-arrow-left:before { content: @circle-arrow-left; }
-.icon-circle-arrow-right:before { content: @circle-arrow-right; }
-.icon-circle-arrow-up:before { content: @circle-arrow-up; }
-.icon-circle-arrow-down:before { content: @circle-arrow-down; }
-.icon-globe:before { content: @globe; }
-.icon-wrench:before { content: @wrench; }
-.icon-tasks:before { content: @tasks; }
-.icon-filter:before { content: @filter; }
-.icon-briefcase:before { content: @briefcase; }
-.icon-fullscreen:before { content: @fullscreen; }
-.icon-group:before { content: @group; }
-.icon-link:before { content: @link; }
-.icon-cloud:before { content: @cloud; }
-.icon-beaker:before { content: @beaker; }
-.icon-cut:before { content: @cut; }
-.icon-copy:before { content: @copy; }
-.icon-paperclip:before,
-.icon-paper-clip:before { content: @paper-clip; }
-.icon-save:before { content: @save; }
-.icon-sign-blank:before { content: @sign-blank; }
-.icon-reorder:before { content: @reorder; }
-.icon-list-ul:before { content: @list-ul; }
-.icon-list-ol:before { content: @list-ol; }
-.icon-strikethrough:before { content: @strikethrough; }
-.icon-underline:before { content: @underline; }
-.icon-table:before { content: @table; }
-.icon-magic:before { content: @magic; }
-.icon-truck:before { content: @truck; }
-.icon-pinterest:before { content: @pinterest; }
-.icon-pinterest-sign:before { content: @pinterest-sign; }
-.icon-google-plus-sign:before { content: @google-plus-sign; }
-.icon-google-plus:before { content: @google-plus; }
-.icon-money:before { content: @money; }
-.icon-caret-down:before { content: @caret-down; }
-.icon-caret-up:before { content: @caret-up; }
-.icon-caret-left:before { content: @caret-left; }
-.icon-caret-right:before { content: @caret-right; }
-.icon-columns:before { content: @columns; }
-.icon-sort:before { content: @sort; }
-.icon-sort-down:before { content: @sort-down; }
-.icon-sort-up:before { content: @sort-up; }
-.icon-envelope:before { content: @envelope; }
-.icon-linkedin:before { content: @linkedin; }
-.icon-rotate-left:before,
-.icon-undo:before { content: @undo; }
-.icon-legal:before { content: @legal; }
-.icon-dashboard:before { content: @dashboard; }
-.icon-comment-alt:before { content: @comment-alt; }
-.icon-comments-alt:before { content: @comments-alt; }
-.icon-bolt:before { content: @bolt; }
-.icon-sitemap:before { content: @sitemap; }
-.icon-umbrella:before { content: @umbrella; }
-.icon-paste:before { content: @paste; }
-.icon-lightbulb:before { content: @lightbulb; }
-.icon-exchange:before { content: @exchange; }
-.icon-cloud-download:before { content: @cloud-download; }
-.icon-cloud-upload:before { content: @cloud-upload; }
-.icon-user-md:before { content: @user-md; }
-.icon-stethoscope:before { content: @stethoscope; }
-.icon-suitcase:before { content: @suitcase; }
-.icon-bell-alt:before { content: @bell-alt; }
-.icon-coffee:before { content: @coffee; }
-.icon-food:before { content: @food; }
-.icon-file-text-alt:before { content: @file-text-alt; }
-.icon-building:before { content: @building; }
-.icon-hospital:before { content: @hospital; }
-.icon-ambulance:before { content: @ambulance; }
-.icon-medkit:before { content: @medkit; }
-.icon-fighter-jet:before { content: @fighter-jet; }
-.icon-beer:before { content: @beer; }
-.icon-h-sign:before { content: @h-sign; }
-.icon-plus-sign-alt:before { content: @plus-sign-alt; }
-.icon-double-angle-left:before { content: @double-angle-left; }
-.icon-double-angle-right:before { content: @double-angle-right; }
-.icon-double-angle-up:before { content: @double-angle-up; }
-.icon-double-angle-down:before { content: @double-angle-down; }
-.icon-angle-left:before { content: @angle-left; }
-.icon-angle-right:before { content: @angle-right; }
-.icon-angle-up:before { content: @angle-up; }
-.icon-angle-down:before { content: @angle-down; }
-.icon-desktop:before { content: @desktop; }
-.icon-laptop:before { content: @laptop; }
-.icon-tablet:before { content: @tablet; }
-.icon-mobile-phone:before { content: @mobile-phone; }
-.icon-circle-blank:before { content: @circle-blank; }
-.icon-quote-left:before { content: @quote-left; }
-.icon-quote-right:before { content: @quote-right; }
-.icon-spinner:before { content: @spinner; }
-.icon-circle:before { content: @circle; }
-.icon-mail-reply:before,
-.icon-reply:before { content: @reply; }
-.icon-github-alt:before { content: @github-alt; }
-.icon-folder-close-alt:before { content: @folder-close-alt; }
-.icon-folder-open-alt:before { content: @folder-open-alt; }
-.icon-expand-alt:before { content: @expand-alt; }
-.icon-collapse-alt:before { content: @collapse-alt; }
-.icon-smile:before { content: @smile; }
-.icon-frown:before { content: @frown; }
-.icon-meh:before { content: @meh; }
-.icon-gamepad:before { content: @gamepad; }
-.icon-keyboard:before { content: @keyboard; }
-.icon-flag-alt:before { content: @flag-alt; }
-.icon-flag-checkered:before { content: @flag-checkered; }
-.icon-terminal:before { content: @terminal; }
-.icon-code:before { content: @code; }
-.icon-reply-all:before { content: @reply-all; }
-.icon-mail-reply-all:before { content: @mail-reply-all; }
-.icon-star-half-full:before,
-.icon-star-half-empty:before { content: @star-half-empty; }
-.icon-location-arrow:before { content: @location-arrow; }
-.icon-crop:before { content: @crop; }
-.icon-code-fork:before { content: @code-fork; }
-.icon-unlink:before { content: @unlink; }
-.icon-question:before { content: @question; }
-.icon-info:before { content: @info; }
-.icon-exclamation:before { content: @exclamation; }
-.icon-superscript:before { content: @superscript; }
-.icon-subscript:before { content: @subscript; }
-.icon-eraser:before { content: @eraser; }
-.icon-puzzle-piece:before { content: @puzzle-piece; }
-.icon-microphone:before { content: @microphone; }
-.icon-microphone-off:before { content: @microphone-off; }
-.icon-shield:before { content: @shield; }
-.icon-calendar-empty:before { content: @calendar-empty; }
-.icon-fire-extinguisher:before { content: @fire-extinguisher; }
-.icon-rocket:before { content: @rocket; }
-.icon-maxcdn:before { content: @maxcdn; }
-.icon-chevron-sign-left:before { content: @chevron-sign-left; }
-.icon-chevron-sign-right:before { content: @chevron-sign-right; }
-.icon-chevron-sign-up:before { content: @chevron-sign-up; }
-.icon-chevron-sign-down:before { content: @chevron-sign-down; }
-.icon-html5:before { content: @html5; }
-.icon-css3:before { content: @css3; }
-.icon-anchor:before { content: @anchor; }
-.icon-unlock-alt:before { content: @unlock-alt; }
-.icon-bullseye:before { content: @bullseye; }
-.icon-ellipsis-horizontal:before { content: @ellipsis-horizontal; }
-.icon-ellipsis-vertical:before { content: @ellipsis-vertical; }
-.icon-rss-sign:before { content: @rss-sign; }
-.icon-play-sign:before { content: @play-sign; }
-.icon-ticket:before { content: @ticket; }
-.icon-minus-sign-alt:before { content: @minus-sign-alt; }
-.icon-check-minus:before { content: @check-minus; }
-.icon-level-up:before { content: @level-up; }
-.icon-level-down:before { content: @level-down; }
-.icon-check-sign:before { content: @check-sign; }
-.icon-edit-sign:before { content: @edit-sign; }
-.icon-external-link-sign:before { content: @external-link-sign; }
-.icon-share-sign:before { content: @share-sign; }
-.icon-compass:before { content: @compass; }
-.icon-collapse:before { content: @collapse; }
-.icon-collapse-top:before { content: @collapse-top; }
-.icon-expand:before { content: @expand; }
-.icon-euro:before,
-.icon-eur:before { content: @eur; }
-.icon-gbp:before { content: @gbp; }
-.icon-dollar:before,
-.icon-usd:before { content: @usd; }
-.icon-rupee:before,
-.icon-inr:before { content: @inr; }
-.icon-yen:before,
-.icon-jpy:before { content: @jpy; }
-.icon-renminbi:before,
-.icon-cny:before { content: @cny; }
-.icon-won:before,
-.icon-krw:before { content: @krw; }
-.icon-bitcoin:before,
-.icon-btc:before { content: @btc; }
-.icon-file:before { content: @file; }
-.icon-file-text:before { content: @file-text; }
-.icon-sort-by-alphabet:before { content: @sort-by-alphabet; }
-.icon-sort-by-alphabet-alt:before { content: @sort-by-alphabet-alt; }
-.icon-sort-by-attributes:before { content: @sort-by-attributes; }
-.icon-sort-by-attributes-alt:before { content: @sort-by-attributes-alt; }
-.icon-sort-by-order:before { content: @sort-by-order; }
-.icon-sort-by-order-alt:before { content: @sort-by-order-alt; }
-.icon-thumbs-up:before { content: @thumbs-up; }
-.icon-thumbs-down:before { content: @thumbs-down; }
-.icon-youtube-sign:before { content: @youtube-sign; }
-.icon-youtube:before { content: @youtube; }
-.icon-xing:before { content: @xing; }
-.icon-xing-sign:before { content: @xing-sign; }
-.icon-youtube-play:before { content: @youtube-play; }
-.icon-dropbox:before { content: @dropbox; }
-.icon-stackexchange:before { content: @stackexchange; }
-.icon-instagram:before { content: @instagram; }
-.icon-flickr:before { content: @flickr; }
-.icon-adn:before { content: @adn; }
-.icon-bitbucket:before { content: @bitbucket; }
-.icon-bitbucket-sign:before { content: @bitbucket-sign; }
-.icon-tumblr:before { content: @tumblr; }
-.icon-tumblr-sign:before { content: @tumblr-sign; }
-.icon-long-arrow-down:before { content: @long-arrow-down; }
-.icon-long-arrow-up:before { content: @long-arrow-up; }
-.icon-long-arrow-left:before { content: @long-arrow-left; }
-.icon-long-arrow-right:before { content: @long-arrow-right; }
-.icon-apple:before { content: @apple; }
-.icon-windows:before { content: @windows; }
-.icon-android:before { content: @android; }
-.icon-linux:before { content: @linux; }
-.icon-dribbble:before { content: @dribbble; }
-.icon-skype:before { content: @skype; }
-.icon-foursquare:before { content: @foursquare; }
-.icon-trello:before { content: @trello; }
-.icon-female:before { content: @female; }
-.icon-male:before { content: @male; }
-.icon-gittip:before { content: @gittip; }
-.icon-sun:before { content: @sun; }
-.icon-moon:before { content: @moon; }
-.icon-archive:before { content: @archive; }
-.icon-bug:before { content: @bug; }
-.icon-vk:before { content: @vk; }
-.icon-weibo:before { content: @weibo; }
-.icon-renren:before { content: @renren; }

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/font-awesome/mixins.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/font-awesome/mixins.less b/apps/fauxton/assets/less/bootstrap/font-awesome/mixins.less
deleted file mode 100644
index f7fdda5..0000000
--- a/apps/fauxton/assets/less/bootstrap/font-awesome/mixins.less
+++ /dev/null
@@ -1,48 +0,0 @@
-// Mixins
-// --------------------------
-
-.icon(@icon) {
-  .icon-FontAwesome();
-  content: @icon;
-}
-
-.icon-FontAwesome() {
-  font-family: FontAwesome;
-  font-weight: normal;
-  font-style: normal;
-  text-decoration: inherit;
-  -webkit-font-smoothing: antialiased;
-  *margin-right: .3em; // fixes ie7 issues
-}
-
-.border-radius(@radius) {
-  -webkit-border-radius: @radius;
-  -moz-border-radius: @radius;
-  border-radius: @radius;
-}
-
-.icon-stack(@width: 2em, @height: 2em, @top-font-size: 1em, @base-font-size: 2em) {
-  .icon-stack {
-    position: relative;
-    display: inline-block;
-    width: @width;
-    height: @height;
-    line-height: @width;
-    vertical-align: -35%;
-    [class^="icon-"],
-    [class*=" icon-"] {
-      display: block;
-      text-align: center;
-      position: absolute;
-      width: 100%;
-      height: 100%;
-      font-size: @top-font-size;
-      line-height: inherit;
-      *line-height: @height;
-    }
-    .icon-stack-base {
-      font-size: @base-font-size;
-      *line-height: @height / @base-font-size;
-    }
-  }
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/font-awesome/path.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/font-awesome/path.less b/apps/fauxton/assets/less/bootstrap/font-awesome/path.less
deleted file mode 100644
index 8ccef8c..0000000
--- a/apps/fauxton/assets/less/bootstrap/font-awesome/path.less
+++ /dev/null
@@ -1,14 +0,0 @@
-/* FONT PATH
- * -------------------------- */
-
-@font-face {
-  font-family: 'FontAwesome';
-  src: url('@{FontAwesomePath}/fontawesome-webfont.eot?v=@{FontAwesomeVersion}');
-  src: url('@{FontAwesomePath}/fontawesome-webfont.eot?#iefix&v=@{FontAwesomeVersion}') format('embedded-opentype'),
-    url('@{FontAwesomePath}/fontawesome-webfont.woff?v=@{FontAwesomeVersion}') format('woff'),
-    url('@{FontAwesomePath}/fontawesome-webfont.ttf?v=@{FontAwesomeVersion}') format('truetype'),
-    url('@{FontAwesomePath}/fontawesome-webfont.svg#fontawesomeregular?v=@{FontAwesomeVersion}') format('svg');
-//  src: url('@{FontAwesomePath}/FontAwesome.otf') format('opentype'); // used when developing fonts
-  font-weight: normal;
-  font-style: normal;
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/font-awesome/variables.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/font-awesome/variables.less b/apps/fauxton/assets/less/bootstrap/font-awesome/variables.less
deleted file mode 100644
index bb2986d..0000000
--- a/apps/fauxton/assets/less/bootstrap/font-awesome/variables.less
+++ /dev/null
@@ -1,735 +0,0 @@
-// Variables
-// --------------------------
-
-//@FontAwesomePath:    "../../img";
-@FontAwesomePath:    "//netdna.bootstrapcdn.com/font-awesome/3.2.1/font"; // for referencing Bootstrap CDN font files directly
-@FontAwesomeVersion: "3.2.1";
-@borderColor:        #eee;
-@iconMuted:          #eee;
-@iconLight:          #fff;
-@iconDark:           #333;
-@icons-li-width:     30/14em;
-
-
-  @glass: "\f000";
-
-  @music: "\f001";
-
-  @search: "\f002";
-
-  @envelope-alt: "\f003";
-
-  @heart: "\f004";
-
-  @star: "\f005";
-
-  @star-empty: "\f006";
-
-  @user: "\f007";
-
-  @film: "\f008";
-
-  @th-large: "\f009";
-
-  @th: "\f00a";
-
-  @th-list: "\f00b";
-
-  @ok: "\f00c";
-
-  @remove: "\f00d";
-
-  @zoom-in: "\f00e";
-
-  @zoom-out: "\f010";
-
-  @off: "\f011";
-
-  @signal: "\f012";
-
-  @cog: "\f013";
-
-  @trash: "\f014";
-
-  @home: "\f015";
-
-  @file-alt: "\f016";
-
-  @time: "\f017";
-
-  @road: "\f018";
-
-  @download-alt: "\f019";
-
-  @download: "\f01a";
-
-  @upload: "\f01b";
-
-  @inbox: "\f01c";
-
-  @play-circle: "\f01d";
-
-  @repeat: "\f01e";
-
-  @refresh: "\f021";
-
-  @list-alt: "\f022";
-
-  @lock: "\f023";
-
-  @flag: "\f024";
-
-  @headphones: "\f025";
-
-  @volume-off: "\f026";
-
-  @volume-down: "\f027";
-
-  @volume-up: "\f028";
-
-  @qrcode: "\f029";
-
-  @barcode: "\f02a";
-
-  @tag: "\f02b";
-
-  @tags: "\f02c";
-
-  @book: "\f02d";
-
-  @bookmark: "\f02e";
-
-  @print: "\f02f";
-
-  @camera: "\f030";
-
-  @font: "\f031";
-
-  @bold: "\f032";
-
-  @italic: "\f033";
-
-  @text-height: "\f034";
-
-  @text-width: "\f035";
-
-  @align-left: "\f036";
-
-  @align-center: "\f037";
-
-  @align-right: "\f038";
-
-  @align-justify: "\f039";
-
-  @list: "\f03a";
-
-  @indent-left: "\f03b";
-
-  @indent-right: "\f03c";
-
-  @facetime-video: "\f03d";
-
-  @picture: "\f03e";
-
-  @pencil: "\f040";
-
-  @map-marker: "\f041";
-
-  @adjust: "\f042";
-
-  @tint: "\f043";
-
-  @edit: "\f044";
-
-  @share: "\f045";
-
-  @check: "\f046";
-
-  @move: "\f047";
-
-  @step-backward: "\f048";
-
-  @fast-backward: "\f049";
-
-  @backward: "\f04a";
-
-  @play: "\f04b";
-
-  @pause: "\f04c";
-
-  @stop: "\f04d";
-
-  @forward: "\f04e";
-
-  @fast-forward: "\f050";
-
-  @step-forward: "\f051";
-
-  @eject: "\f052";
-
-  @chevron-left: "\f053";
-
-  @chevron-right: "\f054";
-
-  @plus-sign: "\f055";
-
-  @minus-sign: "\f056";
-
-  @remove-sign: "\f057";
-
-  @ok-sign: "\f058";
-
-  @question-sign: "\f059";
-
-  @info-sign: "\f05a";
-
-  @screenshot: "\f05b";
-
-  @remove-circle: "\f05c";
-
-  @ok-circle: "\f05d";
-
-  @ban-circle: "\f05e";
-
-  @arrow-left: "\f060";
-
-  @arrow-right: "\f061";
-
-  @arrow-up: "\f062";
-
-  @arrow-down: "\f063";
-
-  @share-alt: "\f064";
-
-  @resize-full: "\f065";
-
-  @resize-small: "\f066";
-
-  @plus: "\f067";
-
-  @minus: "\f068";
-
-  @asterisk: "\f069";
-
-  @exclamation-sign: "\f06a";
-
-  @gift: "\f06b";
-
-  @leaf: "\f06c";
-
-  @fire: "\f06d";
-
-  @eye-open: "\f06e";
-
-  @eye-close: "\f070";
-
-  @warning-sign: "\f071";
-
-  @plane: "\f072";
-
-  @calendar: "\f073";
-
-  @random: "\f074";
-
-  @comment: "\f075";
-
-  @magnet: "\f076";
-
-  @chevron-up: "\f077";
-
-  @chevron-down: "\f078";
-
-  @retweet: "\f079";
-
-  @shopping-cart: "\f07a";
-
-  @folder-close: "\f07b";
-
-  @folder-open: "\f07c";
-
-  @resize-vertical: "\f07d";
-
-  @resize-horizontal: "\f07e";
-
-  @bar-chart: "\f080";
-
-  @twitter-sign: "\f081";
-
-  @facebook-sign: "\f082";
-
-  @camera-retro: "\f083";
-
-  @key: "\f084";
-
-  @cogs: "\f085";
-
-  @comments: "\f086";
-
-  @thumbs-up-alt: "\f087";
-
-  @thumbs-down-alt: "\f088";
-
-  @star-half: "\f089";
-
-  @heart-empty: "\f08a";
-
-  @signout: "\f08b";
-
-  @linkedin-sign: "\f08c";
-
-  @pushpin: "\f08d";
-
-  @external-link: "\f08e";
-
-  @signin: "\f090";
-
-  @trophy: "\f091";
-
-  @github-sign: "\f092";
-
-  @upload-alt: "\f093";
-
-  @lemon: "\f094";
-
-  @phone: "\f095";
-
-  @check-empty: "\f096";
-
-  @bookmark-empty: "\f097";
-
-  @phone-sign: "\f098";
-
-  @twitter: "\f099";
-
-  @facebook: "\f09a";
-
-  @github: "\f09b";
-
-  @unlock: "\f09c";
-
-  @credit-card: "\f09d";
-
-  @rss: "\f09e";
-
-  @hdd: "\f0a0";
-
-  @bullhorn: "\f0a1";
-
-  @bell: "\f0a2";
-
-  @certificate: "\f0a3";
-
-  @hand-right: "\f0a4";
-
-  @hand-left: "\f0a5";
-
-  @hand-up: "\f0a6";
-
-  @hand-down: "\f0a7";
-
-  @circle-arrow-left: "\f0a8";
-
-  @circle-arrow-right: "\f0a9";
-
-  @circle-arrow-up: "\f0aa";
-
-  @circle-arrow-down: "\f0ab";
-
-  @globe: "\f0ac";
-
-  @wrench: "\f0ad";
-
-  @tasks: "\f0ae";
-
-  @filter: "\f0b0";
-
-  @briefcase: "\f0b1";
-
-  @fullscreen: "\f0b2";
-
-  @group: "\f0c0";
-
-  @link: "\f0c1";
-
-  @cloud: "\f0c2";
-
-  @beaker: "\f0c3";
-
-  @cut: "\f0c4";
-
-  @copy: "\f0c5";
-
-  @paper-clip: "\f0c6";
-
-  @save: "\f0c7";
-
-  @sign-blank: "\f0c8";
-
-  @reorder: "\f0c9";
-
-  @list-ul: "\f0ca";
-
-  @list-ol: "\f0cb";
-
-  @strikethrough: "\f0cc";
-
-  @underline: "\f0cd";
-
-  @table: "\f0ce";
-
-  @magic: "\f0d0";
-
-  @truck: "\f0d1";
-
-  @pinterest: "\f0d2";
-
-  @pinterest-sign: "\f0d3";
-
-  @google-plus-sign: "\f0d4";
-
-  @google-plus: "\f0d5";
-
-  @money: "\f0d6";
-
-  @caret-down: "\f0d7";
-
-  @caret-up: "\f0d8";
-
-  @caret-left: "\f0d9";
-
-  @caret-right: "\f0da";
-
-  @columns: "\f0db";
-
-  @sort: "\f0dc";
-
-  @sort-down: "\f0dd";
-
-  @sort-up: "\f0de";
-
-  @envelope: "\f0e0";
-
-  @linkedin: "\f0e1";
-
-  @undo: "\f0e2";
-
-  @legal: "\f0e3";
-
-  @dashboard: "\f0e4";
-
-  @comment-alt: "\f0e5";
-
-  @comments-alt: "\f0e6";
-
-  @bolt: "\f0e7";
-
-  @sitemap: "\f0e8";
-
-  @umbrella: "\f0e9";
-
-  @paste: "\f0ea";
-
-  @lightbulb: "\f0eb";
-
-  @exchange: "\f0ec";
-
-  @cloud-download: "\f0ed";
-
-  @cloud-upload: "\f0ee";
-
-  @user-md: "\f0f0";
-
-  @stethoscope: "\f0f1";
-
-  @suitcase: "\f0f2";
-
-  @bell-alt: "\f0f3";
-
-  @coffee: "\f0f4";
-
-  @food: "\f0f5";
-
-  @file-text-alt: "\f0f6";
-
-  @building: "\f0f7";
-
-  @hospital: "\f0f8";
-
-  @ambulance: "\f0f9";
-
-  @medkit: "\f0fa";
-
-  @fighter-jet: "\f0fb";
-
-  @beer: "\f0fc";
-
-  @h-sign: "\f0fd";
-
-  @plus-sign-alt: "\f0fe";
-
-  @double-angle-left: "\f100";
-
-  @double-angle-right: "\f101";
-
-  @double-angle-up: "\f102";
-
-  @double-angle-down: "\f103";
-
-  @angle-left: "\f104";
-
-  @angle-right: "\f105";
-
-  @angle-up: "\f106";
-
-  @angle-down: "\f107";
-
-  @desktop: "\f108";
-
-  @laptop: "\f109";
-
-  @tablet: "\f10a";
-
-  @mobile-phone: "\f10b";
-
-  @circle-blank: "\f10c";
-
-  @quote-left: "\f10d";
-
-  @quote-right: "\f10e";
-
-  @spinner: "\f110";
-
-  @circle: "\f111";
-
-  @reply: "\f112";
-
-  @github-alt: "\f113";
-
-  @folder-close-alt: "\f114";
-
-  @folder-open-alt: "\f115";
-
-  @expand-alt: "\f116";
-
-  @collapse-alt: "\f117";
-
-  @smile: "\f118";
-
-  @frown: "\f119";
-
-  @meh: "\f11a";
-
-  @gamepad: "\f11b";
-
-  @keyboard: "\f11c";
-
-  @flag-alt: "\f11d";
-
-  @flag-checkered: "\f11e";
-
-  @terminal: "\f120";
-
-  @code: "\f121";
-
-  @reply-all: "\f122";
-
-  @mail-reply-all: "\f122";
-
-  @star-half-empty: "\f123";
-
-  @location-arrow: "\f124";
-
-  @crop: "\f125";
-
-  @code-fork: "\f126";
-
-  @unlink: "\f127";
-
-  @question: "\f128";
-
-  @info: "\f129";
-
-  @exclamation: "\f12a";
-
-  @superscript: "\f12b";
-
-  @subscript: "\f12c";
-
-  @eraser: "\f12d";
-
-  @puzzle-piece: "\f12e";
-
-  @microphone: "\f130";
-
-  @microphone-off: "\f131";
-
-  @shield: "\f132";
-
-  @calendar-empty: "\f133";
-
-  @fire-extinguisher: "\f134";
-
-  @rocket: "\f135";
-
-  @maxcdn: "\f136";
-
-  @chevron-sign-left: "\f137";
-
-  @chevron-sign-right: "\f138";
-
-  @chevron-sign-up: "\f139";
-
-  @chevron-sign-down: "\f13a";
-
-  @html5: "\f13b";
-
-  @css3: "\f13c";
-
-  @anchor: "\f13d";
-
-  @unlock-alt: "\f13e";
-
-  @bullseye: "\f140";
-
-  @ellipsis-horizontal: "\f141";
-
-  @ellipsis-vertical: "\f142";
-
-  @rss-sign: "\f143";
-
-  @play-sign: "\f144";
-
-  @ticket: "\f145";
-
-  @minus-sign-alt: "\f146";
-
-  @check-minus: "\f147";
-
-  @level-up: "\f148";
-
-  @level-down: "\f149";
-
-  @check-sign: "\f14a";
-
-  @edit-sign: "\f14b";
-
-  @external-link-sign: "\f14c";
-
-  @share-sign: "\f14d";
-
-  @compass: "\f14e";
-
-  @collapse: "\f150";
-
-  @collapse-top: "\f151";
-
-  @expand: "\f152";
-
-  @eur: "\f153";
-
-  @gbp: "\f154";
-
-  @usd: "\f155";
-
-  @inr: "\f156";
-
-  @jpy: "\f157";
-
-  @cny: "\f158";
-
-  @krw: "\f159";
-
-  @btc: "\f15a";
-
-  @file: "\f15b";
-
-  @file-text: "\f15c";
-
-  @sort-by-alphabet: "\f15d";
-
-  @sort-by-alphabet-alt: "\f15e";
-
-  @sort-by-attributes: "\f160";
-
-  @sort-by-attributes-alt: "\f161";
-
-  @sort-by-order: "\f162";
-
-  @sort-by-order-alt: "\f163";
-
-  @thumbs-up: "\f164";
-
-  @thumbs-down: "\f165";
-
-  @youtube-sign: "\f166";
-
-  @youtube: "\f167";
-
-  @xing: "\f168";
-
-  @xing-sign: "\f169";
-
-  @youtube-play: "\f16a";
-
-  @dropbox: "\f16b";
-
-  @stackexchange: "\f16c";
-
-  @instagram: "\f16d";
-
-  @flickr: "\f16e";
-
-  @adn: "\f170";
-
-  @bitbucket: "\f171";
-
-  @bitbucket-sign: "\f172";
-
-  @tumblr: "\f173";
-
-  @tumblr-sign: "\f174";
-
-  @long-arrow-down: "\f175";
-
-  @long-arrow-up: "\f176";
-
-  @long-arrow-left: "\f177";
-
-  @long-arrow-right: "\f178";
-
-  @apple: "\f179";
-
-  @windows: "\f17a";
-
-  @android: "\f17b";
-
-  @linux: "\f17c";
-
-  @dribbble: "\f17d";
-
-  @skype: "\f17e";
-
-  @foursquare: "\f180";
-
-  @trello: "\f181";
-
-  @female: "\f182";
-
-  @male: "\f183";
-
-  @gittip: "\f184";
-
-  @sun: "\f185";
-
-  @moon: "\f186";
-
-  @archive: "\f187";
-
-  @bug: "\f188";
-
-  @vk: "\f189";
-
-  @weibo: "\f18a";
-
-  @renren: "\f18b";
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/forms.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/forms.less b/apps/fauxton/assets/less/bootstrap/forms.less
deleted file mode 100644
index 06767bd..0000000
--- a/apps/fauxton/assets/less/bootstrap/forms.less
+++ /dev/null
@@ -1,690 +0,0 @@
-//
-// Forms
-// --------------------------------------------------
-
-
-// GENERAL STYLES
-// --------------
-
-// Make all forms have space below them
-form {
-  margin: 0 0 @baseLineHeight;
-}
-
-fieldset {
-  padding: 0;
-  margin: 0;
-  border: 0;
-}
-
-// Groups of fields with labels on top (legends)
-legend {
-  display: block;
-  width: 100%;
-  padding: 0;
-  margin-bottom: @baseLineHeight;
-  font-size: @baseFontSize * 1.5;
-  line-height: @baseLineHeight * 2;
-  color: @grayDark;
-  border: 0;
-  border-bottom: 1px solid #e5e5e5;
-
-  // Small
-  small {
-    font-size: @baseLineHeight * .75;
-    color: @grayLight;
-  }
-}
-
-// Set font for forms
-label,
-input,
-button,
-select,
-textarea {
-  #font > .shorthand(@baseFontSize,normal,@baseLineHeight); // Set size, weight, line-height here
-}
-input,
-button,
-select,
-textarea {
-  font-family: @baseFontFamily; // And only set font-family here for those that need it (note the missing label element)
-}
-
-// Identify controls by their labels
-label {
-  display: block;
-  margin-bottom: 5px;
-}
-
-// Form controls
-// -------------------------
-
-// Shared size and type resets
-select,
-textarea,
-input[type="text"],
-input[type="password"],
-input[type="datetime"],
-input[type="datetime-local"],
-input[type="date"],
-input[type="month"],
-input[type="time"],
-input[type="week"],
-input[type="number"],
-input[type="email"],
-input[type="url"],
-input[type="search"],
-input[type="tel"],
-input[type="color"],
-.uneditable-input {
-  display: inline-block;
-  height: @baseLineHeight;
-  padding: 4px 6px;
-  margin-bottom: @baseLineHeight / 2;
-  font-size: @baseFontSize;
-  line-height: @baseLineHeight;
-  color: @gray;
-  .border-radius(@inputBorderRadius);
-  vertical-align: middle;
-}
-
-// Reset appearance properties for textual inputs and textarea
-// Declare width for legacy (can't be on input[type=*] selectors or it's too specific)
-input,
-textarea,
-.uneditable-input {
-  width: 206px; // plus 12px padding and 2px border
-}
-// Reset height since textareas have rows
-textarea {
-  height: auto;
-}
-// Everything else
-textarea,
-input[type="text"],
-input[type="password"],
-input[type="datetime"],
-input[type="datetime-local"],
-input[type="date"],
-input[type="month"],
-input[type="time"],
-input[type="week"],
-input[type="number"],
-input[type="email"],
-input[type="url"],
-input[type="search"],
-input[type="tel"],
-input[type="color"],
-.uneditable-input {
-  background-color: @inputBackground;
-  border: 1px solid @inputBorder;
-  .box-shadow(inset 0 1px 1px rgba(0,0,0,.075));
-  .transition(~"border linear .2s, box-shadow linear .2s");
-
-  // Focus state
-  &:focus {
-    border-color: rgba(82,168,236,.8);
-    outline: 0;
-    outline: thin dotted \9; /* IE6-9 */
-    .box-shadow(~"inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6)");
-  }
-}
-
-// Position radios and checkboxes better
-input[type="radio"],
-input[type="checkbox"] {
-  margin: 4px 0 0;
-  *margin-top: 0; /* IE7 */
-  margin-top: 1px \9; /* IE8-9 */
-  line-height: normal;
-}
-
-// Reset width of input images, buttons, radios, checkboxes
-input[type="file"],
-input[type="image"],
-input[type="submit"],
-input[type="reset"],
-input[type="button"],
-input[type="radio"],
-input[type="checkbox"] {
-  width: auto; // Override of generic input selector
-}
-
-// Set the height of select and file controls to match text inputs
-select,
-input[type="file"] {
-  height: @inputHeight; /* In IE7, the height of the select element cannot be changed by height, only font-size */
-  *margin-top: 4px; /* For IE7, add top margin to align select with labels */
-  line-height: @inputHeight;
-}
-
-// Make select elements obey height by applying a border
-select {
-  width: 220px; // default input width + 10px of padding that doesn't get applied
-  border: 1px solid @inputBorder;
-  background-color: @inputBackground; // Chrome on Linux and Mobile Safari need background-color
-}
-
-// Make multiple select elements height not fixed
-select[multiple],
-select[size] {
-  height: auto;
-}
-
-// Focus for select, file, radio, and checkbox
-select:focus,
-input[type="file"]:focus,
-input[type="radio"]:focus,
-input[type="checkbox"]:focus {
-  .tab-focus();
-}
-
-
-// Uneditable inputs
-// -------------------------
-
-// Make uneditable inputs look inactive
-.uneditable-input,
-.uneditable-textarea {
-  color: @grayLight;
-  background-color: darken(@inputBackground, 1%);
-  border-color: @inputBorder;
-  .box-shadow(inset 0 1px 2px rgba(0,0,0,.025));
-  cursor: not-allowed;
-}
-
-// For text that needs to appear as an input but should not be an input
-.uneditable-input {
-  overflow: hidden; // prevent text from wrapping, but still cut it off like an input does
-  white-space: nowrap;
-}
-
-// Make uneditable textareas behave like a textarea
-.uneditable-textarea {
-  width: auto;
-  height: auto;
-}
-
-
-// Placeholder
-// -------------------------
-
-// Placeholder text gets special styles because when browsers invalidate entire lines if it doesn't understand a selector
-input,
-textarea {
-  .placeholder();
-}
-
-
-// CHECKBOXES & RADIOS
-// -------------------
-
-// Indent the labels to position radios/checkboxes as hanging
-.radio,
-.checkbox {
-  min-height: @baseLineHeight; // clear the floating input if there is no label text
-  padding-left: 20px;
-}
-.radio input[type="radio"],
-.checkbox input[type="checkbox"] {
-  float: left;
-  margin-left: -20px;
-}
-
-// Move the options list down to align with labels
-.controls > .radio:first-child,
-.controls > .checkbox:first-child {
-  padding-top: 5px; // has to be padding because margin collaspes
-}
-
-// Radios and checkboxes on same line
-// TODO v3: Convert .inline to .control-inline
-.radio.inline,
-.checkbox.inline {
-  display: inline-block;
-  padding-top: 5px;
-  margin-bottom: 0;
-  vertical-align: middle;
-}
-.radio.inline + .radio.inline,
-.checkbox.inline + .checkbox.inline {
-  margin-left: 10px; // space out consecutive inline controls
-}
-
-
-
-// INPUT SIZES
-// -----------
-
-// General classes for quick sizes
-.input-mini       { width: 60px; }
-.input-small      { width: 90px; }
-.input-medium     { width: 150px; }
-.input-large      { width: 210px; }
-.input-xlarge     { width: 270px; }
-.input-xxlarge    { width: 530px; }
-
-// Grid style input sizes
-input[class*="span"],
-select[class*="span"],
-textarea[class*="span"],
-.uneditable-input[class*="span"],
-// Redeclare since the fluid row class is more specific
-.row-fluid input[class*="span"],
-.row-fluid select[class*="span"],
-.row-fluid textarea[class*="span"],
-.row-fluid .uneditable-input[class*="span"] {
-  float: none;
-  margin-left: 0;
-}
-// Ensure input-prepend/append never wraps
-.input-append input[class*="span"],
-.input-append .uneditable-input[class*="span"],
-.input-prepend input[class*="span"],
-.input-prepend .uneditable-input[class*="span"],
-.row-fluid input[class*="span"],
-.row-fluid select[class*="span"],
-.row-fluid textarea[class*="span"],
-.row-fluid .uneditable-input[class*="span"],
-.row-fluid .input-prepend [class*="span"],
-.row-fluid .input-append [class*="span"] {
-  display: inline-block;
-}
-
-
-
-// GRID SIZING FOR INPUTS
-// ----------------------
-
-// Grid sizes
-#grid > .input(@gridColumnWidth, @gridGutterWidth);
-
-// Control row for multiple inputs per line
-.controls-row {
-  .clearfix(); // Clear the float from controls
-}
-
-// Float to collapse white-space for proper grid alignment
-.controls-row [class*="span"],
-// Redeclare the fluid grid collapse since we undo the float for inputs
-.row-fluid .controls-row [class*="span"] {
-  float: left;
-}
-// Explicity set top padding on all checkboxes/radios, not just first-child
-.controls-row .checkbox[class*="span"],
-.controls-row .radio[class*="span"] {
-  padding-top: 5px;
-}
-
-
-
-
-// DISABLED STATE
-// --------------
-
-// Disabled and read-only inputs
-input[disabled],
-select[disabled],
-textarea[disabled],
-input[readonly],
-select[readonly],
-textarea[readonly] {
-  cursor: not-allowed;
-  background-color: @inputDisabledBackground;
-}
-// Explicitly reset the colors here
-input[type="radio"][disabled],
-input[type="checkbox"][disabled],
-input[type="radio"][readonly],
-input[type="checkbox"][readonly] {
-  background-color: transparent;
-}
-
-
-
-
-// FORM FIELD FEEDBACK STATES
-// --------------------------
-
-// Warning
-.control-group.warning {
-  .formFieldState(@warningText, @warningText, @warningBackground);
-}
-// Error
-.control-group.error {
-  .formFieldState(@errorText, @errorText, @errorBackground);
-}
-// Success
-.control-group.success {
-  .formFieldState(@successText, @successText, @successBackground);
-}
-// Success
-.control-group.info {
-  .formFieldState(@infoText, @infoText, @infoBackground);
-}
-
-// HTML5 invalid states
-// Shares styles with the .control-group.error above
-input:focus:invalid,
-textarea:focus:invalid,
-select:focus:invalid {
-  color: #b94a48;
-  border-color: #ee5f5b;
-  &:focus {
-    border-color: darken(#ee5f5b, 10%);
-    @shadow: 0 0 6px lighten(#ee5f5b, 20%);
-    .box-shadow(@shadow);
-  }
-}
-
-
-
-// FORM ACTIONS
-// ------------
-
-.form-actions {
-  padding: (@baseLineHeight - 1) 20px @baseLineHeight;
-  margin-top: @baseLineHeight;
-  margin-bottom: @baseLineHeight;
-  background-color: @formActionsBackground;
-  border-top: 1px solid #e5e5e5;
-  .clearfix(); // Adding clearfix to allow for .pull-right button containers
-}
-
-
-
-// HELP TEXT
-// ---------
-
-.help-block,
-.help-inline {
-  color: lighten(@textColor, 15%); // lighten the text some for contrast
-}
-
-.help-block {
-  display: block; // account for any element using help-block
-  margin-bottom: @baseLineHeight / 2;
-}
-
-.help-inline {
-  display: inline-block;
-  .ie7-inline-block();
-  vertical-align: middle;
-  padding-left: 5px;
-}
-
-
-
-// INPUT GROUPS
-// ------------
-
-// Allow us to put symbols and text within the input field for a cleaner look
-.input-append,
-.input-prepend {
-  display: inline-block;
-  margin-bottom: @baseLineHeight / 2;
-  vertical-align: middle;
-  font-size: 0; // white space collapse hack
-  white-space: nowrap; // Prevent span and input from separating
-
-  // Reset the white space collapse hack
-  input,
-  select,
-  .uneditable-input,
-  .dropdown-menu,
-  .popover {
-    font-size: @baseFontSize;
-  }
-
-  input,
-  select,
-  .uneditable-input {
-    position: relative; // placed here by default so that on :focus we can place the input above the .add-on for full border and box-shadow goodness
-    margin-bottom: 0; // prevent bottom margin from screwing up alignment in stacked forms
-    *margin-left: 0;
-    vertical-align: top;
-    .border-radius(0 @inputBorderRadius @inputBorderRadius 0);
-    // Make input on top when focused so blue border and shadow always show
-    &:focus {
-      z-index: 2;
-    }
-  }
-  .add-on {
-    display: inline-block;
-    width: auto;
-    height: @baseLineHeight;
-    min-width: 16px;
-    padding: 4px 5px;
-    font-size: @baseFontSize;
-    font-weight: normal;
-    line-height: @baseLineHeight;
-    text-align: center;
-    text-shadow: 0 1px 0 @white;
-    background-color: @grayLighter;
-    border: 1px solid #ccc;
-  }
-  .add-on,
-  .btn,
-  .btn-group > .dropdown-toggle {
-    vertical-align: top;
-    .border-radius(0);
-  }
-  .active {
-    background-color: lighten(@green, 30);
-    border-color: @green;
-  }
-}
-
-.input-prepend {
-  .add-on,
-  .btn {
-    margin-right: -1px;
-  }
-  .add-on:first-child,
-  .btn:first-child {
-    // FYI, `.btn:first-child` accounts for a button group that's prepended
-    .border-radius(@inputBorderRadius 0 0 @inputBorderRadius);
-  }
-}
-
-.input-append {
-  input,
-  select,
-  .uneditable-input {
-    .border-radius(@inputBorderRadius 0 0 @inputBorderRadius);
-    + .btn-group .btn:last-child {
-      .border-radius(0 @inputBorderRadius @inputBorderRadius 0);
-    }
-  }
-  .add-on,
-  .btn,
-  .btn-group {
-    margin-left: -1px;
-  }
-  .add-on:last-child,
-  .btn:last-child,
-  .btn-group:last-child > .dropdown-toggle {
-    .border-radius(0 @inputBorderRadius @inputBorderRadius 0);
-  }
-}
-
-// Remove all border-radius for inputs with both prepend and append
-.input-prepend.input-append {
-  input,
-  select,
-  .uneditable-input {
-    .border-radius(0);
-    + .btn-group .btn {
-      .border-radius(0 @inputBorderRadius @inputBorderRadius 0);
-    }
-  }
-  .add-on:first-child,
-  .btn:first-child {
-    margin-right: -1px;
-    .border-radius(@inputBorderRadius 0 0 @inputBorderRadius);
-  }
-  .add-on:last-child,
-  .btn:last-child {
-    margin-left: -1px;
-    .border-radius(0 @inputBorderRadius @inputBorderRadius 0);
-  }
-  .btn-group:first-child {
-    margin-left: 0;
-  }
-}
-
-
-
-
-// SEARCH FORM
-// -----------
-
-input.search-query {
-  padding-right: 14px;
-  padding-right: 4px \9;
-  padding-left: 14px;
-  padding-left: 4px \9; /* IE7-8 doesn't have border-radius, so don't indent the padding */
-  margin-bottom: 0; // Remove the default margin on all inputs
-  .border-radius(15px);
-}
-
-/* Allow for input prepend/append in search forms */
-.form-search .input-append .search-query,
-.form-search .input-prepend .search-query {
-  .border-radius(0); // Override due to specificity
-}
-.form-search .input-append .search-query {
-  .border-radius(14px 0 0 14px);
-}
-.form-search .input-append .btn {
-  .border-radius(0 14px 14px 0);
-}
-.form-search .input-prepend .search-query {
-  .border-radius(0 14px 14px 0);
-}
-.form-search .input-prepend .btn {
-  .border-radius(14px 0 0 14px);
-}
-
-
-
-
-// HORIZONTAL & VERTICAL FORMS
-// ---------------------------
-
-// Common properties
-// -----------------
-
-.form-search,
-.form-inline,
-.form-horizontal {
-  input,
-  textarea,
-  select,
-  .help-inline,
-  .uneditable-input,
-  .input-prepend,
-  .input-append {
-    display: inline-block;
-    .ie7-inline-block();
-    margin-bottom: 0;
-    vertical-align: middle;
-  }
-  // Re-hide hidden elements due to specifity
-  .hide {
-    display: none;
-  }
-}
-.form-search label,
-.form-inline label,
-.form-search .btn-group,
-.form-inline .btn-group {
-  display: inline-block;
-}
-// Remove margin for input-prepend/-append
-.form-search .input-append,
-.form-inline .input-append,
-.form-search .input-prepend,
-.form-inline .input-prepend {
-  margin-bottom: 0;
-}
-// Inline checkbox/radio labels (remove padding on left)
-.form-search .radio,
-.form-search .checkbox,
-.form-inline .radio,
-.form-inline .checkbox {
-  padding-left: 0;
-  margin-bottom: 0;
-  vertical-align: middle;
-}
-// Remove float and margin, set to inline-block
-.form-search .radio input[type="radio"],
-.form-search .checkbox input[type="checkbox"],
-.form-inline .radio input[type="radio"],
-.form-inline .checkbox input[type="checkbox"] {
-  float: left;
-  margin-right: 3px;
-  margin-left: 0;
-}
-
-
-// Margin to space out fieldsets
-.control-group {
-  margin-bottom: @baseLineHeight / 2;
-}
-
-// Legend collapses margin, so next element is responsible for spacing
-legend + .control-group {
-  margin-top: @baseLineHeight;
-  -webkit-margin-top-collapse: separate;
-}
-
-// Horizontal-specific styles
-// --------------------------
-
-.form-horizontal {
-  // Increase spacing between groups
-  .control-group {
-    margin-bottom: @baseLineHeight;
-    .clearfix();
-  }
-  // Float the labels left
-  .control-label {
-    float: left;
-    width: @horizontalComponentOffset - 20;
-    padding-top: 5px;
-    text-align: right;
-  }
-  // Move over all input controls and content
-  .controls {
-    // Super jank IE7 fix to ensure the inputs in .input-append and input-prepend
-    // don't inherit the margin of the parent, in this case .controls
-    *display: inline-block;
-    *padding-left: 20px;
-    margin-left: @horizontalComponentOffset;
-    *margin-left: 0;
-    &:first-child {
-      *padding-left: @horizontalComponentOffset;
-    }
-  }
-  // Remove bottom margin on block level help text since that's accounted for on .control-group
-  .help-block {
-    margin-bottom: 0;
-  }
-  // And apply it only to .help-block instances that follow a form control
-  input,
-  select,
-  textarea,
-  .uneditable-input,
-  .input-prepend,
-  .input-append {
-    + .help-block {
-      margin-top: @baseLineHeight / 2;
-    }
-  }
-  // Move over buttons in .form-actions to align with .controls
-  .form-actions {
-    padding-left: @horizontalComponentOffset;
-  }
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/grid.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/grid.less b/apps/fauxton/assets/less/bootstrap/grid.less
deleted file mode 100644
index 750d203..0000000
--- a/apps/fauxton/assets/less/bootstrap/grid.less
+++ /dev/null
@@ -1,21 +0,0 @@
-//
-// Grid system
-// --------------------------------------------------
-
-
-// Fixed (940px)
-#grid > .core(@gridColumnWidth, @gridGutterWidth);
-
-// Fluid (940px)
-#grid > .fluid(@fluidGridColumnWidth, @fluidGridGutterWidth);
-
-// Reset utility classes due to specificity
-[class*="span"].hide,
-.row-fluid [class*="span"].hide {
-  display: none;
-}
-
-[class*="span"].pull-right,
-.row-fluid [class*="span"].pull-right {
-  float: right;
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/hero-unit.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/hero-unit.less b/apps/fauxton/assets/less/bootstrap/hero-unit.less
deleted file mode 100644
index 763d86a..0000000
--- a/apps/fauxton/assets/less/bootstrap/hero-unit.less
+++ /dev/null
@@ -1,25 +0,0 @@
-//
-// Hero unit
-// --------------------------------------------------
-
-
-.hero-unit {
-  padding: 60px;
-  margin-bottom: 30px;
-  font-size: 18px;
-  font-weight: 200;
-  line-height: @baseLineHeight * 1.5;
-  color: @heroUnitLeadColor;
-  background-color: @heroUnitBackground;
-  .border-radius(6px);
-  h1 {
-    margin-bottom: 0;
-    font-size: 60px;
-    line-height: 1;
-    color: @heroUnitHeadingColor;
-    letter-spacing: -1px;
-  }
-  li {
-    line-height: @baseLineHeight * 1.5; // Reset since we specify in type.less
-  }
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/labels-badges.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/labels-badges.less b/apps/fauxton/assets/less/bootstrap/labels-badges.less
deleted file mode 100644
index bc321fe..0000000
--- a/apps/fauxton/assets/less/bootstrap/labels-badges.less
+++ /dev/null
@@ -1,84 +0,0 @@
-//
-// Labels and badges
-// --------------------------------------------------
-
-
-// Base classes
-.label,
-.badge {
-  display: inline-block;
-  padding: 2px 4px;
-  font-size: @baseFontSize * .846;
-  font-weight: bold;
-  line-height: 14px; // ensure proper line-height if floated
-  color: @white;
-  vertical-align: baseline;
-  white-space: nowrap;
-  text-shadow: 0 -1px 0 rgba(0,0,0,.25);
-  background-color: @grayLight;
-}
-// Set unique padding and border-radii
-.label {
-  .border-radius(3px);
-}
-.badge {
-  padding-left: 9px;
-  padding-right: 9px;
-  .border-radius(9px);
-}
-
-// Empty labels/badges collapse
-.label,
-.badge {
-  &:empty {
-    display: none;
-  }
-}
-
-// Hover/focus state, but only for links
-a {
-  &.label:hover,
-  &.label:focus,
-  &.badge:hover,
-  &.badge:focus {
-    color: @white;
-    text-decoration: none;
-    cursor: pointer;
-  }
-}
-
-// Colors
-// Only give background-color difference to links (and to simplify, we don't qualifty with `a` but [href] attribute)
-.label,
-.badge {
-  // Important (red)
-  &-important         { background-color: @errorText; }
-  &-important[href]   { background-color: darken(@errorText, 10%); }
-  // Warnings (orange)
-  &-warning           { background-color: @orange; }
-  &-warning[href]     { background-color: darken(@orange, 10%); }
-  // Success (green)
-  &-success           { background-color: @successText; }
-  &-success[href]     { background-color: darken(@successText, 10%); }
-  // Info (turquoise)
-  &-info              { background-color: @infoText; }
-  &-info[href]        { background-color: darken(@infoText, 10%); }
-  // Inverse (black)
-  &-inverse           { background-color: @grayDark; }
-  &-inverse[href]     { background-color: darken(@grayDark, 10%); }
-}
-
-// Quick fix for labels/badges in buttons
-.btn {
-  .label,
-  .badge {
-    position: relative;
-    top: -1px;
-  }
-}
-.btn-mini {
-  .label,
-  .badge {
-    top: 0;
-  }
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/layouts.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/layouts.less b/apps/fauxton/assets/less/bootstrap/layouts.less
deleted file mode 100644
index 24a2062..0000000
--- a/apps/fauxton/assets/less/bootstrap/layouts.less
+++ /dev/null
@@ -1,16 +0,0 @@
-//
-// Layouts
-// --------------------------------------------------
-
-
-// Container (centered, fixed-width layouts)
-.container {
-  .container-fixed();
-}
-
-// Fluid layouts (left aligned, with sidebar, min- & max-width content)
-.container-fluid {
-  padding-right: @gridGutterWidth;
-  padding-left: @gridGutterWidth;
-  .clearfix();
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/media.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/media.less b/apps/fauxton/assets/less/bootstrap/media.less
deleted file mode 100644
index e461e44..0000000
--- a/apps/fauxton/assets/less/bootstrap/media.less
+++ /dev/null
@@ -1,55 +0,0 @@
-// Media objects
-// Source: http://stubbornella.org/content/?p=497
-// --------------------------------------------------
-
-
-// Common styles
-// -------------------------
-
-// Clear the floats
-.media,
-.media-body {
-  overflow: hidden;
-  *overflow: visible;
-  zoom: 1;
-}
-
-// Proper spacing between instances of .media
-.media,
-.media .media {
-  margin-top: 15px;
-}
-.media:first-child {
-  margin-top: 0;
-}
-
-// For images and videos, set to block
-.media-object {
-  display: block;
-}
-
-// Reset margins on headings for tighter default spacing
-.media-heading {
-  margin: 0 0 5px;
-}
-
-
-// Media image alignment
-// -------------------------
-
-.media > .pull-left {
-  margin-right: 10px;
-}
-.media > .pull-right {
-  margin-left: 10px;
-}
-
-
-// Media list variation
-// -------------------------
-
-// Undo default ul/ol styles
-.media-list {
-  margin-left: 0;
-  list-style: none;
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/mixins.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/mixins.less b/apps/fauxton/assets/less/bootstrap/mixins.less
deleted file mode 100644
index 92034a0..0000000
--- a/apps/fauxton/assets/less/bootstrap/mixins.less
+++ /dev/null
@@ -1,716 +0,0 @@
-//
-// Mixins
-// --------------------------------------------------
-
-
-// UTILITY MIXINS
-// --------------------------------------------------
-
-// Clearfix
-// --------
-// For clearing floats like a boss h5bp.com/q
-.clearfix {
-  *zoom: 1;
-  &:before,
-  &:after {
-    display: table;
-    content: "";
-    // Fixes Opera/contenteditable bug:
-    // http://nicolasgallagher.com/micro-clearfix-hack/#comment-36952
-    line-height: 0;
-  }
-  &:after {
-    clear: both;
-  }
-}
-
-// Webkit-style focus
-// ------------------
-.tab-focus() {
-  // Default
-  outline: thin dotted #333;
-  // Webkit
-  outline: 5px auto -webkit-focus-ring-color;
-  outline-offset: -2px;
-}
-
-// Center-align a block level element
-// ----------------------------------
-.center-block() {
-  display: block;
-  margin-left: auto;
-  margin-right: auto;
-}
-
-// IE7 inline-block
-// ----------------
-.ie7-inline-block() {
-  *display: inline; /* IE7 inline-block hack */
-  *zoom: 1;
-}
-
-// IE7 likes to collapse whitespace on either side of the inline-block elements.
-// Ems because we're attempting to match the width of a space character. Left
-// version is for form buttons, which typically come after other elements, and
-// right version is for icons, which come before. Applying both is ok, but it will
-// mean that space between those elements will be .6em (~2 space characters) in IE7,
-// instead of the 1 space in other browsers.
-.ie7-restore-left-whitespace() {
-  *margin-left: .3em;
-
-  &:first-child {
-    *margin-left: 0;
-  }
-}
-
-.ie7-restore-right-whitespace() {
-  *margin-right: .3em;
-}
-
-// Sizing shortcuts
-// -------------------------
-.size(@height, @width) {
-  width: @width;
-  height: @height;
-}
-.square(@size) {
-  .size(@size, @size);
-}
-
-// Placeholder text
-// -------------------------
-.placeholder(@color: @placeholderText) {
-  &:-moz-placeholder {
-    color: @color;
-  }
-  &:-ms-input-placeholder {
-    color: @color;
-  }
-  &::-webkit-input-placeholder {
-    color: @color;
-  }
-}
-
-// Text overflow
-// -------------------------
-// Requires inline-block or block for proper styling
-.text-overflow() {
-  overflow: hidden;
-  text-overflow: ellipsis;
-  white-space: nowrap;
-}
-
-// CSS image replacement
-// -------------------------
-// Source: https://github.com/h5bp/html5-boilerplate/commit/aa0396eae757
-.hide-text {
-  font: 0/0 a;
-  color: transparent;
-  text-shadow: none;
-  background-color: transparent;
-  border: 0;
-}
-
-
-// FONTS
-// --------------------------------------------------
-
-#font {
-  #family {
-    .serif() {
-      font-family: @serifFontFamily;
-    }
-    .sans-serif() {
-      font-family: @sansFontFamily;
-    }
-    .monospace() {
-      font-family: @monoFontFamily;
-    }
-  }
-  .shorthand(@size: @baseFontSize, @weight: normal, @lineHeight: @baseLineHeight) {
-    font-size: @size;
-    font-weight: @weight;
-    line-height: @lineHeight;
-  }
-  .serif(@size: @baseFontSize, @weight: normal, @lineHeight: @baseLineHeight) {
-    #font > #family > .serif;
-    #font > .shorthand(@size, @weight, @lineHeight);
-  }
-  .sans-serif(@size: @baseFontSize, @weight: normal, @lineHeight: @baseLineHeight) {
-    #font > #family > .sans-serif;
-    #font > .shorthand(@size, @weight, @lineHeight);
-  }
-  .monospace(@size: @baseFontSize, @weight: normal, @lineHeight: @baseLineHeight) {
-    #font > #family > .monospace;
-    #font > .shorthand(@size, @weight, @lineHeight);
-  }
-}
-
-
-// FORMS
-// --------------------------------------------------
-
-// Block level inputs
-.input-block-level {
-  display: block;
-  width: 100%;
-  min-height: @inputHeight; // Make inputs at least the height of their button counterpart (base line-height + padding + border)
-  .box-sizing(border-box); // Makes inputs behave like true block-level elements
-}
-
-
-
-// Mixin for form field states
-.formFieldState(@textColor: #555, @borderColor: #ccc, @backgroundColor: #f5f5f5) {
-  // Set the text color
-  .control-label,
-  .help-block,
-  .help-inline {
-    color: @textColor;
-  }
-  // Style inputs accordingly
-  .checkbox,
-  .radio,
-  input,
-  select,
-  textarea {
-    color: @textColor;
-  }
-  input,
-  select,
-  textarea {
-    border-color: @borderColor;
-    .box-shadow(inset 0 1px 1px rgba(0,0,0,.075)); // Redeclare so transitions work
-    &:focus {
-      border-color: darken(@borderColor, 10%);
-      @shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 6px lighten(@borderColor, 20%);
-      .box-shadow(@shadow);
-    }
-  }
-  // Give a small background color for input-prepend/-append
-  .input-prepend .add-on,
-  .input-append .add-on {
-    color: @textColor;
-    background-color: @backgroundColor;
-    border-color: @textColor;
-  }
-}
-
-
-
-// CSS3 PROPERTIES
-// --------------------------------------------------
-
-// Border Radius
-.border-radius(@radius) {
-  -webkit-border-radius: @radius;
-     -moz-border-radius: @radius;
-          border-radius: @radius;
-}
-
-// Single Corner Border Radius
-.border-top-left-radius(@radius) {
-  -webkit-border-top-left-radius: @radius;
-      -moz-border-radius-topleft: @radius;
-          border-top-left-radius: @radius;
-}
-.border-top-right-radius(@radius) {
-  -webkit-border-top-right-radius: @radius;
-      -moz-border-radius-topright: @radius;
-          border-top-right-radius: @radius;
-}
-.border-bottom-right-radius(@radius) {
-  -webkit-border-bottom-right-radius: @radius;
-      -moz-border-radius-bottomright: @radius;
-          border-bottom-right-radius: @radius;
-}
-.border-bottom-left-radius(@radius) {
-  -webkit-border-bottom-left-radius: @radius;
-      -moz-border-radius-bottomleft: @radius;
-          border-bottom-left-radius: @radius;
-}
-
-// Single Side Border Radius
-.border-top-radius(@radius) {
-  .border-top-right-radius(@radius);
-  .border-top-left-radius(@radius);
-}
-.border-right-radius(@radius) {
-  .border-top-right-radius(@radius);
-  .border-bottom-right-radius(@radius);
-}
-.border-bottom-radius(@radius) {
-  .border-bottom-right-radius(@radius);
-  .border-bottom-left-radius(@radius);
-}
-.border-left-radius(@radius) {
-  .border-top-left-radius(@radius);
-  .border-bottom-left-radius(@radius);
-}
-
-// Drop shadows
-.box-shadow(@shadow) {
-  -webkit-box-shadow: @shadow;
-     -moz-box-shadow: @shadow;
-          box-shadow: @shadow;
-}
-
-// Transitions
-.transition(@transition) {
-  -webkit-transition: @transition;
-     -moz-transition: @transition;
-       -o-transition: @transition;
-          transition: @transition;
-}
-.transition-delay(@transition-delay) {
-  -webkit-transition-delay: @transition-delay;
-     -moz-transition-delay: @transition-delay;
-       -o-transition-delay: @transition-delay;
-          transition-delay: @transition-delay;
-}
-.transition-duration(@transition-duration) {
-  -webkit-transition-duration: @transition-duration;
-     -moz-transition-duration: @transition-duration;
-       -o-transition-duration: @transition-duration;
-          transition-duration: @transition-duration;
-}
-
-// Transformations
-.rotate(@degrees) {
-  -webkit-transform: rotate(@degrees);
-     -moz-transform: rotate(@degrees);
-      -ms-transform: rotate(@degrees);
-       -o-transform: rotate(@degrees);
-          transform: rotate(@degrees);
-}
-.scale(@ratio) {
-  -webkit-transform: scale(@ratio);
-     -moz-transform: scale(@ratio);
-      -ms-transform: scale(@ratio);
-       -o-transform: scale(@ratio);
-          transform: scale(@ratio);
-}
-.translate(@x, @y) {
-  -webkit-transform: translate(@x, @y);
-     -moz-transform: translate(@x, @y);
-      -ms-transform: translate(@x, @y);
-       -o-transform: translate(@x, @y);
-          transform: translate(@x, @y);
-}
-.skew(@x, @y) {
-  -webkit-transform: skew(@x, @y);
-     -moz-transform: skew(@x, @y);
-      -ms-transform: skewX(@x) skewY(@y); // See https://github.com/twitter/bootstrap/issues/4885
-       -o-transform: skew(@x, @y);
-          transform: skew(@x, @y);
-  -webkit-backface-visibility: hidden; // See https://github.com/twitter/bootstrap/issues/5319
-}
-.translate3d(@x, @y, @z) {
-  -webkit-transform: translate3d(@x, @y, @z);
-     -moz-transform: translate3d(@x, @y, @z);
-       -o-transform: translate3d(@x, @y, @z);
-          transform: translate3d(@x, @y, @z);
-}
-
-// Backface visibility
-// Prevent browsers from flickering when using CSS 3D transforms.
-// Default value is `visible`, but can be changed to `hidden
-// See git pull https://github.com/dannykeane/bootstrap.git backface-visibility for examples
-.backface-visibility(@visibility){
-	-webkit-backface-visibility: @visibility;
-	   -moz-backface-visibility: @visibility;
-	        backface-visibility: @visibility;
-}
-
-// Background clipping
-// Heads up: FF 3.6 and under need "padding" instead of "padding-box"
-.background-clip(@clip) {
-  -webkit-background-clip: @clip;
-     -moz-background-clip: @clip;
-          background-clip: @clip;
-}
-
-// Background sizing
-.background-size(@size) {
-  -webkit-background-size: @size;
-     -moz-background-size: @size;
-       -o-background-size: @size;
-          background-size: @size;
-}
-
-
-// Box sizing
-.box-sizing(@boxmodel) {
-  -webkit-box-sizing: @boxmodel;
-     -moz-box-sizing: @boxmodel;
-          box-sizing: @boxmodel;
-}
-
-// User select
-// For selecting text on the page
-.user-select(@select) {
-  -webkit-user-select: @select;
-     -moz-user-select: @select;
-      -ms-user-select: @select;
-       -o-user-select: @select;
-          user-select: @select;
-}
-
-// Resize anything
-.resizable(@direction) {
-  resize: @direction; // Options: horizontal, vertical, both
-  overflow: auto; // Safari fix
-}
-
-// CSS3 Content Columns
-.content-columns(@columnCount, @columnGap: @gridGutterWidth) {
-  -webkit-column-count: @columnCount;
-     -moz-column-count: @columnCount;
-          column-count: @columnCount;
-  -webkit-column-gap: @columnGap;
-     -moz-column-gap: @columnGap;
-          column-gap: @columnGap;
-}
-
-// Optional hyphenation
-.hyphens(@mode: auto) {
-  word-wrap: break-word;
-  -webkit-hyphens: @mode;
-     -moz-hyphens: @mode;
-      -ms-hyphens: @mode;
-       -o-hyphens: @mode;
-          hyphens: @mode;
-}
-
-// Opacity
-.opacity(@opacity) {
-  opacity: @opacity / 100;
-  filter: ~"alpha(opacity=@{opacity})";
-}
-
-
-
-// BACKGROUNDS
-// --------------------------------------------------
-
-// Add an alphatransparency value to any background or border color (via Elyse Holladay)
-#translucent {
-  .background(@color: @white, @alpha: 1) {
-    background-color: hsla(hue(@color), saturation(@color), lightness(@color), @alpha);
-  }
-  .border(@color: @white, @alpha: 1) {
-    border-color: hsla(hue(@color), saturation(@color), lightness(@color), @alpha);
-    .background-clip(padding-box);
-  }
-}
-
-// Gradient Bar Colors for buttons and alerts
-.gradientBar(@primaryColor, @secondaryColor, @textColor: #fff, @textShadow: 0 -1px 0 rgba(0,0,0,.25)) {
-  color: @textColor;
-  text-shadow: @textShadow;
-  #gradient > .vertical(@primaryColor, @secondaryColor);
-  border-color: @secondaryColor @secondaryColor darken(@secondaryColor, 15%);
-  border-color: rgba(0,0,0,.1) rgba(0,0,0,.1) fadein(rgba(0,0,0,.1), 15%);
-}
-
-// Gradients
-#gradient {
-  .horizontal(@startColor: #555, @endColor: #333) {
-    background-color: @endColor;
-    background-image: -moz-linear-gradient(left, @startColor, @endColor); // FF 3.6+
-    background-image: -webkit-gradient(linear, 0 0, 100% 0, from(@startColor), to(@endColor)); // Safari 4+, Chrome 2+
-    background-image: -webkit-linear-gradient(left, @startColor, @endColor); // Safari 5.1+, Chrome 10+
-    background-image: -o-linear-gradient(left, @startColor, @endColor); // Opera 11.10
-    background-image: linear-gradient(to right, @startColor, @endColor); // Standard, IE10
-    background-repeat: repeat-x;
-    filter: e(%("progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d', GradientType=1)",argb(@startColor),argb(@endColor))); // IE9 and down
-  }
-  .vertical(@startColor: #555, @endColor: #333) {
-    background-color: mix(@startColor, @endColor, 60%);
-    background-image: -moz-linear-gradient(top, @startColor, @endColor); // FF 3.6+
-    background-image: -webkit-gradient(linear, 0 0, 0 100%, from(@startColor), to(@endColor)); // Safari 4+, Chrome 2+
-    background-image: -webkit-linear-gradient(top, @startColor, @endColor); // Safari 5.1+, Chrome 10+
-    background-image: -o-linear-gradient(top, @startColor, @endColor); // Opera 11.10
-    background-image: linear-gradient(to bottom, @startColor, @endColor); // Standard, IE10
-    background-repeat: repeat-x;
-    filter: e(%("progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d', GradientType=0)",argb(@startColor),argb(@endColor))); // IE9 and down
-  }
-  .directional(@startColor: #555, @endColor: #333, @deg: 45deg) {
-    background-color: @endColor;
-    background-repeat: repeat-x;
-    background-image: -moz-linear-gradient(@deg, @startColor, @endColor); // FF 3.6+
-    background-image: -webkit-linear-gradient(@deg, @startColor, @endColor); // Safari 5.1+, Chrome 10+
-    background-image: -o-linear-gradient(@deg, @startColor, @endColor); // Opera 11.10
-    background-image: linear-gradient(@deg, @startColor, @endColor); // Standard, IE10
-  }
-  .horizontal-three-colors(@startColor: #00b3ee, @midColor: #7a43b6, @colorStop: 50%, @endColor: #c3325f) {
-    background-color: mix(@midColor, @endColor, 80%);
-    background-image: -webkit-gradient(left, linear, 0 0, 0 100%, from(@startColor), color-stop(@colorStop, @midColor), to(@endColor));
-    background-image: -webkit-linear-gradient(left, @startColor, @midColor @colorStop, @endColor);
-    background-image: -moz-linear-gradient(left, @startColor, @midColor @colorStop, @endColor);
-    background-image: -o-linear-gradient(left, @startColor, @midColor @colorStop, @endColor);
-    background-image: linear-gradient(to right, @startColor, @midColor @colorStop, @endColor);
-    background-repeat: no-repeat;
-    filter: e(%("progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d', GradientType=0)",argb(@startColor),argb(@endColor))); // IE9 and down, gets no color-stop at all for proper fallback
-  }
-
-  .vertical-three-colors(@startColor: #00b3ee, @midColor: #7a43b6, @colorStop: 50%, @endColor: #c3325f) {
-    background-color: mix(@midColor, @endColor, 80%);
-    background-image: -webkit-gradient(linear, 0 0, 0 100%, from(@startColor), color-stop(@colorStop, @midColor), to(@endColor));
-    background-image: -webkit-linear-gradient(@startColor, @midColor @colorStop, @endColor);
-    background-image: -moz-linear-gradient(top, @startColor, @midColor @colorStop, @endColor);
-    background-image: -o-linear-gradient(@startColor, @midColor @colorStop, @endColor);
-    background-image: linear-gradient(@startColor, @midColor @colorStop, @endColor);
-    background-repeat: no-repeat;
-    filter: e(%("progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d', GradientType=0)",argb(@startColor),argb(@endColor))); // IE9 and down, gets no color-stop at all for proper fallback
-  }
-  .radial(@innerColor: #555, @outerColor: #333) {
-    background-color: @outerColor;
-    background-image: -webkit-gradient(radial, center center, 0, center center, 460, from(@innerColor), to(@outerColor));
-    background-image: -webkit-radial-gradient(circle, @innerColor, @outerColor);
-    background-image: -moz-radial-gradient(circle, @innerColor, @outerColor);
-    background-image: -o-radial-gradient(circle, @innerColor, @outerColor);
-    background-repeat: no-repeat;
-  }
-  .striped(@color: #555, @angle: 45deg) {
-    background-color: @color;
-    background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(.25, rgba(255,255,255,.15)), color-stop(.25, transparent), color-stop(.5, transparent), color-stop(.5, rgba(255,255,255,.15)), color-stop(.75, rgba(255,255,255,.15)), color-stop(.75, transparent), to(transparent));
-    background-image: -webkit-linear-gradient(@angle, rgba(255,255,255,.15) 25%, transparent 25%, transparent 50%, rgba(255,255,255,.15) 50%, rgba(255,255,255,.15) 75%, transparent 75%, transparent);
-    background-image: -moz-linear-gradient(@angle, rgba(255,255,255,.15) 25%, transparent 25%, transparent 50%, rgba(255,255,255,.15) 50%, rgba(255,255,255,.15) 75%, transparent 75%, transparent);
-    background-image: -o-linear-gradient(@angle, rgba(255,255,255,.15) 25%, transparent 25%, transparent 50%, rgba(255,255,255,.15) 50%, rgba(255,255,255,.15) 75%, transparent 75%, transparent);
-    background-image: linear-gradient(@angle, rgba(255,255,255,.15) 25%, transparent 25%, transparent 50%, rgba(255,255,255,.15) 50%, rgba(255,255,255,.15) 75%, transparent 75%, transparent);
-  }
-}
-// Reset filters for IE
-.reset-filter() {
-  filter: e(%("progid:DXImageTransform.Microsoft.gradient(enabled = false)"));
-}
-
-
-
-// COMPONENT MIXINS
-// --------------------------------------------------
-
-// Horizontal dividers
-// -------------------------
-// Dividers (basically an hr) within dropdowns and nav lists
-.nav-divider(@top: #e5e5e5, @bottom: @white) {
-  // IE7 needs a set width since we gave a height. Restricting just
-  // to IE7 to keep the 1px left/right space in other browsers.
-  // It is unclear where IE is getting the extra space that we need
-  // to negative-margin away, but so it goes.
-  *width: 100%;
-  height: 1px;
-  margin: ((@baseLineHeight / 2) - 1) 1px; // 8px 1px
-  *margin: -5px 0 5px;
-  overflow: hidden;
-  background-color: @top;
-  border-bottom: 1px solid @bottom;
-}
-
-// Button backgrounds
-// ------------------
-.buttonBackground(@startColor, @endColor, @textColor: #fff, @textShadow: 0 -1px 0 rgba(0,0,0,.25)) {
-  // gradientBar will set the background to a pleasing blend of these, to support IE<=9
-  .gradientBar(@startColor, @endColor, @textColor, @textShadow);
-  *background-color: @endColor; /* Darken IE7 buttons by default so they stand out more given they won't have borders */
-  .reset-filter();
-
-  // in these cases the gradient won't cover the background, so we override
-  &:hover, &:focus, &:active, &.active, &.disabled, &[disabled] {
-    color: @textColor;
-    background-color: @endColor;
-    *background-color: darken(@endColor, 5%);
-  }
-
-  // IE 7 + 8 can't handle box-shadow to show active, so we darken a bit ourselves
-  &:active,
-  &.active {
-    background-color: darken(@endColor, 10%) e("\9");
-  }
-}
-
-// Navbar vertical align
-// -------------------------
-// Vertically center elements in the navbar.
-// Example: an element has a height of 30px, so write out `.navbarVerticalAlign(30px);` to calculate the appropriate top margin.
-.navbarVerticalAlign(@elementHeight) {
-  margin-top: (@navbarHeight - @elementHeight) / 2;
-}
-
-
-
-// Grid System
-// -----------
-
-// Centered container element
-.container-fixed() {
-  margin-right: auto;
-  margin-left: auto;
-  .clearfix();
-}
-
-// Table columns
-.tableColumns(@columnSpan: 1) {
-  float: none; // undo default grid column styles
-  width: ((@gridColumnWidth) * @columnSpan) + (@gridGutterWidth * (@columnSpan - 1)) - 16; // 16 is total padding on left and right of table cells
-  margin-left: 0; // undo default grid column styles
-}
-
-// Make a Grid
-// Use .makeRow and .makeColumn to assign semantic layouts grid system behavior
-.makeRow() {
-  margin-left: @gridGutterWidth * -1;
-  .clearfix();
-}
-.makeColumn(@columns: 1, @offset: 0) {
-  float: left;
-  margin-left: (@gridColumnWidth * @offset) + (@gridGutterWidth * (@offset - 1)) + (@gridGutterWidth * 2);
-  width: (@gridColumnWidth * @columns) + (@gridGutterWidth * (@columns - 1));
-}
-
-// The Grid
-#grid {
-
-  .core (@gridColumnWidth, @gridGutterWidth) {
-
-    .spanX (@index) when (@index > 0) {
-      .span@{index} { .span(@index); }
-      .spanX(@index - 1);
-    }
-    .spanX (0) {}
-
-    .offsetX (@index) when (@index > 0) {
-      .offset@{index} { .offset(@index); }
-      .offsetX(@index - 1);
-    }
-    .offsetX (0) {}
-
-    .offset (@columns) {
-      margin-left: (@gridColumnWidth * @columns) + (@gridGutterWidth * (@columns + 1));
-    }
-
-    .span (@columns) {
-      width: (@gridColumnWidth * @columns) + (@gridGutterWidth * (@columns - 1));
-    }
-
-    .row {
-      margin-left: @gridGutterWidth * -1;
-      .clearfix();
-    }
-
-    [class*="span"] {
-      float: left;
-      min-height: 1px; // prevent collapsing columns
-      margin-left: @gridGutterWidth;
-    }
-
-    // Set the container width, and override it for fixed navbars in media queries
-    .container,
-    .navbar-static-top .container,
-    .navbar-fixed-top .container,
-    .navbar-fixed-bottom .container { .span(@gridColumns); }
-
-    // generate .spanX and .offsetX
-    .spanX (@gridColumns);
-    .offsetX (@gridColumns);
-
-  }
-
-  .fluid (@fluidGridColumnWidth, @fluidGridGutterWidth) {
-
-    .spanX (@index) when (@index > 0) {
-      .span@{index} { .span(@index); }
-      .spanX(@index - 1);
-    }
-    .spanX (0) {}
-
-    .offsetX (@index) when (@index > 0) {
-      .offset@{index} { .offset(@index); }
-      .offset@{index}:first-child { .offsetFirstChild(@index); }
-      .offsetX(@index - 1);
-    }
-    .offsetX (0) {}
-
-    .offset (@columns) {
-      margin-left: (@fluidGridColumnWidth * @columns) + (@fluidGridGutterWidth * (@columns - 1)) + (@fluidGridGutterWidth*2);
-  	  *margin-left: (@fluidGridColumnWidth * @columns) + (@fluidGridGutterWidth * (@columns - 1)) - (.5 / @gridRowWidth * 100 * 1%) + (@fluidGridGutterWidth*2) - (.5 / @gridRowWidth * 100 * 1%);
-    }
-
-    .offsetFirstChild (@columns) {
-      margin-left: (@fluidGridColumnWidth * @columns) + (@fluidGridGutterWidth * (@columns - 1)) + (@fluidGridGutterWidth);
-      *margin-left: (@fluidGridColumnWidth * @columns) + (@fluidGridGutterWidth * (@columns - 1)) - (.5 / @gridRowWidth * 100 * 1%) + @fluidGridGutterWidth - (.5 / @gridRowWidth * 100 * 1%);
-    }
-
-    .span (@columns) {
-      width: (@fluidGridColumnWidth * @columns) + (@fluidGridGutterWidth * (@columns - 1));
-      *width: (@fluidGridColumnWidth * @columns) + (@fluidGridGutterWidth * (@columns - 1)) - (.5 / @gridRowWidth * 100 * 1%);
-    }
-
-    .row-fluid {
-      width: 100%;
-      .clearfix();
-      [class*="span"] {
-        .input-block-level();
-        float: left;
-        margin-left: @fluidGridGutterWidth;
-        *margin-left: @fluidGridGutterWidth - (.5 / @gridRowWidth * 100 * 1%);
-      }
-      [class*="span"]:first-child {
-        margin-left: 0;
-      }
-
-      // Space grid-sized controls properly if multiple per line
-      .controls-row [class*="span"] + [class*="span"] {
-        margin-left: @fluidGridGutterWidth;
-      }
-
-      // generate .spanX and .offsetX
-      .spanX (@gridColumns);
-      .offsetX (@gridColumns);
-    }
-
-  }
-
-  .input(@gridColumnWidth, @gridGutterWidth) {
-
-    .spanX (@index) when (@index > 0) {
-      input.span@{index}, textarea.span@{index}, .uneditable-input.span@{index} { .span(@index); }
-      .spanX(@index - 1);
-    }
-    .spanX (0) {}
-
-    .span(@columns) {
-      width: ((@gridColumnWidth) * @columns) + (@gridGutterWidth * (@columns - 1)) - 14;
-    }
-
-    input,
-    textarea,
-    .uneditable-input {
-      margin-left: 0; // override margin-left from core grid system
-    }
-
-    // Space grid-sized controls properly if multiple per line
-    .controls-row [class*="span"] + [class*="span"] {
-      margin-left: @gridGutterWidth;
-    }
-
-    // generate .spanX
-    .spanX (@gridColumns);
-
-  }
-}
-
-.customTransition(@prop, @delay, @a, @b, @c, @d){
--webkit-transition: @prop, @delay cubic-bezier(@a, @b, @c, @d); 
-   -moz-transition: @prop, @delay cubic-bezier(@a, @b, @c, @d); 
-    -ms-transition: @prop, @delay cubic-bezier(@a, @b, @c, @d); 
-     -o-transition: @prop, @delay cubic-bezier(@a, @b, @c, @d); 
-        transition: @prop, @delay cubic-bezier(@a, @b, @c, @d); /* custom */
-
--webkit-transition-timing-function: cubic-bezier(@a, @b, @c, @d); 
-   -moz-transition-timing-function: cubic-bezier(@a, @b, @c, @d); 
-    -ms-transition-timing-function: cubic-bezier(@a, @b, @c, @d); 
-     -o-transition-timing-function: cubic-bezier(@a, @b, @c, @d); 
-        transition-timing-function: cubic-bezier(@a, @b, @c, @d); /* custom */
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/modals.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/modals.less b/apps/fauxton/assets/less/bootstrap/modals.less
deleted file mode 100644
index 8e272d4..0000000
--- a/apps/fauxton/assets/less/bootstrap/modals.less
+++ /dev/null
@@ -1,95 +0,0 @@
-//
-// Modals
-// --------------------------------------------------
-
-// Background
-.modal-backdrop {
-  position: fixed;
-  top: 0;
-  right: 0;
-  bottom: 0;
-  left: 0;
-  z-index: @zindexModalBackdrop;
-  background-color: @black;
-  // Fade for backdrop
-  &.fade { opacity: 0; }
-}
-
-.modal-backdrop,
-.modal-backdrop.fade.in {
-  .opacity(80);
-}
-
-// Base modal
-.modal {
-  position: fixed;
-  top: 10%;
-  left: 50%;
-  z-index: @zindexModal;
-  width: 560px;
-  margin-left: -280px;
-  background-color: @white;
-  border: 1px solid #999;
-  border: 1px solid rgba(0,0,0,.3);
-  *border: 1px solid #999; /* IE6-7 */
-  .border-radius(6px);
-  .box-shadow(0 3px 7px rgba(0,0,0,0.3));
-  .background-clip(padding-box);
-  // Remove focus outline from opened modal
-  outline: none;
-
-  &.fade {
-    .transition(e('opacity .3s linear, top .3s ease-out'));
-    top: -25%;
-  }
-  &.fade.in { top: 10%; }
-}
-.modal-header {
-  padding: 9px 15px;
-  border-bottom: 1px solid #eee;
-  // Close icon
-  .close { margin-top: 2px; }
-  // Heading
-  h3 {
-    margin: 0;
-    line-height: 30px;
-  }
-}
-
-// Body (where all modal content resides)
-.modal-body {
-  position: relative;
-  overflow-y: auto;
-  max-height: 400px;
-  padding: 15px;
-}
-// Remove bottom margin if need be
-.modal-form {
-  margin-bottom: 0;
-}
-
-// Footer (for actions)
-.modal-footer {
-  padding: 14px 15px 15px;
-  margin-bottom: 0;
-  text-align: right; // right align buttons
-  background-color: #f5f5f5;
-  border-top: 1px solid #ddd;
-  .border-radius(0 0 6px 6px);
-  .box-shadow(inset 0 1px 0 @white);
-  .clearfix(); // clear it in case folks use .pull-* classes on buttons
-
-  // Properly space out buttons
-  .btn + .btn {
-    margin-left: 5px;
-    margin-bottom: 0; // account for input[type="submit"] which gets the bottom margin like all other inputs
-  }
-  // but override that for button groups
-  .btn-group .btn + .btn {
-    margin-left: -1px;
-  }
-  // and override it for block buttons as well
-  .btn-block + .btn-block {
-    margin-left: 0;
-  }
-}


[05/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/test/mocha/chai.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/test/mocha/chai.js b/apps/fauxton/test/mocha/chai.js
deleted file mode 100644
index 2a67f98..0000000
--- a/apps/fauxton/test/mocha/chai.js
+++ /dev/null
@@ -1,4330 +0,0 @@
-;(function(){
-
-/**
- * Require the given path.
- *
- * @param {String} path
- * @return {Object} exports
- * @api public
- */
-
-function require(path, parent, orig) {
-  var resolved = require.resolve(path);
-
-  // lookup failed
-  if (null == resolved) {
-    orig = orig || path;
-    parent = parent || 'root';
-    var err = new Error('Failed to require "' + orig + '" from "' + parent + '"');
-    err.path = orig;
-    err.parent = parent;
-    err.require = true;
-    throw err;
-  }
-
-  var module = require.modules[resolved];
-
-  // perform real require()
-  // by invoking the module's
-  // registered function
-  if (!module.exports) {
-    module.exports = {};
-    module.client = module.component = true;
-    module.call(this, module.exports, require.relative(resolved), module);
-  }
-
-  return module.exports;
-}
-
-/**
- * Registered modules.
- */
-
-require.modules = {};
-
-/**
- * Registered aliases.
- */
-
-require.aliases = {};
-
-/**
- * Resolve `path`.
- *
- * Lookup:
- *
- *   - PATH/index.js
- *   - PATH.js
- *   - PATH
- *
- * @param {String} path
- * @return {String} path or null
- * @api private
- */
-
-require.resolve = function(path) {
-  if (path.charAt(0) === '/') path = path.slice(1);
-
-  var paths = [
-    path,
-    path + '.js',
-    path + '.json',
-    path + '/index.js',
-    path + '/index.json'
-  ];
-
-  for (var i = 0; i < paths.length; i++) {
-    var path = paths[i];
-    if (require.modules.hasOwnProperty(path)) return path;
-    if (require.aliases.hasOwnProperty(path)) return require.aliases[path];
-  }
-};
-
-/**
- * Normalize `path` relative to the current path.
- *
- * @param {String} curr
- * @param {String} path
- * @return {String}
- * @api private
- */
-
-require.normalize = function(curr, path) {
-  var segs = [];
-
-  if ('.' != path.charAt(0)) return path;
-
-  curr = curr.split('/');
-  path = path.split('/');
-
-  for (var i = 0; i < path.length; ++i) {
-    if ('..' == path[i]) {
-      curr.pop();
-    } else if ('.' != path[i] && '' != path[i]) {
-      segs.push(path[i]);
-    }
-  }
-
-  return curr.concat(segs).join('/');
-};
-
-/**
- * Register module at `path` with callback `definition`.
- *
- * @param {String} path
- * @param {Function} definition
- * @api private
- */
-
-require.register = function(path, definition) {
-  require.modules[path] = definition;
-};
-
-/**
- * Alias a module definition.
- *
- * @param {String} from
- * @param {String} to
- * @api private
- */
-
-require.alias = function(from, to) {
-  if (!require.modules.hasOwnProperty(from)) {
-    throw new Error('Failed to alias "' + from + '", it does not exist');
-  }
-  require.aliases[to] = from;
-};
-
-/**
- * Return a require function relative to the `parent` path.
- *
- * @param {String} parent
- * @return {Function}
- * @api private
- */
-
-require.relative = function(parent) {
-  var p = require.normalize(parent, '..');
-
-  /**
-   * lastIndexOf helper.
-   */
-
-  function lastIndexOf(arr, obj) {
-    var i = arr.length;
-    while (i--) {
-      if (arr[i] === obj) return i;
-    }
-    return -1;
-  }
-
-  /**
-   * The relative require() itself.
-   */
-
-  function localRequire(path) {
-    var resolved = localRequire.resolve(path);
-    return require(resolved, parent, path);
-  }
-
-  /**
-   * Resolve relative to the parent.
-   */
-
-  localRequire.resolve = function(path) {
-    var c = path.charAt(0);
-    if ('/' == c) return path.slice(1);
-    if ('.' == c) return require.normalize(p, path);
-
-    // resolve deps by returning
-    // the dep in the nearest "deps"
-    // directory
-    var segs = parent.split('/');
-    var i = lastIndexOf(segs, 'deps') + 1;
-    if (!i) i = 0;
-    path = segs.slice(0, i + 1).join('/') + '/deps/' + path;
-    return path;
-  };
-
-  /**
-   * Check if module is defined at `path`.
-   */
-
-  localRequire.exists = function(path) {
-    return require.modules.hasOwnProperty(localRequire.resolve(path));
-  };
-
-  return localRequire;
-};
-require.register("chaijs-assertion-error/index.js", function(exports, require, module){
-/*!
- * assertion-error
- * Copyright(c) 2013 Jake Luer <ja...@qualiancy.com>
- * MIT Licensed
- */
-
-/*!
- * Return a function that will copy properties from
- * one object to another excluding any originally
- * listed. Returned function will create a new `{}`.
- *
- * @param {String} excluded properties ...
- * @return {Function}
- */
-
-function exclude () {
-  var excludes = [].slice.call(arguments);
-
-  function excludeProps (res, obj) {
-    Object.keys(obj).forEach(function (key) {
-      if (!~excludes.indexOf(key)) res[key] = obj[key];
-    });
-  }
-
-  return function extendExclude () {
-    var args = [].slice.call(arguments)
-      , i = 0
-      , res = {};
-
-    for (; i < args.length; i++) {
-      excludeProps(res, args[i]);
-    }
-
-    return res;
-  };
-};
-
-/*!
- * Primary Exports
- */
-
-module.exports = AssertionError;
-
-/**
- * ### AssertionError
- *
- * An extension of the JavaScript `Error` constructor for
- * assertion and validation scenarios.
- *
- * @param {String} message
- * @param {Object} properties to include (optional)
- * @param {callee} start stack function (optional)
- */
-
-function AssertionError (message, _props, ssf) {
-  var extend = exclude('name', 'message', 'stack', 'constructor', 'toJSON')
-    , props = extend(_props || {});
-
-  // default values
-  this.message = message || 'Unspecified AssertionError';
-  this.showDiff = false;
-
-  // copy from properties
-  for (var key in props) {
-    this[key] = props[key];
-  }
-
-  // capture stack trace
-  ssf = ssf || arguments.callee;
-  if (ssf && Error.captureStackTrace) {
-    Error.captureStackTrace(this, ssf);
-  }
-}
-
-/*!
- * Inherit from Error.prototype
- */
-
-AssertionError.prototype = Object.create(Error.prototype);
-
-/*!
- * Statically set name
- */
-
-AssertionError.prototype.name = 'AssertionError';
-
-/*!
- * Ensure correct constructor
- */
-
-AssertionError.prototype.constructor = AssertionError;
-
-/**
- * Allow errors to be converted to JSON for static transfer.
- *
- * @param {Boolean} include stack (default: `true`)
- * @return {Object} object that can be `JSON.stringify`
- */
-
-AssertionError.prototype.toJSON = function (stack) {
-  var extend = exclude('constructor', 'toJSON', 'stack')
-    , props = extend({ name: this.name }, this);
-
-  // include stack if exists and not turned off
-  if (false !== stack && this.stack) {
-    props.stack = this.stack;
-  }
-
-  return props;
-};
-
-});
-require.register("chai/index.js", function(exports, require, module){
-module.exports = require('./lib/chai');
-
-});
-require.register("chai/lib/chai.js", function(exports, require, module){
-/*!
- * chai
- * Copyright(c) 2011-2013 Jake Luer <ja...@alogicalparadox.com>
- * MIT Licensed
- */
-
-var used = []
-  , exports = module.exports = {};
-
-/*!
- * Chai version
- */
-
-exports.version = '1.7.2';
-
-/*!
- * Assertion Error
- */
-
-exports.AssertionError = require('assertion-error');
-
-/*!
- * Utils for plugins (not exported)
- */
-
-var util = require('./chai/utils');
-
-/**
- * # .use(function)
- *
- * Provides a way to extend the internals of Chai
- *
- * @param {Function}
- * @returns {this} for chaining
- * @api public
- */
-
-exports.use = function (fn) {
-  if (!~used.indexOf(fn)) {
-    fn(this, util);
-    used.push(fn);
-  }
-
-  return this;
-};
-
-/*!
- * Primary `Assertion` prototype
- */
-
-var assertion = require('./chai/assertion');
-exports.use(assertion);
-
-/*!
- * Core Assertions
- */
-
-var core = require('./chai/core/assertions');
-exports.use(core);
-
-/*!
- * Expect interface
- */
-
-var expect = require('./chai/interface/expect');
-exports.use(expect);
-
-/*!
- * Should interface
- */
-
-var should = require('./chai/interface/should');
-exports.use(should);
-
-/*!
- * Assert interface
- */
-
-var assert = require('./chai/interface/assert');
-exports.use(assert);
-
-});
-require.register("chai/lib/chai/assertion.js", function(exports, require, module){
-/*!
- * chai
- * http://chaijs.com
- * Copyright(c) 2011-2013 Jake Luer <ja...@alogicalparadox.com>
- * MIT Licensed
- */
-
-module.exports = function (_chai, util) {
-  /*!
-   * Module dependencies.
-   */
-
-  var AssertionError = _chai.AssertionError
-    , flag = util.flag;
-
-  /*!
-   * Module export.
-   */
-
-  _chai.Assertion = Assertion;
-
-  /*!
-   * Assertion Constructor
-   *
-   * Creates object for chaining.
-   *
-   * @api private
-   */
-
-  function Assertion (obj, msg, stack) {
-    flag(this, 'ssfi', stack || arguments.callee);
-    flag(this, 'object', obj);
-    flag(this, 'message', msg);
-  }
-
-  /*!
-    * ### Assertion.includeStack
-    *
-    * User configurable property, influences whether stack trace
-    * is included in Assertion error message. Default of false
-    * suppresses stack trace in the error message
-    *
-    *     Assertion.includeStack = true;  // enable stack on error
-    *
-    * @api public
-    */
-
-  Assertion.includeStack = false;
-
-  /*!
-   * ### Assertion.showDiff
-   *
-   * User configurable property, influences whether or not
-   * the `showDiff` flag should be included in the thrown
-   * AssertionErrors. `false` will always be `false`; `true`
-   * will be true when the assertion has requested a diff
-   * be shown.
-   *
-   * @api public
-   */
-
-  Assertion.showDiff = true;
-
-  Assertion.addProperty = function (name, fn) {
-    util.addProperty(this.prototype, name, fn);
-  };
-
-  Assertion.addMethod = function (name, fn) {
-    util.addMethod(this.prototype, name, fn);
-  };
-
-  Assertion.addChainableMethod = function (name, fn, chainingBehavior) {
-    util.addChainableMethod(this.prototype, name, fn, chainingBehavior);
-  };
-
-  Assertion.overwriteProperty = function (name, fn) {
-    util.overwriteProperty(this.prototype, name, fn);
-  };
-
-  Assertion.overwriteMethod = function (name, fn) {
-    util.overwriteMethod(this.prototype, name, fn);
-  };
-
-  /*!
-   * ### .assert(expression, message, negateMessage, expected, actual)
-   *
-   * Executes an expression and check expectations. Throws AssertionError for reporting if test doesn't pass.
-   *
-   * @name assert
-   * @param {Philosophical} expression to be tested
-   * @param {String} message to display if fails
-   * @param {String} negatedMessage to display if negated expression fails
-   * @param {Mixed} expected value (remember to check for negation)
-   * @param {Mixed} actual (optional) will default to `this.obj`
-   * @api private
-   */
-
-  Assertion.prototype.assert = function (expr, msg, negateMsg, expected, _actual, showDiff) {
-    var ok = util.test(this, arguments);
-    if (true !== showDiff) showDiff = false;
-    if (true !== Assertion.showDiff) showDiff = false;
-
-    if (!ok) {
-      var msg = util.getMessage(this, arguments)
-        , actual = util.getActual(this, arguments);
-      throw new AssertionError(msg, {
-          actual: actual
-        , expected: expected
-        , showDiff: showDiff
-      }, (Assertion.includeStack) ? this.assert : flag(this, 'ssfi'));
-    }
-  };
-
-  /*!
-   * ### ._obj
-   *
-   * Quick reference to stored `actual` value for plugin developers.
-   *
-   * @api private
-   */
-
-  Object.defineProperty(Assertion.prototype, '_obj',
-    { get: function () {
-        return flag(this, 'object');
-      }
-    , set: function (val) {
-        flag(this, 'object', val);
-      }
-  });
-};
-
-});
-require.register("chai/lib/chai/core/assertions.js", function(exports, require, module){
-/*!
- * chai
- * http://chaijs.com
- * Copyright(c) 2011-2013 Jake Luer <ja...@alogicalparadox.com>
- * MIT Licensed
- */
-
-module.exports = function (chai, _) {
-  var Assertion = chai.Assertion
-    , toString = Object.prototype.toString
-    , flag = _.flag;
-
-  /**
-   * ### Language Chains
-   *
-   * The following are provide as chainable getters to
-   * improve the readability of your assertions. They
-   * do not provide an testing capability unless they
-   * have been overwritten by a plugin.
-   *
-   * **Chains**
-   *
-   * - to
-   * - be
-   * - been
-   * - is
-   * - that
-   * - and
-   * - have
-   * - with
-   * - at
-   * - of
-   * - same
-   *
-   * @name language chains
-   * @api public
-   */
-
-  [ 'to', 'be', 'been'
-  , 'is', 'and', 'have'
-  , 'with', 'that', 'at'
-  , 'of', 'same' ].forEach(function (chain) {
-    Assertion.addProperty(chain, function () {
-      return this;
-    });
-  });
-
-  /**
-   * ### .not
-   *
-   * Negates any of assertions following in the chain.
-   *
-   *     expect(foo).to.not.equal('bar');
-   *     expect(goodFn).to.not.throw(Error);
-   *     expect({ foo: 'baz' }).to.have.property('foo')
-   *       .and.not.equal('bar');
-   *
-   * @name not
-   * @api public
-   */
-
-  Assertion.addProperty('not', function () {
-    flag(this, 'negate', true);
-  });
-
-  /**
-   * ### .deep
-   *
-   * Sets the `deep` flag, later used by the `equal` and
-   * `property` assertions.
-   *
-   *     expect(foo).to.deep.equal({ bar: 'baz' });
-   *     expect({ foo: { bar: { baz: 'quux' } } })
-   *       .to.have.deep.property('foo.bar.baz', 'quux');
-   *
-   * @name deep
-   * @api public
-   */
-
-  Assertion.addProperty('deep', function () {
-    flag(this, 'deep', true);
-  });
-
-  /**
-   * ### .a(type)
-   *
-   * The `a` and `an` assertions are aliases that can be
-   * used either as language chains or to assert a value's
-   * type.
-   *
-   *     // typeof
-   *     expect('test').to.be.a('string');
-   *     expect({ foo: 'bar' }).to.be.an('object');
-   *     expect(null).to.be.a('null');
-   *     expect(undefined).to.be.an('undefined');
-   *
-   *     // language chain
-   *     expect(foo).to.be.an.instanceof(Foo);
-   *
-   * @name a
-   * @alias an
-   * @param {String} type
-   * @param {String} message _optional_
-   * @api public
-   */
-
-  function an (type, msg) {
-    if (msg) flag(this, 'message', msg);
-    type = type.toLowerCase();
-    var obj = flag(this, 'object')
-      , article = ~[ 'a', 'e', 'i', 'o', 'u' ].indexOf(type.charAt(0)) ? 'an ' : 'a ';
-
-    this.assert(
-        type === _.type(obj)
-      , 'expected #{this} to be ' + article + type
-      , 'expected #{this} not to be ' + article + type
-    );
-  }
-
-  Assertion.addChainableMethod('an', an);
-  Assertion.addChainableMethod('a', an);
-
-  /**
-   * ### .include(value)
-   *
-   * The `include` and `contain` assertions can be used as either property
-   * based language chains or as methods to assert the inclusion of an object
-   * in an array or a substring in a string. When used as language chains,
-   * they toggle the `contain` flag for the `keys` assertion.
-   *
-   *     expect([1,2,3]).to.include(2);
-   *     expect('foobar').to.contain('foo');
-   *     expect({ foo: 'bar', hello: 'universe' }).to.include.keys('foo');
-   *
-   * @name include
-   * @alias contain
-   * @param {Object|String|Number} obj
-   * @param {String} message _optional_
-   * @api public
-   */
-
-  function includeChainingBehavior () {
-    flag(this, 'contains', true);
-  }
-
-  function include (val, msg) {
-    if (msg) flag(this, 'message', msg);
-    var obj = flag(this, 'object')
-    this.assert(
-        ~obj.indexOf(val)
-      , 'expected #{this} to include ' + _.inspect(val)
-      , 'expected #{this} to not include ' + _.inspect(val));
-  }
-
-  Assertion.addChainableMethod('include', include, includeChainingBehavior);
-  Assertion.addChainableMethod('contain', include, includeChainingBehavior);
-
-  /**
-   * ### .ok
-   *
-   * Asserts that the target is truthy.
-   *
-   *     expect('everthing').to.be.ok;
-   *     expect(1).to.be.ok;
-   *     expect(false).to.not.be.ok;
-   *     expect(undefined).to.not.be.ok;
-   *     expect(null).to.not.be.ok;
-   *
-   * @name ok
-   * @api public
-   */
-
-  Assertion.addProperty('ok', function () {
-    this.assert(
-        flag(this, 'object')
-      , 'expected #{this} to be truthy'
-      , 'expected #{this} to be falsy');
-  });
-
-  /**
-   * ### .true
-   *
-   * Asserts that the target is `true`.
-   *
-   *     expect(true).to.be.true;
-   *     expect(1).to.not.be.true;
-   *
-   * @name true
-   * @api public
-   */
-
-  Assertion.addProperty('true', function () {
-    this.assert(
-        true === flag(this, 'object')
-      , 'expected #{this} to be true'
-      , 'expected #{this} to be false'
-      , this.negate ? false : true
-    );
-  });
-
-  /**
-   * ### .false
-   *
-   * Asserts that the target is `false`.
-   *
-   *     expect(false).to.be.false;
-   *     expect(0).to.not.be.false;
-   *
-   * @name false
-   * @api public
-   */
-
-  Assertion.addProperty('false', function () {
-    this.assert(
-        false === flag(this, 'object')
-      , 'expected #{this} to be false'
-      , 'expected #{this} to be true'
-      , this.negate ? true : false
-    );
-  });
-
-  /**
-   * ### .null
-   *
-   * Asserts that the target is `null`.
-   *
-   *     expect(null).to.be.null;
-   *     expect(undefined).not.to.be.null;
-   *
-   * @name null
-   * @api public
-   */
-
-  Assertion.addProperty('null', function () {
-    this.assert(
-        null === flag(this, 'object')
-      , 'expected #{this} to be null'
-      , 'expected #{this} not to be null'
-    );
-  });
-
-  /**
-   * ### .undefined
-   *
-   * Asserts that the target is `undefined`.
-   *
-   *      expect(undefined).to.be.undefined;
-   *      expect(null).to.not.be.undefined;
-   *
-   * @name undefined
-   * @api public
-   */
-
-  Assertion.addProperty('undefined', function () {
-    this.assert(
-        undefined === flag(this, 'object')
-      , 'expected #{this} to be undefined'
-      , 'expected #{this} not to be undefined'
-    );
-  });
-
-  /**
-   * ### .exist
-   *
-   * Asserts that the target is neither `null` nor `undefined`.
-   *
-   *     var foo = 'hi'
-   *       , bar = null
-   *       , baz;
-   *
-   *     expect(foo).to.exist;
-   *     expect(bar).to.not.exist;
-   *     expect(baz).to.not.exist;
-   *
-   * @name exist
-   * @api public
-   */
-
-  Assertion.addProperty('exist', function () {
-    this.assert(
-        null != flag(this, 'object')
-      , 'expected #{this} to exist'
-      , 'expected #{this} to not exist'
-    );
-  });
-
-
-  /**
-   * ### .empty
-   *
-   * Asserts that the target's length is `0`. For arrays, it checks
-   * the `length` property. For objects, it gets the count of
-   * enumerable keys.
-   *
-   *     expect([]).to.be.empty;
-   *     expect('').to.be.empty;
-   *     expect({}).to.be.empty;
-   *
-   * @name empty
-   * @api public
-   */
-
-  Assertion.addProperty('empty', function () {
-    var obj = flag(this, 'object')
-      , expected = obj;
-
-    if (Array.isArray(obj) || 'string' === typeof object) {
-      expected = obj.length;
-    } else if (typeof obj === 'object') {
-      expected = Object.keys(obj).length;
-    }
-
-    this.assert(
-        !expected
-      , 'expected #{this} to be empty'
-      , 'expected #{this} not to be empty'
-    );
-  });
-
-  /**
-   * ### .arguments
-   *
-   * Asserts that the target is an arguments object.
-   *
-   *     function test () {
-   *       expect(arguments).to.be.arguments;
-   *     }
-   *
-   * @name arguments
-   * @alias Arguments
-   * @api public
-   */
-
-  function checkArguments () {
-    var obj = flag(this, 'object')
-      , type = Object.prototype.toString.call(obj);
-    this.assert(
-        '[object Arguments]' === type
-      , 'expected #{this} to be arguments but got ' + type
-      , 'expected #{this} to not be arguments'
-    );
-  }
-
-  Assertion.addProperty('arguments', checkArguments);
-  Assertion.addProperty('Arguments', checkArguments);
-
-  /**
-   * ### .equal(value)
-   *
-   * Asserts that the target is strictly equal (`===`) to `value`.
-   * Alternately, if the `deep` flag is set, asserts that
-   * the target is deeply equal to `value`.
-   *
-   *     expect('hello').to.equal('hello');
-   *     expect(42).to.equal(42);
-   *     expect(1).to.not.equal(true);
-   *     expect({ foo: 'bar' }).to.not.equal({ foo: 'bar' });
-   *     expect({ foo: 'bar' }).to.deep.equal({ foo: 'bar' });
-   *
-   * @name equal
-   * @alias equals
-   * @alias eq
-   * @alias deep.equal
-   * @param {Mixed} value
-   * @param {String} message _optional_
-   * @api public
-   */
-
-  function assertEqual (val, msg) {
-    if (msg) flag(this, 'message', msg);
-    var obj = flag(this, 'object');
-    if (flag(this, 'deep')) {
-      return this.eql(val);
-    } else {
-      this.assert(
-          val === obj
-        , 'expected #{this} to equal #{exp}'
-        , 'expected #{this} to not equal #{exp}'
-        , val
-        , this._obj
-        , true
-      );
-    }
-  }
-
-  Assertion.addMethod('equal', assertEqual);
-  Assertion.addMethod('equals', assertEqual);
-  Assertion.addMethod('eq', assertEqual);
-
-  /**
-   * ### .eql(value)
-   *
-   * Asserts that the target is deeply equal to `value`.
-   *
-   *     expect({ foo: 'bar' }).to.eql({ foo: 'bar' });
-   *     expect([ 1, 2, 3 ]).to.eql([ 1, 2, 3 ]);
-   *
-   * @name eql
-   * @alias eqls
-   * @param {Mixed} value
-   * @param {String} message _optional_
-   * @api public
-   */
-
-  function assertEql(obj, msg) {
-    if (msg) flag(this, 'message', msg);
-    this.assert(
-        _.eql(obj, flag(this, 'object'))
-      , 'expected #{this} to deeply equal #{exp}'
-      , 'expected #{this} to not deeply equal #{exp}'
-      , obj
-      , this._obj
-      , true
-    );
-  }
-
-  Assertion.addMethod('eql', assertEql);
-  Assertion.addMethod('eqls', assertEql);
-
-  /**
-   * ### .above(value)
-   *
-   * Asserts that the target is greater than `value`.
-   *
-   *     expect(10).to.be.above(5);
-   *
-   * Can also be used in conjunction with `length` to
-   * assert a minimum length. The benefit being a
-   * more informative error message than if the length
-   * was supplied directly.
-   *
-   *     expect('foo').to.have.length.above(2);
-   *     expect([ 1, 2, 3 ]).to.have.length.above(2);
-   *
-   * @name above
-   * @alias gt
-   * @alias greaterThan
-   * @param {Number} value
-   * @param {String} message _optional_
-   * @api public
-   */
-
-  function assertAbove (n, msg) {
-    if (msg) flag(this, 'message', msg);
-    var obj = flag(this, 'object');
-    if (flag(this, 'doLength')) {
-      new Assertion(obj, msg).to.have.property('length');
-      var len = obj.length;
-      this.assert(
-          len > n
-        , 'expected #{this} to have a length above #{exp} but got #{act}'
-        , 'expected #{this} to not have a length above #{exp}'
-        , n
-        , len
-      );
-    } else {
-      this.assert(
-          obj > n
-        , 'expected #{this} to be above ' + n
-        , 'expected #{this} to be at most ' + n
-      );
-    }
-  }
-
-  Assertion.addMethod('above', assertAbove);
-  Assertion.addMethod('gt', assertAbove);
-  Assertion.addMethod('greaterThan', assertAbove);
-
-  /**
-   * ### .least(value)
-   *
-   * Asserts that the target is greater than or equal to `value`.
-   *
-   *     expect(10).to.be.at.least(10);
-   *
-   * Can also be used in conjunction with `length` to
-   * assert a minimum length. The benefit being a
-   * more informative error message than if the length
-   * was supplied directly.
-   *
-   *     expect('foo').to.have.length.of.at.least(2);
-   *     expect([ 1, 2, 3 ]).to.have.length.of.at.least(3);
-   *
-   * @name least
-   * @alias gte
-   * @param {Number} value
-   * @param {String} message _optional_
-   * @api public
-   */
-
-  function assertLeast (n, msg) {
-    if (msg) flag(this, 'message', msg);
-    var obj = flag(this, 'object');
-    if (flag(this, 'doLength')) {
-      new Assertion(obj, msg).to.have.property('length');
-      var len = obj.length;
-      this.assert(
-          len >= n
-        , 'expected #{this} to have a length at least #{exp} but got #{act}'
-        , 'expected #{this} to have a length below #{exp}'
-        , n
-        , len
-      );
-    } else {
-      this.assert(
-          obj >= n
-        , 'expected #{this} to be at least ' + n
-        , 'expected #{this} to be below ' + n
-      );
-    }
-  }
-
-  Assertion.addMethod('least', assertLeast);
-  Assertion.addMethod('gte', assertLeast);
-
-  /**
-   * ### .below(value)
-   *
-   * Asserts that the target is less than `value`.
-   *
-   *     expect(5).to.be.below(10);
-   *
-   * Can also be used in conjunction with `length` to
-   * assert a maximum length. The benefit being a
-   * more informative error message than if the length
-   * was supplied directly.
-   *
-   *     expect('foo').to.have.length.below(4);
-   *     expect([ 1, 2, 3 ]).to.have.length.below(4);
-   *
-   * @name below
-   * @alias lt
-   * @alias lessThan
-   * @param {Number} value
-   * @param {String} message _optional_
-   * @api public
-   */
-
-  function assertBelow (n, msg) {
-    if (msg) flag(this, 'message', msg);
-    var obj = flag(this, 'object');
-    if (flag(this, 'doLength')) {
-      new Assertion(obj, msg).to.have.property('length');
-      var len = obj.length;
-      this.assert(
-          len < n
-        , 'expected #{this} to have a length below #{exp} but got #{act}'
-        , 'expected #{this} to not have a length below #{exp}'
-        , n
-        , len
-      );
-    } else {
-      this.assert(
-          obj < n
-        , 'expected #{this} to be below ' + n
-        , 'expected #{this} to be at least ' + n
-      );
-    }
-  }
-
-  Assertion.addMethod('below', assertBelow);
-  Assertion.addMethod('lt', assertBelow);
-  Assertion.addMethod('lessThan', assertBelow);
-
-  /**
-   * ### .most(value)
-   *
-   * Asserts that the target is less than or equal to `value`.
-   *
-   *     expect(5).to.be.at.most(5);
-   *
-   * Can also be used in conjunction with `length` to
-   * assert a maximum length. The benefit being a
-   * more informative error message than if the length
-   * was supplied directly.
-   *
-   *     expect('foo').to.have.length.of.at.most(4);
-   *     expect([ 1, 2, 3 ]).to.have.length.of.at.most(3);
-   *
-   * @name most
-   * @alias lte
-   * @param {Number} value
-   * @param {String} message _optional_
-   * @api public
-   */
-
-  function assertMost (n, msg) {
-    if (msg) flag(this, 'message', msg);
-    var obj = flag(this, 'object');
-    if (flag(this, 'doLength')) {
-      new Assertion(obj, msg).to.have.property('length');
-      var len = obj.length;
-      this.assert(
-          len <= n
-        , 'expected #{this} to have a length at most #{exp} but got #{act}'
-        , 'expected #{this} to have a length above #{exp}'
-        , n
-        , len
-      );
-    } else {
-      this.assert(
-          obj <= n
-        , 'expected #{this} to be at most ' + n
-        , 'expected #{this} to be above ' + n
-      );
-    }
-  }
-
-  Assertion.addMethod('most', assertMost);
-  Assertion.addMethod('lte', assertMost);
-
-  /**
-   * ### .within(start, finish)
-   *
-   * Asserts that the target is within a range.
-   *
-   *     expect(7).to.be.within(5,10);
-   *
-   * Can also be used in conjunction with `length` to
-   * assert a length range. The benefit being a
-   * more informative error message than if the length
-   * was supplied directly.
-   *
-   *     expect('foo').to.have.length.within(2,4);
-   *     expect([ 1, 2, 3 ]).to.have.length.within(2,4);
-   *
-   * @name within
-   * @param {Number} start lowerbound inclusive
-   * @param {Number} finish upperbound inclusive
-   * @param {String} message _optional_
-   * @api public
-   */
-
-  Assertion.addMethod('within', function (start, finish, msg) {
-    if (msg) flag(this, 'message', msg);
-    var obj = flag(this, 'object')
-      , range = start + '..' + finish;
-    if (flag(this, 'doLength')) {
-      new Assertion(obj, msg).to.have.property('length');
-      var len = obj.length;
-      this.assert(
-          len >= start && len <= finish
-        , 'expected #{this} to have a length within ' + range
-        , 'expected #{this} to not have a length within ' + range
-      );
-    } else {
-      this.assert(
-          obj >= start && obj <= finish
-        , 'expected #{this} to be within ' + range
-        , 'expected #{this} to not be within ' + range
-      );
-    }
-  });
-
-  /**
-   * ### .instanceof(constructor)
-   *
-   * Asserts that the target is an instance of `constructor`.
-   *
-   *     var Tea = function (name) { this.name = name; }
-   *       , Chai = new Tea('chai');
-   *
-   *     expect(Chai).to.be.an.instanceof(Tea);
-   *     expect([ 1, 2, 3 ]).to.be.instanceof(Array);
-   *
-   * @name instanceof
-   * @param {Constructor} constructor
-   * @param {String} message _optional_
-   * @alias instanceOf
-   * @api public
-   */
-
-  function assertInstanceOf (constructor, msg) {
-    if (msg) flag(this, 'message', msg);
-    var name = _.getName(constructor);
-    this.assert(
-        flag(this, 'object') instanceof constructor
-      , 'expected #{this} to be an instance of ' + name
-      , 'expected #{this} to not be an instance of ' + name
-    );
-  };
-
-  Assertion.addMethod('instanceof', assertInstanceOf);
-  Assertion.addMethod('instanceOf', assertInstanceOf);
-
-  /**
-   * ### .property(name, [value])
-   *
-   * Asserts that the target has a property `name`, optionally asserting that
-   * the value of that property is strictly equal to  `value`.
-   * If the `deep` flag is set, you can use dot- and bracket-notation for deep
-   * references into objects and arrays.
-   *
-   *     // simple referencing
-   *     var obj = { foo: 'bar' };
-   *     expect(obj).to.have.property('foo');
-   *     expect(obj).to.have.property('foo', 'bar');
-   *
-   *     // deep referencing
-   *     var deepObj = {
-   *         green: { tea: 'matcha' }
-   *       , teas: [ 'chai', 'matcha', { tea: 'konacha' } ]
-   *     };
-
-   *     expect(deepObj).to.have.deep.property('green.tea', 'matcha');
-   *     expect(deepObj).to.have.deep.property('teas[1]', 'matcha');
-   *     expect(deepObj).to.have.deep.property('teas[2].tea', 'konacha');
-   *
-   * You can also use an array as the starting point of a `deep.property`
-   * assertion, or traverse nested arrays.
-   *
-   *     var arr = [
-   *         [ 'chai', 'matcha', 'konacha' ]
-   *       , [ { tea: 'chai' }
-   *         , { tea: 'matcha' }
-   *         , { tea: 'konacha' } ]
-   *     ];
-   *
-   *     expect(arr).to.have.deep.property('[0][1]', 'matcha');
-   *     expect(arr).to.have.deep.property('[1][2].tea', 'konacha');
-   *
-   * Furthermore, `property` changes the subject of the assertion
-   * to be the value of that property from the original object. This
-   * permits for further chainable assertions on that property.
-   *
-   *     expect(obj).to.have.property('foo')
-   *       .that.is.a('string');
-   *     expect(deepObj).to.have.property('green')
-   *       .that.is.an('object')
-   *       .that.deep.equals({ tea: 'matcha' });
-   *     expect(deepObj).to.have.property('teas')
-   *       .that.is.an('array')
-   *       .with.deep.property('[2]')
-   *         .that.deep.equals({ tea: 'konacha' });
-   *
-   * @name property
-   * @alias deep.property
-   * @param {String} name
-   * @param {Mixed} value (optional)
-   * @param {String} message _optional_
-   * @returns value of property for chaining
-   * @api public
-   */
-
-  Assertion.addMethod('property', function (name, val, msg) {
-    if (msg) flag(this, 'message', msg);
-
-    var descriptor = flag(this, 'deep') ? 'deep property ' : 'property '
-      , negate = flag(this, 'negate')
-      , obj = flag(this, 'object')
-      , value = flag(this, 'deep')
-        ? _.getPathValue(name, obj)
-        : obj[name];
-
-    if (negate && undefined !== val) {
-      if (undefined === value) {
-        msg = (msg != null) ? msg + ': ' : '';
-        throw new Error(msg + _.inspect(obj) + ' has no ' + descriptor + _.inspect(name));
-      }
-    } else {
-      this.assert(
-          undefined !== value
-        , 'expected #{this} to have a ' + descriptor + _.inspect(name)
-        , 'expected #{this} to not have ' + descriptor + _.inspect(name));
-    }
-
-    if (undefined !== val) {
-      this.assert(
-          val === value
-        , 'expected #{this} to have a ' + descriptor + _.inspect(name) + ' of #{exp}, but got #{act}'
-        , 'expected #{this} to not have a ' + descriptor + _.inspect(name) + ' of #{act}'
-        , val
-        , value
-      );
-    }
-
-    flag(this, 'object', value);
-  });
-
-
-  /**
-   * ### .ownProperty(name)
-   *
-   * Asserts that the target has an own property `name`.
-   *
-   *     expect('test').to.have.ownProperty('length');
-   *
-   * @name ownProperty
-   * @alias haveOwnProperty
-   * @param {String} name
-   * @param {String} message _optional_
-   * @api public
-   */
-
-  function assertOwnProperty (name, msg) {
-    if (msg) flag(this, 'message', msg);
-    var obj = flag(this, 'object');
-    this.assert(
-        obj.hasOwnProperty(name)
-      , 'expected #{this} to have own property ' + _.inspect(name)
-      , 'expected #{this} to not have own property ' + _.inspect(name)
-    );
-  }
-
-  Assertion.addMethod('ownProperty', assertOwnProperty);
-  Assertion.addMethod('haveOwnProperty', assertOwnProperty);
-
-  /**
-   * ### .length(value)
-   *
-   * Asserts that the target's `length` property has
-   * the expected value.
-   *
-   *     expect([ 1, 2, 3]).to.have.length(3);
-   *     expect('foobar').to.have.length(6);
-   *
-   * Can also be used as a chain precursor to a value
-   * comparison for the length property.
-   *
-   *     expect('foo').to.have.length.above(2);
-   *     expect([ 1, 2, 3 ]).to.have.length.above(2);
-   *     expect('foo').to.have.length.below(4);
-   *     expect([ 1, 2, 3 ]).to.have.length.below(4);
-   *     expect('foo').to.have.length.within(2,4);
-   *     expect([ 1, 2, 3 ]).to.have.length.within(2,4);
-   *
-   * @name length
-   * @alias lengthOf
-   * @param {Number} length
-   * @param {String} message _optional_
-   * @api public
-   */
-
-  function assertLengthChain () {
-    flag(this, 'doLength', true);
-  }
-
-  function assertLength (n, msg) {
-    if (msg) flag(this, 'message', msg);
-    var obj = flag(this, 'object');
-    new Assertion(obj, msg).to.have.property('length');
-    var len = obj.length;
-
-    this.assert(
-        len == n
-      , 'expected #{this} to have a length of #{exp} but got #{act}'
-      , 'expected #{this} to not have a length of #{act}'
-      , n
-      , len
-    );
-  }
-
-  Assertion.addChainableMethod('length', assertLength, assertLengthChain);
-  Assertion.addMethod('lengthOf', assertLength, assertLengthChain);
-
-  /**
-   * ### .match(regexp)
-   *
-   * Asserts that the target matches a regular expression.
-   *
-   *     expect('foobar').to.match(/^foo/);
-   *
-   * @name match
-   * @param {RegExp} RegularExpression
-   * @param {String} message _optional_
-   * @api public
-   */
-
-  Assertion.addMethod('match', function (re, msg) {
-    if (msg) flag(this, 'message', msg);
-    var obj = flag(this, 'object');
-    this.assert(
-        re.exec(obj)
-      , 'expected #{this} to match ' + re
-      , 'expected #{this} not to match ' + re
-    );
-  });
-
-  /**
-   * ### .string(string)
-   *
-   * Asserts that the string target contains another string.
-   *
-   *     expect('foobar').to.have.string('bar');
-   *
-   * @name string
-   * @param {String} string
-   * @param {String} message _optional_
-   * @api public
-   */
-
-  Assertion.addMethod('string', function (str, msg) {
-    if (msg) flag(this, 'message', msg);
-    var obj = flag(this, 'object');
-    new Assertion(obj, msg).is.a('string');
-
-    this.assert(
-        ~obj.indexOf(str)
-      , 'expected #{this} to contain ' + _.inspect(str)
-      , 'expected #{this} to not contain ' + _.inspect(str)
-    );
-  });
-
-
-  /**
-   * ### .keys(key1, [key2], [...])
-   *
-   * Asserts that the target has exactly the given keys, or
-   * asserts the inclusion of some keys when using the
-   * `include` or `contain` modifiers.
-   *
-   *     expect({ foo: 1, bar: 2 }).to.have.keys(['foo', 'bar']);
-   *     expect({ foo: 1, bar: 2, baz: 3 }).to.contain.keys('foo', 'bar');
-   *
-   * @name keys
-   * @alias key
-   * @param {String...|Array} keys
-   * @api public
-   */
-
-  function assertKeys (keys) {
-    var obj = flag(this, 'object')
-      , str
-      , ok = true;
-
-    keys = keys instanceof Array
-      ? keys
-      : Array.prototype.slice.call(arguments);
-
-    if (!keys.length) throw new Error('keys required');
-
-    var actual = Object.keys(obj)
-      , len = keys.length;
-
-    // Inclusion
-    ok = keys.every(function(key){
-      return ~actual.indexOf(key);
-    });
-
-    // Strict
-    if (!flag(this, 'negate') && !flag(this, 'contains')) {
-      ok = ok && keys.length == actual.length;
-    }
-
-    // Key string
-    if (len > 1) {
-      keys = keys.map(function(key){
-        return _.inspect(key);
-      });
-      var last = keys.pop();
-      str = keys.join(', ') + ', and ' + last;
-    } else {
-      str = _.inspect(keys[0]);
-    }
-
-    // Form
-    str = (len > 1 ? 'keys ' : 'key ') + str;
-
-    // Have / include
-    str = (flag(this, 'contains') ? 'contain ' : 'have ') + str;
-
-    // Assertion
-    this.assert(
-        ok
-      , 'expected #{this} to ' + str
-      , 'expected #{this} to not ' + str
-    );
-  }
-
-  Assertion.addMethod('keys', assertKeys);
-  Assertion.addMethod('key', assertKeys);
-
-  /**
-   * ### .throw(constructor)
-   *
-   * Asserts that the function target will throw a specific error, or specific type of error
-   * (as determined using `instanceof`), optionally with a RegExp or string inclusion test
-   * for the error's message.
-   *
-   *     var err = new ReferenceError('This is a bad function.');
-   *     var fn = function () { throw err; }
-   *     expect(fn).to.throw(ReferenceError);
-   *     expect(fn).to.throw(Error);
-   *     expect(fn).to.throw(/bad function/);
-   *     expect(fn).to.not.throw('good function');
-   *     expect(fn).to.throw(ReferenceError, /bad function/);
-   *     expect(fn).to.throw(err);
-   *     expect(fn).to.not.throw(new RangeError('Out of range.'));
-   *
-   * Please note that when a throw expectation is negated, it will check each
-   * parameter independently, starting with error constructor type. The appropriate way
-   * to check for the existence of a type of error but for a message that does not match
-   * is to use `and`.
-   *
-   *     expect(fn).to.throw(ReferenceError)
-   *        .and.not.throw(/good function/);
-   *
-   * @name throw
-   * @alias throws
-   * @alias Throw
-   * @param {ErrorConstructor} constructor
-   * @param {String|RegExp} expected error message
-   * @param {String} message _optional_
-   * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types
-   * @api public
-   */
-
-  function assertThrows (constructor, errMsg, msg) {
-    if (msg) flag(this, 'message', msg);
-    var obj = flag(this, 'object');
-    new Assertion(obj, msg).is.a('function');
-
-    var thrown = false
-      , desiredError = null
-      , name = null
-      , thrownError = null;
-
-    if (arguments.length === 0) {
-      errMsg = null;
-      constructor = null;
-    } else if (constructor && (constructor instanceof RegExp || 'string' === typeof constructor)) {
-      errMsg = constructor;
-      constructor = null;
-    } else if (constructor && constructor instanceof Error) {
-      desiredError = constructor;
-      constructor = null;
-      errMsg = null;
-    } else if (typeof constructor === 'function') {
-      name = (new constructor()).name;
-    } else {
-      constructor = null;
-    }
-
-    try {
-      obj();
-    } catch (err) {
-      // first, check desired error
-      if (desiredError) {
-        this.assert(
-            err === desiredError
-          , 'expected #{this} to throw #{exp} but #{act} was thrown'
-          , 'expected #{this} to not throw #{exp}'
-          , desiredError
-          , err
-        );
-
-        return this;
-      }
-      // next, check constructor
-      if (constructor) {
-        this.assert(
-            err instanceof constructor
-          , 'expected #{this} to throw #{exp} but #{act} was thrown'
-          , 'expected #{this} to not throw #{exp} but #{act} was thrown'
-          , name
-          , err
-        );
-
-        if (!errMsg) return this;
-      }
-      // next, check message
-      var message = 'object' === _.type(err) && "message" in err
-        ? err.message
-        : '' + err;
-
-      if ((message != null) && errMsg && errMsg instanceof RegExp) {
-        this.assert(
-            errMsg.exec(message)
-          , 'expected #{this} to throw error matching #{exp} but got #{act}'
-          , 'expected #{this} to throw error not matching #{exp}'
-          , errMsg
-          , message
-        );
-
-        return this;
-      } else if ((message != null) && errMsg && 'string' === typeof errMsg) {
-        this.assert(
-            ~message.indexOf(errMsg)
-          , 'expected #{this} to throw error including #{exp} but got #{act}'
-          , 'expected #{this} to throw error not including #{act}'
-          , errMsg
-          , message
-        );
-
-        return this;
-      } else {
-        thrown = true;
-        thrownError = err;
-      }
-    }
-
-    var actuallyGot = ''
-      , expectedThrown = name !== null
-        ? name
-        : desiredError
-          ? '#{exp}' //_.inspect(desiredError)
-          : 'an error';
-
-    if (thrown) {
-      actuallyGot = ' but #{act} was thrown'
-    }
-
-    this.assert(
-        thrown === true
-      , 'expected #{this} to throw ' + expectedThrown + actuallyGot
-      , 'expected #{this} to not throw ' + expectedThrown + actuallyGot
-      , desiredError
-      , thrownError
-    );
-  };
-
-  Assertion.addMethod('throw', assertThrows);
-  Assertion.addMethod('throws', assertThrows);
-  Assertion.addMethod('Throw', assertThrows);
-
-  /**
-   * ### .respondTo(method)
-   *
-   * Asserts that the object or class target will respond to a method.
-   *
-   *     Klass.prototype.bar = function(){};
-   *     expect(Klass).to.respondTo('bar');
-   *     expect(obj).to.respondTo('bar');
-   *
-   * To check if a constructor will respond to a static function,
-   * set the `itself` flag.
-   *
-   *    Klass.baz = function(){};
-   *    expect(Klass).itself.to.respondTo('baz');
-   *
-   * @name respondTo
-   * @param {String} method
-   * @param {String} message _optional_
-   * @api public
-   */
-
-  Assertion.addMethod('respondTo', function (method, msg) {
-    if (msg) flag(this, 'message', msg);
-    var obj = flag(this, 'object')
-      , itself = flag(this, 'itself')
-      , context = ('function' === _.type(obj) && !itself)
-        ? obj.prototype[method]
-        : obj[method];
-
-    this.assert(
-        'function' === typeof context
-      , 'expected #{this} to respond to ' + _.inspect(method)
-      , 'expected #{this} to not respond to ' + _.inspect(method)
-    );
-  });
-
-  /**
-   * ### .itself
-   *
-   * Sets the `itself` flag, later used by the `respondTo` assertion.
-   *
-   *    function Foo() {}
-   *    Foo.bar = function() {}
-   *    Foo.prototype.baz = function() {}
-   *
-   *    expect(Foo).itself.to.respondTo('bar');
-   *    expect(Foo).itself.not.to.respondTo('baz');
-   *
-   * @name itself
-   * @api public
-   */
-
-  Assertion.addProperty('itself', function () {
-    flag(this, 'itself', true);
-  });
-
-  /**
-   * ### .satisfy(method)
-   *
-   * Asserts that the target passes a given truth test.
-   *
-   *     expect(1).to.satisfy(function(num) { return num > 0; });
-   *
-   * @name satisfy
-   * @param {Function} matcher
-   * @param {String} message _optional_
-   * @api public
-   */
-
-  Assertion.addMethod('satisfy', function (matcher, msg) {
-    if (msg) flag(this, 'message', msg);
-    var obj = flag(this, 'object');
-    this.assert(
-        matcher(obj)
-      , 'expected #{this} to satisfy ' + _.objDisplay(matcher)
-      , 'expected #{this} to not satisfy' + _.objDisplay(matcher)
-      , this.negate ? false : true
-      , matcher(obj)
-    );
-  });
-
-  /**
-   * ### .closeTo(expected, delta)
-   *
-   * Asserts that the target is equal `expected`, to within a +/- `delta` range.
-   *
-   *     expect(1.5).to.be.closeTo(1, 0.5);
-   *
-   * @name closeTo
-   * @param {Number} expected
-   * @param {Number} delta
-   * @param {String} message _optional_
-   * @api public
-   */
-
-  Assertion.addMethod('closeTo', function (expected, delta, msg) {
-    if (msg) flag(this, 'message', msg);
-    var obj = flag(this, 'object');
-    this.assert(
-        Math.abs(obj - expected) <= delta
-      , 'expected #{this} to be close to ' + expected + ' +/- ' + delta
-      , 'expected #{this} not to be close to ' + expected + ' +/- ' + delta
-    );
-  });
-
-  function isSubsetOf(subset, superset) {
-    return subset.every(function(elem) {
-      return superset.indexOf(elem) !== -1;
-    })
-  }
-
-  /**
-   * ### .members(set)
-   *
-   * Asserts that the target is a superset of `set`,
-   * or that the target and `set` have the same members.
-   *
-   *     expect([1, 2, 3]).to.include.members([3, 2]);
-   *     expect([1, 2, 3]).to.not.include.members([3, 2, 8]);
-   *
-   *     expect([4, 2]).to.have.members([2, 4]);
-   *     expect([5, 2]).to.not.have.members([5, 2, 1]);
-   *
-   * @name members
-   * @param {Array} set
-   * @param {String} message _optional_
-   * @api public
-   */
-
-  Assertion.addMethod('members', function (subset, msg) {
-    if (msg) flag(this, 'message', msg);
-    var obj = flag(this, 'object');
-
-    new Assertion(obj).to.be.an('array');
-    new Assertion(subset).to.be.an('array');
-
-    if (flag(this, 'contains')) {
-      return this.assert(
-          isSubsetOf(subset, obj)
-        , 'expected #{this} to be a superset of #{act}'
-        , 'expected #{this} to not be a superset of #{act}'
-        , obj
-        , subset
-      );
-    }
-
-    this.assert(
-        isSubsetOf(obj, subset) && isSubsetOf(subset, obj)
-        , 'expected #{this} to have the same members as #{act}'
-        , 'expected #{this} to not have the same members as #{act}'
-        , obj
-        , subset
-    );
-  });
-};
-
-});
-require.register("chai/lib/chai/interface/assert.js", function(exports, require, module){
-/*!
- * chai
- * Copyright(c) 2011-2013 Jake Luer <ja...@alogicalparadox.com>
- * MIT Licensed
- */
-
-
-module.exports = function (chai, util) {
-
-  /*!
-   * Chai dependencies.
-   */
-
-  var Assertion = chai.Assertion
-    , flag = util.flag;
-
-  /*!
-   * Module export.
-   */
-
-  /**
-   * ### assert(expression, message)
-   *
-   * Write your own test expressions.
-   *
-   *     assert('foo' !== 'bar', 'foo is not bar');
-   *     assert(Array.isArray([]), 'empty arrays are arrays');
-   *
-   * @param {Mixed} expression to test for truthiness
-   * @param {String} message to display on error
-   * @name assert
-   * @api public
-   */
-
-  var assert = chai.assert = function (express, errmsg) {
-    var test = new Assertion(null);
-    test.assert(
-        express
-      , errmsg
-      , '[ negation message unavailable ]'
-    );
-  };
-
-  /**
-   * ### .fail(actual, expected, [message], [operator])
-   *
-   * Throw a failure. Node.js `assert` module-compatible.
-   *
-   * @name fail
-   * @param {Mixed} actual
-   * @param {Mixed} expected
-   * @param {String} message
-   * @param {String} operator
-   * @api public
-   */
-
-  assert.fail = function (actual, expected, message, operator) {
-    throw new chai.AssertionError({
-        actual: actual
-      , expected: expected
-      , message: message
-      , operator: operator
-      , stackStartFunction: assert.fail
-    });
-  };
-
-  /**
-   * ### .ok(object, [message])
-   *
-   * Asserts that `object` is truthy.
-   *
-   *     assert.ok('everything', 'everything is ok');
-   *     assert.ok(false, 'this will fail');
-   *
-   * @name ok
-   * @param {Mixed} object to test
-   * @param {String} message
-   * @api public
-   */
-
-  assert.ok = function (val, msg) {
-    new Assertion(val, msg).is.ok;
-  };
-
-  /**
-   * ### .notOk(object, [message])
-   *
-   * Asserts that `object` is falsy.
-   *
-   *     assert.notOk('everything', 'this will fail');
-   *     assert.notOk(false, 'this will pass');
-   *
-   * @name notOk
-   * @param {Mixed} object to test
-   * @param {String} message
-   * @api public
-   */
-
-  assert.notOk = function (val, msg) {
-    new Assertion(val, msg).is.not.ok;
-  };
-
-  /**
-   * ### .equal(actual, expected, [message])
-   *
-   * Asserts non-strict equality (`==`) of `actual` and `expected`.
-   *
-   *     assert.equal(3, '3', '== coerces values to strings');
-   *
-   * @name equal
-   * @param {Mixed} actual
-   * @param {Mixed} expected
-   * @param {String} message
-   * @api public
-   */
-
-  assert.equal = function (act, exp, msg) {
-    var test = new Assertion(act, msg);
-
-    test.assert(
-        exp == flag(test, 'object')
-      , 'expected #{this} to equal #{exp}'
-      , 'expected #{this} to not equal #{act}'
-      , exp
-      , act
-    );
-  };
-
-  /**
-   * ### .notEqual(actual, expected, [message])
-   *
-   * Asserts non-strict inequality (`!=`) of `actual` and `expected`.
-   *
-   *     assert.notEqual(3, 4, 'these numbers are not equal');
-   *
-   * @name notEqual
-   * @param {Mixed} actual
-   * @param {Mixed} expected
-   * @param {String} message
-   * @api public
-   */
-
-  assert.notEqual = function (act, exp, msg) {
-    var test = new Assertion(act, msg);
-
-    test.assert(
-        exp != flag(test, 'object')
-      , 'expected #{this} to not equal #{exp}'
-      , 'expected #{this} to equal #{act}'
-      , exp
-      , act
-    );
-  };
-
-  /**
-   * ### .strictEqual(actual, expected, [message])
-   *
-   * Asserts strict equality (`===`) of `actual` and `expected`.
-   *
-   *     assert.strictEqual(true, true, 'these booleans are strictly equal');
-   *
-   * @name strictEqual
-   * @param {Mixed} actual
-   * @param {Mixed} expected
-   * @param {String} message
-   * @api public
-   */
-
-  assert.strictEqual = function (act, exp, msg) {
-    new Assertion(act, msg).to.equal(exp);
-  };
-
-  /**
-   * ### .notStrictEqual(actual, expected, [message])
-   *
-   * Asserts strict inequality (`!==`) of `actual` and `expected`.
-   *
-   *     assert.notStrictEqual(3, '3', 'no coercion for strict equality');
-   *
-   * @name notStrictEqual
-   * @param {Mixed} actual
-   * @param {Mixed} expected
-   * @param {String} message
-   * @api public
-   */
-
-  assert.notStrictEqual = function (act, exp, msg) {
-    new Assertion(act, msg).to.not.equal(exp);
-  };
-
-  /**
-   * ### .deepEqual(actual, expected, [message])
-   *
-   * Asserts that `actual` is deeply equal to `expected`.
-   *
-   *     assert.deepEqual({ tea: 'green' }, { tea: 'green' });
-   *
-   * @name deepEqual
-   * @param {Mixed} actual
-   * @param {Mixed} expected
-   * @param {String} message
-   * @api public
-   */
-
-  assert.deepEqual = function (act, exp, msg) {
-    new Assertion(act, msg).to.eql(exp);
-  };
-
-  /**
-   * ### .notDeepEqual(actual, expected, [message])
-   *
-   * Assert that `actual` is not deeply equal to `expected`.
-   *
-   *     assert.notDeepEqual({ tea: 'green' }, { tea: 'jasmine' });
-   *
-   * @name notDeepEqual
-   * @param {Mixed} actual
-   * @param {Mixed} expected
-   * @param {String} message
-   * @api public
-   */
-
-  assert.notDeepEqual = function (act, exp, msg) {
-    new Assertion(act, msg).to.not.eql(exp);
-  };
-
-  /**
-   * ### .isTrue(value, [message])
-   *
-   * Asserts that `value` is true.
-   *
-   *     var teaServed = true;
-   *     assert.isTrue(teaServed, 'the tea has been served');
-   *
-   * @name isTrue
-   * @param {Mixed} value
-   * @param {String} message
-   * @api public
-   */
-
-  assert.isTrue = function (val, msg) {
-    new Assertion(val, msg).is['true'];
-  };
-
-  /**
-   * ### .isFalse(value, [message])
-   *
-   * Asserts that `value` is false.
-   *
-   *     var teaServed = false;
-   *     assert.isFalse(teaServed, 'no tea yet? hmm...');
-   *
-   * @name isFalse
-   * @param {Mixed} value
-   * @param {String} message
-   * @api public
-   */
-
-  assert.isFalse = function (val, msg) {
-    new Assertion(val, msg).is['false'];
-  };
-
-  /**
-   * ### .isNull(value, [message])
-   *
-   * Asserts that `value` is null.
-   *
-   *     assert.isNull(err, 'there was no error');
-   *
-   * @name isNull
-   * @param {Mixed} value
-   * @param {String} message
-   * @api public
-   */
-
-  assert.isNull = function (val, msg) {
-    new Assertion(val, msg).to.equal(null);
-  };
-
-  /**
-   * ### .isNotNull(value, [message])
-   *
-   * Asserts that `value` is not null.
-   *
-   *     var tea = 'tasty chai';
-   *     assert.isNotNull(tea, 'great, time for tea!');
-   *
-   * @name isNotNull
-   * @param {Mixed} value
-   * @param {String} message
-   * @api public
-   */
-
-  assert.isNotNull = function (val, msg) {
-    new Assertion(val, msg).to.not.equal(null);
-  };
-
-  /**
-   * ### .isUndefined(value, [message])
-   *
-   * Asserts that `value` is `undefined`.
-   *
-   *     var tea;
-   *     assert.isUndefined(tea, 'no tea defined');
-   *
-   * @name isUndefined
-   * @param {Mixed} value
-   * @param {String} message
-   * @api public
-   */
-
-  assert.isUndefined = function (val, msg) {
-    new Assertion(val, msg).to.equal(undefined);
-  };
-
-  /**
-   * ### .isDefined(value, [message])
-   *
-   * Asserts that `value` is not `undefined`.
-   *
-   *     var tea = 'cup of chai';
-   *     assert.isDefined(tea, 'tea has been defined');
-   *
-   * @name isDefined
-   * @param {Mixed} value
-   * @param {String} message
-   * @api public
-   */
-
-  assert.isDefined = function (val, msg) {
-    new Assertion(val, msg).to.not.equal(undefined);
-  };
-
-  /**
-   * ### .isFunction(value, [message])
-   *
-   * Asserts that `value` is a function.
-   *
-   *     function serveTea() { return 'cup of tea'; };
-   *     assert.isFunction(serveTea, 'great, we can have tea now');
-   *
-   * @name isFunction
-   * @param {Mixed} value
-   * @param {String} message
-   * @api public
-   */
-
-  assert.isFunction = function (val, msg) {
-    new Assertion(val, msg).to.be.a('function');
-  };
-
-  /**
-   * ### .isNotFunction(value, [message])
-   *
-   * Asserts that `value` is _not_ a function.
-   *
-   *     var serveTea = [ 'heat', 'pour', 'sip' ];
-   *     assert.isNotFunction(serveTea, 'great, we have listed the steps');
-   *
-   * @name isNotFunction
-   * @param {Mixed} value
-   * @param {String} message
-   * @api public
-   */
-
-  assert.isNotFunction = function (val, msg) {
-    new Assertion(val, msg).to.not.be.a('function');
-  };
-
-  /**
-   * ### .isObject(value, [message])
-   *
-   * Asserts that `value` is an object (as revealed by
-   * `Object.prototype.toString`).
-   *
-   *     var selection = { name: 'Chai', serve: 'with spices' };
-   *     assert.isObject(selection, 'tea selection is an object');
-   *
-   * @name isObject
-   * @param {Mixed} value
-   * @param {String} message
-   * @api public
-   */
-
-  assert.isObject = function (val, msg) {
-    new Assertion(val, msg).to.be.a('object');
-  };
-
-  /**
-   * ### .isNotObject(value, [message])
-   *
-   * Asserts that `value` is _not_ an object.
-   *
-   *     var selection = 'chai'
-   *     assert.isObject(selection, 'tea selection is not an object');
-   *     assert.isObject(null, 'null is not an object');
-   *
-   * @name isNotObject
-   * @param {Mixed} value
-   * @param {String} message
-   * @api public
-   */
-
-  assert.isNotObject = function (val, msg) {
-    new Assertion(val, msg).to.not.be.a('object');
-  };
-
-  /**
-   * ### .isArray(value, [message])
-   *
-   * Asserts that `value` is an array.
-   *
-   *     var menu = [ 'green', 'chai', 'oolong' ];
-   *     assert.isArray(menu, 'what kind of tea do we want?');
-   *
-   * @name isArray
-   * @param {Mixed} value
-   * @param {String} message
-   * @api public
-   */
-
-  assert.isArray = function (val, msg) {
-    new Assertion(val, msg).to.be.an('array');
-  };
-
-  /**
-   * ### .isNotArray(value, [message])
-   *
-   * Asserts that `value` is _not_ an array.
-   *
-   *     var menu = 'green|chai|oolong';
-   *     assert.isNotArray(menu, 'what kind of tea do we want?');
-   *
-   * @name isNotArray
-   * @param {Mixed} value
-   * @param {String} message
-   * @api public
-   */
-
-  assert.isNotArray = function (val, msg) {
-    new Assertion(val, msg).to.not.be.an('array');
-  };
-
-  /**
-   * ### .isString(value, [message])
-   *
-   * Asserts that `value` is a string.
-   *
-   *     var teaOrder = 'chai';
-   *     assert.isString(teaOrder, 'order placed');
-   *
-   * @name isString
-   * @param {Mixed} value
-   * @param {String} message
-   * @api public
-   */
-
-  assert.isString = function (val, msg) {
-    new Assertion(val, msg).to.be.a('string');
-  };
-
-  /**
-   * ### .isNotString(value, [message])
-   *
-   * Asserts that `value` is _not_ a string.
-   *
-   *     var teaOrder = 4;
-   *     assert.isNotString(teaOrder, 'order placed');
-   *
-   * @name isNotString
-   * @param {Mixed} value
-   * @param {String} message
-   * @api public
-   */
-
-  assert.isNotString = function (val, msg) {
-    new Assertion(val, msg).to.not.be.a('string');
-  };
-
-  /**
-   * ### .isNumber(value, [message])
-   *
-   * Asserts that `value` is a number.
-   *
-   *     var cups = 2;
-   *     assert.isNumber(cups, 'how many cups');
-   *
-   * @name isNumber
-   * @param {Number} value
-   * @param {String} message
-   * @api public
-   */
-
-  assert.isNumber = function (val, msg) {
-    new Assertion(val, msg).to.be.a('number');
-  };
-
-  /**
-   * ### .isNotNumber(value, [message])
-   *
-   * Asserts that `value` is _not_ a number.
-   *
-   *     var cups = '2 cups please';
-   *     assert.isNotNumber(cups, 'how many cups');
-   *
-   * @name isNotNumber
-   * @param {Mixed} value
-   * @param {String} message
-   * @api public
-   */
-
-  assert.isNotNumber = function (val, msg) {
-    new Assertion(val, msg).to.not.be.a('number');
-  };
-
-  /**
-   * ### .isBoolean(value, [message])
-   *
-   * Asserts that `value` is a boolean.
-   *
-   *     var teaReady = true
-   *       , teaServed = false;
-   *
-   *     assert.isBoolean(teaReady, 'is the tea ready');
-   *     assert.isBoolean(teaServed, 'has tea been served');
-   *
-   * @name isBoolean
-   * @param {Mixed} value
-   * @param {String} message
-   * @api public
-   */
-
-  assert.isBoolean = function (val, msg) {
-    new Assertion(val, msg).to.be.a('boolean');
-  };
-
-  /**
-   * ### .isNotBoolean(value, [message])
-   *
-   * Asserts that `value` is _not_ a boolean.
-   *
-   *     var teaReady = 'yep'
-   *       , teaServed = 'nope';
-   *
-   *     assert.isNotBoolean(teaReady, 'is the tea ready');
-   *     assert.isNotBoolean(teaServed, 'has tea been served');
-   *
-   * @name isNotBoolean
-   * @param {Mixed} value
-   * @param {String} message
-   * @api public
-   */
-
-  assert.isNotBoolean = function (val, msg) {
-    new Assertion(val, msg).to.not.be.a('boolean');
-  };
-
-  /**
-   * ### .typeOf(value, name, [message])
-   *
-   * Asserts that `value`'s type is `name`, as determined by
-   * `Object.prototype.toString`.
-   *
-   *     assert.typeOf({ tea: 'chai' }, 'object', 'we have an object');
-   *     assert.typeOf(['chai', 'jasmine'], 'array', 'we have an array');
-   *     assert.typeOf('tea', 'string', 'we have a string');
-   *     assert.typeOf(/tea/, 'regexp', 'we have a regular expression');
-   *     assert.typeOf(null, 'null', 'we have a null');
-   *     assert.typeOf(undefined, 'undefined', 'we have an undefined');
-   *
-   * @name typeOf
-   * @param {Mixed} value
-   * @param {String} name
-   * @param {String} message
-   * @api public
-   */
-
-  assert.typeOf = function (val, type, msg) {
-    new Assertion(val, msg).to.be.a(type);
-  };
-
-  /**
-   * ### .notTypeOf(value, name, [message])
-   *
-   * Asserts that `value`'s type is _not_ `name`, as determined by
-   * `Object.prototype.toString`.
-   *
-   *     assert.notTypeOf('tea', 'number', 'strings are not numbers');
-   *
-   * @name notTypeOf
-   * @param {Mixed} value
-   * @param {String} typeof name
-   * @param {String} message
-   * @api public
-   */
-
-  assert.notTypeOf = function (val, type, msg) {
-    new Assertion(val, msg).to.not.be.a(type);
-  };
-
-  /**
-   * ### .instanceOf(object, constructor, [message])
-   *
-   * Asserts that `value` is an instance of `constructor`.
-   *
-   *     var Tea = function (name) { this.name = name; }
-   *       , chai = new Tea('chai');
-   *
-   *     assert.instanceOf(chai, Tea, 'chai is an instance of tea');
-   *
-   * @name instanceOf
-   * @param {Object} object
-   * @param {Constructor} constructor
-   * @param {String} message
-   * @api public
-   */
-
-  assert.instanceOf = function (val, type, msg) {
-    new Assertion(val, msg).to.be.instanceOf(type);
-  };
-
-  /**
-   * ### .notInstanceOf(object, constructor, [message])
-   *
-   * Asserts `value` is not an instance of `constructor`.
-   *
-   *     var Tea = function (name) { this.name = name; }
-   *       , chai = new String('chai');
-   *
-   *     assert.notInstanceOf(chai, Tea, 'chai is not an instance of tea');
-   *
-   * @name notInstanceOf
-   * @param {Object} object
-   * @param {Constructor} constructor
-   * @param {String} message
-   * @api public
-   */
-
-  assert.notInstanceOf = function (val, type, msg) {
-    new Assertion(val, msg).to.not.be.instanceOf(type);
-  };
-
-  /**
-   * ### .include(haystack, needle, [message])
-   *
-   * Asserts that `haystack` includes `needle`. Works
-   * for strings and arrays.
-   *
-   *     assert.include('foobar', 'bar', 'foobar contains string "bar"');
-   *     assert.include([ 1, 2, 3 ], 3, 'array contains value');
-   *
-   * @name include
-   * @param {Array|String} haystack
-   * @param {Mixed} needle
-   * @param {String} message
-   * @api public
-   */
-
-  assert.include = function (exp, inc, msg) {
-    var obj = new Assertion(exp, msg);
-
-    if (Array.isArray(exp)) {
-      obj.to.include(inc);
-    } else if ('string' === typeof exp) {
-      obj.to.contain.string(inc);
-    } else {
-      throw new chai.AssertionError(
-          'expected an array or string'
-        , null
-        , assert.include
-      );
-    }
-  };
-
-  /**
-   * ### .notInclude(haystack, needle, [message])
-   *
-   * Asserts that `haystack` does not include `needle`. Works
-   * for strings and arrays.
-   *i
-   *     assert.notInclude('foobar', 'baz', 'string not include substring');
-   *     assert.notInclude([ 1, 2, 3 ], 4, 'array not include contain value');
-   *
-   * @name notInclude
-   * @param {Array|String} haystack
-   * @param {Mixed} needle
-   * @param {String} message
-   * @api public
-   */
-
-  assert.notInclude = function (exp, inc, msg) {
-    var obj = new Assertion(exp, msg);
-
-    if (Array.isArray(exp)) {
-      obj.to.not.include(inc);
-    } else if ('string' === typeof exp) {
-      obj.to.not.contain.string(inc);
-    } else {
-      throw new chai.AssertionError(
-          'expected an array or string'
-        , null
-        , assert.notInclude
-      );
-    }
-  };
-
-  /**
-   * ### .match(value, regexp, [message])
-   *
-   * Asserts that `value` matches the regular expression `regexp`.
-   *
-   *     assert.match('foobar', /^foo/, 'regexp matches');
-   *
-   * @name match
-   * @param {Mixed} value
-   * @param {RegExp} regexp
-   * @param {String} message
-   * @api public
-   */
-
-  assert.match = function (exp, re, msg) {
-    new Assertion(exp, msg).to.match(re);
-  };
-
-  /**
-   * ### .notMatch(value, regexp, [message])
-   *
-   * Asserts that `value` does not match the regular expression `regexp`.
-   *
-   *     assert.notMatch('foobar', /^foo/, 'regexp does not match');
-   *
-   * @name notMatch
-   * @param {Mixed} value
-   * @param {RegExp} regexp
-   * @param {String} message
-   * @api public
-   */
-
-  assert.notMatch = function (exp, re, msg) {
-    new Assertion(exp, msg).to.not.match(re);
-  };
-
-  /**
-   * ### .property(object, property, [message])
-   *
-   * Asserts that `object` has a property named by `property`.
-   *
-   *     assert.property({ tea: { green: 'matcha' }}, 'tea');
-   *
-   * @name property
-   * @param {Object} object
-   * @param {String} property
-   * @param {String} message
-   * @api public
-   */
-
-  assert.property = function (obj, prop, msg) {
-    new Assertion(obj, msg).to.have.property(prop);
-  };
-
-  /**
-   * ### .notProperty(object, property, [message])
-   *
-   * Asserts that `object` does _not_ have a property named by `property`.
-   *
-   *     assert.notProperty({ tea: { green: 'matcha' }}, 'coffee');
-   *
-   * @name notProperty
-   * @param {Object} object
-   * @param {String} property
-   * @param {String} message
-   * @api public
-   */
-
-  assert.notProperty = function (obj, prop, msg) {
-    new Assertion(obj, msg).to.not.have.property(prop);
-  };
-
-  /**
-   * ### .deepProperty(object, property, [message])
-   *
-   * Asserts that `object` has a property named by `property`, which can be a
-   * string using dot- and bracket-notation for deep reference.
-   *
-   *     assert.deepProperty({ tea: { green: 'matcha' }}, 'tea.green');
-   *
-   * @name deepProperty
-   * @param {Object} object
-   * @param {String} property
-   * @param {String} message
-   * @api public
-   */
-
-  assert.deepProperty = function (obj, prop, msg) {
-    new Assertion(obj, msg).to.have.deep.property(prop);
-  };
-
-  /**
-   * ### .notDeepProperty(object, property, [message])
-   *
-   * Asserts that `object` does _not_ have a property named by `property`, which
-   * can be a string using dot- and bracket-notation for deep reference.
-   *
-   *     assert.notDeepProperty({ tea: { green: 'matcha' }}, 'tea.oolong');
-   *
-   * @name notDeepProperty
-   * @param {Object} object
-   * @param {String} property
-   * @param {String} message
-   * @api public
-   */
-
-  assert.notDeepProperty = function (obj, prop, msg) {
-    new Assertion(obj, msg).to.not.have.deep.property(prop);
-  };
-
-  /**
-   * ### .propertyVal(object, property, value, [message])
-   *
-   * Asserts that `object` has a property named by `property` with value given
-   * by `value`.
-   *
-   *     assert.propertyVal({ tea: 'is good' }, 'tea', 'is good');
-   *
-   * @name propertyVal
-   * @param {Object} object
-   * @param {String} property
-   * @param {Mixed} value
-   * @param {String} message
-   * @api public
-   */
-
-  assert.propertyVal = function (obj, prop, val, msg) {
-    new Assertion(obj, msg).to.have.property(prop, val);
-  };
-
-  /**
-   * ### .propertyNotVal(object, property, value, [message])
-   *
-   * Asserts that `object` has a property named by `property`, but with a value
-   * different from that given by `value`.
-   *
-   *     assert.propertyNotVal({ tea: 'is good' }, 'tea', 'is bad');
-   *
-   * @name propertyNotVal
-   * @param {Object} object
-   * @param {String} property
-   * @param {Mixed} value
-   * @param {String} message
-   * @api public
-   */
-
-  assert.propertyNotVal = function (obj, prop, val, msg) {
-    new Assertion(obj, msg).to.not.have.property(prop, val);
-  };
-
-  /**
-   * ### .deepPropertyVal(object, property, value, [message])
-   *
-   * Asserts that `object` has a property named by `property` with value given
-   * by `value`. `property` can use dot- and bracket-notation for deep
-   * reference.
-   *
-   *     assert.deepPropertyVal({ tea: { green: 'matcha' }}, 'tea.green', 'matcha');
-   *
-   * @name deepPropertyVal
-   * @param {Object} object
-   * @param {String} property
-   * @param {Mixed} value
-   * @param {String} message
-   * @api public
-   */
-
-  assert.deepPropertyVal = function (obj, prop, val, msg) {
-    new Assertion(obj, msg).to.have.deep.property(prop, val);
-  };
-
-  /**
-   * ### .deepPropertyNotVal(object, property, value, [message])
-   *
-   * Asserts that `object` has a property named by `property`, but with a value
-   * different from that given by `value`. `property` can use dot- and
-   * bracket-notation for deep reference.
-   *
-   *     assert.deepPropertyNotVal({ tea: { green: 'matcha' }}, 'tea.green', 'konacha');
-   *
-   * @name deepPropertyNotVal
-   * @param {Object} object
-   * @param {String} property
-   * @param {Mixed} value
-   * @param {String} message
-   * @api public
-   */
-
-  assert.deepPropertyNotVal = function (obj, prop, val, msg) {
-    new Assertion(obj, msg).to.not.have.deep.property(prop, val);
-  };
-
-  /**
-   * ### .lengthOf(object, length, [message])
-   *
-   * Asserts that `object` has a `length` property with the expected value.
-   *
-   *     assert.lengthOf([1,2,3], 3, 'array has length of 3');
-   *     assert.lengthOf('foobar', 5, 'string has length of 6');
-   *
-   * @name lengthOf
-   * @param {Mixed} object
-   * @param {Number} length
-   * @param {String} message
-   * @api public
-   */
-
-  assert.lengthOf = function (exp, len, msg) {
-    new Assertion(exp, msg).to.have.length(len);
-  };
-
-  /**
-   * ### .throws(function, [constructor/string/regexp], [string/regexp], [message])
-   *
-   * Asserts that `function` will throw an error that is an instance of
-   * `constructor`, or alternately that it will throw an error with message
-   * matching `regexp`.
-   *
-   *     assert.throw(fn, 'function throws a reference error');
-   *     assert.throw(fn, /function throws a reference error/);
-   *     assert.throw(fn, ReferenceError);
-   *     assert.throw(fn, ReferenceError, 'function throws a reference error');
-   *     assert.throw(fn, ReferenceError, /function throws a reference error/);
-   *
-   * @name throws
-   * @alias throw
-   * @alias Throw
-   * @param {Function} function
-   * @param {ErrorConstructor} constructor
-   * @param {RegExp} regexp
-   * @param {String} message
-   * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types
-   * @api public
-   */
-
-  assert.Throw = function (fn, errt, errs, msg) {
-    if ('string' === typeof errt || errt instanceof RegExp) {
-      errs = errt;
-      errt = null;
-    }
-
-    new Assertion(fn, msg).to.Throw(errt, errs);
-  };
-
-  /**
-   * ### .doesNotThrow(function, [constructor/regexp], [message])
-   *
-   * Asserts that `function` will _not_ throw an error that is an instance of
-   * `constructor`, or alternately that it will not throw an error with message
-   * matching `regexp`.
-   *
-   *     assert.doesNotThrow(fn, Error, 'function does not throw');
-   *
-   * @name doesNotThrow
-   * @param {Function} function
-   * @param {ErrorConstructor} constructor
-   * @param {RegExp} regexp
-   * @param {String} message
-   * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types
-   * @api public
-   */
-
-  assert.doesNotThrow = function (fn, type, msg) {
-    if ('string' === typeof type) {
-      msg = type;
-      type = null;
-    }
-
-    new Assertion(fn, msg).to.not.Throw(type);
-  };
-
-  /**
-   * ### .operator(val1, operator, val2, [message])
-   *
-   * Compares two values using `operator`.
-   *
-   *     assert.operator(1, '<', 2, 'everything is ok');
-   *     assert.operator(1, '>', 2, 'this will fail');
-   *
-   * @name operator
-   * @param {Mixed} val1
-   * @param {String} operator
-   * @param {Mixed} val2
-   * @param {String} message
-   * @api public
-   */
-
-  assert.operator = function (val, operator, val2, msg) {
-    if (!~['==', '===', '>', '>=', '<', '<=', '!=', '!=='].indexOf(operator)) {
-      throw new Error('Invalid operator "' + operator + '"');
-    }
-    var test = new Assertion(eval(val + operator + val2), msg);
-    test.assert(
-        true === flag(test, 'object')
-      , 'expected ' + util.inspect(val) + ' to be ' + operator + ' ' + util.inspect(val2)
-      , 'expected ' + util.inspect(val) + ' to not be ' + operator + ' ' + util.inspect(val2) );
-  };
-
-  /**
-   * ### .closeTo(actual, expected, delta, [message])
-   *
-   * Asserts that the target is equal `expected`, to within a +/- `delta` range.
-   *
-   *     assert.closeTo(1.5, 1, 0.5, 'numbers are close');
-   *
-   * @name closeTo
-   * @param {Number} actual
-   * @param {Number} expected
-   * @param {Number} delta
-   * @param {String} message
-   * @api public
-   */
-
-  assert.closeTo = function (act, exp, delta, msg) {
-    new Assertion(act, msg).to.be.closeTo(exp, delta);
-  };
-
-  /**
-   * ### .sameMembers(set1, set2, [message])
-   *
-   * Asserts that `set1` and `set2` have the same members.
-   * Order is not taken into account.
-   *
-   *     assert.sameMembers([ 1, 2, 3 ], [ 2, 1, 3 ], 'same members');
-   *
-   * @name sameMembers
-   * @param {Array} superset
-   * @param {Array} subset
-   * @param {String} message
-   * @api public
-   */
-
-  assert.sameMembers = function (set1, set2, msg) {
-    new Assertion(set1, msg).to.have.same.members(set2);
-  }
-
-  /**
-   * ### .includeMembers(superset, subset, [message])
-   *
-   * Asserts that `subset` is included in `superset`.
-   * Order is not taken into account.
-   *
-   *     assert.includeMembers([ 1, 2, 3 ], [ 2, 1 ], 'include members');
-   *
-   * @name includeMembers
-   * @param {Array} superset
-   * @param {Array} subset
-   * @param {String} message
-   * @api public
-   */
-
-  assert.includeMembers = function (superset, subset, msg) {
-    new Assertion(superset, msg).to.include.members(subset);
-  }
-
-  /*!
-   * Undocumented / untested
-   */
-
-  assert.ifError = function (val, msg) {
-    new Assertion(val, msg).to.not.be.ok;
-  };
-
-  /*!
-   * Aliases.
-   */
-
-  (function alias(name, as){
-    assert[as] = assert[name];
-    return alias;
-  })
-  ('Throw', 'throw')
-  ('Throw', 'throws');
-};
-
-});
-require.register("chai/lib/chai/interface/expect.js", function(exports, require, module){
-/*!
- * chai
- * Copyright(c) 2011-2013 Jake Luer <ja...@alogicalparadox.com>
- * MIT Licensed
- */
-
-module.exports = function (chai, util) {
-  chai.expect = function (val, message) {
-    return new chai.Assertion(val, message);
-  };
-};
-
-
-});
-require.register("chai/lib/chai/interface/should.js", function(exports, require, module){
-/*!
- * chai
- * Copyright(c) 2011-2013 Jake Luer <ja...@alogicalparadox.com>
- * MIT Licensed
- */
-
-module.exports = function (chai, util) {
-  var Assertion = chai.Assertion;
-
-  function loadShould () {
-    // modify Object.prototype to have `should`
-    Object.defineProperty(Object.prototype, 'should',
-      {
-        set: function (value) {
-          // See https://github.com/chaijs/chai/issues/86: this makes
-          // `whatever.should = someValue` actually set `someValue`, which is
-          // especially useful for `global.should = require('chai').should()`.
-          //
-          // Note that we have to use [[DefineProperty]] instead of [[Put]]
-          // since otherwise we would trigger this very setter!
-          Object.defineProperty(this, 'should', {
-            value: value,
-            enumerable: true,
-            configurable: true,
-            writable: true
-          });
-        }
-      , get: function(){
-          if (this instanceof String || this instanceof Number) {
-            return new Assertion(this.constructor(this));
-          } else if (this instanceof Boolean) {
-            return new Assertion(this == true);
-          }
-          return new Assertion(this);
-        }
-      , configurable: true
-    });
-
-    var should = {};
-
-    should.equal = function (val1, val2, msg) {
-      new Assertion(val1, msg).to.equal(val2);
-    };
-
-    should.Throw = function (fn, errt, errs, msg) {
-      new Assertion(fn, msg).to.Throw(errt, errs);
-    };
-
-    should.exist = function (val, msg) {
-      new Assertion(val, msg).to.exist;
-    }
-
-    // negation
-    should.not = {}
-
-    should.not.equal = function (val1, val2, msg) {
-      new Assertion(val1, msg).to.not.equal(val2);
-    };
-
-    should.not.Throw = function (fn, errt, errs, msg) {
-      new Assertion(fn, msg).to.not.Throw(errt, errs);
-    };
-
-    should.not.exist = function (val, msg) {
-      new Assertion(val, msg).to.not.exist;
-    }
-
-    should['throw'] = should['Throw'];
-    should.not['throw'] = should.not['Throw'];
-
-    return should;
-  };
-
-  chai.should = loadShould;
-  chai.Should = loadShould;
-};
-
-});
-require.register("chai/lib/chai/utils/addChainableMethod.js", function(exports, require, module){
-/*!
- * Chai - addChainingMethod utility
- * Copyright(c) 2012-2013 Jake Luer <ja...@alogicalparadox.com>
- * MIT Licensed
- */
-
-/*!
- * Module dependencies
- */
-
-var transferFlags = require('./transferFlags');
-
-/*!
- * Module variables
- */
-
-// Check whether `__proto__` is supported
-var hasProtoSupport = '__proto__' in Object;
-
-// Without `__proto__` support, this module will need to add properties to a function.
-// However, some Function.prototype methods cannot be overwritten,
-// and there seems no easy cross-platform way to detect them (@see chaijs/chai/issues/69).
-var excludeNames = /^(?:length|name|arguments|caller)$/;
-
-// Cache `Function` properties
-var call  = Function.prototype.call,
-    apply = Function.prototype.apply;
-
-/**
- * ### addChainableMethod (ctx, name, method, chainingBehavior)
- *
- * Adds a method to an object, such that the method can also be chained.
- *
- *     utils.addChainableMethod(chai.Assertion.prototype, 'foo', function (str) {
- *       var obj = utils.flag(this, 'object');
- *       new chai.Assertion(obj).to.be.equal(str);
- *     });
- *
- * Can also be accessed directly from `chai.Assertion`.
- *
- *     chai.Assertion.addChainableMethod('foo', fn, chainingBehavior);
- *
- * The result can then be used as both a method assertion, executing both `method` and
- * `chainingBehavior`, or as a language chain, which only executes `chainingBehavior`.
- *
- *     expect(fooStr).to.be.foo('bar');
- *     expect(fooStr).to.be.foo.equal('foo');
- *
- * @param {Object} ctx object to which the method is added
- * @param {String} name of method to add
- * @param {Function} method function to be used for `name`, when called
- * @param {Function} chainingBehavior function to be called every time the property is accessed
- * @name addChainableMethod
- * @api public
- */
-
-module.exports = function (ctx, name, method, chainingBehavior) {
-  if (typeof chainingBehavior !== 'function')
-    chainingBehavior = function () { };
-
-  Object.defineProperty(ctx, name,
-    { get: function () {
-        chainingBehavior.call(this);
-
-        var assert = function () {
-          var result = method.apply(this, arguments);
-          return result === undefined ? this : result;
-        };
-
-        // Use `__proto__` if available
-        if (hasProtoSupport) {
-          // Inherit all properties from the object by replacing the `Function` prototype
-          var prototype = assert.__proto__ = Object.create(this);
-          // Restore the `call` and `apply` methods from `Function`
-          prototype.call = call;
-          prototype.apply = apply;
-        }
-        // Otherwise, redefine all properties (slow!)
-        else {
-          var asserterNames = Object.getOwnPropertyNames(ctx);
-          asserterNames.forEach(function (asserterName) {
-            if (!excludeNames.test(asserterName)) {
-              var pd = Object.getOwnPropertyDescriptor(ctx, asserterName);
-              Object.defineProperty(assert, asserterName, pd);
-            }
-          });
-        }
-
-        transferFlags(this, assert);
-        return assert;
-      }
-    , configurable: true
-  });
-};
-
-});
-require.register("chai/lib/chai/utils/addMethod.js", function(exports, require, module){
-/*!
- * Chai - addMethod utility
- * Copyright(c) 2012-2013 Jake Luer <ja...@alogicalparadox.com>
- * MIT Licensed
- */
-
-/**
- * ### .addMethod (ctx, name, method)
- *
- * Adds a method to the prototype of an object.
- *
- *     utils.addMethod(chai.Assertion.prototype, 'foo', function (str) {
- *       var obj = utils.flag(this, 'object');
- *       new chai.Assertion(obj).to.be.equal(str);
- *     });
- *
- * Can also be accessed directly from `chai.Assertion`.
- *
- *     chai.Assertion.addMethod('foo', fn);
- *
- * Then can be used as any other assertion.
- *
- *     expect(fooStr).to.be.foo('bar');
- *
- * @param {Object} ctx object to which the method is added
- * @param {String} name of method to add
- * @param {Function} method function to be used for name
- * @name addMethod
- * @api public
- */
-
-module.exports = function (ctx, name, method) {
-  ctx[name] = function () {
-    var result = method.apply(this, arguments);
-    return result === undefined ? this : result;
-  };
-};
-
-});
-require.register("chai/lib/chai/utils/addProperty.js", function(exports, require, module){
-/*!
- * Chai - addProperty utility
- * Copyright(c) 2012-2013 Jake Luer <ja...@alogicalparadox.com>
- * MIT Licensed
- */
-
-/**
- * ### addProperty (ctx, name, getter)
- *
- * Adds a property to the prototype of an object.
- *
- *     utils.addProperty(chai.Assertion.prototype, 'foo', function () {
- *       var obj = utils.flag(this, 'object');
- *       new chai.Assertion(obj).to.be.instanceof(Foo);
- *     });
- *
- * Can also be accessed directly from `chai.Assertion`.
- *
- *     chai.Assertion.addProperty('foo', fn);
- *
- * Then can be used as any other assertion.
- *
- *     expect(myFoo).to.be.foo;
- *
- * @param {Object} ctx object to which the property is added
- * @param {String} name of property to add
- * @param {Function} getter function to be used for name
- * @name addProperty
- * @api public
- */
-
-module.exports = function (ctx, name, getter) {
-  Object.defineProperty(ctx, name,
-    { get: function () {
-        var result = getter.call(this);
-        return result === undefined ? this : result;
-      }
-    , configurable: true
-  });
-};
-
-});
-require.register("chai/lib/chai/utils/eql.js", function(exports, require, module){
-// This is (almost) directly from Node.js assert
-// https://github.com/joyent/node/blob/f8c335d0caf47f16d31413f89aa28eda3878e3aa/lib/assert.js
-
-module.exports = _deepEqual;
-
-var getEnumerableProperties = require('./getEnumerableProperties');
-
-// for the browser
-var Buffer;
-try {
-  Buffer = require('buffer').Buffer;
-} catch (ex) {
-  Buffer = {
-    isBuffer: function () { return false; }
-  };
-}
-
-function _deepEqual(actual, expected, memos) {
-
-  // 7.1. All identical values are equivalent, as determined by ===.
-  if (actual === expected) {
-    return true;
-
-  } else if (Buffer.isBuffer(actual) && Buffer.isBuffer(expected)) {
-    if (actual.length != expected.length) return false;
-
-    for (var i = 0; i < actual.length; i++) {
-      if (actual[i] !== expected[i]) return false;
-    }
-
-    return true;
-
-  // 7.2. If the expected value is a Date object, the actual value is
-  // equivalent if it is also a Date object that refers to the same time.
-  } else if (expected instanceof Date) {
-    if (!(actual instanceof Date)) return false;
-    return actual.getTime() === expected.getTime();
-
-  // 7.3. Other pairs that do not both pass typeof value == 'object',
-  // equivalence is determined by ==.
-  } else if (typeof actual != 'object' && typeof expected != 'object') {
-    return actual === expected;
-
-  } else if (expected instanceof RegExp) {
-    if (!(actual instanceof RegExp)) return false;
-    return actual.toString() === expected.toString();
-
-  // 7.4. For all other Object pairs, including Array objects, equivalence is
-  // determined by having the same number of owned properties (as verified
-  // with Object.prototype.hasOwnProperty.call), the same set of keys
-  // (although not necessarily the same order), equivalent values for every
-  // corresponding key, and an identical 'prototype' property. Note: this
-  // accounts for both named and indexed properties on Arrays.
-  } else {
-    return objEquiv(actual, expected, memos);
-  }
-}
-
-function isUndefinedOrNull(value) {
-  return value === null || value === undefined;
-}
-
-function isArguments(object) {
-  return Object.prototype.toString.call(object) == '[object Arguments]';
-}
-
-function objEquiv(a, b, memos) {
-  if (isUndefinedOrNull(a) || isUndefinedOrNull(b))
-    return false;
-
-  // an identical 'prototype' property.
-  if (a.prototype !== b.prototype) return false;
-
-  // check if we have already compared a and b
-  var i;
-  if (memos) {
-    for(i = 0; i < memos.length; i++) {
-      if ((memos[i][0] === a && memos[i][1] === b) ||
-          (memos[i][0] === b && memos[i][1] === a))
-        return true;
-    }
-  } else {
-    memos = [];
-  }
-
-  //~~~I've managed to break Object.keys through screwy arguments passing.
-  //   Converting to array solves the problem.
-  if (isArguments(a)) {
-    if (!isArguments(b)) {
-      return false;
-    }
-    a = pSlice.call(a);
-    b = pSlice.call(b);
-    return _deepEqual(a, b, memos);
-  }
-  try {
-    var ka = getEnumerableProperties(a),
-        kb = getEnumerableProperties(b),
-        key;
-  } catch (e) {//happens when one is a string literal and the other isn't
-    return false;
-  }
-
-  // having the same number of owned properties (keys incorporates
-  // hasOwnProperty)
-  if (ka.length != kb.length)
-    return false;
-
-  //the same set of keys (although not necessarily the same order),
-  ka.sort();
-  kb.sort();
-  //~~~cheap key test
-  for (i = ka.length - 1; i >= 0; i--) {
-    if (ka[i] != kb[i])
-      return false;
-  }
-
-  // remember objects we have compared to guard against circular references
-  memos.push([ a, b ]);
-
-  //equivalent values for every corresponding key, and
-  //~~~possibly expensive deep test
-  for (i = ka.length - 1; i >= 0; i--) {
-    key = ka[i];
-    if (!_deepEqual(a[key], b[key], memos)) return false;
-  }
-
-  return true;
-}
-
-});
-require.register("chai/lib/chai/utils/flag.js", function(exports, require, module){
-/*!
- * Chai - flag utility
- * Copyright(c) 2012-2013 Jake Luer <ja...@alogicalparadox.com>
- * MIT Licensed
- */
-
-/**
- * ### flag(object ,key, [value])
- *
- * Get or set a flag value on an object. If a
- * value is provided it will be set, else it will
- * return the currently set value or `undefined` if
- * the value is not set.
- *
- *     utils.flag(this, 'foo', 'bar'); // setter
- *     utils.flag(this, 'foo'); // getter, returns `bar`
- *
- * @param {Object} object (constructed Assertion
- * @param {String} key
- * @param {Mixed} value (optional)
- * @name flag
- * @api private
- */
-
-module.exports = function (obj, key, value) {
-  var flags = obj.__flags || (obj.__flags = Object.create(null));
-  if (arguments.length === 3) {
-    flags[key] = value;
-  } else {
-    return flags[key];
-  }
-};
-
-});
-require.register("chai/lib/chai/utils/getActual.js", function(exports, require, module){
-/*!
- * Chai - getActual utility
- * Copyright(c) 2012-2013 Jake Luer <ja...@alogicalparadox.com>
- * MIT Licensed
- */
-
-/**
- * # getActual(object, [actual])
- *
- * Returns the `actual` value for an Assertion
- *
- * @param {Object} object (constructed Assertion)
- * @param {Arguments} chai.Assertion.prototype.assert arguments
- */
-
-module.exports = function (obj, args) {
-  var actual = args[4];
-  return 'undefined' !== typeof actual ? actual : obj._obj;
-};
-
-});
-require.register("chai/lib/chai/utils/getEnumerableProperties.js", function(exports, require, module){
-/*!
- * Chai - getEnumerableProperties utility
- * Copyright(c) 2012-2013 Jake Luer <ja...@alogicalparadox.com>
- * MIT Licensed
- */
-
-/**
- * ### .getEnumerableProperties(object)
- *
- * This allows the retrieval of enumerable property names of an object,
- * inherited or not.
- *
- * @param {Object} object
- * @returns {Array}
- * @name getEnumerableProperties
- * @api public
- */
-
-module.exports = function getEnumerableProperties(object) {
-  var result = [];
-  for (var name in object) {
-    result.push(name);
-  }
-  return result;
-};
-
-});
-require.register("chai/lib/chai/utils/getMessage.js", function(exports, require, module){
-/*!
- * Chai - message composition utili

<TRUNCATED>

[21/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/js/libs/ace/snippets/javascript.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/js/libs/ace/snippets/javascript.js b/apps/fauxton/assets/js/libs/ace/snippets/javascript.js
deleted file mode 100644
index 2e7a35d..0000000
--- a/apps/fauxton/assets/js/libs/ace/snippets/javascript.js
+++ /dev/null
@@ -1,202 +0,0 @@
-define('ace/snippets/javascript', ['require', 'exports', 'module' ], function(require, exports, module) {
-
-
-exports.snippetText = "# Prototype\n\
-snippet proto\n\
-	${1:class_name}.prototype.${2:method_name} = function(${3:first_argument}) {\n\
-		${4:// body...}\n\
-	};\n\
-# Function\n\
-snippet fun\n\
-	function ${1?:function_name}(${2:argument}) {\n\
-		${3:// body...}\n\
-	}\n\
-# Anonymous Function\n\
-regex /((=)\\s*|(:)\\s*|(\\()|\\b)/f/(\\))?/\n\
-snippet f\n\
-	function${M1?: ${1:functionName}}($2) {\n\
-		${0:$TM_SELECTED_TEXT}\n\
-	}${M2?;}${M3?,}${M4?)}\n\
-# Immediate function\n\
-trigger \\(?f\\(\n\
-endTrigger \\)?\n\
-snippet f(\n\
-	(function(${1}) {\n\
-		${0:${TM_SELECTED_TEXT:/* code */}}\n\
-	}(${1}));\n\
-# if\n\
-snippet if\n\
-	if (${1:true}) {\n\
-		${0}\n\
-	}\n\
-# if ... else\n\
-snippet ife\n\
-	if (${1:true}) {\n\
-		${2}\n\
-	} else {\n\
-		${0}\n\
-	}\n\
-# tertiary conditional\n\
-snippet ter\n\
-	${1:/* condition */} ? ${2:a} : ${3:b}\n\
-# switch\n\
-snippet switch\n\
-	switch (${1:expression}) {\n\
-		case '${3:case}':\n\
-			${4:// code}\n\
-			break;\n\
-		${5}\n\
-		default:\n\
-			${2:// code}\n\
-	}\n\
-# case\n\
-snippet case\n\
-	case '${1:case}':\n\
-		${2:// code}\n\
-		break;\n\
-	${3}\n\
-\n\
-# while (...) {...}\n\
-snippet wh\n\
-	while (${1:/* condition */}) {\n\
-		${0:/* code */}\n\
-	}\n\
-# try\n\
-snippet try\n\
-	try {\n\
-		${0:/* code */}\n\
-	} catch (e) {}\n\
-# do...while\n\
-snippet do\n\
-	do {\n\
-		${2:/* code */}\n\
-	} while (${1:/* condition */});\n\
-# Object Method\n\
-snippet :f\n\
-regex /([,{[])|^\\s*/:f/\n\
-	${1:method_name}: function(${2:attribute}) {\n\
-		${0}\n\
-	}${3:,}\n\
-# setTimeout function\n\
-snippet setTimeout\n\
-regex /\\b/st|timeout|setTimeo?u?t?/\n\
-	setTimeout(function() {${3:$TM_SELECTED_TEXT}}, ${1:10});\n\
-# Get Elements\n\
-snippet gett\n\
-	getElementsBy${1:TagName}('${2}')${3}\n\
-# Get Element\n\
-snippet get\n\
-	getElementBy${1:Id}('${2}')${3}\n\
-# console.log (Firebug)\n\
-snippet cl\n\
-	console.log(${1});\n\
-# return\n\
-snippet ret\n\
-	return ${1:result}\n\
-# for (property in object ) { ... }\n\
-snippet fori\n\
-	for (var ${1:prop} in ${2:Things}) {\n\
-		${0:$2[$1]}\n\
-	}\n\
-# hasOwnProperty\n\
-snippet has\n\
-	hasOwnProperty(${1})\n\
-# docstring\n\
-snippet /**\n\
-	/**\n\
-	 * ${1:description}\n\
-	 *\n\
-	 */\n\
-snippet @par\n\
-regex /^\\s*\\*\\s*/@(para?m?)?/\n\
-	@param {${1:type}} ${2:name} ${3:description}\n\
-snippet @ret\n\
-	@return {${1:type}} ${2:description}\n\
-# JSON.parse\n\
-snippet jsonp\n\
-	JSON.parse(${1:jstr});\n\
-# JSON.stringify\n\
-snippet jsons\n\
-	JSON.stringify(${1:object});\n\
-# self-defining function\n\
-snippet sdf\n\
-	var ${1:function_name} = function(${2:argument}) {\n\
-		${3:// initial code ...}\n\
-\n\
-		$1 = function($2) {\n\
-			${4:// main code}\n\
-		};\n\
-	}\n\
-# singleton\n\
-snippet sing\n\
-	function ${1:Singleton} (${2:argument}) {\n\
-		// the cached instance\n\
-		var instance;\n\
-\n\
-		// rewrite the constructor\n\
-		$1 = function $1($2) {\n\
-			return instance;\n\
-		};\n\
-		\n\
-		// carry over the prototype properties\n\
-		$1.prototype = this;\n\
-\n\
-		// the instance\n\
-		instance = new $1();\n\
-\n\
-		// reset the constructor pointer\n\
-		instance.constructor = $1;\n\
-\n\
-		${3:// code ...}\n\
-\n\
-		return instance;\n\
-	}\n\
-# class\n\
-snippet class\n\
-regex /^\\s*/clas{0,2}/\n\
-	var ${1:class} = function(${20}) {\n\
-		$40$0\n\
-	};\n\
-	\n\
-	(function() {\n\
-		${60:this.prop = \"\"}\n\
-	}).call(${1:class}.prototype);\n\
-	\n\
-	exports.${1:class} = ${1:class};\n\
-# \n\
-snippet for-\n\
-	for (var ${1:i} = ${2:Things}.length; ${1:i}--; ) {\n\
-		${0:${2:Things}[${1:i}];}\n\
-	}\n\
-# for (...) {...}\n\
-snippet for\n\
-	for (var ${1:i} = 0; $1 < ${2:Things}.length; $1++) {\n\
-		${3:$2[$1]}$0\n\
-	}\n\
-# for (...) {...} (Improved Native For-Loop)\n\
-snippet forr\n\
-	for (var ${1:i} = ${2:Things}.length - 1; $1 >= 0; $1--) {\n\
-		${3:$2[$1]}$0\n\
-	}\n\
-\n\
-\n\
-#modules\n\
-snippet def\n\
-	define(function(require, exports, module) {\n\
-	\"use strict\";\n\
-	var ${1/.*\\///} = require(\"${1}\");\n\
-	\n\
-	$TM_SELECTED_TEXT\n\
-	});\n\
-snippet req\n\
-guard ^\\s*\n\
-	var ${1/.*\\///} = require(\"${1}\");\n\
-	$0\n\
-snippet requ\n\
-guard ^\\s*\n\
-	var ${1/.*\\/(.)/\\u$1/} = require(\"${1}\").${1/.*\\/(.)/\\u$1/};\n\
-	$0\n\
-";
-exports.scope = "javascript";
-
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/js/libs/ace/snippets/json.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/js/libs/ace/snippets/json.js b/apps/fauxton/assets/js/libs/ace/snippets/json.js
deleted file mode 100644
index 07841a2..0000000
--- a/apps/fauxton/assets/js/libs/ace/snippets/json.js
+++ /dev/null
@@ -1,7 +0,0 @@
-define('ace/snippets/json', ['require', 'exports', 'module' ], function(require, exports, module) {
-
-
-exports.snippetText = "";
-exports.scope = "json";
-
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/js/libs/ace/snippets/jsoniq.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/js/libs/ace/snippets/jsoniq.js b/apps/fauxton/assets/js/libs/ace/snippets/jsoniq.js
deleted file mode 100644
index 13b9bd7..0000000
--- a/apps/fauxton/assets/js/libs/ace/snippets/jsoniq.js
+++ /dev/null
@@ -1,7 +0,0 @@
-define('ace/snippets/jsoniq', ['require', 'exports', 'module' ], function(require, exports, module) {
-
-
-exports.snippetText = "";
-exports.scope = "jsoniq";
-
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/js/libs/ace/theme-crimson_editor.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/js/libs/ace/theme-crimson_editor.js b/apps/fauxton/assets/js/libs/ace/theme-crimson_editor.js
deleted file mode 100644
index 5192579..0000000
--- a/apps/fauxton/assets/js/libs/ace/theme-crimson_editor.js
+++ /dev/null
@@ -1,148 +0,0 @@
-/* ***** BEGIN LICENSE BLOCK *****
- * Distributed under the BSD license:
- *
- * Copyright (c) 2010, Ajax.org B.V.
- * All rights reserved.
- * 
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above copyright
- *       notice, this list of conditions and the following disclaimer in the
- *       documentation and/or other materials provided with the distribution.
- *     * Neither the name of Ajax.org B.V. nor the
- *       names of its contributors may be used to endorse or promote products
- *       derived from this software without specific prior written permission.
- * 
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * ***** END LICENSE BLOCK ***** */
-
-define('ace/theme/crimson_editor', ['require', 'exports', 'module' , 'ace/lib/dom'], function(require, exports, module) {
-exports.isDark = false;
-exports.cssText = ".ace-crimson-editor .ace_gutter {\
-background: #ebebeb;\
-color: #333;\
-overflow : hidden;\
-}\
-.ace-crimson-editor .ace_gutter-layer {\
-width: 100%;\
-text-align: right;\
-}\
-.ace-crimson-editor .ace_print-margin {\
-width: 1px;\
-background: #e8e8e8;\
-}\
-.ace-crimson-editor {\
-background-color: #FFFFFF;\
-color: rgb(64, 64, 64);\
-}\
-.ace-crimson-editor .ace_cursor {\
-color: black;\
-}\
-.ace-crimson-editor .ace_invisible {\
-color: rgb(191, 191, 191);\
-}\
-.ace-crimson-editor .ace_identifier {\
-color: black;\
-}\
-.ace-crimson-editor .ace_keyword {\
-color: blue;\
-}\
-.ace-crimson-editor .ace_constant.ace_buildin {\
-color: rgb(88, 72, 246);\
-}\
-.ace-crimson-editor .ace_constant.ace_language {\
-color: rgb(255, 156, 0);\
-}\
-.ace-crimson-editor .ace_constant.ace_library {\
-color: rgb(6, 150, 14);\
-}\
-.ace-crimson-editor .ace_invalid {\
-text-decoration: line-through;\
-color: rgb(224, 0, 0);\
-}\
-.ace-crimson-editor .ace_fold {\
-}\
-.ace-crimson-editor .ace_support.ace_function {\
-color: rgb(192, 0, 0);\
-}\
-.ace-crimson-editor .ace_support.ace_constant {\
-color: rgb(6, 150, 14);\
-}\
-.ace-crimson-editor .ace_support.ace_type,\
-.ace-crimson-editor .ace_support.ace_class {\
-color: rgb(109, 121, 222);\
-}\
-.ace-crimson-editor .ace_keyword.ace_operator {\
-color: rgb(49, 132, 149);\
-}\
-.ace-crimson-editor .ace_string {\
-color: rgb(128, 0, 128);\
-}\
-.ace-crimson-editor .ace_comment {\
-color: rgb(76, 136, 107);\
-}\
-.ace-crimson-editor .ace_comment.ace_doc {\
-color: rgb(0, 102, 255);\
-}\
-.ace-crimson-editor .ace_comment.ace_doc.ace_tag {\
-color: rgb(128, 159, 191);\
-}\
-.ace-crimson-editor .ace_constant.ace_numeric {\
-color: rgb(0, 0, 64);\
-}\
-.ace-crimson-editor .ace_variable {\
-color: rgb(0, 64, 128);\
-}\
-.ace-crimson-editor .ace_xml-pe {\
-color: rgb(104, 104, 91);\
-}\
-.ace-crimson-editor .ace_marker-layer .ace_selection {\
-background: rgb(181, 213, 255);\
-}\
-.ace-crimson-editor .ace_marker-layer .ace_step {\
-background: rgb(252, 255, 0);\
-}\
-.ace-crimson-editor .ace_marker-layer .ace_stack {\
-background: rgb(164, 229, 101);\
-}\
-.ace-crimson-editor .ace_marker-layer .ace_bracket {\
-margin: -1px 0 0 -1px;\
-border: 1px solid rgb(192, 192, 192);\
-}\
-.ace-crimson-editor .ace_marker-layer .ace_active-line {\
-background: rgb(232, 242, 254);\
-}\
-.ace-crimson-editor .ace_gutter-active-line {\
-background-color : #dcdcdc;\
-}\
-.ace-crimson-editor .ace_meta.ace_tag {\
-color:rgb(28, 2, 255);\
-}\
-.ace-crimson-editor .ace_marker-layer .ace_selected-word {\
-background: rgb(250, 250, 255);\
-border: 1px solid rgb(200, 200, 250);\
-}\
-.ace-crimson-editor .ace_string.ace_regex {\
-color: rgb(192, 0, 192);\
-}\
-.ace-crimson-editor .ace_indent-guide {\
-background: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAE0lEQVQImWP4////f4bLly//BwAmVgd1/w11/gAAAABJRU5ErkJggg==\") right repeat-y;\
-}";
-
-exports.cssClass = "ace-crimson-editor";
-
-var dom = require("../lib/dom");
-dom.importCssString(exports.cssText, exports.cssClass);
-});


[83/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/numfmt.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/numfmt.h b/src/apps/couch_collate/platform/osx/icu/unicode/numfmt.h
new file mode 100644
index 0000000..6deab8f
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/numfmt.h
@@ -0,0 +1,886 @@
+/*
+********************************************************************************
+* Copyright (C) 1997-2009, International Business Machines Corporation and others.
+* All Rights Reserved.
+********************************************************************************
+*
+* File NUMFMT.H
+*
+* Modification History:
+*
+*   Date        Name        Description
+*   02/19/97    aliu        Converted from java.
+*   03/18/97    clhuang     Updated per C++ implementation.
+*   04/17/97    aliu        Changed DigitCount to int per code review.
+*    07/20/98    stephen        JDK 1.2 sync up. Added scientific support.
+*                            Changed naming conventions to match C++ guidelines
+*                            Derecated Java style constants (eg, INTEGER_FIELD)
+********************************************************************************
+*/
+
+#ifndef NUMFMT_H
+#define NUMFMT_H
+
+
+#include "unicode/utypes.h"
+
+/**
+ * \file 
+ * \brief C++ API: Abstract base class for all number formats.
+ */
+ 
+#if !UCONFIG_NO_FORMATTING
+
+#include "unicode/unistr.h"
+#include "unicode/format.h"
+#include "unicode/unum.h" // UNumberFormatStyle
+#include "unicode/locid.h"
+
+U_NAMESPACE_BEGIN
+
+#if !UCONFIG_NO_SERVICE
+class NumberFormatFactory;
+class StringEnumeration;
+#endif
+
+/**
+ *
+ * Abstract base class for all number formats.  Provides interface for
+ * formatting and parsing a number.  Also provides methods for
+ * determining which locales have number formats, and what their names
+ * are.
+ * <P>
+ * NumberFormat helps you to format and parse numbers for any locale.
+ * Your code can be completely independent of the locale conventions
+ * for decimal points, thousands-separators, or even the particular
+ * decimal digits used, or whether the number format is even decimal.
+ * <P>
+ * To format a number for the current Locale, use one of the static
+ * factory methods:
+ * <pre>
+ * \code
+ *    double myNumber = 7.0;
+ *    UnicodeString myString;
+ *    UErrorCode success = U_ZERO_ERROR;
+ *    NumberFormat* nf = NumberFormat::createInstance(success)
+ *    nf->format(myNumber, myString);
+ *    cout << " Example 1: " << myString << endl;
+ * \endcode
+ * </pre>
+ * If you are formatting multiple numbers, it is more efficient to get
+ * the format and use it multiple times so that the system doesn't
+ * have to fetch the information about the local language and country
+ * conventions multiple times.
+ * <pre>
+ * \code
+ *     UnicodeString myString;
+ *     UErrorCode success = U_ZERO_ERROR;
+ *     nf = NumberFormat::createInstance( success );
+ *     int32_t a[] = { 123, 3333, -1234567 };
+ *     const int32_t a_len = sizeof(a) / sizeof(a[0]);
+ *     myString.remove();
+ *     for (int32_t i = 0; i < a_len; i++) {
+ *         nf->format(a[i], myString);
+ *         myString += " ; ";
+ *     }
+ *     cout << " Example 2: " << myString << endl;
+ * \endcode
+ * </pre>
+ * To format a number for a different Locale, specify it in the
+ * call to createInstance().
+ * <pre>
+ * \code
+ *     nf = NumberFormat::createInstance( Locale::FRENCH, success );
+ * \endcode
+ * </pre>
+ * You can use a NumberFormat to parse also.
+ * <pre>
+ * \code
+ *    UErrorCode success;
+ *    Formattable result(-999);  // initialized with error code
+ *    nf->parse(myString, result, success);
+ * \endcode
+ * </pre>
+ * Use createInstance to get the normal number format for that country.
+ * There are other static factory methods available.  Use getCurrency
+ * to get the currency number format for that country.  Use getPercent
+ * to get a format for displaying percentages. With this format, a
+ * fraction from 0.53 is displayed as 53%.
+ * <P>
+ * You can also control the display of numbers with such methods as
+ * getMinimumFractionDigits.  If you want even more control over the
+ * format or parsing, or want to give your users more control, you can
+ * try casting the NumberFormat you get from the factory methods to a
+ * DecimalNumberFormat. This will work for the vast majority of
+ * countries; just remember to put it in a try block in case you
+ * encounter an unusual one.
+ * <P>
+ * You can also use forms of the parse and format methods with
+ * ParsePosition and FieldPosition to allow you to:
+ * <ul type=round>
+ *   <li>(a) progressively parse through pieces of a string.
+ *   <li>(b) align the decimal point and other areas.
+ * </ul>
+ * For example, you can align numbers in two ways.
+ * <P>
+ * If you are using a monospaced font with spacing for alignment, you
+ * can pass the FieldPosition in your format call, with field =
+ * INTEGER_FIELD. On output, getEndIndex will be set to the offset
+ * between the last character of the integer and the decimal. Add
+ * (desiredSpaceCount - getEndIndex) spaces at the front of the
+ * string.
+ * <P>
+ * If you are using proportional fonts, instead of padding with
+ * spaces, measure the width of the string in pixels from the start to
+ * getEndIndex.  Then move the pen by (desiredPixelWidth -
+ * widthToAlignmentPoint) before drawing the text.  It also works
+ * where there is no decimal, but possibly additional characters at
+ * the end, e.g. with parentheses in negative numbers: "(12)" for -12.
+ * <p>
+ * <em>User subclasses are not supported.</em> While clients may write
+ * subclasses, such code will not necessarily work and will not be
+ * guaranteed to work stably from release to release.
+ *
+ * @stable ICU 2.0
+ */
+class U_I18N_API NumberFormat : public Format {
+public:
+
+    /**
+     * Alignment Field constants used to construct a FieldPosition object.
+     * Signifies that the position of the integer part or fraction part of
+     * a formatted number should be returned.
+     *
+     * @see FieldPosition
+     * @stable ICU 2.0
+     */
+    enum EAlignmentFields {
+        kIntegerField,
+        kFractionField,
+
+
+    /**
+     * These constants are provided for backwards compatibility only.
+     * Please use the C++ style constants defined above.
+     * @stable ICU 2.0
+     */
+        INTEGER_FIELD        = kIntegerField,
+        FRACTION_FIELD        = kFractionField
+    };
+
+    /**
+     * Destructor.
+     * @stable ICU 2.0
+     */
+    virtual ~NumberFormat();
+
+    /**
+     * Return true if the given Format objects are semantically equal.
+     * Objects of different subclasses are considered unequal.
+     * @return    true if the given Format objects are semantically equal.
+     * @stable ICU 2.0
+     */
+    virtual UBool operator==(const Format& other) const;
+
+    /**
+     * Format an object to produce a string.  This method handles
+     * Formattable objects with numeric types. If the Formattable
+     * object type is not a numeric type, then it returns a failing
+     * UErrorCode.
+     *
+     * @param obj       The object to format.
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     * @param pos       On input: an alignment field, if desired.
+     *                  On output: the offsets of the alignment field.
+     * @param status    Output param filled with success/failure status.
+     * @return          Reference to 'appendTo' parameter.
+     * @stable ICU 2.0
+     */
+    virtual UnicodeString& format(const Formattable& obj,
+                                  UnicodeString& appendTo,
+                                  FieldPosition& pos,
+                                  UErrorCode& status) const;
+
+    /**
+     * Parse a string to produce an object.  This methods handles
+     * parsing of numeric strings into Formattable objects with numeric
+     * types.
+     * <P>
+     * Before calling, set parse_pos.index to the offset you want to
+     * start parsing at in the source. After calling, parse_pos.index
+     * indicates the position after the successfully parsed text.  If
+     * an error occurs, parse_pos.index is unchanged.
+     * <P>
+     * When parsing, leading whitespace is discarded (with successful
+     * parse), while trailing whitespace is left as is.
+     * <P>
+     * See Format::parseObject() for more.
+     *
+     * @param source    The string to be parsed into an object.
+     * @param result    Formattable to be set to the parse result.
+     *                  If parse fails, return contents are undefined.
+     * @param parse_pos The position to start parsing at. Upon return
+     *                  this param is set to the position after the
+     *                  last character successfully parsed. If the
+     *                  source is not parsed successfully, this param
+     *                  will remain unchanged.
+     * @return          A newly created Formattable* object, or NULL
+     *                  on failure.  The caller owns this and should
+     *                  delete it when done.
+     * @stable ICU 2.0
+     */
+    virtual void parseObject(const UnicodeString& source,
+                             Formattable& result,
+                             ParsePosition& parse_pos) const;
+
+    /**
+     * Format a double number. These methods call the NumberFormat
+     * pure virtual format() methods with the default FieldPosition.
+     *
+     * @param number    The value to be formatted.
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     * @return          Reference to 'appendTo' parameter.
+     * @stable ICU 2.0
+     */
+    UnicodeString& format(  double number,
+                            UnicodeString& appendTo) const;
+
+    /**
+     * Format a long number. These methods call the NumberFormat
+     * pure virtual format() methods with the default FieldPosition.
+     *
+     * @param number    The value to be formatted.
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     * @return          Reference to 'appendTo' parameter.
+     * @stable ICU 2.0
+     */
+    UnicodeString& format(  int32_t number,
+                            UnicodeString& appendTo) const;
+
+    /**
+     * Format an int64 number. These methods call the NumberFormat
+     * pure virtual format() methods with the default FieldPosition.
+     *
+     * @param number    The value to be formatted.
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     * @return          Reference to 'appendTo' parameter.
+     * @stable ICU 2.8
+     */
+    UnicodeString& format(  int64_t number,
+                            UnicodeString& appendTo) const;
+
+    /**
+     * Format a double number. Concrete subclasses must implement
+     * these pure virtual methods.
+     *
+     * @param number    The value to be formatted.
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     * @param pos       On input: an alignment field, if desired.
+     *                  On output: the offsets of the alignment field.
+     * @return          Reference to 'appendTo' parameter.
+     * @stable ICU 2.0
+     */
+    virtual UnicodeString& format(double number,
+                                  UnicodeString& appendTo,
+                                  FieldPosition& pos) const = 0;
+    /**
+     * Format a long number. Concrete subclasses must implement
+     * these pure virtual methods.
+     *
+     * @param number    The value to be formatted.
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     * @param pos       On input: an alignment field, if desired.
+     *                  On output: the offsets of the alignment field.
+     * @return          Reference to 'appendTo' parameter.
+     * @stable ICU 2.0
+    */
+    virtual UnicodeString& format(int32_t number,
+                                  UnicodeString& appendTo,
+                                  FieldPosition& pos) const = 0;
+
+    /**
+     * Format an int64 number. (Not abstract to retain compatibility
+     * with earlier releases, however subclasses should override this
+     * method as it just delegates to format(int32_t number...);
+     *
+     * @param number    The value to be formatted.
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     * @param pos       On input: an alignment field, if desired.
+     *                  On output: the offsets of the alignment field.
+     * @return          Reference to 'appendTo' parameter.
+     * @stable ICU 2.8
+    */
+    virtual UnicodeString& format(int64_t number,
+                                  UnicodeString& appendTo,
+                                  FieldPosition& pos) const;
+    /**
+     * Redeclared Format method.
+     * @param obj       The object to be formatted.
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     * @param status    Output parameter set to a failure error code
+     *                  when a failure occurs.
+     * @return          Reference to 'appendTo' parameter.
+     * @stable ICU 2.0
+     */
+    UnicodeString& format(const Formattable& obj,
+                          UnicodeString& appendTo,
+                          UErrorCode& status) const;
+
+   /**
+    * Return a long if possible (e.g. within range LONG_MAX,
+    * LONG_MAX], and with no decimals), otherwise a double.  If
+    * IntegerOnly is set, will stop at a decimal point (or equivalent;
+    * e.g. for rational numbers "1 2/3", will stop after the 1).
+    * <P>
+    * If no object can be parsed, index is unchanged, and NULL is
+    * returned.
+    * <P>
+    * This is a pure virtual which concrete subclasses must implement.
+    *
+    * @param text           The text to be parsed.
+    * @param result         Formattable to be set to the parse result.
+    *                       If parse fails, return contents are undefined.
+    * @param parsePosition  The position to start parsing at on input.
+    *                       On output, moved to after the last successfully
+    *                       parse character. On parse failure, does not change.
+    * @return               A Formattable object of numeric type.  The caller
+    *                       owns this an must delete it.  NULL on failure.
+    * @stable ICU 2.0
+    */
+    virtual void parse(const UnicodeString& text,
+                       Formattable& result,
+                       ParsePosition& parsePosition) const = 0;
+
+    /**
+     * Parse a string as a numeric value, and return a Formattable
+     * numeric object. This method parses integers only if IntegerOnly
+     * is set.
+     *
+     * @param text          The text to be parsed.
+     * @param result        Formattable to be set to the parse result.
+     *                      If parse fails, return contents are undefined.
+     * @param status        Output parameter set to a failure error code
+     *                      when a failure occurs.
+     * @return              A Formattable object of numeric type.  The caller
+     *                      owns this an must delete it.  NULL on failure.
+     * @see                 NumberFormat::isParseIntegerOnly
+     * @stable ICU 2.0
+     */
+    virtual void parse( const UnicodeString& text,
+                        Formattable& result,
+                        UErrorCode& status) const;
+
+    /**
+     * Parses text from the given string as a currency amount.  Unlike
+     * the parse() method, this method will attempt to parse a generic
+     * currency name, searching for a match of this object's locale's
+     * currency display names, or for a 3-letter ISO currency code.
+     * This method will fail if this format is not a currency format,
+     * that is, if it does not contain the currency pattern symbol
+     * (U+00A4) in its prefix or suffix.
+     *
+     * @param text the string to parse
+     * @param result output parameter to receive result. This will have
+     * its currency set to the parsed ISO currency code.
+     * @param pos input-output position; on input, the position within
+     * text to match; must have 0 <= pos.getIndex() < text.length();
+     * on output, the position after the last matched character. If
+     * the parse fails, the position in unchanged upon output.
+     * @return a reference to result
+     * @internal
+     */
+    virtual Formattable& parseCurrency(const UnicodeString& text,
+                                       Formattable& result,
+                                       ParsePosition& pos) const;
+
+    /**
+     * Return true if this format will parse numbers as integers
+     * only.  For example in the English locale, with ParseIntegerOnly
+     * true, the string "1234." would be parsed as the integer value
+     * 1234 and parsing would stop at the "." character.  Of course,
+     * the exact format accepted by the parse operation is locale
+     * dependant and determined by sub-classes of NumberFormat.
+     * @return    true if this format will parse numbers as integers
+     *            only.
+     * @stable ICU 2.0
+     */
+    UBool isParseIntegerOnly(void) const;
+
+    /**
+     * Sets whether or not numbers should be parsed as integers only.
+     * @param value    set True, this format will parse numbers as integers
+     *                 only.
+     * @see isParseIntegerOnly
+     * @stable ICU 2.0
+     */
+    virtual void setParseIntegerOnly(UBool value);
+	
+    /**
+     * Return whether or not strict parsing is in effect.
+     *
+     * @return <code>TRUE</code> if strict parsing is in effect,
+     *         <code>FALSE</code> otherwise.
+     *  @internal
+     */
+    UBool isParseStrict(void) const;
+	
+    /**
+     * Set whether or not strict parsing should be used.
+     *
+     * @param value <code>TRUE</code> if strict parsing should be used,
+     *              <code>FALSE</code> otherwise.
+     *  @internal
+     */
+    virtual void setParseStrict(UBool value);
+	
+    /**
+     * Returns the default number format for the current default
+     * locale.  The default format is one of the styles provided by
+     * the other factory methods: getNumberInstance,
+     * getCurrencyInstance or getPercentInstance.  Exactly which one
+     * is locale dependant.
+     * @stable ICU 2.0
+     */
+    static NumberFormat* U_EXPORT2 createInstance(UErrorCode&);
+
+    /**
+     * Returns the default number format for the specified locale.
+     * The default format is one of the styles provided by the other
+     * factory methods: getNumberInstance, getCurrencyInstance or
+     * getPercentInstance.  Exactly which one is locale dependant.
+     * @param inLocale    the given locale.
+     * @stable ICU 2.0
+     */
+    static NumberFormat* U_EXPORT2 createInstance(const Locale& inLocale,
+                                        UErrorCode&);
+
+    /**
+     * Returns a currency format for the current default locale.
+     * @stable ICU 2.0
+     */
+    static NumberFormat* U_EXPORT2 createCurrencyInstance(UErrorCode&);
+
+    /**
+     * Returns a currency format for the specified locale.
+     * @param inLocale    the given locale.
+     * @stable ICU 2.0
+     */
+    static NumberFormat* U_EXPORT2 createCurrencyInstance(const Locale& inLocale,
+                                                UErrorCode&);
+
+    /**
+     * Returns a percentage format for the current default locale.
+     * @stable ICU 2.0
+     */
+    static NumberFormat* U_EXPORT2 createPercentInstance(UErrorCode&);
+
+    /**
+     * Returns a percentage format for the specified locale.
+     * @param inLocale    the given locale.
+     * @stable ICU 2.0
+     */
+    static NumberFormat* U_EXPORT2 createPercentInstance(const Locale& inLocale,
+                                               UErrorCode&);
+
+    /**
+     * Returns a scientific format for the current default locale.
+     * @stable ICU 2.0
+     */
+    static NumberFormat* U_EXPORT2 createScientificInstance(UErrorCode&);
+
+    /**
+     * Returns a scientific format for the specified locale.
+     * @param inLocale    the given locale.
+     * @stable ICU 2.0
+     */
+    static NumberFormat* U_EXPORT2 createScientificInstance(const Locale& inLocale,
+                                                UErrorCode&);
+
+    /**
+     * Get the set of Locales for which NumberFormats are installed.
+     * @param count    Output param to receive the size of the locales
+     * @stable ICU 2.0
+     */
+    static const Locale* U_EXPORT2 getAvailableLocales(int32_t& count);
+
+#if !UCONFIG_NO_SERVICE
+    /**
+     * Register a new NumberFormatFactory.  The factory will be adopted.
+     * @param toAdopt the NumberFormatFactory instance to be adopted
+     * @param status the in/out status code, no special meanings are assigned
+     * @return a registry key that can be used to unregister this factory
+     * @stable ICU 2.6
+     */
+    static URegistryKey U_EXPORT2 registerFactory(NumberFormatFactory* toAdopt, UErrorCode& status);
+
+    /**
+     * Unregister a previously-registered NumberFormatFactory using the key returned from the
+     * register call.  Key becomes invalid after a successful call and should not be used again.
+     * The NumberFormatFactory corresponding to the key will be deleted.
+     * @param key the registry key returned by a previous call to registerFactory
+     * @param status the in/out status code, no special meanings are assigned
+     * @return TRUE if the factory for the key was successfully unregistered
+     * @stable ICU 2.6
+     */
+    static UBool U_EXPORT2 unregister(URegistryKey key, UErrorCode& status);
+
+    /**
+     * Return a StringEnumeration over the locales available at the time of the call,
+     * including registered locales.
+     * @return a StringEnumeration over the locales available at the time of the call
+     * @stable ICU 2.6
+     */
+    static StringEnumeration* U_EXPORT2 getAvailableLocales(void);
+#endif /* UCONFIG_NO_SERVICE */
+
+    /**
+     * Returns true if grouping is used in this format. For example,
+     * in the English locale, with grouping on, the number 1234567
+     * might be formatted as "1,234,567". The grouping separator as
+     * well as the size of each group is locale dependant and is
+     * determined by sub-classes of NumberFormat.
+     * @see setGroupingUsed
+     * @stable ICU 2.0
+     */
+    UBool isGroupingUsed(void) const;
+
+    /**
+     * Set whether or not grouping will be used in this format.
+     * @param newValue    True, grouping will be used in this format.
+     * @see getGroupingUsed
+     * @stable ICU 2.0
+     */
+    virtual void setGroupingUsed(UBool newValue);
+
+    /**
+     * Returns the maximum number of digits allowed in the integer portion of a
+     * number.
+     * @return     the maximum number of digits allowed in the integer portion of a
+     *             number.
+     * @see setMaximumIntegerDigits
+     * @stable ICU 2.0
+     */
+    int32_t getMaximumIntegerDigits(void) const;
+
+    /**
+     * Sets the maximum number of digits allowed in the integer portion of a
+     * number. maximumIntegerDigits must be >= minimumIntegerDigits.  If the
+     * new value for maximumIntegerDigits is less than the current value
+     * of minimumIntegerDigits, then minimumIntegerDigits will also be set to
+     * the new value.
+     *
+     * @param newValue    the new value for the maximum number of digits
+     *                    allowed in the integer portion of a number.
+     * @see getMaximumIntegerDigits
+     * @stable ICU 2.0
+     */
+    virtual void setMaximumIntegerDigits(int32_t newValue);
+
+    /**
+     * Returns the minimum number of digits allowed in the integer portion of a
+     * number.
+     * @return    the minimum number of digits allowed in the integer portion of a
+     *            number.
+     * @see setMinimumIntegerDigits
+     * @stable ICU 2.0
+     */
+    int32_t getMinimumIntegerDigits(void) const;
+
+    /**
+     * Sets the minimum number of digits allowed in the integer portion of a
+     * number. minimumIntegerDigits must be &lt;= maximumIntegerDigits.  If the
+     * new value for minimumIntegerDigits exceeds the current value
+     * of maximumIntegerDigits, then maximumIntegerDigits will also be set to
+     * the new value.
+     * @param newValue    the new value to be set.
+     * @see getMinimumIntegerDigits
+     * @stable ICU 2.0
+     */
+    virtual void setMinimumIntegerDigits(int32_t newValue);
+
+    /**
+     * Returns the maximum number of digits allowed in the fraction portion of a
+     * number.
+     * @return    the maximum number of digits allowed in the fraction portion of a
+     *            number.
+     * @see setMaximumFractionDigits
+     * @stable ICU 2.0
+     */
+    int32_t getMaximumFractionDigits(void) const;
+
+    /**
+     * Sets the maximum number of digits allowed in the fraction portion of a
+     * number. maximumFractionDigits must be >= minimumFractionDigits.  If the
+     * new value for maximumFractionDigits is less than the current value
+     * of minimumFractionDigits, then minimumFractionDigits will also be set to
+     * the new value.
+     * @param newValue    the new value to be set.
+     * @see getMaximumFractionDigits
+     * @stable ICU 2.0
+     */
+    virtual void setMaximumFractionDigits(int32_t newValue);
+
+    /**
+     * Returns the minimum number of digits allowed in the fraction portion of a
+     * number.
+     * @return    the minimum number of digits allowed in the fraction portion of a
+     *            number.
+     * @see setMinimumFractionDigits
+     * @stable ICU 2.0
+     */
+    int32_t getMinimumFractionDigits(void) const;
+
+    /**
+     * Sets the minimum number of digits allowed in the fraction portion of a
+     * number. minimumFractionDigits must be &lt;= maximumFractionDigits.   If the
+     * new value for minimumFractionDigits exceeds the current value
+     * of maximumFractionDigits, then maximumIntegerDigits will also be set to
+     * the new value
+     * @param newValue    the new value to be set.
+     * @see getMinimumFractionDigits
+     * @stable ICU 2.0
+     */
+    virtual void setMinimumFractionDigits(int32_t newValue);
+
+    /**
+     * Sets the currency used to display currency
+     * amounts.  This takes effect immediately, if this format is a
+     * currency format.  If this format is not a currency format, then
+     * the currency is used if and when this object becomes a
+     * currency format.
+     * @param theCurrency a 3-letter ISO code indicating new currency
+     * to use.  It need not be null-terminated.  May be the empty
+     * string or NULL to indicate no currency.
+     * @param ec input-output error code
+     * @stable ICU 3.0
+     */
+    virtual void setCurrency(const UChar* theCurrency, UErrorCode& ec);
+
+    /**
+     * Gets the currency used to display currency
+     * amounts.  This may be an empty string for some subclasses.
+     * @return a 3-letter null-terminated ISO code indicating
+     * the currency in use, or a pointer to the empty string.
+     * @stable ICU 2.6
+     */
+    const UChar* getCurrency() const;
+
+public:
+
+    /**
+     * Return the class ID for this class.  This is useful for
+     * comparing to a return value from getDynamicClassID(). Note that,
+     * because NumberFormat is an abstract base class, no fully constructed object
+     * will have the class ID returned by NumberFormat::getStaticClassID().
+     * @return The class ID for all objects of this class.
+     * @stable ICU 2.0
+     */
+    static UClassID U_EXPORT2 getStaticClassID(void);
+
+    /**
+     * Returns a unique class ID POLYMORPHICALLY.  Pure virtual override.
+     * This method is to implement a simple version of RTTI, since not all
+     * C++ compilers support genuine RTTI.  Polymorphic operator==() and
+     * clone() methods call this method.
+     * <P>
+     * @return The class ID for this object. All objects of a
+     * given class have the same class ID.  Objects of
+     * other classes have different class IDs.
+     * @stable ICU 2.0
+     */
+    virtual UClassID getDynamicClassID(void) const = 0;
+
+protected:
+
+    /**
+     * Default constructor for subclass use only.
+     * @stable ICU 2.0
+     */
+    NumberFormat();
+
+    /**
+     * Copy constructor.
+     * @stable ICU 2.0
+     */
+    NumberFormat(const NumberFormat&);
+
+    /**
+     * Assignment operator.
+     * @stable ICU 2.0
+     */
+    NumberFormat& operator=(const NumberFormat&);
+
+    /**
+     * Returns the currency in effect for this formatter.  Subclasses
+     * should override this method as needed.  Unlike getCurrency(),
+     * this method should never return "".
+     * @result output parameter for null-terminated result, which must
+     * have a capacity of at least 4
+     * @internal
+     */
+    virtual void getEffectiveCurrency(UChar* result, UErrorCode& ec) const;
+
+private:
+
+    enum EStyles {
+        kNumberStyle,
+        kCurrencyStyle,
+        kPercentStyle,
+        kScientificStyle,
+        kStyleCount // ALWAYS LAST ENUM: number of styles
+    };
+
+    /**
+     * Creates the specified decimal format style of the desired locale.
+     * Hook for service registration, uses makeInstance directly if no services
+     * registered.
+     * @param desiredLocale    the given locale.
+     * @param choice           the given style.
+     * @param success          Output param filled with success/failure status.
+     * @return                 A new NumberFormat instance.
+     */
+    static NumberFormat* U_EXPORT2 createInstance(const Locale& desiredLocale, EStyles choice, UErrorCode& success);
+
+    /**
+     * Creates the specified decimal format style of the desired locale.
+     * @param desiredLocale    the given locale.
+     * @param choice           the given style.
+     * @param success          Output param filled with success/failure status.
+     * @return                 A new NumberFormat instance.
+     */
+    static NumberFormat* makeInstance(const Locale& desiredLocale, EStyles choice, UErrorCode& success);
+
+    UBool      fGroupingUsed;
+    int32_t    fMaxIntegerDigits;
+    int32_t    fMinIntegerDigits;
+    int32_t    fMaxFractionDigits;
+    int32_t    fMinFractionDigits;
+    UBool      fParseIntegerOnly;
+    UBool      fParseStrict;
+
+    // ISO currency code
+    UChar      fCurrency[4];
+
+    friend class ICUNumberFormatFactory; // access to makeInstance, EStyles
+    friend class ICUNumberFormatService;
+};
+
+#if !UCONFIG_NO_SERVICE
+/**
+ * A NumberFormatFactory is used to register new number formats.  The factory
+ * should be able to create any of the predefined formats for each locale it
+ * supports.  When registered, the locales it supports extend or override the
+ * locale already supported by ICU.
+ *
+ * @stable ICU 2.6
+ */
+class U_I18N_API NumberFormatFactory : public UObject {
+public:
+
+    /**
+     * Destructor
+     * @stable ICU 3.0
+     */
+    virtual ~NumberFormatFactory();
+
+    /**
+     * Return true if this factory will be visible.  Default is true.
+     * If not visible, the locales supported by this factory will not
+     * be listed by getAvailableLocales.
+     * @stable ICU 2.6
+     */
+    virtual UBool visible(void) const = 0;
+
+    /**
+     * Return the locale names directly supported by this factory.  The number of names
+     * is returned in count;
+     * @stable ICU 2.6
+     */
+    virtual const UnicodeString * getSupportedIDs(int32_t &count, UErrorCode& status) const = 0;
+
+    /**
+     * Return a number format of the appropriate type.  If the locale
+     * is not supported, return null.  If the locale is supported, but
+     * the type is not provided by this service, return null.  Otherwise
+     * return an appropriate instance of NumberFormat.
+     * @stable ICU 2.6
+     */
+    virtual NumberFormat* createFormat(const Locale& loc, UNumberFormatStyle formatType) = 0;
+};
+
+/**
+ * A NumberFormatFactory that supports a single locale.  It can be visible or invisible.
+ * @stable ICU 2.6
+ */
+class U_I18N_API SimpleNumberFormatFactory : public NumberFormatFactory {
+protected:
+    /**
+     * True if the locale supported by this factory is visible.
+     * @stable ICU 2.6
+     */
+    const UBool _visible;
+
+    /**
+     * The locale supported by this factory, as a UnicodeString.
+     * @stable ICU 2.6
+     */
+    UnicodeString _id;
+
+public:
+    /**
+     * @stable ICU 2.6
+     */
+    SimpleNumberFormatFactory(const Locale& locale, UBool visible = TRUE);
+
+    /**
+     * @stable ICU 3.0
+     */
+    virtual ~SimpleNumberFormatFactory();
+
+    /**
+     * @stable ICU 2.6
+     */
+    virtual UBool visible(void) const;
+
+    /**
+     * @stable ICU 2.6
+     */
+    virtual const UnicodeString * getSupportedIDs(int32_t &count, UErrorCode& status) const;
+};
+#endif /* #if !UCONFIG_NO_SERVICE */
+
+// -------------------------------------
+
+inline UBool
+NumberFormat::isParseIntegerOnly() const
+{
+    return fParseIntegerOnly;
+}
+
+inline UBool
+NumberFormat::isParseStrict() const
+{
+	return fParseStrict;
+}
+
+inline UnicodeString&
+NumberFormat::format(const Formattable& obj,
+                     UnicodeString& appendTo,
+                     UErrorCode& status) const {
+    return Format::format(obj, appendTo, status);
+}
+
+U_NAMESPACE_END
+
+#endif /* #if !UCONFIG_NO_FORMATTING */
+
+#endif // _NUMFMT
+//eof

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/parseerr.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/parseerr.h b/src/apps/couch_collate/platform/osx/icu/unicode/parseerr.h
new file mode 100644
index 0000000..44ff008
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/parseerr.h
@@ -0,0 +1,92 @@
+/*
+**********************************************************************
+*   Copyright (C) 1999-2005, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+**********************************************************************
+*   Date        Name        Description
+*   03/14/00    aliu        Creation.
+*   06/27/00    aliu        Change from C++ class to C struct
+**********************************************************************
+*/
+#ifndef PARSEERR_H
+#define PARSEERR_H
+
+#include "unicode/utypes.h"
+
+
+/**
+ * \file
+ * \brief C API: Parse Error Information
+ */
+/**
+ * The capacity of the context strings in UParseError.
+ * @stable ICU 2.0
+ */ 
+enum { U_PARSE_CONTEXT_LEN = 16 };
+
+/**
+ * A UParseError struct is used to returned detailed information about
+ * parsing errors.  It is used by ICU parsing engines that parse long
+ * rules, patterns, or programs, where the text being parsed is long
+ * enough that more information than a UErrorCode is needed to
+ * localize the error.
+ *
+ * <p>The line, offset, and context fields are optional; parsing
+ * engines may choose not to use to use them.
+ *
+ * <p>The preContext and postContext strings include some part of the
+ * context surrounding the error.  If the source text is "let for=7"
+ * and "for" is the error (e.g., because it is a reserved word), then
+ * some examples of what a parser might produce are the following:
+ *
+ * <pre>
+ * preContext   postContext
+ * ""           ""            The parser does not support context
+ * "let "       "=7"          Pre- and post-context only
+ * "let "       "for=7"       Pre- and post-context and error text
+ * ""           "for"         Error text only
+ * </pre>
+ *
+ * <p>Examples of engines which use UParseError (or may use it in the
+ * future) are Transliterator, RuleBasedBreakIterator, and
+ * RegexPattern.
+ * 
+ * @stable ICU 2.0
+ */
+typedef struct UParseError {
+
+    /**
+     * The line on which the error occured.  If the parser uses this
+     * field, it sets it to the line number of the source text line on
+     * which the error appears, which will be be a value >= 1.  If the
+     * parse does not support line numbers, the value will be <= 0.
+     * @stable ICU 2.0
+     */
+    int32_t        line;
+
+    /**
+     * The character offset to the error.  If the line field is >= 1,
+     * then this is the offset from the start of the line.  Otherwise,
+     * this is the offset from the start of the text.  If the parser
+     * does not support this field, it will have a value < 0.
+     * @stable ICU 2.0
+     */
+    int32_t        offset;
+
+    /**
+     * Textual context before the error.  Null-terminated.  The empty
+     * string if not supported by parser.
+     * @stable ICU 2.0   
+     */
+    UChar          preContext[U_PARSE_CONTEXT_LEN];
+
+    /**
+     * The error itself and/or textual context after the error.
+     * Null-terminated.  The empty string if not supported by parser.
+     * @stable ICU 2.0   
+     */
+    UChar          postContext[U_PARSE_CONTEXT_LEN];
+
+} UParseError;
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/parsepos.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/parsepos.h b/src/apps/couch_collate/platform/osx/icu/unicode/parsepos.h
new file mode 100644
index 0000000..cdf49e0
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/parsepos.h
@@ -0,0 +1,230 @@
+/*
+* Copyright (C) 1997-2005, International Business Machines Corporation and others. All Rights Reserved.
+*******************************************************************************
+*
+* File PARSEPOS.H
+*
+* Modification History:
+*
+*   Date        Name        Description
+*   07/09/97    helena      Converted from java.
+*   07/17/98    stephen     Added errorIndex support.
+*   05/11/99    stephen     Cleaned up.
+*******************************************************************************
+*/
+
+#ifndef PARSEPOS_H
+#define PARSEPOS_H
+
+#include "unicode/utypes.h"
+#include "unicode/uobject.h"
+
+ 
+U_NAMESPACE_BEGIN
+
+/**
+ * \file
+ * \brief C++ API: Canonical Iterator
+ */
+/** 
+ * <code>ParsePosition</code> is a simple class used by <code>Format</code>
+ * and its subclasses to keep track of the current position during parsing.
+ * The <code>parseObject</code> method in the various <code>Format</code>
+ * classes requires a <code>ParsePosition</code> object as an argument.
+ *
+ * <p>
+ * By design, as you parse through a string with different formats,
+ * you can use the same <code>ParsePosition</code>, since the index parameter
+ * records the current position.
+ *
+ * The ParsePosition class is not suitable for subclassing.
+ *
+ * @version     1.3 10/30/97
+ * @author      Mark Davis, Helena Shih
+ * @see         java.text.Format
+ */
+
+class U_COMMON_API ParsePosition : public UObject {
+public:
+    /**
+     * Default constructor, the index starts with 0 as default.
+     * @stable ICU 2.0
+     */
+    ParsePosition()
+        : UObject(),
+        index(0),
+        errorIndex(-1)
+      {}
+
+    /**
+     * Create a new ParsePosition with the given initial index.
+     * @param newIndex the new text offset.
+     * @stable ICU 2.0
+     */
+    ParsePosition(int32_t newIndex)
+        : UObject(),
+        index(newIndex),
+        errorIndex(-1)
+      {}
+
+    /**
+     * Copy constructor
+     * @param copy the object to be copied from.
+     * @stable ICU 2.0
+     */
+    ParsePosition(const ParsePosition& copy)
+        : UObject(copy),
+        index(copy.index),
+        errorIndex(copy.errorIndex)
+      {}
+
+    /**
+     * Destructor
+     * @stable ICU 2.0
+     */
+    virtual ~ParsePosition();
+
+    /**
+     * Assignment operator
+     * @stable ICU 2.0
+     */
+    ParsePosition&      operator=(const ParsePosition& copy);
+
+    /**
+     * Equality operator.
+     * @return TRUE if the two parse positions are equal, FALSE otherwise.
+     * @stable ICU 2.0
+     */
+    UBool              operator==(const ParsePosition& that) const;
+
+    /**
+     * Equality operator.
+     * @return TRUE if the two parse positions are not equal, FALSE otherwise.
+     * @stable ICU 2.0
+     */
+    UBool              operator!=(const ParsePosition& that) const;
+
+    /**
+     * Clone this object.
+     * Clones can be used concurrently in multiple threads.
+     * If an error occurs, then NULL is returned.
+     * The caller must delete the clone.
+     *
+     * @return a clone of this object
+     *
+     * @see getDynamicClassID
+     * @stable ICU 2.8
+     */
+    ParsePosition *clone() const;
+
+    /**
+     * Retrieve the current parse position.  On input to a parse method, this
+     * is the index of the character at which parsing will begin; on output, it
+     * is the index of the character following the last character parsed.
+     * @return the current index.
+     * @stable ICU 2.0
+     */
+    int32_t getIndex(void) const;
+
+    /**
+     * Set the current parse position.
+     * @param index the new index.
+     * @stable ICU 2.0
+     */
+    void setIndex(int32_t index);
+
+    /**
+     * Set the index at which a parse error occurred.  Formatters
+     * should set this before returning an error code from their
+     * parseObject method.  The default value is -1 if this is not
+     * set.
+     * @stable ICU 2.0
+     */
+    void setErrorIndex(int32_t ei);
+
+    /**
+     * Retrieve the index at which an error occurred, or -1 if the
+     * error index has not been set.
+     * @stable ICU 2.0
+     */
+    int32_t getErrorIndex(void) const;
+
+    /**
+     * ICU "poor man's RTTI", returns a UClassID for this class.
+     *
+     * @stable ICU 2.2
+     */
+    static UClassID U_EXPORT2 getStaticClassID();
+
+    /**
+     * ICU "poor man's RTTI", returns a UClassID for the actual class.
+     *
+     * @stable ICU 2.2
+     */
+    virtual UClassID getDynamicClassID() const;
+
+private:
+    /**
+     * Input: the place you start parsing.
+     * <br>Output: position where the parse stopped.
+     * This is designed to be used serially,
+     * with each call setting index up for the next one.
+     */
+    int32_t index;
+
+    /**
+     * The index at which a parse error occurred.
+     */
+    int32_t errorIndex;
+
+};
+
+inline ParsePosition&
+ParsePosition::operator=(const ParsePosition& copy)
+{
+  index = copy.index;
+  errorIndex = copy.errorIndex;
+  return *this;
+}
+
+inline UBool
+ParsePosition::operator==(const ParsePosition& copy) const
+{
+  if(index != copy.index || errorIndex != copy.errorIndex)
+  return FALSE;
+  else
+  return TRUE;
+}
+
+inline UBool
+ParsePosition::operator!=(const ParsePosition& copy) const
+{
+  return !operator==(copy);
+}
+
+inline int32_t
+ParsePosition::getIndex() const
+{
+  return index;
+}
+
+inline void
+ParsePosition::setIndex(int32_t offset)
+{
+  this->index = offset;
+}
+
+inline int32_t
+ParsePosition::getErrorIndex() const
+{
+  return errorIndex;
+}
+
+inline void
+ParsePosition::setErrorIndex(int32_t ei)
+{
+  this->errorIndex = ei;
+}
+U_NAMESPACE_END
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/platform.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/platform.h b/src/apps/couch_collate/platform/osx/icu/unicode/platform.h
new file mode 100644
index 0000000..15ccbf5
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/platform.h
@@ -0,0 +1,316 @@
+/*
+******************************************************************************
+*
+*   Copyright (C) 1997-2007, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+*
+******************************************************************************
+*
+*  FILE NAME : platform.h
+*
+*   Date        Name        Description
+*   05/13/98    nos         Creation (content moved here from ptypes.h).
+*   03/02/99    stephen     Added AS400 support.
+*   03/30/99    stephen     Added Linux support.
+*   04/13/99    stephen     Reworked for autoconf.
+******************************************************************************
+*/
+
+/**
+ * \file 
+ * \brief Basic types for the platform 
+ */
+
+/* Define the platform we're on. */
+#ifndef U_DARWIN
+#define U_DARWIN
+#endif
+
+/* Define whether inttypes.h is available */
+#ifndef U_HAVE_INTTYPES_H
+#define U_HAVE_INTTYPES_H 1
+#endif
+
+/*
+ * Define what support for C++ streams is available.
+ *     If U_IOSTREAM_SOURCE is set to 199711, then <iostream> is available
+ * (1997711 is the date the ISO/IEC C++ FDIS was published), and then
+ * one should qualify streams using the std namespace in ICU header
+ * files.
+ *     If U_IOSTREAM_SOURCE is set to 198506, then <iostream.h> is
+ * available instead (198506 is the date when Stroustrup published
+ * "An Extensible I/O Facility for C++" at the summer USENIX conference).
+ *     If U_IOSTREAM_SOURCE is 0, then C++ streams are not available and
+ * support for them will be silently suppressed in ICU.
+ *
+ */
+
+#ifndef U_IOSTREAM_SOURCE
+#define U_IOSTREAM_SOURCE 199711
+#endif
+
+/* Determines whether specific types are available */
+#ifndef U_HAVE_INT8_T
+#define U_HAVE_INT8_T 1
+#endif
+
+#ifndef U_HAVE_UINT8_T
+#define U_HAVE_UINT8_T 1
+#endif
+
+#ifndef U_HAVE_INT16_T
+#define U_HAVE_INT16_T 1
+#endif
+
+#ifndef U_HAVE_UINT16_T
+#define U_HAVE_UINT16_T 1
+#endif
+
+#ifndef U_HAVE_INT32_T
+#define U_HAVE_INT32_T 1
+#endif
+
+#ifndef U_HAVE_UINT32_T
+#define U_HAVE_UINT32_T 1
+#endif
+
+#ifndef U_HAVE_INT64_T
+#define U_HAVE_INT64_T 1
+#endif
+
+#ifndef U_HAVE_UINT64_T
+#define U_HAVE_UINT64_T 1
+#endif
+
+/*===========================================================================*/
+/* Generic data types                                                        */
+/*===========================================================================*/
+
+#include <sys/types.h>
+
+/* If your platform does not have the <inttypes.h> header, you may
+   need to edit the typedefs below. */
+#if U_HAVE_INTTYPES_H
+
+/* autoconf 2.13 sometimes can't properly find the data types in <inttypes.h> */
+/* os/390 needs <inttypes.h>, but it doesn't have int8_t, and it sometimes */
+/* doesn't have uint8_t depending on the OS version. */
+/* So we have this work around. */
+#ifdef OS390
+/* The features header is needed to get (u)int64_t sometimes. */
+#include <features.h>
+#if ! U_HAVE_INT8_T
+typedef signed char int8_t;
+#endif
+#if !defined(__uint8_t)
+#define __uint8_t 1
+typedef unsigned char uint8_t;
+#endif
+#endif /* OS390 */
+
+#include <inttypes.h>
+
+#else /* U_HAVE_INTTYPES_H */
+
+#if ! U_HAVE_INT8_T
+typedef signed char int8_t;
+#endif
+
+#if ! U_HAVE_UINT8_T
+typedef unsigned char uint8_t;
+#endif
+
+#if ! U_HAVE_INT16_T
+typedef signed short int16_t;
+#endif
+
+#if ! U_HAVE_UINT16_T
+typedef unsigned short uint16_t;
+#endif
+
+#if ! U_HAVE_INT32_T
+typedef signed int int32_t;
+#endif
+
+#if ! U_HAVE_UINT32_T
+typedef unsigned int uint32_t;
+#endif
+
+#if ! U_HAVE_INT64_T
+    typedef signed long long int64_t;
+/* else we may not have a 64-bit type */
+#endif
+
+#if ! U_HAVE_UINT64_T
+    typedef unsigned long long uint64_t;
+/* else we may not have a 64-bit type */
+#endif
+
+#endif
+
+/*===========================================================================*/
+/* Compiler and environment features                                         */
+/*===========================================================================*/
+
+/* Define whether namespace is supported */
+#ifndef U_HAVE_NAMESPACE
+#define U_HAVE_NAMESPACE 1
+#endif
+
+/* Determines the endianness of the platform
+   It's done this way in case multiple architectures are being built at once.
+   For example, Darwin supports fat binaries, which can be both PPC and x86 based. */
+#if defined(BYTE_ORDER) && defined(BIG_ENDIAN)
+#define U_IS_BIG_ENDIAN (BYTE_ORDER == BIG_ENDIAN)
+#else
+#define U_IS_BIG_ENDIAN 0
+#endif
+
+/* 1 or 0 to enable or disable threads.  If undefined, default is: enable threads. */
+#define ICU_USE_THREADS 1
+
+/* On strong memory model CPUs (e.g. x86 CPUs), we use a safe & quick double check lock. */
+#if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
+#define UMTX_STRONG_MEMORY_MODEL 1
+#endif
+
+#ifndef U_DEBUG
+#define U_DEBUG 0
+#endif
+
+#ifndef U_RELEASE
+#define U_RELEASE 1
+#endif
+
+/* Determine whether to disable renaming or not. This overrides the
+   setting in umachine.h which is for all platforms. */
+#ifndef U_DISABLE_RENAMING
+#define U_DISABLE_RENAMING 1
+#endif
+
+/* Determine whether to override new and delete. */
+#ifndef U_OVERRIDE_CXX_ALLOCATION
+#define U_OVERRIDE_CXX_ALLOCATION 1
+#endif
+/* Determine whether to override placement new and delete for STL. */
+#ifndef U_HAVE_PLACEMENT_NEW
+#define U_HAVE_PLACEMENT_NEW 1
+#endif
+
+/* Determine whether to enable tracing. */
+#ifndef U_ENABLE_TRACING
+#define U_ENABLE_TRACING 0
+#endif
+
+/* Do we allow ICU users to use the draft APIs by default? */
+#ifndef U_DEFAULT_SHOW_DRAFT
+#define U_DEFAULT_SHOW_DRAFT 1
+#endif
+
+/* Define the library suffix in a C syntax. */
+#define U_HAVE_LIB_SUFFIX 0
+#define U_LIB_SUFFIX_C_NAME 
+#define U_LIB_SUFFIX_C_NAME_STRING ""
+
+/*===========================================================================*/
+/* Character data types                                                      */
+/*===========================================================================*/
+
+#if ((defined(OS390) && (!defined(__CHARSET_LIB) || !__CHARSET_LIB))) || defined(OS400)
+#   define U_CHARSET_FAMILY 1
+#endif
+
+/*===========================================================================*/
+/* Information about wchar support                                           */
+/*===========================================================================*/
+
+#define U_HAVE_WCHAR_H      1
+#define U_SIZEOF_WCHAR_T    4
+
+#define U_HAVE_WCSCPY       1
+
+/**
+ * \def U_DECLARE_UTF16
+ * Do not use this macro. Use the UNICODE_STRING or U_STRING_DECL macros
+ * instead.
+ * @internal
+ */
+#if 1 || defined(U_CHECK_UTF16_STRING)
+#if (defined(__xlC__) && defined(__IBM_UTF_LITERAL) && U_SIZEOF_WCHAR_T != 2) \
+    || (defined(__HP_aCC) && __HP_aCC >= 035000) \
+    || (defined(__HP_cc) && __HP_cc >= 111106)
+#define U_DECLARE_UTF16(string) u ## string
+#elif (defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x550)
+/* || (defined(__SUNPRO_C) && __SUNPRO_C >= 0x580) */
+/* Sun's C compiler has issues with this notation, and it's unreliable. */
+#define U_DECLARE_UTF16(string) U ## string
+#elif U_SIZEOF_WCHAR_T == 2 \
+    && (U_CHARSET_FAMILY == 0 || ((defined(OS390) || defined(OS400)) && defined(__UCS2__)))
+#define U_DECLARE_UTF16(string) L ## string
+#endif
+#endif
+
+/*===========================================================================*/
+/* Information about POSIX support                                           */
+/*===========================================================================*/
+
+#define U_HAVE_NL_LANGINFO_CODESET  1
+#define U_NL_LANGINFO_CODESET       CODESET
+
+#if 1
+#define U_TZSET         tzset
+#endif
+#if 1
+#define U_TIMEZONE      timezone
+#endif
+#if 1
+#define U_TZNAME        tzname
+#endif
+
+#define U_HAVE_MMAP     1
+#define U_HAVE_POPEN    1
+
+/*===========================================================================*/
+/* Symbol import-export control                                              */
+/*===========================================================================*/
+
+#if 1
+#define U_EXPORT __attribute__((visibility("default")))
+#elif (defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x550) \
+   || (defined(__SUNPRO_C) && __SUNPRO_C >= 0x550) 
+#define U_EXPORT __global
+/*#elif defined(__HP_aCC) || defined(__HP_cc)
+#define U_EXPORT __declspec(dllexport)*/
+#else
+#define U_EXPORT
+#endif
+
+/* U_CALLCONV is releated to U_EXPORT2 */
+#define U_EXPORT2
+
+/* cygwin needs to export/import data */
+#ifdef U_CYGWIN
+#define U_IMPORT __declspec(dllimport)
+#else
+#define U_IMPORT 
+#endif
+
+/*===========================================================================*/
+/* Code alignment and C function inlining                                    */
+/*===========================================================================*/
+
+#ifndef U_INLINE
+#   ifdef __cplusplus
+#       define U_INLINE inline
+#   else
+#       define U_INLINE inline
+#   endif
+#endif
+
+#define U_ALIGN_CODE(n) 
+
+/*===========================================================================*/
+/* Programs used by ICU code                                                 */
+/*===========================================================================*/
+
+#define U_MAKE  "/usr/bin/gnumake"

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/plurfmt.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/plurfmt.h b/src/apps/couch_collate/platform/osx/icu/unicode/plurfmt.h
new file mode 100644
index 0000000..445db39
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/plurfmt.h
@@ -0,0 +1,541 @@
+/*
+*******************************************************************************
+* Copyright (C) 2007-2008, International Business Machines Corporation and
+* others. All Rights Reserved.
+*******************************************************************************
+*
+
+* File PLURFMT.H
+*
+* Modification History:*
+*   Date        Name        Description
+*
+********************************************************************************
+*/
+
+#ifndef PLURFMT
+#define PLURFMT
+
+#include "unicode/utypes.h"
+
+/**
+ * \file
+ * \brief C++ API: PluralFormat object
+ */
+
+#if !UCONFIG_NO_FORMATTING
+
+#include "unicode/numfmt.h"
+#include "unicode/plurrule.h"
+
+U_NAMESPACE_BEGIN
+
+class Hashtable;
+
+/**
+ * <p>
+ * <code>PluralFormat</code> supports the creation of internationalized
+ * messages with plural inflection. It is based on <i>plural
+ * selection</i>, i.e. the caller specifies messages for each
+ * plural case that can appear in the users language and the
+ * <code>PluralFormat</code> selects the appropriate message based on
+ * the number.
+ * </p>
+ * <h4>The Problem of Plural Forms in Internationalized Messages</h4>
+ * <p>
+ * Different languages have different ways to inflect
+ * plurals. Creating internationalized messages that include plural
+ * forms is only feasible when the framework is able to handle plural
+ * forms of <i>all</i> languages correctly. <code>ChoiceFormat</code>
+ * doesn't handle this well, because it attaches a number interval to
+ * each message and selects the message whose interval contains a
+ * given number. This can only handle a finite number of
+ * intervals. But in some languages, like Polish, one plural case
+ * applies to infinitely many intervals (e.g., paucal applies to
+ * numbers ending with 2, 3, or 4 except those ending with 12, 13, or
+ * 14). Thus <code>ChoiceFormat</code> is not adequate.
+ * </p><p>
+ * <code>PluralFormat</code> deals with this by breaking the problem
+ * into two parts:
+ * <ul>
+ * <li>It uses <code>PluralRules</code> that can define more complex
+ *     conditions for a plural case than just a single interval. These plural
+ *     rules define both what plural cases exist in a language, and to
+ *     which numbers these cases apply.
+ * <li>It provides predefined plural rules for many locales. Thus, the programmer
+ *     need not worry about the plural cases of a language. On the flip side,
+ *     the localizer does not have to specify the plural cases; he can simply
+ *     use the predefined keywords. The whole plural formatting of messages can
+ *     be done using localized patterns from resource bundles.
+ * </ul>
+ * </p>
+ * <h4>Usage of <code>PluralFormat</code></h4>
+ * <p>
+ * This discussion assumes that you use <code>PluralFormat</code> with
+ * a predefined set of plural rules. You can create one using one of
+ * the constructors that takes a <code>locale</code> object. To
+ * specify the message pattern, you can either pass it to the
+ * constructor or set it explicitly using the
+ * <code>applyPattern()</code> method. The <code>format()</code>
+ * method takes a number object and selects the message of the
+ * matching plural case. This message will be returned.
+ * </p>
+ * <h5>Patterns and Their Interpretation</h5>
+ * <p>
+ * The pattern text defines the message output for each plural case of the
+ * used locale. The pattern is a sequence of
+ * <code><i>caseKeyword</i>{<i>message</i>}</code> clauses, separated by white
+ * space characters. Each clause assigns the message <code><i>message</i></code>
+ * to the plural case identified by <code><i>caseKeyword</i></code>.
+ * </p><p>
+ * You always have to define a message text for the default plural case
+ * "<code>other</code>" which is contained in every rule set. If the plural
+ * rules of the <code>PluralFormat</code> object do not contain a plural case
+ * identified by <code><i>caseKeyword</i></code>, U_DEFAULT_KEYWORD_MISSING
+ * will be set to status.
+ * If you do not specify a message text for a particular plural case, the
+ * message text of the plural case "<code>other</code>" gets assigned to this
+ * plural case. If you specify more than one message for the same plural case,
+ * U_DUPLICATE_KEYWORD will be set to status.
+ * <br/>
+ * Spaces between <code><i>caseKeyword</i></code> and
+ * <code><i>message</i></code>  will be ignored; spaces within
+ * <code><i>message</i></code> will be preserved.
+ * </p><p>
+ * The message text for a particular plural case may contain other message
+ * format patterns. <code>PluralFormat</code> preserves these so that you
+ * can use the strings produced by <code>PluralFormat</code> with other
+ * formatters. If you are using <code>PluralFormat</code> inside a
+ * <code>MessageFormat</code> pattern, <code>MessageFormat</code> will
+ * automatically evaluate the resulting format pattern.<br/>
+ * Thus, curly braces (<code>{</code>, <code>}</code>) are <i>only</i> allowed
+ * in message texts to define a nested format pattern.<br/>
+ * The pound sign (<code>#</code>) will be interpreted as the number placeholder
+ * in the message text, if it is not contained in curly braces (to preserve
+ * <code>NumberFormat</code> patterns). <code>PluralFormat</code> will
+ * replace each of those pound signs by the number passed to the
+ * <code>format()</code> method. It will be formatted using a
+ * <code>NumberFormat</code> for the <code>PluralFormat</code>'s locale. If you
+ * need special number formatting, you have to explicitly specify a
+ * <code>NumberFormat</code> for the <code>PluralFormat</code> to use.
+ * </p>
+ * Example
+ * <pre>
+ * UErrorCode status = U_ZERO_ERROR;
+ * MessageFormat* msgFmt = new MessageFormat(UnicodeString("{0, plural,
+ *   one{{0, number, C''est #,##0.0#  fichier}} other {Ce sont # fichiers}} dans la liste."),
+ *   Locale("fr"), status);
+ * if (U_FAILURE(status)) {
+ *     return;
+ * }
+ * Formattable args1[] = {(int32_t)0};
+ * Formattable args2[] = {(int32_t)3};
+ * FieldPosition ignore(FieldPosition::DONT_CARE);
+ * UnicodeString result;
+ * msgFmt->format(args1, 1, result, ignore, status);
+ * cout << result << endl;
+ * result.remove();
+ * msgFmt->format(args2, 1, result, ignore, status);
+ * cout << result << endl;
+ * </pre>
+ * Produces the output:<br/>
+ * <code>C'est 0,0 fichier dans la liste.</code><br/>
+ * <code>Ce sont 3 fichiers dans la liste."</code>
+ * <p>
+ * <strong>Note:</strong><br/>
+ *   Currently <code>PluralFormat</code>
+ *   does not make use of quotes like <code>MessageFormat</code>.
+ *   If you use plural format strings with <code>MessageFormat</code> and want
+ *   to use a quote sign "<code>'</code>", you have to write "<code>''</code>".
+ *   <code>MessageFormat</code> unquotes this pattern and  passes the unquoted
+ *   pattern to <code>PluralFormat</code>. It's a bit trickier if you use
+ *   nested formats that do quoting. In the example above, we wanted to insert
+ *   "<code>'</code>" in the number format pattern. Since
+ *   <code>NumberFormat</code> supports quotes, we had to insert
+ *   "<code>''</code>". But since <code>MessageFormat</code> unquotes the
+ *   pattern before it gets passed to <code>PluralFormat</code>, we have to
+ *   double these quotes, i.e. write "<code>''''</code>".
+ * </p>
+ * <h4>Defining Custom Plural Rules</h4>
+ * <p>If you need to use <code>PluralFormat</code> with custom rules, you can
+ * create a <code>PluralRules</code> object and pass it to
+ * <code>PluralFormat</code>'s constructor. If you also specify a locale in this
+ * constructor, this locale will be used to format the number in the message
+ * texts.
+ * </p><p>
+ * For more information about <code>PluralRules</code>, see
+ * {@link PluralRules}.
+ * </p>
+ *
+ * ported from Java
+ * @draft ICU 4.0
+ */
+
+class U_I18N_API PluralFormat : public Format {
+public:
+
+    /**
+     * Creates a new <code>PluralFormat</code> for the default locale.
+     * This locale will be used to get the set of plural rules and for standard
+     * number formatting.
+     * @param status  output param set to success/failure code on exit, which
+     *                must not indicate a failure before the function call.
+     * @draft ICU 4.0
+     */
+    PluralFormat(UErrorCode& status);
+
+    /**
+     * Creates a new <code>PluralFormat</code> for a given locale.
+     * @param locale the <code>PluralFormat</code> will be configured with
+     *               rules for this locale. This locale will also be used for
+     *               standard number formatting.
+     * @param status output param set to success/failure code on exit, which
+     *               must not indicate a failure before the function call.
+     * @draft ICU 4.0
+     */
+    PluralFormat(const Locale& locale, UErrorCode& status);
+
+    /**
+     * Creates a new <code>PluralFormat</code> for a given set of rules.
+     * The standard number formatting will be done using the default locale.
+     * @param rules   defines the behavior of the <code>PluralFormat</code>
+     *                object.
+     * @param status  output param set to success/failure code on exit, which
+     *                must not indicate a failure before the function call.
+     * @draft ICU 4.0
+     */
+    PluralFormat(const PluralRules& rules, UErrorCode& status);
+
+    /**
+     * Creates a new <code>PluralFormat</code> for a given set of rules.
+     * The standard number formatting will be done using the given locale.
+     * @param locale  the default number formatting will be done using this
+     *                locale.
+     * @param rules   defines the behavior of the <code>PluralFormat</code>
+     *                object.
+     * @param status  output param set to success/failure code on exit, which
+     *                must not indicate a failure before the function call.
+     * @draft ICU 4.0
+     */
+    PluralFormat(const Locale& locale, const PluralRules& rules, UErrorCode& status);
+
+    /**
+     * Creates a new <code>PluralFormat</code> for a given pattern string.
+     * The default locale will be used to get the set of plural rules and for
+     * standard number formatting.
+     * @param  pattern the pattern for this <code>PluralFormat</code>.
+     *                 errors are returned to status if the pattern is invalid.
+     * @param status   output param set to success/failure code on exit, which
+     *                 must not indicate a failure before the function call.
+     * @draft ICU 4.0
+     */
+    PluralFormat(const UnicodeString& pattern, UErrorCode& status);
+
+    /**
+     * Creates a new <code>PluralFormat</code> for a given pattern string and
+     * locale.
+     * The locale will be used to get the set of plural rules and for
+     * standard number formatting.
+     * @param locale   the <code>PluralFormat</code> will be configured with
+     *                 rules for this locale. This locale will also be used for
+     *                 standard number formatting.
+     * @param pattern  the pattern for this <code>PluralFormat</code>.
+     *                 errors are returned to status if the pattern is invalid.
+     * @param status   output param set to success/failure code on exit, which
+     *                 must not indicate a failure before the function call.
+     * @draft ICU 4.0
+     */
+    PluralFormat(const Locale& locale, const UnicodeString& pattern, UErrorCode& status);
+
+    /**
+     * Creates a new <code>PluralFormat</code> for a given set of rules, a
+     * pattern and a locale.
+     * @param rules    defines the behavior of the <code>PluralFormat</code>
+     *                 object.
+     * @param pattern  the pattern for this <code>PluralFormat</code>.
+     *                 errors are returned to status if the pattern is invalid.
+     * @param status   output param set to success/failure code on exit, which
+     *                 must not indicate a failure before the function call.
+     * @draft ICU 4.0
+     */
+    PluralFormat(const PluralRules& rules,
+                 const UnicodeString& pattern,
+                 UErrorCode& status);
+
+    /**
+     * Creates a new <code>PluralFormat</code> for a given set of rules, a
+     * pattern and a locale.
+     * @param locale  the <code>PluralFormat</code> will be configured with
+     *                rules for this locale. This locale will also be used for
+     *                standard number formatting.
+     * @param rules   defines the behavior of the <code>PluralFormat</code>
+     *                object.
+     * @param pattern the pattern for this <code>PluralFormat</code>.
+     *                errors are returned to status if the pattern is invalid.
+     * @param status  output param set to success/failure code on exit, which
+     *                must not indicate a failure before the function call.
+     * @draft ICU 4.0
+     */
+    PluralFormat(const Locale& locale,
+                 const PluralRules& rules,
+                 const UnicodeString& pattern,
+                 UErrorCode& status);
+
+    /**
+      * copy constructor.
+      * @draft ICU 4.0
+      */
+    PluralFormat(const PluralFormat& other);
+
+    /**
+     * Destructor.
+     * @draft ICU 4.0
+     */
+    virtual ~PluralFormat();
+
+    /**
+     * Sets the pattern used by this plural format.
+     * The method parses the pattern and creates a map of format strings
+     * for the plural rules.
+     * Patterns and their interpretation are specified in the class description.
+     *
+     * @param pattern the pattern for this plural format
+     *                errors are returned to status if the pattern is invalid.
+     * @param status  output param set to success/failure code on exit, which
+     *                must not indicate a failure before the function call.
+     * @draft ICU 4.0
+     */
+    void applyPattern(const UnicodeString& pattern, UErrorCode& status);
+
+    /**
+     * Formats a plural message for a given number.
+     *
+     * @param number  a number for which the plural message should be formatted
+     *                for. If no pattern has been applied to this
+     *                <code>PluralFormat</code> object yet, the formatted number
+     *                will be returned.
+     * @param status  output param set to success/failure code on exit, which
+     *                must not indicate a failure before the function call.
+     * @return        the string containing the formatted plural message.
+     * @draft ICU 4.0
+     */
+    UnicodeString format(int32_t number, UErrorCode& status) const;   
+    
+    /**
+     * Formats a plural message for a given number.
+     *
+     * @param number  a number for which the plural message should be formatted
+     *                for. If no pattern has been applied to this
+     *                <code>PluralFormat</code> object yet, the formatted number
+     *                will be returned.
+     * @param status  output param set to success/failure code on exit, which
+     *                must not indicate a failure before the function call.
+     * @return        the string containing the formatted plural message.
+     * @draft ICU 4.0
+     */
+    UnicodeString format(double number, UErrorCode& status) const;
+
+    /**
+     * Formats a plural message for a given number.
+     *
+     * @param number   a number for which the plural message should be formatted
+     *                 for. If no pattern has been applied to this
+     *                 <code>PluralFormat</code> object yet, the formatted number
+     *                 will be returned.
+     * @param appendTo output parameter to receive result.
+     *                 result is appended to existing contents.
+     * @param pos      On input: an alignment field, if desired.
+     *                 On output: the offsets of the alignment field.
+     * @param status   output param set to success/failure code on exit, which
+     *                 must not indicate a failure before the function call.
+     * @return         the string containing the formatted plural message.
+     * @draft ICU 4.0
+     */
+    UnicodeString& format(int32_t number,
+                          UnicodeString& appendTo,
+                          FieldPosition& pos,
+                          UErrorCode& status) const;
+    
+    /**
+     * Formats a plural message for a given number.
+     *
+     * @param number   a number for which the plural message should be formatted
+     *                 for. If no pattern has been applied to this
+     *                 <code>PluralFormat</code> object yet, the formatted number
+     *                 will be returned.
+     * @param appendTo output parameter to receive result.
+     *                 result is appended to existing contents.
+     * @param pos      On input: an alignment field, if desired.
+     *                 On output: the offsets of the alignment field.
+     * @param status   output param set to success/failure code on exit, which
+     *                 must not indicate a failure before the function call.
+     * @return         the string containing the formatted plural message.
+     * @draft ICU 4.0
+     */
+    UnicodeString& format(double number,
+                          UnicodeString& appendTo,
+                          FieldPosition& pos,
+                          UErrorCode& status) const;
+
+    /**
+     * Sets the locale used by this <code>PluraFormat</code> object.
+     * Note: Calling this method resets this <code>PluraFormat</code> object,
+     *     i.e., a pattern that was applied previously will be removed,
+     *     and the NumberFormat is set to the default number format for
+     *     the locale.  The resulting format behaves the same as one
+     *     constructed from {@link #PluralFormat(locale)}.
+     * @param locale  the <code>locale</code> to use to configure the formatter.
+     * @param status  output param set to success/failure code on exit, which
+     *                must not indicate a failure before the function call.
+     * @draft ICU 4.0
+     */
+    void setLocale(const Locale& locale, UErrorCode& status);
+
+    /**
+      * Sets the number format used by this formatter.  You only need to
+      * call this if you want a different number format than the default
+      * formatter for the locale.
+      * @param format  the number format to use.
+      * @param status  output param set to success/failure code on exit, which
+      *                must not indicate a failure before the function call.
+      * @draft ICU 4.0
+      */
+    void setNumberFormat(const NumberFormat* format, UErrorCode& status);
+
+    /**
+       * Assignment operator
+       *
+       * @param other    the PluralFormat object to copy from.
+       * @draft ICU 4.0
+       */
+    PluralFormat& operator=(const PluralFormat& other);
+
+    /**
+      * Return true if another object is semantically equal to this one.
+      *
+      * @param other    the PluralFormat object to be compared with.
+      * @return         true if other is semantically equal to this.
+      * @draft ICU 4.0
+      */
+    virtual UBool operator==(const Format& other) const;
+
+    /**
+     * Return true if another object is semantically unequal to this one.
+     *
+     * @param other    the PluralFormat object to be compared with.
+     * @return         true if other is semantically unequal to this.
+     * @draft ICU 4.0
+     */
+    virtual UBool operator!=(const Format& other) const;
+
+    /**
+     * Clones this Format object polymorphically.  The caller owns the
+     * result and should delete it when done.
+     * @draft ICU 4.0
+     */
+    virtual Format* clone(void) const;
+
+    /**
+    * Redeclared Format method.
+    *
+    * @param obj       The object to be formatted into a string.
+    * @param appendTo  output parameter to receive result.
+    *                  Result is appended to existing contents.
+    * @param pos       On input: an alignment field, if desired.
+    *                  On output: the offsets of the alignment field.
+    * @param status    output param filled with success/failure status.
+    * @return          Reference to 'appendTo' parameter.
+    * @draft ICU 4.0
+    */
+   UnicodeString& format(const Formattable& obj,
+                         UnicodeString& appendTo,
+                         FieldPosition& pos,
+                         UErrorCode& status) const;
+
+   /**
+    * Returns the pattern from applyPattern() or constructor().
+    *
+    * @param  appendTo  output parameter to receive result.
+     *                  Result is appended to existing contents.
+    * @return the UnicodeString with inserted pattern.
+    * @draft ICU 4.0
+    */
+   UnicodeString& toPattern(UnicodeString& appendTo);
+
+   /**
+    * This method is not yet supported by <code>PluralFormat</code>.
+    * <P>
+    * Before calling, set parse_pos.index to the offset you want to start
+    * parsing at in the source. After calling, parse_pos.index is the end of
+    * the text you parsed. If error occurs, index is unchanged.
+    * <P>
+    * When parsing, leading whitespace is discarded (with a successful parse),
+    * while trailing whitespace is left as is.
+    * <P>
+    * See Format::parseObject() for more.
+    *
+    * @param source    The string to be parsed into an object.
+    * @param result    Formattable to be set to the parse result.
+    *                  If parse fails, return contents are undefined.
+    * @param parse_pos The position to start parsing at. Upon return
+    *                  this param is set to the position after the
+    *                  last character successfully parsed. If the
+    *                  source is not parsed successfully, this param
+    *                  will remain unchanged.
+    * @draft ICU 4.0
+    */
+   virtual void parseObject(const UnicodeString& source,
+                            Formattable& result,
+                            ParsePosition& parse_pos) const;
+
+    /**
+     * ICU "poor man's RTTI", returns a UClassID for this class.
+     *
+     * @draft ICU 4.0
+     *
+     */
+    static UClassID U_EXPORT2 getStaticClassID(void);
+
+    /**
+     * ICU "poor man's RTTI", returns a UClassID for the actual class.
+     *
+     * @draft ICU 4.0
+     */
+     virtual UClassID getDynamicClassID() const;
+
+private:
+    typedef enum fmtToken {
+        none,
+        tLetter,
+        tNumber,
+        tSpace,
+        tNumberSign,
+        tLeftBrace,
+        tRightBrace
+    }fmtToken;
+
+    Locale  locale;
+    PluralRules* pluralRules;
+    UnicodeString pattern;
+    Hashtable  *fParsedValuesHash;
+    NumberFormat*  numberFormat;
+    NumberFormat*  replacedNumberFormat;
+
+    PluralFormat();   // default constructor not implemented
+    void init(const PluralRules* rules, const Locale& curlocale, UErrorCode& status);
+    UBool inRange(UChar ch, fmtToken& type);
+    UBool checkSufficientDefinition();
+    void parsingFailure();
+    UnicodeString insertFormattedNumber(double number,
+                                        UnicodeString& message,
+                                        UnicodeString& appendTo,
+                                        FieldPosition& pos) const;
+    void copyHashtable(Hashtable *other, UErrorCode& status);
+};
+
+U_NAMESPACE_END
+
+#endif /* #if !UCONFIG_NO_FORMATTING */
+
+#endif // _PLURFMT
+//eof

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/plurrule.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/plurrule.h b/src/apps/couch_collate/platform/osx/icu/unicode/plurrule.h
new file mode 100644
index 0000000..7c3fedb
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/plurrule.h
@@ -0,0 +1,291 @@
+/*
+*******************************************************************************
+* Copyright (C) 2008, International Business Machines Corporation and
+* others. All Rights Reserved.
+*******************************************************************************
+*
+*
+* File PLURRULE.H
+*
+* Modification History:*
+*   Date        Name        Description
+*
+********************************************************************************
+*/
+
+#ifndef PLURRULE
+#define PLURRULE
+
+#include "unicode/utypes.h"
+
+/**
+ * \file
+ * \brief C++ API: PluralRules object
+ */
+
+#if !UCONFIG_NO_FORMATTING
+
+#include "unicode/format.h"
+
+U_NAMESPACE_BEGIN
+
+class Hashtable;
+class RuleChain;
+class RuleParser;
+
+/**
+ * Defines rules for mapping positive long values onto a small set of
+ * keywords. Rules are constructed from a text description, consisting
+ * of a series of keywords and conditions.  The {@link #select} method
+ * examines each condition in order and returns the keyword for the
+ * first condition that matches the number.  If none match,
+ * default rule(other) is returned.
+ *
+ * Examples:<pre>
+ *   "one: n is 1; few: n in 2..4"</pre>
+ *  This defines two rules, for 'one' and 'few'.  The condition for
+ *  'one' is "n is 1" which means that the number must be equal to
+ *  1 for this condition to pass.  The condition for 'few' is
+ *  "n in 2..4" which means that the number must be between 2 and
+ *  4 inclusive for this condition to pass.  All other numbers
+ *  are assigned the keyword "other" by the default rule.
+ *  </p><pre>
+ *    "zero: n is 0; one: n is 1; zero: n mod 100 in 1..19"</pre>
+ *  This illustrates that the same keyword can be defined multiple times.
+ *  Each rule is examined in order, and the first keyword whose condition
+ *  passes is the one returned.  Also notes that a modulus is applied
+ *  to n in the last rule.  Thus its condition holds for 119, 219, 319...
+ *  </p><pre>
+ *    "one: n is 1; few: n mod 10 in 2..4 and n mod 100 not in 12..14"</pre>
+ *  This illustrates conjunction and negation.  The condition for 'few'
+ *  has two parts, both of which must be met: "n mod 10 in 2..4" and
+ *  "n mod 100 not in 12..14".  The first part applies a modulus to n
+ *  before the test as in the previous example.  The second part applies
+ *  a different modulus and also uses negation, thus it matches all
+ *  numbers _not_ in 12, 13, 14, 112, 113, 114, 212, 213, 214...
+ *  </p>
+ *  <p>
+ * Syntax:<pre>
+ * rules         = rule (';' rule)*
+ * rule          = keyword ':' condition
+ * keyword       = <identifier>
+ * condition     = and_condition ('or' and_condition)*
+ * and_condition = relation ('and' relation)*
+ * relation      = is_relation | in_relation | within_relation | 'n' <EOL>
+ * is_relation   = expr 'is' ('not')? value
+ * in_relation   = expr ('not')? 'in' range
+ * within_relation = expr ('not')? 'within' range
+ * expr          = 'n' ('mod' value)?
+ * value         = digit+
+ * digit         = 0|1|2|3|4|5|6|7|8|9
+ * range         = value'..'value
+ * </pre></p>
+ * <p>
+ *  The difference between 'in' and 'within' is that 'in' only includes
+ *  integers in the specified range, while 'within' includes all values.</p>
+ *  <p>
+ *  Keywords
+ *  could be defined by users or from ICU locale data. There are 6
+ *  predefined values in ICU - 'zero', 'one', 'two', 'few', 'many' and
+ *  'other'. Callers need to check the value of keyword returned by
+ *  {@link #select} method.
+ *  </p>
+ *
+ * Examples:<pre>
+ * UnicodeString keyword = pl->select(number);
+ * if (keyword== UnicodeString("one") {
+ *     ...
+ * }
+ * else if ( ... )
+ * </pre>
+ */
+class U_I18N_API PluralRules : public UObject {
+public:
+
+    /**
+     * Constructor.
+     * @param status  Output param set to success/failure code on exit, which
+     *                must not indicate a failure before the function call.
+     *
+     * @draft ICU 4.0
+     */
+    PluralRules(UErrorCode& status);
+
+    /**
+     * Copy constructor.
+     * @draft ICU 4.0
+     */
+    PluralRules(const PluralRules& other);
+
+    /**
+     * Destructor.
+     * @draft ICU 4.0
+     */
+    virtual ~PluralRules();
+
+    /**
+     * Clone
+     * @draft ICU 4.0
+     */
+    PluralRules* clone() const;
+
+    /**
+      * Assignment operator.
+      * @draft ICU 4.0
+      */
+    PluralRules& operator=(const PluralRules&);
+
+    /**
+     * Creates a PluralRules from a description if it is parsable, otherwise
+     * returns null.
+     *
+     * @param description rule description
+     * @param status      Output param set to success/failure code on exit, which
+     *                    must not indicate a failure before the function call.
+     * @return            new PluralRules pointer. NULL if there is an error.
+     * @draft ICU 4.0
+     */
+    static PluralRules* U_EXPORT2 createRules(const UnicodeString& description,
+                                              UErrorCode& status);
+
+    /**
+     * The default rules that accept any number.
+     *
+     * @param status  Output param set to success/failure code on exit, which
+     *                must not indicate a failure before the function call.
+     * @return        new PluralRules pointer. NULL if there is an error.
+     * @draft ICU 4.0
+     */
+    static PluralRules* U_EXPORT2 createDefaultRules(UErrorCode& status);
+
+    /**
+     * Provides access to the predefined <code>PluralRules</code> for a given
+     * locale.
+     *
+     * @param locale  The locale for which a <code>PluralRules</code> object is
+     *                returned.
+     * @param status  Output param set to success/failure code on exit, which
+     *                must not indicate a failure before the function call.
+     * @return        The predefined <code>PluralRules</code> object pointer for
+     *                this locale. If there's no predefined rules for this locale,
+     *                the rules for the closest parent in the locale hierarchy
+     *                that has one will  be returned.  The final fallback always
+     *                returns the default 'other' rules.
+     * @draft ICU 4.0
+     */
+    static PluralRules* U_EXPORT2 forLocale(const Locale& locale, UErrorCode& status);
+    
+    /**
+     * Given a number, returns the keyword of the first rule that applies to
+     * the number.  This function can be used with isKeyword* functions to
+     * determine the keyword for default plural rules.
+     *
+     * @param number  The number for which the rule has to be determined.
+     * @return        The keyword of the selected rule.
+     * @draft ICU 4.0
+     */
+    UnicodeString select(int32_t number) const;
+    
+    /**
+     * Given a number, returns the keyword of the first rule that applies to
+     * the number.  This function can be used with isKeyword* functions to
+     * determine the keyword for default plural rules.
+     *
+     * @param number  The number for which the rule has to be determined.
+     * @return        The keyword of the selected rule.
+     * @draft ICU 4.0
+     */
+    UnicodeString select(double number) const;
+
+    /**
+     * Returns a list of all rule keywords used in this <code>PluralRules</code>
+     * object.  The rule 'other' is always present by default.
+     *
+     * @param status Output param set to success/failure code on exit, which
+     *               must not indicate a failure before the function call.
+     * @return       StringEnumeration with the keywords.
+     *               The caller must delete the object.
+     * @draft ICU 4.0
+     */
+    StringEnumeration* getKeywords(UErrorCode& status) const;
+
+    /**
+     * Returns TRUE if the given keyword is defined in this
+     * <code>PluralRules</code> object.
+     *
+     * @param keyword  the input keyword.
+     * @return         TRUE if the input keyword is defined.
+     *                 Otherwise, return FALSE.
+     * @draft ICU 4.0
+     */
+    UBool isKeyword(const UnicodeString& keyword) const;
+
+
+    /**
+     * Returns keyword for default plural form.
+     *
+     * @return         keyword for default plural form.
+     * @internal 4.0
+     * @draft ICU 4.0
+     */
+    UnicodeString getKeywordOther() const;
+
+    /**
+     * Compares the equality of two PluralRules objects.
+     *
+     * @param other The other PluralRules object to be compared with.
+     * @return      True if the given PluralRules is the same as this
+     *              PluralRules; false otherwise.
+     * @draft ICU 4.0
+     */
+    virtual UBool operator==(const PluralRules& other) const;
+
+    /**
+     * Compares the inequality of two PluralRules objects.
+     *
+     * @param other The PluralRules object to be compared with.
+     * @return      True if the given PluralRules is not the same as this
+     *              PluralRules; false otherwise.
+     * @draft ICU 4.0
+     */
+    UBool operator!=(const PluralRules& other) const  {return !operator==(other);}
+
+
+    /**
+     * ICU "poor man's RTTI", returns a UClassID for this class.
+     *
+     * @draft ICU 4.0
+     *
+    */
+    static UClassID U_EXPORT2 getStaticClassID(void);
+
+    /**
+     * ICU "poor man's RTTI", returns a UClassID for the actual class.
+     *
+     * @draft ICU 4.0
+     */
+    virtual UClassID getDynamicClassID() const;
+
+
+private:
+    Hashtable       *fLocaleStringsHash;
+    UnicodeString   mLocaleName;
+    RuleChain       *mRules;
+    RuleParser      *mParser;
+
+    PluralRules();   // default constructor not implemented
+    int32_t getRepeatLimit() const;
+    void parseDescription(UnicodeString& ruleData, RuleChain& rules, UErrorCode &status);
+    void getNextLocale(const UnicodeString& localeData, int32_t* curIndex, UnicodeString& localeName);
+    void addRules(RuleChain& rules);
+    int32_t getNumberValue(const UnicodeString& token) const;
+    UnicodeString getRuleFromResource(const Locale& locale, UErrorCode& status);
+
+};
+
+U_NAMESPACE_END
+
+#endif /* #if !UCONFIG_NO_FORMATTING */
+
+#endif // _PLURRULE
+//eof


[54/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/utf8.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/utf8.h b/src/apps/couch_collate/platform/osx/icu/unicode/utf8.h
new file mode 100644
index 0000000..1142c44
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/utf8.h
@@ -0,0 +1,652 @@
+/*
+*******************************************************************************
+*
+*   Copyright (C) 1999-2007, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+*
+*******************************************************************************
+*   file name:  utf8.h
+*   encoding:   US-ASCII
+*   tab size:   8 (not used)
+*   indentation:4
+*
+*   created on: 1999sep13
+*   created by: Markus W. Scherer
+*/
+
+/**
+ * \file
+ * \brief C API: 8-bit Unicode handling macros
+ * 
+ * This file defines macros to deal with 8-bit Unicode (UTF-8) code units (bytes) and strings.
+ * utf8.h is included by utf.h after unicode/umachine.h
+ * and some common definitions.
+ *
+ * For more information see utf.h and the ICU User Guide Strings chapter
+ * (http://icu-project.org/userguide/strings.html).
+ *
+ * <em>Usage:</em>
+ * ICU coding guidelines for if() statements should be followed when using these macros.
+ * Compound statements (curly braces {}) must be used  for if-else-while... 
+ * bodies and all macro statements should be terminated with semicolon.
+ */
+
+#ifndef __UTF8_H__
+#define __UTF8_H__
+
+/* utf.h must be included first. */
+#ifndef __UTF_H__
+#   include "unicode/utf.h"
+#endif
+
+/* internal definitions ----------------------------------------------------- */
+
+/**
+ * \var utf8_countTrailBytes
+ * Internal array with numbers of trail bytes for any given byte used in
+ * lead byte position.
+ * @internal
+ */
+#ifdef U_UTF8_IMPL
+U_EXPORT const uint8_t 
+#elif defined(U_STATIC_IMPLEMENTATION) || defined(U_COMMON_IMPLEMENTATION)
+U_CFUNC const uint8_t
+#else
+U_CFUNC U_IMPORT const uint8_t /* U_IMPORT2? */ /*U_IMPORT*/ 
+#endif
+utf8_countTrailBytes[256];
+
+/**
+ * Count the trail bytes for a UTF-8 lead byte.
+ * @internal
+ */
+#define U8_COUNT_TRAIL_BYTES(leadByte) (utf8_countTrailBytes[(uint8_t)leadByte])
+
+/**
+ * Mask a UTF-8 lead byte, leave only the lower bits that form part of the code point value.
+ * @internal
+ */
+#define U8_MASK_LEAD_BYTE(leadByte, countTrailBytes) ((leadByte)&=(1<<(6-(countTrailBytes)))-1)
+
+/**
+ * Function for handling "next code point" with error-checking.
+ * @internal
+ */
+U_INTERNAL UChar32 U_EXPORT2
+utf8_nextCharSafeBody(const uint8_t *s, int32_t *pi, int32_t length, UChar32 c, UBool strict);
+
+/**
+ * Function for handling "append code point" with error-checking.
+ * @internal
+ */
+U_INTERNAL int32_t U_EXPORT2
+utf8_appendCharSafeBody(uint8_t *s, int32_t i, int32_t length, UChar32 c, UBool *pIsError);
+
+/**
+ * Function for handling "previous code point" with error-checking.
+ * @internal
+ */
+U_INTERNAL UChar32 U_EXPORT2
+utf8_prevCharSafeBody(const uint8_t *s, int32_t start, int32_t *pi, UChar32 c, UBool strict);
+
+/**
+ * Function for handling "skip backward one code point" with error-checking.
+ * @internal
+ */
+U_INTERNAL int32_t U_EXPORT2
+utf8_back1SafeBody(const uint8_t *s, int32_t start, int32_t i);
+
+/* single-code point definitions -------------------------------------------- */
+
+/**
+ * Does this code unit (byte) encode a code point by itself (US-ASCII 0..0x7f)?
+ * @param c 8-bit code unit (byte)
+ * @return TRUE or FALSE
+ * @stable ICU 2.4
+ */
+#define U8_IS_SINGLE(c) (((c)&0x80)==0)
+
+/**
+ * Is this code unit (byte) a UTF-8 lead byte?
+ * @param c 8-bit code unit (byte)
+ * @return TRUE or FALSE
+ * @stable ICU 2.4
+ */
+#define U8_IS_LEAD(c) ((uint8_t)((c)-0xc0)<0x3e)
+
+/**
+ * Is this code unit (byte) a UTF-8 trail byte?
+ * @param c 8-bit code unit (byte)
+ * @return TRUE or FALSE
+ * @stable ICU 2.4
+ */
+#define U8_IS_TRAIL(c) (((c)&0xc0)==0x80)
+
+/**
+ * How many code units (bytes) are used for the UTF-8 encoding
+ * of this Unicode code point?
+ * @param c 32-bit code point
+ * @return 1..4, or 0 if c is a surrogate or not a Unicode code point
+ * @stable ICU 2.4
+ */
+#define U8_LENGTH(c) \
+    ((uint32_t)(c)<=0x7f ? 1 : \
+        ((uint32_t)(c)<=0x7ff ? 2 : \
+            ((uint32_t)(c)<=0xd7ff ? 3 : \
+                ((uint32_t)(c)<=0xdfff || (uint32_t)(c)>0x10ffff ? 0 : \
+                    ((uint32_t)(c)<=0xffff ? 3 : 4)\
+                ) \
+            ) \
+        ) \
+    )
+
+/**
+ * The maximum number of UTF-8 code units (bytes) per Unicode code point (U+0000..U+10ffff).
+ * @return 4
+ * @stable ICU 2.4
+ */
+#define U8_MAX_LENGTH 4
+
+/**
+ * Get a code point from a string at a random-access offset,
+ * without changing the offset.
+ * The offset may point to either the lead byte or one of the trail bytes
+ * for a code point, in which case the macro will read all of the bytes
+ * for the code point.
+ * The result is undefined if the offset points to an illegal UTF-8
+ * byte sequence.
+ * Iteration through a string is more efficient with U8_NEXT_UNSAFE or U8_NEXT.
+ *
+ * @param s const uint8_t * string
+ * @param i string offset
+ * @param c output UChar32 variable
+ * @see U8_GET
+ * @stable ICU 2.4
+ */
+#define U8_GET_UNSAFE(s, i, c) { \
+    int32_t _u8_get_unsafe_index=(int32_t)(i); \
+    U8_SET_CP_START_UNSAFE(s, _u8_get_unsafe_index); \
+    U8_NEXT_UNSAFE(s, _u8_get_unsafe_index, c); \
+}
+
+/**
+ * Get a code point from a string at a random-access offset,
+ * without changing the offset.
+ * The offset may point to either the lead byte or one of the trail bytes
+ * for a code point, in which case the macro will read all of the bytes
+ * for the code point.
+ * If the offset points to an illegal UTF-8 byte sequence, then
+ * c is set to a negative value.
+ * Iteration through a string is more efficient with U8_NEXT_UNSAFE or U8_NEXT.
+ *
+ * @param s const uint8_t * string
+ * @param start starting string offset
+ * @param i string offset, must be start<=i<length
+ * @param length string length
+ * @param c output UChar32 variable, set to <0 in case of an error
+ * @see U8_GET_UNSAFE
+ * @stable ICU 2.4
+ */
+#define U8_GET(s, start, i, length, c) { \
+    int32_t _u8_get_index=(int32_t)(i); \
+    U8_SET_CP_START(s, start, _u8_get_index); \
+    U8_NEXT(s, _u8_get_index, length, c); \
+}
+
+/* definitions with forward iteration --------------------------------------- */
+
+/**
+ * Get a code point from a string at a code point boundary offset,
+ * and advance the offset to the next code point boundary.
+ * (Post-incrementing forward iteration.)
+ * "Unsafe" macro, assumes well-formed UTF-8.
+ *
+ * The offset may point to the lead byte of a multi-byte sequence,
+ * in which case the macro will read the whole sequence.
+ * The result is undefined if the offset points to a trail byte
+ * or an illegal UTF-8 sequence.
+ *
+ * @param s const uint8_t * string
+ * @param i string offset
+ * @param c output UChar32 variable
+ * @see U8_NEXT
+ * @stable ICU 2.4
+ */
+#define U8_NEXT_UNSAFE(s, i, c) { \
+    (c)=(uint8_t)(s)[(i)++]; \
+    if((uint8_t)((c)-0xc0)<0x35) { \
+        uint8_t __count=U8_COUNT_TRAIL_BYTES(c); \
+        U8_MASK_LEAD_BYTE(c, __count); \
+        switch(__count) { \
+        /* each following branch falls through to the next one */ \
+        case 3: \
+            (c)=((c)<<6)|((s)[(i)++]&0x3f); \
+        case 2: \
+            (c)=((c)<<6)|((s)[(i)++]&0x3f); \
+        case 1: \
+            (c)=((c)<<6)|((s)[(i)++]&0x3f); \
+        /* no other branches to optimize switch() */ \
+            break; \
+        } \
+    } \
+}
+
+/**
+ * Get a code point from a string at a code point boundary offset,
+ * and advance the offset to the next code point boundary.
+ * (Post-incrementing forward iteration.)
+ * "Safe" macro, checks for illegal sequences and for string boundaries.
+ *
+ * The offset may point to the lead byte of a multi-byte sequence,
+ * in which case the macro will read the whole sequence.
+ * If the offset points to a trail byte or an illegal UTF-8 sequence, then
+ * c is set to a negative value.
+ *
+ * @param s const uint8_t * string
+ * @param i string offset, must be i<length
+ * @param length string length
+ * @param c output UChar32 variable, set to <0 in case of an error
+ * @see U8_NEXT_UNSAFE
+ * @stable ICU 2.4
+ */
+#define U8_NEXT(s, i, length, c) { \
+    (c)=(uint8_t)(s)[(i)++]; \
+    if((c)>=0x80) { \
+        uint8_t __t1, __t2; \
+        if( /* handle U+1000..U+CFFF inline */ \
+            (0xe0<(c) && (c)<=0xec) && \
+            (((i)+1)<(length)) && \
+            (__t1=(uint8_t)((s)[i]-0x80))<=0x3f && \
+            (__t2=(uint8_t)((s)[(i)+1]-0x80))<= 0x3f \
+        ) { \
+            /* no need for (c&0xf) because the upper bits are truncated after <<12 in the cast to (UChar) */ \
+            (c)=(UChar)(((c)<<12)|(__t1<<6)|__t2); \
+            (i)+=2; \
+        } else if( /* handle U+0080..U+07FF inline */ \
+            ((c)<0xe0 && (c)>=0xc2) && \
+            ((i)<(length)) && \
+            (__t1=(uint8_t)((s)[i]-0x80))<=0x3f \
+        ) { \
+            (c)=(UChar)((((c)&0x1f)<<6)|__t1); \
+            ++(i); \
+        } else if(U8_IS_LEAD(c)) { \
+            /* function call for "complicated" and error cases */ \
+            (c)=utf8_nextCharSafeBody((const uint8_t *)s, &(i), (int32_t)(length), c, -1); \
+        } else { \
+            (c)=U_SENTINEL; \
+        } \
+    } \
+}
+
+/**
+ * Append a code point to a string, overwriting 1 to 4 bytes.
+ * The offset points to the current end of the string contents
+ * and is advanced (post-increment).
+ * "Unsafe" macro, assumes a valid code point and sufficient space in the string.
+ * Otherwise, the result is undefined.
+ *
+ * @param s const uint8_t * string buffer
+ * @param i string offset
+ * @param c code point to append
+ * @see U8_APPEND
+ * @stable ICU 2.4
+ */
+#define U8_APPEND_UNSAFE(s, i, c) { \
+    if((uint32_t)(c)<=0x7f) { \
+        (s)[(i)++]=(uint8_t)(c); \
+    } else { \
+        if((uint32_t)(c)<=0x7ff) { \
+            (s)[(i)++]=(uint8_t)(((c)>>6)|0xc0); \
+        } else { \
+            if((uint32_t)(c)<=0xffff) { \
+                (s)[(i)++]=(uint8_t)(((c)>>12)|0xe0); \
+            } else { \
+                (s)[(i)++]=(uint8_t)(((c)>>18)|0xf0); \
+                (s)[(i)++]=(uint8_t)((((c)>>12)&0x3f)|0x80); \
+            } \
+            (s)[(i)++]=(uint8_t)((((c)>>6)&0x3f)|0x80); \
+        } \
+        (s)[(i)++]=(uint8_t)(((c)&0x3f)|0x80); \
+    } \
+}
+
+/**
+ * Append a code point to a string, overwriting 1 to 4 bytes.
+ * The offset points to the current end of the string contents
+ * and is advanced (post-increment).
+ * "Safe" macro, checks for a valid code point.
+ * If a non-ASCII code point is written, checks for sufficient space in the string.
+ * If the code point is not valid or trail bytes do not fit,
+ * then isError is set to TRUE.
+ *
+ * @param s const uint8_t * string buffer
+ * @param i string offset, must be i<capacity
+ * @param capacity size of the string buffer
+ * @param c code point to append
+ * @param isError output UBool set to TRUE if an error occurs, otherwise not modified
+ * @see U8_APPEND_UNSAFE
+ * @stable ICU 2.4
+ */
+#define U8_APPEND(s, i, capacity, c, isError) { \
+    if((uint32_t)(c)<=0x7f) { \
+        (s)[(i)++]=(uint8_t)(c); \
+    } else if((uint32_t)(c)<=0x7ff && (i)+1<(capacity)) { \
+        (s)[(i)++]=(uint8_t)(((c)>>6)|0xc0); \
+        (s)[(i)++]=(uint8_t)(((c)&0x3f)|0x80); \
+    } else if((uint32_t)(c)<=0xd7ff && (i)+2<(capacity)) { \
+        (s)[(i)++]=(uint8_t)(((c)>>12)|0xe0); \
+        (s)[(i)++]=(uint8_t)((((c)>>6)&0x3f)|0x80); \
+        (s)[(i)++]=(uint8_t)(((c)&0x3f)|0x80); \
+    } else { \
+        (i)=utf8_appendCharSafeBody(s, (int32_t)(i), (int32_t)(capacity), c, &(isError)); \
+    } \
+}
+
+/**
+ * Advance the string offset from one code point boundary to the next.
+ * (Post-incrementing iteration.)
+ * "Unsafe" macro, assumes well-formed UTF-8.
+ *
+ * @param s const uint8_t * string
+ * @param i string offset
+ * @see U8_FWD_1
+ * @stable ICU 2.4
+ */
+#define U8_FWD_1_UNSAFE(s, i) { \
+    (i)+=1+U8_COUNT_TRAIL_BYTES((s)[i]); \
+}
+
+/**
+ * Advance the string offset from one code point boundary to the next.
+ * (Post-incrementing iteration.)
+ * "Safe" macro, checks for illegal sequences and for string boundaries.
+ *
+ * @param s const uint8_t * string
+ * @param i string offset, must be i<length
+ * @param length string length
+ * @see U8_FWD_1_UNSAFE
+ * @stable ICU 2.4
+ */
+#define U8_FWD_1(s, i, length) { \
+    uint8_t __b=(uint8_t)(s)[(i)++]; \
+    if(U8_IS_LEAD(__b)) { \
+        uint8_t __count=U8_COUNT_TRAIL_BYTES(__b); \
+        if((i)+__count>(length)) { \
+            __count=(uint8_t)((length)-(i)); \
+        } \
+        while(__count>0 && U8_IS_TRAIL((s)[i])) { \
+            ++(i); \
+            --__count; \
+        } \
+    } \
+}
+
+/**
+ * Advance the string offset from one code point boundary to the n-th next one,
+ * i.e., move forward by n code points.
+ * (Post-incrementing iteration.)
+ * "Unsafe" macro, assumes well-formed UTF-8.
+ *
+ * @param s const uint8_t * string
+ * @param i string offset
+ * @param n number of code points to skip
+ * @see U8_FWD_N
+ * @stable ICU 2.4
+ */
+#define U8_FWD_N_UNSAFE(s, i, n) { \
+    int32_t __N=(n); \
+    while(__N>0) { \
+        U8_FWD_1_UNSAFE(s, i); \
+        --__N; \
+    } \
+}
+
+/**
+ * Advance the string offset from one code point boundary to the n-th next one,
+ * i.e., move forward by n code points.
+ * (Post-incrementing iteration.)
+ * "Safe" macro, checks for illegal sequences and for string boundaries.
+ *
+ * @param s const uint8_t * string
+ * @param i string offset, must be i<length
+ * @param length string length
+ * @param n number of code points to skip
+ * @see U8_FWD_N_UNSAFE
+ * @stable ICU 2.4
+ */
+#define U8_FWD_N(s, i, length, n) { \
+    int32_t __N=(n); \
+    while(__N>0 && (i)<(length)) { \
+        U8_FWD_1(s, i, length); \
+        --__N; \
+    } \
+}
+
+/**
+ * Adjust a random-access offset to a code point boundary
+ * at the start of a code point.
+ * If the offset points to a UTF-8 trail byte,
+ * then the offset is moved backward to the corresponding lead byte.
+ * Otherwise, it is not modified.
+ * "Unsafe" macro, assumes well-formed UTF-8.
+ *
+ * @param s const uint8_t * string
+ * @param i string offset
+ * @see U8_SET_CP_START
+ * @stable ICU 2.4
+ */
+#define U8_SET_CP_START_UNSAFE(s, i) { \
+    while(U8_IS_TRAIL((s)[i])) { --(i); } \
+}
+
+/**
+ * Adjust a random-access offset to a code point boundary
+ * at the start of a code point.
+ * If the offset points to a UTF-8 trail byte,
+ * then the offset is moved backward to the corresponding lead byte.
+ * Otherwise, it is not modified.
+ * "Safe" macro, checks for illegal sequences and for string boundaries.
+ *
+ * @param s const uint8_t * string
+ * @param start starting string offset (usually 0)
+ * @param i string offset, must be start<=i
+ * @see U8_SET_CP_START_UNSAFE
+ * @stable ICU 2.4
+ */
+#define U8_SET_CP_START(s, start, i) { \
+    if(U8_IS_TRAIL((s)[(i)])) { \
+        (i)=utf8_back1SafeBody(s, start, (int32_t)(i)); \
+    } \
+}
+
+/* definitions with backward iteration -------------------------------------- */
+
+/**
+ * Move the string offset from one code point boundary to the previous one
+ * and get the code point between them.
+ * (Pre-decrementing backward iteration.)
+ * "Unsafe" macro, assumes well-formed UTF-8.
+ *
+ * The input offset may be the same as the string length.
+ * If the offset is behind a multi-byte sequence, then the macro will read
+ * the whole sequence.
+ * If the offset is behind a lead byte, then that itself
+ * will be returned as the code point.
+ * The result is undefined if the offset is behind an illegal UTF-8 sequence.
+ *
+ * @param s const uint8_t * string
+ * @param i string offset
+ * @param c output UChar32 variable
+ * @see U8_PREV
+ * @stable ICU 2.4
+ */
+#define U8_PREV_UNSAFE(s, i, c) { \
+    (c)=(uint8_t)(s)[--(i)]; \
+    if(U8_IS_TRAIL(c)) { \
+        uint8_t __b, __count=1, __shift=6; \
+\
+        /* c is a trail byte */ \
+        (c)&=0x3f; \
+        for(;;) { \
+            __b=(uint8_t)(s)[--(i)]; \
+            if(__b>=0xc0) { \
+                U8_MASK_LEAD_BYTE(__b, __count); \
+                (c)|=(UChar32)__b<<__shift; \
+                break; \
+            } else { \
+                (c)|=(UChar32)(__b&0x3f)<<__shift; \
+                ++__count; \
+                __shift+=6; \
+            } \
+        } \
+    } \
+}
+
+/**
+ * Move the string offset from one code point boundary to the previous one
+ * and get the code point between them.
+ * (Pre-decrementing backward iteration.)
+ * "Safe" macro, checks for illegal sequences and for string boundaries.
+ *
+ * The input offset may be the same as the string length.
+ * If the offset is behind a multi-byte sequence, then the macro will read
+ * the whole sequence.
+ * If the offset is behind a lead byte, then that itself
+ * will be returned as the code point.
+ * If the offset is behind an illegal UTF-8 sequence, then c is set to a negative value.
+ *
+ * @param s const uint8_t * string
+ * @param start starting string offset (usually 0)
+ * @param i string offset, must be start<i
+ * @param c output UChar32 variable, set to <0 in case of an error
+ * @see U8_PREV_UNSAFE
+ * @stable ICU 2.4
+ */
+#define U8_PREV(s, start, i, c) { \
+    (c)=(uint8_t)(s)[--(i)]; \
+    if((c)>=0x80) { \
+        if((c)<=0xbf) { \
+            (c)=utf8_prevCharSafeBody((const uint8_t *)s, start, &(i), c, -1); \
+        } else { \
+            (c)=U_SENTINEL; \
+        } \
+    } \
+}
+
+/**
+ * Move the string offset from one code point boundary to the previous one.
+ * (Pre-decrementing backward iteration.)
+ * The input offset may be the same as the string length.
+ * "Unsafe" macro, assumes well-formed UTF-8.
+ *
+ * @param s const uint8_t * string
+ * @param i string offset
+ * @see U8_BACK_1
+ * @stable ICU 2.4
+ */
+#define U8_BACK_1_UNSAFE(s, i) { \
+    while(U8_IS_TRAIL((s)[--(i)])) {} \
+}
+
+/**
+ * Move the string offset from one code point boundary to the previous one.
+ * (Pre-decrementing backward iteration.)
+ * The input offset may be the same as the string length.
+ * "Safe" macro, checks for illegal sequences and for string boundaries.
+ *
+ * @param s const uint8_t * string
+ * @param start starting string offset (usually 0)
+ * @param i string offset, must be start<i
+ * @see U8_BACK_1_UNSAFE
+ * @stable ICU 2.4
+ */
+#define U8_BACK_1(s, start, i) { \
+    if(U8_IS_TRAIL((s)[--(i)])) { \
+        (i)=utf8_back1SafeBody(s, start, (int32_t)(i)); \
+    } \
+}
+
+/**
+ * Move the string offset from one code point boundary to the n-th one before it,
+ * i.e., move backward by n code points.
+ * (Pre-decrementing backward iteration.)
+ * The input offset may be the same as the string length.
+ * "Unsafe" macro, assumes well-formed UTF-8.
+ *
+ * @param s const uint8_t * string
+ * @param i string offset
+ * @param n number of code points to skip
+ * @see U8_BACK_N
+ * @stable ICU 2.4
+ */
+#define U8_BACK_N_UNSAFE(s, i, n) { \
+    int32_t __N=(n); \
+    while(__N>0) { \
+        U8_BACK_1_UNSAFE(s, i); \
+        --__N; \
+    } \
+}
+
+/**
+ * Move the string offset from one code point boundary to the n-th one before it,
+ * i.e., move backward by n code points.
+ * (Pre-decrementing backward iteration.)
+ * The input offset may be the same as the string length.
+ * "Safe" macro, checks for illegal sequences and for string boundaries.
+ *
+ * @param s const uint8_t * string
+ * @param start index of the start of the string
+ * @param i string offset, must be start<i
+ * @param n number of code points to skip
+ * @see U8_BACK_N_UNSAFE
+ * @stable ICU 2.4
+ */
+#define U8_BACK_N(s, start, i, n) { \
+    int32_t __N=(n); \
+    while(__N>0 && (i)>(start)) { \
+        U8_BACK_1(s, start, i); \
+        --__N; \
+    } \
+}
+
+/**
+ * Adjust a random-access offset to a code point boundary after a code point.
+ * If the offset is behind a partial multi-byte sequence,
+ * then the offset is incremented to behind the whole sequence.
+ * Otherwise, it is not modified.
+ * The input offset may be the same as the string length.
+ * "Unsafe" macro, assumes well-formed UTF-8.
+ *
+ * @param s const uint8_t * string
+ * @param i string offset
+ * @see U8_SET_CP_LIMIT
+ * @stable ICU 2.4
+ */
+#define U8_SET_CP_LIMIT_UNSAFE(s, i) { \
+    U8_BACK_1_UNSAFE(s, i); \
+    U8_FWD_1_UNSAFE(s, i); \
+}
+
+/**
+ * Adjust a random-access offset to a code point boundary after a code point.
+ * If the offset is behind a partial multi-byte sequence,
+ * then the offset is incremented to behind the whole sequence.
+ * Otherwise, it is not modified.
+ * The input offset may be the same as the string length.
+ * "Safe" macro, checks for illegal sequences and for string boundaries.
+ *
+ * @param s const uint8_t * string
+ * @param start starting string offset (usually 0)
+ * @param i string offset, must be start<=i<=length
+ * @param length string length
+ * @see U8_SET_CP_LIMIT_UNSAFE
+ * @stable ICU 2.4
+ */
+#define U8_SET_CP_LIMIT(s, start, i, length) { \
+    if((start)<(i) && (i)<(length)) { \
+        U8_BACK_1(s, start, i); \
+        U8_FWD_1(s, i, length); \
+    } \
+}
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/utf_old.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/utf_old.h b/src/apps/couch_collate/platform/osx/icu/unicode/utf_old.h
new file mode 100644
index 0000000..2397889
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/utf_old.h
@@ -0,0 +1,1171 @@
+/*
+*******************************************************************************
+*
+*   Copyright (C) 2002-2005, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+*
+*******************************************************************************
+*   file name:  utf.h
+*   encoding:   US-ASCII
+*   tab size:   8 (not used)
+*   indentation:4
+*
+*   created on: 2002sep21
+*   created by: Markus W. Scherer
+*/
+
+/**
+ * \file 
+ * \brief C API: Deprecated macros for Unicode string handling
+ */
+
+/**
+ * 
+ * The macros in utf_old.h are all deprecated and their use discouraged.
+ * Some of the design principles behind the set of UTF macros
+ * have changed or proved impractical.
+ * Almost all of the old "UTF macros" are at least renamed.
+ * If you are looking for a new equivalent to an old macro, please see the
+ * comment at the old one.
+ *
+ * utf_old.h is included by utf.h after unicode/umachine.h
+ * and some common definitions, to not break old code.
+ *
+ * Brief summary of reasons for deprecation:
+ * - Switch on UTF_SIZE (selection of UTF-8/16/32 default string processing)
+ *   was impractical.
+ * - Switch on UTF_SAFE etc. (selection of unsafe/safe/strict default string processing)
+ *   was of little use and impractical.
+ * - Whole classes of macros became obsolete outside of the UTF_SIZE/UTF_SAFE
+ *   selection framework: UTF32_ macros (all trivial)
+ *   and UTF_ default and intermediate macros (all aliases).
+ * - The selection framework also caused many macro aliases.
+ * - Change in Unicode standard: "irregular" sequences (3.0) became illegal (3.2).
+ * - Change of language in Unicode standard:
+ *   Growing distinction between internal x-bit Unicode strings and external UTF-x
+ *   forms, with the former more lenient.
+ *   Suggests renaming of UTF16_ macros to U16_.
+ * - The prefix "UTF_" without a width number confused some users.
+ * - "Safe" append macros needed the addition of an error indicator output.
+ * - "Safe" UTF-8 macros used legitimate (if rarely used) code point values
+ *   to indicate error conditions.
+ * - The use of the "_CHAR" infix for code point operations confused some users.
+ *
+ * More details:
+ *
+ * Until ICU 2.2, utf.h theoretically allowed to choose among UTF-8/16/32
+ * for string processing, and among unsafe/safe/strict default macros for that.
+ *
+ * It proved nearly impossible to write non-trivial, high-performance code
+ * that is UTF-generic.
+ * Unsafe default macros would be dangerous for default string processing,
+ * and the main reason for the "strict" versions disappeared:
+ * Between Unicode 3.0 and 3.2 all "irregular" UTF-8 sequences became illegal.
+ * The only other conditions that "strict" checked for were non-characters,
+ * which are valid during processing. Only during text input/output should they
+ * be checked, and at that time other well-formedness checks may be
+ * necessary or useful as well.
+ * This can still be done by using U16_NEXT and U_IS_UNICODE_NONCHAR
+ * or U_IS_UNICODE_CHAR.
+ *
+ * The old UTF8_..._SAFE macros also used some normal Unicode code points
+ * to indicate malformed sequences.
+ * The new UTF8_ macros without suffix use negative values instead.
+ *
+ * The entire contents of utf32.h was moved here without replacement
+ * because all those macros were trivial and
+ * were meaningful only in the framework of choosing the UTF size.
+ *
+ * See Jitterbug 2150 and its discussion on the ICU mailing list
+ * in September 2002.
+ *
+ * <hr>
+ *
+ * <em>Obsolete part</em> of pre-ICU 2.4 utf.h file documentation:
+ *
+ * <p>The original concept for these files was for ICU to allow
+ * in principle to set which UTF (UTF-8/16/32) is used internally
+ * by defining UTF_SIZE to either 8, 16, or 32. utf.h would then define the UChar type
+ * accordingly. UTF-16 was the default.</p>
+ *
+ * <p>This concept has been abandoned.
+ * A lot of the ICU source code assumes UChar strings are in UTF-16.
+ * This is especially true for low-level code like
+ * conversion, normalization, and collation.
+ * The utf.h header enforces the default of UTF-16.
+ * The UTF-8 and UTF-32 macros remain for now for completeness and backward compatibility.</p>
+ *
+ * <p>Accordingly, utf.h defines UChar to be an unsigned 16-bit integer. If this matches wchar_t, then
+ * UChar is defined to be exactly wchar_t, otherwise uint16_t.</p>
+ *
+ * <p>UChar32 is defined to be a signed 32-bit integer (int32_t), large enough for a 21-bit
+ * Unicode code point (Unicode scalar value, 0..0x10ffff).
+ * Before ICU 2.4, the definition of UChar32 was similarly platform-dependent as
+ * the definition of UChar. For details see the documentation for UChar32 itself.</p>
+ *
+ * <p>utf.h also defines a number of C macros for handling single Unicode code points and
+ * for using UTF Unicode strings. It includes utf8.h, utf16.h, and utf32.h for the actual
+ * implementations of those macros and then aliases one set of them (for UTF-16) for general use.
+ * The UTF-specific macros have the UTF size in the macro name prefixes (UTF16_...), while
+ * the general alias macros always begin with UTF_...</p>
+ *
+ * <p>Many string operations can be done with or without error checking.
+ * Where such a distinction is useful, there are two versions of the macros, "unsafe" and "safe"
+ * ones with ..._UNSAFE and ..._SAFE suffixes. The unsafe macros are fast but may cause
+ * program failures if the strings are not well-formed. The safe macros have an additional, boolean
+ * parameter "strict". If strict is FALSE, then only illegal sequences are detected.
+ * Otherwise, irregular sequences and non-characters are detected as well (like single surrogates).
+ * Safe macros return special error code points for illegal/irregular sequences:
+ * Typically, U+ffff, or values that would result in a code unit sequence of the same length
+ * as the erroneous input sequence.<br>
+ * Note that _UNSAFE macros have fewer parameters: They do not have the strictness parameter, and
+ * they do not have start/length parameters for boundary checking.</p>
+ *
+ * <p>Here, the macros are aliased in two steps:
+ * In the first step, the UTF-specific macros with UTF16_ prefix and _UNSAFE and _SAFE suffixes are
+ * aliased according to the UTF_SIZE to macros with UTF_ prefix and the same suffixes and signatures.
+ * Then, in a second step, the default, general alias macros are set to use either the unsafe or
+ * the safe/not strict (default) or the safe/strict macro;
+ * these general macros do not have a strictness parameter.</p>
+ *
+ * <p>It is possible to change the default choice for the general alias macros to be unsafe, safe/not strict or safe/strict.
+ * The default is safe/not strict. It is not recommended to select the unsafe macros as the basis for
+ * Unicode string handling in ICU! To select this, define UTF_SAFE, UTF_STRICT, or UTF_UNSAFE.</p>
+ *
+ * <p>For general use, one should use the default, general macros with UTF_ prefix and no _SAFE/_UNSAFE suffix.
+ * Only in some cases it may be necessary to control the choice of macro directly and use a less generic alias.
+ * For example, if it can be assumed that a string is well-formed and the index will stay within the bounds,
+ * then the _UNSAFE version may be used.
+ * If a UTF-8 string is to be processed, then the macros with UTF8_ prefixes need to be used.</p>
+ *
+ * <hr>
+ *
+ * @deprecated ICU 2.4. Use the macros in utf.h, utf16.h, utf8.h instead.
+ */
+
+#ifndef __UTF_OLD_H__
+#define __UTF_OLD_H__
+
+#ifndef U_HIDE_DEPRECATED_API
+
+/* utf.h must be included first. */
+#ifndef __UTF_H__
+#   include "unicode/utf.h"
+#endif
+
+/* Formerly utf.h, part 1 --------------------------------------------------- */
+
+#ifdef U_USE_UTF_DEPRECATES
+/**
+ * Unicode string and array offset and index type.
+ * ICU always counts Unicode code units (UChars) for
+ * string offsets, indexes, and lengths, not Unicode code points.
+ *
+ * @obsolete ICU 2.6. Use int32_t directly instead since this API will be removed in that release.
+ */
+typedef int32_t UTextOffset;
+#endif
+
+/** Number of bits in a Unicode string code unit - ICU uses 16-bit Unicode. @deprecated ICU 2.4. Obsolete, see utf_old.h. */
+#define UTF_SIZE 16
+
+/**
+ * The default choice for general Unicode string macros is to use the ..._SAFE macro implementations
+ * with strict=FALSE.
+ *
+ * @deprecated ICU 2.4. Obsolete, see utf_old.h.
+ */
+#define UTF_SAFE
+/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */
+#undef UTF_UNSAFE
+/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */
+#undef UTF_STRICT
+
+/**
+ * <p>UTF8_ERROR_VALUE_1 and UTF8_ERROR_VALUE_2 are special error values for UTF-8,
+ * which need 1 or 2 bytes in UTF-8:<br>
+ * U+0015 = NAK = Negative Acknowledge, C0 control character<br>
+ * U+009f = highest C1 control character</p>
+ *
+ * <p>These are used by UTF8_..._SAFE macros so that they can return an error value
+ * that needs the same number of code units (bytes) as were seen by
+ * a macro. They should be tested with UTF_IS_ERROR() or UTF_IS_VALID().</p>
+ *
+ * @deprecated ICU 2.4. Obsolete, see utf_old.h.
+ */
+#define UTF8_ERROR_VALUE_1 0x15
+
+/**
+ * See documentation on UTF8_ERROR_VALUE_1 for details.
+ *
+ * @deprecated ICU 2.4. Obsolete, see utf_old.h.
+ */
+#define UTF8_ERROR_VALUE_2 0x9f
+
+/**
+ * Error value for all UTFs. This code point value will be set by macros with error
+ * checking if an error is detected.
+ *
+ * @deprecated ICU 2.4. Obsolete, see utf_old.h.
+ */
+#define UTF_ERROR_VALUE 0xffff
+
+/**
+ * Is a given 32-bit code an error value
+ * as returned by one of the macros for any UTF?
+ *
+ * @deprecated ICU 2.4. Obsolete, see utf_old.h.
+ */
+#define UTF_IS_ERROR(c) \
+    (((c)&0xfffe)==0xfffe || (c)==UTF8_ERROR_VALUE_1 || (c)==UTF8_ERROR_VALUE_2)
+
+/**
+ * This is a combined macro: Is c a valid Unicode value _and_ not an error code?
+ *
+ * @deprecated ICU 2.4. Obsolete, see utf_old.h.
+ */
+#define UTF_IS_VALID(c) \
+    (UTF_IS_UNICODE_CHAR(c) && \
+     (c)!=UTF8_ERROR_VALUE_1 && (c)!=UTF8_ERROR_VALUE_2)
+
+/**
+ * Is this code unit or code point a surrogate (U+d800..U+dfff)?
+ * @deprecated ICU 2.4. Renamed to U_IS_SURROGATE and U16_IS_SURROGATE, see utf_old.h.
+ */
+#define UTF_IS_SURROGATE(uchar) (((uchar)&0xfffff800)==0xd800)
+
+/**
+ * Is a given 32-bit code point a Unicode noncharacter?
+ *
+ * @deprecated ICU 2.4. Renamed to U_IS_UNICODE_NONCHAR, see utf_old.h.
+ */
+#define UTF_IS_UNICODE_NONCHAR(c) \
+    ((c)>=0xfdd0 && \
+     ((uint32_t)(c)<=0xfdef || ((c)&0xfffe)==0xfffe) && \
+     (uint32_t)(c)<=0x10ffff)
+
+/**
+ * Is a given 32-bit value a Unicode code point value (0..U+10ffff)
+ * that can be assigned a character?
+ *
+ * Code points that are not characters include:
+ * - single surrogate code points (U+d800..U+dfff, 2048 code points)
+ * - the last two code points on each plane (U+__fffe and U+__ffff, 34 code points)
+ * - U+fdd0..U+fdef (new with Unicode 3.1, 32 code points)
+ * - the highest Unicode code point value is U+10ffff
+ *
+ * This means that all code points below U+d800 are character code points,
+ * and that boundary is tested first for performance.
+ *
+ * @deprecated ICU 2.4. Renamed to U_IS_UNICODE_CHAR, see utf_old.h.
+ */
+#define UTF_IS_UNICODE_CHAR(c) \
+    ((uint32_t)(c)<0xd800 || \
+        ((uint32_t)(c)>0xdfff && \
+         (uint32_t)(c)<=0x10ffff && \
+         !UTF_IS_UNICODE_NONCHAR(c)))
+
+/* Formerly utf8.h ---------------------------------------------------------- */
+
+/**
+ * Count the trail bytes for a UTF-8 lead byte.
+ * @deprecated ICU 2.4. Renamed to U8_COUNT_TRAIL_BYTES, see utf_old.h.
+ */
+#define UTF8_COUNT_TRAIL_BYTES(leadByte) (utf8_countTrailBytes[(uint8_t)leadByte])
+
+/**
+ * Mask a UTF-8 lead byte, leave only the lower bits that form part of the code point value.
+ * @deprecated ICU 2.4. Renamed to U8_MASK_LEAD_BYTE, see utf_old.h.
+ */
+#define UTF8_MASK_LEAD_BYTE(leadByte, countTrailBytes) ((leadByte)&=(1<<(6-(countTrailBytes)))-1)
+
+/** Is this this code point a single code unit (byte)? @deprecated ICU 2.4. Renamed to U8_IS_SINGLE, see utf_old.h. */
+#define UTF8_IS_SINGLE(uchar) (((uchar)&0x80)==0)
+/** Is this this code unit the lead code unit (byte) of a code point? @deprecated ICU 2.4. Renamed to U8_IS_LEAD, see utf_old.h. */
+#define UTF8_IS_LEAD(uchar) ((uint8_t)((uchar)-0xc0)<0x3e)
+/** Is this this code unit a trailing code unit (byte) of a code point? @deprecated ICU 2.4. Renamed to U8_IS_TRAIL, see utf_old.h. */
+#define UTF8_IS_TRAIL(uchar) (((uchar)&0xc0)==0x80)
+
+/** Does this scalar Unicode value need multiple code units for storage? @deprecated ICU 2.4. Use U8_LENGTH or test ((uint32_t)(c)>0x7f) instead, see utf_old.h. */
+#define UTF8_NEED_MULTIPLE_UCHAR(c) ((uint32_t)(c)>0x7f)
+
+/**
+ * Given the lead character, how many bytes are taken by this code point.
+ * ICU does not deal with code points >0x10ffff
+ * unless necessary for advancing in the byte stream.
+ *
+ * These length macros take into account that for values >0x10ffff
+ * the UTF8_APPEND_CHAR_SAFE macros would write the error code point 0xffff
+ * with 3 bytes.
+ * Code point comparisons need to be in uint32_t because UChar32
+ * may be a signed type, and negative values must be recognized.
+ *
+ * @deprecated ICU 2.4. Use U8_LENGTH instead, see utf_old.h.
+ */
+#if 1
+#   define UTF8_CHAR_LENGTH(c) \
+        ((uint32_t)(c)<=0x7f ? 1 : \
+            ((uint32_t)(c)<=0x7ff ? 2 : \
+                ((uint32_t)((c)-0x10000)>0xfffff ? 3 : 4) \
+            ) \
+        )
+#else
+#   define UTF8_CHAR_LENGTH(c) \
+        ((uint32_t)(c)<=0x7f ? 1 : \
+            ((uint32_t)(c)<=0x7ff ? 2 : \
+                ((uint32_t)(c)<=0xffff ? 3 : \
+                    ((uint32_t)(c)<=0x10ffff ? 4 : \
+                        ((uint32_t)(c)<=0x3ffffff ? 5 : \
+                            ((uint32_t)(c)<=0x7fffffff ? 6 : 3) \
+                        ) \
+                    ) \
+                ) \
+            ) \
+        )
+#endif
+
+/** The maximum number of bytes per code point. @deprecated ICU 2.4. Renamed to U8_MAX_LENGTH, see utf_old.h. */
+#define UTF8_MAX_CHAR_LENGTH 4
+
+/** Average number of code units compared to UTF-16. @deprecated ICU 2.4. Obsolete, see utf_old.h. */
+#define UTF8_ARRAY_SIZE(size) ((5*(size))/2)
+
+/** @deprecated ICU 2.4. Renamed to U8_GET_UNSAFE, see utf_old.h. */
+#define UTF8_GET_CHAR_UNSAFE(s, i, c) { \
+    int32_t _utf8_get_char_unsafe_index=(int32_t)(i); \
+    UTF8_SET_CHAR_START_UNSAFE(s, _utf8_get_char_unsafe_index); \
+    UTF8_NEXT_CHAR_UNSAFE(s, _utf8_get_char_unsafe_index, c); \
+}
+
+/** @deprecated ICU 2.4. Use U8_GET instead, see utf_old.h. */
+#define UTF8_GET_CHAR_SAFE(s, start, i, length, c, strict) { \
+    int32_t _utf8_get_char_safe_index=(int32_t)(i); \
+    UTF8_SET_CHAR_START_SAFE(s, start, _utf8_get_char_safe_index); \
+    UTF8_NEXT_CHAR_SAFE(s, _utf8_get_char_safe_index, length, c, strict); \
+}
+
+/** @deprecated ICU 2.4. Renamed to U8_NEXT_UNSAFE, see utf_old.h. */
+#define UTF8_NEXT_CHAR_UNSAFE(s, i, c) { \
+    (c)=(s)[(i)++]; \
+    if((uint8_t)((c)-0xc0)<0x35) { \
+        uint8_t __count=UTF8_COUNT_TRAIL_BYTES(c); \
+        UTF8_MASK_LEAD_BYTE(c, __count); \
+        switch(__count) { \
+        /* each following branch falls through to the next one */ \
+        case 3: \
+            (c)=((c)<<6)|((s)[(i)++]&0x3f); \
+        case 2: \
+            (c)=((c)<<6)|((s)[(i)++]&0x3f); \
+        case 1: \
+            (c)=((c)<<6)|((s)[(i)++]&0x3f); \
+        /* no other branches to optimize switch() */ \
+            break; \
+        } \
+    } \
+}
+
+/** @deprecated ICU 2.4. Renamed to U8_APPEND_UNSAFE, see utf_old.h. */
+#define UTF8_APPEND_CHAR_UNSAFE(s, i, c) { \
+    if((uint32_t)(c)<=0x7f) { \
+        (s)[(i)++]=(uint8_t)(c); \
+    } else { \
+        if((uint32_t)(c)<=0x7ff) { \
+            (s)[(i)++]=(uint8_t)(((c)>>6)|0xc0); \
+        } else { \
+            if((uint32_t)(c)<=0xffff) { \
+                (s)[(i)++]=(uint8_t)(((c)>>12)|0xe0); \
+            } else { \
+                (s)[(i)++]=(uint8_t)(((c)>>18)|0xf0); \
+                (s)[(i)++]=(uint8_t)((((c)>>12)&0x3f)|0x80); \
+            } \
+            (s)[(i)++]=(uint8_t)((((c)>>6)&0x3f)|0x80); \
+        } \
+        (s)[(i)++]=(uint8_t)(((c)&0x3f)|0x80); \
+    } \
+}
+
+/** @deprecated ICU 2.4. Renamed to U8_FWD_1_UNSAFE, see utf_old.h. */
+#define UTF8_FWD_1_UNSAFE(s, i) { \
+    (i)+=1+UTF8_COUNT_TRAIL_BYTES((s)[i]); \
+}
+
+/** @deprecated ICU 2.4. Renamed to U8_FWD_N_UNSAFE, see utf_old.h. */
+#define UTF8_FWD_N_UNSAFE(s, i, n) { \
+    int32_t __N=(n); \
+    while(__N>0) { \
+        UTF8_FWD_1_UNSAFE(s, i); \
+        --__N; \
+    } \
+}
+
+/** @deprecated ICU 2.4. Renamed to U8_SET_CP_START_UNSAFE, see utf_old.h. */
+#define UTF8_SET_CHAR_START_UNSAFE(s, i) { \
+    while(UTF8_IS_TRAIL((s)[i])) { --(i); } \
+}
+
+/** @deprecated ICU 2.4. Use U8_NEXT instead, see utf_old.h. */
+#define UTF8_NEXT_CHAR_SAFE(s, i, length, c, strict) { \
+    (c)=(s)[(i)++]; \
+    if((c)>=0x80) { \
+        if(UTF8_IS_LEAD(c)) { \
+            (c)=utf8_nextCharSafeBody(s, &(i), (int32_t)(length), c, strict); \
+        } else { \
+            (c)=UTF8_ERROR_VALUE_1; \
+        } \
+    } \
+}
+
+/** @deprecated ICU 2.4. Use U8_APPEND instead, see utf_old.h. */
+#define UTF8_APPEND_CHAR_SAFE(s, i, length, c)  { \
+    if((uint32_t)(c)<=0x7f) { \
+        (s)[(i)++]=(uint8_t)(c); \
+    } else { \
+        (i)=utf8_appendCharSafeBody(s, (int32_t)(i), (int32_t)(length), c, NULL); \
+    } \
+}
+
+/** @deprecated ICU 2.4. Renamed to U8_FWD_1, see utf_old.h. */
+#define UTF8_FWD_1_SAFE(s, i, length) U8_FWD_1(s, i, length)
+
+/** @deprecated ICU 2.4. Renamed to U8_FWD_N, see utf_old.h. */
+#define UTF8_FWD_N_SAFE(s, i, length, n) U8_FWD_N(s, i, length, n)
+
+/** @deprecated ICU 2.4. Renamed to U8_SET_CP_START, see utf_old.h. */
+#define UTF8_SET_CHAR_START_SAFE(s, start, i) U8_SET_CP_START(s, start, i)
+
+/** @deprecated ICU 2.4. Renamed to U8_PREV_UNSAFE, see utf_old.h. */
+#define UTF8_PREV_CHAR_UNSAFE(s, i, c) { \
+    (c)=(s)[--(i)]; \
+    if(UTF8_IS_TRAIL(c)) { \
+        uint8_t __b, __count=1, __shift=6; \
+\
+        /* c is a trail byte */ \
+        (c)&=0x3f; \
+        for(;;) { \
+            __b=(s)[--(i)]; \
+            if(__b>=0xc0) { \
+                UTF8_MASK_LEAD_BYTE(__b, __count); \
+                (c)|=(UChar32)__b<<__shift; \
+                break; \
+            } else { \
+                (c)|=(UChar32)(__b&0x3f)<<__shift; \
+                ++__count; \
+                __shift+=6; \
+            } \
+        } \
+    } \
+}
+
+/** @deprecated ICU 2.4. Renamed to U8_BACK_1_UNSAFE, see utf_old.h. */
+#define UTF8_BACK_1_UNSAFE(s, i) { \
+    while(UTF8_IS_TRAIL((s)[--(i)])) {} \
+}
+
+/** @deprecated ICU 2.4. Renamed to U8_BACK_N_UNSAFE, see utf_old.h. */
+#define UTF8_BACK_N_UNSAFE(s, i, n) { \
+    int32_t __N=(n); \
+    while(__N>0) { \
+        UTF8_BACK_1_UNSAFE(s, i); \
+        --__N; \
+    } \
+}
+
+/** @deprecated ICU 2.4. Renamed to U8_SET_CP_LIMIT_UNSAFE, see utf_old.h. */
+#define UTF8_SET_CHAR_LIMIT_UNSAFE(s, i) { \
+    UTF8_BACK_1_UNSAFE(s, i); \
+    UTF8_FWD_1_UNSAFE(s, i); \
+}
+
+/** @deprecated ICU 2.4. Use U8_PREV instead, see utf_old.h. */
+#define UTF8_PREV_CHAR_SAFE(s, start, i, c, strict) { \
+    (c)=(s)[--(i)]; \
+    if((c)>=0x80) { \
+        if((c)<=0xbf) { \
+            (c)=utf8_prevCharSafeBody(s, start, &(i), c, strict); \
+        } else { \
+            (c)=UTF8_ERROR_VALUE_1; \
+        } \
+    } \
+}
+
+/** @deprecated ICU 2.4. Renamed to U8_BACK_1, see utf_old.h. */
+#define UTF8_BACK_1_SAFE(s, start, i) U8_BACK_1(s, start, i)
+
+/** @deprecated ICU 2.4. Renamed to U8_BACK_N, see utf_old.h. */
+#define UTF8_BACK_N_SAFE(s, start, i, n) U8_BACK_N(s, start, i, n)
+
+/** @deprecated ICU 2.4. Renamed to U8_SET_CP_LIMIT, see utf_old.h. */
+#define UTF8_SET_CHAR_LIMIT_SAFE(s, start, i, length) U8_SET_CP_LIMIT(s, start, i, length)
+
+/* Formerly utf16.h --------------------------------------------------------- */
+
+/** Is uchar a first/lead surrogate? @deprecated ICU 2.4. Renamed to U_IS_LEAD and U16_IS_LEAD, see utf_old.h. */
+#define UTF_IS_FIRST_SURROGATE(uchar) (((uchar)&0xfffffc00)==0xd800)
+
+/** Is uchar a second/trail surrogate? @deprecated ICU 2.4. Renamed to U_IS_TRAIL and U16_IS_TRAIL, see utf_old.h. */
+#define UTF_IS_SECOND_SURROGATE(uchar) (((uchar)&0xfffffc00)==0xdc00)
+
+/** Assuming c is a surrogate, is it a first/lead surrogate? @deprecated ICU 2.4. Renamed to U_IS_SURROGATE_LEAD and U16_IS_SURROGATE_LEAD, see utf_old.h. */
+#define UTF_IS_SURROGATE_FIRST(c) (((c)&0x400)==0)
+
+/** Helper constant for UTF16_GET_PAIR_VALUE. @deprecated ICU 2.4. Renamed to U16_SURROGATE_OFFSET, see utf_old.h. */
+#define UTF_SURROGATE_OFFSET ((0xd800<<10UL)+0xdc00-0x10000)
+
+/** Get the UTF-32 value from the surrogate code units. @deprecated ICU 2.4. Renamed to U16_GET_SUPPLEMENTARY, see utf_old.h. */
+#define UTF16_GET_PAIR_VALUE(first, second) \
+    (((first)<<10UL)+(second)-UTF_SURROGATE_OFFSET)
+
+/** @deprecated ICU 2.4. Renamed to U16_LEAD, see utf_old.h. */
+#define UTF_FIRST_SURROGATE(supplementary) (UChar)(((supplementary)>>10)+0xd7c0)
+
+/** @deprecated ICU 2.4. Renamed to U16_TRAIL, see utf_old.h. */
+#define UTF_SECOND_SURROGATE(supplementary) (UChar)(((supplementary)&0x3ff)|0xdc00)
+
+/** @deprecated ICU 2.4. Renamed to U16_LEAD, see utf_old.h. */
+#define UTF16_LEAD(supplementary) UTF_FIRST_SURROGATE(supplementary)
+
+/** @deprecated ICU 2.4. Renamed to U16_TRAIL, see utf_old.h. */
+#define UTF16_TRAIL(supplementary) UTF_SECOND_SURROGATE(supplementary)
+
+/** @deprecated ICU 2.4. Renamed to U16_IS_SINGLE, see utf_old.h. */
+#define UTF16_IS_SINGLE(uchar) !UTF_IS_SURROGATE(uchar)
+
+/** @deprecated ICU 2.4. Renamed to U16_IS_LEAD, see utf_old.h. */
+#define UTF16_IS_LEAD(uchar) UTF_IS_FIRST_SURROGATE(uchar)
+
+/** @deprecated ICU 2.4. Renamed to U16_IS_TRAIL, see utf_old.h. */
+#define UTF16_IS_TRAIL(uchar) UTF_IS_SECOND_SURROGATE(uchar)
+
+/** Does this scalar Unicode value need multiple code units for storage? @deprecated ICU 2.4. Use U16_LENGTH or test ((uint32_t)(c)>0xffff) instead, see utf_old.h. */
+#define UTF16_NEED_MULTIPLE_UCHAR(c) ((uint32_t)(c)>0xffff)
+
+/** @deprecated ICU 2.4. Renamed to U16_LENGTH, see utf_old.h. */
+#define UTF16_CHAR_LENGTH(c) ((uint32_t)(c)<=0xffff ? 1 : 2)
+
+/** @deprecated ICU 2.4. Renamed to U16_MAX_LENGTH, see utf_old.h. */
+#define UTF16_MAX_CHAR_LENGTH 2
+
+/** Average number of code units compared to UTF-16. @deprecated ICU 2.4. Obsolete, see utf_old.h. */
+#define UTF16_ARRAY_SIZE(size) (size)
+
+/**
+ * Get a single code point from an offset that points to any
+ * of the code units that belong to that code point.
+ * Assume 0<=i<length.
+ *
+ * This could be used for iteration together with
+ * UTF16_CHAR_LENGTH() and UTF_IS_ERROR(),
+ * but the use of UTF16_NEXT_CHAR[_UNSAFE]() and
+ * UTF16_PREV_CHAR[_UNSAFE]() is more efficient for that.
+ * @deprecated ICU 2.4. Renamed to U16_GET_UNSAFE, see utf_old.h.
+ */
+#define UTF16_GET_CHAR_UNSAFE(s, i, c) { \
+    (c)=(s)[i]; \
+    if(UTF_IS_SURROGATE(c)) { \
+        if(UTF_IS_SURROGATE_FIRST(c)) { \
+            (c)=UTF16_GET_PAIR_VALUE((c), (s)[(i)+1]); \
+        } else { \
+            (c)=UTF16_GET_PAIR_VALUE((s)[(i)-1], (c)); \
+        } \
+    } \
+}
+
+/** @deprecated ICU 2.4. Use U16_GET instead, see utf_old.h. */
+#define UTF16_GET_CHAR_SAFE(s, start, i, length, c, strict) { \
+    (c)=(s)[i]; \
+    if(UTF_IS_SURROGATE(c)) { \
+        uint16_t __c2; \
+        if(UTF_IS_SURROGATE_FIRST(c)) { \
+            if((i)+1<(length) && UTF_IS_SECOND_SURROGATE(__c2=(s)[(i)+1])) { \
+                (c)=UTF16_GET_PAIR_VALUE((c), __c2); \
+                /* strict: ((c)&0xfffe)==0xfffe is caught by UTF_IS_ERROR() and UTF_IS_UNICODE_CHAR() */ \
+            } else if(strict) {\
+                /* unmatched first surrogate */ \
+                (c)=UTF_ERROR_VALUE; \
+            } \
+        } else { \
+            if((i)-1>=(start) && UTF_IS_FIRST_SURROGATE(__c2=(s)[(i)-1])) { \
+                (c)=UTF16_GET_PAIR_VALUE(__c2, (c)); \
+                /* strict: ((c)&0xfffe)==0xfffe is caught by UTF_IS_ERROR() and UTF_IS_UNICODE_CHAR() */ \
+            } else if(strict) {\
+                /* unmatched second surrogate */ \
+                (c)=UTF_ERROR_VALUE; \
+            } \
+        } \
+    } else if((strict) && !UTF_IS_UNICODE_CHAR(c)) { \
+        (c)=UTF_ERROR_VALUE; \
+    } \
+}
+
+/** @deprecated ICU 2.4. Renamed to U16_NEXT_UNSAFE, see utf_old.h. */
+#define UTF16_NEXT_CHAR_UNSAFE(s, i, c) { \
+    (c)=(s)[(i)++]; \
+    if(UTF_IS_FIRST_SURROGATE(c)) { \
+        (c)=UTF16_GET_PAIR_VALUE((c), (s)[(i)++]); \
+    } \
+}
+
+/** @deprecated ICU 2.4. Renamed to U16_APPEND_UNSAFE, see utf_old.h. */
+#define UTF16_APPEND_CHAR_UNSAFE(s, i, c) { \
+    if((uint32_t)(c)<=0xffff) { \
+        (s)[(i)++]=(uint16_t)(c); \
+    } else { \
+        (s)[(i)++]=(uint16_t)(((c)>>10)+0xd7c0); \
+        (s)[(i)++]=(uint16_t)(((c)&0x3ff)|0xdc00); \
+    } \
+}
+
+/** @deprecated ICU 2.4. Renamed to U16_FWD_1_UNSAFE, see utf_old.h. */
+#define UTF16_FWD_1_UNSAFE(s, i) { \
+    if(UTF_IS_FIRST_SURROGATE((s)[(i)++])) { \
+        ++(i); \
+    } \
+}
+
+/** @deprecated ICU 2.4. Renamed to U16_FWD_N_UNSAFE, see utf_old.h. */
+#define UTF16_FWD_N_UNSAFE(s, i, n) { \
+    int32_t __N=(n); \
+    while(__N>0) { \
+        UTF16_FWD_1_UNSAFE(s, i); \
+        --__N; \
+    } \
+}
+
+/** @deprecated ICU 2.4. Renamed to U16_SET_CP_START_UNSAFE, see utf_old.h. */
+#define UTF16_SET_CHAR_START_UNSAFE(s, i) { \
+    if(UTF_IS_SECOND_SURROGATE((s)[i])) { \
+        --(i); \
+    } \
+}
+
+/** @deprecated ICU 2.4. Use U16_NEXT instead, see utf_old.h. */
+#define UTF16_NEXT_CHAR_SAFE(s, i, length, c, strict) { \
+    (c)=(s)[(i)++]; \
+    if(UTF_IS_FIRST_SURROGATE(c)) { \
+        uint16_t __c2; \
+        if((i)<(length) && UTF_IS_SECOND_SURROGATE(__c2=(s)[(i)])) { \
+            ++(i); \
+            (c)=UTF16_GET_PAIR_VALUE((c), __c2); \
+            /* strict: ((c)&0xfffe)==0xfffe is caught by UTF_IS_ERROR() and UTF_IS_UNICODE_CHAR() */ \
+        } else if(strict) {\
+            /* unmatched first surrogate */ \
+            (c)=UTF_ERROR_VALUE; \
+        } \
+    } else if((strict) && !UTF_IS_UNICODE_CHAR(c)) { \
+        /* unmatched second surrogate or other non-character */ \
+        (c)=UTF_ERROR_VALUE; \
+    } \
+}
+
+/** @deprecated ICU 2.4. Use U16_APPEND instead, see utf_old.h. */
+#define UTF16_APPEND_CHAR_SAFE(s, i, length, c) { \
+    if((uint32_t)(c)<=0xffff) { \
+        (s)[(i)++]=(uint16_t)(c); \
+    } else if((uint32_t)(c)<=0x10ffff) { \
+        if((i)+1<(length)) { \
+            (s)[(i)++]=(uint16_t)(((c)>>10)+0xd7c0); \
+            (s)[(i)++]=(uint16_t)(((c)&0x3ff)|0xdc00); \
+        } else /* not enough space */ { \
+            (s)[(i)++]=UTF_ERROR_VALUE; \
+        } \
+    } else /* c>0x10ffff, write error value */ { \
+        (s)[(i)++]=UTF_ERROR_VALUE; \
+    } \
+}
+
+/** @deprecated ICU 2.4. Renamed to U16_FWD_1, see utf_old.h. */
+#define UTF16_FWD_1_SAFE(s, i, length) U16_FWD_1(s, i, length)
+
+/** @deprecated ICU 2.4. Renamed to U16_FWD_N, see utf_old.h. */
+#define UTF16_FWD_N_SAFE(s, i, length, n) U16_FWD_N(s, i, length, n)
+
+/** @deprecated ICU 2.4. Renamed to U16_SET_CP_START, see utf_old.h. */
+#define UTF16_SET_CHAR_START_SAFE(s, start, i) U16_SET_CP_START(s, start, i)
+
+/** @deprecated ICU 2.4. Renamed to U16_PREV_UNSAFE, see utf_old.h. */
+#define UTF16_PREV_CHAR_UNSAFE(s, i, c) { \
+    (c)=(s)[--(i)]; \
+    if(UTF_IS_SECOND_SURROGATE(c)) { \
+        (c)=UTF16_GET_PAIR_VALUE((s)[--(i)], (c)); \
+    } \
+}
+
+/** @deprecated ICU 2.4. Renamed to U16_BACK_1_UNSAFE, see utf_old.h. */
+#define UTF16_BACK_1_UNSAFE(s, i) { \
+    if(UTF_IS_SECOND_SURROGATE((s)[--(i)])) { \
+        --(i); \
+    } \
+}
+
+/** @deprecated ICU 2.4. Renamed to U16_BACK_N_UNSAFE, see utf_old.h. */
+#define UTF16_BACK_N_UNSAFE(s, i, n) { \
+    int32_t __N=(n); \
+    while(__N>0) { \
+        UTF16_BACK_1_UNSAFE(s, i); \
+        --__N; \
+    } \
+}
+
+/** @deprecated ICU 2.4. Renamed to U16_SET_CP_LIMIT_UNSAFE, see utf_old.h. */
+#define UTF16_SET_CHAR_LIMIT_UNSAFE(s, i) { \
+    if(UTF_IS_FIRST_SURROGATE((s)[(i)-1])) { \
+        ++(i); \
+    } \
+}
+
+/** @deprecated ICU 2.4. Use U16_PREV instead, see utf_old.h. */
+#define UTF16_PREV_CHAR_SAFE(s, start, i, c, strict) { \
+    (c)=(s)[--(i)]; \
+    if(UTF_IS_SECOND_SURROGATE(c)) { \
+        uint16_t __c2; \
+        if((i)>(start) && UTF_IS_FIRST_SURROGATE(__c2=(s)[(i)-1])) { \
+            --(i); \
+            (c)=UTF16_GET_PAIR_VALUE(__c2, (c)); \
+            /* strict: ((c)&0xfffe)==0xfffe is caught by UTF_IS_ERROR() and UTF_IS_UNICODE_CHAR() */ \
+        } else if(strict) {\
+            /* unmatched second surrogate */ \
+            (c)=UTF_ERROR_VALUE; \
+        } \
+    } else if((strict) && !UTF_IS_UNICODE_CHAR(c)) { \
+        /* unmatched first surrogate or other non-character */ \
+        (c)=UTF_ERROR_VALUE; \
+    } \
+}
+
+/** @deprecated ICU 2.4. Renamed to U16_BACK_1, see utf_old.h. */
+#define UTF16_BACK_1_SAFE(s, start, i) U16_BACK_1(s, start, i)
+
+/** @deprecated ICU 2.4. Renamed to U16_BACK_N, see utf_old.h. */
+#define UTF16_BACK_N_SAFE(s, start, i, n) U16_BACK_N(s, start, i, n)
+
+/** @deprecated ICU 2.4. Renamed to U16_SET_CP_LIMIT, see utf_old.h. */
+#define UTF16_SET_CHAR_LIMIT_SAFE(s, start, i, length) U16_SET_CP_LIMIT(s, start, i, length)
+
+/* Formerly utf32.h --------------------------------------------------------- */
+
+/*
+* Old documentation:
+*
+*   This file defines macros to deal with UTF-32 code units and code points.
+*   Signatures and semantics are the same as for the similarly named macros
+*   in utf16.h.
+*   utf32.h is included by utf.h after unicode/umachine.h</p>
+*   and some common definitions.
+*   <p><b>Usage:</b>  ICU coding guidelines for if() statements should be followed when using these macros.
+*                  Compound statements (curly braces {}) must be used  for if-else-while...
+*                  bodies and all macro statements should be terminated with semicolon.</p>
+*/
+
+/* internal definitions ----------------------------------------------------- */
+
+/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */
+#define UTF32_IS_SAFE(c, strict) \
+    (!(strict) ? \
+        (uint32_t)(c)<=0x10ffff : \
+        UTF_IS_UNICODE_CHAR(c))
+
+/*
+ * For the semantics of all of these macros, see utf16.h.
+ * The UTF-32 versions are trivial because any code point is
+ * encoded using exactly one code unit.
+ */
+
+/* single-code point definitions -------------------------------------------- */
+
+/* classes of code unit values */
+
+/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */
+#define UTF32_IS_SINGLE(uchar) 1
+/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */
+#define UTF32_IS_LEAD(uchar) 0
+/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */
+#define UTF32_IS_TRAIL(uchar) 0
+
+/* number of code units per code point */
+
+/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */
+#define UTF32_NEED_MULTIPLE_UCHAR(c) 0
+/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */
+#define UTF32_CHAR_LENGTH(c) 1
+/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */
+#define UTF32_MAX_CHAR_LENGTH 1
+
+/* average number of code units compared to UTF-16 */
+
+/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */
+#define UTF32_ARRAY_SIZE(size) (size)
+
+/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */
+#define UTF32_GET_CHAR_UNSAFE(s, i, c) { \
+    (c)=(s)[i]; \
+}
+
+/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */
+#define UTF32_GET_CHAR_SAFE(s, start, i, length, c, strict) { \
+    (c)=(s)[i]; \
+    if(!UTF32_IS_SAFE(c, strict)) { \
+        (c)=UTF_ERROR_VALUE; \
+    } \
+}
+
+/* definitions with forward iteration --------------------------------------- */
+
+/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */
+#define UTF32_NEXT_CHAR_UNSAFE(s, i, c) { \
+    (c)=(s)[(i)++]; \
+}
+
+/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */
+#define UTF32_APPEND_CHAR_UNSAFE(s, i, c) { \
+    (s)[(i)++]=(c); \
+}
+
+/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */
+#define UTF32_FWD_1_UNSAFE(s, i) { \
+    ++(i); \
+}
+
+/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */
+#define UTF32_FWD_N_UNSAFE(s, i, n) { \
+    (i)+=(n); \
+}
+
+/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */
+#define UTF32_SET_CHAR_START_UNSAFE(s, i) { \
+}
+
+/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */
+#define UTF32_NEXT_CHAR_SAFE(s, i, length, c, strict) { \
+    (c)=(s)[(i)++]; \
+    if(!UTF32_IS_SAFE(c, strict)) { \
+        (c)=UTF_ERROR_VALUE; \
+    } \
+}
+
+/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */
+#define UTF32_APPEND_CHAR_SAFE(s, i, length, c) { \
+    if((uint32_t)(c)<=0x10ffff) { \
+        (s)[(i)++]=(c); \
+    } else /* c>0x10ffff, write 0xfffd */ { \
+        (s)[(i)++]=0xfffd; \
+    } \
+}
+
+/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */
+#define UTF32_FWD_1_SAFE(s, i, length) { \
+    ++(i); \
+}
+
+/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */
+#define UTF32_FWD_N_SAFE(s, i, length, n) { \
+    if(((i)+=(n))>(length)) { \
+        (i)=(length); \
+    } \
+}
+
+/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */
+#define UTF32_SET_CHAR_START_SAFE(s, start, i) { \
+}
+
+/* definitions with backward iteration -------------------------------------- */
+
+/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */
+#define UTF32_PREV_CHAR_UNSAFE(s, i, c) { \
+    (c)=(s)[--(i)]; \
+}
+
+/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */
+#define UTF32_BACK_1_UNSAFE(s, i) { \
+    --(i); \
+}
+
+/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */
+#define UTF32_BACK_N_UNSAFE(s, i, n) { \
+    (i)-=(n); \
+}
+
+/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */
+#define UTF32_SET_CHAR_LIMIT_UNSAFE(s, i) { \
+}
+
+/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */
+#define UTF32_PREV_CHAR_SAFE(s, start, i, c, strict) { \
+    (c)=(s)[--(i)]; \
+    if(!UTF32_IS_SAFE(c, strict)) { \
+        (c)=UTF_ERROR_VALUE; \
+    } \
+}
+
+/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */
+#define UTF32_BACK_1_SAFE(s, start, i) { \
+    --(i); \
+}
+
+/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */
+#define UTF32_BACK_N_SAFE(s, start, i, n) { \
+    (i)-=(n); \
+    if((i)<(start)) { \
+        (i)=(start); \
+    } \
+}
+
+/** @deprecated ICU 2.4. Obsolete, see utf_old.h. */
+#define UTF32_SET_CHAR_LIMIT_SAFE(s, i, length) { \
+}
+
+/* Formerly utf.h, part 2 --------------------------------------------------- */
+
+/**
+ * Estimate the number of code units for a string based on the number of UTF-16 code units.
+ *
+ * @deprecated ICU 2.4. Obsolete, see utf_old.h.
+ */
+#define UTF_ARRAY_SIZE(size) UTF16_ARRAY_SIZE(size)
+
+/** @deprecated ICU 2.4. Renamed to U16_GET_UNSAFE, see utf_old.h. */
+#define UTF_GET_CHAR_UNSAFE(s, i, c)                 UTF16_GET_CHAR_UNSAFE(s, i, c)
+
+/** @deprecated ICU 2.4. Use U16_GET instead, see utf_old.h. */
+#define UTF_GET_CHAR_SAFE(s, start, i, length, c, strict) UTF16_GET_CHAR_SAFE(s, start, i, length, c, strict)
+
+
+/** @deprecated ICU 2.4. Renamed to U16_NEXT_UNSAFE, see utf_old.h. */
+#define UTF_NEXT_CHAR_UNSAFE(s, i, c)                UTF16_NEXT_CHAR_UNSAFE(s, i, c)
+
+/** @deprecated ICU 2.4. Use U16_NEXT instead, see utf_old.h. */
+#define UTF_NEXT_CHAR_SAFE(s, i, length, c, strict)  UTF16_NEXT_CHAR_SAFE(s, i, length, c, strict)
+
+
+/** @deprecated ICU 2.4. Renamed to U16_APPEND_UNSAFE, see utf_old.h. */
+#define UTF_APPEND_CHAR_UNSAFE(s, i, c)              UTF16_APPEND_CHAR_UNSAFE(s, i, c)
+
+/** @deprecated ICU 2.4. Use U16_APPEND instead, see utf_old.h. */
+#define UTF_APPEND_CHAR_SAFE(s, i, length, c)        UTF16_APPEND_CHAR_SAFE(s, i, length, c)
+
+
+/** @deprecated ICU 2.4. Renamed to U16_FWD_1_UNSAFE, see utf_old.h. */
+#define UTF_FWD_1_UNSAFE(s, i)                       UTF16_FWD_1_UNSAFE(s, i)
+
+/** @deprecated ICU 2.4. Renamed to U16_FWD_1, see utf_old.h. */
+#define UTF_FWD_1_SAFE(s, i, length)                 UTF16_FWD_1_SAFE(s, i, length)
+
+
+/** @deprecated ICU 2.4. Renamed to U16_FWD_N_UNSAFE, see utf_old.h. */
+#define UTF_FWD_N_UNSAFE(s, i, n)                    UTF16_FWD_N_UNSAFE(s, i, n)
+
+/** @deprecated ICU 2.4. Renamed to U16_FWD_N, see utf_old.h. */
+#define UTF_FWD_N_SAFE(s, i, length, n)              UTF16_FWD_N_SAFE(s, i, length, n)
+
+
+/** @deprecated ICU 2.4. Renamed to U16_SET_CP_START_UNSAFE, see utf_old.h. */
+#define UTF_SET_CHAR_START_UNSAFE(s, i)              UTF16_SET_CHAR_START_UNSAFE(s, i)
+
+/** @deprecated ICU 2.4. Renamed to U16_SET_CP_START, see utf_old.h. */
+#define UTF_SET_CHAR_START_SAFE(s, start, i)         UTF16_SET_CHAR_START_SAFE(s, start, i)
+
+
+/** @deprecated ICU 2.4. Renamed to U16_PREV_UNSAFE, see utf_old.h. */
+#define UTF_PREV_CHAR_UNSAFE(s, i, c)                UTF16_PREV_CHAR_UNSAFE(s, i, c)
+
+/** @deprecated ICU 2.4. Use U16_PREV instead, see utf_old.h. */
+#define UTF_PREV_CHAR_SAFE(s, start, i, c, strict)   UTF16_PREV_CHAR_SAFE(s, start, i, c, strict)
+
+
+/** @deprecated ICU 2.4. Renamed to U16_BACK_1_UNSAFE, see utf_old.h. */
+#define UTF_BACK_1_UNSAFE(s, i)                      UTF16_BACK_1_UNSAFE(s, i)
+
+/** @deprecated ICU 2.4. Renamed to U16_BACK_1, see utf_old.h. */
+#define UTF_BACK_1_SAFE(s, start, i)                 UTF16_BACK_1_SAFE(s, start, i)
+
+
+/** @deprecated ICU 2.4. Renamed to U16_BACK_N_UNSAFE, see utf_old.h. */
+#define UTF_BACK_N_UNSAFE(s, i, n)                   UTF16_BACK_N_UNSAFE(s, i, n)
+
+/** @deprecated ICU 2.4. Renamed to U16_BACK_N, see utf_old.h. */
+#define UTF_BACK_N_SAFE(s, start, i, n)              UTF16_BACK_N_SAFE(s, start, i, n)
+
+
+/** @deprecated ICU 2.4. Renamed to U16_SET_CP_LIMIT_UNSAFE, see utf_old.h. */
+#define UTF_SET_CHAR_LIMIT_UNSAFE(s, i)              UTF16_SET_CHAR_LIMIT_UNSAFE(s, i)
+
+/** @deprecated ICU 2.4. Renamed to U16_SET_CP_LIMIT, see utf_old.h. */
+#define UTF_SET_CHAR_LIMIT_SAFE(s, start, i, length) UTF16_SET_CHAR_LIMIT_SAFE(s, start, i, length)
+
+/* Define default macros (UTF-16 "safe") ------------------------------------ */
+
+/**
+ * Does this code unit alone encode a code point (BMP, not a surrogate)?
+ * Same as UTF16_IS_SINGLE.
+ * @deprecated ICU 2.4. Renamed to U_IS_SINGLE and U16_IS_SINGLE, see utf_old.h.
+ */
+#define UTF_IS_SINGLE(uchar) U16_IS_SINGLE(uchar)
+
+/**
+ * Is this code unit the first one of several (a lead surrogate)?
+ * Same as UTF16_IS_LEAD.
+ * @deprecated ICU 2.4. Renamed to U_IS_LEAD and U16_IS_LEAD, see utf_old.h.
+ */
+#define UTF_IS_LEAD(uchar) U16_IS_LEAD(uchar)
+
+/**
+ * Is this code unit one of several but not the first one (a trail surrogate)?
+ * Same as UTF16_IS_TRAIL.
+ * @deprecated ICU 2.4. Renamed to U_IS_TRAIL and U16_IS_TRAIL, see utf_old.h.
+ */
+#define UTF_IS_TRAIL(uchar) U16_IS_TRAIL(uchar)
+
+/**
+ * Does this code point require multiple code units (is it a supplementary code point)?
+ * Same as UTF16_NEED_MULTIPLE_UCHAR.
+ * @deprecated ICU 2.4. Use U16_LENGTH or test ((uint32_t)(c)>0xffff) instead.
+ */
+#define UTF_NEED_MULTIPLE_UCHAR(c) UTF16_NEED_MULTIPLE_UCHAR(c)
+
+/**
+ * How many code units are used to encode this code point (1 or 2)?
+ * Same as UTF16_CHAR_LENGTH.
+ * @deprecated ICU 2.4. Renamed to U16_LENGTH, see utf_old.h.
+ */
+#define UTF_CHAR_LENGTH(c) U16_LENGTH(c)
+
+/**
+ * How many code units are used at most for any Unicode code point (2)?
+ * Same as UTF16_MAX_CHAR_LENGTH.
+ * @deprecated ICU 2.4. Renamed to U16_MAX_LENGTH, see utf_old.h.
+ */
+#define UTF_MAX_CHAR_LENGTH U16_MAX_LENGTH
+
+/**
+ * Set c to the code point that contains the code unit i.
+ * i could point to the lead or the trail surrogate for the code point.
+ * i is not modified.
+ * Same as UTF16_GET_CHAR.
+ * \pre 0<=i<length
+ *
+ * @deprecated ICU 2.4. Renamed to U16_GET, see utf_old.h.
+ */
+#define UTF_GET_CHAR(s, start, i, length, c) U16_GET(s, start, i, length, c)
+
+/**
+ * Set c to the code point that starts at code unit i
+ * and advance i to beyond the code units of this code point (post-increment).
+ * i must point to the first code unit of a code point.
+ * Otherwise c is set to the trail unit (surrogate) itself.
+ * Same as UTF16_NEXT_CHAR.
+ * \pre 0<=i<length
+ * \post 0<i<=length
+ *
+ * @deprecated ICU 2.4. Renamed to U16_NEXT, see utf_old.h.
+ */
+#define UTF_NEXT_CHAR(s, i, length, c) U16_NEXT(s, i, length, c)
+
+/**
+ * Append the code units of code point c to the string at index i
+ * and advance i to beyond the new code units (post-increment).
+ * The code units beginning at index i will be overwritten.
+ * Same as UTF16_APPEND_CHAR.
+ * \pre 0<=c<=0x10ffff
+ * \pre 0<=i<length
+ * \post 0<i<=length
+ *
+ * @deprecated ICU 2.4. Use U16_APPEND instead, see utf_old.h.
+ */
+#define UTF_APPEND_CHAR(s, i, length, c) UTF16_APPEND_CHAR_SAFE(s, i, length, c)
+
+/**
+ * Advance i to beyond the code units of the code point that begins at i.
+ * I.e., advance i by one code point.
+ * Same as UTF16_FWD_1.
+ * \pre 0<=i<length
+ * \post 0<i<=length
+ *
+ * @deprecated ICU 2.4. Renamed to U16_FWD_1, see utf_old.h.
+ */
+#define UTF_FWD_1(s, i, length) U16_FWD_1(s, i, length)
+
+/**
+ * Advance i to beyond the code units of the n code points where the first one begins at i.
+ * I.e., advance i by n code points.
+ * Same as UT16_FWD_N.
+ * \pre 0<=i<length
+ * \post 0<i<=length
+ *
+ * @deprecated ICU 2.4. Renamed to U16_FWD_N, see utf_old.h.
+ */
+#define UTF_FWD_N(s, i, length, n) U16_FWD_N(s, i, length, n)
+
+/**
+ * Take the random-access index i and adjust it so that it points to the beginning
+ * of a code point.
+ * The input index points to any code unit of a code point and is moved to point to
+ * the first code unit of the same code point. i is never incremented.
+ * In other words, if i points to a trail surrogate that is preceded by a matching
+ * lead surrogate, then i is decremented. Otherwise it is not modified.
+ * This can be used to start an iteration with UTF_NEXT_CHAR() from a random index.
+ * Same as UTF16_SET_CHAR_START.
+ * \pre start<=i<length
+ * \post start<=i<length
+ *
+ * @deprecated ICU 2.4. Renamed to U16_SET_CP_START, see utf_old.h.
+ */
+#define UTF_SET_CHAR_START(s, start, i) U16_SET_CP_START(s, start, i)
+
+/**
+ * Set c to the code point that has code units before i
+ * and move i backward (towards the beginning of the string)
+ * to the first code unit of this code point (pre-increment).
+ * i must point to the first code unit after the last unit of a code point (i==length is allowed).
+ * Same as UTF16_PREV_CHAR.
+ * \pre start<i<=length
+ * \post start<=i<length
+ *
+ * @deprecated ICU 2.4. Renamed to U16_PREV, see utf_old.h.
+ */
+#define UTF_PREV_CHAR(s, start, i, c) U16_PREV(s, start, i, c)
+
+/**
+ * Move i backward (towards the beginning of the string)
+ * to the first code unit of the code point that has code units before i.
+ * I.e., move i backward by one code point.
+ * i must point to the first code unit after the last unit of a code point (i==length is allowed).
+ * Same as UTF16_BACK_1.
+ * \pre start<i<=length
+ * \post start<=i<length
+ *
+ * @deprecated ICU 2.4. Renamed to U16_BACK_1, see utf_old.h.
+ */
+#define UTF_BACK_1(s, start, i) U16_BACK_1(s, start, i)
+
+/**
+ * Move i backward (towards the beginning of the string)
+ * to the first code unit of the n code points that have code units before i.
+ * I.e., move i backward by n code points.
+ * i must point to the first code unit after the last unit of a code point (i==length is allowed).
+ * Same as UTF16_BACK_N.
+ * \pre start<i<=length
+ * \post start<=i<length
+ *
+ * @deprecated ICU 2.4. Renamed to U16_BACK_N, see utf_old.h.
+ */
+#define UTF_BACK_N(s, start, i, n) U16_BACK_N(s, start, i, n)
+
+/**
+ * Take the random-access index i and adjust it so that it points beyond
+ * a code point. The input index points beyond any code unit
+ * of a code point and is moved to point beyond the last code unit of the same
+ * code point. i is never decremented.
+ * In other words, if i points to a trail surrogate that is preceded by a matching
+ * lead surrogate, then i is incremented. Otherwise it is not modified.
+ * This can be used to start an iteration with UTF_PREV_CHAR() from a random index.
+ * Same as UTF16_SET_CHAR_LIMIT.
+ * \pre start<i<=length
+ * \post start<i<=length
+ *
+ * @deprecated ICU 2.4. Renamed to U16_SET_CP_LIMIT, see utf_old.h.
+ */
+#define UTF_SET_CHAR_LIMIT(s, start, i, length) U16_SET_CP_LIMIT(s, start, i, length)
+
+#endif /* U_HIDE_DEPRECATED_API */
+
+#endif
+

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/utmscale.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/utmscale.h b/src/apps/couch_collate/platform/osx/icu/unicode/utmscale.h
new file mode 100644
index 0000000..368e426
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/utmscale.h
@@ -0,0 +1,481 @@
+/*
+*******************************************************************************
+* Copyright (C) 2004 - 2008, International Business Machines Corporation and
+* others. All Rights Reserved.
+*******************************************************************************
+*/
+
+#ifndef UTMSCALE_H
+#define UTMSCALE_H
+
+#include "unicode/utypes.h"
+
+#if !UCONFIG_NO_FORMATTING
+
+/** 
+ * \file
+ * \brief C API: Universal Time Scale
+ *
+ * There are quite a few different conventions for binary datetime, depending on different
+ * platforms and protocols. Some of these have severe drawbacks. For example, people using
+ * Unix time (seconds since Jan 1, 1970) think that they are safe until near the year 2038.
+ * But cases can and do arise where arithmetic manipulations causes serious problems. Consider
+ * the computation of the average of two datetimes, for example: if one calculates them with
+ * <code>averageTime = (time1 + time2)/2</code>, there will be overflow even with dates
+ * around the present. Moreover, even if these problems don't occur, there is the issue of
+ * conversion back and forth between different systems.
+ *
+ * <p>
+ * Binary datetimes differ in a number of ways: the datatype, the unit,
+ * and the epoch (origin). We'll refer to these as time scales. For example:
+ *
+ * <table border="1" cellspacing="0" cellpadding="4">
+ *  <caption>Table 1: Binary Time Scales</caption>
+ *  <tr>
+ *    <th align="left">Source</th>
+ *    <th align="left">Datatype</th>
+ *    <th align="left">Unit</th>
+ *    <th align="left">Epoch</th>
+ *  </tr>
+ *
+ *  <tr>
+ *    <td>UDTS_JAVA_TIME</td>
+ *    <td>int64_t</td>
+ *    <td>milliseconds</td>
+ *    <td>Jan 1, 1970</td>
+ *  </tr>
+ *  <tr>
+ *
+ *    <td>UDTS_UNIX_TIME</td>
+ *    <td>int32_t or int64_t</td>
+ *    <td>seconds</td>
+ *    <td>Jan 1, 1970</td>
+ *  </tr>
+ *  <tr>
+ *    <td>UDTS_ICU4C_TIME</td>
+ *
+ *    <td>double</td>
+ *    <td>milliseconds</td>
+ *    <td>Jan 1, 1970</td>
+ *  </tr>
+ *  <tr>
+ *    <td>UDTS_WINDOWS_FILE_TIME</td>
+ *    <td>int64_t</td>
+ *
+ *    <td>ticks (100 nanoseconds)</td>
+ *    <td>Jan 1, 1601</td>
+ *  </tr>
+ *  <tr>
+ *    <td>UDTS_DOTNET_DATE_TIME</td>
+ *    <td>int64_t</td>
+ *    <td>ticks (100 nanoseconds)</td>
+ *
+ *    <td>Jan 1, 0001</td>
+ *  </tr>
+ *  <tr>
+ *    <td>UDTS_MAC_OLD_TIME</td>
+ *    <td>int32_t or int64_t</td>
+ *    <td>seconds</td>
+ *    <td>Jan 1, 1904</td>
+ *
+ *  </tr>
+ *  <tr>
+ *    <td>UDTS_MAC_TIME</td>
+ *    <td>double</td>
+ *    <td>seconds</td>
+ *    <td>Jan 1, 2001</td>
+ *  </tr>
+ *
+ *  <tr>
+ *    <td>UDTS_EXCEL_TIME</td>
+ *    <td>?</td>
+ *    <td>days</td>
+ *    <td>Dec 31, 1899</td>
+ *  </tr>
+ *  <tr>
+ *
+ *    <td>UDTS_DB2_TIME</td>
+ *    <td>?</td>
+ *    <td>days</td>
+ *    <td>Dec 31, 1899</td>
+ *  </tr>
+ *
+ *  <tr>
+ *    <td>UDTS_UNIX_MICROSECONDS_TIME</td>
+ *    <td>int64_t</td>
+ *    <td>microseconds</td>
+ *    <td>Jan 1, 1970</td>
+ *  </tr>
+ * </table>
+ *
+ * <p>
+ * All of the epochs start at 00:00 am (the earliest possible time on the day in question),
+ * and are assumed to be UTC.
+ *
+ * <p>
+ * The ranges for different datatypes are given in the following table (all values in years).
+ * The range of years includes the entire range expressible with positive and negative
+ * values of the datatype. The range of years for double is the range that would be allowed
+ * without losing precision to the corresponding unit.
+ *
+ * <table border="1" cellspacing="0" cellpadding="4">
+ *  <tr>
+ *    <th align="left">Units</th>
+ *    <th align="left">int64_t</th>
+ *    <th align="left">double</th>
+ *    <th align="left">int32_t</th>
+ *  </tr>
+ *
+ *  <tr>
+ *    <td>1 sec</td>
+ *    <td align="right">5.84542x10<sup>11</sup></td>
+ *    <td align="right">285,420,920.94</td>
+ *    <td align="right">136.10</td>
+ *  </tr>
+ *  <tr>
+ *
+ *    <td>1 millisecond</td>
+ *    <td align="right">584,542,046.09</td>
+ *    <td align="right">285,420.92</td>
+ *    <td align="right">0.14</td>
+ *  </tr>
+ *  <tr>
+ *    <td>1 microsecond</td>
+ *
+ *    <td align="right">584,542.05</td>
+ *    <td align="right">285.42</td>
+ *    <td align="right">0.00</td>
+ *  </tr>
+ *  <tr>
+ *    <td>100 nanoseconds (tick)</td>
+ *    <td align="right">58,454.20</td>
+ *    <td align="right">28.54</td>
+ *    <td align="right">0.00</td>
+ *  </tr>
+ *  <tr>
+ *    <td>1 nanosecond</td>
+ *    <td align="right">584.5420461</td>
+ *    <td align="right">0.2854</td>
+ *    <td align="right">0.00</td>
+ *  </tr>
+ * </table>
+ *
+ * <p>
+ * These functions implement a universal time scale which can be used as a 'pivot',
+ * and provide conversion functions to and from all other major time scales.
+ * This datetimes to be converted to the pivot time, safely manipulated,
+ * and converted back to any other datetime time scale.
+ *
+ *<p>
+ * So what to use for this pivot? Java time has plenty of range, but cannot represent
+ * .NET <code>System.DateTime</code> values without severe loss of precision. ICU4C time addresses this by using a
+ * <code>double</code> that is otherwise equivalent to the Java time. However, there are disadvantages
+ * with <code>doubles</code>. They provide for much more graceful degradation in arithmetic operations.
+ * But they only have 53 bits of accuracy, which means that they will lose precision when
+ * converting back and forth to ticks. What would really be nice would be a
+ * <code>long double</code> (80 bits -- 64 bit mantissa), but that is not supported on most systems.
+ *
+ *<p>
+ * The Unix extended time uses a structure with two components: time in seconds and a
+ * fractional field (microseconds). However, this is clumsy, slow, and
+ * prone to error (you always have to keep track of overflow and underflow in the
+ * fractional field). <code>BigDecimal</code> would allow for arbitrary precision and arbitrary range,
+ * but we do not want to use this as the normal type, because it is slow and does not
+ * have a fixed size.
+ *
+ *<p>
+ * Because of these issues, we ended up concluding that the .NET framework's
+ * <code>System.DateTime</code> would be the best pivot. However, we use the full range
+ * allowed by the datatype, allowing for datetimes back to 29,000 BC and up to 29,000 AD.
+ * This time scale is very fine grained, does not lose precision, and covers a range that
+ * will meet almost all requirements. It will not handle the range that Java times do,
+ * but frankly, being able to handle dates before 29,000 BC or after 29,000 AD is of very limited interest.
+ *
+ */
+
+/**
+ * <code>UDateTimeScale</code> values are used to specify the time scale used for
+ * conversion into or out if the universal time scale.
+ *
+ * @stable ICU 3.2
+ */
+typedef enum UDateTimeScale {
+    /**
+     * Used in the JDK. Data is a Java <code>long</code> (<code>int64_t</code>). Value
+     * is milliseconds since January 1, 1970.
+     *
+     * @stable ICU 3.2
+     */
+    UDTS_JAVA_TIME = 0,
+
+    /**
+     * Used on Unix systems. Data is <code>int32_t</code> or <code>int64_t</code>. Value
+     * is seconds since January 1, 1970.
+     *
+     * @stable ICU 3.2
+     */
+    UDTS_UNIX_TIME,
+    
+    /**
+     * Used in IUC4C. Data is a <code>double</code>. Value
+     * is milliseconds since January 1, 1970.
+     *
+     * @stable ICU 3.2
+     */
+    UDTS_ICU4C_TIME,
+    
+    /**
+     * Used in Windows for file times. Data is an <code>int64_t</code>. Value
+     * is ticks (1 tick == 100 nanoseconds) since January 1, 1601.
+     *
+     * @stable ICU 3.2
+     */
+    UDTS_WINDOWS_FILE_TIME,
+    
+    /**
+     * Used in the .NET framework's <code>System.DateTime</code> structure. Data is an <code>int64_t</code>. Value
+     * is ticks (1 tick == 100 nanoseconds) since January 1, 0001.
+     *
+     * @stable ICU 3.2
+     */
+    UDTS_DOTNET_DATE_TIME,
+    
+    /**
+     * Used in older Macintosh systems. Data is <code>int32_t</code> or <code>int64_t</code>. Value
+     * is seconds since January 1, 1904.
+     *
+     * @stable ICU 3.2
+     */
+    UDTS_MAC_OLD_TIME,
+    
+    /**
+     * Used in newer Macintosh systems. Data is a <code>double</code>. Value
+     * is seconds since January 1, 2001.
+     *
+     * @stable ICU 3.2
+     */
+    UDTS_MAC_TIME,
+    
+    /**
+     * Used in Excel. Data is an <code>?unknown?</code>. Value
+     * is days since December 31, 1899.
+     *
+     * @stable ICU 3.2
+     */
+    UDTS_EXCEL_TIME,
+    
+    /**
+     * Used in DB2. Data is an <code>?unknown?</code>. Value
+     * is days since December 31, 1899.
+     *
+     * @stable ICU 3.2
+     */
+    UDTS_DB2_TIME,
+
+    /**
+     * Data is a <code>long</code>. Value is microseconds since January 1, 1970.
+     * Similar to Unix time (linear value from 1970) and struct timeval
+     * (microseconds resolution).
+     *
+     * @stable ICU 4.0
+     */
+    UDTS_UNIX_MICROSECONDS_TIME,
+
+    /**
+     * The first unused time scale value. The limit of this enum
+     */
+    UDTS_MAX_SCALE
+} UDateTimeScale;
+
+/**
+ * <code>UTimeScaleValue</code> values are used to specify the time scale values
+ * to <code>utmscale_getTimeScaleValue</code>.
+ *
+ * @see utmscale_getTimeScaleValue
+ *
+ * @stable ICU 3.2
+ */
+typedef enum UTimeScaleValue {
+    /**
+     * The constant used to select the units vale
+     * for a time scale.
+     * 
+     * @see utmscale_getTimeScaleValue
+     *
+     * @stable ICU 3.2
+     */
+    UTSV_UNITS_VALUE = 0,
+
+    /**
+     * The constant used to select the epoch offset value
+     * for a time scale.
+     * 
+     * @see utmscale_getTimeScaleValue
+     *
+     * @stable ICU 3.2
+     */
+    UTSV_EPOCH_OFFSET_VALUE=1,
+
+    /**
+     * The constant used to select the minimum from value
+     * for a time scale.
+     * 
+     * @see utmscale_getTimeScaleValue
+     *
+     * @stable ICU 3.2
+     */
+    UTSV_FROM_MIN_VALUE=2,
+
+    /**
+     * The constant used to select the maximum from value
+     * for a time scale.
+     * 
+     * @see utmscale_getTimeScaleValue
+     *
+     * @stable ICU 3.2
+     */
+    UTSV_FROM_MAX_VALUE=3,
+
+    /**
+     * The constant used to select the minimum to value
+     * for a time scale.
+     * 
+     * @see utmscale_getTimeScaleValue
+     *
+     * @stable ICU 3.2
+     */
+    UTSV_TO_MIN_VALUE=4,
+
+    /**
+     * The constant used to select the maximum to value
+     * for a time scale.
+     * 
+     * @see utmscale_getTimeScaleValue
+     *
+     * @stable ICU 3.2
+     */
+    UTSV_TO_MAX_VALUE=5,
+
+#ifndef U_HIDE_INTERNAL_API
+    /**
+     * The constant used to select the epoch plus one value
+     * for a time scale.
+     * 
+     * NOTE: This is an internal value. DO NOT USE IT. May not
+     * actually be equal to the epoch offset value plus one.
+     * 
+     * @see utmscale_getTimeScaleValue
+     *
+     * @internal ICU 3.2
+     */
+    UTSV_EPOCH_OFFSET_PLUS_1_VALUE=6,
+
+    /**
+     * The constant used to select the epoch plus one value
+     * for a time scale.
+     * 
+     * NOTE: This is an internal value. DO NOT USE IT. May not
+     * actually be equal to the epoch offset value plus one.
+     * 
+     * @see utmscale_getTimeScaleValue
+     *
+     * @internal ICU 3.2
+     */
+    UTSV_EPOCH_OFFSET_MINUS_1_VALUE=7,
+
+    /**
+     * The constant used to select the units round value
+     * for a time scale.
+     * 
+     * NOTE: This is an internal value. DO NOT USE IT.
+     * 
+     * @see utmscale_getTimeScaleValue
+     *
+     * @internal ICU 3.2
+     */
+    UTSV_UNITS_ROUND_VALUE=8,
+
+    /**
+     * The constant used to select the minimum safe rounding value
+     * for a time scale.
+     * 
+     * NOTE: This is an internal value. DO NOT USE IT.
+     * 
+     * @see utmscale_getTimeScaleValue
+     *
+     * @internal ICU 3.2
+     */
+    UTSV_MIN_ROUND_VALUE=9,
+
+    /**
+     * The constant used to select the maximum safe rounding value
+     * for a time scale.
+     * 
+     * NOTE: This is an internal value. DO NOT USE IT.
+     * 
+     * @see utmscale_getTimeScaleValue
+     *
+     * @internal ICU 3.2
+     */
+    UTSV_MAX_ROUND_VALUE=10,
+
+#endif /* U_HIDE_INTERNAL_API */
+
+    /**
+     * The number of time scale values, in other words limit of this enum.
+     * 
+     * @see utmscale_getTimeScaleValue
+     */
+    UTSV_MAX_SCALE_VALUE=11
+
+} UTimeScaleValue;
+
+/**
+ * Get a value associated with a particular time scale.
+ * 
+ * @param timeScale The time scale
+ * @param value A constant representing the value to get
+ * @param status The status code. Set to <code>U_ILLEGAL_ARGUMENT_ERROR</code> if arguments are invalid.
+ * @return - the value.
+ * 
+ * @stable ICU 3.2
+ */
+U_STABLE int64_t U_EXPORT2
+    utmscale_getTimeScaleValue(UDateTimeScale timeScale, UTimeScaleValue value, UErrorCode *status);
+
+/* Conversion to 'universal time scale' */
+
+/**
+ * Convert a <code>int64_t</code> datetime from the given time scale to the universal time scale.
+ *
+ * @param otherTime The <code>int64_t</code> datetime
+ * @param timeScale The time scale to convert from
+ * @param status The status code. Set to <code>U_ILLEGAL_ARGUMENT_ERROR</code> if the conversion is out of range.
+ * 
+ * @return The datetime converted to the universal time scale
+ *
+ * @stable ICU 3.2
+ */
+U_STABLE int64_t U_EXPORT2
+    utmscale_fromInt64(int64_t otherTime, UDateTimeScale timeScale, UErrorCode *status);
+
+/* Conversion from 'universal time scale' */
+
+/**
+ * Convert a datetime from the universal time scale to a <code>int64_t</code> in the given time scale.
+ *
+ * @param universalTime The datetime in the universal time scale
+ * @param timeScale The time scale to convert to
+ * @param status The status code. Set to <code>U_ILLEGAL_ARGUMENT_ERROR</code> if the conversion is out of range.
+ * 
+ * @return The datetime converted to the given time scale
+ *
+ * @stable ICU 3.2
+ */
+U_STABLE int64_t U_EXPORT2
+    utmscale_toInt64(int64_t universalTime, UDateTimeScale timeScale, UErrorCode *status);
+
+#endif /* #if !UCONFIG_NO_FORMATTING */
+
+#endif
+


[80/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/regex.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/regex.h b/src/apps/couch_collate/platform/osx/icu/unicode/regex.h
new file mode 100644
index 0000000..64b58bb
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/regex.h
@@ -0,0 +1,1232 @@
+/*
+**********************************************************************
+*   Copyright (C) 2002-2008, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+**********************************************************************
+*   file name:  regex.h
+*   encoding:   US-ASCII
+*   indentation:4
+*
+*   created on: 2002oct22
+*   created by: Andy Heninger
+*
+*   ICU Regular Expressions, API for C++
+*/
+
+#ifndef REGEX_H
+#define REGEX_H
+
+//#define REGEX_DEBUG
+
+/**
+ * \file
+ * \brief  C++ API:  Regular Expressions
+ *
+ * <h2>Regular Expression API</h2>
+ *
+ * <p>The ICU API for processing regular expressions consists of two classes,
+ *  <code>RegexPattern</code> and <code>RegexMatcher</code>.
+ *  <code>RegexPattern</code> objects represent a pre-processed, or compiled
+ *  regular expression.  They are created from a regular expression pattern string,
+ *  and can be used to create <code>RegexMatcher</code> objects for the pattern.</p>
+ *
+ * <p>Class <code>RegexMatcher</code> bundles together a regular expression
+ *  pattern and a target string to which the search pattern will be applied.
+ *  <code>RegexMatcher</code> includes API for doing plain find or search
+ *  operations, for search and replace operations, and for obtaining detailed
+ *  information about bounds of a match. </p>
+ *
+ * <p>Note that by constructing <code>RegexMatcher</code> objects directly from regular
+ * expression pattern strings application code can be simplified and the explicit
+ * need for <code>RegexPattern</code> objects can usually be eliminated.
+ * </p>
+ */
+
+#include "unicode/utypes.h"
+
+#if !UCONFIG_NO_REGULAR_EXPRESSIONS
+
+#include "unicode/uobject.h"
+#include "unicode/unistr.h"
+#include "unicode/parseerr.h"
+
+#include "unicode/uregex.h"
+
+U_NAMESPACE_BEGIN
+
+
+// Forward Declarations...
+
+class RegexMatcher;
+class RegexPattern;
+class UVector;
+class UVector32;
+class UnicodeSet;
+struct REStackFrame;
+struct Regex8BitSet;
+class  RuleBasedBreakIterator;
+class  RegexCImpl;
+
+
+
+
+/**
+ *   RBBIPatternDump   Debug function, displays the compiled form of a pattern.
+ *   @internal
+ */
+#ifdef REGEX_DEBUG
+U_INTERNAL void U_EXPORT2
+    RegexPatternDump(const RegexPattern *pat);
+#else
+    #define RegexPatternDump(pat)
+#endif
+
+
+
+/**
+  * Class <code>RegexPattern</code> represents a compiled regular expression.  It includes
+  * factory methods for creating a RegexPattern object from the source (string) form
+  * of a regular expression, methods for creating RegexMatchers that allow the pattern
+  * to be applied to input text, and a few convenience methods for simple common
+  * uses of regular expressions.
+  *
+  * <p>Class RegexPattern is not intended to be subclassed.</p>
+  *
+  * @stable ICU 2.4
+  */
+class U_I18N_API RegexPattern: public UObject {
+public:
+
+    /**
+     * default constructor.  Create a RegexPattern object that refers to no actual
+     *   pattern.  Not normally needed; RegexPattern objects are usually
+     *   created using the factory method <code>compile()</code>.
+     *
+     * @stable ICU 2.4
+     */
+    RegexPattern();
+
+    /**
+     * Copy Constructor.  Create a new RegexPattern object that is equivalent
+     *                    to the source object.
+     * @param source the pattern object to be copied.
+     * @stable ICU 2.4
+     */
+    RegexPattern(const RegexPattern &source);
+
+    /**
+     * Destructor.  Note that a RegexPattern object must persist so long as any
+     *  RegexMatcher objects that were created from the RegexPattern are active.
+     * @stable ICU 2.4
+     */
+    virtual ~RegexPattern();
+
+    /**
+     * Comparison operator.  Two RegexPattern objects are considered equal if they
+     * were constructed from identical source patterns using the same match flag
+     * settings.
+     * @param that a RegexPattern object to compare with "this".
+     * @return TRUE if the objects are equivalent.
+     * @stable ICU 2.4
+     */
+    UBool           operator==(const RegexPattern& that) const;
+
+    /**
+     * Comparison operator.  Two RegexPattern objects are considered equal if they
+     * were constructed from identical source patterns using the same match flag
+     * settings.
+     * @param that a RegexPattern object to compare with "this".
+     * @return TRUE if the objects are different.
+     * @stable ICU 2.4
+     */
+    inline UBool    operator!=(const RegexPattern& that) const {return ! operator ==(that);};
+
+    /**
+     * Assignment operator.  After assignment, this RegexPattern will behave identically
+     *     to the source object.
+     * @stable ICU 2.4
+     */
+    RegexPattern  &operator =(const RegexPattern &source);
+
+    /**
+     * Create an exact copy of this RegexPattern object.  Since RegexPattern is not
+     * intended to be subclasses, <code>clone()</code> and the copy construction are
+     * equivalent operations.
+     * @return the copy of this RegexPattern
+     * @stable ICU 2.4
+     */
+    virtual RegexPattern  *clone() const;
+
+
+   /**
+    * Compiles the regular expression in string form into a RegexPattern
+    * object.  These compile methods, rather than the constructors, are the usual
+    * way that RegexPattern objects are created.
+    *
+    * <p>Note that RegexPattern objects must not be deleted while RegexMatcher
+    * objects created from the pattern are active.  RegexMatchers keep a pointer
+    * back to their pattern, so premature deletion of the pattern is a
+    * catastrophic error.</p>
+    *
+    * <p>All pattern match mode flags are set to their default values.</p>
+    *
+    * <p>Note that it is often more convenient to construct a RegexMatcher directly
+    *    from a pattern string rather than separately compiling the pattern and
+    *    then creating a RegexMatcher object from the pattern.</p>
+    *
+    * @param regex The regular expression to be compiled.
+    * @param pe    Receives the position (line and column nubers) of any error
+    *              within the regular expression.)
+    * @param status A reference to a UErrorCode to receive any errors.
+    * @return      A regexPattern object for the compiled pattern.
+    *
+    * @stable ICU 2.4
+    */
+    static RegexPattern * U_EXPORT2 compile( const UnicodeString &regex,
+        UParseError          &pe,
+        UErrorCode           &status);
+
+   /**
+    * Compiles the regular expression in string form into a RegexPattern
+    * object using the specified match mode flags.  These compile methods,
+    * rather than the constructors, are the usual way that RegexPattern objects
+    * are created.
+    *
+    * <p>Note that RegexPattern objects must not be deleted while RegexMatcher
+    * objects created from the pattern are active.  RegexMatchers keep a pointer
+    * back to their pattern, so premature deletion of the pattern is a
+    * catastrophic error.</p>
+    *
+    * <p>Note that it is often more convenient to construct a RegexMatcher directly
+    *    from a pattern string instead of than separately compiling the pattern and
+    *    then creating a RegexMatcher object from the pattern.</p>
+    *
+    * @param regex The regular expression to be compiled.
+    * @param flags The match mode flags to be used.
+    * @param pe    Receives the position (line and column nubers) of any error
+    *              within the regular expression.)
+    * @param status   A reference to a UErrorCode to receive any errors.
+    * @return      A regexPattern object for the compiled pattern.
+    *
+    * @stable ICU 2.4
+    */
+    static RegexPattern * U_EXPORT2 compile( const UnicodeString &regex,
+        uint32_t             flags,
+        UParseError          &pe,
+        UErrorCode           &status);
+
+
+   /**
+    * Compiles the regular expression in string form into a RegexPattern
+    * object using the specified match mode flags.  These compile methods,
+    * rather than the constructors, are the usual way that RegexPattern objects
+    * are created.
+    *
+    * <p>Note that RegexPattern objects must not be deleted while RegexMatcher
+    * objects created from the pattern are active.  RegexMatchers keep a pointer
+    * back to their pattern, so premature deletion of the pattern is a
+    * catastrophic error.</p>
+    *
+    * <p>Note that it is often more convenient to construct a RegexMatcher directly
+    *    from a pattern string instead of than separately compiling the pattern and
+    *    then creating a RegexMatcher object from the pattern.</p>
+    *
+    * @param regex The regular expression to be compiled.
+    * @param flags The match mode flags to be used.
+    * @param status   A reference to a UErrorCode to receive any errors.
+    * @return      A regexPattern object for the compiled pattern.
+    *
+    * @stable ICU 2.6
+    */
+    static RegexPattern * U_EXPORT2 compile( const UnicodeString &regex,
+        uint32_t             flags,
+        UErrorCode           &status);
+
+
+   /**
+    * Get the match mode flags that were used when compiling this pattern.
+    * @return  the match mode flags
+    * @stable ICU 2.4
+    */
+    virtual uint32_t flags() const;
+
+   /**
+    * Creates a RegexMatcher that will match the given input against this pattern.  The
+    * RegexMatcher can then be used to perform match, find or replace operations
+    * on the input.  Note that a RegexPattern object must not be deleted while
+    * RegexMatchers created from it still exist and might possibly be used again.
+    * <p>
+    * The matcher will retain a reference to the supplied input string, and all regexp
+    * pattern matching operations happen directly on this original string.  It is
+    * critical that the string not be altered or deleted before use by the regular
+    * expression operations is complete.
+    *
+    * @param input    The input string to which the regular expression will be applied.
+    * @param status   A reference to a UErrorCode to receive any errors.
+    * @return         A RegexMatcher object for this pattern and input.
+    *
+    * @stable ICU 2.4
+    */
+    virtual RegexMatcher *matcher(const UnicodeString &input,
+        UErrorCode          &status) const;
+
+private:
+    /**
+     * Cause a compilation error if an application accidently attempts to
+     *   create a matcher with a (UChar *) string as input rather than
+     *   a UnicodeString.  Avoids a dangling reference to a temporary string.
+     * <p>
+     * To efficiently work with UChar *strings, wrap the data in a UnicodeString
+     * using one of the aliasing constructors, such as
+     * <code>UnicodeString(UBool isTerminated, const UChar *text, int32_t textLength);</code>
+     *
+     * @internal
+     */
+    RegexMatcher *matcher(const UChar *input,
+        UErrorCode          &status) const;
+public:
+
+
+   /**
+    * Creates a RegexMatcher that will match against this pattern.  The
+    * RegexMatcher can be used to perform match, find or replace operations.
+    * Note that a RegexPattern object must not be deleted while
+    * RegexMatchers created from it still exist and might possibly be used again.
+    *
+    * @param status   A reference to a UErrorCode to receive any errors.
+    * @return      A RegexMatcher object for this pattern and input.
+    *
+    * @stable ICU 2.6
+    */
+    virtual RegexMatcher *matcher(UErrorCode  &status) const;
+
+
+   /**
+    * Test whether a string matches a regular expression.  This convenience function
+    * both compiles the reguluar expression and applies it in a single operation.
+    * Note that if the same pattern needs to be applied repeatedly, this method will be
+    * less efficient than creating and reusing a RegexMatcher object.
+    *
+    * @param regex The regular expression
+    * @param input The string data to be matched
+    * @param pe Receives the position of any syntax errors within the regular expression
+    * @param status A reference to a UErrorCode to receive any errors.
+    * @return True if the regular expression exactly matches the full input string.
+    *
+    * @stable ICU 2.4
+    */
+    static UBool U_EXPORT2 matches(const UnicodeString   &regex,
+        const UnicodeString   &input,
+        UParseError     &pe,
+        UErrorCode      &status);
+
+
+   /**
+    *    Returns the regular expression from which this pattern was compiled.
+    *    @stable ICU 2.4
+    */
+    virtual UnicodeString pattern() const;
+
+
+    /**
+     * Split a string into fields.  Somewhat like split() from Perl.
+     * The pattern matches identify delimiters that separate the input
+     *  into fields.  The input data between the matches becomes the
+     *  fields themselves.
+     * <p>
+     *  For the best performance on split() operations,
+     *  <code>RegexMatcher::split</code> is perferable to this function
+     *
+     * @param input   The string to be split into fields.  The field delimiters
+     *                match the pattern (in the "this" object)
+     * @param dest    An array of UnicodeStrings to receive the results of the split.
+     *                This is an array of actual UnicodeString objects, not an
+     *                array of pointers to strings.  Local (stack based) arrays can
+     *                work well here.
+     * @param destCapacity  The number of elements in the destination array.
+     *                If the number of fields found is less than destCapacity, the
+     *                extra strings in the destination array are not altered.
+     *                If the number of destination strings is less than the number
+     *                of fields, the trailing part of the input string, including any
+     *                field delimiters, is placed in the last destination string.
+     * @param status  A reference to a UErrorCode to receive any errors.
+     * @return        The number of fields into which the input string was split.
+     * @stable ICU 2.4
+     */
+    virtual int32_t  split(const UnicodeString &input,
+        UnicodeString    dest[],
+        int32_t          destCapacity,
+        UErrorCode       &status) const;
+
+
+    /**
+     * ICU "poor man's RTTI", returns a UClassID for the actual class.
+     *
+     * @stable ICU 2.4
+     */
+    virtual UClassID getDynamicClassID() const;
+
+    /**
+     * ICU "poor man's RTTI", returns a UClassID for this class.
+     *
+     * @stable ICU 2.4
+     */
+    static UClassID U_EXPORT2 getStaticClassID();
+
+private:
+    //
+    //  Implementation Data
+    //
+    UnicodeString   fPattern;      // The original pattern string.
+    uint32_t        fFlags;        // The flags used when compiling the pattern.
+                                   //
+    UVector32       *fCompiledPat; // The compiled pattern p-code.
+    UnicodeString   fLiteralText;  // Any literal string data from the pattern,
+                                   //   after un-escaping, for use during the match.
+
+    UVector         *fSets;        // Any UnicodeSets referenced from the pattern.
+    Regex8BitSet    *fSets8;       //      (and fast sets for latin-1 range.)
+
+
+    UErrorCode      fDeferredStatus; // status if some prior error has left this
+                                   //  RegexPattern in an unusable state.
+
+    int32_t         fMinMatchLen;  // Minimum Match Length.  All matches will have length
+                                   //   >= this value.  For some patterns, this calculated
+                                   //   value may be less than the true shortest
+                                   //   possible match.
+
+    int32_t         fFrameSize;    // Size of a state stack frame in the
+                                   //   execution engine.
+
+    int32_t         fDataSize;     // The size of the data needed by the pattern that
+                                   //   does not go on the state stack, but has just
+                                   //   a single copy per matcher.
+
+    UVector32       *fGroupMap;    // Map from capture group number to position of
+                                   //   the group's variables in the matcher stack frame.
+
+    int32_t         fMaxCaptureDigits;
+
+    UnicodeSet     **fStaticSets;  // Ptr to static (shared) sets for predefined
+                                   //   regex character classes, e.g. Word.
+
+    Regex8BitSet   *fStaticSets8;  // Ptr to the static (shared) latin-1 only
+                                   //  sets for predefined regex classes.
+
+    int32_t         fStartType;    // Info on how a match must start.
+    int32_t         fInitialStringIdx;     //
+    int32_t         fInitialStringLen;
+    UnicodeSet     *fInitialChars;
+    UChar32         fInitialChar;
+    Regex8BitSet   *fInitialChars8;
+
+    friend class RegexCompile;
+    friend class RegexMatcher;
+    friend class RegexCImpl;
+
+    //
+    //  Implementation Methods
+    //
+    void        init();            // Common initialization, for use by constructors.
+    void        zap();             // Common cleanup
+#ifdef REGEX_DEBUG
+    void        dumpOp(int32_t index) const;
+    friend     void U_EXPORT2 RegexPatternDump(const RegexPattern *);
+#endif
+
+};
+
+
+
+/**
+ *  class RegexMatcher bundles together a reular expression pattern and
+ *  input text to which the expression can be applied.  It includes methods
+ *  for testing for matches, and for find and replace operations.
+ *
+ * <p>Class RegexMatcher is not intended to be subclassed.</p>
+ *
+ * @stable ICU 2.4
+ */
+class U_I18N_API RegexMatcher: public UObject {
+public:
+
+    /**
+      * Construct a RegexMatcher for a regular expression.
+      * This is a convenience method that avoids the need to explicitly create
+      * a RegexPattern object.  Note that if several RegexMatchers need to be
+      * created for the same expression, it will be more efficient to
+      * separately create and cache a RegexPattern object, and use
+      * its matcher() method to create the RegexMatcher objects.
+      *
+      *  @param regexp The Regular Expression to be compiled.
+      *  @param flags  Regular expression options, such as case insensitive matching.
+      *                @see UREGEX_CASE_INSENSITIVE
+      *  @param status Any errors are reported by setting this UErrorCode variable.
+      *  @stable ICU 2.6
+      */
+    RegexMatcher(const UnicodeString &regexp, uint32_t flags, UErrorCode &status);
+
+    /**
+      * Construct a RegexMatcher for a regular expression.
+      * This is a convenience method that avoids the need to explicitly create
+      * a RegexPattern object.  Note that if several RegexMatchers need to be
+      * created for the same expression, it will be more efficient to
+      * separately create and cache a RegexPattern object, and use
+      * its matcher() method to create the RegexMatcher objects.
+      * <p>
+      * The matcher will retain a reference to the supplied input string, and all regexp
+      * pattern matching operations happen directly on the original string.  It is
+      * critical that the string not be altered or deleted before use by the regular
+      * expression operations is complete.
+      *
+      *  @param regexp The Regular Expression to be compiled.
+      *  @param input  The string to match.  The matcher retains a reference to the
+      *                caller's string; mo copy is made.
+      *  @param flags  Regular expression options, such as case insensitive matching.
+      *                @see UREGEX_CASE_INSENSITIVE
+      *  @param status Any errors are reported by setting this UErrorCode variable.
+      *  @stable ICU 2.6
+      */
+    RegexMatcher(const UnicodeString &regexp, const UnicodeString &input,
+        uint32_t flags, UErrorCode &status);
+
+private:
+    /**
+     * Cause a compilation error if an application accidently attempts to
+     *   create a matcher with a (UChar *) string as input rather than
+     *   a UnicodeString.    Avoids a dangling reference to a temporary string.
+     * <p>
+     * To efficiently work with UChar *strings, wrap the data in a UnicodeString
+     * using one of the aliasing constructors, such as
+     * <code>UnicodeString(UBool isTerminated, const UChar *text, int32_t textLength);</code>
+     *
+     * @internal
+     */
+    RegexMatcher(const UnicodeString &regexp, const UChar *input,
+        uint32_t flags, UErrorCode &status);
+public:
+
+
+   /**
+    *   Destructor.
+    *
+    *  @stable ICU 2.4
+    */
+    virtual ~RegexMatcher();
+
+
+   /**
+    *   Attempts to match the entire input region against the pattern.
+    *    @param   status     A reference to a UErrorCode to receive any errors.
+    *    @return TRUE if there is a match
+    *    @stable ICU 2.4
+    */
+    virtual UBool matches(UErrorCode &status);
+
+   /**
+    *   Resets the matcher, then attempts to match the input beginning 
+    *   at the specified startIndex, and extending to the end of the input.
+    *   The input region is reset to include the entire input string.
+    *   A successful match must extend to the end of the input.
+    *    @param   startIndex The input string index at which to begin matching.
+    *    @param   status     A reference to a UErrorCode to receive any errors.
+    *    @return TRUE if there is a match
+    *    @stable ICU 2.8
+    */
+    virtual UBool matches(int32_t startIndex, UErrorCode &status);
+
+
+
+
+   /**
+    *   Attempts to match the input string, starting from the beginning of the region,
+    *   against the pattern.  Like the matches() method, this function 
+    *   always starts at the beginning of the input region;
+    *   unlike that function, it does not require that the entire region be matched.
+    *
+    *   <p>If the match succeeds then more information can be obtained via the <code>start()</code>,
+    *     <code>end()</code>, and <code>group()</code> functions.</p>
+    *
+    *    @param   status     A reference to a UErrorCode to receive any errors.
+    *    @return  TRUE if there is a match at the start of the input string.
+    *    @stable ICU 2.4
+    */
+    virtual UBool lookingAt(UErrorCode &status);
+
+
+  /**
+    *   Attempts to match the input string, starting from the specified index, against the pattern.
+    *   The match may be of any length, and is not required to extend to the end
+    *   of the input string.  Contrast with match().
+    *
+    *   <p>If the match succeeds then more information can be obtained via the <code>start()</code>,
+    *     <code>end()</code>, and <code>group()</code> functions.</p>
+    *
+    *    @param   startIndex The input string index at which to begin matching.
+    *    @param   status     A reference to a UErrorCode to receive any errors.
+    *    @return  TRUE if there is a match.
+    *    @stable ICU 2.8
+    */
+    virtual UBool lookingAt(int32_t startIndex, UErrorCode &status);
+
+   /**
+    *  Find the next pattern match in the input string.
+    *  The find begins searching the input at the location following the end of
+    *  the previous match, or at the start of the string if there is no previous match.
+    *  If a match is found, <code>start(), end()</code> and <code>group()</code>
+    *  will provide more information regarding the match.
+    *  <p>Note that if the input string is changed by the application,
+    *     use find(startPos, status) instead of find(), because the saved starting
+    *     position may not be valid with the altered input string.</p>
+    *  @return  TRUE if a match is found.
+    *  @stable ICU 2.4
+    */
+    virtual UBool find();
+
+
+   /**
+    *   Resets this RegexMatcher and then attempts to find the next substring of the
+    *   input string that matches the pattern, starting at the specified index.
+    *
+    *   @param   start     the position in the input string to begin the search
+    *   @param   status    A reference to a UErrorCode to receive any errors.
+    *   @return  TRUE if a match is found.
+    *   @stable ICU 2.4
+    */
+    virtual UBool find(int32_t start, UErrorCode &status);
+
+
+   /**
+    *   Returns a string containing the text matched by the previous match.
+    *   If the pattern can match an empty string, an empty string may be returned.
+    *   @param   status      A reference to a UErrorCode to receive any errors.
+    *                        Possible errors are  U_REGEX_INVALID_STATE if no match
+    *                        has been attempted or the last match failed.
+    *   @return  a string containing the matched input text.
+    *   @stable ICU 2.4
+    */
+    virtual UnicodeString group(UErrorCode &status) const;
+
+
+   /**
+    *    Returns a string containing the text captured by the given group
+    *    during the previous match operation.  Group(0) is the entire match.
+    *
+    *    @param groupNum the capture group number
+    *    @param   status     A reference to a UErrorCode to receive any errors.
+    *                        Possible errors are  U_REGEX_INVALID_STATE if no match
+    *                        has been attempted or the last match failed and
+    *                        U_INDEX_OUTOFBOUNDS_ERROR for a bad capture group number.
+    *    @return the captured text
+    *    @stable ICU 2.4
+    */
+    virtual UnicodeString group(int32_t groupNum, UErrorCode &status) const;
+
+
+   /**
+    *   Returns the number of capturing groups in this matcher's pattern.
+    *   @return the number of capture groups
+    *   @stable ICU 2.4
+    */
+    virtual int32_t groupCount() const;
+
+
+   /**
+    *   Returns the index in the input string of the start of the text matched
+    *   during the previous match operation.
+    *    @param   status      a reference to a UErrorCode to receive any errors.
+    *    @return              The position in the input string of the start of the last match.
+    *    @stable ICU 2.4
+    */
+    virtual int32_t start(UErrorCode &status) const;
+
+
+   /**
+    *   Returns the index in the input string of the start of the text matched by the
+    *    specified capture group during the previous match operation.  Return -1 if
+    *    the capture group exists in the pattern, but was not part of the last match.
+    *
+    *    @param  group       the capture group number
+    *    @param  status      A reference to a UErrorCode to receive any errors.  Possible
+    *                        errors are  U_REGEX_INVALID_STATE if no match has been
+    *                        attempted or the last match failed, and
+    *                        U_INDEX_OUTOFBOUNDS_ERROR for a bad capture group number
+    *    @return the start position of substring matched by the specified group.
+    *    @stable ICU 2.4
+    */
+    virtual int32_t start(int32_t group, UErrorCode &status) const;
+
+
+   /**
+    *    Returns the index in the input string of the first character following the
+    *    text matched during the previous match operation.
+    *   @param   status      A reference to a UErrorCode to receive any errors.  Possible
+    *                        errors are  U_REGEX_INVALID_STATE if no match has been
+    *                        attempted or the last match failed.
+    *    @return the index of the last character matched, plus one.
+    *   @stable ICU 2.4
+    */
+    virtual int32_t end(UErrorCode &status) const;
+
+
+   /**
+    *    Returns the index in the input string of the character following the
+    *    text matched by the specified capture group during the previous match operation.
+    *    @param group  the capture group number
+    *    @param   status      A reference to a UErrorCode to receive any errors.  Possible
+    *                        errors are  U_REGEX_INVALID_STATE if no match has been
+    *                        attempted or the last match failed and
+    *                        U_INDEX_OUTOFBOUNDS_ERROR for a bad capture group number
+    *    @return  the index of the first character following the text
+    *              captured by the specifed group during the previous match operation.
+    *              Return -1 if the capture group exists in the pattern but was not part of the match.
+    *    @stable ICU 2.4
+    */
+    virtual int32_t end(int32_t group, UErrorCode &status) const;
+
+
+   /**
+    *   Resets this matcher.  The effect is to remove any memory of previous matches,
+    *       and to cause subsequent find() operations to begin at the beginning of
+    *       the input string.
+    *
+    *   @return this RegexMatcher.
+    *   @stable ICU 2.4
+    */
+    virtual RegexMatcher &reset();
+
+
+   /**
+    *   Resets this matcher, and set the current input position.
+    *   The effect is to remove any memory of previous matches,
+    *       and to cause subsequent find() operations to begin at
+    *       the specified position in the input string.
+    * <p>
+    *   The matcher's region is reset to its default, which is the entire
+    *   input string.
+    * <p>
+    *   An alternative to this function is to set a match region
+    *   beginning at the desired index.
+    *
+    *   @return this RegexMatcher.
+    *   @stable ICU 2.8
+    */
+    virtual RegexMatcher &reset(int32_t index, UErrorCode &status);
+
+
+   /**
+    *   Resets this matcher with a new input string.  This allows instances of RegexMatcher
+    *     to be reused, which is more efficient than creating a new RegexMatcher for
+    *     each input string to be processed.
+    *   @param input The new string on which subsequent pattern matches will operate.
+    *                The matcher retains a reference to the callers string, and operates
+    *                directly on that.  Ownership of the string remains with the caller.
+    *                Because no copy of the string is made, it is essential that the
+    *                caller not delete the string until after regexp operations on it
+    *                are done.
+    *   @return this RegexMatcher.
+    *   @stable ICU 2.4
+    */
+    virtual RegexMatcher &reset(const UnicodeString &input);
+
+private:
+    /**
+     * Cause a compilation error if an application accidently attempts to
+     *   reset a matcher with a (UChar *) string as input rather than
+     *   a UnicodeString.    Avoids a dangling reference to a temporary string.
+     * <p>
+     * To efficiently work with UChar *strings, wrap the data in a UnicodeString
+     * using one of the aliasing constructors, such as
+     * <code>UnicodeString(UBool isTerminated, const UChar *text, int32_t textLength);</code>
+     *
+     * @internal
+     */
+    RegexMatcher &reset(const UChar *input);
+public:
+
+   /**
+    *   Returns the input string being matched.  The returned string is not a copy,
+    *   but the live input string.  It should not be altered or deleted.
+    *   @return the input string
+    *   @stable ICU 2.4
+    */
+    virtual const UnicodeString &input() const;
+    
+    
+
+   /** Sets the limits of this matcher's region.
+     * The region is the part of the input string that will be searched to find a match.
+     * Invoking this method resets the matcher, and then sets the region to start
+     * at the index specified by the start parameter and end at the index specified
+     * by the end parameter.
+     *
+     * Depending on the transparency and anchoring being used (see useTransparentBounds
+     * and useAnchoringBounds), certain constructs such as anchors may behave differently
+     * at or around the boundaries of the region
+     *
+     * The function will fail if start is greater than limit, or if either index
+     *  is less than zero or greater than the length of the string being matched.
+     *
+     * @param start  The index to begin searches at.
+     * @param limit  The index to end searches at (exclusive).
+     * @param status A reference to a UErrorCode to receive any errors.
+     * @draft ICU 4.0
+     */
+     virtual RegexMatcher &region(int32_t start, int32_t limit, UErrorCode &status);
+
+
+   /**
+     * Reports the start index of this matcher's region. The searches this matcher
+     * conducts are limited to finding matches within regionStart (inclusive) and
+     * regionEnd (exclusive).
+     *
+     * @return The starting index of this matcher's region.
+     * @draft ICU 4.0
+     */
+     virtual int32_t regionStart() const;
+
+
+    /**
+      * Reports the end (limit) index (exclusive) of this matcher's region. The searches
+      * this matcher conducts are limited to finding matches within regionStart
+      * (inclusive) and regionEnd (exclusive).
+      *
+      * @return The ending point of this matcher's region.
+      * @draft ICU 4.0
+      */
+      virtual int32_t regionEnd() const;
+
+    /**
+      * Queries the transparency of region bounds for this matcher.
+      * See useTransparentBounds for a description of transparent and opaque bounds.
+      * By default, a matcher uses opaque region boundaries.
+      *
+      * @return TRUE if this matcher is using opaque bounds, false if it is not.
+      * @draft ICU 4.0
+      */
+      virtual UBool hasTransparentBounds() const;
+
+    /**
+      * Sets the transparency of region bounds for this matcher.
+      * Invoking this function with an argument of true will set this matcher to use transparent bounds.
+      * If the boolean argument is false, then opaque bounds will be used.
+      *
+      * Using transparent bounds, the boundaries of this matcher's region are transparent
+      * to lookahead, lookbehind, and boundary matching constructs. Those constructs can
+      * see text beyond the boundaries of the region while checking for a match.
+      *
+      * With opaque bounds, no text outside of the matcher's region is visible to lookahead,
+      * lookbehind, and boundary matching constructs.
+      *
+      * By default, a matcher uses opaque bounds.
+      *
+      * @param   b TRUE for transparent bounds; FALSE for opaque bounds
+      * @return  This Matcher;
+      * @draft   ICU 4.0
+      **/
+      virtual RegexMatcher &useTransparentBounds(UBool b);
+
+     
+    /**
+      * Return true if this matcher is using anchoring bounds.
+      * By default, matchers use anchoring region boounds.
+      *
+      * @return TRUE if this matcher is using anchoring bounds.
+      * @draft  ICU 4.0
+      */    
+      virtual UBool hasAnchoringBounds() const;
+
+    /**
+      * Set whether this matcher is using Anchoring Bounds for its region.
+      * With anchoring bounds, pattern anchors such as ^ and $ will match at the start
+      * and end of the region.  Without Anchoring Bounds, anchors will only match at
+      * the positions they would in the complete text.
+      *
+      * Anchoring Bounds are the default for regions.
+      *
+      * @param b TRUE if to enable anchoring bounds; FALSE to disable them.
+      * @return  This Matcher
+      * @draft   ICU 4.0
+      */
+      virtual RegexMatcher &useAnchoringBounds(UBool b);
+
+    /**
+      * Return TRUE if the most recent matching operation touched the
+      *  end of the text being processed.  In this case, additional input text could
+      *  change the results of that match.
+      *
+      *  hitEnd() is defined for both successful and unsuccessful matches.
+      *  In either case hitEnd() will return TRUE if if the end of the text was
+      *  reached at any point during the matching process.
+      *
+      *  @return  TRUE if the most recent match hit the end of input
+      *  @draft   ICU 4.0
+      */
+      virtual UBool hitEnd() const;
+
+    /**
+      * Return TRUE the most recent match succeeded and additional input could cause
+      * it to fail. If this method returns false and a match was found, then more input
+      * might change the match but the match won't be lost. If a match was not found,
+      * then requireEnd has no meaning.
+      *
+      * @return TRUE if more input could cause the most recent match to no longer match.
+      * @draft  ICU 4.0
+      */
+      virtual UBool requireEnd() const;
+
+
+
+
+
+   /**
+    *    Returns the pattern that is interpreted by this matcher.
+    *    @return  the RegexPattern for this RegexMatcher
+    *    @stable ICU 2.4
+    */
+    virtual const RegexPattern &pattern() const;
+
+
+   /**
+    *    Replaces every substring of the input that matches the pattern
+    *    with the given replacement string.  This is a convenience function that
+    *    provides a complete find-and-replace-all operation.
+    *
+    *    This method first resets this matcher. It then scans the input string
+    *    looking for matches of the pattern. Input that is not part of any
+    *    match is left unchanged; each match is replaced in the result by the
+    *    replacement string. The replacement string may contain references to
+    *    capture groups.
+    *
+    *    @param   replacement a string containing the replacement text.
+    *    @param   status      a reference to a UErrorCode to receive any errors.
+    *    @return              a string containing the results of the find and replace.
+    *    @stable ICU 2.4
+    */
+    virtual UnicodeString replaceAll(const UnicodeString &replacement, UErrorCode &status);
+
+
+   /**
+    * Replaces the first substring of the input that matches
+    * the pattern with the replacement string.   This is a convenience
+    * function that provides a complete find-and-replace operation.
+    *
+    * <p>This function first resets this RegexMatcher. It then scans the input string
+    * looking for a match of the pattern. Input that is not part
+    * of the match is appended directly to the result string; the match is replaced
+    * in the result by the replacement string. The replacement string may contain
+    * references to captured groups.</p>
+    *
+    * <p>The state of the matcher (the position at which a subsequent find()
+    *    would begin) after completing a replaceFirst() is not specified.  The
+    *    RegexMatcher should be reset before doing additional find() operations.</p>
+    *
+    *    @param   replacement a string containing the replacement text.
+    *    @param   status      a reference to a UErrorCode to receive any errors.
+    *    @return              a string containing the results of the find and replace.
+    *    @stable ICU 2.4
+    */
+    virtual UnicodeString replaceFirst(const UnicodeString &replacement, UErrorCode &status);
+
+   /**
+    *   Implements a replace operation intended to be used as part of an
+    *   incremental find-and-replace.
+    *
+    *   <p>The input string, starting from the end of the previous replacement and ending at
+    *   the start of the current match, is appended to the destination string.  Then the
+    *   replacement string is appended to the output string,
+    *   including handling any substitutions of captured text.</p>
+    *
+    *   <p>For simple, prepackaged, non-incremental find-and-replace
+    *   operations, see replaceFirst() or replaceAll().</p>
+    *
+    *   @param   dest        A UnicodeString to which the results of the find-and-replace are appended.
+    *   @param   replacement A UnicodeString that provides the text to be substituted for
+    *                        the input text that matched the regexp pattern.  The replacement
+    *                        text may contain references to captured text from the
+    *                        input.
+    *   @param   status      A reference to a UErrorCode to receive any errors.  Possible
+    *                        errors are  U_REGEX_INVALID_STATE if no match has been
+    *                        attempted or the last match failed, and U_INDEX_OUTOFBOUNDS_ERROR
+    *                        if the replacement text specifies a capture group that
+    *                        does not exist in the pattern.
+    *
+    *   @return  this  RegexMatcher
+    *   @stable ICU 2.4
+    *
+    */
+    virtual RegexMatcher &appendReplacement(UnicodeString &dest,
+        const UnicodeString &replacement, UErrorCode &status);
+
+
+   /**
+    * As the final step in a find-and-replace operation, append the remainder
+    * of the input string, starting at the position following the last appendReplacement(),
+    * to the destination string. <code>appendTail()</code> is intended to be invoked after one
+    * or more invocations of the <code>RegexMatcher::appendReplacement()</code>.
+    *
+    *  @param dest A UnicodeString to which the results of the find-and-replace are appended.
+    *  @return  the destination string.
+    *  @stable ICU 2.4
+    */
+    virtual UnicodeString &appendTail(UnicodeString &dest);
+
+
+
+    /**
+     * Split a string into fields.  Somewhat like split() from Perl.
+     * The pattern matches identify delimiters that separate the input
+     *  into fields.  The input data between the matches becomes the
+     *  fields themselves.
+     * <p>
+     *
+     * @param input   The string to be split into fields.  The field delimiters
+     *                match the pattern (in the "this" object).  This matcher
+     *                will be reset to this input string.
+     * @param dest    An array of UnicodeStrings to receive the results of the split.
+     *                This is an array of actual UnicodeString objects, not an
+     *                array of pointers to strings.  Local (stack based) arrays can
+     *                work well here.
+     * @param destCapacity  The number of elements in the destination array.
+     *                If the number of fields found is less than destCapacity, the
+     *                extra strings in the destination array are not altered.
+     *                If the number of destination strings is less than the number
+     *                of fields, the trailing part of the input string, including any
+     *                field delimiters, is placed in the last destination string.
+     * @param status  A reference to a UErrorCode to receive any errors.
+     * @return        The number of fields into which the input string was split.
+     * @stable ICU 2.6
+     */
+    virtual int32_t  split(const UnicodeString &input,
+        UnicodeString    dest[],
+        int32_t          destCapacity,
+        UErrorCode       &status);
+
+  /**
+    *   Set a processing time limit for match operations with this Matcher.
+    *  
+    *   Some patterns, when matching certain strings, can run in exponential time.
+    *   For practical purposes, the match operation may appear to be in an
+    *   infinite loop.
+    *   When a limit is set a match operation will fail with an error if the
+    *   limit is exceeded.
+    *   <p>
+    *   The units of the limit are steps of the match engine.
+    *   Correspondence with actual processor time will depend on the speed
+    *   of the processor and the details of the specific pattern, but will
+    *   typically be on the order of milliseconds.
+    *   <p>
+    *   By default, the matching time is not limited.
+    *   <p>
+    *
+    *   @param   limit       The limit value, or 0 for no limit.
+    *   @param   status      A reference to a UErrorCode to receive any errors.
+    *   @draft ICU 4.0
+    */
+    virtual void setTimeLimit(int32_t limit, UErrorCode &status);
+
+  /**
+    * Get the time limit, if any, for match operations made with this Matcher.
+    *
+    *   @return the maximum allowed time for a match, in units of processing steps.
+    *   @draft ICU 4.0
+    */
+    virtual int32_t getTimeLimit() const;
+
+  /**
+    *  Set the amount of heap storage avaliable for use by the match backtracking stack.
+    *  The matcher is also reset, discarding any results from previous matches.
+    *  <p>
+    *  ICU uses a backtracking regular expression engine, with the backtrack stack
+    *  maintained on the heap.  This function sets the limit to the amount of memory
+    *  that can be used  for this purpose.  A backtracking stack overflow will
+    *  result in an error from the match operation that caused it.
+    *  <p>
+    *  A limit is desirable because a malicious or poorly designed pattern can use
+    *  excessive memory, potentially crashing the process.  A limit is enabled
+    *  by default.
+    *  <p>
+    *  @param limit  The maximum size, in bytes, of the matching backtrack stack.
+    *                A value of zero means no limit.
+    *                The limit must be greater or equal to zero.
+    *
+    *  @param status   A reference to a UErrorCode to receive any errors.
+    *
+    *  @draft ICU 4.0
+    */
+    virtual void setStackLimit(int32_t  limit, UErrorCode &status);
+    
+  /**
+    *  Get the size of the heap storage available for use by the back tracking stack.
+    *
+    *  @return  the maximum backtracking stack size, in bytes, or zero if the
+    *           stack size is unlimited.
+    *  @draft ICU 4.0
+    */
+    virtual int32_t  getStackLimit() const;
+
+
+  /**
+    * Set a callback function for use with this Matcher.
+    * During matching operations the function will be called periodically,
+    * giving the application the opportunity to terminate a long-running
+    * match.
+    *
+    *    @param   callback    A pointer to the user-supplied callback function.
+    *    @param   context     User context pointer.  The value supplied at the
+    *                         time the callback function is set will be saved
+    *                         and passed to the callback each time that it is called.
+    *    @param   status      A reference to a UErrorCode to receive any errors.
+    *  @draft ICU 4.0
+    */
+    virtual void setMatchCallback(URegexMatchCallback     *callback,
+                                  const void              *context,
+                                  UErrorCode              &status);
+
+
+
+  /**
+    *  Get the callback function for this URegularExpression.
+    *
+    *    @param   callback    Out paramater, receives a pointer to the user-supplied 
+    *                         callback function.
+    *    @param   context     Out parameter, receives the user context pointer that
+    *                         was set when uregex_setMatchCallback() was called.
+    *    @param   status      A reference to a UErrorCode to receive any errors.
+    *    @draft ICU 4.0
+    */
+    virtual void getMatchCallback(URegexMatchCallback     *&callback,
+                                  const void              *&context,
+                                  UErrorCode              &status);
+
+
+   /**
+     *   setTrace   Debug function, enable/disable tracing of the matching engine.
+     *              For internal ICU development use only.  DO NO USE!!!!
+     *   @internal
+     */
+    void setTrace(UBool state);
+
+
+    /**
+    * ICU "poor man's RTTI", returns a UClassID for this class.
+    *
+    * @stable ICU 2.2
+    */
+    static UClassID U_EXPORT2 getStaticClassID();
+
+    /**
+     * ICU "poor man's RTTI", returns a UClassID for the actual class.
+     *
+     * @stable ICU 2.2
+     */
+    virtual UClassID getDynamicClassID() const;
+
+private:
+    // Constructors and other object boilerplate are private.
+    // Instances of RegexMatcher can not be assigned, copied, cloned, etc.
+    RegexMatcher();                  // default constructor not implemented
+    RegexMatcher(const RegexPattern *pat);
+    RegexMatcher(const RegexMatcher &other);
+    RegexMatcher &operator =(const RegexMatcher &rhs);
+    void init(UErrorCode &status);                      // Common initialization
+    void init2(const UnicodeString &s, UErrorCode &e);  // Common initialization, part 2.
+
+    friend class RegexPattern;
+    friend class RegexCImpl;
+public:
+    /** @internal  */
+    void resetPreserveRegion();  // Reset matcher state, but preserve any region.
+private:
+
+    //
+    //  MatchAt   This is the internal interface to the match engine itself.
+    //            Match status comes back in matcher member variables.
+    //
+    void                 MatchAt(int32_t startIdx, UBool toEnd, UErrorCode &status);
+    inline void          backTrack(int32_t &inputIdx, int32_t &patIdx);
+    UBool                isWordBoundary(int32_t pos);         // perform Perl-like  \b test
+    UBool                isUWordBoundary(int32_t pos);        // perform RBBI based \b test
+    REStackFrame        *resetStack();
+    inline REStackFrame *StateSave(REStackFrame *fp, int32_t savePatIdx, UErrorCode &status);
+    void                 IncrementTime(UErrorCode &status);
+
+
+    const RegexPattern  *fPattern;
+    RegexPattern        *fPatternOwned;    // Non-NULL if this matcher owns the pattern, and
+                                           //   should delete it when through.
+
+    const UnicodeString *fInput;           // The text being matched. Is never NULL.
+    int32_t              fFrameSize;       // The size of a frame in the backtrack stack.
+    
+    int32_t              fRegionStart;     // Start of the input region, default = 0.
+    int32_t              fRegionLimit;     // End of input region, default to input.length.
+    
+    int32_t              fAnchorStart;     // Region bounds for anchoring operations (^ or $).
+    int32_t              fAnchorLimit;     //   See useAnchoringBounds
+    
+    int32_t              fLookStart;       // Region bounds for look-ahead/behind and
+    int32_t              fLookLimit;       //   and other boundary tests.  See
+                                           //   useTransparentBounds
+
+    int32_t              fActiveStart;     // Currently active bounds for matching.
+    int32_t              fActiveLimit;     //   Usually is the same as region, but
+                                           //   is changed to fLookStart/Limit when
+                                           //   entering look around regions.
+
+    UBool                fTransparentBounds;  // True if using transparent bounds.
+    UBool                fAnchoringBounds; // True if using anchoring bounds.
+
+    UBool                fMatch;           // True if the last attempted match was successful.
+    int32_t              fMatchStart;      // Position of the start of the most recent match
+    int32_t              fMatchEnd;        // First position after the end of the most recent match
+                                           //   Zero if no previous match, even when a region
+                                           //   is active.
+    int32_t              fLastMatchEnd;    // First position after the end of the previous match,
+                                           //   or -1 if there was no previous match.
+    int32_t              fAppendPosition;  // First position after the end of the previous
+                                           //   appendReplacement().  As described by the
+                                           //   JavaDoc for Java Matcher, where it is called 
+                                           //   "append position"
+    UBool                fHitEnd;          // True if the last match touched the end of input.
+    UBool                fRequireEnd;      // True if the last match required end-of-input
+                                           //    (matched $ or Z)
+
+    UVector32           *fStack;
+    REStackFrame        *fFrame;           // After finding a match, the last active stack frame,
+                                           //   which will contain the capture group results.
+                                           //   NOT valid while match engine is running.
+
+    int32_t             *fData;            // Data area for use by the compiled pattern.
+    int32_t             fSmallData[8];     //   Use this for data if it's enough.
+
+    int32_t             fTimeLimit;        // Max time (in arbitrary steps) to let the
+                                           //   match engine run.  Zero for unlimited.
+    
+    int32_t             fTime;             // Match time, accumulates while matching.
+    int32_t             fTickCounter;      // Low bits counter for time.  Counts down StateSaves.
+                                           //   Kept separately from fTime to keep as much
+                                           //   code as possible out of the inline
+                                           //   StateSave function.
+
+    int32_t             fStackLimit;       // Maximum memory size to use for the backtrack
+                                           //   stack, in bytes.  Zero for unlimited.
+
+    URegexMatchCallback *fCallbackFn;       // Pointer to match progress callback funct.
+                                           //   NULL if there is no callback.
+    const void         *fCallbackContext;  // User Context ptr for callback function.
+
+    UBool               fTraceDebug;       // Set true for debug tracing of match engine.
+
+    UErrorCode          fDeferredStatus;   // Save error state that cannot be immediately
+                                           //   reported, or that permanently disables this matcher.
+
+    RuleBasedBreakIterator  *fWordBreakItr;
+
+
+};
+
+U_NAMESPACE_END
+#endif  // UCONFIG_NO_REGULAR_EXPRESSIONS
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/rep.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/rep.h b/src/apps/couch_collate/platform/osx/icu/unicode/rep.h
new file mode 100644
index 0000000..3fab6fa
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/rep.h
@@ -0,0 +1,259 @@
+/*
+**************************************************************************
+* Copyright (C) 1999-2005, International Business Machines Corporation and
+* others. All Rights Reserved.
+**************************************************************************
+*   Date        Name        Description
+*   11/17/99    aliu        Creation.  Ported from java.  Modified to
+*                           match current UnicodeString API.  Forced
+*                           to use name "handleReplaceBetween" because
+*                           of existing methods in UnicodeString.
+**************************************************************************
+*/
+
+#ifndef REP_H
+#define REP_H
+
+#include "unicode/uobject.h"
+
+/**
+ * \file 
+ * \brief C++ API: Replaceable String
+ */
+ 
+U_NAMESPACE_BEGIN
+
+class UnicodeString;
+
+/**
+ * <code>Replaceable</code> is an abstract base class representing a
+ * string of characters that supports the replacement of a range of
+ * itself with a new string of characters.  It is used by APIs that
+ * change a piece of text while retaining metadata.  Metadata is data
+ * other than the Unicode characters returned by char32At().  One
+ * example of metadata is style attributes; another is an edit
+ * history, marking each character with an author and revision number.
+ *
+ * <p>An implicit aspect of the <code>Replaceable</code> API is that
+ * during a replace operation, new characters take on the metadata of
+ * the old characters.  For example, if the string "the <b>bold</b>
+ * font" has range (4, 8) replaced with "strong", then it becomes "the
+ * <b>strong</b> font".
+ *
+ * <p><code>Replaceable</code> specifies ranges using a start
+ * offset and a limit offset.  The range of characters thus specified
+ * includes the characters at offset start..limit-1.  That is, the
+ * start offset is inclusive, and the limit offset is exclusive.
+ *
+ * <p><code>Replaceable</code> also includes API to access characters
+ * in the string: <code>length()</code>, <code>charAt()</code>,
+ * <code>char32At()</code>, and <code>extractBetween()</code>.
+ *
+ * <p>For a subclass to support metadata, typical behavior of
+ * <code>replace()</code> is the following:
+ * <ul>
+ *   <li>Set the metadata of the new text to the metadata of the first
+ *   character replaced</li>
+ *   <li>If no characters are replaced, use the metadata of the
+ *   previous character</li>
+ *   <li>If there is no previous character (i.e. start == 0), use the
+ *   following character</li>
+ *   <li>If there is no following character (i.e. the replaceable was
+ *   empty), use default metadata.<br>
+ *   <li>If the code point U+FFFF is seen, it should be interpreted as
+ *   a special marker having no metadata<li>
+ *   </li>
+ * </ul>
+ * If this is not the behavior, the subclass should document any differences.
+ * @author Alan Liu
+ * @stable ICU 2.0
+ */
+class U_COMMON_API Replaceable : public UObject {
+
+public:
+    /**
+     * Destructor.
+     * @stable ICU 2.0
+     */
+    virtual ~Replaceable();
+
+    /**
+     * Returns the number of 16-bit code units in the text.
+     * @return number of 16-bit code units in text
+     * @stable ICU 1.8
+     */ 
+    inline int32_t length() const;
+
+    /**
+     * Returns the 16-bit code unit at the given offset into the text.
+     * @param offset an integer between 0 and <code>length()</code>-1
+     * inclusive
+     * @return 16-bit code unit of text at given offset
+     * @stable ICU 1.8
+     */
+    inline UChar charAt(int32_t offset) const;
+
+    /**
+     * Returns the 32-bit code point at the given 16-bit offset into
+     * the text.  This assumes the text is stored as 16-bit code units
+     * with surrogate pairs intermixed.  If the offset of a leading or
+     * trailing code unit of a surrogate pair is given, return the
+     * code point of the surrogate pair.
+     *
+     * @param offset an integer between 0 and <code>length()</code>-1
+     * inclusive
+     * @return 32-bit code point of text at given offset
+     * @stable ICU 1.8
+     */
+    inline UChar32 char32At(int32_t offset) const;
+
+    /**
+     * Copies characters in the range [<tt>start</tt>, <tt>limit</tt>) 
+     * into the UnicodeString <tt>target</tt>.
+     * @param start offset of first character which will be copied
+     * @param limit offset immediately following the last character to
+     * be copied
+     * @param target UnicodeString into which to copy characters.
+     * @return A reference to <TT>target</TT>
+     * @stable ICU 2.1
+     */
+    virtual void extractBetween(int32_t start,
+                                int32_t limit,
+                                UnicodeString& target) const = 0;
+
+    /**
+     * Replaces a substring of this object with the given text.  If the
+     * characters being replaced have metadata, the new characters
+     * that replace them should be given the same metadata.
+     *
+     * <p>Subclasses must ensure that if the text between start and
+     * limit is equal to the replacement text, that replace has no
+     * effect. That is, any metadata
+     * should be unaffected. In addition, subclasses are encouraged to
+     * check for initial and trailing identical characters, and make a
+     * smaller replacement if possible. This will preserve as much
+     * metadata as possible.
+     * @param start the beginning index, inclusive; <code>0 <= start
+     * <= limit</code>.
+     * @param limit the ending index, exclusive; <code>start <= limit
+     * <= length()</code>.
+     * @param text the text to replace characters <code>start</code>
+     * to <code>limit - 1</code> 
+     * @stable ICU 2.0
+     */
+    virtual void handleReplaceBetween(int32_t start,
+                                      int32_t limit,
+                                      const UnicodeString& text) = 0;
+    // Note: All other methods in this class take the names of
+    // existing UnicodeString methods.  This method is the exception.
+    // It is named differently because all replace methods of
+    // UnicodeString return a UnicodeString&.  The 'between' is
+    // required in order to conform to the UnicodeString naming
+    // convention; API taking start/length are named <operation>, and
+    // those taking start/limit are named <operationBetween>.  The
+    // 'handle' is added because 'replaceBetween' and
+    // 'doReplaceBetween' are already taken.
+
+    /**
+     * Copies a substring of this object, retaining metadata.
+     * This method is used to duplicate or reorder substrings.
+     * The destination index must not overlap the source range.
+     * 
+     * @param start the beginning index, inclusive; <code>0 <= start <=
+     * limit</code>.
+     * @param limit the ending index, exclusive; <code>start <= limit <=
+     * length()</code>.
+     * @param dest the destination index.  The characters from
+     * <code>start..limit-1</code> will be copied to <code>dest</code>.
+     * Implementations of this method may assume that <code>dest <= start ||
+     * dest >= limit</code>.
+     * @stable ICU 2.0
+     */
+    virtual void copy(int32_t start, int32_t limit, int32_t dest) = 0;
+
+    /**
+     * Returns true if this object contains metadata.  If a
+     * Replaceable object has metadata, calls to the Replaceable API
+     * must be made so as to preserve metadata.  If it does not, calls
+     * to the Replaceable API may be optimized to improve performance.
+     * The default implementation returns true.
+     * @return true if this object contains metadata
+     * @stable ICU 2.2
+     */
+    virtual UBool hasMetaData() const;
+
+    /**
+     * Clone this object, an instance of a subclass of Replaceable.
+     * Clones can be used concurrently in multiple threads.
+     * If a subclass does not implement clone(), or if an error occurs,
+     * then NULL is returned.
+     * The clone functions in all subclasses return a pointer to a Replaceable
+     * because some compilers do not support covariant (same-as-this)
+     * return types; cast to the appropriate subclass if necessary.
+     * The caller must delete the clone.
+     *
+     * @return a clone of this object
+     *
+     * @see getDynamicClassID
+     * @stable ICU 2.6
+     */
+    virtual Replaceable *clone() const;
+
+protected:
+
+    /**
+     * Default constructor.
+     * @stable ICU 2.4
+     */
+    Replaceable();
+
+    /*
+     * Assignment operator not declared. The compiler will provide one
+     * which does nothing since this class does not contain any data members.
+     * API/code coverage may show the assignment operator as present and
+     * untested - ignore.
+     * Subclasses need this assignment operator if they use compiler-provided
+     * assignment operators of their own. An alternative to not declaring one
+     * here would be to declare and empty-implement a protected or public one.
+    Replaceable &Replaceable::operator=(const Replaceable &);
+     */
+
+    /**
+     * Virtual version of length().
+     * @stable ICU 2.4
+     */ 
+    virtual int32_t getLength() const = 0;
+
+    /**
+     * Virtual version of charAt().
+     * @stable ICU 2.4
+     */
+    virtual UChar getCharAt(int32_t offset) const = 0;
+
+    /**
+     * Virtual version of char32At().
+     * @stable ICU 2.4
+     */
+    virtual UChar32 getChar32At(int32_t offset) const = 0;
+};
+
+inline int32_t
+Replaceable::length() const {
+    return getLength();
+}
+
+inline UChar
+Replaceable::charAt(int32_t offset) const {
+    return getCharAt(offset);
+}
+
+inline UChar32
+Replaceable::char32At(int32_t offset) const {
+    return getChar32At(offset);
+}
+
+// There is no rep.cpp, see unistr.cpp for Replaceable function implementations.
+
+U_NAMESPACE_END
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/resbund.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/resbund.h b/src/apps/couch_collate/platform/osx/icu/unicode/resbund.h
new file mode 100644
index 0000000..6d6b991
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/resbund.h
@@ -0,0 +1,485 @@
+/*
+******************************************************************************
+*
+*   Copyright (C) 1996-2007, International Business Machines Corporation
+*   and others.  All Rights Reserved.
+*
+******************************************************************************
+*
+* File resbund.h
+*
+*   CREATED BY
+*       Richard Gillam
+*
+* Modification History:
+*
+*   Date        Name        Description
+*   2/5/97      aliu        Added scanForLocaleInFile.  Added
+*                           constructor which attempts to read resource bundle
+*                           from a specific file, without searching other files.
+*   2/11/97     aliu        Added UErrorCode return values to constructors.  Fixed
+*                           infinite loops in scanForFile and scanForLocale.
+*                           Modified getRawResourceData to not delete storage
+*                           in localeData and resourceData which it doesn't own.
+*                           Added Mac compatibility #ifdefs for tellp() and
+*                           ios::nocreate.
+*   2/18/97     helena      Updated with 100% documentation coverage.
+*   3/13/97     aliu        Rewrote to load in entire resource bundle and store
+*                           it as a Hashtable of ResourceBundleData objects.
+*                           Added state table to govern parsing of files.
+*                           Modified to load locale index out of new file
+*                           distinct from default.txt.
+*   3/25/97     aliu        Modified to support 2-d arrays, needed for timezone
+*                           data. Added support for custom file suffixes.  Again,
+*                           needed to support timezone data.
+*   4/7/97      aliu        Cleaned up.
+* 03/02/99      stephen     Removed dependency on FILE*.
+* 03/29/99      helena      Merged Bertrand and Stephen's changes.
+* 06/11/99      stephen     Removed parsing of .txt files.
+*                           Reworked to use new binary format.
+*                           Cleaned up.
+* 06/14/99      stephen     Removed methods taking a filename suffix.
+* 11/09/99      weiv        Added getLocale(), fRealLocale, removed fRealLocaleID
+******************************************************************************
+*/
+
+#ifndef RESBUND_H
+#define RESBUND_H
+
+#include "unicode/utypes.h"
+#include "unicode/uobject.h"
+#include "unicode/ures.h"
+#include "unicode/unistr.h"
+#include "unicode/locid.h"
+
+/**
+ * \file 
+ * \brief C++ API: Resource Bundle
+ */
+ 
+U_NAMESPACE_BEGIN
+
+/**
+ * A class representing a collection of resource information pertaining to a given
+ * locale. A resource bundle provides a way of accessing locale- specfic information in
+ * a data file. You create a resource bundle that manages the resources for a given
+ * locale and then ask it for individual resources.
+ * <P>
+ * Resource bundles in ICU4C are currently defined using text files which conform to the following
+ * <a href="http://source.icu-project.org/repos/icu/icuhtml/trunk/design/bnf_rb.txt">BNF definition</a>.
+ * More on resource bundle concepts and syntax can be found in the
+ * <a href="http://icu-project.org/userguide/ResourceManagement.html">Users Guide</a>.
+ * <P>
+ *
+ * The ResourceBundle class is not suitable for subclassing.
+ *
+ * @stable ICU 2.0
+ */
+class U_COMMON_API ResourceBundle : public UObject {
+public:
+    /**
+     * Constructor
+     *
+     * @param packageName   The packageName and locale together point to an ICU udata object, 
+     *                      as defined by <code> udata_open( packageName, "res", locale, err) </code> 
+     *                      or equivalent.  Typically, packageName will refer to a (.dat) file, or to
+     *                      a package registered with udata_setAppData(). Using a full file or directory
+     *                      pathname for packageName is deprecated.
+     * @param locale  This is the locale this resource bundle is for. To get resources
+     *                for the French locale, for example, you would create a
+     *                ResourceBundle passing Locale::FRENCH for the "locale" parameter,
+     *                and all subsequent calls to that resource bundle will return
+     *                resources that pertain to the French locale. If the caller doesn't
+     *                pass a locale parameter, the default locale for the system (as
+     *                returned by Locale::getDefault()) will be used.
+     * @param err     The Error Code.
+     * The UErrorCode& err parameter is used to return status information to the user. To
+     * check whether the construction succeeded or not, you should check the value of
+     * U_SUCCESS(err). If you wish more detailed information, you can check for
+     * informational error results which still indicate success. U_USING_FALLBACK_WARNING
+     * indicates that a fall back locale was used. For example, 'de_CH' was requested,
+     * but nothing was found there, so 'de' was used. U_USING_DEFAULT_WARNING indicates that
+     * the default locale data was used; neither the requested locale nor any of its
+     * fall back locales could be found.
+     * @stable ICU 2.0
+     */
+    ResourceBundle(const UnicodeString&    packageName,
+                   const Locale&           locale,
+                   UErrorCode&              err);
+
+    /**
+     * Construct a resource bundle for the default bundle in the specified package.
+     *
+     * @param packageName   The packageName and locale together point to an ICU udata object, 
+     *                      as defined by <code> udata_open( packageName, "res", locale, err) </code> 
+     *                      or equivalent.  Typically, packageName will refer to a (.dat) file, or to
+     *                      a package registered with udata_setAppData(). Using a full file or directory
+     *                      pathname for packageName is deprecated.
+     * @param err A UErrorCode value
+     * @stable ICU 2.0
+     */
+    ResourceBundle(const UnicodeString&    packageName,
+                   UErrorCode&              err);
+
+    /**
+     * Construct a resource bundle for the ICU default bundle.
+     *
+     * @param err A UErrorCode value
+     * @stable ICU 2.0
+     */
+    ResourceBundle(UErrorCode &err);
+
+    /**
+     * Standard constructor, onstructs a resource bundle for the locale-specific
+     * bundle in the specified package.
+     *
+     * @param packageName   The packageName and locale together point to an ICU udata object, 
+     *                      as defined by <code> udata_open( packageName, "res", locale, err) </code> 
+     *                      or equivalent.  Typically, packageName will refer to a (.dat) file, or to
+     *                      a package registered with udata_setAppData(). Using a full file or directory
+     *                      pathname for packageName is deprecated.
+     *                      NULL is used to refer to ICU data.
+     * @param locale The locale for which to open a resource bundle.
+     * @param err A UErrorCode value
+     * @stable ICU 2.0
+     */
+    ResourceBundle(const char* packageName,
+                   const Locale& locale,
+                   UErrorCode& err);
+
+    /**
+     * Copy constructor.
+     *
+     * @param original The resource bundle to copy.
+     * @stable ICU 2.0
+     */
+    ResourceBundle(const ResourceBundle &original);
+
+    /**
+     * Constructor from a C UResourceBundle. The resource bundle is
+     * copied and not adopted. ures_close will still need to be used on the
+     * original resource bundle.
+     *
+     * @param res A pointer to the C resource bundle.
+     * @param status A UErrorCode value.
+     * @stable ICU 2.0
+     */
+    ResourceBundle(UResourceBundle *res,
+                   UErrorCode &status);
+
+    /**
+     * Assignment operator.
+     *
+     * @param other The resource bundle to copy.
+     * @stable ICU 2.0
+     */
+    ResourceBundle&
+      operator=(const ResourceBundle& other);
+
+    /** Destructor.
+     * @stable ICU 2.0
+     */
+    virtual ~ResourceBundle();
+
+    /**
+     * Clone this object.
+     * Clones can be used concurrently in multiple threads.
+     * If an error occurs, then NULL is returned.
+     * The caller must delete the clone.
+     *
+     * @return a clone of this object
+     *
+     * @see getDynamicClassID
+     * @stable ICU 2.8
+     */
+    ResourceBundle *clone() const;
+
+    /**
+     * Returns the size of a resource. Size for scalar types is always 1, and for vector/table types is
+     * the number of child resources.
+     * @warning Integer array is treated as a scalar type. There are no
+     *          APIs to access individual members of an integer array. It
+     *          is always returned as a whole.
+     *
+     * @return number of resources in a given resource.
+     * @stable ICU 2.0
+     */
+    int32_t
+      getSize(void) const;
+
+    /**
+     * returns a string from a string resource type
+     *
+     * @param status  fills in the outgoing error code
+     *                could be <TT>U_MISSING_RESOURCE_ERROR</TT> if the key is not found
+     *                could be a warning
+     *                e.g.: <TT>U_USING_FALLBACK_WARNING</TT>,<TT>U_USING_DEFAULT_WARNING </TT>
+     * @return a pointer to a zero-terminated UChar array which lives in a memory mapped/DLL file.
+     * @stable ICU 2.0
+     */
+    UnicodeString
+      getString(UErrorCode& status) const;
+
+    /**
+     * returns a binary data from a resource. Can be used at most primitive resource types (binaries,
+     * strings, ints)
+     *
+     * @param len     fills in the length of resulting byte chunk
+     * @param status  fills in the outgoing error code
+     *                could be <TT>U_MISSING_RESOURCE_ERROR</TT> if the key is not found
+     *                could be a warning
+     *                e.g.: <TT>U_USING_FALLBACK_WARNING</TT>,<TT>U_USING_DEFAULT_WARNING </TT>
+     * @return a pointer to a chunk of unsigned bytes which live in a memory mapped/DLL file.
+     * @stable ICU 2.0
+     */
+    const uint8_t*
+      getBinary(int32_t& len, UErrorCode& status) const;
+
+
+    /**
+     * returns an integer vector from a resource.
+     *
+     * @param len     fills in the length of resulting integer vector
+     * @param status  fills in the outgoing error code
+     *                could be <TT>U_MISSING_RESOURCE_ERROR</TT> if the key is not found
+     *                could be a warning
+     *                e.g.: <TT>U_USING_FALLBACK_WARNING</TT>,<TT>U_USING_DEFAULT_WARNING </TT>
+     * @return a pointer to a vector of integers that lives in a memory mapped/DLL file.
+     * @stable ICU 2.0
+     */
+    const int32_t*
+      getIntVector(int32_t& len, UErrorCode& status) const;
+
+    /**
+     * returns an unsigned integer from a resource.
+     * This integer is originally 28 bits.
+     *
+     * @param status  fills in the outgoing error code
+     *                could be <TT>U_MISSING_RESOURCE_ERROR</TT> if the key is not found
+     *                could be a warning
+     *                e.g.: <TT>U_USING_FALLBACK_WARNING</TT>,<TT>U_USING_DEFAULT_WARNING </TT>
+     * @return an unsigned integer value
+     * @stable ICU 2.0
+     */
+    uint32_t
+      getUInt(UErrorCode& status) const;
+
+    /**
+     * returns a signed integer from a resource.
+     * This integer is originally 28 bit and the sign gets propagated.
+     *
+     * @param status  fills in the outgoing error code
+     *                could be <TT>U_MISSING_RESOURCE_ERROR</TT> if the key is not found
+     *                could be a warning
+     *                e.g.: <TT>U_USING_FALLBACK_WARNING</TT>,<TT>U_USING_DEFAULT_WARNING </TT>
+     * @return a signed integer value
+     * @stable ICU 2.0
+     */
+    int32_t
+      getInt(UErrorCode& status) const;
+
+    /**
+     * Checks whether the resource has another element to iterate over.
+     *
+     * @return TRUE if there are more elements, FALSE if there is no more elements
+     * @stable ICU 2.0
+     */
+    UBool
+      hasNext(void) const;
+
+    /**
+     * Resets the internal context of a resource so that iteration starts from the first element.
+     *
+     * @stable ICU 2.0
+     */
+    void
+      resetIterator(void);
+
+    /**
+     * Returns the key associated with this resource. Not all the resources have a key - only
+     * those that are members of a table.
+     *
+     * @return a key associated to this resource, or NULL if it doesn't have a key
+     * @stable ICU 2.0
+     */
+    const char*
+      getKey(void) const;
+
+    /**
+     * Gets the locale ID of the resource bundle as a string.
+     * Same as getLocale().getName() .
+     *
+     * @return the locale ID of the resource bundle as a string
+     * @stable ICU 2.0
+     */
+    const char*
+      getName(void) const;
+
+
+    /**
+     * Returns the type of a resource. Available types are defined in enum UResType
+     *
+     * @return type of the given resource.
+     * @stable ICU 2.0
+     */
+    UResType
+      getType(void) const;
+
+    /**
+     * Returns the next resource in a given resource or NULL if there are no more resources
+     *
+     * @param status            fills in the outgoing error code
+     * @return                  ResourceBundle object.
+     * @stable ICU 2.0
+     */
+    ResourceBundle
+      getNext(UErrorCode& status);
+
+    /**
+     * Returns the next string in a resource or NULL if there are no more resources
+     * to iterate over.
+     *
+     * @param status            fills in the outgoing error code
+     * @return an UnicodeString object.
+     * @stable ICU 2.0
+     */
+    UnicodeString
+      getNextString(UErrorCode& status);
+
+    /**
+     * Returns the next string in a resource or NULL if there are no more resources
+     * to iterate over.
+     *
+     * @param key               fill in for key associated with this string
+     * @param status            fills in the outgoing error code
+     * @return an UnicodeString object.
+     * @stable ICU 2.0
+     */
+    UnicodeString
+      getNextString(const char ** key,
+                    UErrorCode& status);
+
+    /**
+     * Returns the resource in a resource at the specified index.
+     *
+     * @param index             an index to the wanted resource.
+     * @param status            fills in the outgoing error code
+     * @return                  ResourceBundle object. If there is an error, resource is invalid.
+     * @stable ICU 2.0
+     */
+    ResourceBundle
+      get(int32_t index,
+          UErrorCode& status) const;
+
+    /**
+     * Returns the string in a given resource at the specified index.
+     *
+     * @param index             an index to the wanted string.
+     * @param status            fills in the outgoing error code
+     * @return                  an UnicodeString object. If there is an error, string is bogus
+     * @stable ICU 2.0
+     */
+    UnicodeString
+      getStringEx(int32_t index,
+                  UErrorCode& status) const;
+
+    /**
+     * Returns a resource in a resource that has a given key. This procedure works only with table
+     * resources.
+     *
+     * @param key               a key associated with the wanted resource
+     * @param status            fills in the outgoing error code.
+     * @return                  ResourceBundle object. If there is an error, resource is invalid.
+     * @stable ICU 2.0
+     */
+    ResourceBundle
+      get(const char* key,
+          UErrorCode& status) const;
+
+    /**
+     * Returns a string in a resource that has a given key. This procedure works only with table
+     * resources.
+     *
+     * @param key               a key associated with the wanted string
+     * @param status            fills in the outgoing error code
+     * @return                  an UnicodeString object. If there is an error, string is bogus
+     * @stable ICU 2.0
+     */
+    UnicodeString
+      getStringEx(const char* key,
+                  UErrorCode& status) const;
+
+    /**
+     * Return the version number associated with this ResourceBundle as a string. Please
+     * use getVersion, as this method is going to be deprecated.
+     *
+     * @return  A version number string as specified in the resource bundle or its parent.
+     *          The caller does not own this string.
+     * @see getVersion
+     * @deprecated ICU 2.8 Use getVersion instead.
+     */
+    const char*
+      getVersionNumber(void) const;
+
+    /**
+     * Return the version number associated with this ResourceBundle as a UVersionInfo array.
+     *
+     * @param versionInfo A UVersionInfo array that is filled with the version number
+     *                    as specified in the resource bundle or its parent.
+     * @stable ICU 2.0
+     */
+    void
+      getVersion(UVersionInfo versionInfo) const;
+
+    /**
+     * Return the Locale associated with this ResourceBundle.
+     *
+     * @return a Locale object
+     * @deprecated ICU 2.8 Use getLocale(ULocDataLocaleType type, UErrorCode &status) overload instead.
+     */
+    const Locale&
+      getLocale(void) const;
+
+    /**
+     * Return the Locale associated with this ResourceBundle.
+     * @param type You can choose between requested, valid and actual
+     *             locale. For description see the definition of
+     *             ULocDataLocaleType in uloc.h
+     * @param status just for catching illegal arguments
+     *
+     * @return a Locale object
+     * @stable ICU 2.8
+     */
+    const Locale
+      getLocale(ULocDataLocaleType type, UErrorCode &status) const;
+    /**
+     * This API implements multilevel fallback
+     * @internal
+     */
+    ResourceBundle
+        getWithFallback(const char* key, UErrorCode& status);
+    /**
+     * ICU "poor man's RTTI", returns a UClassID for the actual class.
+     *
+     * @stable ICU 2.2
+     */
+    virtual UClassID getDynamicClassID() const;
+
+    /**
+     * ICU "poor man's RTTI", returns a UClassID for this class.
+     *
+     * @stable ICU 2.2
+     */
+    static UClassID U_EXPORT2 getStaticClassID();
+
+private:
+    ResourceBundle(); // default constructor not implemented
+
+    UResourceBundle *fResource;
+    void constructForLocale(const UnicodeString& path, const Locale& locale, UErrorCode& error);
+    Locale *fLocale;
+
+};
+
+U_NAMESPACE_END
+#endif


[39/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_mrview/test/02-map-views.t
----------------------------------------------------------------------
diff --git a/apps/couch_mrview/test/02-map-views.t b/apps/couch_mrview/test/02-map-views.t
deleted file mode 100644
index 7e1ca0c..0000000
--- a/apps/couch_mrview/test/02-map-views.t
+++ /dev/null
@@ -1,131 +0,0 @@
-#!/usr/bin/env escript
-%% -*- erlang -*-
-
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
-main(_) ->
-    test_util:init_code_path(),
-
-    etap:plan(6),
-    case (catch test()) of
-        ok ->
-            etap:end_tests();
-        Other ->
-            etap:diag(io_lib:format("Test died abnormally: ~p", [Other])),
-            etap:bail(Other)
-    end,
-    timer:sleep(300),
-    ok.
-
-test() ->
-    couch_server_sup:start_link(test_util:config_files()),
-
-    {ok, Db} = couch_mrview_test_util:init_db(<<"foo">>, map),
-
-    test_basic(Db),
-    test_range(Db),
-    test_rev_range(Db),
-    test_limit_and_skip(Db),
-    test_include_docs(Db),
-    test_empty_view(Db),
-
-    ok.
-
-
-test_basic(Db) ->
-    Result = run_query(Db, []),
-    Expect = {ok, [
-        {meta, [{total, 10}, {offset, 0}]},
-        {row, [{id, <<"1">>}, {key, 1}, {value, 1}]},
-        {row, [{id, <<"2">>}, {key, 2}, {value, 2}]},
-        {row, [{id, <<"3">>}, {key, 3}, {value, 3}]},
-        {row, [{id, <<"4">>}, {key, 4}, {value, 4}]},
-        {row, [{id, <<"5">>}, {key, 5}, {value, 5}]},
-        {row, [{id, <<"6">>}, {key, 6}, {value, 6}]},
-        {row, [{id, <<"7">>}, {key, 7}, {value, 7}]},
-        {row, [{id, <<"8">>}, {key, 8}, {value, 8}]},
-        {row, [{id, <<"9">>}, {key, 9}, {value, 9}]},
-        {row, [{id, <<"10">>}, {key, 10}, {value, 10}]}
-    ]},
-    etap:is(Result, Expect, "Simple view query worked.").
-
-
-test_range(Db) ->
-    Result = run_query(Db, [{start_key, 3}, {end_key, 5}]),
-    Expect = {ok, [
-        {meta, [{total, 10}, {offset, 2}]},
-        {row, [{id, <<"3">>}, {key, 3}, {value, 3}]},
-        {row, [{id, <<"4">>}, {key, 4}, {value, 4}]},
-        {row, [{id, <<"5">>}, {key, 5}, {value, 5}]}
-    ]},
-    etap:is(Result, Expect, "Query with range works.").
-
-
-test_rev_range(Db) ->
-    Result = run_query(Db, [
-        {direction, rev},
-        {start_key, 5}, {end_key, 3},
-        {inclusive_end, true}
-    ]),
-    Expect = {ok, [
-        {meta, [{total, 10}, {offset, 5}]},
-        {row, [{id, <<"5">>}, {key, 5}, {value, 5}]},
-        {row, [{id, <<"4">>}, {key, 4}, {value, 4}]},
-        {row, [{id, <<"3">>}, {key, 3}, {value, 3}]}
-    ]},
-    etap:is(Result, Expect, "Query with reversed range works.").
-
-
-test_limit_and_skip(Db) ->
-    Result = run_query(Db, [
-        {start_key, 2},
-        {limit, 3},
-        {skip, 3}
-    ]),
-    Expect = {ok, [
-        {meta, [{total, 10}, {offset, 4}]},
-        {row, [{id, <<"5">>}, {key, 5}, {value, 5}]},
-        {row, [{id, <<"6">>}, {key, 6}, {value, 6}]},
-        {row, [{id, <<"7">>}, {key, 7}, {value, 7}]}
-    ]},
-    etap:is(Result, Expect, "Query with limit and skip works.").
-
-
-test_include_docs(Db) ->
-    Result = run_query(Db, [
-        {start_key, 8},
-        {end_key, 8},
-        {include_docs, true}
-    ]),
-    Doc = {[
-        {<<"_id">>,<<"8">>},
-        {<<"_rev">>, <<"1-55b9a29311341e07ec0a7ca13bc1b59f">>},
-        {<<"val">>,8}
-    ]},
-    Expect = {ok, [
-        {meta, [{total, 10}, {offset, 7}]},
-        {row, [{id, <<"8">>}, {key, 8}, {value, 8}, {doc, Doc}]}
-    ]},
-    etap:is(Result, Expect, "Query with include docs works.").
-
-
-test_empty_view(Db) ->
-    Result = couch_mrview:query_view(Db, <<"_design/bar">>, <<"bing">>),
-    Expect = {ok, [
-        {meta, [{total, 0}, {offset, 0}]}
-    ]},
-    etap:is(Result, Expect, "Empty views are correct.").
-
-
-run_query(Db, Opts) ->
-    couch_mrview:query_view(Db, <<"_design/bar">>, <<"baz">>, Opts).

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_mrview/test/03-red-views.t
----------------------------------------------------------------------
diff --git a/apps/couch_mrview/test/03-red-views.t b/apps/couch_mrview/test/03-red-views.t
deleted file mode 100644
index 6ad341b..0000000
--- a/apps/couch_mrview/test/03-red-views.t
+++ /dev/null
@@ -1,78 +0,0 @@
-#!/usr/bin/env escript
-%% -*- erlang -*-
-
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
-main(_) ->
-    test_util:run(4, fun() -> test() end).
-
-test() ->
-    couch_server_sup:start_link(test_util:config_files()),
-
-    {ok, Db} = couch_mrview_test_util:init_db(<<"foo">>, red),
-
-    test_basic(Db),
-    test_key_range(Db),
-    test_group_level(Db),
-    test_group_exact(Db),
-
-    ok.
-
-
-test_basic(Db) ->
-    Result = run_query(Db, []),
-    Expect = {ok, [
-        {meta, []},
-        {row, [{key, null}, {value, 55}]}
-    ]},
-    etap:is(Result, Expect, "Simple reduce view works.").
-
-
-test_key_range(Db) ->
-    Result = run_query(Db, [{start_key, [0, 2]}, {end_key, [0, 4]}]),
-    Expect = {ok, [
-        {meta, []},
-        {row, [{key, null}, {value, 6}]}
-    ]},
-    etap:is(Result, Expect, "Reduce with key range works.").
-
-
-test_group_level(Db) ->
-    Result = run_query(Db, [{group_level, 1}]),
-    Expect = {ok, [
-        {meta, []},
-        {row, [{key, [0]}, {value, 30}]},
-        {row, [{key, [1]}, {value, 25}]}
-    ]},
-    etap:is(Result, Expect, "Group level works.").
-
-test_group_exact(Db) ->
-    Result = run_query(Db, [{group_level, exact}]),
-    Expect = {ok, [
-        {meta, []},
-        {row, [{key, [0, 2]}, {value, 2}]},
-        {row, [{key, [0, 4]}, {value, 4}]},
-        {row, [{key, [0, 6]}, {value, 6}]},
-        {row, [{key, [0, 8]}, {value, 8}]},
-        {row, [{key, [0, 10]}, {value, 10}]},
-        {row, [{key, [1, 1]}, {value, 1}]},
-        {row, [{key, [1, 3]}, {value, 3}]},
-        {row, [{key, [1, 5]}, {value, 5}]},
-        {row, [{key, [1, 7]}, {value, 7}]},
-        {row, [{key, [1, 9]}, {value, 9}]}
-    ]},
-    etap:is(Result, Expect, "Group exact works.").
-
-
-run_query(Db, Opts) ->
-    couch_mrview:query_view(Db, <<"_design/bar">>, <<"baz">>, Opts).

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_mrview/test/04-index-info.t
----------------------------------------------------------------------
diff --git a/apps/couch_mrview/test/04-index-info.t b/apps/couch_mrview/test/04-index-info.t
deleted file mode 100644
index 6b67b56..0000000
--- a/apps/couch_mrview/test/04-index-info.t
+++ /dev/null
@@ -1,54 +0,0 @@
-#!/usr/bin/env escript
-%% -*- erlang -*-
-
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
-main(_) ->
-    test_util:init_code_path(),
-
-    etap:plan(9),
-    case (catch test()) of
-        ok ->
-            etap:end_tests();
-        Other ->
-            etap:diag(io_lib:format("Test died abnormally: ~p", [Other])),
-            etap:bail(Other)
-    end,
-    timer:sleep(300),
-    ok.
-
-sig() -> <<"276df562b152b3c4e5d34024f62672ed">>.
-
-test() ->
-    couch_server_sup:start_link(test_util:config_files()),
-
-    {ok, Db} = couch_mrview_test_util:init_db(<<"foo">>, map),
-    couch_mrview:query_view(Db, <<"_design/bar">>, <<"baz">>),
-
-    {ok, Info} = couch_mrview:get_info(Db, <<"_design/bar">>),
-
-    etap:is(getval(signature, Info), sig(), "Signature is ok."),
-    etap:is(getval(language, Info), <<"javascript">>, "Language is ok."),
-    etap:is_greater(getval(disk_size, Info), 0, "Disk size is ok."),
-    etap:is_greater(getval(data_size, Info), 0, "Data size is ok."),
-    etap:is(getval(update_seq, Info), 11, "Update seq is ok."),
-    etap:is(getval(purge_seq, Info), 0, "Purge seq is ok."),
-    etap:is(getval(updater_running, Info), false, "No updater running."),
-    etap:is(getval(compact_running, Info), false, "No compaction running."),
-    etap:is(getval(waiting_clients, Info), 0, "No waiting clients."),
-
-    ok.
-
-getval(Key, PL) ->
-    {value, {Key, Val}} = lists:keysearch(Key, 1, PL),
-    Val.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_mrview/test/05-collation.t
----------------------------------------------------------------------
diff --git a/apps/couch_mrview/test/05-collation.t b/apps/couch_mrview/test/05-collation.t
deleted file mode 100644
index ac8f8bc..0000000
--- a/apps/couch_mrview/test/05-collation.t
+++ /dev/null
@@ -1,163 +0,0 @@
-#!/usr/bin/env escript
-%% -*- erlang -*-
-
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
-main(_) ->
-    test_util:run(9, fun() -> test() end).
-
-
-test() ->
-    couch_server_sup:start_link(test_util:config_files()),
-    {ok, Db0} = couch_mrview_test_util:new_db(<<"foo">>, map),
-    {ok, Db1} = couch_mrview_test_util:save_docs(Db0, docs()),
-
-    test_collated_fwd(Db1),
-    test_collated_rev(Db1),
-    test_range_collation(Db1),
-    test_inclusive_end(Db1),
-    test_uninclusive_end(Db1),
-    test_with_endkey_docid(Db1),
-
-    ok.
-
-test_collated_fwd(Db) ->
-    {ok, Results} = run_query(Db, []),
-    Expect = [{meta, [{total, 26}, {offset, 0}]}] ++ rows(),
-    etap:is(Results, Expect, "Values were collated correctly.").
-
-
-test_collated_rev(Db) ->
-    {ok, Results} = run_query(Db, [{direction, rev}]),
-    Expect = [{meta, [{total, 26}, {offset, 0}]}] ++ lists:reverse(rows()),
-    etap:is(Results, Expect, "Values were collated correctly descending.").
-
-
-test_range_collation(Db) ->
-    {_, Error} = lists:foldl(fun(V, {Count, Error}) ->
-        {ok, Results} = run_query(Db, [{start_key, V}, {end_key, V}]),
-        Id = list_to_binary(integer_to_list(Count)),
-        Expect = [
-            {meta, [{total, 26}, {offset, Count}]},
-            {row, [{id, Id}, {key, V}, {value, 0}]}
-        ],
-        case Results == Expect of
-            true -> {Count+1, Error};
-            _ -> {Count+1, true}
-        end
-    end, {0, false}, vals()),
-    etap:is(Error, false, "Found each individual key correctly.").
-
-
-test_inclusive_end(Db) ->
-    Opts = [{end_key, <<"b">>}, {inclusive_end, true}],
-    {ok, Rows0} = run_query(Db, Opts),
-    LastRow0 = lists:last(Rows0),
-    Expect0 = {row, [{id,<<"10">>}, {key,<<"b">>}, {value,0}]},
-    etap:is(LastRow0, Expect0, "Inclusive end is correct."),
-
-    {ok, Rows1} = run_query(Db, Opts ++ [{direction, rev}]),
-    LastRow1 = lists:last(Rows1),
-    Expect1 = {row, [{id,<<"10">>}, {key,<<"b">>}, {value,0}]},
-    etap:is(LastRow1, Expect1,
-            "Inclusive end is correct with descending=true").
-
-test_uninclusive_end(Db) ->
-    Opts = [{end_key, <<"b">>}, {inclusive_end, false}],
-    {ok, Rows0} = run_query(Db, Opts),
-    LastRow0 = lists:last(Rows0),
-    Expect0 = {row, [{id,<<"9">>}, {key,<<"aa">>}, {value,0}]},
-    etap:is(LastRow0, Expect0, "Uninclusive end is correct."),
-
-    {ok, Rows1} = run_query(Db, Opts ++ [{direction, rev}]),
-    LastRow1 = lists:last(Rows1),
-    Expect1 = {row, [{id,<<"11">>}, {key,<<"B">>}, {value,0}]},
-    etap:is(LastRow1, Expect1,
-            "Uninclusive end is correct with descending=true").
-
-
-test_with_endkey_docid(Db) ->
-    {ok, Rows0} = run_query(Db, [
-        {end_key, <<"b">>}, {end_key_docid, <<"10">>},
-        {inclusive_end, false}
-    ]),
-    Result0 = lists:last(Rows0),
-    Expect0 = {row, [{id,<<"9">>}, {key,<<"aa">>}, {value,0}]},
-    etap:is(Result0, Expect0, "Uninclsuive end with endkey_docid set is ok."),
-
-    {ok, Rows1} = run_query(Db, [
-        {end_key, <<"b">>}, {end_key_docid, <<"11">>},
-        {inclusive_end, false}
-    ]),
-    Result1 = lists:last(Rows1),
-    Expect1 = {row, [{id,<<"10">>}, {key,<<"b">>}, {value,0}]},
-    etap:is(Result1, Expect1, "Uninclsuive end with endkey_docid set is ok.").
-
-
-run_query(Db, Opts) ->
-    couch_mrview:query_view(Db, <<"_design/bar">>, <<"zing">>, Opts).
-
-
-docs() ->
-    {Docs, _} = lists:foldl(fun(V, {Docs0, Count}) ->
-        Doc = couch_doc:from_json_obj({[
-            {<<"_id">>, list_to_binary(integer_to_list(Count))},
-            {<<"foo">>, V}
-        ]}),
-        {[Doc | Docs0], Count+1}
-    end, {[], 0}, vals()),
-    Docs.
-
-
-rows() ->
-    {Rows, _} = lists:foldl(fun(V, {Rows0, Count}) ->
-        Id = list_to_binary(integer_to_list(Count)),
-        Row = {row, [{id, Id}, {key, V}, {value, 0}]},
-        {[Row | Rows0], Count+1}
-    end, {[], 0}, vals()),
-    lists:reverse(Rows).
-
-
-vals() ->
-    [
-        null,
-        false,
-        true,
-
-        1,
-        2,
-        3.0,
-        4,
-
-        <<"a">>,
-        <<"A">>,
-        <<"aa">>,
-        <<"b">>,
-        <<"B">>,
-        <<"ba">>,
-        <<"bb">>,
-
-        [<<"a">>],
-        [<<"b">>],
-        [<<"b">>, <<"c">>],
-        [<<"b">>, <<"c">>, <<"a">>],
-        [<<"b">>, <<"d">>],
-        [<<"b">>, <<"d">>, <<"e">>],
-
-        {[{<<"a">>, 1}]},
-        {[{<<"a">>, 2}]},
-        {[{<<"b">>, 1}]},
-        {[{<<"b">>, 2}]},
-        {[{<<"b">>, 2}, {<<"a">>, 1}]},
-        {[{<<"b">>, 2}, {<<"c">>, 2}]}
-    ].

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_mrview/test/06-all-docs.t
----------------------------------------------------------------------
diff --git a/apps/couch_mrview/test/06-all-docs.t b/apps/couch_mrview/test/06-all-docs.t
deleted file mode 100644
index 4501aa5..0000000
--- a/apps/couch_mrview/test/06-all-docs.t
+++ /dev/null
@@ -1,127 +0,0 @@
-#!/usr/bin/env escript
-%% -*- erlang -*-
-
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
-main(_) ->
-    test_util:run(6, fun() -> test() end).
-
-
-test() ->
-    couch_server_sup:start_link(test_util:config_files()),
-
-    {ok, Db} = couch_mrview_test_util:init_db(<<"foo">>, map),
-
-    test_basic(Db),
-    test_range(Db),
-    test_rev_range(Db),
-    test_limit_and_skip(Db),
-    test_include_docs(Db),
-    test_empty_view(Db),
-
-    ok.
-
-
-test_basic(Db) ->
-    Result = run_query(Db, []),
-    Expect = {ok, [
-        {meta, [{total, 11}, {offset, 0}]},
-        mk_row(<<"1">>, <<"1-08d53a5760b95fce6df2e2c5b008be39">>),
-        mk_row(<<"10">>, <<"1-a05b6ea2bc0243949f103d5b4f15f71e">>),
-        mk_row(<<"2">>, <<"1-b57c77a9e6f7574ca6469f0d6dcd78bb">>),
-        mk_row(<<"3">>, <<"1-7fbf84d56f8017880974402d60f5acd6">>),
-        mk_row(<<"4">>, <<"1-fcaf5852c08ffb239ac8ce16c409f253">>),
-        mk_row(<<"5">>, <<"1-aaac5d460fd40f9286e57b9bf12e23d2">>),
-        mk_row(<<"6">>, <<"1-aca21c2e7bc5f8951424fcfc5d1209d8">>),
-        mk_row(<<"7">>, <<"1-4374aeec17590d82f16e70f318116ad9">>),
-        mk_row(<<"8">>, <<"1-55b9a29311341e07ec0a7ca13bc1b59f">>),
-        mk_row(<<"9">>, <<"1-558c8487d9aee25399a91b5d31d90fe2">>),
-        mk_row(<<"_design/bar">>, <<"1-a44e1dd1994a7717bf89c894ebd1f081">>)
-    ]},
-    etap:is(Result, Expect, "Simple view query worked.").
-
-
-test_range(Db) ->
-    Result = run_query(Db, [{start_key, <<"3">>}, {end_key, <<"5">>}]),
-    Expect = {ok, [
-        {meta, [{total, 11}, {offset, 3}]},
-        mk_row(<<"3">>, <<"1-7fbf84d56f8017880974402d60f5acd6">>),
-        mk_row(<<"4">>, <<"1-fcaf5852c08ffb239ac8ce16c409f253">>),
-        mk_row(<<"5">>, <<"1-aaac5d460fd40f9286e57b9bf12e23d2">>)
-    ]},
-    etap:is(Result, Expect, "Query with range works.").
-
-
-test_rev_range(Db) ->
-    Result = run_query(Db, [
-        {direction, rev},
-        {start_key, <<"5">>}, {end_key, <<"3">>},
-        {inclusive_end, true}
-    ]),
-    Expect = {ok, [
-        {meta, [{total, 11}, {offset, 5}]},
-        mk_row(<<"5">>, <<"1-aaac5d460fd40f9286e57b9bf12e23d2">>),
-        mk_row(<<"4">>, <<"1-fcaf5852c08ffb239ac8ce16c409f253">>),
-        mk_row(<<"3">>, <<"1-7fbf84d56f8017880974402d60f5acd6">>)
-    ]},
-    etap:is(Result, Expect, "Query with reversed range works.").
-
-
-test_limit_and_skip(Db) ->
-    Result = run_query(Db, [
-        {start_key, <<"2">>},
-        {limit, 3},
-        {skip, 3}
-    ]),
-    Expect = {ok, [
-        {meta, [{total, 11}, {offset, 5}]},
-        mk_row(<<"5">>, <<"1-aaac5d460fd40f9286e57b9bf12e23d2">>),
-        mk_row(<<"6">>, <<"1-aca21c2e7bc5f8951424fcfc5d1209d8">>),
-        mk_row(<<"7">>, <<"1-4374aeec17590d82f16e70f318116ad9">>)
-    ]},
-    etap:is(Result, Expect, "Query with limit and skip works.").
-
-
-test_include_docs(Db) ->
-    Result = run_query(Db, [
-        {start_key, <<"8">>},
-        {end_key, <<"8">>},
-        {include_docs, true}
-    ]),
-    Doc = {[
-        {<<"_id">>,<<"8">>},
-        {<<"_rev">>, <<"1-55b9a29311341e07ec0a7ca13bc1b59f">>},
-        {<<"val">>, 8}
-    ]},
-    Val = {[{rev, <<"1-55b9a29311341e07ec0a7ca13bc1b59f">>}]},
-    Expect = {ok, [
-        {meta, [{total, 11}, {offset, 8}]},
-        {row, [{id, <<"8">>}, {key, <<"8">>}, {value, Val}, {doc, Doc}]}
-    ]},
-    etap:is(Result, Expect, "Query with include docs works.").
-
-
-test_empty_view(Db) ->
-    Result = couch_mrview:query_view(Db, <<"_design/bar">>, <<"bing">>),
-    Expect = {ok, [
-        {meta, [{total, 0}, {offset, 0}]}
-    ]},
-    etap:is(Result, Expect, "Empty views are correct.").
-
-
-mk_row(Id, Rev) ->
-    {row, [{id, Id}, {key, Id}, {value, {[{rev, Rev}]}}]}.
-
-
-run_query(Db, Opts) ->
-    couch_mrview:query_all_docs(Db, Opts).

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_mrview/test/07-compact-swap.t
----------------------------------------------------------------------
diff --git a/apps/couch_mrview/test/07-compact-swap.t b/apps/couch_mrview/test/07-compact-swap.t
deleted file mode 100644
index 4bfe124..0000000
--- a/apps/couch_mrview/test/07-compact-swap.t
+++ /dev/null
@@ -1,57 +0,0 @@
-#!/usr/bin/env escript
-%% -*- erlang -*-
-
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
-main(_) ->
-    test_util:run(1, fun() -> test() end).
-
-
-test() ->
-    couch_server_sup:start_link(test_util:config_files()),
-    {ok, Db} = couch_mrview_test_util:init_db(<<"foo">>, map, 1000),
-    couch_mrview:query_view(Db, <<"_design/bar">>, <<"baz">>),
-    test_swap(Db),
-    ok.
-
-
-test_swap(Db) ->
-    {ok, QPid} = start_query(Db),    
-    {ok, MonRef} = couch_mrview:compact(Db, <<"_design/bar">>, [monitor]),
-    receive
-        {'DOWN', MonRef, process, _, _} -> ok
-    after 1000 ->
-        throw(compaction_failed)
-    end,
-    QPid ! {self(), continue},
-    receive
-        {QPid, Count} ->
-            etap:is(Count, 1000, "View finished successfully.")
-    after 1000 ->
-        throw("query failed")
-    end.
-
-
-start_query(Db) ->
-    Self = self(),
-    Pid = spawn(fun() ->
-        CB = fun
-            (_, wait) -> receive {Self, continue} -> {ok, 0} end;
-            ({row, _}, Count) -> {ok, Count+1};
-            (_, Count) -> {ok, Count}
-        end,
-        {ok, Result} = 
-        couch_mrview:query_view(Db, <<"_design/bar">>, <<"baz">>, [], CB, wait),
-        Self ! {self(), Result}
-    end),
-    {ok, Pid}.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_plugins/README.md
----------------------------------------------------------------------
diff --git a/apps/couch_plugins/README.md b/apps/couch_plugins/README.md
deleted file mode 100644
index b00a080..0000000
--- a/apps/couch_plugins/README.md
+++ /dev/null
@@ -1,159 +0,0 @@
-Heya,
-
-I couldn’t help myself thinking about plugin stuff and ended up
-whipping up a proof of concept.
-
-Here’s a <1 minute demo video:
-
-  https://dl.dropboxusercontent.com/u/82149/couchdb-plugins-demo.mov
-
-Alternative encoding:
-
-  https://dl.dropboxusercontent.com/u/82149/couchdb-plugins-demo.m4v)
-
-
-In my head the whole plugin idea is a very wide area, but I was so
-intrigued by the idea of getting something running with a click on a
-button in Futon. So I looked for a minimally viable plugin system.
-
-
-## Design principles
-
-It took me a day to put this all together and this was only possible
-because I took a lot of shortcuts. I believe they are all viable for a
-first iteration of a plugins system:
-
-1. Install with one click on a button in Futon (or HTTP call)
-2. Only pure Erlang plugins are allowed.
-3. The plugin author must provide a binary package for each Erlang (and,
-   later, each CouchDB version).
-4. Complete trust-based system. You trust me to not do any nasty things
-   when you click on the install button. No crypto, no nothing. Only
-   people who can commit to Futon can release new versions of plugins.
-5. Minimal user-friendlyness: won’t install plugins that don’t match
-   the current Erlang version, gives semi-sensible error messages
-   (wrapped in a HTTP 500 response :)
-6. Require a pretty strict format for binary releases.
-
-
-## Roadmap
-
-Here’s a list of things this first iterations does and doesn’t do:
-
-- Pure Erlang plugins only. No C-dependencies, no JavaScript, no nothing.
-- No C-dependencies.
-- Install a plugin via Futon (or HTTP call). Admin only.
-- A hardcoded list of plugins in Futon.
-- Loads a pre-packaged, pre-compiled .tar.gz file from a URL.
-- Only installs if Erlang version matches.
-- No security checking of binaries.
-- No identity checking of binaries.
-- Register installed plugins in the config system.
-- Make sure plugins start with the next restart of CouchDB.
-- Uninstall a plugin via Futon (or HTTP call). Admin only.
-- Show when a particular plugin is installed.
-- Only installs if CouchDB version matches.
-- Serve static web assets (for Futon/Fauxton) from `/_plugins/<name>/`.
-
-I hope you agree we can ship this with a few warnings so people can get a
-hang of it.
-
-
-A roadmap, progress and issues can be found here:
-
-https://issues.apache.org/jira/issues/?jql=component+%3D+Plugins+AND+project+%3D+COUCHDB+AND+resolution+%3D+Unresolved+ORDER+BY+priority+DESC
-
-
-
-## How it works
-
-This plugin system lives in `src/couch_plugins` and is a tiny CouchDB
-module.
-
-It exposes one new API endpoint `/_plugins` that an admin user can
-POST to.
-
-The additional Futon page lives at `/_utils/plugins.html` it is
-hardcoded.
-
-Futon (or you) post an object to `/_plugins` with four properties:
-
-    {
-      "name": "geocouch", // name of the plugin, must be unique
-      "url": "http://people.apache.org/~jan", // “base URL” for plugin releases (see below)
-      "version": "couchdb1.2.x_v0.3.0-11-g4ea0bea", // whatever version internal to the plugin
-      "checksums": {
-        "R15B03": "ZetgdHj2bY2w37buulWVf3USOZs=" // base64’d sha hash over the binary
-      }
-    }
-
-`couch_plugins` then attempts to download a .tar.gz from this
-location:
-
-    http://people.apache.org/~jan/geocouch-couchdb1.2.x_v0.3.0-12-g4ea0bea-R15B03.tar.gz
-
-It should be obvious how the URL is constructed from the POST data.
-(This url is live, feel free to play around with this tarball).
-
-Next it calculates the sha hash for the downloaded .tar.gz file and
-matches it against the correct version in the `checksums` parameter.
-
-If that succeeds, we unpack the .tar.gz file (currently in `/tmp`,
-need to find a better place for this) and adds the extracted directory
-to the Erlang code path
-(`code:add_path("/tmp/couchdb_plugins/geocouch-couchdb1.2.x_v0.3.0-12-g4ea0bea-R15B03/ebin")`)
-and loads the included application (`application:load(geocouch)`).
-
-Then it looks into the `./priv/default.d` directory that lives next to
-`ebin/` in the plugin directory for configuration `.ini` files and loads them.
-On next startup these configuration files are loaded after global defaults,
-and before any local configuration.
-
-If that all goes to plan, we report success back to the HTTP caller.
-
-That’s it! :)
-
-It’s deceptively simple, probably does a few things very wrong and
-leaves a few things open (see above).
-
-One open question I’d like an answer for is finding a good location to
-unpack & install the plugin files that isn’t `tmp`. If the answer is
-different for a pre-BigCouch/rcouch-merge and post-BigCouch/rcouch-
-merge world, I’d love to know :)
-
-
-## Code
-
-The main branch for this is 1867-feature-plugins:
-
-  ASF: https://git-wip-us.apache.org/repos/asf?p=couchdb.git;a=log;h=refs/heads/1867-feature-plugins
-  GitHub: https://github.com/janl/couchdb/compare/apache:master...1867-feature-plugins
-
-I created a branch on GeoCouch that adds a few lines to its `Makefile`
-that shows how a binary package is built:
-
-    https://github.com/janl/geocouch/compare/couchbase:couchdb1.3.x...couchdb1.3.x-plugins
-
-
-## Build
-
-Build CouchDB as usual:
-
-    ./bootstrap
-    ./configure
-    make
-    make dev
-    ./utils/run
-
-* * *
-
-I hope you like this :) Please comment and improve heavily!
-
-Let me know if you have any questions :)
-
-If you have any criticism, please phrase it in a way that we can use
-to improve this, thanks!
-
-Best,
-Jan
---

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_plugins/src/couch_plugins.app.src
----------------------------------------------------------------------
diff --git a/apps/couch_plugins/src/couch_plugins.app.src b/apps/couch_plugins/src/couch_plugins.app.src
deleted file mode 100644
index 9e69b84..0000000
--- a/apps/couch_plugins/src/couch_plugins.app.src
+++ /dev/null
@@ -1,23 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-{application, couch_plugins,
- [
-  {description, "A CouchDB Plugin Installer"},
-  {vsn, "0.1.0"},
-  {registered, []},
-  {applications, [
-                  kernel,
-                  stdlib
-                 ]},
-  {mod, { couch_plugins_app, []}},
-  {env, []}
- ]}.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_plugins/src/couch_plugins.erl
----------------------------------------------------------------------
diff --git a/apps/couch_plugins/src/couch_plugins.erl b/apps/couch_plugins/src/couch_plugins.erl
deleted file mode 100644
index dcbd2d3..0000000
--- a/apps/couch_plugins/src/couch_plugins.erl
+++ /dev/null
@@ -1,300 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
--module(couch_plugins).
--include_lib("couch/include/couch_db.hrl").
--export([install/1, uninstall/1]).
-
-% couch_plugins:install({"geocouch", "http://127.0.0.1:8000", "1.0.0", [{"R15B03", "+XOJP6GSzmuO2qKdnjO+mWckXVs="}]}).
-% couch_plugins:install({"geocouch", "http://people.apache.org/~jan/", "couchdb1.2.x_v0.3.0-11-gd83ba22", [{"R15B03", "ZetgdHj2bY2w37buulWVf3USOZs="}]}).
-
-plugin_dir() ->
-  couch_config:get("couchdb", "plugin_dir").
-
-log(T) ->
-  ?LOG_DEBUG("[couch_plugins] ~p ~n", [T]).
-
-%% "geocouch", "http://localhost:8000/dist", "1.0.0"
--type plugin() :: {string(), string(), string(), list()}.
--spec install(plugin()) -> ok | {error, string()}.
-install({Name, _BaseUrl, Version, Checksums}=Plugin) ->
-  log("Installing " ++ Name),
-
-  {ok, LocalFilename} = download(Plugin),
-  log("downloaded to " ++ LocalFilename),
-
-  ok = verify_checksum(LocalFilename, Checksums),
-  log("checksum verified"),
-
-  ok = untargz(LocalFilename),
-  log("extraction done"),
-
-  ok = add_code_path(Name, Version),
-  log("added code path"),
-
-  ok = register_plugin(Name, Version),
-  log("registered plugin"),
-
-  load_config(Name, Version),
-  log("loaded config"),
-
-  ok.
-
-% Idempotent uninstall, if you uninstall a non-existant
-% plugin, you get an `ok`.
--spec uninstall(plugin()) -> ok | {error, string()}.
-uninstall({Name, _BaseUrl, Version, _Checksums}) ->
-  % unload config
-  ok = unload_config(Name, Version),
-  log("config unloaded"),
-
-  % delete files
-  ok = delete_files(Name, Version),
-  log("files deleted"),
-
-  % delete code path
-  ok = del_code_path(Name, Version),
-  log("deleted code path"),
-
-  % unregister plugin
-  ok = unregister_plugin(Name),
-  log("unregistered plugin"),
-
-  % done
-  ok.
-
-%% * * *
-
-
-%% Plugin Registration
-%% On uninstall:
-%%  - add plugins/name = version to config
-%% On uninstall:
-%%  - remove plugins/name from config
-
--spec register_plugin(string(), string()) -> ok.
-register_plugin(Name, Version) ->
-  couch_config:set("plugins", Name, Version).
-
--spec unregister_plugin(string()) -> ok.
-unregister_plugin(Name) ->
-  couch_config:delete("plugins", Name).
-
-%% * * *
-
-
-%% Load Config
-%% Parses <plugindir>/priv/default.d/<pluginname.ini> and applies
-%% the contents to the config system, or removes them on uninstall
-
--spec load_config(string(), string()) -> ok.
-load_config(Name, Version) ->
-    loop_config(Name, Version, fun set_config/1).
-
--spec unload_config(string(), string()) -> ok.
-unload_config(Name, Version) ->
-    loop_config(Name, Version, fun delete_config/1).
-
--spec loop_config(string(), string(), function()) -> ok.
-loop_config(Name, Version, Fun) ->
-    lists:foreach(fun(File) -> load_config_file(File, Fun) end,
-      filelib:wildcard(file_names(Name, Version))).
-
--spec load_config_file(string(), function()) -> ok.
-load_config_file(File, Fun) ->
-    {ok, Config} = couch_config:parse_ini_file(File),
-    lists:foreach(Fun, Config).
-
--spec set_config({{string(), string()}, string()}) -> ok.
-set_config({{Section, Key}, Value}) ->
-    ok = couch_config:set(Section, Key, Value).
-
--spec delete_config({{string(), string()}, _Value}) -> ok.
-delete_config({{Section, Key}, _Value}) ->
-    ok = couch_config:delete(Section, Key).
-
--spec file_names(string(), string()) -> string().
-file_names(Name, Version) ->
-  filename:join(
-    [plugin_dir(), get_file_slug(Name, Version),
-     "priv", "default.d", "*.ini"]).
-
-%% * * *
-
-
-%% Code Path Management
-%% The Erlang code path is where the Erlang runtime looks for `.beam`
-%% files to load on, say, `application:load()`. Since plugin directories
-%% are created on demand and named after CouchDB and Erlang versions,
-%% we manage the Erlang code path semi-automatically here.
-
--spec add_code_path(string(), string()) -> ok | {error, bad_directory}.
-add_code_path(Name, Version) ->
-  PluginPath = plugin_dir() ++ "/" ++ get_file_slug(Name, Version) ++ "/ebin",
-  case code:add_path(PluginPath) of
-    true -> ok;
-    Else ->
-      ?LOG_ERROR("Failed to add PluginPath: '~s'", [PluginPath]),
-      Else
-  end.
-
--spec del_code_path(string(), string()) -> ok | {error, atom()}.
-del_code_path(Name, Version) ->
-  PluginPath = plugin_dir() ++ "/" ++ get_file_slug(Name, Version) ++ "/ebin",
-  case code:del_path(PluginPath) of
-    true -> ok;
-    _Else ->
-      ?LOG_DEBUG("Failed to delete PluginPath: '~s', ignoring", [PluginPath]),
-      ok
-  end.
-
-%% * * *
-
-
--spec untargz(string()) -> {ok, string()} | {error, string()}.
-untargz(Filename) ->
-  % read .gz file
-  {ok, GzData} = file:read_file(Filename),
-  % gunzip
-  log("unzipped"),
-  TarData = zlib:gunzip(GzData),
-  ok = filelib:ensure_dir(plugin_dir()),
-  % untar
-  erl_tar:extract({binary, TarData}, [{cwd, plugin_dir()}, keep_old_files]).
-
--spec delete_files(string(), string()) -> ok | {error, atom()}.
-delete_files(Name, Version) ->
-  PluginPath = plugin_dir() ++ "/" ++ get_file_slug(Name, Version),
-  mochitemp:rmtempdir(PluginPath).
-
-
-% downloads a pluygin .tar.gz into a local plugins directory
--spec download(string()) -> ok | {error, string()}.
-download({Name, _BaseUrl, Version, _Checksums}=Plugin) ->
-  TargetFile = "/tmp/" ++ get_filename(Name, Version),
-  case file_exists(TargetFile) of
-    %% wipe and redownload
-    true -> file:delete(TargetFile);
-    _Else -> ok
-  end,
-  Url = get_url(Plugin),
-  HTTPOptions = [
-    {connect_timeout, 30*1000}, % 30 seconds
-    {timeout, 30*1000} % 30 seconds
-  ],
-  % todo: windows
-  Options = [
-    {stream, TargetFile}, % /tmp/something
-    {body_format, binary},
-    {full_result, false}
-  ],
-  % todo: reduce to just httpc:request()
-  case httpc:request(get, {Url, []}, HTTPOptions, Options) of
-    {ok, _Result} ->
-      log("downloading " ++ Url),
-      {ok, TargetFile};
-    Error -> Error
-  end.
-
--spec verify_checksum(string(), list()) -> ok | {error, string()}.
-verify_checksum(Filename, Checksums) ->
-
-  CouchDBVersion = couchdb_version(),
-  case proplists:get_value(CouchDBVersion, Checksums) of
-  undefined ->
-    ?LOG_ERROR("[couch_plugins] Can't find checksum for CouchDB Version '~s'", [CouchDBVersion]),
-    {error, no_couchdb_checksum};
-  OTPChecksum ->
-    OTPRelease = erlang:system_info(otp_release),
-    case proplists:get_value(OTPRelease, OTPChecksum) of
-    undefined ->
-      ?LOG_ERROR("[couch_plugins] Can't find checksum for Erlang Version '~s'", [OTPRelease]),
-      {error, no_erlang_checksum};
-    Checksum ->
-      do_verify_checksum(Filename, Checksum)
-    end
-  end.
-
--spec do_verify_checksum(string(), string()) -> ok | {error, string()}.
-do_verify_checksum(Filename, Checksum) ->
-  ?LOG_DEBUG("Checking Filename: ~s", [Filename]),
-  case file:read_file(Filename) of
-  {ok, Data} ->
-    ComputedChecksum = binary_to_list(base64:encode(crypto:sha(Data))),
-    case ComputedChecksum of
-    Checksum -> ok;
-    _Else ->
-      ?LOG_ERROR("Checksum mismatch. Wanted: '~p'. Got '~p'", [Checksum, ComputedChecksum]),
-      {error, checksum_mismatch}
-    end;
-  Error -> Error
-  end.
-
-
-%% utils
-
--spec get_url(plugin()) -> string().
-get_url({Name, BaseUrl, Version, _Checksums}) ->
-  BaseUrl ++ "/" ++ get_filename(Name, Version).
-
--spec get_filename(string(), string()) -> string().
-get_filename(Name, Version) ->
-  get_file_slug(Name, Version) ++ ".tar.gz".
-
--spec get_file_slug(string(), string()) -> string().
-get_file_slug(Name, Version) ->
-  % OtpRelease does not include patch levels like the -1 in R15B03-1
-  OTPRelease = erlang:system_info(otp_release),
-  CouchDBVersion = couchdb_version(),
-  string:join([Name, Version, OTPRelease, CouchDBVersion], "-").
-
--spec file_exists(string()) -> boolean().
-file_exists(Filename) ->
-  does_file_exist(file:read_file_info(Filename)).
--spec does_file_exist(term()) -> boolean().
-does_file_exist({error, enoent}) -> false;
-does_file_exist(_Else) -> true.
-
-couchdb_version() ->
-  couch_server:get_version(short).
-
-% installing a plugin:
-%  - POST /_plugins -d {plugin-def}
-%  - get plugin definition
-%  - get download URL (matching erlang version)
-%  - download archive
-%  - match checksum
-%  - untar-gz archive into a plugins dir
-%  - code:add_path(“geocouch-{geocouch_version}-{erlang_version}/ebin”)
-%  - [cp geocouch-{geocouch_version}-{erlang_version}/etc/ ]
-%  - application:start(geocouch)
-%  - register plugin in plugin registry
-
-% Plugin registry impl:
-%  - _plugins database
-%   - pro: known db ops
-%   - con: no need for replication, needs to be system db etc.
-%  - _config/plugins namespace in config
-%   - pro: lightweight, fits rarely-changing nature better
-%   - con: potentially not flexible enough
-
-
-
-% /geocouch
-% /geocouch/dist/
-% /geocouch/dist/geocouch-{geocouch_version}-{erlang_version}.tar.gz
-
-% tar.gz includes:
-% geocouch-{geocouch_version}-{erlang_version}/
-% geocouch-{geocouch_version}-{erlang_version}/ebin
-% [geocouch-{geocouch_version}-{erlang_version}/config/config.erlt]
-% [geocouch-{geocouch_version}-{erlang_version}/share/]
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_plugins/src/couch_plugins_httpd.erl
----------------------------------------------------------------------
diff --git a/apps/couch_plugins/src/couch_plugins_httpd.erl b/apps/couch_plugins/src/couch_plugins_httpd.erl
deleted file mode 100644
index 4dabbb4..0000000
--- a/apps/couch_plugins/src/couch_plugins_httpd.erl
+++ /dev/null
@@ -1,65 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
--module(couch_plugins_httpd).
-
--export([handle_req/1]).
-
--include_lib("couch/include/couch_db.hrl").
-
-handle_req(#httpd{method='POST'}=Req) ->
-    ok = couch_httpd:verify_is_server_admin(Req),
-    couch_httpd:validate_ctype(Req, "application/json"),
-
-    {PluginSpec} = couch_httpd:json_body_obj(Req),
-    Url = binary_to_list(couch_util:get_value(<<"url">>, PluginSpec)),
-    Name = binary_to_list(couch_util:get_value(<<"name">>, PluginSpec)),
-    Version = binary_to_list(couch_util:get_value(<<"version">>, PluginSpec)),
-    Delete = couch_util:get_value(<<"delete">>, PluginSpec),
-    {Checksums0} = couch_util:get_value(<<"checksums">>, PluginSpec),
-    Checksums = parse_checksums(Checksums0),
-
-    Plugin = {Name, Url, Version, Checksums},
-    case do_install(Delete, Plugin) of
-    ok ->
-        couch_httpd:send_json(Req, 202, {[{ok, true}]});
-    Error ->
-        ?LOG_DEBUG("Plugin Spec: ~p", [PluginSpec]),
-        couch_httpd:send_error(Req, {bad_request, Error})
-    end;
-% handles /_plugins/<pluginname>/<file>
-% serves <plugin_dir>/<pluginname>-<pluginversion>-<otpversion>-<couchdbversion>/<file>
-handle_req(#httpd{method='GET',path_parts=[_, Name0 | Path0]}=Req) ->
-    Name = ?b2l(Name0),
-    Path = lists:map(fun binary_to_list/1, Path0),
-    OTPRelease = erlang:system_info(otp_release),
-    PluginVersion = couch_config:get("plugins", Name),
-    CouchDBVersion = couch_server:get_version(short),
-    FullName = string:join([Name, PluginVersion, OTPRelease, CouchDBVersion], "-"),
-    FullPath = filename:join([FullName, "priv", "www", string:join(Path, "/")]) ++ "/",
-    ?LOG_DEBUG("Serving ~p from ~p", [FullPath, plugin_dir()]),
-    couch_httpd:serve_file(Req, FullPath, plugin_dir());
-handle_req(Req) ->
-    couch_httpd:send_method_not_allowed(Req, "POST").
-
-plugin_dir() ->
-  couch_config:get("couchdb", "plugin_dir").
-do_install(false, Plugin) ->
-    couch_plugins:install(Plugin);
-do_install(true, Plugin) ->
-    couch_plugins:uninstall(Plugin).
-
-parse_checksums(Checksums) ->
-    lists:map(fun({K, {V}}) ->
-        {binary_to_list(K), parse_checksums(V)};
-      ({K, V}) ->
-         {binary_to_list(K), binary_to_list(V)}
-    end, Checksums).

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_rel/ebin/couch_rel.app
----------------------------------------------------------------------
diff --git a/apps/couch_rel/ebin/couch_rel.app b/apps/couch_rel/ebin/couch_rel.app
deleted file mode 100644
index 2d207c9..0000000
--- a/apps/couch_rel/ebin/couch_rel.app
+++ /dev/null
@@ -1,18 +0,0 @@
-%% -*- tab-width: 4;erlang-indent-level: 4;indent-tabs-mode: nil -*-
-%% ex: ft=erlang ts=4 sw=4 et
-%%
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
-{application, couch_rel, [
-    {description,"couch extremely-early boot items"},
-        {modules, [etop_txt]}]}.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_rel/src/etop_txt.erl
----------------------------------------------------------------------
diff --git a/apps/couch_rel/src/etop_txt.erl b/apps/couch_rel/src/etop_txt.erl
deleted file mode 100644
index 031f5d8..0000000
--- a/apps/couch_rel/src/etop_txt.erl
+++ /dev/null
@@ -1,134 +0,0 @@
-%%
-%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2002-2009. All Rights Reserved.
-%%
-%% The contents of this file are subject to the Erlang Public License,
-%% Version 1.1, (the "License"); you may not use this file except in
-%% compliance with the License. You should have received a copy of the
-%% Erlang Public License along with this software. If not, it can be
-%% retrieved online at http://www.erlang.org/.
-%%
-%% Software distributed under the License is distributed on an "AS IS"
-%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
-%% the License for the specific language governing rights and limitations
-%% under the License.
-%%
-%% %CopyrightEnd%
-%%
--module(etop_txt).
--author('siri@erix.ericsson.se').
--author('scott@basho.com').
-
-%%-compile(export_all).
--export([init/1,stop/1]).
--export([do_update/3]).
-
-%%-include("etop.hrl").
--record(etop_proc_info,
-        {pid,
-         mem=0,
-         reds=0,
-         name,
-         runtime=0,
-         cf,
-         mq=0}).
--record(etop_info,
-        {now = {0, 0, 0},
-         n_procs = 0,
-         wall_clock = {0, 0},
-         runtime = {0, 0},
-         run_queue = 0,
-         alloc_areas = [],
-         memi = [{total, 0},
-                 {processes, 0},
-                 {ets, 0},
-                 {atom, 0},
-                 {code, 0},
-                 {binary, 0}],
-         procinfo = []
-        }).
-%%-include("etop_defs.hrl").
--define(SYSFORM,
-        " ~-72w~10s~n"
-        " Load:  cpu  ~8w               Memory:  total    ~8w    binary   ~8w~n"
-        "        procs~8w                        processes~8w    code     ~8w~n"
-        "        runq ~8w                        atom     ~8w    ets      ~8w~n").
--record(opts, {node=node(), port = 8415, accum = false, intv = 5000, lines = 10,
-               width = 700, height = 340, sort = runtime, tracing = on,
-               %% Other state information
-               out_mod=etop_gui, out_proc, server, host, tracer, store,
-               accum_tab, remote}).
-
--import(etop,[loadinfo/1,meminfo/2]).
--import(etop_gui,[formatmfa/1,to_list/1]).
-
--define(PROCFORM,"~-20w~-25s~8w~11w~11w~11w ~-40s~n").
-
-stop(Pid) -> Pid ! stop.
-
-init(Config) ->
-    loop(Config).
-
-loop(Config) ->
-    Info = do_update(Config),
-    receive
-	stop -> stopped;
-	{dump,Fd} -> do_update(Fd,Info,Config), loop(Config);
-	{config,_,Config1} -> loop(Config1)
-    after Config#opts.intv-500 -> loop(Config)
-    end.
-
-do_update(Config) ->
-    Info = etop:update(Config),
-    do_update(standard_io,Info,Config).
-
-do_update(Fd,Info,Config) ->
-    {Cpu,NProcs,RQ,Clock} = loadinfo(Info),
-    io:nl(Fd),
-    writedoubleline(Fd),
-    case Info#etop_info.memi of
-	undefined ->
-	    io:fwrite(Fd, " ~-72w~10s~n"
-		      " Load:  cpu  ~8w~n"
-		      "        procs~8w~n"
-		      "        runq ~8w~n",
-		      [Config#opts.node,Clock,
-		       Cpu,NProcs,RQ]);
-	Memi ->
-	    [Tot,Procs,Atom,Bin,Code,Ets] =
-		meminfo(Memi, [total,processes,atom,binary,code,ets]),
-	    io:fwrite(Fd, ?SYSFORM,
-		      [Config#opts.node,Clock,
-		       Cpu,Tot,Bin,
-		       NProcs,Procs,Code,
-		       RQ,Atom,Ets])
-    end,
-    io:nl(Fd),
-    writepinfo_header(Fd),
-    writesingleline(Fd),
-    writepinfo(Fd,Info#etop_info.procinfo),
-    %%writedoubleline(Fd),
-    %%io:nl(Fd),
-    Info.
-
-writepinfo_header(Fd) ->
-    io:fwrite(Fd,"Pid                 Name or Initial Func         Time       Reds     Memory       MsgQ Current Function~n",[]).
-
-writesingleline(Fd) ->
-    io:fwrite(Fd,"-------------------------------------------------------------------------------------------------------------------------------~n",[]).
-writedoubleline(Fd) ->
-    io:fwrite(Fd,"===============================================================================================================================~n",[]).
-
-writepinfo(Fd,[#etop_proc_info{pid=Pid,
-			       mem=Mem,
-			       reds=Reds,
-			       name=Name,
-			       runtime=Time,
-			       cf=MFA,
-			       mq=MQ}
-	       |T]) ->
-    io:fwrite(Fd,?PROCFORM,[Pid,to_list(Name),Time,Reds,Mem,MQ,formatmfa(MFA)]),
-    writepinfo(Fd,T);
-writepinfo(_Fd,[]) ->
-    ok.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_replicator/src/couch_replicator.app.src
----------------------------------------------------------------------
diff --git a/apps/couch_replicator/src/couch_replicator.app.src b/apps/couch_replicator/src/couch_replicator.app.src
deleted file mode 100644
index 3e71b3b..0000000
--- a/apps/couch_replicator/src/couch_replicator.app.src
+++ /dev/null
@@ -1,28 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
-{application, couch_replicator, [
-    {description, "CouchDB replicator"},
-    {vsn, "1.6.1"},
-    {modules, []},
-    {registered, [
-        couch_replicator_manager_sup,
-        couch_replicator_job_sup,
-        couch_replicator_sup
-    ]},
-    {applications, [kernel, stdlib, crypto, sasl, inets, oauth, ibrowse,
-                   couch]},
-
-    {mod, { couch_replicator_app, []}},
-    {env, []}
-]}.
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_replicator/src/couch_replicator.erl
----------------------------------------------------------------------
diff --git a/apps/couch_replicator/src/couch_replicator.erl b/apps/couch_replicator/src/couch_replicator.erl
deleted file mode 100644
index d470c8a..0000000
--- a/apps/couch_replicator/src/couch_replicator.erl
+++ /dev/null
@@ -1,965 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_replicator).
--behaviour(gen_server).
-
-% public API
--export([replicate/1]).
-
-% meant to be used only by the replicator database listener
--export([async_replicate/1]).
--export([cancel_replication/1]).
-
-% gen_server callbacks
--export([init/1, terminate/2, code_change/3]).
--export([handle_call/3, handle_cast/2, handle_info/2]).
-
--include_lib("couch/include/couch_db.hrl").
--include("couch_replicator_api_wrap.hrl").
--include("couch_replicator.hrl").
-
--import(couch_util, [
-    get_value/2,
-    get_value/3,
-    to_binary/1
-]).
-
--import(couch_replicator_utils, [
-    start_db_compaction_notifier/2,
-    stop_db_compaction_notifier/1
-]).
-
--record(rep_state, {
-    rep_details,
-    source_name,
-    target_name,
-    source,
-    target,
-    history,
-    checkpoint_history,
-    start_seq,
-    committed_seq,
-    current_through_seq,
-    seqs_in_progress = [],
-    highest_seq_done = {0, ?LOWEST_SEQ},
-    source_log,
-    target_log,
-    rep_starttime,
-    src_starttime,
-    tgt_starttime,
-    timer, % checkpoint timer
-    changes_queue,
-    changes_manager,
-    changes_reader,
-    workers,
-    stats = #rep_stats{},
-    session_id,
-    source_db_compaction_notifier = nil,
-    target_db_compaction_notifier = nil,
-    source_monitor = nil,
-    target_monitor = nil,
-    source_seq = nil,
-    use_checkpoints = true,
-    checkpoint_interval = 5000
-}).
-
-
-replicate(#rep{id = RepId, options = Options, user_ctx = UserCtx} = Rep) ->
-    case get_value(cancel, Options, false) of
-    true ->
-        case get_value(id, Options, nil) of
-        nil ->
-            cancel_replication(RepId);
-        RepId2 ->
-            cancel_replication(RepId2, UserCtx)
-        end;
-    false ->
-        {ok, Listener} = rep_result_listener(RepId),
-        Result = do_replication_loop(Rep),
-        couch_replicator_notifier:stop(Listener),
-        Result
-    end.
-
-
-do_replication_loop(#rep{id = {BaseId, Ext} = Id, options = Options} = Rep) ->
-    case async_replicate(Rep) of
-    {ok, _Pid} ->
-        case get_value(continuous, Options, false) of
-        true ->
-            {ok, {continuous, ?l2b(BaseId ++ Ext)}};
-        false ->
-            wait_for_result(Id)
-        end;
-    Error ->
-        Error
-    end.
-
-
-async_replicate(#rep{id = {BaseId, Ext}, source = Src, target = Tgt} = Rep) ->
-    RepChildId = BaseId ++ Ext,
-    Source = couch_replicator_api_wrap:db_uri(Src),
-    Target = couch_replicator_api_wrap:db_uri(Tgt),
-    Timeout = get_value(connection_timeout, Rep#rep.options),
-    ChildSpec = {
-        RepChildId,
-        {gen_server, start_link, [?MODULE, Rep, [{timeout, Timeout}]]},
-        temporary,
-        250,
-        worker,
-        [?MODULE]
-    },
-    % All these nested cases to attempt starting/restarting a replication child
-    % are ugly and not 100% race condition free. The following patch submission
-    % is a solution:
-    %
-    % http://erlang.2086793.n4.nabble.com/PATCH-supervisor-atomically-delete-child-spec-when-child-terminates-td3226098.html
-    %
-    case supervisor:start_child(couch_replicator_job_sup, ChildSpec) of
-    {ok, Pid} ->
-        ?LOG_INFO("starting new replication `~s` at ~p (`~s` -> `~s`)",
-            [RepChildId, Pid, Source, Target]),
-        {ok, Pid};
-    {error, already_present} ->
-        case supervisor:restart_child(couch_replicator_job_sup, RepChildId) of
-        {ok, Pid} ->
-            ?LOG_INFO("restarting replication `~s` at ~p (`~s` -> `~s`)",
-                [RepChildId, Pid, Source, Target]),
-            {ok, Pid};
-        {error, running} ->
-            %% this error occurs if multiple replicators are racing
-            %% each other to start and somebody else won. Just grab
-            %% the Pid by calling start_child again.
-            {error, {already_started, Pid}} =
-                supervisor:start_child(couch_replicator_job_sup, ChildSpec),
-            ?LOG_INFO("replication `~s` already running at ~p (`~s` -> `~s`)",
-                [RepChildId, Pid, Source, Target]),
-            {ok, Pid};
-        {error, {'EXIT', {badarg,
-            [{erlang, apply, [gen_server, start_link, undefined]} | _]}}} ->
-            % Clause to deal with a change in the supervisor module introduced
-            % in R14B02. For more details consult the thread at:
-            %     http://erlang.org/pipermail/erlang-bugs/2011-March/002273.html
-            _ = supervisor:delete_child(couch_replicator_job_sup, RepChildId),
-            async_replicate(Rep);
-        {error, _} = Error ->
-            Error
-        end;
-    {error, {already_started, Pid}} ->
-        ?LOG_INFO("replication `~s` already running at ~p (`~s` -> `~s`)",
-            [RepChildId, Pid, Source, Target]),
-        {ok, Pid};
-    {error, {Error, _}} ->
-        {error, Error}
-    end.
-
-
-rep_result_listener(RepId) ->
-    ReplyTo = self(),
-    {ok, _Listener} = couch_replicator_notifier:start_link(
-        fun({_, RepId2, _} = Ev) when RepId2 =:= RepId ->
-                ReplyTo ! Ev;
-            (_) ->
-                ok
-        end).
-
-
-wait_for_result(RepId) ->
-    receive
-    {finished, RepId, RepResult} ->
-        {ok, RepResult};
-    {error, RepId, Reason} ->
-        {error, Reason}
-    end.
-
-
-cancel_replication({BaseId, Extension}) ->
-    FullRepId = BaseId ++ Extension,
-    ?LOG_INFO("Canceling replication `~s`...", [FullRepId]),
-    case supervisor:terminate_child(couch_replicator_job_sup, FullRepId) of
-    ok ->
-        ?LOG_INFO("Replication `~s` canceled.", [FullRepId]),
-        case supervisor:delete_child(couch_replicator_job_sup, FullRepId) of
-            ok ->
-                {ok, {cancelled, ?l2b(FullRepId)}};
-            {error, not_found} ->
-                {ok, {cancelled, ?l2b(FullRepId)}};
-            Error ->
-                Error
-        end;
-    Error ->
-        ?LOG_ERROR("Error canceling replication `~s`: ~p", [FullRepId, Error]),
-        Error
-    end.
-
-cancel_replication(RepId, #user_ctx{name = Name, roles = Roles}) ->
-    case lists:member(<<"_admin">>, Roles) of
-    true ->
-        cancel_replication(RepId);
-    false ->
-        {BaseId, Ext} = RepId,
-        case lists:keysearch(
-            BaseId ++ Ext, 1, supervisor:which_children(couch_replicator_job_sup)) of
-        {value, {_, Pid, _, _}} when is_pid(Pid) ->
-            case (catch gen_server:call(Pid, get_details, infinity)) of
-            {ok, #rep{user_ctx = #user_ctx{name = Name}}} ->
-                cancel_replication(RepId);
-            {ok, _} ->
-                throw({unauthorized,
-                    <<"Can't cancel a replication triggered by another user">>});
-            {'EXIT', {noproc, {gen_server, call, _}}} ->
-                {error, not_found};
-            Error ->
-                throw(Error)
-            end;
-        _ ->
-            {error, not_found}
-        end
-    end.
-
-init(InitArgs) ->
-    try
-        do_init(InitArgs)
-    catch
-    throw:{unauthorized, DbUri} ->
-        {stop, {unauthorized,
-            <<"unauthorized to access or create database ", DbUri/binary>>}};
-    throw:{db_not_found, DbUri} ->
-        {stop, {db_not_found, <<"could not open ", DbUri/binary>>}};
-    throw:Error ->
-        {stop, Error}
-    end.
-
-do_init(#rep{options = Options, id = {BaseId, Ext}} = Rep) ->
-    process_flag(trap_exit, true),
-
-    #rep_state{
-        source = Source,
-        target = Target,
-        source_name = SourceName,
-        target_name = TargetName,
-        start_seq = {_Ts, StartSeq},
-        source_seq = SourceCurSeq,
-        committed_seq = {_, CommittedSeq},
-        checkpoint_interval = CheckpointInterval
-    } = State = init_state(Rep),
-
-    NumWorkers = get_value(worker_processes, Options),
-    BatchSize = get_value(worker_batch_size, Options),
-    {ok, ChangesQueue} = couch_work_queue:new([
-        {max_items, BatchSize * NumWorkers * 2},
-        {max_size, 100 * 1024 * NumWorkers}
-    ]),
-    % This starts the _changes reader process. It adds the changes from
-    % the source db to the ChangesQueue.
-    ChangesReader = spawn_changes_reader(StartSeq, Source, ChangesQueue, Options),
-    % Changes manager - responsible for dequeing batches from the changes queue
-    % and deliver them to the worker processes.
-    ChangesManager = spawn_changes_manager(self(), ChangesQueue, BatchSize),
-    % This starts the worker processes. They ask the changes queue manager for a
-    % a batch of _changes rows to process -> check which revs are missing in the
-    % target, and for the missing ones, it copies them from the source to the target.
-    MaxConns = get_value(http_connections, Options),
-    Workers = lists:map(
-        fun(_) ->
-            {ok, Pid} = couch_replicator_worker:start_link(
-                self(), Source, Target, ChangesManager, MaxConns),
-            Pid
-        end,
-        lists:seq(1, NumWorkers)),
-
-    couch_task_status:add_task([
-        {type, replication},
-        {replication_id, ?l2b(BaseId ++ Ext)},
-        {doc_id, Rep#rep.doc_id},
-        {source, ?l2b(SourceName)},
-        {target, ?l2b(TargetName)},
-        {continuous, get_value(continuous, Options, false)},
-        {revisions_checked, 0},
-        {missing_revisions_found, 0},
-        {docs_read, 0},
-        {docs_written, 0},
-        {doc_write_failures, 0},
-        {source_seq, SourceCurSeq},
-        {checkpointed_source_seq, CommittedSeq},
-        {progress, 0},
-        {checkpoint_interval, CheckpointInterval}
-    ]),
-    couch_task_status:set_update_frequency(1000),
-
-    % Until OTP R14B03:
-    %
-    % Restarting a temporary supervised child implies that the original arguments
-    % (#rep{} record) specified in the MFA component of the supervisor
-    % child spec will always be used whenever the child is restarted.
-    % This implies the same replication performance tunning parameters will
-    % always be used. The solution is to delete the child spec (see
-    % cancel_replication/1) and then start the replication again, but this is
-    % unfortunately not immune to race conditions.
-
-    ?LOG_INFO("Replication `~p` is using:~n"
-        "~c~p worker processes~n"
-        "~ca worker batch size of ~p~n"
-        "~c~p HTTP connections~n"
-        "~ca connection timeout of ~p milliseconds~n"
-        "~c~p retries per request~n"
-        "~csocket options are: ~s~s",
-        [BaseId ++ Ext, $\t, NumWorkers, $\t, BatchSize, $\t,
-            MaxConns, $\t, get_value(connection_timeout, Options),
-            $\t, get_value(retries, Options),
-            $\t, io_lib:format("~p", [get_value(socket_options, Options)]),
-            case StartSeq of
-            ?LOWEST_SEQ ->
-                "";
-            _ ->
-                io_lib:format("~n~csource start sequence ~p", [$\t, StartSeq])
-            end]),
-
-    ?LOG_DEBUG("Worker pids are: ~p", [Workers]),
-
-    couch_replicator_manager:replication_started(Rep),
-
-    {ok, State#rep_state{
-            changes_queue = ChangesQueue,
-            changes_manager = ChangesManager,
-            changes_reader = ChangesReader,
-            workers = Workers
-        }
-    }.
-
-
-handle_info(shutdown, St) ->
-    {stop, shutdown, St};
-
-handle_info({'DOWN', Ref, _, _, Why}, #rep_state{source_monitor = Ref} = St) ->
-    ?LOG_ERROR("Source database is down. Reason: ~p", [Why]),
-    {stop, source_db_down, St};
-
-handle_info({'DOWN', Ref, _, _, Why}, #rep_state{target_monitor = Ref} = St) ->
-    ?LOG_ERROR("Target database is down. Reason: ~p", [Why]),
-    {stop, target_db_down, St};
-
-handle_info({'EXIT', Pid, normal}, #rep_state{changes_reader=Pid} = State) ->
-    {noreply, State};
-
-handle_info({'EXIT', Pid, Reason}, #rep_state{changes_reader=Pid} = State) ->
-    ?LOG_ERROR("ChangesReader process died with reason: ~p", [Reason]),
-    {stop, changes_reader_died, cancel_timer(State)};
-
-handle_info({'EXIT', Pid, normal}, #rep_state{changes_manager = Pid} = State) ->
-    {noreply, State};
-
-handle_info({'EXIT', Pid, Reason}, #rep_state{changes_manager = Pid} = State) ->
-    ?LOG_ERROR("ChangesManager process died with reason: ~p", [Reason]),
-    {stop, changes_manager_died, cancel_timer(State)};
-
-handle_info({'EXIT', Pid, normal}, #rep_state{changes_queue=Pid} = State) ->
-    {noreply, State};
-
-handle_info({'EXIT', Pid, Reason}, #rep_state{changes_queue=Pid} = State) ->
-    ?LOG_ERROR("ChangesQueue process died with reason: ~p", [Reason]),
-    {stop, changes_queue_died, cancel_timer(State)};
-
-handle_info({'EXIT', Pid, normal}, #rep_state{workers = Workers} = State) ->
-    case Workers -- [Pid] of
-    Workers ->
-        {stop, {unknown_process_died, Pid, normal}, State};
-    [] ->
-        catch unlink(State#rep_state.changes_manager),
-        catch exit(State#rep_state.changes_manager, kill),
-        do_last_checkpoint(State);
-    Workers2 ->
-        {noreply, State#rep_state{workers = Workers2}}
-    end;
-
-handle_info({'EXIT', Pid, Reason}, #rep_state{workers = Workers} = State) ->
-    State2 = cancel_timer(State),
-    case lists:member(Pid, Workers) of
-    false ->
-        {stop, {unknown_process_died, Pid, Reason}, State2};
-    true ->
-        ?LOG_ERROR("Worker ~p died with reason: ~p", [Pid, Reason]),
-        {stop, {worker_died, Pid, Reason}, State2}
-    end.
-
-
-handle_call(get_details, _From, #rep_state{rep_details = Rep} = State) ->
-    {reply, {ok, Rep}, State};
-
-handle_call({add_stats, Stats}, From, State) ->
-    gen_server:reply(From, ok),
-    NewStats = couch_replicator_utils:sum_stats(State#rep_state.stats, Stats),
-    {noreply, State#rep_state{stats = NewStats}};
-
-handle_call({report_seq_done, Seq, StatsInc}, From,
-    #rep_state{seqs_in_progress = SeqsInProgress, highest_seq_done = HighestDone,
-        current_through_seq = ThroughSeq, stats = Stats} = State) ->
-    gen_server:reply(From, ok),
-    {NewThroughSeq0, NewSeqsInProgress} = case SeqsInProgress of
-    [Seq | Rest] ->
-        {Seq, Rest};
-    [_ | _] ->
-        {ThroughSeq, ordsets:del_element(Seq, SeqsInProgress)}
-    end,
-    NewHighestDone = lists:max([HighestDone, Seq]),
-    NewThroughSeq = case NewSeqsInProgress of
-    [] ->
-        lists:max([NewThroughSeq0, NewHighestDone]);
-    _ ->
-        NewThroughSeq0
-    end,
-    ?LOG_DEBUG("Worker reported seq ~p, through seq was ~p, "
-        "new through seq is ~p, highest seq done was ~p, "
-        "new highest seq done is ~p~n"
-        "Seqs in progress were: ~p~nSeqs in progress are now: ~p",
-        [Seq, ThroughSeq, NewThroughSeq, HighestDone,
-            NewHighestDone, SeqsInProgress, NewSeqsInProgress]),
-    SourceCurSeq = source_cur_seq(State),
-    NewState = State#rep_state{
-        stats = couch_replicator_utils:sum_stats(Stats, StatsInc),
-        current_through_seq = NewThroughSeq,
-        seqs_in_progress = NewSeqsInProgress,
-        highest_seq_done = NewHighestDone,
-        source_seq = SourceCurSeq
-    },
-    update_task(NewState),
-    {noreply, NewState}.
-
-
-handle_cast({db_compacted, DbName},
-    #rep_state{source = #db{name = DbName} = Source} = State) ->
-    {ok, NewSource} = couch_db:reopen(Source),
-    {noreply, State#rep_state{source = NewSource}};
-
-handle_cast({db_compacted, DbName},
-    #rep_state{target = #db{name = DbName} = Target} = State) ->
-    {ok, NewTarget} = couch_db:reopen(Target),
-    {noreply, State#rep_state{target = NewTarget}};
-
-handle_cast(checkpoint, State) ->
-    case do_checkpoint(State) of
-    {ok, NewState} ->
-        {noreply, NewState#rep_state{timer = start_timer(State)}};
-    Error ->
-        {stop, Error, State}
-    end;
-
-handle_cast({report_seq, Seq},
-    #rep_state{seqs_in_progress = SeqsInProgress} = State) ->
-    NewSeqsInProgress = ordsets:add_element(Seq, SeqsInProgress),
-    {noreply, State#rep_state{seqs_in_progress = NewSeqsInProgress}}.
-
-
-code_change(OldVsn, OldState, Extra) when tuple_size(OldState) =:= 30 ->
-    code_change(OldVsn, erlang:append_element(OldState, true), Extra);
-code_change(OldVsn, OldState, Extra) when tuple_size(OldState) =:= 31 ->
-    code_change(OldVsn, erlang:append_element(OldState, 5000), Extra);
-code_change(_OldVsn, #rep_state{}=State, _Extra) ->
-    {ok, State}.
-
-
-terminate(normal, #rep_state{rep_details = #rep{id = RepId} = Rep,
-    checkpoint_history = CheckpointHistory} = State) ->
-    terminate_cleanup(State),
-    couch_replicator_notifier:notify({finished, RepId, CheckpointHistory}),
-    couch_replicator_manager:replication_completed(Rep, rep_stats(State));
-
-terminate(shutdown, #rep_state{rep_details = #rep{id = RepId}} = State) ->
-    % cancelled replication throught ?MODULE:cancel_replication/1
-    couch_replicator_notifier:notify({error, RepId, <<"cancelled">>}),
-    terminate_cleanup(State);
-
-terminate(Reason, State) ->
-    #rep_state{
-        source_name = Source,
-        target_name = Target,
-        rep_details = #rep{id = {BaseId, Ext} = RepId} = Rep
-    } = State,
-    ?LOG_ERROR("Replication `~s` (`~s` -> `~s`) failed: ~s",
-        [BaseId ++ Ext, Source, Target, to_binary(Reason)]),
-    terminate_cleanup(State),
-    couch_replicator_notifier:notify({error, RepId, Reason}),
-    couch_replicator_manager:replication_error(Rep, Reason).
-
-
-terminate_cleanup(State) ->
-    update_task(State),
-    stop_db_compaction_notifier(State#rep_state.source_db_compaction_notifier),
-    stop_db_compaction_notifier(State#rep_state.target_db_compaction_notifier),
-    couch_replicator_api_wrap:db_close(State#rep_state.source),
-    couch_replicator_api_wrap:db_close(State#rep_state.target).
-
-
-do_last_checkpoint(#rep_state{seqs_in_progress = [],
-    highest_seq_done = {_Ts, ?LOWEST_SEQ}} = State) ->
-    {stop, normal, cancel_timer(State)};
-do_last_checkpoint(#rep_state{seqs_in_progress = [],
-    highest_seq_done = Seq} = State) ->
-    case do_checkpoint(State#rep_state{current_through_seq = Seq}) of
-    {ok, NewState} ->
-        {stop, normal, cancel_timer(NewState)};
-    Error ->
-        {stop, Error, State}
-    end.
-
-
-start_timer(State) ->
-    After = State#rep_state.checkpoint_interval,
-    case timer:apply_after(After, gen_server, cast, [self(), checkpoint]) of
-    {ok, Ref} ->
-        Ref;
-    Error ->
-        ?LOG_ERROR("Replicator, error scheduling checkpoint:  ~p", [Error]),
-        nil
-    end.
-
-
-cancel_timer(#rep_state{timer = nil} = State) ->
-    State;
-cancel_timer(#rep_state{timer = Timer} = State) ->
-    {ok, cancel} = timer:cancel(Timer),
-    State#rep_state{timer = nil}.
-
-
-init_state(Rep) ->
-    #rep{
-        source = Src, target = Tgt,
-        options = Options, user_ctx = UserCtx
-    } = Rep,
-    {ok, Source} = couch_replicator_api_wrap:db_open(Src, [{user_ctx, UserCtx}]),
-    {ok, Target} = couch_replicator_api_wrap:db_open(Tgt, [{user_ctx, UserCtx}],
-        get_value(create_target, Options, false)),
-
-    {ok, SourceInfo} = couch_replicator_api_wrap:get_db_info(Source),
-    {ok, TargetInfo} = couch_replicator_api_wrap:get_db_info(Target),
-
-    [SourceLog, TargetLog] = find_replication_logs([Source, Target], Rep),
-
-    {StartSeq0, History} = compare_replication_logs(SourceLog, TargetLog),
-    StartSeq1 = get_value(since_seq, Options, StartSeq0),
-    StartSeq = {0, StartSeq1},
-    #doc{body={CheckpointHistory}} = SourceLog,
-    State = #rep_state{
-        rep_details = Rep,
-        source_name = couch_replicator_api_wrap:db_uri(Source),
-        target_name = couch_replicator_api_wrap:db_uri(Target),
-        source = Source,
-        target = Target,
-        history = History,
-        checkpoint_history = {[{<<"no_changes">>, true}| CheckpointHistory]},
-        start_seq = StartSeq,
-        current_through_seq = StartSeq,
-        committed_seq = StartSeq,
-        source_log = SourceLog,
-        target_log = TargetLog,
-        rep_starttime = couch_util:rfc1123_date(),
-        src_starttime = get_value(<<"instance_start_time">>, SourceInfo),
-        tgt_starttime = get_value(<<"instance_start_time">>, TargetInfo),
-        session_id = couch_uuids:random(),
-        source_db_compaction_notifier =
-            start_db_compaction_notifier(Source, self()),
-        target_db_compaction_notifier =
-            start_db_compaction_notifier(Target, self()),
-        source_monitor = db_monitor(Source),
-        target_monitor = db_monitor(Target),
-        source_seq = get_value(<<"update_seq">>, SourceInfo, ?LOWEST_SEQ),
-        use_checkpoints = get_value(use_checkpoints, Options, true),
-        checkpoint_interval = get_value(checkpoint_interval, Options, 5000)
-    },
-    State#rep_state{timer = start_timer(State)}.
-
-
-find_replication_logs(DbList, #rep{id = {BaseId, _}} = Rep) ->
-    LogId = ?l2b(?LOCAL_DOC_PREFIX ++ BaseId),
-    fold_replication_logs(DbList, ?REP_ID_VERSION, LogId, LogId, Rep, []).
-
-
-fold_replication_logs([], _Vsn, _LogId, _NewId, _Rep, Acc) ->
-    lists:reverse(Acc);
-
-fold_replication_logs([Db | Rest] = Dbs, Vsn, LogId, NewId, Rep, Acc) ->
-    case couch_replicator_api_wrap:open_doc(Db, LogId, [ejson_body]) of
-    {error, <<"not_found">>} when Vsn > 1 ->
-        OldRepId = couch_replicator_utils:replication_id(Rep, Vsn - 1),
-        fold_replication_logs(Dbs, Vsn - 1,
-            ?l2b(?LOCAL_DOC_PREFIX ++ OldRepId), NewId, Rep, Acc);
-    {error, <<"not_found">>} ->
-        fold_replication_logs(
-            Rest, ?REP_ID_VERSION, NewId, NewId, Rep, [#doc{id = NewId} | Acc]);
-    {ok, Doc} when LogId =:= NewId ->
-        fold_replication_logs(
-            Rest, ?REP_ID_VERSION, NewId, NewId, Rep, [Doc | Acc]);
-    {ok, Doc} ->
-        MigratedLog = #doc{id = NewId, body = Doc#doc.body},
-        fold_replication_logs(
-            Rest, ?REP_ID_VERSION, NewId, NewId, Rep, [MigratedLog | Acc])
-    end.
-
-
-spawn_changes_reader(StartSeq, #httpdb{} = Db, ChangesQueue, Options) ->
-    spawn_link(fun() ->
-        put(last_seq, StartSeq),
-        put(retries_left, Db#httpdb.retries),
-        read_changes(StartSeq, Db#httpdb{retries = 0}, ChangesQueue, Options)
-    end);
-spawn_changes_reader(StartSeq, Db, ChangesQueue, Options) ->
-    spawn_link(fun() ->
-        read_changes(StartSeq, Db, ChangesQueue, Options)
-    end).
-
-read_changes(StartSeq, Db, ChangesQueue, Options) ->
-    try
-        couch_replicator_api_wrap:changes_since(Db, all_docs, StartSeq,
-            fun(#doc_info{high_seq = Seq, id = Id} = DocInfo) ->
-                case Id of
-                <<>> ->
-                    % Previous CouchDB releases had a bug which allowed a doc
-                    % with an empty ID to be inserted into databases. Such doc
-                    % is impossible to GET.
-                    ?LOG_ERROR("Replicator: ignoring document with empty ID in "
-                        "source database `~s` (_changes sequence ~p)",
-                        [couch_replicator_api_wrap:db_uri(Db), Seq]);
-                _ ->
-                    ok = couch_work_queue:queue(ChangesQueue, DocInfo)
-                end,
-                put(last_seq, Seq)
-            end, Options),
-        couch_work_queue:close(ChangesQueue)
-    catch exit:{http_request_failed, _, _, _} = Error ->
-        case get(retries_left) of
-        N when N > 0 ->
-            put(retries_left, N - 1),
-            LastSeq = get(last_seq),
-            Db2 = case LastSeq of
-            StartSeq ->
-                ?LOG_INFO("Retrying _changes request to source database ~s"
-                    " with since=~p in ~p seconds",
-                    [couch_replicator_api_wrap:db_uri(Db), LastSeq, Db#httpdb.wait / 1000]),
-                ok = timer:sleep(Db#httpdb.wait),
-                Db#httpdb{wait = 2 * Db#httpdb.wait};
-            _ ->
-                ?LOG_INFO("Retrying _changes request to source database ~s"
-                    " with since=~p", [couch_replicator_api_wrap:db_uri(Db), LastSeq]),
-                Db
-            end,
-            read_changes(LastSeq, Db2, ChangesQueue, Options);
-        _ ->
-            exit(Error)
-        end
-    end.
-
-
-spawn_changes_manager(Parent, ChangesQueue, BatchSize) ->
-    spawn_link(fun() ->
-        changes_manager_loop_open(Parent, ChangesQueue, BatchSize, 1)
-    end).
-
-changes_manager_loop_open(Parent, ChangesQueue, BatchSize, Ts) ->
-    receive
-    {get_changes, From} ->
-        case couch_work_queue:dequeue(ChangesQueue, BatchSize) of
-        closed ->
-            From ! {closed, self()};
-        {ok, Changes} ->
-            #doc_info{high_seq = Seq} = lists:last(Changes),
-            ReportSeq = {Ts, Seq},
-            ok = gen_server:cast(Parent, {report_seq, ReportSeq}),
-            From ! {changes, self(), Changes, ReportSeq}
-        end,
-        changes_manager_loop_open(Parent, ChangesQueue, BatchSize, Ts + 1)
-    end.
-
-
-do_checkpoint(#rep_state{use_checkpoints=false} = State) ->
-    NewState = State#rep_state{checkpoint_history = {[{<<"use_checkpoints">>, false}]} },
-    {ok, NewState};
-do_checkpoint(#rep_state{current_through_seq=Seq, committed_seq=Seq} = State) ->
-    SourceCurSeq = source_cur_seq(State),
-    NewState = State#rep_state{source_seq = SourceCurSeq},
-    update_task(NewState),
-    {ok, NewState};
-do_checkpoint(State) ->
-    #rep_state{
-        source_name=SourceName,
-        target_name=TargetName,
-        source = Source,
-        target = Target,
-        history = OldHistory,
-        start_seq = {_, StartSeq},
-        current_through_seq = {_Ts, NewSeq} = NewTsSeq,
-        source_log = SourceLog,
-        target_log = TargetLog,
-        rep_starttime = ReplicationStartTime,
-        src_starttime = SrcInstanceStartTime,
-        tgt_starttime = TgtInstanceStartTime,
-        stats = Stats,
-        rep_details = #rep{options = Options},
-        session_id = SessionId
-    } = State,
-    case commit_to_both(Source, Target) of
-    {source_error, Reason} ->
-         {checkpoint_commit_failure,
-             <<"Failure on source commit: ", (to_binary(Reason))/binary>>};
-    {target_error, Reason} ->
-         {checkpoint_commit_failure,
-             <<"Failure on target commit: ", (to_binary(Reason))/binary>>};
-    {SrcInstanceStartTime, TgtInstanceStartTime} ->
-        ?LOG_INFO("recording a checkpoint for `~s` -> `~s` at source update_seq ~p",
-            [SourceName, TargetName, NewSeq]),
-        StartTime = ?l2b(ReplicationStartTime),
-        EndTime = ?l2b(couch_util:rfc1123_date()),
-        NewHistoryEntry = {[
-            {<<"session_id">>, SessionId},
-            {<<"start_time">>, StartTime},
-            {<<"end_time">>, EndTime},
-            {<<"start_last_seq">>, StartSeq},
-            {<<"end_last_seq">>, NewSeq},
-            {<<"recorded_seq">>, NewSeq},
-            {<<"missing_checked">>, Stats#rep_stats.missing_checked},
-            {<<"missing_found">>, Stats#rep_stats.missing_found},
-            {<<"docs_read">>, Stats#rep_stats.docs_read},
-            {<<"docs_written">>, Stats#rep_stats.docs_written},
-            {<<"doc_write_failures">>, Stats#rep_stats.doc_write_failures}
-        ]},
-        BaseHistory = [
-            {<<"session_id">>, SessionId},
-            {<<"source_last_seq">>, NewSeq},
-            {<<"replication_id_version">>, ?REP_ID_VERSION}
-        ] ++ case get_value(doc_ids, Options) of
-        undefined ->
-            [];
-        _DocIds ->
-            % backwards compatibility with the result of a replication by
-            % doc IDs in versions 0.11.x and 1.0.x
-            % TODO: deprecate (use same history format, simplify code)
-            [
-                {<<"start_time">>, StartTime},
-                {<<"end_time">>, EndTime},
-                {<<"docs_read">>, Stats#rep_stats.docs_read},
-                {<<"docs_written">>, Stats#rep_stats.docs_written},
-                {<<"doc_write_failures">>, Stats#rep_stats.doc_write_failures}
-            ]
-        end,
-        % limit history to 50 entries
-        NewRepHistory = {
-            BaseHistory ++
-            [{<<"history">>, lists:sublist([NewHistoryEntry | OldHistory], 50)}]
-        },
-
-        try
-            {SrcRevPos, SrcRevId} = update_checkpoint(
-                Source, SourceLog#doc{body = NewRepHistory}, source),
-            {TgtRevPos, TgtRevId} = update_checkpoint(
-                Target, TargetLog#doc{body = NewRepHistory}, target),
-            SourceCurSeq = source_cur_seq(State),
-            NewState = State#rep_state{
-                source_seq = SourceCurSeq,
-                checkpoint_history = NewRepHistory,
-                committed_seq = NewTsSeq,
-                source_log = SourceLog#doc{revs={SrcRevPos, [SrcRevId]}},
-                target_log = TargetLog#doc{revs={TgtRevPos, [TgtRevId]}}
-            },
-            update_task(NewState),
-            {ok, NewState}
-        catch throw:{checkpoint_commit_failure, _} = Failure ->
-            Failure
-        end;
-    {SrcInstanceStartTime, _NewTgtInstanceStartTime} ->
-        {checkpoint_commit_failure, <<"Target database out of sync. "
-            "Try to increase max_dbs_open at the target's server.">>};
-    {_NewSrcInstanceStartTime, TgtInstanceStartTime} ->
-        {checkpoint_commit_failure, <<"Source database out of sync. "
-            "Try to increase max_dbs_open at the source's server.">>};
-    {_NewSrcInstanceStartTime, _NewTgtInstanceStartTime} ->
-        {checkpoint_commit_failure, <<"Source and target databases out of "
-            "sync. Try to increase max_dbs_open at both servers.">>}
-    end.
-
-
-update_checkpoint(Db, Doc, DbType) ->
-    try
-        update_checkpoint(Db, Doc)
-    catch throw:{checkpoint_commit_failure, Reason} ->
-        throw({checkpoint_commit_failure,
-            <<"Error updating the ", (to_binary(DbType))/binary,
-                " checkpoint document: ", (to_binary(Reason))/binary>>})
-    end.
-
-update_checkpoint(Db, #doc{id = LogId, body = LogBody} = Doc) ->
-    try
-        case couch_replicator_api_wrap:update_doc(Db, Doc, [delay_commit]) of
-        {ok, PosRevId} ->
-            PosRevId;
-        {error, Reason} ->
-            throw({checkpoint_commit_failure, Reason})
-        end
-    catch throw:conflict ->
-        case (catch couch_replicator_api_wrap:open_doc(Db, LogId, [ejson_body])) of
-        {ok, #doc{body = LogBody, revs = {Pos, [RevId | _]}}} ->
-            % This means that we were able to update successfully the
-            % checkpoint doc in a previous attempt but we got a connection
-            % error (timeout for e.g.) before receiving the success response.
-            % Therefore the request was retried and we got a conflict, as the
-            % revision we sent is not the current one.
-            % We confirm this by verifying the doc body we just got is the same
-            % that we have just sent.
-            {Pos, RevId};
-        _ ->
-            throw({checkpoint_commit_failure, conflict})
-        end
-    end.
-
-
-commit_to_both(Source, Target) ->
-    % commit the src async
-    ParentPid = self(),
-    SrcCommitPid = spawn_link(
-        fun() ->
-            Result = (catch couch_replicator_api_wrap:ensure_full_commit(Source)),
-            ParentPid ! {self(), Result}
-        end),
-
-    % commit tgt sync
-    TargetResult = (catch couch_replicator_api_wrap:ensure_full_commit(Target)),
-
-    SourceResult = receive
-    {SrcCommitPid, Result} ->
-        unlink(SrcCommitPid),
-        receive {'EXIT', SrcCommitPid, _} -> ok after 0 -> ok end,
-        Result;
-    {'EXIT', SrcCommitPid, Reason} ->
-        {error, Reason}
-    end,
-    case TargetResult of
-    {ok, TargetStartTime} ->
-        case SourceResult of
-        {ok, SourceStartTime} ->
-            {SourceStartTime, TargetStartTime};
-        SourceError ->
-            {source_error, SourceError}
-        end;
-    TargetError ->
-        {target_error, TargetError}
-    end.
-
-
-compare_replication_logs(SrcDoc, TgtDoc) ->
-    #doc{body={RepRecProps}} = SrcDoc,
-    #doc{body={RepRecPropsTgt}} = TgtDoc,
-    case get_value(<<"session_id">>, RepRecProps) ==
-            get_value(<<"session_id">>, RepRecPropsTgt) of
-    true ->
-        % if the records have the same session id,
-        % then we have a valid replication history
-        OldSeqNum = get_value(<<"source_last_seq">>, RepRecProps, ?LOWEST_SEQ),
-        OldHistory = get_value(<<"history">>, RepRecProps, []),
-        {OldSeqNum, OldHistory};
-    false ->
-        SourceHistory = get_value(<<"history">>, RepRecProps, []),
-        TargetHistory = get_value(<<"history">>, RepRecPropsTgt, []),
-        ?LOG_INFO("Replication records differ. "
-                "Scanning histories to find a common ancestor.", []),
-        ?LOG_DEBUG("Record on source:~p~nRecord on target:~p~n",
-                [RepRecProps, RepRecPropsTgt]),
-        compare_rep_history(SourceHistory, TargetHistory)
-    end.
-
-compare_rep_history(S, T) when S =:= [] orelse T =:= [] ->
-    ?LOG_INFO("no common ancestry -- performing full replication", []),
-    {?LOWEST_SEQ, []};
-compare_rep_history([{S} | SourceRest], [{T} | TargetRest] = Target) ->
-    SourceId = get_value(<<"session_id">>, S),
-    case has_session_id(SourceId, Target) of
-    true ->
-        RecordSeqNum = get_value(<<"recorded_seq">>, S, ?LOWEST_SEQ),
-        ?LOG_INFO("found a common replication record with source_seq ~p",
-            [RecordSeqNum]),
-        {RecordSeqNum, SourceRest};
-    false ->
-        TargetId = get_value(<<"session_id">>, T),
-        case has_session_id(TargetId, SourceRest) of
-        true ->
-            RecordSeqNum = get_value(<<"recorded_seq">>, T, ?LOWEST_SEQ),
-            ?LOG_INFO("found a common replication record with source_seq ~p",
-                [RecordSeqNum]),
-            {RecordSeqNum, TargetRest};
-        false ->
-            compare_rep_history(SourceRest, TargetRest)
-        end
-    end.
-
-
-has_session_id(_SessionId, []) ->
-    false;
-has_session_id(SessionId, [{Props} | Rest]) ->
-    case get_value(<<"session_id">>, Props, nil) of
-    SessionId ->
-        true;
-    _Else ->
-        has_session_id(SessionId, Rest)
-    end.
-
-
-db_monitor(#db{} = Db) ->
-    couch_db:monitor(Db);
-db_monitor(_HttpDb) ->
-    nil.
-
-
-source_cur_seq(#rep_state{source = #httpdb{} = Db, source_seq = Seq}) ->
-    case (catch couch_replicator_api_wrap:get_db_info(Db#httpdb{retries = 3})) of
-    {ok, Info} ->
-        get_value(<<"update_seq">>, Info, Seq);
-    _ ->
-        Seq
-    end;
-source_cur_seq(#rep_state{source = Db, source_seq = Seq}) ->
-    {ok, Info} = couch_replicator_api_wrap:get_db_info(Db),
-    get_value(<<"update_seq">>, Info, Seq).
-
-
-update_task(State) ->
-    #rep_state{
-        current_through_seq = {_, CurSeq},
-        source_seq = SourceCurSeq
-    } = State,
-    couch_task_status:update(
-        rep_stats(State) ++ [
-        {source_seq, SourceCurSeq},
-        case is_number(CurSeq) andalso is_number(SourceCurSeq) of
-        true ->
-            case SourceCurSeq of
-            0 ->
-                {progress, 0};
-            _ ->
-                {progress, (CurSeq * 100) div SourceCurSeq}
-            end;
-        false ->
-            {progress, null}
-        end
-    ]).
-
-
-rep_stats(State) ->
-    #rep_state{
-        committed_seq = {_, CommittedSeq},
-        stats = Stats
-    } = State,
-    [
-        {revisions_checked, Stats#rep_stats.missing_checked},
-        {missing_revisions_found, Stats#rep_stats.missing_found},
-        {docs_read, Stats#rep_stats.docs_read},
-        {docs_written, Stats#rep_stats.docs_written},
-        {doc_write_failures, Stats#rep_stats.doc_write_failures},
-        {checkpointed_source_seq, CommittedSeq}
-    ].
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_replicator/src/couch_replicator.hrl
----------------------------------------------------------------------
diff --git a/apps/couch_replicator/src/couch_replicator.hrl b/apps/couch_replicator/src/couch_replicator.hrl
deleted file mode 100644
index 018aa4b..0000000
--- a/apps/couch_replicator/src/couch_replicator.hrl
+++ /dev/null
@@ -1,30 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--define(REP_ID_VERSION, 3).
-
--record(rep, {
-    id,
-    source,
-    target,
-    options,
-    user_ctx,
-    doc_id
-}).
-
--record(rep_stats, {
-    missing_checked = 0,
-    missing_found = 0,
-    docs_read = 0,
-    docs_written = 0,
-    doc_write_failures = 0
-}).


[16/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/js/libs/d3.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/js/libs/d3.js b/apps/fauxton/assets/js/libs/d3.js
deleted file mode 100644
index 44fc0b0..0000000
--- a/apps/fauxton/assets/js/libs/d3.js
+++ /dev/null
@@ -1,7026 +0,0 @@
-(function() {
-  function d3_class(ctor, properties) {
-    try {
-      for (var key in properties) {
-        Object.defineProperty(ctor.prototype, key, {
-          value: properties[key],
-          enumerable: false
-        });
-      }
-    } catch (e) {
-      ctor.prototype = properties;
-    }
-  }
-  function d3_arrayCopy(pseudoarray) {
-    var i = -1, n = pseudoarray.length, array = [];
-    while (++i < n) array.push(pseudoarray[i]);
-    return array;
-  }
-  function d3_arraySlice(pseudoarray) {
-    return Array.prototype.slice.call(pseudoarray);
-  }
-  function d3_Map() {}
-  function d3_identity(d) {
-    return d;
-  }
-  function d3_this() {
-    return this;
-  }
-  function d3_true() {
-    return true;
-  }
-  function d3_functor(v) {
-    return typeof v === "function" ? v : function() {
-      return v;
-    };
-  }
-  function d3_rebind(target, source, method) {
-    return function() {
-      var value = method.apply(source, arguments);
-      return arguments.length ? target : value;
-    };
-  }
-  function d3_number(x) {
-    return x != null && !isNaN(x);
-  }
-  function d3_zipLength(d) {
-    return d.length;
-  }
-  function d3_splitter(d) {
-    return d == null;
-  }
-  function d3_collapse(s) {
-    return s.trim().replace(/\s+/g, " ");
-  }
-  function d3_range_integerScale(x) {
-    var k = 1;
-    while (x * k % 1) k *= 10;
-    return k;
-  }
-  function d3_dispatch() {}
-  function d3_dispatch_event(dispatch) {
-    function event() {
-      var z = listeners, i = -1, n = z.length, l;
-      while (++i < n) if (l = z[i].on) l.apply(this, arguments);
-      return dispatch;
-    }
-    var listeners = [], listenerByName = new d3_Map;
-    event.on = function(name, listener) {
-      var l = listenerByName.get(name), i;
-      if (arguments.length < 2) return l && l.on;
-      if (l) {
-        l.on = null;
-        listeners = listeners.slice(0, i = listeners.indexOf(l)).concat(listeners.slice(i + 1));
-        listenerByName.remove(name);
-      }
-      if (listener) listeners.push(listenerByName.set(name, {
-        on: listener
-      }));
-      return dispatch;
-    };
-    return event;
-  }
-  function d3_format_precision(x, p) {
-    return p - (x ? 1 + Math.floor(Math.log(x + Math.pow(10, 1 + Math.floor(Math.log(x) / Math.LN10) - p)) / Math.LN10) : 1);
-  }
-  function d3_format_typeDefault(x) {
-    return x + "";
-  }
-  function d3_format_group(value) {
-    var i = value.lastIndexOf("."), f = i >= 0 ? value.substring(i) : (i = value.length, ""), t = [];
-    while (i > 0) t.push(value.substring(i -= 3, i + 3));
-    return t.reverse().join(",") + f;
-  }
-  function d3_formatPrefix(d, i) {
-    var k = Math.pow(10, Math.abs(8 - i) * 3);
-    return {
-      scale: i > 8 ? function(d) {
-        return d / k;
-      } : function(d) {
-        return d * k;
-      },
-      symbol: d
-    };
-  }
-  function d3_ease_clamp(f) {
-    return function(t) {
-      return t <= 0 ? 0 : t >= 1 ? 1 : f(t);
-    };
-  }
-  function d3_ease_reverse(f) {
-    return function(t) {
-      return 1 - f(1 - t);
-    };
-  }
-  function d3_ease_reflect(f) {
-    return function(t) {
-      return .5 * (t < .5 ? f(2 * t) : 2 - f(2 - 2 * t));
-    };
-  }
-  function d3_ease_identity(t) {
-    return t;
-  }
-  function d3_ease_poly(e) {
-    return function(t) {
-      return Math.pow(t, e);
-    };
-  }
-  function d3_ease_sin(t) {
-    return 1 - Math.cos(t * Math.PI / 2);
-  }
-  function d3_ease_exp(t) {
-    return Math.pow(2, 10 * (t - 1));
-  }
-  function d3_ease_circle(t) {
-    return 1 - Math.sqrt(1 - t * t);
-  }
-  function d3_ease_elastic(a, p) {
-    var s;
-    if (arguments.length < 2) p = .45;
-    if (arguments.length < 1) {
-      a = 1;
-      s = p / 4;
-    } else s = p / (2 * Math.PI) * Math.asin(1 / a);
-    return function(t) {
-      return 1 + a * Math.pow(2, 10 * -t) * Math.sin((t - s) * 2 * Math.PI / p);
-    };
-  }
-  function d3_ease_back(s) {
-    if (!s) s = 1.70158;
-    return function(t) {
-      return t * t * ((s + 1) * t - s);
-    };
-  }
-  function d3_ease_bounce(t) {
-    return t < 1 / 2.75 ? 7.5625 * t * t : t < 2 / 2.75 ? 7.5625 * (t -= 1.5 / 2.75) * t + .75 : t < 2.5 / 2.75 ? 7.5625 * (t -= 2.25 / 2.75) * t + .9375 : 7.5625 * (t -= 2.625 / 2.75) * t + .984375;
-  }
-  function d3_eventCancel() {
-    d3.event.stopPropagation();
-    d3.event.preventDefault();
-  }
-  function d3_eventSource() {
-    var e = d3.event, s;
-    while (s = e.sourceEvent) e = s;
-    return e;
-  }
-  function d3_eventDispatch(target) {
-    var dispatch = new d3_dispatch, i = 0, n = arguments.length;
-    while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch);
-    dispatch.of = function(thiz, argumentz) {
-      return function(e1) {
-        try {
-          var e0 = e1.sourceEvent = d3.event;
-          e1.target = target;
-          d3.event = e1;
-          dispatch[e1.type].apply(thiz, argumentz);
-        } finally {
-          d3.event = e0;
-        }
-      };
-    };
-    return dispatch;
-  }
-  function d3_transform(m) {
-    var r0 = [ m.a, m.b ], r1 = [ m.c, m.d ], kx = d3_transformNormalize(r0), kz = d3_transformDot(r0, r1), ky = d3_transformNormalize(d3_transformCombine(r1, r0, -kz)) || 0;
-    if (r0[0] * r1[1] < r1[0] * r0[1]) {
-      r0[0] *= -1;
-      r0[1] *= -1;
-      kx *= -1;
-      kz *= -1;
-    }
-    this.rotate = (kx ? Math.atan2(r0[1], r0[0]) : Math.atan2(-r1[0], r1[1])) * d3_transformDegrees;
-    this.translate = [ m.e, m.f ];
-    this.scale = [ kx, ky ];
-    this.skew = ky ? Math.atan2(kz, ky) * d3_transformDegrees : 0;
-  }
-  function d3_transformDot(a, b) {
-    return a[0] * b[0] + a[1] * b[1];
-  }
-  function d3_transformNormalize(a) {
-    var k = Math.sqrt(d3_transformDot(a, a));
-    if (k) {
-      a[0] /= k;
-      a[1] /= k;
-    }
-    return k;
-  }
-  function d3_transformCombine(a, b, k) {
-    a[0] += k * b[0];
-    a[1] += k * b[1];
-    return a;
-  }
-  function d3_interpolateByName(name) {
-    return name == "transform" ? d3.interpolateTransform : d3.interpolate;
-  }
-  function d3_uninterpolateNumber(a, b) {
-    b = b - (a = +a) ? 1 / (b - a) : 0;
-    return function(x) {
-      return (x - a) * b;
-    };
-  }
-  function d3_uninterpolateClamp(a, b) {
-    b = b - (a = +a) ? 1 / (b - a) : 0;
-    return function(x) {
-      return Math.max(0, Math.min(1, (x - a) * b));
-    };
-  }
-  function d3_Color() {}
-  function d3_rgb(r, g, b) {
-    return new d3_Rgb(r, g, b);
-  }
-  function d3_Rgb(r, g, b) {
-    this.r = r;
-    this.g = g;
-    this.b = b;
-  }
-  function d3_rgb_hex(v) {
-    return v < 16 ? "0" + Math.max(0, v).toString(16) : Math.min(255, v).toString(16);
-  }
-  function d3_rgb_parse(format, rgb, hsl) {
-    var r = 0, g = 0, b = 0, m1, m2, name;
-    m1 = /([a-z]+)\((.*)\)/i.exec(format);
-    if (m1) {
-      m2 = m1[2].split(",");
-      switch (m1[1]) {
-       case "hsl":
-        {
-          return hsl(parseFloat(m2[0]), parseFloat(m2[1]) / 100, parseFloat(m2[2]) / 100);
-        }
-       case "rgb":
-        {
-          return rgb(d3_rgb_parseNumber(m2[0]), d3_rgb_parseNumber(m2[1]), d3_rgb_parseNumber(m2[2]));
-        }
-      }
-    }
-    if (name = d3_rgb_names.get(format)) return rgb(name.r, name.g, name.b);
-    if (format != null && format.charAt(0) === "#") {
-      if (format.length === 4) {
-        r = format.charAt(1);
-        r += r;
-        g = format.charAt(2);
-        g += g;
-        b = format.charAt(3);
-        b += b;
-      } else if (format.length === 7) {
-        r = format.substring(1, 3);
-        g = format.substring(3, 5);
-        b = format.substring(5, 7);
-      }
-      r = parseInt(r, 16);
-      g = parseInt(g, 16);
-      b = parseInt(b, 16);
-    }
-    return rgb(r, g, b);
-  }
-  function d3_rgb_hsl(r, g, b) {
-    var min = Math.min(r /= 255, g /= 255, b /= 255), max = Math.max(r, g, b), d = max - min, h, s, l = (max + min) / 2;
-    if (d) {
-      s = l < .5 ? d / (max + min) : d / (2 - max - min);
-      if (r == max) h = (g - b) / d + (g < b ? 6 : 0); else if (g == max) h = (b - r) / d + 2; else h = (r - g) / d + 4;
-      h *= 60;
-    } else {
-      s = h = 0;
-    }
-    return d3_hsl(h, s, l);
-  }
-  function d3_rgb_lab(r, g, b) {
-    r = d3_rgb_xyz(r);
-    g = d3_rgb_xyz(g);
-    b = d3_rgb_xyz(b);
-    var x = d3_xyz_lab((.4124564 * r + .3575761 * g + .1804375 * b) / d3_lab_X), y = d3_xyz_lab((.2126729 * r + .7151522 * g + .072175 * b) / d3_lab_Y), z = d3_xyz_lab((.0193339 * r + .119192 * g + .9503041 * b) / d3_lab_Z);
-    return d3_lab(116 * y - 16, 500 * (x - y), 200 * (y - z));
-  }
-  function d3_rgb_xyz(r) {
-    return (r /= 255) <= .04045 ? r / 12.92 : Math.pow((r + .055) / 1.055, 2.4);
-  }
-  function d3_rgb_parseNumber(c) {
-    var f = parseFloat(c);
-    return c.charAt(c.length - 1) === "%" ? Math.round(f * 2.55) : f;
-  }
-  function d3_hsl(h, s, l) {
-    return new d3_Hsl(h, s, l);
-  }
-  function d3_Hsl(h, s, l) {
-    this.h = h;
-    this.s = s;
-    this.l = l;
-  }
-  function d3_hsl_rgb(h, s, l) {
-    function v(h) {
-      if (h > 360) h -= 360; else if (h < 0) h += 360;
-      if (h < 60) return m1 + (m2 - m1) * h / 60;
-      if (h < 180) return m2;
-      if (h < 240) return m1 + (m2 - m1) * (240 - h) / 60;
-      return m1;
-    }
-    function vv(h) {
-      return Math.round(v(h) * 255);
-    }
-    var m1, m2;
-    h = h % 360;
-    if (h < 0) h += 360;
-    s = s < 0 ? 0 : s > 1 ? 1 : s;
-    l = l < 0 ? 0 : l > 1 ? 1 : l;
-    m2 = l <= .5 ? l * (1 + s) : l + s - l * s;
-    m1 = 2 * l - m2;
-    return d3_rgb(vv(h + 120), vv(h), vv(h - 120));
-  }
-  function d3_hcl(h, c, l) {
-    return new d3_Hcl(h, c, l);
-  }
-  function d3_Hcl(h, c, l) {
-    this.h = h;
-    this.c = c;
-    this.l = l;
-  }
-  function d3_hcl_lab(h, c, l) {
-    return d3_lab(l, Math.cos(h *= Math.PI / 180) * c, Math.sin(h) * c);
-  }
-  function d3_lab(l, a, b) {
-    return new d3_Lab(l, a, b);
-  }
-  function d3_Lab(l, a, b) {
-    this.l = l;
-    this.a = a;
-    this.b = b;
-  }
-  function d3_lab_rgb(l, a, b) {
-    var y = (l + 16) / 116, x = y + a / 500, z = y - b / 200;
-    x = d3_lab_xyz(x) * d3_lab_X;
-    y = d3_lab_xyz(y) * d3_lab_Y;
-    z = d3_lab_xyz(z) * d3_lab_Z;
-    return d3_rgb(d3_xyz_rgb(3.2404542 * x - 1.5371385 * y - .4985314 * z), d3_xyz_rgb(-.969266 * x + 1.8760108 * y + .041556 * z), d3_xyz_rgb(.0556434 * x - .2040259 * y + 1.0572252 * z));
-  }
-  function d3_lab_hcl(l, a, b) {
-    return d3_hcl(Math.atan2(b, a) / Math.PI * 180, Math.sqrt(a * a + b * b), l);
-  }
-  function d3_lab_xyz(x) {
-    return x > .206893034 ? x * x * x : (x - 4 / 29) / 7.787037;
-  }
-  function d3_xyz_lab(x) {
-    return x > .008856 ? Math.pow(x, 1 / 3) : 7.787037 * x + 4 / 29;
-  }
-  function d3_xyz_rgb(r) {
-    return Math.round(255 * (r <= .00304 ? 12.92 * r : 1.055 * Math.pow(r, 1 / 2.4) - .055));
-  }
-  function d3_selection(groups) {
-    d3_arraySubclass(groups, d3_selectionPrototype);
-    return groups;
-  }
-  function d3_selection_selector(selector) {
-    return function() {
-      return d3_select(selector, this);
-    };
-  }
-  function d3_selection_selectorAll(selector) {
-    return function() {
-      return d3_selectAll(selector, this);
-    };
-  }
-  function d3_selection_attr(name, value) {
-    function attrNull() {
-      this.removeAttribute(name);
-    }
-    function attrNullNS() {
-      this.removeAttributeNS(name.space, name.local);
-    }
-    function attrConstant() {
-      this.setAttribute(name, value);
-    }
-    function attrConstantNS() {
-      this.setAttributeNS(name.space, name.local, value);
-    }
-    function attrFunction() {
-      var x = value.apply(this, arguments);
-      if (x == null) this.removeAttribute(name); else this.setAttribute(name, x);
-    }
-    function attrFunctionNS() {
-      var x = value.apply(this, arguments);
-      if (x == null) this.removeAttributeNS(name.space, name.local); else this.setAttributeNS(name.space, name.local, x);
-    }
-    name = d3.ns.qualify(name);
-    return value == null ? name.local ? attrNullNS : attrNull : typeof value === "function" ? name.local ? attrFunctionNS : attrFunction : name.local ? attrConstantNS : attrConstant;
-  }
-  function d3_selection_classedRe(name) {
-    return new RegExp("(?:^|\\s+)" + d3.requote(name) + "(?:\\s+|$)", "g");
-  }
-  function d3_selection_classed(name, value) {
-    function classedConstant() {
-      var i = -1;
-      while (++i < n) name[i](this, value);
-    }
-    function classedFunction() {
-      var i = -1, x = value.apply(this, arguments);
-      while (++i < n) name[i](this, x);
-    }
-    name = name.trim().split(/\s+/).map(d3_selection_classedName);
-    var n = name.length;
-    return typeof value === "function" ? classedFunction : classedConstant;
-  }
-  function d3_selection_classedName(name) {
-    var re = d3_selection_classedRe(name);
-    return function(node, value) {
-      if (c = node.classList) return value ? c.add(name) : c.remove(name);
-      var c = node.className, cb = c.baseVal != null, cv = cb ? c.baseVal : c;
-      if (value) {
-        re.lastIndex = 0;
-        if (!re.test(cv)) {
-          cv = d3_collapse(cv + " " + name);
-          if (cb) c.baseVal = cv; else node.className = cv;
-        }
-      } else if (cv) {
-        cv = d3_collapse(cv.replace(re, " "));
-        if (cb) c.baseVal = cv; else node.className = cv;
-      }
-    };
-  }
-  function d3_selection_style(name, value, priority) {
-    function styleNull() {
-      this.style.removeProperty(name);
-    }
-    function styleConstant() {
-      this.style.setProperty(name, value, priority);
-    }
-    function styleFunction() {
-      var x = value.apply(this, arguments);
-      if (x == null) this.style.removeProperty(name); else this.style.setProperty(name, x, priority);
-    }
-    return value == null ? styleNull : typeof value === "function" ? styleFunction : styleConstant;
-  }
-  function d3_selection_property(name, value) {
-    function propertyNull() {
-      delete this[name];
-    }
-    function propertyConstant() {
-      this[name] = value;
-    }
-    function propertyFunction() {
-      var x = value.apply(this, arguments);
-      if (x == null) delete this[name]; else this[name] = x;
-    }
-    return value == null ? propertyNull : typeof value === "function" ? propertyFunction : propertyConstant;
-  }
-  function d3_selection_dataNode(data) {
-    return {
-      __data__: data
-    };
-  }
-  function d3_selection_filter(selector) {
-    return function() {
-      return d3_selectMatches(this, selector);
-    };
-  }
-  function d3_selection_sortComparator(comparator) {
-    if (!arguments.length) comparator = d3.ascending;
-    return function(a, b) {
-      return comparator(a && a.__data__, b && b.__data__);
-    };
-  }
-  function d3_selection_on(type, listener, capture) {
-    function onRemove() {
-      var wrapper = this[name];
-      if (wrapper) {
-        this.removeEventListener(type, wrapper, wrapper.$);
-        delete this[name];
-      }
-    }
-    function onAdd() {
-      function wrapper(e) {
-        var o = d3.event;
-        d3.event = e;
-        args[0] = node.__data__;
-        try {
-          listener.apply(node, args);
-        } finally {
-          d3.event = o;
-        }
-      }
-      var node = this, args = arguments;
-      onRemove.call(this);
-      this.addEventListener(type, this[name] = wrapper, wrapper.$ = capture);
-      wrapper._ = listener;
-    }
-    var name = "__on" + type, i = type.indexOf(".");
-    if (i > 0) type = type.substring(0, i);
-    return listener ? onAdd : onRemove;
-  }
-  function d3_selection_each(groups, callback) {
-    for (var j = 0, m = groups.length; j < m; j++) {
-      for (var group = groups[j], i = 0, n = group.length, node; i < n; i++) {
-        if (node = group[i]) callback(node, i, j);
-      }
-    }
-    return groups;
-  }
-  function d3_selection_enter(selection) {
-    d3_arraySubclass(selection, d3_selection_enterPrototype);
-    return selection;
-  }
-  function d3_transition(groups, id, time) {
-    d3_arraySubclass(groups, d3_transitionPrototype);
-    var tweens = new d3_Map, event = d3.dispatch("start", "end"), ease = d3_transitionEase;
-    groups.id = id;
-    groups.time = time;
-    groups.tween = function(name, tween) {
-      if (arguments.length < 2) return tweens.get(name);
-      if (tween == null) tweens.remove(name); else tweens.set(name, tween);
-      return groups;
-    };
-    groups.ease = function(value) {
-      if (!arguments.length) return ease;
-      ease = typeof value === "function" ? value : d3.ease.apply(d3, arguments);
-      return groups;
-    };
-    groups.each = function(type, listener) {
-      if (arguments.length < 2) return d3_transition_each.call(groups, type);
-      event.on(type, listener);
-      return groups;
-    };
-    d3.timer(function(elapsed) {
-      return d3_selection_each(groups, function(node, i, j) {
-        function start(elapsed) {
-          if (lock.active > id) return stop();
-          lock.active = id;
-          tweens.forEach(function(key, value) {
-            if (value = value.call(node, d, i)) {
-              tweened.push(value);
-            }
-          });
-          event.start.call(node, d, i);
-          if (!tick(elapsed)) d3.timer(tick, 0, time);
-          return 1;
-        }
-        function tick(elapsed) {
-          if (lock.active !== id) return stop();
-          var t = (elapsed - delay) / duration, e = ease(t), n = tweened.length;
-          while (n > 0) {
-            tweened[--n].call(node, e);
-          }
-          if (t >= 1) {
-            stop();
-            d3_transitionId = id;
-            event.end.call(node, d, i);
-            d3_transitionId = 0;
-            return 1;
-          }
-        }
-        function stop() {
-          if (!--lock.count) delete node.__transition__;
-          return 1;
-        }
-        var tweened = [], delay = node.delay, duration = node.duration, lock = (node = node.node).__transition__ || (node.__transition__ = {
-          active: 0,
-          count: 0
-        }), d = node.__data__;
-        ++lock.count;
-        delay <= elapsed ? start(elapsed) : d3.timer(start, delay, time);
-      });
-    }, 0, time);
-    return groups;
-  }
-  function d3_transition_each(callback) {
-    var id = d3_transitionId, ease = d3_transitionEase, delay = d3_transitionDelay, duration = d3_transitionDuration;
-    d3_transitionId = this.id;
-    d3_transitionEase = this.ease();
-    d3_selection_each(this, function(node, i, j) {
-      d3_transitionDelay = node.delay;
-      d3_transitionDuration = node.duration;
-      callback.call(node = node.node, node.__data__, i, j);
-    });
-    d3_transitionId = id;
-    d3_transitionEase = ease;
-    d3_transitionDelay = delay;
-    d3_transitionDuration = duration;
-    return this;
-  }
-  function d3_tweenNull(d, i, a) {
-    return a != "" && d3_tweenRemove;
-  }
-  function d3_tweenByName(b, name) {
-    return d3.tween(b, d3_interpolateByName(name));
-  }
-  function d3_timer_step() {
-    var elapsed, now = Date.now(), t1 = d3_timer_queue;
-    while (t1) {
-      elapsed = now - t1.then;
-      if (elapsed >= t1.delay) t1.flush = t1.callback(elapsed);
-      t1 = t1.next;
-    }
-    var delay = d3_timer_flush() - now;
-    if (delay > 24) {
-      if (isFinite(delay)) {
-        clearTimeout(d3_timer_timeout);
-        d3_timer_timeout = setTimeout(d3_timer_step, delay);
-      }
-      d3_timer_interval = 0;
-    } else {
-      d3_timer_interval = 1;
-      d3_timer_frame(d3_timer_step);
-    }
-  }
-  function d3_timer_flush() {
-    var t0 = null, t1 = d3_timer_queue, then = Infinity;
-    while (t1) {
-      if (t1.flush) {
-        delete d3_timer_byId[t1.callback.id];
-        t1 = t0 ? t0.next = t1.next : d3_timer_queue = t1.next;
-      } else {
-        then = Math.min(then, t1.then + t1.delay);
-        t1 = (t0 = t1).next;
-      }
-    }
-    return then;
-  }
-  function d3_mousePoint(container, e) {
-    var svg = container.ownerSVGElement || container;
-    if (svg.createSVGPoint) {
-      var point = svg.createSVGPoint();
-      if (d3_mouse_bug44083 < 0 && (window.scrollX || window.scrollY)) {
-        svg = d3.select(document.body).append("svg").style("position", "absolute").style("top", 0).style("left", 0);
-        var ctm = svg[0][0].getScreenCTM();
-        d3_mouse_bug44083 = !(ctm.f || ctm.e);
-        svg.remove();
-      }
-      if (d3_mouse_bug44083) {
-        point.x = e.pageX;
-        point.y = e.pageY;
-      } else {
-        point.x = e.clientX;
-        point.y = e.clientY;
-      }
-      point = point.matrixTransform(container.getScreenCTM().inverse());
-      return [ point.x, point.y ];
-    }
-    var rect = container.getBoundingClientRect();
-    return [ e.clientX - rect.left - container.clientLeft, e.clientY - rect.top - container.clientTop ];
-  }
-  function d3_noop() {}
-  function d3_scaleExtent(domain) {
-    var start = domain[0], stop = domain[domain.length - 1];
-    return start < stop ? [ start, stop ] : [ stop, start ];
-  }
-  function d3_scaleRange(scale) {
-    return scale.rangeExtent ? scale.rangeExtent() : d3_scaleExtent(scale.range());
-  }
-  function d3_scale_nice(domain, nice) {
-    var i0 = 0, i1 = domain.length - 1, x0 = domain[i0], x1 = domain[i1], dx;
-    if (x1 < x0) {
-      dx = i0, i0 = i1, i1 = dx;
-      dx = x0, x0 = x1, x1 = dx;
-    }
-    if (nice = nice(x1 - x0)) {
-      domain[i0] = nice.floor(x0);
-      domain[i1] = nice.ceil(x1);
-    }
-    return domain;
-  }
-  function d3_scale_niceDefault() {
-    return Math;
-  }
-  function d3_scale_linear(domain, range, interpolate, clamp) {
-    function rescale() {
-      var linear = Math.min(domain.length, range.length) > 2 ? d3_scale_polylinear : d3_scale_bilinear, uninterpolate = clamp ? d3_uninterpolateClamp : d3_uninterpolateNumber;
-      output = linear(domain, range, uninterpolate, interpolate);
-      input = linear(range, domain, uninterpolate, d3.interpolate);
-      return scale;
-    }
-    function scale(x) {
-      return output(x);
-    }
-    var output, input;
-    scale.invert = function(y) {
-      return input(y);
-    };
-    scale.domain = function(x) {
-      if (!arguments.length) return domain;
-      domain = x.map(Number);
-      return rescale();
-    };
-    scale.range = function(x) {
-      if (!arguments.length) return range;
-      range = x;
-      return rescale();
-    };
-    scale.rangeRound = function(x) {
-      return scale.range(x).interpolate(d3.interpolateRound);
-    };
-    scale.clamp = function(x) {
-      if (!arguments.length) return clamp;
-      clamp = x;
-      return rescale();
-    };
-    scale.interpolate = function(x) {
-      if (!arguments.length) return interpolate;
-      interpolate = x;
-      return rescale();
-    };
-    scale.ticks = function(m) {
-      return d3_scale_linearTicks(domain, m);
-    };
-    scale.tickFormat = function(m) {
-      return d3_scale_linearTickFormat(domain, m);
-    };
-    scale.nice = function() {
-      d3_scale_nice(domain, d3_scale_linearNice);
-      return rescale();
-    };
-    scale.copy = function() {
-      return d3_scale_linear(domain, range, interpolate, clamp);
-    };
-    return rescale();
-  }
-  function d3_scale_linearRebind(scale, linear) {
-    return d3.rebind(scale, linear, "range", "rangeRound", "interpolate", "clamp");
-  }
-  function d3_scale_linearNice(dx) {
-    dx = Math.pow(10, Math.round(Math.log(dx) / Math.LN10) - 1);
-    return dx && {
-      floor: function(x) {
-        return Math.floor(x / dx) * dx;
-      },
-      ceil: function(x) {
-        return Math.ceil(x / dx) * dx;
-      }
-    };
-  }
-  function d3_scale_linearTickRange(domain, m) {
-    var extent = d3_scaleExtent(domain), span = extent[1] - extent[0], step = Math.pow(10, Math.floor(Math.log(span / m) / Math.LN10)), err = m / span * step;
-    if (err <= .15) step *= 10; else if (err <= .35) step *= 5; else if (err <= .75) step *= 2;
-    extent[0] = Math.ceil(extent[0] / step) * step;
-    extent[1] = Math.floor(extent[1] / step) * step + step * .5;
-    extent[2] = step;
-    return extent;
-  }
-  function d3_scale_linearTicks(domain, m) {
-    return d3.range.apply(d3, d3_scale_linearTickRange(domain, m));
-  }
-  function d3_scale_linearTickFormat(domain, m) {
-    return d3.format(",." + Math.max(0, -Math.floor(Math.log(d3_scale_linearTickRange(domain, m)[2]) / Math.LN10 + .01)) + "f");
-  }
-  function d3_scale_bilinear(domain, range, uninterpolate, interpolate) {
-    var u = uninterpolate(domain[0], domain[1]), i = interpolate(range[0], range[1]);
-    return function(x) {
-      return i(u(x));
-    };
-  }
-  function d3_scale_polylinear(domain, range, uninterpolate, interpolate) {
-    var u = [], i = [], j = 0, k = Math.min(domain.length, range.length) - 1;
-    if (domain[k] < domain[0]) {
-      domain = domain.slice().reverse();
-      range = range.slice().reverse();
-    }
-    while (++j <= k) {
-      u.push(uninterpolate(domain[j - 1], domain[j]));
-      i.push(interpolate(range[j - 1], range[j]));
-    }
-    return function(x) {
-      var j = d3.bisect(domain, x, 1, k) - 1;
-      return i[j](u[j](x));
-    };
-  }
-  function d3_scale_log(linear, log) {
-    function scale(x) {
-      return linear(log(x));
-    }
-    var pow = log.pow;
-    scale.invert = function(x) {
-      return pow(linear.invert(x));
-    };
-    scale.domain = function(x) {
-      if (!arguments.length) return linear.domain().map(pow);
-      log = x[0] < 0 ? d3_scale_logn : d3_scale_logp;
-      pow = log.pow;
-      linear.domain(x.map(log));
-      return scale;
-    };
-    scale.nice = function() {
-      linear.domain(d3_scale_nice(linear.domain(), d3_scale_niceDefault));
-      return scale;
-    };
-    scale.ticks = function() {
-      var extent = d3_scaleExtent(linear.domain()), ticks = [];
-      if (extent.every(isFinite)) {
-        var i = Math.floor(extent[0]), j = Math.ceil(extent[1]), u = pow(extent[0]), v = pow(extent[1]);
-        if (log === d3_scale_logn) {
-          ticks.push(pow(i));
-          for (; i++ < j; ) for (var k = 9; k > 0; k--) ticks.push(pow(i) * k);
-        } else {
-          for (; i < j; i++) for (var k = 1; k < 10; k++) ticks.push(pow(i) * k);
-          ticks.push(pow(i));
-        }
-        for (i = 0; ticks[i] < u; i++) {}
-        for (j = ticks.length; ticks[j - 1] > v; j--) {}
-        ticks = ticks.slice(i, j);
-      }
-      return ticks;
-    };
-    scale.tickFormat = function(n, format) {
-      if (arguments.length < 2) format = d3_scale_logFormat;
-      if (arguments.length < 1) return format;
-      var k = Math.max(.1, n / scale.ticks().length), f = log === d3_scale_logn ? (e = -1e-12, Math.floor) : (e = 1e-12, Math.ceil), e;
-      return function(d) {
-        return d / pow(f(log(d) + e)) <= k ? format(d) : "";
-      };
-    };
-    scale.copy = function() {
-      return d3_scale_log(linear.copy(), log);
-    };
-    return d3_scale_linearRebind(scale, linear);
-  }
-  function d3_scale_logp(x) {
-    return Math.log(x < 0 ? 0 : x) / Math.LN10;
-  }
-  function d3_scale_logn(x) {
-    return -Math.log(x > 0 ? 0 : -x) / Math.LN10;
-  }
-  function d3_scale_pow(linear, exponent) {
-    function scale(x) {
-      return linear(powp(x));
-    }
-    var powp = d3_scale_powPow(exponent), powb = d3_scale_powPow(1 / exponent);
-    scale.invert = function(x) {
-      return powb(linear.invert(x));
-    };
-    scale.domain = function(x) {
-      if (!arguments.length) return linear.domain().map(powb);
-      linear.domain(x.map(powp));
-      return scale;
-    };
-    scale.ticks = function(m) {
-      return d3_scale_linearTicks(scale.domain(), m);
-    };
-    scale.tickFormat = function(m) {
-      return d3_scale_linearTickFormat(scale.domain(), m);
-    };
-    scale.nice = function() {
-      return scale.domain(d3_scale_nice(scale.domain(), d3_scale_linearNice));
-    };
-    scale.exponent = function(x) {
-      if (!arguments.length) return exponent;
-      var domain = scale.domain();
-      powp = d3_scale_powPow(exponent = x);
-      powb = d3_scale_powPow(1 / exponent);
-      return scale.domain(domain);
-    };
-    scale.copy = function() {
-      return d3_scale_pow(linear.copy(), exponent);
-    };
-    return d3_scale_linearRebind(scale, linear);
-  }
-  function d3_scale_powPow(e) {
-    return function(x) {
-      return x < 0 ? -Math.pow(-x, e) : Math.pow(x, e);
-    };
-  }
-  function d3_scale_ordinal(domain, ranger) {
-    function scale(x) {
-      return range[((index.get(x) || index.set(x, domain.push(x))) - 1) % range.length];
-    }
-    function steps(start, step) {
-      return d3.range(domain.length).map(function(i) {
-        return start + step * i;
-      });
-    }
-    var index, range, rangeBand;
-    scale.domain = function(x) {
-      if (!arguments.length) return domain;
-      domain = [];
-      index = new d3_Map;
-      var i = -1, n = x.length, xi;
-      while (++i < n) if (!index.has(xi = x[i])) index.set(xi, domain.push(xi));
-      return scale[ranger.t].apply(scale, ranger.a);
-    };
-    scale.range = function(x) {
-      if (!arguments.length) return range;
-      range = x;
-      rangeBand = 0;
-      ranger = {
-        t: "range",
-        a: arguments
-      };
-      return scale;
-    };
-    scale.rangePoints = function(x, padding) {
-      if (arguments.length < 2) padding = 0;
-      var start = x[0], stop = x[1], step = (stop - start) / (Math.max(1, domain.length - 1) + padding);
-      range = steps(domain.length < 2 ? (start + stop) / 2 : start + step * padding / 2, step);
-      rangeBand = 0;
-      ranger = {
-        t: "rangePoints",
-        a: arguments
-      };
-      return scale;
-    };
-    scale.rangeBands = function(x, padding, outerPadding) {
-      if (arguments.length < 2) padding = 0;
-      if (arguments.length < 3) outerPadding = padding;
-      var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = (stop - start) / (domain.length - padding + 2 * outerPadding);
-      range = steps(start + step * outerPadding, step);
-      if (reverse) range.reverse();
-      rangeBand = step * (1 - padding);
-      ranger = {
-        t: "rangeBands",
-        a: arguments
-      };
-      return scale;
-    };
-    scale.rangeRoundBands = function(x, padding, outerPadding) {
-      if (arguments.length < 2) padding = 0;
-      if (arguments.length < 3) outerPadding = padding;
-      var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = Math.floor((stop - start) / (domain.length - padding + 2 * outerPadding)), error = stop - start - (domain.length - padding) * step;
-      range = steps(start + Math.round(error / 2), step);
-      if (reverse) range.reverse();
-      rangeBand = Math.round(step * (1 - padding));
-      ranger = {
-        t: "rangeRoundBands",
-        a: arguments
-      };
-      return scale;
-    };
-    scale.rangeBand = function() {
-      return rangeBand;
-    };
-    scale.rangeExtent = function() {
-      return d3_scaleExtent(ranger.a[0]);
-    };
-    scale.copy = function() {
-      return d3_scale_ordinal(domain, ranger);
-    };
-    return scale.domain(domain);
-  }
-  function d3_scale_quantile(domain, range) {
-    function rescale() {
-      var k = 0, n = domain.length, q = range.length;
-      thresholds = [];
-      while (++k < q) thresholds[k - 1] = d3.quantile(domain, k / q);
-      return scale;
-    }
-    function scale(x) {
-      if (isNaN(x = +x)) return NaN;
-      return range[d3.bisect(thresholds, x)];
-    }
-    var thresholds;
-    scale.domain = function(x) {
-      if (!arguments.length) return domain;
-      domain = x.filter(function(d) {
-        return !isNaN(d);
-      }).sort(d3.ascending);
-      return rescale();
-    };
-    scale.range = function(x) {
-      if (!arguments.length) return range;
-      range = x;
-      return rescale();
-    };
-    scale.quantiles = function() {
-      return thresholds;
-    };
-    scale.copy = function() {
-      return d3_scale_quantile(domain, range);
-    };
-    return rescale();
-  }
-  function d3_scale_quantize(x0, x1, range) {
-    function scale(x) {
-      return range[Math.max(0, Math.min(i, Math.floor(kx * (x - x0))))];
-    }
-    function rescale() {
-      kx = range.length / (x1 - x0);
-      i = range.length - 1;
-      return scale;
-    }
-    var kx, i;
-    scale.domain = function(x) {
-      if (!arguments.length) return [ x0, x1 ];
-      x0 = +x[0];
-      x1 = +x[x.length - 1];
-      return rescale();
-    };
-    scale.range = function(x) {
-      if (!arguments.length) return range;
-      range = x;
-      return rescale();
-    };
-    scale.copy = function() {
-      return d3_scale_quantize(x0, x1, range);
-    };
-    return rescale();
-  }
-  function d3_scale_threshold(domain, range) {
-    function scale(x) {
-      return range[d3.bisect(domain, x)];
-    }
-    scale.domain = function(_) {
-      if (!arguments.length) return domain;
-      domain = _;
-      return scale;
-    };
-    scale.range = function(_) {
-      if (!arguments.length) return range;
-      range = _;
-      return scale;
-    };
-    scale.copy = function() {
-      return d3_scale_threshold(domain, range);
-    };
-    return scale;
-  }
-  function d3_scale_identity(domain) {
-    function identity(x) {
-      return +x;
-    }
-    identity.invert = identity;
-    identity.domain = identity.range = function(x) {
-      if (!arguments.length) return domain;
-      domain = x.map(identity);
-      return identity;
-    };
-    identity.ticks = function(m) {
-      return d3_scale_linearTicks(domain, m);
-    };
-    identity.tickFormat = function(m) {
-      return d3_scale_linearTickFormat(domain, m);
-    };
-    identity.copy = function() {
-      return d3_scale_identity(domain);
-    };
-    return identity;
-  }
-  function d3_svg_arcInnerRadius(d) {
-    return d.innerRadius;
-  }
-  function d3_svg_arcOuterRadius(d) {
-    return d.outerRadius;
-  }
-  function d3_svg_arcStartAngle(d) {
-    return d.startAngle;
-  }
-  function d3_svg_arcEndAngle(d) {
-    return d.endAngle;
-  }
-  function d3_svg_line(projection) {
-    function line(data) {
-      function segment() {
-        segments.push("M", interpolate(projection(points), tension));
-      }
-      var segments = [], points = [], i = -1, n = data.length, d, fx = d3_functor(x), fy = d3_functor(y);
-      while (++i < n) {
-        if (defined.call(this, d = data[i], i)) {
-          points.push([ +fx.call(this, d, i), +fy.call(this, d, i) ]);
-        } else if (points.length) {
-          segment();
-          points = [];
-        }
-      }
-      if (points.length) segment();
-      return segments.length ? segments.join("") : null;
-    }
-    var x = d3_svg_lineX, y = d3_svg_lineY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, tension = .7;
-    line.x = function(_) {
-      if (!arguments.length) return x;
-      x = _;
-      return line;
-    };
-    line.y = function(_) {
-      if (!arguments.length) return y;
-      y = _;
-      return line;
-    };
-    line.defined = function(_) {
-      if (!arguments.length) return defined;
-      defined = _;
-      return line;
-    };
-    line.interpolate = function(_) {
-      if (!arguments.length) return interpolateKey;
-      if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key;
-      return line;
-    };
-    line.tension = function(_) {
-      if (!arguments.length) return tension;
-      tension = _;
-      return line;
-    };
-    return line;
-  }
-  function d3_svg_lineX(d) {
-    return d[0];
-  }
-  function d3_svg_lineY(d) {
-    return d[1];
-  }
-  function d3_svg_lineLinear(points) {
-    return points.join("L");
-  }
-  function d3_svg_lineLinearClosed(points) {
-    return d3_svg_lineLinear(points) + "Z";
-  }
-  function d3_svg_lineStepBefore(points) {
-    var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ];
-    while (++i < n) path.push("V", (p = points[i])[1], "H", p[0]);
-    return path.join("");
-  }
-  function d3_svg_lineStepAfter(points) {
-    var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ];
-    while (++i < n) path.push("H", (p = points[i])[0], "V", p[1]);
-    return path.join("");
-  }
-  function d3_svg_lineCardinalOpen(points, tension) {
-    return points.length < 4 ? d3_svg_lineLinear(points) : points[1] + d3_svg_lineHermite(points.slice(1, points.length - 1), d3_svg_lineCardinalTangents(points, tension));
-  }
-  function d3_svg_lineCardinalClosed(points, tension) {
-    return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite((points.push(points[0]), points), d3_svg_lineCardinalTangents([ points[points.length - 2] ].concat(points, [ points[1] ]), tension));
-  }
-  function d3_svg_lineCardinal(points, tension, closed) {
-    return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineCardinalTangents(points, tension));
-  }
-  function d3_svg_lineHermite(points, tangents) {
-    if (tangents.length < 1 || points.length != tangents.length && points.length != tangents.length + 2) {
-      return d3_svg_lineLinear(points);
-    }
-    var quad = points.length != tangents.length, path = "", p0 = points[0], p = points[1], t0 = tangents[0], t = t0, pi = 1;
-    if (quad) {
-      path += "Q" + (p[0] - t0[0] * 2 / 3) + "," + (p[1] - t0[1] * 2 / 3) + "," + p[0] + "," + p[1];
-      p0 = points[1];
-      pi = 2;
-    }
-    if (tangents.length > 1) {
-      t = tangents[1];
-      p = points[pi];
-      pi++;
-      path += "C" + (p0[0] + t0[0]) + "," + (p0[1] + t0[1]) + "," + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1];
-      for (var i = 2; i < tangents.length; i++, pi++) {
-        p = points[pi];
-        t = tangents[i];
-        path += "S" + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1];
-      }
-    }
-    if (quad) {
-      var lp = points[pi];
-      path += "Q" + (p[0] + t[0] * 2 / 3) + "," + (p[1] + t[1] * 2 / 3) + "," + lp[0] + "," + lp[1];
-    }
-    return path;
-  }
-  function d3_svg_lineCardinalTangents(points, tension) {
-    var tangents = [], a = (1 - tension) / 2, p0, p1 = points[0], p2 = points[1], i = 1, n = points.length;
-    while (++i < n) {
-      p0 = p1;
-      p1 = p2;
-      p2 = points[i];
-      tangents.push([ a * (p2[0] - p0[0]), a * (p2[1] - p0[1]) ]);
-    }
-    return tangents;
-  }
-  function d3_svg_lineBasis(points) {
-    if (points.length < 3) return d3_svg_lineLinear(points);
-    var i = 1, n = points.length, pi = points[0], x0 = pi[0], y0 = pi[1], px = [ x0, x0, x0, (pi = points[1])[0] ], py = [ y0, y0, y0, pi[1] ], path = [ x0, ",", y0 ];
-    d3_svg_lineBasisBezier(path, px, py);
-    while (++i < n) {
-      pi = points[i];
-      px.shift();
-      px.push(pi[0]);
-      py.shift();
-      py.push(pi[1]);
-      d3_svg_lineBasisBezier(path, px, py);
-    }
-    i = -1;
-    while (++i < 2) {
-      px.shift();
-      px.push(pi[0]);
-      py.shift();
-      py.push(pi[1]);
-      d3_svg_lineBasisBezier(path, px, py);
-    }
-    return path.join("");
-  }
-  function d3_svg_lineBasisOpen(points) {
-    if (points.length < 4) return d3_svg_lineLinear(points);
-    var path = [], i = -1, n = points.length, pi, px = [ 0 ], py = [ 0 ];
-    while (++i < 3) {
-      pi = points[i];
-      px.push(pi[0]);
-      py.push(pi[1]);
-    }
-    path.push(d3_svg_lineDot4(d3_svg_lineBasisBezier3, px) + "," + d3_svg_lineDot4(d3_svg_lineBasisBezier3, py));
-    --i;
-    while (++i < n) {
-      pi = points[i];
-      px.shift();
-      px.push(pi[0]);
-      py.shift();
-      py.push(pi[1]);
-      d3_svg_lineBasisBezier(path, px, py);
-    }
-    return path.join("");
-  }
-  function d3_svg_lineBasisClosed(points) {
-    var path, i = -1, n = points.length, m = n + 4, pi, px = [], py = [];
-    while (++i < 4) {
-      pi = points[i % n];
-      px.push(pi[0]);
-      py.push(pi[1]);
-    }
-    path = [ d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ];
-    --i;
-    while (++i < m) {
-      pi = points[i % n];
-      px.shift();
-      px.push(pi[0]);
-      py.shift();
-      py.push(pi[1]);
-      d3_svg_lineBasisBezier(path, px, py);
-    }
-    return path.join("");
-  }
-  function d3_svg_lineBundle(points, tension) {
-    var n = points.length - 1;
-    if (n) {
-      var x0 = points[0][0], y0 = points[0][1], dx = points[n][0] - x0, dy = points[n][1] - y0, i = -1, p, t;
-      while (++i <= n) {
-        p = points[i];
-        t = i / n;
-        p[0] = tension * p[0] + (1 - tension) * (x0 + t * dx);
-        p[1] = tension * p[1] + (1 - tension) * (y0 + t * dy);
-      }
-    }
-    return d3_svg_lineBasis(points);
-  }
-  function d3_svg_lineDot4(a, b) {
-    return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
-  }
-  function d3_svg_lineBasisBezier(path, x, y) {
-    path.push("C", d3_svg_lineDot4(d3_svg_lineBasisBezier1, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier1, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, y));
-  }
-  function d3_svg_lineSlope(p0, p1) {
-    return (p1[1] - p0[1]) / (p1[0] - p0[0]);
-  }
-  function d3_svg_lineFiniteDifferences(points) {
-    var i = 0, j = points.length - 1, m = [], p0 = points[0], p1 = points[1], d = m[0] = d3_svg_lineSlope(p0, p1);
-    while (++i < j) {
-      m[i] = (d + (d = d3_svg_lineSlope(p0 = p1, p1 = points[i + 1]))) / 2;
-    }
-    m[i] = d;
-    return m;
-  }
-  function d3_svg_lineMonotoneTangents(points) {
-    var tangents = [], d, a, b, s, m = d3_svg_lineFiniteDifferences(points), i = -1, j = points.length - 1;
-    while (++i < j) {
-      d = d3_svg_lineSlope(points[i], points[i + 1]);
-      if (Math.abs(d) < 1e-6) {
-        m[i] = m[i + 1] = 0;
-      } else {
-        a = m[i] / d;
-        b = m[i + 1] / d;
-        s = a * a + b * b;
-        if (s > 9) {
-          s = d * 3 / Math.sqrt(s);
-          m[i] = s * a;
-          m[i + 1] = s * b;
-        }
-      }
-    }
-    i = -1;
-    while (++i <= j) {
-      s = (points[Math.min(j, i + 1)][0] - points[Math.max(0, i - 1)][0]) / (6 * (1 + m[i] * m[i]));
-      tangents.push([ s || 0, m[i] * s || 0 ]);
-    }
-    return tangents;
-  }
-  function d3_svg_lineMonotone(points) {
-    return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineMonotoneTangents(points));
-  }
-  function d3_svg_lineRadial(points) {
-    var point, i = -1, n = points.length, r, a;
-    while (++i < n) {
-      point = points[i];
-      r = point[0];
-      a = point[1] + d3_svg_arcOffset;
-      point[0] = r * Math.cos(a);
-      point[1] = r * Math.sin(a);
-    }
-    return points;
-  }
-  function d3_svg_area(projection) {
-    function area(data) {
-      function segment() {
-        segments.push("M", interpolate(projection(points1), tension), L, interpolateReverse(projection(points0.reverse()), tension), "Z");
-      }
-      var segments = [], points0 = [], points1 = [], i = -1, n = data.length, d, fx0 = d3_functor(x0), fy0 = d3_functor(y0), fx1 = x0 === x1 ? function() {
-        return x;
-      } : d3_functor(x1), fy1 = y0 === y1 ? function() {
-        return y;
-      } : d3_functor(y1), x, y;
-      while (++i < n) {
-        if (defined.call(this, d = data[i], i)) {
-          points0.push([ x = +fx0.call(this, d, i), y = +fy0.call(this, d, i) ]);
-          points1.push([ +fx1.call(this, d, i), +fy1.call(this, d, i) ]);
-        } else if (points0.length) {
-          segment();
-          points0 = [];
-          points1 = [];
-        }
-      }
-      if (points0.length) segment();
-      return segments.length ? segments.join("") : null;
-    }
-    var x0 = d3_svg_lineX, x1 = d3_svg_lineX, y0 = 0, y1 = d3_svg_lineY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, interpolateReverse = interpolate, L = "L", tension = .7;
-    area.x = function(_) {
-      if (!arguments.length) return x1;
-      x0 = x1 = _;
-      return area;
-    };
-    area.x0 = function(_) {
-      if (!arguments.length) return x0;
-      x0 = _;
-      return area;
-    };
-    area.x1 = function(_) {
-      if (!arguments.length) return x1;
-      x1 = _;
-      return area;
-    };
-    area.y = function(_) {
-      if (!arguments.length) return y1;
-      y0 = y1 = _;
-      return area;
-    };
-    area.y0 = function(_) {
-      if (!arguments.length) return y0;
-      y0 = _;
-      return area;
-    };
-    area.y1 = function(_) {
-      if (!arguments.length) return y1;
-      y1 = _;
-      return area;
-    };
-    area.defined = function(_) {
-      if (!arguments.length) return defined;
-      defined = _;
-      return area;
-    };
-    area.interpolate = function(_) {
-      if (!arguments.length) return interpolateKey;
-      if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key;
-      interpolateReverse = interpolate.reverse || interpolate;
-      L = interpolate.closed ? "M" : "L";
-      return area;
-    };
-    area.tension = function(_) {
-      if (!arguments.length) return tension;
-      tension = _;
-      return area;
-    };
-    return area;
-  }
-  function d3_svg_chordSource(d) {
-    return d.source;
-  }
-  function d3_svg_chordTarget(d) {
-    return d.target;
-  }
-  function d3_svg_chordRadius(d) {
-    return d.radius;
-  }
-  function d3_svg_chordStartAngle(d) {
-    return d.startAngle;
-  }
-  function d3_svg_chordEndAngle(d) {
-    return d.endAngle;
-  }
-  function d3_svg_diagonalProjection(d) {
-    return [ d.x, d.y ];
-  }
-  function d3_svg_diagonalRadialProjection(projection) {
-    return function() {
-      var d = projection.apply(this, arguments), r = d[0], a = d[1] + d3_svg_arcOffset;
-      return [ r * Math.cos(a), r * Math.sin(a) ];
-    };
-  }
-  function d3_svg_symbolSize() {
-    return 64;
-  }
-  function d3_svg_symbolType() {
-    return "circle";
-  }
-  function d3_svg_symbolCircle(size) {
-    var r = Math.sqrt(size / Math.PI);
-    return "M0," + r + "A" + r + "," + r + " 0 1,1 0," + -r + "A" + r + "," + r + " 0 1,1 0," + r + "Z";
-  }
-  function d3_svg_axisX(selection, x) {
-    selection.attr("transform", function(d) {
-      return "translate(" + x(d) + ",0)";
-    });
-  }
-  function d3_svg_axisY(selection, y) {
-    selection.attr("transform", function(d) {
-      return "translate(0," + y(d) + ")";
-    });
-  }
-  function d3_svg_axisSubdivide(scale, ticks, m) {
-    subticks = [];
-    if (m && ticks.length > 1) {
-      var extent = d3_scaleExtent(scale.domain()), subticks, i = -1, n = ticks.length, d = (ticks[1] - ticks[0]) / ++m, j, v;
-      while (++i < n) {
-        for (j = m; --j > 0; ) {
-          if ((v = +ticks[i] - j * d) >= extent[0]) {
-            subticks.push(v);
-          }
-        }
-      }
-      for (--i, j = 0; ++j < m && (v = +ticks[i] + j * d) < extent[1]; ) {
-        subticks.push(v);
-      }
-    }
-    return subticks;
-  }
-  function d3_behavior_zoomDelta() {
-    if (!d3_behavior_zoomDiv) {
-      d3_behavior_zoomDiv = d3.select("body").append("div").style("visibility", "hidden").style("top", 0).style("height", 0).style("width", 0).style("overflow-y", "scroll").append("div").style("height", "2000px").node().parentNode;
-    }
-    var e = d3.event, delta;
-    try {
-      d3_behavior_zoomDiv.scrollTop = 1e3;
-      d3_behavior_zoomDiv.dispatchEvent(e);
-      delta = 1e3 - d3_behavior_zoomDiv.scrollTop;
-    } catch (error) {
-      delta = e.wheelDelta || -e.detail * 5;
-    }
-    return delta;
-  }
-  function d3_layout_bundlePath(link) {
-    var start = link.source, end = link.target, lca = d3_layout_bundleLeastCommonAncestor(start, end), points = [ start ];
-    while (start !== lca) {
-      start = start.parent;
-      points.push(start);
-    }
-    var k = points.length;
-    while (end !== lca) {
-      points.splice(k, 0, end);
-      end = end.parent;
-    }
-    return points;
-  }
-  function d3_layout_bundleAncestors(node) {
-    var ancestors = [], parent = node.parent;
-    while (parent != null) {
-      ancestors.push(node);
-      node = parent;
-      parent = parent.parent;
-    }
-    ancestors.push(node);
-    return ancestors;
-  }
-  function d3_layout_bundleLeastCommonAncestor(a, b) {
-    if (a === b) return a;
-    var aNodes = d3_layout_bundleAncestors(a), bNodes = d3_layout_bundleAncestors(b), aNode = aNodes.pop(), bNode = bNodes.pop(), sharedNode = null;
-    while (aNode === bNode) {
-      sharedNode = aNode;
-      aNode = aNodes.pop();
-      bNode = bNodes.pop();
-    }
-    return sharedNode;
-  }
-  function d3_layout_forceDragstart(d) {
-    d.fixed |= 2;
-  }
-  function d3_layout_forceDragend(d) {
-    d.fixed &= 1;
-  }
-  function d3_layout_forceMouseover(d) {
-    d.fixed |= 4;
-  }
-  function d3_layout_forceMouseout(d) {
-    d.fixed &= 3;
-  }
-  function d3_layout_forceAccumulate(quad, alpha, charges) {
-    var cx = 0, cy = 0;
-    quad.charge = 0;
-    if (!quad.leaf) {
-      var nodes = quad.nodes, n = nodes.length, i = -1, c;
-      while (++i < n) {
-        c = nodes[i];
-        if (c == null) continue;
-        d3_layout_forceAccumulate(c, alpha, charges);
-        quad.charge += c.charge;
-        cx += c.charge * c.cx;
-        cy += c.charge * c.cy;
-      }
-    }
-    if (quad.point) {
-      if (!quad.leaf) {
-        quad.point.x += Math.random() - .5;
-        quad.point.y += Math.random() - .5;
-      }
-      var k = alpha * charges[quad.point.index];
-      quad.charge += quad.pointCharge = k;
-      cx += k * quad.point.x;
-      cy += k * quad.point.y;
-    }
-    quad.cx = cx / quad.charge;
-    quad.cy = cy / quad.charge;
-  }
-  function d3_layout_forceLinkDistance(link) {
-    return 20;
-  }
-  function d3_layout_forceLinkStrength(link) {
-    return 1;
-  }
-  function d3_layout_stackX(d) {
-    return d.x;
-  }
-  function d3_layout_stackY(d) {
-    return d.y;
-  }
-  function d3_layout_stackOut(d, y0, y) {
-    d.y0 = y0;
-    d.y = y;
-  }
-  function d3_layout_stackOrderDefault(data) {
-    return d3.range(data.length);
-  }
-  function d3_layout_stackOffsetZero(data) {
-    var j = -1, m = data[0].length, y0 = [];
-    while (++j < m) y0[j] = 0;
-    return y0;
-  }
-  function d3_layout_stackMaxIndex(array) {
-    var i = 1, j = 0, v = array[0][1], k, n = array.length;
-    for (; i < n; ++i) {
-      if ((k = array[i][1]) > v) {
-        j = i;
-        v = k;
-      }
-    }
-    return j;
-  }
-  function d3_layout_stackReduceSum(d) {
-    return d.reduce(d3_layout_stackSum, 0);
-  }
-  function d3_layout_stackSum(p, d) {
-    return p + d[1];
-  }
-  function d3_layout_histogramBinSturges(range, values) {
-    return d3_layout_histogramBinFixed(range, Math.ceil(Math.log(values.length) / Math.LN2 + 1));
-  }
-  function d3_layout_histogramBinFixed(range, n) {
-    var x = -1, b = +range[0], m = (range[1] - b) / n, f = [];
-    while (++x <= n) f[x] = m * x + b;
-    return f;
-  }
-  function d3_layout_histogramRange(values) {
-    return [ d3.min(values), d3.max(values) ];
-  }
-  function d3_layout_hierarchyRebind(object, hierarchy) {
-    d3.rebind(object, hierarchy, "sort", "children", "value");
-    object.links = d3_layout_hierarchyLinks;
-    object.nodes = function(d) {
-      d3_layout_hierarchyInline = true;
-      return (object.nodes = object)(d);
-    };
-    return object;
-  }
-  function d3_layout_hierarchyChildren(d) {
-    return d.children;
-  }
-  function d3_layout_hierarchyValue(d) {
-    return d.value;
-  }
-  function d3_layout_hierarchySort(a, b) {
-    return b.value - a.value;
-  }
-  function d3_layout_hierarchyLinks(nodes) {
-    return d3.merge(nodes.map(function(parent) {
-      return (parent.children || []).map(function(child) {
-        return {
-          source: parent,
-          target: child
-        };
-      });
-    }));
-  }
-  function d3_layout_packSort(a, b) {
-    return a.value - b.value;
-  }
-  function d3_layout_packInsert(a, b) {
-    var c = a._pack_next;
-    a._pack_next = b;
-    b._pack_prev = a;
-    b._pack_next = c;
-    c._pack_prev = b;
-  }
-  function d3_layout_packSplice(a, b) {
-    a._pack_next = b;
-    b._pack_prev = a;
-  }
-  function d3_layout_packIntersects(a, b) {
-    var dx = b.x - a.x, dy = b.y - a.y, dr = a.r + b.r;
-    return dr * dr - dx * dx - dy * dy > .001;
-  }
-  function d3_layout_packSiblings(node) {
-    function bound(node) {
-      xMin = Math.min(node.x - node.r, xMin);
-      xMax = Math.max(node.x + node.r, xMax);
-      yMin = Math.min(node.y - node.r, yMin);
-      yMax = Math.max(node.y + node.r, yMax);
-    }
-    if (!(nodes = node.children) || !(n = nodes.length)) return;
-    var nodes, xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity, a, b, c, i, j, k, n;
-    nodes.forEach(d3_layout_packLink);
-    a = nodes[0];
-    a.x = -a.r;
-    a.y = 0;
-    bound(a);
-    if (n > 1) {
-      b = nodes[1];
-      b.x = b.r;
-      b.y = 0;
-      bound(b);
-      if (n > 2) {
-        c = nodes[2];
-        d3_layout_packPlace(a, b, c);
-        bound(c);
-        d3_layout_packInsert(a, c);
-        a._pack_prev = c;
-        d3_layout_packInsert(c, b);
-        b = a._pack_next;
-        for (i = 3; i < n; i++) {
-          d3_layout_packPlace(a, b, c = nodes[i]);
-          var isect = 0, s1 = 1, s2 = 1;
-          for (j = b._pack_next; j !== b; j = j._pack_next, s1++) {
-            if (d3_layout_packIntersects(j, c)) {
-              isect = 1;
-              break;
-            }
-          }
-          if (isect == 1) {
-            for (k = a._pack_prev; k !== j._pack_prev; k = k._pack_prev, s2++) {
-              if (d3_layout_packIntersects(k, c)) {
-                break;
-              }
-            }
-          }
-          if (isect) {
-            if (s1 < s2 || s1 == s2 && b.r < a.r) d3_layout_packSplice(a, b = j); else d3_layout_packSplice(a = k, b);
-            i--;
-          } else {
-            d3_layout_packInsert(a, c);
-            b = c;
-            bound(c);
-          }
-        }
-      }
-    }
-    var cx = (xMin + xMax) / 2, cy = (yMin + yMax) / 2, cr = 0;
-    for (i = 0; i < n; i++) {
-      c = nodes[i];
-      c.x -= cx;
-      c.y -= cy;
-      cr = Math.max(cr, c.r + Math.sqrt(c.x * c.x + c.y * c.y));
-    }
-    node.r = cr;
-    nodes.forEach(d3_layout_packUnlink);
-  }
-  function d3_layout_packLink(node) {
-    node._pack_next = node._pack_prev = node;
-  }
-  function d3_layout_packUnlink(node) {
-    delete node._pack_next;
-    delete node._pack_prev;
-  }
-  function d3_layout_packTransform(node, x, y, k) {
-    var children = node.children;
-    node.x = x += k * node.x;
-    node.y = y += k * node.y;
-    node.r *= k;
-    if (children) {
-      var i = -1, n = children.length;
-      while (++i < n) d3_layout_packTransform(children[i], x, y, k);
-    }
-  }
-  function d3_layout_packPlace(a, b, c) {
-    var db = a.r + c.r, dx = b.x - a.x, dy = b.y - a.y;
-    if (db && (dx || dy)) {
-      var da = b.r + c.r, dc = dx * dx + dy * dy;
-      da *= da;
-      db *= db;
-      var x = .5 + (db - da) / (2 * dc), y = Math.sqrt(Math.max(0, 2 * da * (db + dc) - (db -= dc) * db - da * da)) / (2 * dc);
-      c.x = a.x + x * dx + y * dy;
-      c.y = a.y + x * dy - y * dx;
-    } else {
-      c.x = a.x + db;
-      c.y = a.y;
-    }
-  }
-  function d3_layout_clusterY(children) {
-    return 1 + d3.max(children, function(child) {
-      return child.y;
-    });
-  }
-  function d3_layout_clusterX(children) {
-    return children.reduce(function(x, child) {
-      return x + child.x;
-    }, 0) / children.length;
-  }
-  function d3_layout_clusterLeft(node) {
-    var children = node.children;
-    return children && children.length ? d3_layout_clusterLeft(children[0]) : node;
-  }
-  function d3_layout_clusterRight(node) {
-    var children = node.children, n;
-    return children && (n = children.length) ? d3_layout_clusterRight(children[n - 1]) : node;
-  }
-  function d3_layout_treeSeparation(a, b) {
-    return a.parent == b.parent ? 1 : 2;
-  }
-  function d3_layout_treeLeft(node) {
-    var children = node.children;
-    return children && children.length ? children[0] : node._tree.thread;
-  }
-  function d3_layout_treeRight(node) {
-    var children = node.children, n;
-    return children && (n = children.length) ? children[n - 1] : node._tree.thread;
-  }
-  function d3_layout_treeSearch(node, compare) {
-    var children = node.children;
-    if (children && (n = children.length)) {
-      var child, n, i = -1;
-      while (++i < n) {
-        if (compare(child = d3_layout_treeSearch(children[i], compare), node) > 0) {
-          node = child;
-        }
-      }
-    }
-    return node;
-  }
-  function d3_layout_treeRightmost(a, b) {
-    return a.x - b.x;
-  }
-  function d3_layout_treeLeftmost(a, b) {
-    return b.x - a.x;
-  }
-  function d3_layout_treeDeepest(a, b) {
-    return a.depth - b.depth;
-  }
-  function d3_layout_treeVisitAfter(node, callback) {
-    function visit(node, previousSibling) {
-      var children = node.children;
-      if (children && (n = children.length)) {
-        var child, previousChild = null, i = -1, n;
-        while (++i < n) {
-          child = children[i];
-          visit(child, previousChild);
-          previousChild = child;
-        }
-      }
-      callback(node, previousSibling);
-    }
-    visit(node, null);
-  }
-  function d3_layout_treeShift(node) {
-    var shift = 0, change = 0, children = node.children, i = children.length, child;
-    while (--i >= 0) {
-      child = children[i]._tree;
-      child.prelim += shift;
-      child.mod += shift;
-      shift += child.shift + (change += child.change);
-    }
-  }
-  function d3_layout_treeMove(ancestor, node, shift) {
-    ancestor = ancestor._tree;
-    node = node._tree;
-    var change = shift / (node.number - ancestor.number);
-    ancestor.change += change;
-    node.change -= change;
-    node.shift += shift;
-    node.prelim += shift;
-    node.mod += shift;
-  }
-  function d3_layout_treeAncestor(vim, node, ancestor) {
-    return vim._tree.ancestor.parent == node.parent ? vim._tree.ancestor : ancestor;
-  }
-  function d3_layout_treemapPadNull(node) {
-    return {
-      x: node.x,
-      y: node.y,
-      dx: node.dx,
-      dy: node.dy
-    };
-  }
-  function d3_layout_treemapPad(node, padding) {
-    var x = node.x + padding[3], y = node.y + padding[0], dx = node.dx - padding[1] - padding[3], dy = node.dy - padding[0] - padding[2];
-    if (dx < 0) {
-      x += dx / 2;
-      dx = 0;
-    }
-    if (dy < 0) {
-      y += dy / 2;
-      dy = 0;
-    }
-    return {
-      x: x,
-      y: y,
-      dx: dx,
-      dy: dy
-    };
-  }
-  function d3_dsv(delimiter, mimeType) {
-    function dsv(url, callback) {
-      d3.text(url, mimeType, function(text) {
-        callback(text && dsv.parse(text));
-      });
-    }
-    function formatRow(row) {
-      return row.map(formatValue).join(delimiter);
-    }
-    function formatValue(text) {
-      return reFormat.test(text) ? '"' + text.replace(/\"/g, '""') + '"' : text;
-    }
-    var reParse = new RegExp("\r\n|[" + delimiter + "\r\n]", "g"), reFormat = new RegExp('["' + delimiter + "\n]"), delimiterCode = delimiter.charCodeAt(0);
-    dsv.parse = function(text) {
-      var header;
-      return dsv.parseRows(text, function(row, i) {
-        if (i) {
-          var o = {}, j = -1, m = header.length;
-          while (++j < m) o[header[j]] = row[j];
-          return o;
-        } else {
-          header = row;
-          return null;
-        }
-      });
-    };
-    dsv.parseRows = function(text, f) {
-      function token() {
-        if (reParse.lastIndex >= text.length) return EOF;
-        if (eol) {
-          eol = false;
-          return EOL;
-        }
-        var j = reParse.lastIndex;
-        if (text.charCodeAt(j) === 34) {
-          var i = j;
-          while (i++ < text.length) {
-            if (text.charCodeAt(i) === 34) {
-              if (text.charCodeAt(i + 1) !== 34) break;
-              i++;
-            }
-          }
-          reParse.lastIndex = i + 2;
-          var c = text.charCodeAt(i + 1);
-          if (c === 13) {
-            eol = true;
-            if (text.charCodeAt(i + 2) === 10) reParse.lastIndex++;
-          } else if (c === 10) {
-            eol = true;
-          }
-          return text.substring(j + 1, i).replace(/""/g, '"');
-        }
-        var m = reParse.exec(text);
-        if (m) {
-          eol = m[0].charCodeAt(0) !== delimiterCode;
-          return text.substring(j, m.index);
-        }
-        reParse.lastIndex = text.length;
-        return text.substring(j);
-      }
-      var EOL = {}, EOF = {}, rows = [], n = 0, t, eol;
-      reParse.lastIndex = 0;
-      while ((t = token()) !== EOF) {
-        var a = [];
-        while (t !== EOL && t !== EOF) {
-          a.push(t);
-          t = token();
-        }
-        if (f && !(a = f(a, n++))) continue;
-        rows.push(a);
-      }
-      return rows;
-    };
-    dsv.format = function(rows) {
-      return rows.map(formatRow).join("\n");
-    };
-    return dsv;
-  }
-  function d3_geo_type(types, defaultValue) {
-    return function(object) {
-      return object && types.hasOwnProperty(object.type) ? types[object.type](object) : defaultValue;
-    };
-  }
-  function d3_path_circle(radius) {
-    return "m0," + radius + "a" + radius + "," + radius + " 0 1,1 0," + -2 * radius + "a" + radius + "," + radius + " 0 1,1 0," + +2 * radius + "z";
-  }
-  function d3_geo_bounds(o, f) {
-    if (d3_geo_boundsTypes.hasOwnProperty(o.type)) d3_geo_boundsTypes[o.type](o, f);
-  }
-  function d3_geo_boundsFeature(o, f) {
-    d3_geo_bounds(o.geometry, f);
-  }
-  function d3_geo_boundsFeatureCollection(o, f) {
-    for (var a = o.features, i = 0, n = a.length; i < n; i++) {
-      d3_geo_bounds(a[i].geometry, f);
-    }
-  }
-  function d3_geo_boundsGeometryCollection(o, f) {
-    for (var a = o.geometries, i = 0, n = a.length; i < n; i++) {
-      d3_geo_bounds(a[i], f);
-    }
-  }
-  function d3_geo_boundsLineString(o, f) {
-    for (var a = o.coordinates, i = 0, n = a.length; i < n; i++) {
-      f.apply(null, a[i]);
-    }
-  }
-  function d3_geo_boundsMultiLineString(o, f) {
-    for (var a = o.coordinates, i = 0, n = a.length; i < n; i++) {
-      for (var b = a[i], j = 0, m = b.length; j < m; j++) {
-        f.apply(null, b[j]);
-      }
-    }
-  }
-  function d3_geo_boundsMultiPolygon(o, f) {
-    for (var a = o.coordinates, i = 0, n = a.length; i < n; i++) {
-      for (var b = a[i][0], j = 0, m = b.length; j < m; j++) {
-        f.apply(null, b[j]);
-      }
-    }
-  }
-  function d3_geo_boundsPoint(o, f) {
-    f.apply(null, o.coordinates);
-  }
-  function d3_geo_boundsPolygon(o, f) {
-    for (var a = o.coordinates[0], i = 0, n = a.length; i < n; i++) {
-      f.apply(null, a[i]);
-    }
-  }
-  function d3_geo_greatArcSource(d) {
-    return d.source;
-  }
-  function d3_geo_greatArcTarget(d) {
-    return d.target;
-  }
-  function d3_geo_greatArcInterpolator() {
-    function interpolate(t) {
-      var B = Math.sin(t *= d) * k, A = Math.sin(d - t) * k, x = A * kx0 + B * kx1, y = A * ky0 + B * ky1, z = A * sy0 + B * sy1;
-      return [ Math.atan2(y, x) / d3_geo_radians, Math.atan2(z, Math.sqrt(x * x + y * y)) / d3_geo_radians ];
-    }
-    var x0, y0, cy0, sy0, kx0, ky0, x1, y1, cy1, sy1, kx1, ky1, d, k;
-    interpolate.distance = function() {
-      if (d == null) k = 1 / Math.sin(d = Math.acos(Math.max(-1, Math.min(1, sy0 * sy1 + cy0 * cy1 * Math.cos(x1 - x0)))));
-      return d;
-    };
-    interpolate.source = function(_) {
-      var cx0 = Math.cos(x0 = _[0] * d3_geo_radians), sx0 = Math.sin(x0);
-      cy0 = Math.cos(y0 = _[1] * d3_geo_radians);
-      sy0 = Math.sin(y0);
-      kx0 = cy0 * cx0;
-      ky0 = cy0 * sx0;
-      d = null;
-      return interpolate;
-    };
-    interpolate.target = function(_) {
-      var cx1 = Math.cos(x1 = _[0] * d3_geo_radians), sx1 = Math.sin(x1);
-      cy1 = Math.cos(y1 = _[1] * d3_geo_radians);
-      sy1 = Math.sin(y1);
-      kx1 = cy1 * cx1;
-      ky1 = cy1 * sx1;
-      d = null;
-      return interpolate;
-    };
-    return interpolate;
-  }
-  function d3_geo_greatArcInterpolate(a, b) {
-    var i = d3_geo_greatArcInterpolator().source(a).target(b);
-    i.distance();
-    return i;
-  }
-  function d3_geom_contourStart(grid) {
-    var x = 0, y = 0;
-    while (true) {
-      if (grid(x, y)) {
-        return [ x, y ];
-      }
-      if (x === 0) {
-        x = y + 1;
-        y = 0;
-      } else {
-        x = x - 1;
-        y = y + 1;
-      }
-    }
-  }
-  function d3_geom_hullCCW(i1, i2, i3, v) {
-    var t, a, b, c, d, e, f;
-    t = v[i1];
-    a = t[0];
-    b = t[1];
-    t = v[i2];
-    c = t[0];
-    d = t[1];
-    t = v[i3];
-    e = t[0];
-    f = t[1];
-    return (f - b) * (c - a) - (d - b) * (e - a) > 0;
-  }
-  function d3_geom_polygonInside(p, a, b) {
-    return (b[0] - a[0]) * (p[1] - a[1]) < (b[1] - a[1]) * (p[0] - a[0]);
-  }
-  function d3_geom_polygonIntersect(c, d, a, b) {
-    var x1 = c[0], x2 = d[0], x3 = a[0], x4 = b[0], y1 = c[1], y2 = d[1], y3 = a[1], y4 = b[1], x13 = x1 - x3, x21 = x2 - x1, x43 = x4 - x3, y13 = y1 - y3, y21 = y2 - y1, y43 = y4 - y3, ua = (x43 * y13 - y43 * x13) / (y43 * x21 - x43 * y21);
-    return [ x1 + ua * x21, y1 + ua * y21 ];
-  }
-  function d3_voronoi_tessellate(vertices, callback) {
-    var Sites = {
-      list: vertices.map(function(v, i) {
-        return {
-          index: i,
-          x: v[0],
-          y: v[1]
-        };
-      }).sort(function(a, b) {
-        return a.y < b.y ? -1 : a.y > b.y ? 1 : a.x < b.x ? -1 : a.x > b.x ? 1 : 0;
-      }),
-      bottomSite: null
-    };
-    var EdgeList = {
-      list: [],
-      leftEnd: null,
-      rightEnd: null,
-      init: function() {
-        EdgeList.leftEnd = EdgeList.createHalfEdge(null, "l");
-        EdgeList.rightEnd = EdgeList.createHalfEdge(null, "l");
-        EdgeList.leftEnd.r = EdgeList.rightEnd;
-        EdgeList.rightEnd.l = EdgeList.leftEnd;
-        EdgeList.list.unshift(EdgeList.leftEnd, EdgeList.rightEnd);
-      },
-      createHalfEdge: function(edge, side) {
-        return {
-          edge: edge,
-          side: side,
-          vertex: null,
-          l: null,
-          r: null
-        };
-      },
-      insert: function(lb, he) {
-        he.l = lb;
-        he.r = lb.r;
-        lb.r.l = he;
-        lb.r = he;
-      },
-      leftBound: function(p) {
-        var he = EdgeList.leftEnd;
-        do {
-          he = he.r;
-        } while (he != EdgeList.rightEnd && Geom.rightOf(he, p));
-        he = he.l;
-        return he;
-      },
-      del: function(he) {
-        he.l.r = he.r;
-        he.r.l = he.l;
-        he.edge = null;
-      },
-      right: function(he) {
-        return he.r;
-      },
-      left: function(he) {
-        return he.l;
-      },
-      leftRegion: function(he) {
-        return he.edge == null ? Sites.bottomSite : he.edge.region[he.side];
-      },
-      rightRegion: function(he) {
-        return he.edge == null ? Sites.bottomSite : he.edge.region[d3_voronoi_opposite[he.side]];
-      }
-    };
-    var Geom = {
-      bisect: function(s1, s2) {
-        var newEdge = {
-          region: {
-            l: s1,
-            r: s2
-          },
-          ep: {
-            l: null,
-            r: null
-          }
-        };
-        var dx = s2.x - s1.x, dy = s2.y - s1.y, adx = dx > 0 ? dx : -dx, ady = dy > 0 ? dy : -dy;
-        newEdge.c = s1.x * dx + s1.y * dy + (dx * dx + dy * dy) * .5;
-        if (adx > ady) {
-          newEdge.a = 1;
-          newEdge.b = dy / dx;
-          newEdge.c /= dx;
-        } else {
-          newEdge.b = 1;
-          newEdge.a = dx / dy;
-          newEdge.c /= dy;
-        }
-        return newEdge;
-      },
-      intersect: function(el1, el2) {
-        var e1 = el1.edge, e2 = el2.edge;
-        if (!e1 || !e2 || e1.region.r == e2.region.r) {
-          return null;
-        }
-        var d = e1.a * e2.b - e1.b * e2.a;
-        if (Math.abs(d) < 1e-10) {
-          return null;
-        }
-        var xint = (e1.c * e2.b - e2.c * e1.b) / d, yint = (e2.c * e1.a - e1.c * e2.a) / d, e1r = e1.region.r, e2r = e2.region.r, el, e;
-        if (e1r.y < e2r.y || e1r.y == e2r.y && e1r.x < e2r.x) {
-          el = el1;
-          e = e1;
-        } else {
-          el = el2;
-          e = e2;
-        }
-        var rightOfSite = xint >= e.region.r.x;
-        if (rightOfSite && el.side === "l" || !rightOfSite && el.side === "r") {
-          return null;
-        }
-        return {
-          x: xint,
-          y: yint
-        };
-      },
-      rightOf: function(he, p) {
-        var e = he.edge, topsite = e.region.r, rightOfSite = p.x > topsite.x;
-        if (rightOfSite && he.side === "l") {
-          return 1;
-        }
-        if (!rightOfSite && he.side === "r") {
-          return 0;
-        }
-        if (e.a === 1) {
-          var dyp = p.y - topsite.y, dxp = p.x - topsite.x, fast = 0, above = 0;
-          if (!rightOfSite && e.b < 0 || rightOfSite && e.b >= 0) {
-            above = fast = dyp >= e.b * dxp;
-          } else {
-            above = p.x + p.y * e.b > e.c;
-            if (e.b < 0) {
-              above = !above;
-            }
-            if (!above) {
-              fast = 1;
-            }
-          }
-          if (!fast) {
-            var dxs = topsite.x - e.region.l.x;
-            above = e.b * (dxp * dxp - dyp * dyp) < dxs * dyp * (1 + 2 * dxp / dxs + e.b * e.b);
-            if (e.b < 0) {
-              above = !above;
-            }
-          }
-        } else {
-          var yl = e.c - e.a * p.x, t1 = p.y - yl, t2 = p.x - topsite.x, t3 = yl - topsite.y;
-          above = t1 * t1 > t2 * t2 + t3 * t3;
-        }
-        return he.side === "l" ? above : !above;
-      },
-      endPoint: function(edge, side, site) {
-        edge.ep[side] = site;
-        if (!edge.ep[d3_voronoi_opposite[side]]) return;
-        callback(edge);
-      },
-      distance: function(s, t) {
-        var dx = s.x - t.x, dy = s.y - t.y;
-        return Math.sqrt(dx * dx + dy * dy);
-      }
-    };
-    var EventQueue = {
-      list: [],
-      insert: function(he, site, offset) {
-        he.vertex = site;
-        he.ystar = site.y + offset;
-        for (var i = 0, list = EventQueue.list, l = list.length; i < l; i++) {
-          var next = list[i];
-          if (he.ystar > next.ystar || he.ystar == next.ystar && site.x > next.vertex.x) {
-            continue;
-          } else {
-            break;
-          }
-        }
-        list.splice(i, 0, he);
-      },
-      del: function(he) {
-        for (var i = 0, ls = EventQueue.list, l = ls.length; i < l && ls[i] != he; ++i) {}
-        ls.splice(i, 1);
-      },
-      empty: function() {
-        return EventQueue.list.length === 0;
-      },
-      nextEvent: function(he) {
-        for (var i = 0, ls = EventQueue.list, l = ls.length; i < l; ++i) {
-          if (ls[i] == he) return ls[i + 1];
-        }
-        return null;
-      },
-      min: function() {
-        var elem = EventQueue.list[0];
-        return {
-          x: elem.vertex.x,
-          y: elem.ystar
-        };
-      },
-      extractMin: function() {
-        return EventQueue.list.shift();
-      }
-    };
-    EdgeList.init();
-    Sites.bottomSite = Sites.list.shift();
-    var newSite = Sites.list.shift(), newIntStar;
-    var lbnd, rbnd, llbnd, rrbnd, bisector;
-    var bot, top, temp, p, v;
-    var e, pm;
-    while (true) {
-      if (!EventQueue.empty()) {
-        newIntStar = EventQueue.min();
-      }
-      if (newSite && (EventQueue.empty() || newSite.y < newIntStar.y || newSite.y == newIntStar.y && newSite.x < newIntStar.x)) {
-        lbnd = EdgeList.leftBound(newSite);
-        rbnd = EdgeList.right(lbnd);
-        bot = EdgeList.rightRegion(lbnd);
-        e = Geom.bisect(bot, newSite);
-        bisector = EdgeList.createHalfEdge(e, "l");
-        EdgeList.insert(lbnd, bisector);
-        p = Geom.intersect(lbnd, bisector);
-        if (p) {
-          EventQueue.del(lbnd);
-          EventQueue.insert(lbnd, p, Geom.distance(p, newSite));
-        }
-        lbnd = bisector;
-        bisector = EdgeList.createHalfEdge(e, "r");
-        EdgeList.insert(lbnd, bisector);
-        p = Geom.intersect(bisector, rbnd);
-        if (p) {
-          EventQueue.insert(bisector, p, Geom.distance(p, newSite));
-        }
-        newSite = Sites.list.shift();
-      } else if (!EventQueue.empty()) {
-        lbnd = EventQueue.extractMin();
-        llbnd = EdgeList.left(lbnd);
-        rbnd = EdgeList.right(lbnd);
-        rrbnd = EdgeList.right(rbnd);
-        bot = EdgeList.leftRegion(lbnd);
-        top = EdgeList.rightRegion(rbnd);
-        v = lbnd.vertex;
-        Geom.endPoint(lbnd.edge, lbnd.side, v);
-        Geom.endPoint(rbnd.edge, rbnd.side, v);
-        EdgeList.del(lbnd);
-        EventQueue.del(rbnd);
-        EdgeList.del(rbnd);
-        pm = "l";
-        if (bot.y > top.y) {
-          temp = bot;
-          bot = top;
-          top = temp;
-          pm = "r";
-        }
-        e = Geom.bisect(bot, top);
-        bisector = EdgeList.createHalfEdge(e, pm);
-        EdgeList.insert(llbnd, bisector);
-        Geom.endPoint(e, d3_voronoi_opposite[pm], v);
-        p = Geom.intersect(llbnd, bisector);
-        if (p) {
-          EventQueue.del(llbnd);
-          EventQueue.insert(llbnd, p, Geom.distance(p, bot));
-        }
-        p = Geom.intersect(bisector, rrbnd);
-        if (p) {
-          EventQueue.insert(bisector, p, Geom.distance(p, bot));
-        }
-      } else {
-        break;
-      }
-    }
-    for (lbnd = EdgeList.right(EdgeList.leftEnd); lbnd != EdgeList.rightEnd; lbnd = EdgeList.right(lbnd)) {
-      callback(lbnd.edge);
-    }
-  }
-  function d3_geom_quadtreeNode() {
-    return {
-      leaf: true,
-      nodes: [],
-      point: null
-    };
-  }
-  function d3_geom_quadtreeVisit(f, node, x1, y1, x2, y2) {
-    if (!f(node, x1, y1, x2, y2)) {
-      var sx = (x1 + x2) * .5, sy = (y1 + y2) * .5, children = node.nodes;
-      if (children[0]) d3_geom_quadtreeVisit(f, children[0], x1, y1, sx, sy);
-      if (children[1]) d3_geom_quadtreeVisit(f, children[1], sx, y1, x2, sy);
-      if (children[2]) d3_geom_quadtreeVisit(f, children[2], x1, sy, sx, y2);
-      if (children[3]) d3_geom_quadtreeVisit(f, children[3], sx, sy, x2, y2);
-    }
-  }
-  function d3_geom_quadtreePoint(p) {
-    return {
-      x: p[0],
-      y: p[1]
-    };
-  }
-  function d3_time_utc() {
-    this._ = new Date(arguments.length > 1 ? Date.UTC.apply(this, arguments) : arguments[0]);
-  }
-  function d3_time_formatAbbreviate(name) {
-    return name.substring(0, 3);
-  }
-  function d3_time_parse(date, template, string, j) {
-    var c, p, i = 0, n = template.length, m = string.length;
-    while (i < n) {
-      if (j >= m) return -1;
-      c = template.charCodeAt(i++);
-      if (c == 37) {
-        p = d3_time_parsers[template.charAt(i++)];
-        if (!p || (j = p(date, string, j)) < 0) return -1;
-      } else if (c != string.charCodeAt(j++)) {
-        return -1;
-      }
-    }
-    return j;
-  }
-  function d3_time_formatRe(names) {
-    return new RegExp("^(?:" + names.map(d3.requote).join("|") + ")", "i");
-  }
-  function d3_time_formatLookup(names) {
-    var map = new d3_Map, i = -1, n = names.length;
-    while (++i < n) map.set(names[i].toLowerCase(), i);
-    return map;
-  }
-  function d3_time_parseWeekdayAbbrev(date, string, i) {
-    d3_time_dayAbbrevRe.lastIndex = 0;
-    var n = d3_time_dayAbbrevRe.exec(string.substring(i));
-    return n ? i += n[0].length : -1;
-  }
-  function d3_time_parseWeekday(date, string, i) {
-    d3_time_dayRe.lastIndex = 0;
-    var n = d3_time_dayRe.exec(string.substring(i));
-    return n ? i += n[0].length : -1;
-  }
-  function d3_time_parseMonthAbbrev(date, string, i) {
-    d3_time_monthAbbrevRe.lastIndex = 0;
-    var n = d3_time_monthAbbrevRe.exec(string.substring(i));
-    return n ? (date.m = d3_time_monthAbbrevLookup.get(n[0].toLowerCase()), i += n[0].length) : -1;
-  }
-  function d3_time_parseMonth(date, string, i) {
-    d3_time_monthRe.lastIndex = 0;
-    var n = d3_time_monthRe.exec(string.substring(i));
-    return n ? (date.m = d3_time_monthLookup.get(n[0].toLowerCase()), i += n[0].length) : -1;
-  }
-  function d3_time_parseLocaleFull(date, string, i) {
-    return d3_time_parse(date, d3_time_formats.c.toString(), string, i);
-  }
-  function d3_time_parseLocaleDate(date, string, i) {
-    return d3_time_parse(date, d3_time_formats.x.toString(), string, i);
-  }
-  function d3_time_parseLocaleTime(date, string, i) {
-    return d3_time_parse(date, d3_time_formats.X.toString(), string, i);
-  }
-  function d3_time_parseFullYear(date, string, i) {
-    d3_time_numberRe.lastIndex = 0;
-    var n = d3_time_numberRe.exec(string.substring(i, i + 4));
-    return n ? (date.y = +n[0], i += n[0].length) : -1;
-  }
-  function d3_time_parseYear(date, string, i) {
-    d3_time_numberRe.lastIndex = 0;
-    var n = d3_time_numberRe.exec(string.substring(i, i + 2));
-    return n ? (date.y = d3_time_expandYear(+n[0]), i += n[0].length) : -1;
-  }
-  function d3_time_expandYear(d) {
-    return d + (d > 68 ? 1900 : 2e3);
-  }
-  function d3_time_parseMonthNumber(date, string, i) {
-    d3_time_numberRe.lastIndex = 0;
-    var n = d3_time_numberRe.exec(string.substring(i, i + 2));
-    return n ? (date.m = n[0] - 1, i += n[0].length) : -1;
-  }
-  function d3_time_parseDay(date, string, i) {
-    d3_time_numberRe.lastIndex = 0;
-    var n = d3_time_numberRe.exec(string.substring(i, i + 2));
-    return n ? (date.d = +n[0], i += n[0].length) : -1;
-  }
-  function d3_time_parseHour24(date, string, i) {
-    d3_time_numberRe.lastIndex = 0;
-    var n = d3_time_numberRe.exec(string.substring(i, i + 2));
-    return n ? (date.H = +n[0], i += n[0].length) : -1;
-  }
-  function d3_time_parseMinutes(date, string, i) {
-    d3_time_numberRe.lastIndex = 0;
-    var n = d3_time_numberRe.exec(string.substring(i, i + 2));
-    return n ? (date.M = +n[0], i += n[0].length) : -1;
-  }
-  function d3_time_parseSeconds(date, string, i) {
-    d3_time_numberRe.lastIndex = 0;
-    var n = d3_time_numberRe.exec(string.substring(i, i + 2));
-    return n ? (date.S = +n[0], i += n[0].length) : -1;
-  }
-  function d3_time_parseMilliseconds(date, string, i) {
-    d3_time_numberRe.lastIndex = 0;
-    var n = d3_time_numberRe.exec(string.substring(i, i + 3));
-    return n ? (date.L = +n[0], i += n[0].length) : -1;
-  }
-  function d3_time_parseAmPm(date, string, i) {
-    var n = d3_time_amPmLookup.get(string.substring(i, i += 2).toLowerCase());
-    return n == null ? -1 : (date.p = n, i);
-  }
-  function d3_time_zone(d) {
-    var z = d.getTimezoneOffset(), zs = z > 0 ? "-" : "+", zh = ~~(Math.abs(z) / 60), zm = Math.abs(z) % 60;
-    return zs + d3_time_zfill2(zh) + d3_time_zfill2(zm);
-  }
-  function d3_time_formatIsoNative(date) {
-    return date.toISOString();
-  }
-  function d3_time_interval(local, step, number) {
-    function round(date) {
-      var d0 = local(date), d1 = offset(d0, 1);
-      return date - d0 < d1 - date ? d0 : d1;
-    }
-    function ceil(date) {
-      step(date = local(new d3_time(date - 1)), 1);
-      return date;
-    }
-    function offset(date, k) {
-      step(date = new d3_time(+date), k);
-      return date;
-    }
-    function range(t0, t1, dt) {
-      var time = ceil(t0), times = [];
-      if (dt > 1) {
-        while (time < t1) {
-          if (!(number(time) % dt)) times.push(new Date(+time));
-          step(time, 1);
-        }
-      } else {
-        while (time < t1) times.push(new Date(+time)), step(time, 1);
-      }
-      return times;
-    }
-    function range_utc(t0, t1, dt) {
-      try {
-        d3_time = d3_time_utc;
-        var utc = new d3_time_utc;
-        utc._ = t0;
-        return range(utc, t1, dt);
-      } finally {
-        d3_time = Date;
-      }
-    }
-    local.floor = local;
-    local.round = round;
-    local.ceil = ceil;
-    local.offset = offset;
-    local.range = range;
-    var utc = local.utc = d3_time_interval_utc(local);
-    utc.floor = utc;
-    utc.round = d3_time_interval_utc(round);
-    utc.ceil = d3_time_interval_utc(ceil);
-    utc.offset = d3_time_interval_utc(offset);
-    utc.range = range_utc;
-    return local;
-  }
-  function d3_time_interval_utc(method) {
-    return function(date, k) {
-      try {
-        d3_time = d3_time_utc;
-        var utc = new d3_time_utc;
-        utc._ = date;
-        return method(utc, k)._;
-      } finally {
-        d3_time = Date;
-      }
-    };
-  }
-  function d3_time_scale(linear, methods, format) {
-    function scale(x) {
-      return linear(x);
-    }
-    scale.invert = function(x) {
-      return d3_time_scaleDate(linear.invert(x));
-    };
-    scale.domain = function(x) {
-      if (!arguments.length) return linear.domain().map(d3_time_scaleDate);
-      linear.domain(x);
-      return scale;
-    };
-    scale.nice = function(m) {
-      return scale.domain(d3_scale_nice(scale.domain(), function() {
-        return m;
-      }));
-    };
-    scale.ticks = function(m, k) {
-      var extent = d3_time_scaleExtent(scale.domain());
-      if (typeof m !== "function") {
-        var span = extent[1] - extent[0], target = span / m, i = d3.bisect(d3_time_scaleSteps, target);
-        if (i == d3_time_scaleSteps.length) return methods.year(extent, m);
-        if (!i) return linear.ticks(m).map(d3_time_scaleDate);
-        if (Math.log(target / d3_time_scaleSteps[i - 1]) < Math.log(d3_time_scaleSteps[i] / target)) --i;
-        m = methods[i];
-        k = m[1];
-        m = m[0].range;
-      }
-      return m(extent[0], new Date(+extent[1] + 1), k);
-    };
-    scale.tickFormat = function() {
-      return format;
-    };
-    scale.copy = function() {
-      return d3_time_scale(linear.copy(), methods, format);
-    };
-    return d3.rebind(scale, linear, "range", "rangeRound", "interpolate", "clamp");
-  }
-  function d3_time_scaleExtent(domain) {
-    var start = domain[0], stop = domain[domain.length - 1];
-    return start < stop ? [ start, stop ] : [ stop, start ];
-  }
-  function d3_time_scaleDate(t) {
-    return new Date(t);
-  }
-  function d3_time_scaleFormat(formats) {
-    return function(date) {
-      var i = formats.length - 1, f = formats[i];
-      while (!f[1](date)) f = formats[--i];
-      return f[0](date);
-    };
-  }
-  function d3_time_scaleSetYear(y) {
-    var d = new Date(y, 0, 1);
-    d.setFullYear(y);
-    return d;
-  }
-  function d3_time_scaleGetYear(d) {
-    var y = d.getFullYear(), d0 = d3_time_scaleSetYear(y), d1 = d3_time_scaleSetYear(y + 1);
-    return y + (d - d0) / (d1 - d0);
-  }
-  function d3_time_scaleUTCSetYear(y) {
-    var d = new Date(Date.UTC(y, 0, 1));
-    d.setUTCFullYear(y);
-    return d;
-  }
-  function d3_time_scaleUTCGetYear(d) {
-    var y = d.getUTCFullYear(), d0 = d3_time_scaleUTCSetYear(y), d1 = d3_time_scaleUTCSetYear(y + 1);
-    return y + (d - d0) / (d1 - d0);
-  }
-  if (!Date.now) Date.now = function() {
-    return +(new Date);
-  };
-  try {
-    document.createElement("div").style.setProperty("opacity", 0, "");
-  } catch (error) {
-    var d3_style_prototype = CSSStyleDeclaration.prototype, d3_style_setProperty = d3_style_prototype.setProperty;
-    d3_style_prototype.setProperty = function(name, value, priority) {
-      d3_style_setProperty.call(this, name, value + "", priority);
-    };
-  }
-  d3 = {
-    version: "2.10.3"
-  };
-  var d3_array = d3_arraySlice;
-  try {
-    d3_array(document.documentElement.childNodes)[0].nodeType;
-  } catch (e) {
-    d3_array = d3_arrayCopy;
-  }
-  var d3_arraySubclass = [].__proto__ ? function(array, prototype) {
-    array.__proto__ = prototype;
-  } : function(array, prototype) {
-    for (var property in prototype) array[property] = prototype[property];
-  };
-  d3.map = function(object) {
-    var map = new d3_Map;
-    for (var key in object) map.set(key, object[key]);
-    return map;
-  };
-  d3_class(d3_Map, {
-    has: function(key) {
-      return d3_map_prefix + key in this;
-    },
-    get: function(key) {
-      return this[d3_map_prefix + key];
-    },
-    set: function(key, value) {
-      return this[d3_map_prefix + key] = value;
-    },
-    remove: function(key) {
-      key = d3_map_prefix + key;
-      return key in this && delete this[key];
-    },
-    keys: function() {
-      var keys = [];
-      this.forEach(function(key) {
-        keys.push(key);
-      });
-      return keys;
-    },
-    values: function() {
-      var values = [];
-      this.forEach(function(key, value) {
-        values.push(value);
-      });
-      return values;
-    },
-    entries: function() {
-      var entries = [];
-      this.forEach(function(key, value) {
-        entries.push({
-          key: key,
-          value: value
-        });
-      });
-      return entries;
-    },
-    forEach: function(f) {
-      for (var key in this) {
-        if (key.charCodeAt(0) === d3_map_prefixCode) {
-          f.call(this, key.substring(1), this[key]);
-        }
-      }
-    }
-  });
-  var d3_map_prefix = "\0", d3_map_prefixCode = d3_map_prefix.charCodeAt(0);
-  d3.functor = d3_functor;
-  d3.rebind = function(target, source) {
-    var i = 1, n = arguments.length, method;
-    while (++i < n) target[method = arguments[i]] = d3_rebind(target, source, source[method]);
-    return target;
-  };
-  d3.ascending = function(a, b) {
-    return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
-  };
-  d3.descending = function(a, b) {
-    return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;
-  };
-  d3.mean = function(array, f) {
-    var n = array.length, a, m = 0, i = -1, j = 0;
-    if (arguments.length === 1) {
-      while (++i < n) if (d3_number(a = array[i])) m += (a - m) / ++j;
-    } else {
-      while (++i < n) if (d3_number(a = f.call(array, array[i], i))) m += (a - m) / ++j;
-    }
-    return j ? m : undefined;
-  };
-  d3.median = function(array, f) {
-    if (arguments.length > 1) array = array.map(f);
-    array = array.filter(d3_number);
-    return array.length ? d3.quantile(array.sort(d3.ascending), .5) : undefined;
-  };
-  d3.min = function(array, f) {
-    var i = -1, n = array.length, a, b;
-    if (arguments.length === 1) {
-      while (++i < n && ((a = array[i]) == null || a != a)) a = undefined;
-      while (++i < n) if ((b = array[i]) != null && a > b) a = b;
-    } else {
-      while (++i < n && ((a = f.call(array, array[i], i)) == null || a != a)) a = undefined;
-      while (++i < n) if ((b = f.call(array, array[i], i)) != null && a > b) a = b;
-    }
-    return a;
-  };
-  d3.max = function(array, f) {
-    var i = -1, n = array.length, a, b;
-    if (arguments.length === 1) {
-      while (++i < n && ((a = array[i]) == null || a != a)) a = undefined;
-      while (++i < n) if ((b = array[i]) != null && b > a) a = b;
-    } else {
-      while (++i < n && ((a = f.call(array, array[i], i)) == null || a != a)) a = undefined;
-      while (++i < n) if ((b = f.call(array, array[i], i)) != null && b > a) a = b;
-    }
-    return a;
-  };
-  d3.extent = function(array, f) {
-    var i = -1, n = array.length, a, b, c;
-    if (arguments.length === 1) {
-      while (++i < n && ((a = c = array[i]) == null || a != a)) a = c = undefined;
-      while (++i < n) if ((b = array[i]) != null) {
-        if (a > b) a = b;
-        if (c < b) c = b;
-      }
-    } else {
-      while (++i < n && ((a = c = f.call(array, array[i], i)) == null || a != a)) a = undefined;
-      while (++i < n) if ((b = f.call(array, array[i], i)) != null) {
-        if (a > b) a = b;
-        if (c < b) c = b;
-      }
-    }
-    return [ a, c ];
-  };
-  d3.random = {
-    normal: function(µ, σ) {
-      var n = arguments.length;
-      if (n < 2) σ = 1;
-      if (n < 1) µ = 0;
-      return function() {
-        var x, y, r;
-        d

<TRUNCATED>

[25/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/js/libs/ace/ext-language_tools.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/js/libs/ace/ext-language_tools.js b/apps/fauxton/assets/js/libs/ace/ext-language_tools.js
deleted file mode 100644
index d6e6ef6..0000000
--- a/apps/fauxton/assets/js/libs/ace/ext-language_tools.js
+++ /dev/null
@@ -1,1615 +0,0 @@
-/* ***** BEGIN LICENSE BLOCK *****
- * Distributed under the BSD license:
- *
- * Copyright (c) 2012, Ajax.org B.V.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above copyright
- *       notice, this list of conditions and the following disclaimer in the
- *       documentation and/or other materials provided with the distribution.
- *     * Neither the name of Ajax.org B.V. nor the
- *       names of its contributors may be used to endorse or promote products
- *       derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * ***** END LICENSE BLOCK ***** */
-
-define('ace/ext/language_tools', ['require', 'exports', 'module' , 'ace/snippets', 'ace/autocomplete', 'ace/config', 'ace/autocomplete/text_completer', 'ace/editor'], function(require, exports, module) {
-
-
-var snippetManager = require("../snippets").snippetManager;
-var Autocomplete = require("../autocomplete").Autocomplete;
-var config = require("../config");
-
-var textCompleter = require("../autocomplete/text_completer");
-var keyWordCompleter = {
-    getCompletions: function(editor, session, pos, prefix, callback) {
-        var state = editor.session.getState(pos.row);
-        var completions = session.$mode.getCompletions(state, session, pos, prefix);
-        callback(null, completions);
-    }
-};
-
-var snippetCompleter = {
-    getCompletions: function(editor, session, pos, prefix, callback) {
-        var scope = snippetManager.$getScope(editor);
-        var snippetMap = snippetManager.snippetMap;
-        var completions = [];
-        [scope, "_"].forEach(function(scope) {
-            var snippets = snippetMap[scope] || [];
-            for (var i = snippets.length; i--;) {
-                var s = snippets[i];
-                var caption = s.name || s.tabTrigger;
-                if (!caption)
-                    continue;
-                completions.push({
-                    caption: caption,
-                    snippet: s.content,
-                    meta: s.tabTrigger && !s.name ? s.tabTrigger + "\u21E5 " : "snippet"
-                });
-            }
-        }, this);
-        callback(null, completions);
-    }
-};
-
-var completers = [snippetCompleter, textCompleter, keyWordCompleter];
-exports.addCompleter = function(completer) {
-    completers.push(completer);
-};
-
-var expandSnippet = {
-    name: "expandSnippet",
-    exec: function(editor) {
-        var success = snippetManager.expandWithTab(editor);
-        if (!success)
-            editor.execCommand("indent");
-    },
-    bindKey: "tab"
-}
-
-var onChangeMode = function(e, editor) {
-    var mode = editor.session.$mode;
-    var id = mode.$id
-    if (!snippetManager.files) snippetManager.files = {};
-    if (id && !snippetManager.files[id]) {
-        var snippetFilePath = id.replace("mode", "snippets");
-        config.loadModule(snippetFilePath, function(m) {
-            if (m) {
-                snippetManager.files[id] = m;
-                m.snippets = snippetManager.parseSnippetFile(m.snippetText);
-                snippetManager.register(m.snippets, m.scope);
-            }
-        });
-    }
-};
-
-var Editor = require("../editor").Editor;
-require("../config").defineOptions(Editor.prototype, "editor", {
-    enableBasicAutocompletion: {
-        set: function(val) {
-            if (val) {
-                this.completers = completers
-                this.commands.addCommand(Autocomplete.startCommand);
-            } else {
-                this.commands.removeCommand(Autocomplete.startCommand);
-            }
-        },
-        value: false
-    },
-    enableSnippets: {
-        set: function(val) {
-            if (val) {
-                this.commands.addCommand(expandSnippet);
-                this.on("changeMode", onChangeMode);
-                onChangeMode(null, this)
-            } else {
-                this.commands.removeCommand(expandSnippet);
-                this.off("changeMode", onChangeMode);
-            }
-        },
-        value: false
-    }
-});
-
-});
-
-define('ace/snippets', ['require', 'exports', 'module' , 'ace/lib/lang', 'ace/range', 'ace/keyboard/hash_handler', 'ace/tokenizer', 'ace/lib/dom'], function(require, exports, module) {
-
-var lang = require("./lib/lang")
-var Range = require("./range").Range
-var HashHandler = require("./keyboard/hash_handler").HashHandler;
-var Tokenizer = require("./tokenizer").Tokenizer;
-var comparePoints = Range.comparePoints;
-
-var SnippetManager = function() {
-    this.snippetMap = {};
-    this.snippetNameMap = {};
-};
-
-(function() {
-    this.getTokenizer = function() {
-        function TabstopToken(str, _, stack) {
-            str = str.substr(1);
-            if (/^\d+$/.test(str) && !stack.inFormatString)
-                return [{tabstopId: parseInt(str, 10)}];
-            return [{text: str}]
-        }
-        function escape(ch) {
-            return "(?:[^\\\\" + ch + "]|\\\\.)";
-        }
-        SnippetManager.$tokenizer = new Tokenizer({
-            start: [
-                {regex: /:/, onMatch: function(val, state, stack) {
-                    if (stack.length && stack[0].expectIf) {
-                        stack[0].expectIf = false;
-                        stack[0].elseBranch = stack[0];
-                        return [stack[0]];
-                    }
-                    return ":";
-                }},
-                {regex: /\\./, onMatch: function(val, state, stack) {
-                    var ch = val[1];
-                    if (ch == "}" && stack.length) {
-                        val = ch;
-                    }else if ("`$\\".indexOf(ch) != -1) {
-                        val = ch;
-                    } else if (stack.inFormatString) {
-                        if (ch == "n")
-                            val = "\n";
-                        else if (ch == "t")
-                            val = "\n";
-                        else if ("ulULE".indexOf(ch) != -1) {
-                            val = {changeCase: ch, local: ch > "a"};
-                        }
-                    }
-
-                    return [val];
-                }},
-                {regex: /}/, onMatch: function(val, state, stack) {
-                    return [stack.length ? stack.shift() : val];
-                }},
-                {regex: /\$(?:\d+|\w+)/, onMatch: TabstopToken},
-                {regex: /\$\{[\dA-Z_a-z]+/, onMatch: function(str, state, stack) {
-                    var t = TabstopToken(str.substr(1), state, stack);
-                    stack.unshift(t[0]);
-                    return t;
-                }, next: "snippetVar"},
-                {regex: /\n/, token: "newline", merge: false}
-            ],
-            snippetVar: [
-                {regex: "\\|" + escape("\\|") + "*\\|", onMatch: function(val, state, stack) {
-                    stack[0].choices = val.slice(1, -1).split(",");
-                }, next: "start"},
-                {regex: "/(" + escape("/") + "+)/(?:(" + escape("/") + "*)/)(\\w*):?",
-                 onMatch: function(val, state, stack) {
-                    var ts = stack[0];
-                    ts.fmtString = val;
-
-                    val = this.splitRegex.exec(val);
-                    ts.guard = val[1];
-                    ts.fmt = val[2];
-                    ts.flag = val[3];
-                    return "";
-                }, next: "start"},
-                {regex: "`" + escape("`") + "*`", onMatch: function(val, state, stack) {
-                    stack[0].code = val.splice(1, -1);
-                    return "";
-                }, next: "start"},
-                {regex: "\\?", onMatch: function(val, state, stack) {
-                    if (stack[0])
-                        stack[0].expectIf = true;
-                }, next: "start"},
-                {regex: "([^:}\\\\]|\\\\.)*:?", token: "", next: "start"}
-            ],
-            formatString: [
-                {regex: "/(" + escape("/") + "+)/", token: "regex"},
-                {regex: "", onMatch: function(val, state, stack) {
-                    stack.inFormatString = true;
-                }, next: "start"}
-            ]
-        });
-        SnippetManager.prototype.getTokenizer = function() {
-            return SnippetManager.$tokenizer;
-        }
-        return SnippetManager.$tokenizer;
-    };
-
-    this.tokenizeTmSnippet = function(str, startState) {
-        return this.getTokenizer().getLineTokens(str, startState).tokens.map(function(x) {
-            return x.value || x;
-        });
-    };
-
-    this.$getDefaultValue = function(editor, name) {
-        if (/^[A-Z]\d+$/.test(name)) {
-            var i = name.substr(1);
-            return (this.variables[name[0] + "__"] || {})[i];
-        }
-        if (/^\d+$/.test(name)) {
-            return (this.variables.__ || {})[name];
-        }
-        name = name.replace(/^TM_/, "");
-
-        if (!editor)
-            return;
-        var s = editor.session;
-        switch(name) {
-            case "CURRENT_WORD":
-                var r = s.getWordRange();
-            case "SELECTION":
-            case "SELECTED_TEXT":
-                return s.getTextRange(r);
-            case "CURRENT_LINE":
-                return s.getLine(editor.getCursorPosition().row);
-            case "PREV_LINE": // not possible in textmate
-                return s.getLine(editor.getCursorPosition().row - 1);
-            case "LINE_INDEX":
-                return editor.getCursorPosition().column;
-            case "LINE_NUMBER":
-                return editor.getCursorPosition().row + 1;
-            case "SOFT_TABS":
-                return s.getUseSoftTabs() ? "YES" : "NO";
-            case "TAB_SIZE":
-                return s.getTabSize();
-            case "FILENAME":
-            case "FILEPATH":
-                return "ace.ajax.org";
-            case "FULLNAME":
-                return "Ace";
-        }
-    };
-    this.variables = {};
-    this.getVariableValue = function(editor, varName) {
-        if (this.variables.hasOwnProperty(varName))
-            return this.variables[varName](editor, varName) || "";
-        return this.$getDefaultValue(editor, varName) || "";
-    };
-    this.tmStrFormat = function(str, ch, editor) {
-        var flag = ch.flag || "";
-        var re = ch.guard;
-        re = new RegExp(re, flag.replace(/[^gi]/, ""));
-        var fmtTokens = this.tokenizeTmSnippet(ch.fmt, "formatString");
-        var _self = this;
-        var formatted = str.replace(re, function() {
-            _self.variables.__ = arguments;
-            var fmtParts = _self.resolveVariables(fmtTokens, editor);
-            var gChangeCase = "E";
-            for (var i  = 0; i < fmtParts.length; i++) {
-                var ch = fmtParts[i];
-                if (typeof ch == "object") {
-                    fmtParts[i] = "";
-                    if (ch.changeCase && ch.local) {
-                        var next = fmtParts[i + 1];
-                        if (next && typeof next == "string") {
-                            if (ch.changeCase == "u")
-                                fmtParts[i] = next[0].toUpperCase();
-                            else
-                                fmtParts[i] = next[0].toLowerCase();
-                            fmtParts[i + 1] = next.substr(1);
-                        }
-                    } else if (ch.changeCase) {
-                        gChangeCase = ch.changeCase;
-                    }
-                } else if (gChangeCase == "U") {
-                    fmtParts[i] = ch.toUpperCase();
-                } else if (gChangeCase == "L") {
-                    fmtParts[i] = ch.toLowerCase();
-                }
-            }
-            return fmtParts.join("");
-        });
-        this.variables.__ = null;
-        return formatted;
-    };
-
-    this.resolveVariables = function(snippet, editor) {
-        var result = [];
-        for (var i = 0; i < snippet.length; i++) {
-            var ch = snippet[i];
-            if (typeof ch == "string") {
-                result.push(ch);
-            } else if (typeof ch != "object") {
-                continue;
-            } else if (ch.skip) {
-                gotoNext(ch);
-            } else if (ch.processed < i) {
-                continue;
-            } else if (ch.text) {
-                var value = this.getVariableValue(editor, ch.text);
-                if (value && ch.fmtString)
-                    value = this.tmStrFormat(value, ch);
-                ch.processed = i;
-                if (ch.expectIf == null) {
-                    if (value) {
-                        result.push(value);
-                        gotoNext(ch);
-                    }
-                } else {
-                    if (value) {
-                        ch.skip = ch.elseBranch;
-                    } else
-                        gotoNext(ch);
-                }
-            } else if (ch.tabstopId != null) {
-                result.push(ch);
-            } else if (ch.changeCase != null) {
-                result.push(ch);
-            }
-        }
-        function gotoNext(ch) {
-            var i1 = snippet.indexOf(ch, i + 1);
-            if (i1 != -1)
-                i = i1;
-        }
-        return result;
-    };
-
-    this.insertSnippet = function(editor, snippetText) {
-        var cursor = editor.getCursorPosition();
-        var line = editor.session.getLine(cursor.row);
-        var indentString = line.match(/^\s*/)[0];
-        var tabString = editor.session.getTabString();
-
-        var tokens = this.tokenizeTmSnippet(snippetText);
-        tokens = this.resolveVariables(tokens, editor);
-        tokens = tokens.map(function(x) {
-            if (x == "\n")
-                return x + indentString;
-            if (typeof x == "string")
-                return x.replace(/\t/g, tabString);
-            return x;
-        });
-        var tabstops = [];
-        tokens.forEach(function(p, i) {
-            if (typeof p != "object")
-                return;
-            var id = p.tabstopId;
-            var ts = tabstops[id];
-            if (!ts) {
-                ts = tabstops[id] = [];
-                ts.index = id;
-                ts.value = "";
-            }
-            if (ts.indexOf(p) !== -1)
-                return;
-            ts.push(p);
-            var i1 = tokens.indexOf(p, i + 1);
-            if (i1 === -1)
-                return;
-
-            var value = tokens.slice(i + 1, i1);
-            var isNested = value.some(function(t) {return typeof t === "object"});          
-            if (isNested && !ts.value) {
-                ts.value = value;
-            } else if (value.length && (!ts.value || typeof ts.value !== "string")) {
-                ts.value = value.join("");
-            }
-        });
-        tabstops.forEach(function(ts) {ts.length = 0});
-        var expanding = {};
-        function copyValue(val) {
-            var copy = []
-            for (var i = 0; i < val.length; i++) {
-                var p = val[i];
-                if (typeof p == "object") {
-                    if (expanding[p.tabstopId])
-                        continue;
-                    var j = val.lastIndexOf(p, i - 1);
-                    p = copy[j] || {tabstopId: p.tabstopId};
-                }
-                copy[i] = p;
-            }
-            return copy;
-        }
-        for (var i = 0; i < tokens.length; i++) {
-            var p = tokens[i];
-            if (typeof p != "object")
-                continue;
-            var id = p.tabstopId;
-            var i1 = tokens.indexOf(p, i + 1);
-            if (expanding[id] == p) { 
-                expanding[id] = null;
-                continue;
-            }
-            
-            var ts = tabstops[id];
-            var arg = typeof ts.value == "string" ? [ts.value] : copyValue(ts.value);
-            arg.unshift(i + 1, Math.max(0, i1 - i));
-            arg.push(p);
-            expanding[id] = p;
-            tokens.splice.apply(tokens, arg);
-
-            if (ts.indexOf(p) === -1)
-                ts.push(p);
-        };
-        var row = 0, column = 0;
-        var text = "";
-        tokens.forEach(function(t) {
-            if (typeof t === "string") {
-                if (t[0] === "\n"){
-                    column = t.length - 1;
-                    row ++;
-                } else
-                    column += t.length;
-                text += t;
-            } else {
-                if (!t.start)
-                    t.start = {row: row, column: column};
-                else
-                    t.end = {row: row, column: column};
-            }
-        });
-        var range = editor.getSelectionRange();
-        var end = editor.session.replace(range, text);
-
-        var tabstopManager = new TabstopManager(editor);
-        tabstopManager.addTabstops(tabstops, range.start, end);
-        tabstopManager.tabNext();
-    };
-
-    this.$getScope = function(editor) {
-        var scope = editor.session.$mode.$id || "";
-        scope = scope.split("/").pop();
-        if (scope === "html" || scope === "php") {
-            if (scope === "php") 
-                scope = "html";
-            var c = editor.getCursorPosition()
-            var state = editor.session.getState(c.row);
-            if (typeof state === "object") {
-                state = state[0];
-            }
-            if (state.substring) {
-                if (state.substring(0, 3) == "js-")
-                    scope = "javascript";
-                else if (state.substring(0, 4) == "css-")
-                    scope = "css";
-                else if (state.substring(0, 4) == "php-")
-                    scope = "php";
-            }
-        }
-        
-        return scope;
-    };
-
-    this.expandWithTab = function(editor) {
-        var cursor = editor.getCursorPosition();
-        var line = editor.session.getLine(cursor.row);
-        var before = line.substring(0, cursor.column);
-        var after = line.substr(cursor.column);
-
-        var scope = this.$getScope(editor);
-        var snippetMap = this.snippetMap;
-        var snippet;
-        [scope, "_"].some(function(scope) {
-            var snippets = snippetMap[scope];
-            if (snippets)
-                snippet = this.findMatchingSnippet(snippets, before, after);
-            return !!snippet;
-        }, this);
-        if (!snippet)
-            return false;
-
-        editor.session.doc.removeInLine(cursor.row,
-            cursor.column - snippet.replaceBefore.length,
-            cursor.column + snippet.replaceAfter.length
-        );
-
-        this.variables.M__ = snippet.matchBefore;
-        this.variables.T__ = snippet.matchAfter;
-        this.insertSnippet(editor, snippet.content);
-
-        this.variables.M__ = this.variables.T__ = null;
-        return true;
-    };
-
-    this.findMatchingSnippet = function(snippetList, before, after) {
-        for (var i = snippetList.length; i--;) {
-            var s = snippetList[i];
-            if (s.startRe && !s.startRe.test(before))
-                continue;
-            if (s.endRe && !s.endRe.test(after))
-                continue;
-            if (!s.startRe && !s.endRe)
-                continue;
-
-            s.matchBefore = s.startRe ? s.startRe.exec(before) : [""];
-            s.matchAfter = s.endRe ? s.endRe.exec(after) : [""];
-            s.replaceBefore = s.triggerRe ? s.triggerRe.exec(before)[0] : "";
-            s.replaceAfter = s.endTriggerRe ? s.endTriggerRe.exec(after)[0] : "";
-            return s;
-        }
-    };
-
-    this.snippetMap = {};
-    this.snippetNameMap = {};
-    this.register = function(snippets, scope) {
-        var snippetMap = this.snippetMap;
-        var snippetNameMap = this.snippetNameMap;
-        var self = this;
-        function wrapRegexp(src) {
-            if (src && !/^\^?\(.*\)\$?$|^\\b$/.test(src))
-                src = "(?:" + src + ")"
-
-            return src || "";
-        }
-        function guardedRegexp(re, guard, opening) {
-            re = wrapRegexp(re);
-            guard = wrapRegexp(guard);
-            if (opening) {
-                re = guard + re;
-                if (re && re[re.length - 1] != "$")
-                    re = re + "$";
-            } else {
-                re = re + guard;
-                if (re && re[0] != "^")
-                    re = "^" + re;
-            }
-            return new RegExp(re);
-        }
-
-        function addSnippet(s) {
-            if (!s.scope)
-                s.scope = scope || "_";
-            scope = s.scope
-            if (!snippetMap[scope]) {
-                snippetMap[scope] = [];
-                snippetNameMap[scope] = {};
-            }
-
-            var map = snippetNameMap[scope];
-            if (s.name) {
-                var old = map[s.name];
-                if (old)
-                    self.unregister(old);
-                map[s.name] = s;
-            }
-            snippetMap[scope].push(s);
-
-            if (s.tabTrigger && !s.trigger) {
-                if (!s.guard && /^\w/.test(s.tabTrigger))
-                    s.guard = "\\b";
-                s.trigger = lang.escapeRegExp(s.tabTrigger);
-            }
-
-            s.startRe = guardedRegexp(s.trigger, s.guard, true);
-            s.triggerRe = new RegExp(s.trigger, "", true);
-
-            s.endRe = guardedRegexp(s.endTrigger, s.endGuard, true);
-            s.endTriggerRe = new RegExp(s.endTrigger, "", true);
-        };
-
-        if (snippets.content)
-            addSnippet(snippets);
-        else if (Array.isArray(snippets))
-            snippets.forEach(addSnippet);
-    };
-    this.unregister = function(snippets, scope) {
-        var snippetMap = this.snippetMap;
-        var snippetNameMap = this.snippetNameMap;
-
-        function removeSnippet(s) {
-            var nameMap = snippetNameMap[s.scope||scope];
-            if (nameMap && nameMap[s.name]) {
-                delete nameMap[s.name];
-                var map = snippetMap[s.scope||scope];
-                var i = map && map.indexOf(s);
-                if (i >= 0)
-                    map.splice(i, 1);
-            }
-        }
-        if (snippets.content)
-            removeSnippet(snippets);
-        else if (Array.isArray(snippets))
-            snippets.forEach(removeSnippet);
-    };
-    this.parseSnippetFile = function(str) {
-        str = str.replace(/\r/g, "");
-        var list = [], snippet = {};
-        var re = /^#.*|^({[\s\S]*})\s*$|^(\S+) (.*)$|^((?:\n*\t.*)+)/gm;
-        var m;
-        while (m = re.exec(str)) {
-            if (m[1]) {
-                try {
-                    snippet = JSON.parse(m[1])
-                    list.push(snippet);
-                } catch (e) {}
-            } if (m[4]) {
-                snippet.content = m[4].replace(/^\t/gm, "");
-                list.push(snippet);
-                snippet = {};
-            } else {
-                var key = m[2], val = m[3];
-                if (key == "regex") {
-                    var guardRe = /\/((?:[^\/\\]|\\.)*)|$/g;
-                    snippet.guard = guardRe.exec(val)[1];
-                    snippet.trigger = guardRe.exec(val)[1];
-                    snippet.endTrigger = guardRe.exec(val)[1];
-                    snippet.endGuard = guardRe.exec(val)[1];
-                } else if (key == "snippet") {
-                    snippet.tabTrigger = val.match(/^\S*/)[0];
-                    if (!snippet.name)
-                        snippet.name = val;
-                } else {
-                    snippet[key] = val;
-                }
-            }
-        }
-        return list;
-    };
-    this.getSnippetByName = function(name, editor) {
-        var scope = editor && this.$getScope(editor);
-        var snippetMap = this.snippetNameMap;
-        var snippet;
-        [scope, "_"].some(function(scope) {
-            var snippets = snippetMap[scope];
-            if (snippets)
-                snippet = snippets[name];
-            return !!snippet;
-        }, this);
-        return snippet;
-    };
-
-}).call(SnippetManager.prototype);
-
-
-var TabstopManager = function(editor) {
-    if (editor.tabstopManager)
-        return editor.tabstopManager;
-    editor.tabstopManager = this;
-    this.$onChange = this.onChange.bind(this);
-    this.$onChangeSelection = lang.delayedCall(this.onChangeSelection.bind(this)).schedule;
-    this.$onChangeSession = this.onChangeSession.bind(this);
-    this.$onAfterExec = this.onAfterExec.bind(this);
-    this.attach(editor);
-};
-(function() {
-    this.attach = function(editor) {
-        this.index = -1;
-        this.ranges = [];
-        this.tabstops = [];
-        this.selectedTabstop = null;
-
-        this.editor = editor;
-        this.editor.on("change", this.$onChange);
-        this.editor.on("changeSelection", this.$onChangeSelection);
-        this.editor.on("changeSession", this.$onChangeSession);
-        this.editor.commands.on("afterExec", this.$onAfterExec);
-        this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler);
-    };
-    this.detach = function() {
-        this.tabstops.forEach(this.removeTabstopMarkers, this);
-        this.ranges = null;
-        this.tabstops = null;
-        this.selectedTabstop = null;
-        this.editor.removeListener("change", this.$onChange);
-        this.editor.removeListener("changeSelection", this.$onChangeSelection);
-        this.editor.removeListener("changeSession", this.$onChangeSession);
-        this.editor.commands.removeListener("afterExec", this.$onAfterExec);
-        this.editor.keyBinding.removeKeyboardHandler(this.keyboardHandler);
-        this.editor.tabstopManager = null;
-        this.editor = null;
-    };
-
-    this.onChange = function(e) {
-        var changeRange = e.data.range;
-        var isRemove = e.data.action[0] == "r";
-        var start = changeRange.start;
-        var end = changeRange.end;
-        var startRow = start.row;
-        var endRow = end.row;
-        var lineDif = endRow - startRow;
-        var colDiff = end.column - start.column;
-
-        if (isRemove) {
-            lineDif = -lineDif;
-            colDiff = -colDiff;
-        }
-        if (!this.$inChange && isRemove) {
-            var ts = this.selectedTabstop;
-            var changedOutside = !ts.some(function(r) {
-                return comparePoints(r.start, start) <= 0 && comparePoints(r.end, end) >= 0;
-            });
-            if (changedOutside)
-                return this.detach();
-        }
-        var ranges = this.ranges;
-        for (var i = 0; i < ranges.length; i++) {
-            var r = ranges[i];
-            if (r.end.row < start.row)
-                continue;
-
-            if (comparePoints(start, r.start) < 0 && comparePoints(end, r.end) > 0) {
-                this.removeRange(r);
-                i--;
-                continue;
-            }
-
-            if (r.start.row == startRow && r.start.column > start.column)
-                r.start.column += colDiff;
-            if (r.end.row == startRow && r.end.column >= start.column)
-                r.end.column += colDiff;
-            if (r.start.row >= startRow)
-                r.start.row += lineDif;
-            if (r.end.row >= startRow)
-                r.end.row += lineDif;
-
-            if (comparePoints(r.start, r.end) > 0)
-                this.removeRange(r);
-        }
-        if (!ranges.length)
-            this.detach();
-    };
-    this.updateLinkedFields = function() {
-        var ts = this.selectedTabstop;
-        if (!ts.hasLinkedRanges)
-            return;
-        this.$inChange = true;
-        var session = this.editor.session;
-        var text = session.getTextRange(ts.firstNonLinked);
-        for (var i = ts.length; i--;) {
-            var range = ts[i];
-            if (!range.linked)
-                continue;
-            var fmt = exports.snippetManager.tmStrFormat(text, range.original)
-            session.replace(range, fmt);
-        }
-        this.$inChange = false;
-    };
-    this.onAfterExec = function(e) {
-        if (e.command && !e.command.readOnly)
-            this.updateLinkedFields();
-    };
-    this.onChangeSelection = function() {
-        if (!this.editor)
-            return
-        var lead = this.editor.selection.lead;
-        var anchor = this.editor.selection.anchor;
-        var isEmpty = this.editor.selection.isEmpty();
-        for (var i = this.ranges.length; i--;) {
-            if (this.ranges[i].linked)
-                continue;
-            var containsLead = this.ranges[i].contains(lead.row, lead.column);
-            var containsAnchor = isEmpty || this.ranges[i].contains(anchor.row, anchor.column);
-            if (containsLead && containsAnchor)
-                return;
-        }
-        this.detach();
-    };
-    this.onChangeSession = function() {
-        this.detach();
-    };
-    this.tabNext = function(dir) {
-        var max = this.tabstops.length - 1;
-        var index = this.index + (dir || 1);
-        index = Math.min(Math.max(index, 0), max);
-        this.selectTabstop(index);
-        if (index == max)
-            this.detach();
-    };
-    this.selectTabstop = function(index) {
-        var ts = this.tabstops[this.index];
-        if (ts)
-            this.addTabstopMarkers(ts);
-        this.index = index;
-        ts = this.tabstops[this.index];
-        if (!ts || !ts.length)
-            return;
-        
-        this.selectedTabstop = ts;
-        if (!this.editor.inVirtualSelectionMode) {        
-            var sel = this.editor.multiSelect;
-            sel.toSingleRange(ts.firstNonLinked.clone());
-            for (var i = ts.length; i--;) {
-                if (ts.hasLinkedRanges && ts[i].linked)
-                    continue;
-                sel.addRange(ts[i].clone(), true);
-            }
-        } else {
-            this.editor.selection.setRange(ts.firstNonLinked);
-        }
-        
-        this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler);
-    };
-    this.addTabstops = function(tabstops, start, end) {
-        if (!tabstops[0]) {
-            var p = Range.fromPoints(end, end);
-            moveRelative(p.start, start);
-            moveRelative(p.end, start);
-            tabstops[0] = [p];
-            tabstops[0].index = 0;
-        }
-
-        var i = this.index;
-        var arg = [i, 0];
-        var ranges = this.ranges;
-        var editor = this.editor;
-        tabstops.forEach(function(ts) {
-            for (var i = ts.length; i--;) {
-                var p = ts[i];
-                var range = Range.fromPoints(p.start, p.end || p.start);
-                movePoint(range.start, start);
-                movePoint(range.end, start);
-                range.original = p;
-                range.tabstop = ts;
-                ranges.push(range);
-                ts[i] = range;
-                if (p.fmtString) {
-                    range.linked = true;
-                    ts.hasLinkedRanges = true;
-                } else if (!ts.firstNonLinked)
-                    ts.firstNonLinked = range;
-            }
-            if (!ts.firstNonLinked)
-                ts.hasLinkedRanges = false;
-            arg.push(ts);
-            this.addTabstopMarkers(ts);
-        }, this);
-        arg.push(arg.splice(2, 1)[0]);
-        this.tabstops.splice.apply(this.tabstops, arg);
-    };
-
-    this.addTabstopMarkers = function(ts) {
-        var session = this.editor.session;
-        ts.forEach(function(range) {
-            if  (!range.markerId)
-                range.markerId = session.addMarker(range, "ace_snippet-marker", "text");
-        });
-    };
-    this.removeTabstopMarkers = function(ts) {
-        var session = this.editor.session;
-        ts.forEach(function(range) {
-            session.removeMarker(range.markerId);
-            range.markerId = null;
-        });
-    };
-    this.removeRange = function(range) {
-        var i = range.tabstop.indexOf(range);
-        range.tabstop.splice(i, 1);
-        i = this.ranges.indexOf(range);
-        this.ranges.splice(i, 1);
-        this.editor.session.removeMarker(range.markerId);
-    };
-
-    this.keyboardHandler = new HashHandler();
-    this.keyboardHandler.bindKeys({
-        "Tab": function(ed) {
-            ed.tabstopManager.tabNext(1);
-        },
-        "Shift-Tab": function(ed) {
-            ed.tabstopManager.tabNext(-1);
-        },
-        "Esc": function(ed) {
-            ed.tabstopManager.detach();
-        },
-        "Return": function(ed) {
-            return false;
-        }
-    });
-}).call(TabstopManager.prototype);
-
-
-var movePoint = function(point, diff) {
-    if (point.row == 0)
-        point.column += diff.column;
-    point.row += diff.row;
-};
-
-var moveRelative = function(point, start) {
-    if (point.row == start.row)
-        point.column -= start.column;
-    point.row -= start.row;
-};
-
-
-require("./lib/dom").importCssString("\
-.ace_snippet-marker {\
-    -moz-box-sizing: border-box;\
-    box-sizing: border-box;\
-    background: rgba(194, 193, 208, 0.09);\
-    border: 1px dotted rgba(211, 208, 235, 0.62);\
-    position: absolute;\
-}");
-
-exports.snippetManager = new SnippetManager();
-
-
-});
-
-define('ace/autocomplete', ['require', 'exports', 'module' , 'ace/keyboard/hash_handler', 'ace/autocomplete/popup', 'ace/autocomplete/util', 'ace/lib/event', 'ace/lib/lang', 'ace/snippets'], function(require, exports, module) {
-
-
-var HashHandler = require("./keyboard/hash_handler").HashHandler;
-var AcePopup = require("./autocomplete/popup").AcePopup;
-var util = require("./autocomplete/util");
-var event = require("./lib/event");
-var lang = require("./lib/lang");
-var snippetManager = require("./snippets").snippetManager;
-
-var Autocomplete = function() {
-    this.keyboardHandler = new HashHandler();
-    this.keyboardHandler.bindKeys(this.commands);
-
-    this.blurListener = this.blurListener.bind(this);
-    this.changeListener = this.changeListener.bind(this);
-    this.mousedownListener = this.mousedownListener.bind(this);
-    this.mousewheelListener = this.mousewheelListener.bind(this);
-    
-    this.changeTimer = lang.delayedCall(function() {
-        this.updateCompletions(true);
-    }.bind(this))
-};
-
-(function() {
-    this.$init = function() {
-        this.popup = new AcePopup(document.body || document.documentElement);
-        this.popup.on("click", function(e) {
-            this.insertMatch();
-            e.stop();
-        }.bind(this));
-    };
-
-    this.openPopup = function(editor, prefix, keepPopupPosition) {
-        if (!this.popup)
-            this.$init();
-
-        this.popup.setData(this.completions.filtered);
-
-        var renderer = editor.renderer;
-        if (!keepPopupPosition) {
-            this.popup.setFontSize(editor.getFontSize());
-
-            var lineHeight = renderer.layerConfig.lineHeight;
-            
-            var pos = renderer.$cursorLayer.getPixelPosition(this.base, true);            
-            pos.left -= this.popup.getTextLeftOffset();
-            
-            var rect = editor.container.getBoundingClientRect();
-            pos.top += rect.top - renderer.layerConfig.offset;
-            pos.left += rect.left;
-            pos.left += renderer.$gutterLayer.gutterWidth;
-
-            this.popup.show(pos, lineHeight);
-        }
-    };
-
-    this.detach = function() {
-        this.editor.keyBinding.removeKeyboardHandler(this.keyboardHandler);
-        this.editor.off("changeSelection", this.changeListener);
-        this.editor.off("blur", this.changeListener);
-        this.editor.off("mousedown", this.mousedownListener);
-        this.editor.off("mousewheel", this.mousewheelListener);
-        this.changeTimer.cancel();
-        
-        if (this.popup)
-            this.popup.hide();
-
-        this.activated = false;
-        this.completions = this.base = null;
-    };
-
-    this.changeListener = function(e) {
-        var cursor = this.editor.selection.lead;
-        if (cursor.row != this.base.row || cursor.column < this.base.column) {
-            this.detach();
-        }
-        if (this.activated)
-            this.changeTimer.schedule();
-        else
-            this.detach();
-    };
-
-    this.blurListener = function() {
-        if (document.activeElement != this.editor.textInput.getElement())
-            this.detach();
-    };
-
-    this.mousedownListener = function(e) {
-        this.detach();
-    };
-
-    this.mousewheelListener = function(e) {
-        this.detach();
-    };
-
-    this.goTo = function(where) {
-        var row = this.popup.getRow();
-        var max = this.popup.session.getLength() - 1;
-
-        switch(where) {
-            case "up": row = row < 0 ? max : row - 1; break;
-            case "down": row = row >= max ? -1 : row + 1; break;
-            case "start": row = 0; break;
-            case "end": row = max; break;
-        }
-
-        this.popup.setRow(row);
-    };
-
-    this.insertMatch = function(data) {
-        if (!data)
-            data = this.popup.getData(this.popup.getRow());
-        if (!data)
-            return false;
-        if (data.completer && data.completer.insertMatch) {
-            data.completer.insertMatch(this.editor);
-        } else {
-            if (this.completions.filterText) {
-                var ranges = this.editor.selection.getAllRanges();
-                for (var i = 0, range; range = ranges[i]; i++) {
-                    range.start.column -= this.completions.filterText.length;
-                    this.editor.session.remove(range);
-                }
-            }
-            if (data.snippet)
-                snippetManager.insertSnippet(this.editor, data.snippet);
-            else
-                this.editor.execCommand("insertstring", data.value || data);
-        }
-        this.detach();
-    };
-
-    this.commands = {
-        "Up": function(editor) { editor.completer.goTo("up"); },
-        "Down": function(editor) { editor.completer.goTo("down"); },
-        "Ctrl-Up|Ctrl-Home": function(editor) { editor.completer.goTo("start"); },
-        "Ctrl-Down|Ctrl-End": function(editor) { editor.completer.goTo("end"); },
-
-        "Esc": function(editor) { editor.completer.detach(); },
-        "Space": function(editor) { editor.completer.detach(); editor.insert(" ");},
-        "Return": function(editor) { editor.completer.insertMatch(); },
-        "Shift-Return": function(editor) { editor.completer.insertMatch(true); },
-        "Tab": function(editor) { editor.completer.insertMatch(); },
-
-        "PageUp": function(editor) { editor.completer.popup.gotoPageUp(); },
-        "PageDown": function(editor) { editor.completer.popup.gotoPageDown(); }
-    };
-
-    this.gatherCompletions = function(editor, callback) {
-        var session = editor.getSession();
-        var pos = editor.getCursorPosition();
-        
-        var line = session.getLine(pos.row);
-        var prefix = util.retrievePrecedingIdentifier(line, pos.column);
-        
-        this.base = editor.getCursorPosition();
-        this.base.column -= prefix.length;
-
-        var matches = [];
-        util.parForEach(editor.completers, function(completer, next) {
-            completer.getCompletions(editor, session, pos, prefix, function(err, results) {
-                if (!err)
-                    matches = matches.concat(results);
-                next();
-            });
-        }, function() {
-            callback(null, {
-                prefix: prefix,
-                matches: matches
-            });
-        });
-        return true;
-    };
-
-    this.showPopup = function(editor) {
-        if (this.editor)
-            this.detach();
-        
-        this.activated = true;
-
-        this.editor = editor;
-        if (editor.completer != this) {
-            if (editor.completer)
-                editor.completer.detach();
-            editor.completer = this;
-        }
-
-        editor.keyBinding.addKeyboardHandler(this.keyboardHandler);
-        editor.on("changeSelection", this.changeListener);
-        editor.on("blur", this.blurListener);
-        editor.on("mousedown", this.mousedownListener);
-        editor.on("mousewheel", this.mousewheelListener);
-        
-        this.updateCompletions();
-    };
-    
-    this.updateCompletions = function(keepPopupPosition) {
-        if (keepPopupPosition && this.base && this.completions) {
-            var pos = this.editor.getCursorPosition();
-            var prefix = this.editor.session.getTextRange({start: this.base, end: pos});
-            if (prefix == this.completions.filterText)
-                return;
-            this.completions.setFilter(prefix);
-            if (!this.completions.filtered.length)
-                return this.detach();
-            this.openPopup(this.editor, prefix, keepPopupPosition);
-            return;
-        }
-        this.gatherCompletions(this.editor, function(err, results) {
-            var matches = results && results.matches;
-            if (!matches || !matches.length)
-                return this.detach();
-
-            this.completions = new FilteredList(matches);
-            this.completions.setFilter(results.prefix);
-            if (!this.completions.filtered.length)
-                return this.detach();
-            this.openPopup(this.editor, results.prefix, keepPopupPosition);
-        }.bind(this));
-    };
-
-    this.cancelContextMenu = function() {
-        var stop = function(e) {
-            this.editor.off("nativecontextmenu", stop);
-            if (e && e.domEvent)
-                event.stopEvent(e.domEvent);
-        }.bind(this);
-        setTimeout(stop, 10);
-        this.editor.on("nativecontextmenu", stop);
-    };
-
-}).call(Autocomplete.prototype);
-
-Autocomplete.startCommand = {
-    name: "startAutocomplete",
-    exec: function(editor) {
-        if (!editor.completer)
-            editor.completer = new Autocomplete();
-        editor.completer.showPopup(editor);
-        editor.completer.cancelContextMenu();
-    },
-    bindKey: "Ctrl-Space|Ctrl-Shift-Space|Alt-Space"
-};
-
-var FilteredList = function(array, filterText, mutateData) {
-    this.all = array;
-    this.filtered = array;
-    this.filterText = filterText || "";
-};
-(function(){
-    this.setFilter = function(str) {
-        if (str.length > this.filterText && str.lastIndexOf(this.filterText, 0) === 0)
-            var matches = this.filtered;
-        else
-            var matches = this.all;
-
-        this.filterText = str;
-        matches = this.filterCompletions(matches, this.filterText);
-        matches = matches.sort(function(a, b) {
-            return b.exactMatch - a.exactMatch || b.score - a.score;
-        });
-        var prev = null;
-        matches = matches.filter(function(item){
-            var caption = item.value || item.caption || item.snippet; 
-            if (caption === prev) return false;
-            prev = caption;
-            return true;
-        });
-        
-        this.filtered = matches;
-    };
-    this.filterCompletions = function(items, needle) {
-        var results = [];
-        var upper = needle.toUpperCase();
-        var lower = needle.toLowerCase();
-        loop: for (var i = 0, item; item = items[i]; i++) {
-            var caption = item.value || item.caption || item.snippet;
-            if (!caption) continue;
-            var lastIndex = -1;
-            var matchMask = 0;
-            var penalty = 0;
-            var index, distance;
-            for (var j = 0; j < needle.length; j++) {
-                var i1 = caption.indexOf(lower[j], lastIndex + 1);
-                var i2 = caption.indexOf(upper[j], lastIndex + 1);
-                index = (i1 >= 0) ? ((i2 < 0 || i1 < i2) ? i1 : i2) : i2;
-                if (index < 0)
-                    continue loop;
-                distance = index - lastIndex - 1;
-                if (distance > 0) {
-                    if (lastIndex === -1)
-                        penalty += 10;
-                    penalty += distance;
-                }
-                matchMask = matchMask | (1 << index);
-                lastIndex = index;
-            }
-            item.matchMask = matchMask;
-            item.exactMatch = penalty ? 0 : 1;
-            item.score = (item.score || 0) - penalty;
-            results.push(item);
-        }
-        return results;
-    };
-}).call(FilteredList.prototype);
-
-exports.Autocomplete = Autocomplete;
-exports.FilteredList = FilteredList;
-
-});
-
-define('ace/autocomplete/popup', ['require', 'exports', 'module' , 'ace/edit_session', 'ace/virtual_renderer', 'ace/editor', 'ace/range', 'ace/lib/event', 'ace/lib/lang', 'ace/lib/dom'], function(require, exports, module) {
-
-
-var EditSession = require("../edit_session").EditSession;
-var Renderer = require("../virtual_renderer").VirtualRenderer;
-var Editor = require("../editor").Editor;
-var Range = require("../range").Range;
-var event = require("../lib/event");
-var lang = require("../lib/lang");
-var dom = require("../lib/dom");
-
-var $singleLineEditor = function(el) {
-    var renderer = new Renderer(el);
-
-    renderer.$maxLines = 4;
-    
-    var editor = new Editor(renderer);
-
-    editor.setHighlightActiveLine(false);
-    editor.setShowPrintMargin(false);
-    editor.renderer.setShowGutter(false);
-    editor.renderer.setHighlightGutterLine(false);
-
-    editor.$mouseHandler.$focusWaitTimout = 0;
-
-    return editor;
-};
-
-var AcePopup = function(parentNode) {
-    var el = dom.createElement("div");
-    var popup = new $singleLineEditor(el);
-    
-    if (parentNode)
-        parentNode.appendChild(el);
-    el.style.display = "none";
-    popup.renderer.content.style.cursor = "default";
-    popup.renderer.setStyle("ace_autocomplete");
-    
-    popup.setOption("displayIndentGuides", false);
-
-    var noop = function(){};
-
-    popup.focus = noop;
-    popup.$isFocused = true;
-
-    popup.renderer.$cursorLayer.restartTimer = noop;
-    popup.renderer.$cursorLayer.element.style.opacity = 0;
-
-    popup.renderer.$maxLines = 8;
-    popup.renderer.$keepTextAreaAtCursor = false;
-
-    popup.setHighlightActiveLine(false);
-    popup.session.highlight("");
-    popup.session.$searchHighlight.clazz = "ace_highlight-marker";
-
-    popup.on("mousedown", function(e) {
-        var pos = e.getDocumentPosition();
-        popup.moveCursorToPosition(pos);
-        popup.selection.clearSelection();
-        selectionMarker.start.row = selectionMarker.end.row = pos.row;
-        e.stop();
-    });
-
-    var lastMouseEvent;
-    var hoverMarker = new Range(-1,0,-1,Infinity);
-    var selectionMarker = new Range(-1,0,-1,Infinity);
-    selectionMarker.id = popup.session.addMarker(selectionMarker, "ace_active-line", "fullLine");
-    popup.setSelectOnHover = function(val) {
-        if (!val) {
-            hoverMarker.id = popup.session.addMarker(hoverMarker, "ace_line-hover", "fullLine");
-        } else if (hoverMarker.id) {
-            popup.session.removeMarker(hoverMarker.id);
-            hoverMarker.id = null;
-        }
-    }
-    popup.setSelectOnHover(false);
-    popup.on("mousemove", function(e) {
-        if (!lastMouseEvent) {
-            lastMouseEvent = e;
-            return;
-        }
-        if (lastMouseEvent.x == e.x && lastMouseEvent.y == e.y) {
-            return;
-        }
-        lastMouseEvent = e;
-        lastMouseEvent.scrollTop = popup.renderer.scrollTop;
-        var row = lastMouseEvent.getDocumentPosition().row;
-        if (hoverMarker.start.row != row) {
-            if (!hoverMarker.id)
-                popup.setRow(row);
-            setHoverMarker(row);
-        }
-    });
-    popup.renderer.on("beforeRender", function() {
-        if (lastMouseEvent && hoverMarker.start.row != -1) {
-            lastMouseEvent.$pos = null;
-            var row = lastMouseEvent.getDocumentPosition().row;
-            if (!hoverMarker.id)
-                popup.setRow(row);
-            setHoverMarker(row, true);
-        }
-    });
-    popup.renderer.on("afterRender", function() {
-        var row = popup.getRow();
-        var t = popup.renderer.$textLayer;
-        var selected = t.element.childNodes[row - t.config.firstRow];
-        if (selected == t.selectedNode)
-            return;
-        if (t.selectedNode)
-            dom.removeCssClass(t.selectedNode, "ace_selected");
-        t.selectedNode = selected;
-        if (selected)
-            dom.addCssClass(selected, "ace_selected");
-    });
-    var hideHoverMarker = function() { setHoverMarker(-1) };
-    var setHoverMarker = function(row, suppressRedraw) {
-        if (row !== hoverMarker.start.row) {
-            hoverMarker.start.row = hoverMarker.end.row = row;
-            if (!suppressRedraw)
-                popup.session._emit("changeBackMarker");
-            popup._emit("changeHoverMarker");
-        }
-    };
-    popup.getHoveredRow = function() {
-        return hoverMarker.start.row;
-    };
-    
-    event.addListener(popup.container, "mouseout", hideHoverMarker);
-    popup.on("hide", hideHoverMarker);
-    popup.on("changeSelection", hideHoverMarker);
-    
-    popup.session.doc.getLength = function() {
-        return popup.data.length;
-    };
-    popup.session.doc.getLine = function(i) {
-        var data = popup.data[i];
-        if (typeof data == "string")
-            return data;
-        return (data && data.value) || "";
-    };
-
-    var bgTokenizer = popup.session.bgTokenizer;
-    bgTokenizer.$tokenizeRow = function(i) {
-        var data = popup.data[i];
-        var tokens = [];
-        if (!data)
-            return tokens;
-        if (typeof data == "string")
-            data = {value: data};
-        if (!data.caption)
-            data.caption = data.value;
-
-        var last = -1;
-        var flag, c;
-        for (var i = 0; i < data.caption.length; i++) {
-            c = data.caption[i];
-            flag = data.matchMask & (1 << i) ? 1 : 0;
-            if (last !== flag) {
-                tokens.push({type: data.className || "" + ( flag ? "completion-highlight" : ""), value: c});
-                last = flag;
-            } else {
-                tokens[tokens.length - 1].value += c;
-            }
-        }
-
-        if (data.meta) {
-            var maxW = popup.renderer.$size.scrollerWidth / popup.renderer.layerConfig.characterWidth;
-            if (data.meta.length + data.caption.length < maxW - 2)
-                tokens.push({type: "rightAlignedText", value: data.meta});
-        }
-        return tokens;
-    };
-    bgTokenizer.$updateOnChange = noop;
-    bgTokenizer.start = noop;
-    
-    popup.session.$computeWidth = function() {
-        return this.screenWidth = 0;
-    }
-    popup.data = [];
-    popup.setData = function(list) {
-        popup.data = list || [];
-        popup.setValue(lang.stringRepeat("\n", list.length), -1);
-        popup.setRow(0);
-    };
-    popup.getData = function(row) {
-        return popup.data[row];
-    };
-
-    popup.getRow = function() {
-        return selectionMarker.start.row;
-    };
-    popup.setRow = function(line) {
-        line = Math.max(-1, Math.min(this.data.length, line));
-        if (selectionMarker.start.row != line) {
-            popup.selection.clearSelection();
-            selectionMarker.start.row = selectionMarker.end.row = line || 0;
-            popup.session._emit("changeBackMarker");
-            popup.moveCursorTo(line || 0, 0);
-            if (popup.isOpen)
-                popup._signal("select");
-        }
-    };
-
-    popup.hide = function() {
-        this.container.style.display = "none";
-        this._signal("hide");
-        popup.isOpen = false;
-    };
-    popup.show = function(pos, lineHeight) {
-        var el = this.container;
-        var screenHeight = window.innerHeight;
-        var renderer = this.renderer;
-        var maxH = renderer.$maxLines * lineHeight * 1.4;
-        var top = pos.top + this.$borderSize;
-        if (top + maxH > screenHeight - lineHeight) {
-            el.style.top = "";
-            el.style.bottom = screenHeight - top + "px";
-        } else {
-            top += lineHeight;
-            el.style.top = top + "px";
-            el.style.bottom = "";
-        }
-
-        el.style.left = pos.left + "px";
-        el.style.display = "";
-        this.renderer.$textLayer.checkForSizeChanges();
-
-        this._signal("show");
-        lastMouseEvent = null;
-        popup.isOpen = true;
-    };
-    
-    popup.getTextLeftOffset = function() {
-        return this.$borderSize + this.renderer.$padding + this.$imageSize;
-    };
-    
-    popup.$imageSize = 0;
-    popup.$borderSize = 1;
-
-    return popup;
-};
-
-dom.importCssString("\
-.ace_autocomplete.ace-tm .ace_marker-layer .ace_active-line {\
-    background-color: #CAD6FA;\
-    z-index: 1;\
-}\
-.ace_autocomplete.ace-tm .ace_line-hover {\
-    border: 1px solid #abbffe;\
-    margin-top: -1px;\
-    background: rgba(233,233,253,0.4);\
-}\
-.ace_autocomplete .ace_line-hover {\
-    position: absolute;\
-    z-index: 2;\
-}\
-.ace_rightAlignedText {\
-    color: gray;\
-    display: inline-block;\
-    position: absolute;\
-    right: 4px;\
-    text-align: right;\
-    z-index: -1;\
-}\
-.ace_autocomplete .ace_completion-highlight{\
-    color: #000;\
-    text-shadow: 0 0 0.01em;\
-}\
-.ace_autocomplete {\
-    width: 280px;\
-    z-index: 200000;\
-    background: #fbfbfb;\
-    color: #444;\
-    border: 1px lightgray solid;\
-    position: fixed;\
-    box-shadow: 2px 3px 5px rgba(0,0,0,.2);\
-    line-height: 1.4;\
-}");
-
-exports.AcePopup = AcePopup;
-
-});
-
-define('ace/autocomplete/util', ['require', 'exports', 'module' ], function(require, exports, module) {
-
-
-exports.parForEach = function(array, fn, callback) {
-    var completed = 0;
-    var arLength = array.length;
-    if (arLength === 0)
-        callback();
-    for (var i = 0; i < arLength; i++) {
-        fn(array[i], function(result, err) {
-            completed++;
-            if (completed === arLength)
-                callback(result, err);
-        });
-    }
-}
-
-var ID_REGEX = /[a-zA-Z_0-9\$-]/;
-
-exports.retrievePrecedingIdentifier = function(text, pos, regex) {
-    regex = regex || ID_REGEX;
-    var buf = [];
-    for (var i = pos-1; i >= 0; i--) {
-        if (regex.test(text[i]))
-            buf.push(text[i]);
-        else
-            break;
-    }
-    return buf.reverse().join("");
-}
-
-exports.retrieveFollowingIdentifier = function(text, pos, regex) {
-    regex = regex || ID_REGEX;
-    var buf = [];
-    for (var i = pos; i < text.length; i++) {
-        if (regex.test(text[i]))
-            buf.push(text[i]);
-        else
-            break;
-    }
-    return buf;
-}
-
-});
-
-define('ace/autocomplete/text_completer', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) {
-    var Range = require("ace/range").Range;
-    
-    var splitRegex = /[^a-zA-Z_0-9\$\-]+/;
-
-    function getWordIndex(doc, pos) {
-        var textBefore = doc.getTextRange(Range.fromPoints({row: 0, column:0}, pos));
-        return textBefore.split(splitRegex).length - 1;
-    }
-    function wordDistance(doc, pos) {
-        var prefixPos = getWordIndex(doc, pos);
-        var words = doc.getValue().split(splitRegex);
-        var wordScores = Object.create(null);
-        
-        var currentWord = words[prefixPos];
-
-        words.forEach(function(word, idx) {
-            if (!word || word === currentWord) return;
-
-            var distance = Math.abs(prefixPos - idx);
-            var score = words.length - distance;
-            if (wordScores[word]) {
-                wordScores[word] = Math.max(score, wordScores[word]);
-            } else {
-                wordScores[word] = score;
-            }
-        });
-        return wordScores;
-    }
-
-    exports.getCompletions = function(editor, session, pos, prefix, callback) {
-        var wordScore = wordDistance(session, pos, prefix);
-        var wordList = Object.keys(wordScore);
-        callback(null, wordList.map(function(word) {
-            return {
-                name: word,
-                value: word,
-                score: wordScore[word],
-                meta: "local"
-            };
-        }));
-    };
-});
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/js/libs/ace/ext-modelist.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/js/libs/ace/ext-modelist.js b/apps/fauxton/assets/js/libs/ace/ext-modelist.js
deleted file mode 100644
index b3f0cc8..0000000
--- a/apps/fauxton/assets/js/libs/ace/ext-modelist.js
+++ /dev/null
@@ -1,166 +0,0 @@
-define('ace/ext/modelist', ['require', 'exports', 'module' ], function(require, exports, module) {
-
-
-var modes = [];
-function getModeForPath(path) {
-    var mode = modesByName.text;
-    var fileName = path.split(/[\/\\]/).pop();
-    for (var i = 0; i < modes.length; i++) {
-        if (modes[i].supportsFile(fileName)) {
-            mode = modes[i];
-            break;
-        }
-    }
-    return mode;
-}
-
-var Mode = function(name, caption, extensions) {
-    this.name = name;
-    this.caption = caption;
-    this.mode = "ace/mode/" + name;
-    this.extensions = extensions;
-    if (/\^/.test(extensions)) {
-        var re = extensions.replace(/\|(\^)?/g, function(a, b){
-            return "$|" + (b ? "^" : "^.*\\.");
-        }) + "$";
-    } else {
-        var re = "^.*\\.(" + extensions + ")$";
-    }
-
-    this.extRe = new RegExp(re, "gi");
-};
-
-Mode.prototype.supportsFile = function(filename) {
-    return filename.match(this.extRe);
-};
-var supportedModes = {
-    ABAP:        ["abap"],
-    ActionScript:["as"],
-    ADA:         ["ada|adb"],
-    AsciiDoc:    ["asciidoc"],
-    Assembly_x86:["asm"],
-    AutoHotKey:  ["ahk"],
-    BatchFile:   ["bat|cmd"],
-    C9Search:    ["c9search_results"],
-    C_Cpp:       ["cpp|c|cc|cxx|h|hh|hpp"],
-    Clojure:     ["clj"],
-    Cobol:       ["CBL|COB"],
-    coffee:      ["coffee|cf|cson|^Cakefile"],
-    ColdFusion:  ["cfm"],
-    CSharp:      ["cs"],
-    CSS:         ["css"],
-    Curly:       ["curly"],
-    D:           ["d|di"],
-    Dart:        ["dart"],
-    Diff:        ["diff|patch"],
-    Dot:         ["dot"],
-    Erlang:      ["erl|hrl"],
-    EJS:         ["ejs"],
-    Forth:       ["frt|fs|ldr"],
-    FTL:         ["ftl"],
-    Glsl:        ["glsl|frag|vert"],
-    golang:      ["go"],
-    Groovy:      ["groovy"],
-    HAML:        ["haml"],
-    Handlebars:  ["hbs|handlebars|tpl|mustache"],
-    Haskell:     ["hs"],
-    haXe:        ["hx"],
-    HTML:        ["html|htm|xhtml"],
-    HTML_Ruby:   ["erb|rhtml|html.erb"],
-    INI:         ["ini|conf|cfg|prefs"],
-    Jack:        ["jack"],
-    Jade:        ["jade"],
-    Java:        ["java"],
-    JavaScript:  ["js|jsm"],
-    JSON:        ["json"],
-    JSONiq:      ["jq"],
-    JSP:         ["jsp"],
-    JSX:         ["jsx"],
-    Julia:       ["jl"],
-    LaTeX:       ["tex|latex|ltx|bib"],
-    LESS:        ["less"],
-    Liquid:      ["liquid"],
-    Lisp:        ["lisp"],
-    LiveScript:  ["ls"],
-    LogiQL:      ["logic|lql"],
-    LSL:         ["lsl"],
-    Lua:         ["lua"],
-    LuaPage:     ["lp"],
-    Lucene:      ["lucene"],
-    Makefile:    ["^Makefile|^GNUmakefile|^makefile|^OCamlMakefile|make"],
-    MATLAB:      ["matlab"],
-    Markdown:    ["md|markdown"],
-    MySQL:       ["mysql"],
-    MUSHCode:    ["mc|mush"],
-    Nix:         ["nix"],
-    ObjectiveC:  ["m|mm"],
-    OCaml:       ["ml|mli"],
-    Pascal:      ["pas|p"],
-    Perl:        ["pl|pm"],
-    pgSQL:       ["pgsql"],
-    PHP:         ["php|phtml"],
-    Powershell:  ["ps1"],
-    Prolog:      ["plg|prolog"],
-    Properties:  ["properties"],
-    Protobuf:    ["proto"],
-    Python:      ["py"],
-    R:           ["r"],
-    RDoc:        ["Rd"],
-    RHTML:       ["Rhtml"],
-    Ruby:        ["rb|ru|gemspec|rake|^Guardfile|^Rakefile|^Gemfile"],
-    Rust:        ["rs"],
-    SASS:        ["sass"],
-    SCAD:        ["scad"],
-    Scala:       ["scala"],
-    Scheme:      ["scm|rkt"],
-    SCSS:        ["scss"],
-    SH:          ["sh|bash|^.bashrc"],
-    SJS:         ["sjs"],
-    Space:       ["space"],
-    snippets:    ["snippets"],
-    Soy_Template:["soy"],
-    SQL:         ["sql"],
-    Stylus:      ["styl|stylus"],
-    SVG:         ["svg"],
-    Tcl:         ["tcl"],
-    Tex:         ["tex"],
-    Text:        ["txt"],
-    Textile:     ["textile"],
-    Toml:        ["toml"],
-    Twig:        ["twig"],
-    Typescript:  ["ts|typescript|str"],
-    VBScript:    ["vbs"],
-    Velocity:    ["vm"],
-    Verilog:     ["v|vh|sv|svh"],
-    XML:         ["xml|rdf|rss|wsdl|xslt|atom|mathml|mml|xul|xbl"],
-    XQuery:      ["xq"],
-    YAML:        ["yaml|yml"]
-};
-
-var nameOverrides = {
-    ObjectiveC: "Objective-C",
-    CSharp: "C#",
-    golang: "Go",
-    C_Cpp: "C/C++",
-    coffee: "CoffeeScript",
-    HTML_Ruby: "HTML (Ruby)",
-    FTL: "FreeMarker"
-};
-var modesByName = {};
-for (var name in supportedModes) {
-    var data = supportedModes[name];
-    var displayName = nameOverrides[name] || name;
-    var filename = name.toLowerCase();
-    var mode = new Mode(filename, displayName, data[0]);
-    modesByName[filename] = mode;
-    modes.push(mode);
-}
-
-module.exports = {
-    getModeForPath: getModeForPath,
-    modes: modes,
-    modesByName: modesByName
-};
-
-});
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/js/libs/ace/ext-old_ie.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/js/libs/ace/ext-old_ie.js b/apps/fauxton/assets/js/libs/ace/ext-old_ie.js
deleted file mode 100644
index f926b62..0000000
--- a/apps/fauxton/assets/js/libs/ace/ext-old_ie.js
+++ /dev/null
@@ -1,499 +0,0 @@
-/* ***** BEGIN LICENSE BLOCK *****
- * Distributed under the BSD license:
- *
- * Copyright (c) 2010, Ajax.org B.V.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above copyright
- *       notice, this list of conditions and the following disclaimer in the
- *       documentation and/or other materials provided with the distribution.
- *     * Neither the name of Ajax.org B.V. nor the
- *       names of its contributors may be used to endorse or promote products
- *       derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * ***** END LICENSE BLOCK ***** */
-
-define('ace/ext/old_ie', ['require', 'exports', 'module' , 'ace/lib/useragent', 'ace/tokenizer', 'ace/ext/searchbox'], function(require, exports, module) {
-
-var MAX_TOKEN_COUNT = 1000;
-var useragent = require("../lib/useragent");
-var TokenizerModule = require("../tokenizer");
-
-function patch(obj, name, regexp, replacement) {
-    eval("obj['" + name + "']=" + obj[name].toString().replace(
-        regexp, replacement
-    ));
-}
-
-if (useragent.isIE && useragent.isIE < 10 && window.top.document.compatMode === "BackCompat")
-    useragent.isOldIE = true;
-
-if (typeof document != "undefined" && !document.documentElement.querySelector) {    
-    useragent.isOldIE = true;
-    var qs = function(el, selector) {
-        if (selector.charAt(0) == ".") {
-            var classNeme = selector.slice(1);
-        } else {
-            var m = selector.match(/(\w+)=(\w+)/);
-            var attr = m && m[1];
-            var attrVal = m && m[2];
-        }
-        for (var i = 0; i < el.all.length; i++) {
-            var ch = el.all[i];
-            if (classNeme) {
-                if (ch.className.indexOf(classNeme) != -1)
-                    return ch;
-            } else if (attr) {
-                if (ch.getAttribute(attr) == attrVal)
-                    return ch;
-            }
-        }
-    };
-    var sb = require("./searchbox").SearchBox.prototype;
-    patch(
-        sb, "$initElements",
-        /([^\s=]*).querySelector\((".*?")\)/g, 
-        "qs($1, $2)"
-    );
-}
-    
-var compliantExecNpcg = /()??/.exec("")[1] === undefined;
-if (compliantExecNpcg)
-    return;
-var proto = TokenizerModule.Tokenizer.prototype;
-TokenizerModule.Tokenizer_orig = TokenizerModule.Tokenizer;
-proto.getLineTokens_orig = proto.getLineTokens;
-
-patch(
-    TokenizerModule, "Tokenizer",
-    "ruleRegExps.push(adjustedregex);\n", 
-    function(m) {
-        return m + '\
-        if (state[i].next && RegExp(adjustedregex).test(""))\n\
-            rule._qre = RegExp(adjustedregex, "g");\n\
-        ';
-    }
-);
-TokenizerModule.Tokenizer.prototype = proto;
-patch(
-    proto, "getLineTokens",
-    /if \(match\[i \+ 1\] === undefined\)\s*continue;/, 
-    "if (!match[i + 1]) {\n\
-        if (value)continue;\n\
-        var qre = state[mapping[i]]._qre;\n\
-        if (!qre) continue;\n\
-        qre.lastIndex = lastIndex;\n\
-        if (!qre.exec(line) || qre.lastIndex != lastIndex)\n\
-            continue;\n\
-    }"
-);
-
-useragent.isOldIE = true;
-
-});
-
-define('ace/ext/searchbox', ['require', 'exports', 'module' , 'ace/lib/dom', 'ace/lib/lang', 'ace/lib/event', 'ace/keyboard/hash_handler', 'ace/lib/keys'], function(require, exports, module) {
-
-
-var dom = require("../lib/dom");
-var lang = require("../lib/lang");
-var event = require("../lib/event");
-var searchboxCss = "\
-/* ------------------------------------------------------------------------------------------\
-* Editor Search Form\
-* --------------------------------------------------------------------------------------- */\
-.ace_search {\
-background-color: #ddd;\
-border: 1px solid #cbcbcb;\
-border-top: 0 none;\
-max-width: 297px;\
-overflow: hidden;\
-margin: 0;\
-padding: 4px;\
-padding-right: 6px;\
-padding-bottom: 0;\
-position: absolute;\
-top: 0px;\
-z-index: 99;\
-}\
-.ace_search.left {\
-border-left: 0 none;\
-border-radius: 0px 0px 5px 0px;\
-left: 0;\
-}\
-.ace_search.right {\
-border-radius: 0px 0px 0px 5px;\
-border-right: 0 none;\
-right: 0;\
-}\
-.ace_search_form, .ace_replace_form {\
-border-radius: 3px;\
-border: 1px solid #cbcbcb;\
-float: left;\
-margin-bottom: 4px;\
-overflow: hidden;\
-}\
-.ace_search_form.ace_nomatch {\
-outline: 1px solid red;\
-}\
-.ace_search_field {\
-background-color: white;\
-border-right: 1px solid #cbcbcb;\
-border: 0 none;\
--webkit-box-sizing: border-box;\
--moz-box-sizing: border-box;\
-box-sizing: border-box;\
-display: block;\
-float: left;\
-height: 22px;\
-outline: 0;\
-padding: 0 7px;\
-width: 214px;\
-margin: 0;\
-}\
-.ace_searchbtn,\
-.ace_replacebtn {\
-background: #fff;\
-border: 0 none;\
-border-left: 1px solid #dcdcdc;\
-cursor: pointer;\
-display: block;\
-float: left;\
-height: 22px;\
-margin: 0;\
-padding: 0;\
-position: relative;\
-}\
-.ace_searchbtn:last-child,\
-.ace_replacebtn:last-child {\
-border-top-right-radius: 3px;\
-border-bottom-right-radius: 3px;\
-}\
-.ace_searchbtn:disabled {\
-background: none;\
-cursor: default;\
-}\
-.ace_searchbtn {\
-background-position: 50% 50%;\
-background-repeat: no-repeat;\
-width: 27px;\
-}\
-.ace_searchbtn.prev {\
-background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAFCAYAAAB4ka1VAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAADFJREFUeNpiSU1NZUAC/6E0I0yACYskCpsJiySKIiY0SUZk40FyTEgCjGgKwTRAgAEAQJUIPCE+qfkAAAAASUVORK5CYII=);    \
-}\
-.ace_searchbtn.next {\
-background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAFCAYAAAB4ka1VAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAADRJREFUeNpiTE1NZQCC/0DMyIAKwGJMUAYDEo3M/s+EpvM/mkKwCQxYjIeLMaELoLMBAgwAU7UJObTKsvAAAAAASUVORK5CYII=);    \
-}\
-.ace_searchbtn_close {\
-background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAcCAYAAABRVo5BAAAAZ0lEQVR42u2SUQrAMAhDvazn8OjZBilCkYVVxiis8H4CT0VrAJb4WHT3C5xU2a2IQZXJjiQIRMdkEoJ5Q2yMqpfDIo+XY4k6h+YXOyKqTIj5REaxloNAd0xiKmAtsTHqW8sR2W5f7gCu5nWFUpVjZwAAAABJRU5ErkJggg==) no-repeat 50% 0;\
-border-radius: 50%;\
-border: 0 none;\
-color: #656565;\
-cursor: pointer;\
-display: block;\
-float: right;\
-font-family: Arial;\
-font-size: 16px;\
-height: 14px;\
-line-height: 16px;\
-margin: 5px 1px 9px 5px;\
-padding: 0;\
-text-align: center;\
-width: 14px;\
-}\
-.ace_searchbtn_close:hover {\
-background-color: #656565;\
-background-position: 50% 100%;\
-color: white;\
-}\
-.ace_replacebtn.prev {\
-width: 54px\
-}\
-.ace_replacebtn.next {\
-width: 27px\
-}\
-.ace_button {\
-margin-left: 2px;\
-cursor: pointer;\
--webkit-user-select: none;\
--moz-user-select: none;\
--o-user-select: none;\
--ms-user-select: none;\
-user-select: none;\
-overflow: hidden;\
-opacity: 0.7;\
-border: 1px solid rgba(100,100,100,0.23);\
-padding: 1px;\
--moz-box-sizing: border-box;\
-box-sizing:    border-box;\
-color: black;\
-}\
-.ace_button:hover {\
-background-color: #eee;\
-opacity:1;\
-}\
-.ace_button:active {\
-background-color: #ddd;\
-}\
-.ace_button.checked {\
-border-color: #3399ff;\
-opacity:1;\
-}\
-.ace_search_options{\
-margin-bottom: 3px;\
-text-align: right;\
--webkit-user-select: none;\
--moz-user-select: none;\
--o-user-select: none;\
--ms-user-select: none;\
-user-select: none;\
-}";
-var HashHandler = require("../keyboard/hash_handler").HashHandler;
-var keyUtil = require("../lib/keys");
-
-dom.importCssString(searchboxCss, "ace_searchbox");
-
-var html = '<div class="ace_search right">\
-    <button type="button" action="hide" class="ace_searchbtn_close"></button>\
-    <div class="ace_search_form">\
-        <input class="ace_search_field" placeholder="Search for" spellcheck="false"></input>\
-        <button type="button" action="findNext" class="ace_searchbtn next"></button>\
-        <button type="button" action="findPrev" class="ace_searchbtn prev"></button>\
-    </div>\
-    <div class="ace_replace_form">\
-        <input class="ace_search_field" placeholder="Replace with" spellcheck="false"></input>\
-        <button type="button" action="replaceAndFindNext" class="ace_replacebtn">Replace</button>\
-        <button type="button" action="replaceAll" class="ace_replacebtn">All</button>\
-    </div>\
-    <div class="ace_search_options">\
-        <span action="toggleRegexpMode" class="ace_button" title="RegExp Search">.*</span>\
-        <span action="toggleCaseSensitive" class="ace_button" title="CaseSensitive Search">Aa</span>\
-        <span action="toggleWholeWords" class="ace_button" title="Whole Word Search">\\b</span>\
-    </div>\
-</div>'.replace(/>\s+/g, ">");
-
-var SearchBox = function(editor, range, showReplaceForm) {
-    var div = dom.createElement("div");
-    div.innerHTML = html;
-    this.element = div.firstChild;
-
-    this.$init();
-    this.setEditor(editor);
-};
-
-(function() {
-    this.setEditor = function(editor) {
-        editor.searchBox = this;
-        editor.container.appendChild(this.element);
-        this.editor = editor;
-    };
-
-    this.$initElements = function(sb) {
-        this.searchBox = sb.querySelector(".ace_search_form");
-        this.replaceBox = sb.querySelector(".ace_replace_form");
-        this.searchOptions = sb.querySelector(".ace_search_options");
-        this.regExpOption = sb.querySelector("[action=toggleRegexpMode]");
-        this.caseSensitiveOption = sb.querySelector("[action=toggleCaseSensitive]");
-        this.wholeWordOption = sb.querySelector("[action=toggleWholeWords]");
-        this.searchInput = this.searchBox.querySelector(".ace_search_field");
-        this.replaceInput = this.replaceBox.querySelector(".ace_search_field");
-    };
-    
-    this.$init = function() {
-        var sb = this.element;
-        
-        this.$initElements(sb);
-        
-        var _this = this;
-        event.addListener(sb, "mousedown", function(e) {
-            setTimeout(function(){
-                _this.activeInput.focus();
-            }, 0);
-            event.stopPropagation(e);
-        });
-        event.addListener(sb, "click", function(e) {
-            var t = e.target || e.srcElement;
-            var action = t.getAttribute("action");
-            if (action && _this[action])
-                _this[action]();
-            else if (_this.$searchBarKb.commands[action])
-                _this.$searchBarKb.commands[action].exec(_this);
-            event.stopPropagation(e);
-        });
-
-        event.addCommandKeyListener(sb, function(e, hashId, keyCode) {
-            var keyString = keyUtil.keyCodeToString(keyCode);
-            var command = _this.$searchBarKb.findKeyCommand(hashId, keyString);
-            if (command && command.exec) {
-                command.exec(_this);
-                event.stopEvent(e);
-            }
-        });
-
-        this.$onChange = lang.delayedCall(function() {
-            _this.find(false, false);
-        });
-
-        event.addListener(this.searchInput, "input", function() {
-            _this.$onChange.schedule(20);
-        });
-        event.addListener(this.searchInput, "focus", function() {
-            _this.activeInput = _this.searchInput;
-            _this.searchInput.value && _this.highlight();
-        });
-        event.addListener(this.replaceInput, "focus", function() {
-            _this.activeInput = _this.replaceInput;
-            _this.searchInput.value && _this.highlight();
-        });
-    };
-    this.$closeSearchBarKb = new HashHandler([{
-        bindKey: "Esc",
-        name: "closeSearchBar",
-        exec: function(editor) {
-            editor.searchBox.hide();
-        }
-    }]);
-    this.$searchBarKb = new HashHandler();
-    this.$searchBarKb.bindKeys({
-        "Ctrl-f|Command-f|Ctrl-H|Command-Option-F": function(sb) {
-            var isReplace = sb.isReplace = !sb.isReplace;
-            sb.replaceBox.style.display = isReplace ? "" : "none";
-            sb[isReplace ? "replaceInput" : "searchInput"].focus();
-        },
-        "Ctrl-G|Command-G": function(sb) {
-            sb.findNext();
-        },
-        "Ctrl-Shift-G|Command-Shift-G": function(sb) {
-            sb.findPrev();
-        },
-        "esc": function(sb) {
-            setTimeout(function() { sb.hide();});
-        },
-        "Return": function(sb) {
-            if (sb.activeInput == sb.replaceInput)
-                sb.replace();
-            sb.findNext();
-        },
-        "Shift-Return": function(sb) {
-            if (sb.activeInput == sb.replaceInput)
-                sb.replace();
-            sb.findPrev();
-        },
-        "Tab": function(sb) {
-            (sb.activeInput == sb.replaceInput ? sb.searchInput : sb.replaceInput).focus();
-        }
-    });
-
-    this.$searchBarKb.addCommands([{
-        name: "toggleRegexpMode",
-        bindKey: {win: "Alt-R|Alt-/", mac: "Ctrl-Alt-R|Ctrl-Alt-/"},
-        exec: function(sb) {
-            sb.regExpOption.checked = !sb.regExpOption.checked;
-            sb.$syncOptions();
-        }
-    }, {
-        name: "toggleCaseSensitive",
-        bindKey: {win: "Alt-C|Alt-I", mac: "Ctrl-Alt-R|Ctrl-Alt-I"},
-        exec: function(sb) {
-            sb.caseSensitiveOption.checked = !sb.caseSensitiveOption.checked;
-            sb.$syncOptions();
-        }
-    }, {
-        name: "toggleWholeWords",
-        bindKey: {win: "Alt-B|Alt-W", mac: "Ctrl-Alt-B|Ctrl-Alt-W"},
-        exec: function(sb) {
-            sb.wholeWordOption.checked = !sb.wholeWordOption.checked;
-            sb.$syncOptions();
-        }
-    }]);
-
-    this.$syncOptions = function() {
-        dom.setCssClass(this.regExpOption, "checked", this.regExpOption.checked);
-        dom.setCssClass(this.wholeWordOption, "checked", this.wholeWordOption.checked);
-        dom.setCssClass(this.caseSensitiveOption, "checked", this.caseSensitiveOption.checked);
-        this.find(false, false);
-    };
-
-    this.highlight = function(re) {
-        this.editor.session.highlight(re || this.editor.$search.$options.re);
-        this.editor.renderer.updateBackMarkers()
-    };
-    this.find = function(skipCurrent, backwards) {
-        var range = this.editor.find(this.searchInput.value, {
-            skipCurrent: skipCurrent,
-            backwards: backwards,
-            wrap: true,
-            regExp: this.regExpOption.checked,
-            caseSensitive: this.caseSensitiveOption.checked,
-            wholeWord: this.wholeWordOption.checked
-        });
-        var noMatch = !range && this.searchInput.value;
-        dom.setCssClass(this.searchBox, "ace_nomatch", noMatch);
-        this.editor._emit("findSearchBox", { match: !noMatch });
-        this.highlight();
-    };
-    this.findNext = function() {
-        this.find(true, false);
-    };
-    this.findPrev = function() {
-        this.find(true, true);
-    };
-    this.replace = function() {
-        if (!this.editor.getReadOnly())
-            this.editor.replace(this.replaceInput.value);
-    };    
-    this.replaceAndFindNext = function() {
-        if (!this.editor.getReadOnly()) {
-            this.editor.replace(this.replaceInput.value);
-            this.findNext()
-        }
-    };
-    this.replaceAll = function() {
-        if (!this.editor.getReadOnly())
-            this.editor.replaceAll(this.replaceInput.value);
-    };
-
-    this.hide = function() {
-        this.element.style.display = "none";
-        this.editor.keyBinding.removeKeyboardHandler(this.$closeSearchBarKb);
-        this.editor.focus();
-    };
-    this.show = function(value, isReplace) {
-        this.element.style.display = "";
-        this.replaceBox.style.display = isReplace ? "" : "none";
-
-        this.isReplace = isReplace;
-
-        if (value)
-            this.searchInput.value = value;
-        this.searchInput.focus();
-        this.searchInput.select();
-
-        this.editor.keyBinding.addKeyboardHandler(this.$closeSearchBarKb);
-    };
-
-}).call(SearchBox.prototype);
-
-exports.SearchBox = SearchBox;
-
-exports.Search = function(editor, isReplace) {
-    var sb = editor.searchBox || new SearchBox(editor);
-    sb.show(editor.session.getTextRange(), isReplace);
-};
-
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/js/libs/ace/ext-options.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/js/libs/ace/ext-options.js b/apps/fauxton/assets/js/libs/ace/ext-options.js
deleted file mode 100644
index 9086a16..0000000
--- a/apps/fauxton/assets/js/libs/ace/ext-options.js
+++ /dev/null
@@ -1,252 +0,0 @@
-define('ace/ext/options', ['require', 'exports', 'module' ], function(require, exports, module) {
-
-
-var modesByName = modelist.modesByName;
-
-var options = [
-    ["Document", function(name) {
-        doclist.loadDoc(name, function(session) {
-            if (!session)
-                return;
-            session = env.split.setSession(session);
-            updateUIEditorOptions();
-            env.editor.focus();
-        });
-    }, doclist.all],
-	["Mode", function(value) {
-        env.editor.session.setMode(modesByName[value].mode || modesByName.text.mode);
-        env.editor.session.modeName = value;
-	}, function(value) {
-		return env.editor.session.modeName || "text"
-	}, modelist.modes],
-	["Split", function(value) {
-		var sp = env.split;
-		if (value == "none") {
-			if (sp.getSplits() == 2) {
-				env.secondSession = sp.getEditor(1).session;
-        }
-        sp.setSplits(1);
-    } else {
-        var newEditor = (sp.getSplits() == 1);
-        if (value == "below") {
-            sp.setOrientation(sp.BELOW);
-        } else {
-            sp.setOrientation(sp.BESIDE);
-        }
-        sp.setSplits(2);
-
-        if (newEditor) {
-				var session = env.secondSession || sp.getEditor(0).session;
-            var newSession = sp.setSession(session, 1);
-            newSession.name = session.name;
-        }
-    }
-	}, ["None", "Beside", "Below"]],
-	["Theme", function(value) {
-		if (!value)
-			return;
-		env.editor.setTheme("ace/theme/" + value);
-		themeEl.selectedValue = value;
-	}, function() {
-		return env.editor.getTheme();
-	}, {
-		"Bright": {
-            chrome: "Chrome",
-            clouds: "Clouds",
-            crimson_editor: "Crimson Editor",
-            dawn: "Dawn",
-            dreamweaver: "Dreamweaver",
-            eclipse: "Eclipse",
-            github: "GitHub",
-            solarized_light: "Solarized Light",
-            textmate: "TextMate",
-            tomorrow: "Tomorrow",
-            xcode: "XCode"
-        },
-        "Dark": {
-            ambiance: "Ambiance",
-            chaos: "Chaos",
-            clouds_midnight: "Clouds Midnight",
-            cobalt: "Cobalt",
-            idle_fingers: "idleFingers",
-            kr_theme: "krTheme",
-            merbivore: "Merbivore",
-            merbivore_soft: "Merbivore Soft",
-            mono_industrial: "Mono Industrial",
-            monokai: "Monokai",
-            pastel_on_dark: "Pastel on dark",
-            solarized_dark: "Solarized Dark",
-            twilight: "Twilight",
-            tomorrow_night: "Tomorrow Night",
-            tomorrow_night_blue: "Tomorrow Night Blue",
-            tomorrow_night_bright: "Tomorrow Night Bright",
-            tomorrow_night_eighties: "Tomorrow Night 80s",
-            vibrant_ink: "Vibrant Ink",
-        }
-	}],
-	["Code Folding", function(value) {
-		env.editor.getSession().setFoldStyle(value);
-		env.editor.setShowFoldWidgets(value !== "manual");
-	}, ["manual", "mark begin", "mark begin and end"]],
-	["Soft Wrap", function(value) {
-		value = value.toLowerCase()
-		var session = env.editor.getSession();
-		var renderer = env.editor.renderer;
-		session.setUseWrapMode(value == "off");
-		var col = parseInt(value) || null;
-		renderer.setPrintMarginColumn(col || 80);
-		session.setWrapLimitRange(col, col);
-	}, ["Off", "40 Chars", "80 Chars", "Free"]],
-	["Key Binding", function(value) {
-		env.editor.setKeyboardHandler(keybindings[value]);
-	}, ["Ace", "Vim", "Emacs", "Custom"]],
-	["Font Size", function(value) {
-		env.split.setFontSize(value + "px");
-	}, [10, 11, 12, 14, 16, 20, 24]],
-    ["Full Line Selection", function(checked) {
-		env.editor.setSelectionStyle(checked ? "line" : "text");
-	}],
-	["Highlight Active Line", function(checked) {
-		env.editor.setHighlightActiveLine(checked);
-	}],
-	["Show Invisibles", function(checked) {
-		env.editor.setShowInvisibles(checked);
-	}],
-	["Show Gutter", function(checked) {
-		env.editor.renderer.setShowGutter(checked);
-	}],
-    ["Show Indent Guides", function(checked) {
-		env.editor.renderer.setDisplayIndentGuides(checked);
-	}],
-	["Show Print Margin", function(checked) {
-		env.editor.renderer.setShowPrintMargin(checked);
-	}],
-	["Persistent HScroll", function(checked) {
-		env.editor.renderer.setHScrollBarAlwaysVisible(checked);
-	}],
-	["Animate Scrolling", function(checked) {
-		env.editor.setAnimatedScroll(checked);
-	}],
-	["Use Soft Tab", function(checked) {
-		env.editor.getSession().setUseSoftTabs(checked);
-	}],
-	["Highlight Selected Word", function(checked) {
-		env.editor.setHighlightSelectedWord(checked);
-	}],
-	["Enable Behaviours", function(checked) {
-		env.editor.setBehavioursEnabled(checked);
-	}],
-	["Fade Fold Widgets", function(checked) {
-		env.editor.setFadeFoldWidgets(checked);
-	}],
-	["Show Token info", function(checked) {
-		env.editor.setFadeFoldWidgets(checked);
-	}]
-]
-
-var createOptionsPanel = function(options) {
-	var html = []
-	var container = document.createElement("div");
-	container.style.cssText = "position: absolute; overflow: hidden";
-	var inner = document.createElement("div");
-	inner.style.cssText = "width: 120%;height:100%;overflow: scroll";
-	container.appendChild(inner);
-	html.push("<table><tbody>");
-	
-	options.forEach(function(o) {
-		
-    });
-
-	html.push(
-		'<tr>',
-		  '<td>',
-			'<label for="', s,'"></label>',
-		  '</td><td>',
-			'<input type="', s,'" name="', s,'" id="',s ,'">',
-		  '</td>',
-		'</tr>'
-	)
-	html.push("</tbody></table>");	
-	return container;
-}
-
-function bindCheckbox(id, callback) {
-    var el = document.getElementById(id);
-    if (localStorage && localStorage.getItem(id))
-        el.checked = localStorage.getItem(id) == "1";
-
-    var onCheck = function() {
-        callback(!!el.checked);
-        saveOption(el);
-    };
-    el.onclick = onCheck;
-    onCheck();
-}
-
-function bindDropdown(id, callback) {
-    var el = document.getElementById(id);
-    if (localStorage && localStorage.getItem(id))
-        el.value = localStorage.getItem(id);
-
-    var onChange = function() {
-        callback(el.value);
-        saveOption(el);
-    };
-
-    el.onchange = onChange;
-    onChange();
-}
-
-function fillOptgroup(list, el) {
-    list.forEach(function(item) {
-        var option = document.createElement("option");
-        option.setAttribute("value", item.name);
-        option.innerHTML = item.desc;
-        el.appendChild(option);
-    });
-}
-
-function fillDropdown(list, el) {
-	if (Array.isArray(list)) {
-		fillOptgroup(list, el);
-		return;
-	}
-	for(var i in list) {
-		var group = document.createElement("optgroup");
-		group.setAttribute("label", i);
-		fillOptgroup(list[i], group);
-		el.appendChild(group);
-	}
-}
-
-function createOptionControl(opt) {
-    if (opt.values) {
-        var el = dom.createElement("select");
-        el.setAttribute("size", opt.visibleSize || 1);
-        fillDropdown(opt.values, el)        
-    } else {
-        var el = dom.createElement("checkbox");
-    }
-    el.setAttribute("name", "opt_" + opt.name)
-    return el;
-}
-
-function createOptionCell(opt) {
-    if (opt.values) {
-        var el = dom.createElement("select");
-        el.setAttribute("size", opt.visibleSize || 1);
-        fillDropdown(opt.values, el)        
-    } else {
-        var el = dom.createElement("checkbox");
-    }
-    el.setAttribute("name", "opt_" + opt.name)
-    return el;
-}
-
-
-createOptionsPanel(options)
-
-
-
-});
-


[07/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/tooltip.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/tooltip.less b/apps/fauxton/assets/less/bootstrap/tooltip.less
deleted file mode 100644
index 83d5f2b..0000000
--- a/apps/fauxton/assets/less/bootstrap/tooltip.less
+++ /dev/null
@@ -1,70 +0,0 @@
-//
-// Tooltips
-// --------------------------------------------------
-
-
-// Base class
-.tooltip {
-  position: absolute;
-  z-index: @zindexTooltip;
-  display: block;
-  visibility: visible;
-  font-size: 11px;
-  line-height: 1.4;
-  .opacity(0);
-  &.in     { .opacity(80); }
-  &.top    { margin-top:  -3px; padding: 5px 0; }
-  &.right  { margin-left:  3px; padding: 0 5px; }
-  &.bottom { margin-top:   3px; padding: 5px 0; }
-  &.left   { margin-left: -3px; padding: 0 5px; }
-}
-
-// Wrapper for the tooltip content
-.tooltip-inner {
-  max-width: 200px;
-  padding: 8px;
-  color: @tooltipColor;
-  text-align: center;
-  text-decoration: none;
-  background-color: @tooltipBackground;
-  .border-radius(@baseBorderRadius);
-}
-
-// Arrows
-.tooltip-arrow {
-  position: absolute;
-  width: 0;
-  height: 0;
-  border-color: transparent;
-  border-style: solid;
-}
-.tooltip {
-  &.top .tooltip-arrow {
-    bottom: 0;
-    left: 50%;
-    margin-left: -@tooltipArrowWidth;
-    border-width: @tooltipArrowWidth @tooltipArrowWidth 0;
-    border-top-color: @tooltipArrowColor;
-  }
-  &.right .tooltip-arrow {
-    top: 50%;
-    left: 0;
-    margin-top: -@tooltipArrowWidth;
-    border-width: @tooltipArrowWidth @tooltipArrowWidth @tooltipArrowWidth 0;
-    border-right-color: @tooltipArrowColor;
-  }
-  &.left .tooltip-arrow {
-    top: 50%;
-    right: 0;
-    margin-top: -@tooltipArrowWidth;
-    border-width: @tooltipArrowWidth 0 @tooltipArrowWidth @tooltipArrowWidth;
-    border-left-color: @tooltipArrowColor;
-  }
-  &.bottom .tooltip-arrow {
-    top: 0;
-    left: 50%;
-    margin-left: -@tooltipArrowWidth;
-    border-width: 0 @tooltipArrowWidth @tooltipArrowWidth;
-    border-bottom-color: @tooltipArrowColor;
-  }
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/type.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/type.less b/apps/fauxton/assets/less/bootstrap/type.less
deleted file mode 100644
index 337138a..0000000
--- a/apps/fauxton/assets/less/bootstrap/type.less
+++ /dev/null
@@ -1,247 +0,0 @@
-//
-// Typography
-// --------------------------------------------------
-
-
-// Body text
-// -------------------------
-
-p {
-  margin: 0 0 @baseLineHeight / 2;
-}
-.lead {
-  margin-bottom: @baseLineHeight;
-  font-size: @baseFontSize * 1.5;
-  font-weight: 200;
-  line-height: @baseLineHeight * 1.5;
-}
-
-
-// Emphasis & misc
-// -------------------------
-
-// Ex: 14px base font * 85% = about 12px
-small   { font-size: 85%; }
-
-strong  { font-weight: bold; }
-em      { font-style: italic; }
-cite    { font-style: normal; }
-
-// Utility classes
-.muted               { color: @grayLight; }
-a.muted:hover,
-a.muted:focus        { color: darken(@grayLight, 10%); }
-
-.text-warning        { color: @warningText; }
-a.text-warning:hover,
-a.text-warning:focus { color: darken(@warningText, 10%); }
-
-.text-error          { color: @errorText; }
-a.text-error:hover,
-a.text-error:focus   { color: darken(@errorText, 10%); }
-
-.text-info           { color: @infoText; }
-a.text-info:hover,
-a.text-info:focus    { color: darken(@infoText, 10%); }
-
-.text-success        { color: @successText; }
-a.text-success:hover,
-a.text-success:focus { color: darken(@successText, 10%); }
-
-.text-left           { text-align: left; }
-.text-right          { text-align: right; }
-.text-center         { text-align: center; }
-
-
-// Headings
-// -------------------------
-
-h1, h2, h3, h4, h5, h6 {
-  margin: (@baseLineHeight / 2) 0;
-  font-family: @headingsFontFamily;
-  font-weight: @headingsFontWeight;
-  line-height: @baseLineHeight;
-  color: @headingsColor;
-  text-rendering: optimizelegibility; // Fix the character spacing for headings
-  small {
-    font-weight: normal;
-    line-height: 1;
-    color: @grayLight;
-  }
-}
-
-h1,
-h2,
-h3 { line-height: @baseLineHeight * 2; }
-
-h1 { font-size: @baseFontSize * 2.75; } // ~38px
-h2 { font-size: @baseFontSize * 2.25; } // ~32px
-h3 { font-size: @baseFontSize * 1.75; } // ~24px
-h4 { font-size: @baseFontSize * 1.25; } // ~18px
-h5 { font-size: @baseFontSize; }
-h6 { font-size: @baseFontSize * 0.85; } // ~12px
-
-h1 small { font-size: @baseFontSize * 1.75; } // ~24px
-h2 small { font-size: @baseFontSize * 1.25; } // ~18px
-h3 small { font-size: @baseFontSize; }
-h4 small { font-size: @baseFontSize; }
-
-
-// Page header
-// -------------------------
-
-.page-header {
-  padding-bottom: (@baseLineHeight / 2) - 1;
-  margin: @baseLineHeight 0 (@baseLineHeight * 1.5);
-  border-bottom: 1px solid @grayLighter;
-}
-
-
-
-// Lists
-// --------------------------------------------------
-
-// Unordered and Ordered lists
-ul, ol {
-  padding: 0;
-  margin: 0 0 @baseLineHeight / 2 25px;
-}
-ul ul,
-ul ol,
-ol ol,
-ol ul {
-  margin-bottom: 0;
-}
-li {
-  line-height: @baseLineHeight;
-}
-
-// Remove default list styles
-ul.unstyled,
-ol.unstyled {
-  margin-left: 0;
-  list-style: none;
-}
-
-// Single-line list items
-ul.inline,
-ol.inline {
-  margin-left: 0;
-  list-style: none;
-  > li {
-    display: inline-block;
-    .ie7-inline-block();
-    padding-left: 5px;
-    padding-right: 5px;
-  }
-}
-
-// Description Lists
-dl {
-  margin-bottom: @baseLineHeight;
-}
-dt,
-dd {
-  line-height: @baseLineHeight;
-}
-dt {
-  font-weight: bold;
-}
-dd {
-  margin-left: @baseLineHeight / 2;
-}
-// Horizontal layout (like forms)
-.dl-horizontal {
-  .clearfix(); // Ensure dl clears floats if empty dd elements present
-  dt {
-    float: left;
-    width: @horizontalComponentOffset - 20;
-    clear: left;
-    text-align: right;
-    .text-overflow();
-  }
-  dd {
-    margin-left: @horizontalComponentOffset;
-  }
-}
-
-// MISC
-// ----
-
-// Horizontal rules
-hr {
-  margin: @baseLineHeight 0;
-  border: 0;
-  border-top: 1px solid @hrBorder;
-  border-bottom: 1px solid @white;
-}
-
-// Abbreviations and acronyms
-abbr[title],
-// Added data-* attribute to help out our tooltip plugin, per https://github.com/twitter/bootstrap/issues/5257
-abbr[data-original-title] {
-  cursor: help;
-  border-bottom: 1px dotted @grayLight;
-}
-abbr.initialism {
-  font-size: 90%;
-  text-transform: uppercase;
-}
-
-// Blockquotes
-blockquote {
-  padding: 0 0 0 15px;
-  margin: 0 0 @baseLineHeight;
-  border-left: 5px solid @grayLighter;
-  p {
-    margin-bottom: 0;
-    font-size: @baseFontSize * 1.25;
-    font-weight: 300;
-    line-height: 1.25;
-  }
-  small {
-    display: block;
-    line-height: @baseLineHeight;
-    color: @grayLight;
-    &:before {
-      content: '\2014 \00A0';
-    }
-  }
-
-  // Float right with text-align: right
-  &.pull-right {
-    float: right;
-    padding-right: 15px;
-    padding-left: 0;
-    border-right: 5px solid @grayLighter;
-    border-left: 0;
-    p,
-    small {
-      text-align: right;
-    }
-    small {
-      &:before {
-        content: '';
-      }
-      &:after {
-        content: '\00A0 \2014';
-      }
-    }
-  }
-}
-
-// Quotes
-q:before,
-q:after,
-blockquote:before,
-blockquote:after {
-  content: "";
-}
-
-// Addresses
-address {
-  display: block;
-  margin-bottom: @baseLineHeight;
-  font-style: normal;
-  line-height: @baseLineHeight;
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/utilities.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/utilities.less b/apps/fauxton/assets/less/bootstrap/utilities.less
deleted file mode 100644
index 314b4ff..0000000
--- a/apps/fauxton/assets/less/bootstrap/utilities.less
+++ /dev/null
@@ -1,30 +0,0 @@
-//
-// Utility classes
-// --------------------------------------------------
-
-
-// Quick floats
-.pull-right {
-  float: right;
-}
-.pull-left {
-  float: left;
-}
-
-// Toggling content
-.hide {
-  display: none;
-}
-.show {
-  display: block;
-}
-
-// Visibility
-.invisible {
-  visibility: hidden;
-}
-
-// For Affix plugin
-.affix {
-  position: fixed;
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/variables.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/variables.less b/apps/fauxton/assets/less/bootstrap/variables.less
deleted file mode 100644
index 31c131b..0000000
--- a/apps/fauxton/assets/less/bootstrap/variables.less
+++ /dev/null
@@ -1,301 +0,0 @@
-//
-// Variables
-// --------------------------------------------------
-
-
-// Global values
-// --------------------------------------------------
-
-
-// Grays
-// -------------------------
-@black:                 #000;
-@grayDarker:            #222;
-@grayDark:              #333;
-@gray:                  #555;
-@grayLight:             #999;
-@grayLighter:           #eee;
-@white:                 #fff;
-
-
-// Accent colors
-// -------------------------
-@blue:                  #049cdb;
-@blueDark:              #0064cd;
-@green:                 #46a546;
-@red:                   #9d261d;
-@yellow:                #ffc40d;
-@orange:                #f89406;
-@pink:                  #c3325f;
-@purple:                #7a43b6;
-
-
-// Scaffolding
-// -------------------------
-@bodyBackground:        @white;
-@textColor:             @grayDark;
-
-
-// Links
-// -------------------------
-@linkColor:             #08c;
-@linkColorHover:        darken(@linkColor, 15%);
-
-
-// Typography
-// -------------------------
-@sansFontFamily:        "Helvetica Neue", Helvetica, Arial, sans-serif;
-@serifFontFamily:       Georgia, "Times New Roman", Times, serif;
-@monoFontFamily:        Monaco, Menlo, Consolas, "Courier New", monospace;
-
-@baseFontSize:          14px;
-@baseFontFamily:        @sansFontFamily;
-@baseLineHeight:        20px;
-@altFontFamily:         @serifFontFamily;
-
-@headingsFontFamily:    inherit; // empty to use BS default, @baseFontFamily
-@headingsFontWeight:    bold;    // instead of browser default, bold
-@headingsColor:         inherit; // empty to use BS default, @textColor
-
-
-// Component sizing
-// -------------------------
-// Based on 14px font-size and 20px line-height
-
-@fontSizeLarge:         @baseFontSize * 1.25; // ~18px
-@fontSizeSmall:         @baseFontSize * 0.85; // ~12px
-@fontSizeMini:          @baseFontSize * 0.75; // ~11px
-
-@paddingLarge:          11px 19px; // 44px
-@paddingSmall:          2px 10px;  // 26px
-@paddingMini:           0 6px;   // 22px
-
-@baseBorderRadius:      4px;
-@borderRadiusLarge:     6px;
-@borderRadiusSmall:     3px;
-
-
-// Tables
-// -------------------------
-@tableBackground:                   transparent; // overall background-color
-@tableBackgroundAccent:             #f9f9f9; // for striping
-@tableBackgroundHover:              #f5f5f5; // for hover
-@tableBorder:                       #ddd; // table and cell border
-
-// Buttons
-// -------------------------
-@btnBackground:                     @white;
-@btnBackgroundHighlight:            darken(@white, 10%);
-@btnBorder:                         #ccc;
-
-@btnPrimaryBackground:              @linkColor;
-@btnPrimaryBackgroundHighlight:     spin(@btnPrimaryBackground, 20%);
-
-@btnInfoBackground:                 #5bc0de;
-@btnInfoBackgroundHighlight:        #2f96b4;
-
-@btnSuccessBackground:              #62c462;
-@btnSuccessBackgroundHighlight:     #51a351;
-
-@btnWarningBackground:              lighten(@orange, 15%);
-@btnWarningBackgroundHighlight:     @orange;
-
-@btnDangerBackground:               #ee5f5b;
-@btnDangerBackgroundHighlight:      #bd362f;
-
-@btnInverseBackground:              #444;
-@btnInverseBackgroundHighlight:     @grayDarker;
-
-
-// Forms
-// -------------------------
-@inputBackground:               @white;
-@inputBorder:                   #ccc;
-@inputBorderRadius:             @baseBorderRadius;
-@inputDisabledBackground:       @grayLighter;
-@formActionsBackground:         #f5f5f5;
-@inputHeight:                   @baseLineHeight + 10px; // base line-height + 8px vertical padding + 2px top/bottom border
-
-
-// Dropdowns
-// -------------------------
-@dropdownBackground:            @white;
-@dropdownBorder:                rgba(0,0,0,.2);
-@dropdownDividerTop:            #e5e5e5;
-@dropdownDividerBottom:         @white;
-
-@dropdownLinkColor:             @grayDark;
-@dropdownLinkColorHover:        @white;
-@dropdownLinkColorActive:       @white;
-
-@dropdownLinkBackgroundActive:  @linkColor;
-@dropdownLinkBackgroundHover:   @dropdownLinkBackgroundActive;
-
-
-
-// COMPONENT VARIABLES
-// --------------------------------------------------
-
-
-// Z-index master list
-// -------------------------
-// Used for a bird's eye view of components dependent on the z-axis
-// Try to avoid customizing these :)
-@zindexDropdown:          1000;
-@zindexPopover:           1010;
-@zindexTooltip:           1030;
-@zindexFixedNavbar:       1030;
-@zindexModalBackdrop:     1040;
-@zindexModal:             1050;
-
-
-// Sprite icons path
-// -------------------------
-@iconSpritePath:          "../img/glyphicons-halflings.png";
-@iconWhiteSpritePath:     "../img/glyphicons-halflings-white.png";
-
-
-// Input placeholder text color
-// -------------------------
-@placeholderText:         @grayLight;
-
-
-// Hr border color
-// -------------------------
-@hrBorder:                @grayLighter;
-
-
-// Horizontal forms & lists
-// -------------------------
-@horizontalComponentOffset:       180px;
-
-
-// Wells
-// -------------------------
-@wellBackground:                  #f5f5f5;
-
-
-// Navbar
-// -------------------------
-@navbarCollapseWidth:             979px;
-@navbarCollapseDesktopWidth:      @navbarCollapseWidth + 1;
-
-@navbarHeight:                    40px;
-@navbarBackgroundHighlight:       #ffffff;
-@navbarBackground:                darken(@navbarBackgroundHighlight, 5%);
-@navbarBorder:                    darken(@navbarBackground, 12%);
-
-@navbarText:                      #777;
-@navbarLinkColor:                 #777;
-@navbarLinkColorHover:            @grayDark;
-@navbarLinkColorActive:           @gray;
-@navbarLinkBackgroundHover:       transparent;
-@navbarLinkBackgroundActive:      darken(@navbarBackground, 5%);
-
-@navbarBrandColor:                @navbarLinkColor;
-
-// Inverted navbar
-@navbarInverseBackground:                #111111;
-@navbarInverseBackgroundHighlight:       #222222;
-@navbarInverseBorder:                    #252525;
-
-@navbarInverseText:                      @grayLight;
-@navbarInverseLinkColor:                 @grayLight;
-@navbarInverseLinkColorHover:            @white;
-@navbarInverseLinkColorActive:           @navbarInverseLinkColorHover;
-@navbarInverseLinkBackgroundHover:       transparent;
-@navbarInverseLinkBackgroundActive:      @navbarInverseBackground;
-
-@navbarInverseSearchBackground:          lighten(@navbarInverseBackground, 25%);
-@navbarInverseSearchBackgroundFocus:     @white;
-@navbarInverseSearchBorder:              @navbarInverseBackground;
-@navbarInverseSearchPlaceholderColor:    #ccc;
-
-@navbarInverseBrandColor:                @navbarInverseLinkColor;
-
-
-// Pagination
-// -------------------------
-@paginationBackground:                #fff;
-@paginationBorder:                    #ddd;
-@paginationActiveBackground:          #f5f5f5;
-
-
-// Hero unit
-// -------------------------
-@heroUnitBackground:              @grayLighter;
-@heroUnitHeadingColor:            inherit;
-@heroUnitLeadColor:               inherit;
-
-
-// Form states and alerts
-// -------------------------
-@warningText:             #c09853;
-@warningBackground:       #fcf8e3;
-@warningBorder:           darken(spin(@warningBackground, -10), 3%);
-
-@errorText:               #b94a48;
-@errorBackground:         #f2dede;
-@errorBorder:             darken(spin(@errorBackground, -10), 3%);
-
-@successText:             #468847;
-@successBackground:       #dff0d8;
-@successBorder:           darken(spin(@successBackground, -10), 5%);
-
-@infoText:                #3a87ad;
-@infoBackground:          #d9edf7;
-@infoBorder:              darken(spin(@infoBackground, -10), 7%);
-
-
-// Tooltips and popovers
-// -------------------------
-@tooltipColor:            #fff;
-@tooltipBackground:       #000;
-@tooltipArrowWidth:       5px;
-@tooltipArrowColor:       @tooltipBackground;
-
-@popoverBackground:       #fff;
-@popoverArrowWidth:       10px;
-@popoverArrowColor:       #fff;
-@popoverTitleBackground:  darken(@popoverBackground, 3%);
-
-// Special enhancement for popovers
-@popoverArrowOuterWidth:  @popoverArrowWidth + 1;
-@popoverArrowOuterColor:  rgba(0,0,0,.25);
-
-
-
-// GRID
-// --------------------------------------------------
-
-
-// Default 940px grid
-// -------------------------
-@gridColumns:             12;
-@gridColumnWidth:         60px;
-@gridGutterWidth:         20px;
-@gridRowWidth:            (@gridColumns * @gridColumnWidth) + (@gridGutterWidth * (@gridColumns - 1));
-
-// 1200px min
-@gridColumnWidth1200:     70px;
-@gridGutterWidth1200:     30px;
-@gridRowWidth1200:        (@gridColumns * @gridColumnWidth1200) + (@gridGutterWidth1200 * (@gridColumns - 1));
-
-// 768px-979px
-@gridColumnWidth768:      42px;
-@gridGutterWidth768:      20px;
-@gridRowWidth768:         (@gridColumns * @gridColumnWidth768) + (@gridGutterWidth768 * (@gridColumns - 1));
-
-
-// Fluid grid
-// -------------------------
-@fluidGridColumnWidth:    percentage(@gridColumnWidth/@gridRowWidth);
-@fluidGridGutterWidth:    percentage(@gridGutterWidth/@gridRowWidth);
-
-// 1200px min
-@fluidGridColumnWidth1200:     percentage(@gridColumnWidth1200/@gridRowWidth1200);
-@fluidGridGutterWidth1200:     percentage(@gridGutterWidth1200/@gridRowWidth1200);
-
-// 768px-979px
-@fluidGridColumnWidth768:      percentage(@gridColumnWidth768/@gridRowWidth768);
-@fluidGridGutterWidth768:      percentage(@gridGutterWidth768/@gridRowWidth768);

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/bootstrap/wells.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/bootstrap/wells.less b/apps/fauxton/assets/less/bootstrap/wells.less
deleted file mode 100644
index 84a744b..0000000
--- a/apps/fauxton/assets/less/bootstrap/wells.less
+++ /dev/null
@@ -1,29 +0,0 @@
-//
-// Wells
-// --------------------------------------------------
-
-
-// Base class
-.well {
-  min-height: 20px;
-  padding: 19px;
-  margin-bottom: 20px;
-  background-color: @wellBackground;
-  border: 1px solid darken(@wellBackground, 7%);
-  .border-radius(@baseBorderRadius);
-  .box-shadow(inset 0 1px 1px rgba(0,0,0,.05));
-  blockquote {
-    border-color: #ddd;
-    border-color: rgba(0,0,0,.15);
-  }
-}
-
-// Sizes
-.well-large {
-  padding: 24px;
-  .border-radius(@borderRadiusLarge);
-}
-.well-small {
-  padding: 9px;
-  .border-radius(@borderRadiusSmall);
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/config.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/config.less b/apps/fauxton/assets/less/config.less
deleted file mode 100644
index fe03796..0000000
--- a/apps/fauxton/assets/less/config.less
+++ /dev/null
@@ -1,46 +0,0 @@
-/*  Licensed under the Apache License, Version 2.0 (the "License"); you may not
- *  use this file except in compliance with the License. You may obtain a copy of
- *  the License at
- *
- *    http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- *  License for the specific language governing permissions and limitations under
- *  the License.
- */
-
-.config-item {
-  height: 41px;
-
-  .edit-button {
-    float: right;
-    .btn;
-    .btn-mini;
-    display:none;
-  }
-
-  td:hover .edit-button {
-    display: block;
-  }
-
-  .value-input {
-    width: 98%;
-  }
-
-  #delete-value {
-    cursor: pointer;
-  }
-}
-
-.button-margin {
-  margin-bottom: 15px;
-}
-
-#add-section-modal {
-  width: 400px;
-}
-
-
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/couchdb.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/couchdb.less b/apps/fauxton/assets/less/couchdb.less
deleted file mode 100644
index 20da486..0000000
--- a/apps/fauxton/assets/less/couchdb.less
+++ /dev/null
@@ -1,72 +0,0 @@
-/*  Licensed under the Apache License, Version 2.0 (the "License"); you may not
- *  use this file except in compliance with the License. You may obtain a copy of
- *  the License at
- *
- *    http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- *  License for the specific language governing permissions and limitations under
- *  the License.
- */
-
-/*!
- *
- * CouchDB less style files
- *
- */
-@import "bootstrap/bootstrap.less";
-
-//
-// Variables
-// --------------------------------------------------
-
-
-// Global values
-// --------------------------------------------------
-
-// Links
-@linkColor:             #CA2530;
-@linkColorHover:        darken(@linkColor, 15%);
-
-// Grays
-@black:                 #0C0C0C;
-@grayDark:              #5A5A5A;
-@grayDarker:            darken(@grayDark, 10%);
-@gray:                  #F80507;
-@grayLight:             #E27B81;
-@grayLighter:           #B95D40;
-@white:                 #FDFBFB;
-
-// Accent colors
-// -------------------------
-@blue:                  #049cdb;
-@blueDark:              #0064cd;
-@green:                 #46a546;
-@red:                   #9d261d;
-@yellow:                #ffc40d;
-@orange:                #f89406;
-@pink:                  #c3325f;
-@purple:                #7a43b6;
-
-
-// Scaffolding
-// -------------------------
-@bodyBackground:        @white;
-@textColor:             @grayDark;
-
-// Typography
-// -------------------------
-@sansFontFamily:        "Helvetica Neue", Helvetica, Arial, sans-serif;
-@serifFontFamily:       Georgia, "Times New Roman", Times, serif;
-@monoFontFamily:        Monaco, Menlo, Consolas, "Courier New", monospace;
-
-@baseFontSize:          14px;
-@baseFontFamily:        @sansFontFamily;
-@baseLineHeight:        20px;
-@altFontFamily:         @serifFontFamily;
-
-@headingsFontFamily:    inherit; // empty to use BS default, @baseFontFamily
-@headingsFontWeight:    bold;    // instead of browser default, bold
-@headingsColor:         inherit; // empty to use BS default, @textColor

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/database.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/database.less b/apps/fauxton/assets/less/database.less
deleted file mode 100644
index 377b136..0000000
--- a/apps/fauxton/assets/less/database.less
+++ /dev/null
@@ -1,245 +0,0 @@
-/*  Licensed under the Apache License, Version 2.0 (the "License"); you may not
- *  use this file except in compliance with the License. You may obtain a copy of
- *  the License at
- *
- *    http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- *  License for the specific language governing permissions and limitations under
- *  the License.
- */
-
-/* =database
-   ---------------------------------------------------------------------- */
-#db-tools {
-    position: absolute;
-    top: -7px;
-    right: 0;
-    width: 390px;
-
-    .btn-group {
-        position: absolute;
-        left: 0;
-        top: 6px;
-    }
-
-    form {
-        position: absolute;
-        right: 0;
-        top: 0;
-    }
-}
-
-.tools .nav {
-    margin-bottom: 10px;
-}
-
-#sidenav {
-    padding-top: 10px;
-
-    h3 {
-        margin: 10px 0;
-    }
-
-    li a span.divider {
-        background: none;
-        color: #ccc;
-        padding: 0 2px;
-    }
-
-    li.nav-header a {
-        display: inline
-    }
-
-    div.btn-group {
-        display: inline-block;
-    }
-
-    li.nav-header, #sidenav li a {
-        padding-left: 4px;
-    }
-
-    li.active a {
-        background-color: #ddd;
-        color: #333;
-        text-shadow: none;
-    }
-}
-
-.edit {
-    display: none;
-
-    form {
-        margin-bottom: 0;
-    }
-
-    h3 {
-        border-bottom: 1px solid #ccc;
-        font-size: 100%;
-        line-height: 1;
-        margin-bottom: 18px;
-    }
-
-    textarea {
-        height: 100px;
-        width: 95%;
-    }
-
-    .btn-toolbar {
-        margin-bottom: 0;
-    }
-
-    .preview {
-        width: 100px;
-    }
-
-    .save {
-    }
-}
-
-#new-view-index {
-    .confirm {
-        display: none;
-    }
-
-    .confirm .progress {
-        display: none;
-        margin: 20px;
-    }
-
-    textarea {
-        height: 100px;
-        width: 95%;
-    }
-}
-
-.view {
-    display: none;
-
-    .result-tools {
-        float: left;
-        width: 100%;
-        margin-bottom: 10px;
-    }
-
-    table td div  {
-        position: relative;
-    }
-
-    table td div div {
-        display: none;
-        line-height: 1;
-        position: absolute;
-        right: 4px;
-        top: 4px;
-    }
-
-    table td div:hover div a.edits {
-        padding-left: 16px;
-        padding-right: 16px;
-    }
-
-    table td div:hover div {
-        display: block;
-    }
-
-}
-.view.show {
-    display: block;
-}
-.view.show.hidden-by-params {
-    display: none;
-}
-#database .view table tr td {
-    padding: 0;
-}
-
-.loading {display: none;}
-
-.view-request-duration {
-  padding-right: 10px;
-  float: right;
-}
-
-table.active-tasks{
-    th {
-        cursor: pointer;
-    }
-}
-
-.well{
-    .row-fluid{
-        margin: 0;
-    }
-    .row-fluid .row-fluid:last-child .well-item {
-        border: none;
-    }
-    .well-item{
-        color: #666;
-        font-size: 12px;
-        border-bottom: 1px solid #e5e5e5;
-        padding: 8px 4px;
-        strong {
-            font-size: 16px;
-        }  
-    } 
-}
-
-
-#doc {
-    .dropdown-menu{
-        width: auto;
-    }
-}
-// #tabs {
-//     height: 40px;
-// }
-
-.databases{
-    a.db-actions,
-    a.db-actions:visited{
-        color: @red; 
-        border: 1px solid #e3e3e3;
-        padding: 5px 7px;
-        .border-radius(6px);
-        text-decoration: none;
-        font-size: 19px;
-    }
-}
-.btn-group{
-    ul.dropdown-menu li a:before{
-        margin-right: 10px;
-    }
-}
-
-.design-doc-group{
-    .span3 { margin: 0;}
-    #new-ddoc-section {
-        margin-top: 10px;
-        label{ width: 100px}
-        .controls{
-            margin-left: 100px;
-        }
-    }
-}
-table#changes-table {
-
-  #changes {
-    width: 50%;
-  }
-
-  #seq, #deleted {
-    width: 5%;
-  }
-
-}
-
-.doc-editor-buttons {
-    margin-bottom: 15px;
-    a.button.btn-large.gray {
-        padding: 9px 10px;
-        vertical-align: middle;
-    }
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/fauxton.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/fauxton.less b/apps/fauxton/assets/less/fauxton.less
deleted file mode 100644
index 510c3c1..0000000
--- a/apps/fauxton/assets/less/fauxton.less
+++ /dev/null
@@ -1,1009 +0,0 @@
-/*  Licensed under the Apache License, Version 2.0 (the "License"); you may not
- *  use this file except in compliance with the License. You may obtain a copy of
- *  the License at
- *
- *    http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- *  License for the specific language governing permissions and limitations under
- *  the License.
- */
-
-/*!
- *
- * Fauxton less style files
- *
- */
-@import "bootstrap/bootstrap.less";
-@import "bootstrap/mixins.less";
-@import "variables.less";
-@import "config.less";
-@import "logs.less";
-@import "prettyprint.less";
-@import "database.less";
-@import "icons.less";
-
-
-body {
-  background-color: #F2F2F2;
-}
-#main > footer {
-  position: fixed;
-  bottom: 0;
-  font-size: 10px;
-  margin-left: @navWidth;
-  padding: 5px 10px;
-  background-color: #F2F2F2;
-  width: 100%;
-  .closeMenu & {
-    margin-left: @collapsedNavWidth;
-  }
-}
-
-.hide-text {
-  font: 0/0 a;
-  color: transparent;
-  text-shadow: none;
-  background-color: transparent;
-  border: 0;
-}
-
-.row {
-  margin-left: 0;
-}
-
-// globals
-body {
-  font-size: 16px;
-  line-height:1.3;
-  padding-bottom: 0px;
-  color: #333;
-  padding-top: 92px;
-  &#home{
-    padding-top: 90px;
-  }
-  background-color: @sidebarBG;
-  /* OVERRIDE BOOTSTRAP BTN STYLES */
-  .btn{
-    .box-shadow(none);
-    .border-radius(0);
-    background-image: none;
-    text-shadow: none;
-    background-repeat: no-repeat;
-  }
-}
-
-h2,h3,h4 {font-weight: 600;}
-
-
-a, .btn{
-  .transition(all .25s linear);
-}
-
-a,
-a:visited,
-a:active {
-  color: @linkColor;
-}
-
-a:hover{
-  color: @red;
-}
-
-/* ajax loader */
-.loader {
-  background: url('../img/loader.gif') center center no-repeat;
-  min-height:  100px;
-}
-#app-container.loader{
-  min-height: 400px;
-  > *{
-    display: none;
-  }
-}
-
-#global-notifications {
-  position: fixed;
-  top: 0px;
-  display: block;
-  z-index: 100000;
-  left: @navWidth;
-  .closeMenu & {
-    left: @collapsedNavWidth;
-  }
-  width: 100%;
-}
-
-#app-container{
-  padding: 0;
-  height: 100%;
-  width: 100%;
-  position: absolute;
-  top: 0;
-  left: 0;
-  > .row-fluid {
-    height: 100%;
-  }
-}
-
-/* bootstrap override */
-.container-fluid {
-  padding-right: 0px;
-  padding-left: 0px;
-}
-
-/* Fixed side navigation */
-#primary-navbar {
-  height: 100%;
-  position: fixed;
-  width: @navWidth;
-  top: 0;
-  bottom: 0;
-  background-color: @primaryNav;
-  #footer-links{
-    position: absolute;
-    bottom: 0;
-    width: 100%;
-  }
-
-  .navbar {
-    .brand {
-      .box-sizing(content-box);
-      .hide-text;
-      .customTransition(left, 1s, 0.805, 0.005, 0.165, 0.985);
-      margin: 10px 0 6px;
-      width: 174px;
-      height: 40px;
-      padding: 10px;
-      .icon{
-        .box-sizing(content-box);
-        background: url(../img/couchdb-site.png) no-repeat 0 0;
-        display: block;
-        height: 100%;
-        width: 100%; 
-      }
-      .burger{
-        .transition(all @transitionSpeed @transitionEaseType);
-        padding-top: 6px;
-        left: -8px;
-        position: absolute;
-        div{
-          .transition(all @transitionSpeed @transitionEaseType);
-          height: 4px;
-          width: 8px;
-          .border-radius(2);
-          background-color: @navBG;
-          margin: 4px 0px;
-        }
-      }
-      &:hover .burger div{
-        background-color: @orange;
-      }
-      .closeMenu & {
-        .icon {
-          background: url(../img/minilogo.png) no-repeat 0 0;
-        }
-        width: 45px;
-        .burger{
-          left: 0;
-        }
-      }
-    }
-    nav {
-      .nav{
-        margin: 0;
-        li{
-          .transition(all @transitionSpeed @transitionEaseType);
-          padding: 0;
-          font-size: 20px;
-          line-height: 23px;
-          width: @navWidth;
-          font-weight: normal;
-          font-family: helvetica;
-          .box-sizing(border-box);
-          background-color: @navBG;
-          border-bottom:  1px solid @primaryNav;
-          min-height: 55px;
-          &.active, &:hover{
-            a{
-              .box-shadow(none);
-            }
-            background-color: @red;
-          }
-          &:hover a.fonticon:before{
-            color: @white;
-          }
-          &.active a.fonticon:before,
-          &:hover a.fonticon:before,
-          {
-            text-shadow: @boxShadow;
-            color: @NavIconActive;
-          }
-          a{
-            padding: 17px 25px 12px 60px;
-            background-color: transparent;
-            color: #fff;
-            text-shadow: @textShadowOff;
-            &.closeMenu{
-              color: transparent;
-            }
-            & span.fonticon {
-              position: relative;
-              &:before {
-                position: absolute;
-                top: -5px;
-                left: -44px;
-                font-size: 28px;
-                color: @NavIcon;
-                text-shadow: @boxShadowOff;
-              }
-            }
-            .closeMenu &{
-              color: transparent;
-            }
-          }
-        }
-      }
-      ul#footer-nav-links{
-        li{
-          background-color: @primaryNav;
-          border-top: 1px solid @red;
-          border-bottom: none;
-          font-size: 12px;
-          padding: 12px;
-          min-height: 44px;
-          &.active, &:hover{
-            background-color: @linkRed;
-            border-top: 1px solid @red;
-            a{
-              color: white;
-            }
-          }
-          a{
-            color: @red;
-          }
-        }
-      }
-      ul#bottom-nav-links{
-        margin-top: 0;
-        li{
-          min-height: 46px;
-          background-color: @bottomNav;
-          &.active{
-            background-color:@linkRed;
-          } 
-          &:hover{
-            background-color: @navBGHover;
-          }
-          a{
-            &.fonticon {
-              position: relative;
-              &:before {
-                left: -40px;
-                font-size: 22px;
-              }
-            }
-          }
-        }
-      }
-    }
-  }
-}
-
-
-#dashboard {
-  max-width: 1500px;
-  .box-shadow(-6px 0 rgba(0, 0, 0, 0.1));
-  border-left: 1px solid #999;
-  position: absolute;
-  left: @navWidth;
-  margin-left: 0;
-  background-color: @sidebarBG;
-  min-width: 600px;
-  height: 100%;
-  .closeMenu &{
-    left: @collapsedNavWidth;
-  }
-  &.one-pane{
-    min-width: 800px;
-    margin-top: 0;
-  }
-}
-
-/*dashboard content can be in multiple templates*/
-
-#dashboard-content{
-  &.row-fluid,
-  &.window-resizeable{
-    /*remove gutter without rewriting variable*/
-    margin-left: 0px;
-  }
-  padding: 20px;
-  .with-sidebar &{
-    border-left: 1px solid #999;
-    border-right: 1px solid #999;
-    width: auto;
-    .box-shadow(-6px 0 rgba(0, 0, 0, 0.1));
-    padding: 0px;
-    bottom: 0px;
-    top: 60px;
-    position: absolute;
-    overflow-x: hidden;
-    overflow-y: auto;
-    left: @sidebarWidth;
-    right: 0;
-    .box-sizing(border-box);
-  }
-  > div.inner {
-    display: block;
-  }
-}
-
-.with-sidebar.content-area {
-  position: absolute;
-  top: 0;
-  bottom: 0;
-  left: 0;
-  right: 0;
-}
-
-// .closeMenu .with-sidebar.content-area {
-//   left: 0;
-// }
-/*tools*/
-
-.row-fluid.content-area{
-  background-color: @background;
-}
-
-
-.fixed-header{
-  background-color: @breadcrumbBG;
-  position: fixed;
-  top: 0;
-  right: 0;
-  left: @navWidth;
-  .closeMenu & {
-    left: @collapsedNavWidth;
-  }
-  border-bottom: 5px solid @breadcrumbBorder;
-  .box-shadow(0 4px 6px -2px #808080);
-  z-index: 100;
-  .one-pane & {
-    position: relative;
-    border: none;
-    .box-shadow(none);
-    left: auto;
-  }
-}
-
-#breadcrumbs {
-   padding: 15px 20px;
-   .breadcrumb {
-    margin-bottom: 0;
-    background-color: transparent;
-    padding: 0;
-    li {
-      .divider {
-        font-size: 12px;
-        color: @breadcrumbArrow;
-      }
-      &:first-child {
-        font-size: 30px;
-      }
-      color: @breadcrumbText;
-      font-size: 18px;
-      text-shadow: none;
-      &.active{
-        color: #333;
-      }
-      a{
-        color: @breadcrumbText;
-      }
-    }
-   }
-}
-
-
-footer#mainFooter{
-  position: fixed;
-  bottom: 0;
-}
-
-/*SIDEBAR TEMPLATE STYLES*/
-.topmenu-defaults {
-  height: 70px;
-  padding: 12px 10px 0;
-  border-bottom: 1px solid @darkRed;
-  .box-sizing(border-box);
-}
-
-#dashboard-upper-menu{
-  position: fixed;
-  z-index: 11;
-  .topmenu-defaults;
-  background-color: #CBCBCB;
-}
-
-#dashboard-lower-content{
-  padding: 20px;
-  background-color: #F1F1F1;
-}
-
-#dashboard-upper-content{
-  .well{
-    padding: 20px;
-    .border-radius(0);
-    .box-shadow(none);
-  }
-}
-
-#sidenav{
-  padding: 0;
-  header {
-    width: @sidebarWidth;
-    .box-shadow(inset -7px 0 15px -6px #000);
-    background: transparent url('../img/linen.png') repeat 0 0;
-    .topmenu-defaults;
-  }
-  nav {
-    .nav-list{
-      .divider {
-        border: none;
-      }
-      li.active a {
-        background-color: @darkRed;
-        color: #fff;
-      }
-      a{
-        display: block;
-        padding: 10px 5px 10px 15px;
-        color: #333333;
-        border-bottom: 1px solid #989898;
-      }
-      .nav-header{
-        background-color: #B2B2B2;
-        padding: 5px;
-        text-shadow: none;
-        color: #333333;
-        border-bottom: 1px solid #989898;
-      }
-
-    }
-  }
-}
-#sidebar-content {
-.box-shadow(-7px 0 15px -6px #000);
-  position: absolute;
-  bottom: 0px;
-  top: 60px;
-  width: @sidebarWidth;
-  left: 0;
-  overflow-x: hidden;
-  overflow-y: auto;
-  background-color: @secondarySidebar;
-  > div.inner {
-    display: block;
-  }
-}
-
-
-/*ONE PANEL TEMPLATE ONLY STYLES  AKA _all_dbs */
-
-.result-tools{
-  border-bottom: 1px solid #999999;
-  padding: 5px 0;
-  border-bottom: 1px solid #999999;
-  padding: 10px 0;
-  float: left;
-  width: 100%;
-  margin-bottom: 10px;
-}
-
-.navbar-form.pull-right.database-search {
-  margin: -10px 50px 12px 0;
-  padding: 11px;
-    input[type=text]{
-      margin-top: 0px;
-    }
-}
-
-#db-views-tabs-nav{
-  position: fixed;
-  z-index: 12;
-  margin-top: 31px;
-  margin-bottom: 0;
-  /*background-color: #f4f4f4;*/
-  padding: 0 20px;
-}
-
-.db-views-smaller {
-  max-width: 500px;
-}
-
-.nav-tabs > li{
-  margin-right: 2px;
-  > a {
-  cursor: pointer;
-  color: #333;
-  border-color: #eeeeee #eeeeee #dddddd;
-  text-decoration: none;
-  background-color: #eeeeee;
-  border-radius: 0;
-  border-left: none;
-  border-right: none;
-    &.fonticon:before{
-      margin-right: 6px;
-      font-size: 16px;
-    }
-  }
-}
-
-.nav-tabs > li > a:hover, .nav-tabs > li > a:focus {
-  background-color: @linkRed;
-  border-top: 1px solid @red;
-  color: white;
-}
-
-
-.tab-content {
-  margin-top: 70px;
-}
-
-.well { 
-  .controls-group {
-  &:first-child, &:last-child{
-    margin-top: 24px;
-  }
-  margin-bottom: 8px;
-  }
-  .controls-row {
-    margin-bottom: 8px;
-  }
-}
-
-/*TABLE STYLES*/
-table.table {
-  table-layout: fixed;
-}
-table {
-  tr{
-    td{
-      word-wrap: break-word;
-      &.select {
-        width: 20px;
-      }
-    }
-  }
-}
-table.databases {clear: both;}
-thead {border-bottom: 2px solid @redButton;}
-tbody {padding-top: 10px;}
-.table-condensed td {padding: 18px 5px;}
-.table-striped tbody > tr:nth-child(odd) > td, 
-.table-striped tbody > tr:nth-child(odd) > th
-{
-  background-color: #F7F7F7;
-}
-
-
-/*form elements and buttons*/
-.btn-group {
-  > .btn + .dropdown-toggle,
-  > .btn:first-child,
-  > .btn:last-child,
-  > .dropdown-toggle
-  {
-    .border-radius(0);
-    background-image: none;
-    text-shadow: none;
-  }
-}
-
-.btn {
-  padding-top: 12px;
-  padding-bottom: 12px;
-  margin-top: 0px;
-}
-
-.button{
-  .button-style;
-  .transition(all @transitionSpeed @transitionEaseType);
-  border: none;
-  background-color: @redButton;
-  color: #fff;
-  padding: 10px;
-  .icon {
-    margin-right: 10px;
-    font-size: 20px;
-  }
-  &:hover {
-    color: #fff;
-    text-decoration: none;
-  }
-}
-
-
-.button-style{
-  background-color: @redButton;
-  color: #fff;
-  padding: 10px 15px;
-  cursor: pointer;
-  &:before{
-    padding-right: 5px;
-  }
-  &.outlineGray{
-    border: 1px solid @grayLight;
-    background-color: transparent;
-    color: @grayDark;
-    &:hover{
-      border: 1px solid @orange;
-    }
-  }
-  &.gray{
-    background-color: #ddd;
-    color: @grayDark;
-  }
-  &.green{
-    background-color: @green;
-  }
-
-  &.round-btn {
-    .border-radius(@radius);
-  }
-  .icon {
-    margin-right: 10px;
-    font-size: 20px;
-  }
-  &:hover {
-    color: #fff;
-    text-decoration: none;
-    background-color: @orange;
-  }
-  a&,
-  a&:visited,
-  a&:active{
-    color: #fff;
-  }
-  &:disabled {
-    opacity: 0.5;
-  }
-}
-
-
-
-
-a.button, 
-a.button:visited, 
-a.button:active {
-  .button-style;
-}
-
-.select{
-  > a{
-    display: block;
-    padding: 5px 15px 5px 5px;
-    border: 1px solid #989898;
-    position: relative;
-    background-color: #FFFFFF;
-    color: #666666;
-    &:after {
-      content: '';
-      width: 0;
-      height: 0;
-      border-left: 7px solid transparent;
-      border-right: 7px solid transparent;
-      border-top: 7px solid #989898;
-      position: absolute;
-      right: 9px;
-      top: 12px;
-    }
-    &:before{
-      content: '';
-      border-left:  1px solid #989898;
-      height: 30px;
-      position: absolute;
-      right: 30px;
-      top: 0;
-    }
-  }
-}
-
-input[type=text], input[type=password],
-.navbar-form input{
-  .border-radius(0);
-  padding: 12px;
-  border: 1px solid #ccc;
-  height: auto;
-  font-size: 16px;
-  margin-top: 0;
-}
-
-
-
-label.fonticon-search {
-  .box-sizing(content-box);
-  position: relative;
-  &:before {
-    .transition(all .25s linear);
-    font-size: 16px;
-    position: absolute;
-    right: -47px;
-    background-color: #E1E1E1;
-    height: 46px;
-    width: 48px;
-    border: 1px solid #cccccc;
-    padding: 14px;
-    top: -4px;
-  }
-  &:hover{
-    color:white;
-    &:before {
-      background-color: @red;
-    }
-  }
-}
-
-
-.form-inline {
-  input[type=password],
-  input[type=text]{
-    width: auto;
-  }
-}
-*, *:before, *:after {
-  .box-sizing(border-box);
-}
-
-input[type="checkbox"], input[type="radio"] {
-  box-sizing: border-box;
-  padding: 0;
-}
-
-input[type="file"], input[type="checkbox"], input[type="radio"], select {
-  margin: 0 0 1em 0;
-}
-
-.well select {
-  margin: 0;
-}
-
-form.custom .hidden-field {
-  margin-left: -99999px;
-  position: absolute;
-  visibility: hidden;
-}
-
-
-.checkbox {
-  label{
-    display: inline-block;
-    padding-left:25px;
-  }
-}
-
-label{ 
-  margin-right: 15px; 
-  padding-left:0;
-  display: block;  
-  cursor: pointer;  
-  position: relative;  
-  font-size: 14px; 
-  &.inline{
-    display: inline-block;
-  } 
-}
-.help-block{
-  font-size: 12px;
-}
-
-input[type=text].error{
-  border: red 1px solid;
-}
-
-.custom-inputs{
-
-  input[type=radio], 
-  input[type=checkbox] {  
-    display: none;  
-  } 
-
-  .checkbox label:before {  
-    border-radius: 3px;  
-  }  
-
-  .controls > .radio:first-child, .controls > .checkbox:first-child {
-    padding-top: 15px;
-  }
-
-  .radio.inline, .checkbox.inline {
-    display: inline-block;
-    padding-top: 15px;
-    margin-bottom: 12px;
-    vertical-align: middle;
-  }
-
-  input[type=checkbox]:checked + label:before {  
-    /*content: "\2713"; */
-    content: "\00d7"; 
-    text-shadow: 1px 1px 1px rgba(0, 0, 0, .2);  
-    font-size: 16px;
-    background-color: @red;  
-    color: white;  
-    text-align: center;  
-    line-height: 15px;  
-  }  
-
-  label:before {  
-    content: "";  
-    display: inline-block;  
-
-    width: 16px;  
-    height: 16px;  
-
-    margin-right: 10px;  
-    position: absolute;  
-    left: 0;  
-    bottom: 1px;  
-    background-color: #aaa;  
-    box-shadow: inset 0px 2px 3px 0px rgba(0, 0, 0, .3), 0px 1px 0px 0px rgba(255, 255, 255, .8);  
-  }  
-
-  .radio label:before {  
-    border-radius: 8px;  
-  }  
-
-  input[type=radio]:checked + label:before {  
-    content: "\2022";  
-    color: #f3f3f3;  
-    font-size: 30px;  
-    text-align: center;  
-    line-height: 18px;  
-  }
-
-  label.drop-down{
-    &:before{
-    display: none;
-    }
-  }
-}
-
-form.view-query-update, form.view-query-save {
-  max-width: 100%;
-}
-
-
-.form-actions {
-  background: none;
-  border: none;
-}
-
-.input-append,
-.input-prepend {
-  .add-on {
-    font-size: 18px;
-    padding: 14px 5px 30px;
-  }
-}
-
-.input-append .btn:last-child, 
-.input-append .btn-group:last-child > .dropdown-toggle {
-  padding: 10px 5px 14px;
-}
-.input-append .btn{
-  padding: 10px 5px 14px;
-}
-.row-fluid .input-append [class*="span"],
-.input-prepend input[class*="span"]{
-  width: auto;
-}
-
-/*pretty print*/
-pre.prettyprint {
-  background: #E5E0DD;
-  border: none;
-}
-
-.prettyprint .str, .prettyprint .lit {
-  color: @red;
-}
-
-.prettyprint .pln, .prettyprint .pun, .prettyprint .typ{
-  color: #333333;
-}
-
-/*ALL DOCS TABLE*/
-tr.all-docs-item{
-  border: none;
-  background: transparent;
-}
-
-/*logs*/
-#log-sidebar{
-  padding: 20px;
-}
-
-
-/*documents and databases */
-.view.show{
-  color: @fontGrey;
-}
-
-div.spinner {
-  position: absolute;
-  left: 50%;
-  top: 50%;
-}
-
-/* Code mirror overrides */
-.CodeMirror-scroll {
-  .border-radius(2px);
-  border: solid 1px #ddd;
-}
-
-.btn-primary a:visited {
-  color: #fff;
-}
-
-#api-navbar{
-  position: relative;
-}
-
-.button.api-url-btn {
-  position: absolute;
-  right: 15px;
-  top: -50px;
-  span.icon {
-    font-size: 11px;
-  }
-}
-
-.api-navbar {
-  border-top: 1px solid @red;
-  padding: 20px 20px 15px;
-  .input-append.input-prepend {
-    margin-bottom: 0px;
-    .add-on {
-      background: none;
-      padding: 14px 12px 32px 12px;
-      border: none;
-    }
-    .btn:last-child{
-      margin-left: -1px;
-      background: none;
-      padding: 13px 12px 11px 12px;
-      &:hover{
-        background-color: @red;
-        color: white;
-      }
-    }
-  }
-}
-
-#jump-to-doc,
-#jump-to-db
- {
-  width: auto;
-  float:right;
-  button{
-    padding-left: 20px;
-    padding-right: 10px;
-  }
-}
-
-#map-function, #reduce-function{
-    width: 100%;
-    font-size: 16px;
-}
-
-#editor-container {
-    width: 1316px;
-    height: 688px;
-    font-size: 16px;
-}
-
-#delete-database {
-  float: right;
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/icons.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/icons.less b/apps/fauxton/assets/less/icons.less
deleted file mode 100644
index cf0593c..0000000
--- a/apps/fauxton/assets/less/icons.less
+++ /dev/null
@@ -1,111 +0,0 @@
-/*  Licensed under the Apache License, Version 2.0 (the "License"); you may not
- *  use this file except in compliance with the License. You may obtain a copy of
- *  the License at
- *
- *    http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- *  License for the specific language governing permissions and limitations under
- *  the License.
- */
-
-@font-face {
-  font-family: "fauxtonicon";
-  src: url("../img/fontcustom_fauxton.eot");
-  src: url("../img/fontcustom_fauxton.eot?#iefix") format("embedded-opentype"),
-       url("../img/fontcustom_fauxton.woff") format("woff"),
-       url("../img/fontcustom_fauxton.ttf") format("truetype"),
-       url("../img/fontcustom_fauxton.svg#fontcustom_fauxton") format("svg");
-  font-weight: normal;
-  font-style: normal;
-}
-
-.fonticon-activetasks:before,
-.fonticon-bookmark:before,
-.fonticon-carrot:before,
-.fonticon-circle-check:before,
-.fonticon-circle-minus:before,
-.fonticon-circle-plus:before,
-.fonticon-circle-x:before,
-.fonticon-cog:before,
-.fonticon-collapse:before,
-.fonticon-dashboard:before,
-.fonticon-database:before,
-.fonticon-document:before,
-.fonticon-documents:before,
-.fonticon-expand:before,
-.fonticon-eye:before,
-.fonticon-key:before,
-.fonticon-link:before,
-.fonticon-log:before,
-.fonticon-minus:before,
-.fonticon-mixer:before,
-.fonticon-new-database:before,
-.fonticon-paperclip:before,
-.fonticon-pencil:before,
-.fonticon-play:before,
-.fonticon-plus:before,
-.fonticon-profile:before,
-.fonticon-replicate:before,
-.fonticon-reply:before,
-.fonticon-save:before,
-.fonticon-search:before,
-.fonticon-stats:before,
-.fonticon-support:before,
-.fonticon-swap-arrows:before,
-.fonticon-trash:before,
-.fonticon-user:before,
-.fonticon-users:before,
-.fonticon-wrench:before,
-.fonticon-x:before {
-  font-family: "fauxtonicon";
-  font-style: normal;
-  font-weight: normal;
-  font-variant: normal;
-  text-transform: none;
-  line-height: 1;
-  -webkit-font-smoothing: antialiased;
-  display: inline-block;
-  text-decoration: inherit;
-}
-
-.fonticon-activetasks:before { content: "\f100"; }
-.fonticon-bookmark:before { content: "\f101"; }
-.fonticon-carrot:before { content: "\f102"; }
-.fonticon-circle-check:before { content: "\f103"; }
-.fonticon-circle-minus:before { content: "\f104"; }
-.fonticon-circle-plus:before { content: "\f105"; }
-.fonticon-circle-x:before { content: "\f106"; }
-.fonticon-cog:before { content: "\f107"; }
-.fonticon-collapse:before { content: "\f108"; }
-.fonticon-dashboard:before { content: "\f109"; }
-.fonticon-database:before { content: "\f10a"; }
-.fonticon-document:before { content: "\f10b"; }
-.fonticon-documents:before { content: "\f10c"; }
-.fonticon-expand:before { content: "\f10d"; }
-.fonticon-eye:before { content: "\f10e"; }
-.fonticon-key:before { content: "\f10f"; }
-.fonticon-link:before { content: "\f110"; }
-.fonticon-log:before { content: "\f111"; }
-.fonticon-minus:before { content: "\f112"; }
-.fonticon-mixer:before { content: "\f113"; }
-.fonticon-new-database:before { content: "\f114"; }
-.fonticon-paperclip:before { content: "\f115"; }
-.fonticon-pencil:before { content: "\f116"; }
-.fonticon-play:before { content: "\f117"; }
-.fonticon-plus:before { content: "\f118"; }
-.fonticon-profile:before { content: "\f119"; }
-.fonticon-replicate:before { content: "\f11a"; }
-.fonticon-reply:before { content: "\f11b"; }
-.fonticon-save:before { content: "\f11c"; }
-.fonticon-search:before { content: "\f11d"; }
-.fonticon-stats:before { content: "\f11e"; }
-.fonticon-support:before { content: "\f11f"; }
-.fonticon-swap-arrows:before { content: "\f120"; }
-.fonticon-trash:before { content: "\f121"; }
-.fonticon-user:before { content: "\f122"; }
-.fonticon-users:before { content: "\f123"; }
-.fonticon-wrench:before { content: "\f124"; }
-.fonticon-x:before { content: "\f125"; }

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/logs.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/logs.less b/apps/fauxton/assets/less/logs.less
deleted file mode 100644
index e50f903..0000000
--- a/apps/fauxton/assets/less/logs.less
+++ /dev/null
@@ -1,24 +0,0 @@
-/*  Licensed under the Apache License, Version 2.0 (the "License"); you may not
- *  use this file except in compliance with the License. You may obtain a copy of
- *  the License at
- *
- *    http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- *  License for the specific language governing permissions and limitations under
- *  the License.
- */
-
-#log-sidebar {
-  
-  ul {
-    margin-left: 0px;
-    list-style: none;
-  }
-
-  .remove-filter {
-     opacity: 0.2;
-  }
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/prettyprint.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/prettyprint.less b/apps/fauxton/assets/less/prettyprint.less
deleted file mode 100644
index 7925fa7..0000000
--- a/apps/fauxton/assets/less/prettyprint.less
+++ /dev/null
@@ -1,46 +0,0 @@
-/*  Licensed under the Apache License, Version 2.0 (the "License"); you may not
- *  use this file except in compliance with the License. You may obtain a copy of
- *  the License at
- *
- *    http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- *  License for the specific language governing permissions and limitations under
- *  the License.
- */
-
-pre.prettyprint {
-  background: #000;
-  border-radius: 0;
-  font-size: 83%;
-  line-height: 1.4;
-  margin: 0;
-  padding: 16px;
-}
-.prettyprint {
-  .pln, .pun,  .typ {
-    color: #f8f8f8;
-  }
-  .kwd {
-    color: #ff8300;
-  }
-  .str {
-    color: #ff8300;
-  }
-  .lit {
-    color: #00ff00;
-  }
-  .com {
-    color: #666;
-  }
-}
-.CodeMirror-wrap pre{
-  &.view-code-error{
-    color: @darkRed;
-  }
-  .tooltip{
-    z-index: 100000000;
-  }
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/less/variables.less
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/less/variables.less b/apps/fauxton/assets/less/variables.less
deleted file mode 100644
index bf97b5d..0000000
--- a/apps/fauxton/assets/less/variables.less
+++ /dev/null
@@ -1,82 +0,0 @@
-/*  Licensed under the Apache License, Version 2.0 (the "License"); you may not
- *  use this file except in compliance with the License. You may obtain a copy of
- *  the License at
- *
- *    http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- *  License for the specific language governing permissions and limitations under
- *  the License.
- */
-
-/* = color variables
-   ---------------------------------------------------------------------- */
-@brown: #3A2C2B;
-@red: #E33F3B;
-@darkRed: #AF2D24;
-@linkRed: #DA4F49;
-@greyBrown: #554D4C;
-@fontGrey: #808080;
-@secondarySidebar: #E4DFDC;
-
-
-@orange: #F3622D;
-
-/*nav*/
-@primaryNav : @brown;
-@navBG: @darkRed;
-@navBGHighlight: @red;
-@navBGHover: @red;
-@navIconColor: @darkRed;
-@navIconHighlight: #FFFFFF;
-@bottomNav: @greyBrown;
-
-/*top header*/
-@breadcrumbBG: #F1F1F1;
-@breadcrumbText: @red;
-@breadcrumbArrow: #999999;
-@breadcrumbBorder: @red;
-
-/*background colors*/
-@background: #F2F2F2;
-@leftPanel: @background;
-@rightPanel: #CBCBCB;
-@defaultText: #4D4D4D;
-@defaultHTag: #333333;
-
-@saveButton: #80A221;
-
-@collapsedNavWidth: 62px;
-@navWidth: 220px;
-@sidebarBG: #F2F2F2;
-@sidebarWidth: 330px;
-
-@NavIconActive: #ffffff;
-@NavIcon: @brown;
-
-
-/*buttons */
-@redButton: @red;
-@linkColor: @red;
-@blue:                  #049cdb;
-@blueDark:              #0064cd;
-@green:                 #7FA30C;
-//@red:                   #9d261d;
-@yellow:                #ffcc00;
-@pink:                  #c3325f;
-@purple:                #7a43b6;
-
-
-
-
-@boxShadow: 2px 2px rgba(0,0,0,0.2);
-@boxShadowOff: 2px 2px rgba(0,0,0,0);
-@textShadow: 1px 2px rgba(0,0,0,0.2);
-@textShadowOff: 1px 2px rgba(0,0,0,0);
-
-@radius: 4px;
-@transitionSpeed: .25s;
-@transitionEaseType: linear;
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/bin/grunt
----------------------------------------------------------------------
diff --git a/apps/fauxton/bin/grunt b/apps/fauxton/bin/grunt
deleted file mode 100755
index 2c52393..0000000
--- a/apps/fauxton/bin/grunt
+++ /dev/null
@@ -1,18 +0,0 @@
-#!/bin/sh
-
-# Licensed under the Apache License, Version 2.0 (the "License"); you may not
-# use this file except in compliance with the License. You may obtain a copy of
-# the License at
-#
-#   http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-# License for the specific language governing permissions and limitations under
-# the License.
-
-REL_PATH="`dirname \"$0\"`"
-GRUNT_PATH="$REL_PATH/../node_modules/.bin/grunt"
-
-$GRUNT_PATH $*

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/couchapp.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/couchapp.js b/apps/fauxton/couchapp.js
deleted file mode 100644
index fec8dd3..0000000
--- a/apps/fauxton/couchapp.js
+++ /dev/null
@@ -1,39 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-var couchapp = require('couchapp'),
-    path = require('path'),
-    ddoc;
-
-ddoc = {
-  _id: '_design/fauxton',
-  rewrites: [
-    { "from": "_db" ,    "to"  : "../.." },
-    { "from": "_db/*" ,  "to"  : "../../*" },
-    { "from": "_ddoc" ,  "to"  : "" },
-    { "from": "_ddoc/*", "to"  : "*"},
-    {from: '/', to: 'index.html'},
-    {from: '/*', to: '*'}
-  ],
-  views: {},
-  shows: {},
-  lists: {},
-  validate_doc_update: function(newDoc, oldDoc, userCtx) {
-    /*if (newDoc._deleted === true && userCtx.roles.indexOf('_admin') === -1) {
-      throw "Only admin can delete documents on this database.";
-    }*/
-  }
-};
-
-
-couchapp.loadAttachments(ddoc, path.join(__dirname, 'dist', 'release'));
-module.exports = ddoc;

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/extensions.md
----------------------------------------------------------------------
diff --git a/apps/fauxton/extensions.md b/apps/fauxton/extensions.md
deleted file mode 100644
index 13fcf8d..0000000
--- a/apps/fauxton/extensions.md
+++ /dev/null
@@ -1,17 +0,0 @@
-#Extensions
-
-Extensions allow Fauxton views to be have extra functionality.
-
-A module registers an extension by
-
-    FauxtonAPI.registerExtension('extensionName', myObjectToRegister);
-
-Any other module wanting to use that extension can then get 
-all objects registered for an extension by:
-
-    var extensions = FauxtonAPI.getExtensions('extensionName');
-    // extensions will always be an array
-
-The module can then use those extensions to extend its functionality.
-An example of extensions in the compaction module (app/addons/compaction/base.js) 
-and in documents module (app/modules/documents/views line 1003)

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/favicon.ico
----------------------------------------------------------------------
diff --git a/apps/fauxton/favicon.ico b/apps/fauxton/favicon.ico
deleted file mode 100644
index 0baa6f3..0000000
Binary files a/apps/fauxton/favicon.ico and /dev/null differ

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/index.html
----------------------------------------------------------------------
diff --git a/apps/fauxton/index.html b/apps/fauxton/index.html
deleted file mode 100644
index 892f499..0000000
--- a/apps/fauxton/index.html
+++ /dev/null
@@ -1,53 +0,0 @@
-<!doctype html>
-
-<!--
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
--->
-
-<html lang="en">
-<head>
-  <meta charset="utf-8">
-  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
-  <meta name="viewport" content="width=device-width,initial-scale=1">
-
-  <title>Project Fauxton</title>
-
-  <!-- Application styles. -->
-  <link rel="stylesheet" href="/css/index.css">
-  <style type="text/css">
-    body {
-    padding-top: 60px;
-    padding-bottom: 40px;
-    }
-  </style>
-  <base href="/"></base>
-</head>
-
-<body id="home">
-  <!-- Main container. -->
-  <div role="main" id="main">
-    <div id="global-notifications" class="container errors-container"></div>
-    <div id="app-container"></div>
-    <hr>
-
-    <footer>
-      <div id="footer-content" class="container">
-        <p>&copy; Project Fauxton 2012</p>
-      </div>
-    </footer>
-  </div>
-
-  <!-- Application source. -->
-  <script data-main="/app/config" src="/assets/js/libs/require.js"></script>
-</body>
-</html>

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/package.json
----------------------------------------------------------------------
diff --git a/apps/fauxton/package.json b/apps/fauxton/package.json
deleted file mode 100644
index fd5e3d3..0000000
--- a/apps/fauxton/package.json
+++ /dev/null
@@ -1,48 +0,0 @@
-{
-  "name": "fauxton",
-  "version": "0.1.0",
-  "description": "Fauxton is a modular CouchDB dashboard and Futon replacement.",
-  "main": "grunt.js",
-  "directories": {
-    "test": "test"
-  },
-  "dependencies": {
-    "async": "~0.2.6",
-    "grunt": "~0.4.1",
-    "grunt-cli": "~0.1.6",
-    "couchapp": "~0.9.1",
-    "grunt-contrib-cssmin": "~0.5.0",
-    "grunt-contrib-clean": "~0.4.1",
-    "grunt-contrib-jshint": "~0.6.0",
-    "grunt-contrib-concat": "~0.3.0",
-    "grunt-contrib-less": "~0.5.0",
-    "grunt-contrib-jst": "~0.5.0",
-    "grunt-contrib-watch": "~0.4.4",
-    "grunt-contrib-uglify": "~0.2.0",
-    "grunt-contrib-copy": "~0.4.1",
-    "grunt-couchapp": "~0.1.0",
-    "grunt-exec": "~0.4.0",
-    "grunt-init": "~0.2.0",
-    "grunt-contrib-requirejs": "~0.4.1",
-    "underscore": "~1.4.2",
-    "url": "~0.7.9",
-    "urls": "~0.0.3",
-    "http-proxy": "~0.10.2",
-    "send": "~0.1.1",
-    "grunt-mocha-phantomjs": "~0.3.0"
-  },
-  "scripts": {
-    "test": "echo \"Error: no test specified\" && exit 1"
-  },
-  "repository": {
-    "type": "git",
-    "url": "https://git-wip-us.apache.org/repos/asf/couchdb.git"
-  },
-  "keywords": [
-    "couchdb",
-    "futon",
-    "fauxton"
-  ],
-  "author": "",
-  "license": "Apache V2"
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/readme.md
----------------------------------------------------------------------
diff --git a/apps/fauxton/readme.md b/apps/fauxton/readme.md
deleted file mode 100644
index a0c7702..0000000
--- a/apps/fauxton/readme.md
+++ /dev/null
@@ -1,79 +0,0 @@
-Fauxton
-=======
-
-This is the initial implementation of Fauxton, focused on fleshing out
-the various pieces of functionality and as a test bed for new ideas.
-Full functionality and design considerations will be added later.
-
-
-
-Current items of interest:
-
-  * Live JSON editor with dynamic JS Hinting and error popups
-  * Initial plugin system
-  * Minimal externally loadable plugin example
-  * Data popups for additional db info on \_all_dbs page
-  * CouchDB API compliant urls
-
-## Setup Fauxton ##
-
-A recent of [node.js](http://nodejs.org/) and npm is required.
-
-### CouchDB Setup ###
-
-    1. Clone the Couchdb repo: https://github.com/apache/couchdb.git or http://git-wip-us.apache.org/repos/asf/couchdb.git
-    cd couchdb
-
-### Fauxton Setup ###
-
-    cd src/fauxton
-
-    # Install all dependencies
-    npm install
-
-### Dev Server
-    Using the dev server is the easiest way to use fauxton, specially when developing for it.
-
-    grunt dev
-
-#### (Optional) To avoid a npm global install
-    # Add node_modules/.bin to your path
-    # export PATH=./node_modules/.bin:$PATH
-		# Or just use the wrappers in ./bin/
-
-    # Development mode, non minified files
-    ./bin/grunt couchdebug
-
-    # Or fully compiled install
-    # ./bin/grunt couchdb
-
-### Prepare Fauxton Release
-    Follow the "Fauxton Setup" section,
-    Edit settings.json variable root where the document will live.  eg.  "/_utils/fauxton/"
-    
-    then:
-
-    ./bin/grunt couchdb
-
-    This will install the latest version of Fauxton into `/share/www/fauxton`
-
-### Running Tests
-    There are two ways to run the tests. `grunt test` will run the tests via the commandline. It is also possible to view them via the url
-    `http://localhost:8000/testrunner` when the dev server is running. Refreshing the url will rerun the tests via phantomjs and in the browser.
-
-### To Deploy Fauxton
-
-    ./bin/grunt couchapp_deploy - to deploy to your local [Couchdb instance] (http://localhost:5984/fauxton/_design/fauxton/index.html)
-
-## Understang Fauxton Code layout
-
-Each bit of functionality is its own seperate module or addon. All core modules are stored under `app/module` and any addons that are optional are under `app/addons`.
-We use [backbone.js](http://backbonejs.org/) and [Backbone.layoutmanager](https://github.com/tbranyen/backbone.layoutmanager) quite heavily, so best to get an idea how they work.
-Its best at this point to read through a couple of the modules and addons to get an idea of how they work. Two good starting points are `app/addon/config` and `app/modules/databases`.
-Each module must have a `base.js` file, this is read and compile when Fauxton is deployed. A `resource.js` file is usually for your Backbone.Models and Backbone.Collections,
-`view.js` for your Backbone.Views. The `routes.js` is used to register a url path for your view along with what layout, data, breadcrumbs and api point is required for the view.
-
-## Todo items
-
-Checkout [Jira](https://issues.apache.org/jira/browse/COUCHDB/component/12320406) for a list of items to do.
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/settings.json.default
----------------------------------------------------------------------
diff --git a/apps/fauxton/settings.json.default b/apps/fauxton/settings.json.default
deleted file mode 100644
index ad7e6b5..0000000
--- a/apps/fauxton/settings.json.default
+++ /dev/null
@@ -1,55 +0,0 @@
-{
-  "deps": [
-  { "name": "activetasks" },
-  { "name": "config" },
-  { "name": "logs" },
-  { "name": "stats" },
-  { "name": "replication" },
-  { "name": "plugins" },
-  { "name": "contribute" },
-  { "name": "permissions" },
-  { "name": "compaction" },
-  { "name": "auth" },
-  { "name": "verifyinstall" }
-  ],
-    "template": {
-      "development": {
-        "src": "assets/index.underscore",
-        "dest": "dist/debug/index.html",
-        "variables": {
-          "requirejs": "/assets/js/libs/require.js",
-          "css": "./css/index.css",
-          "base": null
-        },
-        "app": {
-          "root": "/",
-          "host": "../..",
-          "version": "1.0.dev"
-        }
-      },
-      "release": {
-        "src": "assets/index.underscore",
-        "dest": "dist/debug/index.html",
-        "variables": {
-          "requirejs": "./js/require.js",
-          "css": "./css/index.css",
-          "base": null
-        },
-        "app": {
-          "root": "/_utils/fauxton/",
-          "host": "../..",
-          "version": "1.0"
-        }
-      }
-    },
-
-    "couch_config": {
-      "fauxton": {
-        "db": "http://localhost:5984/fauxton",
-        "app": "./couchapp.js",
-        "options": {
-          "okay_if_missing": true
-        }
-      }
-    }
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/settings.json.sample_external
----------------------------------------------------------------------
diff --git a/apps/fauxton/settings.json.sample_external b/apps/fauxton/settings.json.sample_external
deleted file mode 100644
index 71c45b4..0000000
--- a/apps/fauxton/settings.json.sample_external
+++ /dev/null
@@ -1,10 +0,0 @@
-{
-  "deps": [
-    {
-      "name": "fauxton-demo-plugin",
-      "url": "git://github.com/chewbranca/fauxton-demo-plugin.git"
-    },
-    { "name": "config" },
-    { "name": "logs" }
-  ]
-}

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/tasks/addon/rename.json
----------------------------------------------------------------------
diff --git a/apps/fauxton/tasks/addon/rename.json b/apps/fauxton/tasks/addon/rename.json
deleted file mode 100644
index 046ca50..0000000
--- a/apps/fauxton/tasks/addon/rename.json
+++ /dev/null
@@ -1,5 +0,0 @@
-{
-  "routes.js.underscore": "{%= path %}/{%= name.toLowerCase() %}/routes.js",
-  "resources.js.underscore": "{%= path %}/{%= name.toLowerCase() %}/resources.js",
-  "base.js.underscore": "{%= path %}/{%= name.toLowerCase() %}/base.js"
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/tasks/addon/root/base.js.underscore
----------------------------------------------------------------------
diff --git a/apps/fauxton/tasks/addon/root/base.js.underscore b/apps/fauxton/tasks/addon/root/base.js.underscore
deleted file mode 100644
index d002cd5..0000000
--- a/apps/fauxton/tasks/addon/root/base.js.underscore
+++ /dev/null
@@ -1,21 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-  "app",
-  "api",
-  "addons/{%= name.toLowerCase() %}/routes"
-],
-
-function(app, FauxtonAPI, {%= name %}) {
-  return {%= name %};
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/tasks/addon/root/resources.js.underscore
----------------------------------------------------------------------
diff --git a/apps/fauxton/tasks/addon/root/resources.js.underscore b/apps/fauxton/tasks/addon/root/resources.js.underscore
deleted file mode 100644
index 8d0ef32..0000000
--- a/apps/fauxton/tasks/addon/root/resources.js.underscore
+++ /dev/null
@@ -1,21 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-  "app",
-  "api"
-],
-
-function (app, FauxtonAPI) {
-  var {%= name %} = FauxtonAPI.addon();
-  return {%= name %};
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/tasks/addon/root/routes.js.underscore
----------------------------------------------------------------------
diff --git a/apps/fauxton/tasks/addon/root/routes.js.underscore b/apps/fauxton/tasks/addon/root/routes.js.underscore
deleted file mode 100644
index fa565b3..0000000
--- a/apps/fauxton/tasks/addon/root/routes.js.underscore
+++ /dev/null
@@ -1,42 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-define([
-  "app",
-  "api",
-  "addons/{%= name.toLowerCase() %}/resources"
-],
-function(app, FauxtonAPI, {%= name %}) {
-  {%= name.substr(0, 1).toUpperCase() + name.substr(1)%}RouteObject = FauxtonAPI.RouteObject.extend({
-    layout: "with_sidebar",
-
-    crumbs: [
-    ],
-
-    routes: {
-    },
-
-    roles: [],
-
-    apiUrl: function() {
-      return ["insert url here..."];
-    },
-
-    initialize: function () {
-    },
-
-  });
-
-
-  {%= name %}.RouteObjects =  [{%= name.substr(0, 1).toUpperCase() + name.substr(1)%}RouteObject];
-  return {%= name %};
-});

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/tasks/addon/template.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/tasks/addon/template.js b/apps/fauxton/tasks/addon/template.js
deleted file mode 100644
index 459ff34..0000000
--- a/apps/fauxton/tasks/addon/template.js
+++ /dev/null
@@ -1,70 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-'use strict';
-
-exports.description = 'Generate a skeleton for an addon.';
-
-exports.notes = '';
-
-exports.after = "Created your addon! Don't forget to update your"+
-                " settings.json for it to be compiled and deployed";
-
-// Any existing file or directory matching this wildcard will cause a warning.
-// exports.warnOn = '*';
-
-// The actual init template.
-exports.template = function(grunt, init, done) {
-
-  // destpath
-  init.process(
-    {},
-    [
-      {
-        name: "name",
-        message: "Add on Name",
-        validator: /^[\w\-\.]+$/,
-        default: "WickedCool"
-      },
-      {
-        name: "path",
-        message: "Location of add ons",
-        default: "app/addons"
-      },
-      {
-        name: "assets",
-        message: "Do you need an assets folder? (for .less)",
-        default: 'y/N'
-      }
-    ],
-    function (err, props) {
-      // Files to copy (and process).
-      var files = init.filesToCopy(props);
-
-      // Actually copy and process (apply the template props) files.
-      init.copyAndProcess(files, props);
-
-      // Make the assets dir if requested
-      if (props.assets == "y"){
-        var asspath = props.path + "/" + props.name.toLowerCase() + "/assets";
-        grunt.file.mkdir(asspath);
-        grunt.log.writeln("Created " + asspath);
-      }
-
-      var tmplpath = props.path + "/" + props.name.toLowerCase() + "/templates";
-      grunt.file.mkdir(tmplpath);
-      grunt.log.writeln("Created " + tmplpath);
-      // All done!
-      done();
-    }
-  )
-};
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/tasks/couchserver.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/tasks/couchserver.js b/apps/fauxton/tasks/couchserver.js
deleted file mode 100644
index b9ff3ef..0000000
--- a/apps/fauxton/tasks/couchserver.js
+++ /dev/null
@@ -1,104 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-module.exports = function (grunt) {
-  var log = grunt.log;
-
-  grunt.registerTask("couchserver", 'Run a couch dev proxy server', function () {
-    var fs = require("fs"),
-        path = require("path"),
-        http = require("http"),
-        httpProxy = require('http-proxy'),
-        send = require('send'),
-        options = grunt.config('couchserver');
-
-    // Options
-    var dist_dir = options.dist || './dist/debug/',
-        app_dir = './app',
-        port = options.port || 8000;
-
-    // Proxy options with default localhost
-    var proxy_settings = options.proxy || {
-      target: {
-        host: 'localhost',
-        port: 5984,
-        https: false
-      }
-    };
-
-    // inform grunt that this task is async
-    var done = this.async();
-
-    // create proxy to couch for all couch requests
-    var proxy = new httpProxy.HttpProxy(proxy_settings);
-
-    http.createServer(function (req, res) {
-      var url = req.url.replace('app/',''),
-          accept = req.headers.accept.split(','),
-          filePath;
-
-      if (!!url.match(/assets/)) {
-        // serve any javascript or css files from here assets dir
-        filePath = path.join('./',url);
-      } else if (!!url.match(/mocha|\/test\/core\/|test\.config/)) {
-        filePath = path.join('./test', url.replace('/test/',''));
-      } else if (!!url.match(/\.css|img/)) {
-        filePath = path.join(dist_dir,url);
-      /*} else if (!!url.match(/\/js\//)) {
-        // serve any javascript or files from dist debug dir
-        filePath = path.join(dist_dir,req.url);*/
-      } else if (!!url.match(/\.js$|\.html$/)) {
-        // server js from app directory
-        filePath = path.join(app_dir, url.replace('/_utils/fauxton/',''));
-      } else if (!!url.match(/testrunner/)) {
-        var testSetup = grunt.util.spawn({cmd: 'grunt', grunt: true, args: ['mochaSetup']}, function (error, result, code) {/* log.writeln(String(result));*/ });
-        testSetup.stdout.pipe(process.stdout);
-        testSetup.stderr.pipe(process.stderr);
-        filePath = path.join('./test/runner.html');
-      } else if (url === '/' && accept[0] !== 'application/json') {
-        // serve main index file from here
-        filePath = path.join(dist_dir, 'index.html');
-      };
-
-      if (filePath) {
-        return send(req, filePath)
-          .on('error', function (err) {
-            if (err.status === 404) {
-              log.writeln('Could not locate', filePath);
-            } else {
-              log.writeln('ERROR', filePath, err);
-            }
-
-            res.setHeader("Content-Type", "text/javascript");
-            res.statusCode = 404;
-            res.end(JSON.stringify({error: err.message}));
-          })
-          .pipe(res);
-      } 
-
-      proxy.proxyRequest(req, res);
-    }).listen(port);
-
-    // Fail this task if any errors have been logged
-    if (grunt.errors) {
-      return false;
-    }
-
-    var watch = grunt.util.spawn({cmd: 'grunt', grunt: true, args: ['watch']}, function (error, result, code) {/* log.writeln(String(result));*/ });
-
-    watch.stdout.pipe(process.stdout);
-    watch.stderr.pipe(process.stderr);
-
-    log.writeln('Listening on ' + port);
-  });
-
-};

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/tasks/fauxton.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/tasks/fauxton.js b/apps/fauxton/tasks/fauxton.js
deleted file mode 100644
index e54bab8..0000000
--- a/apps/fauxton/tasks/fauxton.js
+++ /dev/null
@@ -1,137 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-module.exports = function(grunt) {
-  var _ = grunt.util._;
-
-  grunt.registerMultiTask('template', 'generates an html file from a specified template', function(){
-    var data = this.data,
-        _ = grunt.util._,
-        tmpl = _.template(grunt.file.read(data.src), null, data.variables);
-
-    grunt.file.write(data.dest, tmpl(data.variables));
-  });
-
-  grunt.registerMultiTask('get_deps', 'Fetch external dependencies', function(version) {
-    grunt.log.writeln("Fetching external dependencies");
-
-    var path = require('path');
-        done = this.async(),
-        data = this.data,
-        target = data.target || "app/addons/",
-        settingsFile = path.existsSync(data.src) ? data.src : "settings.json.default",
-        settings = grunt.file.readJSON(settingsFile),
-        _ = grunt.util._;
-
-    // This should probably be a helper, though they seem to have been removed
-    var fetch = function(deps, command){
-      var child_process = require('child_process');
-      var async = require('async');
-      async.forEach(deps, function(dep, cb) {
-        var path = target + dep.name;
-        var location = dep.url || dep.path;
-        grunt.log.writeln("Fetching: " + dep.name + " (" + location + ")");
-
-        child_process.exec(command(dep, path), function(error, stdout, stderr) {
-          grunt.log.writeln(stderr);
-          grunt.log.writeln(stdout);
-          cb(error);
-        });
-      }, function(error) {
-        if (error) {
-          grunt.log.writeln("ERROR: " + error.message);
-          return false;
-        } else {
-          return true;
-        }
-      });
-    };
-
-    var remoteDeps = _.filter(settings.deps, function(dep) { return !! dep.url; });
-    grunt.log.writeln(remoteDeps.length + " remote dependencies");
-    var remote = fetch(remoteDeps, function(dep, destination){
-      return "git clone " + dep.url + " " + destination;
-    });
-
-    var localDeps = _.filter(settings.deps, function(dep) { return !! dep.path; });
-    grunt.log.writeln(localDeps.length + " local dependencies");
-    var local = fetch(localDeps, function(dep, destination){
-      // TODO: Windows
-      var command = "cp -r " + dep.path + " " + destination;
-      grunt.log.writeln(command);
-      return command;
-    });
-
-    done(remote && local);
-
-  });
-
-  grunt.registerMultiTask('gen_load_addons', 'Generate the load_addons.js file', function() {
-    var path = require('path');
-        data = this.data,
-        _ = grunt.util._,
-        settingsFile = path.existsSync(data.src) ? data.src : "settings.json.default",
-        settings = grunt.file.readJSON(settingsFile),
-        template = "app/load_addons.js.underscore",
-        dest = "app/load_addons.js",
-        deps = _.map(settings.deps, function(dep) {
-          return "addons/" + dep.name + "/base";
-        });
-
-    var tmpl = _.template(grunt.file.read(template));
-    grunt.file.write(dest, tmpl({deps: deps}));
-  });
-
-  grunt.registerMultiTask('gen_initialize', 'Generate the app.js file', function() {
-    var _ = grunt.util._,
-        settings = this.data,
-        template = "app/initialize.js.underscore",
-        dest = "app/initialize.js"
-        tmpl = _.template(grunt.file.read(template)),
-        app = {};
-      
-
-    _.defaults(app, settings.app, {
-      root: '/',
-      host: '../..',
-      version: "0.0"
-    });
-
-    grunt.file.write(dest, tmpl(app));
-  });
-
-  grunt.registerMultiTask('mochaSetup','Generate a config.js and runner.html for tests', function(){
-    var data = this.data,
-        configInfo,
-        _ = grunt.util._,
-        configTemplateSrc = data.template,
-        testFiles = grunt.file.expand(data.files.src);
-
-    var configTemplate = _.template(grunt.file.read(configTemplateSrc));
-    // a bit of a nasty hack to read our current config.js and get the info so we can change it 
-    // for our testing setup
-    var require = {
-      config: function (args) {
-        configInfo = args;
-        configInfo.paths['chai'] = "../test/mocha/chai";
-        configInfo.paths['sinon-chai'] = "../test/mocha/sinon-chai";
-        configInfo.paths['testUtils'] = "../test/mocha/testUtils";
-        configInfo.baseUrl = '../app';
-        delete configInfo.deps;
-      }
-    };
-
-    eval(grunt.file.read(data.config) +'');
-
-    grunt.file.write('./test/test.config.js', configTemplate({configInfo: configInfo, testFiles: testFiles}));
-  });
-};

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/tasks/helper.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/tasks/helper.js b/apps/fauxton/tasks/helper.js
deleted file mode 100644
index 4b66e55..0000000
--- a/apps/fauxton/tasks/helper.js
+++ /dev/null
@@ -1,45 +0,0 @@
-// Licensed under the Apache License, Version 2.0 (the "License"); you may not
-// use this file except in compliance with the License. You may obtain a copy of
-// the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-// License for the specific language governing permissions and limitations under
-// the License.
-
-var fs = require('fs'),
-    path = require('path');
-
-exports.init = function(grunt) {
-  var _ = grunt.util._;
-
-  return { 
-    readSettingsFile: function () {
-      if (fs.existsSync("settings.json")) {
-        return grunt.file.readJSON("settings.json");
-      } else if (fs.existsSync("settings.json.default")) {
-        return grunt.file.readJSON("settings.json.default");
-      } else {
-        return {deps: []};
-      }
-    },
-
-    processAddons: function (callback) {
-      this.readSettingsFile().deps.forEach(callback);
-    },
-
-    watchFiles: function (fileExtensions, defaults) {
-      return _.reduce(this.readSettingsFile().deps, function (files, dep) { 
-        if (dep.path) { 
-          _.each(fileExtensions, function (fileExtension) {
-            files.push(path.join(dep.path, '**/*' + fileExtension ));
-          });
-        }
-        return files
-      }, defaults);
-    }
-  };
-};


[04/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/test/mocha/mocha.css
----------------------------------------------------------------------
diff --git a/apps/fauxton/test/mocha/mocha.css b/apps/fauxton/test/mocha/mocha.css
deleted file mode 100755
index 1d74784..0000000
--- a/apps/fauxton/test/mocha/mocha.css
+++ /dev/null
@@ -1,251 +0,0 @@
-@charset "utf-8";
-
-body {
-  margin:0;
-}
-
-#mocha {
-  font: 20px/1.5 "Helvetica Neue", Helvetica, Arial, sans-serif;
-  margin: 60px 50px;
-}
-
-#mocha ul, #mocha li {
-  margin: 0;
-  padding: 0;
-}
-
-#mocha ul {
-  list-style: none;
-}
-
-#mocha h1, #mocha h2 {
-  margin: 0;
-}
-
-#mocha h1 {
-  margin-top: 15px;
-  font-size: 1em;
-  font-weight: 200;
-}
-
-#mocha h1 a {
-  text-decoration: none;
-  color: inherit;
-}
-
-#mocha h1 a:hover {
-  text-decoration: underline;
-}
-
-#mocha .suite .suite h1 {
-  margin-top: 0;
-  font-size: .8em;
-}
-
-#mocha .hidden {
-  display: none;
-}
-
-#mocha h2 {
-  font-size: 12px;
-  font-weight: normal;
-  cursor: pointer;
-}
-
-#mocha .suite {
-  margin-left: 15px;
-}
-
-#mocha .test {
-  margin-left: 15px;
-  overflow: hidden;
-}
-
-#mocha .test.pending:hover h2::after {
-  content: '(pending)';
-  font-family: arial, sans-serif;
-}
-
-#mocha .test.pass.medium .duration {
-  background: #C09853;
-}
-
-#mocha .test.pass.slow .duration {
-  background: #B94A48;
-}
-
-#mocha .test.pass::before {
-  content: '✓';
-  font-size: 12px;
-  display: block;
-  float: left;
-  margin-right: 5px;
-  color: #00d6b2;
-}
-
-#mocha .test.pass .duration {
-  font-size: 9px;
-  margin-left: 5px;
-  padding: 2px 5px;
-  color: white;
-  -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.2);
-  -moz-box-shadow: inset 0 1px 1px rgba(0,0,0,.2);
-  box-shadow: inset 0 1px 1px rgba(0,0,0,.2);
-  -webkit-border-radius: 5px;
-  -moz-border-radius: 5px;
-  -ms-border-radius: 5px;
-  -o-border-radius: 5px;
-  border-radius: 5px;
-}
-
-#mocha .test.pass.fast .duration {
-  display: none;
-}
-
-#mocha .test.pending {
-  color: #0b97c4;
-}
-
-#mocha .test.pending::before {
-  content: '◦';
-  color: #0b97c4;
-}
-
-#mocha .test.fail {
-  color: #c00;
-}
-
-#mocha .test.fail pre {
-  color: black;
-}
-
-#mocha .test.fail::before {
-  content: '✖';
-  font-size: 12px;
-  display: block;
-  float: left;
-  margin-right: 5px;
-  color: #c00;
-}
-
-#mocha .test pre.error {
-  color: #c00;
-  max-height: 300px;
-  overflow: auto;
-}
-
-#mocha .test pre {
-  display: block;
-  float: left;
-  clear: left;
-  font: 12px/1.5 monaco, monospace;
-  margin: 5px;
-  padding: 15px;
-  border: 1px solid #eee;
-  border-bottom-color: #ddd;
-  -webkit-border-radius: 3px;
-  -webkit-box-shadow: 0 1px 3px #eee;
-  -moz-border-radius: 3px;
-  -moz-box-shadow: 0 1px 3px #eee;
-}
-
-#mocha .test h2 {
-  position: relative;
-}
-
-#mocha .test a.replay {
-  position: absolute;
-  top: 3px;
-  right: 0;
-  text-decoration: none;
-  vertical-align: middle;
-  display: block;
-  width: 15px;
-  height: 15px;
-  line-height: 15px;
-  text-align: center;
-  background: #eee;
-  font-size: 15px;
-  -moz-border-radius: 15px;
-  border-radius: 15px;
-  -webkit-transition: opacity 200ms;
-  -moz-transition: opacity 200ms;
-  transition: opacity 200ms;
-  opacity: 0.3;
-  color: #888;
-}
-
-#mocha .test:hover a.replay {
-  opacity: 1;
-}
-
-#mocha-report.pass .test.fail {
-  display: none;
-}
-
-#mocha-report.fail .test.pass {
-  display: none;
-}
-
-#mocha-error {
-  color: #c00;
-  font-size: 1.5em;
-  font-weight: 100;
-  letter-spacing: 1px;
-}
-
-#mocha-stats {
-  position: fixed;
-  top: 15px;
-  right: 10px;
-  font-size: 12px;
-  margin: 0;
-  color: #888;
-  z-index: 1;
-}
-
-#mocha-stats .progress {
-  float: right;
-  padding-top: 0;
-}
-
-#mocha-stats em {
-  color: black;
-}
-
-#mocha-stats a {
-  text-decoration: none;
-  color: inherit;
-}
-
-#mocha-stats a:hover {
-  border-bottom: 1px solid #eee;
-}
-
-#mocha-stats li {
-  display: inline-block;
-  margin: 0 5px;
-  list-style: none;
-  padding-top: 11px;
-}
-
-#mocha-stats canvas {
-  width: 40px;
-  height: 40px;
-}
-
-#mocha code .comment { color: #ddd }
-#mocha code .init { color: #2F6FAD }
-#mocha code .string { color: #5890AD }
-#mocha code .keyword { color: #8A6343 }
-#mocha code .number { color: #2F6FAD }
-
-@media screen and (max-device-width: 480px) {
-  #mocha  {
-    margin: 60px 0px;
-  }
-
-  #mocha #stats {
-    position: absolute;
-  }
-}


[81/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/rbnf.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/rbnf.h b/src/apps/couch_collate/platform/osx/icu/unicode/rbnf.h
new file mode 100644
index 0000000..030565e
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/rbnf.h
@@ -0,0 +1,1049 @@
+/*
+*******************************************************************************
+* Copyright (C) 1997-2006, International Business Machines Corporation and others.
+* All Rights Reserved.
+*******************************************************************************
+*/
+
+#ifndef RBNF_H
+#define RBNF_H
+
+#include "unicode/utypes.h"
+
+/**
+ * \file 
+ * \brief C++ API: Rule Based Number Format
+ */
+
+/**
+ * \def U_HAVE_RBNF
+ * This will be 0 if RBNF support is not included in ICU
+ * and 1 if it is.
+ *
+ * @stable ICU 2.4
+ */
+#if UCONFIG_NO_FORMATTING
+#define U_HAVE_RBNF 0
+#else
+#define U_HAVE_RBNF 1
+
+#include "unicode/coll.h"
+#include "unicode/dcfmtsym.h"
+#include "unicode/fmtable.h"
+#include "unicode/locid.h"
+#include "unicode/numfmt.h"
+#include "unicode/unistr.h"
+#include "unicode/strenum.h"
+
+U_NAMESPACE_BEGIN
+
+class NFRuleSet;
+class LocalizationInfo;
+
+/**
+ * Tags for the predefined rulesets.
+ *
+ * @stable ICU 2.2
+ */
+enum URBNFRuleSetTag {
+    URBNF_SPELLOUT,
+    URBNF_ORDINAL,
+    URBNF_DURATION,
+    URBNF_COUNT
+};
+
+#if UCONFIG_NO_COLLATION
+class Collator;
+#endif
+
+/**
+ * The RuleBasedNumberFormat class formats numbers according to a set of rules. This number formatter is
+ * typically used for spelling out numeric values in words (e.g., 25,3476 as
+ * &quot;twenty-five thousand three hundred seventy-six&quot; or &quot;vingt-cinq mille trois
+ * cents soixante-seize&quot; or
+ * &quot;f&uuml;nfundzwanzigtausenddreihundertsechsundsiebzig&quot;), but can also be used for
+ * other complicated formatting tasks, such as formatting a number of seconds as hours,
+ * minutes and seconds (e.g., 3,730 as &quot;1:02:10&quot;).
+ *
+ * <p>The resources contain three predefined formatters for each locale: spellout, which
+ * spells out a value in words (123 is &quot;one hundred twenty-three&quot;); ordinal, which
+ * appends an ordinal suffix to the end of a numeral (123 is &quot;123rd&quot;); and
+ * duration, which shows a duration in seconds as hours, minutes, and seconds (123 is
+ * &quot;2:03&quot;).&nbsp; The client can also define more specialized <tt>RuleBasedNumberFormat</tt>s
+ * by supplying programmer-defined rule sets.</p>
+ *
+ * <p>The behavior of a <tt>RuleBasedNumberFormat</tt> is specified by a textual description
+ * that is either passed to the constructor as a <tt>String</tt> or loaded from a resource
+ * bundle. In its simplest form, the description consists of a semicolon-delimited list of <em>rules.</em>
+ * Each rule has a string of output text and a value or range of values it is applicable to.
+ * In a typical spellout rule set, the first twenty rules are the words for the numbers from
+ * 0 to 19:</p>
+ *
+ * <pre>zero; one; two; three; four; five; six; seven; eight; nine;
+ * ten; eleven; twelve; thirteen; fourteen; fifteen; sixteen; seventeen; eighteen; nineteen;</pre>
+ *
+ * <p>For larger numbers, we can use the preceding set of rules to format the ones place, and
+ * we only have to supply the words for the multiples of 10:</p>
+ *
+ * <pre> 20: twenty[-&gt;&gt;];
+ * 30: thirty[-&gt;&gt;];
+ * 40: forty[-&gt;&gt;];
+ * 50: fifty[-&gt;&gt;];
+ * 60: sixty[-&gt;&gt;];
+ * 70: seventy[-&gt;&gt;];
+ * 80: eighty[-&gt;&gt;];
+ * 90: ninety[-&gt;&gt;];</pre>
+ *
+ * <p>In these rules, the <em>base value</em> is spelled out explicitly and set off from the
+ * rule's output text with a colon. The rules are in a sorted list, and a rule is applicable
+ * to all numbers from its own base value to one less than the next rule's base value. The
+ * &quot;&gt;&gt;&quot; token is called a <em>substitution</em> and tells the fomatter to
+ * isolate the number's ones digit, format it using this same set of rules, and place the
+ * result at the position of the &quot;&gt;&gt;&quot; token. Text in brackets is omitted if
+ * the number being formatted is an even multiple of 10 (the hyphen is a literal hyphen; 24
+ * is &quot;twenty-four,&quot; not &quot;twenty four&quot;).</p>
+ *
+ * <p>For even larger numbers, we can actually look up several parts of the number in the
+ * list:</p>
+ *
+ * <pre>100: &lt;&lt; hundred[ &gt;&gt;];</pre>
+ *
+ * <p>The &quot;&lt;&lt;&quot; represents a new kind of substitution. The &lt;&lt; isolates
+ * the hundreds digit (and any digits to its left), formats it using this same rule set, and
+ * places the result where the &quot;&lt;&lt;&quot; was. Notice also that the meaning of
+ * &gt;&gt; has changed: it now refers to both the tens and the ones digits. The meaning of
+ * both substitutions depends on the rule's base value. The base value determines the rule's <em>divisor,</em>
+ * which is the highest power of 10 that is less than or equal to the base value (the user
+ * can change this). To fill in the substitutions, the formatter divides the number being
+ * formatted by the divisor. The integral quotient is used to fill in the &lt;&lt;
+ * substitution, and the remainder is used to fill in the &gt;&gt; substitution. The meaning
+ * of the brackets changes similarly: text in brackets is omitted if the value being
+ * formatted is an even multiple of the rule's divisor. The rules are applied recursively, so
+ * if a substitution is filled in with text that includes another substitution, that
+ * substitution is also filled in.</p>
+ *
+ * <p>This rule covers values up to 999, at which point we add another rule:</p>
+ *
+ * <pre>1000: &lt;&lt; thousand[ &gt;&gt;];</pre>
+ *
+ * <p>Again, the meanings of the brackets and substitution tokens shift because the rule's
+ * base value is a higher power of 10, changing the rule's divisor. This rule can actually be
+ * used all the way up to 999,999. This allows us to finish out the rules as follows:</p>
+ *
+ * <pre> 1,000,000: &lt;&lt; million[ &gt;&gt;];
+ * 1,000,000,000: &lt;&lt; billion[ &gt;&gt;];
+ * 1,000,000,000,000: &lt;&lt; trillion[ &gt;&gt;];
+ * 1,000,000,000,000,000: OUT OF RANGE!;</pre>
+ *
+ * <p>Commas, periods, and spaces can be used in the base values to improve legibility and
+ * are ignored by the rule parser. The last rule in the list is customarily treated as an
+ * &quot;overflow rule,&quot; applying to everything from its base value on up, and often (as
+ * in this example) being used to print out an error message or default representation.
+ * Notice also that the size of the major groupings in large numbers is controlled by the
+ * spacing of the rules: because in English we group numbers by thousand, the higher rules
+ * are separated from each other by a factor of 1,000.</p>
+ *
+ * <p>To see how these rules actually work in practice, consider the following example:
+ * Formatting 25,430 with this rule set would work like this:</p>
+ *
+ * <table border="0" width="100%">
+ *   <tr>
+ *     <td><strong>&lt;&lt; thousand &gt;&gt;</strong></td>
+ *     <td>[the rule whose base value is 1,000 is applicable to 25,340]</td>
+ *   </tr>
+ *   <tr>
+ *     <td><strong>twenty-&gt;&gt;</strong> thousand &gt;&gt;</td>
+ *     <td>[25,340 over 1,000 is 25. The rule for 20 applies.]</td>
+ *   </tr>
+ *   <tr>
+ *     <td>twenty-<strong>five</strong> thousand &gt;&gt;</td>
+ *     <td>[25 mod 10 is 5. The rule for 5 is &quot;five.&quot;</td>
+ *   </tr>
+ *   <tr>
+ *     <td>twenty-five thousand <strong>&lt;&lt; hundred &gt;&gt;</strong></td>
+ *     <td>[25,340 mod 1,000 is 340. The rule for 100 applies.]</td>
+ *   </tr>
+ *   <tr>
+ *     <td>twenty-five thousand <strong>three</strong> hundred &gt;&gt;</td>
+ *     <td>[340 over 100 is 3. The rule for 3 is &quot;three.&quot;]</td>
+ *   </tr>
+ *   <tr>
+ *     <td>twenty-five thousand three hundred <strong>forty</strong></td>
+ *     <td>[340 mod 100 is 40. The rule for 40 applies. Since 40 divides
+ *     evenly by 10, the hyphen and substitution in the brackets are omitted.]</td>
+ *   </tr>
+ * </table>
+ *
+ * <p>The above syntax suffices only to format positive integers. To format negative numbers,
+ * we add a special rule:</p>
+ *
+ * <pre>-x: minus &gt;&gt;;</pre>
+ *
+ * <p>This is called a <em>negative-number rule,</em> and is identified by &quot;-x&quot;
+ * where the base value would be. This rule is used to format all negative numbers. the
+ * &gt;&gt; token here means &quot;find the number's absolute value, format it with these
+ * rules, and put the result here.&quot;</p>
+ *
+ * <p>We also add a special rule called a <em>fraction rule </em>for numbers with fractional
+ * parts:</p>
+ *
+ * <pre>x.x: &lt;&lt; point &gt;&gt;;</pre>
+ *
+ * <p>This rule is used for all positive non-integers (negative non-integers pass through the
+ * negative-number rule first and then through this rule). Here, the &lt;&lt; token refers to
+ * the number's integral part, and the &gt;&gt; to the number's fractional part. The
+ * fractional part is formatted as a series of single-digit numbers (e.g., 123.456 would be
+ * formatted as &quot;one hundred twenty-three point four five six&quot;).</p>
+ *
+ * <p>To see how this rule syntax is applied to various languages, examine the resource data.</p>
+ *
+ * <p>There is actually much more flexibility built into the rule language than the
+ * description above shows. A formatter may own multiple rule sets, which can be selected by
+ * the caller, and which can use each other to fill in their substitutions. Substitutions can
+ * also be filled in with digits, using a DecimalFormat object. There is syntax that can be
+ * used to alter a rule's divisor in various ways. And there is provision for much more
+ * flexible fraction handling. A complete description of the rule syntax follows:</p>
+ *
+ * <hr>
+ *
+ * <p>The description of a <tt>RuleBasedNumberFormat</tt>'s behavior consists of one or more <em>rule
+ * sets.</em> Each rule set consists of a name, a colon, and a list of <em>rules.</em> A rule
+ * set name must begin with a % sign. Rule sets with names that begin with a single % sign
+ * are <em>public:</em> the caller can specify that they be used to format and parse numbers.
+ * Rule sets with names that begin with %% are <em>private:</em> they exist only for the use
+ * of other rule sets. If a formatter only has one rule set, the name may be omitted.</p>
+ *
+ * <p>The user can also specify a special &quot;rule set&quot; named <tt>%%lenient-parse</tt>.
+ * The body of <tt>%%lenient-parse</tt> isn't a set of number-formatting rules, but a <tt>RuleBasedCollator</tt>
+ * description which is used to define equivalences for lenient parsing. For more information
+ * on the syntax, see <tt>RuleBasedCollator</tt>. For more information on lenient parsing,
+ * see <tt>setLenientParse()</tt>.  <em>Note:</em> symbols that have syntactic meaning
+ * in collation rules, such as '&amp;', have no particular meaning when appearing outside
+ * of the <tt>lenient-parse</tt> rule set.</p>
+ *
+ * <p>The body of a rule set consists of an ordered, semicolon-delimited list of <em>rules.</em>
+ * Internally, every rule has a base value, a divisor, rule text, and zero, one, or two <em>substitutions.</em>
+ * These parameters are controlled by the description syntax, which consists of a <em>rule
+ * descriptor,</em> a colon, and a <em>rule body.</em></p>
+ *
+ * <p>A rule descriptor can take one of the following forms (text in <em>italics</em> is the
+ * name of a token):</p>
+ *
+ * <table border="0" width="100%">
+ *   <tr>
+ *     <td><em>bv</em>:</td>
+ *     <td><em>bv</em> specifies the rule's base value. <em>bv</em> is a decimal
+ *     number expressed using ASCII digits. <em>bv</em> may contain spaces, period, and commas,
+ *     which are ignored. The rule's divisor is the highest power of 10 less than or equal to
+ *     the base value.</td>
+ *   </tr>
+ *   <tr>
+ *     <td><em>bv</em>/<em>rad</em>:</td>
+ *     <td><em>bv</em> specifies the rule's base value. The rule's divisor is the
+ *     highest power of <em>rad</em> less than or equal to the base value.</td>
+ *   </tr>
+ *   <tr>
+ *     <td><em>bv</em>&gt;:</td>
+ *     <td><em>bv</em> specifies the rule's base value. To calculate the divisor,
+ *     let the radix be 10, and the exponent be the highest exponent of the radix that yields a
+ *     result less than or equal to the base value. Every &gt; character after the base value
+ *     decreases the exponent by 1. If the exponent is positive or 0, the divisor is the radix
+ *     raised to the power of the exponent; otherwise, the divisor is 1.</td>
+ *   </tr>
+ *   <tr>
+ *     <td><em>bv</em>/<em>rad</em>&gt;:</td>
+ *     <td><em>bv</em> specifies the rule's base value. To calculate the divisor,
+ *     let the radix be <em>rad</em>, and the exponent be the highest exponent of the radix that
+ *     yields a result less than or equal to the base value. Every &gt; character after the radix
+ *     decreases the exponent by 1. If the exponent is positive or 0, the divisor is the radix
+ *     raised to the power of the exponent; otherwise, the divisor is 1.</td>
+ *   </tr>
+ *   <tr>
+ *     <td>-x:</td>
+ *     <td>The rule is a negative-number rule.</td>
+ *   </tr>
+ *   <tr>
+ *     <td>x.x:</td>
+ *     <td>The rule is an <em>improper fraction rule.</em></td>
+ *   </tr>
+ *   <tr>
+ *     <td>0.x:</td>
+ *     <td>The rule is a <em>proper fraction rule.</em></td>
+ *   </tr>
+ *   <tr>
+ *     <td>x.0:</td>
+ *     <td>The rule is a <em>master rule.</em></td>
+ *   </tr>
+ *   <tr>
+ *     <td><em>nothing</em></td>
+ *     <td>If the rule's rule descriptor is left out, the base value is one plus the
+ *     preceding rule's base value (or zero if this is the first rule in the list) in a normal
+ *     rule set.&nbsp; In a fraction rule set, the base value is the same as the preceding rule's
+ *     base value.</td>
+ *   </tr>
+ * </table>
+ *
+ * <p>A rule set may be either a regular rule set or a <em>fraction rule set,</em> depending
+ * on whether it is used to format a number's integral part (or the whole number) or a
+ * number's fractional part. Using a rule set to format a rule's fractional part makes it a
+ * fraction rule set.</p>
+ *
+ * <p>Which rule is used to format a number is defined according to one of the following
+ * algorithms: If the rule set is a regular rule set, do the following:
+ *
+ * <ul>
+ *   <li>If the rule set includes a master rule (and the number was passed in as a <tt>double</tt>),
+ *     use the master rule.&nbsp; (If the number being formatted was passed in as a <tt>long</tt>,
+ *     the master rule is ignored.)</li>
+ *   <li>If the number is negative, use the negative-number rule.</li>
+ *   <li>If the number has a fractional part and is greater than 1, use the improper fraction
+ *     rule.</li>
+ *   <li>If the number has a fractional part and is between 0 and 1, use the proper fraction
+ *     rule.</li>
+ *   <li>Binary-search the rule list for the rule with the highest base value less than or equal
+ *     to the number. If that rule has two substitutions, its base value is not an even multiple
+ *     of its divisor, and the number <em>is</em> an even multiple of the rule's divisor, use the
+ *     rule that precedes it in the rule list. Otherwise, use the rule itself.</li>
+ * </ul>
+ *
+ * <p>If the rule set is a fraction rule set, do the following:
+ *
+ * <ul>
+ *   <li>Ignore negative-number and fraction rules.</li>
+ *   <li>For each rule in the list, multiply the number being formatted (which will always be
+ *     between 0 and 1) by the rule's base value. Keep track of the distance between the result
+ *     the nearest integer.</li>
+ *   <li>Use the rule that produced the result closest to zero in the above calculation. In the
+ *     event of a tie or a direct hit, use the first matching rule encountered. (The idea here is
+ *     to try each rule's base value as a possible denominator of a fraction. Whichever
+ *     denominator produces the fraction closest in value to the number being formatted wins.) If
+ *     the rule following the matching rule has the same base value, use it if the numerator of
+ *     the fraction is anything other than 1; if the numerator is 1, use the original matching
+ *     rule. (This is to allow singular and plural forms of the rule text without a lot of extra
+ *     hassle.)</li>
+ * </ul>
+ *
+ * <p>A rule's body consists of a string of characters terminated by a semicolon. The rule
+ * may include zero, one, or two <em>substitution tokens,</em> and a range of text in
+ * brackets. The brackets denote optional text (and may also include one or both
+ * substitutions). The exact meanings of the substitution tokens, and under what conditions
+ * optional text is omitted, depend on the syntax of the substitution token and the context.
+ * The rest of the text in a rule body is literal text that is output when the rule matches
+ * the number being formatted.</p>
+ *
+ * <p>A substitution token begins and ends with a <em>token character.</em> The token
+ * character and the context together specify a mathematical operation to be performed on the
+ * number being formatted. An optional <em>substitution descriptor </em>specifies how the
+ * value resulting from that operation is used to fill in the substitution. The position of
+ * the substitution token in the rule body specifies the location of the resultant text in
+ * the original rule text.</p>
+ *
+ * <p>The meanings of the substitution token characters are as follows:</p>
+ *
+ * <table border="0" width="100%">
+ *   <tr>
+ *     <td>&gt;&gt;</td>
+ *     <td>in normal rule</td>
+ *     <td>Divide the number by the rule's divisor and format the remainder</td>
+ *   </tr>
+ *   <tr>
+ *     <td></td>
+ *     <td>in negative-number rule</td>
+ *     <td>Find the absolute value of the number and format the result</td>
+ *   </tr>
+ *   <tr>
+ *     <td></td>
+ *     <td>in fraction or master rule</td>
+ *     <td>Isolate the number's fractional part and format it.</td>
+ *   </tr>
+ *   <tr>
+ *     <td></td>
+ *     <td>in rule in fraction rule set</td>
+ *     <td>Not allowed.</td>
+ *   </tr>
+ *   <tr>
+ *     <td>&gt;&gt;&gt;</td>
+ *     <td>in normal rule</td>
+ *     <td>Divide the number by the rule's divisor and format the remainder,
+ *       but bypass the normal rule-selection process and just use the
+ *       rule that precedes this one in this rule list.</td>
+ *   </tr>
+ *   <tr>
+ *     <td></td>
+ *     <td>in all other rules</td>
+ *     <td>Not allowed.</td>
+ *   </tr>
+ *   <tr>
+ *     <td>&lt;&lt;</td>
+ *     <td>in normal rule</td>
+ *     <td>Divide the number by the rule's divisor and format the quotient</td>
+ *   </tr>
+ *   <tr>
+ *     <td></td>
+ *     <td>in negative-number rule</td>
+ *     <td>Not allowed.</td>
+ *   </tr>
+ *   <tr>
+ *     <td></td>
+ *     <td>in fraction or master rule</td>
+ *     <td>Isolate the number's integral part and format it.</td>
+ *   </tr>
+ *   <tr>
+ *     <td></td>
+ *     <td>in rule in fraction rule set</td>
+ *     <td>Multiply the number by the rule's base value and format the result.</td>
+ *   </tr>
+ *   <tr>
+ *     <td>==</td>
+ *     <td>in all rule sets</td>
+ *     <td>Format the number unchanged</td>
+ *   </tr>
+ *   <tr>
+ *     <td>[]</td>
+ *     <td>in normal rule</td>
+ *     <td>Omit the optional text if the number is an even multiple of the rule's divisor</td>
+ *   </tr>
+ *   <tr>
+ *     <td></td>
+ *     <td>in negative-number rule</td>
+ *     <td>Not allowed.</td>
+ *   </tr>
+ *   <tr>
+ *     <td></td>
+ *     <td>in improper-fraction rule</td>
+ *     <td>Omit the optional text if the number is between 0 and 1 (same as specifying both an
+ *     x.x rule and a 0.x rule)</td>
+ *   </tr>
+ *   <tr>
+ *     <td></td>
+ *     <td>in master rule</td>
+ *     <td>Omit the optional text if the number is an integer (same as specifying both an x.x
+ *     rule and an x.0 rule)</td>
+ *   </tr>
+ *   <tr>
+ *     <td></td>
+ *     <td>in proper-fraction rule</td>
+ *     <td>Not allowed.</td>
+ *   </tr>
+ *   <tr>
+ *     <td></td>
+ *     <td>in rule in fraction rule set</td>
+ *     <td>Omit the optional text if multiplying the number by the rule's base value yields 1.</td>
+ *   </tr>
+ * </table>
+ *
+ * <p>The substitution descriptor (i.e., the text between the token characters) may take one
+ * of three forms:</p>
+ *
+ * <table border="0" width="100%">
+ *   <tr>
+ *     <td>a rule set name</td>
+ *     <td>Perform the mathematical operation on the number, and format the result using the
+ *     named rule set.</td>
+ *   </tr>
+ *   <tr>
+ *     <td>a DecimalFormat pattern</td>
+ *     <td>Perform the mathematical operation on the number, and format the result using a
+ *     DecimalFormat with the specified pattern.&nbsp; The pattern must begin with 0 or #.</td>
+ *   </tr>
+ *   <tr>
+ *     <td>nothing</td>
+ *     <td>Perform the mathematical operation on the number, and format the result using the rule
+ *     set containing the current rule, except:
+ *     <ul>
+ *       <li>You can't have an empty substitution descriptor with a == substitution.</li>
+ *       <li>If you omit the substitution descriptor in a &gt;&gt; substitution in a fraction rule,
+ *         format the result one digit at a time using the rule set containing the current rule.</li>
+ *       <li>If you omit the substitution descriptor in a &lt;&lt; substitution in a rule in a
+ *         fraction rule set, format the result using the default rule set for this formatter.</li>
+ *     </ul>
+ *     </td>
+ *   </tr>
+ * </table>
+ *
+ * <p>Whitespace is ignored between a rule set name and a rule set body, between a rule
+ * descriptor and a rule body, or between rules. If a rule body begins with an apostrophe,
+ * the apostrophe is ignored, but all text after it becomes significant (this is how you can
+ * have a rule's rule text begin with whitespace). There is no escape function: the semicolon
+ * is not allowed in rule set names or in rule text, and the colon is not allowed in rule set
+ * names. The characters beginning a substitution token are always treated as the beginning
+ * of a substitution token.</p>
+ *
+ * <p>See the resource data and the demo program for annotated examples of real rule sets
+ * using these features.</p>
+ *
+ * <p><em>User subclasses are not supported.</em> While clients may write
+ * subclasses, such code will not necessarily work and will not be
+ * guaranteed to work stably from release to release.
+ *
+ * <p><b>Localizations</b></p>
+ * <p>Constructors are available that allow the specification of localizations for the
+ * public rule sets (and also allow more control over what public rule sets are available).
+ * Localization data is represented as a textual description.  The description represents
+ * an array of arrays of string.  The first element is an array of the public rule set names,
+ * each of these must be one of the public rule set names that appear in the rules.  Only
+ * names in this array will be treated as public rule set names by the API.  Each subsequent
+ * element is an array of localizations of these names.  The first element of one of these
+ * subarrays is the locale name, and the remaining elements are localizations of the
+ * public rule set names, in the same order as they were listed in the first arrray.</p>
+ * <p>In the syntax, angle brackets '<', '>' are used to delimit the arrays, and comma ',' is used
+ * to separate elements of an array.  Whitespace is ignored, unless quoted.</p>
+ * <p>For example:<pre>
+ * < < %foo, %bar, %baz >, 
+ *   < en, Foo, Bar, Baz >, 
+ *   < fr, 'le Foo', 'le Bar', 'le Baz' > 
+ *   < zh, \\u7532, \\u4e59, \\u4e19 > >
+ * </pre></p>
+ * @author Richard Gillam
+ * @see NumberFormat
+ * @see DecimalFormat
+ * @stable ICU 2.0
+ */
+class U_I18N_API RuleBasedNumberFormat : public NumberFormat {
+public:
+
+  //-----------------------------------------------------------------------
+  // constructors
+  //-----------------------------------------------------------------------
+
+    /**
+     * Creates a RuleBasedNumberFormat that behaves according to the description
+     * passed in.  The formatter uses the default locale.
+     * @param rules A description of the formatter's desired behavior.
+     * See the class documentation for a complete explanation of the description
+     * syntax.
+     * @param perror The parse error if an error was encountered.
+     * @param status The status indicating whether the constructor succeeded.
+     * @stable ICU 3.2
+     */
+    RuleBasedNumberFormat(const UnicodeString& rules, UParseError& perror, UErrorCode& status);
+
+    /**
+     * Creates a RuleBasedNumberFormat that behaves according to the description
+     * passed in.  The formatter uses the default locale.  
+     * <p>
+     * The localizations data provides information about the public
+     * rule sets and their localized display names for different
+     * locales. The first element in the list is an array of the names
+     * of the public rule sets.  The first element in this array is
+     * the initial default ruleset.  The remaining elements in the
+     * list are arrays of localizations of the names of the public
+     * rule sets.  Each of these is one longer than the initial array,
+     * with the first String being the ULocale ID, and the remaining
+     * Strings being the localizations of the rule set names, in the
+     * same order as the initial array.  Arrays are NULL-terminated.
+     * @param rules A description of the formatter's desired behavior.
+     * See the class documentation for a complete explanation of the description
+     * syntax.
+     * @param localizations the localization information.
+     * names in the description.  These will be copied by the constructor.
+     * @param perror The parse error if an error was encountered.
+     * @param status The status indicating whether the constructor succeeded.
+     * @stable ICU 3.2
+     */
+    RuleBasedNumberFormat(const UnicodeString& rules, const UnicodeString& localizations,
+                        UParseError& perror, UErrorCode& status);
+
+  /**
+   * Creates a RuleBasedNumberFormat that behaves according to the rules
+   * passed in.  The formatter uses the specified locale to determine the
+   * characters to use when formatting numerals, and to define equivalences
+   * for lenient parsing.
+   * @param rules The formatter rules.
+   * See the class documentation for a complete explanation of the rule
+   * syntax.
+   * @param locale A locale that governs which characters are used for
+   * formatting values in numerals and which characters are equivalent in
+   * lenient parsing.
+   * @param perror The parse error if an error was encountered.
+   * @param status The status indicating whether the constructor succeeded.
+   * @stable ICU 2.0
+   */
+  RuleBasedNumberFormat(const UnicodeString& rules, const Locale& locale,
+                        UParseError& perror, UErrorCode& status);
+
+    /**
+     * Creates a RuleBasedNumberFormat that behaves according to the description
+     * passed in.  The formatter uses the default locale.  
+     * <p>
+     * The localizations data provides information about the public
+     * rule sets and their localized display names for different
+     * locales. The first element in the list is an array of the names
+     * of the public rule sets.  The first element in this array is
+     * the initial default ruleset.  The remaining elements in the
+     * list are arrays of localizations of the names of the public
+     * rule sets.  Each of these is one longer than the initial array,
+     * with the first String being the ULocale ID, and the remaining
+     * Strings being the localizations of the rule set names, in the
+     * same order as the initial array.  Arrays are NULL-terminated.
+     * @param rules A description of the formatter's desired behavior.
+     * See the class documentation for a complete explanation of the description
+     * syntax.
+     * @param localizations a list of localizations for the rule set
+     * names in the description.  These will be copied by the constructor.
+     * @param locale A locale that governs which characters are used for
+     * formatting values in numerals and which characters are equivalent in
+     * lenient parsing.
+     * @param perror The parse error if an error was encountered.
+     * @param status The status indicating whether the constructor succeeded.
+     * @stable ICU 3.2
+     */
+    RuleBasedNumberFormat(const UnicodeString& rules, const UnicodeString& localizations,
+                        const Locale& locale, UParseError& perror, UErrorCode& status);
+
+  /**
+   * Creates a RuleBasedNumberFormat from a predefined ruleset.  The selector
+   * code choosed among three possible predefined formats: spellout, ordinal,
+   * and duration.
+   * @param tag A selector code specifying which kind of formatter to create for that
+   * locale.  There are three legal values: URBNF_SPELLOUT, which creates a formatter that
+   * spells out a value in words in the desired language, URBNF_ORDINAL, which attaches
+   * an ordinal suffix from the desired language to the end of a number (e.g. "123rd"),
+   * and URBNF_DURATION, which formats a duration in seconds as hours, minutes, and seconds.
+   * @param locale The locale for the formatter.
+   * @param status The status indicating whether the constructor succeeded.
+   * @stable ICU 2.0
+   */
+  RuleBasedNumberFormat(URBNFRuleSetTag tag, const Locale& locale, UErrorCode& status);
+
+  //-----------------------------------------------------------------------
+  // boilerplate
+  //-----------------------------------------------------------------------
+
+  /**
+   * Copy constructor
+   * @param rhs    the object to be copied from.
+   * @stable ICU 2.6
+   */
+  RuleBasedNumberFormat(const RuleBasedNumberFormat& rhs);
+
+  /**
+   * Assignment operator
+   * @param rhs    the object to be copied from.
+   * @stable ICU 2.6
+   */
+  RuleBasedNumberFormat& operator=(const RuleBasedNumberFormat& rhs);
+
+  /**
+   * Release memory allocated for a RuleBasedNumberFormat when you are finished with it.
+   * @stable ICU 2.6
+   */
+  virtual ~RuleBasedNumberFormat();
+
+  /**
+   * Clone this object polymorphically.  The caller is responsible
+   * for deleting the result when done.
+   * @return  A copy of the object.
+   * @stable ICU 2.6
+   */
+  virtual Format* clone(void) const;
+
+  /**
+   * Return true if the given Format objects are semantically equal.
+   * Objects of different subclasses are considered unequal.
+   * @param other    the object to be compared with.
+   * @return        true if the given Format objects are semantically equal.
+   * @stable ICU 2.6
+   */
+  virtual UBool operator==(const Format& other) const;
+
+//-----------------------------------------------------------------------
+// public API functions
+//-----------------------------------------------------------------------
+
+  /**
+   * return the rules that were provided to the RuleBasedNumberFormat.
+   * @return the result String that was passed in
+   * @stable ICU 2.0
+   */
+  virtual UnicodeString getRules() const;
+
+  /**
+   * Return the number of public rule set names.
+   * @return the number of public rule set names.
+   * @stable ICU 2.0
+   */
+  virtual int32_t getNumberOfRuleSetNames() const;
+
+  /**
+   * Return the name of the index'th public ruleSet.  If index is not valid,
+   * the function returns null.
+   * @param index the index of the ruleset
+   * @return the name of the index'th public ruleSet.
+   * @stable ICU 2.0
+   */
+  virtual UnicodeString getRuleSetName(int32_t index) const;
+
+  /**
+   * Return the number of locales for which we have localized rule set display names.
+   * @return the number of locales for which we have localized rule set display names.
+   * @stable ICU 3.2
+   */
+  virtual int32_t getNumberOfRuleSetDisplayNameLocales(void) const;
+
+  /**
+   * Return the index'th display name locale.
+   * @param index the index of the locale
+   * @param status set to a failure code when this function fails
+   * @return the locale
+   * @see #getNumberOfRuleSetDisplayNameLocales
+   * @stable ICU 3.2
+   */
+  virtual Locale getRuleSetDisplayNameLocale(int32_t index, UErrorCode& status) const;
+
+    /**
+     * Return the rule set display names for the provided locale.  These are in the same order
+     * as those returned by getRuleSetName.  The locale is matched against the locales for
+     * which there is display name data, using normal fallback rules.  If no locale matches, 
+     * the default display names are returned.  (These are the internal rule set names minus
+     * the leading '%'.)
+     * @param index the index of the rule set
+     * @param locale the locale (returned by getRuleSetDisplayNameLocales) for which the localized
+     * display name is desired
+     * @return the display name for the given index, which might be bogus if there is an error
+     * @see #getRuleSetName
+     * @stable ICU 3.2
+     */
+  virtual UnicodeString getRuleSetDisplayName(int32_t index, 
+                          const Locale& locale = Locale::getDefault());
+
+    /**
+     * Return the rule set display name for the provided rule set and locale.  
+     * The locale is matched against the locales for which there is display name data, using
+     * normal fallback rules.  If no locale matches, the default display name is returned.
+     * @return the display name for the rule set
+     * @stable ICU 3.2
+     * @see #getRuleSetDisplayName
+     */
+  virtual UnicodeString getRuleSetDisplayName(const UnicodeString& ruleSetName, 
+                          const Locale& locale = Locale::getDefault());
+
+  /**
+   * Formats the specified 32-bit number using the default ruleset.
+   * @param number The number to format.
+   * @param toAppendTo the string that will hold the (appended) result
+   * @param pos the fieldposition
+   * @return A textual representation of the number.
+   * @stable ICU 2.0
+   */
+  virtual UnicodeString& format(int32_t number,
+                                UnicodeString& toAppendTo,
+                                FieldPosition& pos) const;
+
+  /**
+   * Formats the specified 64-bit number using the default ruleset.
+   * @param number The number to format.
+   * @param toAppendTo the string that will hold the (appended) result
+   * @param pos the fieldposition
+   * @return A textual representation of the number.
+   * @stable ICU 2.1
+   */
+  virtual UnicodeString& format(int64_t number,
+                                UnicodeString& toAppendTo,
+                                FieldPosition& pos) const;
+  /**
+   * Formats the specified number using the default ruleset.
+   * @param number The number to format.
+   * @param toAppendTo the string that will hold the (appended) result
+   * @param pos the fieldposition
+   * @return A textual representation of the number.
+   * @stable ICU 2.0
+   */
+  virtual UnicodeString& format(double number,
+                                UnicodeString& toAppendTo,
+                                FieldPosition& pos) const;
+
+  /**
+   * Formats the specified number using the named ruleset.
+   * @param number The number to format.
+   * @param ruleSetName The name of the rule set to format the number with.
+   * This must be the name of a valid public rule set for this formatter.
+   * @param toAppendTo the string that will hold the (appended) result
+   * @param pos the fieldposition
+   * @param status the status
+   * @return A textual representation of the number.
+   * @stable ICU 2.0
+   */
+  virtual UnicodeString& format(int32_t number,
+                                const UnicodeString& ruleSetName,
+                                UnicodeString& toAppendTo,
+                                FieldPosition& pos,
+                                UErrorCode& status) const;
+  /**
+   * Formats the specified 64-bit number using the named ruleset.
+   * @param number The number to format.
+   * @param ruleSetName The name of the rule set to format the number with.
+   * This must be the name of a valid public rule set for this formatter.
+   * @param toAppendTo the string that will hold the (appended) result
+   * @param pos the fieldposition
+   * @param status the status
+   * @return A textual representation of the number.
+   * @stable ICU 2.1
+   */
+  virtual UnicodeString& format(int64_t number,
+                                const UnicodeString& ruleSetName,
+                                UnicodeString& toAppendTo,
+                                FieldPosition& pos,
+                                UErrorCode& status) const;
+  /**
+   * Formats the specified number using the named ruleset.
+   * @param number The number to format.
+   * @param ruleSetName The name of the rule set to format the number with.
+   * This must be the name of a valid public rule set for this formatter.
+   * @param toAppendTo the string that will hold the (appended) result
+   * @param pos the fieldposition
+   * @param status the status
+   * @return A textual representation of the number.
+   * @stable ICU 2.0
+   */
+  virtual UnicodeString& format(double number,
+                                const UnicodeString& ruleSetName,
+                                UnicodeString& toAppendTo,
+                                FieldPosition& pos,
+                                UErrorCode& status) const;
+
+  /**
+   * Formats the specified number using the default ruleset.
+   * @param obj The number to format.
+   * @param toAppendTo the string that will hold the (appended) result
+   * @param pos the fieldposition
+   * @param status the status
+   * @return A textual representation of the number.
+   * @stable ICU 2.0
+   */
+  virtual UnicodeString& format(const Formattable& obj,
+                                UnicodeString& toAppendTo,
+                                FieldPosition& pos,
+                                UErrorCode& status) const;
+  /**
+   * Redeclared Format method.
+   * @param obj    the object to be formatted.
+   * @param result Output param which will receive the formatted string.
+   * @param status Output param set to success/failure code
+   * @return       A reference to 'result'.
+   * @stable ICU 2.0
+   */
+  UnicodeString& format(const Formattable& obj,
+                        UnicodeString& result,
+                        UErrorCode& status) const;
+
+  /**
+   * Redeclared NumberFormat method.
+   * @param number    the double value to be formatted.
+   * @param output    Output param which will receive the formatted string.
+   * @return          A reference to 'output'.
+   * @stable ICU 2.0
+   */
+   UnicodeString& format(double number,
+                         UnicodeString& output) const;
+
+  /**
+   * Redeclared NumberFormat method.
+   * @param number    the long value to be formatted.
+   * @param output    Output param which will receive the formatted string.
+   * @return          A reference to 'output'.
+   * @stable ICU 2.0
+   */
+   UnicodeString& format(int32_t number,
+                         UnicodeString& output) const;
+
+  /**
+   * Parses the specfied string, beginning at the specified position, according
+   * to this formatter's rules.  This will match the string against all of the
+   * formatter's public rule sets and return the value corresponding to the longest
+   * parseable substring.  This function's behavior is affected by the lenient
+   * parse mode.
+   * @param text The string to parse
+   * @param result the result of the parse, either a double or a long.
+   * @param parsePosition On entry, contains the position of the first character
+   * in "text" to examine.  On exit, has been updated to contain the position
+   * of the first character in "text" that wasn't consumed by the parse.
+   * @see #setLenient
+   * @stable ICU 2.0
+   */
+  virtual void parse(const UnicodeString& text,
+                     Formattable& result,
+                     ParsePosition& parsePosition) const;
+
+
+  /**
+   * Redeclared Format method.
+   * @param text   The string to parse
+   * @param result the result of the parse, either a double or a long.
+   * @param status Output param set to failure code when a problem occurs.
+   * @stable ICU 2.0
+   */
+  virtual inline void parse(const UnicodeString& text,
+                      Formattable& result,
+                      UErrorCode& status) const;
+
+#if !UCONFIG_NO_COLLATION
+
+  /**
+   * Turns lenient parse mode on and off.
+   *
+   * When in lenient parse mode, the formatter uses a Collator for parsing the text.
+   * Only primary differences are treated as significant.  This means that case
+   * differences, accent differences, alternate spellings of the same letter
+   * (e.g., ae and a-umlaut in German), ignorable characters, etc. are ignored in
+   * matching the text.  In many cases, numerals will be accepted in place of words
+   * or phrases as well.
+   *
+   * For example, all of the following will correctly parse as 255 in English in
+   * lenient-parse mode:
+   * <br>"two hundred fifty-five"
+   * <br>"two hundred fifty five"
+   * <br>"TWO HUNDRED FIFTY-FIVE"
+   * <br>"twohundredfiftyfive"
+   * <br>"2 hundred fifty-5"
+   *
+   * The Collator used is determined by the locale that was
+   * passed to this object on construction.  The description passed to this object
+   * on construction may supply additional collation rules that are appended to the
+   * end of the default collator for the locale, enabling additional equivalences
+   * (such as adding more ignorable characters or permitting spelled-out version of
+   * symbols; see the demo program for examples).
+   *
+   * It's important to emphasize that even strict parsing is relatively lenient: it
+   * will accept some text that it won't produce as output.  In English, for example,
+   * it will correctly parse "two hundred zero" and "fifteen hundred".
+   *
+   * @param enabled If true, turns lenient-parse mode on; if false, turns it off.
+   * @see RuleBasedCollator
+   * @stable ICU 2.0
+   */
+  virtual void setLenient(UBool enabled);
+
+  /**
+   * Returns true if lenient-parse mode is turned on.  Lenient parsing is off
+   * by default.
+   * @return true if lenient-parse mode is turned on.
+   * @see #setLenient
+   * @stable ICU 2.0
+   */
+  virtual inline UBool isLenient(void) const;
+
+#endif
+
+  /**
+   * Override the default rule set to use.  If ruleSetName is null, reset
+   * to the initial default rule set.  If the rule set is not a public rule set name,
+   * U_ILLEGAL_ARGUMENT_ERROR is returned in status.
+   * @param ruleSetName the name of the rule set, or null to reset the initial default.
+   * @param status set to failure code when a problem occurs.
+   * @stable ICU 2.6
+   */
+  virtual void setDefaultRuleSet(const UnicodeString& ruleSetName, UErrorCode& status);
+
+  /**
+   * Return the name of the current default rule set.  If the current rule set is
+   * not public, returns a bogus (and empty) UnicodeString.
+   * @return the name of the current default rule set
+   * @stable ICU 3.0
+   */
+  virtual UnicodeString getDefaultRuleSetName() const;
+
+public:
+    /**
+     * ICU "poor man's RTTI", returns a UClassID for this class.
+     *
+     * @stable ICU 2.8
+     */
+    static UClassID U_EXPORT2 getStaticClassID(void);
+
+    /**
+     * ICU "poor man's RTTI", returns a UClassID for the actual class.
+     *
+     * @stable ICU 2.8
+     */
+    virtual UClassID getDynamicClassID(void) const;
+
+private:
+    RuleBasedNumberFormat(); // default constructor not implemented
+
+    // this will ref the localizations if they are not NULL
+    // caller must deref to get adoption 
+    RuleBasedNumberFormat(const UnicodeString& description, LocalizationInfo* localizations, 
+              const Locale& locale, UParseError& perror, UErrorCode& status);
+
+    void init(const UnicodeString& rules, LocalizationInfo* localizations, UParseError& perror, UErrorCode& status);
+    void dispose();
+    void stripWhitespace(UnicodeString& src);
+    void initDefaultRuleSet();
+    void format(double number, NFRuleSet& ruleSet);
+    NFRuleSet* findRuleSet(const UnicodeString& name, UErrorCode& status) const;
+
+    /* friend access */
+    friend class NFSubstitution;
+    friend class NFRule;
+    friend class FractionalPartSubstitution;
+
+    inline NFRuleSet * getDefaultRuleSet() const;
+    Collator * getCollator() const;
+    DecimalFormatSymbols * getDecimalFormatSymbols() const;
+
+private:
+    NFRuleSet **ruleSets;
+    NFRuleSet *defaultRuleSet;
+    Locale locale;
+    Collator* collator;
+    DecimalFormatSymbols* decimalFormatSymbols;
+    UBool lenient;
+    UnicodeString* lenientParseRules;
+    LocalizationInfo* localizations;
+};
+
+// ---------------
+
+inline UnicodeString&
+RuleBasedNumberFormat::format(const Formattable& obj,
+                              UnicodeString& result,
+                              UErrorCode& status) const
+{
+    // Don't use Format:: - use immediate base class only,
+    // in case immediate base modifies behavior later.
+    // dlf - the above comment is bogus, if there were a reason to modify
+    // it, it would be virtual, and there's no reason because it is
+    // a one-line macro in NumberFormat anyway, just like this one.
+    return NumberFormat::format(obj, result, status);
+}
+
+inline UnicodeString&
+RuleBasedNumberFormat::format(double number, UnicodeString& output) const {
+    FieldPosition pos(0);
+    return format(number, output, pos);
+}
+
+inline UnicodeString&
+RuleBasedNumberFormat::format(int32_t number, UnicodeString& output) const {
+    FieldPosition pos(0);
+    return format(number, output, pos);
+}
+
+inline void
+RuleBasedNumberFormat::parse(const UnicodeString& text, Formattable& result, UErrorCode& status) const
+{
+    NumberFormat::parse(text, result, status);
+}
+
+#if !UCONFIG_NO_COLLATION
+
+inline UBool
+RuleBasedNumberFormat::isLenient(void) const {
+    return lenient;
+}
+
+#endif
+
+inline NFRuleSet*
+RuleBasedNumberFormat::getDefaultRuleSet() const {
+    return defaultRuleSet;
+}
+
+U_NAMESPACE_END
+
+/* U_HAVE_RBNF */
+#endif
+
+/* RBNF_H */
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/rbtz.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/rbtz.h b/src/apps/couch_collate/platform/osx/icu/unicode/rbtz.h
new file mode 100644
index 0000000..78215f3
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/rbtz.h
@@ -0,0 +1,361 @@
+/*
+*******************************************************************************
+* Copyright (C) 2007-2008, International Business Machines Corporation and    *
+* others. All Rights Reserved.                                                *
+*******************************************************************************
+*/
+#ifndef RBTZ_H
+#define RBTZ_H
+
+#include "unicode/utypes.h"
+
+/**
+ * \file 
+ * \brief C++ API: Rule based customizable time zone
+ */
+
+#if !UCONFIG_NO_FORMATTING
+
+#include "unicode/basictz.h"
+#include "unicode/unistr.h"
+
+U_NAMESPACE_BEGIN
+
+// forward declaration
+class UVector;
+struct Transition;
+
+/**
+ * a BasicTimeZone subclass implemented in terms of InitialTimeZoneRule and TimeZoneRule instances
+ * @see BasicTimeZone
+ * @see InitialTimeZoneRule
+ * @see TimeZoneRule
+ */
+class U_I18N_API RuleBasedTimeZone : public BasicTimeZone {
+public:
+    /**
+     * Constructs a <code>RuleBasedTimeZone</code> object with the ID and the
+     * <code>InitialTimeZoneRule</code>.  The input <code>InitialTimeZoneRule</code>
+     * is adopted by this <code>RuleBasedTimeZone</code>, thus the caller must not
+     * delete it.
+     * @param id                The time zone ID.
+     * @param initialRule       The initial time zone rule.
+     * @stable ICU 4.0
+     */
+    RuleBasedTimeZone(const UnicodeString& id, InitialTimeZoneRule* initialRule);
+
+    /**
+     * Copy constructor.
+     * @param source    The RuleBasedTimeZone object to be copied.
+     * @stable ICU 4.0
+     */
+    RuleBasedTimeZone(const RuleBasedTimeZone& source);
+
+    /**
+     * Destructor.
+     * @stable ICU 4.0
+     */
+    virtual ~RuleBasedTimeZone();
+
+    /**
+     * Assignment operator.
+     * @param right The object to be copied.
+     * @stable ICU 4.0
+     */
+    RuleBasedTimeZone& operator=(const RuleBasedTimeZone& right);
+
+    /**
+     * Return true if the given <code>TimeZone</code> objects are
+     * semantically equal. Objects of different subclasses are considered unequal.
+     * @param that  The object to be compared with.
+     * @return  true if the given <code>TimeZone</code> objects are
+      *semantically equal.
+     * @stable ICU 4.0
+     */
+    virtual UBool operator==(const TimeZone& that) const;
+
+    /**
+     * Return true if the given <code>TimeZone</code> objects are
+     * semantically unequal. Objects of different subclasses are considered unequal.
+     * @param that  The object to be compared with.
+     * @return  true if the given <code>TimeZone</code> objects are
+     * semantically unequal.
+     * @stable ICU 4.0
+     */
+    virtual UBool operator!=(const TimeZone& that) const;
+
+    /**
+     * Adds the <code>TimeZoneRule</code> which represents time transitions.
+     * The <code>TimeZoneRule</code> must have start times, that is, the result
+     * of isTransitionRule() must be true. Otherwise, U_ILLEGAL_ARGUMENT_ERROR
+     * is set to the error code.
+     * The input <code>TimeZoneRule</code> is adopted by this
+     * <code>RuleBasedTimeZone</code> on successful completion of this method,
+     * thus, the caller must not delete it when no error is returned.
+     * After all rules are added, the caller must call complete() method to
+     * make this <code>RuleBasedTimeZone</code> ready to handle common time
+     * zone functions.
+     * @param rule The <code>TimeZoneRule</code>.
+     * @param status Output param to filled in with a success or an error.
+     * @stable ICU 4.0
+     */
+    void addTransitionRule(TimeZoneRule* rule, UErrorCode& status);
+
+    /**
+     * Makes the <code>TimeZoneRule</code> ready to handle actual timezone
+     * calcuation APIs.  This method collects time zone rules specified
+     * by the caller via the constructor and addTransitionRule() and
+     * builds internal structure for making the object ready to support
+     * time zone APIs such as getOffset(), getNextTransition() and others.
+     * @param status Output param to filled in with a success or an error.
+     * @stable ICU 4.0
+     */
+    void complete(UErrorCode& status);
+
+    /**
+     * Clones TimeZone objects polymorphically. Clients are responsible for deleting
+     * the TimeZone object cloned.
+     *
+     * @return   A new copy of this TimeZone object.
+     * @stable ICU 4.0
+     */
+    virtual TimeZone* clone(void) const;
+
+    /**
+     * Returns the TimeZone's adjusted GMT offset (i.e., the number of milliseconds to add
+     * to GMT to get local time in this time zone, taking daylight savings time into
+     * account) as of a particular reference date.  The reference date is used to determine
+     * whether daylight savings time is in effect and needs to be figured into the offset
+     * that is returned (in other words, what is the adjusted GMT offset in this time zone
+     * at this particular date and time?).  For the time zones produced by createTimeZone(),
+     * the reference data is specified according to the Gregorian calendar, and the date
+     * and time fields are local standard time.
+     *
+     * <p>Note: Don't call this method. Instead, call the getOffset(UDate...) overload,
+     * which returns both the raw and the DST offset for a given time. This method
+     * is retained only for backward compatibility.
+     *
+     * @param era        The reference date's era
+     * @param year       The reference date's year
+     * @param month      The reference date's month (0-based; 0 is January)
+     * @param day        The reference date's day-in-month (1-based)
+     * @param dayOfWeek  The reference date's day-of-week (1-based; 1 is Sunday)
+     * @param millis     The reference date's milliseconds in day, local standard time
+     * @param status     Output param to filled in with a success or an error.
+     * @return           The offset in milliseconds to add to GMT to get local time.
+     * @stable ICU 4.0
+     */
+    virtual int32_t getOffset(uint8_t era, int32_t year, int32_t month, int32_t day,
+                              uint8_t dayOfWeek, int32_t millis, UErrorCode& status) const;
+
+    /**
+     * Gets the time zone offset, for current date, modified in case of
+     * daylight savings. This is the offset to add *to* UTC to get local time.
+     *
+     * <p>Note: Don't call this method. Instead, call the getOffset(UDate...) overload,
+     * which returns both the raw and the DST offset for a given time. This method
+     * is retained only for backward compatibility.
+     *
+     * @param era        The reference date's era
+     * @param year       The reference date's year
+     * @param month      The reference date's month (0-based; 0 is January)
+     * @param day        The reference date's day-in-month (1-based)
+     * @param dayOfWeek  The reference date's day-of-week (1-based; 1 is Sunday)
+     * @param millis     The reference date's milliseconds in day, local standard time
+     * @param monthLength The length of the given month in days.
+     * @param status     Output param to filled in with a success or an error.
+     * @return           The offset in milliseconds to add to GMT to get local time.
+     * @stable ICU 4.0
+     */
+    virtual int32_t getOffset(uint8_t era, int32_t year, int32_t month, int32_t day,
+                           uint8_t dayOfWeek, int32_t millis,
+                           int32_t monthLength, UErrorCode& status) const;
+
+    /**
+     * Returns the time zone raw and GMT offset for the given moment
+     * in time.  Upon return, local-millis = GMT-millis + rawOffset +
+     * dstOffset.  All computations are performed in the proleptic
+     * Gregorian calendar.  The default implementation in the TimeZone
+     * class delegates to the 8-argument getOffset().
+     *
+     * @param date moment in time for which to return offsets, in
+     * units of milliseconds from January 1, 1970 0:00 GMT, either GMT
+     * time or local wall time, depending on `local'.
+     * @param local if true, `date' is local wall time; otherwise it
+     * is in GMT time.
+     * @param rawOffset output parameter to receive the raw offset, that
+     * is, the offset not including DST adjustments
+     * @param dstOffset output parameter to receive the DST offset,
+     * that is, the offset to be added to `rawOffset' to obtain the
+     * total offset between local and GMT time. If DST is not in
+     * effect, this value is zero; otherwise it is a positive value,
+     * typically one hour.
+     * @param ec input-output error code
+     * @stable ICU 4.0
+     */
+    virtual void getOffset(UDate date, UBool local, int32_t& rawOffset,
+                           int32_t& dstOffset, UErrorCode& ec) const;
+
+    /**
+     * Sets the TimeZone's raw GMT offset (i.e., the number of milliseconds to add
+     * to GMT to get local time, before taking daylight savings time into account).
+     *
+     * @param offsetMillis  The new raw GMT offset for this time zone.
+     * @stable ICU 4.0
+     */
+    virtual void setRawOffset(int32_t offsetMillis);
+
+    /**
+     * Returns the TimeZone's raw GMT offset (i.e., the number of milliseconds to add
+     * to GMT to get local time, before taking daylight savings time into account).
+     *
+     * @return   The TimeZone's raw GMT offset.
+     * @stable ICU 4.0
+     */
+    virtual int32_t getRawOffset(void) const;
+
+    /**
+     * Queries if this time zone uses daylight savings time.
+     * @return true if this time zone uses daylight savings time,
+     * false, otherwise.
+     * @stable ICU 4.0
+     */
+    virtual UBool useDaylightTime(void) const;
+
+    /**
+     * Queries if the given date is in daylight savings time in
+     * this time zone.
+     * This method is wasteful since it creates a new GregorianCalendar and
+     * deletes it each time it is called. This is a deprecated method
+     * and provided only for Java compatibility.
+     *
+     * @param date the given UDate.
+     * @param status Output param filled in with success/error code.
+     * @return true if the given date is in daylight savings time,
+     * false, otherwise.
+     * @deprecated ICU 2.4. Use Calendar::inDaylightTime() instead.
+     */
+    virtual UBool inDaylightTime(UDate date, UErrorCode& status) const;
+
+    /**
+     * Returns true if this zone has the same rule and offset as another zone.
+     * That is, if this zone differs only in ID, if at all.
+     * @param other the <code>TimeZone</code> object to be compared with
+     * @return true if the given zone is the same as this one,
+     * with the possible exception of the ID
+     * @stable ICU 4.0
+     */
+    virtual UBool hasSameRules(const TimeZone& other) const;
+
+    /**
+     * Gets the first time zone transition after the base time.
+     * @param base      The base time.
+     * @param inclusive Whether the base time is inclusive or not.
+     * @param result    Receives the first transition after the base time.
+     * @return  TRUE if the transition is found.
+     * @stable ICU 4.0
+     */
+    virtual UBool getNextTransition(UDate base, UBool inclusive, TimeZoneTransition& result) /*const*/;
+
+    /**
+     * Gets the most recent time zone transition before the base time.
+     * @param base      The base time.
+     * @param inclusive Whether the base time is inclusive or not.
+     * @param result    Receives the most recent transition before the base time.
+     * @return  TRUE if the transition is found.
+     * @stable ICU 4.0
+     */
+    virtual UBool getPreviousTransition(UDate base, UBool inclusive, TimeZoneTransition& result) /*const*/;
+
+    /**
+     * Returns the number of <code>TimeZoneRule</code>s which represents time transitions,
+     * for this time zone, that is, all <code>TimeZoneRule</code>s for this time zone except
+     * <code>InitialTimeZoneRule</code>.  The return value range is 0 or any positive value.
+     * @param status    Receives error status code.
+     * @return The number of <code>TimeZoneRule</code>s representing time transitions.
+     * @stable ICU 4.0
+     */
+    virtual int32_t countTransitionRules(UErrorCode& status) /*const*/;
+
+    /**
+     * Gets the <code>InitialTimeZoneRule</code> and the set of <code>TimeZoneRule</code>
+     * which represent time transitions for this time zone.  On successful return,
+     * the argument initial points to non-NULL <code>InitialTimeZoneRule</code> and
+     * the array trsrules is filled with 0 or multiple <code>TimeZoneRule</code>
+     * instances up to the size specified by trscount.  The results are referencing the
+     * rule instance held by this time zone instance.  Therefore, after this time zone
+     * is destructed, they are no longer available.
+     * @param initial       Receives the initial timezone rule
+     * @param trsrules      Receives the timezone transition rules
+     * @param trscount      On input, specify the size of the array 'transitions' receiving
+     *                      the timezone transition rules.  On output, actual number of
+     *                      rules filled in the array will be set.
+     * @param status        Receives error status code.
+     * @stable ICU 4.0
+     */
+    virtual void getTimeZoneRules(const InitialTimeZoneRule*& initial,
+        const TimeZoneRule* trsrules[], int32_t& trscount, UErrorCode& status) /*const*/;
+
+    /**
+     * Get time zone offsets from local wall time.
+     * @internal
+     */
+    virtual void getOffsetFromLocal(UDate date, int32_t nonExistingTimeOpt, int32_t duplicatedTimeOpt,
+        int32_t& rawOffset, int32_t& dstOffset, UErrorCode& status) /*const*/;
+
+private:
+    void deleteRules(void);
+    void deleteTransitions(void);
+    UVector* copyRules(UVector* source);
+    TimeZoneRule* findRuleInFinal(UDate date, UBool local,
+        int32_t NonExistingTimeOpt, int32_t DuplicatedTimeOpt) const;
+    UBool findNext(UDate base, UBool inclusive, UDate& time, TimeZoneRule*& from, TimeZoneRule*& to) const;
+    UBool findPrev(UDate base, UBool inclusive, UDate& time, TimeZoneRule*& from, TimeZoneRule*& to) const;
+    int32_t getLocalDelta(int32_t rawBefore, int32_t dstBefore, int32_t rawAfter, int32_t dstAfter,
+        int32_t NonExistingTimeOpt, int32_t DuplicatedTimeOpt) const;
+    UDate getTransitionTime(Transition* transition, UBool local,
+        int32_t NonExistingTimeOpt, int32_t DuplicatedTimeOpt) const;
+    void getOffsetInternal(UDate date, UBool local, int32_t NonExistingTimeOpt, int32_t DuplicatedTimeOpt,
+        int32_t& rawOffset, int32_t& dstOffset, UErrorCode& ec) const;
+
+    InitialTimeZoneRule *fInitialRule;
+    UVector             *fHistoricRules;
+    UVector             *fFinalRules;
+    UVector             *fHistoricTransitions;
+    UBool               fUpToDate;
+
+public:
+    /**
+     * Return the class ID for this class. This is useful only for comparing to
+     * a return value from getDynamicClassID(). For example:
+     * <pre>
+     * .   Base* polymorphic_pointer = createPolymorphicObject();
+     * .   if (polymorphic_pointer->getDynamicClassID() ==
+     * .       erived::getStaticClassID()) ...
+     * </pre>
+     * @return          The class ID for all objects of this class.
+     * @stable ICU 4.0
+     */
+    static UClassID U_EXPORT2 getStaticClassID(void);
+
+    /**
+     * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This
+     * method is to implement a simple version of RTTI, since not all C++
+     * compilers support genuine RTTI. Polymorphic operator==() and clone()
+     * methods call this method.
+     *
+     * @return          The class ID for this object. All objects of a
+     *                  given class have the same class ID.  Objects of
+     *                  other classes have different class IDs.
+     * @stable ICU 4.0
+     */
+    virtual UClassID getDynamicClassID(void) const;
+};
+
+U_NAMESPACE_END
+
+#endif /* #if !UCONFIG_NO_FORMATTING */
+
+#endif // RBTZ_H
+
+//eof


[41/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/json_stream_parse.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/json_stream_parse.erl b/apps/couch/src/json_stream_parse.erl
deleted file mode 100644
index b63e011..0000000
--- a/apps/couch/src/json_stream_parse.erl
+++ /dev/null
@@ -1,432 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(json_stream_parse).
-
-
--export([events/2, to_ejson/1, collect_object/2]).
-
--define(IS_WS(X), (X == $\  orelse X == $\t orelse X == $\n orelse X == $\r)).
--define(IS_DELIM(X), (X == $} orelse X == $] orelse X == $,)).
--define(IS_DIGIT(X), (X >= $0 andalso X =< $9)).
-
-
-
-% Parses the json into events.
-%
-% The DataFun param is a function that produces the data for parsing. When
-% called it must yield a tuple, or the atom done. The first element in the
-% tuple is the data itself, and the second element is a function to be called
-% next to get the next chunk of data in the stream.
-%
-% The EventFun is called everytime a json element is parsed. It must produce
-% a new function to be called for the next event.
-%
-% Events happen each time a new element in the json string is parsed.
-% For simple value types, the data itself is returned:
-% Strings
-% Integers
-% Floats
-% true
-% false
-% null
-%
-% For arrays, the start of the array is signaled by the event array_start
-% atom. The end is signaled by array_end. The events before the end are the
-% values, or nested values.
-%
-% For objects, the start of the object is signaled by the event object_start
-% atom. The end is signaled by object_end. Each key is signaled by
-% {key, KeyString}, and the following event is the value, or start of the
-% value (array_start, object_start).
-%
-events(Data,EventFun) when is_list(Data)->
-    events(list_to_binary(Data),EventFun);
-events(Data,EventFun) when is_binary(Data)->
-    events(fun() -> {Data, fun() -> done end} end,EventFun);
-events(DataFun,EventFun) ->
-    parse_one(DataFun, EventFun, <<>>).
-
-% converts the JSON directly to the erlang represention of Json
-to_ejson(DF) ->
-    {_DF2, EF, _Rest} = events(DF, fun(Ev) -> collect_events(Ev, []) end),
-    [[EJson]] = make_ejson(EF(get_results), [[]]),
-    EJson.
-
-
-% This function is used to return complete objects while parsing streams.
-%
-% Return this function from inside an event function right after getting an
-% object_start event. It then collects the remaining events for that object
-% and converts it to the erlang represention of Json.
-%
-% It then calls your ReturnControl function with the erlang object. Your
-% return control function then should yield another event function.
-%
-% This example stream parses an array of objects, calling
-% fun do_something_with_the_object/1 for each object.
-%
-%    ev_array(array_start) ->
-%        fun(Ev) -> ev_object_loop(Ev) end.
-%
-%    ev_object_loop(object_start) ->
-%        fun(Ev) ->
-%            json_stream_parse:collect_object(Ev,
-%                fun(Obj) ->
-%                    do_something_with_the_object(Obj),
-%                    fun(Ev2) -> ev_object_loop(Ev2) end
-%                end)
-%        end;
-%    ev_object_loop(array_end) ->
-%        ok
-%    end.
-%
-%    % invoke the parse
-%    main() ->
-%        ...
-%        events(Data, fun(Ev) -> ev_array(Ev) end).
-
-collect_object(Ev, ReturnControl) ->
-    collect_object(Ev, 0, ReturnControl, [object_start]).
-
-
-
-% internal methods
-
-parse_one(DF,EF,Acc) ->
-    case toke(DF, Acc) of
-    none ->
-        none;
-    {Token, DF2, Rest} ->
-        case Token of
-        "{" ->
-            EF2 = EF(object_start),
-            {DF3, EF3, Rest2} = parse_object(DF2, EF2, Rest),
-            {DF3, EF3(object_end), Rest2};
-        "[" ->
-            EF2 = EF(array_start),
-            {DF3, EF3, Rest2} = parse_array(DF2, EF2, Rest),
-            {DF3, EF3(array_end), Rest2};
-        Int when is_integer(Int)->
-            {DF2, EF(Int), Rest};
-        Float when is_float(Float)->
-            {DF2, EF(Float), Rest};
-        Atom when is_atom(Atom)->
-            {DF2, EF(Atom), Rest};
-        String when is_binary(String)->
-            {DF2, EF(String), Rest};
-        _OtherToken ->
-            err(unexpected_token)
-        end
-    end.
-
-must_parse_one(DF,EF,Acc,Error)->
-    case parse_one(DF, EF, Acc) of
-    none ->
-        err(Error);
-    Else ->
-        Else
-    end.
-
-must_toke(DF, Data, Error) ->
-    case toke(DF, Data) of
-    none ->
-        err(Error);
-    Result ->
-        Result
-    end.
-
-toke(DF, <<>>) ->
-    case DF() of
-    done ->
-        none;
-    {Data, DF2} ->
-        toke(DF2, Data)
-    end;
-toke(DF, <<C,Rest/binary>>) when ?IS_WS(C)->
-    toke(DF, Rest);
-toke(DF, <<${,Rest/binary>>) ->
-    {"{", DF, Rest};
-toke(DF, <<$},Rest/binary>>) ->
-    {"}", DF, Rest};
-toke(DF, <<$[,Rest/binary>>) ->
-    {"[", DF, Rest};
-toke(DF, <<$],Rest/binary>>) ->
-    {"]", DF, Rest};
-toke(DF, <<$",Rest/binary>>) ->
-    toke_string(DF,Rest,[]);
-toke(DF, <<$,,Rest/binary>>) ->
-    {",", DF, Rest};
-toke(DF, <<$:,Rest/binary>>) ->
-    {":", DF, Rest};
-toke(DF, <<$-,Rest/binary>>) ->
-    {<<C,_/binary>> = Data, DF2} = must_df(DF,1,Rest,expected_number),
-    case ?IS_DIGIT(C) of
-    true ->
-        toke_number_leading(DF2, Data, "-");
-    false ->
-        err(expected_number)
-    end;
-toke(DF, <<C,_/binary>> = Data) when ?IS_DIGIT(C) ->
-    toke_number_leading(DF, Data, []);
-toke(DF, <<$t,Rest/binary>>) ->
-    {Data, DF2} = must_match(<<"rue">>, DF, Rest),
-    {true, DF2, Data};
-toke(DF, <<$f,Rest/binary>>) ->
-    {Data, DF2} = must_match(<<"alse">>, DF, Rest),
-    {false, DF2, Data};
-toke(DF, <<$n,Rest/binary>>) ->
-    {Data, DF2} = must_match(<<"ull">>, DF, Rest),
-    {null, DF2, Data};
-toke(_, _) ->
-    err(bad_token).
-
-
-must_match(Pattern, DF, Data) ->
-    Size = size(Pattern),
-    case must_df(DF, Size, Data, bad_token) of
-    {<<Pattern:Size/binary,Data2/binary>>, DF2} ->
-        {Data2, DF2};
-    {_, _} ->
-        err(bad_token)
-    end.
-
-must_df(DF,Error)->
-    case DF() of
-    done ->
-        err(Error);
-    {Data, DF2} ->
-        {Data, DF2}
-    end.
-
-
-must_df(DF,NeedLen,Acc,Error)->
-    if size(Acc) >= NeedLen ->
-        {Acc, DF};
-    true ->
-        case DF() of
-        done ->
-            err(Error);
-        {Data, DF2} ->
-            must_df(DF2, NeedLen, <<Acc/binary, Data/binary>>, Error)
-        end
-    end.
-
-
-parse_object(DF,EF,Acc) ->
-    case must_toke(DF, Acc, unterminated_object) of
-    {String, DF2, Rest} when is_binary(String)->
-        EF2 = EF({key,String}),
-        case must_toke(DF2,Rest,unterminated_object) of
-        {":", DF3, Rest2} ->
-            {DF4, EF3, Rest3} = must_parse_one(DF3, EF2, Rest2, expected_value),
-            case must_toke(DF4,Rest3, unterminated_object) of
-            {",", DF5, Rest4} ->
-                parse_object(DF5, EF3, Rest4);
-            {"}", DF5, Rest4} ->
-                {DF5, EF3, Rest4};
-            {_, _, _} ->
-                err(unexpected_token)
-            end;
-        _Else ->
-            err(expected_colon)
-        end;
-    {"}", DF2, Rest} ->
-        {DF2, EF, Rest};
-    {_, _, _} ->
-        err(unexpected_token)
-    end.
-
-parse_array0(DF,EF,Acc) ->
-    case toke(DF, Acc) of
-    none ->
-        err(unterminated_array);
-    {",", DF2, Rest} ->
-        parse_array(DF2,EF,Rest);
-    {"]", DF2, Rest} ->
-        {DF2,EF,Rest};
-    _ ->
-        err(unexpected_token)
-    end.
-
-parse_array(DF,EF,Acc) ->
-    case toke(DF, Acc) of
-    none ->
-         err(unterminated_array);
-    {Token, DF2, Rest} ->
-        case Token of
-        "{" ->
-            EF2 = EF(object_start),
-            {DF3, EF3, Rest2} = parse_object(DF2, EF2, Rest),
-            parse_array0(DF3, EF3(object_end), Rest2);
-        "[" ->
-            EF2 = EF(array_start),
-            {DF3, EF3, Rest2} = parse_array(DF2, EF2, Rest),
-            parse_array0(DF3, EF3(array_end), Rest2);
-        Int when is_integer(Int)->
-            parse_array0(DF2, EF(Int), Rest);
-        Float when is_float(Float)->
-            parse_array0(DF2, EF(Float), Rest);
-        Atom when is_atom(Atom)->
-            parse_array0(DF2, EF(Atom), Rest);
-        String when is_binary(String)->
-            parse_array0(DF2, EF(String), Rest);
-        "]" ->
-            {DF2, EF, Rest};
-        _ ->
-            err(unexpected_token)
-        end
-    end.
-
-
-toke_string(DF, <<>>, Acc) ->
-    {Data, DF2} = must_df(DF, unterminated_string),
-    toke_string(DF2, Data, Acc);
-toke_string(DF, <<$\\,$",Rest/binary>>, Acc) ->
-    toke_string(DF, Rest, [$" | Acc]);
-toke_string(DF, <<$\\,$\\,Rest/binary>>, Acc) ->
-    toke_string(DF, Rest, [$\\ | Acc]);
-toke_string(DF, <<$\\,$/,Rest/binary>>, Acc) ->
-    toke_string(DF, Rest, [$/ | Acc]);
-toke_string(DF, <<$\\,$b,Rest/binary>>, Acc) ->
-    toke_string(DF, Rest, [$\b | Acc]);
-toke_string(DF, <<$\\,$f,Rest/binary>>, Acc) ->
-    toke_string(DF, Rest, [$\f | Acc]);
-toke_string(DF, <<$\\,$n,Rest/binary>>, Acc) ->
-    toke_string(DF, Rest, [$\n | Acc]);
-toke_string(DF, <<$\\,$r,Rest/binary>>, Acc) ->
-    toke_string(DF, Rest, [$\r | Acc]);
-toke_string(DF, <<$\\,$t,Rest/binary>>, Acc) ->
-    toke_string(DF, Rest, [$\t | Acc]);
-toke_string(DF, <<$\\,$u,Rest/binary>>, Acc) ->
-    {<<A,B,C,D,Data/binary>>, DF2} = must_df(DF,4,Rest,missing_hex),
-    UTFChar = erlang:list_to_integer([A, B, C, D], 16),
-    if UTFChar == 16#FFFF orelse UTFChar == 16#FFFE ->
-        err(invalid_utf_char);
-    true ->
-        ok
-    end,
-    Chars = xmerl_ucs:to_utf8(UTFChar),
-    toke_string(DF2, Data, lists:reverse(Chars) ++ Acc);
-toke_string(DF, <<$\\>>, Acc) ->
-    {Data, DF2} = must_df(DF, unterminated_string),
-    toke_string(DF2, <<$\\,Data/binary>>, Acc);
-toke_string(_DF, <<$\\, _/binary>>, _Acc) ->
-    err(bad_escape);
-toke_string(DF, <<$", Rest/binary>>, Acc) ->
-    {list_to_binary(lists:reverse(Acc)), DF, Rest};
-toke_string(DF, <<C, Rest/binary>>, Acc) ->
-    toke_string(DF, Rest, [C | Acc]).
-
-
-toke_number_leading(DF, <<Digit,Rest/binary>>, Acc)
-        when ?IS_DIGIT(Digit) ->
-    toke_number_leading(DF, Rest, [Digit | Acc]);
-toke_number_leading(DF, <<C,_/binary>>=Rest, Acc)
-        when ?IS_WS(C) orelse ?IS_DELIM(C) ->
-    {list_to_integer(lists:reverse(Acc)), DF, Rest};
-toke_number_leading(DF, <<>>, Acc) ->
-    case DF() of
-    done ->
-         {list_to_integer(lists:reverse(Acc)), fun() -> done end, <<>>};
-    {Data, DF2} ->
-        toke_number_leading(DF2, Data, Acc)
-    end;
-toke_number_leading(DF, <<$., Rest/binary>>, Acc) ->
-    toke_number_trailing(DF, Rest, [$.|Acc]);
-toke_number_leading(DF, <<$e, Rest/binary>>, Acc) ->
-    toke_number_exponent(DF, Rest, [$e, $0, $.|Acc]);
-toke_number_leading(DF, <<$E, Rest/binary>>, Acc) ->
-    toke_number_exponent(DF, Rest, [$e, $0, $.|Acc]);
-toke_number_leading(_, _, _) ->
-    err(unexpected_character_in_number).
-
-toke_number_trailing(DF, <<Digit,Rest/binary>>, Acc)
-        when ?IS_DIGIT(Digit) ->
-    toke_number_trailing(DF, Rest, [Digit | Acc]);
-toke_number_trailing(DF, <<C,_/binary>>=Rest, Acc)
-        when ?IS_WS(C) orelse ?IS_DELIM(C) ->
-    {list_to_float(lists:reverse(Acc)), DF, Rest};
-toke_number_trailing(DF, <<>>, Acc) ->
-    case DF() of
-    done ->
-        {list_to_float(lists:reverse(Acc)), fun() -> done end, <<>>};
-    {Data, DF2} ->
-        toke_number_trailing(DF2, Data, Acc)
-    end;
-toke_number_trailing(DF, <<"e", Rest/binary>>, [C|_]=Acc) when C /= $. ->
-    toke_number_exponent(DF, Rest, [$e|Acc]);
-toke_number_trailing(DF, <<"E", Rest/binary>>, [C|_]=Acc) when C /= $. ->
-    toke_number_exponent(DF, Rest, [$e|Acc]);
-toke_number_trailing(_, _, _) ->
-    err(unexpected_character_in_number).
-
-
-toke_number_exponent(DF, <<Digit,Rest/binary>>, Acc) when ?IS_DIGIT(Digit) ->
-    toke_number_exponent(DF, Rest, [Digit | Acc]);
-toke_number_exponent(DF, <<Sign,Rest/binary>>, [$e|_]=Acc)
-        when Sign == $+ orelse Sign == $- ->
-    toke_number_exponent(DF, Rest, [Sign | Acc]);
-toke_number_exponent(DF, <<C,_/binary>>=Rest, Acc)
-        when ?IS_WS(C) orelse ?IS_DELIM(C) ->
-    {list_to_float(lists:reverse(Acc)), DF, Rest};
-toke_number_exponent(DF, <<>>, Acc) ->
-    case DF() of
-    done ->
-        {list_to_float(lists:reverse(Acc)), fun() -> done end, <<>>};
-    {Data, DF2} ->
-        toke_number_exponent(DF2, Data, Acc)
-    end;
-toke_number_exponent(_, _, _) ->
-        err(unexpected_character_in_number).
-
-
-err(Error)->
-    throw({parse_error,Error}).
-
-
-make_ejson([], Stack) ->
-    Stack;
-make_ejson([array_start | RevEvs], [ArrayValues, PrevValues | RestStack]) ->
-    make_ejson(RevEvs, [[ArrayValues | PrevValues] | RestStack]);
-make_ejson([array_end | RevEvs], Stack) ->
-    make_ejson(RevEvs, [[] | Stack]);
-make_ejson([object_start | RevEvs], [ObjValues, PrevValues | RestStack]) ->
-    make_ejson(RevEvs, [[{ObjValues} | PrevValues] | RestStack]);
-make_ejson([object_end | RevEvs], Stack) ->
-    make_ejson(RevEvs, [[] | Stack]);
-make_ejson([{key, String} | RevEvs], [[PrevValue|RestObject] | RestStack] = _Stack) ->
-    make_ejson(RevEvs, [[{String, PrevValue}|RestObject] | RestStack]);
-make_ejson([Value | RevEvs], [Vals | RestStack] = _Stack) ->
-    make_ejson(RevEvs, [[Value | Vals] | RestStack]).
-
-collect_events(get_results, Acc) ->
-    Acc;
-collect_events(Ev, Acc) ->
-    fun(NextEv) -> collect_events(NextEv, [Ev | Acc]) end.
-
-
-collect_object(object_end, 0, ReturnControl, Acc) ->
-    [[Obj]] = make_ejson([object_end | Acc], [[]]),
-    ReturnControl(Obj);
-collect_object(object_end, NestCount, ReturnControl, Acc) ->
-    fun(Ev) ->
-        collect_object(Ev, NestCount - 1, ReturnControl, [object_end | Acc])
-    end;
-collect_object(object_start, NestCount, ReturnControl, Acc) ->
-    fun(Ev) ->
-        collect_object(Ev, NestCount + 1, ReturnControl, [object_start | Acc])
-    end;
-collect_object(Ev, NestCount, ReturnControl, Acc) ->
-    fun(Ev2) ->
-        collect_object(Ev2, NestCount, ReturnControl, [Ev | Acc])
-    end.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_collate/c_src/couch_collate.c
----------------------------------------------------------------------
diff --git a/apps/couch_collate/c_src/couch_collate.c b/apps/couch_collate/c_src/couch_collate.c
deleted file mode 100644
index c5453d2..0000000
--- a/apps/couch_collate/c_src/couch_collate.c
+++ /dev/null
@@ -1,281 +0,0 @@
-/*
-
-Licensed under the Apache License, Version 2.0 (the "License"); you may not use
-this file except in compliance with the License. You may obtain a copy of the
-License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software distributed
-under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
-CONDITIONS OF ANY KIND, either express or implied. See the License for the
-specific language governing permissions and limitations under the License.
-
-*/
-
-#ifdef DARWIN
-#define U_HIDE_DRAFT_API 1
-#define U_DISABLE_RENAMING 1
-#endif
-
-#include "erl_nif.h"
-#include "unicode/ucol.h"
-#include "unicode/ucasemap.h"
-#include <stdio.h>
-#include <assert.h>
-
-static ERL_NIF_TERM ATOM_TRUE;
-static ERL_NIF_TERM ATOM_FALSE;
-static ERL_NIF_TERM ATOM_NULL;
-
-typedef struct {
-    ErlNifEnv* env;
-    int error;
-    UCollator* coll;
-} ctx_t;
-
-typedef struct {
-    UCollator** collators;
-    int collStackTop;
-    int numCollators;
-    ErlNifMutex* collMutex;
-} priv_data_t;
-
-static ERL_NIF_TERM collate_nif(ErlNifEnv*, int, const ERL_NIF_TERM []);
-static int collate_binary(priv_data_t*, ctx_t*, ERL_NIF_TERM, ERL_NIF_TERM, ERL_NIF_TERM);
-static int on_load(ErlNifEnv*, void**, ERL_NIF_TERM);
-static void on_unload(ErlNifEnv*, void*);
-static __inline void reserve_coll(priv_data_t*, ctx_t*);
-static __inline void release_coll(priv_data_t*, ctx_t*);
-int on_reload(ErlNifEnv*, void**, ERL_NIF_TERM);
-int on_upgrade(ErlNifEnv*, void**, void**, ERL_NIF_TERM);
-
-void
-reserve_coll(priv_data_t* pData, ctx_t *ctx)
-{
-    if (ctx->coll == NULL) {
-        enif_mutex_lock(pData->collMutex);
-        assert(pData->collStackTop < pData->numCollators);
-        ctx->coll = pData->collators[pData->collStackTop];
-        pData->collStackTop += 1;
-        enif_mutex_unlock(pData->collMutex);
-    }
-}
-
-
-void
-release_coll(priv_data_t* pData, ctx_t *ctx)
-{
-    if (ctx->coll != NULL) {
-        enif_mutex_lock(pData->collMutex);
-        pData->collStackTop -= 1;
-        assert(pData->collStackTop >= 0);
-        enif_mutex_unlock(pData->collMutex);
-    }
-}
-
-/* ------------------------------------------------------------------------- */
-
-static ERL_NIF_TERM
-collate_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {
-    ERL_NIF_TERM term_a          = argv[0];
-    ERL_NIF_TERM term_b          = argv[1];
-    ERL_NIF_TERM term_has_nocase = argv[2];
-
-    ctx_t ctx;
-    int result;
-    priv_data_t* pData;
-
-    ctx.env = env;
-    ctx.error = 0;
-    ctx.coll = NULL;
-
-    pData = (priv_data_t*) enif_priv_data(env);
-
-    result = collate_binary(pData, &ctx, term_a, term_b, term_has_nocase);
-    release_coll(pData, &ctx);
-
-    return enif_make_int(env, result);
-}
-
-int
-collate_binary(priv_data_t* pData, ctx_t* ctx, ERL_NIF_TERM term_a, ERL_NIF_TERM term_b, ERL_NIF_TERM term_has_nocase)
-{
-    ErlNifBinary binA, binB;
-    int has_nocase, response;
-
-    if(!enif_get_int(ctx->env, term_has_nocase, &has_nocase)) {
-        ctx->error = 1;
-        return 0;
-    }
-    if(!enif_inspect_binary(ctx->env, term_a, &binA)) {
-        ctx->error = 1;
-        return 0;
-    }
-    if(!enif_inspect_binary(ctx->env, term_b, &binB)) {
-        ctx->error = 1;
-        return 0;
-    }
-
-    switch(has_nocase) {
-    case 0: /* COLLATE */
-    case 1: /* COLLATE_NO_CASE: */
-        {
-        UErrorCode status = U_ZERO_ERROR;
-        UCharIterator iterA;
-        UCharIterator iterB;
-
-        uiter_setUTF8(&iterA, (const char *) binA.data, (uint32_t) binA.size);
-        uiter_setUTF8(&iterB, (const char *) binB.data, (uint32_t) binB.size);
-
-        /* grab a collator */
-        reserve_coll(pData, ctx);
-
-        if (has_nocase == 1) /* switching this collator to case insensitive */
-          ucol_setAttribute(ctx->coll, UCOL_STRENGTH, UCOL_PRIMARY, &status);
-
-        /* by default, it will collate case sensitive */
-        response = ucol_strcollIter(ctx->coll, &iterA, &iterB, &status);
-
-        if (has_nocase == 1) /* puting back this collator to case sensitive */
-          ucol_setAttribute(ctx->coll, UCOL_STRENGTH, UCOL_DEFAULT, &status);
-
-        break;
-        }
-
-    default:
-        response = -1;
-    }
-
-    return response;
-}
-
-/* ------------------------------------------------------------------------- */
-
-int
-on_load(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM info)
-{
-    UErrorCode status = U_ZERO_ERROR;
-    priv_data_t* pData = (priv_data_t*)enif_alloc(sizeof(priv_data_t));
-    int i, j;
-
-    /* Initialize the structure */
-    pData->collators = NULL;
-    pData->collStackTop = 0;
-    pData->numCollators = 0;
-    pData->collMutex = NULL;
-
-    if (!enif_get_int(env, info, &(pData->numCollators) )) {
-        enif_free((char*)pData);
-        return 1;
-    }
-
-    if (pData->numCollators < 1) {
-        enif_free((char*)pData);
-        return 2;
-    }
-
-    pData->collMutex = enif_mutex_create((char *)"coll_mutex");
-
-    if (pData->collMutex == NULL) {
-        enif_free((char*)pData);
-        return 3;
-    }
-
-    pData->collators = enif_alloc(sizeof(UCollator*) * pData->numCollators);
-
-    if (pData->collators == NULL) {
-        enif_mutex_destroy(pData->collMutex);
-        enif_free((char*)pData);
-        return 4;
-    }
-
-    for (i = 0; i < pData->numCollators; i++) {
-        pData->collators[i] = ucol_open("", &status);
-
-        if (U_FAILURE(status)) {
-            for (j = 0; j < i; j++) {
-                ucol_close(pData->collators[j]);
-            }
-
-            enif_free(pData->collators);
-            enif_mutex_destroy(pData->collMutex);
-
-            enif_free((char*)pData);
-
-            return 5;
-        }
-    }
-
-    ATOM_TRUE = enif_make_atom(env, "true");
-    ATOM_FALSE = enif_make_atom(env, "false");
-    ATOM_NULL = enif_make_atom(env, "null");
-
-    *priv_data = pData;
-
-    return 0;
-}
-
-
-void
-on_unload(ErlNifEnv* env, void* priv_data)
-{
-    priv_data_t* pData = (priv_data_t*)priv_data;
-    if (pData->collators != NULL) {
-        int i;
-
-        for (i = 0; i < pData->numCollators; i++) {
-            ucol_close(pData->collators[i]);
-        }
-
-        enif_free(pData->collators);
-    }
-
-    if (pData->collMutex != NULL) {
-        enif_mutex_destroy(pData->collMutex);
-    }
-
-    enif_free((char*)pData);
-}
-
-int
-on_reload(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM info)
-{
-    return 0;
-}
-
-int
-on_upgrade(ErlNifEnv* env, void** priv_data, void** old_data, ERL_NIF_TERM info)
-{
-    if (*old_data != NULL) {
-        priv_data_t* pData = (priv_data_t*)old_data;
-
-        if (pData->collators != NULL) {
-            int i;
-
-            for (i = 0; i < pData->numCollators; i++) {
-                ucol_close(pData->collators[i]);
-            }
-
-            enif_free(pData->collators);
-        }
-
-        if (pData->collMutex != NULL) {
-            enif_mutex_destroy(pData->collMutex);
-        }
-
-        enif_free((char*)pData);
-    }
-
-    return on_load(env, priv_data, info);
-}
-
-/* ------------------------------------------------------------------------- */
-
-static ErlNifFunc
-nif_funcs[] =
-{
-    {"collate_nif", 3, collate_nif}
-};
-
-ERL_NIF_INIT(couch_collate, nif_funcs, &on_load, &on_reload, &on_upgrade, &on_unload)

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_collate/rebar.config
----------------------------------------------------------------------
diff --git a/apps/couch_collate/rebar.config b/apps/couch_collate/rebar.config
deleted file mode 100644
index 7bfd49e..0000000
--- a/apps/couch_collate/rebar.config
+++ /dev/null
@@ -1,9 +0,0 @@
-%% -*- tab-width: 4;erlang-indent-level: 4;indent-tabs-mode: nil -*-
-%% ex: ft=erlang ts=4 sw=4 et
-
-{erl_opts, [
-        warnings_as_errors,
-        warn_export_all
-]}.
-
-{pre_hooks, [{clean, "rm -fr ebin priv erl_crash.dump"}]}.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_collate/rebar.config.script
----------------------------------------------------------------------
diff --git a/apps/couch_collate/rebar.config.script b/apps/couch_collate/rebar.config.script
deleted file mode 100644
index ff5ef9b..0000000
--- a/apps/couch_collate/rebar.config.script
+++ /dev/null
@@ -1,46 +0,0 @@
-%% -*- tab-width: 4;erlang-indent-level: 4;indent-tabs-mode: nil -*-
-%% ex: ft=erlang ts=4 sw=4 et
-
-%% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-%% use this file except in compliance with the License. You may obtain a copy of
-%% the License at
-%%
-%%   http://www.apache.org/licenses/LICENSE-2.0
-%%
-%% Unless required by applicable law or agreed to in writing, software
-%% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-%% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-%% License for the specific language governing permissions and limitations under
-%% the License.
-
-Arch = erlang:system_info(system_architecture),
-
-ICUConfig = fun(Args) ->
-    {0, Value} = eunit_lib:command("icu-config " ++ Args),
-    [C||C <- Value, C =/= $\n]
-end,
-
-GetFlag = fun(Name, Args) ->
-        case os:getenv(Name) of
-            false -> ICUConfig(Args);
-            Val -> Val
-        end
-    end,
-
-ICUCFLAGS = GetFlag("ICU_CFLAGS", "--cflags"),
-ICUCXXFLAGS = GetFlag("ICU_CXXFLAGS", "--cxxflags"),
-ICULDFLAGS = GetFlag("ICU_LDFLAGS", "--ldflags"),
-ICUINCPATH = GetFlag("ICU_INCPATH", "--cppflags-searchpath"),
-
-
-PortEnv = [{port_env, [
-            {"CFLAGS",  ICUCFLAGS ++  " $CFLAGS " ++ ICUINCPATH},
-            {"CXXFLAGS", ICUCXXFLAGS ++ " $CXXFLAGS " ++ ICUINCPATH},
-            {"LDFLAGS",  ICULDFLAGS ++ " $LDFLAGS"}]},
-
-           {port_specs, [
-            {filename:join(["priv", Arch, "couch_collate.so"]),
-            ["c_src/*.c"]}]}
-],
-
-lists:keymerge(1,lists:keysort(1, PortEnv), lists:keysort(1, CONFIG)).

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_collate/src/couch_collate.app.src
----------------------------------------------------------------------
diff --git a/apps/couch_collate/src/couch_collate.app.src b/apps/couch_collate/src/couch_collate.app.src
deleted file mode 100644
index c41495c..0000000
--- a/apps/couch_collate/src/couch_collate.app.src
+++ /dev/null
@@ -1,13 +0,0 @@
-%% -*- tab-width: 4;erlang-indent-level: 4;indent-tabs-mode: nil -*-
-%% ex: ft=erlang ts=4 sw=4 et
-
-{application, couch_collate,
-    [
-        {description, "couchdb collation module"},
-        {vsn, "1.0.0"},
-        {registered, []},
-        {applications, [kernel,
-                        stdlib]},
-        {included_applications, []},
-        {env, []}
-]}.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_collate/src/couch_collate.erl
----------------------------------------------------------------------
diff --git a/apps/couch_collate/src/couch_collate.erl b/apps/couch_collate/src/couch_collate.erl
deleted file mode 100644
index 341510f..0000000
--- a/apps/couch_collate/src/couch_collate.erl
+++ /dev/null
@@ -1,62 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_collate).
-
--export([init/0]).
--export([collate/2, collate/3]).
-
--on_load(init/0).
-
--type collate_options() :: [nocase].
--export_type([collate_options/0]).
-
-init() ->
-    PrivDir = case code:priv_dir(?MODULE) of
-        {error, _} ->
-            EbinDir = filename:dirname(code:which(?MODULE)),
-            AppPath = filename:dirname(EbinDir),
-            filename:join(AppPath, "priv");
-        Path ->
-            Path
-    end,
-    NumScheds = erlang:system_info(schedulers),
-    Arch = erlang:system_info(system_architecture),
-    (catch erlang:load_nif(filename:join([PrivDir, Arch, ?MODULE]),
-                           NumScheds)),
-    case erlang:system_info(otp_release) of
-        "R13B03" -> true;
-        _ -> ok
-    end.
-
-%% @doc compare 2 string, result is -1 for lt, 0 for eq and 1 for gt.
--spec collate(binary(), binary()) -> 0 | -1 | 1.
-collate(A, B) ->
-    collate(A, B, []).
-
--spec collate(binary(), binary(), collate_options()) -> 0 | -1 | 1.
-collate(A, B, Options) when is_binary(A), is_binary(B) ->
-    HasNoCase = case lists:member(nocase, Options) of
-        true -> 1; % Case insensitive
-        false -> 0 % Case sensitive
-    end,
-    do_collate(A, B, HasNoCase).
-
-%% @private
-
-do_collate(BinaryA, BinaryB, 0) ->
-    collate_nif(BinaryA, BinaryB, 0);
-do_collate(BinaryA, BinaryB, 1) ->
-    collate_nif(BinaryA, BinaryB, 1).
-
-collate_nif(_BinaryA, _BinaryB, _HasCase) ->
-    exit(couch_collate_not_loaded).

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_dbupdates/src/couch_dbupdates.app.src
----------------------------------------------------------------------
diff --git a/apps/couch_dbupdates/src/couch_dbupdates.app.src b/apps/couch_dbupdates/src/couch_dbupdates.app.src
deleted file mode 100644
index 54a543e..0000000
--- a/apps/couch_dbupdates/src/couch_dbupdates.app.src
+++ /dev/null
@@ -1,11 +0,0 @@
-{application, couch_dbupdates,
- [
-  {description, ""},
-  {vsn, "1.0.0"},
-  {registered, []},
-  {applications, [
-                  kernel,
-                  stdlib
-                 ]},
-  {env, []}
- ]}.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_dbupdates/src/couch_dbupdates.erl
----------------------------------------------------------------------
diff --git a/apps/couch_dbupdates/src/couch_dbupdates.erl b/apps/couch_dbupdates/src/couch_dbupdates.erl
deleted file mode 100644
index e37362f..0000000
--- a/apps/couch_dbupdates/src/couch_dbupdates.erl
+++ /dev/null
@@ -1,46 +0,0 @@
--module(couch_dbupdates).
-
--export([handle_dbupdates/3]).
-
-
-handle_dbupdates(Fun, Acc, Options) ->
-    NotifierPid = db_update_notifier(),
-    try
-        loop(Fun, Acc, Options)
-    after
-        couch_db_update_notifier:stop(NotifierPid)
-    end.
-
-
-loop(Fun, Acc, Options) ->
-    [{timeout, Timeout}, {heartbeat, Heartbeat}] = Options,
-    receive
-        {db_updated, Event} ->
-            case Fun(Event, Acc) of
-                {ok, Acc1} ->
-                    loop(Fun, Acc1, Options);
-                stop ->
-                    Fun(stop, Acc)
-
-            end
-    after Timeout ->
-        case Heartbeat of
-            true ->
-                case Fun(heartbeat, Acc) of
-                {ok, Acc1} ->
-                    loop(Fun, Acc1, Options);
-                stop ->
-                    Fun(stop, Acc)
-
-                end;
-            _ ->
-                Fun(stop, Acc)
-        end
-    end.
-
-db_update_notifier() ->
-    Self = self(),
-    {ok, Notifier} = couch_db_update_notifier:start_link(fun(Event) ->
-        Self ! {db_updated, Event}
-    end),
-    Notifier.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_dbupdates/src/couch_dbupdates_httpd.erl
----------------------------------------------------------------------
diff --git a/apps/couch_dbupdates/src/couch_dbupdates_httpd.erl b/apps/couch_dbupdates/src/couch_dbupdates_httpd.erl
deleted file mode 100644
index 09f1104..0000000
--- a/apps/couch_dbupdates/src/couch_dbupdates_httpd.erl
+++ /dev/null
@@ -1,69 +0,0 @@
--module(couch_dbupdates_httpd).
-
--export([handle_req/1]).
-
--include_lib("couch/include/couch_db.hrl").
-
--record(state, {resp, feed}).
-
-handle_req(#httpd{method='GET'}=Req) ->
-    ok = couch_httpd:verify_is_server_admin(Req),
-    Qs = couch_httpd:qs(Req),
-    Feed = proplists:get_value("feed", Qs, "longpoll"),
-
-    Timeout = list_to_integer(
-                proplists:get_value("timeout", Qs, "60000")
-    ),
-
-    Heartbeat0 = proplists:get_value("heartbeat", Qs),
-    Heartbeat = case {Feed, Heartbeat0} of
-        {"longpoll", _} -> false;
-        {_, "false"} -> false;
-        _ -> true
-    end,
-
-    Options = [{timeout, Timeout}, {heartbeat, Heartbeat}],
-
-    {ok, Resp} = case Feed of
-        "eventsource" ->
-            Headers = [
-                {"Content-Type", "text/event-stream"},
-                {"Cache-Control", "no-cache"}
-            ],
-            couch_httpd:start_json_response(Req, 200, Headers);
-        _ ->
-            couch_httpd:start_json_response(Req, 200)
-    end,
-
-    State = #state{resp=Resp, feed=Feed},
-    couch_dbupdates:handle_dbupdates(fun handle_update/2,
-                                     State, Options);
-
-handle_req(Req) ->
-    couch_httpd:send_method_not_allowed(Req, "GET").
-
-handle_update(stop, #state{resp=Resp}) ->
-    couch_httpd:end_json_response(Resp);
-handle_update(heartbeat, #state{resp=Resp}=State) ->
-    {ok, Resp1} = couch_httpd:send_chunk(Resp, "\n"),
-    {ok, State#state{resp=Resp1}};
-handle_update(Event, #state{resp=Resp, feed="eventsource"}=State) ->
-    EventObj = event_obj(Event),
-    {ok, Resp1} = couch_httpd:send_chunk(Resp, ["data: ",
-                                                ?JSON_ENCODE(EventObj),
-                                                "\n\n"]),
-    {ok, State#state{resp=Resp1}};
-handle_update(Event, #state{resp=Resp, feed="continuous"}=State) ->
-    EventObj = event_obj(Event),
-    {ok, Resp1} = couch_httpd:send_chunk(Resp, [?JSON_ENCODE(EventObj) |
-                            "\n"]),
-    {ok, State#state{resp=Resp1}};
-handle_update(Event, #state{resp=Resp, feed="longpoll"}) ->
-    {Props} = event_obj(Event),
-    JsonObj = {[{<<"ok">>, true} | Props]},
-    couch_httpd:send_chunk(Resp, ?JSON_ENCODE(JsonObj)),
-    stop.
-
-event_obj({Type, DbName}) ->
-    {[{<<"type">>, couch_util:to_binary(Type)},
-      {<<"db_name">>, couch_util:to_binary(DbName)}]}.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_index/src/couch_index.app.src
----------------------------------------------------------------------
diff --git a/apps/couch_index/src/couch_index.app.src b/apps/couch_index/src/couch_index.app.src
deleted file mode 100644
index 6a59e99..0000000
--- a/apps/couch_index/src/couch_index.app.src
+++ /dev/null
@@ -1,20 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
-{application, couch_index, [
-    {description, "CouchDB Secondary Index Manager"},
-    {vsn, "1.3.0"},
-    {modules, []},
-    {registered, [couch_index_server]},
-    {applications, [kernel, stdlib, couch]},
-    {mod, {couch_index_app, []}}
-]}.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_index/src/couch_index.erl
----------------------------------------------------------------------
diff --git a/apps/couch_index/src/couch_index.erl b/apps/couch_index/src/couch_index.erl
deleted file mode 100644
index c09a110..0000000
--- a/apps/couch_index/src/couch_index.erl
+++ /dev/null
@@ -1,338 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_index).
--behaviour(gen_server).
-
-
-%% API
--export([start_link/1, stop/1, get_state/2, get_info/1]).
--export([compact/1, compact/2, get_compactor_pid/1]).
--export([config_change/3]).
-
-%% gen_server callbacks
--export([init/1, terminate/2, code_change/3]).
--export([handle_call/3, handle_cast/2, handle_info/2]).
-
--include_lib("couch/include/couch_db.hrl").
-
--record(st, {
-    mod,
-    idx_state,
-    updater,
-    compactor,
-    waiters=[],
-    commit_delay,
-    committed=true,
-    shutdown=false
-}).
-
-
-start_link({Module, IdxState}) ->
-    proc_lib:start_link(?MODULE, init, [{Module, IdxState}]).
-
-
-stop(Pid) ->
-    gen_server:cast(Pid, stop).
-
-
-get_state(Pid, RequestSeq) ->
-    gen_server:call(Pid, {get_state, RequestSeq}, infinity).
-
-
-get_info(Pid) ->
-    gen_server:call(Pid, get_info).
-
-
-compact(Pid) ->
-    compact(Pid, []).
-
-
-compact(Pid, Options) ->
-    {ok, CPid} = gen_server:call(Pid, compact),
-    case lists:member(monitor, Options) of
-        true -> {ok, erlang:monitor(process, CPid)};
-        false -> ok
-    end.
-
-
-get_compactor_pid(Pid) ->
-    gen_server:call(Pid, get_compactor_pid).
-
-config_change("query_server_config", "commit_freq", NewValue) ->
-    ok = gen_server:cast(?MODULE, {config_update, NewValue}).
-
-
-init({Mod, IdxState}) ->
-    ok = couch_config:register(fun ?MODULE:config_change/3),
-    DbName = Mod:get(db_name, IdxState),
-    Resp = couch_util:with_db(DbName, fun(Db) ->
-        case Mod:open(Db, IdxState) of
-            {ok, IdxSt} ->
-                couch_db:monitor(Db),
-                {ok, IdxSt};
-            Error ->
-                Error
-        end
-    end),
-    case Resp of
-        {ok, NewIdxState} ->
-            {ok, UPid} = couch_index_updater:start_link(self(), Mod),
-            {ok, CPid} = couch_index_compactor:start_link(self(), Mod),
-            Delay = couch_config:get("query_server_config", "commit_freq", "5"),
-            MsDelay = 1000 * list_to_integer(Delay),
-            State = #st{
-                mod=Mod,
-                idx_state=NewIdxState,
-                updater=UPid,
-                compactor=CPid,
-                commit_delay=MsDelay
-            },
-            Args = [
-                Mod:get(db_name, IdxState),
-                Mod:get(idx_name, IdxState),
-                couch_index_util:hexsig(Mod:get(signature, IdxState))
-            ],
-            ?LOG_INFO("Opening index for db: ~s idx: ~s sig: ~p", Args),
-            proc_lib:init_ack({ok, self()}),
-            gen_server:enter_loop(?MODULE, [], State);
-        Other ->
-            proc_lib:init_ack(Other)
-    end.
-
-
-terminate(Reason, State) ->
-    #st{mod=Mod, idx_state=IdxState}=State,
-    Mod:close(IdxState),
-    send_all(State#st.waiters, Reason),
-    couch_util:shutdown_sync(State#st.updater),
-    couch_util:shutdown_sync(State#st.compactor),
-    Args = [
-        Mod:get(db_name, IdxState),
-        Mod:get(idx_name, IdxState),
-        couch_index_util:hexsig(Mod:get(signature, IdxState)),
-        Reason
-    ],
-    ?LOG_INFO("Closing index for db: ~s idx: ~s sig: ~p~nreason: ~p", Args),
-    ok.
-
-
-handle_call({get_state, ReqSeq}, From, State) ->
-    #st{
-        mod=Mod,
-        idx_state=IdxState,
-        waiters=Waiters
-    } = State,
-    IdxSeq = Mod:get(update_seq, IdxState),
-    case ReqSeq =< IdxSeq of
-        true ->
-            {reply, {ok, IdxState}, State};
-        _ -> % View update required
-            couch_index_updater:run(State#st.updater, IdxState),
-            Waiters2 = [{From, ReqSeq} | Waiters],
-            {noreply, State#st{waiters=Waiters2}, infinity}
-    end;
-handle_call(get_info, _From, State) ->
-    #st{mod=Mod} = State,
-    {ok, Info0} = Mod:get(info, State#st.idx_state),
-    IsUpdating = couch_index_updater:is_running(State#st.updater),
-    IsCompacting = couch_index_compactor:is_running(State#st.compactor),
-    Info = Info0 ++ [
-        {updater_running, IsUpdating},
-        {compact_running, IsCompacting},
-        {waiting_commit, State#st.committed == false},
-        {waiting_clients, length(State#st.waiters)}
-    ],
-    {reply, {ok, Info}, State};
-handle_call(reset, _From, State) ->
-    #st{
-        mod=Mod,
-        idx_state=IdxState
-    } = State,
-    {ok, NewIdxState} = Mod:reset(IdxState),
-    {reply, {ok, NewIdxState}, State#st{idx_state=NewIdxState}};
-handle_call(compact, _From, State) ->
-    Resp = couch_index_compactor:run(State#st.compactor, State#st.idx_state),
-    {reply, Resp, State};
-handle_call(get_compactor_pid, _From, State) ->
-    {reply, {ok, State#st.compactor}, State};
-handle_call({compacted, NewIdxState}, _From, State) ->
-    #st{
-        mod=Mod,
-        idx_state=OldIdxState,
-        updater=Updater,
-        commit_delay=Delay
-    } = State,
-    assert_signature_match(Mod, OldIdxState, NewIdxState),
-    NewSeq = Mod:get(update_seq, NewIdxState),
-    OldSeq = Mod:get(update_seq, OldIdxState),
-    % For indices that require swapping files, we have to make sure we're
-    % up to date with the current index. Otherwise indexes could roll back
-    % (perhaps considerably) to previous points in history.
-    case NewSeq >= OldSeq of
-        true ->
-            {ok, NewIdxState1} = Mod:swap_compacted(OldIdxState, NewIdxState),
-            % Restart the indexer if it's running.
-            case couch_index_updater:is_running(Updater) of
-                true -> ok = couch_index_updater:restart(Updater, NewIdxState1);
-                false -> ok
-            end,
-            case State#st.committed of
-                true -> erlang:send_after(Delay, self(), commit);
-                false -> ok
-            end,
-            {reply, ok, State#st{
-                idx_state=NewIdxState1,
-                committed=false
-            }};
-        _ ->
-            {reply, recompact, State}
-    end.
-
-
-handle_cast({config_change, NewDelay}, State) ->
-    MsDelay = 1000 * list_to_integer(NewDelay),
-    {noreply, State#st{commit_delay=MsDelay}};
-handle_cast({updated, NewIdxState}, State) ->
-    {noreply, NewState} = handle_cast({new_state, NewIdxState}, State),
-    case NewState#st.shutdown andalso (NewState#st.waiters =:= []) of
-        true ->
-            {stop, normal, NewState};
-        false ->
-            maybe_restart_updater(NewState),
-            {noreply, NewState}
-    end;
-handle_cast({new_state, NewIdxState}, State) ->
-    #st{
-        mod=Mod,
-        idx_state=OldIdxState,
-        commit_delay=Delay
-    } = State,
-    assert_signature_match(Mod, OldIdxState, NewIdxState),
-    CurrSeq = Mod:get(update_seq, NewIdxState),
-    Args = [
-        Mod:get(db_name, NewIdxState),
-        Mod:get(idx_name, NewIdxState),
-        CurrSeq
-    ],
-    ?LOG_DEBUG("Updated index for db: ~s idx: ~s seq: ~B", Args),
-    Rest = send_replies(State#st.waiters, CurrSeq, NewIdxState),
-    case State#st.committed of
-        true -> erlang:send_after(Delay, self(), commit);
-        false -> ok
-    end,
-    {noreply, State#st{
-        idx_state=NewIdxState,
-        waiters=Rest,
-        committed=false
-    }};
-handle_cast({update_error, Error}, State) ->
-    send_all(State#st.waiters, Error),
-    {noreply, State#st{waiters=[]}};
-handle_cast(stop, State) ->
-    {stop, normal, State};
-handle_cast(delete, State) ->
-    #st{mod=Mod, idx_state=IdxState} = State,
-    ok = Mod:delete(IdxState),
-    {stop, normal, State};
-handle_cast(ddoc_updated, State) ->
-    #st{mod = Mod, idx_state = IdxState, waiters = Waiters} = State,
-    DbName = Mod:get(db_name, IdxState),
-    DDocId = Mod:get(idx_name, IdxState),
-    Shutdown = couch_util:with_db(DbName, fun(Db) ->
-        case couch_db:open_doc(Db, DDocId, [ejson_body]) of
-            {not_found, deleted} ->
-                true;
-            {ok, DDoc} ->
-                {ok, NewIdxState} = Mod:init(Db, DDoc),
-                Mod:get(signature, NewIdxState) =/= Mod:get(signature, IdxState)
-        end
-    end),
-    case Shutdown of
-        true ->
-            case Waiters of
-                [] ->
-                    {stop, normal, State};
-                _ ->
-                    {noreply, State#st{shutdown = true}}
-            end;
-        false ->
-            {noreply, State#st{shutdown = false}}
-    end;
-handle_cast(_Mesg, State) ->
-    {stop, unhandled_cast, State}.
-
-
-handle_info(commit, #st{committed=true}=State) ->
-    {noreply, State};
-handle_info(commit, State) ->
-    #st{mod=Mod, idx_state=IdxState, commit_delay=Delay} = State,
-    DbName = Mod:get(db_name, IdxState),
-    GetCommSeq = fun(Db) -> couch_db:get_committed_update_seq(Db) end,
-    CommittedSeq = couch_util:with_db(DbName, GetCommSeq),
-    case CommittedSeq >= Mod:get(update_seq, IdxState) of
-        true ->
-            % Commit the updates
-            ok = Mod:commit(IdxState),
-            {noreply, State#st{committed=true}};
-        _ ->
-            % We can't commit the header because the database seq that's
-            % fully committed to disk is still behind us. If we committed
-            % now and the database lost those changes our view could be
-            % forever out of sync with the database. But a crash before we
-            % commit these changes, no big deal, we only lose incremental
-            % changes since last committal.
-            erlang:send_after(Delay, self(), commit),
-            {noreply, State}
-    end;
-handle_info({'DOWN', _, _, _Pid, _}, #st{mod=Mod, idx_state=IdxState}=State) ->
-    Args = [Mod:get(db_name, IdxState), Mod:get(idx_name, IdxState)],
-    ?LOG_INFO("Index shutdown by monitor notice for db: ~s idx: ~s", Args),
-    catch send_all(State#st.waiters, shutdown),
-    {stop, normal, State#st{waiters=[]}}.
-
-
-code_change(_OldVsn, State, _Extra) ->
-    {ok, State}.
-
-
-maybe_restart_updater(#st{waiters=[]}) ->
-    ok;
-maybe_restart_updater(#st{mod=Mod, idx_state=IdxState}=State) ->
-    couch_util:with_db(Mod:get(db_name, IdxState), fun(Db) ->
-        UpdateSeq = couch_db:get_update_seq(Db),
-        CommittedSeq = couch_db:get_committed_update_seq(Db),
-        CanUpdate = UpdateSeq > CommittedSeq,
-        UOpts = Mod:get(update_options, IdxState),
-        case CanUpdate and lists:member(committed_only, UOpts) of
-            true -> couch_db:ensure_full_commit(Db);
-            false -> ok
-        end
-    end),
-    couch_index_updater:run(State#st.updater, IdxState).
-
-
-send_all(Waiters, Reply) ->
-    [gen_server:reply(From, Reply) || {From, _} <- Waiters].
-
-
-send_replies(Waiters, UpdateSeq, IdxState) ->
-    Pred = fun({_, S}) -> S =< UpdateSeq end,
-    {ToSend, Remaining} = lists:partition(Pred, Waiters),
-    [gen_server:reply(From, {ok, IdxState}) || {From, _} <- ToSend],
-    Remaining.
-
-assert_signature_match(Mod, OldIdxState, NewIdxState) ->
-    case {Mod:get(signature, OldIdxState), Mod:get(signature, NewIdxState)} of
-        {Sig, Sig} -> ok;
-        _ -> erlang:error(signature_mismatch)
-    end.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_index/src/couch_index_api.erl
----------------------------------------------------------------------
diff --git a/apps/couch_index/src/couch_index_api.erl b/apps/couch_index/src/couch_index_api.erl
deleted file mode 100644
index 9d3a67c..0000000
--- a/apps/couch_index/src/couch_index_api.erl
+++ /dev/null
@@ -1,54 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_index_api).
-
-get(Field, State) ->
-    ok.
-
-init(Db, Ddoc) ->
-    ok.
-
-open(Db, State) ->
-    ok.
-
-close(State) ->
-    ok.
-
-delete(State) ->
-    ok.
-
-reset(State) ->
-    ok.
-
-
-start_update(State, PurgedState, NumChanges) ->
-    {ok, State}.
-
-purge(Db, PurgeSeq, PurgedIdRevs, State) ->
-    ok.
-
-process_doc(Doc, Seq, State) ->
-    ok.
-
-finish_update(State) ->
-    {ok, State}.
-
-commit(State) ->
-    ok.
-
-
-compact(Parent, State, Opts) ->
-    ok.
-
-swap_compacted(OldState, NewState) ->
-    ok.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_index/src/couch_index_app.erl
----------------------------------------------------------------------
diff --git a/apps/couch_index/src/couch_index_app.erl b/apps/couch_index/src/couch_index_app.erl
deleted file mode 100644
index 6bafdcb..0000000
--- a/apps/couch_index/src/couch_index_app.erl
+++ /dev/null
@@ -1,27 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_index_app).
-
--behaviour(application).
-
--include_lib("couch/include/couch_db.hrl").
-
--export([start/2, stop/1]).
-
-start(_Type, _Args) ->
-    couch_util:start_app_deps(couch_index),
-    couch_index_sup:start_link().
-
-
-stop(_) ->
-    ok.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_index/src/couch_index_compactor.erl
----------------------------------------------------------------------
diff --git a/apps/couch_index/src/couch_index_compactor.erl b/apps/couch_index/src/couch_index_compactor.erl
deleted file mode 100644
index 6e9fb2e..0000000
--- a/apps/couch_index/src/couch_index_compactor.erl
+++ /dev/null
@@ -1,113 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_index_compactor).
--behaviour(gen_server).
-
-
-%% API
--export([start_link/2, run/2, cancel/1, is_running/1]).
-
-%% gen_server callbacks
--export([init/1, terminate/2, code_change/3]).
--export([handle_call/3, handle_cast/2, handle_info/2]).
-
-
--include_lib("couch/include/couch_db.hrl").
-
--record(st, {
-    idx,
-    mod,
-    pid
-}).
-
-
-start_link(Index, Module) ->
-    gen_server:start_link(?MODULE, {Index, Module}, []).
-
-
-run(Pid, IdxState) ->
-    gen_server:call(Pid, {compact, IdxState}).
-
-
-cancel(Pid) ->
-    gen_server:call(Pid, cancel).
-
-
-is_running(Pid) ->
-    gen_server:call(Pid, is_running).
-
-
-init({Index, Module}) ->
-    process_flag(trap_exit, true),
-    {ok, #st{idx=Index, mod=Module}}.
-
-
-terminate(_Reason, State) ->
-    couch_util:shutdown_sync(State#st.pid),
-    ok.
-
-
-handle_call({compact, _}, _From, #st{pid=Pid}=State) when is_pid(Pid) ->
-    {reply, {ok, Pid}, State};
-handle_call({compact, IdxState}, _From, #st{idx=Idx}=State) ->
-    Pid = spawn_link(fun() -> compact(Idx, State#st.mod, IdxState) end),
-    {reply, {ok, Pid}, State#st{pid=Pid}};
-handle_call(cancel, _From, #st{pid=undefined}=State) ->
-    {reply, ok, State};
-handle_call(cancel, _From, #st{pid=Pid}=State) ->
-    unlink(Pid),
-    exit(Pid, kill),
-    {reply, ok, State#st{pid=undefined}};
-handle_call(is_running, _From, #st{pid=Pid}=State) when is_pid(Pid) ->
-    {reply, true, State};
-handle_call(is_running, _From, State) ->
-    {reply, false, State}.
-
-
-handle_cast(_Mesg, State) ->
-    {stop, unknown_cast, State}.
-
-
-handle_info({'EXIT', Pid, normal}, #st{pid=Pid}=State) ->
-    {noreply, State#st{pid=undefined}};
-handle_info({'EXIT', _Pid, normal}, State) ->
-    {noreply, State};
-handle_info({'EXIT', Pid, _Reason}, #st{idx=Pid}=State) ->
-    {stop, normal, State};
-handle_info(_Mesg, State) ->
-    {stop, unknown_info, State}.
-
-
-code_change(_OldVsn, State, _Extra) ->
-    {ok, State}.
-
-
-compact(Parent, Mod, IdxState) ->
-    compact(Parent, Mod, IdxState, []).
-
-compact(Idx, Mod, IdxState, Opts) ->
-    DbName = Mod:get(db_name, IdxState),
-    Args = [DbName, Mod:get(idx_name, IdxState)],
-    ?LOG_INFO("Compaction started for db: ~s idx: ~s", Args),
-    {ok, NewIdxState} = couch_util:with_db(DbName, fun(Db) ->
-        Mod:compact(Db, IdxState, Opts)
-    end),
-    ok = Mod:commit(NewIdxState),
-    case gen_server:call(Idx, {compacted, NewIdxState}) of
-        recompact ->
-            ?LOG_INFO("Compaction restarting for db: ~s idx: ~s", Args),
-            compact(Idx, Mod, NewIdxState, [recompact]);
-        _ ->
-            ?LOG_INFO("Compaction finished for db: ~s idx: ~s", Args),
-            ok
-    end.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_index/src/couch_index_server.erl
----------------------------------------------------------------------
diff --git a/apps/couch_index/src/couch_index_server.erl b/apps/couch_index/src/couch_index_server.erl
deleted file mode 100644
index 7a7bd55..0000000
--- a/apps/couch_index/src/couch_index_server.erl
+++ /dev/null
@@ -1,201 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_index_server).
--behaviour(gen_server).
-
--export([start_link/0, get_index/4, get_index/3, get_index/2]).
--export([config_change/2, update_notify/1]).
-
--export([init/1, terminate/2, code_change/3]).
--export([handle_call/3, handle_cast/2, handle_info/2]).
-
--include_lib("couch/include/couch_db.hrl").
-
--define(BY_SIG, couchdb_indexes_by_sig).
--define(BY_PID, couchdb_indexes_by_pid).
--define(BY_DB, couchdb_indexes_by_db).
-
-
--record(st, {root_dir}).
-
-start_link() ->
-    gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
-
-
-get_index(Module, DbName, DDoc) ->
-    get_index(Module, DbName, DDoc, nil).
-
-
-get_index(Module, DbName, DDoc, Fun) when is_binary(DbName) ->
-    couch_util:with_db(DbName, fun(Db) ->
-        get_index(Module, Db, DDoc, Fun)
-    end);
-get_index(Module, Db, DDoc, Fun) when is_binary(DDoc) ->
-    case couch_db:open_doc(Db, DDoc, [ejson_body]) of
-        {ok, Doc} -> get_index(Module, Db, Doc, Fun);
-        Error -> Error
-    end;
-get_index(Module, Db, DDoc, Fun) when is_function(Fun, 1) ->
-    {ok, InitState} = Module:init(Db, DDoc),
-    {ok, FunResp} = Fun(InitState),
-    {ok, Pid} = get_index(Module, InitState),
-    {ok, Pid, FunResp};
-get_index(Module, Db, DDoc, _Fun) ->
-    {ok, InitState} = Module:init(Db, DDoc),
-    get_index(Module, InitState).
-
-
-get_index(Module, IdxState) ->
-    DbName = Module:get(db_name, IdxState),
-    Sig = Module:get(signature, IdxState),
-    case ets:lookup(?BY_SIG, {DbName, Sig}) of
-        [{_, Pid}] when is_pid(Pid) ->
-            {ok, Pid};
-        _ ->
-            Args = {Module, IdxState, DbName, Sig},
-            gen_server:call(?MODULE, {get_index, Args}, infinity)
-    end.
-
-
-init([]) ->
-    process_flag(trap_exit, true),
-    couch_config:register(fun ?MODULE:config_change/2),
-    ets:new(?BY_SIG, [protected, set, named_table]),
-    ets:new(?BY_PID, [private, set, named_table]),
-    ets:new(?BY_DB, [protected, bag, named_table]),
-    couch_db_update_notifier:start_link(fun ?MODULE:update_notify/1),
-    RootDir = couch_index_util:root_dir(),
-    couch_file:init_delete_dir(RootDir),
-    {ok, #st{root_dir=RootDir}}.
-
-
-terminate(_Reason, _State) ->
-    Pids = [Pid || {Pid, _} <- ets:tab2list(?BY_PID)],
-    lists:map(fun couch_util:shutdown_sync/1, Pids),
-    ok.
-
-
-handle_call({get_index, {_Mod, _IdxState, DbName, Sig}=Args}, From, State) ->
-    case ets:lookup(?BY_SIG, {DbName, Sig}) of
-        [] ->
-            spawn_link(fun() -> new_index(Args) end),
-            ets:insert(?BY_SIG, {{DbName, Sig}, [From]}),
-            {noreply, State};
-        [{_, Waiters}] when is_list(Waiters) ->
-            ets:insert(?BY_SIG, {{DbName, Sig}, [From | Waiters]}),
-            {noreply, State};
-        [{_, Pid}] when is_pid(Pid) ->
-            {reply, {ok, Pid}, State}
-    end;
-handle_call({async_open, {DbName, DDocId, Sig}, {ok, Pid}}, _From, State) ->
-    [{_, Waiters}] = ets:lookup(?BY_SIG, {DbName, Sig}),
-    [gen_server:reply(From, {ok, Pid}) || From <- Waiters],
-    link(Pid),
-    add_to_ets(DbName, Sig, DDocId, Pid),
-    {reply, ok, State};
-handle_call({async_error, {DbName, _DDocId, Sig}, Error}, _From, State) ->
-    [{_, Waiters}] = ets:lookup(?BY_SIG, {DbName, Sig}),
-    [gen_server:reply(From, Error) || From <- Waiters],
-    ets:delete(?BY_SIG, {DbName, Sig}),
-    {reply, ok, State};
-handle_call({reset_indexes, DbName}, _From, State) ->
-    reset_indexes(DbName, State#st.root_dir),
-    {reply, ok, State}.
-
-
-handle_cast({reset_indexes, DbName}, State) ->
-    reset_indexes(DbName, State#st.root_dir),
-    {noreply, State}.
-
-
-handle_info({'EXIT', Pid, Reason}, Server) ->
-    case ets:lookup(?BY_PID, Pid) of
-        [{Pid, {DbName, Sig}}] ->
-            [{DbName, {DDocId, Sig}}] =
-                ets:match_object(?BY_DB, {DbName, {'$1', Sig}}),
-            rem_from_ets(DbName, Sig, DDocId, Pid);
-        [] when Reason /= normal ->
-            exit(Reason);
-        _Else ->
-            ok
-    end,
-    {noreply, Server}.
-
-
-code_change(_OldVsn, State, _Extra) ->
-    {ok, State}.
-
-
-new_index({Mod, IdxState, DbName, Sig}) ->
-    DDocId = Mod:get(idx_name, IdxState),
-    case couch_index:start_link({Mod, IdxState}) of
-        {ok, Pid} ->
-            ok = gen_server:call(
-                ?MODULE, {async_open, {DbName, DDocId, Sig}, {ok, Pid}}),
-            unlink(Pid);
-        Error ->
-            ok = gen_server:call(
-                ?MODULE, {async_error, {DbName, DDocId, Sig}, Error})
-    end.
-
-
-reset_indexes(DbName, Root) ->
-    % shutdown all the updaters and clear the files, the db got changed
-    Fun = fun({_, {DDocId, Sig}}) ->
-        [{_, Pid}] = ets:lookup(?BY_SIG, {DbName, Sig}),
-        MRef = erlang:monitor(process, Pid),
-        gen_server:cast(Pid, delete),
-        receive {'DOWN', MRef, _, _, _} -> ok end,
-        rem_from_ets(DbName, Sig, DDocId, Pid)
-    end,
-    lists:foreach(Fun, ets:lookup(?BY_DB, DbName)),
-    Path = couch_index_util:index_dir("", DbName),
-    couch_file:nuke_dir(Root, Path).
-
-
-add_to_ets(DbName, Sig, DDocId, Pid) ->
-    ets:insert(?BY_SIG, {{DbName, Sig}, Pid}),
-    ets:insert(?BY_PID, {Pid, {DbName, Sig}}),
-    ets:insert(?BY_DB, {DbName, {DDocId, Sig}}).
-
-
-rem_from_ets(DbName, Sig, DDocId, Pid) ->
-    ets:delete(?BY_SIG, {DbName, Sig}),
-    ets:delete(?BY_PID, Pid),
-    ets:delete_object(?BY_DB, {DbName, {DDocId, Sig}}).
-
-
-config_change("couchdb", "view_index_dir") ->
-    exit(whereis(?MODULE), config_change);
-config_change("couchdb", "index_dir") ->
-    exit(whereis(?MODULE), config_change).
-
-
-update_notify({deleted, DbName}) ->
-    gen_server:cast(?MODULE, {reset_indexes, DbName});
-update_notify({created, DbName}) ->
-    gen_server:cast(?MODULE, {reset_indexes, DbName});
-update_notify({ddoc_updated, {DbName, DDocId}}) ->
-    lists:foreach(
-        fun({_DbName, {_DDocId, Sig}}) ->
-            case ets:lookup(?BY_SIG, {DbName, Sig}) of
-                [{_, IndexPid}] ->
-                    (catch gen_server:cast(IndexPid, ddoc_updated));
-                [] ->
-                    ok
-            end
-        end,
-        ets:match_object(?BY_DB, {DbName, {DDocId, '$1'}}));
-update_notify(_) ->
-    ok.
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_index/src/couch_index_sup.erl
----------------------------------------------------------------------
diff --git a/apps/couch_index/src/couch_index_sup.erl b/apps/couch_index/src/couch_index_sup.erl
deleted file mode 100644
index d7b1033..0000000
--- a/apps/couch_index/src/couch_index_sup.erl
+++ /dev/null
@@ -1,30 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_index_sup).
--behaviour(supervisor).
-
--export([start_link/0]).
--export([init/1]).
-
-
-%% Helper macro for declaring children of supervisor
--define(CHILD(I), {I, {I, start_link, []}, permanent, 5000, worker, [I]}).
-
-start_link() ->
-    supervisor:start_link({local, ?MODULE}, ?MODULE, []).
-
-
-init([]) ->
-    Server = ?CHILD(couch_index_server),
-    {ok, {{one_for_one, 10, 3600}, [Server]}}.
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_index/src/couch_index_updater.erl
----------------------------------------------------------------------
diff --git a/apps/couch_index/src/couch_index_updater.erl b/apps/couch_index/src/couch_index_updater.erl
deleted file mode 100644
index 9f54a56..0000000
--- a/apps/couch_index/src/couch_index_updater.erl
+++ /dev/null
@@ -1,200 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_index_updater).
--behaviour(gen_server).
-
-
-%% API
--export([start_link/2, run/2, is_running/1, update/2, restart/2]).
-
-%% gen_server callbacks
--export([init/1, terminate/2, code_change/3]).
--export([handle_call/3, handle_cast/2, handle_info/2]).
-
--include_lib("couch/include/couch_db.hrl").
-
--record(st, {
-    idx,
-    mod,
-    pid=nil
-}).
-
-
-start_link(Index, Module) ->
-    gen_server:start_link(?MODULE, {Index, Module}, []).
-
-
-run(Pid, IdxState) ->
-    gen_server:call(Pid, {update, IdxState}).
-
-
-is_running(Pid) ->
-    gen_server:call(Pid, is_running).
-
-
-update(Mod, State) ->
-    update(nil, Mod, State).
-
-
-restart(Pid, IdxState) ->
-    gen_server:call(Pid, {restart, IdxState}).
-
-
-init({Index, Module}) ->
-    process_flag(trap_exit, true),
-    {ok, #st{idx=Index, mod=Module}}.
-
-
-terminate(_Reason, State) ->
-    couch_util:shutdown_sync(State#st.pid),
-    ok.
-
-
-handle_call({update, _IdxState}, _From, #st{pid=Pid}=State) when is_pid(Pid) ->
-    {reply, ok, State};
-handle_call({update, IdxState}, _From, #st{idx=Idx, mod=Mod}=State) ->
-    Args = [Mod:get(db_name, IdxState), Mod:get(idx_name, IdxState)],
-    ?LOG_INFO("Starting index update for db: ~s idx: ~s", Args),
-    Pid = spawn_link(fun() -> update(Idx, Mod, IdxState) end),
-    {reply, ok, State#st{pid=Pid}};
-handle_call({restart, IdxState}, _From, #st{idx=Idx, mod=Mod}=State) ->
-    Args = [Mod:get(db_name, IdxState), Mod:get(idx_name, IdxState)],
-    ?LOG_INFO("Restarting index update for db: ~s idx: ~s", Args),
-    case is_pid(State#st.pid) of
-        true -> couch_util:shutdown_sync(State#st.pid);
-        _ -> ok
-    end,
-    Pid = spawn_link(fun() -> update(Idx, State#st.mod, IdxState) end),
-    {reply, ok, State#st{pid=Pid}};
-handle_call(is_running, _From, #st{pid=Pid}=State) when is_pid(Pid) ->
-    {reply, true, State};
-handle_call(is_running, _From, State) ->
-    {reply, false, State}.
-
-
-handle_cast(_Mesg, State) ->
-    {stop, unknown_cast, State}.
-
-
-handle_info({'EXIT', _, {updated, Pid, IdxState}}, #st{pid=Pid}=State) ->
-    Mod = State#st.mod,
-    Args = [Mod:get(db_name, IdxState), Mod:get(idx_name, IdxState)],
-    ?LOG_INFO("Index update finished for db: ~s idx: ~s", Args),
-    ok = gen_server:cast(State#st.idx, {updated, IdxState}),
-    {noreply, State#st{pid=undefined}};
-handle_info({'EXIT', _, {reset, Pid}}, #st{idx=Idx, pid=Pid}=State) ->
-    {ok, NewIdxState} = gen_server:call(State#st.idx, reset),
-    Pid2 = spawn_link(fun() -> update(Idx, State#st.mod, NewIdxState) end),
-    {noreply, State#st{pid=Pid2}};
-handle_info({'EXIT', Pid, normal}, #st{pid=Pid}=State) ->
-    {noreply, State#st{pid=undefined}};
-handle_info({'EXIT', Pid, {{nocatch, Error}, _Trace}}, State) ->
-    handle_info({'EXIT', Pid, Error}, State);
-handle_info({'EXIT', Pid, Error}, #st{pid=Pid}=State) ->
-    ok = gen_server:cast(State#st.idx, {update_error, Error}),
-    {noreply, State#st{pid=undefined}};
-handle_info({'EXIT', Pid, _Reason}, #st{idx=Pid}=State) ->
-    {stop, normal, State};
-handle_info({'EXIT', _Pid, normal}, State) ->
-    {noreply, State};
-handle_info(_Mesg, State) ->
-    {stop, unknown_info, State}.
-
-
-code_change(_OldVsn, State, _Extra) ->
-    {ok, State}.
-
-
-update(Idx, Mod, IdxState) ->
-    DbName = Mod:get(db_name, IdxState),
-    CurrSeq = Mod:get(update_seq, IdxState),
-    UpdateOpts = Mod:get(update_options, IdxState),
-    CommittedOnly = lists:member(committed_only, UpdateOpts),
-    IncludeDesign = lists:member(include_design, UpdateOpts),
-    DocOpts = case lists:member(local_seq, UpdateOpts) of
-        true -> [conflicts, deleted_conflicts, local_seq];
-        _ -> [conflicts, deleted_conflicts]
-    end,
-
-    couch_util:with_db(DbName, fun(Db) ->
-        DbUpdateSeq = couch_db:get_update_seq(Db),
-        DbCommittedSeq = couch_db:get_committed_update_seq(Db),
-
-        PurgedIdxState = case purge_index(Db, Mod, IdxState) of
-            {ok, IdxState0} -> IdxState0;
-            reset -> exit({reset, self()})
-        end,
-
-        NumChanges = couch_db:count_changes_since(Db, CurrSeq),
-
-        LoadDoc = fun(DocInfo) ->
-            #doc_info{
-                id=DocId,
-                high_seq=Seq,
-                revs=[#rev_info{deleted=Deleted} | _]
-            } = DocInfo,
-
-            case {IncludeDesign, DocId} of
-                {false, <<"_design/", _/binary>>} ->
-                    {nil, Seq};
-                _ when Deleted ->
-                    {#doc{id=DocId, deleted=true}, Seq};
-                _ ->
-                    {ok, Doc} = couch_db:open_doc_int(Db, DocInfo, DocOpts),
-                    {Doc, Seq}
-            end
-        end,
-
-        Proc = fun(DocInfo, _, {IdxStateAcc, _}) ->
-            HighSeq = DocInfo#doc_info.high_seq,
-            case CommittedOnly and (HighSeq > DbCommittedSeq) of
-                true ->
-                    {stop, {IdxStateAcc, false}};
-                false ->
-                    {Doc, Seq} = LoadDoc(DocInfo),
-                    {ok, NewSt} = Mod:process_doc(Doc, Seq, IdxStateAcc),
-                    {ok, {NewSt, true}}
-            end
-        end,
-
-        {ok, InitIdxState} = Mod:start_update(Idx, PurgedIdxState, NumChanges),
-        Acc0 = {InitIdxState, true},
-        {ok, _, Acc} = couch_db:enum_docs_since(Db, CurrSeq, Proc, Acc0, []),
-        {ProcIdxSt, SendLast} = Acc,
-
-        % If we didn't bail due to hitting the last committed seq we need
-        % to send our last update_seq through.
-        {ok, LastIdxSt} = case SendLast of
-            true ->
-                Mod:process_doc(nil, DbUpdateSeq, ProcIdxSt);
-            _ ->
-                {ok, ProcIdxSt}
-        end,
-
-        {ok, FinalIdxState} = Mod:finish_update(LastIdxSt),
-        exit({updated, self(), FinalIdxState})
-    end).
-
-
-purge_index(Db, Mod, IdxState) ->
-    DbPurgeSeq = couch_db:get_purge_seq(Db),
-    IdxPurgeSeq = Mod:get(purge_seq, IdxState),
-    if
-        DbPurgeSeq == IdxPurgeSeq ->
-            {ok, IdxState};
-        DbPurgeSeq == IdxPurgeSeq + 1 ->
-            {ok, PurgedIdRevs} = couch_db:get_last_purged(Db),
-            Mod:purge(Db, DbPurgeSeq, PurgedIdRevs, IdxState);
-        true ->
-            reset
-    end.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_index/src/couch_index_util.erl
----------------------------------------------------------------------
diff --git a/apps/couch_index/src/couch_index_util.erl b/apps/couch_index/src/couch_index_util.erl
deleted file mode 100644
index c833920..0000000
--- a/apps/couch_index/src/couch_index_util.erl
+++ /dev/null
@@ -1,77 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_index_util).
-
--export([root_dir/0, index_dir/2, index_file/3]).
--export([load_doc/3, sort_lib/1, hexsig/1]).
-
--include_lib("couch/include/couch_db.hrl").
-
-root_dir() ->
-  couch_config:get("couchdb", "view_index_dir").
-
-
-index_dir(Module, DbName) when is_binary(DbName) ->
-    DbDir = "." ++ binary_to_list(DbName) ++ "_design",
-    filename:join([root_dir(), DbDir, Module]);
-index_dir(Module, #db{}=Db) ->
-    index_dir(Module, couch_db:name(Db)).
-
-
-index_file(Module, DbName, FileName) ->
-    filename:join(index_dir(Module, DbName), FileName).
-
-
-load_doc(Db, #doc_info{}=DI, Opts) ->
-    Deleted = lists:member(deleted, Opts),
-    case (catch couch_db:open_doc(Db, DI, Opts)) of
-        {ok, #doc{deleted=false}=Doc} -> Doc;
-        {ok, #doc{deleted=true}=Doc} when Deleted -> Doc;
-        _Else -> null
-    end;
-load_doc(Db, {DocId, Rev}, Opts) ->
-    case (catch load_doc(Db, DocId, Rev, Opts)) of
-        #doc{deleted=false} = Doc -> Doc;
-        _ -> null
-    end.
-
-
-load_doc(Db, DocId, Rev, Options) ->
-    case Rev of
-        nil -> % open most recent rev
-            case (catch couch_db:open_doc(Db, DocId, Options)) of
-                {ok, Doc} -> Doc;
-                _Error -> null
-            end;
-        _ -> % open a specific rev (deletions come back as stubs)
-            case (catch couch_db:open_doc_revs(Db, DocId, [Rev], Options)) of
-                {ok, [{ok, Doc}]} -> Doc;
-                {ok, [{{not_found, missing}, Rev}]} -> null;
-                {ok, [_Else]} -> null
-            end
-    end.
-
-
-sort_lib({Lib}) ->
-    sort_lib(Lib, []).
-sort_lib([], LAcc) ->
-    lists:keysort(1, LAcc);
-sort_lib([{LName, {LObj}}|Rest], LAcc) ->
-    LSorted = sort_lib(LObj, []), % descend into nested object
-    sort_lib(Rest, [{LName, LSorted}|LAcc]);
-sort_lib([{LName, LCode}|Rest], LAcc) ->
-    sort_lib(Rest, [{LName, LCode}|LAcc]).
-
-
-hexsig(Sig) ->
-    couch_util:to_hex(binary_to_list(Sig)).

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_mrview/include/couch_mrview.hrl
----------------------------------------------------------------------
diff --git a/apps/couch_mrview/include/couch_mrview.hrl b/apps/couch_mrview/include/couch_mrview.hrl
deleted file mode 100644
index e4ec66d..0000000
--- a/apps/couch_mrview/include/couch_mrview.hrl
+++ /dev/null
@@ -1,81 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--record(mrst, {
-    sig=nil,
-    fd=nil,
-    refc,
-    db_name,
-    idx_name,
-    language,
-    design_opts=[],
-    lib,
-    views,
-    id_btree=nil,
-    update_seq=0,
-    purge_seq=0,
-
-    first_build,
-    partial_resp_pid,
-    doc_acc,
-    doc_queue,
-    write_queue,
-    qserver=nil
-}).
-
-
--record(mrview, {
-    id_num,
-    update_seq=0,
-    purge_seq=0,
-    map_names=[],
-    reduce_funs=[],
-    def,
-    btree=nil,
-    options=[]
-}).
-
-
--record(mrheader, {
-    seq=0,
-    purge_seq=0,
-    id_btree_state=nil,
-    view_states=nil
-}).
-
-
--record(mrargs, {
-    view_type,
-    reduce,
-
-    preflight_fun,
-
-    start_key,
-    start_key_docid,
-    end_key,
-    end_key_docid,
-    keys,
-
-    direction = fwd,
-    limit = 16#10000000,
-    skip = 0,
-    group_level = 0,
-    stale = false,
-    inclusive_end = true,
-    include_docs = false,
-    doc_options = [],
-    update_seq=false,
-    conflicts,
-    callback,
-    list,
-    extra = []
-}).

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_mrview/src/couch_mrview.app.src
----------------------------------------------------------------------
diff --git a/apps/couch_mrview/src/couch_mrview.app.src b/apps/couch_mrview/src/couch_mrview.app.src
deleted file mode 100644
index cce2c97..0000000
--- a/apps/couch_mrview/src/couch_mrview.app.src
+++ /dev/null
@@ -1,28 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
-{application, couch_mrview, [
-    {description, "CouchDB Map/Reduce Views"},
-    {vsn, "1.3.0"},
-    {modules, [
-        couch_mrview,
-        couch_mrview_compactor,
-        couch_mrview_http,
-        couch_mrview_index,
-        couch_mrview_show,
-        couch_mrview_test_util,
-        couch_mrview_updater,
-        couch_mrview_util
-    ]},
-    {registered, []},
-    {applications, [kernel, stdlib, couch_index]}
-]}.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch_mrview/src/couch_mrview.erl
----------------------------------------------------------------------
diff --git a/apps/couch_mrview/src/couch_mrview.erl b/apps/couch_mrview/src/couch_mrview.erl
deleted file mode 100644
index d31ed18..0000000
--- a/apps/couch_mrview/src/couch_mrview.erl
+++ /dev/null
@@ -1,387 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_mrview).
-
--export([query_all_docs/2, query_all_docs/4]).
--export([query_view/3, query_view/4, query_view/6]).
--export([get_info/2]).
--export([compact/2, compact/3, cancel_compaction/2]).
--export([cleanup/1]).
-
--include_lib("couch/include/couch_db.hrl").
--include_lib("couch_mrview/include/couch_mrview.hrl").
-
--record(mracc, {
-    db,
-    meta_sent=false,
-    total_rows,
-    offset,
-    limit,
-    skip,
-    group_level,
-    doc_info,
-    callback,
-    user_acc,
-    last_go=ok,
-    reduce_fun,
-    update_seq,
-    args
-}).
-
-
-query_all_docs(Db, Args) ->
-    query_all_docs(Db, Args, fun default_cb/2, []).
-
-
-query_all_docs(Db, Args, Callback, Acc) when is_list(Args) ->
-    query_all_docs(Db, to_mrargs(Args), Callback, Acc);
-query_all_docs(Db, Args0, Callback, Acc) ->
-    Sig = couch_util:with_db(Db, fun(WDb) ->
-        {ok, Info} = couch_db:get_db_info(WDb),
-        couch_index_util:hexsig(couch_util:md5(term_to_binary(Info)))
-    end),
-    Args1 = Args0#mrargs{view_type=map},
-    Args2 = couch_mrview_util:validate_args(Args1),
-    {ok, Acc1} = case Args2#mrargs.preflight_fun of
-        PFFun when is_function(PFFun, 2) -> PFFun(Sig, Acc);
-        _ -> {ok, Acc}
-    end,
-    all_docs_fold(Db, Args2, Callback, Acc1).
-
-
-query_view(Db, DDoc, VName) ->
-    query_view(Db, DDoc, VName, #mrargs{}).
-
-
-query_view(Db, DDoc, VName, Args) when is_list(Args) ->
-    query_view(Db, DDoc, VName, to_mrargs(Args), fun default_cb/2, []);
-query_view(Db, DDoc, VName, Args) ->
-    query_view(Db, DDoc, VName, Args, fun default_cb/2, []).
-
-
-query_view(Db, DDoc, VName, Args, Callback, Acc) when is_list(Args) ->
-    query_view(Db, DDoc, VName, to_mrargs(Args), Callback, Acc);
-query_view(Db, DDoc, VName, Args0, Callback, Acc0) ->
-    {ok, VInfo, Sig, Args} = couch_mrview_util:get_view(Db, DDoc, VName, Args0),
-    {ok, Acc1} = case Args#mrargs.preflight_fun of
-        PFFun when is_function(PFFun, 2) -> PFFun(Sig, Acc0);
-        _ -> {ok, Acc0}
-    end,
-    query_view(Db, VInfo, Args, Callback, Acc1).
-
-
-query_view(Db, {Type, View}, Args, Callback, Acc) ->
-    case Type of
-        map -> map_fold(Db, View, Args, Callback, Acc);
-        red -> red_fold(Db, View, Args, Callback, Acc)
-    end.
-
-
-get_info(Db, DDoc) ->
-    {ok, Pid} = couch_index_server:get_index(couch_mrview_index, Db, DDoc),
-    couch_index:get_info(Pid).
-
-
-compact(Db, DDoc) ->
-    compact(Db, DDoc, []).
-
-
-compact(Db, DDoc, Opts) ->
-    {ok, Pid} = couch_index_server:get_index(couch_mrview_index, Db, DDoc),
-    couch_index:compact(Pid, Opts).
-
-
-cancel_compaction(Db, DDoc) ->
-    {ok, IPid} = couch_index_server:get_index(couch_mrview_index, Db, DDoc),
-    {ok, CPid} = couch_index:get_compactor_pid(IPid),
-    ok = couch_index_compactor:cancel(CPid),
-
-    % Cleanup the compaction file if it exists
-    {ok, #mrst{sig=Sig, db_name=DbName}} = couch_index:get_state(IPid, 0),
-    couch_mrview_util:delete_compaction_file(DbName, Sig),
-    ok.
-
-
-cleanup(Db) ->
-    couch_mrview_cleanup:run(Db).
-
-
-all_docs_fold(Db, #mrargs{keys=undefined}=Args, Callback, UAcc) ->
-    {ok, Info} = couch_db:get_db_info(Db),
-    Total = couch_util:get_value(doc_count, Info),
-    UpdateSeq = couch_db:get_update_seq(Db),
-    Acc = #mracc{
-        db=Db,
-        total_rows=Total,
-        limit=Args#mrargs.limit,
-        skip=Args#mrargs.skip,
-        callback=Callback,
-        user_acc=UAcc,
-        reduce_fun=fun couch_mrview_util:all_docs_reduce_to_count/1,
-        update_seq=UpdateSeq,
-        args=Args
-    },
-    [Opts] = couch_mrview_util:all_docs_key_opts(Args),
-    {ok, Offset, FinalAcc} = couch_db:enum_docs(Db, fun map_fold/3, Acc, Opts),
-    finish_fold(FinalAcc, [{total, Total}, {offset, Offset}]);
-all_docs_fold(Db, #mrargs{direction=Dir, keys=Keys0}=Args, Callback, UAcc) ->
-    {ok, Info} = couch_db:get_db_info(Db),
-    Total = couch_util:get_value(doc_count, Info),
-    UpdateSeq = couch_db:get_update_seq(Db),
-    Acc = #mracc{
-        db=Db,
-        total_rows=Total,
-        limit=Args#mrargs.limit,
-        skip=Args#mrargs.skip,
-        callback=Callback,
-        user_acc=UAcc,
-        reduce_fun=fun couch_mrview_util:all_docs_reduce_to_count/1,
-        update_seq=UpdateSeq,
-        args=Args
-    },
-    % Backwards compatibility hack. The old _all_docs iterates keys
-    % in reverse if descending=true was passed. Here we'll just
-    % reverse the list instead.
-    Keys = if Dir =:= fwd -> Keys0; true -> lists:reverse(Keys0) end,
-
-    FoldFun = fun(Key, Acc0) ->
-        DocInfo = (catch couch_db:get_doc_info(Db, Key)),
-        {Doc, Acc1} = case DocInfo of
-            {ok, #doc_info{id=Id, revs=[RevInfo | _RestRevs]}=DI} ->
-                Rev = couch_doc:rev_to_str(RevInfo#rev_info.rev),
-                Props = [{rev, Rev}] ++ case RevInfo#rev_info.deleted of
-                    true -> [{deleted, true}];
-                    false -> []
-                end,
-                {{{Id, Id}, {Props}}, Acc0#mracc{doc_info=DI}};
-            not_found ->
-                {{{Key, error}, not_found}, Acc0}
-        end,
-        {_, Acc2} = map_fold(Doc, {[], [{0, 0, 0}]}, Acc1),
-        Acc2
-    end,
-    FinalAcc = lists:foldl(FoldFun, Acc, Keys),
-    finish_fold(FinalAcc, [{total, Total}]).
-
-
-map_fold(Db, View, Args, Callback, UAcc) ->
-    {ok, Total} = couch_mrview_util:get_row_count(View),
-    Acc = #mracc{
-        db=Db,
-        total_rows=Total,
-        limit=Args#mrargs.limit,
-        skip=Args#mrargs.skip,
-        callback=Callback,
-        user_acc=UAcc,
-        reduce_fun=fun couch_mrview_util:reduce_to_count/1,
-        update_seq=View#mrview.update_seq,
-        args=Args
-    },
-    OptList = couch_mrview_util:key_opts(Args),
-    {Reds, Acc2} = lists:foldl(fun(Opts, {_, Acc0}) ->
-        {ok, R, A} = couch_mrview_util:fold(View, fun map_fold/3, Acc0, Opts),
-        {R, A}
-    end, {nil, Acc}, OptList),
-    Offset = couch_mrview_util:reduce_to_count(Reds),
-    finish_fold(Acc2, [{total, Total}, {offset, Offset}]).
-
-
-map_fold(#full_doc_info{} = FullDocInfo, OffsetReds, Acc) ->
-    % matches for _all_docs and translates #full_doc_info{} -> KV pair
-    case couch_doc:to_doc_info(FullDocInfo) of
-        #doc_info{id=Id, revs=[#rev_info{deleted=false, rev=Rev}|_]} = DI ->
-            Value = {[{rev, couch_doc:rev_to_str(Rev)}]},
-            map_fold({{Id, Id}, Value}, OffsetReds, Acc#mracc{doc_info=DI});
-        #doc_info{revs=[#rev_info{deleted=true}|_]} ->
-            {ok, Acc}
-    end;
-map_fold(_KV, _Offset, #mracc{skip=N}=Acc) when N > 0 ->
-    {ok, Acc#mracc{skip=N-1, last_go=ok}};
-map_fold(KV, OffsetReds, #mracc{offset=undefined}=Acc) ->
-    #mracc{
-        total_rows=Total,
-        callback=Callback,
-        user_acc=UAcc0,
-        reduce_fun=Reduce,
-        update_seq=UpdateSeq,
-        args=Args
-    } = Acc,
-    Offset = Reduce(OffsetReds),
-    Meta = make_meta(Args, UpdateSeq, [{total, Total}, {offset, Offset}]),
-    {Go, UAcc1} = Callback(Meta, UAcc0),
-    Acc1 = Acc#mracc{meta_sent=true, offset=Offset, user_acc=UAcc1, last_go=Go},
-    case Go of
-        ok -> map_fold(KV, OffsetReds, Acc1);
-        stop -> {stop, Acc1}
-    end;
-map_fold(_KV, _Offset, #mracc{limit=0}=Acc) ->
-    {stop, Acc};
-map_fold({{Key, Id}, Val}, _Offset, Acc) ->
-    #mracc{
-        db=Db,
-        limit=Limit,
-        doc_info=DI,
-        callback=Callback,
-        user_acc=UAcc0,
-        args=Args
-    } = Acc,
-    Doc = case DI of
-        #doc_info{} -> couch_mrview_util:maybe_load_doc(Db, DI, Args);
-        _ -> couch_mrview_util:maybe_load_doc(Db, Id, Val, Args)
-    end,
-    Row = [{id, Id}, {key, Key}, {value, Val}] ++ Doc,
-    {Go, UAcc1} = Callback({row, Row}, UAcc0),
-    {Go, Acc#mracc{
-        limit=Limit-1,
-        doc_info=undefined,
-        user_acc=UAcc1,
-        last_go=Go
-    }}.
-
-
-red_fold(Db, {_Nth, _Lang, View}=RedView, Args, Callback, UAcc) ->
-    Acc = #mracc{
-        db=Db,
-        total_rows=null,
-        limit=Args#mrargs.limit,
-        skip=Args#mrargs.skip,
-        group_level=Args#mrargs.group_level,
-        callback=Callback,
-        user_acc=UAcc,
-        update_seq=View#mrview.update_seq,
-        args=Args
-    },
-    GroupFun = group_rows_fun(Args#mrargs.group_level),
-    OptList = couch_mrview_util:key_opts(Args, [{key_group_fun, GroupFun}]),
-    Acc2 = lists:foldl(fun(Opts, Acc0) ->
-        {ok, Acc1} =
-            couch_mrview_util:fold_reduce(RedView, fun red_fold/3,  Acc0, Opts),
-        Acc1
-    end, Acc, OptList),
-    finish_fold(Acc2, []).
-
-red_fold(_Key, _Red, #mracc{skip=N}=Acc) when N > 0 ->
-    {ok, Acc#mracc{skip=N-1, last_go=ok}};
-red_fold(Key, Red, #mracc{meta_sent=false}=Acc) ->
-    #mracc{
-        args=Args,
-        callback=Callback,
-        user_acc=UAcc0,
-        update_seq=UpdateSeq
-    } = Acc,
-    Meta = make_meta(Args, UpdateSeq, []),
-    {Go, UAcc1} = Callback(Meta, UAcc0),
-    Acc1 = Acc#mracc{user_acc=UAcc1, meta_sent=true, last_go=Go},
-    case Go of
-        ok -> red_fold(Key, Red, Acc1);
-        _ -> {Go, Acc1}
-    end;
-red_fold(_Key, _Red, #mracc{limit=0} = Acc) ->
-    {stop, Acc};
-red_fold(_Key, Red, #mracc{group_level=0} = Acc) ->
-    #mracc{
-        limit=Limit,
-        callback=Callback,
-        user_acc=UAcc0
-    } = Acc,
-    Row = [{key, null}, {value, Red}],
-    {Go, UAcc1} = Callback({row, Row}, UAcc0),
-    {Go, Acc#mracc{user_acc=UAcc1, limit=Limit-1, last_go=Go}};
-red_fold(Key, Red, #mracc{group_level=exact} = Acc) ->
-    #mracc{
-        limit=Limit,
-        callback=Callback,
-        user_acc=UAcc0
-    } = Acc,
-    Row = [{key, Key}, {value, Red}],
-    {Go, UAcc1} = Callback({row, Row}, UAcc0),
-    {Go, Acc#mracc{user_acc=UAcc1, limit=Limit-1, last_go=Go}};
-red_fold(K, Red, #mracc{group_level=I} = Acc) when I > 0, is_list(K) ->
-    #mracc{
-        limit=Limit,
-        callback=Callback,
-        user_acc=UAcc0
-    } = Acc,
-    Row = [{key, lists:sublist(K, I)}, {value, Red}],
-    {Go, UAcc1} = Callback({row, Row}, UAcc0),
-    {Go, Acc#mracc{user_acc=UAcc1, limit=Limit-1, last_go=Go}};
-red_fold(K, Red, #mracc{group_level=I} = Acc) when I > 0 ->
-    #mracc{
-        limit=Limit,
-        callback=Callback,
-        user_acc=UAcc0
-    } = Acc,
-    Row = [{key, K}, {value, Red}],
-    {Go, UAcc1} = Callback({row, Row}, UAcc0),
-    {Go, Acc#mracc{user_acc=UAcc1, limit=Limit-1, last_go=Go}}.
-
-
-finish_fold(#mracc{last_go=ok, update_seq=UpdateSeq}=Acc,  ExtraMeta) ->
-    #mracc{callback=Callback, user_acc=UAcc, args=Args}=Acc,
-    % Possible send meta info
-    Meta = make_meta(Args, UpdateSeq, ExtraMeta),
-    {Go, UAcc1} = case Acc#mracc.meta_sent of
-        false -> Callback(Meta, UAcc);
-        _ -> {ok, Acc#mracc.user_acc}
-    end,
-    % Notify callback that the fold is complete.
-    {_, UAcc2} = case Go of
-        ok -> Callback(complete, UAcc1);
-        _ -> {ok, UAcc1}
-    end,
-    {ok, UAcc2};
-finish_fold(#mracc{user_acc=UAcc}, _ExtraMeta) ->
-    {ok, UAcc}.
-
-
-make_meta(Args, UpdateSeq, Base) ->
-    case Args#mrargs.update_seq of
-        true -> {meta, Base ++ [{update_seq, UpdateSeq}]};
-        _ -> {meta, Base}
-    end.
-
-
-group_rows_fun(exact) ->
-    fun({Key1,_}, {Key2,_}) -> Key1 == Key2 end;
-group_rows_fun(0) ->
-    fun(_A, _B) -> true end;
-group_rows_fun(GroupLevel) when is_integer(GroupLevel) ->
-    fun({[_|_] = Key1,_}, {[_|_] = Key2,_}) ->
-        lists:sublist(Key1, GroupLevel) == lists:sublist(Key2, GroupLevel);
-    ({Key1,_}, {Key2,_}) ->
-        Key1 == Key2
-    end.
-
-
-default_cb(complete, Acc) ->
-    {ok, lists:reverse(Acc)};
-default_cb({final, Info}, []) ->
-    {ok, [Info]};
-default_cb({final, _}, Acc) ->
-    {ok, Acc};
-default_cb(Row, Acc) ->
-    {ok, [Row | Acc]}.
-
-
-to_mrargs(KeyList) ->
-    lists:foldl(fun({Key, Value}, Acc) ->
-        Index = lookup_index(couch_util:to_existing_atom(Key)),
-        setelement(Index, Acc, Value)
-    end, #mrargs{}, KeyList).
-
-
-lookup_index(Key) ->
-    Index = lists:zip(
-        record_info(fields, mrargs), lists:seq(2, record_info(size, mrargs))
-    ),
-    couch_util:get_value(Key, Index).


[96/96] [abbrv] git commit: updated refs/heads/1994-merge-rcouch to 9605700

Posted by be...@apache.org.
remove useless files


Project: http://git-wip-us.apache.org/repos/asf/couchdb/repo
Commit: http://git-wip-us.apache.org/repos/asf/couchdb/commit/96057002
Tree: http://git-wip-us.apache.org/repos/asf/couchdb/tree/96057002
Diff: http://git-wip-us.apache.org/repos/asf/couchdb/diff/96057002

Branch: refs/heads/1994-merge-rcouch
Commit: 96057002eeaecaff6554f63e245a05a5a98d27f1
Parents: 79f67b6
Author: Benoit Chesneau <be...@apache.org>
Authored: Wed Jan 8 03:55:37 2014 +0100
Committer: Benoit Chesneau <bc...@gmail.com>
Committed: Thu Jan 9 00:59:38 2014 +0100

----------------------------------------------------------------------
 acinclude.m4.in             |  30 ---
 bin/Makefile.am             | 159 ----------------
 bin/couch-config.tpl.in     | 140 --------------
 bin/couchdb.bat.tpl.in      |  26 ---
 bin/couchdb.tpl.in          | 382 ---------------------------------------
 bin/erlang-version.escript  |   3 -
 src/etc/couchdb/Makefile.am |  95 ----------
 utils/Makefile.am           |  45 -----
 var/Makefile.am             |  23 ---
 9 files changed, 903 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/couchdb/blob/96057002/acinclude.m4.in
----------------------------------------------------------------------
diff --git a/acinclude.m4.in b/acinclude.m4.in
deleted file mode 100644
index db2f149..0000000
--- a/acinclude.m4.in
+++ /dev/null
@@ -1,30 +0,0 @@
-dnl Licensed under the Apache License, Version 2.0 (the "License"); you may not
-dnl use this file except in compliance with the License.  dnl You may obtain a
-dnl copy of the License at
-dnl
-dnl   http://www.apache.org/licenses/LICENSE-2.0
-dnl
-dnl Unless required by applicable law or agreed to in writing, software
-dnl distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-dnl WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-dnl License for the specific language governing permissions and limitations
-dnl under the License.
-
-m4_define([LOCAL_PACKAGE_AUTHOR_NAME], [The Apache Software Foundation])
-m4_define([LOCAL_PACKAGE_AUTHOR_ADDRESS], [dev@couchdb.apache.org])
-m4_define([LOCAL_PACKAGE_IDENTIFIER], [couchdb])
-m4_define([LOCAL_PACKAGE_TARNAME], [apache-couchdb])
-m4_define([LOCAL_PACKAGE_NAME], [Apache CouchDB])
-m4_define([LOCAL_BUG_URI], [https://issues.apache.org/jira/browse/COUCHDB])
-m4_define([LOCAL_VERSION_MAJOR], [1])
-m4_define([LOCAL_VERSION_MINOR], [6])
-m4_define([LOCAL_VERSION_REVISION], [0])
-m4_define([LOCAL_VERSION_STAGE], [+build])
-m4_define([LOCAL_VERSION_RELEASE], [.%revision%])
-m4_define([LOCAL_VERSION_PRIMARY],
-    [LOCAL_VERSION_MAJOR.LOCAL_VERSION_MINOR.LOCAL_VERSION_REVISION])
-m4_define([LOCAL_VERSION_SECONDARY],
-    [LOCAL_VERSION_STAGE[]LOCAL_VERSION_RELEASE])
-m4_define([LOCAL_VERSION],
-    [LOCAL_VERSION_PRIMARY[]LOCAL_VERSION_SECONDARY])
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/96057002/bin/Makefile.am
----------------------------------------------------------------------
diff --git a/bin/Makefile.am b/bin/Makefile.am
deleted file mode 100644
index aeb0953..0000000
--- a/bin/Makefile.am
+++ /dev/null
@@ -1,159 +0,0 @@
-## Licensed under the Apache License, Version 2.0 (the "License"); you may not
-## use this file except in compliance with the License. You may obtain a copy of
-## the License at
-##
-##   http://www.apache.org/licenses/LICENSE-2.0
-##
-## Unless required by applicable law or agreed to in writing, software
-## distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-## WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-## License for the specific language governing permissions and limitations under
-## the License.
-
-MAKE_SAFE = $(MAKE)
-
-if WINDOWS
-bin_SCRIPTS = couchdb.bat
-else
-bin_SCRIPTS = couchdb couch-config
-endif
-
-man1dir = $(mandir)/man1
-
-noinst_SCRIPTS = couchjs_dev couch-config_dev
-
-man_file = couchdb.1
-
-if BUILD_MAN
-man_file_build = $(man_file)
-else
-man_file_build =
-endif
-
-BUILT_SOURCES = $(man_file_build)
-
-EXTRA_DIST = $(man_file_build) erlang-version.escript
-
-CLEANFILES = $(bin_SCRIPTS) $(man_file_build) $(noinst_SCRIPTS)
-
-transform = @program_transform_name@
-couchdb_command_name = `echo couchdb | sed '$(transform)'`
-couchjs_command_name = `echo couchjs | sed '$(transform)'`
-
-couchdb: couchdb.tpl
-	sed -e "s|%ERL%|$(ERL)|g" \
-	    -e "s|%ICU_CONFIG%|$(ICU_CONFIG)|g" \
-	    -e "s|%bindir%|@bindir@|g" \
-	    -e "s|%localerlanglibdir%|@localerlanglibdir@|g" \
-	    -e "s|%defaultini%|default.ini|g" \
-	    -e "s|%localini%|local.ini|g" \
-	    -e "s|%localconfdir%|@localconfdir@|g" \
-	    -e "s|%localstatelogdir%|@localstatelogdir@|g" \
-	    -e "s|%localstatelibdir%|@localstatelibdir@|g" \
-	    -e "s|%localstatedir%|@localstatedir@|g" \
-	    -e "s|%locallibdir%|@locallibdir@|g" \
-	    -e "s|%bug_uri%|@bug_uri@|g" \
-	    -e "s|%package_author_address%|@package_author_address@|g" \
-	    -e "s|%package_author_name%|@package_author_name@|g" \
-	    -e "s|%package_name%|@package_name@|g" \
-	    -e "s|%version%|@version@|g" \
-	    -e "s|%couchdb_command_name%|$(couchdb_command_name)|g" > \
-	$@ < $<
-	chmod +x $@
-
-if !WINDOWS
-install-exec-hook:
-	$(LN_S) -f "$(locallibbindir)/$(couchjs_command_name)" \
-		"$(DESTDIR)$(bindir)/$(couchjs_command_name)"
-endif
-
-couchjs_dev:
-	$(LN_S) -f "$(abs_top_builddir)/src/couchdb/priv/couchjs" "$@"
-
-couchdb.bat: couchdb.bat.tpl
-	sed -e "s|%ICU_CONFIG%|$(ICU_CONFIG)|g" \
-	    -e "s|%version%|@version@|g" \
-	$< > $@
-
-couch-config: couch-config.tpl
-	sed -e "s|%ERL%|$(ERL)|g" \
-	    -e "s|%bindir%|@bindir@|g" \
-	    -e "s|%localerlanglibdir%|@localerlanglibdir@|g" \
-	    -e "s|%localconfdir%|@localconfdir@|g" \
-	    -e "s|%localdatadir%|$(localdatadir)|g" \
-	    -e "s|%localbuilddatadir%|$(localdatadir)|g" \
-	    -e "s|%localstatelogdir%|@localstatelogdir@|g" \
-	    -e "s|%localstatelibdir%|@localstatelibdir@|g" \
-	    -e "s|%localstatedir%|@localstatedir@|g" \
-	    -e "s|%localstaterundir%|@localstaterundir@|g" \
-	    -e "s|%couchlibdir%|@localerlanglibdir@/couch-%version%|g"\
-	    -e "s|%couchincludedir%|@localerlanglibdir@/include|g"\
-	    -e "s|%couchebindir%|@localerlanglibdir@/ebin|g"\
-	    -e "s|%couchprivlibdir%|@localerlanglibdir@/couch-%version%/priv/lib|g"\
-	    -e "s|%bug_uri%|@bug_uri@|g" \
-	    -e "s|%package_author_address%|@package_author_address@|g" \
-	    -e "s|%package_author_name%|@package_author_name@|g" \
-	    -e "s|%package_name%|@package_name@|g" \
-	    -e "s|%version%|@version@|g" \
-	    -e "s|%erlangversion%|@erlangversion@|g" \
-	    -e "s|%erlangbin%|@erlangbin@|g" \
-	    -e "s|%couchdb_command_name%|$(couchdb_command_name)|g" > \
-	$@ < $<
-	chmod +x $@
-
-couch-config_dev: couch-config.tpl
-	sed -e "s|%ERL%|$(ERL)|g" \
-	    -e "s|%bindir%|$(abs_top_builddir)/bin|g" \
-	    -e "s|%localerlanglibdir%|$(abs_top_builddir)\/src\/couchdb|g" \
-	    -e "s|%couchlibdir%|$(abs_top_builddir)\/src\/couchdb|g"\
-	    -e "s|%couchincludedir%|$(abs_top_builddir)\/src\/couchdb|g"\
-	    -e "s|%couchebindir%|$(abs_top_builddir)\/src\/couchdb|g"\
-	    -e "s|%couchprivlibdir%|$(abs_top_builddir)/src/couchdb/priv/.libs|g"\
-	    -e "s|%localdatadir%|$(abs_top_srcdir)/share|g" \
-	    -e "s|%localbuilddatadir%|$(abs_top_builddir)/share|g" \
-	    -e "s|%localstatelibdir%|$(abs_top_builddir)/tmp/lib|g" \
-	    -e "s|%localstatelogdir%|$(abs_top_builddir)/tmp/log|g" \
-	    -e "s|%localstatedir%|$(abs_top_builddir)/tmp|g" \
-	    -e "s|%localstaterundir%|$(abs_top_builddir)/tmp/run|g" \
-	    -e "s|%bug_uri%|@bug_uri@|g" \
-	    -e "s|%package_author_address%|@package_author_address@|g" \
-	    -e "s|%package_author_name%|@package_author_name@|g" \
-	    -e "s|%package_name%|@package_name@|g" \
-	    -e "s|%version%|@version@|g" \
-	    -e "s|%erlangversion%|@erlangversion@|g" \
-	    -e "s|%erlangbin%|@erlangbin@|g" \
-	    -e "s|%couchdb_command_name%|$(abs_top_builddir)/utils/run|g" > \
-	$@ < $<
-	chmod +x $@
-
-# Depend on source files so distributed man pages are not rebuilt for end user.
-
-$(man_file): couchdb.tpl.in
-	$(MAKE_SAFE) -f Makefile couchdb; \
-	$(top_srcdir)/build-aux/missing --run \
-	    help2man \
-	        --no-info \
-	        --help-option="-h" \
-	        --version-option="-V" \
-	        --name="$(package_name) database server" \
-	        ./couchdb --output $@
-
-install-data-local:
-	if test -s $(man_file); then \
-	    if test `cat $(man_file) | wc -l` -gt 1; then \
-	        $(INSTALL) -d $(DESTDIR)$(man1dir); \
-	        $(INSTALL_DATA) $(man_file) $(DESTDIR)$(man1dir)/$(man_file); \
-	    fi \
-	fi
-
-uninstall-local:
-	rm -f $(DESTDIR)$(man1dir)/$(man_file)
-
-distcheck-hook:
-	if test ! -s $(man_file); then \
-	    $(top_srcdir)/build-aux/dist-error $(man_file); \
-	else \
-	    if test ! `cat $(man_file) | wc -l` -gt 1; then \
-	        $(top_srcdir)/build-aux/dist-error $(man_file); \
-	    fi \
-	fi

http://git-wip-us.apache.org/repos/asf/couchdb/blob/96057002/bin/couch-config.tpl.in
----------------------------------------------------------------------
diff --git a/bin/couch-config.tpl.in b/bin/couch-config.tpl.in
deleted file mode 100644
index bd27d0e..0000000
--- a/bin/couch-config.tpl.in
+++ /dev/null
@@ -1,140 +0,0 @@
-#! /bin/sh -e
-
-# Licensed under the Apache License, Version 2.0 (the "License"); you
-# may not use this file except in compliance with the License. You may
-# obtain a copy of the License at
-#
-#   http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
-# implied. See the License for the specific language governing
-# permissions and limitations under the License.
-
-basename=`basename "$0"`
-
-staticdir="%localbuilddatadir%"
-erlanglibdir="%localerlanglibdir%"
-couchversion="%version%"
-dbdir="%localstatelibdir%"
-viewdir="%localstatelibdir%"
-confdir="%localconfdir%"
-urifile="%localstaterundir%/couch.uri"
-logdir="%localstatelogdir%"
-erlangversion="%erlangversion%"
-erlangbin="%erlangbin%"
-
-version () {
-    cat << EOF
-$basename - %package_name% configuration helper %version%
-
-Licensed under the Apache License, Version 2.0 (the "License"); you may not use
-this file except in compliance with the License. You may obtain a copy of the
-License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software distributed
-under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
-CONDITIONS OF ANY KIND, either express or implied. See the License for the
-specific language governing permissions and limitations under the License.
-
-EOF
-}
-
-usage()
-{
-    cat << EOF
-Usage: $basename [OPTION]
-
-The $basename command runs the %package_name% configuration helper
-script.
-
-Options:
-
-  --erl-libs-dir    Erlang library directory
-  --erl-bin         Erlang binary
-  --config-dir      configuration directory
-  --db-dir          database directory
-  --view-dir        view index directory
-  --static-dir      static asset directory
-  --doc-dir         documentation directory
-  --log-dir         log directory
-  --uri-file        daemon sockets file 
-  --couch-version   version of Apache CouchDB
-  --erlang-version  version of Erlang that CouchDB was built with
-  --version         version of $basename
-  --help            Print usage
-
-If you want to add an option in couch-config or report bugs please do it
-at <%bug_uri%>.
-EOF
-}
-  
-
-if [ $# -lt 1 ]; then
-    usage
-    exit 1
-fi
-
-
-while [ $# -gt 0 ];
-do
-    arg="$1"
-    var=`echo $arg | sed -e 's/^[^=]*=//'`
-    
-    case "$arg" in
-        --erl-libs-dir)
-            echo $erlanglibdir
-            ;;
-        --erl-bin)
-            echo $erlangbin
-            ;;
-        --config-dir)
-            echo $confdir
-            ;;
-        --db-dir)
-            echo $dbdir
-            ;;
-        --view-dir)
-            echo $viewdir
-            ;;
-        --static-dir)
-            echo $staticdir
-            ;;
-        --doc-dir)
-            echo $staticdir
-            ;;
-        --log-dir)
-            echo $logdir
-            ;;
-        --uri-file)
-            echo $urifile
-            ;;
-        --couch-version)
-            echo $couchversion
-            ;;
-        --erlang-version)
-            echo $erlangversion
-            ;;
-        --version)
-            version
-            exit 0
-            ;;
-        --help)
-            usage
-            exit 0
-            ;;
-        *|-*)
-	        echo $basename: ERROR Unknown Option $arg 1>&2
-            echo 1>&2
-            usage 1>&2
-            echo "### $basename: Exitting." 1>&2
-            exit 1;
-            ;;
-    esac
-    shift
-done
-
-exit 0

http://git-wip-us.apache.org/repos/asf/couchdb/blob/96057002/bin/couchdb.bat.tpl.in
----------------------------------------------------------------------
diff --git a/bin/couchdb.bat.tpl.in b/bin/couchdb.bat.tpl.in
deleted file mode 100644
index 8718ee6..0000000
--- a/bin/couchdb.bat.tpl.in
+++ /dev/null
@@ -1,26 +0,0 @@
-@echo off
-rem Licensed under the Apache License, Version 2.0 (the "License"); you may not
-rem use this file except in compliance with the License. You may obtain a copy
-rem of the License at
-rem
-rem   http://www.apache.org/licenses/LICENSE-2.0
-rem
-rem Unless required by applicable law or agreed to in writing, software
-rem distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-rem WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-rem License for the specific language governing permissions and limitations
-rem under the License.
-
-setlocal
-rem First change to the drive with the erlang bin directory
-%~d0
-rem then change to the erlang bin directory
-cd %~dp0
-
-rem Allow a different erlang executable (eg, erl) to be used.
-rem When using erl instead of werl, server restarts during test runs can fail
-rem intermittently. But using erl should be fine for production use.
-if "%ERL%x" == "x" set ERL=werl.exe
-
-echo CouchDB %version% - prepare to relax...
-%ERL% -sasl errlog_type error -s couch +A 4 +W w

http://git-wip-us.apache.org/repos/asf/couchdb/blob/96057002/bin/couchdb.tpl.in
----------------------------------------------------------------------
diff --git a/bin/couchdb.tpl.in b/bin/couchdb.tpl.in
deleted file mode 100644
index 538ebcb..0000000
--- a/bin/couchdb.tpl.in
+++ /dev/null
@@ -1,382 +0,0 @@
-#! /bin/sh -e
-
-# Licensed under the Apache License, Version 2.0 (the "License"); you may not
-# use this file except in compliance with the License. You may obtain a copy of
-# the License at
-#
-#   http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-# License for the specific language governing permissions and limitations under
-# the License.
-
-BACKGROUND=false
-DEFAULT_CONFIG_DIR=%localconfdir%/default.d
-DEFAULT_CONFIG_FILE=%localconfdir%/%defaultini%
-ERL_OS_MON_OPTIONS="-os_mon \
-    start_memsup false \
-    start_cpu_sup false \
-    disk_space_check_interval 1 \
-    disk_almost_full_threshold 1"
-ERL_START_OPTIONS="$ERL_OS_MON_OPTIONS -sasl errlog_type error +K true +A 4"
-HEART_BEAT_TIMEOUT=11
-HEART_COMMAND="%bindir%/%couchdb_command_name% -k"
-INTERACTIVE=false
-KILL=false
-PLUGINS_DIR=%locallibdir%/plugins
-LOCAL_CONFIG_DIR=%localconfdir%/local.d
-LOCAL_CONFIG_FILE=%localconfdir%/%localini%
-PID_FILE=%localstatedir%/run/couchdb/couchdb.pid
-RECURSED=false
-RESET_CONFIG=true
-RESPAWN_TIMEOUT=0
-SCRIPT_ERROR=1
-SCRIPT_OK=0
-SHUTDOWN=false
-STDERR_FILE=couchdb.stderr
-STDOUT_FILE=couchdb.stdout
-
-print_arguments=""
-start_arguments=""
-background_start_arguments=""
-
-basename=`basename $0`
-
-display_version () {
-    cat << EOF
-$basename - %package_name% %version%
-
-Licensed under the Apache License, Version 2.0 (the "License"); you may not use
-this file except in compliance with the License. You may obtain a copy of the
-License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software distributed
-under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
-CONDITIONS OF ANY KIND, either express or implied. See the License for the
-specific language governing permissions and limitations under the License.
-
-EOF
-}
-
-display_help () {
-    cat << EOF
-Usage: $basename [OPTION]
-
-The $basename command runs the %package_name% server.
-
-Erlang is called with:
-
-    $ERL_START_OPTIONS
-
-Erlang inherits the environment of this command.
-
-You can override these options using the environment:
-
-    ERL_AFLAGS, ERL_FLAGS, ERL_ZFLAGS
-
-See erl(1) for more information about the environment variables.
-
-The exit status is 0 for success or 1 for failure.
-
-Options:
-
-  -h          display a short help message and exit
-  -V          display version information and exit
-  -a FILE     add configuration FILE to chain
-  -A DIR      add configuration DIR to chain
-  -n          reset configuration file chain (including system default)
-  -c          print configuration file chain and exit
-  -i          use the interactive Erlang shell
-  -b          spawn as a background process
-  -p FILE     set the background PID FILE (overrides system default)
-  -r SECONDS  respawn background process after SECONDS (defaults to no respawn)
-  -o FILE     redirect background stdout to FILE (defaults to $STDOUT_FILE)
-  -e FILE     redirect background stderr to FILE (defaults to $STDERR_FILE)
-  -s          display the status of the background process
-  -k          kill the background process, will respawn if needed
-  -d          shutdown the background process
-
-Report bugs at <%bug_uri%>.
-EOF
-}
-
-display_error () {
-    if test -n "$1"; then
-        echo $1 >&2
-    fi
-    echo >&2
-    echo "Try \`"$basename" -h' for more information." >&2
-    false
-}
-
-_get_pid () {
-    if test -f $PID_FILE; then
-        PID=`cat $PID_FILE`
-    fi
-    echo $PID
-}
-
-_add_config_file () {
-    if test -z "$print_arguments"; then
-        print_arguments="$1"
-    else
-        print_arguments="`cat <<EOF
-$print_arguments
-$1
-EOF
-`"
-    fi
-    start_arguments="$start_arguments $1"
-    background_start_arguments="$background_start_arguments -a $1"
-}
-
-_add_config_dir () {
-    for file in "$1"/*.ini; do
-        if [ -r "$file" ]; then
-          _add_config_file "$file"
-        fi
-    done
-}
-
-_add_erlang_config () {
-    if [ -r "$1" ]; then
-        ERL_START_OPTIONS="$ERL_START_OPTIONS -config '$1'"
-    fi
-}
-
-_load_config () {
-    _add_config_file "$DEFAULT_CONFIG_FILE"
-    _add_config_dir "$DEFAULT_CONFIG_DIR"
-    # We initialize plugins here to get the desired default config load order
-    _find_plugins
-    _add_config_file "$LOCAL_CONFIG_FILE"
-    _add_config_dir "$LOCAL_CONFIG_DIR"
-    if [ "$COUCHDB_ADDITIONAL_CONFIG_FILE" != '' ]
-    then
-        _add_config_file "$COUCHDB_ADDITIONAL_CONFIG_FILE"
-    fi
-}
-
-_reset_config () {
-    print_arguments=""
-    start_arguments=""
-    background_start_arguments="-n"
-}
-
-_print_config () {
-    cat <<EOF
-$print_arguments
-EOF
-}
-
-check_status () {
-    PID=`_get_pid`
-    if test -n "$PID"; then
-        if kill -0 $PID 2> /dev/null; then
-            echo "Apache CouchDB is running as process $PID, time to relax."
-            return $SCRIPT_OK
-        else
-            echo >&2 << EOF
-Apache CouchDB is not running but a stale PID file exists: $PID_FILE
-EOF
-        fi
-    else
-        echo "Apache CouchDB is not running." >&2
-    fi
-    return $SCRIPT_ERROR
-}
-
-check_environment () {
-    if test "$BACKGROUND" != "true"; then
-        return
-    fi
-    touch $PID_FILE 2> /dev/null || true
-    touch $STDOUT_FILE 2> /dev/null || true
-    touch $STDERR_FILE 2> /dev/null || true
-    message_prefix="Apache CouchDB needs write permission on the"
-    if test ! -w $PID_FILE; then
-        echo "$message_prefix PID file: $PID_FILE" >&2
-        false
-    fi
-    if test ! -w $STDOUT_FILE; then
-        echo "$message_prefix STDOUT file: $STDOUT_FILE" >&2
-        false
-    fi
-    if test ! -w $STDERR_FILE; then
-        echo "$message_prefix STDERR file: $STDERR_FILE" >&2
-        false
-    fi
-    message_prefix="Apache CouchDB needs a regular"
-    if test `echo 2> /dev/null >> $PID_FILE; echo $?` -gt 0; then
-        echo "$message_prefix PID file: $PID_FILE" >&2
-        false
-    fi
-    if test `echo 2> /dev/null >> $STDOUT_FILE; echo $?` -gt 0; then
-        echo "$message_prefix STDOUT file: $STDOUT_FILE" >&2
-        false
-    fi
-    if test `echo 2> /dev/null >> $STDERR_FILE; echo $?` -gt 0; then
-        echo "$message_prefix STDERR file: $STDERR_FILE" >&2
-        false
-    fi
-}
-
-_find_plugins () {
-    # Find plugins and add them to the Erlang path and load their default
-    # configurations. This should be called from _load_config.
-    if test -d "$PLUGINS_DIR"; then
-        for plugin in "$PLUGINS_DIR"/*; do
-            if echo "$COUCH_PLUGIN_BLACKLIST" | grep "$plugin" > /dev/null 2> /dev/null; then
-                : # Do not use this plugin.
-            else
-                if echo "$ERL_ZFLAGS" | grep "$plugin/ebin" > /dev/null 2> /dev/null; then
-                    : # It's already loaded.
-                else
-                    ERL_ZFLAGS="$ERL_ZFLAGS -pz '$plugin/ebin'"
-                fi
-                _add_config_dir "$plugin/priv/default.d"
-                _add_erlang_config "$plugin/priv/couch_plugin.config"
-            fi
-        done
-        export ERL_ZFLAGS
-    fi
-}
-
-start_couchdb () {
-    if test ! "$RECURSED" = "true"; then
-        if check_status 2> /dev/null; then
-            exit
-        fi
-        check_environment
-    fi
-    interactive_option="+Bd -noinput"
-    if test "$INTERACTIVE" = "true"; then
-        interactive_option=""
-    fi
-    if test "$BACKGROUND" = "true"; then
-        touch $PID_FILE
-        interactive_option="+Bd -noinput"
-    fi
-
-    command="%ERL% $interactive_option $ERL_START_OPTIONS \
-        -env ERL_LIBS $ERL_LIBS:%localerlanglibdir% -couch_ini $start_arguments -s couch"
-    if test "$BACKGROUND" = "true" -a "$RECURSED" = "false"; then
-        $0 $background_start_arguments -b -r $RESPAWN_TIMEOUT -p $PID_FILE \
-            -o $STDOUT_FILE -e $STDERR_FILE -R &
-        echo "Apache CouchDB has started, time to relax."
-    else
-        if test "$RECURSED" = "true"; then
-            while true; do
-                export HEART_COMMAND
-                export HEART_BEAT_TIMEOUT
-                `eval $command -pidfile $PID_FILE -heart \
-                    >> $STDOUT_FILE 2>> $STDERR_FILE` || true
-                PID=`_get_pid`
-                if test -n "$PID"; then
-                    if kill -0 $PID 2> /dev/null; then
-                        return $SCRIPT_ERROR
-                    fi
-                else
-                    return $SCRIPT_OK
-                fi
-                if test "$RESPAWN_TIMEOUT" = "0"; then
-                    return $SCRIPT_OK
-                fi
-                if test "$RESPAWN_TIMEOUT" != "1"; then
-                    plural_ending="s"
-                fi
-                cat << EOF
-Apache CouchDB crashed, restarting in $RESPAWN_TIMEOUT second$plural_ending.
-EOF
-                sleep $RESPAWN_TIMEOUT
-            done
-        else
-            eval exec $command
-        fi
-    fi
-}
-
-stop_couchdb () {
-    PID=`_get_pid`
-    STOP_TIMEOUT=60
-    if test -n "$PID"; then
-        if test "$1" = "false"; then
-            echo > $PID_FILE
-        fi
-
-        if kill -0 $PID 2> /dev/null; then
-            if kill -TERM $PID 2> /dev/null; then
-                count=0
-                while kill -0 $PID 2> /dev/null; do
-                    if [ $count -ge $STOP_TIMEOUT ]; then
-                        echo "Apache CouchDB failed to shutdown."
-                        return $SCRIPT_ERROR
-                    else
-                        count=$[count+1]
-                        sleep 1
-                    fi
-                done
-                if test "$1" = "false"; then
-                    echo "Apache CouchDB has been shutdown."
-                else
-                    echo "Apache CouchDB has been killed."
-                fi
-                return $SCRIPT_OK
-            else
-                echo "Apache CouchDB could not be killed." >&2
-                return $SCRIPT_ERROR
-            fi
-            if test "$1" = "false"; then
-                echo "Stale PID file exists but Apache CouchDB is not running."
-            else
-                echo "Stale PID file existed but Apache CouchDB is not running."
-            fi
-        fi
-    else
-        echo "Apache CouchDB is not running."
-    fi
-}
-
-parse_script_option_list () {
-    _load_config
-    set +e
-    options=`getopt hVa:A:ncibp:r:Ro:e:skd $@`
-    if test ! $? -eq 0; then
-        display_error
-    fi
-    set -e
-    eval set -- $options
-    while [ $# -gt 0 ]; do
-        case "$1" in
-            -h) shift; display_help; exit;;
-            -V) shift; display_version; exit;;
-            -a) shift; _add_config_file "$1"; shift;;
-            -A) shift; _add_config_dir "$1"; shift;;
-            -n) shift; _reset_config;;
-            -c) shift; _print_config; exit;;
-            -i) shift; INTERACTIVE=true;;
-            -b) shift; BACKGROUND=true;;
-            -r) shift; RESPAWN_TIMEOUT=$1; shift;;
-            -R) shift; RECURSED=true;;
-            -p) shift; PID_FILE=$1; shift;;
-            -o) shift; STDOUT_FILE=$1; shift;;
-            -e) shift; STDERR_FILE=$1; shift;;
-            -s) shift; check_status; exit;;
-            -k) shift; KILL=true;;
-            -d) shift; SHUTDOWN=true;;
-            --) shift; break;;
-            *) display_error "Unknown option: $1" >&2;;
-        esac
-    done
-    if test "$KILL" = "true" -o "$SHUTDOWN" = "true"; then
-        stop_couchdb $KILL
-    else
-        start_couchdb
-    fi
-}
-
-parse_script_option_list $@

http://git-wip-us.apache.org/repos/asf/couchdb/blob/96057002/bin/erlang-version.escript
----------------------------------------------------------------------
diff --git a/bin/erlang-version.escript b/bin/erlang-version.escript
deleted file mode 100644
index 66aae1c..0000000
--- a/bin/erlang-version.escript
+++ /dev/null
@@ -1,3 +0,0 @@
-
-main(_) ->
-  io:format("~s~n", [erlang:system_info(otp_release)]).

http://git-wip-us.apache.org/repos/asf/couchdb/blob/96057002/src/etc/couchdb/Makefile.am
----------------------------------------------------------------------
diff --git a/src/etc/couchdb/Makefile.am b/src/etc/couchdb/Makefile.am
deleted file mode 100644
index 51b8fcb..0000000
--- a/src/etc/couchdb/Makefile.am
+++ /dev/null
@@ -1,95 +0,0 @@
-## Licensed under the Apache License, Version 2.0 (the "License"); you may not
-## use this file except in compliance with the License. You may obtain a copy of
-## the License at
-##
-##   http://www.apache.org/licenses/LICENSE-2.0
-##
-## Unless required by applicable law or agreed to in writing, software
-## distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-## WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-## License for the specific language governing permissions and limitations under
-## the License.
-
-couchprivlibdir = $(localerlanglibdir)/couch-$(version)/priv/lib
-devcouchprivlibdir = $(abs_top_builddir)/src/couchdb/priv/.libs
-
-localconf_DATA = default.ini
-noinst_DATA = default_dev.ini local_dev.ini
-
-EXTRA_DIST = local.ini
-
-CLEANFILES = $(localconf_DATA) $(noinst_DATA)
-
-transform = @program_transform_name@
-couchjs_command_name = `echo couchjs | sed '$(transform)'`
-couchjs_dev_command_name = `echo couchjs_dev | sed '$(transform)'`
-
-if WINDOWS
-default.ini: default.ini.tpl
-	sed -e "s|%bindir%|.|g" \
-	    -e "s|%localconfdir%|$(localconfdir)|g" \
-	    -e "s|%localdatadir%|../share/couchdb|g" \
-	    -e "s|%localbuilddatadir%|../share/couchdb|g" \
-	    -e "s|%localstatelibdir%|../var/lib/couchdb|g" \
-	    -e "s|%localstatelogdir%|../var/log/couchdb|g" \
-	    -e "s|%localstaterundir%|../var/run/couchdb|g" \
-	    -e "s|%couchprivlibdir%|../lib/couch-$(version)/priv/lib|g" \
-	    -e "s|%couchjs_command_name%|couchjs.exe|g" \
-	    -e "s|%package_author_name%|$(package_author_name)|g" \
-	    -e "s|%version%|$(version)|g" \
-	< $< > $@
-else
-default.ini: default.ini.tpl
-	sed -e "s|%bindir%|$(bindir)|g" \
-	    -e "s|%localconfdir%|$(localconfdir)|g" \
-	    -e "s|%localdatadir%|$(localdatadir)|g" \
-	    -e "s|%localbuilddatadir%|$(localdatadir)|g" \
-	    -e "s|%locallibdir%|$(locallibdir)|g" \
-	    -e "s|%localstatelibdir%|$(localstatelibdir)|g" \
-	    -e "s|%localstatelogdir%|$(localstatelogdir)|g" \
-	    -e "s|%localstaterundir%|$(localstaterundir)|g" \
-	    -e "s|%couchprivlibdir%|$(couchprivlibdir)|g" \
-	    -e "s|%couchjs_command_name%|$(couchjs_command_name)|g" \
-	    -e "s|%package_author_name%|$(package_author_name)|g" \
-	    -e "s|%version%|$(version)|g" \
-	< $< > $@
-endif
-
-default_dev.ini: default.ini.tpl
-	sed -e "s|%bindir%|$(abs_top_builddir)/bin|g" \
-	    -e "s|%localconfdir%|$(abs_top_builddir)/etc/couchdb|g" \
-	    -e "s|%localdatadir%|$(abs_top_srcdir)/share|g" \
-	    -e "s|%locallibdir%|$(abs_top_builddir)/tmp|g" \
-	    -e "s|%localbuilddatadir%|$(abs_top_builddir)/share|g" \
-	    -e "s|%localstatelibdir%|$(abs_top_builddir)/tmp/lib|g" \
-	    -e "s|%localstatelogdir%|$(abs_top_builddir)/tmp/log|g" \
-	    -e "s|%localstaterundir%|$(abs_top_builddir)/tmp/run|g" \
-	    -e "s|%couchprivlibdir%|$(devcouchprivlibdir)|g" \
-	    -e "s|%couchjs_command_name%|$(couchjs_dev_command_name)|g" \
-	    -e "s|%package_author_name%|$(package_author_name)|g" \
-	    -e "s|%version%|$(version)|g" \
-	< $< > $@
-
-# Noah said to not specify local.ini but it borks
-# VPATH builds that make distcheck uses.
-local_dev.ini: local.ini
-	if test ! -f "$@"; then \
-	    cp $< $@; \
-	    chmod +w $@; \
-	fi
-
-install-data-hook:
-	if test ! -f "$(DESTDIR)$(localconfdir)/local.ini"; then \
-	    cp $(srcdir)/local.ini "$(DESTDIR)$(localconfdir)/local.ini"; \
-	fi
-	if test ! "$(mkdir_p)" = ""; then \
-	    $(mkdir_p) "$(DESTDIR)$(localconfdir)/default.d"; \
-	    $(mkdir_p) "$(DESTDIR)$(localconfdir)/local.d"; \
-	else \
-	    echo "WARNING: You may have to create these directories by hand."; \
-	    mkdir -p "$(DESTDIR)$(localconfdir)/default.d"; \
-	    mkdir -p "$(DESTDIR)$(localconfdir)/local.d"; \
-	fi
-
-uninstall-local:
-	rm -f "$(DESTDIR)/$(localconfdir)/local.ini"

http://git-wip-us.apache.org/repos/asf/couchdb/blob/96057002/utils/Makefile.am
----------------------------------------------------------------------
diff --git a/utils/Makefile.am b/utils/Makefile.am
deleted file mode 100644
index 5afe707..0000000
--- a/utils/Makefile.am
+++ /dev/null
@@ -1,45 +0,0 @@
-## Licensed under the Apache License, Version 2.0 (the "License"); you may not
-## use this file except in compliance with the License. You may obtain a copy of
-## the License at
-##
-##   http://www.apache.org/licenses/LICENSE-2.0
-##
-## Unless required by applicable law or agreed to in writing, software
-## distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-## WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-## License for the specific language governing permissions and limitations under
-## the License.
-
-noinst_SCRIPTS = run
-
-CLEANFILES = $(noinst_SCRIPTS)
-
-transform = @program_transform_name@
-couchdb_command_name = `echo couchdb | sed '$(transform)'`
-
-run: ../bin/couchdb.tpl
-	sed -e "s|%ERL%|$(ERL)|g" \
-	    -e "s|%ICU_CONFIG%|$(ICU_CONFIG)|g" \
-	    -e "s|%bindir%|$(abs_top_builddir)/bin|g" \
-	    -e "s|%defaultini%|default_dev.ini|g" \
-	    -e "s|%localini%|local_dev.ini|g" \
-	    -e "s|%localerlanglibdir%|$(abs_top_builddir)\/src \
-			-pa $(abs_top_builddir)\/src\/couchdb \
-			-pa $(abs_top_builddir)\/src\/ejson \
-			-pa $(abs_top_builddir)\/src\/erlang-oauth \
-			-pa $(abs_top_builddir)\/src\/ibrowse \
-			-pa $(abs_top_builddir)\/src\/mochiweb \
-			-pa $(abs_top_builddir)\/src\/snappy|g" \
-	    -e "s|%localconfdir%|$(abs_top_builddir)/etc/couchdb|g" \
-	    -e "s|%localstatelogdir%|$(abs_top_builddir)/tmp/log|g" \
-	    -e "s|%localstatelibdir%|$(abs_top_builddir)/tmp/lib|g" \
-	    -e "s|%localstatedir%|$(abs_top_builddir)/tmp|g" \
-	    -e "s|%locallibdir%|$(abs_top_builddir)/tmp|g" \
-	    -e "s|%bug_uri%|@bug_uri@|g" \
-	    -e "s|%package_author_address%|@package_author_address@|g" \
-	    -e "s|%package_author_name%|@package_author_name@|g" \
-	    -e "s|%package_name%|@package_name@|g" \
-	    -e "s|%version%|@version@|g" \
-	    -e "s|%couchdb_command_name%|$(couchdb_command_name)|g" > \
-	$@ < $<
-	chmod +x $@

http://git-wip-us.apache.org/repos/asf/couchdb/blob/96057002/var/Makefile.am
----------------------------------------------------------------------
diff --git a/var/Makefile.am b/var/Makefile.am
deleted file mode 100644
index 901ab2b..0000000
--- a/var/Makefile.am
+++ /dev/null
@@ -1,23 +0,0 @@
-## Licensed under the Apache License, Version 2.0 (the "License"); you may not
-## use this file except in compliance with the License. You may obtain a copy of
-## the License at
-##
-##   http://www.apache.org/licenses/LICENSE-2.0
-##
-## Unless required by applicable law or agreed to in writing, software
-## distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-## WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-## License for the specific language governing permissions and limitations under
-## the License.
-
-install-data-hook:
-	if test ! "$(mkdir_p)" = ""; then \
-	    $(mkdir_p) "$(DESTDIR)$(localstatelibdir)"; \
-	    $(mkdir_p) "$(DESTDIR)$(localstatelogdir)"; \
-	    $(mkdir_p) "$(DESTDIR)$(localstaterundir)"; \
-	else \
-	    echo "WARNING: You may have to create these directories by hand."; \
-	    mkdir -p "$(DESTDIR)$(localstatelibdir)"; \
-	    mkdir -p "$(DESTDIR)$(localstatelogdir)"; \
-	    mkdir -p "$(DESTDIR)$(localstaterundir)"; \
-	fi


[48/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_config.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_config.erl b/apps/couch/src/couch_config.erl
deleted file mode 100644
index 22d7cdc..0000000
--- a/apps/couch/src/couch_config.erl
+++ /dev/null
@@ -1,251 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
-% Reads CouchDB's ini file and gets queried for configuration parameters.
-% This module is initialized with a list of ini files that it consecutively
-% reads Key/Value pairs from and saves them in an ets table. If more than one
-% ini file is specified, the last one is used to write changes that are made
-% with store/2 back to that ini file.
-
--module(couch_config).
--behaviour(gen_server).
-
--include("couch_db.hrl").
-
-
--export([start_link/1, stop/0]).
--export([all/0, get/1, get/2, get/3, set/3, set/4, delete/2, delete/3]).
--export([register/1, register/2]).
--export([parse_ini_file/1]).
-
--export([init/1, terminate/2, code_change/3]).
--export([handle_call/3, handle_cast/2, handle_info/2]).
-
--record(config, {
-    notify_funs=[],
-    write_filename=undefined
-}).
-
-
-start_link(IniFiles) ->
-    gen_server:start_link({local, ?MODULE}, ?MODULE, IniFiles, []).
-
-stop() ->
-    gen_server:cast(?MODULE, stop).
-
-
-all() ->
-    lists:sort(gen_server:call(?MODULE, all, infinity)).
-
-
-get(Section) when is_binary(Section) ->
-    ?MODULE:get(?b2l(Section));
-get(Section) ->
-    Matches = ets:match(?MODULE, {{Section, '$1'}, '$2'}),
-    [{Key, Value} || [Key, Value] <- Matches].
-
-get(Section, Key) ->
-    ?MODULE:get(Section, Key, undefined).
-
-get(Section, Key, Default) when is_binary(Section) and is_binary(Key) ->
-    ?MODULE:get(?b2l(Section), ?b2l(Key), Default);
-get(Section, Key, Default) ->
-    case ets:lookup(?MODULE, {Section, Key}) of
-        [] -> Default;
-        [{_, Match}] -> Match
-    end.
-
-set(Section, Key, Value) ->
-    ?MODULE:set(Section, Key, Value, true).
-
-set(Section, Key, Value, Persist) when is_binary(Section) and is_binary(Key)  ->
-    ?MODULE:set(?b2l(Section), ?b2l(Key), Value, Persist);
-set(Section, Key, Value, Persist) ->
-    gen_server:call(?MODULE, {set, Section, Key, Value, Persist}).
-
-
-delete(Section, Key) when is_binary(Section) and is_binary(Key) ->
-    delete(?b2l(Section), ?b2l(Key));
-delete(Section, Key) ->
-    delete(Section, Key, true).
-
-delete(Section, Key, Persist) when is_binary(Section) and is_binary(Key) ->
-    delete(?b2l(Section), ?b2l(Key), Persist);
-delete(Section, Key, Persist) ->
-    gen_server:call(?MODULE, {delete, Section, Key, Persist}).
-
-
-register(Fun) ->
-    ?MODULE:register(Fun, self()).
-
-register(Fun, Pid) ->
-    gen_server:call(?MODULE, {register, Fun, Pid}).
-
-
-init(IniFiles) ->
-    ets:new(?MODULE, [named_table, set, protected]),
-    try
-        lists:foreach(fun(IniFile) ->
-            {ok, ParsedIniValues} = parse_ini_file(IniFile),
-            ets:insert(?MODULE, ParsedIniValues)
-        end, IniFiles),
-        WriteFile = case IniFiles of
-            [_|_] -> lists:last(IniFiles);
-            _ -> undefined
-        end,
-        {ok, #config{write_filename = WriteFile}}
-    catch _Tag:Error ->
-        {stop, Error}
-    end.
-
-
-terminate(_Reason, _State) ->
-    ok.
-
-
-handle_call(all, _From, Config) ->
-    Resp = lists:sort((ets:tab2list(?MODULE))),
-    {reply, Resp, Config};
-handle_call({set, Sec, Key, Val, Persist}, From, Config) ->
-    Result = case {Persist, Config#config.write_filename} of
-        {true, undefined} ->
-            ok;
-        {true, FileName} ->
-            couch_config_writer:save_to_file({{Sec, Key}, Val}, FileName);
-        _ ->
-            ok
-    end,
-    case Result of
-    ok ->
-        true = ets:insert(?MODULE, {{Sec, Key}, Val}),
-        spawn_link(fun() ->
-            [catch F(Sec, Key, Val, Persist) || {_Pid, F} <- Config#config.notify_funs],
-                gen_server:reply(From, ok)
-        end),
-        {noreply, Config};
-    _Error ->
-        {reply, Result, Config}
-    end;
-handle_call({delete, Sec, Key, Persist}, From, Config) ->
-    true = ets:delete(?MODULE, {Sec,Key}),
-    case {Persist, Config#config.write_filename} of
-        {true, undefined} ->
-            ok;
-        {true, FileName} ->
-            couch_config_writer:save_to_file({{Sec, Key}, ""}, FileName);
-        _ ->
-            ok
-    end,
-    spawn_link(fun() ->
-        [catch F(Sec, Key, deleted, Persist) || {_Pid, F} <- Config#config.notify_funs],
-            gen_server:reply(From, ok)
-    end),
-    {noreply, Config};
-handle_call({register, Fun, Pid}, _From, #config{notify_funs=PidFuns}=Config) ->
-    erlang:monitor(process, Pid),
-    % convert 1 and 2 arity to 3 arity
-    Fun2 =
-    case Fun of
-        _ when is_function(Fun, 1) ->
-            fun(Section, _Key, _Value, _Persist) -> Fun(Section) end;
-        _ when is_function(Fun, 2) ->
-            fun(Section, Key, _Value, _Persist) -> Fun(Section, Key) end;
-        _ when is_function(Fun, 3) ->
-            fun(Section, Key, Value, _Persist) -> Fun(Section, Key, Value) end;
-        _ when is_function(Fun, 4) ->
-            Fun
-    end,
-    {reply, ok, Config#config{notify_funs=[{Pid, Fun2} | PidFuns]}}.
-
-
-handle_cast(stop, State) ->
-    {stop, normal, State};
-handle_cast(_Msg, State) ->
-    {noreply, State}.
-
-handle_info({'DOWN', _, _, DownPid, _}, #config{notify_funs=PidFuns}=Config) ->
-    % remove any funs registered by the downed process
-    FilteredPidFuns = [{Pid,Fun} || {Pid,Fun} <- PidFuns, Pid /= DownPid],
-    {noreply, Config#config{notify_funs=FilteredPidFuns}}.
-
-code_change(_OldVsn, State, _Extra) ->
-    {ok, State}.
-
-
-parse_ini_file(IniFile) ->
-    IniFilename = couch_util:abs_pathname(IniFile),
-    IniBin =
-    case file:read_file(IniFilename) of
-        {ok, IniBin0} ->
-            IniBin0;
-        {error, Reason} = Error ->
-            ?LOG_ERROR("Could not read server configuration file ~s: ~s",
-                [IniFilename, file:format_error(Reason)]),
-            throw(Error)
-    end,
-
-    Lines = re:split(IniBin, "\r\n|\n|\r|\032", [{return, list}]),
-    {_, ParsedIniValues} =
-    lists:foldl(fun(Line, {AccSectionName, AccValues}) ->
-            case string:strip(Line) of
-            "[" ++ Rest ->
-                case re:split(Rest, "\\]", [{return, list}]) of
-                [NewSectionName, ""] ->
-                    {NewSectionName, AccValues};
-                _Else -> % end bracket not at end, ignore this line
-                    {AccSectionName, AccValues}
-                end;
-            ";" ++ _Comment ->
-                {AccSectionName, AccValues};
-            Line2 ->
-                case re:split(Line2, "\s*=\s*", [{return, list}]) of
-                [Value] ->
-                    MultiLineValuePart = case re:run(Line, "^ \\S", []) of
-                    {match, _} ->
-                        true;
-                    _ ->
-                        false
-                    end,
-                    case {MultiLineValuePart, AccValues} of
-                    {true, [{{_, ValueName}, PrevValue} | AccValuesRest]} ->
-                        % remove comment
-                        case re:split(Value, " ;|\t;", [{return, list}]) of
-                        [[]] ->
-                            % empty line
-                            {AccSectionName, AccValues};
-                        [LineValue | _Rest] ->
-                            E = {{AccSectionName, ValueName},
-                                PrevValue ++ " " ++ LineValue},
-                            {AccSectionName, [E | AccValuesRest]}
-                        end;
-                    _ ->
-                        {AccSectionName, AccValues}
-                    end;
-                [""|_LineValues] -> % line begins with "=", ignore
-                    {AccSectionName, AccValues};
-                [ValueName|LineValues] -> % yeehaw, got a line!
-                    RemainingLine = couch_util:implode(LineValues, "="),
-                    % removes comments
-                    case re:split(RemainingLine, " ;|\t;", [{return, list}]) of
-                    [[]] ->
-                        % empty line means delete this key
-                        ets:delete(?MODULE, {AccSectionName, ValueName}),
-                        {AccSectionName, AccValues};
-                    [LineValue | _Rest] ->
-                        {AccSectionName,
-                            [{{AccSectionName, ValueName}, LineValue} | AccValues]}
-                    end
-                end
-            end
-        end, {"", []}, Lines),
-    {ok, ParsedIniValues}.
-

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_config_writer.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_config_writer.erl b/apps/couch/src/couch_config_writer.erl
deleted file mode 100644
index 21f1c3f..0000000
--- a/apps/couch/src/couch_config_writer.erl
+++ /dev/null
@@ -1,88 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
-%% @doc Saves a Key/Value pair to a ini file. The Key consists of a Section
-%%      and Option combination. If that combination is found in the ini file
-%%      the new value replaces the old value. If only the Section is found the
-%%      Option and value combination is appended to the Section. If the Section
-%%      does not yet exist in the ini file, it is added and the Option/Value
-%%      pair is appended.
-%% @see couch_config
-
--module(couch_config_writer).
-
--export([save_to_file/2]).
-
--include("couch_db.hrl").
-
-%% @spec save_to_file(
-%%           Config::{{Section::string(), Option::string()}, Value::string()},
-%%           File::filename()) -> ok
-%% @doc Saves a Section/Key/Value triple to the ini file File::filename()
-save_to_file({{Section, Key}, Value}, File) ->
-    {ok, OldFileContents} = file:read_file(File),
-    Lines = re:split(OldFileContents, "\r\n|\n|\r|\032", [{return, list}]),
-
-    SectionLine = "[" ++ Section ++ "]",
-    {ok, Pattern} = re:compile(["^(", Key, "\\s*=)|\\[[a-zA-Z0-9\_-]*\\]"]),
-
-    NewLines = process_file_lines(Lines, [], SectionLine, Pattern, Key, Value),
-    NewFileContents = reverse_and_add_newline(strip_empty_lines(NewLines), []),
-    case file:write_file(File, NewFileContents) of
-    ok ->
-        ok;
-    {error, Reason} = Error ->
-        ?LOG_ERROR("Could not write config file ~s: ~s",
-            [File, file:format_error(Reason)]),
-        Error
-    end.
-
-
-process_file_lines([Section|Rest], SeenLines, Section, Pattern, Key, Value) ->
-    process_section_lines(Rest, [Section|SeenLines], Pattern, Key, Value);
-
-process_file_lines([Line|Rest], SeenLines, Section, Pattern, Key, Value) ->
-    process_file_lines(Rest, [Line|SeenLines], Section, Pattern, Key, Value);
-
-process_file_lines([], SeenLines, Section, _Pattern, Key, Value) ->
-    % Section wasn't found.  Append it with the option here.
-    [Key ++ " = " ++ Value, Section, "" | strip_empty_lines(SeenLines)].
-
-
-process_section_lines([Line|Rest], SeenLines, Pattern, Key, Value) ->
-    case re:run(Line, Pattern, [{capture, all_but_first}]) of
-    nomatch -> % Found nothing interesting. Move on.
-        process_section_lines(Rest, [Line|SeenLines], Pattern, Key, Value);
-    {match, []} -> % Found another section. Append the option here.
-        lists:reverse(Rest) ++
-        [Line, "", Key ++ " = " ++ Value | strip_empty_lines(SeenLines)];
-    {match, _} -> % Found the option itself. Replace it.
-        lists:reverse(Rest) ++ [Key ++ " = " ++ Value | SeenLines]
-    end;
-
-process_section_lines([], SeenLines, _Pattern, Key, Value) ->
-    % Found end of file within the section. Append the option here.
-    [Key ++ " = " ++ Value | strip_empty_lines(SeenLines)].
-
-
-reverse_and_add_newline([Line|Rest], Content) ->
-    reverse_and_add_newline(Rest, [Line, "\n", Content]);
-
-reverse_and_add_newline([], Content) ->
-    Content.
-
-
-strip_empty_lines(["" | Rest]) ->
-    strip_empty_lines(Rest);
-
-strip_empty_lines(All) ->
-    All.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_db.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_db.erl b/apps/couch/src/couch_db.erl
deleted file mode 100644
index 11ea0fd..0000000
--- a/apps/couch/src/couch_db.erl
+++ /dev/null
@@ -1,1358 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
--module(couch_db).
--behaviour(gen_server).
-
--export([open/2,open_int/2,close/1,create/2,get_db_info/1,get_design_docs/1]).
--export([start_compact/1, cancel_compact/1]).
--export([open_ref_counted/2,is_idle/1,monitor/1,count_changes_since/2]).
--export([update_doc/3,update_doc/4,update_docs/4,update_docs/2,update_docs/3,delete_doc/3]).
--export([get_doc_info/2,get_full_doc_info/2,get_full_doc_infos/2]).
--export([open_doc/2,open_doc/3,open_doc_revs/4]).
--export([set_revs_limit/2,get_revs_limit/1]).
--export([get_missing_revs/2,name/1,get_update_seq/1,get_committed_update_seq/1]).
--export([enum_docs/4,enum_docs_since/5]).
--export([enum_docs_since_reduce_to_count/1,enum_docs_reduce_to_count/1]).
--export([increment_update_seq/1,get_purge_seq/1,purge_docs/2,get_last_purged/1]).
--export([start_link/3,open_doc_int/3,ensure_full_commit/1]).
--export([set_security/2,get_security/1]).
--export([init/1,terminate/2,handle_call/3,handle_cast/2,code_change/3,handle_info/2]).
--export([changes_since/4,changes_since/5,read_doc/2,new_revid/1]).
--export([check_is_admin/1, check_is_member/1]).
--export([reopen/1, is_system_db/1, compression/1]).
-
--include("couch_db.hrl").
-
-
-start_link(DbName, Filepath, Options) ->
-    case open_db_file(Filepath, Options) of
-    {ok, Fd} ->
-        StartResult = gen_server:start_link(couch_db, {DbName, Filepath, Fd, Options}, []),
-        unlink(Fd),
-        StartResult;
-    Else ->
-        Else
-    end.
-
-open_db_file(Filepath, Options) ->
-    case couch_file:open(Filepath, Options) of
-    {ok, Fd} ->
-        {ok, Fd};
-    {error, enoent} ->
-        % couldn't find file. is there a compact version? This can happen if
-        % crashed during the file switch.
-        case couch_file:open(Filepath ++ ".compact", [nologifmissing]) of
-        {ok, Fd} ->
-            ?LOG_INFO("Found ~s~s compaction file, using as primary storage.", [Filepath, ".compact"]),
-            ok = file:rename(Filepath ++ ".compact", Filepath),
-            ok = couch_file:sync(Fd),
-            {ok, Fd};
-        {error, enoent} ->
-            {not_found, no_db_file}
-        end;
-    Error ->
-        Error
-    end.
-
-
-create(DbName, Options) ->
-    couch_server:create(DbName, Options).
-
-% this is for opening a database for internal purposes like the replicator
-% or the view indexer. it never throws a reader error.
-open_int(DbName, Options) ->
-    couch_server:open(DbName, Options).
-
-% this should be called anytime an http request opens the database.
-% it ensures that the http userCtx is a valid reader
-open(DbName, Options) ->
-    case couch_server:open(DbName, Options) of
-        {ok, Db} ->
-            try
-                check_is_member(Db),
-                {ok, Db}
-            catch
-                throw:Error ->
-                    close(Db),
-                    throw(Error)
-            end;
-        Else -> Else
-    end.
-
-reopen(#db{main_pid = Pid, fd_ref_counter = OldRefCntr, user_ctx = UserCtx}) ->
-    {ok, #db{fd_ref_counter = NewRefCntr} = NewDb} =
-        gen_server:call(Pid, get_db, infinity),
-    case NewRefCntr =:= OldRefCntr of
-    true ->
-        ok;
-    false ->
-        couch_ref_counter:add(NewRefCntr),
-        catch couch_ref_counter:drop(OldRefCntr)
-    end,
-    {ok, NewDb#db{user_ctx = UserCtx}}.
-
-is_system_db(#db{options = Options}) ->
-    lists:member(sys_db, Options).
-
-ensure_full_commit(#db{update_pid=UpdatePid,instance_start_time=StartTime}) ->
-    ok = gen_server:call(UpdatePid, full_commit, infinity),
-    {ok, StartTime}.
-
-close(#db{fd_ref_counter=RefCntr}) ->
-    couch_ref_counter:drop(RefCntr).
-
-open_ref_counted(MainPid, OpenedPid) ->
-    gen_server:call(MainPid, {open_ref_count, OpenedPid}).
-
-is_idle(#db{main_pid = MainPid}) ->
-    is_idle(MainPid);
-is_idle(MainPid) ->
-    gen_server:call(MainPid, is_idle).
-
-monitor(#db{main_pid=MainPid}) ->
-    erlang:monitor(process, MainPid).
-
-start_compact(#db{update_pid=Pid}) ->
-    gen_server:call(Pid, start_compact).
-
-cancel_compact(#db{update_pid=Pid}) ->
-    gen_server:call(Pid, cancel_compact).
-
-delete_doc(Db, Id, Revisions) ->
-    DeletedDocs = [#doc{id=Id, revs=[Rev], deleted=true} || Rev <- Revisions],
-    {ok, [Result]} = update_docs(Db, DeletedDocs, []),
-    {ok, Result}.
-
-open_doc(Db, IdOrDocInfo) ->
-    open_doc(Db, IdOrDocInfo, []).
-
-open_doc(Db, Id, Options) ->
-    increment_stat(Db, {couchdb, database_reads}),
-    case open_doc_int(Db, Id, Options) of
-    {ok, #doc{deleted=true}=Doc} ->
-        case lists:member(deleted, Options) of
-        true ->
-            apply_open_options({ok, Doc},Options);
-        false ->
-            {not_found, deleted}
-        end;
-    Else ->
-        apply_open_options(Else,Options)
-    end.
-
-apply_open_options({ok, Doc},Options) ->
-    apply_open_options2(Doc,Options);
-apply_open_options(Else,_Options) ->
-    Else.
-
-apply_open_options2(Doc,[]) ->
-    {ok, Doc};
-apply_open_options2(#doc{atts=Atts,revs=Revs}=Doc,
-        [{atts_since, PossibleAncestors}|Rest]) ->
-    RevPos = find_ancestor_rev_pos(Revs, PossibleAncestors),
-    apply_open_options2(Doc#doc{atts=[A#att{data=
-        if AttPos>RevPos -> Data; true -> stub end}
-        || #att{revpos=AttPos,data=Data}=A <- Atts]}, Rest);
-apply_open_options2(Doc, [ejson_body | Rest]) ->
-    apply_open_options2(couch_doc:with_ejson_body(Doc), Rest);
-apply_open_options2(Doc,[_|Rest]) ->
-    apply_open_options2(Doc,Rest).
-
-
-find_ancestor_rev_pos({_, []}, _AttsSinceRevs) ->
-    0;
-find_ancestor_rev_pos(_DocRevs, []) ->
-    0;
-find_ancestor_rev_pos({RevPos, [RevId|Rest]}, AttsSinceRevs) ->
-    case lists:member({RevPos, RevId}, AttsSinceRevs) of
-    true ->
-        RevPos;
-    false ->
-        find_ancestor_rev_pos({RevPos - 1, Rest}, AttsSinceRevs)
-    end.
-
-open_doc_revs(Db, Id, Revs, Options) ->
-    increment_stat(Db, {couchdb, database_reads}),
-    [{ok, Results}] = open_doc_revs_int(Db, [{Id, Revs}], Options),
-    {ok, [apply_open_options(Result, Options) || Result <- Results]}.
-
-% Each returned result is a list of tuples:
-% {Id, MissingRevs, PossibleAncestors}
-% if no revs are missing, it's omitted from the results.
-get_missing_revs(Db, IdRevsList) ->
-    Results = get_full_doc_infos(Db, [Id1 || {Id1, _Revs} <- IdRevsList]),
-    {ok, find_missing(IdRevsList, Results)}.
-
-find_missing([], []) ->
-    [];
-find_missing([{Id, Revs}|RestIdRevs], [{ok, FullInfo} | RestLookupInfo]) ->
-    case couch_key_tree:find_missing(FullInfo#full_doc_info.rev_tree, Revs) of
-    [] ->
-        find_missing(RestIdRevs, RestLookupInfo);
-    MissingRevs ->
-        #doc_info{revs=RevsInfo} = couch_doc:to_doc_info(FullInfo),
-        LeafRevs = [Rev || #rev_info{rev=Rev} <- RevsInfo],
-        % Find the revs that are possible parents of this rev
-        PossibleAncestors =
-        lists:foldl(fun({LeafPos, LeafRevId}, Acc) ->
-            % this leaf is a "possible ancenstor" of the missing
-            % revs if this LeafPos lessthan any of the missing revs
-            case lists:any(fun({MissingPos, _}) ->
-                    LeafPos < MissingPos end, MissingRevs) of
-            true ->
-                [{LeafPos, LeafRevId} | Acc];
-            false ->
-                Acc
-            end
-        end, [], LeafRevs),
-        [{Id, MissingRevs, PossibleAncestors} |
-                find_missing(RestIdRevs, RestLookupInfo)]
-    end;
-find_missing([{Id, Revs}|RestIdRevs], [not_found | RestLookupInfo]) ->
-    [{Id, Revs, []} | find_missing(RestIdRevs, RestLookupInfo)].
-
-get_doc_info(Db, Id) ->
-    case get_full_doc_info(Db, Id) of
-    {ok, DocInfo} ->
-        {ok, couch_doc:to_doc_info(DocInfo)};
-    Else ->
-        Else
-    end.
-
-%   returns {ok, DocInfo} or not_found
-get_full_doc_info(Db, Id) ->
-    [Result] = get_full_doc_infos(Db, [Id]),
-    Result.
-
-get_full_doc_infos(Db, Ids) ->
-    couch_btree:lookup(by_id_btree(Db), Ids).
-
-increment_update_seq(#db{update_pid=UpdatePid}) ->
-    gen_server:call(UpdatePid, increment_update_seq).
-
-purge_docs(#db{update_pid=UpdatePid}, IdsRevs) ->
-    gen_server:call(UpdatePid, {purge_docs, IdsRevs}).
-
-get_committed_update_seq(#db{committed_update_seq=Seq}) ->
-    Seq.
-
-get_update_seq(#db{update_seq=Seq})->
-    Seq.
-
-get_purge_seq(#db{header=#db_header{purge_seq=PurgeSeq}})->
-    PurgeSeq.
-
-get_last_purged(#db{header=#db_header{purged_docs=nil}}) ->
-    {ok, []};
-get_last_purged(#db{fd=Fd, header=#db_header{purged_docs=PurgedPointer}}) ->
-    couch_file:pread_term(Fd, PurgedPointer).
-
-get_db_info(Db) ->
-    #db{fd=Fd,
-        header=#db_header{disk_version=DiskVersion},
-        compactor_pid=Compactor,
-        update_seq=SeqNum,
-        name=Name,
-        instance_start_time=StartTime,
-        committed_update_seq=CommittedUpdateSeq,
-        fulldocinfo_by_id_btree = IdBtree,
-        docinfo_by_seq_btree = SeqBtree,
-        local_docs_btree = LocalBtree
-    } = Db,
-    {ok, Size} = couch_file:bytes(Fd),
-    {ok, DbReduction} = couch_btree:full_reduce(by_id_btree(Db)),
-    InfoList = [
-        {db_name, Name},
-        {doc_count, element(1, DbReduction)},
-        {doc_del_count, element(2, DbReduction)},
-        {update_seq, SeqNum},
-        {purge_seq, couch_db:get_purge_seq(Db)},
-        {compact_running, Compactor/=nil},
-        {disk_size, Size},
-        {data_size, db_data_size(DbReduction, [SeqBtree, IdBtree, LocalBtree])},
-        {instance_start_time, StartTime},
-        {disk_format_version, DiskVersion},
-        {committed_update_seq, CommittedUpdateSeq}
-        ],
-    {ok, InfoList}.
-
-db_data_size({_Count, _DelCount}, _Trees) ->
-    % pre 1.2 format, upgraded on compaction
-    null;
-db_data_size({_Count, _DelCount, nil}, _Trees) ->
-    null;
-db_data_size({_Count, _DelCount, DocAndAttsSize}, Trees) ->
-    sum_tree_sizes(DocAndAttsSize, Trees).
-
-sum_tree_sizes(Acc, []) ->
-    Acc;
-sum_tree_sizes(Acc, [T | Rest]) ->
-    case couch_btree:size(T) of
-    nil ->
-        null;
-    Sz ->
-        sum_tree_sizes(Acc + Sz, Rest)
-    end.
-
-get_design_docs(Db) ->
-    FoldFun = skip_deleted(fun
-        (#full_doc_info{deleted = true}, _Reds, Acc) ->
-            {ok, Acc};
-        (#full_doc_info{id= <<"_design/",_/binary>>}=FullDocInfo, _Reds, Acc) ->
-            {ok, [FullDocInfo | Acc]};
-        (_, _Reds, Acc) ->
-            {stop, Acc}
-    end),
-    KeyOpts = [{start_key, <<"_design/">>}, {end_key_gt, <<"_design0">>}],
-    {ok, _, Docs} = couch_btree:fold(by_id_btree(Db), FoldFun, [], KeyOpts),
-    Docs.
-
-check_is_admin(#db{user_ctx=#user_ctx{name=Name,roles=Roles}}=Db) ->
-    {Admins} = get_admins(Db),
-    AdminRoles = [<<"_admin">> | couch_util:get_value(<<"roles">>, Admins, [])],
-    AdminNames = couch_util:get_value(<<"names">>, Admins,[]),
-    case AdminRoles -- Roles of
-    AdminRoles -> % same list, not an admin role
-        case AdminNames -- [Name] of
-        AdminNames -> % same names, not an admin
-            throw({unauthorized, <<"You are not a db or server admin.">>});
-        _ ->
-            ok
-        end;
-    _ ->
-        ok
-    end.
-
-check_is_member(#db{user_ctx=#user_ctx{name=Name,roles=Roles}=UserCtx}=Db) ->
-    case (catch check_is_admin(Db)) of
-    ok -> ok;
-    _ ->
-        {Members} = get_members(Db),
-        ReaderRoles = couch_util:get_value(<<"roles">>, Members,[]),
-        WithAdminRoles = [<<"_admin">> | ReaderRoles],
-        ReaderNames = couch_util:get_value(<<"names">>, Members,[]),
-        case ReaderRoles ++ ReaderNames of
-        [] -> ok; % no readers == public access
-        _Else ->
-            case WithAdminRoles -- Roles of
-            WithAdminRoles -> % same list, not an reader role
-                case ReaderNames -- [Name] of
-                ReaderNames -> % same names, not a reader
-                    ?LOG_DEBUG("Not a reader: UserCtx ~p vs Names ~p Roles ~p",[UserCtx, ReaderNames, WithAdminRoles]),
-                    throw({unauthorized, <<"You are not authorized to access this db.">>});
-                _ ->
-                    ok
-                end;
-            _ ->
-                ok
-            end
-        end
-    end.
-
-get_admins(#db{security=SecProps}) ->
-    couch_util:get_value(<<"admins">>, SecProps, {[]}).
-
-get_members(#db{security=SecProps}) ->
-    % we fallback to readers here for backwards compatibility
-    couch_util:get_value(<<"members">>, SecProps,
-        couch_util:get_value(<<"readers">>, SecProps, {[]})).
-
-get_security(#db{security=SecProps}) ->
-    {SecProps}.
-
-set_security(#db{update_pid=Pid}=Db, {NewSecProps}) when is_list(NewSecProps) ->
-    check_is_admin(Db),
-    ok = validate_security_object(NewSecProps),
-    ok = gen_server:call(Pid, {set_security, NewSecProps}, infinity),
-    {ok, _} = ensure_full_commit(Db),
-    ok;
-set_security(_, _) ->
-    throw(bad_request).
-
-validate_security_object(SecProps) ->
-    Admins = couch_util:get_value(<<"admins">>, SecProps, {[]}),
-    % we fallback to readers here for backwards compatibility
-    Members = couch_util:get_value(<<"members">>, SecProps,
-        couch_util:get_value(<<"readers">>, SecProps, {[]})),
-    ok = validate_names_and_roles(Admins),
-    ok = validate_names_and_roles(Members),
-    ok.
-
-% validate user input
-validate_names_and_roles({Props}) when is_list(Props) ->
-    case couch_util:get_value(<<"names">>,Props,[]) of
-    Ns when is_list(Ns) ->
-            [throw("names must be a JSON list of strings") ||N <- Ns, not is_binary(N)],
-            Ns;
-    _ -> throw("names must be a JSON list of strings")
-    end,
-    case couch_util:get_value(<<"roles">>,Props,[]) of
-    Rs when is_list(Rs) ->
-        [throw("roles must be a JSON list of strings") ||R <- Rs, not is_binary(R)],
-        Rs;
-    _ -> throw("roles must be a JSON list of strings")
-    end,
-    ok.
-
-get_revs_limit(#db{revs_limit=Limit}) ->
-    Limit.
-
-set_revs_limit(#db{update_pid=Pid}=Db, Limit) when Limit > 0 ->
-    check_is_admin(Db),
-    gen_server:call(Pid, {set_revs_limit, Limit}, infinity);
-set_revs_limit(_Db, _Limit) ->
-    throw(invalid_revs_limit).
-
-name(#db{name=Name}) ->
-    Name.
-
-compression(#db{compression=Compression}) ->
-    Compression.
-
-update_doc(Db, Doc, Options) ->
-    update_doc(Db, Doc, Options, interactive_edit).
-
-update_doc(Db, Doc, Options, UpdateType) ->
-    case update_docs(Db, [Doc], Options, UpdateType) of
-    {ok, [{ok, NewRev}]} ->
-        {ok, NewRev};
-    {ok, [{{_Id, _Rev}, Error}]} ->
-        throw(Error);
-    {ok, [Error]} ->
-        throw(Error);
-    {ok, []} ->
-        % replication success
-        {Pos, [RevId | _]} = Doc#doc.revs,
-        {ok, {Pos, RevId}}
-    end.
-
-update_docs(Db, Docs) ->
-    update_docs(Db, Docs, []).
-
-% group_alike_docs groups the sorted documents into sublist buckets, by id.
-% ([DocA, DocA, DocB, DocC], []) -> [[DocA, DocA], [DocB], [DocC]]
-group_alike_docs(Docs) ->
-    Sorted = lists:sort(fun({#doc{id=A},_},{#doc{id=B},_})-> A < B end, Docs),
-    group_alike_docs(Sorted, []).
-
-group_alike_docs([], Buckets) ->
-    lists:reverse(lists:map(fun lists:reverse/1, Buckets));
-group_alike_docs([Doc|Rest], []) ->
-    group_alike_docs(Rest, [[Doc]]);
-group_alike_docs([{Doc,Ref}|Rest], [Bucket|RestBuckets]) ->
-    [{#doc{id=BucketId},_Ref}|_] = Bucket,
-    case Doc#doc.id == BucketId of
-    true ->
-        % add to existing bucket
-        group_alike_docs(Rest, [[{Doc,Ref}|Bucket]|RestBuckets]);
-    false ->
-        % add to new bucket
-       group_alike_docs(Rest, [[{Doc,Ref}]|[Bucket|RestBuckets]])
-    end.
-
-validate_doc_update(#db{}=Db, #doc{id= <<"_design/",_/binary>>}, _GetDiskDocFun) ->
-    catch check_is_admin(Db);
-validate_doc_update(#db{validate_doc_funs=[]}, _Doc, _GetDiskDocFun) ->
-    ok;
-validate_doc_update(_Db, #doc{id= <<"_local/",_/binary>>}, _GetDiskDocFun) ->
-    ok;
-validate_doc_update(Db, Doc, GetDiskDocFun) ->
-    DiskDoc = GetDiskDocFun(),
-    JsonCtx = couch_util:json_user_ctx(Db),
-    SecObj = get_security(Db),
-    try [case Fun(Doc, DiskDoc, JsonCtx, SecObj) of
-            ok -> ok;
-            Error -> throw(Error)
-        end || Fun <- Db#db.validate_doc_funs],
-        ok
-    catch
-        throw:Error ->
-            Error
-    end.
-
-
-prep_and_validate_update(Db, #doc{id=Id,revs={RevStart, Revs}}=Doc,
-        OldFullDocInfo, LeafRevsDict, AllowConflict) ->
-    case Revs of
-    [PrevRev|_] ->
-        case dict:find({RevStart, PrevRev}, LeafRevsDict) of
-        {ok, {Deleted, DiskSp, DiskRevs}} ->
-            case couch_doc:has_stubs(Doc) of
-            true ->
-                DiskDoc = make_doc(Db, Id, Deleted, DiskSp, DiskRevs),
-                Doc2 = couch_doc:merge_stubs(Doc, DiskDoc),
-                {validate_doc_update(Db, Doc2, fun() -> DiskDoc end), Doc2};
-            false ->
-                LoadDiskDoc = fun() -> make_doc(Db,Id,Deleted,DiskSp,DiskRevs) end,
-                {validate_doc_update(Db, Doc, LoadDiskDoc), Doc}
-            end;
-        error when AllowConflict ->
-            couch_doc:merge_stubs(Doc, #doc{}), % will generate error if
-                                                        % there are stubs
-            {validate_doc_update(Db, Doc, fun() -> nil end), Doc};
-        error ->
-            {conflict, Doc}
-        end;
-    [] ->
-        % new doc, and we have existing revs.
-        % reuse existing deleted doc
-        if OldFullDocInfo#full_doc_info.deleted orelse AllowConflict ->
-            {validate_doc_update(Db, Doc, fun() -> nil end), Doc};
-        true ->
-            {conflict, Doc}
-        end
-    end.
-
-
-
-prep_and_validate_updates(_Db, [], [], _AllowConflict, AccPrepped,
-        AccFatalErrors) ->
-   {AccPrepped, AccFatalErrors};
-prep_and_validate_updates(Db, [DocBucket|RestBuckets], [not_found|RestLookups],
-        AllowConflict, AccPrepped, AccErrors) ->
-    {PreppedBucket, AccErrors3} = lists:foldl(
-        fun({#doc{revs=Revs}=Doc,Ref}, {AccBucket, AccErrors2}) ->
-            case couch_doc:has_stubs(Doc) of
-            true ->
-                couch_doc:merge_stubs(Doc, #doc{}); % will throw exception
-            false -> ok
-            end,
-            case Revs of
-            {0, []} ->
-                case validate_doc_update(Db, Doc, fun() -> nil end) of
-                ok ->
-                    {[{Doc, Ref} | AccBucket], AccErrors2};
-                Error ->
-                    {AccBucket, [{Ref, Error} | AccErrors2]}
-                end;
-            _ ->
-                % old revs specified but none exist, a conflict
-                {AccBucket, [{Ref, conflict} | AccErrors2]}
-            end
-        end,
-        {[], AccErrors}, DocBucket),
-
-    prep_and_validate_updates(Db, RestBuckets, RestLookups, AllowConflict,
-            [lists:reverse(PreppedBucket) | AccPrepped], AccErrors3);
-prep_and_validate_updates(Db, [DocBucket|RestBuckets],
-        [{ok, #full_doc_info{rev_tree=OldRevTree}=OldFullDocInfo}|RestLookups],
-        AllowConflict, AccPrepped, AccErrors) ->
-    Leafs = couch_key_tree:get_all_leafs(OldRevTree),
-    LeafRevsDict = dict:from_list([
-        begin
-            Deleted = element(1, LeafVal),
-            Sp = element(2, LeafVal),
-            {{Start, RevId}, {Deleted, Sp, Revs}}
-        end ||
-        {LeafVal, {Start, [RevId | _]} = Revs} <- Leafs
-    ]),
-    {PreppedBucket, AccErrors3} = lists:foldl(
-        fun({Doc, Ref}, {Docs2Acc, AccErrors2}) ->
-            case prep_and_validate_update(Db, Doc, OldFullDocInfo,
-                    LeafRevsDict, AllowConflict) of
-            {ok, Doc2} ->
-                {[{Doc2, Ref} | Docs2Acc], AccErrors2};
-            {Error, #doc{}} ->
-                % Record the error
-                {Docs2Acc, [{Ref, Error} |AccErrors2]}
-            end
-        end,
-        {[], AccErrors}, DocBucket),
-    prep_and_validate_updates(Db, RestBuckets, RestLookups, AllowConflict,
-            [PreppedBucket | AccPrepped], AccErrors3).
-
-
-update_docs(Db, Docs, Options) ->
-    update_docs(Db, Docs, Options, interactive_edit).
-
-
-prep_and_validate_replicated_updates(_Db, [], [], AccPrepped, AccErrors) ->
-    Errors2 = [{{Id, {Pos, Rev}}, Error} ||
-            {#doc{id=Id,revs={Pos,[Rev|_]}}, Error} <- AccErrors],
-    {lists:reverse(AccPrepped), lists:reverse(Errors2)};
-prep_and_validate_replicated_updates(Db, [Bucket|RestBuckets], [OldInfo|RestOldInfo], AccPrepped, AccErrors) ->
-    case OldInfo of
-    not_found ->
-        {ValidatedBucket, AccErrors3} = lists:foldl(
-            fun({Doc, Ref}, {AccPrepped2, AccErrors2}) ->
-                case couch_doc:has_stubs(Doc) of
-                true ->
-                    couch_doc:merge_stubs(Doc, #doc{}); % will throw exception
-                false -> ok
-                end,
-                case validate_doc_update(Db, Doc, fun() -> nil end) of
-                ok ->
-                    {[{Doc, Ref} | AccPrepped2], AccErrors2};
-                Error ->
-                    {AccPrepped2, [{Doc, Error} | AccErrors2]}
-                end
-            end,
-            {[], AccErrors}, Bucket),
-        prep_and_validate_replicated_updates(Db, RestBuckets, RestOldInfo, [ValidatedBucket | AccPrepped], AccErrors3);
-    {ok, #full_doc_info{rev_tree=OldTree}} ->
-        NewRevTree = lists:foldl(
-            fun({NewDoc, _Ref}, AccTree) ->
-                {NewTree, _} = couch_key_tree:merge(AccTree,
-                    couch_doc:to_path(NewDoc), Db#db.revs_limit),
-                NewTree
-            end,
-            OldTree, Bucket),
-        Leafs = couch_key_tree:get_all_leafs_full(NewRevTree),
-        LeafRevsFullDict = dict:from_list( [{{Start, RevId}, FullPath} || {Start, [{RevId, _}|_]}=FullPath <- Leafs]),
-        {ValidatedBucket, AccErrors3} =
-        lists:foldl(
-            fun({#doc{id=Id,revs={Pos, [RevId|_]}}=Doc, Ref}, {AccValidated, AccErrors2}) ->
-                case dict:find({Pos, RevId}, LeafRevsFullDict) of
-                {ok, {Start, Path}} ->
-                    % our unflushed doc is a leaf node. Go back on the path
-                    % to find the previous rev that's on disk.
-
-                    LoadPrevRevFun = fun() ->
-                                make_first_doc_on_disk(Db,Id,Start-1, tl(Path))
-                            end,
-
-                    case couch_doc:has_stubs(Doc) of
-                    true ->
-                        DiskDoc = LoadPrevRevFun(),
-                        Doc2 = couch_doc:merge_stubs(Doc, DiskDoc),
-                        GetDiskDocFun = fun() -> DiskDoc end;
-                    false ->
-                        Doc2 = Doc,
-                        GetDiskDocFun = LoadPrevRevFun
-                    end,
-
-                    case validate_doc_update(Db, Doc2, GetDiskDocFun) of
-                    ok ->
-                        {[{Doc2, Ref} | AccValidated], AccErrors2};
-                    Error ->
-                        {AccValidated, [{Doc, Error} | AccErrors2]}
-                    end;
-                _ ->
-                    % this doc isn't a leaf or already exists in the tree.
-                    % ignore but consider it a success.
-                    {AccValidated, AccErrors2}
-                end
-            end,
-            {[], AccErrors}, Bucket),
-        prep_and_validate_replicated_updates(Db, RestBuckets, RestOldInfo,
-                [ValidatedBucket | AccPrepped], AccErrors3)
-    end.
-
-
-
-new_revid(#doc{body=Body,revs={OldStart,OldRevs},
-        atts=Atts,deleted=Deleted}) ->
-    case [{N, T, M} || #att{name=N,type=T,md5=M} <- Atts, M =/= <<>>] of
-    Atts2 when length(Atts) =/= length(Atts2) ->
-        % We must have old style non-md5 attachments
-        ?l2b(integer_to_list(couch_util:rand32()));
-    Atts2 ->
-        OldRev = case OldRevs of [] -> 0; [OldRev0|_] -> OldRev0 end,
-        couch_util:md5(term_to_binary([Deleted, OldStart, OldRev, Body, Atts2]))
-    end.
-
-new_revs([], OutBuckets, IdRevsAcc) ->
-    {lists:reverse(OutBuckets), IdRevsAcc};
-new_revs([Bucket|RestBuckets], OutBuckets, IdRevsAcc) ->
-    {NewBucket, IdRevsAcc3} = lists:mapfoldl(
-        fun({#doc{revs={Start, RevIds}}=Doc, Ref}, IdRevsAcc2)->
-        NewRevId = new_revid(Doc),
-        {{Doc#doc{revs={Start+1, [NewRevId | RevIds]}}, Ref},
-            [{Ref, {ok, {Start+1, NewRevId}}} | IdRevsAcc2]}
-    end, IdRevsAcc, Bucket),
-    new_revs(RestBuckets, [NewBucket|OutBuckets], IdRevsAcc3).
-
-check_dup_atts(#doc{atts=Atts}=Doc) ->
-    Atts2 = lists:sort(fun(#att{name=N1}, #att{name=N2}) -> N1 < N2 end, Atts),
-    check_dup_atts2(Atts2),
-    Doc.
-
-check_dup_atts2([#att{name=N}, #att{name=N} | _]) ->
-    throw({bad_request, <<"Duplicate attachments">>});
-check_dup_atts2([_ | Rest]) ->
-    check_dup_atts2(Rest);
-check_dup_atts2(_) ->
-    ok.
-
-
-update_docs(Db, Docs, Options, replicated_changes) ->
-    increment_stat(Db, {couchdb, database_writes}),
-    % associate reference with each doc in order to track duplicates
-    Docs2 = lists:map(fun(Doc) -> {Doc, make_ref()} end, Docs),
-    DocBuckets = before_docs_update(Db, group_alike_docs(Docs2)),
-    case (Db#db.validate_doc_funs /= []) orelse
-        lists:any(
-            fun({#doc{id= <<?DESIGN_DOC_PREFIX, _/binary>>}, _Ref}) -> true;
-            ({#doc{atts=Atts}, _Ref}) ->
-                Atts /= []
-            end, Docs2) of
-    true ->
-        Ids = [Id || [{#doc{id=Id}, _Ref}|_] <- DocBuckets],
-        ExistingDocs = get_full_doc_infos(Db, Ids),
-
-        {DocBuckets2, DocErrors} =
-                prep_and_validate_replicated_updates(Db, DocBuckets, ExistingDocs, [], []),
-        DocBuckets3 = [Bucket || [_|_]=Bucket <- DocBuckets2]; % remove empty buckets
-    false ->
-        DocErrors = [],
-        DocBuckets3 = DocBuckets
-    end,
-    DocBuckets4 = [[{doc_flush_atts(check_dup_atts(Doc), Db#db.updater_fd), Ref}
-            || {Doc, Ref} <- Bucket] || Bucket <- DocBuckets3],
-    {ok, []} = write_and_commit(Db, DocBuckets4, [], [merge_conflicts | Options]),
-    {ok, DocErrors};
-
-update_docs(Db, Docs, Options, interactive_edit) ->
-    increment_stat(Db, {couchdb, database_writes}),
-    AllOrNothing = lists:member(all_or_nothing, Options),
-    % go ahead and generate the new revision ids for the documents.
-    % separate out the NonRep documents from the rest of the documents
-
-    % associate reference with each doc in order to track duplicates
-    Docs2 = lists:map(fun(Doc) -> {Doc, make_ref()} end,Docs),
-    {Docs3, NonRepDocs} = lists:foldl(
-         fun({#doc{id=Id},_Ref}=Doc, {DocsAcc, NonRepDocsAcc}) ->
-            case Id of
-            <<?LOCAL_DOC_PREFIX, _/binary>> ->
-                {DocsAcc, [Doc | NonRepDocsAcc]};
-            Id->
-                {[Doc | DocsAcc], NonRepDocsAcc}
-            end
-        end, {[], []}, Docs2),
-
-    DocBuckets = before_docs_update(Db, group_alike_docs(Docs3)),
-
-    case (Db#db.validate_doc_funs /= []) orelse
-        lists:any(
-            fun({#doc{id= <<?DESIGN_DOC_PREFIX, _/binary>>}, _Ref}) ->
-                true;
-            ({#doc{atts=Atts}, _Ref}) ->
-                Atts /= []
-            end, Docs3) of
-    true ->
-        % lookup the doc by id and get the most recent
-        Ids = [Id || [{#doc{id=Id}, _Ref}|_] <- DocBuckets],
-        ExistingDocInfos = get_full_doc_infos(Db, Ids),
-
-        {DocBucketsPrepped, PreCommitFailures} = prep_and_validate_updates(Db,
-                DocBuckets, ExistingDocInfos, AllOrNothing, [], []),
-
-        % strip out any empty buckets
-        DocBuckets2 = [Bucket || [_|_] = Bucket <- DocBucketsPrepped];
-    false ->
-        PreCommitFailures = [],
-        DocBuckets2 = DocBuckets
-    end,
-
-    if (AllOrNothing) and (PreCommitFailures /= []) ->
-        {aborted,
-         lists:foldl(fun({#doc{id=Id,revs=Revs}, Ref},Acc) ->
-                         case lists:keyfind(Ref,1,PreCommitFailures) of
-                         {Ref, Error} ->
-                             case Revs of
-                             {Pos, [RevId|_]} ->
-                                 [{{Id,{Pos, RevId}}, Error} | Acc];
-                             {0, []} ->
-                                 [{{Id,{0, <<>>}}, Error} | Acc]
-                             end;
-                         false ->
-                             Acc
-                         end
-                     end,[],Docs3)};
-
-    true ->
-        Options2 = if AllOrNothing -> [merge_conflicts];
-                true -> [] end ++ Options,
-        DocBuckets3 = [[
-                {doc_flush_atts(set_new_att_revpos(
-                        check_dup_atts(Doc)), Db#db.updater_fd), Ref}
-                || {Doc, Ref} <- B] || B <- DocBuckets2],
-        {DocBuckets4, IdRevs} = new_revs(DocBuckets3, [], []),
-
-        {ok, CommitResults} = write_and_commit(Db, DocBuckets4, NonRepDocs, Options2),
-
-        ResultsDict = dict:from_list(IdRevs ++ CommitResults ++ PreCommitFailures),
-        {ok, lists:map(
-            fun({#doc{}, Ref}) ->
-                {ok, Result} = dict:find(Ref, ResultsDict),
-                Result
-            end, Docs2)}
-    end.
-
-% Returns the first available document on disk. Input list is a full rev path
-% for the doc.
-make_first_doc_on_disk(_Db, _Id, _Pos, []) ->
-    nil;
-make_first_doc_on_disk(Db, Id, Pos, [{_Rev, #doc{}} | RestPath]) ->
-    make_first_doc_on_disk(Db, Id, Pos-1, RestPath);
-make_first_doc_on_disk(Db, Id, Pos, [{_Rev, ?REV_MISSING}|RestPath]) ->
-    make_first_doc_on_disk(Db, Id, Pos - 1, RestPath);
-make_first_doc_on_disk(Db, Id, Pos, [{_Rev, RevValue} |_]=DocPath) ->
-    IsDel = element(1, RevValue),
-    Sp = element(2, RevValue),
-    Revs = [Rev || {Rev, _} <- DocPath],
-    make_doc(Db, Id, IsDel, Sp, {Pos, Revs}).
-
-set_commit_option(Options) ->
-    CommitSettings = {
-        [true || O <- Options, O==full_commit orelse O==delay_commit],
-        couch_config:get("couchdb", "delayed_commits", "false")
-    },
-    case CommitSettings of
-    {[true], _} ->
-        Options; % user requested explicit commit setting, do not change it
-    {_, "true"} ->
-        Options; % delayed commits are enabled, do nothing
-    {_, "false"} ->
-        [full_commit|Options];
-    {_, Else} ->
-        ?LOG_ERROR("[couchdb] delayed_commits setting must be true/false, not ~p",
-            [Else]),
-        [full_commit|Options]
-    end.
-
-collect_results(UpdatePid, MRef, ResultsAcc) ->
-    receive
-    {result, UpdatePid, Result} ->
-        collect_results(UpdatePid, MRef, [Result | ResultsAcc]);
-    {done, UpdatePid} ->
-        {ok, ResultsAcc};
-    {retry, UpdatePid} ->
-        retry;
-    {'DOWN', MRef, _, _, Reason} ->
-        exit(Reason)
-    end.
-
-write_and_commit(#db{update_pid=UpdatePid}=Db, DocBuckets1,
-        NonRepDocs, Options0) ->
-    DocBuckets = prepare_doc_summaries(Db, DocBuckets1),
-    Options = set_commit_option(Options0),
-    MergeConflicts = lists:member(merge_conflicts, Options),
-    FullCommit = lists:member(full_commit, Options),
-    MRef = erlang:monitor(process, UpdatePid),
-    try
-        UpdatePid ! {update_docs, self(), DocBuckets, NonRepDocs, MergeConflicts, FullCommit},
-        case collect_results(UpdatePid, MRef, []) of
-        {ok, Results} -> {ok, Results};
-        retry ->
-            % This can happen if the db file we wrote to was swapped out by
-            % compaction. Retry by reopening the db and writing to the current file
-            {ok, Db2} = open_ref_counted(Db#db.main_pid, self()),
-            DocBuckets2 = [
-                [{doc_flush_atts(Doc, Db2#db.updater_fd), Ref} || {Doc, Ref} <- Bucket] ||
-                Bucket <- DocBuckets1
-            ],
-            % We only retry once
-            DocBuckets3 = prepare_doc_summaries(Db2, DocBuckets2),
-            close(Db2),
-            UpdatePid ! {update_docs, self(), DocBuckets3, NonRepDocs, MergeConflicts, FullCommit},
-            case collect_results(UpdatePid, MRef, []) of
-            {ok, Results} -> {ok, Results};
-            retry -> throw({update_error, compaction_retry})
-            end
-        end
-    after
-        erlang:demonitor(MRef, [flush])
-    end.
-
-
-prepare_doc_summaries(Db, BucketList) ->
-    [lists:map(
-        fun({#doc{body = Body, atts = Atts} = Doc, Ref}) ->
-            DiskAtts = [{N, T, P, AL, DL, R, M, E} ||
-                #att{name = N, type = T, data = {_, P}, md5 = M, revpos = R,
-                    att_len = AL, disk_len = DL, encoding = E} <- Atts],
-            AttsFd = case Atts of
-            [#att{data = {Fd, _}} | _] ->
-                Fd;
-            [] ->
-                nil
-            end,
-            SummaryChunk = couch_db_updater:make_doc_summary(Db, {Body, DiskAtts}),
-            {Doc#doc{body = {summary, SummaryChunk, AttsFd}}, Ref}
-        end,
-        Bucket) || Bucket <- BucketList].
-
-
-before_docs_update(#db{before_doc_update = nil}, BucketList) ->
-    BucketList;
-before_docs_update(#db{before_doc_update = Fun} = Db, BucketList) ->
-    [lists:map(
-        fun({Doc, Ref}) ->
-            NewDoc = Fun(couch_doc:with_ejson_body(Doc), Db),
-            {NewDoc, Ref}
-        end,
-        Bucket) || Bucket <- BucketList].
-
-
-set_new_att_revpos(#doc{revs={RevPos,_Revs},atts=Atts}=Doc) ->
-    Doc#doc{atts= lists:map(fun(#att{data={_Fd,_Sp}}=Att) ->
-            % already commited to disk, do not set new rev
-            Att;
-        (Att) ->
-            Att#att{revpos=RevPos+1}
-        end, Atts)}.
-
-
-doc_flush_atts(Doc, Fd) ->
-    Doc#doc{atts=[flush_att(Fd, Att) || Att <- Doc#doc.atts]}.
-
-check_md5(_NewSig, <<>>) -> ok;
-check_md5(Sig, Sig) -> ok;
-check_md5(_, _) -> throw(md5_mismatch).
-
-flush_att(Fd, #att{data={Fd0, _}}=Att) when Fd0 == Fd ->
-    % already written to our file, nothing to write
-    Att;
-
-flush_att(Fd, #att{data={OtherFd,StreamPointer}, md5=InMd5,
-    disk_len=InDiskLen} = Att) ->
-    {NewStreamData, Len, _IdentityLen, Md5, IdentityMd5} =
-            couch_stream:copy_to_new_stream(OtherFd, StreamPointer, Fd),
-    check_md5(IdentityMd5, InMd5),
-    Att#att{data={Fd, NewStreamData}, md5=Md5, att_len=Len, disk_len=InDiskLen};
-
-flush_att(Fd, #att{data=Data}=Att) when is_binary(Data) ->
-    with_stream(Fd, Att, fun(OutputStream) ->
-        couch_stream:write(OutputStream, Data)
-    end);
-
-flush_att(Fd, #att{data=Fun,att_len=undefined}=Att) when is_function(Fun) ->
-    MaxChunkSize = list_to_integer(
-        couch_config:get("couchdb", "attachment_stream_buffer_size", "4096")),
-    with_stream(Fd, Att, fun(OutputStream) ->
-        % Fun(MaxChunkSize, WriterFun) must call WriterFun
-        % once for each chunk of the attachment,
-        Fun(MaxChunkSize,
-            % WriterFun({Length, Binary}, State)
-            % WriterFun({0, _Footers}, State)
-            % Called with Length == 0 on the last time.
-            % WriterFun returns NewState.
-            fun({0, Footers}, _) ->
-                F = mochiweb_headers:from_binary(Footers),
-                case mochiweb_headers:get_value("Content-MD5", F) of
-                undefined ->
-                    ok;
-                Md5 ->
-                    {md5, base64:decode(Md5)}
-                end;
-            ({_Length, Chunk}, _) ->
-                couch_stream:write(OutputStream, Chunk)
-            end, ok)
-    end);
-
-flush_att(Fd, #att{data=Fun,att_len=AttLen}=Att) when is_function(Fun) ->
-    with_stream(Fd, Att, fun(OutputStream) ->
-        write_streamed_attachment(OutputStream, Fun, AttLen)
-    end).
-
-
-compressible_att_type(MimeType) when is_binary(MimeType) ->
-    compressible_att_type(?b2l(MimeType));
-compressible_att_type(MimeType) ->
-    TypeExpList = re:split(
-        couch_config:get("attachments", "compressible_types", ""),
-        "\\s*,\\s*",
-        [{return, list}]
-    ),
-    lists:any(
-        fun(TypeExp) ->
-            Regexp = ["^\\s*", re:replace(TypeExp, "\\*", ".*"),
-                "(?:\\s*;.*?)?\\s*", $$],
-            re:run(MimeType, Regexp, [caseless]) =/= nomatch
-        end,
-        [T || T <- TypeExpList, T /= []]
-    ).
-
-% From RFC 2616 3.6.1 - Chunked Transfer Coding
-%
-%   In other words, the origin server is willing to accept
-%   the possibility that the trailer fields might be silently
-%   discarded along the path to the client.
-%
-% I take this to mean that if "Trailers: Content-MD5\r\n"
-% is present in the request, but there is no Content-MD5
-% trailer, we're free to ignore this inconsistency and
-% pretend that no Content-MD5 exists.
-with_stream(Fd, #att{md5=InMd5,type=Type,encoding=Enc}=Att, Fun) ->
-    BufferSize = list_to_integer(
-        couch_config:get("couchdb", "attachment_stream_buffer_size", "4096")),
-    {ok, OutputStream} = case (Enc =:= identity) andalso
-        compressible_att_type(Type) of
-    true ->
-        CompLevel = list_to_integer(
-            couch_config:get("attachments", "compression_level", "0")
-        ),
-        couch_stream:open(Fd, [{buffer_size, BufferSize},
-            {encoding, gzip}, {compression_level, CompLevel}]);
-    _ ->
-        couch_stream:open(Fd, [{buffer_size, BufferSize}])
-    end,
-    ReqMd5 = case Fun(OutputStream) of
-        {md5, FooterMd5} ->
-            case InMd5 of
-                md5_in_footer -> FooterMd5;
-                _ -> InMd5
-            end;
-        _ ->
-            InMd5
-    end,
-    {StreamInfo, Len, IdentityLen, Md5, IdentityMd5} =
-        couch_stream:close(OutputStream),
-    check_md5(IdentityMd5, ReqMd5),
-    {AttLen, DiskLen, NewEnc} = case Enc of
-    identity ->
-        case {Md5, IdentityMd5} of
-        {Same, Same} ->
-            {Len, IdentityLen, identity};
-        _ ->
-            {Len, IdentityLen, gzip}
-        end;
-    gzip ->
-        case {Att#att.att_len, Att#att.disk_len} of
-        {AL, DL} when AL =:= undefined orelse DL =:= undefined ->
-            % Compressed attachment uploaded through the standalone API.
-            {Len, Len, gzip};
-        {AL, DL} ->
-            % This case is used for efficient push-replication, where a
-            % compressed attachment is located in the body of multipart
-            % content-type request.
-            {AL, DL, gzip}
-        end
-    end,
-    Att#att{
-        data={Fd,StreamInfo},
-        att_len=AttLen,
-        disk_len=DiskLen,
-        md5=Md5,
-        encoding=NewEnc
-    }.
-
-
-write_streamed_attachment(_Stream, _F, 0) ->
-    ok;
-write_streamed_attachment(Stream, F, LenLeft) when LenLeft > 0 ->
-    Bin = read_next_chunk(F, LenLeft),
-    ok = couch_stream:write(Stream, Bin),
-    write_streamed_attachment(Stream, F, LenLeft - size(Bin)).
-
-read_next_chunk(F, _) when is_function(F, 0) ->
-    F();
-read_next_chunk(F, LenLeft) when is_function(F, 1) ->
-    F(lists:min([LenLeft, 16#2000])).
-
-enum_docs_since_reduce_to_count(Reds) ->
-    couch_btree:final_reduce(
-            fun couch_db_updater:btree_by_seq_reduce/2, Reds).
-
-enum_docs_reduce_to_count(Reds) ->
-    FinalRed = couch_btree:final_reduce(
-            fun couch_db_updater:btree_by_id_reduce/2, Reds),
-    element(1, FinalRed).
-
-changes_since(Db, StartSeq, Fun, Acc) ->
-    changes_since(Db, StartSeq, Fun, [], Acc).
-
-changes_since(Db, StartSeq, Fun, Options, Acc) ->
-    Wrapper = fun(DocInfo, _Offset, Acc2) -> Fun(DocInfo, Acc2) end,
-    {ok, _LastReduction, AccOut} = couch_btree:fold(by_seq_btree(Db),
-        Wrapper, Acc, [{start_key, StartSeq + 1}] ++ Options),
-    {ok, AccOut}.
-
-count_changes_since(Db, SinceSeq) ->
-    BTree = by_seq_btree(Db),
-    {ok, Changes} =
-    couch_btree:fold_reduce(BTree,
-        fun(_SeqStart, PartialReds, 0) ->
-            {ok, couch_btree:final_reduce(BTree, PartialReds)}
-        end,
-        0, [{start_key, SinceSeq + 1}]),
-    Changes.
-
-enum_docs_since(Db, SinceSeq, InFun, Acc, Options) ->
-    {ok, LastReduction, AccOut} = couch_btree:fold(
-        by_seq_btree(Db), InFun, Acc, [{start_key, SinceSeq + 1} | Options]),
-    {ok, enum_docs_since_reduce_to_count(LastReduction), AccOut}.
-
-enum_docs(Db, InFun, InAcc, Options) ->
-    FoldFun = skip_deleted(InFun),
-    {ok, LastReduce, OutAcc} = couch_btree:fold(
-        by_id_btree(Db), FoldFun, InAcc, Options),
-    {ok, enum_docs_reduce_to_count(LastReduce), OutAcc}.
-
-% server functions
-
-init({DbName, Filepath, Fd, Options}) ->
-    {ok, UpdaterPid} = gen_server:start_link(couch_db_updater, {self(), DbName, Filepath, Fd, Options}, []),
-    {ok, #db{fd_ref_counter=RefCntr}=Db} = gen_server:call(UpdaterPid, get_db),
-    couch_ref_counter:add(RefCntr),
-    case lists:member(sys_db, Options) of
-    true ->
-        ok;
-    false ->
-        couch_stats_collector:track_process_count({couchdb, open_databases})
-    end,
-    process_flag(trap_exit, true),
-    {ok, Db}.
-
-terminate(_Reason, Db) ->
-    couch_util:shutdown_sync(Db#db.update_pid),
-    ok.
-
-handle_call({open_ref_count, OpenerPid}, _, #db{fd_ref_counter=RefCntr}=Db) ->
-    ok = couch_ref_counter:add(RefCntr, OpenerPid),
-    {reply, {ok, Db}, Db};
-handle_call(is_idle, _From, #db{fd_ref_counter=RefCntr, compactor_pid=Compact,
-            waiting_delayed_commit=Delay}=Db) ->
-    % Idle means no referrers. Unless in the middle of a compaction file switch,
-    % there are always at least 2 referrers, couch_db_updater and us.
-    {reply, (Delay == nil) andalso (Compact == nil) andalso (couch_ref_counter:count(RefCntr) == 2), Db};
-handle_call({db_updated, NewDb}, _From, #db{fd_ref_counter=OldRefCntr}) ->
-    #db{fd_ref_counter=NewRefCntr}=NewDb,
-    case NewRefCntr =:= OldRefCntr of
-    true -> ok;
-    false ->
-        couch_ref_counter:add(NewRefCntr),
-        couch_ref_counter:drop(OldRefCntr)
-    end,
-    {reply, ok, NewDb};
-handle_call(get_db, _From, Db) ->
-    {reply, {ok, Db}, Db}.
-
-
-handle_cast(Msg, Db) ->
-    ?LOG_ERROR("Bad cast message received for db ~s: ~p", [Db#db.name, Msg]),
-    exit({error, Msg}).
-
-code_change(_OldVsn, State, _Extra) ->
-    {ok, State}.
-
-handle_info({'EXIT', _Pid, normal}, Db) ->
-    {noreply, Db};
-handle_info({'EXIT', _Pid, Reason}, Server) ->
-    {stop, Reason, Server};
-handle_info(Msg, Db) ->
-    ?LOG_ERROR("Bad message received for db ~s: ~p", [Db#db.name, Msg]),
-    exit({error, Msg}).
-
-
-%%% Internal function %%%
-open_doc_revs_int(Db, IdRevs, Options) ->
-    Ids = [Id || {Id, _Revs} <- IdRevs],
-    LookupResults = get_full_doc_infos(Db, Ids),
-    lists:zipwith(
-        fun({Id, Revs}, Lookup) ->
-            case Lookup of
-            {ok, #full_doc_info{rev_tree=RevTree}} ->
-                {FoundRevs, MissingRevs} =
-                case Revs of
-                all ->
-                    {couch_key_tree:get_all_leafs(RevTree), []};
-                _ ->
-                    case lists:member(latest, Options) of
-                    true ->
-                        couch_key_tree:get_key_leafs(RevTree, Revs);
-                    false ->
-                        couch_key_tree:get(RevTree, Revs)
-                    end
-                end,
-                FoundResults =
-                lists:map(fun({Value, {Pos, [Rev|_]}=FoundRevPath}) ->
-                    case Value of
-                    ?REV_MISSING ->
-                        % we have the rev in our list but know nothing about it
-                        {{not_found, missing}, {Pos, Rev}};
-                    RevValue ->
-                        IsDeleted = element(1, RevValue),
-                        SummaryPtr = element(2, RevValue),
-                        {ok, make_doc(Db, Id, IsDeleted, SummaryPtr, FoundRevPath)}
-                    end
-                end, FoundRevs),
-                Results = FoundResults ++ [{{not_found, missing}, MissingRev} || MissingRev <- MissingRevs],
-                {ok, Results};
-            not_found when Revs == all ->
-                {ok, []};
-            not_found ->
-                {ok, [{{not_found, missing}, Rev} || Rev <- Revs]}
-            end
-        end,
-        IdRevs, LookupResults).
-
-open_doc_int(Db, <<?LOCAL_DOC_PREFIX, _/binary>> = Id, Options) ->
-    case couch_btree:lookup(local_btree(Db), [Id]) of
-    [{ok, {_, {Rev, BodyData}}}] ->
-        Doc = #doc{id=Id, revs={0, [?l2b(integer_to_list(Rev))]}, body=BodyData},
-        apply_open_options({ok, Doc}, Options);
-    [not_found] ->
-        {not_found, missing}
-    end;
-open_doc_int(Db, #doc_info{id=Id,revs=[RevInfo|_]}=DocInfo, Options) ->
-    #rev_info{deleted=IsDeleted,rev={Pos,RevId},body_sp=Bp} = RevInfo,
-    Doc = make_doc(Db, Id, IsDeleted, Bp, {Pos,[RevId]}),
-    apply_open_options(
-       {ok, Doc#doc{meta=doc_meta_info(DocInfo, [], Options)}}, Options);
-open_doc_int(Db, #full_doc_info{id=Id,rev_tree=RevTree}=FullDocInfo, Options) ->
-    #doc_info{revs=[#rev_info{deleted=IsDeleted,rev=Rev,body_sp=Bp}|_]} =
-        DocInfo = couch_doc:to_doc_info(FullDocInfo),
-    {[{_, RevPath}], []} = couch_key_tree:get(RevTree, [Rev]),
-    Doc = make_doc(Db, Id, IsDeleted, Bp, RevPath),
-    apply_open_options(
-        {ok, Doc#doc{meta=doc_meta_info(DocInfo, RevTree, Options)}}, Options);
-open_doc_int(Db, Id, Options) ->
-    case get_full_doc_info(Db, Id) of
-    {ok, FullDocInfo} ->
-        open_doc_int(Db, FullDocInfo, Options);
-    not_found ->
-        {not_found, missing}
-    end.
-
-doc_meta_info(#doc_info{high_seq=Seq,revs=[#rev_info{rev=Rev}|RestInfo]}, RevTree, Options) ->
-    case lists:member(revs_info, Options) of
-    false -> [];
-    true ->
-        {[{Pos, RevPath}],[]} =
-            couch_key_tree:get_full_key_paths(RevTree, [Rev]),
-
-        [{revs_info, Pos, lists:map(
-            fun({Rev1, ?REV_MISSING}) ->
-                {Rev1, missing};
-            ({Rev1, RevValue}) ->
-                case element(1, RevValue) of
-                true ->
-                    {Rev1, deleted};
-                false ->
-                    {Rev1, available}
-                end
-            end, RevPath)}]
-    end ++
-    case lists:member(conflicts, Options) of
-    false -> [];
-    true ->
-        case [Rev1 || #rev_info{rev=Rev1,deleted=false} <- RestInfo] of
-        [] -> [];
-        ConflictRevs -> [{conflicts, ConflictRevs}]
-        end
-    end ++
-    case lists:member(deleted_conflicts, Options) of
-    false -> [];
-    true ->
-        case [Rev1 || #rev_info{rev=Rev1,deleted=true} <- RestInfo] of
-        [] -> [];
-        DelConflictRevs -> [{deleted_conflicts, DelConflictRevs}]
-        end
-    end ++
-    case lists:member(local_seq, Options) of
-    false -> [];
-    true -> [{local_seq, Seq}]
-    end.
-
-read_doc(#db{fd=Fd}, Pos) ->
-    couch_file:pread_term(Fd, Pos).
-
-
-make_doc(#db{updater_fd = Fd} = Db, Id, Deleted, Bp, RevisionPath) ->
-    {BodyData, Atts} =
-    case Bp of
-    nil ->
-        {[], []};
-    _ ->
-        {ok, {BodyData0, Atts00}} = read_doc(Db, Bp),
-        Atts0 = case Atts00 of
-        _ when is_binary(Atts00) ->
-            couch_compress:decompress(Atts00);
-        _ when is_list(Atts00) ->
-            % pre 1.2 format
-            Atts00
-        end,
-        {BodyData0,
-            lists:map(
-                fun({Name,Type,Sp,AttLen,DiskLen,RevPos,Md5,Enc}) ->
-                    #att{name=Name,
-                        type=Type,
-                        att_len=AttLen,
-                        disk_len=DiskLen,
-                        md5=Md5,
-                        revpos=RevPos,
-                        data={Fd,Sp},
-                        encoding=
-                            case Enc of
-                            true ->
-                                % 0110 UPGRADE CODE
-                                gzip;
-                            false ->
-                                % 0110 UPGRADE CODE
-                                identity;
-                            _ ->
-                                Enc
-                            end
-                    };
-                ({Name,Type,Sp,AttLen,RevPos,Md5}) ->
-                    #att{name=Name,
-                        type=Type,
-                        att_len=AttLen,
-                        disk_len=AttLen,
-                        md5=Md5,
-                        revpos=RevPos,
-                        data={Fd,Sp}};
-                ({Name,{Type,Sp,AttLen}}) ->
-                    #att{name=Name,
-                        type=Type,
-                        att_len=AttLen,
-                        disk_len=AttLen,
-                        md5= <<>>,
-                        revpos=0,
-                        data={Fd,Sp}}
-                end, Atts0)}
-    end,
-    Doc = #doc{
-        id = Id,
-        revs = RevisionPath,
-        body = BodyData,
-        atts = Atts,
-        deleted = Deleted
-    },
-    after_doc_read(Db, Doc).
-
-
-after_doc_read(#db{after_doc_read = nil}, Doc) ->
-    Doc;
-after_doc_read(#db{after_doc_read = Fun} = Db, Doc) ->
-    Fun(couch_doc:with_ejson_body(Doc), Db).
-
-
-increment_stat(#db{options = Options}, Stat) ->
-    case lists:member(sys_db, Options) of
-    true ->
-        ok;
-    false ->
-        couch_stats_collector:increment(Stat)
-    end.
-
-local_btree(#db{local_docs_btree = BTree, fd = ReaderFd}) ->
-    BTree#btree{fd = ReaderFd}.
-
-by_seq_btree(#db{docinfo_by_seq_btree = BTree, fd = ReaderFd}) ->
-    BTree#btree{fd = ReaderFd}.
-
-by_id_btree(#db{fulldocinfo_by_id_btree = BTree, fd = ReaderFd}) ->
-    BTree#btree{fd = ReaderFd}.
-
-skip_deleted(FoldFun) ->
-    fun
-        (visit, KV, Reds, Acc) ->
-            FoldFun(KV, Reds, Acc);
-        (traverse, _LK, {Undeleted, _Del, _Size}, Acc) when Undeleted == 0 ->
-            {skip, Acc};
-        (traverse, _, _, Acc) ->
-            {ok, Acc}
-    end.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_db_update_notifier.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_db_update_notifier.erl b/apps/couch/src/couch_db_update_notifier.erl
deleted file mode 100644
index bfa770a..0000000
--- a/apps/couch/src/couch_db_update_notifier.erl
+++ /dev/null
@@ -1,82 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
-%
-% This causes an OS process to spawned and it is notified every time a database
-% is updated.
-%
-% The notifications are in the form of a the database name sent as a line of
-% text to the OS processes stdout.
-%
-
--module(couch_db_update_notifier).
-
--behaviour(gen_event).
-
--export([start_link/1, notify/1]).
--export([init/1, terminate/2, handle_event/2, handle_call/2, handle_info/2, code_change/3,stop/1]).
-
--include("couch_db.hrl").
-
-start_link(Exec) ->
-    couch_event_sup:start_link(couch_db_update, {couch_db_update_notifier, make_ref()}, Exec).
-
-notify(Event) ->
-    gen_event:notify(couch_db_update, Event).
-
-stop(Pid) ->
-    couch_event_sup:stop(Pid).
-
-init(Exec) when is_list(Exec) -> % an exe
-    couch_os_process:start_link(Exec, []);
-init(Else) ->
-    {ok, Else}.
-
-terminate(_Reason, Pid) when is_pid(Pid) ->
-    couch_os_process:stop(Pid),
-    ok;
-terminate(_Reason, _State) ->
-    ok.
-
-handle_event(Event, Fun) when is_function(Fun, 1) ->
-    Fun(Event),
-    {ok, Fun};
-handle_event(Event, {Fun, FunAcc}) ->
-    FunAcc2 = Fun(Event, FunAcc),
-    {ok, {Fun, FunAcc2}};
-handle_event({EventType, EventDesc}, Pid) ->
-    Obj = encode_event(EventType, EventDesc),
-    ok = couch_os_process:send(Pid, Obj),
-    {ok, Pid}.
-
-handle_call(_Request, State) ->
-    {reply, ok, State}.
-
-handle_info({'EXIT', Pid, Reason}, Pid) ->
-    ?LOG_ERROR("Update notification process ~p died: ~p", [Pid, Reason]),
-    remove_handler;
-handle_info({'EXIT', _, _}, Pid) ->
-    %% the db_update event manager traps exits and forwards this message to all
-    %% its handlers. Just ignore as it wasn't our os_process that exited.
-    {ok, Pid}.
-
-code_change(_OldVsn, State, _Extra) ->
-    {ok, State}.
-
-encode_event(EventType, EventDesc) when is_atom(EventType) ->
-    encode_event(atom_to_list(EventType), EventDesc);
-encode_event(EventType, EventDesc) when is_list(EventType) ->
-    encode_event(?l2b(EventType), EventDesc);
-encode_event(EventType, {DbName, DocId}) ->
-    {[{type, EventType}, {db, DbName}, {id, DocId}]};
-encode_event(EventType, DbName) ->
-    {[{type, EventType}, {db, DbName}]}.

http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/couch/src/couch_db_update_notifier_sup.erl
----------------------------------------------------------------------
diff --git a/apps/couch/src/couch_db_update_notifier_sup.erl b/apps/couch/src/couch_db_update_notifier_sup.erl
deleted file mode 100644
index e7cc16c..0000000
--- a/apps/couch/src/couch_db_update_notifier_sup.erl
+++ /dev/null
@@ -1,61 +0,0 @@
-% Licensed under the Apache License, Version 2.0 (the "License"); you may not
-% use this file except in compliance with the License. You may obtain a copy of
-% the License at
-%
-%   http://www.apache.org/licenses/LICENSE-2.0
-%
-% Unless required by applicable law or agreed to in writing, software
-% distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-% WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-% License for the specific language governing permissions and limitations under
-% the License.
-
-%
-% This causes an OS process to spawned and it is notified every time a database
-% is updated.
-%
-% The notifications are in the form of a the database name sent as a line of
-% text to the OS processes stdout.
-%
-
--module(couch_db_update_notifier_sup).
-
--behaviour(supervisor).
-
--export([start_link/0, init/1, config_change/3]).
-
-start_link() ->
-    supervisor:start_link({local, couch_db_update_notifier_sup},
-        couch_db_update_notifier_sup, []).
-
-init([]) ->
-    ok = couch_config:register(fun ?MODULE:config_change/3),
-
-    UpdateNotifierExes = couch_config:get("update_notification"),
-
-    {ok,
-        {{one_for_one, 10, 3600},
-            lists:map(fun({Name, UpdateNotifierExe}) ->
-                {Name,
-                {couch_db_update_notifier, start_link, [UpdateNotifierExe]},
-                    permanent,
-                    1000,
-                    supervisor,
-                    [couch_db_update_notifier]}
-                end, UpdateNotifierExes)}}.
-
-%% @doc when update_notification configuration changes, terminate the process
-%%      for that notifier and start a new one with the updated config
-config_change("update_notification", Id, Exe) ->
-    ChildSpec = {
-        Id,
-        {couch_db_update_notifier, start_link, [Exe]},
-        permanent,
-        1000,
-        supervisor,
-        [couch_db_update_notifier]
-    },
-    supervisor:terminate_child(couch_db_update_notifier_sup, Id),
-    supervisor:delete_child(couch_db_update_notifier_sup, Id),
-    supervisor:start_child(couch_db_update_notifier_sup, ChildSpec).
-


[72/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/ubrk.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/ubrk.h b/src/apps/couch_collate/platform/osx/icu/unicode/ubrk.h
new file mode 100644
index 0000000..d57ba37
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/ubrk.h
@@ -0,0 +1,482 @@
+/*
+******************************************************************************
+* Copyright (C) 1996-2007, International Business Machines Corporation and others.
+* All Rights Reserved.
+******************************************************************************
+*/
+
+#ifndef UBRK_H
+#define UBRK_H
+
+#include "unicode/utypes.h"
+#include "unicode/uloc.h"
+#include "unicode/utext.h"
+
+/**
+ * A text-break iterator.
+ *  For usage in C programs.
+ */
+#ifndef UBRK_TYPEDEF_UBREAK_ITERATOR
+#   define UBRK_TYPEDEF_UBREAK_ITERATOR
+    /**
+     *  Opaque type representing an ICU Break iterator object.
+     *  @stable ICU 2.0
+     */
+    typedef void UBreakIterator;
+#endif
+
+#if !UCONFIG_NO_BREAK_ITERATION
+
+#include "unicode/parseerr.h"
+
+/**
+ * \file
+ * \brief C API: BreakIterator
+ *
+ * <h2> BreakIterator C API </h2>
+ *
+ * The BreakIterator C API defines  methods for finding the location
+ * of boundaries in text. Pointer to a UBreakIterator maintain a
+ * current position and scan over text returning the index of characters
+ * where boundaries occur.
+ * <p>
+ * Line boundary analysis determines where a text string can be broken
+ * when line-wrapping. The mechanism correctly handles punctuation and
+ * hyphenated words.
+ * <p>
+ * Sentence boundary analysis allows selection with correct
+ * interpretation of periods within numbers and abbreviations, and
+ * trailing punctuation marks such as quotation marks and parentheses.
+ * <p>
+ * Word boundary analysis is used by search and replace functions, as
+ * well as within text editing applications that allow the user to
+ * select words with a double click. Word selection provides correct
+ * interpretation of punctuation marks within and following
+ * words. Characters that are not part of a word, such as symbols or
+ * punctuation marks, have word-breaks on both sides.
+ * <p>
+ * Character boundary analysis allows users to interact with
+ * characters as they expect to, for example, when moving the cursor
+ * through a text string. Character boundary analysis provides correct
+ * navigation of through character strings, regardless of how the
+ * character is stored.  For example, an accented character might be
+ * stored as a base character and a diacritical mark. What users
+ * consider to be a character can differ between languages.
+ * <p>
+ * Title boundary analysis locates all positions,
+ * typically starts of words, that should be set to Title Case
+ * when title casing the text.
+ * <p>
+ * The text boundary positions are found according to the rules
+ * described in Unicode Standard Annex #29, Text Boundaries, and
+ * Unicode Standard Annex #14, Line Breaking Properties.  These
+ * are available at http://www.unicode.org/reports/tr14/ and
+ * http://www.unicode.org/reports/tr29/.
+ * <p>
+ * In addition to the plain C API defined in this header file, an
+ * object oriented C++ API with equivalent functionality is defined in the
+ * file brkiter.h.
+ * <p>
+ * Code snippits illustrating the use of the Break Iterator APIs
+ * are available in the ICU User Guide,
+ * http://icu-project.org/userguide/boundaryAnalysis.html
+ * and in the sample program icu/source/samples/break/break.cpp"
+ */
+
+/** The possible types of text boundaries.  @stable ICU 2.0 */
+typedef enum UBreakIteratorType {
+  /** Character breaks  @stable ICU 2.0 */
+  UBRK_CHARACTER = 0,
+  /** Word breaks @stable ICU 2.0 */
+  UBRK_WORD = 1,
+  /** Line breaks @stable ICU 2.0 */
+  UBRK_LINE = 2,
+  /** Sentence breaks @stable ICU 2.0 */
+  UBRK_SENTENCE = 3,
+
+#ifndef U_HIDE_DEPRECATED_API
+  /**
+   * Title Case breaks
+   * The iterator created using this type locates title boundaries as described for
+   * Unicode 3.2 only. For Unicode 4.0 and above title boundary iteration,
+   * please use Word Boundary iterator.
+   *
+   * @deprecated ICU 2.8 Use the word break iterator for titlecasing for Unicode 4 and later.
+   */
+  UBRK_TITLE = 4,
+#endif /* U_HIDE_DEPRECATED_API */
+  UBRK_COUNT = 5
+} UBreakIteratorType;
+
+/** Value indicating all text boundaries have been returned.
+ *  @stable ICU 2.0
+ */
+#define UBRK_DONE ((int32_t) -1)
+
+
+/**
+ *  Enum constants for the word break tags returned by
+ *  getRuleStatus().  A range of values is defined for each category of
+ *  word, to allow for further subdivisions of a category in future releases.
+ *  Applications should check for tag values falling within the range, rather
+ *  than for single individual values.
+ *  @stable ICU 2.2
+*/
+typedef enum UWordBreak {
+    /** Tag value for "words" that do not fit into any of other categories.
+     *  Includes spaces and most punctuation. */
+    UBRK_WORD_NONE           = 0,
+    /** Upper bound for tags for uncategorized words. */
+    UBRK_WORD_NONE_LIMIT     = 100,
+    /** Tag value for words that appear to be numbers, lower limit.    */
+    UBRK_WORD_NUMBER         = 100,
+    /** Tag value for words that appear to be numbers, upper limit.    */
+    UBRK_WORD_NUMBER_LIMIT   = 200,
+    /** Tag value for words that contain letters, excluding
+     *  hiragana, katakana or ideographic characters, lower limit.    */
+    UBRK_WORD_LETTER         = 200,
+    /** Tag value for words containing letters, upper limit  */
+    UBRK_WORD_LETTER_LIMIT   = 300,
+    /** Tag value for words containing kana characters, lower limit */
+    UBRK_WORD_KANA           = 300,
+    /** Tag value for words containing kana characters, upper limit */
+    UBRK_WORD_KANA_LIMIT     = 400,
+    /** Tag value for words containing ideographic characters, lower limit */
+    UBRK_WORD_IDEO           = 400,
+    /** Tag value for words containing ideographic characters, upper limit */
+    UBRK_WORD_IDEO_LIMIT     = 500
+} UWordBreak;
+
+/**
+ *  Enum constants for the line break tags returned by getRuleStatus().
+ *  A range of values is defined for each category of
+ *  word, to allow for further subdivisions of a category in future releases.
+ *  Applications should check for tag values falling within the range, rather
+ *  than for single individual values.
+ *  @stable ICU 2.8
+*/
+typedef enum ULineBreakTag {
+    /** Tag value for soft line breaks, positions at which a line break
+      *  is acceptable but not required                */
+    UBRK_LINE_SOFT            = 0,
+    /** Upper bound for soft line breaks.              */
+    UBRK_LINE_SOFT_LIMIT      = 100,
+    /** Tag value for a hard, or mandatory line break  */
+    UBRK_LINE_HARD            = 100,
+    /** Upper bound for hard line breaks.              */
+    UBRK_LINE_HARD_LIMIT      = 200
+} ULineBreakTag;
+
+
+
+/**
+ *  Enum constants for the sentence break tags returned by getRuleStatus().
+ *  A range of values is defined for each category of
+ *  sentence, to allow for further subdivisions of a category in future releases.
+ *  Applications should check for tag values falling within the range, rather
+ *  than for single individual values.
+ *  @stable ICU 2.8
+*/
+typedef enum USentenceBreakTag {
+    /** Tag value for for sentences  ending with a sentence terminator
+      * ('.', '?', '!', etc.) character, possibly followed by a
+      * hard separator (CR, LF, PS, etc.)
+      */
+    UBRK_SENTENCE_TERM       = 0,
+    /** Upper bound for tags for sentences ended by sentence terminators.    */
+    UBRK_SENTENCE_TERM_LIMIT = 100,
+    /** Tag value for for sentences that do not contain an ending
+      * sentence terminator ('.', '?', '!', etc.) character, but
+      * are ended only by a hard separator (CR, LF, PS, etc.) or end of input.
+      */
+    UBRK_SENTENCE_SEP        = 100,
+    /** Upper bound for tags for sentences ended by a separator.              */
+    UBRK_SENTENCE_SEP_LIMIT  = 200
+    /** Tag value for a hard, or mandatory line break  */
+} USentenceBreakTag;
+
+
+/**
+ * Open a new UBreakIterator for locating text boundaries for a specified locale.
+ * A UBreakIterator may be used for detecting character, line, word,
+ * and sentence breaks in text.
+ * @param type The type of UBreakIterator to open: one of UBRK_CHARACTER, UBRK_WORD,
+ * UBRK_LINE, UBRK_SENTENCE
+ * @param locale The locale specifying the text-breaking conventions.
+ * @param text The text to be iterated over.
+ * @param textLength The number of characters in text, or -1 if null-terminated.
+ * @param status A UErrorCode to receive any errors.
+ * @return A UBreakIterator for the specified locale.
+ * @see ubrk_openRules
+ * @stable ICU 2.0
+ */
+U_STABLE UBreakIterator* U_EXPORT2
+ubrk_open(UBreakIteratorType type,
+      const char *locale,
+      const UChar *text,
+      int32_t textLength,
+      UErrorCode *status);
+
+/**
+ * Open a new UBreakIterator for locating text boundaries using specified breaking rules.
+ * The rule syntax is ... (TBD)
+ * @param rules A set of rules specifying the text breaking conventions.
+ * @param rulesLength The number of characters in rules, or -1 if null-terminated.
+ * @param text The text to be iterated over.  May be null, in which case ubrk_setText() is
+ *        used to specify the text to be iterated.
+ * @param textLength The number of characters in text, or -1 if null-terminated.
+ * @param parseErr   Receives position and context information for any syntax errors
+ *                   detected while parsing the rules.
+ * @param status A UErrorCode to receive any errors.
+ * @return A UBreakIterator for the specified rules.
+ * @see ubrk_open
+ * @stable ICU 2.2
+ */
+U_STABLE UBreakIterator* U_EXPORT2
+ubrk_openRules(const UChar     *rules,
+               int32_t         rulesLength,
+               const UChar     *text,
+               int32_t          textLength,
+               UParseError     *parseErr,
+               UErrorCode      *status);
+
+/**
+ * Thread safe cloning operation
+ * @param bi iterator to be cloned
+ * @param stackBuffer user allocated space for the new clone. If NULL new memory will be allocated.
+ *  If buffer is not large enough, new memory will be allocated.
+ *  Clients can use the U_BRK_SAFECLONE_BUFFERSIZE. This will probably be enough to avoid memory allocations.
+ * @param pBufferSize pointer to size of allocated space.
+ *  If *pBufferSize == 0, a sufficient size for use in cloning will
+ *  be returned ('pre-flighting')
+ *  If *pBufferSize is not enough for a stack-based safe clone,
+ *  new memory will be allocated.
+ * @param status to indicate whether the operation went on smoothly or there were errors
+ *  An informational status value, U_SAFECLONE_ALLOCATED_ERROR, is used if any allocations were necessary.
+ * @return pointer to the new clone
+ * @stable ICU 2.0
+ */
+U_STABLE UBreakIterator * U_EXPORT2
+ubrk_safeClone(
+          const UBreakIterator *bi,
+          void *stackBuffer,
+          int32_t *pBufferSize,
+          UErrorCode *status);
+
+/**
+  * A recommended size (in bytes) for the memory buffer to be passed to ubrk_saveClone().
+  * @stable ICU 2.0
+  */
+#define U_BRK_SAFECLONE_BUFFERSIZE 512
+
+/**
+* Close a UBreakIterator.
+* Once closed, a UBreakIterator may no longer be used.
+* @param bi The break iterator to close.
+ * @stable ICU 2.0
+*/
+U_STABLE void U_EXPORT2
+ubrk_close(UBreakIterator *bi);
+
+/**
+ * Sets an existing iterator to point to a new piece of text
+ * @param bi The iterator to use
+ * @param text The text to be set
+ * @param textLength The length of the text
+ * @param status The error code
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2
+ubrk_setText(UBreakIterator* bi,
+             const UChar*    text,
+             int32_t         textLength,
+             UErrorCode*     status);
+
+
+/**
+ * Sets an existing iterator to point to a new piece of text
+ * @param bi The iterator to use
+ * @param text The text to be set.
+ *             This function makes a shallow clone of the supplied UText.  This means
+ *             that the caller is free to immediately close or otherwise reuse the
+ *             UText that was passed as a parameter, but that the underlying text itself
+ *             must not be altered while being referenced by the break iterator.
+ * @param status The error code
+ * @stable ICU 3.4
+ */
+U_STABLE void U_EXPORT2
+ubrk_setUText(UBreakIterator* bi,
+             UText*          text,
+             UErrorCode*     status);
+
+
+
+/**
+ * Determine the most recently-returned text boundary.
+ *
+ * @param bi The break iterator to use.
+ * @return The character index most recently returned by \ref ubrk_next, \ref ubrk_previous,
+ * \ref ubrk_first, or \ref ubrk_last.
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+ubrk_current(const UBreakIterator *bi);
+
+/**
+ * Determine the text boundary following the current text boundary.
+ *
+ * @param bi The break iterator to use.
+ * @return The character index of the next text boundary, or UBRK_DONE
+ * if all text boundaries have been returned.
+ * @see ubrk_previous
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+ubrk_next(UBreakIterator *bi);
+
+/**
+ * Determine the text boundary preceding the current text boundary.
+ *
+ * @param bi The break iterator to use.
+ * @return The character index of the preceding text boundary, or UBRK_DONE
+ * if all text boundaries have been returned.
+ * @see ubrk_next
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+ubrk_previous(UBreakIterator *bi);
+
+/**
+ * Determine the index of the first character in the text being scanned.
+ * This is not always the same as index 0 of the text.
+ * @param bi The break iterator to use.
+ * @return The character index of the first character in the text being scanned.
+ * @see ubrk_last
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+ubrk_first(UBreakIterator *bi);
+
+/**
+ * Determine the index immediately <EM>beyond</EM> the last character in the text being
+ * scanned.
+ * This is not the same as the last character.
+ * @param bi The break iterator to use.
+ * @return The character offset immediately <EM>beyond</EM> the last character in the
+ * text being scanned.
+ * @see ubrk_first
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+ubrk_last(UBreakIterator *bi);
+
+/**
+ * Determine the text boundary preceding the specified offset.
+ * The value returned is always smaller than offset, or UBRK_DONE.
+ * @param bi The break iterator to use.
+ * @param offset The offset to begin scanning.
+ * @return The text boundary preceding offset, or UBRK_DONE.
+ * @see ubrk_following
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+ubrk_preceding(UBreakIterator *bi,
+           int32_t offset);
+
+/**
+ * Determine the text boundary following the specified offset.
+ * The value returned is always greater than offset, or UBRK_DONE.
+ * @param bi The break iterator to use.
+ * @param offset The offset to begin scanning.
+ * @return The text boundary following offset, or UBRK_DONE.
+ * @see ubrk_preceding
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+ubrk_following(UBreakIterator *bi,
+           int32_t offset);
+
+/**
+* Get a locale for which text breaking information is available.
+* A UBreakIterator in a locale returned by this function will perform the correct
+* text breaking for the locale.
+* @param index The index of the desired locale.
+* @return A locale for which number text breaking information is available, or 0 if none.
+* @see ubrk_countAvailable
+* @stable ICU 2.0
+*/
+U_STABLE const char* U_EXPORT2
+ubrk_getAvailable(int32_t index);
+
+/**
+* Determine how many locales have text breaking information available.
+* This function is most useful as determining the loop ending condition for
+* calls to \ref ubrk_getAvailable.
+* @return The number of locales for which text breaking information is available.
+* @see ubrk_getAvailable
+* @stable ICU 2.0
+*/
+U_STABLE int32_t U_EXPORT2
+ubrk_countAvailable(void);
+
+
+/**
+* Returns true if the specfied position is a boundary position.  As a side
+* effect, leaves the iterator pointing to the first boundary position at
+* or after "offset".
+* @param bi The break iterator to use.
+* @param offset the offset to check.
+* @return True if "offset" is a boundary position.
+* @stable ICU 2.0
+*/
+U_STABLE  UBool U_EXPORT2
+ubrk_isBoundary(UBreakIterator *bi, int32_t offset);
+
+/**
+ * Return the status from the break rule that determined the most recently
+ * returned break position.  The values appear in the rule source
+ * within brackets, {123}, for example.  For rules that do not specify a
+ * status, a default value of 0 is returned.
+ * <p>
+ * For word break iterators, the possible values are defined in enum UWordBreak.
+ * @stable ICU 2.2
+ */
+U_STABLE  int32_t U_EXPORT2
+ubrk_getRuleStatus(UBreakIterator *bi);
+
+/**
+ * Get the statuses from the break rules that determined the most recently
+ * returned break position.  The values appear in the rule source
+ * within brackets, {123}, for example.  The default status value for rules
+ * that do not explicitly provide one is zero.
+ * <p>
+ * For word break iterators, the possible values are defined in enum UWordBreak.
+ * @param bi        The break iterator to use
+ * @param fillInVec an array to be filled in with the status values.
+ * @param capacity  the length of the supplied vector.  A length of zero causes
+ *                  the function to return the number of status values, in the
+ *                  normal way, without attemtping to store any values.
+ * @param status    receives error codes.
+ * @return          The number of rule status values from rules that determined
+ *                  the most recent boundary returned by the break iterator.
+ * @stable ICU 3.0
+ */
+U_STABLE  int32_t U_EXPORT2
+ubrk_getRuleStatusVec(UBreakIterator *bi, int32_t *fillInVec, int32_t capacity, UErrorCode *status);
+
+/**
+ * Return the locale of the break iterator. You can choose between the valid and
+ * the actual locale.
+ * @param bi break iterator
+ * @param type locale type (valid or actual)
+ * @param status error code
+ * @return locale string
+ * @stable ICU 2.8
+ */
+U_STABLE const char* U_EXPORT2
+ubrk_getLocaleByType(const UBreakIterator *bi, ULocDataLocaleType type, UErrorCode* status);
+
+
+#endif /* #if !UCONFIG_NO_BREAK_ITERATION */
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/ucal.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/ucal.h b/src/apps/couch_collate/platform/osx/icu/unicode/ucal.h
new file mode 100644
index 0000000..9ba2668
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/ucal.h
@@ -0,0 +1,1161 @@
+/*
+ *******************************************************************************
+ * Copyright (C) 1996-2008, International Business Machines Corporation and
+ * others. All Rights Reserved.
+ *******************************************************************************
+ */
+
+#ifndef UCAL_H
+#define UCAL_H
+
+#include "unicode/utypes.h"
+#include "unicode/uenum.h"
+#include "unicode/uloc.h"
+
+#if !UCONFIG_NO_FORMATTING
+
+/**
+ * \file
+ * \brief C API: Calendar
+ *
+ * <h2>Calendar C API</h2>
+ *
+ * UCalendar C API is used  for converting between a <code>UDate</code> object
+ * and a set of integer fields such as <code>UCAL_YEAR</code>, <code>UCAL_MONTH</code>,
+ * <code>UCAL_DAY</code>, <code>UCAL_HOUR</code>, and so on.
+ * (A <code>UDate</code> object represents a specific instant in
+ * time with millisecond precision. See UDate
+ * for information about the <code>UDate</code> .)
+ *
+ * <p>
+ * Types of <code>UCalendar</code> interpret a <code>UDate</code>
+ * according to the rules of a specific calendar system. The U_STABLE
+ * provides the enum UCalendarType with UCAL_TRADITIONAL and
+ * UCAL_GREGORIAN.
+ * <p>
+ * Like other locale-sensitive C API, calendar API  provides a
+ * function, <code>ucal_open()</code>, which returns a pointer to
+ * <code>UCalendar</code> whose time fields have been initialized
+ * with the current date and time. We need to specify the type of
+ * calendar to be opened and the  timezoneId.
+ * \htmlonly<blockquote>\endhtmlonly
+ * <pre>
+ * \code
+ * UCalendar *caldef;
+ * UChar *tzId;
+ * UErrorCode status;
+ * tzId=(UChar*)malloc(sizeof(UChar) * (strlen("PST") +1) );
+ * u_uastrcpy(tzId, "PST");
+ * caldef=ucal_open(tzID, u_strlen(tzID), NULL, UCAL_TRADITIONAL, &status);
+ * \endcode
+ * </pre>
+ * \htmlonly</blockquote>\endhtmlonly
+ *
+ * <p>
+ * A <code>UCalendar</code> object can produce all the time field values
+ * needed to implement the date-time formatting for a particular language
+ * and calendar style (for example, Japanese-Gregorian, Japanese-Traditional).
+ *
+ * <p>
+ * When computing a <code>UDate</code> from time fields, two special circumstances
+ * may arise: there may be insufficient information to compute the
+ * <code>UDate</code> (such as only year and month but no day in the month),
+ * or there may be inconsistent information (such as "Tuesday, July 15, 1996"
+ * -- July 15, 1996 is actually a Monday).
+ *
+ * <p>
+ * <strong>Insufficient information.</strong> The calendar will use default
+ * information to specify the missing fields. This may vary by calendar; for
+ * the Gregorian calendar, the default for a field is the same as that of the
+ * start of the epoch: i.e., UCAL_YEAR = 1970, UCAL_MONTH = JANUARY, UCAL_DATE = 1, etc.
+ *
+ * <p>
+ * <strong>Inconsistent information.</strong> If fields conflict, the calendar
+ * will give preference to fields set more recently. For example, when
+ * determining the day, the calendar will look for one of the following
+ * combinations of fields.  The most recent combination, as determined by the
+ * most recently set single field, will be used.
+ *
+ * \htmlonly<blockquote>\endhtmlonly
+ * <pre>
+ * \code
+ * UCAL_MONTH + UCAL_DAY_OF_MONTH
+ * UCAL_MONTH + UCAL_WEEK_OF_MONTH + UCAL_DAY_OF_WEEK
+ * UCAL_MONTH + UCAL_DAY_OF_WEEK_IN_MONTH + UCAL_DAY_OF_WEEK
+ * UCAL_DAY_OF_YEAR
+ * UCAL_DAY_OF_WEEK + UCAL_WEEK_OF_YEAR
+ * \endcode
+ * </pre>
+ * \htmlonly</blockquote>\endhtmlonly
+ *
+ * For the time of day:
+ *
+ * \htmlonly<blockquote>\endhtmlonly
+ * <pre>
+ * \code
+ * UCAL_HOUR_OF_DAY
+ * UCAL_AM_PM + UCAL_HOUR
+ * \endcode
+ * </pre>
+ * \htmlonly</blockquote>\endhtmlonly
+ *
+ * <p>
+ * <strong>Note:</strong> for some non-Gregorian calendars, different
+ * fields may be necessary for complete disambiguation. For example, a full
+ * specification of the historial Arabic astronomical calendar requires year,
+ * month, day-of-month <em>and</em> day-of-week in some cases.
+ *
+ * <p>
+ * <strong>Note:</strong> There are certain possible ambiguities in
+ * interpretation of certain singular times, which are resolved in the
+ * following ways:
+ * <ol>
+ *     <li> 24:00:00 "belongs" to the following day. That is,
+ *          23:59 on Dec 31, 1969 &lt; 24:00 on Jan 1, 1970 &lt; 24:01:00 on Jan 1, 1970
+ *
+ *     <li> Although historically not precise, midnight also belongs to "am",
+ *          and noon belongs to "pm", so on the same day,
+ *          12:00 am (midnight) &lt; 12:01 am, and 12:00 pm (noon) &lt; 12:01 pm
+ * </ol>
+ *
+ * <p>
+ * The date or time format strings are not part of the definition of a
+ * calendar, as those must be modifiable or overridable by the user at
+ * runtime. Use {@link DateFormat}
+ * to format dates.
+ *
+ * <p>
+ * <code>Calendar</code> provides an API for field "rolling", where fields
+ * can be incremented or decremented, but wrap around. For example, rolling the
+ * month up in the date <code>December 12, <b>1996</b></code> results in
+ * <code>January 12, <b>1996</b></code>.
+ *
+ * <p>
+ * <code>Calendar</code> also provides a date arithmetic function for
+ * adding the specified (signed) amount of time to a particular time field.
+ * For example, subtracting 5 days from the date <code>September 12, 1996</code>
+ * results in <code>September 7, 1996</code>.
+ *
+ * @stable ICU 2.0
+ */
+
+/** A calendar.
+ *  For usage in C programs.
+ * @stable ICU 2.0
+ */
+typedef void* UCalendar;
+
+/** Possible types of UCalendars 
+ * @stable ICU 2.0
+ */
+enum UCalendarType {
+  /**
+   * Despite the name, UCAL_TRADITIONAL designates the locale's default calendar,
+   * which may be the Gregorian calendar or some other calendar.
+   * @stable ICU 2.0
+   */
+  UCAL_TRADITIONAL,
+  /**
+   * Unambiguously designates the Gregorian calendar for the locale.
+   * @stable ICU 2.0
+   */
+  UCAL_GREGORIAN,
+  /**
+   * A better name for UCAL_TRADITIONAL.
+   * @draft ICU 4.2
+   */
+  UCAL_DEFAULT = UCAL_TRADITIONAL
+};
+
+/** @stable ICU 2.0 */
+typedef enum UCalendarType UCalendarType;
+
+/** Possible fields in a UCalendar 
+ * @stable ICU 2.0
+ */
+enum UCalendarDateFields {
+  /** 
+   * Field number indicating the era, e.g., AD or BC in the Gregorian (Julian) calendar. 
+   * This is a calendar-specific value.
+   * @stable ICU 2.6 
+   */
+  UCAL_ERA,
+
+  /**
+   * Field number indicating the year. This is a calendar-specific value.
+   * @stable ICU 2.6 
+   */
+  UCAL_YEAR,
+
+  /**
+   * Field number indicating the month. This is a calendar-specific value. 
+   * The first month of the year is
+   * <code>JANUARY</code>; the last depends on the number of months in a year.
+   * @see #UCAL_JANUARY
+   * @see #UCAL_FEBRUARY
+   * @see #UCAL_MARCH
+   * @see #UCAL_APRIL
+   * @see #UCAL_MAY
+   * @see #UCAL_JUNE
+   * @see #UCAL_JULY
+   * @see #UCAL_AUGUST
+   * @see #UCAL_SEPTEMBER
+   * @see #UCAL_OCTOBER
+   * @see #UCAL_NOVEMBER
+   * @see #UCAL_DECEMBER
+   * @see #UCAL_UNDECIMBER
+   * @stable ICU 2.6 
+   */
+  UCAL_MONTH,
+
+  /**
+   * Field number indicating the
+   * week number within the current year.  The first week of the year, as
+   * defined by <code>UCAL_FIRST_DAY_OF_WEEK</code> and <code>UCAL_MINIMAL_DAYS_IN_FIRST_WEEK</code>
+   * attributes, has value 1.  Subclasses define
+   * the value of <code>UCAL_WEEK_OF_YEAR</code> for days before the first week of
+   * the year.
+   * @see ucal_getAttribute
+   * @see ucal_setAttribute
+   * @stable ICU 2.6 
+   */
+  UCAL_WEEK_OF_YEAR,
+
+ /**
+   * Field number indicating the
+   * week number within the current month.  The first week of the month, as
+   * defined by <code>UCAL_FIRST_DAY_OF_WEEK</code> and <code>UCAL_MINIMAL_DAYS_IN_FIRST_WEEK</code>
+   * attributes, has value 1.  Subclasses define
+   * the value of <code>WEEK_OF_MONTH</code> for days before the first week of
+   * the month.
+   * @see ucal_getAttribute
+   * @see ucal_setAttribute
+   * @see #UCAL_FIRST_DAY_OF_WEEK
+   * @see #UCAL_MINIMAL_DAYS_IN_FIRST_WEEK
+   * @stable ICU 2.6 
+   */
+  UCAL_WEEK_OF_MONTH,
+
+ /**
+   * Field number indicating the
+   * day of the month. This is a synonym for <code>DAY_OF_MONTH</code>.
+   * The first day of the month has value 1.
+   * @see #UCAL_DAY_OF_MONTH
+   * @stable ICU 2.6 
+   */
+  UCAL_DATE,
+
+ /**
+   * Field number indicating the day
+   * number within the current year.  The first day of the year has value 1.
+   * @stable ICU 2.6 
+   */
+  UCAL_DAY_OF_YEAR,
+
+ /**
+   * Field number indicating the day
+   * of the week.  This field takes values <code>SUNDAY</code>,
+   * <code>MONDAY</code>, <code>TUESDAY</code>, <code>WEDNESDAY</code>,
+   * <code>THURSDAY</code>, <code>FRIDAY</code>, and <code>SATURDAY</code>.
+   * @see #UCAL_SUNDAY
+   * @see #UCAL_MONDAY
+   * @see #UCAL_TUESDAY
+   * @see #UCAL_WEDNESDAY
+   * @see #UCAL_THURSDAY
+   * @see #UCAL_FRIDAY
+   * @see #UCAL_SATURDAY
+   * @stable ICU 2.6 
+   */
+  UCAL_DAY_OF_WEEK,
+
+ /**
+   * Field number indicating the
+   * ordinal number of the day of the week within the current month. Together
+   * with the <code>DAY_OF_WEEK</code> field, this uniquely specifies a day
+   * within a month.  Unlike <code>WEEK_OF_MONTH</code> and
+   * <code>WEEK_OF_YEAR</code>, this field's value does <em>not</em> depend on
+   * <code>getFirstDayOfWeek()</code> or
+   * <code>getMinimalDaysInFirstWeek()</code>.  <code>DAY_OF_MONTH 1</code>
+   * through <code>7</code> always correspond to <code>DAY_OF_WEEK_IN_MONTH
+   * 1</code>; <code>8</code> through <code>15</code> correspond to
+   * <code>DAY_OF_WEEK_IN_MONTH 2</code>, and so on.
+   * <code>DAY_OF_WEEK_IN_MONTH 0</code> indicates the week before
+   * <code>DAY_OF_WEEK_IN_MONTH 1</code>.  Negative values count back from the
+   * end of the month, so the last Sunday of a month is specified as
+   * <code>DAY_OF_WEEK = SUNDAY, DAY_OF_WEEK_IN_MONTH = -1</code>.  Because
+   * negative values count backward they will usually be aligned differently
+   * within the month than positive values.  For example, if a month has 31
+   * days, <code>DAY_OF_WEEK_IN_MONTH -1</code> will overlap
+   * <code>DAY_OF_WEEK_IN_MONTH 5</code> and the end of <code>4</code>.
+   * @see #UCAL_DAY_OF_WEEK
+   * @see #UCAL_WEEK_OF_MONTH
+   * @stable ICU 2.6 
+   */
+  UCAL_DAY_OF_WEEK_IN_MONTH,
+
+ /**
+   * Field number indicating
+   * whether the <code>HOUR</code> is before or after noon.
+   * E.g., at 10:04:15.250 PM the <code>AM_PM</code> is <code>PM</code>.
+   * @see #UCAL_AM
+   * @see #UCAL_PM
+   * @see #UCAL_HOUR
+   * @stable ICU 2.6 
+   */
+  UCAL_AM_PM,
+
+ /**
+   * Field number indicating the
+   * hour of the morning or afternoon. <code>HOUR</code> is used for the 12-hour
+   * clock.
+   * E.g., at 10:04:15.250 PM the <code>HOUR</code> is 10.
+   * @see #UCAL_AM_PM
+   * @see #UCAL_HOUR_OF_DAY
+   * @stable ICU 2.6 
+   */
+  UCAL_HOUR,
+
+ /**
+   * Field number indicating the
+   * hour of the day. <code>HOUR_OF_DAY</code> is used for the 24-hour clock.
+   * E.g., at 10:04:15.250 PM the <code>HOUR_OF_DAY</code> is 22.
+   * @see #UCAL_HOUR
+   * @stable ICU 2.6 
+   */
+  UCAL_HOUR_OF_DAY,
+
+ /**
+   * Field number indicating the
+   * minute within the hour.
+   * E.g., at 10:04:15.250 PM the <code>UCAL_MINUTE</code> is 4.
+   * @stable ICU 2.6 
+   */
+  UCAL_MINUTE,
+
+ /**
+   * Field number indicating the
+   * second within the minute.
+   * E.g., at 10:04:15.250 PM the <code>UCAL_SECOND</code> is 15.
+   * @stable ICU 2.6 
+   */
+  UCAL_SECOND,
+
+ /**
+   * Field number indicating the
+   * millisecond within the second.
+   * E.g., at 10:04:15.250 PM the <code>UCAL_MILLISECOND</code> is 250.
+   * @stable ICU 2.6 
+   */
+  UCAL_MILLISECOND,
+
+ /**
+   * Field number indicating the
+   * raw offset from GMT in milliseconds.
+   * @stable ICU 2.6 
+   */
+  UCAL_ZONE_OFFSET,
+
+ /**
+   * Field number indicating the
+   * daylight savings offset in milliseconds.
+   * @stable ICU 2.6 
+   */
+  UCAL_DST_OFFSET,
+  
+ /**
+   * Field number 
+   * indicating the extended year corresponding to the
+   * <code>UCAL_WEEK_OF_YEAR</code> field.  This may be one greater or less
+   * than the value of <code>UCAL_EXTENDED_YEAR</code>.
+   * @stable ICU 2.6
+   */
+  UCAL_YEAR_WOY,
+
+ /**
+   * Field number 
+   * indicating the localized day of week.  This will be a value from 1
+   * to 7 inclusive, with 1 being the localized first day of the week.
+   * @stable ICU 2.6
+   */
+  UCAL_DOW_LOCAL,
+
+  /**
+   * Year of this calendar system, encompassing all supra-year fields. For example, 
+   * in Gregorian/Julian calendars, positive Extended Year values indicate years AD,
+   *  1 BC = 0 extended, 2 BC = -1 extended, and so on. 
+   * @stable ICU 2.8 
+   */
+  UCAL_EXTENDED_YEAR,
+
+ /**
+   * Field number 
+   * indicating the modified Julian day number.  This is different from
+   * the conventional Julian day number in two regards.  First, it
+   * demarcates days at local zone midnight, rather than noon GMT.
+   * Second, it is a local number; that is, it depends on the local time
+   * zone.  It can be thought of as a single number that encompasses all
+   * the date-related fields.
+   * @stable ICU 2.8
+   */
+  UCAL_JULIAN_DAY, 
+
+  /**
+   * Ranges from 0 to 23:59:59.999 (regardless of DST).  This field behaves <em>exactly</em> 
+   * like a composite of all time-related fields, not including the zone fields.  As such, 
+   * it also reflects discontinuities of those fields on DST transition days.  On a day
+   * of DST onset, it will jump forward.  On a day of DST cessation, it will jump 
+   * backward.  This reflects the fact that it must be combined with the DST_OFFSET field
+   * to obtain a unique local time value.
+   * @stable ICU 2.8
+   */
+  UCAL_MILLISECONDS_IN_DAY,
+
+  /**
+   * Whether or not the current month is a leap month (0 or 1). See the Chinese calendar for
+   * an example of this.
+   */
+  UCAL_IS_LEAP_MONTH,
+  
+  /**
+   * Field count
+   * @stable ICU 2.6
+   */
+  UCAL_FIELD_COUNT,
+
+ /**
+   * Field number indicating the
+   * day of the month. This is a synonym for <code>UCAL_DATE</code>.
+   * The first day of the month has value 1.
+   * @see #UCAL_DATE
+   * Synonym for UCAL_DATE
+   * @stable ICU 2.8
+   **/
+  UCAL_DAY_OF_MONTH=UCAL_DATE
+};
+
+/** @stable ICU 2.0 */
+typedef enum UCalendarDateFields UCalendarDateFields;
+    /**
+     * Useful constant for days of week. Note: Calendar day-of-week is 1-based. Clients
+     * who create locale resources for the field of first-day-of-week should be aware of
+     * this. For instance, in US locale, first-day-of-week is set to 1, i.e., UCAL_SUNDAY.
+     */
+/** Possible days of the week in a UCalendar 
+ * @stable ICU 2.0
+ */
+enum UCalendarDaysOfWeek {
+  /** Sunday */
+  UCAL_SUNDAY = 1,
+  /** Monday */
+  UCAL_MONDAY,
+  /** Tuesday */
+  UCAL_TUESDAY,
+  /** Wednesday */
+  UCAL_WEDNESDAY,
+  /** Thursday */
+  UCAL_THURSDAY,
+  /** Friday */
+  UCAL_FRIDAY,
+  /** Saturday */
+  UCAL_SATURDAY
+};
+
+/** @stable ICU 2.0 */
+typedef enum UCalendarDaysOfWeek UCalendarDaysOfWeek;
+
+/** Possible months in a UCalendar. Note: Calendar month is 0-based.
+ * @stable ICU 2.0
+ */
+enum UCalendarMonths {
+  /** January */
+  UCAL_JANUARY,
+  /** February */
+  UCAL_FEBRUARY,
+  /** March */
+  UCAL_MARCH,
+  /** April */
+  UCAL_APRIL,
+  /** May */
+  UCAL_MAY,
+  /** June */
+  UCAL_JUNE,
+  /** July */
+  UCAL_JULY,
+  /** August */
+  UCAL_AUGUST,
+  /** September */
+  UCAL_SEPTEMBER,
+  /** October */
+  UCAL_OCTOBER,
+  /** November */
+  UCAL_NOVEMBER,
+  /** December */
+  UCAL_DECEMBER,
+  /** Value of the <code>UCAL_MONTH</code> field indicating the
+    * thirteenth month of the year. Although the Gregorian calendar
+    * does not use this value, lunar calendars do.
+    */
+  UCAL_UNDECIMBER
+};
+
+/** @stable ICU 2.0 */
+typedef enum UCalendarMonths UCalendarMonths;
+
+/** Possible AM/PM values in a UCalendar 
+ * @stable ICU 2.0
+ */
+enum UCalendarAMPMs {
+    /** AM */
+  UCAL_AM,
+  /** PM */
+  UCAL_PM
+};
+
+/** @stable ICU 2.0 */
+typedef enum UCalendarAMPMs UCalendarAMPMs;
+
+/**
+ * Create an enumeration over all time zones.
+ *
+ * @param ec input/output error code
+ *
+ * @return an enumeration object that the caller must dispose of using
+ * uenum_close(), or NULL upon failure. In case of failure *ec will
+ * indicate the error.
+ *
+ * @stable ICU 2.6
+ */
+U_STABLE UEnumeration* U_EXPORT2
+ucal_openTimeZones(UErrorCode* ec);
+
+/**
+ * Create an enumeration over all time zones associated with the given
+ * country. Some zones are affiliated with no country (e.g., "UTC");
+ * these may also be retrieved, as a group.
+ *
+ * @param country the ISO 3166 two-letter country code, or NULL to
+ * retrieve zones not affiliated with any country
+ *
+ * @param ec input/output error code
+ *
+ * @return an enumeration object that the caller must dispose of using
+ * uenum_close(), or NULL upon failure. In case of failure *ec will
+ * indicate the error.
+ *
+ * @stable ICU 2.6
+ */
+U_STABLE UEnumeration* U_EXPORT2
+ucal_openCountryTimeZones(const char* country, UErrorCode* ec);
+
+/**
+ * Return the default time zone. The default is determined initially
+ * by querying the host operating system. It may be changed with
+ * ucal_setDefaultTimeZone() or with the C++ TimeZone API.
+ *
+ * @param result A buffer to receive the result, or NULL
+ *
+ * @param resultCapacity The capacity of the result buffer
+ *
+ * @param ec input/output error code
+ *
+ * @return The result string length, not including the terminating
+ * null
+ *
+ * @stable ICU 2.6
+ */
+U_STABLE int32_t U_EXPORT2
+ucal_getDefaultTimeZone(UChar* result, int32_t resultCapacity, UErrorCode* ec);
+
+/**
+ * Set the default time zone.
+ *
+ * @param zoneID null-terminated time zone ID
+ *
+ * @param ec input/output error code
+ *
+ * @stable ICU 2.6
+ */
+U_STABLE void U_EXPORT2
+ucal_setDefaultTimeZone(const UChar* zoneID, UErrorCode* ec);
+
+/**
+ * Return the amount of time in milliseconds that the clock is
+ * advanced during daylight savings time for the given time zone, or
+ * zero if the time zone does not observe daylight savings time.
+ *
+ * @param zoneID null-terminated time zone ID
+ *
+ * @param ec input/output error code
+ *
+ * @return the number of milliseconds the time is advanced with
+ * respect to standard time when the daylight savings rules are in
+ * effect. This is always a non-negative number, most commonly either
+ * 3,600,000 (one hour) or zero.
+ *
+ * @stable ICU 2.6
+ */
+U_STABLE int32_t U_EXPORT2
+ucal_getDSTSavings(const UChar* zoneID, UErrorCode* ec);
+
+/**
+ * Get the current date and time.
+ * The value returned is represented as milliseconds from the epoch.
+ * @return The current date and time.
+ * @stable ICU 2.0
+ */
+U_STABLE UDate U_EXPORT2 
+ucal_getNow(void);
+
+/**
+ * Open a UCalendar.
+ * A UCalendar may be used to convert a millisecond value to a year,
+ * month, and day.
+ * @param zoneID The desired TimeZone ID.  If 0, use the default time zone.
+ * @param len The length of zoneID, or -1 if null-terminated.
+ * @param locale The desired locale
+ * @param type The type of UCalendar to open. This can be UCAL_GREGORIAN to open the Gregorian
+ * calendar for the locale, or UCAL_DEFAULT to open the default calendar for the locale (the
+ * default calendar may also be Gregorian). To open a specific non-Gregorian calendar for the
+ * locale, use uloc_setKeywordValue to set the value of the calendar keyword for the locale
+ * and then pass the locale to ucal_open with UCAL_DEFAULT as the type.
+ * @param status A pointer to an UErrorCode to receive any errors
+ * @return A pointer to a UCalendar, or 0 if an error occurred.
+ * @stable ICU 2.0
+ */
+U_STABLE UCalendar* U_EXPORT2 
+ucal_open(const UChar*   zoneID,
+          int32_t        len,
+          const char*    locale,
+          UCalendarType  type,
+          UErrorCode*    status);
+
+/**
+ * Close a UCalendar.
+ * Once closed, a UCalendar may no longer be used.
+ * @param cal The UCalendar to close.
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+ucal_close(UCalendar *cal);
+
+/**
+ * Open a copy of a UCalendar.
+ * This function performs a deep copy.
+ * @param cal The calendar to copy
+ * @param status A pointer to an UErrorCode to receive any errors.
+ * @return A pointer to a UCalendar identical to cal.
+ * @draft ICU 4.0
+ */
+U_DRAFT UCalendar* U_EXPORT2 
+ucal_clone(const UCalendar* cal,
+           UErrorCode*      status);
+
+/**
+ * Set the TimeZone used by a UCalendar.
+ * A UCalendar uses a timezone for converting from Greenwich time to local time.
+ * @param cal The UCalendar to set.
+ * @param zoneID The desired TimeZone ID.  If 0, use the default time zone.
+ * @param len The length of zoneID, or -1 if null-terminated.
+ * @param status A pointer to an UErrorCode to receive any errors.
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+ucal_setTimeZone(UCalendar*    cal,
+                 const UChar*  zoneID,
+                 int32_t       len,
+                 UErrorCode*   status);
+
+/**
+ * Possible formats for a UCalendar's display name 
+ * @stable ICU 2.0
+ */
+enum UCalendarDisplayNameType {
+  /** Standard display name */
+  UCAL_STANDARD,
+  /** Short standard display name */
+  UCAL_SHORT_STANDARD,
+  /** Daylight savings display name */
+  UCAL_DST,
+  /** Short daylight savings display name */
+  UCAL_SHORT_DST
+};
+
+/** @stable ICU 2.0 */
+typedef enum UCalendarDisplayNameType UCalendarDisplayNameType;
+
+/**
+ * Get the display name for a UCalendar's TimeZone.
+ * A display name is suitable for presentation to a user.
+ * @param cal          The UCalendar to query.
+ * @param type         The desired display name format; one of UCAL_STANDARD, UCAL_SHORT_STANDARD,
+ *                     UCAL_DST, UCAL_SHORT_DST
+ * @param locale       The desired locale for the display name.
+ * @param result       A pointer to a buffer to receive the formatted number.
+ * @param resultLength The maximum size of result.
+ * @param status       A pointer to an UErrorCode to receive any errors
+ * @return             The total buffer size needed; if greater than resultLength, the output was truncated.
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2 
+ucal_getTimeZoneDisplayName(const UCalendar*          cal,
+                            UCalendarDisplayNameType  type,
+                            const char*               locale,
+                            UChar*                    result,
+                            int32_t                   resultLength,
+                            UErrorCode*               status);
+
+/**
+ * Determine if a UCalendar is currently in daylight savings time.
+ * Daylight savings time is not used in all parts of the world.
+ * @param cal The UCalendar to query.
+ * @param status A pointer to an UErrorCode to receive any errors
+ * @return TRUE if cal is currently in daylight savings time, FALSE otherwise
+ * @stable ICU 2.0
+ */
+U_STABLE UBool U_EXPORT2 
+ucal_inDaylightTime(const UCalendar*  cal,
+                    UErrorCode*       status );
+
+/**
+ * Sets the GregorianCalendar change date. This is the point when the switch from
+ * Julian dates to Gregorian dates occurred. Default is 00:00:00 local time, October
+ * 15, 1582. Previous to this time and date will be Julian dates.
+ *
+ * This function works only for Gregorian calendars. If the UCalendar is not
+ * an instance of a Gregorian calendar, then a U_UNSUPPORTED_ERROR
+ * error code is set.
+ *
+ * @param cal        The calendar object.
+ * @param date       The given Gregorian cutover date.
+ * @param pErrorCode Pointer to a standard ICU error code. Its input value must
+ *                   pass the U_SUCCESS() test, or else the function returns
+ *                   immediately. Check for U_FAILURE() on output or use with
+ *                   function chaining. (See User Guide for details.)
+ *
+ * @see GregorianCalendar::setGregorianChange
+ * @see ucal_getGregorianChange
+ * @stable ICU 3.6
+ */
+U_STABLE void U_EXPORT2
+ucal_setGregorianChange(UCalendar *cal, UDate date, UErrorCode *pErrorCode);
+
+/**
+ * Gets the Gregorian Calendar change date. This is the point when the switch from
+ * Julian dates to Gregorian dates occurred. Default is 00:00:00 local time, October
+ * 15, 1582. Previous to this time and date will be Julian dates.
+ *
+ * This function works only for Gregorian calendars. If the UCalendar is not
+ * an instance of a Gregorian calendar, then a U_UNSUPPORTED_ERROR
+ * error code is set.
+ *
+ * @param cal        The calendar object.
+ * @param pErrorCode Pointer to a standard ICU error code. Its input value must
+ *                   pass the U_SUCCESS() test, or else the function returns
+ *                   immediately. Check for U_FAILURE() on output or use with
+ *                   function chaining. (See User Guide for details.)
+ * @return   The Gregorian cutover time for this calendar.
+ *
+ * @see GregorianCalendar::getGregorianChange
+ * @see ucal_setGregorianChange
+ * @stable ICU 3.6
+ */
+U_STABLE UDate U_EXPORT2
+ucal_getGregorianChange(const UCalendar *cal, UErrorCode *pErrorCode);
+
+/**
+ * Types of UCalendar attributes 
+ * @stable ICU 2.0
+ */
+enum UCalendarAttribute {
+    /** Lenient parsing */
+  UCAL_LENIENT,
+  /** First day of week */
+  UCAL_FIRST_DAY_OF_WEEK,
+  /** Minimum number of days in first week */
+  UCAL_MINIMAL_DAYS_IN_FIRST_WEEK
+};
+
+/** @stable ICU 2.0 */
+typedef enum UCalendarAttribute UCalendarAttribute;
+
+/**
+ * Get a numeric attribute associated with a UCalendar.
+ * Numeric attributes include the first day of the week, or the minimal numbers
+ * of days in the first week of the month.
+ * @param cal The UCalendar to query.
+ * @param attr The desired attribute; one of UCAL_LENIENT, UCAL_FIRST_DAY_OF_WEEK,
+ * or UCAL_MINIMAL_DAYS_IN_FIRST_WEEK
+ * @return The value of attr.
+ * @see ucal_setAttribute
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2 
+ucal_getAttribute(const UCalendar*    cal,
+                  UCalendarAttribute  attr);
+
+/**
+ * Set a numeric attribute associated with a UCalendar.
+ * Numeric attributes include the first day of the week, or the minimal numbers
+ * of days in the first week of the month.
+ * @param cal The UCalendar to set.
+ * @param attr The desired attribute; one of UCAL_LENIENT, UCAL_FIRST_DAY_OF_WEEK,
+ * or UCAL_MINIMAL_DAYS_IN_FIRST_WEEK
+ * @param newValue The new value of attr.
+ * @see ucal_getAttribute
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+ucal_setAttribute(UCalendar*          cal,
+                  UCalendarAttribute  attr,
+                  int32_t             newValue);
+
+/**
+ * Get a locale for which calendars are available.
+ * A UCalendar in a locale returned by this function will contain the correct
+ * day and month names for the locale.
+ * @param index The index of the desired locale.
+ * @return A locale for which calendars are available, or 0 if none.
+ * @see ucal_countAvailable
+ * @stable ICU 2.0
+ */
+U_STABLE const char* U_EXPORT2 
+ucal_getAvailable(int32_t index);
+
+/**
+ * Determine how many locales have calendars available.
+ * This function is most useful as determining the loop ending condition for
+ * calls to \ref ucal_getAvailable.
+ * @return The number of locales for which calendars are available.
+ * @see ucal_getAvailable
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2 
+ucal_countAvailable(void);
+
+/**
+ * Get a UCalendar's current time in millis.
+ * The time is represented as milliseconds from the epoch.
+ * @param cal The UCalendar to query.
+ * @param status A pointer to an UErrorCode to receive any errors
+ * @return The calendar's current time in millis.
+ * @see ucal_setMillis
+ * @see ucal_setDate
+ * @see ucal_setDateTime
+ * @stable ICU 2.0
+ */
+U_STABLE UDate U_EXPORT2 
+ucal_getMillis(const UCalendar*  cal,
+               UErrorCode*       status);
+
+/**
+ * Set a UCalendar's current time in millis.
+ * The time is represented as milliseconds from the epoch.
+ * @param cal The UCalendar to set.
+ * @param dateTime The desired date and time.
+ * @param status A pointer to an UErrorCode to receive any errors
+ * @see ucal_getMillis
+ * @see ucal_setDate
+ * @see ucal_setDateTime
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+ucal_setMillis(UCalendar*   cal,
+               UDate        dateTime,
+               UErrorCode*  status );
+
+/**
+ * Set a UCalendar's current date.
+ * The date is represented as a series of 32-bit integers.
+ * @param cal The UCalendar to set.
+ * @param year The desired year.
+ * @param month The desired month; one of UCAL_JANUARY, UCAL_FEBRUARY, UCAL_MARCH, UCAL_APRIL, UCAL_MAY,
+ * UCAL_JUNE, UCAL_JULY, UCAL_AUGUST, UCAL_SEPTEMBER, UCAL_OCTOBER, UCAL_NOVEMBER, UCAL_DECEMBER, UCAL_UNDECIMBER
+ * @param date The desired day of the month.
+ * @param status A pointer to an UErrorCode to receive any errors
+ * @see ucal_getMillis
+ * @see ucal_setMillis
+ * @see ucal_setDateTime
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+ucal_setDate(UCalendar*   cal,
+             int32_t      year,
+             int32_t      month,
+             int32_t      date,
+             UErrorCode*  status);
+
+/**
+ * Set a UCalendar's current date.
+ * The date is represented as a series of 32-bit integers.
+ * @param cal The UCalendar to set.
+ * @param year The desired year.
+ * @param month The desired month; one of UCAL_JANUARY, UCAL_FEBRUARY, UCAL_MARCH, UCAL_APRIL, UCAL_MAY,
+ * UCAL_JUNE, UCAL_JULY, UCAL_AUGUST, UCAL_SEPTEMBER, UCAL_OCTOBER, UCAL_NOVEMBER, UCAL_DECEMBER, UCAL_UNDECIMBER
+ * @param date The desired day of the month.
+ * @param hour The desired hour of day.
+ * @param minute The desired minute.
+ * @param second The desirec second.
+ * @param status A pointer to an UErrorCode to receive any errors
+ * @see ucal_getMillis
+ * @see ucal_setMillis
+ * @see ucal_setDate
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+ucal_setDateTime(UCalendar*   cal,
+                 int32_t      year,
+                 int32_t      month,
+                 int32_t      date,
+                 int32_t      hour,
+                 int32_t      minute,
+                 int32_t      second,
+                 UErrorCode*  status);
+
+/**
+ * Returns TRUE if two UCalendars are equivalent.  Equivalent
+ * UCalendars will behave identically, but they may be set to
+ * different times.
+ * @param cal1 The first of the UCalendars to compare.
+ * @param cal2 The second of the UCalendars to compare.
+ * @return TRUE if cal1 and cal2 are equivalent, FALSE otherwise.
+ * @stable ICU 2.0
+ */
+U_STABLE UBool U_EXPORT2 
+ucal_equivalentTo(const UCalendar*  cal1,
+                  const UCalendar*  cal2);
+
+/**
+ * Add a specified signed amount to a particular field in a UCalendar.
+ * This can modify more significant fields in the calendar.
+ * @param cal The UCalendar to which to add.
+ * @param field The field to which to add the signed value; one of UCAL_ERA, UCAL_YEAR, UCAL_MONTH,
+ * UCAL_WEEK_OF_YEAR, UCAL_WEEK_OF_MONTH, UCAL_DATE, UCAL_DAY_OF_YEAR, UCAL_DAY_OF_WEEK,
+ * UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_AM_PM, UCAL_HOUR, UCAL_HOUR_OF_DAY, UCAL_MINUTE, UCAL_SECOND,
+ * UCAL_MILLISECOND, UCAL_ZONE_OFFSET, UCAL_DST_OFFSET.
+ * @param amount The signed amount to add to field. If the amount causes the value
+ * to exceed to maximum or minimum values for that field, other fields are modified
+ * to preserve the magnitude of the change.
+ * @param status A pointer to an UErrorCode to receive any errors
+ * @see ucal_roll
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+ucal_add(UCalendar*           cal,
+         UCalendarDateFields  field,
+         int32_t              amount,
+         UErrorCode*          status);
+
+/**
+ * Add a specified signed amount to a particular field in a UCalendar.
+ * This will not modify more significant fields in the calendar.
+ * @param cal The UCalendar to which to add.
+ * @param field The field to which to add the signed value; one of UCAL_ERA, UCAL_YEAR, UCAL_MONTH,
+ * UCAL_WEEK_OF_YEAR, UCAL_WEEK_OF_MONTH, UCAL_DATE, UCAL_DAY_OF_YEAR, UCAL_DAY_OF_WEEK,
+ * UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_AM_PM, UCAL_HOUR, UCAL_HOUR_OF_DAY, UCAL_MINUTE, UCAL_SECOND,
+ * UCAL_MILLISECOND, UCAL_ZONE_OFFSET, UCAL_DST_OFFSET.
+ * @param amount The signed amount to add to field. If the amount causes the value
+ * to exceed to maximum or minimum values for that field, the field is pinned to a permissible
+ * value.
+ * @param status A pointer to an UErrorCode to receive any errors
+ * @see ucal_add
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+ucal_roll(UCalendar*           cal,
+          UCalendarDateFields  field,
+          int32_t              amount,
+          UErrorCode*          status);
+
+/**
+ * Get the current value of a field from a UCalendar.
+ * All fields are represented as 32-bit integers.
+ * @param cal The UCalendar to query.
+ * @param field The desired field; one of UCAL_ERA, UCAL_YEAR, UCAL_MONTH,
+ * UCAL_WEEK_OF_YEAR, UCAL_WEEK_OF_MONTH, UCAL_DATE, UCAL_DAY_OF_YEAR, UCAL_DAY_OF_WEEK,
+ * UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_AM_PM, UCAL_HOUR, UCAL_HOUR_OF_DAY, UCAL_MINUTE, UCAL_SECOND,
+ * UCAL_MILLISECOND, UCAL_ZONE_OFFSET, UCAL_DST_OFFSET.
+ * @param status A pointer to an UErrorCode to receive any errors
+ * @return The value of the desired field.
+ * @see ucal_set
+ * @see ucal_isSet
+ * @see ucal_clearField
+ * @see ucal_clear
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2 
+ucal_get(const UCalendar*     cal,
+         UCalendarDateFields  field,
+         UErrorCode*          status );
+
+/**
+ * Set the value of a field in a UCalendar.
+ * All fields are represented as 32-bit integers.
+ * @param cal The UCalendar to set.
+ * @param field The field to set; one of UCAL_ERA, UCAL_YEAR, UCAL_MONTH,
+ * UCAL_WEEK_OF_YEAR, UCAL_WEEK_OF_MONTH, UCAL_DATE, UCAL_DAY_OF_YEAR, UCAL_DAY_OF_WEEK,
+ * UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_AM_PM, UCAL_HOUR, UCAL_HOUR_OF_DAY, UCAL_MINUTE, UCAL_SECOND,
+ * UCAL_MILLISECOND, UCAL_ZONE_OFFSET, UCAL_DST_OFFSET.
+ * @param value The desired value of field.
+ * @see ucal_get
+ * @see ucal_isSet
+ * @see ucal_clearField
+ * @see ucal_clear
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+ucal_set(UCalendar*           cal,
+         UCalendarDateFields  field,
+         int32_t              value);
+
+/**
+ * Determine if a field in a UCalendar is set.
+ * All fields are represented as 32-bit integers.
+ * @param cal The UCalendar to query.
+ * @param field The desired field; one of UCAL_ERA, UCAL_YEAR, UCAL_MONTH,
+ * UCAL_WEEK_OF_YEAR, UCAL_WEEK_OF_MONTH, UCAL_DATE, UCAL_DAY_OF_YEAR, UCAL_DAY_OF_WEEK,
+ * UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_AM_PM, UCAL_HOUR, UCAL_HOUR_OF_DAY, UCAL_MINUTE, UCAL_SECOND,
+ * UCAL_MILLISECOND, UCAL_ZONE_OFFSET, UCAL_DST_OFFSET.
+ * @return TRUE if field is set, FALSE otherwise.
+ * @see ucal_get
+ * @see ucal_set
+ * @see ucal_clearField
+ * @see ucal_clear
+ * @stable ICU 2.0
+ */
+U_STABLE UBool U_EXPORT2 
+ucal_isSet(const UCalendar*     cal,
+           UCalendarDateFields  field);
+
+/**
+ * Clear a field in a UCalendar.
+ * All fields are represented as 32-bit integers.
+ * @param cal The UCalendar containing the field to clear.
+ * @param field The field to clear; one of UCAL_ERA, UCAL_YEAR, UCAL_MONTH,
+ * UCAL_WEEK_OF_YEAR, UCAL_WEEK_OF_MONTH, UCAL_DATE, UCAL_DAY_OF_YEAR, UCAL_DAY_OF_WEEK,
+ * UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_AM_PM, UCAL_HOUR, UCAL_HOUR_OF_DAY, UCAL_MINUTE, UCAL_SECOND,
+ * UCAL_MILLISECOND, UCAL_ZONE_OFFSET, UCAL_DST_OFFSET.
+ * @see ucal_get
+ * @see ucal_set
+ * @see ucal_isSet
+ * @see ucal_clear
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+ucal_clearField(UCalendar*           cal,
+                UCalendarDateFields  field);
+
+/**
+ * Clear all fields in a UCalendar.
+ * All fields are represented as 32-bit integers.
+ * @param calendar The UCalendar to clear.
+ * @see ucal_get
+ * @see ucal_set
+ * @see ucal_isSet
+ * @see ucal_clearField
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+ucal_clear(UCalendar* calendar);
+
+/**
+ * Possible limit values for a UCalendar 
+ * @stable ICU 2.0
+ */
+enum UCalendarLimitType {
+  /** Minimum value */
+  UCAL_MINIMUM,
+  /** Maximum value */
+  UCAL_MAXIMUM,
+  /** Greatest minimum value */
+  UCAL_GREATEST_MINIMUM,
+  /** Leaest maximum value */
+  UCAL_LEAST_MAXIMUM,
+  /** Actual minimum value */
+  UCAL_ACTUAL_MINIMUM,
+  /** Actual maximum value */
+  UCAL_ACTUAL_MAXIMUM
+};
+
+/** @stable ICU 2.0 */
+typedef enum UCalendarLimitType UCalendarLimitType;
+
+/**
+ * Determine a limit for a field in a UCalendar.
+ * A limit is a maximum or minimum value for a field.
+ * @param cal The UCalendar to query.
+ * @param field The desired field; one of UCAL_ERA, UCAL_YEAR, UCAL_MONTH,
+ * UCAL_WEEK_OF_YEAR, UCAL_WEEK_OF_MONTH, UCAL_DATE, UCAL_DAY_OF_YEAR, UCAL_DAY_OF_WEEK,
+ * UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_AM_PM, UCAL_HOUR, UCAL_HOUR_OF_DAY, UCAL_MINUTE, UCAL_SECOND,
+ * UCAL_MILLISECOND, UCAL_ZONE_OFFSET, UCAL_DST_OFFSET.
+ * @param type The desired critical point; one of UCAL_MINIMUM, UCAL_MAXIMUM, UCAL_GREATEST_MINIMUM,
+ * UCAL_LEAST_MAXIMUM, UCAL_ACTUAL_MINIMUM, UCAL_ACTUAL_MAXIMUM
+ * @param status A pointer to an UErrorCode to receive any errors.
+ * @return The requested value.
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2 
+ucal_getLimit(const UCalendar*     cal,
+              UCalendarDateFields  field,
+              UCalendarLimitType   type,
+              UErrorCode*          status);
+
+/** Get the locale for this calendar object. You can choose between valid and actual locale.
+ *  @param cal The calendar object
+ *  @param type type of the locale we're looking for (valid or actual) 
+ *  @param status error code for the operation
+ *  @return the locale name
+ *  @stable ICU 2.8
+ */
+U_STABLE const char * U_EXPORT2
+ucal_getLocaleByType(const UCalendar *cal, ULocDataLocaleType type, UErrorCode* status);
+
+/**
+ * Returns the timezone data version currently used by ICU.
+ * @param status error code for the operation
+ * @return the version string, such as "2007f"
+ * @stable ICU 3.8
+ */
+U_DRAFT const char * U_EXPORT2
+ucal_getTZDataVersion(UErrorCode* status);
+
+/**
+ * Returns the canonical system timezone ID or the normalized
+ * custom time zone ID for the given time zone ID.
+ * @param id        The input timezone ID to be canonicalized.
+ * @param len       The length of id, or -1 if null-terminated.
+ * @param result    The buffer receives the canonical system timezone ID
+ *                  or the custom timezone ID in normalized format.
+ * @param resultCapacity    The capacity of the result buffer.
+ * @param isSystemID        Receives if the given ID is a known system
+     *                      timezone ID.
+ * @param status    Recevies the status.  When the given timezone ID
+ *                  is neither a known system time zone ID nor a
+ *                  valid custom timezone ID, U_ILLEGAL_ARGUMENT_ERROR
+ *                  is set.
+ * @return          The result string length, not including the terminating
+ *                  null.
+ * @draft ICU 4.0
+ */
+U_DRAFT int32_t U_EXPORT2
+ucal_getCanonicalTimeZoneID(const UChar* id, int32_t len,
+                            UChar* result, int32_t resultCapacity, UBool *isSystemID, UErrorCode* status);
+/**
+ * Get the resource keyword value string designating the calendar type for the UCalendar.
+ * @param cal The UCalendar to query.
+ * @param status The error code for the operation.
+ * @return The resource keyword value string.
+ * @draft ICU 4.2
+ */
+U_DRAFT const char * U_EXPORT2
+ucal_getType(const UCalendar *cal, UErrorCode* status);
+
+/**
+ * The following is a temporary Apple-specific API to help InternationalPrefs
+ * transition to the updated version of the above ICU API. It will be removed soon.
+ */
+U_DRAFT const char * U_EXPORT2
+ucal_getTypeWithError(const UCalendar *cal, UErrorCode* status);
+
+#endif /* #if !UCONFIG_NO_FORMATTING */
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/ucasemap.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/ucasemap.h b/src/apps/couch_collate/platform/osx/icu/unicode/ucasemap.h
new file mode 100644
index 0000000..7ba622b
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/ucasemap.h
@@ -0,0 +1,391 @@
+/*
+*******************************************************************************
+*
+*   Copyright (C) 2005-2008, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+*
+*******************************************************************************
+*   file name:  ucasemap.h
+*   encoding:   US-ASCII
+*   tab size:   8 (not used)
+*   indentation:4
+*
+*   created on: 2005may06
+*   created by: Markus W. Scherer
+*
+*   Case mapping service object and functions using it.
+*/
+
+#ifndef __UCASEMAP_H__
+#define __UCASEMAP_H__
+
+#include "unicode/utypes.h"
+#include "unicode/ustring.h"
+
+/**
+ * \file
+ * \brief C API: Unicode case mapping functions using a UCaseMap service object.
+ *
+ * The service object takes care of memory allocations, data loading, and setup
+ * for the attributes, as usual.
+ *
+ * Currently, the functionality provided here does not overlap with uchar.h
+ * and ustring.h, except for ucasemap_toTitle().
+ *
+ * ucasemap_utf8XYZ() functions operate directly on UTF-8 strings.
+ */
+
+/**
+ * UCaseMap is an opaque service object for newer ICU case mapping functions.
+ * Older functions did not use a service object.
+ * @stable ICU 3.4
+ */
+struct UCaseMap;
+typedef struct UCaseMap UCaseMap; /**< C typedef for struct UCaseMap. @stable ICU 3.4 */
+
+/**
+ * Open a UCaseMap service object for a locale and a set of options.
+ * The locale ID and options are preprocessed so that functions using the
+ * service object need not process them in each call.
+ *
+ * @param locale ICU locale ID, used for language-dependent
+ *               upper-/lower-/title-casing according to the Unicode standard.
+ *               Usual semantics: ""=root, NULL=default locale, etc.
+ * @param options Options bit set, used for case folding and string comparisons.
+ *                Same flags as for u_foldCase(), u_strFoldCase(),
+ *                u_strCaseCompare(), etc.
+ *                Use 0 or U_FOLD_CASE_DEFAULT for default behavior.
+ * @param pErrorCode Must be a valid pointer to an error code value,
+ *                   which must not indicate a failure before the function call.
+ * @return Pointer to a UCaseMap service object, if successful.
+ *
+ * @see U_FOLD_CASE_DEFAULT
+ * @see U_FOLD_CASE_EXCLUDE_SPECIAL_I
+ * @see U_TITLECASE_NO_LOWERCASE
+ * @see U_TITLECASE_NO_BREAK_ADJUSTMENT
+ * @stable ICU 3.4
+ */
+U_STABLE UCaseMap * U_EXPORT2
+ucasemap_open(const char *locale, uint32_t options, UErrorCode *pErrorCode);
+
+/**
+ * Close a UCaseMap service object.
+ * @param csm Object to be closed.
+ * @stable ICU 3.4
+ */
+U_STABLE void U_EXPORT2
+ucasemap_close(UCaseMap *csm);
+
+/**
+ * Get the locale ID that is used for language-dependent case mappings.
+ * @param csm UCaseMap service object.
+ * @return locale ID
+ * @stable ICU 3.4
+ */
+U_STABLE const char * U_EXPORT2
+ucasemap_getLocale(const UCaseMap *csm);
+
+/**
+ * Get the options bit set that is used for case folding and string comparisons.
+ * @param csm UCaseMap service object.
+ * @return options bit set
+ * @stable ICU 3.4
+ */
+U_STABLE uint32_t U_EXPORT2
+ucasemap_getOptions(const UCaseMap *csm);
+
+/**
+ * Set the locale ID that is used for language-dependent case mappings.
+ *
+ * @param csm UCaseMap service object.
+ * @param locale Locale ID, see ucasemap_open().
+ * @param pErrorCode Must be a valid pointer to an error code value,
+ *                   which must not indicate a failure before the function call.
+ *
+ * @see ucasemap_open
+ * @stable ICU 3.4
+ */
+U_STABLE void U_EXPORT2
+ucasemap_setLocale(UCaseMap *csm, const char *locale, UErrorCode *pErrorCode);
+
+/**
+ * Set the options bit set that is used for case folding and string comparisons.
+ *
+ * @param csm UCaseMap service object.
+ * @param options Options bit set, see ucasemap_open().
+ * @param pErrorCode Must be a valid pointer to an error code value,
+ *                   which must not indicate a failure before the function call.
+ *
+ * @see ucasemap_open
+ * @stable ICU 3.4
+ */
+U_STABLE void U_EXPORT2
+ucasemap_setOptions(UCaseMap *csm, uint32_t options, UErrorCode *pErrorCode);
+
+/**
+ * Do not lowercase non-initial parts of words when titlecasing.
+ * Option bit for titlecasing APIs that take an options bit set.
+ *
+ * By default, titlecasing will titlecase the first cased character
+ * of a word and lowercase all other characters.
+ * With this option, the other characters will not be modified.
+ *
+ * @see ucasemap_setOptions
+ * @see ucasemap_toTitle
+ * @see ucasemap_utf8ToTitle
+ * @see UnicodeString::toTitle
+ * @stable ICU 4.0
+ */
+#define U_TITLECASE_NO_LOWERCASE 0x100
+
+/**
+ * Do not adjust the titlecasing indexes from BreakIterator::next() indexes;
+ * titlecase exactly the characters at breaks from the iterator.
+ * Option bit for titlecasing APIs that take an options bit set.
+ *
+ * By default, titlecasing will take each break iterator index,
+ * adjust it by looking for the next cased character, and titlecase that one.
+ * Other characters are lowercased.
+ *
+ * This follows Unicode 4 & 5 section 3.13 Default Case Operations:
+ *
+ * R3  toTitlecase(X): Find the word boundaries based on Unicode Standard Annex
+ * #29, "Text Boundaries." Between each pair of word boundaries, find the first
+ * cased character F. If F exists, map F to default_title(F); then map each
+ * subsequent character C to default_lower(C).
+ *
+ * @see ucasemap_setOptions
+ * @see ucasemap_toTitle
+ * @see ucasemap_utf8ToTitle
+ * @see UnicodeString::toTitle
+ * @see U_TITLECASE_NO_LOWERCASE
+ * @stable ICU 4.0
+ */
+#define U_TITLECASE_NO_BREAK_ADJUSTMENT 0x200
+
+#if !UCONFIG_NO_BREAK_ITERATION
+
+/**
+ * Get the break iterator that is used for titlecasing.
+ * Do not modify the returned break iterator.
+ * @param csm UCaseMap service object.
+ * @return titlecasing break iterator
+ * @stable ICU 4.0
+ */
+U_DRAFT const UBreakIterator * U_EXPORT2
+ucasemap_getBreakIterator(const UCaseMap *csm);
+
+/**
+ * Set the break iterator that is used for titlecasing.
+ * The UCaseMap service object releases a previously set break iterator
+ * and "adopts" this new one, taking ownership of it.
+ * It will be released in a subsequent call to ucasemap_setBreakIterator()
+ * or ucasemap_close().
+ *
+ * Break iterator operations are not thread-safe. Therefore, titlecasing
+ * functions use non-const UCaseMap objects. It is not possible to titlecase
+ * strings concurrently using the same UCaseMap.
+ *
+ * @param csm UCaseMap service object.
+ * @param iterToAdopt Break iterator to be adopted for titlecasing.
+ * @param pErrorCode Must be a valid pointer to an error code value,
+ *                   which must not indicate a failure before the function call.
+ *
+ * @see ucasemap_toTitle
+ * @see ucasemap_utf8ToTitle
+ * @stable ICU 4.0
+ */
+U_DRAFT void U_EXPORT2
+ucasemap_setBreakIterator(UCaseMap *csm, UBreakIterator *iterToAdopt, UErrorCode *pErrorCode);
+
+/**
+ * Titlecase a UTF-16 string. This function is almost a duplicate of u_strToTitle(),
+ * except that it takes ucasemap_setOptions() into account and has performance
+ * advantages from being able to use a UCaseMap object for multiple case mapping
+ * operations, saving setup time.
+ *
+ * Casing is locale-dependent and context-sensitive.
+ * Titlecasing uses a break iterator to find the first characters of words
+ * that are to be titlecased. It titlecases those characters and lowercases
+ * all others. (This can be modified with ucasemap_setOptions().)
+ *
+ * The titlecase break iterator can be provided to customize for arbitrary
+ * styles, using rules and dictionaries beyond the standard iterators.
+ * It may be more efficient to always provide an iterator to avoid
+ * opening and closing one for each string.
+ * The standard titlecase iterator for the root locale implements the
+ * algorithm of Unicode TR 21.
+ *
+ * This function uses only the setText(), first() and next() methods of the
+ * provided break iterator.
+ *
+ * The result may be longer or shorter than the original.
+ * The source string and the destination buffer must not overlap.
+ *
+ * @param csm       UCaseMap service object.
+ * @param dest      A buffer for the result string. The result will be NUL-terminated if
+ *                  the buffer is large enough.
+ *                  The contents is undefined in case of failure.
+ * @param destCapacity The size of the buffer (number of bytes). If it is 0, then
+ *                  dest may be NULL and the function will only return the length of the result
+ *                  without writing any of the result string.
+ * @param src       The original string.
+ * @param srcLength The length of the original string. If -1, then src must be NUL-terminated.
+ * @param pErrorCode Must be a valid pointer to an error code value,
+ *                  which must not indicate a failure before the function call.
+ * @return The length of the result string, if successful - or in case of a buffer overflow,
+ *         in which case it will be greater than destCapacity.
+ *
+ * @see u_strToTitle
+ * @stable ICU 4.0
+ */
+U_DRAFT int32_t U_EXPORT2
+ucasemap_toTitle(UCaseMap *csm,
+                 UChar *dest, int32_t destCapacity,
+                 const UChar *src, int32_t srcLength,
+                 UErrorCode *pErrorCode);
+
+#endif
+
+/**
+ * Lowercase the characters in a UTF-8 string.
+ * Casing is locale-dependent and context-sensitive.
+ * The result may be longer or shorter than the original.
+ * The source string and the destination buffer must not overlap.
+ *
+ * @param csm       UCaseMap service object.
+ * @param dest      A buffer for the result string. The result will be NUL-terminated if
+ *                  the buffer is large enough.
+ *                  The contents is undefined in case of failure.
+ * @param destCapacity The size of the buffer (number of bytes). If it is 0, then
+ *                  dest may be NULL and the function will only return the length of the result
+ *                  without writing any of the result string.
+ * @param src       The original string.
+ * @param srcLength The length of the original string. If -1, then src must be NUL-terminated.
+ * @param pErrorCode Must be a valid pointer to an error code value,
+ *                  which must not indicate a failure before the function call.
+ * @return The length of the result string, if successful - or in case of a buffer overflow,
+ *         in which case it will be greater than destCapacity.
+ *
+ * @see u_strToLower
+ * @stable ICU 3.4
+ */
+U_STABLE int32_t U_EXPORT2
+ucasemap_utf8ToLower(const UCaseMap *csm,
+                     char *dest, int32_t destCapacity,
+                     const char *src, int32_t srcLength,
+                     UErrorCode *pErrorCode);
+
+/**
+ * Uppercase the characters in a UTF-8 string.
+ * Casing is locale-dependent and context-sensitive.
+ * The result may be longer or shorter than the original.
+ * The source string and the destination buffer must not overlap.
+ *
+ * @param csm       UCaseMap service object.
+ * @param dest      A buffer for the result string. The result will be NUL-terminated if
+ *                  the buffer is large enough.
+ *                  The contents is undefined in case of failure.
+ * @param destCapacity The size of the buffer (number of bytes). If it is 0, then
+ *                  dest may be NULL and the function will only return the length of the result
+ *                  without writing any of the result string.
+ * @param src       The original string.
+ * @param srcLength The length of the original string. If -1, then src must be NUL-terminated.
+ * @param pErrorCode Must be a valid pointer to an error code value,
+ *                  which must not indicate a failure before the function call.
+ * @return The length of the result string, if successful - or in case of a buffer overflow,
+ *         in which case it will be greater than destCapacity.
+ *
+ * @see u_strToUpper
+ * @stable ICU 3.4
+ */
+U_STABLE int32_t U_EXPORT2
+ucasemap_utf8ToUpper(const UCaseMap *csm,
+                     char *dest, int32_t destCapacity,
+                     const char *src, int32_t srcLength,
+                     UErrorCode *pErrorCode);
+
+#if !UCONFIG_NO_BREAK_ITERATION
+
+/**
+ * Titlecase a UTF-8 string.
+ * Casing is locale-dependent and context-sensitive.
+ * Titlecasing uses a break iterator to find the first characters of words
+ * that are to be titlecased. It titlecases those characters and lowercases
+ * all others. (This can be modified with ucasemap_setOptions().)
+ *
+ * The titlecase break iterator can be provided to customize for arbitrary
+ * styles, using rules and dictionaries beyond the standard iterators.
+ * It may be more efficient to always provide an iterator to avoid
+ * opening and closing one for each string.
+ * The standard titlecase iterator for the root locale implements the
+ * algorithm of Unicode TR 21.
+ *
+ * This function uses only the setText(), first() and next() methods of the
+ * provided break iterator.
+ *
+ * The result may be longer or shorter than the original.
+ * The source string and the destination buffer must not overlap.
+ *
+ * @param csm       UCaseMap service object.
+ * @param dest      A buffer for the result string. The result will be NUL-terminated if
+ *                  the buffer is large enough.
+ *                  The contents is undefined in case of failure.
+ * @param destCapacity The size of the buffer (number of bytes). If it is 0, then
+ *                  dest may be NULL and the function will only return the length of the result
+ *                  without writing any of the result string.
+ * @param src       The original string.
+ * @param srcLength The length of the original string. If -1, then src must be NUL-terminated.
+ * @param pErrorCode Must be a valid pointer to an error code value,
+ *                  which must not indicate a failure before the function call.
+ * @return The length of the result string, if successful - or in case of a buffer overflow,
+ *         in which case it will be greater than destCapacity.
+ *
+ * @see u_strToTitle
+ * @see U_TITLECASE_NO_LOWERCASE
+ * @see U_TITLECASE_NO_BREAK_ADJUSTMENT
+ * @stable ICU 4.0
+ */
+U_DRAFT int32_t U_EXPORT2
+ucasemap_utf8ToTitle(UCaseMap *csm,
+                    char *dest, int32_t destCapacity,
+                    const char *src, int32_t srcLength,
+                    UErrorCode *pErrorCode);
+
+#endif
+
+/**
+ * Case-fold the characters in a UTF-8 string.
+ * Case-folding is locale-independent and not context-sensitive,
+ * but there is an option for whether to include or exclude mappings for dotted I
+ * and dotless i that are marked with 'I' in CaseFolding.txt.
+ * The result may be longer or shorter than the original.
+ * The source string and the destination buffer must not overlap.
+ *
+ * @param csm       UCaseMap service object.
+ * @param dest      A buffer for the result string. The result will be NUL-terminated if
+ *                  the buffer is large enough.
+ *                  The contents is undefined in case of failure.
+ * @param destCapacity The size of the buffer (number of bytes). If it is 0, then
+ *                  dest may be NULL and the function will only return the length of the result
+ *                  without writing any of the result string.
+ * @param src       The original string.
+ * @param srcLength The length of the original string. If -1, then src must be NUL-terminated.
+ * @param pErrorCode Must be a valid pointer to an error code value,
+ *                  which must not indicate a failure before the function call.
+ * @return The length of the result string, if successful - or in case of a buffer overflow,
+ *         in which case it will be greater than destCapacity.
+ *
+ * @see u_strFoldCase
+ * @see ucasemap_setOptions
+ * @see U_FOLD_CASE_DEFAULT
+ * @see U_FOLD_CASE_EXCLUDE_SPECIAL_I
+ * @stable ICU 4.0
+ */
+U_DRAFT int32_t U_EXPORT2
+ucasemap_utf8FoldCase(const UCaseMap *csm,
+                      char *dest, int32_t destCapacity,
+                      const char *src, int32_t srcLength,
+                      UErrorCode *pErrorCode);
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/ucat.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/ucat.h b/src/apps/couch_collate/platform/osx/icu/unicode/ucat.h
new file mode 100644
index 0000000..ad9f037
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/ucat.h
@@ -0,0 +1,158 @@
+/*
+**********************************************************************
+* Copyright (c) 2003-2004, International Business Machines
+* Corporation and others.  All Rights Reserved.
+**********************************************************************
+* Author: Alan Liu
+* Created: March 19 2003
+* Since: ICU 2.6
+**********************************************************************
+*/
+#ifndef UCAT_H
+#define UCAT_H
+
+#include "unicode/utypes.h"
+#include "unicode/ures.h"
+
+/**
+ * \file
+ * \brief C API: Message Catalog Wrappers
+ *
+ * This C API provides look-alike functions that deliberately resemble
+ * the POSIX catopen, catclose, and catgets functions.  The underlying
+ * implementation is in terms of ICU resource bundles, rather than
+ * POSIX message catalogs.
+ *
+ * The ICU resource bundles obey standard ICU inheritance policies.
+ * To facilitate this, sets and messages are flattened into one tier.
+ * This is done by creating resource bundle keys of the form
+ * &lt;set_num&gt;%&lt;msg_num&gt; where set_num is the set number and msg_num is
+ * the message number, formatted as decimal strings.
+ *
+ * Example:  Consider a message catalog containing two sets:
+ *
+ * Set 1: Message 4  = "Good morning."
+ *        Message 5  = "Good afternoon."
+ *        Message 7  = "Good evening."
+ *        Message 8  = "Good night."
+ * Set 4: Message 14 = "Please "
+ *        Message 19 = "Thank you."
+ *        Message 20 = "Sincerely,"
+ *
+ * The ICU resource bundle source file would, assuming it is named
+ * "greet.txt", would look like this:
+ *
+ * greet
+ * {
+ *     1%4  { "Good morning." }
+ *     1%5  { "Good afternoon." }
+ *     1%7  { "Good evening." }
+ *     1%8  { "Good night." }
+ * 
+ *     4%14 { "Please " }
+ *     4%19 { "Thank you." }
+ *     4%20 { "Sincerely," }
+ * }
+ *
+ * The catgets function is commonly used in combination with functions
+ * like printf and strftime.  ICU components like message format can
+ * be used instead, although they use a different format syntax.
+ * There is an ICU package, icuio, that provides some of
+ * the POSIX-style formatting API.
+ */
+
+U_CDECL_BEGIN
+
+/**
+ * An ICU message catalog descriptor, analogous to nl_catd.
+ * 
+ * @stable ICU 2.6
+ */
+typedef UResourceBundle* u_nl_catd;
+
+/**
+ * Open and return an ICU message catalog descriptor. The descriptor
+ * may be passed to u_catgets() to retrieve localized strings.
+ *
+ * @param name string containing the full path pointing to the
+ * directory where the resources reside followed by the package name
+ * e.g. "/usr/resource/my_app/resources/guimessages" on a Unix system.
+ * If NULL, ICU default data files will be used.
+ *
+ * Unlike POSIX, environment variables are not interpolated within the
+ * name.
+ *
+ * @param locale the locale for which we want to open the resource. If
+ * NULL, the default ICU locale will be used (see uloc_getDefault). If
+ * strlen(locale) == 0, the root locale will be used.
+ *
+ * @param ec input/output error code. Upon output,
+ * U_USING_FALLBACK_WARNING indicates that a fallback locale was
+ * used. For example, 'de_CH' was requested, but nothing was found
+ * there, so 'de' was used. U_USING_DEFAULT_WARNING indicates that the
+ * default locale data or root locale data was used; neither the
+ * requested locale nor any of its fallback locales were found.
+ *
+ * @return a message catalog descriptor that may be passed to
+ * u_catgets(). If the ec parameter indicates success, then the caller
+ * is responsible for calling u_catclose() to close the message
+ * catalog. If the ec parameter indicates failure, then NULL will be
+ * returned.
+ * 
+ * @stable ICU 2.6
+ */
+U_STABLE u_nl_catd U_EXPORT2
+u_catopen(const char* name, const char* locale, UErrorCode* ec);
+
+/**
+ * Close an ICU message catalog, given its descriptor.
+ *
+ * @param catd a message catalog descriptor to be closed. May be NULL,
+ * in which case no action is taken.
+ * 
+ * @stable ICU 2.6
+ */
+U_STABLE void U_EXPORT2
+u_catclose(u_nl_catd catd);
+
+/**
+ * Retrieve a localized string from an ICU message catalog.
+ *
+ * @param catd a message catalog descriptor returned by u_catopen.
+ *
+ * @param set_num the message catalog set number. Sets need not be
+ * numbered consecutively.
+ *
+ * @param msg_num the message catalog message number within the
+ * set. Messages need not be numbered consecutively.
+ *
+ * @param s the default string. This is returned if the string
+ * specified by the set_num and msg_num is not found. It must be
+ * zero-terminated.
+ *
+ * @param len fill-in parameter to receive the length of the result.
+ * May be NULL, in which case it is ignored.
+ *
+ * @param ec input/output error code. May be U_USING_FALLBACK_WARNING
+ * or U_USING_DEFAULT_WARNING. U_MISSING_RESOURCE_ERROR indicates that
+ * the set_num/msg_num tuple does not specify a valid message string
+ * in this catalog.
+ *
+ * @return a pointer to a zero-terminated UChar array which lives in
+ * an internal buffer area, typically a memory mapped/DLL file. The
+ * caller must NOT delete this pointer. If the call is unsuccessful
+ * for any reason, then s is returned.  This includes the situation in
+ * which ec indicates a failing error code upon entry to this
+ * function.
+ * 
+ * @stable ICU 2.6
+ */
+U_STABLE const UChar* U_EXPORT2
+u_catgets(u_nl_catd catd, int32_t set_num, int32_t msg_num,
+          const UChar* s,
+          int32_t* len, UErrorCode* ec);
+
+U_CDECL_END
+
+#endif /*UCAT_H*/
+/*eof*/


[88/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/decimfmt.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/decimfmt.h b/src/apps/couch_collate/platform/osx/icu/unicode/decimfmt.h
new file mode 100644
index 0000000..a584a9c
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/decimfmt.h
@@ -0,0 +1,1901 @@
+/*
+********************************************************************************
+*   Copyright (C) 1997-2009, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+********************************************************************************
+*
+* File DECIMFMT.H
+*
+* Modification History:
+*
+*   Date        Name        Description
+*   02/19/97    aliu        Converted from java.
+*   03/20/97    clhuang     Updated per C++ implementation.
+*   04/03/97    aliu        Rewrote parsing and formatting completely, and
+*                           cleaned up and debugged.  Actually works now.
+*   04/17/97    aliu        Changed DigitCount to int per code review.
+*   07/10/97    helena      Made ParsePosition a class and get rid of the function
+*                           hiding problems.
+*   09/09/97    aliu        Ported over support for exponential formats.
+*    07/20/98    stephen        Changed documentation
+********************************************************************************
+*/
+ 
+#ifndef DECIMFMT_H
+#define DECIMFMT_H
+ 
+#include "unicode/utypes.h"
+/**
+ * \file 
+ * \brief C++ API: Formats decimal numbers.
+ */
+ 
+#if !UCONFIG_NO_FORMATTING
+
+#include "unicode/dcfmtsym.h"
+#include "unicode/numfmt.h"
+#include "unicode/locid.h"
+
+U_NAMESPACE_BEGIN
+
+class DigitList;
+class ChoiceFormat;
+class UnicodeSet;
+
+/**
+ * DecimalFormat is a concrete subclass of NumberFormat that formats decimal
+ * numbers. It has a variety of features designed to make it possible to parse
+ * and format numbers in any locale, including support for Western, Arabic, or
+ * Indic digits.  It also supports different flavors of numbers, including
+ * integers ("123"), fixed-point numbers ("123.4"), scientific notation
+ * ("1.23E4"), percentages ("12%"), and currency amounts ("$123").  All of these
+ * flavors can be easily localized.
+ *
+ * <p>To obtain a NumberFormat for a specific locale (including the default
+ * locale) call one of NumberFormat's factory methods such as
+ * createInstance(). Do not call the DecimalFormat constructors directly, unless
+ * you know what you are doing, since the NumberFormat factory methods may
+ * return subclasses other than DecimalFormat.
+ *
+ * <p><strong>Example Usage</strong>
+ *
+ * \code
+ *     // Normally we would have a GUI with a menu for this
+ *     int32_t locCount;
+ *     const Locale* locales = NumberFormat::getAvailableLocales(locCount);
+ * 
+ *     double myNumber = -1234.56;
+ *     UErrorCode success = U_ZERO_ERROR;
+ *     NumberFormat* form;
+ * 
+ *     // Print out a number with the localized number, currency and percent
+ *     // format for each locale.
+ *     UnicodeString countryName;
+ *     UnicodeString displayName;
+ *     UnicodeString str;
+ *     UnicodeString pattern;
+ *     Formattable fmtable;
+ *     for (int32_t j = 0; j < 3; ++j) {
+ *         cout << endl << "FORMAT " << j << endl;
+ *         for (int32_t i = 0; i < locCount; ++i) {
+ *             if (locales[i].getCountry(countryName).size() == 0) {
+ *                 // skip language-only
+ *                 continue;
+ *             }
+ *             switch (j) {
+ *             case 0:
+ *                 form = NumberFormat::createInstance(locales[i], success ); break;
+ *             case 1:
+ *                 form = NumberFormat::createCurrencyInstance(locales[i], success ); break;
+ *             default:
+ *                 form = NumberFormat::createPercentInstance(locales[i], success ); break;
+ *             }
+ *             if (form) {
+ *                 str.remove();
+ *                 pattern = ((DecimalFormat*)form)->toPattern(pattern);
+ *                 cout << locales[i].getDisplayName(displayName) << ": " << pattern;
+ *                 cout << "  ->  " << form->format(myNumber,str) << endl;
+ *                 form->parse(form->format(myNumber,str), fmtable, success);
+ *                 delete form;  
+ *             }
+ *         }
+ *     }
+ * \endcode
+ *
+ * <p><strong>Patterns</strong>
+ *
+ * <p>A DecimalFormat consists of a <em>pattern</em> and a set of
+ * <em>symbols</em>.  The pattern may be set directly using
+ * applyPattern(), or indirectly using other API methods which
+ * manipulate aspects of the pattern, such as the minimum number of integer
+ * digits.  The symbols are stored in a DecimalFormatSymbols
+ * object.  When using the NumberFormat factory methods, the
+ * pattern and symbols are read from ICU's locale data.
+ * 
+ * <p><strong>Special Pattern Characters</strong>
+ *
+ * <p>Many characters in a pattern are taken literally; they are matched during
+ * parsing and output unchanged during formatting.  Special characters, on the
+ * other hand, stand for other characters, strings, or classes of characters.
+ * For example, the '#' character is replaced by a localized digit.  Often the
+ * replacement character is the same as the pattern character; in the U.S. locale,
+ * the ',' grouping character is replaced by ','.  However, the replacement is
+ * still happening, and if the symbols are modified, the grouping character
+ * changes.  Some special characters affect the behavior of the formatter by
+ * their presence; for example, if the percent character is seen, then the
+ * value is multiplied by 100 before being displayed.
+ *
+ * <p>To insert a special character in a pattern as a literal, that is, without
+ * any special meaning, the character must be quoted.  There are some exceptions to
+ * this which are noted below.
+ *
+ * <p>The characters listed here are used in non-localized patterns.  Localized
+ * patterns use the corresponding characters taken from this formatter's
+ * DecimalFormatSymbols object instead, and these characters lose
+ * their special status.  Two exceptions are the currency sign and quote, which
+ * are not localized.
+ *
+ * <table border=0 cellspacing=3 cellpadding=0>
+ *   <tr bgcolor="#ccccff">
+ *     <td align=left><strong>Symbol</strong>
+ *     <td align=left><strong>Location</strong>
+ *     <td align=left><strong>Localized?</strong>
+ *     <td align=left><strong>Meaning</strong>
+ *   <tr valign=top>
+ *     <td><code>0</code>
+ *     <td>Number
+ *     <td>Yes
+ *     <td>Digit
+ *   <tr valign=top bgcolor="#eeeeff">
+ *     <td><code>1-9</code>
+ *     <td>Number
+ *     <td>Yes
+ *     <td>'1' through '9' indicate rounding.
+ *   <tr valign=top>
+ *     <td><code>\htmlonly&#x40;\endhtmlonly</code> <!--doxygen doesn't like @-->
+ *     <td>Number
+ *     <td>No
+ *     <td>Significant digit
+ *   <tr valign=top bgcolor="#eeeeff">
+ *     <td><code>#</code>
+ *     <td>Number
+ *     <td>Yes
+ *     <td>Digit, zero shows as absent
+ *   <tr valign=top>
+ *     <td><code>.</code>
+ *     <td>Number
+ *     <td>Yes
+ *     <td>Decimal separator or monetary decimal separator
+ *   <tr valign=top bgcolor="#eeeeff">
+ *     <td><code>-</code>
+ *     <td>Number
+ *     <td>Yes
+ *     <td>Minus sign
+ *   <tr valign=top>
+ *     <td><code>,</code>
+ *     <td>Number
+ *     <td>Yes
+ *     <td>Grouping separator
+ *   <tr valign=top bgcolor="#eeeeff">
+ *     <td><code>E</code>
+ *     <td>Number
+ *     <td>Yes
+ *     <td>Separates mantissa and exponent in scientific notation.
+ *         <em>Need not be quoted in prefix or suffix.</em>
+ *   <tr valign=top>
+ *     <td><code>+</code>
+ *     <td>Exponent
+ *     <td>Yes
+ *     <td>Prefix positive exponents with localized plus sign.
+ *         <em>Need not be quoted in prefix or suffix.</em>
+ *   <tr valign=top bgcolor="#eeeeff">
+ *     <td><code>;</code>
+ *     <td>Subpattern boundary
+ *     <td>Yes
+ *     <td>Separates positive and negative subpatterns
+ *   <tr valign=top>
+ *     <td><code>\%</code>
+ *     <td>Prefix or suffix
+ *     <td>Yes
+ *     <td>Multiply by 100 and show as percentage
+ *   <tr valign=top bgcolor="#eeeeff">
+ *     <td><code>\\u2030</code>
+ *     <td>Prefix or suffix
+ *     <td>Yes
+ *     <td>Multiply by 1000 and show as per mille
+ *   <tr valign=top>
+ *     <td><code>\htmlonly&curren;\endhtmlonly</code> (<code>\\u00A4</code>)
+ *     <td>Prefix or suffix
+ *     <td>No
+ *     <td>Currency sign, replaced by currency symbol.  If
+ *         doubled, replaced by international currency symbol.
+ *         If present in a pattern, the monetary decimal separator
+ *         is used instead of the decimal separator.
+ *   <tr valign=top bgcolor="#eeeeff">
+ *     <td><code>'</code>
+ *     <td>Prefix or suffix
+ *     <td>No
+ *     <td>Used to quote special characters in a prefix or suffix,
+ *         for example, <code>"'#'#"</code> formats 123 to
+ *         <code>"#123"</code>.  To create a single quote
+ *         itself, use two in a row: <code>"# o''clock"</code>.
+ *   <tr valign=top>
+ *     <td><code>*</code>
+ *     <td>Prefix or suffix boundary
+ *     <td>Yes
+ *     <td>Pad escape, precedes pad character
+ * </table>
+ *
+ * <p>A DecimalFormat pattern contains a postive and negative
+ * subpattern, for example, "#,##0.00;(#,##0.00)".  Each subpattern has a
+ * prefix, a numeric part, and a suffix.  If there is no explicit negative
+ * subpattern, the negative subpattern is the localized minus sign prefixed to the
+ * positive subpattern. That is, "0.00" alone is equivalent to "0.00;-0.00".  If there
+ * is an explicit negative subpattern, it serves only to specify the negative
+ * prefix and suffix; the number of digits, minimal digits, and other
+ * characteristics are ignored in the negative subpattern. That means that
+ * "#,##0.0#;(#)" has precisely the same result as "#,##0.0#;(#,##0.0#)".
+ *
+ * <p>The prefixes, suffixes, and various symbols used for infinity, digits,
+ * thousands separators, decimal separators, etc. may be set to arbitrary
+ * values, and they will appear properly during formatting.  However, care must
+ * be taken that the symbols and strings do not conflict, or parsing will be
+ * unreliable.  For example, either the positive and negative prefixes or the
+ * suffixes must be distinct for parse() to be able
+ * to distinguish positive from negative values.  Another example is that the
+ * decimal separator and thousands separator should be distinct characters, or
+ * parsing will be impossible.
+ *
+ * <p>The <em>grouping separator</em> is a character that separates clusters of
+ * integer digits to make large numbers more legible.  It commonly used for
+ * thousands, but in some locales it separates ten-thousands.  The <em>grouping
+ * size</em> is the number of digits between the grouping separators, such as 3
+ * for "100,000,000" or 4 for "1 0000 0000". There are actually two different
+ * grouping sizes: One used for the least significant integer digits, the
+ * <em>primary grouping size</em>, and one used for all others, the
+ * <em>secondary grouping size</em>.  In most locales these are the same, but
+ * sometimes they are different. For example, if the primary grouping interval
+ * is 3, and the secondary is 2, then this corresponds to the pattern
+ * "#,##,##0", and the number 123456789 is formatted as "12,34,56,789".  If a
+ * pattern contains multiple grouping separators, the interval between the last
+ * one and the end of the integer defines the primary grouping size, and the
+ * interval between the last two defines the secondary grouping size. All others
+ * are ignored, so "#,##,###,####" == "###,###,####" == "##,#,###,####".
+ *
+ * <p>Illegal patterns, such as "#.#.#" or "#.###,###", will cause
+ * DecimalFormat to set a failing UErrorCode.
+ *
+ * <p><strong>Pattern BNF</strong>
+ *
+ * <pre>
+ * pattern    := subpattern (';' subpattern)?
+ * subpattern := prefix? number exponent? suffix?
+ * number     := (integer ('.' fraction)?) | sigDigits
+ * prefix     := '\\u0000'..'\\uFFFD' - specialCharacters
+ * suffix     := '\\u0000'..'\\uFFFD' - specialCharacters
+ * integer    := '#'* '0'* '0'
+ * fraction   := '0'* '#'*
+ * sigDigits  := '#'* '@' '@'* '#'*
+ * exponent   := 'E' '+'? '0'* '0'
+ * padSpec    := '*' padChar
+ * padChar    := '\\u0000'..'\\uFFFD' - quote
+ * &nbsp;
+ * Notation:
+ *   X*       0 or more instances of X
+ *   X?       0 or 1 instances of X
+ *   X|Y      either X or Y
+ *   C..D     any character from C up to D, inclusive
+ *   S-T      characters in S, except those in T
+ * </pre>
+ * The first subpattern is for positive numbers. The second (optional)
+ * subpattern is for negative numbers.
+ * 
+ * <p>Not indicated in the BNF syntax above:
+ *
+ * <ul><li>The grouping separator ',' can occur inside the integer and
+ * sigDigits elements, between any two pattern characters of that
+ * element, as long as the integer or sigDigits element is not
+ * followed by the exponent element.
+ *
+ * <li>Two grouping intervals are recognized: That between the
+ *     decimal point and the first grouping symbol, and that
+ *     between the first and second grouping symbols. These
+ *     intervals are identical in most locales, but in some
+ *     locales they differ. For example, the pattern
+ *     &quot;#,##,###&quot; formats the number 123456789 as
+ *     &quot;12,34,56,789&quot;.</li>
+ * 
+ * <li>The pad specifier <code>padSpec</code> may appear before the prefix,
+ * after the prefix, before the suffix, after the suffix, or not at all.
+ *
+ * <li>In place of '0', the digits '1' through '9' may be used to
+ * indicate a rounding increment.
+ * </ul>
+ *
+ * <p><strong>Parsing</strong>
+ *
+ * <p>DecimalFormat parses all Unicode characters that represent
+ * decimal digits, as defined by u_charDigitValue().  In addition,
+ * DecimalFormat also recognizes as digits the ten consecutive
+ * characters starting with the localized zero digit defined in the
+ * DecimalFormatSymbols object.  During formatting, the
+ * DecimalFormatSymbols-based digits are output.
+ *
+ * <p>During parsing, grouping separators are ignored.
+ *
+ * <p>If parse(UnicodeString&,Formattable&,ParsePosition&)
+ * fails to parse a string, it leaves the parse position unchanged.
+ * The convenience method parse(UnicodeString&,Formattable&,UErrorCode&)
+ * indicates parse failure by setting a failing
+ * UErrorCode.
+ *
+ * <p><strong>Formatting</strong>
+ *
+ * <p>Formatting is guided by several parameters, all of which can be
+ * specified either using a pattern or using the API.  The following
+ * description applies to formats that do not use <a href="#sci">scientific
+ * notation</a> or <a href="#sigdig">significant digits</a>.
+ *
+ * <ul><li>If the number of actual integer digits exceeds the
+ * <em>maximum integer digits</em>, then only the least significant
+ * digits are shown.  For example, 1997 is formatted as "97" if the
+ * maximum integer digits is set to 2.
+ *
+ * <li>If the number of actual integer digits is less than the
+ * <em>minimum integer digits</em>, then leading zeros are added.  For
+ * example, 1997 is formatted as "01997" if the minimum integer digits
+ * is set to 5.
+ *
+ * <li>If the number of actual fraction digits exceeds the <em>maximum
+ * fraction digits</em>, then half-even rounding it performed to the
+ * maximum fraction digits.  For example, 0.125 is formatted as "0.12"
+ * if the maximum fraction digits is 2.  This behavior can be changed
+ * by specifying a rounding increment and a rounding mode.
+ *
+ * <li>If the number of actual fraction digits is less than the
+ * <em>minimum fraction digits</em>, then trailing zeros are added.
+ * For example, 0.125 is formatted as "0.1250" if the mimimum fraction
+ * digits is set to 4.
+ *
+ * <li>Trailing fractional zeros are not displayed if they occur
+ * <em>j</em> positions after the decimal, where <em>j</em> is less
+ * than the maximum fraction digits. For example, 0.10004 is
+ * formatted as "0.1" if the maximum fraction digits is four or less.
+ * </ul>
+ *
+ * <p><strong>Special Values</strong>
+ *
+ * <p><code>NaN</code> is represented as a single character, typically
+ * <code>\\uFFFD</code>.  This character is determined by the
+ * DecimalFormatSymbols object.  This is the only value for which
+ * the prefixes and suffixes are not used.
+ *
+ * <p>Infinity is represented as a single character, typically
+ * <code>\\u221E</code>, with the positive or negative prefixes and suffixes
+ * applied.  The infinity character is determined by the
+ * DecimalFormatSymbols object.
+ *
+ * <a name="sci"><strong>Scientific Notation</strong></a>
+ *
+ * <p>Numbers in scientific notation are expressed as the product of a mantissa
+ * and a power of ten, for example, 1234 can be expressed as 1.234 x 10<sup>3</sup>. The
+ * mantissa is typically in the half-open interval [1.0, 10.0) or sometimes [0.0, 1.0),
+ * but it need not be.  DecimalFormat supports arbitrary mantissas.
+ * DecimalFormat can be instructed to use scientific
+ * notation through the API or through the pattern.  In a pattern, the exponent
+ * character immediately followed by one or more digit characters indicates
+ * scientific notation.  Example: "0.###E0" formats the number 1234 as
+ * "1.234E3".
+ *
+ * <ul>
+ * <li>The number of digit characters after the exponent character gives the
+ * minimum exponent digit count.  There is no maximum.  Negative exponents are
+ * formatted using the localized minus sign, <em>not</em> the prefix and suffix
+ * from the pattern.  This allows patterns such as "0.###E0 m/s".  To prefix
+ * positive exponents with a localized plus sign, specify '+' between the
+ * exponent and the digits: "0.###E+0" will produce formats "1E+1", "1E+0",
+ * "1E-1", etc.  (In localized patterns, use the localized plus sign rather than
+ * '+'.)
+ *
+ * <li>The minimum number of integer digits is achieved by adjusting the
+ * exponent.  Example: 0.00123 formatted with "00.###E0" yields "12.3E-4".  This
+ * only happens if there is no maximum number of integer digits.  If there is a
+ * maximum, then the minimum number of integer digits is fixed at one.
+ *
+ * <li>The maximum number of integer digits, if present, specifies the exponent
+ * grouping.  The most common use of this is to generate <em>engineering
+ * notation</em>, in which the exponent is a multiple of three, e.g.,
+ * "##0.###E0".  The number 12345 is formatted using "##0.####E0" as "12.345E3".
+ *
+ * <li>When using scientific notation, the formatter controls the
+ * digit counts using significant digits logic.  The maximum number of
+ * significant digits limits the total number of integer and fraction
+ * digits that will be shown in the mantissa; it does not affect
+ * parsing.  For example, 12345 formatted with "##0.##E0" is "12.3E3".
+ * See the section on significant digits for more details.
+ *
+ * <li>The number of significant digits shown is determined as
+ * follows: If areSignificantDigitsUsed() returns false, then the
+ * minimum number of significant digits shown is one, and the maximum
+ * number of significant digits shown is the sum of the <em>minimum
+ * integer</em> and <em>maximum fraction</em> digits, and is
+ * unaffected by the maximum integer digits.  If this sum is zero,
+ * then all significant digits are shown.  If
+ * areSignificantDigitsUsed() returns true, then the significant digit
+ * counts are specified by getMinimumSignificantDigits() and
+ * getMaximumSignificantDigits().  In this case, the number of
+ * integer digits is fixed at one, and there is no exponent grouping.
+ *
+ * <li>Exponential patterns may not contain grouping separators.
+ * </ul>
+ *
+ * <a name="sigdig"><strong>Significant Digits</strong></a>
+ *
+ * <code>DecimalFormat</code> has two ways of controlling how many
+ * digits are shows: (a) significant digits counts, or (b) integer and
+ * fraction digit counts.  Integer and fraction digit counts are
+ * described above.  When a formatter is using significant digits
+ * counts, the number of integer and fraction digits is not specified
+ * directly, and the formatter settings for these counts are ignored.
+ * Instead, the formatter uses however many integer and fraction
+ * digits are required to display the specified number of significant
+ * digits.  Examples:
+ *
+ * <table border=0 cellspacing=3 cellpadding=0>
+ *   <tr bgcolor="#ccccff">
+ *     <td align=left>Pattern
+ *     <td align=left>Minimum significant digits
+ *     <td align=left>Maximum significant digits
+ *     <td align=left>Number
+ *     <td align=left>Output of format()
+ *   <tr valign=top>
+ *     <td><code>\@\@\@</code>
+ *     <td>3
+ *     <td>3
+ *     <td>12345
+ *     <td><code>12300</code>
+ *   <tr valign=top bgcolor="#eeeeff">
+ *     <td><code>\@\@\@</code>
+ *     <td>3
+ *     <td>3
+ *     <td>0.12345
+ *     <td><code>0.123</code>
+ *   <tr valign=top>
+ *     <td><code>\@\@##</code>
+ *     <td>2
+ *     <td>4
+ *     <td>3.14159
+ *     <td><code>3.142</code>
+ *   <tr valign=top bgcolor="#eeeeff">
+ *     <td><code>\@\@##</code>
+ *     <td>2
+ *     <td>4
+ *     <td>1.23004
+ *     <td><code>1.23</code>
+ * </table>
+ *
+ * <ul>
+ * <li>Significant digit counts may be expressed using patterns that
+ * specify a minimum and maximum number of significant digits.  These
+ * are indicated by the <code>'@'</code> and <code>'#'</code>
+ * characters.  The minimum number of significant digits is the number
+ * of <code>'@'</code> characters.  The maximum number of significant
+ * digits is the number of <code>'@'</code> characters plus the number
+ * of <code>'#'</code> characters following on the right.  For
+ * example, the pattern <code>"@@@"</code> indicates exactly 3
+ * significant digits.  The pattern <code>"@##"</code> indicates from
+ * 1 to 3 significant digits.  Trailing zero digits to the right of
+ * the decimal separator are suppressed after the minimum number of
+ * significant digits have been shown.  For example, the pattern
+ * <code>"@##"</code> formats the number 0.1203 as
+ * <code>"0.12"</code>.
+ *
+ * <li>If a pattern uses significant digits, it may not contain a
+ * decimal separator, nor the <code>'0'</code> pattern character.
+ * Patterns such as <code>"@00"</code> or <code>"@.###"</code> are
+ * disallowed.
+ *
+ * <li>Any number of <code>'#'</code> characters may be prepended to
+ * the left of the leftmost <code>'@'</code> character.  These have no
+ * effect on the minimum and maximum significant digits counts, but
+ * may be used to position grouping separators.  For example,
+ * <code>"#,#@#"</code> indicates a minimum of one significant digits,
+ * a maximum of two significant digits, and a grouping size of three.
+ *
+ * <li>In order to enable significant digits formatting, use a pattern
+ * containing the <code>'@'</code> pattern character.  Alternatively,
+ * call setSignificantDigitsUsed(TRUE).
+ *
+ * <li>In order to disable significant digits formatting, use a
+ * pattern that does not contain the <code>'@'</code> pattern
+ * character. Alternatively, call setSignificantDigitsUsed(FALSE).
+ *
+ * <li>The number of significant digits has no effect on parsing.
+ *
+ * <li>Significant digits may be used together with exponential notation. Such
+ * patterns are equivalent to a normal exponential pattern with a minimum and
+ * maximum integer digit count of one, a minimum fraction digit count of
+ * <code>getMinimumSignificantDigits() - 1</code>, and a maximum fraction digit
+ * count of <code>getMaximumSignificantDigits() - 1</code>. For example, the
+ * pattern <code>"@@###E0"</code> is equivalent to <code>"0.0###E0"</code>.
+ *
+ * <li>If signficant digits are in use, then the integer and fraction
+ * digit counts, as set via the API, are ignored.  If significant
+ * digits are not in use, then the signficant digit counts, as set via
+ * the API, are ignored.
+ *
+ * </ul>
+ *
+ * <p><strong>Padding</strong>
+ *
+ * <p>DecimalFormat supports padding the result of
+ * format() to a specific width.  Padding may be specified either
+ * through the API or through the pattern syntax.  In a pattern the pad escape
+ * character, followed by a single pad character, causes padding to be parsed
+ * and formatted.  The pad escape character is '*' in unlocalized patterns, and
+ * can be localized using DecimalFormatSymbols::setSymbol() with a
+ * DecimalFormatSymbols::kPadEscapeSymbol
+ * selector.  For example, <code>"$*x#,##0.00"</code> formats 123 to
+ * <code>"$xx123.00"</code>, and 1234 to <code>"$1,234.00"</code>.
+ *
+ * <ul>
+ * <li>When padding is in effect, the width of the positive subpattern,
+ * including prefix and suffix, determines the format width.  For example, in
+ * the pattern <code>"* #0 o''clock"</code>, the format width is 10.
+ *
+ * <li>The width is counted in 16-bit code units (UChars).
+ *
+ * <li>Some parameters which usually do not matter have meaning when padding is
+ * used, because the pattern width is significant with padding.  In the pattern
+ * "* ##,##,#,##0.##", the format width is 14.  The initial characters "##,##,"
+ * do not affect the grouping size or maximum integer digits, but they do affect
+ * the format width.
+ *
+ * <li>Padding may be inserted at one of four locations: before the prefix,
+ * after the prefix, before the suffix, or after the suffix.  If padding is
+ * specified in any other location, applyPattern()
+ * sets a failing UErrorCode.  If there is no prefix,
+ * before the prefix and after the prefix are equivalent, likewise for the
+ * suffix.
+ *
+ * <li>When specified in a pattern, the 32-bit code point immediately
+ * following the pad escape is the pad character. This may be any character,
+ * including a special pattern character. That is, the pad escape
+ * <em>escapes</em> the following character. If there is no character after
+ * the pad escape, then the pattern is illegal.
+ *
+ * </ul>
+ *
+ * <p><strong>Rounding</strong>
+ *
+ * <p>DecimalFormat supports rounding to a specific increment.  For
+ * example, 1230 rounded to the nearest 50 is 1250.  1.234 rounded to the
+ * nearest 0.65 is 1.3.  The rounding increment may be specified through the API
+ * or in a pattern.  To specify a rounding increment in a pattern, include the
+ * increment in the pattern itself.  "#,#50" specifies a rounding increment of
+ * 50.  "#,##0.05" specifies a rounding increment of 0.05.
+ *
+ * <ul>
+ * <li>Rounding only affects the string produced by formatting.  It does
+ * not affect parsing or change any numerical values.
+ *
+ * <li>A <em>rounding mode</em> determines how values are rounded; see
+ * DecimalFormat::ERoundingMode.  Rounding increments specified in
+ * patterns use the default mode, DecimalFormat::kRoundHalfEven.
+ *
+ * <li>Some locales use rounding in their currency formats to reflect the
+ * smallest currency denomination.
+ *
+ * <li>In a pattern, digits '1' through '9' specify rounding, but otherwise
+ * behave identically to digit '0'.
+ * </ul>
+ *
+ * <p><strong>Synchronization</strong>
+ *
+ * <p>DecimalFormat objects are not synchronized.  Multiple
+ * threads should not access one formatter concurrently.
+ *
+ * <p><strong>Subclassing</strong>
+ *
+ * <p><em>User subclasses are not supported.</em> While clients may write
+ * subclasses, such code will not necessarily work and will not be
+ * guaranteed to work stably from release to release.
+ */
+class U_I18N_API DecimalFormat: public NumberFormat {
+public:
+    /**
+     * Rounding mode.
+     * @stable ICU 2.4
+     */
+    enum ERoundingMode {
+        kRoundCeiling,  /**< Round towards positive infinity */
+        kRoundFloor,    /**< Round towards negative infinity */
+        kRoundDown,     /**< Round towards zero */
+        kRoundUp,       /**< Round away from zero */
+        kRoundHalfEven, /**< Round towards the nearest integer, or
+                             towards the nearest even integer if equidistant */
+        kRoundHalfDown, /**< Round towards the nearest integer, or
+                             towards zero if equidistant */
+        kRoundHalfUp    /**< Round towards the nearest integer, or
+                             away from zero if equidistant */
+        // We don't support ROUND_UNNECESSARY
+    };
+
+    /**
+     * Pad position.
+     * @stable ICU 2.4
+     */
+    enum EPadPosition {
+        kPadBeforePrefix,
+        kPadAfterPrefix,
+        kPadBeforeSuffix,
+        kPadAfterSuffix
+    };
+
+    /**
+     * Create a DecimalFormat using the default pattern and symbols
+     * for the default locale. This is a convenient way to obtain a
+     * DecimalFormat when internationalization is not the main concern.
+     * <P>
+     * To obtain standard formats for a given locale, use the factory methods
+     * on NumberFormat such as createInstance. These factories will
+     * return the most appropriate sub-class of NumberFormat for a given
+     * locale.
+     * @param status    Output param set to success/failure code. If the
+     *                  pattern is invalid this will be set to a failure code.
+     * @stable ICU 2.0
+     */
+    DecimalFormat(UErrorCode& status);
+
+    /**
+     * Create a DecimalFormat from the given pattern and the symbols
+     * for the default locale. This is a convenient way to obtain a
+     * DecimalFormat when internationalization is not the main concern.
+     * <P>
+     * To obtain standard formats for a given locale, use the factory methods
+     * on NumberFormat such as createInstance. These factories will
+     * return the most appropriate sub-class of NumberFormat for a given
+     * locale.
+     * @param pattern   A non-localized pattern string.
+     * @param status    Output param set to success/failure code. If the
+     *                  pattern is invalid this will be set to a failure code.
+     * @stable ICU 2.0
+     */
+    DecimalFormat(const UnicodeString& pattern,
+                  UErrorCode& status);
+
+    /**
+     * Create a DecimalFormat from the given pattern and symbols.
+     * Use this constructor when you need to completely customize the
+     * behavior of the format.
+     * <P>
+     * To obtain standard formats for a given
+     * locale, use the factory methods on NumberFormat such as
+     * createInstance or createCurrencyInstance. If you need only minor adjustments
+     * to a standard format, you can modify the format returned by
+     * a NumberFormat factory method.
+     *
+     * @param pattern           a non-localized pattern string
+     * @param symbolsToAdopt    the set of symbols to be used.  The caller should not
+     *                          delete this object after making this call.
+     * @param status            Output param set to success/failure code. If the
+     *                          pattern is invalid this will be set to a failure code.
+     * @stable ICU 2.0
+     */
+    DecimalFormat(  const UnicodeString& pattern,
+                    DecimalFormatSymbols* symbolsToAdopt,
+                    UErrorCode& status);
+
+    /**
+     * Create a DecimalFormat from the given pattern and symbols.
+     * Use this constructor when you need to completely customize the
+     * behavior of the format.
+     * <P>
+     * To obtain standard formats for a given
+     * locale, use the factory methods on NumberFormat such as
+     * createInstance or createCurrencyInstance. If you need only minor adjustments
+     * to a standard format, you can modify the format returned by
+     * a NumberFormat factory method.
+     *
+     * @param pattern           a non-localized pattern string
+     * @param symbolsToAdopt    the set of symbols to be used.  The caller should not
+     *                          delete this object after making this call.
+     * @param parseError        Output param to receive errors occured during parsing 
+     * @param status            Output param set to success/failure code. If the
+     *                          pattern is invalid this will be set to a failure code.
+     * @stable ICU 2.0
+     */
+    DecimalFormat(  const UnicodeString& pattern,
+                    DecimalFormatSymbols* symbolsToAdopt,
+                    UParseError& parseError,
+                    UErrorCode& status);
+    /**
+     * Create a DecimalFormat from the given pattern and symbols.
+     * Use this constructor when you need to completely customize the
+     * behavior of the format.
+     * <P>
+     * To obtain standard formats for a given
+     * locale, use the factory methods on NumberFormat such as
+     * createInstance or createCurrencyInstance. If you need only minor adjustments
+     * to a standard format, you can modify the format returned by
+     * a NumberFormat factory method.
+     *
+     * @param pattern           a non-localized pattern string
+     * @param symbols   the set of symbols to be used
+     * @param status            Output param set to success/failure code. If the
+     *                          pattern is invalid this will be set to a failure code.
+     * @stable ICU 2.0
+     */
+    DecimalFormat(  const UnicodeString& pattern,
+                    const DecimalFormatSymbols& symbols,
+                    UErrorCode& status);
+
+    /**
+     * Copy constructor.
+     * 
+     * @param source    the DecimalFormat object to be copied from.
+     * @stable ICU 2.0
+     */
+    DecimalFormat(const DecimalFormat& source);
+
+    /**
+     * Assignment operator.
+     *
+     * @param rhs    the DecimalFormat object to be copied.
+     * @stable ICU 2.0
+     */
+    DecimalFormat& operator=(const DecimalFormat& rhs);
+
+    /**
+     * Destructor.
+     * @stable ICU 2.0
+     */
+    virtual ~DecimalFormat();
+
+    /**
+     * Clone this Format object polymorphically. The caller owns the
+     * result and should delete it when done.
+     *
+     * @return    a polymorphic copy of this DecimalFormat.
+     * @stable ICU 2.0
+     */
+    virtual Format* clone(void) const;
+
+    /**
+     * Return true if the given Format objects are semantically equal.
+     * Objects of different subclasses are considered unequal.
+     *
+     * @param other    the object to be compared with.
+     * @return         true if the given Format objects are semantically equal.
+     * @stable ICU 2.0
+     */
+    virtual UBool operator==(const Format& other) const;
+
+    /**
+     * Format a double or long number using base-10 representation.
+     *
+     * @param number    The value to be formatted.
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     * @param pos       On input: an alignment field, if desired.
+     *                  On output: the offsets of the alignment field.
+     * @return          Reference to 'appendTo' parameter.
+     * @stable ICU 2.0
+    */
+    virtual UnicodeString& format(double number,
+                                  UnicodeString& appendTo,
+                                  FieldPosition& pos) const;
+    /**
+     * Format a long number using base-10 representation.
+     *
+     * @param number    The value to be formatted.
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     * @param pos       On input: an alignment field, if desired.
+     *                  On output: the offsets of the alignment field.
+     * @return          Reference to 'appendTo' parameter.
+     * @stable ICU 2.0
+     */
+    virtual UnicodeString& format(int32_t number,
+                                  UnicodeString& appendTo,
+                                  FieldPosition& pos) const;
+    /**
+     * Format an int64 number using base-10 representation.
+     *
+     * @param number    The value to be formatted.
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     * @param pos       On input: an alignment field, if desired.
+     *                  On output: the offsets of the alignment field.
+     * @return          Reference to 'appendTo' parameter.
+     * @stable ICU 2.8
+     */
+    virtual UnicodeString& format(int64_t number,
+                                  UnicodeString& appendTo,
+                                  FieldPosition& pos) const;
+
+    /**
+     * Format a Formattable using base-10 representation.
+     *
+     * @param obj       The value to be formatted.
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     * @param pos       On input: an alignment field, if desired.
+     *                  On output: the offsets of the alignment field.
+     * @param status    Error code indicating success or failure.
+     * @return          Reference to 'appendTo' parameter.
+     * @stable ICU 2.0
+     */
+    virtual UnicodeString& format(const Formattable& obj,
+                                  UnicodeString& appendTo,
+                                  FieldPosition& pos,
+                                  UErrorCode& status) const;
+
+    /**
+     * Redeclared NumberFormat method.
+     * Formats an object to produce a string.
+     *
+     * @param obj       The object to format.
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     * @param status    Output parameter filled in with success or failure status.
+     * @return          Reference to 'appendTo' parameter.
+     * @stable ICU 2.0
+     */
+    UnicodeString& format(const Formattable& obj,
+                          UnicodeString& appendTo,
+                          UErrorCode& status) const;
+
+    /**
+     * Redeclared NumberFormat method.
+     * Format a double number.
+     *
+     * @param number    The value to be formatted.
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     * @return          Reference to 'appendTo' parameter.
+     * @stable ICU 2.0
+     */
+    UnicodeString& format(double number,
+                          UnicodeString& appendTo) const;
+
+    /**
+     * Redeclared NumberFormat method.
+     * Format a long number. These methods call the NumberFormat
+     * pure virtual format() methods with the default FieldPosition.
+     *
+     * @param number    The value to be formatted.
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     * @return          Reference to 'appendTo' parameter.
+     * @stable ICU 2.0
+     */
+    UnicodeString& format(int32_t number,
+                          UnicodeString& appendTo) const;
+
+    /**
+     * Redeclared NumberFormat method.
+     * Format an int64 number. These methods call the NumberFormat
+     * pure virtual format() methods with the default FieldPosition.
+     *
+     * @param number    The value to be formatted.
+     * @param appendTo  Output parameter to receive result.
+     *                  Result is appended to existing contents.
+     * @return          Reference to 'appendTo' parameter.
+     * @stable ICU 2.8
+     */
+    UnicodeString& format(int64_t number,
+                          UnicodeString& appendTo) const;
+   /**
+    * Parse the given string using this object's choices. The method
+    * does string comparisons to try to find an optimal match.
+    * If no object can be parsed, index is unchanged, and NULL is
+    * returned.  The result is returned as the most parsimonious
+    * type of Formattable that will accomodate all of the
+    * necessary precision.  For example, if the result is exactly 12,
+    * it will be returned as a long.  However, if it is 1.5, it will
+    * be returned as a double.
+    *
+    * @param text           The text to be parsed.
+    * @param result         Formattable to be set to the parse result.
+    *                       If parse fails, return contents are undefined.
+    * @param parsePosition  The position to start parsing at on input.
+    *                       On output, moved to after the last successfully
+    *                       parse character. On parse failure, does not change.
+    * @see Formattable
+    * @stable ICU 2.0
+    */
+    virtual void parse(const UnicodeString& text,
+                       Formattable& result,
+                       ParsePosition& parsePosition) const;
+
+    // Declare here again to get rid of function hiding problems.
+    /** 
+     * Parse the given string using this object's choices.
+     *
+     * @param text           The text to be parsed.
+     * @param result         Formattable to be set to the parse result.
+     * @param status    Output parameter filled in with success or failure status.
+     * @stable ICU 2.0
+     */
+    virtual void parse(const UnicodeString& text, 
+                       Formattable& result, 
+                       UErrorCode& status) const;
+
+    /**
+     * Parses text from the given string as a currency amount.  Unlike
+     * the parse() method, this method will attempt to parse a generic
+     * currency name, searching for a match of this object's locale's
+     * currency display names, or for a 3-letter ISO currency code.
+     * This method will fail if this format is not a currency format,
+     * that is, if it does not contain the currency pattern symbol
+     * (U+00A4) in its prefix or suffix.
+     *
+     * @param text the string to parse
+     * @param result output parameter to receive result. This will have
+     * its currency set to the parsed ISO currency code.
+     * @param pos input-output position; on input, the position within
+     * text to match; must have 0 <= pos.getIndex() < text.length();
+     * on output, the position after the last matched character. If
+     * the parse fails, the position in unchanged upon output.
+     * @return a reference to result
+     * @internal
+     */
+    virtual Formattable& parseCurrency(const UnicodeString& text,
+                                       Formattable& result,
+                                       ParsePosition& pos) const;
+
+    /**
+     * Returns the decimal format symbols, which is generally not changed
+     * by the programmer or user.
+     * @return desired DecimalFormatSymbols
+     * @see DecimalFormatSymbols
+     * @stable ICU 2.0
+     */
+    virtual const DecimalFormatSymbols* getDecimalFormatSymbols(void) const;
+
+    /**
+     * Sets the decimal format symbols, which is generally not changed
+     * by the programmer or user.
+     * @param symbolsToAdopt DecimalFormatSymbols to be adopted.
+     * @stable ICU 2.0
+     */
+    virtual void adoptDecimalFormatSymbols(DecimalFormatSymbols* symbolsToAdopt);
+
+    /**
+     * Sets the decimal format symbols, which is generally not changed
+     * by the programmer or user.
+     * @param symbols DecimalFormatSymbols.
+     * @stable ICU 2.0
+     */
+    virtual void setDecimalFormatSymbols(const DecimalFormatSymbols& symbols);
+
+
+    /**
+     * Get the positive prefix.
+     *
+     * @param result    Output param which will receive the positive prefix.
+     * @return          A reference to 'result'.
+     * Examples: +123, $123, sFr123
+     * @stable ICU 2.0
+     */
+    UnicodeString& getPositivePrefix(UnicodeString& result) const;
+
+    /**
+     * Set the positive prefix.
+     *
+     * @param newValue    the new value of the the positive prefix to be set.
+     * Examples: +123, $123, sFr123
+     * @stable ICU 2.0
+     */
+    virtual void setPositivePrefix(const UnicodeString& newValue);
+
+    /**
+     * Get the negative prefix.
+     *
+     * @param result    Output param which will receive the negative prefix.
+     * @return          A reference to 'result'.
+     * Examples: -123, ($123) (with negative suffix), sFr-123
+     * @stable ICU 2.0
+     */
+    UnicodeString& getNegativePrefix(UnicodeString& result) const;
+
+    /**
+     * Set the negative prefix.
+     *
+     * @param newValue    the new value of the the negative prefix to be set.
+     * Examples: -123, ($123) (with negative suffix), sFr-123
+     * @stable ICU 2.0
+     */
+    virtual void setNegativePrefix(const UnicodeString& newValue);
+
+    /**
+     * Get the positive suffix.
+     *
+     * @param result    Output param which will receive the positive suffix.
+     * @return          A reference to 'result'.
+     * Example: 123%
+     * @stable ICU 2.0
+     */
+    UnicodeString& getPositiveSuffix(UnicodeString& result) const;
+
+    /**
+     * Set the positive suffix.
+     *
+     * @param newValue    the new value of the positive suffix to be set.
+     * Example: 123%
+     * @stable ICU 2.0
+     */
+    virtual void setPositiveSuffix(const UnicodeString& newValue);
+
+    /**
+     * Get the negative suffix.
+     *
+     * @param result    Output param which will receive the negative suffix.
+     * @return          A reference to 'result'.
+     * Examples: -123%, ($123) (with positive suffixes)
+     * @stable ICU 2.0
+     */
+    UnicodeString& getNegativeSuffix(UnicodeString& result) const;
+
+    /**
+     * Set the negative suffix.
+     *
+     * @param newValue    the new value of the negative suffix to be set.
+     * Examples: 123%
+     * @stable ICU 2.0
+     */
+    virtual void setNegativeSuffix(const UnicodeString& newValue);
+
+    /**
+     * Get the multiplier for use in percent, permill, etc.
+     * For a percentage, set the suffixes to have "%" and the multiplier to be 100.
+     * (For Arabic, use arabic percent symbol).
+     * For a permill, set the suffixes to have "\\u2031" and the multiplier to be 1000.
+     *
+     * @return    the multiplier for use in percent, permill, etc.
+     * Examples: with 100, 1.23 -> "123", and "123" -> 1.23
+     * @stable ICU 2.0
+     */
+    int32_t getMultiplier(void) const;
+
+    /**
+     * Set the multiplier for use in percent, permill, etc.
+     * For a percentage, set the suffixes to have "%" and the multiplier to be 100.
+     * (For Arabic, use arabic percent symbol).
+     * For a permill, set the suffixes to have "\\u2031" and the multiplier to be 1000.
+     *
+     * @param newValue    the new value of the multiplier for use in percent, permill, etc.
+     * Examples: with 100, 1.23 -> "123", and "123" -> 1.23
+     * @stable ICU 2.0
+     */
+    virtual void setMultiplier(int32_t newValue);
+
+    /**
+     * Get the rounding increment.
+     * @return A positive rounding increment, or 0.0 if rounding
+     * is not in effect.
+     * @see #setRoundingIncrement
+     * @see #getRoundingMode
+     * @see #setRoundingMode
+     * @stable ICU 2.0
+     */
+    virtual double getRoundingIncrement(void) const;
+
+    /**
+     * Set the rounding increment.  This method also controls whether
+     * rounding is enabled.
+     * @param newValue A positive rounding increment, or 0.0 to disable rounding.
+     * Negative increments are equivalent to 0.0.
+     * @see #getRoundingIncrement
+     * @see #getRoundingMode
+     * @see #setRoundingMode
+     * @stable ICU 2.0
+     */
+    virtual void setRoundingIncrement(double newValue);
+
+    /**
+     * Get the rounding mode.
+     * @return A rounding mode
+     * @see #setRoundingIncrement
+     * @see #getRoundingIncrement
+     * @see #setRoundingMode
+     * @stable ICU 2.0
+     */
+    virtual ERoundingMode getRoundingMode(void) const;
+
+    /**
+     * Set the rounding mode.  This has no effect unless the rounding
+     * increment is greater than zero.
+     * @param roundingMode A rounding mode
+     * @see #setRoundingIncrement
+     * @see #getRoundingIncrement
+     * @see #getRoundingMode
+     * @stable ICU 2.0
+     */
+    virtual void setRoundingMode(ERoundingMode roundingMode);
+
+    /**
+     * Get the width to which the output of format() is padded.
+     * The width is counted in 16-bit code units.
+     * @return the format width, or zero if no padding is in effect
+     * @see #setFormatWidth
+     * @see #getPadCharacterString
+     * @see #setPadCharacter
+     * @see #getPadPosition
+     * @see #setPadPosition
+     * @stable ICU 2.0
+     */
+    virtual int32_t getFormatWidth(void) const;
+
+    /**
+     * Set the width to which the output of format() is padded.
+     * The width is counted in 16-bit code units.
+     * This method also controls whether padding is enabled.
+     * @param width the width to which to pad the result of
+     * format(), or zero to disable padding.  A negative
+     * width is equivalent to 0.
+     * @see #getFormatWidth
+     * @see #getPadCharacterString
+     * @see #setPadCharacter
+     * @see #getPadPosition
+     * @see #setPadPosition
+     * @stable ICU 2.0
+     */
+    virtual void setFormatWidth(int32_t width);
+
+    /**
+     * Get the pad character used to pad to the format width.  The
+     * default is ' '.
+     * @return a string containing the pad character. This will always
+     * have a length of one 32-bit code point.
+     * @see #setFormatWidth
+     * @see #getFormatWidth
+     * @see #setPadCharacter
+     * @see #getPadPosition
+     * @see #setPadPosition
+     * @stable ICU 2.0
+     */
+    virtual UnicodeString getPadCharacterString() const;
+
+    /**
+     * Set the character used to pad to the format width.  If padding
+     * is not enabled, then this will take effect if padding is later
+     * enabled.
+     * @param padChar a string containing the pad charcter. If the string
+     * has length 0, then the pad characer is set to ' '.  Otherwise
+     * padChar.char32At(0) will be used as the pad character.
+     * @see #setFormatWidth
+     * @see #getFormatWidth
+     * @see #getPadCharacterString
+     * @see #getPadPosition
+     * @see #setPadPosition
+     * @stable ICU 2.0
+     */
+    virtual void setPadCharacter(const UnicodeString &padChar);
+
+    /**
+     * Get the position at which padding will take place.  This is the location
+     * at which padding will be inserted if the result of format()
+     * is shorter than the format width.
+     * @return the pad position, one of kPadBeforePrefix,
+     * kPadAfterPrefix, kPadBeforeSuffix, or
+     * kPadAfterSuffix.
+     * @see #setFormatWidth
+     * @see #getFormatWidth
+     * @see #setPadCharacter
+     * @see #getPadCharacterString
+     * @see #setPadPosition
+     * @see #EPadPosition
+     * @stable ICU 2.0
+     */
+    virtual EPadPosition getPadPosition(void) const;
+
+    /**
+     * Set the position at which padding will take place.  This is the location
+     * at which padding will be inserted if the result of format()
+     * is shorter than the format width.  This has no effect unless padding is
+     * enabled.
+     * @param padPos the pad position, one of kPadBeforePrefix,
+     * kPadAfterPrefix, kPadBeforeSuffix, or
+     * kPadAfterSuffix.
+     * @see #setFormatWidth
+     * @see #getFormatWidth
+     * @see #setPadCharacter
+     * @see #getPadCharacterString
+     * @see #getPadPosition
+     * @see #EPadPosition
+     * @stable ICU 2.0
+     */
+    virtual void setPadPosition(EPadPosition padPos);
+
+    /**
+     * Return whether or not scientific notation is used.
+     * @return TRUE if this object formats and parses scientific notation
+     * @see #setScientificNotation
+     * @see #getMinimumExponentDigits
+     * @see #setMinimumExponentDigits
+     * @see #isExponentSignAlwaysShown
+     * @see #setExponentSignAlwaysShown
+     * @stable ICU 2.0
+     */
+    virtual UBool isScientificNotation(void);
+
+    /**
+     * Set whether or not scientific notation is used. When scientific notation
+     * is used, the effective maximum number of integer digits is <= 8.  If the
+     * maximum number of integer digits is set to more than 8, the effective
+     * maximum will be 1.  This allows this call to generate a 'default' scientific
+     * number format without additional changes.
+     * @param useScientific TRUE if this object formats and parses scientific
+     * notation
+     * @see #isScientificNotation
+     * @see #getMinimumExponentDigits
+     * @see #setMinimumExponentDigits
+     * @see #isExponentSignAlwaysShown
+     * @see #setExponentSignAlwaysShown
+     * @stable ICU 2.0
+     */
+    virtual void setScientificNotation(UBool useScientific);
+
+    /**
+     * Return the minimum exponent digits that will be shown.
+     * @return the minimum exponent digits that will be shown
+     * @see #setScientificNotation
+     * @see #isScientificNotation
+     * @see #setMinimumExponentDigits
+     * @see #isExponentSignAlwaysShown
+     * @see #setExponentSignAlwaysShown
+     * @stable ICU 2.0
+     */
+    virtual int8_t getMinimumExponentDigits(void) const;
+
+    /**
+     * Set the minimum exponent digits that will be shown.  This has no
+     * effect unless scientific notation is in use.
+     * @param minExpDig a value >= 1 indicating the fewest exponent digits
+     * that will be shown.  Values less than 1 will be treated as 1.
+     * @see #setScientificNotation
+     * @see #isScientificNotation
+     * @see #getMinimumExponentDigits
+     * @see #isExponentSignAlwaysShown
+     * @see #setExponentSignAlwaysShown
+     * @stable ICU 2.0
+     */
+    virtual void setMinimumExponentDigits(int8_t minExpDig);
+
+    /**
+     * Return whether the exponent sign is always shown.
+     * @return TRUE if the exponent is always prefixed with either the
+     * localized minus sign or the localized plus sign, false if only negative
+     * exponents are prefixed with the localized minus sign.
+     * @see #setScientificNotation
+     * @see #isScientificNotation
+     * @see #setMinimumExponentDigits
+     * @see #getMinimumExponentDigits
+     * @see #setExponentSignAlwaysShown
+     * @stable ICU 2.0
+     */
+    virtual UBool isExponentSignAlwaysShown(void);
+
+    /**
+     * Set whether the exponent sign is always shown.  This has no effect
+     * unless scientific notation is in use.
+     * @param expSignAlways TRUE if the exponent is always prefixed with either
+     * the localized minus sign or the localized plus sign, false if only
+     * negative exponents are prefixed with the localized minus sign.
+     * @see #setScientificNotation
+     * @see #isScientificNotation
+     * @see #setMinimumExponentDigits
+     * @see #getMinimumExponentDigits
+     * @see #isExponentSignAlwaysShown
+     * @stable ICU 2.0
+     */
+    virtual void setExponentSignAlwaysShown(UBool expSignAlways);
+
+    /**
+     * Return the grouping size. Grouping size is the number of digits between
+     * grouping separators in the integer portion of a number.  For example,
+     * in the number "123,456.78", the grouping size is 3.
+     *
+     * @return    the grouping size.
+     * @see setGroupingSize
+     * @see NumberFormat::isGroupingUsed
+     * @see DecimalFormatSymbols::getGroupingSeparator
+     * @stable ICU 2.0
+     */
+    int32_t getGroupingSize(void) const;
+
+    /**
+     * Set the grouping size. Grouping size is the number of digits between
+     * grouping separators in the integer portion of a number.  For example,
+     * in the number "123,456.78", the grouping size is 3.
+     *
+     * @param newValue    the new value of the grouping size.
+     * @see getGroupingSize
+     * @see NumberFormat::setGroupingUsed
+     * @see DecimalFormatSymbols::setGroupingSeparator
+     * @stable ICU 2.0
+     */
+    virtual void setGroupingSize(int32_t newValue);
+
+    /**
+     * Return the secondary grouping size. In some locales one
+     * grouping interval is used for the least significant integer
+     * digits (the primary grouping size), and another is used for all
+     * others (the secondary grouping size).  A formatter supporting a
+     * secondary grouping size will return a positive integer unequal
+     * to the primary grouping size returned by
+     * getGroupingSize().  For example, if the primary
+     * grouping size is 4, and the secondary grouping size is 2, then
+     * the number 123456789 formats as "1,23,45,6789", and the pattern
+     * appears as "#,##,###0".
+     * @return the secondary grouping size, or a value less than
+     * one if there is none
+     * @see setSecondaryGroupingSize
+     * @see NumberFormat::isGroupingUsed
+     * @see DecimalFormatSymbols::getGroupingSeparator
+     * @stable ICU 2.4
+     */
+    int32_t getSecondaryGroupingSize(void) const;
+
+    /**
+     * Set the secondary grouping size. If set to a value less than 1,
+     * then secondary grouping is turned off, and the primary grouping
+     * size is used for all intervals, not just the least significant.
+     *
+     * @param newValue    the new value of the secondary grouping size.
+     * @see getSecondaryGroupingSize
+     * @see NumberFormat#setGroupingUsed
+     * @see DecimalFormatSymbols::setGroupingSeparator
+     * @stable ICU 2.4
+     */
+    virtual void setSecondaryGroupingSize(int32_t newValue);
+
+    /**
+     * Allows you to get the behavior of the decimal separator with integers.
+     * (The decimal separator will always appear with decimals.)
+     *
+     * @return    TRUE if the decimal separator always appear with decimals.
+     * Example: Decimal ON: 12345 -> 12345.; OFF: 12345 -> 12345
+     * @stable ICU 2.0
+     */
+    UBool isDecimalSeparatorAlwaysShown(void) const;
+
+    /**
+     * Allows you to set the behavior of the decimal separator with integers.
+     * (The decimal separator will always appear with decimals.)
+     *
+     * @param newValue    set TRUE if the decimal separator will always appear with decimals.
+     * Example: Decimal ON: 12345 -> 12345.; OFF: 12345 -> 12345
+     * @stable ICU 2.0
+     */
+    virtual void setDecimalSeparatorAlwaysShown(UBool newValue);
+
+    /**
+     * Synthesizes a pattern string that represents the current state
+     * of this Format object.
+     *
+     * @param result    Output param which will receive the pattern.
+     *                  Previous contents are deleted.
+     * @return          A reference to 'result'.
+     * @see applyPattern
+     * @stable ICU 2.0
+     */
+    virtual UnicodeString& toPattern(UnicodeString& result) const;
+
+    /**
+     * Synthesizes a localized pattern string that represents the current
+     * state of this Format object.
+     *
+     * @param result    Output param which will receive the localized pattern.
+     *                  Previous contents are deleted.
+     * @return          A reference to 'result'.
+     * @see applyPattern
+     * @stable ICU 2.0
+     */
+    virtual UnicodeString& toLocalizedPattern(UnicodeString& result) const;
+ 
+    /**
+     * Apply the given pattern to this Format object.  A pattern is a
+     * short-hand specification for the various formatting properties.
+     * These properties can also be changed individually through the
+     * various setter methods.
+     * <P>
+     * There is no limit to integer digits are set
+     * by this routine, since that is the typical end-user desire;
+     * use setMaximumInteger if you want to set a real value.
+     * For negative numbers, use a second pattern, separated by a semicolon
+     * <pre>
+     * .      Example "#,#00.0#" -> 1,234.56
+     * </pre>
+     * This means a minimum of 2 integer digits, 1 fraction digit, and
+     * a maximum of 2 fraction digits.
+     * <pre>
+     * .      Example: "#,#00.0#;(#,#00.0#)" for negatives in parantheses.
+     * </pre>
+     * In negative patterns, the minimum and maximum counts are ignored;
+     * these are presumed to be set in the positive pattern.
+     *
+     * @param pattern    The pattern to be applied.
+     * @param parseError Struct to recieve information on position 
+     *                   of error if an error is encountered
+     * @param status     Output param set to success/failure code on
+     *                   exit. If the pattern is invalid, this will be
+     *                   set to a failure result.
+     * @stable ICU 2.0
+     */
+    virtual void applyPattern(const UnicodeString& pattern,
+                             UParseError& parseError,
+                             UErrorCode& status);
+    /**
+     * Sets the pattern.
+     * @param pattern   The pattern to be applied.
+     * @param status    Output param set to success/failure code on
+     *                  exit. If the pattern is invalid, this will be
+     *                  set to a failure result.
+     * @stable ICU 2.0
+     */  
+    virtual void applyPattern(const UnicodeString& pattern,
+                             UErrorCode& status);
+
+    /**
+     * Apply the given pattern to this Format object.  The pattern
+     * is assumed to be in a localized notation. A pattern is a
+     * short-hand specification for the various formatting properties.
+     * These properties can also be changed individually through the
+     * various setter methods.
+     * <P>
+     * There is no limit to integer digits are set
+     * by this routine, since that is the typical end-user desire;
+     * use setMaximumInteger if you want to set a real value.
+     * For negative numbers, use a second pattern, separated by a semicolon
+     * <pre>
+     * .      Example "#,#00.0#" -> 1,234.56
+     * </pre>
+     * This means a minimum of 2 integer digits, 1 fraction digit, and
+     * a maximum of 2 fraction digits.
+     *
+     * Example: "#,#00.0#;(#,#00.0#)" for negatives in parantheses.
+     *
+     * In negative patterns, the minimum and maximum counts are ignored;
+     * these are presumed to be set in the positive pattern.
+     *
+     * @param pattern   The localized pattern to be applied.
+     * @param parseError Struct to recieve information on position 
+     *                   of error if an error is encountered
+     * @param status    Output param set to success/failure code on
+     *                  exit. If the pattern is invalid, this will be
+     *                  set to a failure result.
+     * @stable ICU 2.0
+     */
+    virtual void applyLocalizedPattern(const UnicodeString& pattern,
+                                       UParseError& parseError,
+                                       UErrorCode& status);
+
+    /**
+     * Apply the given pattern to this Format object.
+     *
+     * @param pattern   The localized pattern to be applied.
+     * @param status    Output param set to success/failure code on
+     *                  exit. If the pattern is invalid, this will be
+     *                  set to a failure result.
+     * @stable ICU 2.0
+     */
+    virtual void applyLocalizedPattern(const UnicodeString& pattern,
+                                       UErrorCode& status);
+
+
+    /**
+     * Sets the maximum number of digits allowed in the integer portion of a
+     * number. This override limits the integer digit count to 309.
+     *
+     * @param newValue    the new value of the maximum number of digits 
+     *                      allowed in the integer portion of a number.
+     * @see NumberFormat#setMaximumIntegerDigits
+     * @stable ICU 2.0
+     */
+    virtual void setMaximumIntegerDigits(int32_t newValue);
+
+    /**
+     * Sets the minimum number of digits allowed in the integer portion of a
+     * number. This override limits the integer digit count to 309.
+     * 
+     * @param newValue    the new value of the minimum number of digits 
+     *                      allowed in the integer portion of a number.
+     * @see NumberFormat#setMinimumIntegerDigits
+     * @stable ICU 2.0
+     */
+    virtual void setMinimumIntegerDigits(int32_t newValue);
+
+    /**
+     * Sets the maximum number of digits allowed in the fraction portion of a
+     * number. This override limits the fraction digit count to 340.
+     *
+     * @param newValue    the new value of the maximum number of digits 
+     *                    allowed in the fraction portion of a number.
+     * @see NumberFormat#setMaximumFractionDigits
+     * @stable ICU 2.0
+     */
+    virtual void setMaximumFractionDigits(int32_t newValue);
+
+    /**
+     * Sets the minimum number of digits allowed in the fraction portion of a
+     * number. This override limits the fraction digit count to 340.
+     *
+     * @param newValue    the new value of the minimum number of digits 
+     *                    allowed in the fraction portion of a number.
+     * @see NumberFormat#setMinimumFractionDigits
+     * @stable ICU 2.0
+     */
+    virtual void setMinimumFractionDigits(int32_t newValue);
+
+    /**
+     * Returns the minimum number of significant digits that will be
+     * displayed. This value has no effect unless areSignificantDigitsUsed()
+     * returns true.
+     * @return the fewest significant digits that will be shown
+     * @stable ICU 3.0
+     */
+    int32_t getMinimumSignificantDigits() const;
+
+    /**
+     * Returns the maximum number of significant digits that will be
+     * displayed. This value has no effect unless areSignificantDigitsUsed()
+     * returns true.
+     * @return the most significant digits that will be shown
+     * @stable ICU 3.0
+     */
+    int32_t getMaximumSignificantDigits() const;
+
+    /**
+     * Sets the minimum number of significant digits that will be
+     * displayed.  If <code>min</code> is less than one then it is set
+     * to one.  If the maximum significant digits count is less than
+     * <code>min</code>, then it is set to <code>min</code>. This
+     * value has no effect unless areSignificantDigits() returns true.
+     * @param min the fewest significant digits to be shown 
+     * @stable ICU 3.0
+     */
+    void setMinimumSignificantDigits(int32_t min);
+
+    /**
+     * Sets the maximum number of significant digits that will be
+     * displayed.  If <code>max</code> is less than one then it is set
+     * to one.  If the minimum significant digits count is greater
+     * than <code>max</code>, then it is set to <code>max</code>.
+     * This value has no effect unless areSignificantDigits() returns
+     * true.
+     * @param max the most significant digits to be shown 
+     * @stable ICU 3.0
+     */
+    void setMaximumSignificantDigits(int32_t max);
+
+    /**
+     * Returns true if significant digits are in use, or false if
+     * integer and fraction digit counts are in use.
+     * @return true if significant digits are in use
+     * @stable ICU 3.0
+     */
+    UBool areSignificantDigitsUsed() const;
+
+    /**
+     * Sets whether significant digits are in use, or integer and
+     * fraction digit counts are in use.
+     * @param useSignificantDigits true to use significant digits, or
+     * false to use integer and fraction digit counts
+     * @stable ICU 3.0
+     */
+    void setSignificantDigitsUsed(UBool useSignificantDigits);
+
+ public:
+    /**
+     * Sets the currency used to display currency
+     * amounts.  This takes effect immediately, if this format is a
+     * currency format.  If this format is not a currency format, then
+     * the currency is used if and when this object becomes a
+     * currency format through the application of a new pattern.
+     * @param theCurrency a 3-letter ISO code indicating new currency
+     * to use.  It need not be null-terminated.  May be the empty
+     * string or NULL to indicate no currency.
+     * @param ec input-output error code
+     * @stable ICU 3.0
+     */
+    virtual void setCurrency(const UChar* theCurrency, UErrorCode& ec);
+
+    /**
+     * Sets the currency used to display currency amounts.  See
+     * setCurrency(const UChar*, UErrorCode&).
+     * @deprecated ICU 3.0. Use setCurrency(const UChar*, UErrorCode&).
+     */
+    virtual void setCurrency(const UChar* theCurrency);
+
+    /**
+     * The resource tags we use to retrieve decimal format data from
+     * locale resource bundles.
+     * @deprecated ICU 3.4. This string has no public purpose. Please don't use it.
+     */
+    static const char fgNumberPatterns[];
+
+public:
+
+    /**
+     * Return the class ID for this class.  This is useful only for
+     * comparing to a return value from getDynamicClassID().  For example:
+     * <pre>
+     * .      Base* polymorphic_pointer = createPolymorphicObject();
+     * .      if (polymorphic_pointer->getDynamicClassID() ==
+     * .          Derived::getStaticClassID()) ...
+     * </pre>
+     * @return          The class ID for all objects of this class.
+     * @stable ICU 2.0
+     */
+    static UClassID U_EXPORT2 getStaticClassID(void);
+
+    /**
+     * Returns a unique class ID POLYMORPHICALLY.  Pure virtual override.
+     * This method is to implement a simple version of RTTI, since not all
+     * C++ compilers support genuine RTTI.  Polymorphic operator==() and
+     * clone() methods call this method.
+     *
+     * @return          The class ID for this object. All objects of a
+     *                  given class have the same class ID.  Objects of
+     *                  other classes have different class IDs.
+     * @stable ICU 2.0
+     */
+    virtual UClassID getDynamicClassID(void) const;
+
+private:
+    DecimalFormat(); // default constructor not implemented
+
+    int32_t precision(UBool isIntegral) const;
+
+    /**
+     * Do real work of constructing a new DecimalFormat.
+     */
+    void construct(UErrorCode&               status,
+                   UParseError&             parseErr,
+                   const UnicodeString*     pattern = 0,
+                   DecimalFormatSymbols*    symbolsToAdopt = 0
+                   );
+
+    /**
+     * Does the real work of generating a pattern.
+     *
+     * @param result     Output param which will receive the pattern.
+     *                   Previous contents are deleted.
+     * @param localized  TRUE return localized pattern.
+     * @return           A reference to 'result'.
+     */
+    UnicodeString& toPattern(UnicodeString& result, UBool localized) const;
+
+    /**
+     * Does the real work of applying a pattern.
+     * @param pattern    The pattern to be applied.
+     * @param localized  If true, the pattern is localized; else false.
+     * @param parseError Struct to recieve information on position 
+     *                   of error if an error is encountered
+     * @param status     Output param set to success/failure code on
+     *                   exit. If the pattern is invalid, this will be
+     *                   set to a failure result.
+     */
+    void applyPattern(const UnicodeString& pattern,
+                            UBool localized,
+                            UParseError& parseError,
+                            UErrorCode& status);
+    /**
+     * Do the work of formatting a number, either a double or a long.
+     *
+     * @param appendTo       Output parameter to receive result.
+     *                       Result is appended to existing contents.
+     * @param fieldPosition  On input: an alignment field, if desired.
+     *                       On output: the offsets of the alignment field.
+     * @param digits         the digits to be formatted.
+     * @param isInteger      if TRUE format the digits as Integer.
+     * @return               Reference to 'appendTo' parameter.
+     */
+    UnicodeString& subformat(UnicodeString& appendTo,
+                             FieldPosition& fieldPosition,
+                             DigitList& digits,
+                             UBool         isInteger) const;
+
+    void parse(const UnicodeString& text,
+               Formattable& result,
+               ParsePosition& pos,
+               UBool parseCurrency) const;
+
+    enum {
+        fgStatusInfinite,
+        fgStatusLength      // Leave last in list.
+    } StatusFlags;
+
+    UBool subparse(const UnicodeString& text, ParsePosition& parsePosition,
+                   DigitList& digits, UBool* status,
+                   UChar* currency) const;
+
+    int32_t skipPadding(const UnicodeString& text, int32_t position) const;
+
+    int32_t compareAffix(const UnicodeString& input,
+                         int32_t pos,
+                         UBool isNegative,
+                         UBool isPrefix,
+                         UChar* currency) const;
+    
+    static int32_t compareSimpleAffix(const UnicodeString& affix,
+                                      const UnicodeString& input,
+                                      int32_t pos,
+                                      UBool strict);
+    
+    static int32_t skipRuleWhiteSpace(const UnicodeString& text, int32_t pos);
+    
+    static int32_t skipUWhiteSpace(const UnicodeString& text, int32_t pos);
+    
+    int32_t compareComplexAffix(const UnicodeString& affixPat,
+                                const UnicodeString& input,
+                                int32_t pos,
+                                UChar* currency) const;
+
+    static int32_t match(const UnicodeString& text, int32_t pos, UChar32 ch);
+
+    static int32_t match(const UnicodeString& text, int32_t pos, const UnicodeString& str);
+	
+    static UBool matchSymbol(const UnicodeString &text, int32_t position, int32_t length, const UnicodeString &symbol,
+                             UnicodeSet *sset, UChar32 schar);
+	
+    /**
+     * Get a decimal format symbol.
+     * Returns a const reference to the symbol string.
+     * @internal
+     */
+    inline const UnicodeString &getConstSymbol(DecimalFormatSymbols::ENumberFormatSymbol symbol) const;
+
+    int32_t appendAffix(UnicodeString& buf, double number,
+                        UBool isNegative, UBool isPrefix) const;
+
+    /**
+     * Append an affix to the given UnicodeString, using quotes if
+     * there are special characters.  Single quotes themselves must be
+     * escaped in either case.
+     */
+    void appendAffixPattern(UnicodeString& appendTo, const UnicodeString& affix, 
+                            UBool localized) const;
+
+    void appendAffixPattern(UnicodeString& appendTo,
+                            const UnicodeString* affixPattern,
+                            const UnicodeString& expAffix, UBool localized) const;
+
+    void expandAffix(const UnicodeString& pattern,
+                     UnicodeString& affix,
+                     double number,
+                     UBool doFormat) const;
+
+    void expandAffixes();
+    
+    static double round(double a, ERoundingMode mode, UBool isNegative);
+
+    void addPadding(UnicodeString& appendTo,
+                    FieldPosition& fieldPosition,
+                    int32_t prefixLen, int32_t suffixLen) const;
+
+    UBool isGroupingPosition(int32_t pos) const;
+
+    void setCurrencyForSymbols();
+
+    /**
+     * Constants.
+     */
+    //static const int8_t fgMaxDigit; // The largest digit, in this case 9
+
+    /*transient*/ //DigitList* fDigitList;
+
+    UnicodeString           fPositivePrefix;
+    UnicodeString           fPositiveSuffix;
+    UnicodeString           fNegativePrefix;
+    UnicodeString           fNegativeSuffix;
+    UnicodeString*          fPosPrefixPattern;
+    UnicodeString*          fPosSuffixPattern;
+    UnicodeString*          fNegPrefixPattern;
+    UnicodeString*          fNegSuffixPattern;
+
+    /**
+     * Formatter for ChoiceFormat-based currency names.  If this field
+     * is not null, then delegate to it to format currency symbols.
+     * @since ICU 2.6
+     */
+    ChoiceFormat*           fCurrencyChoice;
+
+    int32_t                 fMultiplier;
+    int32_t                 fGroupingSize;
+    int32_t                 fGroupingSize2;
+    UBool                   fDecimalSeparatorAlwaysShown;
+    /*transient*/ UBool     fIsCurrencyFormat;
+    DecimalFormatSymbols*   fSymbols;
+
+    UBool                   fUseSignificantDigits;
+    int32_t                 fMinSignificantDigits;
+    int32_t                 fMaxSignificantDigits;
+
+    UBool                   fUseExponentialNotation;
+    int8_t                  fMinExponentDigits;
+    UBool                   fExponentSignAlwaysShown;
+
+    /* If fRoundingIncrement is NULL, there is no rounding.  Otherwise, round to
+     * fRoundingIncrement.getDouble().  Since this operation may be expensive,
+     * we cache the result in fRoundingDouble.  All methods that update
+     * fRoundingIncrement also update fRoundingDouble. */
+    DigitList*              fRoundingIncrement;
+    /*transient*/ double    fRoundingDouble;
+    ERoundingMode           fRoundingMode;
+
+    UChar32                 fPad;
+    int32_t                 fFormatWidth;
+    EPadPosition            fPadPosition;
+
+protected:
+
+    /**
+     * Returns the currency in effect for this formatter.  Subclasses
+     * should override this method as needed.  Unlike getCurrency(),
+     * this method should never return "".
+     * @result output parameter for null-terminated result, which must
+     * have a capacity of at least 4
+     * @internal
+     */
+    virtual void getEffectiveCurrency(UChar* result, UErrorCode& ec) const;
+
+  /** number of integer digits 
+   * @stable ICU 2.4
+   */  
+    static const int32_t  kDoubleIntegerDigits;
+  /** number of fraction digits 
+   * @stable ICU 2.4
+   */  
+    static const int32_t  kDoubleFractionDigits;
+
+    /**
+     * When someone turns on scientific mode, we assume that more than this
+     * number of digits is due to flipping from some other mode that didn't
+     * restrict the maximum, and so we force 1 integer digit.  We don't bother
+     * to track and see if someone is using exponential notation with more than
+     * this number, it wouldn't make sense anyway, and this is just to make sure
+     * that someone turning on scientific mode with default settings doesn't
+     * end up with lots of zeroes.
+     * @stable ICU 2.8
+     */
+    static const int32_t  kMaxScientificIntegerDigits;
+};
+
+inline UnicodeString&
+DecimalFormat::format(const Formattable& obj,
+                      UnicodeString& appendTo,
+                      UErrorCode& status) const {
+    // Don't use Format:: - use immediate base class only,
+    // in case immediate base modifies behavior later.
+    return NumberFormat::format(obj, appendTo, status);
+}
+
+inline UnicodeString&
+DecimalFormat::format(double number,
+                      UnicodeString& appendTo) const {
+    FieldPosition pos(0);
+    return format(number, appendTo, pos);
+}
+
+inline UnicodeString&
+DecimalFormat::format(int32_t number,
+                      UnicodeString& appendTo) const {
+    FieldPosition pos(0);
+    return format((int64_t)number, appendTo, pos);
+}
+
+inline const UnicodeString &
+DecimalFormat::getConstSymbol(DecimalFormatSymbols::ENumberFormatSymbol symbol) const {
+    return fSymbols->getConstSymbol(symbol);
+}
+
+U_NAMESPACE_END
+
+#endif /* #if !UCONFIG_NO_FORMATTING */
+
+#endif // _DECIMFMT
+//eof

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/docmain.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/docmain.h b/src/apps/couch_collate/platform/osx/icu/unicode/docmain.h
new file mode 100644
index 0000000..973ebea
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/docmain.h
@@ -0,0 +1,202 @@
+/********************************************************************
+ * COPYRIGHT: 
+ * Copyright (c) 1997-2007, International Business Machines Corporation and
+ * others. All Rights Reserved.
+ *
+ *  FILE NAME: DOCMAIN.h
+ *
+ *   Date          Name        Description
+ *   12/11/2000    Ram        Creation.
+ */
+
+/* This file contains documentation for Doxygen and doesnot have
+ * any significance with respect to C or C++ API
+ */
+
+/*! \mainpage
+ *
+ * \section API API Reference Usage
+ * 
+ * <h3>C++ Programmers:</h3>
+ * <p>Use <a href="hierarchy.html">Class Hierarchy</a> or <a href="classes.html"> Alphabetical List </a>
+ * or <a href="annotated.html"> Compound List</a>
+ * to find the class you are interested in. For example, to find BreakIterator,
+ * you can go to the <a href="classes.html"> Alphabetical List</a>, then click on
+ * "BreakIterator". Once you are at the class, you will find an inheritance
+ * chart, a list of the public members, a detailed description of the class,
+ * then detailed member descriptions.</p>
+ * 
+ * <h3>C Programmers:</h3>
+ * <p>Use <a href="#Module">Module List</a> or <a href="globals.html">File Members</a>
+ * to find a list of all the functions and constants.
+ * For example, to find BreakIterator functions you would click on
+ * <a href="files.html"> File List</a>,
+ * then find "ubrk.h" and click on it. You will find descriptions of Defines,
+ * Typedefs, Enumerations, and Functions, with detailed descriptions below.
+ * If you want to find a specific function, such as ubrk_next(), then click
+ * first on <a href="globals.html"> File Members</a>, then use your browser
+ * Find dialog to search for "ubrk_next()".</p>
+ *
+ *
+ * <h3>API References for Previous Releases</h3>
+ * <p>The API References for each release of ICU are also available as
+ * a zip file from the ICU 
+ * <a href="http://icu-project.org/download/">download page</a>.</p>
+ *
+ * <hr>
+ *
+ * <h2>Architecture (User's Guide)</h2>
+ * <ul>
+ *   <li><a href="http://icu-project.org/userguide/">Introduction</a></li>
+ *   <li><a href="http://icu-project.org/userguide/i18n.html">Internationalization</a></li>
+ *   <li><a href="http://icu-project.org/userguide/design.html">Locale Model</a></li>
+ *   <li><a href="http://icu-project.org/userguide/design.html">Multithreading</a></li>
+ *   <li><a href="http://icu-project.org/userguide/conversion.html">Conversion</a></li>
+ *   <li><a href="http://icu-project.org/userguide/design.html">Error Handling</a></li>
+ * </ul>
+ *
+ * <hr>
+ *\htmlonly <h2><a NAME="Module">Module List</a></h2> \endhtmlonly
+ * <table border="1" cols="3" align="center">
+ *   <tr>
+ *     <td><strong>Module Name</strong></td>
+ *     <td><strong>C</strong></td>
+ *     <td><strong>C++</strong></td>
+ *   </tr>
+ *   <tr>
+ *     <td>Basic Types and Constants</td>
+ *     <td>utypes.h</td>
+ *     <td>utypes.h</td>
+ *   </tr>
+ *   <tr>
+ *     <td>Strings and Character Iteration</td>
+ *     <td>ustring.h, utf.h</td>
+ *     <td>UnicodeString, CharacterIterator</td>
+ *   </tr>
+ *   <tr>
+ *     <td>Unicode Character<br>Properties and Names</td>
+ *     <td>uchar.h</td>
+ *     <td>uchar.h C API</td>
+ *   </tr>
+ *   <tr>
+ *     <td>Codepage Conversion</td>
+ *     <td>ucnv.h</td>
+ *     <td>ucnv.h C API</td>
+ *   </tr>
+ *   <tr>
+ *     <td>Unicode Text Compression</td>
+ *     <td>ucnv.h <br> (encoding name "SCSU" or "BOCU-1")</td>
+ *     <td>ucnv.h C API</td>
+ *   </tr>
+ *   <tr>
+ *     <td>Locales </td>
+ *     <td>uloc.h</a></td>
+ *     <td>Locale</td>
+ *   </tr>
+ *   <tr>
+ *     <td>Resource Bundles</td>
+ *     <td>ures.h</td>
+ *     <td>ResourceBundle</td>
+ *   </tr>
+ *   <tr>
+ *     <td>Normalization</td>
+ *     <td>unorm.h</td>
+ *     <td>Normalizer</td>
+ *   </tr>
+ *   <tr>
+ *     <td>Calendars</td>
+ *     <td>ucal.h</td>
+ *     <td>Calendar</td>
+ *   </tr>
+ *   <tr>
+ *     <td>Date and Time Formatting</td>
+ *     <td>udat.h</td>
+ *     <td>DateFormat</td>
+ *   </tr>
+ *   <tr>
+ *     <td>Message Formatting</td>
+ *     <td>umsg.h</td>
+ *     <td>MessageFormat</td>
+ *   </tr>
+ *   <tr>
+ *     <td>Number Formatting</td>
+ *     <td>unum.h</td>
+ *     <td>NumberFormat</td>
+ *   </tr>
+ *   <tr>
+ *     <td>Number Spellout <br> (Rule Based Number Formatting)</td>
+ *     <td>unum.h <br> (use UNUM_SPELLOUT)</td>
+ *     <td>RuleBasedNumberFormat</td>
+ *   </tr>
+ *   <tr>
+ *     <td>Text Transformation <br> (Transliteration)</td>
+ *     <td>utrans.h</td>
+ *     <td>Transliterator</td>
+ *   </tr>
+ *   <tr>
+ *     <td>Bidirectional Algorithm</td>
+ *     <td>ubidi.h</td>
+ *     <td>ubidi.h C API</td>
+ *   </tr>
+ *   <tr>
+ *     <td>Arabic Shaping</td>
+ *     <td>ushape.h</td>
+ *     <td>ushape.h C API</td>
+ *   </tr>
+ *   <tr>
+ *     <td>Collation</td>
+ *     <td>ucol.h</td>
+ *     <td>Collator</td>
+ *   </tr>
+ *   <tr>
+ *     <td>String Searching</td>
+ *     <td>usearch.h</td>
+ *     <td>StringSearch</td>
+ *   </tr>
+ *   <tr>
+ *     <td>Text Boundary Analysis <br> (Break Iteration)</td>
+ *     <td>ubrk.h</td>
+ *     <td>BreakIterator</td>
+ *   </tr>
+ *   <tr>
+ *     <td>Unicode Set</td>
+ *     <td>uset.h</td>
+ *     <td>UnicodeSet</td>
+ *   </tr>
+ *   <tr>
+ *     <td>Regular Expressions</td>
+ *     <td>uregex.h</td>
+ *     <td>RegexPattern, RegexMatcher</td>
+ *   </tr>
+ *   <tr>
+ *     <td>StringPrep</td>
+ *     <td>usprep.h</td>
+ *     <td>usprep.h C API</td>
+ *   </tr>
+ *   <tr>
+ *     <td>International Domain Names in Applications</td>
+ *     <td>uidna.h</td>
+ *     <td>uidna.h C API</td>
+ *   </tr>
+ *   <tr>
+ *     <td>Universal Time Scale</td>
+ *     <td>utmscale.h</td>
+ *     <td>utmscale.h C API</td>
+ *   </tr>
+ *   <tr>
+ *     <td>Basic Layout Engine Types and Constants</td>
+ *     <td>(no C API)</td>
+ *     <td>LETypes.h</td>
+ *   </tr>
+ *   <tr>
+ *     <td>Complex Text Layout</td>
+ *     <td>(no C API)</td>
+ *     <td>LayoutEngine, ParagraphLayout</td>
+ *   </tr>
+ *   <tr>
+ *     <td>ICU I/O</td>
+ *     <td>ustdio.h</td>
+ *     <td>ustream.h</td>
+ *   </tr>
+ * </table>
+ */


[69/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/ucnv.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/ucnv.h b/src/apps/couch_collate/platform/osx/icu/unicode/ucnv.h
new file mode 100644
index 0000000..bfd7198
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/ucnv.h
@@ -0,0 +1,1967 @@
+/*
+**********************************************************************
+*   Copyright (C) 1999-2008, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+**********************************************************************
+ *  ucnv.h:
+ *  External APIs for the ICU's codeset conversion library
+ *  Bertrand A. Damiba
+ *
+ * Modification History:
+ *
+ *   Date        Name        Description
+ *   04/04/99    helena      Fixed internal header inclusion.
+ *   05/11/00    helena      Added setFallback and usesFallback APIs.
+ *   06/29/2000  helena      Major rewrite of the callback APIs.
+ *   12/07/2000  srl         Update of documentation
+ */
+
+/**
+ * \file
+ * \brief C API: Character conversion 
+ *
+ * <h2>Character Conversion C API</h2>
+ *
+ * <p>This API is used to convert codepage or character encoded data to and
+ * from UTF-16. You can open a converter with {@link ucnv_open() }. With that
+ * converter, you can get its properties, set options, convert your data and
+ * close the converter.</p>
+ *
+ * <p>Since many software programs recogize different converter names for
+ * different types of converters, there are other functions in this API to
+ * iterate over the converter aliases. The functions {@link ucnv_getAvailableName() },
+ * {@link ucnv_getAlias() } and {@link ucnv_getStandardName() } are some of the
+ * more frequently used alias functions to get this information.</p>
+ *
+ * <p>When a converter encounters an illegal, irregular, invalid or unmappable character
+ * its default behavior is to use a substitution character to replace the
+ * bad byte sequence. This behavior can be changed by using {@link ucnv_setFromUCallBack() }
+ * or {@link ucnv_setToUCallBack() } on the converter. The header ucnv_err.h defines
+ * many other callback actions that can be used instead of a character substitution.</p>
+ *
+ * <p>More information about this API can be found in our 
+ * <a href="http://icu-project.org/userguide/conversion.html">User's
+ * Guide</a>.</p>
+ */
+
+#ifndef UCNV_H
+#define UCNV_H
+
+#include "unicode/ucnv_err.h"
+#include "unicode/uenum.h"
+
+#ifndef __USET_H__
+
+/**
+ * USet is the C API type for Unicode sets.
+ * It is forward-declared here to avoid including the header file if related
+ * conversion APIs are not used.
+ * See unicode/uset.h
+ *
+ * @see ucnv_getUnicodeSet
+ * @stable ICU 2.6
+ */
+struct USet;
+/** @stable ICU 2.6 */
+typedef struct USet USet;
+
+#endif
+
+#if !UCONFIG_NO_CONVERSION
+
+U_CDECL_BEGIN
+
+/** Maximum length of a converter name including the terminating NULL @stable ICU 2.0 */
+#define UCNV_MAX_CONVERTER_NAME_LENGTH 60
+/** Maximum length of a converter name including path and terminating NULL @stable ICU 2.0 */
+#define UCNV_MAX_FULL_FILE_NAME_LENGTH (600+UCNV_MAX_CONVERTER_NAME_LENGTH)
+
+/** Shift in for EBDCDIC_STATEFUL and iso2022 states @stable ICU 2.0 */
+#define  UCNV_SI 0x0F
+/** Shift out for EBDCDIC_STATEFUL and iso2022 states @stable ICU 2.0 */
+#define  UCNV_SO 0x0E
+
+/**
+ * Enum for specifying basic types of converters
+ * @see ucnv_getType
+ * @stable ICU 2.0
+ */
+typedef enum {
+    UCNV_UNSUPPORTED_CONVERTER = -1,
+    UCNV_SBCS = 0,
+    UCNV_DBCS = 1,
+    UCNV_MBCS = 2,
+    UCNV_LATIN_1 = 3,
+    UCNV_UTF8 = 4,
+    UCNV_UTF16_BigEndian = 5,
+    UCNV_UTF16_LittleEndian = 6,
+    UCNV_UTF32_BigEndian = 7,
+    UCNV_UTF32_LittleEndian = 8,
+    UCNV_EBCDIC_STATEFUL = 9,
+    UCNV_ISO_2022 = 10,
+
+    UCNV_LMBCS_1 = 11,
+    UCNV_LMBCS_2, 
+    UCNV_LMBCS_3,
+    UCNV_LMBCS_4,
+    UCNV_LMBCS_5,
+    UCNV_LMBCS_6,
+    UCNV_LMBCS_8,
+    UCNV_LMBCS_11,
+    UCNV_LMBCS_16,
+    UCNV_LMBCS_17,
+    UCNV_LMBCS_18,
+    UCNV_LMBCS_19,
+    UCNV_LMBCS_LAST = UCNV_LMBCS_19,
+    UCNV_HZ,
+    UCNV_SCSU,
+    UCNV_ISCII,
+    UCNV_US_ASCII,
+    UCNV_UTF7,
+    UCNV_BOCU1,
+    UCNV_UTF16,
+    UCNV_UTF32,
+    UCNV_CESU8,
+    UCNV_IMAP_MAILBOX,
+
+    /* Number of converter types for which we have conversion routines. */
+    UCNV_NUMBER_OF_SUPPORTED_CONVERTER_TYPES
+
+} UConverterType;
+
+/**
+ * Enum for specifying which platform a converter ID refers to.
+ * The use of platform/CCSID is not recommended. See ucnv_openCCSID().
+ *
+ * @see ucnv_getPlatform
+ * @see ucnv_openCCSID
+ * @see ucnv_getCCSID
+ * @stable ICU 2.0
+ */
+typedef enum {
+    UCNV_UNKNOWN = -1,
+    UCNV_IBM = 0
+} UConverterPlatform;
+
+/**
+ * Function pointer for error callback in the codepage to unicode direction.
+ * Called when an error has occured in conversion to unicode, or on open/close of the callback (see reason).
+ * @param context Pointer to the callback's private data
+ * @param args Information about the conversion in progress
+ * @param codeUnits Points to 'length' bytes of the concerned codepage sequence
+ * @param length Size (in bytes) of the concerned codepage sequence
+ * @param reason Defines the reason the callback was invoked
+ * @param pErrorCode    ICU error code in/out parameter.
+ *                      For converter callback functions, set to a conversion error
+ *                      before the call, and the callback may reset it to U_ZERO_ERROR.
+ * @see ucnv_setToUCallBack
+ * @see UConverterToUnicodeArgs
+ * @stable ICU 2.0
+ */
+typedef void (U_EXPORT2 *UConverterToUCallback) (
+                  const void* context,
+                  UConverterToUnicodeArgs *args,
+                  const char *codeUnits,
+                  int32_t length,
+                  UConverterCallbackReason reason,
+                  UErrorCode *pErrorCode);
+
+/**
+ * Function pointer for error callback in the unicode to codepage direction.
+ * Called when an error has occured in conversion from unicode, or on open/close of the callback (see reason).
+ * @param context Pointer to the callback's private data
+ * @param args Information about the conversion in progress
+ * @param codeUnits Points to 'length' UChars of the concerned Unicode sequence
+ * @param length Size (in bytes) of the concerned codepage sequence
+ * @param codePoint Single UChar32 (UTF-32) containing the concerend Unicode codepoint.
+ * @param reason Defines the reason the callback was invoked
+ * @param pErrorCode    ICU error code in/out parameter.
+ *                      For converter callback functions, set to a conversion error
+ *                      before the call, and the callback may reset it to U_ZERO_ERROR.
+ * @see ucnv_setFromUCallBack
+ * @stable ICU 2.0
+ */
+typedef void (U_EXPORT2 *UConverterFromUCallback) (
+                    const void* context,
+                    UConverterFromUnicodeArgs *args,
+                    const UChar* codeUnits,
+                    int32_t length,
+                    UChar32 codePoint,
+                    UConverterCallbackReason reason,
+                    UErrorCode *pErrorCode);
+
+U_CDECL_END
+
+/**
+ * Character that separates converter names from options and options from each other.
+ * @see ucnv_open
+ * @stable ICU 2.0
+ */
+#define UCNV_OPTION_SEP_CHAR ','
+
+/**
+ * String version of UCNV_OPTION_SEP_CHAR. 
+ * @see ucnv_open
+ * @stable ICU 2.0
+ */
+#define UCNV_OPTION_SEP_STRING ","
+
+/**
+ * Character that separates a converter option from its value.
+ * @see ucnv_open
+ * @stable ICU 2.0
+ */
+#define UCNV_VALUE_SEP_CHAR '='
+
+/**
+ * String version of UCNV_VALUE_SEP_CHAR. 
+ * @see ucnv_open
+ * @stable ICU 2.0
+ */
+#define UCNV_VALUE_SEP_STRING "="
+
+/**
+ * Converter option for specifying a locale.
+ * For example, ucnv_open("SCSU,locale=ja", &errorCode);
+ * See convrtrs.txt.
+ *
+ * @see ucnv_open
+ * @stable ICU 2.0
+ */
+#define UCNV_LOCALE_OPTION_STRING ",locale="
+
+/**
+ * Converter option for specifying a version selector (0..9) for some converters.
+ * For example, ucnv_open("UTF-7,version=1", &errorCode);
+ * See convrtrs.txt.
+ *
+ * @see ucnv_open
+ * @stable ICU 2.4
+ */
+#define UCNV_VERSION_OPTION_STRING ",version="
+
+/**
+ * Converter option for EBCDIC SBCS or mixed-SBCS/DBCS (stateful) codepages.
+ * Swaps Unicode mappings for EBCDIC LF and NL codes, as used on
+ * S/390 (z/OS) Unix System Services (Open Edition).
+ * For example, ucnv_open("ibm-1047,swaplfnl", &errorCode);
+ * See convrtrs.txt.
+ *
+ * @see ucnv_open
+ * @stable ICU 2.4
+ */
+#define UCNV_SWAP_LFNL_OPTION_STRING ",swaplfnl"
+
+/**
+ * Do a fuzzy compare of two converter/alias names.
+ * The comparison is case-insensitive, ignores leading zeroes if they are not
+ * followed by further digits, and ignores all but letters and digits.
+ * Thus the strings "UTF-8", "utf_8", "u*T@f08" and "Utf 8" are exactly equivalent.
+ * See section 1.4, Charset Alias Matching in Unicode Technical Standard #22
+ * at http://www.unicode.org/reports/tr22/
+ *
+ * @param name1 a converter name or alias, zero-terminated
+ * @param name2 a converter name or alias, zero-terminated
+ * @return 0 if the names match, or a negative value if the name1
+ * lexically precedes name2, or a positive value if the name1
+ * lexically follows name2.
+ * @stable ICU 2.0
+ */
+U_STABLE int U_EXPORT2
+ucnv_compareNames(const char *name1, const char *name2);
+
+
+/**
+ * Creates a UConverter object with the name of a coded character set specified as a C string.
+ * The actual name will be resolved with the alias file
+ * using a case-insensitive string comparison that ignores
+ * leading zeroes and all non-alphanumeric characters.
+ * E.g., the names "UTF8", "utf-8", "u*T@f08" and "Utf 8" are all equivalent.
+ * (See also ucnv_compareNames().)
+ * If <code>NULL</code> is passed for the converter name, it will create one with the
+ * getDefaultName return value.
+ *
+ * <p>A converter name for ICU 1.5 and above may contain options
+ * like a locale specification to control the specific behavior of
+ * the newly instantiated converter.
+ * The meaning of the options depends on the particular converter.
+ * If an option is not defined for or recognized by a given converter, then it is ignored.</p>
+ *
+ * <p>Options are appended to the converter name string, with a
+ * <code>UCNV_OPTION_SEP_CHAR</code> between the name and the first option and
+ * also between adjacent options.</p>
+ *
+ * <p>If the alias is ambiguous, then the preferred converter is used
+ * and the status is set to U_AMBIGUOUS_ALIAS_WARNING.</p>
+ *
+ * <p>The conversion behavior and names can vary between platforms. ICU may
+ * convert some characters differently from other platforms. Details on this topic
+ * are in the <a href="http://icu-project.org/userguide/conversion.html">User's
+ * Guide</a>. Aliases starting with a "cp" prefix have no specific meaning
+ * other than its an alias starting with the letters "cp". Please do not
+ * associate any meaning to these aliases.</p>
+ *
+ * @param converterName Name of the coded character set table.
+ *          This may have options appended to the string.
+ *          IANA alias character set names, IBM CCSIDs starting with "ibm-",
+ *          Windows codepage numbers starting with "windows-" are frequently
+ *          used for this parameter. See ucnv_getAvailableName and
+ *          ucnv_getAlias for a complete list that is available.
+ *          If this parameter is NULL, the default converter will be used.
+ * @param err outgoing error status <TT>U_MEMORY_ALLOCATION_ERROR, U_FILE_ACCESS_ERROR</TT>
+ * @return the created Unicode converter object, or <TT>NULL</TT> if an error occured
+ * @see ucnv_openU
+ * @see ucnv_openCCSID
+ * @see ucnv_getAvailableName
+ * @see ucnv_getAlias
+ * @see ucnv_getDefaultName
+ * @see ucnv_close
+ * @see ucnv_compareNames
+ * @stable ICU 2.0
+ */
+U_STABLE UConverter* U_EXPORT2 
+ucnv_open(const char *converterName, UErrorCode *err);
+
+
+/**
+ * Creates a Unicode converter with the names specified as unicode string. 
+ * The name should be limited to the ASCII-7 alphanumerics range.
+ * The actual name will be resolved with the alias file
+ * using a case-insensitive string comparison that ignores
+ * leading zeroes and all non-alphanumeric characters.
+ * E.g., the names "UTF8", "utf-8", "u*T@f08" and "Utf 8" are all equivalent.
+ * (See also ucnv_compareNames().)
+ * If <TT>NULL</TT> is passed for the converter name, it will create 
+ * one with the ucnv_getDefaultName() return value.
+ * If the alias is ambiguous, then the preferred converter is used
+ * and the status is set to U_AMBIGUOUS_ALIAS_WARNING.
+ *
+ * <p>See ucnv_open for the complete details</p>
+ * @param name Name of the UConverter table in a zero terminated 
+ *        Unicode string
+ * @param err outgoing error status <TT>U_MEMORY_ALLOCATION_ERROR, 
+ *        U_FILE_ACCESS_ERROR</TT>
+ * @return the created Unicode converter object, or <TT>NULL</TT> if an 
+ *        error occured
+ * @see ucnv_open
+ * @see ucnv_openCCSID
+ * @see ucnv_close
+ * @see ucnv_compareNames
+ * @stable ICU 2.0
+ */
+U_STABLE UConverter* U_EXPORT2 
+ucnv_openU(const UChar *name,
+           UErrorCode *err);
+
+/**
+ * Creates a UConverter object from a CCSID number and platform pair.
+ * Note that the usefulness of this function is limited to platforms with numeric
+ * encoding IDs. Only IBM and Microsoft platforms use numeric (16-bit) identifiers for
+ * encodings.
+ *
+ * In addition, IBM CCSIDs and Unicode conversion tables are not 1:1 related.
+ * For many IBM CCSIDs there are multiple (up to six) Unicode conversion tables, and
+ * for some Unicode conversion tables there are multiple CCSIDs.
+ * Some "alternate" Unicode conversion tables are provided by the
+ * IBM CDRA conversion table registry.
+ * The most prominent example of a systematic modification of conversion tables that is
+ * not provided in the form of conversion table files in the repository is
+ * that S/390 Unix System Services swaps the codes for Line Feed and New Line in all
+ * EBCDIC codepages, which requires such a swap in the Unicode conversion tables as well.
+ *
+ * Only IBM default conversion tables are accessible with ucnv_openCCSID().
+ * ucnv_getCCSID() will return the same CCSID for all conversion tables that are associated
+ * with that CCSID.
+ *
+ * Currently, the only "platform" supported in the ICU converter API is UCNV_IBM.
+ *
+ * In summary, the use of CCSIDs and the associated API functions is not recommended.
+ *
+ * In order to open a converter with the default IBM CDRA Unicode conversion table,
+ * you can use this function or use the prefix "ibm-":
+ * \code
+ *     char name[20];
+ *     sprintf(name, "ibm-%hu", ccsid);
+ *     cnv=ucnv_open(name, &errorCode);
+ * \endcode
+ *
+ * In order to open a converter with the IBM S/390 Unix System Services variant
+ * of a Unicode/EBCDIC conversion table,
+ * you can use the prefix "ibm-" together with the option string UCNV_SWAP_LFNL_OPTION_STRING:
+ * \code
+ *     char name[20];
+ *     sprintf(name, "ibm-%hu" UCNV_SWAP_LFNL_OPTION_STRING, ccsid);
+ *     cnv=ucnv_open(name, &errorCode);
+ * \endcode
+ *
+ * In order to open a converter from a Microsoft codepage number, use the prefix "cp":
+ * \code
+ *     char name[20];
+ *     sprintf(name, "cp%hu", codepageID);
+ *     cnv=ucnv_open(name, &errorCode);
+ * \endcode
+ *
+ * If the alias is ambiguous, then the preferred converter is used
+ * and the status is set to U_AMBIGUOUS_ALIAS_WARNING.
+ *
+ * @param codepage codepage number to create
+ * @param platform the platform in which the codepage number exists
+ * @param err error status <TT>U_MEMORY_ALLOCATION_ERROR, U_FILE_ACCESS_ERROR</TT>
+ * @return the created Unicode converter object, or <TT>NULL</TT> if an error
+ *   occured.
+ * @see ucnv_open
+ * @see ucnv_openU
+ * @see ucnv_close
+ * @see ucnv_getCCSID
+ * @see ucnv_getPlatform
+ * @see UConverterPlatform
+ * @stable ICU 2.0
+ */
+U_STABLE UConverter* U_EXPORT2
+ucnv_openCCSID(int32_t codepage,
+               UConverterPlatform platform,
+               UErrorCode * err);
+
+/**
+ * <p>Creates a UConverter object specified from a packageName and a converterName.</p>
+ * 
+ * <p>The packageName and converterName must point to an ICU udata object, as defined by
+ *   <code> udata_open( packageName, "cnv", converterName, err) </code> or equivalent.
+ * Typically, packageName will refer to a (.dat) file, or to a package registered with
+ * udata_setAppData(). Using a full file or directory pathname for packageName is deprecated.</p>
+ * 
+ * <p>The name will NOT be looked up in the alias mechanism, nor will the converter be
+ * stored in the converter cache or the alias table. The only way to open further converters
+ * is call this function multiple times, or use the ucnv_safeClone() function to clone a 
+ * 'master' converter.</p>
+ *
+ * <p>A future version of ICU may add alias table lookups and/or caching
+ * to this function.</p>
+ * 
+ * <p>Example Use:
+ *      <code>cnv = ucnv_openPackage("myapp", "myconverter", &err);</code>
+ * </p>
+ *
+ * @param packageName name of the package (equivalent to 'path' in udata_open() call)
+ * @param converterName name of the data item to be used, without suffix.
+ * @param err outgoing error status <TT>U_MEMORY_ALLOCATION_ERROR, U_FILE_ACCESS_ERROR</TT>
+ * @return the created Unicode converter object, or <TT>NULL</TT> if an error occured
+ * @see udata_open
+ * @see ucnv_open
+ * @see ucnv_safeClone
+ * @see ucnv_close
+ * @stable ICU 2.2
+ */
+U_STABLE UConverter* U_EXPORT2 
+ucnv_openPackage(const char *packageName, const char *converterName, UErrorCode *err);
+
+/**
+ * Thread safe converter cloning operation.
+ * For most efficient operation, pass in a stackBuffer (and a *pBufferSize)
+ * with at least U_CNV_SAFECLONE_BUFFERSIZE bytes of space.
+ * If the buffer size is sufficient, then the clone will use the stack buffer;
+ * otherwise, it will be allocated, and *pBufferSize will indicate
+ * the actual size. (This should not occur with U_CNV_SAFECLONE_BUFFERSIZE.)
+ *
+ * You must ucnv_close() the clone in any case.
+ *
+ * If *pBufferSize==0, (regardless of whether stackBuffer==NULL or not)
+ * then *pBufferSize will be changed to a sufficient size
+ * for cloning this converter,
+ * without actually cloning the converter ("pure pre-flighting").
+ *
+ * If *pBufferSize is greater than zero but not large enough for a stack-based
+ * clone, then the converter is cloned using newly allocated memory
+ * and *pBufferSize is changed to the necessary size.
+ *
+ * If the converter clone fits into the stack buffer but the stack buffer is not
+ * sufficiently aligned for the clone, then the clone will use an
+ * adjusted pointer and use an accordingly smaller buffer size.
+ *
+ * @param cnv converter to be cloned
+ * @param stackBuffer user allocated space for the new clone. If NULL new memory will be allocated. 
+ *  If buffer is not large enough, new memory will be allocated.
+ *  Clients can use the U_CNV_SAFECLONE_BUFFERSIZE. This will probably be enough to avoid memory allocations.
+ * @param pBufferSize pointer to size of allocated space. pBufferSize must not be NULL.
+ * @param status to indicate whether the operation went on smoothly or there were errors
+ *  An informational status value, U_SAFECLONE_ALLOCATED_WARNING,
+ *  is used if any allocations were necessary.
+ *  However, it is better to check if *pBufferSize grew for checking for
+ *  allocations because warning codes can be overridden by subsequent
+ *  function calls.
+ * @return pointer to the new clone
+ * @stable ICU 2.0
+ */
+U_STABLE UConverter * U_EXPORT2 
+ucnv_safeClone(const UConverter *cnv, 
+               void             *stackBuffer,
+               int32_t          *pBufferSize, 
+               UErrorCode       *status);
+
+/**
+ * \def U_CNV_SAFECLONE_BUFFERSIZE
+ * Definition of a buffer size that is designed to be large enough for
+ * converters to be cloned with ucnv_safeClone().
+ * @stable ICU 2.0
+ */
+#define U_CNV_SAFECLONE_BUFFERSIZE  1024
+
+/**
+ * Deletes the unicode converter and releases resources associated
+ * with just this instance.
+ * Does not free up shared converter tables.
+ *
+ * @param converter the converter object to be deleted
+ * @see ucnv_open
+ * @see ucnv_openU
+ * @see ucnv_openCCSID
+ * @stable ICU 2.0
+ */
+U_STABLE void  U_EXPORT2
+ucnv_close(UConverter * converter);
+
+/**
+ * Fills in the output parameter, subChars, with the substitution characters
+ * as multiple bytes.
+ * If ucnv_setSubstString() set a Unicode string because the converter is
+ * stateful, then subChars will be an empty string.
+ *
+ * @param converter the Unicode converter
+ * @param subChars the subsitution characters
+ * @param len on input the capacity of subChars, on output the number 
+ * of bytes copied to it
+ * @param  err the outgoing error status code.
+ * If the substitution character array is too small, an
+ * <TT>U_INDEX_OUTOFBOUNDS_ERROR</TT> will be returned.
+ * @see ucnv_setSubstString
+ * @see ucnv_setSubstChars
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2
+ucnv_getSubstChars(const UConverter *converter,
+                   char *subChars,
+                   int8_t *len,
+                   UErrorCode *err);
+
+/**
+ * Sets the substitution chars when converting from unicode to a codepage. The
+ * substitution is specified as a string of 1-4 bytes, and may contain
+ * <TT>NULL</TT> bytes.
+ * The subChars must represent a single character. The caller needs to know the
+ * byte sequence of a valid character in the converter's charset.
+ * For some converters, for example some ISO 2022 variants, only single-byte
+ * substitution characters may be supported.
+ * The newer ucnv_setSubstString() function relaxes these limitations.
+ *
+ * @param converter the Unicode converter
+ * @param subChars the substitution character byte sequence we want set
+ * @param len the number of bytes in subChars
+ * @param err the error status code.  <TT>U_INDEX_OUTOFBOUNDS_ERROR </TT> if
+ * len is bigger than the maximum number of bytes allowed in subchars
+ * @see ucnv_setSubstString
+ * @see ucnv_getSubstChars
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2
+ucnv_setSubstChars(UConverter *converter,
+                   const char *subChars,
+                   int8_t len,
+                   UErrorCode *err);
+
+/**
+ * Set a substitution string for converting from Unicode to a charset.
+ * The caller need not know the charset byte sequence for each charset.
+ *
+ * Unlike ucnv_setSubstChars() which is designed to set a charset byte sequence
+ * for a single character, this function takes a Unicode string with
+ * zero, one or more characters, and immediately verifies that the string can be
+ * converted to the charset.
+ * If not, or if the result is too long (more than 32 bytes as of ICU 3.6),
+ * then the function returns with an error accordingly.
+ *
+ * Also unlike ucnv_setSubstChars(), this function works for stateful charsets
+ * by converting on the fly at the point of substitution rather than setting
+ * a fixed byte sequence.
+ *
+ * @param cnv The UConverter object.
+ * @param s The Unicode string.
+ * @param length The number of UChars in s, or -1 for a NUL-terminated string.
+ * @param err Pointer to a standard ICU error code. Its input value must
+ *            pass the U_SUCCESS() test, or else the function returns
+ *            immediately. Check for U_FAILURE() on output or use with
+ *            function chaining. (See User Guide for details.)
+ *
+ * @see ucnv_setSubstChars
+ * @see ucnv_getSubstChars
+ * @stable ICU 3.6
+ */
+U_STABLE void U_EXPORT2
+ucnv_setSubstString(UConverter *cnv,
+                    const UChar *s,
+                    int32_t length,
+                    UErrorCode *err);
+
+/**
+ * Fills in the output parameter, errBytes, with the error characters from the
+ * last failing conversion.
+ *
+ * @param converter the Unicode converter
+ * @param errBytes the codepage bytes which were in error
+ * @param len on input the capacity of errBytes, on output the number of
+ *  bytes which were copied to it
+ * @param err the error status code.
+ * If the substitution character array is too small, an
+ * <TT>U_INDEX_OUTOFBOUNDS_ERROR</TT> will be returned.
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2
+ucnv_getInvalidChars(const UConverter *converter,
+                     char *errBytes,
+                     int8_t *len,
+                     UErrorCode *err);
+
+/**
+ * Fills in the output parameter, errChars, with the error characters from the
+ * last failing conversion.
+ *
+ * @param converter the Unicode converter
+ * @param errUChars the UChars which were in error
+ * @param len on input the capacity of errUChars, on output the number of 
+ *  UChars which were copied to it
+ * @param err the error status code.
+ * If the substitution character array is too small, an
+ * <TT>U_INDEX_OUTOFBOUNDS_ERROR</TT> will be returned.
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2
+ucnv_getInvalidUChars(const UConverter *converter,
+                      UChar *errUChars,
+                      int8_t *len,
+                      UErrorCode *err);
+
+/**
+ * Resets the state of a converter to the default state. This is used
+ * in the case of an error, to restart a conversion from a known default state.
+ * It will also empty the internal output buffers.
+ * @param converter the Unicode converter
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2
+ucnv_reset(UConverter *converter);
+
+/**
+ * Resets the to-Unicode part of a converter state to the default state.
+ * This is used in the case of an error to restart a conversion to
+ * Unicode to a known default state. It will also empty the internal
+ * output buffers used for the conversion to Unicode codepoints.
+ * @param converter the Unicode converter
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+ucnv_resetToUnicode(UConverter *converter);
+
+/**
+ * Resets the from-Unicode part of a converter state to the default state.
+ * This is used in the case of an error to restart a conversion from
+ * Unicode to a known default state. It will also empty the internal output
+ * buffers used for the conversion from Unicode codepoints.
+ * @param converter the Unicode converter
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+ucnv_resetFromUnicode(UConverter *converter);
+
+/**
+ * Returns the maximum number of bytes that are output per UChar in conversion
+ * from Unicode using this converter.
+ * The returned number can be used with UCNV_GET_MAX_BYTES_FOR_STRING
+ * to calculate the size of a target buffer for conversion from Unicode.
+ *
+ * Note: Before ICU 2.8, this function did not return reliable numbers for
+ * some stateful converters (EBCDIC_STATEFUL, ISO-2022) and LMBCS.
+ *
+ * This number may not be the same as the maximum number of bytes per
+ * "conversion unit". In other words, it may not be the intuitively expected
+ * number of bytes per character that would be published for a charset,
+ * and may not fulfill any other purpose than the allocation of an output
+ * buffer of guaranteed sufficient size for a given input length and converter.
+ *
+ * Examples for special cases that are taken into account:
+ * - Supplementary code points may convert to more bytes than BMP code points.
+ *   This function returns bytes per UChar (UTF-16 code unit), not per
+ *   Unicode code point, for efficient buffer allocation.
+ * - State-shifting output (SI/SO, escapes, etc.) from stateful converters.
+ * - When m input UChars are converted to n output bytes, then the maximum m/n
+ *   is taken into account.
+ *
+ * The number returned here does not take into account
+ * (see UCNV_GET_MAX_BYTES_FOR_STRING):
+ * - callbacks which output more than one charset character sequence per call,
+ *   like escape callbacks
+ * - initial and final non-character bytes that are output by some converters
+ *   (automatic BOMs, initial escape sequence, final SI, etc.)
+ *
+ * Examples for returned values:
+ * - SBCS charsets: 1
+ * - Shift-JIS: 2
+ * - UTF-16: 2 (2 per BMP, 4 per surrogate _pair_, BOM not counted)
+ * - UTF-8: 3 (3 per BMP, 4 per surrogate _pair_)
+ * - EBCDIC_STATEFUL (EBCDIC mixed SBCS/DBCS): 3 (SO + DBCS)
+ * - ISO-2022: 3 (always outputs UTF-8)
+ * - ISO-2022-JP: 6 (4-byte escape sequences + DBCS)
+ * - ISO-2022-CN: 8 (4-byte designator sequences + 2-byte SS2/SS3 + DBCS)
+ *
+ * @param converter The Unicode converter.
+ * @return The maximum number of bytes per UChar that are output by ucnv_fromUnicode(),
+ *         to be used together with UCNV_GET_MAX_BYTES_FOR_STRING for buffer allocation.
+ *
+ * @see UCNV_GET_MAX_BYTES_FOR_STRING
+ * @see ucnv_getMinCharSize
+ * @stable ICU 2.0
+ */
+U_STABLE int8_t U_EXPORT2
+ucnv_getMaxCharSize(const UConverter *converter);
+
+/**
+ * Calculates the size of a buffer for conversion from Unicode to a charset.
+ * The calculated size is guaranteed to be sufficient for this conversion.
+ *
+ * It takes into account initial and final non-character bytes that are output
+ * by some converters.
+ * It does not take into account callbacks which output more than one charset
+ * character sequence per call, like escape callbacks.
+ * The default (substitution) callback only outputs one charset character sequence.
+ *
+ * @param length Number of UChars to be converted.
+ * @param maxCharSize Return value from ucnv_getMaxCharSize() for the converter
+ *                    that will be used.
+ * @return Size of a buffer that will be large enough to hold the output bytes of
+ *         converting length UChars with the converter that returned the maxCharSize.
+ *
+ * @see ucnv_getMaxCharSize
+ * @stable ICU 2.8
+ */
+#define UCNV_GET_MAX_BYTES_FOR_STRING(length, maxCharSize) \
+     (((int32_t)(length)+10)*(int32_t)(maxCharSize))
+
+/**
+ * Returns the minimum byte length for characters in this codepage. 
+ * This is usually either 1 or 2.
+ * @param converter the Unicode converter
+ * @return the minimum number of bytes allowed by this particular converter
+ * @see ucnv_getMaxCharSize
+ * @stable ICU 2.0
+ */
+U_STABLE int8_t U_EXPORT2
+ucnv_getMinCharSize(const UConverter *converter);
+
+/**
+ * Returns the display name of the converter passed in based on the Locale 
+ * passed in. If the locale contains no display name, the internal ASCII
+ * name will be filled in.
+ *
+ * @param converter the Unicode converter.
+ * @param displayLocale is the specific Locale we want to localised for
+ * @param displayName user provided buffer to be filled in
+ * @param displayNameCapacity size of displayName Buffer
+ * @param err error status code
+ * @return displayNameLength number of UChar needed in displayName
+ * @see ucnv_getName
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+ucnv_getDisplayName(const UConverter *converter,
+                    const char *displayLocale,
+                    UChar *displayName,
+                    int32_t displayNameCapacity,
+                    UErrorCode *err);
+
+/**
+ * Gets the internal, canonical name of the converter (zero-terminated).
+ * The lifetime of the returned string will be that of the converter 
+ * passed to this function.
+ * @param converter the Unicode converter
+ * @param err UErrorCode status
+ * @return the internal name of the converter
+ * @see ucnv_getDisplayName
+ * @stable ICU 2.0
+ */
+U_STABLE const char * U_EXPORT2 
+ucnv_getName(const UConverter *converter, UErrorCode *err);
+
+/**
+ * Gets a codepage number associated with the converter. This is not guaranteed
+ * to be the one used to create the converter. Some converters do not represent
+ * platform registered codepages and return zero for the codepage number.
+ * The error code fill-in parameter indicates if the codepage number
+ * is available.
+ * Does not check if the converter is <TT>NULL</TT> or if converter's data
+ * table is <TT>NULL</TT>.
+ *
+ * Important: The use of CCSIDs is not recommended because it is limited
+ * to only two platforms in principle and only one (UCNV_IBM) in the current
+ * ICU converter API.
+ * Also, CCSIDs are insufficient to identify IBM Unicode conversion tables precisely.
+ * For more details see ucnv_openCCSID().
+ *
+ * @param converter the Unicode converter
+ * @param err the error status code.
+ * @return If any error occurrs, -1 will be returned otherwise, the codepage number
+ * will be returned
+ * @see ucnv_openCCSID
+ * @see ucnv_getPlatform
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+ucnv_getCCSID(const UConverter *converter,
+              UErrorCode *err);
+
+/**
+ * Gets a codepage platform associated with the converter. Currently, 
+ * only <TT>UCNV_IBM</TT> will be returned.
+ * Does not test if the converter is <TT>NULL</TT> or if converter's data 
+ * table is <TT>NULL</TT>. 
+ * @param converter the Unicode converter
+ * @param err the error status code.
+ * @return The codepage platform
+ * @stable ICU 2.0
+ */
+U_STABLE UConverterPlatform U_EXPORT2
+ucnv_getPlatform(const UConverter *converter,
+                 UErrorCode *err);
+
+/**
+ * Gets the type of the converter
+ * e.g. SBCS, MBCS, DBCS, UTF8, UTF16_BE, UTF16_LE, ISO_2022, 
+ * EBCDIC_STATEFUL, LATIN_1
+ * @param converter a valid, opened converter
+ * @return the type of the converter
+ * @stable ICU 2.0
+ */
+U_STABLE UConverterType U_EXPORT2
+ucnv_getType(const UConverter * converter);
+
+/**
+ * Gets the "starter" (lead) bytes for converters of type MBCS.
+ * Will fill in an <TT>U_ILLEGAL_ARGUMENT_ERROR</TT> if converter passed in
+ * is not MBCS. Fills in an array of type UBool, with the value of the byte 
+ * as offset to the array. For example, if (starters[0x20] == TRUE) at return,
+ * it means that the byte 0x20 is a starter byte in this converter.
+ * Context pointers are always owned by the caller.
+ * 
+ * @param converter a valid, opened converter of type MBCS
+ * @param starters an array of size 256 to be filled in
+ * @param err error status, <TT>U_ILLEGAL_ARGUMENT_ERROR</TT> if the 
+ * converter is not a type which can return starters.
+ * @see ucnv_getType
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2
+ucnv_getStarters(const UConverter* converter, 
+                 UBool starters[256],
+                 UErrorCode* err);
+
+
+/**
+ * Selectors for Unicode sets that can be returned by ucnv_getUnicodeSet().
+ * @see ucnv_getUnicodeSet
+ * @stable ICU 2.6
+ */
+typedef enum UConverterUnicodeSet {
+    /** Select the set of roundtrippable Unicode code points. @stable ICU 2.6 */
+    UCNV_ROUNDTRIP_SET,
+    /** Select the set of Unicode code points with roundtrip or fallback mappings. @draft ICU 4.0 */
+    UCNV_ROUNDTRIP_AND_FALLBACK_SET,
+    /** Number of UConverterUnicodeSet selectors. @stable ICU 2.6 */
+    UCNV_SET_COUNT
+} UConverterUnicodeSet;
+
+
+/**
+ * Returns the set of Unicode code points that can be converted by an ICU converter.
+ *
+ * Returns one of several kinds of set:
+ *
+ * 1. UCNV_ROUNDTRIP_SET
+ *
+ * The set of all Unicode code points that can be roundtrip-converted
+ * (converted without any data loss) with the converter (ucnv_fromUnicode()).
+ * This set will not include code points that have fallback mappings
+ * or are only the result of reverse fallback mappings.
+ * This set will also not include PUA code points with fallbacks, although
+ * ucnv_fromUnicode() will always uses those mappings despite ucnv_setFallback().
+ * See UTR #22 "Character Mapping Markup Language"
+ * at http://www.unicode.org/reports/tr22/
+ *
+ * This is useful for example for
+ * - checking that a string or document can be roundtrip-converted with a converter,
+ *   without/before actually performing the conversion
+ * - testing if a converter can be used for text for typical text for a certain locale,
+ *   by comparing its roundtrip set with the set of ExemplarCharacters from
+ *   ICU's locale data or other sources
+ *
+ * 2. UCNV_ROUNDTRIP_AND_FALLBACK_SET
+ *
+ * The set of all Unicode code points that can be converted with the converter (ucnv_fromUnicode())
+ * when fallbacks are turned on (see ucnv_setFallback()).
+ * This set includes all code points with roundtrips and fallbacks (but not reverse fallbacks).
+ *
+ * In the future, there may be more UConverterUnicodeSet choices to select
+ * sets with different properties.
+ *
+ * @param cnv The converter for which a set is requested.
+ * @param setFillIn A valid USet *. It will be cleared by this function before
+ *            the converter's specific set is filled into the USet.
+ * @param whichSet A UConverterUnicodeSet selector;
+ *              currently UCNV_ROUNDTRIP_SET is the only supported value.
+ * @param pErrorCode ICU error code in/out parameter.
+ *                   Must fulfill U_SUCCESS before the function call.
+ *
+ * @see UConverterUnicodeSet
+ * @see uset_open
+ * @see uset_close
+ * @stable ICU 2.6
+ */
+U_STABLE void U_EXPORT2
+ucnv_getUnicodeSet(const UConverter *cnv,
+                   USet *setFillIn,
+                   UConverterUnicodeSet whichSet,
+                   UErrorCode *pErrorCode);
+
+/**
+ * Gets the current calback function used by the converter when an illegal
+ *  or invalid codepage sequence is found. 
+ * Context pointers are always owned by the caller.
+ *
+ * @param converter the unicode converter
+ * @param action fillin: returns the callback function pointer
+ * @param context fillin: returns the callback's private void* context
+ * @see ucnv_setToUCallBack
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2
+ucnv_getToUCallBack (const UConverter * converter,
+                     UConverterToUCallback *action,
+                     const void **context);
+
+/**
+ * Gets the current callback function used by the converter when illegal 
+ * or invalid Unicode sequence is found.
+ * Context pointers are always owned by the caller.
+ *
+ * @param converter the unicode converter
+ * @param action fillin: returns the callback function pointer
+ * @param context fillin: returns the callback's private void* context
+ * @see ucnv_setFromUCallBack
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2
+ucnv_getFromUCallBack (const UConverter * converter,
+                       UConverterFromUCallback *action,
+                       const void **context);
+
+/**
+ * Changes the callback function used by the converter when
+ * an illegal or invalid sequence is found.
+ * Context pointers are always owned by the caller.
+ * Predefined actions and contexts can be found in the ucnv_err.h header.
+ *
+ * @param converter the unicode converter
+ * @param newAction the new callback function
+ * @param newContext the new toUnicode callback context pointer. This can be NULL.
+ * @param oldAction fillin: returns the old callback function pointer. This can be NULL.
+ * @param oldContext fillin: returns the old callback's private void* context. This can be NULL.
+ * @param err The error code status
+ * @see ucnv_getToUCallBack
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2
+ucnv_setToUCallBack (UConverter * converter,
+                     UConverterToUCallback newAction,
+                     const void* newContext,
+                     UConverterToUCallback *oldAction,
+                     const void** oldContext,
+                     UErrorCode * err);
+
+/**
+ * Changes the current callback function used by the converter when
+ * an illegal or invalid sequence is found.
+ * Context pointers are always owned by the caller.
+ * Predefined actions and contexts can be found in the ucnv_err.h header.
+ *
+ * @param converter the unicode converter
+ * @param newAction the new callback function
+ * @param newContext the new fromUnicode callback context pointer. This can be NULL.
+ * @param oldAction fillin: returns the old callback function pointer. This can be NULL.
+ * @param oldContext fillin: returns the old callback's private void* context. This can be NULL.
+ * @param err The error code status
+ * @see ucnv_getFromUCallBack
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2
+ucnv_setFromUCallBack (UConverter * converter,
+                       UConverterFromUCallback newAction,
+                       const void *newContext,
+                       UConverterFromUCallback *oldAction,
+                       const void **oldContext,
+                       UErrorCode * err);
+
+/**
+ * Converts an array of unicode characters to an array of codepage
+ * characters. This function is optimized for converting a continuous
+ * stream of data in buffer-sized chunks, where the entire source and
+ * target does not fit in available buffers.
+ * 
+ * The source pointer is an in/out parameter. It starts out pointing where the 
+ * conversion is to begin, and ends up pointing after the last UChar consumed. 
+ * 
+ * Target similarly starts out pointer at the first available byte in the output
+ * buffer, and ends up pointing after the last byte written to the output.
+ * 
+ * The converter always attempts to consume the entire source buffer, unless 
+ * (1.) the target buffer is full, or (2.) a failing error is returned from the
+ * current callback function.  When a successful error status has been
+ * returned, it means that all of the source buffer has been
+ *  consumed. At that point, the caller should reset the source and
+ *  sourceLimit pointers to point to the next chunk.
+ * 
+ * At the end of the stream (flush==TRUE), the input is completely consumed
+ * when *source==sourceLimit and no error code is set.
+ * The converter object is then automatically reset by this function.
+ * (This means that a converter need not be reset explicitly between data
+ * streams if it finishes the previous stream without errors.)
+ * 
+ * This is a <I>stateful</I> conversion. Additionally, even when all source data has
+ * been consumed, some data may be in the converters' internal state.
+ * Call this function repeatedly, updating the target pointers with
+ * the next empty chunk of target in case of a
+ * <TT>U_BUFFER_OVERFLOW_ERROR</TT>, and updating the source  pointers
+ *  with the next chunk of source when a successful error status is
+ * returned, until there are no more chunks of source data.
+ * @param converter the Unicode converter
+ * @param target I/O parameter. Input : Points to the beginning of the buffer to copy
+ *  codepage characters to. Output : points to after the last codepage character copied
+ *  to <TT>target</TT>.
+ * @param targetLimit the pointer just after last of the <TT>target</TT> buffer
+ * @param source I/O parameter, pointer to pointer to the source Unicode character buffer. 
+ * @param sourceLimit the pointer just after the last of the source buffer
+ * @param offsets if NULL is passed, nothing will happen to it, otherwise it needs to have the same number
+ * of allocated cells as <TT>target</TT>. Will fill in offsets from target to source pointer
+ * e.g: <TT>offsets[3]</TT> is equal to 6, it means that the <TT>target[3]</TT> was a result of transcoding <TT>source[6]</TT>
+ * For output data carried across calls, and other data without a specific source character
+ * (such as from escape sequences or callbacks)  -1 will be placed for offsets. 
+ * @param flush set to <TT>TRUE</TT> if the current source buffer is the last available
+ * chunk of the source, <TT>FALSE</TT> otherwise. Note that if a failing status is returned,
+ * this function may have to be called multiple times with flush set to <TT>TRUE</TT> until
+ * the source buffer is consumed.
+ * @param err the error status.  <TT>U_ILLEGAL_ARGUMENT_ERROR</TT> will be set if the
+ * converter is <TT>NULL</TT>.
+ * <code>U_BUFFER_OVERFLOW_ERROR</code> will be set if the target is full and there is 
+ * still data to be written to the target.
+ * @see ucnv_fromUChars
+ * @see ucnv_convert
+ * @see ucnv_getMinCharSize
+ * @see ucnv_setToUCallBack
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+ucnv_fromUnicode (UConverter * converter,
+                  char **target,
+                  const char *targetLimit,
+                  const UChar ** source,
+                  const UChar * sourceLimit,
+                  int32_t* offsets,
+                  UBool flush,
+                  UErrorCode * err);
+
+/**
+ * Converts a buffer of codepage bytes into an array of unicode UChars
+ * characters. This function is optimized for converting a continuous
+ * stream of data in buffer-sized chunks, where the entire source and
+ * target does not fit in available buffers.
+ * 
+ * The source pointer is an in/out parameter. It starts out pointing where the 
+ * conversion is to begin, and ends up pointing after the last byte of source consumed. 
+ * 
+ * Target similarly starts out pointer at the first available UChar in the output
+ * buffer, and ends up pointing after the last UChar written to the output. 
+ * It does NOT necessarily keep UChar sequences together.
+ * 
+ * The converter always attempts to consume the entire source buffer, unless 
+ * (1.) the target buffer is full, or (2.) a failing error is returned from the
+ * current callback function.  When a successful error status has been
+ * returned, it means that all of the source buffer has been
+ *  consumed. At that point, the caller should reset the source and
+ *  sourceLimit pointers to point to the next chunk.
+ *
+ * At the end of the stream (flush==TRUE), the input is completely consumed
+ * when *source==sourceLimit and no error code is set
+ * The converter object is then automatically reset by this function.
+ * (This means that a converter need not be reset explicitly between data
+ * streams if it finishes the previous stream without errors.)
+ * 
+ * This is a <I>stateful</I> conversion. Additionally, even when all source data has
+ * been consumed, some data may be in the converters' internal state.
+ * Call this function repeatedly, updating the target pointers with
+ * the next empty chunk of target in case of a
+ * <TT>U_BUFFER_OVERFLOW_ERROR</TT>, and updating the source  pointers
+ *  with the next chunk of source when a successful error status is
+ * returned, until there are no more chunks of source data.
+ * @param converter the Unicode converter
+ * @param target I/O parameter. Input : Points to the beginning of the buffer to copy
+ *  UChars into. Output : points to after the last UChar copied.
+ * @param targetLimit the pointer just after the end of the <TT>target</TT> buffer
+ * @param source I/O parameter, pointer to pointer to the source codepage buffer. 
+ * @param sourceLimit the pointer to the byte after the end of the source buffer
+ * @param offsets if NULL is passed, nothing will happen to it, otherwise it needs to have the same number
+ * of allocated cells as <TT>target</TT>. Will fill in offsets from target to source pointer
+ * e.g: <TT>offsets[3]</TT> is equal to 6, it means that the <TT>target[3]</TT> was a result of transcoding <TT>source[6]</TT>
+ * For output data carried across calls, and other data without a specific source character
+ * (such as from escape sequences or callbacks)  -1 will be placed for offsets. 
+ * @param flush set to <TT>TRUE</TT> if the current source buffer is the last available
+ * chunk of the source, <TT>FALSE</TT> otherwise. Note that if a failing status is returned,
+ * this function may have to be called multiple times with flush set to <TT>TRUE</TT> until
+ * the source buffer is consumed.
+ * @param err the error status.  <TT>U_ILLEGAL_ARGUMENT_ERROR</TT> will be set if the
+ * converter is <TT>NULL</TT>.
+ * <code>U_BUFFER_OVERFLOW_ERROR</code> will be set if the target is full and there is 
+ * still data to be written to the target. 
+ * @see ucnv_fromUChars
+ * @see ucnv_convert
+ * @see ucnv_getMinCharSize
+ * @see ucnv_setFromUCallBack
+ * @see ucnv_getNextUChar
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+ucnv_toUnicode(UConverter *converter,
+               UChar **target,
+               const UChar *targetLimit,
+               const char **source,
+               const char *sourceLimit,
+               int32_t *offsets,
+               UBool flush,
+               UErrorCode *err);
+
+/**
+ * Convert the Unicode string into a codepage string using an existing UConverter.
+ * The output string is NUL-terminated if possible.
+ *
+ * This function is a more convenient but less powerful version of ucnv_fromUnicode().
+ * It is only useful for whole strings, not for streaming conversion.
+ *
+ * The maximum output buffer capacity required (barring output from callbacks) will be
+ * UCNV_GET_MAX_BYTES_FOR_STRING(srcLength, ucnv_getMaxCharSize(cnv)).
+ *
+ * @param cnv the converter object to be used (ucnv_resetFromUnicode() will be called)
+ * @param src the input Unicode string
+ * @param srcLength the input string length, or -1 if NUL-terminated
+ * @param dest destination string buffer, can be NULL if destCapacity==0
+ * @param destCapacity the number of chars available at dest
+ * @param pErrorCode normal ICU error code;
+ *                  common error codes that may be set by this function include
+ *                  U_BUFFER_OVERFLOW_ERROR, U_STRING_NOT_TERMINATED_WARNING,
+ *                  U_ILLEGAL_ARGUMENT_ERROR, and conversion errors
+ * @return the length of the output string, not counting the terminating NUL;
+ *         if the length is greater than destCapacity, then the string will not fit
+ *         and a buffer of the indicated length would need to be passed in
+ * @see ucnv_fromUnicode
+ * @see ucnv_convert
+ * @see UCNV_GET_MAX_BYTES_FOR_STRING
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+ucnv_fromUChars(UConverter *cnv,
+                char *dest, int32_t destCapacity,
+                const UChar *src, int32_t srcLength,
+                UErrorCode *pErrorCode);
+
+/**
+ * Convert the codepage string into a Unicode string using an existing UConverter.
+ * The output string is NUL-terminated if possible.
+ *
+ * This function is a more convenient but less powerful version of ucnv_toUnicode().
+ * It is only useful for whole strings, not for streaming conversion.
+ *
+ * The maximum output buffer capacity required (barring output from callbacks) will be
+ * 2*srcLength (each char may be converted into a surrogate pair).
+ *
+ * @param cnv the converter object to be used (ucnv_resetToUnicode() will be called)
+ * @param src the input codepage string
+ * @param srcLength the input string length, or -1 if NUL-terminated
+ * @param dest destination string buffer, can be NULL if destCapacity==0
+ * @param destCapacity the number of UChars available at dest
+ * @param pErrorCode normal ICU error code;
+ *                  common error codes that may be set by this function include
+ *                  U_BUFFER_OVERFLOW_ERROR, U_STRING_NOT_TERMINATED_WARNING,
+ *                  U_ILLEGAL_ARGUMENT_ERROR, and conversion errors
+ * @return the length of the output string, not counting the terminating NUL;
+ *         if the length is greater than destCapacity, then the string will not fit
+ *         and a buffer of the indicated length would need to be passed in
+ * @see ucnv_toUnicode
+ * @see ucnv_convert
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+ucnv_toUChars(UConverter *cnv,
+              UChar *dest, int32_t destCapacity,
+              const char *src, int32_t srcLength,
+              UErrorCode *pErrorCode);
+
+/**
+ * Convert a codepage buffer into Unicode one character at a time.
+ * The input is completely consumed when the U_INDEX_OUTOFBOUNDS_ERROR is set.
+ *
+ * Advantage compared to ucnv_toUnicode() or ucnv_toUChars():
+ * - Faster for small amounts of data, for most converters, e.g.,
+ *   US-ASCII, ISO-8859-1, UTF-8/16/32, and most "normal" charsets.
+ *   (For complex converters, e.g., SCSU, UTF-7 and ISO 2022 variants,
+ *    it uses ucnv_toUnicode() internally.)
+ * - Convenient.
+ *
+ * Limitations compared to ucnv_toUnicode():
+ * - Always assumes flush=TRUE.
+ *   This makes ucnv_getNextUChar() unsuitable for "streaming" conversion,
+ *   that is, for where the input is supplied in multiple buffers,
+ *   because ucnv_getNextUChar() will assume the end of the input at the end
+ *   of the first buffer.
+ * - Does not provide offset output.
+ *
+ * It is possible to "mix" ucnv_getNextUChar() and ucnv_toUnicode() because
+ * ucnv_getNextUChar() uses the current state of the converter
+ * (unlike ucnv_toUChars() which always resets first).
+ * However, if ucnv_getNextUChar() is called after ucnv_toUnicode()
+ * stopped in the middle of a character sequence (with flush=FALSE),
+ * then ucnv_getNextUChar() will always use the slower ucnv_toUnicode()
+ * internally until the next character boundary.
+ * (This is new in ICU 2.6. In earlier releases, ucnv_getNextUChar() had to
+ * start at a character boundary.)
+ *
+ * Instead of using ucnv_getNextUChar(), it is recommended
+ * to convert using ucnv_toUnicode() or ucnv_toUChars()
+ * and then iterate over the text using U16_NEXT() or a UCharIterator (uiter.h)
+ * or a C++ CharacterIterator or similar.
+ * This allows streaming conversion and offset output, for example.
+ *
+ * <p>Handling of surrogate pairs and supplementary-plane code points:<br>
+ * There are two different kinds of codepages that provide mappings for surrogate characters:
+ * <ul>
+ *   <li>Codepages like UTF-8, UTF-32, and GB 18030 provide direct representations for Unicode
+ *       code points U+10000-U+10ffff as well as for single surrogates U+d800-U+dfff.
+ *       Each valid sequence will result in exactly one returned code point.
+ *       If a sequence results in a single surrogate, then that will be returned
+ *       by itself, even if a neighboring sequence encodes the matching surrogate.</li>
+ *   <li>Codepages like SCSU and LMBCS (and UTF-16) provide direct representations only for BMP code points
+ *       including surrogates. Code points in supplementary planes are represented with
+ *       two sequences, each encoding a surrogate.
+ *       For these codepages, matching pairs of surrogates will be combined into single
+ *       code points for returning from this function.
+ *       (Note that SCSU is actually a mix of these codepage types.)</li>
+ * </ul></p>
+ *
+ * @param converter an open UConverter
+ * @param source the address of a pointer to the codepage buffer, will be
+ *  updated to point after the bytes consumed in the conversion call.
+ * @param sourceLimit points to the end of the input buffer
+ * @param err fills in error status (see ucnv_toUnicode)
+ * <code>U_INDEX_OUTOFBOUNDS_ERROR</code> will be set if the input 
+ * is empty or does not convert to any output (e.g.: pure state-change 
+ * codes SI/SO, escape sequences for ISO 2022,
+ * or if the callback did not output anything, ...).
+ * This function will not set a <code>U_BUFFER_OVERFLOW_ERROR</code> because
+ *  the "buffer" is the return code. However, there might be subsequent output
+ *  stored in the converter object
+ * that will be returned in following calls to this function.
+ * @return a UChar32 resulting from the partial conversion of source
+ * @see ucnv_toUnicode
+ * @see ucnv_toUChars
+ * @see ucnv_convert
+ * @stable ICU 2.0
+ */
+U_STABLE UChar32 U_EXPORT2
+ucnv_getNextUChar(UConverter * converter,
+                  const char **source,
+                  const char * sourceLimit,
+                  UErrorCode * err);
+
+/**
+ * Convert from one external charset to another using two existing UConverters.
+ * Internally, two conversions - ucnv_toUnicode() and ucnv_fromUnicode() -
+ * are used, "pivoting" through 16-bit Unicode.
+ *
+ * Important: For streaming conversion (multiple function calls for successive
+ * parts of a text stream), the caller must provide a pivot buffer explicitly,
+ * and must preserve the pivot buffer and associated pointers from one
+ * call to another. (The buffer may be moved if its contents and the relative
+ * pointer positions are preserved.)
+ *
+ * There is a similar function, ucnv_convert(),
+ * which has the following limitations:
+ * - it takes charset names, not converter objects, so that
+ *   - two converters are opened for each call
+ *   - only single-string conversion is possible, not streaming operation
+ * - it does not provide enough information to find out,
+ *   in case of failure, whether the toUnicode or
+ *   the fromUnicode conversion failed
+ *
+ * By contrast, ucnv_convertEx()
+ * - takes UConverter parameters instead of charset names
+ * - fully exposes the pivot buffer for streaming conversion and complete error handling
+ *
+ * ucnv_convertEx() also provides further convenience:
+ * - an option to reset the converters at the beginning
+ *   (if reset==TRUE, see parameters;
+ *    also sets *pivotTarget=*pivotSource=pivotStart)
+ * - allow NUL-terminated input
+ *   (only a single NUL byte, will not work for charsets with multi-byte NULs)
+ *   (if sourceLimit==NULL, see parameters)
+ * - terminate with a NUL on output
+ *   (only a single NUL byte, not useful for charsets with multi-byte NULs),
+ *   or set U_STRING_NOT_TERMINATED_WARNING if the output exactly fills
+ *   the target buffer
+ * - the pivot buffer can be provided internally;
+ *   possible only for whole-string conversion, not streaming conversion;
+ *   in this case, the caller will not be able to get details about where an
+ *   error occurred
+ *   (if pivotStart==NULL, see below)
+ *
+ * The function returns when one of the following is true:
+ * - the entire source text has been converted successfully to the target buffer
+ * - a target buffer overflow occurred (U_BUFFER_OVERFLOW_ERROR)
+ * - a conversion error occurred
+ *   (other U_FAILURE(), see description of pErrorCode)
+ *
+ * Limitation compared to the direct use of
+ * ucnv_fromUnicode() and ucnv_toUnicode():
+ * ucnv_convertEx() does not provide offset information.
+ *
+ * Limitation compared to ucnv_fromUChars() and ucnv_toUChars():
+ * ucnv_convertEx() does not support preflighting directly.
+ *
+ * Sample code for converting a single string from
+ * one external charset to UTF-8, ignoring the location of errors:
+ *
+ * \code
+ * int32_t
+ * myToUTF8(UConverter *cnv,
+ *          const char *s, int32_t length,
+ *          char *u8, int32_t capacity,
+ *          UErrorCode *pErrorCode) {
+ *     UConverter *utf8Cnv;
+ *     char *target;
+ *
+ *     if(U_FAILURE(*pErrorCode)) {
+ *         return 0;
+ *     }
+ *
+ *     utf8Cnv=myGetCachedUTF8Converter(pErrorCode);
+ *     if(U_FAILURE(*pErrorCode)) {
+ *         return 0;
+ *     }
+ *
+ *     if(length<0) {
+ *         length=strlen(s);
+ *     }
+ *     target=u8;
+ *     ucnv_convertEx(cnv, utf8Cnv,
+ *                    &target, u8+capacity,
+ *                    &s, s+length,
+ *                    NULL, NULL, NULL, NULL,
+ *                    TRUE, TRUE,
+ *                    pErrorCode);
+ * 
+ *     myReleaseCachedUTF8Converter(utf8Cnv);
+ *
+ *     // return the output string length, but without preflighting
+ *     return (int32_t)(target-u8);
+ * }
+ * \endcode
+ *
+ * @param targetCnv     Output converter, used to convert from the UTF-16 pivot
+ *                      to the target using ucnv_fromUnicode().
+ * @param sourceCnv     Input converter, used to convert from the source to
+ *                      the UTF-16 pivot using ucnv_toUnicode().
+ * @param target        I/O parameter, same as for ucnv_fromUChars().
+ *                      Input: *target points to the beginning of the target buffer.
+ *                      Output: *target points to the first unit after the last char written.
+ * @param targetLimit   Pointer to the first unit after the target buffer.
+ * @param source        I/O parameter, same as for ucnv_toUChars().
+ *                      Input: *source points to the beginning of the source buffer.
+ *                      Output: *source points to the first unit after the last char read.
+ * @param sourceLimit   Pointer to the first unit after the source buffer.
+ * @param pivotStart    Pointer to the UTF-16 pivot buffer. If pivotStart==NULL,
+ *                      then an internal buffer is used and the other pivot
+ *                      arguments are ignored and can be NULL as well.
+ * @param pivotSource   I/O parameter, same as source in ucnv_fromUChars() for
+ *                      conversion from the pivot buffer to the target buffer.
+ * @param pivotTarget   I/O parameter, same as target in ucnv_toUChars() for
+ *                      conversion from the source buffer to the pivot buffer.
+ *                      It must be pivotStart<=*pivotSource<=*pivotTarget<=pivotLimit
+ *                      and pivotStart<pivotLimit (unless pivotStart==NULL).
+ * @param pivotLimit    Pointer to the first unit after the pivot buffer.
+ * @param reset         If TRUE, then ucnv_resetToUnicode(sourceCnv) and
+ *                      ucnv_resetFromUnicode(targetCnv) are called, and the
+ *                      pivot pointers are reset (*pivotTarget=*pivotSource=pivotStart).
+ * @param flush         If true, indicates the end of the input.
+ *                      Passed directly to ucnv_toUnicode(), and carried over to
+ *                      ucnv_fromUnicode() when the source is empty as well.
+ * @param pErrorCode    ICU error code in/out parameter.
+ *                      Must fulfill U_SUCCESS before the function call.
+ *                      U_BUFFER_OVERFLOW_ERROR always refers to the target buffer
+ *                      because overflows into the pivot buffer are handled internally.
+ *                      Other conversion errors are from the source-to-pivot
+ *                      conversion if *pivotSource==pivotStart, otherwise from
+ *                      the pivot-to-target conversion.
+ *
+ * @see ucnv_convert
+ * @see ucnv_fromAlgorithmic
+ * @see ucnv_toAlgorithmic
+ * @see ucnv_fromUnicode
+ * @see ucnv_toUnicode
+ * @see ucnv_fromUChars
+ * @see ucnv_toUChars
+ * @stable ICU 2.6
+ */
+U_STABLE void U_EXPORT2
+ucnv_convertEx(UConverter *targetCnv, UConverter *sourceCnv,
+               char **target, const char *targetLimit,
+               const char **source, const char *sourceLimit,
+               UChar *pivotStart, UChar **pivotSource,
+               UChar **pivotTarget, const UChar *pivotLimit,
+               UBool reset, UBool flush,
+               UErrorCode *pErrorCode);
+
+/**
+ * Convert from one external charset to another.
+ * Internally, two converters are opened according to the name arguments,
+ * then the text is converted to and from the 16-bit Unicode "pivot"
+ * using ucnv_convertEx(), then the converters are closed again.
+ *
+ * This is a convenience function, not an efficient way to convert a lot of text:
+ * ucnv_convert()
+ * - takes charset names, not converter objects, so that
+ *   - two converters are opened for each call
+ *   - only single-string conversion is possible, not streaming operation
+ * - does not provide enough information to find out,
+ *   in case of failure, whether the toUnicode or
+ *   the fromUnicode conversion failed
+ * - allows NUL-terminated input
+ *   (only a single NUL byte, will not work for charsets with multi-byte NULs)
+ *   (if sourceLength==-1, see parameters)
+ * - terminate with a NUL on output
+ *   (only a single NUL byte, not useful for charsets with multi-byte NULs),
+ *   or set U_STRING_NOT_TERMINATED_WARNING if the output exactly fills
+ *   the target buffer
+ * - a pivot buffer is provided internally
+ *
+ * The function returns when one of the following is true:
+ * - the entire source text has been converted successfully to the target buffer
+ *   and either the target buffer is terminated with a single NUL byte
+ *   or the error code is set to U_STRING_NOT_TERMINATED_WARNING
+ * - a target buffer overflow occurred (U_BUFFER_OVERFLOW_ERROR)
+ *   and the full output string length is returned ("preflighting")
+ * - a conversion error occurred
+ *   (other U_FAILURE(), see description of pErrorCode)
+ *
+ * @param toConverterName   The name of the converter that is used to convert
+ *                          from the UTF-16 pivot buffer to the target.
+ * @param fromConverterName The name of the converter that is used to convert
+ *                          from the source to the UTF-16 pivot buffer.
+ * @param target            Pointer to the output buffer.
+ * @param targetCapacity    Capacity of the target, in bytes.
+ * @param source            Pointer to the input buffer.
+ * @param sourceLength      Length of the input text, in bytes, or -1 for NUL-terminated input.
+ * @param pErrorCode        ICU error code in/out parameter.
+ *                          Must fulfill U_SUCCESS before the function call.
+ * @return Length of the complete output text in bytes, even if it exceeds the targetCapacity
+ *         and a U_BUFFER_OVERFLOW_ERROR is set.
+ *
+ * @see ucnv_convertEx
+ * @see ucnv_fromAlgorithmic
+ * @see ucnv_toAlgorithmic
+ * @see ucnv_fromUnicode
+ * @see ucnv_toUnicode
+ * @see ucnv_fromUChars
+ * @see ucnv_toUChars
+ * @see ucnv_getNextUChar
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+ucnv_convert(const char *toConverterName,
+             const char *fromConverterName,
+             char *target,
+             int32_t targetCapacity,
+             const char *source,
+             int32_t sourceLength,
+             UErrorCode *pErrorCode);
+
+/**
+ * Convert from one external charset to another.
+ * Internally, the text is converted to and from the 16-bit Unicode "pivot"
+ * using ucnv_convertEx(). ucnv_toAlgorithmic() works exactly like ucnv_convert()
+ * except that the two converters need not be looked up and opened completely.
+ *
+ * The source-to-pivot conversion uses the cnv converter parameter.
+ * The pivot-to-target conversion uses a purely algorithmic converter
+ * according to the specified type, e.g., UCNV_UTF8 for a UTF-8 converter.
+ *
+ * Internally, the algorithmic converter is opened and closed for each
+ * function call, which is more efficient than using the public ucnv_open()
+ * but somewhat less efficient than only resetting an existing converter
+ * and using ucnv_convertEx().
+ *
+ * This function is more convenient than ucnv_convertEx() for single-string
+ * conversions, especially when "preflighting" is desired (returning the length
+ * of the complete output even if it does not fit into the target buffer;
+ * see the User Guide Strings chapter). See ucnv_convert() for details.
+ *
+ * @param algorithmicType   UConverterType constant identifying the desired target
+ *                          charset as a purely algorithmic converter.
+ *                          Those are converters for Unicode charsets like
+ *                          UTF-8, BOCU-1, SCSU, UTF-7, IMAP-mailbox-name, etc.,
+ *                          as well as US-ASCII and ISO-8859-1.
+ * @param cnv               The converter that is used to convert
+ *                          from the source to the UTF-16 pivot buffer.
+ * @param target            Pointer to the output buffer.
+ * @param targetCapacity    Capacity of the target, in bytes.
+ * @param source            Pointer to the input buffer.
+ * @param sourceLength      Length of the input text, in bytes
+ * @param pErrorCode        ICU error code in/out parameter.
+ *                          Must fulfill U_SUCCESS before the function call.
+ * @return Length of the complete output text in bytes, even if it exceeds the targetCapacity
+ *         and a U_BUFFER_OVERFLOW_ERROR is set.
+ *
+ * @see ucnv_fromAlgorithmic
+ * @see ucnv_convert
+ * @see ucnv_convertEx
+ * @see ucnv_fromUnicode
+ * @see ucnv_toUnicode
+ * @see ucnv_fromUChars
+ * @see ucnv_toUChars
+ * @stable ICU 2.6
+ */
+U_STABLE int32_t U_EXPORT2
+ucnv_toAlgorithmic(UConverterType algorithmicType,
+                   UConverter *cnv,
+                   char *target, int32_t targetCapacity,
+                   const char *source, int32_t sourceLength,
+                   UErrorCode *pErrorCode);
+
+/**
+ * Convert from one external charset to another.
+ * Internally, the text is converted to and from the 16-bit Unicode "pivot"
+ * using ucnv_convertEx(). ucnv_fromAlgorithmic() works exactly like ucnv_convert()
+ * except that the two converters need not be looked up and opened completely.
+ *
+ * The source-to-pivot conversion uses a purely algorithmic converter
+ * according to the specified type, e.g., UCNV_UTF8 for a UTF-8 converter.
+ * The pivot-to-target conversion uses the cnv converter parameter.
+ *
+ * Internally, the algorithmic converter is opened and closed for each
+ * function call, which is more efficient than using the public ucnv_open()
+ * but somewhat less efficient than only resetting an existing converter
+ * and using ucnv_convertEx().
+ *
+ * This function is more convenient than ucnv_convertEx() for single-string
+ * conversions, especially when "preflighting" is desired (returning the length
+ * of the complete output even if it does not fit into the target buffer;
+ * see the User Guide Strings chapter). See ucnv_convert() for details.
+ *
+ * @param cnv               The converter that is used to convert
+ *                          from the UTF-16 pivot buffer to the target.
+ * @param algorithmicType   UConverterType constant identifying the desired source
+ *                          charset as a purely algorithmic converter.
+ *                          Those are converters for Unicode charsets like
+ *                          UTF-8, BOCU-1, SCSU, UTF-7, IMAP-mailbox-name, etc.,
+ *                          as well as US-ASCII and ISO-8859-1.
+ * @param target            Pointer to the output buffer.
+ * @param targetCapacity    Capacity of the target, in bytes.
+ * @param source            Pointer to the input buffer.
+ * @param sourceLength      Length of the input text, in bytes
+ * @param pErrorCode        ICU error code in/out parameter.
+ *                          Must fulfill U_SUCCESS before the function call.
+ * @return Length of the complete output text in bytes, even if it exceeds the targetCapacity
+ *         and a U_BUFFER_OVERFLOW_ERROR is set.
+ *
+ * @see ucnv_fromAlgorithmic
+ * @see ucnv_convert
+ * @see ucnv_convertEx
+ * @see ucnv_fromUnicode
+ * @see ucnv_toUnicode
+ * @see ucnv_fromUChars
+ * @see ucnv_toUChars
+ * @stable ICU 2.6
+ */
+U_STABLE int32_t U_EXPORT2
+ucnv_fromAlgorithmic(UConverter *cnv,
+                     UConverterType algorithmicType,
+                     char *target, int32_t targetCapacity,
+                     const char *source, int32_t sourceLength,
+                     UErrorCode *pErrorCode);
+
+/**
+ * Frees up memory occupied by unused, cached converter shared data.
+ *
+ * @return the number of cached converters successfully deleted
+ * @see ucnv_close
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+ucnv_flushCache(void);
+
+/**
+ * Returns the number of available converters, as per the alias file.
+ *
+ * @return the number of available converters
+ * @see ucnv_getAvailableName
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2
+ucnv_countAvailable(void);
+
+/**
+ * Gets the canonical converter name of the specified converter from a list of
+ * all available converters contaied in the alias file. All converters
+ * in this list can be opened.
+ *
+ * @param n the index to a converter available on the system (in the range <TT>[0..ucnv_countAvaiable()]</TT>)
+ * @return a pointer a string (library owned), or <TT>NULL</TT> if the index is out of bounds.
+ * @see ucnv_countAvailable
+ * @stable ICU 2.0
+ */
+U_STABLE const char* U_EXPORT2
+ucnv_getAvailableName(int32_t n);
+
+/**
+ * Returns a UEnumeration to enumerate all of the canonical converter
+ * names, as per the alias file, regardless of the ability to open each
+ * converter.
+ *
+ * @return A UEnumeration object for getting all the recognized canonical
+ *   converter names.
+ * @see ucnv_getAvailableName
+ * @see uenum_close
+ * @see uenum_next
+ * @stable ICU 2.4
+ */
+U_STABLE UEnumeration * U_EXPORT2
+ucnv_openAllNames(UErrorCode *pErrorCode);
+
+/**
+ * Gives the number of aliases for a given converter or alias name.
+ * If the alias is ambiguous, then the preferred converter is used
+ * and the status is set to U_AMBIGUOUS_ALIAS_WARNING.
+ * This method only enumerates the listed entries in the alias file.
+ * @param alias alias name
+ * @param pErrorCode error status
+ * @return number of names on alias list for given alias
+ * @stable ICU 2.0
+ */
+U_STABLE uint16_t U_EXPORT2 
+ucnv_countAliases(const char *alias, UErrorCode *pErrorCode);
+
+/**
+ * Gives the name of the alias at given index of alias list.
+ * This method only enumerates the listed entries in the alias file.
+ * If the alias is ambiguous, then the preferred converter is used
+ * and the status is set to U_AMBIGUOUS_ALIAS_WARNING.
+ * @param alias alias name
+ * @param n index in alias list
+ * @param pErrorCode result of operation
+ * @return returns the name of the alias at given index
+ * @see ucnv_countAliases
+ * @stable ICU 2.0
+ */
+U_STABLE const char * U_EXPORT2 
+ucnv_getAlias(const char *alias, uint16_t n, UErrorCode *pErrorCode);
+
+/**
+ * Fill-up the list of alias names for the given alias.
+ * This method only enumerates the listed entries in the alias file.
+ * If the alias is ambiguous, then the preferred converter is used
+ * and the status is set to U_AMBIGUOUS_ALIAS_WARNING.
+ * @param alias alias name
+ * @param aliases fill-in list, aliases is a pointer to an array of
+ *        <code>ucnv_countAliases()</code> string-pointers
+ *        (<code>const char *</code>) that will be filled in.
+ *        The strings themselves are owned by the library.
+ * @param pErrorCode result of operation
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+ucnv_getAliases(const char *alias, const char **aliases, UErrorCode *pErrorCode);
+
+/**
+ * Return a new UEnumeration object for enumerating all the
+ * alias names for a given converter that are recognized by a standard.
+ * This method only enumerates the listed entries in the alias file.
+ * The convrtrs.txt file can be modified to change the results of
+ * this function.
+ * The first result in this list is the same result given by
+ * <code>ucnv_getStandardName</code>, which is the default alias for
+ * the specified standard name. The returned object must be closed with
+ * <code>uenum_close</code> when you are done with the object.
+ *
+ * @param convName original converter name
+ * @param standard name of the standard governing the names; MIME and IANA
+ *      are such standards
+ * @param pErrorCode The error code
+ * @return A UEnumeration object for getting all aliases that are recognized
+ *      by a standard. If any of the parameters are invalid, NULL
+ *      is returned.
+ * @see ucnv_getStandardName
+ * @see uenum_close
+ * @see uenum_next
+ * @stable ICU 2.2
+ */
+U_STABLE UEnumeration * U_EXPORT2
+ucnv_openStandardNames(const char *convName,
+                       const char *standard,
+                       UErrorCode *pErrorCode);
+
+/**
+ * Gives the number of standards associated to converter names.
+ * @return number of standards
+ * @stable ICU 2.0
+ */
+U_STABLE uint16_t U_EXPORT2
+ucnv_countStandards(void);
+
+/**
+ * Gives the name of the standard at given index of standard list.
+ * @param n index in standard list
+ * @param pErrorCode result of operation
+ * @return returns the name of the standard at given index. Owned by the library.
+ * @stable ICU 2.0
+ */
+U_STABLE const char * U_EXPORT2
+ucnv_getStandard(uint16_t n, UErrorCode *pErrorCode);
+
+/**
+ * Returns a standard name for a given converter name.
+ * <p>
+ * Example alias table:<br>
+ * conv alias1 { STANDARD1 } alias2 { STANDARD1* }
+ * <p>
+ * Result of ucnv_getStandardName("conv", "STANDARD1") from example
+ * alias table:<br>
+ * <b>"alias2"</b>
+ *
+ * @param name original converter name
+ * @param standard name of the standard governing the names; MIME and IANA
+ *        are such standards
+ * @param pErrorCode result of operation
+ * @return returns the standard converter name;
+ *         if a standard converter name cannot be determined,
+ *         then <code>NULL</code> is returned. Owned by the library.
+ * @stable ICU 2.0
+ */
+U_STABLE const char * U_EXPORT2
+ucnv_getStandardName(const char *name, const char *standard, UErrorCode *pErrorCode);
+
+/**
+ * This function will return the internal canonical converter name of the
+ * tagged alias. This is the opposite of ucnv_openStandardNames, which
+ * returns the tagged alias given the canonical name.
+ * <p>
+ * Example alias table:<br>
+ * conv alias1 { STANDARD1 } alias2 { STANDARD1* }
+ * <p>
+ * Result of ucnv_getStandardName("alias1", "STANDARD1") from example
+ * alias table:<br>
+ * <b>"conv"</b>
+ *
+ * @return returns the canonical converter name;
+ *         if a standard or alias name cannot be determined,
+ *         then <code>NULL</code> is returned. The returned string is
+ *         owned by the library.
+ * @see ucnv_getStandardName
+ * @stable ICU 2.4
+ */
+U_STABLE const char * U_EXPORT2
+ucnv_getCanonicalName(const char *alias, const char *standard, UErrorCode *pErrorCode);
+
+/**
+ * Returns the current default converter name. If you want to open
+ * a default converter, you do not need to use this function.
+ * It is faster if you pass a NULL argument to ucnv_open the
+ * default converter.
+ *
+ * @return returns the current default converter name.
+ *         Storage owned by the library
+ * @see ucnv_setDefaultName
+ * @stable ICU 2.0
+ */
+U_STABLE const char * U_EXPORT2
+ucnv_getDefaultName(void);
+
+/**
+ * This function is not thread safe. DO NOT call this function when ANY ICU
+ * function is being used from more than one thread! This function sets the
+ * current default converter name. If this function needs to be called, it
+ * should be called during application initialization. Most of the time, the
+ * results from ucnv_getDefaultName() or ucnv_open with a NULL string argument
+ * is sufficient for your application.
+ * @param name the converter name to be the default (must be known by ICU).
+ * @see ucnv_getDefaultName
+ * @system
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2
+ucnv_setDefaultName(const char *name);
+
+/**
+ * Fixes the backslash character mismapping.  For example, in SJIS, the backslash 
+ * character in the ASCII portion is also used to represent the yen currency sign.  
+ * When mapping from Unicode character 0x005C, it's unclear whether to map the 
+ * character back to yen or backslash in SJIS.  This function will take the input
+ * buffer and replace all the yen sign characters with backslash.  This is necessary
+ * when the user tries to open a file with the input buffer on Windows.
+ * This function will test the converter to see whether such mapping is
+ * required.  You can sometimes avoid using this function by using the correct version
+ * of Shift-JIS.
+ *
+ * @param cnv The converter representing the target codepage.
+ * @param source the input buffer to be fixed
+ * @param sourceLen the length of the input buffer
+ * @see ucnv_isAmbiguous
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2
+ucnv_fixFileSeparator(const UConverter *cnv, UChar *source, int32_t sourceLen);
+
+/**
+ * Determines if the converter contains ambiguous mappings of the same
+ * character or not.
+ * @param cnv the converter to be tested
+ * @return TRUE if the converter contains ambiguous mapping of the same 
+ * character, FALSE otherwise.
+ * @stable ICU 2.0
+ */
+U_STABLE UBool U_EXPORT2
+ucnv_isAmbiguous(const UConverter *cnv);
+
+/**
+ * Sets the converter to use fallback mappings or not.
+ * Regardless of this flag, the converter will always use
+ * fallbacks from Unicode Private Use code points, as well as
+ * reverse fallbacks (to Unicode).
+ * For details see ".ucm File Format"
+ * in the Conversion Data chapter of the ICU User Guide:
+ * http://www.icu-project.org/userguide/conversion-data.html#ucmformat
+ *
+ * @param cnv The converter to set the fallback mapping usage on.
+ * @param usesFallback TRUE if the user wants the converter to take advantage of the fallback 
+ * mapping, FALSE otherwise.
+ * @stable ICU 2.0
+ * @see ucnv_usesFallback
+ */
+U_STABLE void U_EXPORT2 
+ucnv_setFallback(UConverter *cnv, UBool usesFallback);
+
+/**
+ * Determines if the converter uses fallback mappings or not.
+ * This flag has restrictions, see ucnv_setFallback().
+ *
+ * @param cnv The converter to be tested
+ * @return TRUE if the converter uses fallback, FALSE otherwise.
+ * @stable ICU 2.0
+ * @see ucnv_setFallback
+ */
+U_STABLE UBool U_EXPORT2 
+ucnv_usesFallback(const UConverter *cnv);
+
+/**
+ * Detects Unicode signature byte sequences at the start of the byte stream
+ * and returns the charset name of the indicated Unicode charset.
+ * NULL is returned when no Unicode signature is recognized.
+ * The number of bytes in the signature is output as well.
+ *
+ * The caller can ucnv_open() a converter using the charset name.
+ * The first code unit (UChar) from the start of the stream will be U+FEFF
+ * (the Unicode BOM/signature character) and can usually be ignored.
+ *
+ * For most Unicode charsets it is also possible to ignore the indicated
+ * number of initial stream bytes and start converting after them.
+ * However, there are stateful Unicode charsets (UTF-7 and BOCU-1) for which
+ * this will not work. Therefore, it is best to ignore the first output UChar
+ * instead of the input signature bytes.
+ * <p>
+ * Usage:
+ * @code     
+ *      UErrorCode err = U_ZERO_ERROR;
+ *      char input[] = { '\xEF','\xBB', '\xBF','\x41','\x42','\x43' };
+ *      int32_t signatureLength = 0;
+ *      char *encoding = ucnv_detectUnicodeSignature(input,sizeof(input),&signatureLength,&err);
+ *      UConverter *conv = NULL;
+ *      UChar output[100];
+ *      UChar *target = output, *out;
+ *      char *source = input;
+ *      if(encoding!=NULL && U_SUCCESS(err)){
+ *          // should signature be discarded ?
+ *          conv = ucnv_open(encoding, &err);
+ *          // do the conversion
+ *          ucnv_toUnicode(conv,
+ *                         target, output + sizeof(output)/U_SIZEOF_UCHAR,
+ *                         source, input + sizeof(input),
+ *                         NULL, TRUE, &err);
+ *          out = output;
+ *          if (discardSignature){
+ *              ++out; // ignore initial U+FEFF
+ *          }
+ *          while(out != target) {
+ *              printf("%04x ", *out++);
+ *          }
+ *          puts("");
+ *      }
+ *     
+ * @endcode
+ *
+ * @param source            The source string in which the signature should be detected.
+ * @param sourceLength      Length of the input string, or -1 if terminated with a NUL byte.
+ * @param signatureLength   A pointer to int32_t to receive the number of bytes that make up the signature 
+ *                          of the detected UTF. 0 if not detected.
+ *                          Can be a NULL pointer.
+ * @param pErrorCode        ICU error code in/out parameter.
+ *                          Must fulfill U_SUCCESS before the function call.
+ * @return The name of the encoding detected. NULL if encoding is not detected. 
+ * @stable ICU 2.4
+ */
+U_STABLE const char* U_EXPORT2
+ucnv_detectUnicodeSignature(const char* source,
+                            int32_t sourceLength,
+                            int32_t *signatureLength,
+                            UErrorCode *pErrorCode);
+
+/**
+ * Returns the number of UChars held in the converter's internal state 
+ * because more input is needed for completing the conversion. This function is 
+ * useful for mapping semantics of ICU's converter interface to those of iconv,
+ * and this information is not needed for normal conversion.
+ * @param cnv       The converter in which the input is held
+ * @param status    ICU error code in/out parameter.
+ *                  Must fulfill U_SUCCESS before the function call.
+ * @return The number of UChars in the state. -1 if an error is encountered.
+ * @stable ICU 3.4
+ */
+U_STABLE int32_t U_EXPORT2
+ucnv_fromUCountPending(const UConverter* cnv, UErrorCode* status);
+
+/**
+ * Returns the number of chars held in the converter's internal state
+ * because more input is needed for completing the conversion. This function is 
+ * useful for mapping semantics of ICU's converter interface to those of iconv,
+ * and this information is not needed for normal conversion.
+ * @param cnv       The converter in which the input is held as internal state
+ * @param status    ICU error code in/out parameter.
+ *                  Must fulfill U_SUCCESS before the function call.
+ * @return The number of chars in the state. -1 if an error is encountered.
+ * @stable ICU 3.4
+ */
+U_STABLE int32_t U_EXPORT2
+ucnv_toUCountPending(const UConverter* cnv, UErrorCode* status);
+
+#endif
+
+#endif
+/*_UCNV*/


[14/96] [abbrv] [partial] move sources to src

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/941a8236/apps/fauxton/assets/js/libs/lodash.js
----------------------------------------------------------------------
diff --git a/apps/fauxton/assets/js/libs/lodash.js b/apps/fauxton/assets/js/libs/lodash.js
deleted file mode 100644
index 514eeb0..0000000
--- a/apps/fauxton/assets/js/libs/lodash.js
+++ /dev/null
@@ -1,4493 +0,0 @@
-/**
- * @license
- * Lo-Dash 1.3.1 (Custom Build) <http://lodash.com/>
- * Build: `lodash underscore exports="amd,commonjs,global,node" -o ./dist/lodash.underscore.js`
- * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
- * Based on Underscore.js 1.4.4 <http://underscorejs.org/>
- * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud Inc.
- * Available under MIT license <http://lodash.com/license>
- */
-;(function(window) {
-
-  /** Used as a safe reference for `undefined` in pre ES5 environments */
-  var undefined;
-
-  /** Used to generate unique IDs */
-  var idCounter = 0;
-
-  /** Used internally to indicate various things */
-  var indicatorObject = {};
-
-  /** Used to prefix keys to avoid issues with `__proto__` and properties on `Object.prototype` */
-  var keyPrefix = +new Date + '';
-
-  /** Used as the size when optimizations are enabled for large arrays */
-  var largeArraySize = 75;
-
-  /** Used to match empty string literals in compiled template source */
-  var reEmptyStringLeading = /\b__p \+= '';/g,
-      reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
-      reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
-
-  /** Used to match HTML entities */
-  var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g;
-
-  /**
-   * Used to match ES6 template delimiters
-   * http://people.mozilla.org/~jorendorff/es6-draft.html#sec-7.8.6
-   */
-  var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
-
-  /** Used to match regexp flags from their coerced string values */
-  var reFlags = /\w*$/;
-
-  /** Used to match "interpolate" template delimiters */
-  var reInterpolate = /<%=([\s\S]+?)%>/g;
-
-  /** Used to ensure capturing order of template delimiters */
-  var reNoMatch = /($^)/;
-
-  /** Used to match HTML characters */
-  var reUnescapedHtml = /[&<>"']/g;
-
-  /** Used to match unescaped characters in compiled string literals */
-  var reUnescapedString = /['\n\r\t\u2028\u2029\\]/g;
-
-  /** Used to make template sourceURLs easier to identify */
-  var templateCounter = 0;
-
-  /** `Object#toString` result shortcuts */
-  var argsClass = '[object Arguments]',
-      arrayClass = '[object Array]',
-      boolClass = '[object Boolean]',
-      dateClass = '[object Date]',
-      errorClass = '[object Error]',
-      funcClass = '[object Function]',
-      numberClass = '[object Number]',
-      objectClass = '[object Object]',
-      regexpClass = '[object RegExp]',
-      stringClass = '[object String]';
-
-  /** Used to determine if values are of the language type Object */
-  var objectTypes = {
-    'boolean': false,
-    'function': true,
-    'object': true,
-    'number': false,
-    'string': false,
-    'undefined': false
-  };
-
-  /** Used to escape characters for inclusion in compiled string literals */
-  var stringEscapes = {
-    '\\': '\\',
-    "'": "'",
-    '\n': 'n',
-    '\r': 'r',
-    '\t': 't',
-    '\u2028': 'u2028',
-    '\u2029': 'u2029'
-  };
-
-  /** Detect free variable `exports` */
-  var freeExports = objectTypes[typeof exports] && exports;
-
-  /** Detect free variable `module` */
-  var freeModule = objectTypes[typeof module] && module && module.exports == freeExports && module;
-
-  /** Detect free variable `global`, from Node.js or Browserified code, and use it as `window` */
-  var freeGlobal = objectTypes[typeof global] && global;
-  if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
-    window = freeGlobal;
-  }
-
-  /*--------------------------------------------------------------------------*/
-
-  /**
-   * A basic implementation of `_.indexOf` without support for binary searches
-   * or `fromIndex` constraints.
-   *
-   * @private
-   * @param {Array} array The array to search.
-   * @param {Mixed} value The value to search for.
-   * @param {Number} [fromIndex=0] The index to search from.
-   * @returns {Number} Returns the index of the matched value or `-1`.
-   */
-  function basicIndexOf(array, value, fromIndex) {
-    var index = (fromIndex || 0) - 1,
-        length = array.length;
-
-    while (++index < length) {
-      if (array[index] === value) {
-        return index;
-      }
-    }
-    return -1;
-  }
-
-  /**
-   * Used by `sortBy` to compare transformed `collection` values, stable sorting
-   * them in ascending order.
-   *
-   * @private
-   * @param {Object} a The object to compare to `b`.
-   * @param {Object} b The object to compare to `a`.
-   * @returns {Number} Returns the sort order indicator of `1` or `-1`.
-   */
-  function compareAscending(a, b) {
-    var ai = a.index,
-        bi = b.index;
-
-    a = a.criteria;
-    b = b.criteria;
-
-    // ensure a stable sort in V8 and other engines
-    // http://code.google.com/p/v8/issues/detail?id=90
-    if (a !== b) {
-      if (a > b || typeof a == 'undefined') {
-        return 1;
-      }
-      if (a < b || typeof b == 'undefined') {
-        return -1;
-      }
-    }
-    return ai < bi ? -1 : 1;
-  }
-
-  /**
-   * Used by `template` to escape characters for inclusion in compiled
-   * string literals.
-   *
-   * @private
-   * @param {String} match The matched character to escape.
-   * @returns {String} Returns the escaped character.
-   */
-  function escapeStringChar(match) {
-    return '\\' + stringEscapes[match];
-  }
-
-  /**
-   * A no-operation function.
-   *
-   * @private
-   */
-  function noop() {
-    // no operation performed
-  }
-
-  /*--------------------------------------------------------------------------*/
-
-  /**
-   * Used for `Array` method references.
-   *
-   * Normally `Array.prototype` would suffice, however, using an array literal
-   * avoids issues in Narwhal.
-   */
-  var arrayRef = [];
-
-  /** Used for native method references */
-  var objectProto = Object.prototype,
-      stringProto = String.prototype;
-
-  /** Used to restore the original `_` reference in `noConflict` */
-  var oldDash = window._;
-
-  /** Used to detect if a method is native */
-  var reNative = RegExp('^' +
-    String(objectProto.valueOf)
-      .replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
-      .replace(/valueOf|for [^\]]+/g, '.+?') + '$'
-  );
-
-  /** Native method shortcuts */
-  var ceil = Math.ceil,
-      clearTimeout = window.clearTimeout,
-      concat = arrayRef.concat,
-      floor = Math.floor,
-      hasOwnProperty = objectProto.hasOwnProperty,
-      push = arrayRef.push,
-      propertyIsEnumerable = objectProto.propertyIsEnumerable,
-      setTimeout = window.setTimeout,
-      toString = objectProto.toString;
-
-  /* Native method shortcuts for methods with the same name as other `lodash` methods */
-  var nativeBind = reNative.test(nativeBind = toString.bind) && nativeBind,
-      nativeCreate = reNative.test(nativeCreate =  Object.create) && nativeCreate,
-      nativeIsArray = reNative.test(nativeIsArray = Array.isArray) && nativeIsArray,
-      nativeIsFinite = window.isFinite,
-      nativeIsNaN = window.isNaN,
-      nativeKeys = reNative.test(nativeKeys = Object.keys) && nativeKeys,
-      nativeMax = Math.max,
-      nativeMin = Math.min,
-      nativeRandom = Math.random,
-      nativeSlice = arrayRef.slice;
-
-  /** Detect various environments */
-  var isIeOpera = reNative.test(window.attachEvent),
-      isV8 = nativeBind && !/\n|true/.test(nativeBind + isIeOpera);
-
-  /*--------------------------------------------------------------------------*/
-
-  /**
-   * Creates a `lodash` object, which wraps the given `value`, to enable method
-   * chaining.
-   *
-   * In addition to Lo-Dash methods, wrappers also have the following `Array` methods:
-   * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`, `splice`,
-   * and `unshift`
-   *
-   * Chaining is supported in custom builds as long as the `value` method is
-   * implicitly or explicitly included in the build.
-   *
-   * The chainable wrapper functions are:
-   * `after`, `assign`, `bind`, `bindAll`, `bindKey`, `chain`, `compact`,
-   * `compose`, `concat`, `countBy`, `createCallback`, `debounce`, `defaults`,
-   * `defer`, `delay`, `difference`, `filter`, `flatten`, `forEach`, `forIn`,
-   * `forOwn`, `functions`, `groupBy`, `initial`, `intersection`, `invert`,
-   * `invoke`, `keys`, `map`, `max`, `memoize`, `merge`, `min`, `object`, `omit`,
-   * `once`, `pairs`, `partial`, `partialRight`, `pick`, `pluck`, `push`, `range`,
-   * `reject`, `rest`, `reverse`, `shuffle`, `slice`, `sort`, `sortBy`, `splice`,
-   * `tap`, `throttle`, `times`, `toArray`, `transform`, `union`, `uniq`, `unshift`,
-   * `unzip`, `values`, `where`, `without`, `wrap`, and `zip`
-   *
-   * The non-chainable wrapper functions are:
-   * `clone`, `cloneDeep`, `contains`, `escape`, `every`, `find`, `has`,
-   * `identity`, `indexOf`, `isArguments`, `isArray`, `isBoolean`, `isDate`,
-   * `isElement`, `isEmpty`, `isEqual`, `isFinite`, `isFunction`, `isNaN`,
-   * `isNull`, `isNumber`, `isObject`, `isPlainObject`, `isRegExp`, `isString`,
-   * `isUndefined`, `join`, `lastIndexOf`, `mixin`, `noConflict`, `parseInt`,
-   * `pop`, `random`, `reduce`, `reduceRight`, `result`, `shift`, `size`, `some`,
-   * `sortedIndex`, `runInContext`, `template`, `unescape`, `uniqueId`, and `value`
-   *
-   * The wrapper functions `first` and `last` return wrapped values when `n` is
-   * passed, otherwise they return unwrapped values.
-   *
-   * @name _
-   * @constructor
-   * @alias chain
-   * @category Chaining
-   * @param {Mixed} value The value to wrap in a `lodash` instance.
-   * @returns {Object} Returns a `lodash` instance.
-   * @example
-   *
-   * var wrapped = _([1, 2, 3]);
-   *
-   * // returns an unwrapped value
-   * wrapped.reduce(function(sum, num) {
-   *   return sum + num;
-   * });
-   * // => 6
-   *
-   * // returns a wrapped value
-   * var squares = wrapped.map(function(num) {
-   *   return num * num;
-   * });
-   *
-   * _.isArray(squares);
-   * // => false
-   *
-   * _.isArray(squares.value());
-   * // => true
-   */
-  function lodash(value) {
-    return (value instanceof lodash)
-      ? value
-      : new lodashWrapper(value);
-  }
-
-  /**
-   * A fast path for creating `lodash` wrapper objects.
-   *
-   * @private
-   * @param {Mixed} value The value to wrap in a `lodash` instance.
-   * @returns {Object} Returns a `lodash` instance.
-   */
-  function lodashWrapper(value) {
-    this.__wrapped__ = value;
-  }
-  // ensure `new lodashWrapper` is an instance of `lodash`
-  lodashWrapper.prototype = lodash.prototype;
-
-  /**
-   * An object used to flag environments features.
-   *
-   * @static
-   * @memberOf _
-   * @type Object
-   */
-  var support = {};
-
-  (function() {
-    var object = { '0': 1, 'length': 1 };
-
-    /**
-     * Detect if `Function#bind` exists and is inferred to be fast (all but V8).
-     *
-     * @memberOf _.support
-     * @type Boolean
-     */
-    support.fastBind = nativeBind && !isV8;
-
-    /**
-     * Detect if `Array#shift` and `Array#splice` augment array-like objects correctly.
-     *
-     * Firefox < 10, IE compatibility mode, and IE < 9 have buggy Array `shift()`
-     * and `splice()` functions that fail to remove the last element, `value[0]`,
-     * of array-like objects even though the `length` property is set to `0`.
-     * The `shift()` method is buggy in IE 8 compatibility mode, while `splice()`
-     * is buggy regardless of mode in IE < 9 and buggy in compatibility mode in IE 9.
-     *
-     * @memberOf _.support
-     * @type Boolean
-     */
-    support.spliceObjects = (arrayRef.splice.call(object, 0, 1), !object[0]);
-  }(1));
-
-  /**
-   * By default, the template delimiters used by Lo-Dash are similar to those in
-   * embedded Ruby (ERB). Change the following template settings to use alternative
-   * delimiters.
-   *
-   * @static
-   * @memberOf _
-   * @type Object
-   */
-  lodash.templateSettings = {
-
-    /**
-     * Used to detect `data` property values to be HTML-escaped.
-     *
-     * @memberOf _.templateSettings
-     * @type RegExp
-     */
-    'escape': /<%-([\s\S]+?)%>/g,
-
-    /**
-     * Used to detect code to be evaluated.
-     *
-     * @memberOf _.templateSettings
-     * @type RegExp
-     */
-    'evaluate': /<%([\s\S]+?)%>/g,
-
-    /**
-     * Used to detect `data` property values to inject.
-     *
-     * @memberOf _.templateSettings
-     * @type RegExp
-     */
-    'interpolate': reInterpolate,
-
-    /**
-     * Used to reference the data object in the template text.
-     *
-     * @memberOf _.templateSettings
-     * @type String
-     */
-    'variable': ''
-  };
-
-  /*--------------------------------------------------------------------------*/
-
-  /**
-   * Creates a function that, when called, invokes `func` with the `this` binding
-   * of `thisArg` and prepends any `partialArgs` to the arguments passed to the
-   * bound function.
-   *
-   * @private
-   * @param {Function|String} func The function to bind or the method name.
-   * @param {Mixed} [thisArg] The `this` binding of `func`.
-   * @param {Array} partialArgs An array of arguments to be partially applied.
-   * @param {Object} [idicator] Used to indicate binding by key or partially
-   *  applying arguments from the right.
-   * @returns {Function} Returns the new bound function.
-   */
-  function createBound(func, thisArg, partialArgs, indicator) {
-    var isFunc = isFunction(func),
-        isPartial = !partialArgs,
-        key = thisArg;
-
-    // juggle arguments
-    if (isPartial) {
-      var rightIndicator = indicator;
-      partialArgs = thisArg;
-    }
-    else if (!isFunc) {
-      if (!indicator) {
-        throw new TypeError;
-      }
-      thisArg = func;
-    }
-
-    function bound() {
-      // `Function#bind` spec
-      // http://es5.github.com/#x15.3.4.5
-      var args = arguments,
-          thisBinding = isPartial ? this : thisArg;
-
-      if (!isFunc) {
-        func = thisArg[key];
-      }
-      if (partialArgs.length) {
-        args = args.length
-          ? (args = nativeSlice.call(args), rightIndicator ? args.concat(partialArgs) : partialArgs.concat(args))
-          : partialArgs;
-      }
-      if (this instanceof bound) {
-        // ensure `new bound` is an instance of `func`
-        thisBinding = createObject(func.prototype);
-
-        // mimic the constructor's `return` behavior
-        // http://es5.github.com/#x13.2.2
-        var result = func.apply(thisBinding, args);
-        return isObject(result) ? result : thisBinding;
-      }
-      return func.apply(thisBinding, args);
-    }
-    return bound;
-  }
-
-  /**
-   * Creates a new object with the specified `prototype`.
-   *
-   * @private
-   * @param {Object} prototype The prototype object.
-   * @returns {Object} Returns the new object.
-   */
-  function createObject(prototype) {
-    return isObject(prototype) ? nativeCreate(prototype) : {};
-  }
-  // fallback for browsers without `Object.create`
-  if  (!nativeCreate) {
-    var createObject = function(prototype) {
-      if (isObject(prototype)) {
-        noop.prototype = prototype;
-        var result = new noop;
-        noop.prototype = null;
-      }
-      return result || {};
-    };
-  }
-
-  /**
-   * Used by `escape` to convert characters to HTML entities.
-   *
-   * @private
-   * @param {String} match The matched character to escape.
-   * @returns {String} Returns the escaped character.
-   */
-  function escapeHtmlChar(match) {
-    return htmlEscapes[match];
-  }
-
-  /**
-   * Gets the appropriate "indexOf" function. If the `_.indexOf` method is
-   * customized, this method returns the custom method, otherwise it returns
-   * the `basicIndexOf` function.
-   *
-   * @private
-   * @returns {Function} Returns the "indexOf" function.
-   */
-  function getIndexOf(array, value, fromIndex) {
-    var result = (result = lodash.indexOf) === indexOf ? basicIndexOf : result;
-    return result;
-  }
-
-  /**
-   * Used by `unescape` to convert HTML entities to characters.
-   *
-   * @private
-   * @param {String} match The matched character to unescape.
-   * @returns {String} Returns the unescaped character.
-   */
-  function unescapeHtmlChar(match) {
-    return htmlUnescapes[match];
-  }
-
-  /*--------------------------------------------------------------------------*/
-
-  /**
-   * Checks if `value` is an `arguments` object.
-   *
-   * @static
-   * @memberOf _
-   * @category Objects
-   * @param {Mixed} value The value to check.
-   * @returns {Boolean} Returns `true`, if the `value` is an `arguments` object, else `false`.
-   * @example
-   *
-   * (function() { return _.isArguments(arguments); })(1, 2, 3);
-   * // => true
-   *
-   * _.isArguments([1, 2, 3]);
-   * // => false
-   */
-  function isArguments(value) {
-    return toString.call(value) == argsClass;
-  }
-  // fallback for browsers that can't detect `arguments` objects by [[Class]]
-  if (!isArguments(arguments)) {
-    isArguments = function(value) {
-      return value ? hasOwnProperty.call(value, 'callee') : false;
-    };
-  }
-
-  /**
-   * Checks if `value` is an array.
-   *
-   * @static
-   * @memberOf _
-   * @category Objects
-   * @param {Mixed} value The value to check.
-   * @returns {Boolean} Returns `true`, if the `value` is an array, else `false`.
-   * @example
-   *
-   * (function() { return _.isArray(arguments); })();
-   * // => false
-   *
-   * _.isArray([1, 2, 3]);
-   * // => true
-   */
-  var isArray = nativeIsArray || function(value) {
-    return value ? (typeof value == 'object' && toString.call(value) == arrayClass) : false;
-  };
-
-  /**
-   * A fallback implementation of `Object.keys` which produces an array of the
-   * given object's own enumerable property names.
-   *
-   * @private
-   * @type Function
-   * @param {Object} object The object to inspect.
-   * @returns {Array} Returns a new array of property names.
-   */
-  var shimKeys = function (object) {
-    var index, iterable = object, result = [];
-    if (!iterable) return result;
-    if (!(objectTypes[typeof object])) return result;  
-      for (index in iterable) {
-        if (hasOwnProperty.call(iterable, index)) {
-          result.push(index);    
-        }
-      }  
-    return result
-  };
-
-  /**
-   * Creates an array composed of the own enumerable property names of `object`.
-   *
-   * @static
-   * @memberOf _
-   * @category Objects
-   * @param {Object} object The object to inspect.
-   * @returns {Array} Returns a new array of property names.
-   * @example
-   *
-   * _.keys({ 'one': 1, 'two': 2, 'three': 3 });
-   * // => ['one', 'two', 'three'] (order is not guaranteed)
-   */
-  var keys = !nativeKeys ? shimKeys : function(object) {
-    if (!isObject(object)) {
-      return [];
-    }
-    return nativeKeys(object);
-  };
-
-  /**
-   * Used to convert characters to HTML entities:
-   *
-   * Though the `>` character is escaped for symmetry, characters like `>` and `/`
-   * don't require escaping in HTML and have no special meaning unless they're part
-   * of a tag or an unquoted attribute value.
-   * http://mathiasbynens.be/notes/ambiguous-ampersands (under "semi-related fun fact")
-   */
-  var htmlEscapes = {
-    '&': '&amp;',
-    '<': '&lt;',
-    '>': '&gt;',
-    '"': '&quot;',
-    "'": '&#39;'
-  };
-
-  /** Used to convert HTML entities to characters */
-  var htmlUnescapes = invert(htmlEscapes);
-
-  /*--------------------------------------------------------------------------*/
-
-  /**
-   * Assigns own enumerable properties of source object(s) to the destination
-   * object. Subsequent sources will overwrite property assignments of previous
-   * sources. If a `callback` function is passed, it will be executed to produce
-   * the assigned values. The `callback` is bound to `thisArg` and invoked with
-   * two arguments; (objectValue, sourceValue).
-   *
-   * @static
-   * @memberOf _
-   * @type Function
-   * @alias extend
-   * @category Objects
-   * @param {Object} object The destination object.
-   * @param {Object} [source1, source2, ...] The source objects.
-   * @param {Function} [callback] The function to customize assigning values.
-   * @param {Mixed} [thisArg] The `this` binding of `callback`.
-   * @returns {Object} Returns the destination object.
-   * @example
-   *
-   * _.assign({ 'name': 'moe' }, { 'age': 40 });
-   * // => { 'name': 'moe', 'age': 40 }
-   *
-   * var defaults = _.partialRight(_.assign, function(a, b) {
-   *   return typeof a == 'undefined' ? b : a;
-   * });
-   *
-   * var food = { 'name': 'apple' };
-   * defaults(food, { 'name': 'banana', 'type': 'fruit' });
-   * // => { 'name': 'apple', 'type': 'fruit' }
-   */
-  function assign(object) {
-    if (!object) {
-      return object;
-    }
-    for (var argsIndex = 1, argsLength = arguments.length; argsIndex < argsLength; argsIndex++) {
-      var iterable = arguments[argsIndex];
-      if (iterable) {
-        for (var key in iterable) {
-          object[key] = iterable[key];
-        }
-      }
-    }
-    return object;
-  }
-
-  /**
-   * Creates a clone of `value`. If `deep` is `true`, nested objects will also
-   * be cloned, otherwise they will be assigned by reference. If a `callback`
-   * function is passed, it will be executed to produce the cloned values. If
-   * `callback` returns `undefined`, cloning will be handled by the method instead.
-   * The `callback` is bound to `thisArg` and invoked with one argument; (value).
-   *
-   * @static
-   * @memberOf _
-   * @category Objects
-   * @param {Mixed} value The value to clone.
-   * @param {Boolean} [deep=false] A flag to indicate a deep clone.
-   * @param {Function} [callback] The function to customize cloning values.
-   * @param {Mixed} [thisArg] The `this` binding of `callback`.
-   * @param- {Array} [stackA=[]] Tracks traversed source objects.
-   * @param- {Array} [stackB=[]] Associates clones with source counterparts.
-   * @returns {Mixed} Returns the cloned `value`.
-   * @example
-   *
-   * var stooges = [
-   *   { 'name': 'moe', 'age': 40 },
-   *   { 'name': 'larry', 'age': 50 }
-   * ];
-   *
-   * var shallow = _.clone(stooges);
-   * shallow[0] === stooges[0];
-   * // => true
-   *
-   * var deep = _.clone(stooges, true);
-   * deep[0] === stooges[0];
-   * // => false
-   *
-   * _.mixin({
-   *   'clone': _.partialRight(_.clone, function(value) {
-   *     return _.isElement(value) ? value.cloneNode(false) : undefined;
-   *   })
-   * });
-   *
-   * var clone = _.clone(document.body);
-   * clone.childNodes.length;
-   * // => 0
-   */
-  function clone(value) {
-    return isObject(value)
-      ? (isArray(value) ? nativeSlice.call(value) : assign({}, value))
-      : value;
-  }
-
-  /**
-   * Assigns own enumerable properties of source object(s) to the destination
-   * object for all destination properties that resolve to `undefined`. Once a
-   * property is set, additional defaults of the same property will be ignored.
-   *
-   * @static
-   * @memberOf _
-   * @type Function
-   * @category Objects
-   * @param {Object} object The destination object.
-   * @param {Object} [source1, source2, ...] The source objects.
-   * @param- {Object} [guard] Allows working with `_.reduce` without using its
-   *  callback's `key` and `object` arguments as sources.
-   * @returns {Object} Returns the destination object.
-   * @example
-   *
-   * var food = { 'name': 'apple' };
-   * _.defaults(food, { 'name': 'banana', 'type': 'fruit' });
-   * // => { 'name': 'apple', 'type': 'fruit' }
-   */
-  function defaults(object) {
-    if (!object) {
-      return object;
-    }
-    for (var argsIndex = 1, argsLength = arguments.length; argsIndex < argsLength; argsIndex++) {
-      var iterable = arguments[argsIndex];
-      if (iterable) {
-        for (var key in iterable) {
-          if (object[key] == null) {
-            object[key] = iterable[key];
-          }
-        }
-      }
-    }
-    return object;
-  }
-
-  /**
-   * Iterates over `object`'s own and inherited enumerable properties, executing
-   * the `callback` for each property. The `callback` is bound to `thisArg` and
-   * invoked with three arguments; (value, key, object). Callbacks may exit iteration
-   * early by explicitly returning `false`.
-   *
-   * @static
-   * @memberOf _
-   * @type Function
-   * @category Objects
-   * @param {Object} object The object to iterate over.
-   * @param {Function} [callback=identity] The function called per iteration.
-   * @param {Mixed} [thisArg] The `this` binding of `callback`.
-   * @returns {Object} Returns `object`.
-   * @example
-   *
-   * function Dog(name) {
-   *   this.name = name;
-   * }
-   *
-   * Dog.prototype.bark = function() {
-   *   alert('Woof, woof!');
-   * };
-   *
-   * _.forIn(new Dog('Dagny'), function(value, key) {
-   *   alert(key);
-   * });
-   * // => alerts 'name' and 'bark' (order is not guaranteed)
-   */
-  var forIn = function (collection, callback) {
-    var index, iterable = collection, result = iterable;
-    if (!iterable) return result;
-    if (!objectTypes[typeof iterable]) return result;
-      for (index in iterable) {
-        if (callback(iterable[index], index, collection) === indicatorObject) return result;    
-      }  
-    return result
-  };
-
-  /**
-   * Iterates over an object's own enumerable properties, executing the `callback`
-   * for each property. The `callback` is bound to `thisArg` and invoked with three
-   * arguments; (value, key, object). Callbacks may exit iteration early by explicitly
-   * returning `false`.
-   *
-   * @static
-   * @memberOf _
-   * @type Function
-   * @category Objects
-   * @param {Object} object The object to iterate over.
-   * @param {Function} [callback=identity] The function called per iteration.
-   * @param {Mixed} [thisArg] The `this` binding of `callback`.
-   * @returns {Object} Returns `object`.
-   * @example
-   *
-   * _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) {
-   *   alert(key);
-   * });
-   * // => alerts '0', '1', and 'length' (order is not guaranteed)
-   */
-  var forOwn = function (collection, callback) {
-    var index, iterable = collection, result = iterable;
-    if (!iterable) return result;
-    if (!objectTypes[typeof iterable]) return result;
-      for (index in iterable) {
-        if (hasOwnProperty.call(iterable, index)) {
-          if (callback(iterable[index], index, collection) === indicatorObject) return result;    
-        }
-      }  
-    return result
-  };
-
-  /**
-   * Creates a sorted array of all enumerable properties, own and inherited,
-   * of `object` that have function values.
-   *
-   * @static
-   * @memberOf _
-   * @alias methods
-   * @category Objects
-   * @param {Object} object The object to inspect.
-   * @returns {Array} Returns a new array of property names that have function values.
-   * @example
-   *
-   * _.functions(_);
-   * // => ['all', 'any', 'bind', 'bindAll', 'clone', 'compact', 'compose', ...]
-   */
-  function functions(object) {
-    var result = [];
-    forIn(object, function(value, key) {
-      if (isFunction(value)) {
-        result.push(key);
-      }
-    });
-    return result.sort();
-  }
-
-  /**
-   * Checks if the specified object `property` exists and is a direct property,
-   * instead of an inherited property.
-   *
-   * @static
-   * @memberOf _
-   * @category Objects
-   * @param {Object} object The object to check.
-   * @param {String} property The property to check for.
-   * @returns {Boolean} Returns `true` if key is a direct property, else `false`.
-   * @example
-   *
-   * _.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b');
-   * // => true
-   */
-  function has(object, property) {
-    return object ? hasOwnProperty.call(object, property) : false;
-  }
-
-  /**
-   * Creates an object composed of the inverted keys and values of the given `object`.
-   *
-   * @static
-   * @memberOf _
-   * @category Objects
-   * @param {Object} object The object to invert.
-   * @returns {Object} Returns the created inverted object.
-   * @example
-   *
-   *  _.invert({ 'first': 'moe', 'second': 'larry' });
-   * // => { 'moe': 'first', 'larry': 'second' }
-   */
-  function invert(object) {
-    var index = -1,
-        props = keys(object),
-        length = props.length,
-        result = {};
-
-    while (++index < length) {
-      var key = props[index];
-      result[object[key]] = key;
-    }
-    return result;
-  }
-
-  /**
-   * Checks if `value` is a boolean value.
-   *
-   * @static
-   * @memberOf _
-   * @category Objects
-   * @param {Mixed} value The value to check.
-   * @returns {Boolean} Returns `true`, if the `value` is a boolean value, else `false`.
-   * @example
-   *
-   * _.isBoolean(null);
-   * // => false
-   */
-  function isBoolean(value) {
-    return value === true || value === false || toString.call(value) == boolClass;
-  }
-
-  /**
-   * Checks if `value` is a date.
-   *
-   * @static
-   * @memberOf _
-   * @category Objects
-   * @param {Mixed} value The value to check.
-   * @returns {Boolean} Returns `true`, if the `value` is a date, else `false`.
-   * @example
-   *
-   * _.isDate(new Date);
-   * // => true
-   */
-  function isDate(value) {
-    return value ? (typeof value == 'object' && toString.call(value) == dateClass) : false;
-  }
-
-  /**
-   * Checks if `value` is a DOM element.
-   *
-   * @static
-   * @memberOf _
-   * @category Objects
-   * @param {Mixed} value The value to check.
-   * @returns {Boolean} Returns `true`, if the `value` is a DOM element, else `false`.
-   * @example
-   *
-   * _.isElement(document.body);
-   * // => true
-   */
-  function isElement(value) {
-    return value ? value.nodeType === 1 : false;
-  }
-
-  /**
-   * Checks if `value` is empty. Arrays, strings, or `arguments` objects with a
-   * length of `0` and objects with no own enumerable properties are considered
-   * "empty".
-   *
-   * @static
-   * @memberOf _
-   * @category Objects
-   * @param {Array|Object|String} value The value to inspect.
-   * @returns {Boolean} Returns `true`, if the `value` is empty, else `false`.
-   * @example
-   *
-   * _.isEmpty([1, 2, 3]);
-   * // => false
-   *
-   * _.isEmpty({});
-   * // => true
-   *
-   * _.isEmpty('');
-   * // => true
-   */
-  function isEmpty(value) {
-    if (!value) {
-      return true;
-    }
-    if (isArray(value) || isString(value)) {
-      return !value.length;
-    }
-    for (var key in value) {
-      if (hasOwnProperty.call(value, key)) {
-        return false;
-      }
-    }
-    return true;
-  }
-
-  /**
-   * Performs a deep comparison between two values to determine if they are
-   * equivalent to each other. If `callback` is passed, it will be executed to
-   * compare values. If `callback` returns `undefined`, comparisons will be handled
-   * by the method instead. The `callback` is bound to `thisArg` and invoked with
-   * two arguments; (a, b).
-   *
-   * @static
-   * @memberOf _
-   * @category Objects
-   * @param {Mixed} a The value to compare.
-   * @param {Mixed} b The other value to compare.
-   * @param {Function} [callback] The function to customize comparing values.
-   * @param {Mixed} [thisArg] The `this` binding of `callback`.
-   * @param- {Array} [stackA=[]] Tracks traversed `a` objects.
-   * @param- {Array} [stackB=[]] Tracks traversed `b` objects.
-   * @returns {Boolean} Returns `true`, if the values are equivalent, else `false`.
-   * @example
-   *
-   * var moe = { 'name': 'moe', 'age': 40 };
-   * var copy = { 'name': 'moe', 'age': 40 };
-   *
-   * moe == copy;
-   * // => false
-   *
-   * _.isEqual(moe, copy);
-   * // => true
-   *
-   * var words = ['hello', 'goodbye'];
-   * var otherWords = ['hi', 'goodbye'];
-   *
-   * _.isEqual(words, otherWords, function(a, b) {
-   *   var reGreet = /^(?:hello|hi)$/i,
-   *       aGreet = _.isString(a) && reGreet.test(a),
-   *       bGreet = _.isString(b) && reGreet.test(b);
-   *
-   *   return (aGreet || bGreet) ? (aGreet == bGreet) : undefined;
-   * });
-   * // => true
-   */
-  function isEqual(a, b, stackA, stackB) {
-    if (a === b) {
-      return a !== 0 || (1 / a == 1 / b);
-    }
-    var type = typeof a,
-        otherType = typeof b;
-
-    if (a === a &&
-        (!a || (type != 'function' && type != 'object')) &&
-        (!b || (otherType != 'function' && otherType != 'object'))) {
-      return false;
-    }
-    if (a == null || b == null) {
-      return a === b;
-    }
-    var className = toString.call(a),
-        otherClass = toString.call(b);
-
-    if (className != otherClass) {
-      return false;
-    }
-    switch (className) {
-      case boolClass:
-      case dateClass:
-        return +a == +b;
-
-      case numberClass:
-        return a != +a
-          ? b != +b
-          : (a == 0 ? (1 / a == 1 / b) : a == +b);
-
-      case regexpClass:
-      case stringClass:
-        return a == String(b);
-    }
-    var isArr = className == arrayClass;
-    if (!isArr) {
-      if (a instanceof lodash || b instanceof lodash) {
-        return isEqual(a.__wrapped__ || a, b.__wrapped__ || b, stackA, stackB);
-      }
-      if (className != objectClass) {
-        return false;
-      }
-      var ctorA = a.constructor,
-          ctorB = b.constructor;
-
-      if (ctorA != ctorB && !(
-            isFunction(ctorA) && ctorA instanceof ctorA &&
-            isFunction(ctorB) && ctorB instanceof ctorB
-          )) {
-        return false;
-      }
-    }
-    stackA || (stackA = []);
-    stackB || (stackB = []);
-
-    var length = stackA.length;
-    while (length--) {
-      if (stackA[length] == a) {
-        return stackB[length] == b;
-      }
-    }
-    var result = true,
-        size = 0;
-
-    stackA.push(a);
-    stackB.push(b);
-
-    if (isArr) {
-      size = b.length;
-      result = size == a.length;
-
-      if (result) {
-        while (size--) {
-          if (!(result = isEqual(a[size], b[size], stackA, stackB))) {
-            break;
-          }
-        }
-      }
-      return result;
-    }
-    forIn(b, function(value, key, b) {
-      if (hasOwnProperty.call(b, key)) {
-        size++;
-        return !(result = hasOwnProperty.call(a, key) && isEqual(a[key], value, stackA, stackB)) && indicatorObject;
-      }
-    });
-
-    if (result) {
-      forIn(a, function(value, key, a) {
-        if (hasOwnProperty.call(a, key)) {
-          return !(result = --size > -1) && indicatorObject;
-        }
-      });
-    }
-    return result;
-  }
-
-  /**
-   * Checks if `value` is, or can be coerced to, a finite number.
-   *
-   * Note: This is not the same as native `isFinite`, which will return true for
-   * booleans and empty strings. See http://es5.github.com/#x15.1.2.5.
-   *
-   * @static
-   * @memberOf _
-   * @category Objects
-   * @param {Mixed} value The value to check.
-   * @returns {Boolean} Returns `true`, if the `value` is finite, else `false`.
-   * @example
-   *
-   * _.isFinite(-101);
-   * // => true
-   *
-   * _.isFinite('10');
-   * // => true
-   *
-   * _.isFinite(true);
-   * // => false
-   *
-   * _.isFinite('');
-   * // => false
-   *
-   * _.isFinite(Infinity);
-   * // => false
-   */
-  function isFinite(value) {
-    return nativeIsFinite(value) && !nativeIsNaN(parseFloat(value));
-  }
-
-  /**
-   * Checks if `value` is a function.
-   *
-   * @static
-   * @memberOf _
-   * @category Objects
-   * @param {Mixed} value The value to check.
-   * @returns {Boolean} Returns `true`, if the `value` is a function, else `false`.
-   * @example
-   *
-   * _.isFunction(_);
-   * // => true
-   */
-  function isFunction(value) {
-    return typeof value == 'function';
-  }
-  // fallback for older versions of Chrome and Safari
-  if (isFunction(/x/)) {
-    isFunction = function(value) {
-      return typeof value == 'function' && toString.call(value) == funcClass;
-    };
-  }
-
-  /**
-   * Checks if `value` is the language type of Object.
-   * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
-   *
-   * @static
-   * @memberOf _
-   * @category Objects
-   * @param {Mixed} value The value to check.
-   * @returns {Boolean} Returns `true`, if the `value` is an object, else `false`.
-   * @example
-   *
-   * _.isObject({});
-   * // => true
-   *
-   * _.isObject([1, 2, 3]);
-   * // => true
-   *
-   * _.isObject(1);
-   * // => false
-   */
-  function isObject(value) {
-    // check if the value is the ECMAScript language type of Object
-    // http://es5.github.com/#x8
-    // and avoid a V8 bug
-    // http://code.google.com/p/v8/issues/detail?id=2291
-    return !!(value && objectTypes[typeof value]);
-  }
-
-  /**
-   * Checks if `value` is `NaN`.
-   *
-   * Note: This is not the same as native `isNaN`, which will return `true` for
-   * `undefined` and other values. See http://es5.github.com/#x15.1.2.4.
-   *
-   * @static
-   * @memberOf _
-   * @category Objects
-   * @param {Mixed} value The value to check.
-   * @returns {Boolean} Returns `true`, if the `value` is `NaN`, else `false`.
-   * @example
-   *
-   * _.isNaN(NaN);
-   * // => true
-   *
-   * _.isNaN(new Number(NaN));
-   * // => true
-   *
-   * isNaN(undefined);
-   * // => true
-   *
-   * _.isNaN(undefined);
-   * // => false
-   */
-  function isNaN(value) {
-    // `NaN` as a primitive is the only value that is not equal to itself
-    // (perform the [[Class]] check first to avoid errors with some host objects in IE)
-    return isNumber(value) && value != +value
-  }
-
-  /**
-   * Checks if `value` is `null`.
-   *
-   * @static
-   * @memberOf _
-   * @category Objects
-   * @param {Mixed} value The value to check.
-   * @returns {Boolean} Returns `true`, if the `value` is `null`, else `false`.
-   * @example
-   *
-   * _.isNull(null);
-   * // => true
-   *
-   * _.isNull(undefined);
-   * // => false
-   */
-  function isNull(value) {
-    return value === null;
-  }
-
-  /**
-   * Checks if `value` is a number.
-   *
-   * @static
-   * @memberOf _
-   * @category Objects
-   * @param {Mixed} value The value to check.
-   * @returns {Boolean} Returns `true`, if the `value` is a number, else `false`.
-   * @example
-   *
-   * _.isNumber(8.4 * 5);
-   * // => true
-   */
-  function isNumber(value) {
-    return typeof value == 'number' || toString.call(value) == numberClass;
-  }
-
-  /**
-   * Checks if `value` is a regular expression.
-   *
-   * @static
-   * @memberOf _
-   * @category Objects
-   * @param {Mixed} value The value to check.
-   * @returns {Boolean} Returns `true`, if the `value` is a regular expression, else `false`.
-   * @example
-   *
-   * _.isRegExp(/moe/);
-   * // => true
-   */
-  function isRegExp(value) {
-    return !!(value && objectTypes[typeof value]) && toString.call(value) == regexpClass;
-  }
-
-  /**
-   * Checks if `value` is a string.
-   *
-   * @static
-   * @memberOf _
-   * @category Objects
-   * @param {Mixed} value The value to check.
-   * @returns {Boolean} Returns `true`, if the `value` is a string, else `false`.
-   * @example
-   *
-   * _.isString('moe');
-   * // => true
-   */
-  function isString(value) {
-    return typeof value == 'string' || toString.call(value) == stringClass;
-  }
-
-  /**
-   * Checks if `value` is `undefined`.
-   *
-   * @static
-   * @memberOf _
-   * @category Objects
-   * @param {Mixed} value The value to check.
-   * @returns {Boolean} Returns `true`, if the `value` is `undefined`, else `false`.
-   * @example
-   *
-   * _.isUndefined(void 0);
-   * // => true
-   */
-  function isUndefined(value) {
-    return typeof value == 'undefined';
-  }
-
-  /**
-   * Creates a shallow clone of `object` excluding the specified properties.
-   * Property names may be specified as individual arguments or as arrays of
-   * property names. If a `callback` function is passed, it will be executed
-   * for each property in the `object`, omitting the properties `callback`
-   * returns truthy for. The `callback` is bound to `thisArg` and invoked
-   * with three arguments; (value, key, object).
-   *
-   * @static
-   * @memberOf _
-   * @category Objects
-   * @param {Object} object The source object.
-   * @param {Function|String} callback|[prop1, prop2, ...] The properties to omit
-   *  or the function called per iteration.
-   * @param {Mixed} [thisArg] The `this` binding of `callback`.
-   * @returns {Object} Returns an object without the omitted properties.
-   * @example
-   *
-   * _.omit({ 'name': 'moe', 'age': 40 }, 'age');
-   * // => { 'name': 'moe' }
-   *
-   * _.omit({ 'name': 'moe', 'age': 40 }, function(value) {
-   *   return typeof value == 'number';
-   * });
-   * // => { 'name': 'moe' }
-   */
-  function omit(object) {
-    var indexOf = getIndexOf(),
-        props = concat.apply(arrayRef, nativeSlice.call(arguments, 1)),
-        result = {};
-
-    forIn(object, function(value, key) {
-      if (indexOf(props, key) < 0) {
-        result[key] = value;
-      }
-    });
-    return result;
-  }
-
-  /**
-   * Creates a two dimensional array of the given object's key-value pairs,
-   * i.e. `[[key1, value1], [key2, value2]]`.
-   *
-   * @static
-   * @memberOf _
-   * @category Objects
-   * @param {Object} object The object to inspect.
-   * @returns {Array} Returns new array of key-value pairs.
-   * @example
-   *
-   * _.pairs({ 'moe': 30, 'larry': 40 });
-   * // => [['moe', 30], ['larry', 40]] (order is not guaranteed)
-   */
-  function pairs(object) {
-    var index = -1,
-        props = keys(object),
-        length = props.length,
-        result = Array(length);
-
-    while (++index < length) {
-      var key = props[index];
-      result[index] = [key, object[key]];
-    }
-    return result;
-  }
-
-  /**
-   * Creates a shallow clone of `object` composed of the specified properties.
-   * Property names may be specified as individual arguments or as arrays of property
-   * names. If `callback` is passed, it will be executed for each property in the
-   * `object`, picking the properties `callback` returns truthy for. The `callback`
-   * is bound to `thisArg` and invoked with three arguments; (value, key, object).
-   *
-   * @static
-   * @memberOf _
-   * @category Objects
-   * @param {Object} object The source object.
-   * @param {Array|Function|String} callback|[prop1, prop2, ...] The function called
-   *  per iteration or properties to pick, either as individual arguments or arrays.
-   * @param {Mixed} [thisArg] The `this` binding of `callback`.
-   * @returns {Object} Returns an object composed of the picked properties.
-   * @example
-   *
-   * _.pick({ 'name': 'moe', '_userid': 'moe1' }, 'name');
-   * // => { 'name': 'moe' }
-   *
-   * _.pick({ 'name': 'moe', '_userid': 'moe1' }, function(value, key) {
-   *   return key.charAt(0) != '_';
-   * });
-   * // => { 'name': 'moe' }
-   */
-  function pick(object) {
-    var index = -1,
-        props = concat.apply(arrayRef, nativeSlice.call(arguments, 1)),
-        length = props.length,
-        result = {};
-
-    while (++index < length) {
-      var prop = props[index];
-      if (prop in object) {
-        result[prop] = object[prop];
-      }
-    }
-    return result;
-  }
-
-  /**
-   * Creates an array composed of the own enumerable property values of `object`.
-   *
-   * @static
-   * @memberOf _
-   * @category Objects
-   * @param {Object} object The object to inspect.
-   * @returns {Array} Returns a new array of property values.
-   * @example
-   *
-   * _.values({ 'one': 1, 'two': 2, 'three': 3 });
-   * // => [1, 2, 3] (order is not guaranteed)
-   */
-  function values(object) {
-    var index = -1,
-        props = keys(object),
-        length = props.length,
-        result = Array(length);
-
-    while (++index < length) {
-      result[index] = object[props[index]];
-    }
-    return result;
-  }
-
-  /*--------------------------------------------------------------------------*/
-
-  /**
-   * Checks if a given `target` element is present in a `collection` using strict
-   * equality for comparisons, i.e. `===`. If `fromIndex` is negative, it is used
-   * as the offset from the end of the collection.
-   *
-   * @static
-   * @memberOf _
-   * @alias include
-   * @category Collections
-   * @param {Array|Object|String} collection The collection to iterate over.
-   * @param {Mixed} target The value to check for.
-   * @param {Number} [fromIndex=0] The index to search from.
-   * @returns {Boolean} Returns `true` if the `target` element is found, else `false`.
-   * @example
-   *
-   * _.contains([1, 2, 3], 1);
-   * // => true
-   *
-   * _.contains([1, 2, 3], 1, 2);
-   * // => false
-   *
-   * _.contains({ 'name': 'moe', 'age': 40 }, 'moe');
-   * // => true
-   *
-   * _.contains('curly', 'ur');
-   * // => true
-   */
-  function contains(collection, target) {
-    var indexOf = getIndexOf(),
-        length = collection ? collection.length : 0,
-        result = false;
-    if (length && typeof length == 'number') {
-      result = indexOf(collection, target) > -1;
-    } else {
-      forOwn(collection, function(value) {
-        return (result = value === target) && indicatorObject;
-      });
-    }
-    return result;
-  }
-
-  /**
-   * Creates an object composed of keys returned from running each element of the
-   * `collection` through the given `callback`. The corresponding value of each key
-   * is the number of times the key was returned by the `callback`. The `callback`
-   * is bound to `thisArg` and invoked with three arguments; (value, index|key, collection).
-   *
-   * If a property name is passed for `callback`, the created "_.pluck" style
-   * callback will return the property value of the given element.
-   *
-   * If an object is passed for `callback`, the created "_.where" style callback
-   * will return `true` for elements that have the properties of the given object,
-   * else `false`.
-   *
-   * @static
-   * @memberOf _
-   * @category Collections
-   * @param {Array|Object|String} collection The collection to iterate over.
-   * @param {Function|Object|String} [callback=identity] The function called per
-   *  iteration. If a property name or object is passed, it will be used to create
-   *  a "_.pluck" or "_.where" style callback, respectively.
-   * @param {Mixed} [thisArg] The `this` binding of `callback`.
-   * @returns {Object} Returns the composed aggregate object.
-   * @example
-   *
-   * _.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); });
-   * // => { '4': 1, '6': 2 }
-   *
-   * _.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, Math);
-   * // => { '4': 1, '6': 2 }
-   *
-   * _.countBy(['one', 'two', 'three'], 'length');
-   * // => { '3': 2, '5': 1 }
-   */
-  function countBy(collection, callback, thisArg) {
-    var result = {};
-    callback = createCallback(callback, thisArg);
-
-    forEach(collection, function(value, key, collection) {
-      key = String(callback(value, key, collection));
-      (hasOwnProperty.call(result, key) ? result[key]++ : result[key] = 1);
-    });
-    return result;
-  }
-
-  /**
-   * Checks if the `callback` returns a truthy value for **all** elements of a
-   * `collection`. The `callback` is bound to `thisArg` and invoked with three
-   * arguments; (value, index|key, collection).
-   *
-   * If a property name is passed for `callback`, the created "_.pluck" style
-   * callback will return the property value of the given element.
-   *
-   * If an object is passed for `callback`, the created "_.where" style callback
-   * will return `true` for elements that have the properties of the given object,
-   * else `false`.
-   *
-   * @static
-   * @memberOf _
-   * @alias all
-   * @category Collections
-   * @param {Array|Object|String} collection The collection to iterate over.
-   * @param {Function|Object|String} [callback=identity] The function called per
-   *  iteration. If a property name or object is passed, it will be used to create
-   *  a "_.pluck" or "_.where" style callback, respectively.
-   * @param {Mixed} [thisArg] The `this` binding of `callback`.
-   * @returns {Boolean} Returns `true` if all elements pass the callback check,
-   *  else `false`.
-   * @example
-   *
-   * _.every([true, 1, null, 'yes'], Boolean);
-   * // => false
-   *
-   * var stooges = [
-   *   { 'name': 'moe', 'age': 40 },
-   *   { 'name': 'larry', 'age': 50 }
-   * ];
-   *
-   * // using "_.pluck" callback shorthand
-   * _.every(stooges, 'age');
-   * // => true
-   *
-   * // using "_.where" callback shorthand
-   * _.every(stooges, { 'age': 50 });
-   * // => false
-   */
-  function every(collection, callback, thisArg) {
-    var result = true;
-    callback = createCallback(callback, thisArg);
-
-    var index = -1,
-        length = collection ? collection.length : 0;
-
-    if (typeof length == 'number') {
-      while (++index < length) {
-        if (!(result = !!callback(collection[index], index, collection))) {
-          break;
-        }
-      }
-    } else {
-      forOwn(collection, function(value, index, collection) {
-        return !(result = !!callback(value, index, collection)) && indicatorObject;
-      });
-    }
-    return result;
-  }
-
-  /**
-   * Examines each element in a `collection`, returning an array of all elements
-   * the `callback` returns truthy for. The `callback` is bound to `thisArg` and
-   * invoked with three arguments; (value, index|key, collection).
-   *
-   * If a property name is passed for `callback`, the created "_.pluck" style
-   * callback will return the property value of the given element.
-   *
-   * If an object is passed for `callback`, the created "_.where" style callback
-   * will return `true` for elements that have the properties of the given object,
-   * else `false`.
-   *
-   * @static
-   * @memberOf _
-   * @alias select
-   * @category Collections
-   * @param {Array|Object|String} collection The collection to iterate over.
-   * @param {Function|Object|String} [callback=identity] The function called per
-   *  iteration. If a property name or object is passed, it will be used to create
-   *  a "_.pluck" or "_.where" style callback, respectively.
-   * @param {Mixed} [thisArg] The `this` binding of `callback`.
-   * @returns {Array} Returns a new array of elements that passed the callback check.
-   * @example
-   *
-   * var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
-   * // => [2, 4, 6]
-   *
-   * var food = [
-   *   { 'name': 'apple',  'organic': false, 'type': 'fruit' },
-   *   { 'name': 'carrot', 'organic': true,  'type': 'vegetable' }
-   * ];
-   *
-   * // using "_.pluck" callback shorthand
-   * _.filter(food, 'organic');
-   * // => [{ 'name': 'carrot', 'organic': true, 'type': 'vegetable' }]
-   *
-   * // using "_.where" callback shorthand
-   * _.filter(food, { 'type': 'fruit' });
-   * // => [{ 'name': 'apple', 'organic': false, 'type': 'fruit' }]
-   */
-  function filter(collection, callback, thisArg) {
-    var result = [];
-    callback = createCallback(callback, thisArg);
-
-    var index = -1,
-        length = collection ? collection.length : 0;
-
-    if (typeof length == 'number') {
-      while (++index < length) {
-        var value = collection[index];
-        if (callback(value, index, collection)) {
-          result.push(value);
-        }
-      }
-    } else {
-      forOwn(collection, function(value, index, collection) {
-        if (callback(value, index, collection)) {
-          result.push(value);
-        }
-      });
-    }
-    return result;
-  }
-
-  /**
-   * Examines each element in a `collection`, returning the first that the `callback`
-   * returns truthy for. The `callback` is bound to `thisArg` and invoked with three
-   * arguments; (value, index|key, collection).
-   *
-   * If a property name is passed for `callback`, the created "_.pluck" style
-   * callback will return the property value of the given element.
-   *
-   * If an object is passed for `callback`, the created "_.where" style callback
-   * will return `true` for elements that have the properties of the given object,
-   * else `false`.
-   *
-   * @static
-   * @memberOf _
-   * @alias detect, findWhere
-   * @category Collections
-   * @param {Array|Object|String} collection The collection to iterate over.
-   * @param {Function|Object|String} [callback=identity] The function called per
-   *  iteration. If a property name or object is passed, it will be used to create
-   *  a "_.pluck" or "_.where" style callback, respectively.
-   * @param {Mixed} [thisArg] The `this` binding of `callback`.
-   * @returns {Mixed} Returns the found element, else `undefined`.
-   * @example
-   *
-   * _.find([1, 2, 3, 4], function(num) {
-   *   return num % 2 == 0;
-   * });
-   * // => 2
-   *
-   * var food = [
-   *   { 'name': 'apple',  'organic': false, 'type': 'fruit' },
-   *   { 'name': 'banana', 'organic': true,  'type': 'fruit' },
-   *   { 'name': 'beet',   'organic': false, 'type': 'vegetable' }
-   * ];
-   *
-   * // using "_.where" callback shorthand
-   * _.find(food, { 'type': 'vegetable' });
-   * // => { 'name': 'beet', 'organic': false, 'type': 'vegetable' }
-   *
-   * // using "_.pluck" callback shorthand
-   * _.find(food, 'organic');
-   * // => { 'name': 'banana', 'organic': true, 'type': 'fruit' }
-   */
-  function find(collection, callback, thisArg) {
-    callback = createCallback(callback, thisArg);
-
-    var index = -1,
-        length = collection ? collection.length : 0;
-
-    if (typeof length == 'number') {
-      while (++index < length) {
-        var value = collection[index];
-        if (callback(value, index, collection)) {
-          return value;
-        }
-      }
-    } else {
-      var result;
-      forOwn(collection, function(value, index, collection) {
-        if (callback(value, index, collection)) {
-          result = value;
-          return indicatorObject;
-        }
-      });
-      return result;
-    }
-  }
-
-  /**
-   * Examines each element in a `collection`, returning the first that
-   * has the given `properties`. When checking `properties`, this method
-   * performs a deep comparison between values to determine if they are
-   * equivalent to each other.
-   *
-   * @static
-   * @memberOf _
-   * @category Collections
-   * @param {Array|Object|String} collection The collection to iterate over.
-   * @param {Object} properties The object of property values to filter by.
-   * @returns {Mixed} Returns the found element, else `undefined`.
-   * @example
-   *
-   * var food = [
-   *   { 'name': 'apple',  'organic': false, 'type': 'fruit' },
-   *   { 'name': 'banana', 'organic': true,  'type': 'fruit' },
-   *   { 'name': 'beet',   'organic': false, 'type': 'vegetable' }
-   * ];
-   *
-   * _.findWhere(food, { 'type': 'vegetable' });
-   * // => { 'name': 'beet', 'organic': false, 'type': 'vegetable' }
-   */
-  function findWhere(object, properties) {
-    return where(object, properties, true);
-  }
-
-  /**
-   * Iterates over a `collection`, executing the `callback` for each element in
-   * the `collection`. The `callback` is bound to `thisArg` and invoked with three
-   * arguments; (value, index|key, collection). Callbacks may exit iteration early
-   * by explicitly returning `false`.
-   *
-   * @static
-   * @memberOf _
-   * @alias each
-   * @category Collections
-   * @param {Array|Object|String} collection The collection to iterate over.
-   * @param {Function} [callback=identity] The function called per iteration.
-   * @param {Mixed} [thisArg] The `this` binding of `callback`.
-   * @returns {Array|Object|String} Returns `collection`.
-   * @example
-   *
-   * _([1, 2, 3]).forEach(alert).join(',');
-   * // => alerts each number and returns '1,2,3'
-   *
-   * _.forEach({ 'one': 1, 'two': 2, 'three': 3 }, alert);
-   * // => alerts each number value (order is not guaranteed)
-   */
-  function forEach(collection, callback, thisArg) {
-    var index = -1,
-        length = collection ? collection.length : 0;
-
-    callback = callback && typeof thisArg == 'undefined' ? callback : createCallback(callback, thisArg);
-    if (typeof length == 'number') {
-      while (++index < length) {
-        if (callback(collection[index], index, collection) === indicatorObject) {
-          break;
-        }
-      }
-    } else {
-      forOwn(collection, callback);
-    };
-  }
-
-  /**
-   * Creates an object composed of keys returned from running each element of the
-   * `collection` through the `callback`. The corresponding value of each key is
-   * an array of elements passed to `callback` that returned the key. The `callback`
-   * is bound to `thisArg` and invoked with three arguments; (value, index|key, collection).
-   *
-   * If a property name is passed for `callback`, the created "_.pluck" style
-   * callback will return the property value of the given element.
-   *
-   * If an object is passed for `callback`, the created "_.where" style callback
-   * will return `true` for elements that have the properties of the given object,
-   * else `false`
-   *
-   * @static
-   * @memberOf _
-   * @category Collections
-   * @param {Array|Object|String} collection The collection to iterate over.
-   * @param {Function|Object|String} [callback=identity] The function called per
-   *  iteration. If a property name or object is passed, it will be used to create
-   *  a "_.pluck" or "_.where" style callback, respectively.
-   * @param {Mixed} [thisArg] The `this` binding of `callback`.
-   * @returns {Object} Returns the composed aggregate object.
-   * @example
-   *
-   * _.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num); });
-   * // => { '4': [4.2], '6': [6.1, 6.4] }
-   *
-   * _.groupBy([4.2, 6.1, 6.4], function(num) { return this.floor(num); }, Math);
-   * // => { '4': [4.2], '6': [6.1, 6.4] }
-   *
-   * // using "_.pluck" callback shorthand
-   * _.groupBy(['one', 'two', 'three'], 'length');
-   * // => { '3': ['one', 'two'], '5': ['three'] }
-   */
-  function groupBy(collection, callback, thisArg) {
-    var result = {};
-    callback = createCallback(callback, thisArg);
-
-    forEach(collection, function(value, key, collection) {
-      key = String(callback(value, key, collection));
-      (hasOwnProperty.call(result, key) ? result[key] : result[key] = []).push(value);
-    });
-    return result;
-  }
-
-  /**
-   * Invokes the method named by `methodName` on each element in the `collection`,
-   * returning an array of the results of each invoked method. Additional arguments
-   * will be passed to each invoked method. If `methodName` is a function, it will
-   * be invoked for, and `this` bound to, each element in the `collection`.
-   *
-   * @static
-   * @memberOf _
-   * @category Collections
-   * @param {Array|Object|String} collection The collection to iterate over.
-   * @param {Function|String} methodName The name of the method to invoke or
-   *  the function invoked per iteration.
-   * @param {Mixed} [arg1, arg2, ...] Arguments to invoke the method with.
-   * @returns {Array} Returns a new array of the results of each invoked method.
-   * @example
-   *
-   * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
-   * // => [[1, 5, 7], [1, 2, 3]]
-   *
-   * _.invoke([123, 456], String.prototype.split, '');
-   * // => [['1', '2', '3'], ['4', '5', '6']]
-   */
-  function invoke(collection, methodName) {
-    var args = nativeSlice.call(arguments, 2),
-        index = -1,
-        isFunc = typeof methodName == 'function',
-        length = collection ? collection.length : 0,
-        result = Array(typeof length == 'number' ? length : 0);
-
-    forEach(collection, function(value) {
-      result[++index] = (isFunc ? methodName : value[methodName]).apply(value, args);
-    });
-    return result;
-  }
-
-  /**
-   * Creates an array of values by running each element in the `collection`
-   * through the `callback`. The `callback` is bound to `thisArg` and invoked with
-   * three arguments; (value, index|key, collection).
-   *
-   * If a property name is passed for `callback`, the created "_.pluck" style
-   * callback will return the property value of the given element.
-   *
-   * If an object is passed for `callback`, the created "_.where" style callback
-   * will return `true` for elements that have the properties of the given object,
-   * else `false`.
-   *
-   * @static
-   * @memberOf _
-   * @alias collect
-   * @category Collections
-   * @param {Array|Object|String} collection The collection to iterate over.
-   * @param {Function|Object|String} [callback=identity] The function called per
-   *  iteration. If a property name or object is passed, it will be used to create
-   *  a "_.pluck" or "_.where" style callback, respectively.
-   * @param {Mixed} [thisArg] The `this` binding of `callback`.
-   * @returns {Array} Returns a new array of the results of each `callback` execution.
-   * @example
-   *
-   * _.map([1, 2, 3], function(num) { return num * 3; });
-   * // => [3, 6, 9]
-   *
-   * _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; });
-   * // => [3, 6, 9] (order is not guaranteed)
-   *
-   * var stooges = [
-   *   { 'name': 'moe', 'age': 40 },
-   *   { 'name': 'larry', 'age': 50 }
-   * ];
-   *
-   * // using "_.pluck" callback shorthand
-   * _.map(stooges, 'name');
-   * // => ['moe', 'larry']
-   */
-  function map(collection, callback, thisArg) {
-    var index = -1,
-        length = collection ? collection.length : 0;
-
-    callback = createCallback(callback, thisArg);
-    if (typeof length == 'number') {
-      var result = Array(length);
-      while (++index < length) {
-        result[index] = callback(collection[index], index, collection);
-      }
-    } else {
-      result = [];
-      forOwn(collection, function(value, key, collection) {
-        result[++index] = callback(value, key, collection);
-      });
-    }
-    return result;
-  }
-
-  /**
-   * Retrieves the maximum value of an `array`. If `callback` is passed,
-   * it will be executed for each value in the `array` to generate the
-   * criterion by which the value is ranked. The `callback` is bound to
-   * `thisArg` and invoked with three arguments; (value, index, collection).
-   *
-   * If a property name is passed for `callback`, the created "_.pluck" style
-   * callback will return the property value of the given element.
-   *
-   * If an object is passed for `callback`, the created "_.where" style callback
-   * will return `true` for elements that have the properties of the given object,
-   * else `false`.
-   *
-   * @static
-   * @memberOf _
-   * @category Collections
-   * @param {Array|Object|String} collection The collection to iterate over.
-   * @param {Function|Object|String} [callback=identity] The function called per
-   *  iteration. If a property name or object is passed, it will be used to create
-   *  a "_.pluck" or "_.where" style callback, respectively.
-   * @param {Mixed} [thisArg] The `this` binding of `callback`.
-   * @returns {Mixed} Returns the maximum value.
-   * @example
-   *
-   * _.max([4, 2, 8, 6]);
-   * // => 8
-   *
-   * var stooges = [
-   *   { 'name': 'moe', 'age': 40 },
-   *   { 'name': 'larry', 'age': 50 }
-   * ];
-   *
-   * _.max(stooges, function(stooge) { return stooge.age; });
-   * // => { 'name': 'larry', 'age': 50 };
-   *
-   * // using "_.pluck" callback shorthand
-   * _.max(stooges, 'age');
-   * // => { 'name': 'larry', 'age': 50 };
-   */
-  function max(collection, callback, thisArg) {
-    var computed = -Infinity,
-        result = computed;
-
-    var index = -1,
-        length = collection ? collection.length : 0;
-
-    if (!callback && typeof length == 'number') {
-      while (++index < length) {
-        var value = collection[index];
-        if (value > result) {
-          result = value;
-        }
-      }
-    } else {
-      callback = createCallback(callback, thisArg);
-
-      forEach(collection, function(value, index, collection) {
-        var current = callback(value, index, collection);
-        if (current > computed) {
-          computed = current;
-          result = value;
-        }
-      });
-    }
-    return result;
-  }
-
-  /**
-   * Retrieves the minimum value of an `array`. If `callback` is passed,
-   * it will be executed for each value in the `array` to generate the
-   * criterion by which the value is ranked. The `callback` is bound to `thisArg`
-   * and invoked with three arguments; (value, index, collection).
-   *
-   * If a property name is passed for `callback`, the created "_.pluck" style
-   * callback will return the property value of the given element.
-   *
-   * If an object is passed for `callback`, the created "_.where" style callback
-   * will return `true` for elements that have the properties of the given object,
-   * else `false`.
-   *
-   * @static
-   * @memberOf _
-   * @category Collections
-   * @param {Array|Object|String} collection The collection to iterate over.
-   * @param {Function|Object|String} [callback=identity] The function called per
-   *  iteration. If a property name or object is passed, it will be used to create
-   *  a "_.pluck" or "_.where" style callback, respectively.
-   * @param {Mixed} [thisArg] The `this` binding of `callback`.
-   * @returns {Mixed} Returns the minimum value.
-   * @example
-   *
-   * _.min([4, 2, 8, 6]);
-   * // => 2
-   *
-   * var stooges = [
-   *   { 'name': 'moe', 'age': 40 },
-   *   { 'name': 'larry', 'age': 50 }
-   * ];
-   *
-   * _.min(stooges, function(stooge) { return stooge.age; });
-   * // => { 'name': 'moe', 'age': 40 };
-   *
-   * // using "_.pluck" callback shorthand
-   * _.min(stooges, 'age');
-   * // => { 'name': 'moe', 'age': 40 };
-   */
-  function min(collection, callback, thisArg) {
-    var computed = Infinity,
-        result = computed;
-
-    var index = -1,
-        length = collection ? collection.length : 0;
-
-    if (!callback && typeof length == 'number') {
-      while (++index < length) {
-        var value = collection[index];
-        if (value < result) {
-          result = value;
-        }
-      }
-    } else {
-      callback = createCallback(callback, thisArg);
-
-      forEach(collection, function(value, index, collection) {
-        var current = callback(value, index, collection);
-        if (current < computed) {
-          computed = current;
-          result = value;
-        }
-      });
-    }
-    return result;
-  }
-
-  /**
-   * Retrieves the value of a specified property from all elements in the `collection`.
-   *
-   * @static
-   * @memberOf _
-   * @type Function
-   * @category Collections
-   * @param {Array|Object|String} collection The collection to iterate over.
-   * @param {String} property The property to pluck.
-   * @returns {Array} Returns a new array of property values.
-   * @example
-   *
-   * var stooges = [
-   *   { 'name': 'moe', 'age': 40 },
-   *   { 'name': 'larry', 'age': 50 }
-   * ];
-   *
-   * _.pluck(stooges, 'name');
-   * // => ['moe', 'larry']
-   */
-  function pluck(collection, property) {
-    var index = -1,
-        length = collection ? collection.length : 0;
-
-    if (typeof length == 'number') {
-      var result = Array(length);
-      while (++index < length) {
-        result[index] = collection[index][property];
-      }
-    }
-    return result || map(collection, property);
-  }
-
-  /**
-   * Reduces a `collection` to a value which is the accumulated result of running
-   * each element in the `collection` through the `callback`, where each successive
-   * `callback` execution consumes the return value of the previous execution.
-   * If `accumulator` is not passed, the first element of the `collection` will be
-   * used as the initial `accumulator` value. The `callback` is bound to `thisArg`
-   * and invoked with four arguments; (accumulator, value, index|key, collection).
-   *
-   * @static
-   * @memberOf _
-   * @alias foldl, inject
-   * @category Collections
-   * @param {Array|Object|String} collection The collection to iterate over.
-   * @param {Function} [callback=identity] The function called per iteration.
-   * @param {Mixed} [accumulator] Initial value of the accumulator.
-   * @param {Mixed} [thisArg] The `this` binding of `callback`.
-   * @returns {Mixed} Returns the accumulated value.
-   * @example
-   *
-   * var sum = _.reduce([1, 2, 3], function(sum, num) {
-   *   return sum + num;
-   * });
-   * // => 6
-   *
-   * var mapped = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) {
-   *   result[key] = num * 3;
-   *   return result;
-   * }, {});
-   * // => { 'a': 3, 'b': 6, 'c': 9 }
-   */
-  function reduce(collection, callback, accumulator, thisArg) {
-    if (!collection) return accumulator;
-    var noaccum = arguments.length < 3;
-    callback = createCallback(callback, thisArg, 4);
-
-    var index = -1,
-        length = collection.length;
-
-    if (typeof length == 'number') {
-      if (noaccum) {
-        accumulator = collection[++index];
-      }
-      while (++index < length) {
-        accumulator = callback(accumulator, collection[index], index, collection);
-      }
-    } else {
-      forOwn(collection, function(value, index, collection) {
-        accumulator = noaccum
-          ? (noaccum = false, value)
-          : callback(accumulator, value, index, collection)
-      });
-    }
-    return accumulator;
-  }
-
-  /**
-   * This method is similar to `_.reduce`, except that it iterates over a
-   * `collection` from right to left.
-   *
-   * @static
-   * @memberOf _
-   * @alias foldr
-   * @category Collections
-   * @param {Array|Object|String} collection The collection to iterate over.
-   * @param {Function} [callback=identity] The function called per iteration.
-   * @param {Mixed} [accumulator] Initial value of the accumulator.
-   * @param {Mixed} [thisArg] The `this` binding of `callback`.
-   * @returns {Mixed} Returns the accumulated value.
-   * @example
-   *
-   * var list = [[0, 1], [2, 3], [4, 5]];
-   * var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []);
-   * // => [4, 5, 2, 3, 0, 1]
-   */
-  function reduceRight(collection, callback, accumulator, thisArg) {
-    var iterable = collection,
-        length = collection ? collection.length : 0,
-        noaccum = arguments.length < 3;
-
-    if (typeof length != 'number') {
-      var props = keys(collection);
-      length = props.length;
-    }
-    callback = createCallback(callback, thisArg, 4);
-    forEach(collection, function(value, index, collection) {
-      index = props ? props[--length] : --length;
-      accumulator = noaccum
-        ? (noaccum = false, iterable[index])
-        : callback(accumulator, iterable[index], index, collection);
-    });
-    return accumulator;
-  }
-
-  /**
-   * The opposite of `_.filter`, this method returns the elements of a
-   * `collection` that `callback` does **not** return truthy for.
-   *
-   * If a property name is passed for `callback`, the created "_.pluck" style
-   * callback will return the property value of the given element.
-   *
-   * If an object is passed for `callback`, the created "_.where" style callback
-   * will return `true` for elements that have the properties of the given object,
-   * else `false`.
-   *
-   * @static
-   * @memberOf _
-   * @category Collections
-   * @param {Array|Object|String} collection The collection to iterate over.
-   * @param {Function|Object|String} [callback=identity] The function called per
-   *  iteration. If a property name or object is passed, it will be used to create
-   *  a "_.pluck" or "_.where" style callback, respectively.
-   * @param {Mixed} [thisArg] The `this` binding of `callback`.
-   * @returns {Array} Returns a new array of elements that did **not** pass the
-   *  callback check.
-   * @example
-   *
-   * var odds = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
-   * // => [1, 3, 5]
-   *
-   * var food = [
-   *   { 'name': 'apple',  'organic': false, 'type': 'fruit' },
-   *   { 'name': 'carrot', 'organic': true,  'type': 'vegetable' }
-   * ];
-   *
-   * // using "_.pluck" callback shorthand
-   * _.reject(food, 'organic');
-   * // => [{ 'name': 'apple', 'organic': false, 'type': 'fruit' }]
-   *
-   * // using "_.where" callback shorthand
-   * _.reject(food, { 'type': 'fruit' });
-   * // => [{ 'name': 'carrot', 'organic': true, 'type': 'vegetable' }]
-   */
-  function reject(collection, callback, thisArg) {
-    callback = createCallback(callback, thisArg);
-    return filter(collection, function(value, index, collection) {
-      return !callback(value, index, collection);
-    });
-  }
-
-  /**
-   * Creates an array of shuffled `array` values, using a version of the
-   * Fisher-Yates shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle.
-   *
-   * @static
-   * @memberOf _
-   * @category Collections
-   * @param {Array|Object|String} collection The collection to shuffle.
-   * @returns {Array} Returns a new shuffled collection.
-   * @example
-   *
-   * _.shuffle([1, 2, 3, 4, 5, 6]);
-   * // => [4, 1, 6, 3, 5, 2]
-   */
-  function shuffle(collection) {
-    var index = -1,
-        length = collection ? collection.length : 0,
-        result = Array(typeof length == 'number' ? length : 0);
-
-    forEach(collection, function(value) {
-      var rand = floor(nativeRandom() * (++index + 1));
-      result[index] = result[rand];
-      result[rand] = value;
-    });
-    return result;
-  }
-
-  /**
-   * Gets the size of the `collection` by returning `collection.length` for arrays
-   * and array-like objects or the number of own enumerable properties for objects.
-   *
-   * @static
-   * @memberOf _
-   * @category Collections
-   * @param {Array|Object|String} collection The collection to inspect.
-   * @returns {Number} Returns `collection.length` or number of own enumerable properties.
-   * @example
-   *
-   * _.size([1, 2]);
-   * // => 2
-   *
-   * _.size({ 'one': 1, 'two': 2, 'three': 3 });
-   * // => 3
-   *
-   * _.size('curly');
-   * // => 5
-   */
-  function size(collection) {
-    var length = collection ? collection.length : 0;
-    return typeof length == 'number' ? length : keys(collection).length;
-  }
-
-  /**
-   * Checks if the `callback` returns a truthy value for **any** element of a
-   * `collection`. The function returns as soon as it finds passing value, and
-   * does not iterate over the entire `collection`. The `callback` is bound to
-   * `thisArg` and invoked with three arguments; (value, index|key, collection).
-   *
-   * If a property name is passed for `callback`, the created "_.pluck" style
-   * callback will return the property value of the given element.
-   *
-   * If an object is passed for `callback`, the created "_.where" style callback
-   * will return `true` for elements that have the properties of the given object,
-   * else `false`.
-   *
-   * @static
-   * @memberOf _
-   * @alias any
-   * @category Collections
-   * @param {Array|Object|String} collection The collection to iterate over.
-   * @param {Function|Object|String} [callback=identity] The function called per
-   *  iteration. If a property name or object is passed, it will be used to create
-   *  a "_.pluck" or "_.where" style callback, respectively.
-   * @param {Mixed} [thisArg] The `this` binding of `callback`.
-   * @returns {Boolean} Returns `true` if any element passes the callback check,
-   *  else `false`.
-   * @example
-   *
-   * _.some([null, 0, 'yes', false], Boolean);
-   * // => true
-   *
-   * var food = [
-   *   { 'name': 'apple',  'organic': false, 'type': 'fruit' },
-   *   { 'name': 'carrot', 'organic': true,  'type': 'vegetable' }
-   * ];
-   *
-   * // using "_.pluck" callback shorthand
-   * _.some(food, 'organic');
-   * // => true
-   *
-   * // using "_.where" callback shorthand
-   * _.some(food, { 'type': 'meat' });
-   * // => false
-   */
-  function some(collection, callback, thisArg) {
-    var result;
-    callback = createCallback(callback, thisArg);
-
-    var index = -1,
-        length = collection ? collection.length : 0;
-
-    if (typeof length == 'number') {
-      while (++index < length) {
-        if ((result = callback(collection[index], index, collection))) {
-          break;
-        }
-      }
-    } else {
-      forOwn(collection, function(value, index, collection) {
-        return (result = callback(value, index, collection)) && indicatorObject;
-      });
-    }
-    return !!result;
-  }
-
-  /**
-   * Creates an array of elements, sorted in ascending order by the results of
-   * running each element in the `collection` through the `callback`. This method
-   * performs a stable sort, that is, it will preserve the original sort order of
-   * equal elements. The `callback` is bound to `thisArg` and invoked with three
-   * arguments; (value, index|key, collection).
-   *
-   * If a property name is passed for `callback`, the created "_.pluck" style
-   * callback will return the property value of the given element.
-   *
-   * If an object is passed for `callback`, the created "_.where" style callback
-   * will return `true` for elements that have the properties of the given object,
-   * else `false`.
-   *
-   * @static
-   * @memberOf _
-   * @category Collections
-   * @param {Array|Object|String} collection The collection to iterate over.
-   * @param {Function|Object|String} [callback=identity] The function called per
-   *  iteration. If a property name or object is passed, it will be used to create
-   *  a "_.pluck" or "_.where" style callback, respectively.
-   * @param {Mixed} [thisArg] The `this` binding of `callback`.
-   * @returns {Array} Returns a new array of sorted elements.
-   * @example
-   *
-   * _.sortBy([1, 2, 3], function(num) { return Math.sin(num); });
-   * // => [3, 1, 2]
-   *
-   * _.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math);
-   * // => [3, 1, 2]
-   *
-   * // using "_.pluck" callback shorthand
-   * _.sortBy(['banana', 'strawberry', 'apple'], 'length');
-   * // => ['apple', 'banana', 'strawberry']
-   */
-  function sortBy(collection, callback, thisArg) {
-    var index = -1,
-        length = collection ? collection.length : 0,
-        result = Array(typeof length == 'number' ? length : 0);
-
-    callback = createCallback(callback, thisArg);
-    forEach(collection, function(value, key, collection) {
-      result[++index] = {
-        'criteria': callback(value, key, collection),
-        'index': index,
-        'value': value
-      };
-    });
-
-    length = result.length;
-    result.sort(compareAscending);
-    while (length--) {
-      result[length] = result[length].value;
-    }
-    return result;
-  }
-
-  /**
-   * Converts the `collection` to an array.
-   *
-   * @static
-   * @memberOf _
-   * @category Collections
-   * @param {Array|Object|String} collection The collection to convert.
-   * @returns {Array} Returns the new converted array.
-   * @example
-   *
-   * (function() { return _.toArray(arguments).slice(1); })(1, 2, 3, 4);
-   * // => [2, 3, 4]
-   */
-  function toArray(collection) {
-    if (isArray(collection)) {
-      return nativeSlice.call(collection);
-    }
-    if (collection && typeof collection.length == 'number') {
-      return map(collection);
-    }
-    return values(collection);
-  }
-
-  /**
-   * Examines each element in a `collection`, returning an array of all elements
-   * that have the given `properties`. When checking `properties`, this method
-   * performs a deep comparison between values to determine if they are equivalent
-   * to each other.
-   *
-   * @static
-   * @memberOf _
-   * @type Function
-   * @category Collections
-   * @param {Array|Object|String} collection The collection to iterate over.
-   * @param {Object} properties The object of property values to filter by.
-   * @returns {Array} Returns a new array of elements that have the given `properties`.
-   * @example
-   *
-   * var stooges = [
-   *   { 'name': 'moe', 'age': 40 },
-   *   { 'name': 'larry', 'age': 50 }
-   * ];
-   *
-   * _.where(stooges, { 'age': 40 });
-   * // => [{ 'name': 'moe', 'age': 40 }]
-   */
-  function where(collection, properties, first) {
-    return (first && isEmpty(properties))
-      ? null
-      : (first ? find : filter)(collection, properties);
-  }
-
-  /*--------------------------------------------------------------------------*/
-
-  /**
-   * Creates an array with all falsey values of `array` removed. The values
-   * `false`, `null`, `0`, `""`, `undefined` and `NaN` are all falsey.
-   *
-   * @static
-   * @memberOf _
-   * @category Arrays
-   * @param {Array} array The array to compact.
-   * @returns {Array} Returns a new filtered array.
-   * @example
-   *
-   * _.compact([0, 1, false, 2, '', 3]);
-   * // => [1, 2, 3]
-   */
-  function compact(array) {
-    var index = -1,
-        length = array ? array.length : 0,
-        result = [];
-
-    while (++index < length) {
-      var value = array[index];
-      if (value) {
-        result.push(value);
-      }
-    }
-    return result;
-  }
-
-  /**
-   * Creates an array of `array` elements not present in the other arrays
-   * using strict equality for comparisons, i.e. `===`.
-   *
-   * @static
-   * @memberOf _
-   * @category Arrays
-   * @param {Array} array The array to process.
-   * @param {Array} [array1, array2, ...] Arrays to check.
-   * @returns {Array} Returns a new array of `array` elements not present in the
-   *  other arrays.
-   * @example
-   *
-   * _.difference([1, 2, 3, 4, 5], [5, 2, 10]);
-   * // => [1, 3, 4]
-   */
-  function difference(array) {
-    var index = -1,
-        indexOf = getIndexOf(),
-        length = array.length,
-        flattened = concat.apply(arrayRef, nativeSlice.call(arguments, 1)),
-        result = [];
-
-    while (++index < length) {
-      var value = array[index];
-      if (indexOf(flattened, value) < 0) {
-        result.push(value);
-      }
-    }
-    return result;
-  }
-
-  /**
-   * Gets the first element of the `array`. If a number `n` is passed, the first
-   * `n` elements of the `array` are returned. If a `callback` function is passed,
-   * elements at the beginning of the array are returned as long as the `callback`
-   * returns truthy. The `callback` is bound to `thisArg` and invoked with three
-   * arguments; (value, index, array).
-   *
-   * If a property name is passed for `callback`, the created "_.pluck" style
-   * callback will return the property value of the given element.
-   *
-   * If an object is passed for `callback`, the created "_.where" style callback
-   * will return `true` for elements that have the properties of the given object,
-   * else `false`.
-   *
-   * @static
-   * @memberOf _
-   * @alias head, take
-   * @category Arrays
-   * @param {Array} array The array to query.
-   * @param {Function|Object|Number|String} [callback|n] The function called
-   *  per element or the number of elements to return. If a property name or
-   *  object is passed, it will be used to create a "_.pluck" or "_.where"
-   *  style callback, respectively.
-   * @param {Mixed} [thisArg] The `this` binding of `callback`.
-   * @returns {Mixed} Returns the first element(s) of `array`.
-   * @example
-   *
-   * _.first([1, 2, 3]);
-   * // => 1
-   *
-   * _.first([1, 2, 3], 2);
-   * // => [1, 2]
-   *
-   * _.first([1, 2, 3], function(num) {
-   *   return num < 3;
-   * });
-   * // => [1, 2]
-   *
-   * var food = [
-   *   { 'name': 'banana', 'organic': true },
-   *   { 'name': 'beet',   'organic': false },
-   * ];
-   *
-   * // using "_.pluck" callback shorthand
-   * _.first(food, 'organic');
-   * // => [{ 'name': 'banana', 'organic': true }]
-   *
-   * var food = [
-   *   { 'name': 'apple',  'type': 'fruit' },
-   *   { 'name': 'banana', 'type': 'fruit' },
-   *   { 'name': 'beet',   'type': 'vegetable' }
-   * ];
-   *
-   * // using "_.where" callback shorthand
-   * _.first(food, { 'type': 'fruit' });
-   * // => [{ 'name': 'apple', 'type': 'fruit' }, { 'name': 'banana', 'type': 'fruit' }]
-   */
-  function first(array, callback, thisArg) {
-    if (array) {
-      var n = 0,
-          length = array.length;
-
-      if (typeof callback != 'number' && callback != null) {
-        var index = -1;
-        callback = createCallback(callback, thisArg);
-        while (++index < length && callback(array[index], index, array)) {
-          n++;
-        }
-      } else {
-        n = callback;
-        if (n == null || thisArg) {
-          return array[0];
-        }
-      }
-      return nativeSlice.call(array, 0, nativeMin(nativeMax(0, n), length));
-    }
-  }
-
-  /**
-   * Flattens a nested array (the nesting can be to any depth). If `isShallow`
-   * is truthy, `array` will only be flattened a single level. If `callback`
-   * is passed, each element of `array` is passed through a `callback` before
-   * flattening. The `callback` is bound to `thisArg` and invoked with three
-   * arguments; (value, index, array).
-   *
-   * If a property name is passed for `callback`, the created "_.pluck" style
-   * callback will return the property value of the given element.
-   *
-   * If an object is passed for `callback`, the created "_.where" style callback
-   * will return `true` for elements that have the properties of the given object,
-   * else `false`.
-   *
-   * @static
-   * @memberOf _
-   * @category Arrays
-   * @param {Array} array The array to flatten.
-   * @param {Boolean} [isShallow=false] A flag to indicate only flattening a single level.
-   * @param {Function|Object|String} [callback=identity] The function called per
-   *  iteration. If a property name or object is passed, it will be used to create
-   *  a "_.pluck" or "_.where" style callback, respectively.
-   * @param {Mixed} [thisArg] The `this` binding of `callback`.
-   * @returns {Array} Returns a new flattened array.
-   * @example
-   *
-   * _.flatten([1, [2], [3, [[4]]]]);
-   * // => [1, 2, 3, 4];
-   *
-   * _.flatten([1, [2], [3, [[4]]]], true);
-   * // => [1, 2, 3, [[4]]];
-   *
-   * var stooges = [
-   *   { 'name': 'curly', 'quotes': ['Oh, a wise guy, eh?', 'Poifect!'] },
-   *   { 'name': 'moe', 'quotes': ['Spread out!', 'You knucklehead!'] }
-   * ];
-   *
-   * // using "_.pluck" callback shorthand
-   * _.flatten(stooges, 'quotes');
-   * // => ['Oh, a wise guy, eh?', 'Poifect!', 'Spread out!', 'You knucklehead!']
-   */
-  function flatten(array, isShallow) {
-    var index = -1,
-        length = array ? array.length : 0,
-        result = [];
-
-    while (++index < length) {
-      var value = array[index];
-      if (isArray(value)) {
-        push.apply(result, isShallow ? value : flatten(value));
-      } else {
-        result.push(value);
-      }
-    }
-    return result;
-  }
-
-  /**
-   * Gets the index at which the first occurrence of `value` is found using
-   * strict equality for comparisons, i.e. `===`. If the `array` is already
-   * sorted, passing `true` for `fromIndex` will run a faster binary search.
-   *
-   * @static
-   * @memberOf _
-   * @category Arrays
-   * @param {Array} array The array to search.
-   * @param {Mixed} value The value to search for.
-   * @param {Boolean|Number} [fromIndex=0] The index to search from or `true` to
-   *  perform a binary search on a sorted `array`.
-   * @returns {Number} Returns the index of the matched value or `-1`.
-   * @example
-   *
-   * _.indexOf([1, 2, 3, 1, 2, 3], 2);
-   * // => 1
-   *
-   * _.indexOf([1, 2, 3, 1, 2, 3], 2, 3);
-   * // => 4
-   *
-   * _.indexOf([1, 1, 2, 2, 3, 3], 2, true);
-   * // => 2
-   */
-  function indexOf(array, value, fromIndex) {
-    if (typeof fromIndex == 'number') {
-      var length = array ? array.length : 0;
-      fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex || 0);
-    } else if (fromIndex) {
-      var index = sortedIndex(array, value);
-      return array[index] === value ? index : -1;
-    }
-    return array ? basicIndexOf(array, value, fromIndex) : -1;
-  }
-
-  /**
-   * Gets all but the last element of `array`. If a number `n` is passed, the
-   * last `n` elements are excluded from the result. If a `callback` function
-   * is passed, elements at the end of the array are excluded from the result
-   * as long as the `callback` returns truthy. The `callback` is bound to
-   * `thisArg` and invoked with three arguments; (value, index, array).
-   *
-   * If a property name is passed for `callback`, the created "_.pluck" style
-   * callback will return the property value of the given

<TRUNCATED>

[67/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/ucoleitr.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/ucoleitr.h b/src/apps/couch_collate/platform/osx/icu/unicode/ucoleitr.h
new file mode 100644
index 0000000..9c951a9
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/ucoleitr.h
@@ -0,0 +1,315 @@
+/*
+*******************************************************************************
+*   Copyright (C) 2001-2008, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+*******************************************************************************
+*
+* File ucoleitr.cpp
+*
+* Modification History:
+*
+* Date        Name        Description
+* 02/15/2001  synwee      Modified all methods to process its own function 
+*                         instead of calling the equivalent c++ api (coleitr.h)
+*******************************************************************************/
+
+#ifndef UCOLEITR_H
+#define UCOLEITR_H
+
+#include "unicode/utypes.h"
+
+#if !UCONFIG_NO_COLLATION
+
+/**  
+ * This indicates an error has occured during processing or if no more CEs is 
+ * to be returned.
+ * @stable ICU 2.0
+ */
+#define UCOL_NULLORDER        ((int32_t)0xFFFFFFFF)
+
+/**  
+ * This indicates an error has occured during processing or there are no more CEs 
+ * to be returned.
+ *
+ * @internal
+ */
+#define UCOL_PROCESSED_NULLORDER        ((int64_t)U_INT64_MAX)
+
+#include "unicode/ucol.h"
+
+/** 
+ * The UCollationElements struct.
+ * For usage in C programs.
+ * @stable ICU 2.0
+ */
+typedef struct UCollationElements UCollationElements;
+
+/**
+ * \file
+ * \brief C API: UCollationElements
+ *
+ * The UCollationElements API is used as an iterator to walk through each 
+ * character of an international string. Use the iterator to return the
+ * ordering priority of the positioned character. The ordering priority of a 
+ * character, which we refer to as a key, defines how a character is collated 
+ * in the given collation object.
+ * For example, consider the following in Spanish:
+ * <pre>
+ * .       "ca" -> the first key is key('c') and second key is key('a').
+ * .       "cha" -> the first key is key('ch') and second key is key('a').
+ * </pre>
+ * And in German,
+ * <pre>
+ * .       "<ae ligature>b"-> the first key is key('a'), the second key is key('e'), and
+ * .       the third key is key('b').
+ * </pre>
+ * <p>Example of the iterator usage: (without error checking)
+ * <pre>
+ * .  void CollationElementIterator_Example()
+ * .  {
+ * .      UChar *s;
+ * .      t_int32 order, primaryOrder;
+ * .      UCollationElements *c;
+ * .      UCollatorOld *coll;
+ * .      UErrorCode success = U_ZERO_ERROR;
+ * .      s=(UChar*)malloc(sizeof(UChar) * (strlen("This is a test")+1) );
+ * .      u_uastrcpy(s, "This is a test");
+ * .      coll = ucol_open(NULL, &success);
+ * .      c = ucol_openElements(coll, str, u_strlen(str), &status);
+ * .      order = ucol_next(c, &success);
+ * .      ucol_reset(c);
+ * .      order = ucol_prev(c, &success);
+ * .      free(s);
+ * .      ucol_close(coll);
+ * .      ucol_closeElements(c);
+ * .  }
+ * </pre>
+ * <p>
+ * ucol_next() returns the collation order of the next.
+ * ucol_prev() returns the collation order of the previous character.
+ * The Collation Element Iterator moves only in one direction between calls to
+ * ucol_reset. That is, ucol_next() and ucol_prev can not be inter-used. 
+ * Whenever ucol_prev is to be called after ucol_next() or vice versa, 
+ * ucol_reset has to be called first to reset the status, shifting pointers to 
+ * either the end or the start of the string. Hence at the next call of 
+ * ucol_prev or ucol_next, the first or last collation order will be returned. 
+ * If a change of direction is done without a ucol_reset, the result is 
+ * undefined.
+ * The result of a forward iterate (ucol_next) and reversed result of the  
+ * backward iterate (ucol_prev) on the same string are equivalent, if 
+ * collation orders with the value UCOL_IGNORABLE are ignored.
+ * Character based on the comparison level of the collator.  A collation order 
+ * consists of primary order, secondary order and tertiary order.  The data 
+ * type of the collation order is <strong>t_int32</strong>. 
+ *
+ * @see UCollator
+ */
+
+/**
+ * Open the collation elements for a string.
+ *
+ * @param coll The collator containing the desired collation rules.
+ * @param text The text to iterate over.
+ * @param textLength The number of characters in text, or -1 if null-terminated
+ * @param status A pointer to an UErrorCode to receive any errors.
+ * @return a struct containing collation element information
+ * @stable ICU 2.0
+ */
+U_STABLE UCollationElements* U_EXPORT2 
+ucol_openElements(const UCollator  *coll,
+                  const UChar      *text,
+                        int32_t    textLength,
+                        UErrorCode *status);
+
+/**
+ * get a hash code for a key... Not very useful!
+ * @param key    the given key.
+ * @param length the size of the key array.
+ * @return       the hash code.
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2 
+ucol_keyHashCode(const uint8_t* key, int32_t length);
+
+/**
+ * Close a UCollationElements.
+ * Once closed, a UCollationElements may no longer be used.
+ * @param elems The UCollationElements to close.
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+ucol_closeElements(UCollationElements *elems);
+
+/**
+ * Reset the collation elements to their initial state.
+ * This will move the 'cursor' to the beginning of the text.
+ * Property settings for collation will be reset to the current status.
+ * @param elems The UCollationElements to reset.
+ * @see ucol_next
+ * @see ucol_previous
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+ucol_reset(UCollationElements *elems);
+
+/**
+ * Get the ordering priority of the next collation element in the text.
+ * A single character may contain more than one collation element.
+ * @param elems The UCollationElements containing the text.
+ * @param status A pointer to an UErrorCode to receive any errors.
+ * @return The next collation elements ordering, otherwise returns NULLORDER 
+ *         if an error has occured or if the end of string has been reached
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2 
+ucol_next(UCollationElements *elems, UErrorCode *status);
+
+/**
+ * Get the ordering priority of the previous collation element in the text.
+ * A single character may contain more than one collation element.
+ * Note that internally a stack is used to store buffered collation elements. 
+ * It is very rare that the stack will overflow, however if such a case is 
+ * encountered, the problem can be solved by increasing the size 
+ * UCOL_EXPAND_CE_BUFFER_SIZE in ucol_imp.h.
+ * @param elems The UCollationElements containing the text.
+ * @param status A pointer to an UErrorCode to receive any errors. Noteably 
+ *               a U_BUFFER_OVERFLOW_ERROR is returned if the internal stack
+ *               buffer has been exhausted.
+ * @return The previous collation elements ordering, otherwise returns 
+ *         NULLORDER if an error has occured or if the start of string has 
+ *         been reached.
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2 
+ucol_previous(UCollationElements *elems, UErrorCode *status);
+
+/**
+ * Get the processed ordering priority of the next collation element in the text.
+ * A single character may contain more than one collation element.
+ *
+ * @param elems The UCollationElements containing the text.
+ * @param ixLow a pointer to an int32_t to receive the iterator index before fetching the CE.
+ * @param ixHigh a pointer to an int32_t to receive the iterator index after fetching the CE.
+ * @param status A pointer to an UErrorCode to receive any errors.
+ * @return The next collation elements ordering, otherwise returns UCOL_PROCESSED_NULLORDER 
+ *         if an error has occured or if the end of string has been reached
+ *
+ * @internal
+ */
+U_INTERNAL int64_t U_EXPORT2
+ucol_nextProcessed(UCollationElements *elems, int32_t *ixLow, int32_t *ixHigh, UErrorCode *status);
+
+/**
+ * Get the processed ordering priority of the previous collation element in the text.
+ * A single character may contain more than one collation element.
+ * Note that internally a stack is used to store buffered collation elements. 
+ * It is very rare that the stack will overflow, however if such a case is 
+ * encountered, the problem can be solved by increasing the size 
+ * UCOL_EXPAND_CE_BUFFER_SIZE in ucol_imp.h.
+ *
+ * @param elems The UCollationElements containing the text.
+ * @param ixLow A pointer to an int32_t to receive the iterator index after fetching the CE
+ * @param ixHigh A pointer to an int32_t to receiver the iterator index before fetching the CE
+ * @param status A pointer to an UErrorCode to receive any errors. Noteably 
+ *               a U_BUFFER_OVERFLOW_ERROR is returned if the internal stack
+ *               buffer has been exhausted.
+ * @return The previous collation elements ordering, otherwise returns 
+ *         UCOL_PROCESSED_NULLORDER if an error has occured or if the start of
+ *         string has been reached.
+ *
+ * @internal
+ */
+U_INTERNAL int64_t U_EXPORT2
+ucol_previousProcessed(UCollationElements *elems, int32_t *ixLow, int32_t *ixHigh, UErrorCode *status);
+
+/**
+ * Get the maximum length of any expansion sequences that end with the 
+ * specified comparison order.
+ * This is useful for .... ?
+ * @param elems The UCollationElements containing the text.
+ * @param order A collation order returned by previous or next.
+ * @return maximum size of the expansion sequences ending with the collation 
+ *         element or 1 if collation element does not occur at the end of any 
+ *         expansion sequence
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2 
+ucol_getMaxExpansion(const UCollationElements *elems, int32_t order);
+
+/**
+ * Set the text containing the collation elements.
+ * Property settings for collation will remain the same.
+ * In order to reset the iterator to the current collation property settings,
+ * the API reset() has to be called.
+ * @param elems The UCollationElements to set.
+ * @param text The source text containing the collation elements.
+ * @param textLength The length of text, or -1 if null-terminated.
+ * @param status A pointer to an UErrorCode to receive any errors.
+ * @see ucol_getText
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+ucol_setText(      UCollationElements *elems, 
+             const UChar              *text,
+                   int32_t            textLength,
+                   UErrorCode         *status);
+
+/**
+ * Get the offset of the current source character.
+ * This is an offset into the text of the character containing the current
+ * collation elements.
+ * @param elems The UCollationElements to query.
+ * @return The offset of the current source character.
+ * @see ucol_setOffset
+ * @stable ICU 2.0
+ */
+U_STABLE int32_t U_EXPORT2 
+ucol_getOffset(const UCollationElements *elems);
+
+/**
+ * Set the offset of the current source character.
+ * This is an offset into the text of the character to be processed.
+ * Property settings for collation will remain the same.
+ * In order to reset the iterator to the current collation property settings,
+ * the API reset() has to be called.
+ * @param elems The UCollationElements to set.
+ * @param offset The desired character offset.
+ * @param status A pointer to an UErrorCode to receive any errors.
+ * @see ucol_getOffset
+ * @stable ICU 2.0
+ */
+U_STABLE void U_EXPORT2 
+ucol_setOffset(UCollationElements *elems,
+               int32_t        offset,
+               UErrorCode         *status);
+
+/**
+* Get the primary order of a collation order.
+* @param order the collation order
+* @return the primary order of a collation order.
+* @stable ICU 2.6
+*/
+U_STABLE int32_t U_EXPORT2
+ucol_primaryOrder (int32_t order); 
+
+/**
+* Get the secondary order of a collation order.
+* @param order the collation order
+* @return the secondary order of a collation order.
+* @stable ICU 2.6
+*/
+U_STABLE int32_t U_EXPORT2
+ucol_secondaryOrder (int32_t order); 
+
+/**
+* Get the tertiary order of a collation order.
+* @param order the collation order
+* @return the tertiary order of a collation order.
+* @stable ICU 2.6
+*/
+U_STABLE int32_t U_EXPORT2
+ucol_tertiaryOrder (int32_t order); 
+
+#endif /* #if !UCONFIG_NO_COLLATION */
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/uconfig.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/uconfig.h b/src/apps/couch_collate/platform/osx/icu/unicode/uconfig.h
new file mode 100644
index 0000000..232bb04
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/uconfig.h
@@ -0,0 +1,228 @@
+/*  
+**********************************************************************
+*   Copyright (C) 2002-2008, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+**********************************************************************
+*   file name:  uconfig.h
+*   encoding:   US-ASCII
+*   tab size:   8 (not used)
+*   indentation:4
+*
+*   created on: 2002sep19
+*   created by: Markus W. Scherer
+*/
+
+#ifndef __UCONFIG_H__
+#define __UCONFIG_H__
+
+
+/*!
+ * \file
+ * \brief Switches for excluding parts of ICU library code modules.
+ *
+ * Allows to build partial, smaller libraries for special purposes.
+ * By default, all modules are built.
+ * The switches are fairly coarse, controlling large modules.
+ * Basic services cannot be turned off.
+ *
+ * Building with any of these options does not guarantee that the
+ * ICU build process will completely work. It is recommended that
+ * the ICU libraries and data be built using the normal build.
+ * At that time you should remove the data used by those services.
+ * After building the ICU data library, you should rebuild the ICU
+ * libraries with these switches customized to your needs.
+ *
+ * @stable ICU 2.4
+ */
+
+/**
+ * \def UCONFIG_USE_LOCAL
+ * If this switch is defined, ICU will attempt to load a header file named "uconfig_local.h"
+ * prior to determining default settings for uconfig variables.
+ * 
+ * @internal ICU 4.0
+ * 
+ */
+#if defined(UCONFIG_USE_LOCAL)
+#include "uconfig_local.h"
+#endif
+
+/**
+ * \def UCONFIG_ONLY_COLLATION
+ * This switch turns off modules that are not needed for collation.
+ *
+ * It does not turn off legacy conversion because that is necessary
+ * for ICU to work on EBCDIC platforms (for the default converter).
+ * If you want "only collation" and do not build for EBCDIC,
+ * then you can define UCONFIG_NO_LEGACY_CONVERSION 1 as well.
+ *
+ * @stable ICU 2.4
+ */
+#ifndef UCONFIG_ONLY_COLLATION
+#   define UCONFIG_ONLY_COLLATION 0
+#endif
+
+#if UCONFIG_ONLY_COLLATION
+    /* common library */
+#   define UCONFIG_NO_BREAK_ITERATION 1
+#   define UCONFIG_NO_IDNA 1
+
+    /* i18n library */
+#   if UCONFIG_NO_COLLATION
+#       error Contradictory collation switches in uconfig.h.
+#   endif
+#   define UCONFIG_NO_FORMATTING 1
+#   define UCONFIG_NO_TRANSLITERATION 1
+#   define UCONFIG_NO_REGULAR_EXPRESSIONS 1
+#endif
+
+/* common library switches -------------------------------------------------- */
+
+/**
+ * \def UCONFIG_NO_FILE_IO
+ * This switch turns off all file access in the common library
+ * where file access is only used for data loading.
+ * ICU data must then be provided in the form of a data DLL (or with an
+ * equivalent way to link to the data residing in an executable,
+ * as in building a combined library with both the common library's code and
+ * the data), or via udata_setCommonData().
+ * Application data must be provided via udata_setAppData() or by using
+ * "open" functions that take pointers to data, for example ucol_openBinary().
+ *
+ * File access is not used at all in the i18n library.
+ *
+ * File access cannot be turned off for the icuio library or for the ICU
+ * test suites and ICU tools.
+ *
+ * @stable ICU 3.6
+ */
+#ifndef UCONFIG_NO_FILE_IO
+#   define UCONFIG_NO_FILE_IO 0
+#endif
+
+/**
+ * \def UCONFIG_NO_CONVERSION
+ * ICU will not completely build with this switch turned on.
+ * This switch turns off all converters.
+ *
+ * @stable ICU 3.2
+ */
+#ifndef UCONFIG_NO_CONVERSION
+#   define UCONFIG_NO_CONVERSION 0
+#endif
+
+#if UCONFIG_NO_CONVERSION
+#   define UCONFIG_NO_LEGACY_CONVERSION 1
+#endif
+
+/**
+ * \def UCONFIG_NO_LEGACY_CONVERSION
+ * This switch turns off all converters except for
+ * - Unicode charsets (UTF-7/8/16/32, CESU-8, SCSU, BOCU-1)
+ * - US-ASCII
+ * - ISO-8859-1
+ *
+ * Turning off legacy conversion is not possible on EBCDIC platforms
+ * because they need ibm-37 or ibm-1047 default converters.
+ *
+ * @stable ICU 2.4
+ */
+#ifndef UCONFIG_NO_LEGACY_CONVERSION
+#   define UCONFIG_NO_LEGACY_CONVERSION 0
+#endif
+
+/**
+ * \def UCONFIG_NO_NORMALIZATION
+ * This switch turns off normalization.
+ * It implies turning off several other services as well, for example
+ * collation and IDNA.
+ *
+ * @stable ICU 2.6
+ */
+#ifndef UCONFIG_NO_NORMALIZATION
+#   define UCONFIG_NO_NORMALIZATION 0
+#elif UCONFIG_NO_NORMALIZATION
+    /* common library */
+#   define UCONFIG_NO_IDNA 1
+
+    /* i18n library */
+#   if UCONFIG_ONLY_COLLATION
+#       error Contradictory collation switches in uconfig.h.
+#   endif
+#   define UCONFIG_NO_COLLATION 1
+#   define UCONFIG_NO_TRANSLITERATION 1
+#endif
+
+/**
+ * \def UCONFIG_NO_BREAK_ITERATION
+ * This switch turns off break iteration.
+ *
+ * @stable ICU 2.4
+ */
+#ifndef UCONFIG_NO_BREAK_ITERATION
+#   define UCONFIG_NO_BREAK_ITERATION 0
+#endif
+
+/**
+ * \def UCONFIG_NO_IDNA
+ * This switch turns off IDNA.
+ *
+ * @stable ICU 2.6
+ */
+#ifndef UCONFIG_NO_IDNA
+#   define UCONFIG_NO_IDNA 0
+#endif
+
+/* i18n library switches ---------------------------------------------------- */
+
+/**
+ * \def UCONFIG_NO_COLLATION
+ * This switch turns off collation and collation-based string search.
+ *
+ * @stable ICU 2.4
+ */
+#ifndef UCONFIG_NO_COLLATION
+#   define UCONFIG_NO_COLLATION 0
+#endif
+
+/**
+ * \def UCONFIG_NO_FORMATTING
+ * This switch turns off formatting and calendar/timezone services.
+ *
+ * @stable ICU 2.4
+ */
+#ifndef UCONFIG_NO_FORMATTING
+#   define UCONFIG_NO_FORMATTING 0
+#endif
+
+/**
+ * \def UCONFIG_NO_TRANSLITERATION
+ * This switch turns off transliteration.
+ *
+ * @stable ICU 2.4
+ */
+#ifndef UCONFIG_NO_TRANSLITERATION
+#   define UCONFIG_NO_TRANSLITERATION 0
+#endif
+
+/**
+ * \def UCONFIG_NO_REGULAR_EXPRESSIONS
+ * This switch turns off regular expressions.
+ *
+ * @stable ICU 2.4
+ */
+#ifndef UCONFIG_NO_REGULAR_EXPRESSIONS
+#   define UCONFIG_NO_REGULAR_EXPRESSIONS 0
+#endif
+
+/**
+ * \def UCONFIG_NO_SERVICE
+ * This switch turns off service registration.
+ *
+ * @stable ICU 3.2
+ */
+#ifndef UCONFIG_NO_SERVICE
+#   define UCONFIG_NO_SERVICE 1
+#endif
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/ucsdet.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/ucsdet.h b/src/apps/couch_collate/platform/osx/icu/unicode/ucsdet.h
new file mode 100644
index 0000000..31f622c
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/ucsdet.h
@@ -0,0 +1,349 @@
+/*
+ **********************************************************************
+ *   Copyright (C) 2005-2007, International Business Machines
+ *   Corporation and others.  All Rights Reserved.
+ **********************************************************************
+ *   file name:  ucsdet.h
+ *   encoding:   US-ASCII
+ *   indentation:4
+ *
+ *   created on: 2005Aug04
+ *   created by: Andy Heninger
+ *
+ *   ICU Character Set Detection, API for C
+ *
+ *   Draft version 18 Oct 2005
+ *
+ */
+
+#ifndef __UCSDET_H
+#define __UCSDET_H
+
+#include "unicode/utypes.h"
+
+#if !UCONFIG_NO_CONVERSION
+#include "unicode/uenum.h"
+
+/**
+ * \file 
+ * \brief C API: Charset Detection API
+ *
+ * This API provides a facility for detecting the
+ * charset or encoding of character data in an unknown text format.
+ * The input data can be from an array of bytes.
+ * <p>
+ * Character set detection is at best an imprecise operation.  The detection
+ * process will attempt to identify the charset that best matches the characteristics
+ * of the byte data, but the process is partly statistical in nature, and
+ * the results can not be guaranteed to always be correct.
+ * <p>
+ * For best accuracy in charset detection, the input data should be primarily
+ * in a single language, and a minimum of a few hundred bytes worth of plain text
+ * in the language are needed.  The detection process will attempt to
+ * ignore html or xml style markup that could otherwise obscure the content.
+ */
+ 
+
+struct UCharsetDetector;
+/**
+  * Structure representing a charset detector
+  * @stable ICU 3.6
+  */
+typedef struct UCharsetDetector UCharsetDetector;
+
+struct UCharsetMatch;
+/**
+  *  Opaque structure representing a match that was identified
+  *  from a charset detection operation.
+  *  @stable ICU 3.6
+  */
+typedef struct UCharsetMatch UCharsetMatch;
+
+/**
+  *  Open a charset detector.
+  *
+  *  @param status Any error conditions occurring during the open
+  *                operation are reported back in this variable.
+  *  @return the newly opened charset detector.
+  *  @stable ICU 3.6
+  */
+U_STABLE UCharsetDetector * U_EXPORT2
+ucsdet_open(UErrorCode   *status);
+
+/**
+  * Close a charset detector.  All storage and any other resources
+  *   owned by this charset detector will be released.  Failure to
+  *   close a charset detector when finished with it can result in
+  *   memory leaks in the application.
+  *
+  *  @param ucsd  The charset detector to be closed.
+  *  @stable ICU 3.6
+  */
+U_STABLE void U_EXPORT2
+ucsdet_close(UCharsetDetector *ucsd);
+
+/**
+  * Set the input byte data whose charset is to detected.
+  *
+  * Ownership of the input  text byte array remains with the caller.
+  * The input string must not be altered or deleted until the charset
+  * detector is either closed or reset to refer to different input text.
+  *
+  * @param ucsd   the charset detector to be used.
+  * @param textIn the input text of unknown encoding.   .
+  * @param len    the length of the input text, or -1 if the text
+  *               is NUL terminated.
+  * @param status any error conditions are reported back in this variable.
+  *
+  * @stable ICU 3.6
+  */
+U_STABLE void U_EXPORT2
+ucsdet_setText(UCharsetDetector *ucsd, const char *textIn, int32_t len, UErrorCode *status);
+
+
+/** Set the declared encoding for charset detection.
+ *  The declared encoding of an input text is an encoding obtained
+ *  by the user from an http header or xml declaration or similar source that
+ *  can be provided as an additional hint to the charset detector.
+ *
+ *  How and whether the declared encoding will be used during the
+ *  detection process is TBD.
+ *
+ * @param ucsd      the charset detector to be used.
+ * @param encoding  an encoding for the current data obtained from
+ *                  a header or declaration or other source outside
+ *                  of the byte data itself.
+ * @param length    the length of the encoding name, or -1 if the name string
+ *                  is NUL terminated.
+ * @param status    any error conditions are reported back in this variable.
+ *
+ * @stable ICU 3.6
+ */
+U_STABLE void U_EXPORT2
+ucsdet_setDeclaredEncoding(UCharsetDetector *ucsd, const char *encoding, int32_t length, UErrorCode *status);
+
+
+/**
+ * Return the charset that best matches the supplied input data.
+ * 
+ * Note though, that because the detection 
+ * only looks at the start of the input data,
+ * there is a possibility that the returned charset will fail to handle
+ * the full set of input data.
+ * <p>
+ * The returned UCharsetMatch object is owned by the UCharsetDetector.
+ * It will remain valid until the detector input is reset, or until
+ * the detector is closed.
+ * <p>
+ * The function will fail if
+ *  <ul>
+ *    <li>no charset appears to match the data.</li>
+ *    <li>no input text has been provided</li>
+ *  </ul>
+ *
+ * @param ucsd      the charset detector to be used.
+ * @param status    any error conditions are reported back in this variable.
+ * @return          a UCharsetMatch  representing the best matching charset,
+ *                  or NULL if no charset matches the byte data.
+ *
+ * @stable ICU 3.6
+ */
+U_STABLE const UCharsetMatch * U_EXPORT2
+ucsdet_detect(UCharsetDetector *ucsd, UErrorCode *status);
+    
+
+/**
+ *  Find all charset matches that appear to be consistent with the input,
+ *  returning an array of results.  The results are ordered with the
+ *  best quality match first.
+ *
+ *  Because the detection only looks at a limited amount of the
+ *  input byte data, some of the returned charsets may fail to handle
+ *  the all of input data.
+ *  <p>
+ *  The returned UCharsetMatch objects are owned by the UCharsetDetector.
+ *  They will remain valid until the detector is closed or modified
+ *  
+ * <p>
+ * Return an error if 
+ *  <ul>
+ *    <li>no charsets appear to match the input data.</li>
+ *    <li>no input text has been provided</li>
+ *  </ul>
+ * 
+ * @param ucsd          the charset detector to be used.
+ * @param matchesFound  pointer to a variable that will be set to the
+ *                      number of charsets identified that are consistent with
+ *                      the input data.  Output only.
+ * @param status        any error conditions are reported back in this variable.
+ * @return              A pointer to an array of pointers to UCharSetMatch objects.
+ *                      This array, and the UCharSetMatch instances to which it refers,
+ *                      are owned by the UCharsetDetector, and will remain valid until
+ *                      the detector is closed or modified.
+ * @stable ICU 3.6
+ */
+U_STABLE const UCharsetMatch ** U_EXPORT2
+ucsdet_detectAll(UCharsetDetector *ucsd, int32_t *matchesFound, UErrorCode *status);
+
+
+
+/**
+ *  Get the name of the charset represented by a UCharsetMatch.
+ *
+ *  The storage for the returned name string is owned by the
+ *  UCharsetMatch, and will remain valid while the UCharsetMatch
+ *  is valid.
+ *
+ *  The name returned is suitable for use with the ICU conversion APIs.
+ *
+ *  @param ucsm    The charset match object.
+ *  @param status  Any error conditions are reported back in this variable.
+ *  @return        The name of the matching charset.
+ *
+ *  @stable ICU 3.6
+ */
+U_STABLE const char * U_EXPORT2
+ucsdet_getName(const UCharsetMatch *ucsm, UErrorCode *status);
+
+/**
+ *  Get a confidence number for the quality of the match of the byte
+ *  data with the charset.  Confidence numbers range from zero to 100,
+ *  with 100 representing complete confidence and zero representing
+ *  no confidence.
+ *
+ *  The confidence values are somewhat arbitrary.  They define an
+ *  an ordering within the results for any single detection operation
+ *  but are not generally comparable between the results for different input.
+ *
+ *  A confidence value of ten does have a general meaning - it is used
+ *  for charsets that can represent the input data, but for which there
+ *  is no other indication that suggests that the charset is the correct one.
+ *  Pure 7 bit ASCII data, for example, is compatible with a
+ *  great many charsets, most of which will appear as possible matches
+ *  with a confidence of 10.
+ *
+ *  @param ucsm    The charset match object.
+ *  @param status  Any error conditions are reported back in this variable.
+ *  @return        A confidence number for the charset match.
+ *
+ *  @stable ICU 3.6
+ */
+U_STABLE int32_t U_EXPORT2
+ucsdet_getConfidence(const UCharsetMatch *ucsm, UErrorCode *status);
+
+/**
+ *  Get the RFC 3066 code for the language of the input data.
+ *
+ *  The Charset Detection service is intended primarily for detecting
+ *  charsets, not language.  For some, but not all, charsets, a language is
+ *  identified as a byproduct of the detection process, and that is what
+ *  is returned by this function.
+ *
+ *  CAUTION:
+ *    1.  Language information is not available for input data encoded in
+ *        all charsets. In particular, no language is identified
+ *        for UTF-8 input data.
+ *
+ *    2.  Closely related languages may sometimes be confused.
+ *
+ *  If more accurate language detection is required, a linguistic
+ *  analysis package should be used.
+ *
+ *  The storage for the returned name string is owned by the
+ *  UCharsetMatch, and will remain valid while the UCharsetMatch
+ *  is valid.
+ *
+ *  @param ucsm    The charset match object.
+ *  @param status  Any error conditions are reported back in this variable.
+ *  @return        The RFC 3066 code for the language of the input data, or
+ *                 an empty string if the language could not be determined.
+ *
+ *  @stable ICU 3.6
+ */
+U_STABLE const char * U_EXPORT2
+ucsdet_getLanguage(const UCharsetMatch *ucsm, UErrorCode *status);
+
+
+/**
+  *  Get the entire input text as a UChar string, placing it into
+  *  a caller-supplied buffer.  A terminating
+  *  NUL character will be appended to the buffer if space is available.
+  *
+  *  The number of UChars in the output string, not including the terminating
+  *  NUL, is returned. 
+  *
+  *  If the supplied buffer is smaller than required to hold the output,
+  *  the contents of the buffer are undefined.  The full output string length
+  *  (in UChars) is returned as always, and can be used to allocate a buffer
+  *  of the correct size.
+  *
+  *
+  * @param ucsm    The charset match object.
+  * @param buf     A UChar buffer to be filled with the converted text data.
+  * @param cap     The capacity of the buffer in UChars.
+  * @param status  Any error conditions are reported back in this variable.
+  * @return        The number of UChars in the output string.
+  *
+  * @stable ICU 3.6
+  */
+U_STABLE  int32_t U_EXPORT2
+ucsdet_getUChars(const UCharsetMatch *ucsm,
+                 UChar *buf, int32_t cap, UErrorCode *status);
+
+
+
+/**
+  *  Get an iterator over the set of all detectable charsets - 
+  *  over the charsets that are known to the charset detection
+  *  service.
+  *
+  *  The returned UEnumeration provides access to the names of
+  *  the charsets.
+  *
+  *  The state of the Charset detector that is passed in does not
+  *  affect the result of this function, but requiring a valid, open
+  *  charset detector as a parameter insures that the charset detection
+  *  service has been safely initialized and that the required detection
+  *  data is available.
+  *
+  *  @param ucsd a Charset detector.
+  *  @param status  Any error conditions are reported back in this variable.
+  *  @return an iterator providing access to the detectable charset names.
+  *  @stable ICU 3.6
+  */
+U_STABLE  UEnumeration * U_EXPORT2
+ucsdet_getAllDetectableCharsets(const UCharsetDetector *ucsd,  UErrorCode *status);
+
+
+/**
+  *  Test whether input filtering is enabled for this charset detector.
+  *  Input filtering removes text that appears to be HTML or xml
+  *  markup from the input before applying the code page detection
+  *  heuristics.
+  *
+  *  @param ucsd  The charset detector to check.
+  *  @return TRUE if filtering is enabled.
+  *  @stable ICU 3.6
+  */
+U_STABLE  UBool U_EXPORT2
+ucsdet_isInputFilterEnabled(const UCharsetDetector *ucsd);
+
+
+/**
+ * Enable filtering of input text. If filtering is enabled,
+ * text within angle brackets ("<" and ">") will be removed
+ * before detection, which will remove most HTML or xml markup.
+ *
+ * @param ucsd   the charset detector to be modified.
+ * @param filter <code>true</code> to enable input text filtering.
+ * @return The previous setting.
+ *
+ * @stable ICU 3.6
+ */
+U_STABLE  UBool U_EXPORT2
+ucsdet_enableInputFilter(UCharsetDetector *ucsd, UBool filter);
+
+#endif
+#endif   /* __UCSDET_H */
+
+

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/ucurr.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/ucurr.h b/src/apps/couch_collate/platform/osx/icu/unicode/ucurr.h
new file mode 100644
index 0000000..c6b3713
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/ucurr.h
@@ -0,0 +1,270 @@
+/*
+**********************************************************************
+* Copyright (c) 2002-2008, International Business Machines
+* Corporation and others.  All Rights Reserved.
+**********************************************************************
+*/
+#ifndef _UCURR_H_
+#define _UCURR_H_
+
+#include "unicode/utypes.h"
+#include "unicode/uenum.h"
+
+/**
+ * \file 
+ * \brief C API: Encapsulates information about a currency.
+ */
+
+#if !UCONFIG_NO_FORMATTING
+
+/**
+ * The ucurr API encapsulates information about a currency, as defined by
+ * ISO 4217.  A currency is represented by a 3-character string
+ * containing its ISO 4217 code.  This API can return various data
+ * necessary the proper display of a currency:
+ *
+ * <ul><li>A display symbol, for a specific locale
+ * <li>The number of fraction digits to display
+ * <li>A rounding increment
+ * </ul>
+ *
+ * The <tt>DecimalFormat</tt> class uses these data to display
+ * currencies.
+ * @author Alan Liu
+ * @since ICU 2.2
+ */
+
+/**
+ * Finds a currency code for the given locale.
+ * @param locale the locale for which to retrieve a currency code. 
+ *               Currency can be specified by the "currency" keyword
+ *               in which case it overrides the default currency code
+ * @param buff   fill in buffer. Can be NULL for preflighting.
+ * @param buffCapacity capacity of the fill in buffer. Can be 0 for
+ *               preflighting. If it is non-zero, the buff parameter
+ *               must not be NULL.
+ * @param ec error code
+ * @return length of the currency string. It should always be 3. If 0,
+ *                currency couldn't be found or the input values are 
+ *                invalid. 
+ * @stable ICU 2.8
+ */
+U_STABLE int32_t U_EXPORT2
+ucurr_forLocale(const char* locale,
+                UChar* buff,
+                int32_t buffCapacity,
+                UErrorCode* ec);
+
+/**
+ * Selector constants for ucurr_getName().
+ *
+ * @see ucurr_getName
+ * @stable ICU 2.6
+ */
+typedef enum UCurrNameStyle {
+    /**
+     * Selector for ucurr_getName indicating a symbolic name for a
+     * currency, such as "$" for USD.
+     * @stable ICU 2.6
+     */
+    UCURR_SYMBOL_NAME,
+
+    /**
+     * Selector for ucurr_getName indicating the long name for a
+     * currency, such as "US Dollar" for USD.
+     * @stable ICU 2.6
+     */
+    UCURR_LONG_NAME
+} UCurrNameStyle;
+
+#if !UCONFIG_NO_SERVICE
+/**
+ * @stable ICU 2.6
+ */
+typedef const void* UCurrRegistryKey;
+
+/**
+ * Register an (existing) ISO 4217 currency code for the given locale.
+ * Only the country code and the two variants EURO and PRE_EURO are
+ * recognized.
+ * @param isoCode the three-letter ISO 4217 currency code
+ * @param locale  the locale for which to register this currency code
+ * @param status the in/out status code
+ * @return a registry key that can be used to unregister this currency code, or NULL
+ * if there was an error.
+ * @stable ICU 2.6
+ */
+U_STABLE UCurrRegistryKey U_EXPORT2
+ucurr_register(const UChar* isoCode, 
+                   const char* locale,  
+                   UErrorCode* status);
+/**
+ * Unregister the previously-registered currency definitions using the
+ * URegistryKey returned from ucurr_register.  Key becomes invalid after
+ * a successful call and should not be used again.  Any currency 
+ * that might have been hidden by the original ucurr_register call is 
+ * restored.
+ * @param key the registry key returned by a previous call to ucurr_register
+ * @param status the in/out status code, no special meanings are assigned
+ * @return TRUE if the currency for this key was successfully unregistered
+ * @stable ICU 2.6
+ */
+U_STABLE UBool U_EXPORT2
+ucurr_unregister(UCurrRegistryKey key, UErrorCode* status);
+#endif /* UCONFIG_NO_SERVICE */
+
+/**
+ * Returns the display name for the given currency in the
+ * given locale.  For example, the display name for the USD
+ * currency object in the en_US locale is "$".
+ * @param currency null-terminated 3-letter ISO 4217 code
+ * @param locale locale in which to display currency
+ * @param nameStyle selector for which kind of name to return
+ * @param isChoiceFormat fill-in set to TRUE if the returned value
+ * is a ChoiceFormat pattern; otherwise it is a static string
+ * @param len fill-in parameter to receive length of result
+ * @param ec error code
+ * @return pointer to display string of 'len' UChars.  If the resource
+ * data contains no entry for 'currency', then 'currency' itself is
+ * returned.  If *isChoiceFormat is TRUE, then the result is a
+ * ChoiceFormat pattern.  Otherwise it is a static string.
+ * @stable ICU 2.6
+ */
+U_STABLE const UChar* U_EXPORT2
+ucurr_getName(const UChar* currency,
+              const char* locale,
+              UCurrNameStyle nameStyle,
+              UBool* isChoiceFormat,
+              int32_t* len,
+              UErrorCode* ec);
+
+/**
+ * Returns the number of the number of fraction digits that should
+ * be displayed for the given currency.
+ * @param currency null-terminated 3-letter ISO 4217 code
+ * @param ec input-output error code
+ * @return a non-negative number of fraction digits to be
+ * displayed, or 0 if there is an error
+ * @stable ICU 3.0
+ */
+U_STABLE int32_t U_EXPORT2
+ucurr_getDefaultFractionDigits(const UChar* currency,
+                               UErrorCode* ec);
+
+/**
+ * Returns the rounding increment for the given currency, or 0.0 if no
+ * rounding is done by the currency.
+ * @param currency null-terminated 3-letter ISO 4217 code
+ * @param ec input-output error code
+ * @return the non-negative rounding increment, or 0.0 if none,
+ * or 0.0 if there is an error
+ * @stable ICU 3.0
+ */
+U_STABLE double U_EXPORT2
+ucurr_getRoundingIncrement(const UChar* currency,
+                           UErrorCode* ec);
+
+/**
+ * Selector constants for ucurr_openCurrencies().
+ *
+ * @see ucurr_openCurrencies
+ * @stable ICU 3.2
+ */
+typedef enum UCurrCurrencyType {
+    /**
+     * Select all ISO-4217 currency codes.
+     * @stable ICU 3.2
+     */
+    UCURR_ALL = INT32_MAX,
+    /**
+     * Select only ISO-4217 commonly used currency codes.
+     * These currencies can be found in common use, and they usually have
+     * bank notes or coins associated with the currency code.
+     * This does not include fund codes, precious metals and other
+     * various ISO-4217 codes limited to special financial products.
+     * @stable ICU 3.2
+     */
+    UCURR_COMMON = 1,
+    /**
+     * Select ISO-4217 uncommon currency codes.
+     * These codes respresent fund codes, precious metals and other
+     * various ISO-4217 codes limited to special financial products.
+     * A fund code is a monetary resource associated with a currency.
+     * @stable ICU 3.2
+     */
+    UCURR_UNCOMMON = 2,
+    /**
+     * Select only deprecated ISO-4217 codes.
+     * These codes are no longer in general public use.
+     * @stable ICU 3.2
+     */
+    UCURR_DEPRECATED = 4,
+    /**
+     * Select only non-deprecated ISO-4217 codes.
+     * These codes are in general public use.
+     * @stable ICU 3.2
+     */
+    UCURR_NON_DEPRECATED = 8
+} UCurrCurrencyType;
+
+/**
+ * Provides a UEnumeration object for listing ISO-4217 codes.
+ * @param currType You can use one of several UCurrCurrencyType values for this
+ *      variable. You can also | (or) them together to get a specific list of
+ *      currencies. Most people will want to use the (UCURR_CURRENCY|UCURR_NON_DEPRECATED) value to
+ *      get a list of current currencies.
+ * @param pErrorCode Error code
+ * @stable ICU 3.2
+ */
+U_STABLE UEnumeration * U_EXPORT2
+ucurr_openISOCurrencies(uint32_t currType, UErrorCode *pErrorCode);
+
+/** 
+ * Finds the number of valid currency codes for the
+ * given locale and date.
+ * @param locale the locale for which to retrieve the
+ *               currency count.
+ * @param date   the date for which to retrieve the
+ *               currency count for the given locale.
+ * @param ec     error code
+ * @return       the number of currency codes for the
+ *               given locale and date.  If 0, currency
+ *               codes couldn't be found for the input
+ *               values are invalid.
+ * @draft ICU 4.0
+ */
+U_DRAFT int32_t U_EXPORT2
+ucurr_countCurrencies(const char* locale, 
+                 UDate date, 
+                 UErrorCode* ec); 
+
+/** 
+ * Finds a currency code for the given locale and date 
+ * @param locale the locale for which to retrieve a currency code.  
+ *               Currency can be specified by the "currency" keyword 
+ *               in which case it overrides the default currency code 
+ * @param date   the date for which to retrieve a currency code for 
+ *               the given locale. 
+ * @param index  the index within the available list of currency codes
+ *               for the given locale on the given date.
+ * @param buff   fill in buffer. Can be NULL for preflighting. 
+ * @param buffCapacity capacity of the fill in buffer. Can be 0 for 
+ *               preflighting. If it is non-zero, the buff parameter 
+ *               must not be NULL. 
+ * @param ec     error code 
+ * @return       length of the currency string. It should always be 3. 
+ *               If 0, currency couldn't be found or the input values are  
+ *               invalid.  
+ * @draft ICU 4.0 
+ */ 
+U_DRAFT int32_t U_EXPORT2 
+ucurr_forLocaleAndDate(const char* locale, 
+                UDate date, 
+                int32_t index,
+                UChar* buff, 
+                int32_t buffCapacity, 
+                UErrorCode* ec); 
+
+#endif /* #if !UCONFIG_NO_FORMATTING */
+
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/udat.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/udat.h b/src/apps/couch_collate/platform/osx/icu/unicode/udat.h
new file mode 100644
index 0000000..e4b43a4
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/udat.h
@@ -0,0 +1,962 @@
+/*
+ *******************************************************************************
+ * Copyright (C) 1996-2009, International Business Machines
+ * Corporation and others. All Rights Reserved.
+ *******************************************************************************
+*/
+
+#ifndef UDAT_H
+#define UDAT_H
+
+#include "unicode/utypes.h"
+
+#if !UCONFIG_NO_FORMATTING
+
+#include "unicode/ucal.h"
+#include "unicode/unum.h"
+/**
+ * \file
+ * \brief C API: DateFormat
+ *
+ * <h2> Date Format C API</h2>
+ *
+ * Date Format C API  consists of functions that convert dates and
+ * times from their internal representations to textual form and back again in a
+ * language-independent manner. Converting from the internal representation (milliseconds
+ * since midnight, January 1, 1970) to text is known as "formatting," and converting
+ * from text to millis is known as "parsing."  We currently define only one concrete
+ * structure UDateFormat, which can handle pretty much all normal
+ * date formatting and parsing actions.
+ * <P>
+ * Date Format helps you to format and parse dates for any locale. Your code can
+ * be completely independent of the locale conventions for months, days of the
+ * week, or even the calendar format: lunar vs. solar.
+ * <P>
+ * To format a date for the current Locale with default time and date style,
+ * use one of the static factory methods:
+ * <pre>
+ * \code
+ *  UErrorCode status = U_ZERO_ERROR;
+ *  UChar *myString;
+ *  int32_t myStrlen = 0;
+ *  UDateFormat* dfmt = udat_open(UDAT_DEFAULT, UDAT_DEFAULT, NULL, NULL, -1, NULL, -1, &status);
+ *  myStrlen = udat_format(dfmt, myDate, NULL, myStrlen, NULL, &status);
+ *  if (status==U_BUFFER_OVERFLOW_ERROR){
+ *      status=U_ZERO_ERROR;
+ *      myString=(UChar*)malloc(sizeof(UChar) * (myStrlen+1) );
+ *      udat_format(dfmt, myDate, myString, myStrlen+1, NULL, &status);
+ *  }
+ * \endcode
+ * </pre>
+ * If you are formatting multiple numbers, it is more efficient to get the
+ * format and use it multiple times so that the system doesn't have to fetch the
+ * information about the local language and country conventions multiple times.
+ * <pre>
+ * \code
+ *  UErrorCode status = U_ZERO_ERROR;
+ *  int32_t i, myStrlen = 0;
+ *  UChar* myString;
+ *  char buffer[1024];
+ *  UDate myDateArr[] = { 0.0, 100000000.0, 2000000000.0 }; // test values
+ *  UDateFormat* df = udat_open(UDAT_DEFAULT, UDAT_DEFAULT, NULL, NULL, -1, NULL, 0, &status);
+ *  for (i = 0; i < 3; i++) {
+ *      myStrlen = udat_format(df, myDateArr[i], NULL, myStrlen, NULL, &status);
+ *      if(status == U_BUFFER_OVERFLOW_ERROR){
+ *          status = U_ZERO_ERROR;
+ *          myString = (UChar*)malloc(sizeof(UChar) * (myStrlen+1) );
+ *          udat_format(df, myDateArr[i], myString, myStrlen+1, NULL, &status);
+ *          printf("%s\n", u_austrcpy(buffer, myString) );
+ *          free(myString);
+ *      }
+ *  }
+ * \endcode
+ * </pre>
+ * To get specific fields of a date, you can use UFieldPosition to
+ * get specific fields.
+ * <pre>
+ * \code
+ *  UErrorCode status = U_ZERO_ERROR;
+ *  UFieldPosition pos;
+ *  UChar *myString;
+ *  int32_t myStrlen = 0;
+ *  char buffer[1024];
+ *
+ *  pos.field = 1;  // Same as the DateFormat::EField enum
+ *  UDateFormat* dfmt = udat_open(UDAT_DEFAULT, UDAT_DEFAULT, NULL, -1, NULL, 0, &status);
+ *  myStrlen = udat_format(dfmt, myDate, NULL, myStrlen, &pos, &status);
+ *  if (status==U_BUFFER_OVERFLOW_ERROR){
+ *      status=U_ZERO_ERROR;
+ *      myString=(UChar*)malloc(sizeof(UChar) * (myStrlen+1) );
+ *      udat_format(dfmt, myDate, myString, myStrlen+1, &pos, &status);
+ *  }
+ *  printf("date format: %s\n", u_austrcpy(buffer, myString));
+ *  buffer[pos.endIndex] = 0;   // NULL terminate the string.
+ *  printf("UFieldPosition position equals %s\n", &buffer[pos.beginIndex]);
+ * \endcode
+ * </pre>
+ * To format a date for a different Locale, specify it in the call to
+ * udat_open()
+ * <pre>
+ * \code
+ *        UDateFormat* df = udat_open(UDAT_SHORT, UDAT_SHORT, "fr_FR", NULL, -1, NULL, 0, &status);
+ * \endcode
+ * </pre>
+ * You can use a DateFormat API udat_parse() to parse.
+ * <pre>
+ * \code
+ *  UErrorCode status = U_ZERO_ERROR;
+ *  int32_t parsepos=0;
+ *  UDate myDate = udat_parse(df, myString, u_strlen(myString), &parsepos, &status);
+ * \endcode
+ * </pre>
+ *  You can pass in different options for the arguments for date and time style
+ *  to control the length of the result; from SHORT to MEDIUM to LONG to FULL.
+ *  The exact result depends on the locale, but generally:
+ *  see UDateFormatStyle for more details
+ * <ul type=round>
+ *   <li>   UDAT_SHORT is completely numeric, such as 12/13/52 or 3:30pm
+ *   <li>   UDAT_MEDIUM is longer, such as Jan 12, 1952
+ *   <li>   UDAT_LONG is longer, such as January 12, 1952 or 3:30:32pm
+ *   <li>   UDAT_FULL is pretty completely specified, such as
+ *          Tuesday, April 12, 1952 AD or 3:30:42pm PST.
+ * </ul>
+ * You can also set the time zone on the format if you wish.
+ * <P>
+ * You can also use forms of the parse and format methods with Parse Position and
+ * UFieldPosition to allow you to
+ * <ul type=round>
+ *   <li>   Progressively parse through pieces of a string.
+ *   <li>   Align any particular field, or find out where it is for selection
+ *          on the screen.
+ * </ul>
+ */
+
+/** A date formatter.
+ *  For usage in C programs.
+ *  @stable ICU 2.6
+ */
+typedef void* UDateFormat;
+
+/** The possible date/time format styles 
+ *  @stable ICU 2.6
+ */
+typedef enum UDateFormatStyle {
+    /** Full style */
+    UDAT_FULL,
+    /** Long style */
+    UDAT_LONG,
+    /** Medium style */
+    UDAT_MEDIUM,
+    /** Short style */
+    UDAT_SHORT,
+    /** Default style */
+    UDAT_DEFAULT = UDAT_MEDIUM,
+
+    /** Bitfield for relative date */
+    UDAT_RELATIVE = (1 << 7),
+    
+    UDAT_FULL_RELATIVE = UDAT_FULL | UDAT_RELATIVE,
+        
+    UDAT_LONG_RELATIVE = UDAT_LONG | UDAT_RELATIVE,
+    
+    UDAT_MEDIUM_RELATIVE = UDAT_MEDIUM | UDAT_RELATIVE,
+    
+    UDAT_SHORT_RELATIVE = UDAT_SHORT | UDAT_RELATIVE,
+    
+    
+    /** No style */
+    UDAT_NONE = -1,
+    /** for internal API use only */
+    UDAT_IGNORE = -2
+
+} UDateFormatStyle;
+
+
+/**
+ * @{
+ * Below are a set of pre-defined skeletons.
+ *
+ * <P>
+ * A skeleton 
+ * <ol>
+ * <li>
+ *    only keeps the field pattern letter and ignores all other parts 
+ *    in a pattern, such as space, punctuations, and string literals.
+ * </li>
+ * <li>
+ *    hides the order of fields. 
+ * </li>
+ * <li>
+ *    might hide a field's pattern letter length.
+ *
+ *    For those non-digit calendar fields, the pattern letter length is 
+ *    important, such as MMM, MMMM, and MMMMM; EEE and EEEE, 
+ *    and the field's pattern letter length is honored.
+ *    
+ *    For the digit calendar fields,  such as M or MM, d or dd, yy or yyyy, 
+ *    the field pattern length is ignored and the best match, which is defined 
+ *    in date time patterns, will be returned without honor the field pattern
+ *    letter length in skeleton.
+ * </li>
+ * </ol>
+ *
+ * @stable ICU 4.0
+ */
+
+#define UDAT_MINUTE_SECOND              "ms"
+#define UDAT_HOUR24_MINUTE              "Hm"
+#define UDAT_HOUR24_MINUTE_SECOND       "Hms"      
+#define UDAT_HOUR_MINUTE_SECOND         "hms"
+#define UDAT_STANDALONE_MONTH           "LLLL"
+#define UDAT_ABBR_STANDALONE_MONTH      "LLL"
+#define UDAT_YEAR_QUARTER               "yQQQ"
+#define UDAT_YEAR_ABBR_QUARTER          "yQ"
+
+/** @} */
+
+/**
+ * @{
+ * Below are a set of pre-defined skeletons that 
+ * have pre-defined interval patterns in resource files.
+ * Users are encouraged to use them in date interval format factory methods.
+ *
+ */
+#define UDAT_HOUR_MINUTE                "hm"
+#define UDAT_YEAR                       "y"
+#define UDAT_DAY                        "d"
+#define UDAT_NUM_MONTH_WEEKDAY_DAY      "MEd"
+#define UDAT_YEAR_NUM_MONTH             "yM"              
+#define UDAT_NUM_MONTH_DAY              "Md"
+#define UDAT_YEAR_NUM_MONTH_WEEKDAY_DAY "yMEd"
+#define UDAT_ABBR_MONTH_WEEKDAY_DAY     "MMMEd"
+#define UDAT_YEAR_MONTH                 "yMMMM"
+#define UDAT_YEAR_ABBR_MONTH            "yMMM"
+#define UDAT_MONTH_DAY                  "MMMMd"
+#define UDAT_ABBR_MONTH_DAY             "MMMd" 
+#define UDAT_MONTH_WEEKDAY_DAY          "MMMMEEEEd"
+#define UDAT_YEAR_ABBR_MONTH_WEEKDAY_DAY "yMMMEd" 
+#define UDAT_YEAR_MONTH_WEEKDAY_DAY     "yMMMMEEEEd"
+#define UDAT_YEAR_MONTH_DAY             "yMMMMd"
+#define UDAT_YEAR_ABBR_MONTH_DAY        "yMMMd"
+#define UDAT_YEAR_NUM_MONTH_DAY         "yMd"
+#define UDAT_NUM_MONTH                  "M"
+#define UDAT_ABBR_MONTH                 "MMM"
+#define UDAT_MONTH                      "MMMM"
+#define UDAT_HOUR_MINUTE_GENERIC_TZ     "hmv"
+#define UDAT_HOUR_MINUTE_TZ             "hmz"
+#define UDAT_HOUR                       "h"
+#define UDAT_HOUR_GENERIC_TZ            "hv"
+#define UDAT_HOUR_TZ                    "hz"
+
+/** @} */
+
+
+/**
+ * FieldPosition and UFieldPosition selectors for format fields
+ * defined by DateFormat and UDateFormat.
+ * @stable ICU 3.0
+ */
+typedef enum UDateFormatField {
+    /**
+     * FieldPosition and UFieldPosition selector for 'G' field alignment,
+     * corresponding to the UCAL_ERA field.
+     * @stable ICU 3.0
+     */
+    UDAT_ERA_FIELD = 0,
+
+    /**
+     * FieldPosition and UFieldPosition selector for 'y' field alignment,
+     * corresponding to the UCAL_YEAR field.
+     * @stable ICU 3.0
+     */
+    UDAT_YEAR_FIELD = 1,
+
+    /**
+     * FieldPosition and UFieldPosition selector for 'M' field alignment,
+     * corresponding to the UCAL_MONTH field.
+     * @stable ICU 3.0
+     */
+    UDAT_MONTH_FIELD = 2,
+
+    /**
+     * FieldPosition and UFieldPosition selector for 'd' field alignment,
+     * corresponding to the UCAL_DATE field.
+     * @stable ICU 3.0
+     */
+    UDAT_DATE_FIELD = 3,
+
+    /**
+     * FieldPosition and UFieldPosition selector for 'k' field alignment,
+     * corresponding to the UCAL_HOUR_OF_DAY field.
+     * UDAT_HOUR_OF_DAY1_FIELD is used for the one-based 24-hour clock.
+     * For example, 23:59 + 01:00 results in 24:59.
+     * @stable ICU 3.0
+     */
+    UDAT_HOUR_OF_DAY1_FIELD = 4,
+
+    /**
+     * FieldPosition and UFieldPosition selector for 'H' field alignment,
+     * corresponding to the UCAL_HOUR_OF_DAY field.
+     * UDAT_HOUR_OF_DAY0_FIELD is used for the zero-based 24-hour clock.
+     * For example, 23:59 + 01:00 results in 00:59.
+     * @stable ICU 3.0
+     */
+    UDAT_HOUR_OF_DAY0_FIELD = 5,
+
+    /**
+     * FieldPosition and UFieldPosition selector for 'm' field alignment,
+     * corresponding to the UCAL_MINUTE field.
+     * @stable ICU 3.0
+     */
+    UDAT_MINUTE_FIELD = 6,
+
+    /**
+     * FieldPosition and UFieldPosition selector for 's' field alignment,
+     * corresponding to the UCAL_SECOND field.
+     * @stable ICU 3.0
+     */
+    UDAT_SECOND_FIELD = 7,
+
+    /**
+     * FieldPosition and UFieldPosition selector for 'S' field alignment,
+     * corresponding to the UCAL_MILLISECOND field.
+     * @stable ICU 3.0
+     */
+    UDAT_FRACTIONAL_SECOND_FIELD = 8,
+
+    /**
+     * FieldPosition and UFieldPosition selector for 'E' field alignment,
+     * corresponding to the UCAL_DAY_OF_WEEK field.
+     * @stable ICU 3.0
+     */
+    UDAT_DAY_OF_WEEK_FIELD = 9,
+
+    /**
+     * FieldPosition and UFieldPosition selector for 'D' field alignment,
+     * corresponding to the UCAL_DAY_OF_YEAR field.
+     * @stable ICU 3.0
+     */
+    UDAT_DAY_OF_YEAR_FIELD = 10,
+
+    /**
+     * FieldPosition and UFieldPosition selector for 'F' field alignment,
+     * corresponding to the UCAL_DAY_OF_WEEK_IN_MONTH field.
+     * @stable ICU 3.0
+     */
+    UDAT_DAY_OF_WEEK_IN_MONTH_FIELD = 11,
+
+    /**
+     * FieldPosition and UFieldPosition selector for 'w' field alignment,
+     * corresponding to the UCAL_WEEK_OF_YEAR field.
+     * @stable ICU 3.0
+     */
+    UDAT_WEEK_OF_YEAR_FIELD = 12,
+
+    /**
+     * FieldPosition and UFieldPosition selector for 'W' field alignment,
+     * corresponding to the UCAL_WEEK_OF_MONTH field.
+     * @stable ICU 3.0
+     */
+    UDAT_WEEK_OF_MONTH_FIELD = 13,
+
+    /**
+     * FieldPosition and UFieldPosition selector for 'a' field alignment,
+     * corresponding to the UCAL_AM_PM field.
+     * @stable ICU 3.0
+     */
+    UDAT_AM_PM_FIELD = 14,
+
+    /**
+     * FieldPosition and UFieldPosition selector for 'h' field alignment,
+     * corresponding to the UCAL_HOUR field.
+     * UDAT_HOUR1_FIELD is used for the one-based 12-hour clock.
+     * For example, 11:30 PM + 1 hour results in 12:30 AM.
+     * @stable ICU 3.0
+     */
+    UDAT_HOUR1_FIELD = 15,
+
+    /**
+     * FieldPosition and UFieldPosition selector for 'K' field alignment,
+     * corresponding to the UCAL_HOUR field.
+     * UDAT_HOUR0_FIELD is used for the zero-based 12-hour clock.
+     * For example, 11:30 PM + 1 hour results in 00:30 AM.
+     * @stable ICU 3.0
+     */
+    UDAT_HOUR0_FIELD = 16,
+
+    /**
+     * FieldPosition and UFieldPosition selector for 'z' field alignment,
+     * corresponding to the UCAL_ZONE_OFFSET and
+     * UCAL_DST_OFFSET fields.
+     * @stable ICU 3.0
+     */
+    UDAT_TIMEZONE_FIELD = 17,
+
+    /**
+     * FieldPosition and UFieldPosition selector for 'Y' field alignment,
+     * corresponding to the UCAL_YEAR_WOY field.
+     * @stable ICU 3.0
+     */
+    UDAT_YEAR_WOY_FIELD = 18,
+
+    /**
+     * FieldPosition and UFieldPosition selector for 'e' field alignment,
+     * corresponding to the UCAL_DOW_LOCAL field.
+     * @stable ICU 3.0
+     */
+    UDAT_DOW_LOCAL_FIELD = 19,
+
+    /**
+     * FieldPosition and UFieldPosition selector for 'u' field alignment,
+     * corresponding to the UCAL_EXTENDED_YEAR field.
+     * @stable ICU 3.0
+     */
+    UDAT_EXTENDED_YEAR_FIELD = 20,
+
+    /**
+     * FieldPosition and UFieldPosition selector for 'g' field alignment,
+     * corresponding to the UCAL_JULIAN_DAY field.
+     * @stable ICU 3.0
+     */
+    UDAT_JULIAN_DAY_FIELD = 21,
+
+    /**
+     * FieldPosition and UFieldPosition selector for 'A' field alignment,
+     * corresponding to the UCAL_MILLISECONDS_IN_DAY field.
+     * @stable ICU 3.0
+     */
+    UDAT_MILLISECONDS_IN_DAY_FIELD = 22,
+
+    /**
+     * FieldPosition and UFieldPosition selector for 'Z' field alignment,
+     * corresponding to the UCAL_ZONE_OFFSET and
+     * UCAL_DST_OFFSET fields.
+     * @stable ICU 3.0
+     */
+    UDAT_TIMEZONE_RFC_FIELD = 23,
+
+    /**
+     * FieldPosition and UFieldPosition selector for 'v' field alignment,
+     * corresponding to the UCAL_ZONE_OFFSET field.
+     * @stable ICU 3.4
+     */
+    UDAT_TIMEZONE_GENERIC_FIELD = 24,
+    /**
+     * FieldPosition selector for 'c' field alignment,
+     * corresponding to the {@link #UCAL_DATE} field. 
+     * This displays the stand alone day name, if available.
+     * @stable ICU 3.4
+     */
+    UDAT_STANDALONE_DAY_FIELD = 25,
+    
+    /**
+     * FieldPosition selector for 'L' field alignment,
+     * corresponding to the {@link #UCAL_MONTH} field.  
+     * This displays the stand alone month name, if available.
+     * @stable ICU 3.4
+     */
+    UDAT_STANDALONE_MONTH_FIELD = 26,
+
+    /**
+     * FieldPosition selector for "Q" field alignment,
+     * corresponding to quarters. This is implemented
+     * using the {@link #UCAL_MONTH} field. This
+     * displays the quarter.
+     * @stable ICU 3.6
+     */
+    UDAT_QUARTER_FIELD = 27,
+
+    /**
+     * FieldPosition selector for the "q" field alignment,
+     * corresponding to stand-alone quarters. This is
+     * implemented using the {@link #UCAL_MONTH} field.
+     * This displays the stand-alone quarter.
+     * @stable ICU 3.6
+     */
+    UDAT_STANDALONE_QUARTER_FIELD = 28,
+
+    /**
+     * FieldPosition and UFieldPosition selector for 'V' field alignment,
+     * corresponding to the UCAL_ZONE_OFFSET field.
+     * @stable ICU 3.8
+     */
+    UDAT_TIMEZONE_SPECIAL_FIELD = 29,
+
+   /**
+     * Number of FieldPosition and UFieldPosition selectors for 
+     * DateFormat and UDateFormat.
+     * Valid selectors range from 0 to UDAT_FIELD_COUNT-1.
+     * This value is subject to change if new fields are defined
+     * in the future.
+     * @stable ICU 3.0
+     */
+    UDAT_FIELD_COUNT = 30
+
+} UDateFormatField;
+
+/**
+ * Open a new UDateFormat for formatting and parsing dates and times.
+ * A UDateFormat may be used to format dates in calls to {@link #udat_format },
+ * and to parse dates in calls to {@link #udat_parse }.
+ * @param timeStyle The style used to format times; one of UDAT_FULL, UDAT_LONG,
+ * UDAT_MEDIUM, UDAT_SHORT, UDAT_DEFAULT, or UDAT_NONE (relative time styles
+ * are not currently supported)
+ * @param dateStyle The style used to format dates; one of UDAT_FULL, UDAT_LONG,
+ * UDAT_MEDIUM, UDAT_SHORT, UDAT_DEFAULT, UDAT_FULL_RELATIVE, UDAT_LONG_RELATIVE,
+ * UDAT_MEDIUM_RELATIVE, UDAT_SHORT_RELATIVE, or UDAT_NONE
+ * @param locale The locale specifying the formatting conventions
+ * @param tzID A timezone ID specifying the timezone to use.  If 0, use
+ * the default timezone.
+ * @param tzIDLength The length of tzID, or -1 if null-terminated.
+ * @param pattern A pattern specifying the format to use.
+ * @param patternLength The number of characters in the pattern, or -1 if null-terminated.
+ * @param status A pointer to an UErrorCode to receive any errors
+ * @return A pointer to a UDateFormat to use for formatting dates and times, or 0 if
+ * an error occurred.
+ * @stable ICU 2.0
+ */
+U_STABLE UDateFormat* U_EXPORT2 
+udat_open(UDateFormatStyle  timeStyle,
+          UDateFormatStyle  dateStyle,
+          const char        *locale,
+          const UChar       *tzID,
+          int32_t           tzIDLength,
+          const UChar       *pattern,
+          int32_t           patternLength,
+          UErrorCode        *status);
+
+
+/**
+* Close a UDateFormat.
+* Once closed, a UDateFormat may no longer be used.
+* @param format The formatter to close.
+* @stable ICU 2.0
+*/
+U_STABLE void U_EXPORT2 
+udat_close(UDateFormat* format);
+
+/**
+ * Open a copy of a UDateFormat.
+ * This function performs a deep copy.
+ * @param fmt The format to copy
+ * @param status A pointer to an UErrorCode to receive any errors.
+ * @return A pointer to a UDateFormat identical to fmt.
+ * @stable ICU 2.0
+ */
+U_STABLE UDateFormat* U_EXPORT2 
+udat_clone(const UDateFormat *fmt,
+       UErrorCode *status);
+
+/**
+* Format a date using an UDateFormat.
+* The date will be formatted using the conventions specified in {@link #udat_open }
+* @param format The formatter to use
+* @param dateToFormat The date to format
+* @param result A pointer to a buffer to receive the formatted number.
+* @param resultLength The maximum size of result.
+* @param position A pointer to a UFieldPosition.  On input, position->field
+* is read.  On output, position->beginIndex and position->endIndex indicate
+* the beginning and ending indices of field number position->field, if such
+* a field exists.  This parameter may be NULL, in which case no field
+* position data is returned.
+* @param status A pointer to an UErrorCode to receive any errors
+* @return The total buffer size needed; if greater than resultLength, the output was truncated.
+* @see udat_parse
+* @see UFieldPosition
+* @stable ICU 2.0
+*/
+U_STABLE int32_t U_EXPORT2 
+udat_format(    const    UDateFormat*    format,
+                        UDate           dateToFormat,
+                        UChar*          result,
+                        int32_t         resultLength,
+                        UFieldPosition* position,
+                        UErrorCode*     status);
+
+/**
+* Parse a string into an date/time using a UDateFormat.
+* The date will be parsed using the conventions specified in {@link #udat_open }
+* @param format The formatter to use.
+* @param text The text to parse.
+* @param textLength The length of text, or -1 if null-terminated.
+* @param parsePos If not 0, on input a pointer to an integer specifying the offset at which
+* to begin parsing.  If not 0, on output the offset at which parsing ended.
+* @param status A pointer to an UErrorCode to receive any errors
+* @return The value of the parsed date/time
+* @see udat_format
+* @stable ICU 2.0
+*/
+U_STABLE UDate U_EXPORT2 
+udat_parse(    const    UDateFormat*    format,
+            const    UChar*          text,
+                    int32_t         textLength,
+                    int32_t         *parsePos,
+                    UErrorCode      *status);
+
+/**
+* Parse a string into an date/time using a UDateFormat.
+* The date will be parsed using the conventions specified in {@link #udat_open }
+* @param format The formatter to use.
+* @param calendar The calendar in which to store the parsed data.
+* @param text The text to parse.
+* @param textLength The length of text, or -1 if null-terminated.
+* @param parsePos If not 0, on input a pointer to an integer specifying the offset at which
+* to begin parsing.  If not 0, on output the offset at which parsing ended.
+* @param status A pointer to an UErrorCode to receive any errors
+* @see udat_format
+* @stable ICU 2.0
+*/
+U_STABLE void U_EXPORT2 
+udat_parseCalendar(const    UDateFormat*    format,
+                            UCalendar*      calendar,
+                   const    UChar*          text,
+                            int32_t         textLength,
+                            int32_t         *parsePos,
+                            UErrorCode      *status);
+
+/**
+* Determine if an UDateFormat will perform lenient parsing.
+* With lenient parsing, the parser may use heuristics to interpret inputs that do not
+* precisely match the pattern. With strict parsing, inputs must match the pattern.
+* @param fmt The formatter to query
+* @return TRUE if fmt is set to perform lenient parsing, FALSE otherwise.
+* @see udat_setLenient
+* @stable ICU 2.0
+*/
+U_STABLE UBool U_EXPORT2 
+udat_isLenient(const UDateFormat* fmt);
+
+/**
+* Specify whether an UDateFormat will perform lenient parsing.
+* With lenient parsing, the parser may use heuristics to interpret inputs that do not
+* precisely match the pattern. With strict parsing, inputs must match the pattern.
+* @param fmt The formatter to set
+* @param isLenient TRUE if fmt should perform lenient parsing, FALSE otherwise.
+* @see dat_isLenient
+* @stable ICU 2.0
+*/
+U_STABLE void U_EXPORT2 
+udat_setLenient(    UDateFormat*    fmt,
+                    UBool          isLenient);
+
+/**
+* Get the UCalendar associated with an UDateFormat.
+* A UDateFormat uses a UCalendar to convert a raw value to, for example,
+* the day of the week.
+* @param fmt The formatter to query.
+* @return A pointer to the UCalendar used by fmt.
+* @see udat_setCalendar
+* @stable ICU 2.0
+*/
+U_STABLE const UCalendar* U_EXPORT2 
+udat_getCalendar(const UDateFormat* fmt);
+
+/**
+* Set the UCalendar associated with an UDateFormat.
+* A UDateFormat uses a UCalendar to convert a raw value to, for example,
+* the day of the week.
+* @param fmt The formatter to set.
+* @param calendarToSet A pointer to an UCalendar to be used by fmt.
+* @see udat_setCalendar
+* @stable ICU 2.0
+*/
+U_STABLE void U_EXPORT2 
+udat_setCalendar(            UDateFormat*    fmt,
+                    const   UCalendar*      calendarToSet);
+
+/**
+* Get the UNumberFormat associated with an UDateFormat.
+* A UDateFormat uses a UNumberFormat to format numbers within a date,
+* for example the day number.
+* @param fmt The formatter to query.
+* @return A pointer to the UNumberFormat used by fmt to format numbers.
+* @see udat_setNumberFormat
+* @stable ICU 2.0
+*/
+U_STABLE const UNumberFormat* U_EXPORT2 
+udat_getNumberFormat(const UDateFormat* fmt);
+
+/**
+* Set the UNumberFormat associated with an UDateFormat.
+* A UDateFormat uses a UNumberFormat to format numbers within a date,
+* for example the day number.
+* @param fmt The formatter to set.
+* @param numberFormatToSet A pointer to the UNumberFormat to be used by fmt to format numbers.
+* @see udat_getNumberFormat
+* @stable ICU 2.0
+*/
+U_STABLE void U_EXPORT2 
+udat_setNumberFormat(            UDateFormat*    fmt,
+                        const   UNumberFormat*  numberFormatToSet);
+
+/**
+* Get a locale for which date/time formatting patterns are available.
+* A UDateFormat in a locale returned by this function will perform the correct
+* formatting and parsing for the locale.
+* @param localeIndex The index of the desired locale.
+* @return A locale for which date/time formatting patterns are available, or 0 if none.
+* @see udat_countAvailable
+* @stable ICU 2.0
+*/
+U_STABLE const char* U_EXPORT2 
+udat_getAvailable(int32_t localeIndex);
+
+/**
+* Determine how many locales have date/time  formatting patterns available.
+* This function is most useful as determining the loop ending condition for
+* calls to {@link #udat_getAvailable }.
+* @return The number of locales for which date/time formatting patterns are available.
+* @see udat_getAvailable
+* @stable ICU 2.0
+*/
+U_STABLE int32_t U_EXPORT2 
+udat_countAvailable(void);
+
+/**
+* Get the year relative to which all 2-digit years are interpreted.
+* For example, if the 2-digit start year is 2100, the year 99 will be
+* interpreted as 2199.
+* @param fmt The formatter to query.
+* @param status A pointer to an UErrorCode to receive any errors
+* @return The year relative to which all 2-digit years are interpreted.
+* @see udat_Set2DigitYearStart
+* @stable ICU 2.0
+*/
+U_STABLE UDate U_EXPORT2 
+udat_get2DigitYearStart(    const   UDateFormat     *fmt,
+                                    UErrorCode      *status);
+
+/**
+* Set the year relative to which all 2-digit years will be interpreted.
+* For example, if the 2-digit start year is 2100, the year 99 will be
+* interpreted as 2199.
+* @param fmt The formatter to set.
+* @param d The year relative to which all 2-digit years will be interpreted.
+* @param status A pointer to an UErrorCode to receive any errors
+* @see udat_Set2DigitYearStart
+* @stable ICU 2.0
+*/
+U_STABLE void U_EXPORT2 
+udat_set2DigitYearStart(    UDateFormat     *fmt,
+                            UDate           d,
+                            UErrorCode      *status);
+
+/**
+* Extract the pattern from a UDateFormat.
+* The pattern will follow the pattern syntax rules.
+* @param fmt The formatter to query.
+* @param localized TRUE if the pattern should be localized, FALSE otherwise.
+* @param result A pointer to a buffer to receive the pattern.
+* @param resultLength The maximum size of result.
+* @param status A pointer to an UErrorCode to receive any errors
+* @return The total buffer size needed; if greater than resultLength, the output was truncated.
+* @see udat_applyPattern
+* @stable ICU 2.0
+*/
+U_STABLE int32_t U_EXPORT2 
+udat_toPattern(    const   UDateFormat     *fmt,
+                        UBool          localized,
+                        UChar           *result,
+                        int32_t         resultLength,
+                        UErrorCode      *status);
+
+/**
+* Set the pattern used by an UDateFormat.
+* The pattern should follow the pattern syntax rules.
+* @param format The formatter to set.
+* @param localized TRUE if the pattern is localized, FALSE otherwise.
+* @param pattern The new pattern
+* @param patternLength The length of pattern, or -1 if null-terminated.
+* @see udat_toPattern
+* @stable ICU 2.0
+*/
+U_STABLE void U_EXPORT2 
+udat_applyPattern(            UDateFormat     *format,
+                            UBool          localized,
+                    const   UChar           *pattern,
+                            int32_t         patternLength);
+
+/** 
+ * The possible types of date format symbols 
+ * @stable ICU 2.6
+ */
+typedef enum UDateFormatSymbolType {
+    /** The era names, for example AD */
+    UDAT_ERAS,
+    /** The month names, for example February */
+    UDAT_MONTHS,
+    /** The short month names, for example Feb. */
+    UDAT_SHORT_MONTHS,
+    /** The weekday names, for example Monday */
+    UDAT_WEEKDAYS,
+    /** The short weekday names, for example Mon. */
+    UDAT_SHORT_WEEKDAYS,
+    /** The AM/PM names, for example AM */
+    UDAT_AM_PMS,
+    /** The localized characters */
+    UDAT_LOCALIZED_CHARS,
+    /** The long era names, for example Anno Domini */
+    UDAT_ERA_NAMES,
+    /** The narrow month names, for example F */
+    UDAT_NARROW_MONTHS,
+    /** The narrow weekday names, for example N */
+    UDAT_NARROW_WEEKDAYS,
+    /** Standalone context versions of months */
+    UDAT_STANDALONE_MONTHS,
+    UDAT_STANDALONE_SHORT_MONTHS,
+    UDAT_STANDALONE_NARROW_MONTHS,
+    /** Standalone context versions of weekdays */
+    UDAT_STANDALONE_WEEKDAYS,
+    UDAT_STANDALONE_SHORT_WEEKDAYS,
+    UDAT_STANDALONE_NARROW_WEEKDAYS,
+    /** The quarters, for example 1st Quarter */
+    UDAT_QUARTERS,
+    /** The short quarter names, for example Q1 */
+    UDAT_SHORT_QUARTERS,
+    /** Standalone context versions of quarters */
+    UDAT_STANDALONE_QUARTERS,
+    UDAT_STANDALONE_SHORT_QUARTERS
+
+} UDateFormatSymbolType;
+
+struct UDateFormatSymbols;
+/** Date format symbols.
+ *  For usage in C programs.
+ *  @stable ICU 2.6
+ */
+typedef struct UDateFormatSymbols UDateFormatSymbols;
+
+/**
+* Get the symbols associated with an UDateFormat.
+* The symbols are what a UDateFormat uses to represent locale-specific data,
+* for example month or day names.
+* @param fmt The formatter to query.
+* @param type The type of symbols to get.  One of UDAT_ERAS, UDAT_MONTHS, UDAT_SHORT_MONTHS,
+* UDAT_WEEKDAYS, UDAT_SHORT_WEEKDAYS, UDAT_AM_PMS, or UDAT_LOCALIZED_CHARS
+* @param symbolIndex The desired symbol of type type.
+* @param result A pointer to a buffer to receive the pattern.
+* @param resultLength The maximum size of result.
+* @param status A pointer to an UErrorCode to receive any errors
+* @return The total buffer size needed; if greater than resultLength, the output was truncated.
+* @see udat_countSymbols
+* @see udat_setSymbols
+* @stable ICU 2.0
+*/
+U_STABLE int32_t U_EXPORT2 
+udat_getSymbols(const   UDateFormat             *fmt,
+                        UDateFormatSymbolType   type,
+                        int32_t                 symbolIndex,
+                        UChar                   *result,
+                        int32_t                 resultLength,
+                        UErrorCode              *status);
+
+/**
+* Count the number of particular symbols for an UDateFormat.
+* This function is most useful as for detemining the loop termination condition
+* for calls to {@link #udat_getSymbols }.
+* @param fmt The formatter to query.
+* @param type The type of symbols to count.  One of UDAT_ERAS, UDAT_MONTHS, UDAT_SHORT_MONTHS,
+* UDAT_WEEKDAYS, UDAT_SHORT_WEEKDAYS, UDAT_AM_PMS, or UDAT_LOCALIZED_CHARS
+* @return The number of symbols of type type.
+* @see udat_getSymbols
+* @see udat_setSymbols
+* @stable ICU 2.0
+*/
+U_STABLE int32_t U_EXPORT2 
+udat_countSymbols(    const    UDateFormat                *fmt,
+                            UDateFormatSymbolType    type);
+
+/**
+* Set the symbols associated with an UDateFormat.
+* The symbols are what a UDateFormat uses to represent locale-specific data,
+* for example month or day names.
+* @param format The formatter to set
+* @param type The type of symbols to set.  One of UDAT_ERAS, UDAT_MONTHS, UDAT_SHORT_MONTHS,
+* UDAT_WEEKDAYS, UDAT_SHORT_WEEKDAYS, UDAT_AM_PMS, or UDAT_LOCALIZED_CHARS
+* @param symbolIndex The index of the symbol to set of type type.
+* @param value The new value
+* @param valueLength The length of value, or -1 if null-terminated
+* @param status A pointer to an UErrorCode to receive any errors
+* @see udat_getSymbols
+* @see udat_countSymbols
+* @stable ICU 2.0
+*/
+U_STABLE void U_EXPORT2 
+udat_setSymbols(    UDateFormat             *format,
+                    UDateFormatSymbolType   type,
+                    int32_t                 symbolIndex,
+                    UChar                   *value,
+                    int32_t                 valueLength,
+                    UErrorCode              *status);
+
+/**
+ * Get the locale for this date format object.
+ * You can choose between valid and actual locale.
+ * @param fmt The formatter to get the locale from
+ * @param type type of the locale we're looking for (valid or actual) 
+ * @param status error code for the operation
+ * @return the locale name
+ * @stable ICU 2.8
+ */
+U_STABLE const char* U_EXPORT2
+udat_getLocaleByType(const UDateFormat *fmt,
+                     ULocDataLocaleType type,
+                     UErrorCode* status); 
+
+/**
+* Extract the date pattern from a UDateFormat set for relative date formatting.
+* The pattern will follow the pattern syntax rules.
+* @param fmt The formatter to query.
+* @param result A pointer to a buffer to receive the pattern.
+* @param resultLength The maximum size of result.
+* @param status A pointer to a UErrorCode to receive any errors
+* @return The total buffer size needed; if greater than resultLength, the output was truncated.
+* @see udat_applyPatternRelative
+* @internal ICU 4.2 technology preview
+*/
+U_INTERNAL int32_t U_EXPORT2 
+udat_toPatternRelativeDate(const UDateFormat *fmt,
+                           UChar             *result,
+                           int32_t           resultLength,
+                           UErrorCode        *status);
+
+/**
+* Extract the time pattern from a UDateFormat set for relative date formatting.
+* The pattern will follow the pattern syntax rules.
+* @param fmt The formatter to query.
+* @param result A pointer to a buffer to receive the pattern.
+* @param resultLength The maximum size of result.
+* @param status A pointer to a UErrorCode to receive any errors
+* @return The total buffer size needed; if greater than resultLength, the output was truncated.
+* @see udat_applyPatternRelative
+* @internal ICU 4.2 technology preview
+*/
+U_INTERNAL int32_t U_EXPORT2 
+udat_toPatternRelativeTime(const UDateFormat *fmt,
+                           UChar             *result,
+                           int32_t           resultLength,
+                           UErrorCode        *status);
+
+/**
+* Set the date & time patterns used by a UDateFormat set for relative date formatting.
+* The patterns should follow the pattern syntax rules.
+* @param format The formatter to set.
+* @param datePattern The new date pattern
+* @param datePatternLength The length of datePattern, or -1 if null-terminated.
+* @param timePattern The new time pattern
+* @param timePatternLength The length of timePattern, or -1 if null-terminated.
+* @param status A pointer to a UErrorCode to receive any errors
+* @see udat_toPatternRelativeDate, udat_toPatternRelativeTime
+* @internal ICU 4.2 technology preview
+*/
+U_INTERNAL void U_EXPORT2 
+udat_applyPatternRelative(UDateFormat *format,
+                          const UChar *datePattern,
+                          int32_t     datePatternLength,
+                          const UChar *timePattern,
+                          int32_t     timePatternLength,
+                          UErrorCode  *status);
+
+#endif /* #if !UCONFIG_NO_FORMATTING */
+
+#endif


[70/96] [abbrv] support static build

Posted by be...@apache.org.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/uchriter.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/uchriter.h b/src/apps/couch_collate/platform/osx/icu/unicode/uchriter.h
new file mode 100644
index 0000000..6d5a990
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/uchriter.h
@@ -0,0 +1,381 @@
+/*
+**********************************************************************
+*   Copyright (C) 1998-2005, International Business Machines
+*   Corporation and others.  All Rights Reserved.
+**********************************************************************
+*/
+
+#ifndef UCHRITER_H
+#define UCHRITER_H
+
+#include "unicode/utypes.h"
+#include "unicode/chariter.h"
+
+/**
+ * \file 
+ * \brief C++ API: UChar Character Iterator
+ */
+ 
+U_NAMESPACE_BEGIN
+
+/**
+ * A concrete subclass of CharacterIterator that iterates over the
+ * characters (code units or code points) in a UChar array.
+ * It's possible not only to create an
+ * iterator that iterates over an entire UChar array, but also to
+ * create one that iterates over only a subrange of a UChar array
+ * (iterators over different subranges of the same UChar array don't
+ * compare equal).
+ * @see CharacterIterator
+ * @see ForwardCharacterIterator
+ * @stable ICU 2.0
+ */
+class U_COMMON_API UCharCharacterIterator : public CharacterIterator {
+public:
+  /**
+   * Create an iterator over the UChar array referred to by "textPtr".
+   * The iteration range is 0 to <code>length-1</code>.
+   * text is only aliased, not adopted (the
+   * destructor will not delete it).
+   * @param textPtr The UChar array to be iterated over
+   * @param length The length of the UChar array
+   * @stable ICU 2.0
+   */
+  UCharCharacterIterator(const UChar* textPtr, int32_t length);
+
+  /**
+   * Create an iterator over the UChar array referred to by "textPtr".
+   * The iteration range is 0 to <code>length-1</code>.
+   * text is only aliased, not adopted (the
+   * destructor will not delete it).
+   * The starting
+   * position is specified by "position". If "position" is outside the valid
+   * iteration range, the behavior of this object is undefined.
+   * @param textPtr The UChar array to be iteratd over
+   * @param length The length of the UChar array
+   * @param position The starting position of the iteration
+   * @stable ICU 2.0
+   */
+  UCharCharacterIterator(const UChar* textPtr, int32_t length,
+                         int32_t position);
+
+  /**
+   * Create an iterator over the UChar array referred to by "textPtr".
+   * The iteration range is 0 to <code>end-1</code>.
+   * text is only aliased, not adopted (the
+   * destructor will not delete it).
+   * The starting
+   * position is specified by "position". If begin and end do not
+   * form a valid iteration range or "position" is outside the valid
+   * iteration range, the behavior of this object is undefined.
+   * @param textPtr The UChar array to be iterated over
+   * @param length The length of the UChar array
+   * @param textBegin  The begin position of the iteration range
+   * @param textEnd    The end position of the iteration range
+   * @param position    The starting position of the iteration
+   * @stable ICU 2.0
+   */
+  UCharCharacterIterator(const UChar* textPtr, int32_t length,
+                         int32_t textBegin,
+                         int32_t textEnd,
+                         int32_t position);
+
+  /**
+   * Copy constructor.  The new iterator iterates over the same range
+   * of the same string as "that", and its initial position is the
+   * same as "that"'s current position.
+   * @param that The UCharCharacterIterator to be copied
+   * @stable ICU 2.0
+   */
+  UCharCharacterIterator(const UCharCharacterIterator&  that);
+
+  /**
+   * Destructor.
+   * @stable ICU 2.0
+   */
+  virtual ~UCharCharacterIterator();
+
+  /**
+   * Assignment operator.  *this is altered to iterate over the sane
+   * range of the same string as "that", and refers to the same
+   * character within that string as "that" does.
+   * @param that The object to be copied
+   * @return the newly created object
+   * @stable ICU 2.0
+   */
+  UCharCharacterIterator&
+  operator=(const UCharCharacterIterator&    that);
+
+  /**
+   * Returns true if the iterators iterate over the same range of the
+   * same string and are pointing at the same character.
+   * @param that The ForwardCharacterIterator used to be compared for equality
+   * @return true if the iterators iterate over the same range of the
+   * same string and are pointing at the same character.
+   * @stable ICU 2.0
+   */
+  virtual UBool          operator==(const ForwardCharacterIterator& that) const;
+
+  /**
+   * Generates a hash code for this iterator.
+   * @return the hash code.
+   * @stable ICU 2.0
+   */
+  virtual int32_t         hashCode(void) const;
+
+  /**
+   * Returns a new UCharCharacterIterator referring to the same
+   * character in the same range of the same string as this one.  The
+   * caller must delete the new iterator.
+   * @return the CharacterIterator newly created
+   * @stable ICU 2.0
+   */
+  virtual CharacterIterator* clone(void) const;
+
+  /**
+   * Sets the iterator to refer to the first code unit in its
+   * iteration range, and returns that code unit.
+   * This can be used to begin an iteration with next().
+   * @return the first code unit in its iteration range.
+   * @stable ICU 2.0
+   */
+  virtual UChar         first(void);
+
+  /**
+   * Sets the iterator to refer to the first code unit in its
+   * iteration range, returns that code unit, and moves the position
+   * to the second code unit. This is an alternative to setToStart()
+   * for forward iteration with nextPostInc().
+   * @return the first code unit in its iteration range
+   * @stable ICU 2.0
+   */
+  virtual UChar         firstPostInc(void);
+
+  /**
+   * Sets the iterator to refer to the first code point in its
+   * iteration range, and returns that code unit,
+   * This can be used to begin an iteration with next32().
+   * Note that an iteration with next32PostInc(), beginning with,
+   * e.g., setToStart() or firstPostInc(), is more efficient.
+   * @return the first code point in its iteration range
+   * @stable ICU 2.0
+   */
+  virtual UChar32       first32(void);
+
+  /**
+   * Sets the iterator to refer to the first code point in its
+   * iteration range, returns that code point, and moves the position
+   * to the second code point. This is an alternative to setToStart()
+   * for forward iteration with next32PostInc().
+   * @return the first code point in its iteration range.
+   * @stable ICU 2.0
+   */
+  virtual UChar32       first32PostInc(void);
+
+  /**
+   * Sets the iterator to refer to the last code unit in its
+   * iteration range, and returns that code unit.
+   * This can be used to begin an iteration with previous().
+   * @return the last code unit in its iteration range.
+   * @stable ICU 2.0
+   */
+  virtual UChar         last(void);
+
+  /**
+   * Sets the iterator to refer to the last code point in its
+   * iteration range, and returns that code unit.
+   * This can be used to begin an iteration with previous32().
+   * @return the last code point in its iteration range.
+   * @stable ICU 2.0
+   */
+  virtual UChar32       last32(void);
+
+  /**
+   * Sets the iterator to refer to the "position"-th code unit
+   * in the text-storage object the iterator refers to, and
+   * returns that code unit.
+   * @param position the position within the text-storage object
+   * @return the code unit
+   * @stable ICU 2.0
+   */
+  virtual UChar         setIndex(int32_t position);
+
+  /**
+   * Sets the iterator to refer to the beginning of the code point
+   * that contains the "position"-th code unit
+   * in the text-storage object the iterator refers to, and
+   * returns that code point.
+   * The current position is adjusted to the beginning of the code point
+   * (its first code unit).
+   * @param position the position within the text-storage object
+   * @return the code unit
+   * @stable ICU 2.0
+   */
+  virtual UChar32       setIndex32(int32_t position);
+
+  /**
+   * Returns the code unit the iterator currently refers to.
+   * @return the code unit the iterator currently refers to.
+   * @stable ICU 2.0
+   */
+  virtual UChar         current(void) const;
+
+  /**
+   * Returns the code point the iterator currently refers to.
+   * @return the code point the iterator currently refers to.
+   * @stable ICU 2.0
+   */
+  virtual UChar32       current32(void) const;
+
+  /**
+   * Advances to the next code unit in the iteration range (toward
+   * endIndex()), and returns that code unit.  If there are no more
+   * code units to return, returns DONE.
+   * @return the next code unit in the iteration range.
+   * @stable ICU 2.0
+   */
+  virtual UChar         next(void);
+
+  /**
+   * Gets the current code unit for returning and advances to the next code unit
+   * in the iteration range
+   * (toward endIndex()).  If there are
+   * no more code units to return, returns DONE.
+   * @return the current code unit.
+   * @stable ICU 2.0
+   */
+  virtual UChar         nextPostInc(void);
+
+  /**
+   * Advances to the next code point in the iteration range (toward
+   * endIndex()), and returns that code point.  If there are no more
+   * code points to return, returns DONE.
+   * Note that iteration with "pre-increment" semantics is less
+   * efficient than iteration with "post-increment" semantics
+   * that is provided by next32PostInc().
+   * @return the next code point in the iteration range.
+   * @stable ICU 2.0
+   */
+  virtual UChar32       next32(void);
+
+  /**
+   * Gets the current code point for returning and advances to the next code point
+   * in the iteration range
+   * (toward endIndex()).  If there are
+   * no more code points to return, returns DONE.
+   * @return the current point.
+   * @stable ICU 2.0
+   */
+  virtual UChar32       next32PostInc(void);
+
+  /**
+   * Returns FALSE if there are no more code units or code points
+   * at or after the current position in the iteration range.
+   * This is used with nextPostInc() or next32PostInc() in forward
+   * iteration.
+   * @return FALSE if there are no more code units or code points
+   * at or after the current position in the iteration range.
+   * @stable ICU 2.0
+   */
+  virtual UBool        hasNext();
+
+  /**
+   * Advances to the previous code unit in the iteration range (toward
+   * startIndex()), and returns that code unit.  If there are no more
+   * code units to return, returns DONE.
+   * @return the previous code unit in the iteration range.
+   * @stable ICU 2.0
+   */
+  virtual UChar         previous(void);
+
+  /**
+   * Advances to the previous code point in the iteration range (toward
+   * startIndex()), and returns that code point.  If there are no more
+   * code points to return, returns DONE.
+   * @return the previous code point in the iteration range.
+   * @stable ICU 2.0
+   */
+  virtual UChar32       previous32(void);
+
+  /**
+   * Returns FALSE if there are no more code units or code points
+   * before the current position in the iteration range.
+   * This is used with previous() or previous32() in backward
+   * iteration.
+   * @return FALSE if there are no more code units or code points
+   * before the current position in the iteration range.
+   * @stable ICU 2.0
+   */
+  virtual UBool        hasPrevious();
+
+  /**
+   * Moves the current position relative to the start or end of the
+   * iteration range, or relative to the current position itself.
+   * The movement is expressed in numbers of code units forward
+   * or backward by specifying a positive or negative delta.
+   * @param delta the position relative to origin. A positive delta means forward;
+   * a negative delta means backward.
+   * @param origin Origin enumeration {kStart, kCurrent, kEnd}
+   * @return the new position
+   * @stable ICU 2.0
+   */
+  virtual int32_t      move(int32_t delta, EOrigin origin);
+
+  /**
+   * Moves the current position relative to the start or end of the
+   * iteration range, or relative to the current position itself.
+   * The movement is expressed in numbers of code points forward
+   * or backward by specifying a positive or negative delta.
+   * @param delta the position relative to origin. A positive delta means forward;
+   * a negative delta means backward.
+   * @param origin Origin enumeration {kStart, kCurrent, kEnd}
+   * @return the new position
+   * @stable ICU 2.0
+   */
+  virtual int32_t      move32(int32_t delta, EOrigin origin);
+
+  /**
+   * Sets the iterator to iterate over a new range of text
+   * @stable ICU 2.0
+   */
+  void setText(const UChar* newText, int32_t newTextLength);
+
+  /**
+   * Copies the UChar array under iteration into the UnicodeString
+   * referred to by "result".  Even if this iterator iterates across
+   * only a part of this string, the whole string is copied.
+   * @param result Receives a copy of the text under iteration.
+   * @stable ICU 2.0
+   */
+  virtual void            getText(UnicodeString& result);
+
+  /**
+   * Return a class ID for this class (not really public)
+   * @return a class ID for this class
+   * @stable ICU 2.0
+   */
+  static UClassID         U_EXPORT2 getStaticClassID(void);
+
+  /**
+   * Return a class ID for this object (not really public)
+   * @return a class ID for this object.
+   * @stable ICU 2.0
+   */
+  virtual UClassID        getDynamicClassID(void) const;
+
+protected:
+  /**
+   * Protected constructor
+   * @stable ICU 2.0
+   */
+  UCharCharacterIterator();
+  /**
+   * Protected member text
+   * @stable ICU 2.0
+   */
+  const UChar*            text;
+
+};
+
+U_NAMESPACE_END
+#endif

http://git-wip-us.apache.org/repos/asf/couchdb/blob/79f67b6a/src/apps/couch_collate/platform/osx/icu/unicode/uclean.h
----------------------------------------------------------------------
diff --git a/src/apps/couch_collate/platform/osx/icu/unicode/uclean.h b/src/apps/couch_collate/platform/osx/icu/unicode/uclean.h
new file mode 100644
index 0000000..a13924a
--- /dev/null
+++ b/src/apps/couch_collate/platform/osx/icu/unicode/uclean.h
@@ -0,0 +1,267 @@
+/*
+******************************************************************************
+*                                                                            *
+* Copyright (C) 2001-2005, International Business Machines                   *
+*                Corporation and others. All Rights Reserved.                *
+*                                                                            *
+******************************************************************************
+*   file name:  uclean.h
+*   encoding:   US-ASCII
+*   tab size:   8 (not used)
+*   indentation:4
+*
+*   created on: 2001July05
+*   created by: George Rhoten
+*/
+
+#ifndef __UCLEAN_H__
+#define __UCLEAN_H__
+
+#include "unicode/utypes.h"
+/**
+ * \file
+ * \brief C API: Initialize and clean up ICU
+ */
+ 
+/**
+ *  Initialize ICU. The description further below applies to ICU 2.6 to ICU 3.4.
+ *  Starting with ICU 3.4, u_init() needs not be called any more for
+ *  ensuring thread safety, but it can give an indication for whether ICU
+ *  can load its data. In ICU 3.4, it will try to load the converter alias table
+ *  (cnvalias.icu) and give an error code if that fails.
+ *  This may change in the future.
+ *  <p>
+ *  For ensuring the availability of necessary data, an application should
+ *  open the service objects (converters, collators, etc.) that it will use
+ *  and check for error codes there.
+ *  <p>
+ *  Documentation for ICU 2.6 to ICU 3.4:
+ *  <p>
+ *  This function loads and initializes data items
+ *  that are required internally by various ICU functions.  Use of this explicit
+ *  initialization is required in multi-threaded applications; in 
+ *  single threaded apps, use is optional, but incurs little additional
+ *  cost, and is thus recommended.
+ *  <p>
+ *  In multi-threaded applications, u_init() should be called  in the
+ *  main thread before starting additional threads, or, alternatively
+ *  it can be called in each individual thread once, before other ICU
+ *  functions are called in that thread.  In this second scenario, the
+ *  application must guarantee that the first call to u_init() happen
+ *  without contention, in a single thread only.
+ *  <p>
+ *  If <code>u_setMemoryFunctions()</code> or 
+ *  <code>u_setMutexFunctions</code> are needed (uncommon), they must be
+ *  called _before_ <code>u_init()</code>.
+ *  <p>
+ *  Extra, repeated, or otherwise unneeded calls to u_init() do no harm,
+ *  other than taking a small amount of time.
+ *
+ * @param status An ICU UErrorCode parameter. It must not be <code>NULL</code>.
+ *    An Error will be returned if some required part of ICU data can not
+ *    be loaded or initialized.
+ *    The function returns immediately if the input error code indicates a
+ *    failure, as usual.
+ *
+ * @stable ICU 2.6
+ */  
+U_STABLE void U_EXPORT2 
+u_init(UErrorCode *status);
+
+/**
+ * Clean up the system resources, such as allocated memory or open files,
+ * used in all ICU libraries. This will free/delete all memory owned by the
+ * ICU libraries, and return them to their original load state. All open ICU
+ * items (collators, resource bundles, converters, etc.) must be closed before
+ * calling this function, otherwise ICU may not free its allocated memory
+ * (e.g. close your converters and resource bundles before calling this
+ * function). Generally, this function should be called once just before
+ * an application exits. For applications that dynamically load and unload
+ * the ICU libraries (relatively uncommon), u_cleanup() should be called
+ * just before the library unload.
+ * <p>
+ * u_cleanup() also clears any ICU heap functions, mutex functions or
+ * trace functions that may have been set for the process.  
+ * This has the effect of restoring ICU to its initial condition, before
+ * any of these override functions were installed.  Refer to
+ * u_setMemoryFunctions(), u_setMutexFunctions and 
+ * utrace_setFunctions().  If ICU is to be reinitialized after after
+ * calling u_cleanup(), these runtime override functions will need to
+ * be set up again if they are still required.
+ * <p>
+ * u_cleanup() is not thread safe.  All other threads should stop using ICU
+ * before calling this function.
+ * <p>
+ * Any open ICU items will be left in an undefined state by u_cleanup(),
+ * and any subsequent attempt to use such an item will give unpredictable
+ * results.
+ * <p>
+ * After calling u_cleanup(), an application may continue to use ICU by
+ * calling u_init().  An application must invoke u_init() first from one single
+ * thread before allowing other threads call u_init().  All threads existing
+ * at the time of the first thread's call to u_init() must also call
+ * u_init() themselves before continuing with other ICU operations.  
+ * <p>
+ * The use of u_cleanup() just before an application terminates is optional,
+ * but it should be called only once for performance reasons. The primary
+ * benefit is to eliminate reports of memory or resource leaks originating
+ * in ICU code from the results generated by heap analysis tools.
+ * <p>
+ * <strong>Use this function with great care!</strong>
+ * </p>
+ *
+ * @stable ICU 2.0
+ * @system
+ */
+U_STABLE void U_EXPORT2 
+u_cleanup(void);
+
+
+
+
+/**
+  * An opaque pointer type that represents an ICU mutex.
+  * For user-implemented mutexes, the value will typically point to a
+  *  struct or object that implements the mutex.
+  * @stable ICU 2.8
+  * @system
+  */
+typedef void *UMTX;
+
+/**
+  *  Function Pointer type for a user supplied mutex initialization function.
+  *  The user-supplied function will be called by ICU whenever ICU needs to create a
+  *  new mutex.  The function implementation should create a mutex, and store a pointer
+  *  to something that uniquely identifies the mutex into the UMTX that is supplied
+  *  as a paramter.
+  *  @param context user supplied value, obtained from from u_setMutexFunctions().
+  *  @param mutex   Receives a pointer that identifies the new mutex.
+  *                 The mutex init function must set the UMTX to a non-null value.   
+  *                 Subsequent calls by ICU to lock, unlock, or destroy a mutex will 
+  *                 identify the mutex by the UMTX value.
+  *  @param status  Error status.  Report errors back to ICU by setting this variable
+  *                 with an error code.
+  *  @stable ICU 2.8
+  *  @system
+  */
+typedef void U_CALLCONV UMtxInitFn (const void *context, UMTX  *mutex, UErrorCode* status);
+
+
+/**
+  *  Function Pointer type for a user supplied mutex functions.
+  *  One of the  user-supplied functions with this signature will be called by ICU
+  *  whenever ICU needs to lock, unlock, or destroy a mutex.
+  *  @param context user supplied value, obtained from from u_setMutexFunctions().
+  *  @param mutex   specify the mutex on which to operate.
+  *  @stable ICU 2.8
+  *  @system
+  */
+typedef void U_CALLCONV UMtxFn   (const void *context, UMTX  *mutex);
+
+
+/**
+  *  Set the functions that ICU will use for mutex operations
+  *  Use of this function is optional; by default (without this function), ICU will
+  *  directly access system functions for mutex operations
+  *  This function can only be used when ICU is in an initial, unused state, before
+  *  u_init() has been called.
+  *  This function may be used even when ICU has been built without multi-threaded
+  *  support  (see ICU_USE_THREADS pre-processor variable, umutex.h)
+  *  @param context This pointer value will be saved, and then (later) passed as
+  *                 a parameter to the user-supplied mutex functions each time they
+  *                 are called. 
+  *  @param init    Pointer to a mutex initialization function.  Must be non-null.
+  *  @param destroy Pointer to the mutex destroy function.  Must be non-null.
+  *  @param lock    pointer to the mutex lock function.  Must be non-null.
+  *  @param unlock  Pointer to the mutex unlock function.  Must be non-null.
+  *  @param status  Receives error values.
+  *  @stable ICU 2.8
+  *  @system
+  */  
+U_STABLE void U_EXPORT2 
+u_setMutexFunctions(const void *context, UMtxInitFn *init, UMtxFn *destroy, UMtxFn *lock, UMtxFn *unlock,
+                    UErrorCode *status);
+
+
+/**
+  *  Pointer type for a user supplied atomic increment or decrement function.
+  *  @param context user supplied value, obtained from from u_setAtomicIncDecFunctions().
+  *  @param p   Pointer to a 32 bit int to be incremented or decremented
+  *  @return    The value of the variable after the inc or dec operation.
+  *  @stable ICU 2.8
+  *  @system
+  */
+typedef int32_t U_CALLCONV UMtxAtomicFn(const void *context, int32_t *p);
+
+/**
+ *  Set the functions that ICU will use for atomic increment and decrement of int32_t values.
+ *  Use of this function is optional; by default (without this function), ICU will
+ *  use its own internal implementation of atomic increment/decrement.
+ *  This function can only be used when ICU is in an initial, unused state, before
+ *  u_init() has been called.
+ *  @param context This pointer value will be saved, and then (later) passed as
+ *                 a parameter to the increment and decrement functions each time they
+ *                 are called.  This function can only be called 
+ *  @param inc     Pointer to a function to do an atomic increment operation.  Must be non-null.
+ *  @param dec     Pointer to a function to do an atomic decrement operation.  Must be non-null.
+ *  @param status  Receives error values.
+ *  @stable ICU 2.8
+ *  @system
+ */  
+U_STABLE void U_EXPORT2 
+u_setAtomicIncDecFunctions(const void *context, UMtxAtomicFn *inc, UMtxAtomicFn *dec,
+                    UErrorCode *status);
+
+
+
+/**
+  *  Pointer type for a user supplied memory allocation function.
+  *  @param context user supplied value, obtained from from u_setMemoryFunctions().
+  *  @param size    The number of bytes to be allocated
+  *  @return        Pointer to the newly allocated memory, or NULL if the allocation failed.
+  *  @stable ICU 2.8
+  *  @system
+  */
+typedef void *U_CALLCONV UMemAllocFn(const void *context, size_t size);
+/**
+  *  Pointer type for a user supplied memory re-allocation function.
+  *  @param context user supplied value, obtained from from u_setMemoryFunctions().
+  *  @param size    The number of bytes to be allocated
+  *  @return        Pointer to the newly allocated memory, or NULL if the allocation failed.
+  *  @stable ICU 2.8
+  *  @system
+  */
+typedef void *U_CALLCONV UMemReallocFn(const void *context, void *mem, size_t size);
+/**
+  *  Pointer type for a user supplied memory free  function.  Behavior should be
+  *  similar the standard C library free().
+  *  @param context user supplied value, obtained from from u_setMemoryFunctions().
+  *  @param mem     Pointer to the memory block to be resized
+  *  @param size    The new size for the block
+  *  @return        Pointer to the resized memory block, or NULL if the resizing failed.
+  *  @stable ICU 2.8
+  *  @system
+  */
+typedef void  U_CALLCONV UMemFreeFn (const void *context, void *mem);
+
+/**
+ *  Set the functions that ICU will use for memory allocation.
+ *  Use of this function is optional; by default (without this function), ICU will
+ *  use the standard C library malloc() and free() functions.
+ *  This function can only be used when ICU is in an initial, unused state, before
+ *  u_init() has been called.
+ *  @param context This pointer value will be saved, and then (later) passed as
+ *                 a parameter to the memory functions each time they
+ *                 are called.
+ *  @param a       Pointer to a user-supplied malloc function.
+ *  @param r       Pointer to a user-supplied realloc function.
+ *  @param f       Pointer to a user-supplied free function.
+ *  @param status  Receives error values.
+ *  @stable ICU 2.8
+ *  @system
+ */  
+U_STABLE void U_EXPORT2 
+u_setMemoryFunctions(const void *context, UMemAllocFn *a, UMemReallocFn *r, UMemFreeFn *f, 
+                    UErrorCode *status);
+
+#endif