]> gitweb @ CieloNegro.org - sugar.git/blob - dot-files/_vimperator/plugin/copy_js
Auto commit by The Sugar System.
[sugar.git] / dot-files / _vimperator / plugin / copy_js
1 var INFO =
2 xml`<plugin name="copy" version="0.7.6"
3         href="http://github.com/vimpr/vimperator-plugins/blob/master/copy.js"
4         summary="copy strings from the template (like CopyURL+)"
5         xmlns="http://vimperator.org/namespaces/liberator">
6     <author email="teramako@gmail.com">teramako</author>
7     <license>MPL 1.1/GPL 2.0/LGPL 2.1</license>
8     <project name="Vimperator" minVersion="2.3"/>
9     <item>
10     <tags>:copy</tags>
11     <spec>:copy <a>label</a></spec>
12     <description>
13         <p>copy the argument replaced some certain string.</p>
14     </description>
15     </item>
16     <item>
17     <tags>:copy!</tags>
18     <spec>:copy! <a>expr</a></spec>
19     <description>
20         <p>evaluate the argument(javascript code) and copy the result.</p>
21     </description>
22     </item>
23     <item>
24     <tags>copy-keyword</tags>
25     <spec>copy-keyword</spec>
26     <description>
27         <p>replaces following keywords</p>
28         <dl>
29             <dt>%TITLE%</dt>
30             <dd>to the title of the current page</dd>
31             <dt>%URL%</dt>
32             <dd>to the currenet URL</dd>
33             <dt>%SEL</dt>
34             <dd>to the string of selection</dd>
35             <dt>%HTMLSEL</dt>
36             <dd>to the html string of selection</dd>
37             <dt>%HOSTNAME%</dt>
38             <dd>to the hostname of the current location</dd>
39             <dt>%PATHNAME%</dt>
40             <dd>to the pathname of the current location</dd>
41             <dt>%HOST%</dt>
42             <dd>to the host of the current location</dd>
43             <dt>%PORT%</dt>
44             <dd>to the port of the current location</dd>
45             <dt>%PROTOCOL%</dt>
46             <dd>to the protocol of the current location</dd>
47             <dt>%SERCH%</dt>
48             <dd>to the search(?...) of the curernt location</dd>
49             <dt>%HASH%</dt>
50             <dd>to the hash(anchor #..) of the current location</dd>
51         </dl>
52     </description>
53     </item>
54     <item>
55         <tags>copy-template</tags>
56         <spec>copy-template</spec>
57         <description>
58             <p>you can set your own template using inline JavaScript</p>
59             <code><![CDATA[
60 javascript <<EOM
61 liberator.globalVariables.copy_templates = [
62   { label: 'titleAndURL',    value: '%TITLE%\n%URL%' },
63   { label: 'title',          value: '%TITLE%', map: ',y' },
64   { label: 'anchor',         value: '<a href="%URL%">%TITLE%</a>' },
65   { label: 'selanchor',      value: '<a href="%URL%" title="%TITLE%">%SEL%</a>' },
66   { label: 'htmlblockquote', value: '<blockquote cite="%URL%" title="%TITLE%">%HTMLSEL%</blockquote>' },
67   { label: 'ASIN',   value: 'copy ASIN code from Amazon', custom: function(){return content.document.getElementById('ASIN').value;} },
68 ];
69 EOM
70             ]]></code>
71             <dl>
72                 <dt>label</dt>
73                 <dd>template name which is command argument</dd>
74                 <dt>value</dt>
75                 <dd>copy string. <a>copy-keyword</a> is replaced</dd>
76                 <dt>map</dt>
77                 <dd>key map <a>lhs</a> (optional)</dd>
78                 <dt>custom</dt>
79                 <dd>
80                     <a>function</a> or <a>Array</a> (optional)
81                     <dl>
82                         <dt><a>function</a></dt>
83                         <dd>execute the function and copy return value, if specified</dd>
84                         <dt><a>Array</a></dt>
85                         <dd>
86                             replace to the <a>value</a> by normal way at first.
87                             then replace words matched <a>Array</a>[0] in the repalced string to <a>Array</a>[1].
88                             <dl>
89                             <dt><a>Array</a>[0]</dt>
90                             <dd>String or RegExp</dd>
91                             <dt><a>Array</a>[1]</dt>
92                             <dd>String or Function</dd>
93                             </dl>
94                             see: <link topic="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:String:replace">http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:String:replace</link>
95                         </dd>
96                     </dl>
97                 </dd>
98             </dl>
99         </description>
100     </item>
101     <item>
102         <tags>copy-option</tags>
103         <spec>copy-option</spec>
104         <description>
105             <code><ex>liberator.globalVariables.copy_use_wedata = false; // false by default</ex></code>
106             <p>true に設定すると wedata からテンプレートを読込みます。</p>
107             <code><ex>liberator.globalVariables.copy_wedata_include_custom = true; // false by default</ex></code>
108             <p>custom が設定された wedata を読込みます。
109             SandBox でなく、window.eval を利用してオブジェクトする為、
110             セキュリティ上の理由で初期設定は false になっています。
111             true に設定する場合は、動作を理解したうえ自己責任でご利用ください。</p>
112             <code><ex>liberator.globalVariables.copy_wedata_exclude_labels = ['pathtraqnormalize', ];</ex></code>
113             <p>wedata から読込まない label のリストを定義します。</p>
114         </description>
115     </item>
116 </plugin>`;
117
118 liberator.plugins.exCopy = (function(){
119 var excludeLabelsMap = {};
120 var copy_templates = [];
121 if (!liberator.globalVariables.copy_templates){
122     liberator.globalVariables.copy_templates = [
123         { label: 'titleAndURL',    value: '%TITLE%\n%URL%' },
124         { label: 'title',          value: '%TITLE%' },
125         { label: 'anchor',         value: '<a href="%URL%">%TITLE%</a>' },
126         { label: 'selanchor',      value: '<a href="%URL%" title="%TITLE%">%SEL%</a>' },
127         { label: 'htmlblockquote', value: '<blockquote cite="%URL%" title="%TITLE%">%HTMLSEL%</blockquote>' }
128     ];
129 }
130
131 copy_templates = liberator.globalVariables.copy_templates.map(function(t){
132     return { label: t.label, value: t.value, custom: t.custom, map: t.map }
133 });
134
135 copy_templates.forEach(function(template){
136     if (typeof template.map == 'string')
137         addUserMap(template.label, [template.map]);
138     else if (template.map instanceof Array)
139         addUserMap(template.label, template.map);
140 });
141
142 const REPLACE_TABLE = {
143     get TITLE () buffer.title,
144     get URL () buffer.URL,
145     get SEL () {
146         var sel = '';
147         var win = new XPCNativeWrapper(window.content.window);
148         var selection =  win.getSelection();
149         if (selection.rangeCount < 1)
150             return '';
151
152         for (var i=0, c=selection.rangeCount; i<c; i++){
153             sel += selection.getRangeAt(i).toString();
154         }
155         return sel;
156     },
157     get HTMLSEL () {
158         var htmlsel = '';
159         var win = new XPCNativeWrapper(window.content.window);
160         var selection =  win.getSelection();
161         if (selection.rangeCount < 1)
162             return '';
163
164         var serializer = new XMLSerializer();
165         for (var i=0, c=selection.rangeCount; i<c; i++){
166             htmlsel += serializer.serializeToString(selection.getRangeAt(i).cloneContents());
167         }
168         return htmlsel.replace(/<(\/)?(\w+)([\s\S]*?)>/g, function(all, close, tag, attr){
169             return "<" + close + tag.toLowerCase() + attr + ">";
170         });
171     },
172     get CLIP () {
173         return util.readFromClipboard();
174     }
175 };
176 'hostname pathname host port protocol search hash'.split(' ').forEach(function (name){
177     REPLACE_TABLE[name.toUpperCase()] = function () content.location && content.location[name];
178 });
179
180 // used when argument is none
181 //const defaultValue = templates[0].label;
182 commands.addUserCommand(['copy'],'Copy to clipboard',
183     function(args){
184         liberator.plugins.exCopy.copy(args.literalArg, args.bang, !!args["-append"]);
185     },{
186         completer: function(context, args){
187             if (args.bang){
188                 completion.javascript(context);
189                 return;
190             }
191             context.title = ['Template','Value'];
192             var templates = copy_templates.map(function(template)
193                 [template.label, liberator.modules.util.escapeString(template.value, '"')]
194             );
195             if (!context.filter){ context.completions = templates; return; }
196             var candidates = [];
197             var filter = context.filter.toLowerCase();
198             context.completions = templates.filter(function(template) template[0].toLowerCase().indexOf(filter) == 0);
199         },
200         literal: 0,
201         bang: true,
202         options: [
203             [["-append","-a"], commands.OPTION_NOARG]
204         ]
205     },
206     true
207 );
208
209 function addUserMap(label, map){
210     mappings.addUserMap([modes.NORMAL,modes.VISUAL], map,
211         label,
212         function(){ liberator.plugins.exCopy.copy(label); },
213         { rhs: label }
214     );
215 }
216 function getCopyTemplate(label){
217     var ret = null;
218     copy_templates.some(function(template)
219         template.label == label ? (ret = template) && true : false);
220     return ret;
221 }
222 function replaceVariable(str){
223     if (!str) return '';
224     function replacer(orig, name){ //{{{
225         if (name == '')
226             return '%';
227         if (!REPLACE_TABLE.hasOwnProperty(name))
228             return orig;
229         let value = REPLACE_TABLE[name];
230         if (typeof value == 'function')
231             return value();
232         else
233             return value.toString();
234         return orig;
235     } //}}}
236     return str.replace(/%([A-Z]*)%/g, replacer);
237 }
238
239 function wedataRegister(item){
240     var libly = liberator.plugins.libly;
241     var logger = libly.$U.getLogger("copy");
242     item = item.data;
243     if (excludeLabelsMap[item.label]) return;
244
245     if (item.custom && item.custom.toLowerCase().indexOf('function') != -1) {
246         if (!liberator.globalVariables.copy_wedata_include_custom ||
247              item.label == 'test') {
248             logger.log('skip: ' + item.label);
249             return;
250         }
251
252         let custom = (function(item){
253
254             return function(value, value2){
255                 var STORE_KEY = 'plugins-copy-ok-func';
256                 var store = storage.newMap(STORE_KEY, {store: true});
257                 var check = store.get(item.label);
258                 var ans;
259
260                 if (!check){
261                     ans = window.confirm(
262                         'warning!!!: execute "' + item.label + '" ok ?\n' +
263                         '(this function is working with unsafe sandbox.)\n\n' +
264                         '----- execute code -----\n\n' +
265                         'value: ' + item.value + '\n' +
266                         'function: ' +
267                         item.custom
268                     );
269                 } else {
270                     if (item.value == check.value &&
271                         item.custom == check.custom &&
272                         item.map == check.map){
273                         ans = true;
274                     } else {
275                         ans = window.confirm(
276                             'warning!!!: "' + item.label + '" was changed when you registered the function.\n' +
277                             '(this function is working with unsafe sandbox.)\n\n' +
278                             '----- execute code -----\n\n' +
279                             'value: ' + item.value + '\n' +
280                             'function: ' +
281                             item.custom
282                         );
283                     }
284                 }
285
286                 if (!ans) return;
287                 store.set(item.label, item);
288                 store.save();
289
290                 var func;
291                 try{
292                     func = window.eval('(' + item.custom + ')');
293                 } catch (e){
294                     logger.echoerr(e);
295                     logger.log(item.custom);
296                     return;
297                 }
298                 return func(value, value2);
299             };
300         })(item);
301
302         exCopyManager.add(item.label, item.value, custom, item.map);
303     } else {
304         exCopyManager.add(item.label, item.value, null, item.map);
305     }
306 }
307 var exCopyManager = {
308     add: function(label, value, custom, map){
309         var template = {label: label, value: value, custom: custom, map: map};
310         copy_templates.unshift(template);
311         if (map) addUserMap(label, map);
312
313         return template;
314     },
315     get: function(label){
316         return getCopyTemplate(label);
317     },
318     copy: function(arg, special, appendMode){
319         var copyString = '';
320         var isError = false;
321         if (special && arg){
322             try {
323                 copyString = liberator.eval(arg);
324                 switch (typeof copyString){
325                     case 'object':
326                         copyString = copyString === null ? 'null' : copyString.toSource();
327                         break;
328                     case 'function':
329                         copyString = copyString.toString();
330                         break;
331                     case 'number':
332                     case 'boolean':
333                         copyString = '' + copyString;
334                         break;
335                     case 'undefined':
336                         copyString = 'undefined';
337                         break;
338                 }
339             } catch (e){
340                 isError = true;
341                 copyString = e.toString();
342             }
343         } else {
344             if (!arg) arg = copy_templates[0].label;
345
346             var template = getCopyTemplate(arg) || {value: arg};
347             if (typeof template.custom == 'function'){
348                 copyString = template.custom.call(this, template.value, replaceVariable(template.value));
349             } else if (template.custom instanceof Array){
350                 copyString = replaceVariable(template.value).replace(template.custom[0], template.custom[1]);
351             } else {
352                 copyString = replaceVariable(template.value);
353             }
354         }
355
356         if (appendMode){
357             copyString = util.readFromClipboard() + copyString;
358         }
359
360         if (copyString)
361             util.copyToClipboard(copyString);
362         if (isError){
363             liberator.echoerr('CopiedErrorString: `' + copyString + "'");
364         } else {
365             liberator.echomsg('CopiedString: `' + util.escapeHTML(copyString || '') + "'");
366         }
367     }
368 };
369
370 if (liberator.globalVariables.copy_use_wedata){
371     function loadWedata(){
372         if (!liberator.plugins.libly){
373             liberator.echomsg("need a _libly.js when use wedata.");
374             return;
375         }
376
377         var libly = liberator.plugins.libly;
378         copy_templates.forEach(function(item) excludeLabelsMap[item.label] = item.value);
379         if (liberator.globalVariables.copy_wedata_exclude_labels)
380             liberator.globalVariables.copy_wedata_exclude_labels.forEach(function(item) excludeLabelsMap[item] = 1);
381         var wedata = new libly.Wedata("vimp copy");
382         wedata.getItems(24 * 60 * 60 * 1000, wedataRegister);
383     }
384     loadWedata();
385 }
386
387 return exCopyManager;
388 })();
389
390 // vim: set fdm=marker sw=4 ts=4 et:
391