-
Notifications
You must be signed in to change notification settings - Fork 0
/
shCore.js
1940 lines (1656 loc) · 56.3 KB
/
shCore.js
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* SyntaxHighlighter
* http://alexgorbatchev.com/
*
* @version
* 2.0.278 (February 03 2009)
*
* @author
* Alex Gorbatchev
*
* @copyright
* Copyright (C) 2004-2009 Alex Gorbatchev.
*
* Licensed under a GNU Lesser General Public License.
* http://creativecommons.org/licenses/LGPL/2.1/
*
* SyntaxHighlighter is donationware. You are allowed to download, modify and distribute
* the source code in accordance with LGPL 2.1 license, however if you want to use
* SyntaxHighlighter on your site or include it in your product, you must donate.
* http://alexgorbatchev.com/wiki/SyntaxHighlighter:Donate
*/
//
// Begin anonymous function. This is used to contain local scope variables without polutting global scope.
//
if (!window.SyntaxHighlighter) var SyntaxHighlighter = function() {
// Shortcut object which will be assigned to the SyntaxHighlighter variable.
// This is a shorthand for local reference in order to avoid long namespace
// references to SyntaxHighlighter.whatever...
var sh = {
defaults : {
/** Additional CSS class names to be added to highlighter elements. */
'class-name' : '',
/** First line number. */
'first-line' : 1,
/** Font size of the SyntaxHighlighter block. */
'font-size' : null,
/** Lines to highlight. */
'highlight' : null,
/** Enables or disables smart tabs. */
'smart-tabs' : true,
/** Gets or sets tab size. */
'tab-size' : 4,
/** Enables or disables ruler. */
'ruler' : false,
/** Enables or disables gutter. */
'gutter' : true,
/** Enables or disables toolbar. */
'toolbar' : true,
/** Forces code view to be collapsed. */
'collapse' : false,
/** Enables or disables automatic links. */
'auto-links' : true,
/** Gets or sets light mode. Equavalent to turning off gutter and toolbar. */
'light' : false
},
config : {
/** Path to the copy to clipboard SWF file. */
clipboardSwf : null,
/** Width of an item in the toolbar. */
toolbarItemWidth : 16,
/** Height of an item in the toolbar. */
toolbarItemHeight : 16,
/** Blogger mode flag. */
bloggerMode : false,
/** Name of the tag that SyntaxHighlighter will automatically look for. */
tagName : 'pre',
strings : {
expandSource : 'expand source',
viewSource : 'view source',
copyToClipboard : 'copy to clipboard',
copyToClipboardConfirmation : 'The code is in your clipboard now',
print : 'print',
help : '?',
alert: 'SyntaxHighlighter\n\n',
noBrush : 'Can\'t find brush for: ',
brushNotHtmlScript : 'Brush wasn\'t configured for html-script option: ',
// this is populated by the build script
aboutDialog : '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>About SyntaxHighlighter</title></head><body style="font-family:Georgia,"Times New Roman",Times,serif;background-color:#fff;color:#000;font-size:1em;text-align:center;"><div style="text-align:center;margin-top:3em;"><div style="font-family:Geneva,Arial,Helvetica,sans-serif;font-size:xx-large;">SyntaxHighlighter</div><div style="font-size:.75em;margin-bottom:4em;"><div>version 2.0.278 (February 03 2009)</div><div><a href="http://alexgorbatchev.com" target="_blank" style="color:#0099FF;text-decoration:none;">http://alexgorbatchev.com</a></div></div><div>JavaScript code syntax highlighter.</div><div>Copyright 2004-2009 Alex Gorbatchev.</div></div></body></html>'
},
/** If true, output will show HTML produces instead. */
debug : false
},
/** Internal 'global' variables. */
vars : {
discoveredBrushes : null,
spaceWidth : null,
printFrame : null,
highlighters : {}
},
/** This object is populated by user included external brush files. */
brushes : {},
/** Common regular expressions. */
regexLib : {
multiLineCComments : /\/\*[\s\S]*?\*\//gm,
singleLineCComments : /\/\/.*$/gm,
singleLinePerlComments : /#.*$/gm,
doubleQuotedString : /"(?:\.|(\\\")|[^\""\n])*"/g,
singleQuotedString : /'(?:\.|(\\\')|[^\''\n])*'/g,
multiLineDoubleQuotedString : /"(?:\.|(\\\")|[^\""])*"/g,
multiLineSingleQuotedString : /'(?:\.|(\\\')|[^\''])*'/g,
url : /\w+:\/\/[\w-.\/?%&=]*/g,
/** <?= ?> tags. */
phpScriptTags : { left: /(<|<)\?=?/g, right: /\?(>|>)/g },
/** <%= %> tags. */
aspScriptTags : { left: /(<|<)%=?/g, right: /%(>|>)/g },
/** <script></script> tags. */
scriptScriptTags : { left: /(<|<)\s*script.*?(>|>)/gi, right: /(<|<)\/\s*script\s*(>|>)/gi }
},
toolbar : {
/**
* Creates new toolbar for a highlighter.
* @param {Highlighter} highlighter Target highlighter.
*/
create : function(highlighter)
{
var div = document.createElement('DIV'),
items = sh.toolbar.items
;
div.className = 'toolbar';
for (var name in items)
{
var constructor = items[name],
command = new constructor(highlighter),
element = command.create()
;
highlighter.toolbarCommands[name] = command;
if (element == null)
continue;
if (typeof(element) == 'string')
element = sh.toolbar.createButton(element, highlighter.id, name);
element.className += 'item ' + name;
div.appendChild(element);
}
return div;
},
/**
* Create a standard anchor button for the toolbar.
* @param {String} label Label text to display.
* @param {String} highlighterId Highlighter ID that this button would belong to.
* @param {String} commandName Command name that would be executed.
* @return {Element} Returns an 'A' element.
*/
createButton : function(label, highlighterId, commandName)
{
var a = document.createElement('a'),
style = a.style,
config = sh.config,
width = config.toolbarItemWidth,
height = config.toolbarItemHeight
;
a.href = '#' + commandName;
a.title = label;
a.highlighterId = highlighterId;
a.commandName = commandName;
a.innerHTML = label;
if (isNaN(width) == false)
style.width = width + 'px';
if (isNaN(height) == false)
style.height = height + 'px';
a.onclick = function(e)
{
try
{
sh.toolbar.executeCommand(
this,
e || window.event,
this.highlighterId,
this.commandName
);
}
catch(e)
{
sh.utils.alert(e.message);
}
return false;
};
return a;
},
/**
* Executes a toolbar command.
* @param {Element} sender Sender element.
* @param {MouseEvent} event Original mouse event object.
* @param {String} highlighterId Highlighter DIV element ID.
* @param {String} commandName Name of the command to execute.
* @return {Object} Passes out return value from command execution.
*/
executeCommand : function(sender, event, highlighterId, commandName, args)
{
var highlighter = sh.vars.highlighters[highlighterId],
command
;
if (highlighter == null || (command = highlighter.toolbarCommands[commandName]) == null)
return null;
return command.execute(sender, event, args);
},
/** Collection of toolbar items. */
items : {
expandSource : function(highlighter)
{
this.create = function()
{
if (highlighter.getParam('collapse') != true)
return;
return sh.config.strings.expandSource;
};
this.execute = function(sender, event, args)
{
var div = highlighter.div;
sender.parentNode.removeChild(sender);
div.className = div.className.replace('collapsed', '');
};
},
/**
* Command to open a new window and display the original unformatted source code inside.
*/
viewSource : function(highlighter)
{
this.create = function()
{
return sh.config.strings.viewSource;
};
this.execute = function(sender, event, args)
{
var code = sh.utils.fixForBlogger(highlighter.originalCode).replace(/</g, '<'),
wnd = sh.utils.popup('', '_blank', 750, 400, 'location=0, resizable=1, menubar=0, scrollbars=1')
;
code = sh.utils.unindent(code);
wnd.document.write('<pre>' + code + '</pre>');
wnd.document.close();
};
},
/**
* Command to copy the original source code in to the clipboard.
* Uses Flash method if <code>clipboardSwf</code> is configured.
*/
copyToClipboard : function(highlighter)
{
var flashDiv, flashSwf,
highlighterId = highlighter.id
;
this.create = function()
{
var config = sh.config;
// disable functionality if running locally
if (window.location.protocol == 'file:' || config.clipboardSwf == null)
return null;
function params(list)
{
var result = '';
for (var name in list)
result += "<param name='" + name + "' value='" + list[name] + "'/>";
return result;
};
function attributes(list)
{
var result = '';
for (var name in list)
result += " " + name + "='" + list[name] + "'";
return result;
};
var args1 = {
width : config.toolbarItemWidth,
height : config.toolbarItemHeight,
id : highlighterId + '_clipboard',
type : 'application/x-shockwave-flash'
},
// these arguments are used in IE's <param /> collection
args2 = {
allowScriptAccess : 'always',
wmode : 'transparent',
flashVars : 'highlighterId=' + highlighterId,
menu : 'false'
},
swf = config.clipboardSwf,
html
;
if (/msie/i.test(navigator.userAgent))
{
html = '<object'
+ attributes({
classid : 'clsid:d27cdb6e-ae6d-11cf-96b8-444553540000',
codebase : 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0'
})
+ attributes(args1)
+ '>'
+ params(args2)
+ params({ movie : swf })
+ '</object>'
;
}
else
{
html = '<embed'
+ attributes(args1)
+ attributes(args2)
+ attributes({ src : swf })
+ '/>'
;
}
flashDiv = document.createElement('div');
flashDiv.innerHTML = html;
return flashDiv;
};
this.execute = function(sender, event, args)
{
var command = args.command;
switch (command)
{
case 'get':
var code = sh.utils.unindent(
sh.utils.fixForBlogger(highlighter.originalCode)
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/&/g, '&')
);
if(window.clipboardData)
// will fall through to the confirmation because there isn't a break
window.clipboardData.setData('text', code);
else
return sh.utils.unindent(code);
case 'ok':
sh.utils.alert(sh.config.strings.copyToClipboardConfirmation);
break;
case 'error':
sh.utils.alert(args.message);
break;
}
};
},
/** Command to print the colored source code. */
printSource : function(highlighter)
{
this.create = function()
{
return sh.config.strings.print;
};
this.execute = function(sender, event, args)
{
var iframe = document.createElement('IFRAME'),
doc = null
;
// make sure there is never more than one hidden iframe created by SH
if (sh.vars.printFrame != null)
document.body.removeChild(sh.vars.printFrame);
sh.vars.printFrame = iframe;
// this hides the iframe
iframe.style.cssText = 'position:absolute;width:0px;height:0px;left:-500px;top:-500px;';
document.body.appendChild(iframe);
doc = iframe.contentWindow.document;
copyStyles(doc, window.document);
doc.write('<div class="' + highlighter.div.className.replace('collapsed', '') + ' printing">' + highlighter.div.innerHTML + '</div>');
doc.close();
iframe.contentWindow.focus();
iframe.contentWindow.print();
function copyStyles(destDoc, sourceDoc)
{
var links = sourceDoc.getElementsByTagName('link');
for(var i = 0; i < links.length; i++)
if(links[i].rel.toLowerCase() == 'stylesheet' && /shCore\.css$/.test(links[i].href))
destDoc.write('<link type="text/css" rel="stylesheet" href="' + links[i].href + '"></link>');
};
};
},
/** Command to display the about dialog window. */
about : function(highlighter)
{
this.create = function()
{
return sh.config.strings.help;
};
this.execute = function(sender, event)
{
var wnd = sh.utils.popup('', '_blank', 500, 250, 'scrollbars=0'),
doc = wnd.document
;
doc.write(sh.config.strings.aboutDialog);
doc.close();
wnd.focus();
};
}
}
},
utils : {
guid : function(prefix)
{
return prefix + Math.round(Math.random() * 1000000).toString();
},
/**
* Merges two objects. Values from obj2 override values in obj1.
* Function is NOT recursive and works only for one dimensional objects.
* @param {Object} obj1 First object.
* @param {Object} obj2 Second object.
* @return {Object} Returns combination of both objects.
*/
merge: function(obj1, obj2)
{
var result = {}, name;
for (name in obj1)
result[name] = obj1[name];
for (name in obj2)
result[name] = obj2[name];
return result;
},
/**
* Attempts to convert string to boolean.
* @param {String} value Input string.
* @return {Boolean} Returns true if input was "true", false if input was "false" and value otherwise.
*/
toBoolean: function(value)
{
switch (value)
{
case "true":
return true;
case "false":
return false;
}
return value;
},
/**
* Opens up a centered popup window.
* @param {String} url URL to open in the window.
* @param {String} name Popup name.
* @param {int} width Popup width.
* @param {int} height Popup height.
* @param {String} options window.open() options.
* @return {Window} Returns window instance.
*/
popup: function(url, name, width, height, options)
{
var x = (screen.width - width) / 2,
y = (screen.height - height) / 2
;
options += ', left=' + x +
', top=' + y +
', width=' + width +
', height=' + height
;
options = options.replace(/^,/, '');
var win = window.open(url, name, options);
win.focus();
return win;
},
/**
* Adds event handler to the target object.
* @param {Object} obj Target object.
* @param {String} type Name of the event.
* @param {Function} func Handling function.
*/
addEvent: function(obj, type, func)
{
if (obj.attachEvent)
{
obj['e' + type + func] = func;
obj[type + func] = function()
{
obj['e' + type + func](window.event);
}
obj.attachEvent('on' + type, obj[type + func]);
}
else
{
obj.addEventListener(type, func, false);
}
},
/**
* Displays an alert.
* @param {String} str String to display.
*/
alert: function(str)
{
alert(sh.config.strings.alert + str)
},
/**
* Finds a brush by its alias.
*
* @param {String} alias Brush alias.
* @param {Boolean} alert Suppresses the alert if false.
* @return {Brush} Returns bursh constructor if found, null otherwise.
*/
findBrush: function(alias, alert)
{
var brushes = sh.vars.discoveredBrushes,
result = null
;
if (brushes == null)
{
brushes = {};
// Find all brushes
for (var brush in sh.brushes)
{
var aliases = sh.brushes[brush].aliases;
if (aliases == null)
continue;
for (var i = 0; i < aliases.length; i++)
brushes[aliases[i]] = brush;
}
sh.vars.discoveredBrushes = brushes;
}
result = sh.brushes[brushes[alias]];
if (result == null && alert != false)
sh.utils.alert(sh.config.strings.noBrush + alias);
return result;
},
/**
* Executes a callback on each line and replaces each line with result from the callback.
* @param {Object} str Input string.
* @param {Object} callback Callback function taking one string argument and returning a string.
*/
eachLine: function(str, callback)
{
var lines = str.split('\n');
for (var i = 0; i < lines.length; i++)
lines[i] = callback(lines[i]);
return lines.join('\n');
},
/**
* Creates rules looking div.
*/
createRuler: function()
{
var div = document.createElement('div'),
ruler = document.createElement('div'),
showEvery = 10,
i = 1
;
while (i <= 150)
{
if (i % showEvery === 0)
{
div.innerHTML += i;
i += (i + '').length;
}
else
{
div.innerHTML += '·';
i++;
}
}
ruler.className = 'ruler line';
ruler.appendChild(div);
return ruler;
},
/**
* This is a special trim which only removes first and last empty lines
* and doesn't affect valid leading space on the first line.
*
* @param {String} str Input string
* @return {String} Returns string without empty first and last lines.
*/
trimFirstAndLastLines: function(str)
{
return str.replace(/^[ ]*[\n]+|[\n]*[ ]*$/g, '');
},
/**
* Parses key/value pairs into hash object.
*
* Understands the following formats:
* - name: word;
* - name: [word, word];
* - name: "string";
* - name: 'string';
*
* For example:
* name1: value; name2: [value, value]; name3: 'value'
*
* @param {String} str Input string.
* @return {Object} Returns deserialized object.
*/
parseParams: function(str)
{
var match,
result = {},
arrayRegex = new XRegExp("^\\[(?<values>(.*?))\\]$"),
regex = new XRegExp(
"(?<name>[\\w-]+)" +
"\\s*:\\s*" +
"(?<value>" +
"[\\w-%]+|" + // word
"\\[.*?\\]|" + // [] array
'".*?"|' + // "" string
"'.*?'" + // '' string
")\\s*;?",
"g"
)
;
while ((match = regex.exec(str)) != null)
{
var value = match.value
.replace(/^['"]|['"]$/g, '') // strip quotes from end of strings
;
// try to parse array value
if (value != null && arrayRegex.test(value))
{
var m = arrayRegex.exec(value);
value = m.values.length > 0 ? m.values.split(/\s*,\s*/) : [];
}
result[match.name] = value;
}
return result;
},
/**
* Wraps each line of the string into <code/> tag with given style applied to it.
*
* @param {String} str Input string.
* @param {String} css Style name to apply to the string.
* @return {String} Returns input string with each line surrounded by <span/> tag.
*/
decorate: function(str, css)
{
if (str == null || str.length == 0 || str == '\n')
return str;
str = str.replace(/</g, '<');
// Replace two or more sequential spaces with leaving last space untouched.
str = str.replace(/ {2,}/g, function(m)
{
var spaces = '';
for (var i = 0; i < m.length - 1; i++)
spaces += ' ';
return spaces + ' ';
});
// Split each line and apply <span class="...">...</span> to them so that
// leading spaces aren't included.
if (css != null)
str = sh.utils.eachLine(str, function(line)
{
if (line.length == 0)
return '';
var spaces = '';
line = line.replace(/^( | )+/, function(s)
{
spaces = s;
return '';
});
if (line.length == 0)
return spaces;
return spaces + '<code class="' + css + '">' + line + '</code>';
});
return str;
},
/**
* Pads number with zeros until it's length is the same as given length.
*
* @param {Number} number Number to pad.
* @param {Number} length Max string length with.
* @return {String} Returns a string padded with proper amount of '0'.
*/
padNumber : function(number, length)
{
var result = number.toString();
while (result.length < length)
result = '0' + result;
return result;
},
/**
* Measures width of a single space character.
* @return {Number} Returns width of a single space character.
*/
measureSpace : function()
{
var container = document.createElement('div'),
span,
result = 0,
body = document.body,
id = sh.utils.guid('measureSpace'),
// variable names will be compressed, so it's better than a plain string
divOpen = '<div class="',
closeDiv = '</div>',
closeSpan = '</span>'
;
// we have to duplicate highlighter nested structure in order to get an acurate space measurment
container.innerHTML =
divOpen + 'syntaxhighlighter">'
+ divOpen + 'lines">'
+ divOpen + 'line">'
+ divOpen + 'content'
+ '"><span class="block"><span id="' + id + '"> ' + closeSpan + closeSpan
+ closeDiv
+ closeDiv
+ closeDiv
+ closeDiv
;
body.appendChild(container);
span = document.getElementById(id);
if (/opera/i.test(navigator.userAgent))
{
var style = window.getComputedStyle(span, null);
result = parseInt(style.getPropertyValue("width"));
}
else
{
result = span.offsetWidth;
}
body.removeChild(container);
return result;
},
/**
* Replaces tabs with spaces.
*
* @param {String} code Source code.
* @param {Number} tabSize Size of the tab.
* @return {String} Returns code with all tabs replaces by spaces.
*/
processTabs : function(code, tabSize)
{
var tab = '';
for (var i = 0; i < tabSize; i++)
tab += ' ';
return code.replace(/\t/g, tab);
},
/**
* Replaces tabs with smart spaces.
*
* @param {String} code Code to fix the tabs in.
* @param {Number} tabSize Number of spaces in a column.
* @return {String} Returns code with all tabs replaces with roper amount of spaces.
*/
processSmartTabs : function(code, tabSize)
{
var lines = code.split('\n'),
tab = '\t',
spaces = ''
;
// Create a string with 1000 spaces to copy spaces from...
// It's assumed that there would be no indentation longer than that.
for (var i = 0; i < 50; i++)
spaces += ' '; // 20 spaces * 50
// This function inserts specified amount of spaces in the string
// where a tab is while removing that given tab.
function insertSpaces(line, pos, count)
{
return line.substr(0, pos)
+ spaces.substr(0, count)
+ line.substr(pos + 1, line.length) // pos + 1 will get rid of the tab
;
};
// Go through all the lines and do the 'smart tabs' magic.
code = sh.utils.eachLine(code, function(line)
{
if (line.indexOf(tab) == -1)
return line;
var pos = 0;
while ((pos = line.indexOf(tab)) != -1)
{
// This is pretty much all there is to the 'smart tabs' logic.
// Based on the position within the line and size of a tab,
// calculate the amount of spaces we need to insert.
var spaces = tabSize - pos % tabSize;
line = insertSpaces(line, pos, spaces);
}
return line;
});
return code;
},
fixForBlogger : function(str)
{
return (sh.config.bloggerMode == true) ? str.replace(/<br\s*\/?>|<br\s*\/?>/gi, '\n') : str;
},
/**
* Removes all white space at the begining and end of a string.
*
* @param {String} str String to trim.
* @return {String} Returns string without leading and following white space characters.
*/
trim: function(str)
{
return str.replace(/\s*$/g, '').replace(/^\s*/, '');
},
/**
* Unindents a block of text by the lowest common indent amount.
* @param {String} str Text to unindent.
* @return {String} Returns unindented text block.
*/
unindent: function(str)
{
var lines = sh.utils.fixForBlogger(str).split('\n'),
indents = new Array(),
regex = /^\s*/,
min = 1000
;
// go through every line and check for common number of indents
for (var i = 0; i < lines.length && min > 0; i++)
{
var line = lines[i];
if (sh.utils.trim(line).length == 0)
continue;
var matches = regex.exec(line);
// In the event that just one line doesn't have leading white space
// we can't unindent anything, so bail completely.
if (matches == null)
return str;
min = Math.min(matches[0].length, min);
}
// trim minimum common number of white space from the begining of every line
if (min > 0)
for (var i = 0; i < lines.length; i++)
lines[i] = lines[i].substr(min);
return lines.join('\n');
},
/**
* Callback method for Array.sort() which sorts matches by
* index position and then by length.
*
* @param {Match} m1 Left object.
* @param {Match} m2 Right object.
* @return {Number} Returns -1, 0 or -1 as a comparison result.
*/
matchesSortCallback: function(m1, m2)
{
// sort matches by index first
if(m1.index < m2.index)
return -1;
else if(m1.index > m2.index)
return 1;
else
{
// if index is the same, sort by length
if(m1.length < m2.length)
return -1;
else if(m1.length > m2.length)
return 1;
}
return 0;
},
/**
* Executes given regular expression on provided code and returns all
* matches that are found.
*
* @param {String} code Code to execute regular expression on.
* @param {Object} regex Regular expression item info from <code>regexList</code> collection.
* @return {Array} Returns a list of Match objects.
*/
getMatches: function(code, regexInfo)
{
function defaultAdd(match, regexInfo)
{