-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathbibtex-cite.js
2242 lines (2118 loc) · 81.1 KB
/
bibtex-cite.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
/*
created by Falko Krause
inspired by Alf Eatons exciting.js <https://github.com/hubgit/Exciting>
released under GNU Lesser General Public License v 3 <http://www.gnu.org/licenses/lgpl.html>
the license does not apply to the included source code:
includes Javascript BibTex Parser v0.1 <http://www2.fas.sfu.ca/fas/sites/webgroup/projects/JSBibTexParser>
Usage:
Install this script in any google spreadsheet (or create a new empty spreadsheet) by using the menu Tools > Script Editor ...
Reload the spreadsheet
Use the BibTeX-cite menu and Configure BibTeX-Cite (Upload a .bib file, reload the config, choose .bib file and Document)
Insert \cite{foo} in your Google Document
Use the BibTeX-cite > Update Citation Index
*/
//========================================================
// on install create menu
function onInstall() {
onOpen();
}
//========================================================
// create menu and hook it up to the funcitons
function onOpen() {
var menuEntries = [
{name: "Update Citation Index", functionName: "updateIndex"},
{name: "Clear Citation Index", functionName: "indexToLatex"},
{name: "Insert Complete Index", functionName: "completeIndex"},
{name: "Configure BibTeX-cite", functionName: "configure"}
];
SpreadsheetApp.getActiveSpreadsheet().addMenu("BibTeX-cite", menuEntries);
}
function completeIndex(){
//append complete citation index to the document without [1] in first column but with the citation key
var data = getBibtexAndDoc();
var body = data.body;
var bibtex_dict = data.bibtex_dict;
var section = body.appendParagraph("Complete Bibliography");
section.setHeading(DocumentApp.ParagraphHeading.HEADING1);
var bibliography = body.appendTable().setBorderColor('#FFFFFF');
var counter = 1;
for (key in bibtex_dict) {
//-----------------
//create table citation entry
var row = bibliography.appendTableRow();
row.appendTableCell().setWidth(30.0).setVerticalAlignment(DocumentApp.VerticalAlignment.TOP).appendParagraph('['+counter+']').setFontSize(10.0);
// we must put the citation key hidden in there to re-run the citation index buildup process
// so we can revert the [1] to \cite{abc} and then start this process over again
row.appendTableCell().setWidth(5.0).appendParagraph(key).setFontSize(0.1).setForegroundColor('#FFFFFF');//hidden key
var cell = row.appendTableCell();
var bibtexobj = bibtex_dict[key];
// 'AUTHORS, "<strong>TITLE</strong>", <em>JOURNAL</em>, YEAR<br />';
var citation_paragraph = cell.appendParagraph(bibtexobj.authors+', ').setFontSize(10.0).setForegroundColor('#000000');
citation_paragraph.appendText(bibtexobj.title).setBold(true);
citation_paragraph.appendText(', ').setBold(false);
citation_paragraph.appendText(bibtexobj.journal).setItalic(true);
citation_paragraph.appendText(', '+bibtexobj.year+' ').setItalic(false);
//-----------------
++counter;
}
}
//========================================================
// search for \cite{foobar} and replace it with [1]
// create a Bibliography heading and a table with the bibligraphy corresponding to [1]
function updateIndex(){
var data = getBibtexAndDoc();
var body = data.body;
var bibtex_dict = data.bibtex_dict;
if (body!==undefined) {
var bibliography = indexToLatex();
if (bibliography == undefined){
//append citation index section
var section = body.appendParagraph("Bibliography");
section.setHeading(DocumentApp.ParagraphHeading.HEADING1);
bibliography = body.appendTable().setBorderColor('#FFFFFF');
}
//--------------------------------------
var counter = 1;//counter for [1] [2] replacements
var result = null;
do{
result = body.findText("\\\\cite\\{[^\\}]+\\}", result);//this does not seem to hit every citations????
if (!result) break;
var startOffset = result.getStartOffset();
var endOffset = result.getEndOffsetInclusive();
var text = result.getElement().getText().substr(startOffset, (endOffset - startOffset) + 1);
var replacement = "[" + counter + "]";
//-----------------
var match = text.match(/^.cite\{([^\}]+)\}$/i);
//if (!match) return false;
if (match){
var key = match[1];
if (key in bibtex_dict){
body.replaceText('.cite{'+key+'}', replacement);//replace \cite{foo} with [1]
//-----------------
//create table citation entry
var row = bibliography.appendTableRow();
row.appendTableCell().setWidth(30.0).setVerticalAlignment(DocumentApp.VerticalAlignment.TOP).appendParagraph('['+counter+']').setFontSize(10.0);
// we must put the citation key hidden in there to re-run the citation index buildup process
// so we can revert the [1] to \cite{abc} and then start this process over again
row.appendTableCell().setWidth(5.0).appendParagraph(key).setFontSize(0.1).setForegroundColor('#FFFFFF');//hidden key
var cell = row.appendTableCell();
var bibtexobj = bibtex_dict[key];
// 'AUTHORS, "<strong>TITLE</strong>", <em>JOURNAL</em>, YEAR<br />';
var citation_paragraph = cell.appendParagraph(bibtexobj.authors+', ').setFontSize(10.0).setForegroundColor('#000000');
citation_paragraph.appendText(bibtexobj.title).setBold(true);
if (bibtexobj.journal != ''){
citation_paragraph.appendText(', ').setBold(false);
citation_paragraph.appendText(bibtexobj.journal).setItalic(true);
}
if (bibtexobj.year != '') citation_paragraph.appendText(', '+bibtexobj.year+' ').setItalic(false).setBold(false);
//-----------------
++counter;
}
}
} while (result);
}
}
function indexToLatex(){
var data = getBibtexAndDoc();
var body = data.body;
var bibtex_dict = data.bibtex_dict;
var bibliography;
if (body!==undefined) {
//--------------------------------------
//find if Biblography paragraph was added
for (var i = 0; i<body.getNumChildren(); ++i){
var curChild = body.getChild(i);
if ((curChild.getType() == DocumentApp.ElementType.PARAGRAPH)&&(curChild.getText()=="Bibliography")) {
if (body.getChild(i+1).getType() == DocumentApp.ElementType.TABLE){
bibliography = body.getChild(i+1);
//--------------------------------------
//iterate through table and reverse citation linking
for (var r=0; r<bibliography.getNumRows(); ++r){
var row = bibliography.getRow(r);
var needle =row.getCell(0).getText();
needle = needle.substring(2,needle.length-1);
var replace =row.getCell(1).getText();
replace = replace.substring(1,replace.length);
body.replaceText('\\['+needle+'\\]', '\\cite{'+replace+'}');//replace [1] with \cite{foo}
//body.appendParagraph(needle+" -> "+'\\cite{'+replace+'}');//DEBUG
}
body.removeChild(bibliography);//delete old bib table
}
bibliography = body.appendTable().setBorderColor('#FFFFFF');//create new bib table
break;
}
}
}
return bibliography;
}
//========================================================
// get a Document body instance and bibtex citation dictionary
// dict is of the form {'\cite{Foo123}': 'Foo,F "Foobar title", 1234, Journal' }
function getBibtexAndDoc(){
//init the return vars
var bibtex_dict = []
var body;//inits to undefinded
//-------------
var bibtex_file_ids, doc_file_ids;
bibtex_file_ids = ScriptProperties.getProperty("bibtex_file_ids");
if (bibtex_file_ids == null) bibtex_file_ids = {};
else bibtex_file_ids = JSON.parse(bibtex_file_ids);
doc_file_ids = ScriptProperties.getProperty("doc_file_ids");
if (doc_file_ids == null) doc_file_ids = {};
else doc_file_ids = JSON.parse(doc_file_ids);
//-------------
//go through doc list to find all documents ending with .bib
//TODO only iterate through "Documents"
var doclist = DriveApp.getAllFiles();
var bibtex_doc;
var found = false;
for(var i=0; i<doclist.length; ++i){
var dfile = doclist[i];
if (dfile.getId() in bibtex_file_ids){
//if (dfile.getName().substring(dfile.getName().length-4,dfile.getName().length)=='.bib'){
found = true;
bibtex_doc = dfile;
break;
}
}
//-------------
//use BibTex javascript at the bottom of this script
var bibtex = new BibTex();
bibtex.content = bibtex_doc.getContentAsString(); // the bibtex content as a string
bibtex.parse();
//-------------
//create lookup dict for citations with {'citekey':'citation string: authors, title, ...'}
for(var i=0; i<bibtex.data.length; ++i){
var outobj = bibtex.google(i);
bibtex_dict[bibtex.data[i].cite] = outobj;
}
//-------------
//loop through all documents to find document with title Citation Test, this is just the dev test document
var docid;
var doclist = DriveApp.getAllFiles();
for(var i=0; i<doclist.length; ++i){
var dfile = doclist[i];
if (dfile.getId() in doc_file_ids){
//if (dfile.getName() == 'Citation Test'){
docid = dfile.getId();
break;
}
}
if (docid!=undefined) {
var doc = DocumentApp.openById(docid);
body = doc.getActiveSection();
}
return {bibtex_dict: bibtex_dict, body: body};
}
//========================================================
function configure(){
//create GUI for uploadind BibTeX files and connecting documents and bibtex files
var doc = SpreadsheetApp.getActiveSpreadsheet();
var app = UiApp.createApplication().setTitle("Import BibTeX File");
//-------------
var results = app.createLabel('results here').setId('status');
app.add(results);
//-------------
var bibtex_file_ids, doc_file_ids;
bibtex_file_ids = ScriptProperties.getProperty("bibtex_file_ids");
if (bibtex_file_ids == null) bibtex_file_ids = {};
else bibtex_file_ids = JSON.parse(bibtex_file_ids);
doc_file_ids = ScriptProperties.getProperty("doc_file_ids");
if (doc_file_ids == null) doc_file_ids = {};
else doc_file_ids = JSON.parse(doc_file_ids);
//results.setText('foo: ' + JSON.stringify(bibtex_file_ids)+' '+JSON.stringify(doc_file_ids));
//-------------
app.add(app.createHTML('<h4>Select</h4>'));
var form_select = app.createFormPanel();
var hoizontal_panel = app.createHorizontalPanel();
form_select.add(hoizontal_panel);
var choose_bib = app.createVerticalPanel().setId('choose');
var doclist = DriveApp.getAllFiles();
for(var i=0; i<doclist.length; ++i){
var dfile = doclist[i];
if (dfile.getName().substring(dfile.getName().length-4,dfile.getName().length)=='.bib'){
var checkbox = app.createCheckBox(dfile.getName()).setName('bib_'+dfile.getId());
if (dfile.getId() in bibtex_file_ids) checkbox.setStyleAttribute("backgroundColor","green");
choose_bib.add(checkbox);
}
}
doclist = DriveApp.getFilesByType("document");
var choose_doc = app.createVerticalPanel();
for(var i=0; i<doclist.length; ++i){
var dfile = doclist[i];
var checkbox = app.createCheckBox(dfile.getName()).setName('doc_'+dfile.getId());
if (dfile.getId() in doc_file_ids) checkbox.setStyleAttribute("backgroundColor","green");
choose_doc.add(checkbox);
}
hoizontal_panel.add( app.createScrollPanel(choose_bib).setPixelSize(220, 150) );
hoizontal_panel.add( app.createScrollPanel(choose_doc).setPixelSize(220, 150) );
//hoizontal_panel.add( app.createButton("Update Citation Index") );
//-------------
var saveHandler = app.createServerClickHandler("saveConfiguration");
saveHandler.addCallbackElement(form_select);
app.add( app.createButton("Save Configuration", saveHandler) );
//-------------
app.add(form_select);
//-------------
app.add(app.createHTML('<h4>Upload</h4>'));
var form = app.createFormPanel().setId('frm').setEncoding('multipart/form-data');
var flow = app.createHorizontalPanel().setId('flow');
var fileUpload = app.createFileUpload().setName("bibtex").setId('bibtex');
flow.add(fileUpload);
flow.add(app.createSubmitButton("Upload New BibTeX File"));
form.add(flow);
app.add(form);
//-------------
doc.show(app);
return app
}
//========================================================
function saveConfiguration(e) {
var bibtex_file_ids = {};
var doc_file_ids = {};
for (pkey in e.parameter){
if ( (pkey.substr(0,3) == "doc") && (e.parameter[pkey]=="true"))
doc_file_ids[pkey.substr(4,pkey.length)] = 1;
if ( (pkey.substr(0,3) == "bib") && (e.parameter[pkey]=="true"))
bibtex_file_ids[pkey.substr(4,pkey.length)] = 1;
}
ScriptProperties.setProperty("bibtex_file_ids", JSON.stringify(bibtex_file_ids));
ScriptProperties.setProperty("doc_file_ids", JSON.stringify(doc_file_ids));
//---------------
var app = UiApp.getActiveApplication();
//var bibtex_file_ids1 = ScriptProperties.getProperty("bibtex_file_ids");
//var doc_file_ids1 = ScriptProperties.getProperty("doc_file_ids");
//app.getElementById('status').setText('foo: ' + doc_file_ids1);
app.getElementById('status').setText('saved config, only one file of each will be processed so far');
//---------------
//app.close();
return app;
}
//========================================================
//upload bibtex file
//TODO upload only if file can be verified as bibtex file
function doPost(e){
var app = UiApp.getActiveApplication();
//-------------
var doclist = DriveApp.getAllFiles();
var found = false;
var bibtex_doc;
for(var i=0; i<doclist.length; ++i){
var dfile = doclist[i];
if (dfile.getName() == e.parameter.bibtex.name){
found = true;
bibtex_doc = dfile;
break;
}
}
//-------------
if (! found){
var bibtex_doc = DriveApp.createFile(e.parameter.bibtex);
}
return app
}
//========================================================
//---------------------------------------------------------------
//---------------------------------------------------------------
//---------------------------------------------------------------
//---------------------------------------------------------------
/**
* Javascript BibTex Parser v0.1
* Copyright (c) 2008 Simon Fraser University
* @author Steve Hannah <shannah at sfu dot ca>
*
*
* License:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* Credits:
*
* This library is a port of the PEAR Structures_BibTex parser written
* in PHP (http://pear.php.net/package/Structures_BibTex).
*
* In order to make porting the parser into javascript easier, I have made
* use of many phpjs functions, which are distributed here under the MIT License:
*
*
* More info at: http://kevin.vanzonneveld.net/techblog/category/php2js
*
* php.js is copyright 2008 Kevin van Zonneveld.
*
* Portions copyright Ates Goral (http://magnetiq.com), Legaev Andrey,
* _argos, Jonas Raoni Soares Silva (http://www.jsfromhell.com),
* Webtoolkit.info (http://www.webtoolkit.info/), Carlos R. L. Rodrigues, Ash
* Searle (http://hexmen.com/blog/), Tyler Akins (http://rumkin.com), mdsjack
* (http://www.mdsjack.bo.it), Alexander Ermolaev
* (http://snippets.dzone.com/user/AlexanderErmolaev), Andrea Giammarchi
* (http://webreflection.blogspot.com), Bayron Guevara, Cord, David, Karol
* Kowalski, Leslie Hoare, Lincoln Ramsay, Mick@el, Nick Callen, Peter-Paul
* Koch (http://www.quirksmode.org/js/beat.html), Philippe Baumann, Steve
* Clay, booeyOH
*
* Licensed under the MIT (MIT-LICENSE.txt) license.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL KEVIN VAN ZONNEVELD BE LIABLE FOR ANY CLAIM, DAMAGES
* OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
*
* Synopsis:
* ----------
*
* This class provides the following functionality:
* 1. Parse BibTex into a logical data javascript data structure.
* 2. Output parsed BibTex entries as HTML, RTF, or BibTex.
*
*
* The following usage instructions have been copyed and adapted from the PHP instructions located
* at http://pear.php.net/manual/en/package.structures.structures-bibtex.intro.php
* Introduction
* --------------
* Overview
* ----------
* This package provides methods to access information stored in a BibTex
* file. During parsing it is possible to let the data be validated. In
* addition. the creation of BibTex Strings as well as RTF Strings is also
* supported. A few examples
*
* Example 1. Loading a BibTex File and printing the parsed array
* <script src="BibTex.js"></script>
* <script>
* bibtexæ=ænewæBibTex();
* bibtex.content = content; // the bibtex content as a string
*
* bibtex->parse();
* alert(print_r($bibtex->data,true));
* </script>
*
*
* Options
* --------
* Options can be set either in the constructor or with the method
* setOption(). When setting in the constructor the options are given in an
* associative array. The options are:
*
* - stripDelimiter (default: true) Stripping the delimiter surrounding the entries.
* - validate (default: true) Validation while parsing.
* - unwrap (default: false) Unwrapping entries while parsing.
* - wordWrapWidth (default: false) If set to a number higher one
* that the entries are wrapped after that amount of characters.
* - wordWrapBreak (default: \n) String used to break the line (attached to the line).
* - wordWrapCut (default: 0) If set to zero the line will we
* wrapped at the next possible space, if set to one the line will be
* wrapped exactly after the given amount of characters.
* - removeCurlyBraces (default: false) If set to true Curly Braces will be removed.
*
* Example of setting options in the constructor:
*
* Example 2. Setting options in the constructor
* bibtexæ=ænewæBibTex({'validate':false,æ'unwrap':true});
*
*
* Example of setting options using the method setOption():
*
* Example 62-3. Setting options using setOption
* bibtexæ=ænewæBibTex();
* bibtex.setOption('validate',æfalse);
* bibtex.setOption('unwrap',ætrue);
*
* Stored Data
* ------------
* The data is stored in the class variable data. This is a a list where
* each entry is a hash table representing one bibtex-entry. The keys of
* the hash table correspond to the keys used in bibtex and the values are
* the corresponding values. Some of these keys are:
*
* - cite - The key used in a LaTeX source to do the citing.
* - entryType - The type of the entry, like techreport, book and so on.
* - author - One or more authors of the entry. This entry is also a
* list with hash tables representing the authors as entries. The
* author has table is explained later.
* - title - Title of the entry.
*
* Author
* ------
* As described before the authors are stored in a list. Every entry
* representing one author as a has table. The hash table consits of four
* keys: first, von, last and jr. The keys are explained in the following
* list:
*
* - first - The first name of the author.
* - von - Some names have a 'von' part in their name. This is usually a sign of nobleness.
* - last - The last name of the author.
* - jr - Sometimes a author is the son of his father and has the
* same name, then the value would be jr. The same is true for the
* value sen but vice versa.
*
* Adding an entry
* ----------------
* To add an entry simply create a hash table with the needed keys and
* values and call the method addEntry().
* Example 4. Adding an entry
* bibtexæææææææææææææææææææææææææ=ænewæBibTex();
* var addarrayæææææææææææææææææææææææ=æ{};
* addarray['entryType']ææææææææææ=æ'Article';
* addarray['cite']æææææææææææææææ=æ'art2';
* addarray['title']ææææææææææææææ=æ'TitelæofætheæArticle';
* addarray['author'] = [];
* addarray['author'][0]['first']æ=æ'John';
* addarray['author'][0]['last']ææ=æ'Doe';
* addarray['author'][1]['first']æ=æ'Jane';
* addarray['author'][1]['last']ææ=æ'Doe';
* bibtex.addEntry(addarray);
*/
// ------------BEGIN PHP FUNCTIONS -------------------------------------------------------------- //
// {{{ array
function array( ) {
// #!#!#!#!# array::$descr1 does not contain valid 'array' at line 258
//
// + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_array/
// + version: 805.1716
// + original by: d3x
// * example 1: array('Kevin', 'van', 'Zonneveld');
// * returns 1: ['Kevin', 'van', 'Zonneveld'];
return Array.prototype.slice.call(arguments);
}// }}}
// {{{ array_key_exists
function array_key_exists ( key, search ) {
// Checks if the given key or index exists in the array
//
// + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_array_key_exists/
// + version: 804.1712
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: Felix Geisendoerfer (http://www.debuggable.com/felix)
// * example 1: array_key_exists('kevin', {'kevin': 'van Zonneveld'});
// * returns 1: true
// input sanitation
if( !search || (search.constructor !== Array && search.constructor !== Object) ){
return false;
}
return key in search;
}// }}}// {{{ array_keys
function array_keys( input, search_value, strict ) {
// Return all the keys of an array
//
// + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_array_keys/
// + version: 804.1712
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// * example 1: array_keys( {firstname: 'Kevin', surname: 'van Zonneveld'} );
// * returns 1: {0: 'firstname', 1: 'surname'}
var tmp_arr = new Array(), strict = !!strict, include = true, cnt = 0;
for ( key in input ){
include = true;
if ( search_value != undefined ) {
if( strict && input[key] !== search_value ){
include = false;
} else if( input[key] != search_value ){
include = false;
}
}
if( include ) {
tmp_arr[cnt] = key;
cnt++;
}
}
return tmp_arr;
}// }}}
// {{{ in_array
function in_array(needle, haystack, strict) {
// Checks if a value exists in an array
//
// + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_in_array/
// + version: 804.1712
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// * example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);
// * returns 1: true
var found = false, key, strict = !!strict;
for (key in haystack) {
if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
found = true;
break;
}
}
return found;
}// }}}
// {{{ sizeof
function sizeof ( mixed_var, mode ) {
// Alias of count()
//
// + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_sizeof/
// + version: 804.1712
// + original by: Philip Peterson
// - depends on: count
// * example 1: sizeof([[0,0],[0,-4]], 'COUNT_RECURSIVE');
// * returns 1: 6
// * example 2: sizeof({'one' : [1,2,3,4,5]}, 'COUNT_RECURSIVE');
// * returns 2: 6
return count( mixed_var, mode );
}// }}}
// {{{ count
function count( mixed_var, mode ) {
// Count elements in an array, or properties in an object
//
// + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_count/
// + version: 804.1712
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + input by: _argos
// * example 1: count([[0,0],[0,-4]], 'COUNT_RECURSIVE');
// * returns 1: 6
// * example 2: count({'one' : [1,2,3,4,5]}, 'COUNT_RECURSIVE');
// * returns 2: 6
var key, cnt = 0;
if( mode == 'COUNT_RECURSIVE' ) mode = 1;
if( mode != 1 ) mode = 0;
for (key in mixed_var){
cnt++;
if( mode==1 && mixed_var[key] && (mixed_var[key].constructor === Array || mixed_var[key].constructor === Object) ){
cnt += count(mixed_var[key], 1);
}
}
return cnt;
}// }}}
// {{{ explode
function explode( delimiter, string, limit ) {
// Split a string by string
//
// + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_explode/
// + version: 805.1715
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: kenneth
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: d3x
// + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// * example 1: explode(' ', 'Kevin van Zonneveld');
// * returns 1: {0: 'Kevin', 1: 'van', 2: 'Zonneveld'}
// * example 2: explode('=', 'a=bc=d', 2);
// * returns 2: ['a', 'bc=d']
var emptyArray = { 0: '' };
// third argument is not required
if ( arguments.length < 2
|| typeof arguments[0] == 'undefined'
|| typeof arguments[1] == 'undefined' )
{
return null;
}
if ( delimiter === ''
|| delimiter === false
|| delimiter === null )
{
return false;
}
if ( typeof delimiter == 'function'
|| typeof delimiter == 'object'
|| typeof string == 'function'
|| typeof string == 'object' )
{
return emptyArray;
}
if ( delimiter === true ) {
delimiter = '1';
}
if (!limit) {
return string.toString().split(delimiter.toString());
} else {
// support for limit argument
var splitted = string.toString().split(delimiter.toString());
var partA = splitted.splice(0, limit - 1);
var partB = splitted.join(delimiter.toString());
partA.push(partB);
return partA;
}
}// }}}
// {{{ implode
function implode( glue, pieces ) {
// Join array elements with a string
//
// + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_implode/
// + version: 804.1712
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: _argos
// * example 1: implode(' ', ['Kevin', 'van', 'Zonneveld']);
// * returns 1: 'Kevin van Zonneveld'
return ( ( pieces instanceof Array ) ? pieces.join ( glue ) : pieces );
}// }}}
// {{{ join
function join( glue, pieces ) {
// Alias of implode()
//
// + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_join/
// + version: 804.1712
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// - depends on: implode
// * example 1: join(' ', ['Kevin', 'van', 'Zonneveld']);
// * returns 1: 'Kevin van Zonneveld'
return implode( glue, pieces );
}// }}}
// {{{ split
function split( delimiter, string ) {
// Split string into array by regular expression
//
// + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_split/
// + version: 804.1712
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// - depends on: explode
// * example 1: split(' ', 'Kevin van Zonneveld');
// * returns 1: {0: 'Kevin', 1: 'van', 2: 'Zonneveld'}
return explode( delimiter, string );
}// }}}
// {{{ str_replace
function str_replace(search, replace, subject) {
// Replace all occurrences of the search string with the replacement string
//
// + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_str_replace/
// + version: 805.3114
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: Gabriel Paderni
// + improved by: Philip Peterson
// + improved by: Simon Willison (http://simonwillison.net)
// + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
// - depends on: is_array
// * example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
// * returns 1: 'Kevin.van.Zonneveld'
// * example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
// * returns 2: 'hemmo, mars'
var f = search, r = replace, s = subject;
var ra = is_array(r), sa = is_array(s), f = [].concat(f), r = [].concat(r), i = (s = [].concat(s)).length;
while (j = 0, i--) {
while (s[i] = s[i].split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f){};
};
return sa ? s : s[0];
}// }}}
// {{{ strlen
function strlen( string ){
// Get string length
//
// + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_strlen/
// + version: 805.1616
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: Sakimori
// * example 1: strlen('Kevin van Zonneveld');
// * returns 1: 19
return ("" + string).length;
}// }}}
// {{{ strpos
function strpos( haystack, needle, offset){
// Find position of first occurrence of a string
//
// + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_strpos/
// + version: 804.1712
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// * example 1: strpos('Kevin van Zonneveld', 'e', 5);
// * returns 1: 14
var i = haystack.indexOf( needle, offset ); // returns -1
return i >= 0 ? i : false;
}// }}}
// {{{ strrpos
function strrpos( haystack, needle, offset){
// Find position of last occurrence of a char in a string
//
// + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_strrpos/
// + version: 804.1712
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// * example 1: strrpos('Kevin van Zonneveld', 'e');
// * returns 1: 16
var i = haystack.lastIndexOf( needle, offset ); // returns -1
return i >= 0 ? i : false;
}// }}}
// {{{ strtolower
function strtolower( str ) {
// Make a string lowercase
//
// + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_strtolower/
// + version: 804.1712
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// * example 1: strtolower('Kevin van Zonneveld');
// * returns 1: 'kevin van zonneveld'
return str.toLowerCase();
}// }}}
// {{{ strtoupper
function strtoupper( str ) {
// Make a string uppercase
//
// + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_strtoupper/
// + version: 804.1712
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// * example 1: strtoupper('Kevin van Zonneveld');
// * returns 1: 'KEVIN VAN ZONNEVELD'
return str.toUpperCase();
}// }}}
// {{{ substr
function substr( f_string, f_start, f_length ) {
// Return part of a string
//
// + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_substr/
// + version: 804.1712
// + original by: Martijn Wieringa
// * example 1: substr('abcdef', 0, -1);
// * returns 1: 'abcde'
if(f_start < 0) {
f_start += f_string.length;
}
if(f_length == undefined) {
f_length = f_string.length;
} else if(f_length < 0){
f_length += f_string.length;
} else {
f_length += f_start;
}
if(f_length < f_start) {
f_length = f_start;
}
return f_string.substring(f_start, f_length);
}// }}}
// {{{ trim
function trim( str, charlist ) {
// Strip whitespace (or other characters) from the beginning and end of a string
//
// + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_trim/
// + version: 804.1712
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: mdsjack (http://www.mdsjack.bo.it)
// + improved by: Alexander Ermolaev (http://snippets.dzone.com/user/AlexanderErmolaev)
// + input by: Erkekjetter
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + input by: DxGx
// + improved by: Steven Levithan (http://blog.stevenlevithan.com)
// * example 1: trim(' Kevin van Zonneveld ');
// * returns 1: 'Kevin van Zonneveld'
// * example 2: trim('Hello World', 'Hdle');
// * returns 2: 'o Wor'
var whitespace;
if(!charlist){
whitespace = ' \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000';
} else{
whitespace = charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '\$1');
}
for (var i = 0; i < str.length; i++) {
if (whitespace.indexOf(str.charAt(i)) === -1) {
str = str.substring(i);
break;
}
}
for (i = str.length - 1; i >= 0; i--) {
if (whitespace.indexOf(str.charAt(i)) === -1) {
str = str.substring(0, i + 1);
break;
}
}
return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
}// }}}
// {{{ wordwrap
function wordwrap( str, int_width, str_break, cut ) {
// Wraps a string to a given number of characters
//
// + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_wordwrap/
// + version: 804.1715
// + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
// + improved by: Nick Callen
// + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
// * example 1: wordwrap('Kevin van Zonneveld', 6, '|', true);
// * returns 1: 'Kevin |van |Zonnev|eld'
var m = int_width, b = str_break, c = cut;
var i, j, l, s, r;
if(m < 1) {
return str;
}
for(i = -1, l = (r = str.split("\n")).length; ++i < l; r[i] += s) {
for(s = r[i], r[i] = ""; s.length > m; r[i] += s.slice(0, j) + ((s = s.slice(j)).length ? b : "")){
j = c == 2 || (j = s.slice(0, m + 1).match(/\S*(\s)?$/))[1] ? m : j.input.length - j[0].length || c == 1 && m || j.input.length + (j = s.slice(m).match(/^\S*/)).input.length;
}
}
return r.join("\n");
}// }}}
// {{{ is_string
function is_string( mixed_var ){
// Find whether the type of a variable is string
//
// + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_is_string/
// + version: 804.1712
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// * example 1: is_string('23');
// * returns 1: true
// * example 2: is_string(23.5);
// * returns 2: false
return (typeof( mixed_var ) == 'string');
}// }}}
// {{{ ord
function ord( string ) {
// Return ASCII value of character
//
// + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_ord/
// + version: 804.1712
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// * example 1: ord('K');
// * returns 1: 75
return string.charCodeAt(0);
}// }}}
// {{{ array_unique
function array_unique( array ) {
// Removes duplicate values from an array
//
// + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_array_unique/
// + version: 805.211
// + original by: Carlos R. L. Rodrigues (http://www.jsfromhell.com)
// + input by: duncan
// + bufixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// * example 1: array_unique(['Kevin','Kevin','van','Zonneveld']);
// * returns 1: ['Kevin','van','Zonneveld']
var p, i, j, tmp_arr = array;
for(i = tmp_arr.length; i;){
for(p = --i; p > 0;){
if(tmp_arr[i] === tmp_arr[--p]){
for(j = p; --p && tmp_arr[i] === tmp_arr[p];);
i -= tmp_arr.splice(p + 1, j - p).length;
}
}
}
return tmp_arr;
}// }}}
// {{{ print_r
function print_r( array, return_val ) {
// Prints human-readable information about a variable
//
// + discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_print_r/
// + version: 805.2023
// + original by: Michael White (http://crestidg.com)
// + improved by: Ben Bryan
// * example 1: print_r(1, true);
// * returns 1: 1
var output = "", pad_char = " ", pad_val = 4;
var formatArray = function (obj, cur_depth, pad_val, pad_char) {
if (cur_depth > 0) {
cur_depth++;
}
var base_pad = repeat_char(pad_val*cur_depth, pad_char);
var thick_pad = repeat_char(pad_val*(cur_depth+1), pad_char);
var str = "";
if (obj instanceof Array || obj instanceof Object) {
str += "Array\n" + base_pad + "(\n";
for (var key in obj) {
if (obj[key] instanceof Array || obj[key] instanceof Object) {