aboutsummaryrefslogtreecommitdiffstats
path: root/copy.js
blob: 6b0906d7370c6231fa4bd6cd8b1e1a254c8e4459 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
/**
 * ==VimperatorPlugin==
 * @name           copy.js
 * @description    enable to copy strings from a template (like CopyURL+)
 * @description-ja テンプレートから文字列のコピーを可能にします(CopyURL+みたなもの)
 * @minVersion     1.1
 * @author         teramako teramako@gmail.com
 * @version        0.5a
 * ==/VimperatorPlugin==
 *
 * Usage:
 * :copy {copyString}         -> copy the argument replaced some certain string
 * :copy! {expr}              -> evaluate the argument and copy the result
 *
 * e.g.)
 * :copy %TITLE%              -> copied the title of the current page
 * :copy title                -> same as `:copy %TITLE%' by default
 * :copy! liberator.version   -> copy the value of liberator.version
 *
 * If non-argument, used `default'
 *
 * label: template name which is command argument
 * value:  copy string
 *    the certian string is replace to ...
 *        %TITTLE%  -> to the title of the current page
 *        %URL%     -> to the URL of the current page
 *        %SEL%     -> to the string of selection
 *        %HTMLSEL% -> to the html string of selection
 *
 * map: key map (optional)
 *
 * custom: {function} or {Array} (optional)
 *   {function}:
 *    execute the function and copy return value, if specified.
 *
 *   {Array}:
 *    replaced to the {value} by normal way at first.
 *    and replace words matched {Array}[0] in the replaced string to {Array}[1].
 *    {Array}[0] is string or regexp
 *    {Array}[1] is string or function
 *    see http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:String:replace
 *
 * The copy_templates is a string variable which can set on
 * vimperatorrc as following.
 *
 * let copy_templates = "[{ label: 'titleAndURL', value: '%TITLE%\n%URL%' }, { label: 'title', value: '%TITLE%' }]"
 *
 * or your can set it using inline JavaScript.
 *
 * javascript <<EOM
 * liberator.globalVariables.copy_templates = [
 *   { label: 'titleAndURL',    value: '%TITLE%\n%URL%' },
 *   { label: 'title',          value: '%TITLE%', map: ',y' },
 *   { label: 'anchor',         value: '<a href="%URL%">%TITLE%</a>' },
 *   { label: 'selanchor',      value: '<a href="%URL%" title="%TITLE%">%SEL%</a>' },
 *   { label: 'htmlblockquote', value: '<blockquote cite="%URL%" title="%TITLE%">%HTMLSEL%</blockquote>' }
 *   { label: 'ASIN',   value: 'copy ASIN code from Amazon', custom: function(){return content.document.getElementById('ASIN').value;} },
 * ];
 * EOM
 */
liberator.plugins.exCopy = (function(){
if (!liberator.globalVariables.copy_templates){
    liberator.globalVariables.copy_templates = [
        { label: 'titleAndURL',    value: '%TITLE%\n%URL%' },
        { label: 'title',          value: '%TITLE%' },
        { label: 'anchor',         value: '<a href="%URL%">%TITLE%</a>' },
        { label: 'selanchor',      value: '<a href="%URL%" title="%TITLE%">%SEL%</a>' },
        { label: 'htmlblockquote', value: '<blockquote cite="%URL%" title="%TITLE%">%HTMLSEL%</blockquote>' }
    ];
}

liberator.globalVariables.copy_templates.forEach(function(template){
    if (typeof template.map == 'string')
        addUserMap(template.label, [template.map]);
    else if (template.map instanceof Array)
        addUserMap(template.label, template.map);
});

// used when argument is none
//const defaultValue = templates[0].label;
commands.addUserCommand(['copy'],'Copy to clipboard',
    function(args){
        liberator.plugins.exCopy.copy(args.string, args.bang);
    },{
        completer: function(context, args){
            if (args.bang){
                completion.javascript(context);
                return;
            }
            context.title = ['Template','Value'];
            var templates = liberator.globalVariables.copy_templates.map(function(template)
                [template.label, liberator.modules.util.escapeString(template.value, '"')]
            );
            if (!context.filter){ context.completions = templates; return; }
            var candidates = [];
            var filter = context.filter.toLowerCase();
            context.completions = templates.filter(function(template) template[0].toLowerCase().indexOf(filter) == 0);
        },
        bang: true
    }
);

function addUserMap(label, map){
    mappings.addUserMap([modes.NORMAL,modes.VISUAL], map,
        label,
        function(){ liberator.plugins.exCopy.copy(label); },
        { rhs: label }
    );
}
function getCopyTemplate(label){
    var ret = null;
    liberator.globalVariables.copy_templates.some(function(template)
        template.label == label ? (ret = template) && true : false);
    return ret;
}
function replaceVariable(str){
    if (!str) return '';
    var win = new XPCNativeWrapper(window.content.window);
    var sel = '',htmlsel = '';
    var selection =  win.getSelection();
    function replacer(value){ //{{{
        switch(value){
            case '%TITLE%':
                return buffer.title;
            case '%URL%':
                return buffer.URL;
            case '%SEL%':
                if (sel)
                    return sel;
                else if (selection.rangeCount < 1)
                    return '';

                for (var i=0, c=selection.rangeCount; i<c; i++){
                    sel += selection.getRangeAt(i).toString();
                }
                return sel;
            case '%HTMLSEL%':
                if (htmlsel)
                    return sel;
                else if (selection.rangeCount < 1)
                    return '';

                var serializer = new XMLSerializer();
                for (var i=0, c=selection.rangeCount; i<c; i++){
                    htmlsel += serializer.serializeToString(selection.getRangeAt(i).cloneContents());
                }
                return htmlsel;
        }
        return '';
    } //}}}
    return str.replace(/%(TITLE|URL|SEL|HTMLSEL)%/g, replacer);
}

var exCopyManager = {
    add: function(label, value, custom, map){
        var template = {label: label, value: value, custom: custom, map: map};
        liberator.globalVariables.copy_templates.unshift(template);
        if (map) addUserMap(label, map);

        return template;
    },
    get: function(label){
        return getCopyTemplate(label);
    },
    copy: function(arg, special){
        var copyString = '';
        var isError = false;
        if (special && arg){
            try {
                copyString = liberator.eval( arg);
                switch (typeof copyString){
                    case 'object':
                        copyString = copyString === null ? 'null' : copyString.toSource();
                        break;
                    case 'function':
                        copyString = copyString.toString();
                        break;
                    case 'number':
                    case 'boolean':
                        copyString = '' + copyString;
                        break;
                    case 'undefined':
                        copyString = 'undefined';
                        break;
                }
            } catch (e){
                isError = true;
                copyString = e.toString();
            }
        } else {
            if (!arg) arg = liberator.globalVariables.copy_templates[0];
            var template = getCopyTemplate(arg) || {value: arg};
            if (typeof template.custom == 'function'){
                copyString = template.custom.call(this, template.value);
            } else if (template.custom instanceof Array){
                copyString = replaceVariable(template.value).replace(tempalte.custom[0], template.custom[1]);
            } else {
                copyString = replaceVariable(template.value);
            }
        }
        util.copyToClipboard(copyString);
        if (isError){
            liberator.echoerr('CopiedErrorString: `' + copyString + "'");
        } else {
            liberator.echo('CopiedString: `' + util.escapeHTML(copyString) + "'");
        }
    }
};
return exCopyManager;
})();

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