forked from l0o0/translators_CN
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RefWorks Tagged.js
1185 lines (1094 loc) · 42.6 KB
/
RefWorks Tagged.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
{
"translatorID": "1a3506da-a303-4b0a-a1cd-f216e6138d86",
"label": "RefWorks Tagged",
"creator": "Simon Kornblith, Aurimas Vinckevicius, and Sebastian Karcher",
"target": "txt",
"minVersion": "3.0.4",
"maxVersion": "",
"priority": 100,
"displayOptions": {
"exportCharset": "UTF-8",
"exportNotes": true,
"exportFileData": true
},
"inRepository": true,
"translatorType": 3,
"browserSupport": "gcsv",
"lastUpdated": "2016-06-21 08:45:20"
}
/*This Translator mirrors closely Aurimas Vinckevicius' RIS translator
It may have several relics from that translator that aren't necessary for Refworks,
but since the formats are similar and having them in the translator won't hurt, I maintained them.
Most commenting also refers to RIS
The specifications are here:
http://www.refworks.com/refworks2/help/RefWorks_Tagged_Format.htm
*/
function detectImport() {
var line;
var i = 0;
while ((line = Zotero.read()) !== false) {
line = line.replace(/^\s+/, "");
if (line != "") {
if (line.search(/^RT\s+./) != -1) {
return true;
} else {
if (i++ > 150) { //skip preamble
return false;
}
}
}
}
}
/********************
* Exported options *
********************/
var exportedOptions = {
itemType: false //allows translators to supply item type
};
/************************
* RT <-> itemType maps *
************************/
var DEFAULT_EXPORT_TYPE = 'Generic';
var DEFAULT_IMPORT_TYPE = 'journalArticle';
var exportTypeMap = {
artwork:"Artwork",
audioRecording:"Sound Recording", //consider MUSIC
bill:"Bills",
blogPost:"Web Page",
book:"Book, Whole",
bookSection:"Book, Section",
"case":"Case",
computerProgram:"Computer Program",
conferencePaper:"Conference Proceedings",
email:"Personal Communication",
film:"Motion Picture",
forumPost:"Online Discussion Forum",
hearing:"Hearing",
journalArticle:"Journal Article",
letter:"Personal Communication",
magazineArticle:"Magazine Article",
manuscript:"Unpublished Material",
map:"Map",
newspaperArticle:"Newspaper Article",
patent:"Patent",
report:"Report",
statute:"Statutes",
thesis:"Dissertation",
videoRecording:"Video",
webpage:"Web Page"
};
//These export type maps are degenerate
//They will cause loss of information when exported and reimported
//These should either be duplicates of some of the RW types above
// or be different from the importTypeMap mappings
var degenerateExportTypeMap = {
interview:"Personal Communication",
instantMessage:"Personal Communication",
tvBroadcast:"Motion Picture",
radioBroadcast:"Sound Recording",
presentation:"Report",
podcast:"Sound Recording",
dictionaryEntry:"Book, Section",
encyclopediaArticle:"Book, Section",
document:"Generic" //imported as journalArticle
};
//These are degenerate types that are not exported as the same TY value
//These should not include any types from exportTypeMap
//We add the rest from exportTypeMap
var importTypeMap = {
Abstract:"journalArticle",
"Book, Edited":"book",
"Court Decisions":"case",
DVD:"videoRecording",
Grant:"report",
"Journal, Electronic":"journalArticle",
Laws:"statute",
Monograph:"book",
"Music Score":"audioRecording",
Resolutions:"bill",
"Thesis, Unpublished":"thesis",
Thesis:"thesis"
};
//supplement input map with export
var ty;
for (ty in exportTypeMap) {
importTypeMap[exportTypeMap[ty]] = ty;
}
//merge degenerate export type map into main list
for (ty in degenerateExportTypeMap) {
exportTypeMap[ty] = degenerateExportTypeMap[ty];
}
/*****************************
* Tag <-> zotero field maps *
*****************************/
//used for exporting and importing
//this ensures that we can mostly reimport everything the same way
//(except for item types that do not have unique RW types, see above)
var fieldMap = {
//same for all itemTypes
AB:"abstractNote",
CN:"callNumber",
DO:"DOI",
SL:"archive",
LL:"archiveLocation",
IS:"issue",
JO:"journalAbbreviation",
K1:"tags",
LK:"attachments/other",
NO:"notes",
ST:"shortTitle",
RD:"accessDate",
UL:"url",
//type specific
//tag => field:itemTypes
//if itemType not explicitly given, __default field is used
// unless itemType is excluded in __exclude
T1: {
"__default":"title",
subject:["email"],
caseName:["case"],
nameOfAct:["statute"]
},
T2: {
code:["bill", "statute"],
bookTitle:["bookSection"],
blogTitle:["blogPost"],
conferenceName:["conferencePaper"],
dictionaryTitle:["dictionaryEntry"],
encyclopediaTitle:["encyclopediaArticle"],
committee:["hearing"],
forumTitle:["forumPost"],
websiteTitle:["webpage"],
programTitle:["radioBroadcast", "tvBroadcast"],
meetingName:["presentation"],
seriesTitle:["computerProgram", "map", "report"],
series: ["book"],
publicationTitle:["journalArticle", "magazineArticle", "newspaperArticle"]
},
T3: {
legislativeBody:["hearing", "bill"],
series:["bookSection", "conferencePaper"],
seriesTitle:["audioRecording"]
},
//NOT HANDLED: reviewedAuthor, scriptwriter, contributor, guest
A1: {
"__default":"creators/author",
"creators/artist":["artwork"],
"creators/cartographer":["map"],
"creators/composer":["audioRecording"],
"creators/director":["film", "radioBroadcast", "tvBroadcast", "videoRecording"], //this clashes with audioRecording
"creators/interviewee":["interview"],
"creators/inventor":["patent"],
"creators/podcaster":["podcast"],
"creators/programmer":["computerProgram"]
},
A2: {
"creators/sponsor":["bill"],
"creators/performer":["audioRecording"],
"creators/presenter":["presentation"],
"creators/interviewer":["interview"],
"creators/editor":["journalArticle", "bookSection", "conferencePaper", "dictionaryEntry", "document", "encyclopediaArticle"],
"creators/seriesEditor":["book"],
"creators/recipient":["email", "instantMessage", "letter"],
reporter:["case"],
issuingAuthority:["patent"]
},
A3: {
"creators/cosponsor":["bill"],
"creators/producer":["film", "tvBroadcast", "videoRecording", "radioBroadcast"],
"creators/editor":["book"],
"creators/seriesEditor":["bookSection", "conferencePaper", "dictionaryEntry", "encyclopediaArticle", "map", "report"]
},
A4: {
"__default":"creators/translator",
"creators/counsel":["case"],
"creators/contributor":["conferencePaper", "film"] //translator does not fit these
},
U1: {
filingDate:["patent"], //not in spec
"creators/castMember":["radioBroadcast", "tvBroadcast", "videoRecording"],
scale:["map"],
place:["conferencePaper"]
},
U2: {
issueDate:["patent"], //not in spec
"creators/bookAuthor":["bookSection"],
"creators/commenter":["blogPost"]
},
U3: {
artworkSize:["artwork"],
proceedingsTitle:["conferencePaper"],
country:["patent"]
},
U4: {
"creators/wordsBy":["audioRecording"], //not in spec
"creators/attorneyAgent":["patent"],
genre:["film"]
},
U5: {
references:["patent"],
audioRecordingFormat:["audioRecording", "radioBroadcast"],
videoRecordingFormat:["film", "tvBroadcast", "videoRecording"]
},
U6: {
legalStatus:["patent"],
},
PP: {
"__default":"place",
"__exclude":["conferencePaper"] //should be exported as C1
},
FD: {
"__default":"date",
dateEnacted:["statute"],
dateDecided:["case"],
issueDate:["patent"]
},
ED: {
"__default":"edition",
session:["bill", "hearing", "statute"],
version:["computerProgram"]
},
LA: {
"__default":"language",
programmingLanguage: ["computerProgram"]
},
CL: {
billNumber:["bill"],
system:["computerProgram"],
documentNumber:["hearing"],
applicationNumber:["patent"],
publicLawNumber:["statute"],
episodeNumber:["podcast", "radioBroadcast", "tvBroadcast"],
manuscriptType:["manuscript"],
mapType:["map"],
reportType:["report"],
thesisType:["thesis"],
websiteType:["blogPost", "webpage"],
postType:["forumPost"],
letterType:["letter"],
interviewMedium:["interview"],
presentationType:["presentation"],
artworkMedium:["artwork"],
audioFileType:["podcast"]
},
PB: {
"__default":"publisher",
label:["audioRecording"],
court:["case"],
distributor:["film"],
assignee:["patent"],
institution:["report"],
university:["thesis"],
company:["computerProgram"],
studio:["videoRecording"],
network:["radioBroadcast", "tvBroadcast"]
},
YR: { //duplicate of DA, but this will only output year
"__default":"date",
dateEnacted:["statute"],
dateDecided:["case"],
issueDate:["patent"]
},
SN: {
"__default":"ISBN",
ISSN:["journalArticle", "magazineArticle", "newspaperArticle"],
patentNumber:["patent"],
reportNumber:["report"],
},
SP: {
"__default":"pages", //needs extra processing
codePages:["bill"], //bill
numPages:["book", "thesis", "manuscript"], //manuscript not really in spec
firstPage:["case"],
runningTime:["film"]
},
VO: {
"__default":"volume",
codeNumber:["statute"],
codeVolume:["bill"],
reporterVolume:["case"],
"__exclude":["patent"]
}
};
//non-standard or degenerate field maps
//used ONLY for importing and only if these fields are not specified above (e.g. M3)
//these are not exported the same way
var degenerateImportFieldMap = {
OP: "pages",
JF: "publicationTitle",
JO: {
"__default": "journalAbbreviation",
conferenceName: ["conferencePaper"]
},
T2: "backupPublicationTitle", //most item types should be covered above
T3: {
series: ["book"]
}
};
//generic tag mapping object with caching
//not intended to be used directly
var TagMapper = function(mapList) {
this.cache = {};
this.mapList = mapList;
};
TagMapper.prototype.getFields = function(itemType, tag) {
if (!this.cache[itemType]) this.cache[itemType] = {};
//retrieve from cache if available
if (this.cache[itemType][tag]) {
return this.cache[itemType][tag];
}
var fields = [];
for (var i=0, n=this.mapList.length; i<n; i++) {
var map = this.mapList[i];
var field;
if (typeof(map[tag]) == 'object') {
var def, exclude = false;
for (var f in map[tag]) {
if (f == "__default") {
def = map[tag][f];
continue;
}
if (f == "__exclude") {
if (map[tag][f].indexOf(itemType) != -1) {
exclude = true;
}
continue;
}
if (map[tag][f].indexOf(itemType) != -1) {
field = f;
}
}
if (!field && def && !exclude) field = def;
} else if (typeof(map[tag]) == 'string') {
field = map[tag];
}
if (field) fields.push(field);
}
this.cache[itemType][tag] = fields;
return fields;
};
/********************
* Import Functions *
********************/
//set up import field mapping
var importFields = new TagMapper([fieldMap, degenerateImportFieldMap]);
function processTag(item, entry) {
var tag = entry[1];
var value = entry[2].trim();
var rawLine = entry[0];
var zField = importFields.getFields(item.itemType, tag)[0];
if (!zField) {
Z.debug("Unknown field " + tag + " in entry :\n" + rawLine);
zField = 'unknown'; //this will result in the value being added as note
}
//drop empty fields
if (value === "" || !zField) return;
zField = zField.split('/');
if (tag != "NO" && tag != "AB") {
value = Zotero.Utilities.unescapeHTML(value);
}
//tag based manipulations
var processFields = true; //whether we should continue processing by zField
switch (tag) {
case "NO":
//EndNote duplicates title in the note field sometimes maybe so does RW
if (item.title == value) {
value = undefined;
//do some HTML formatting in non-HTML notes
} else if (!value.match(/<[^>]+>/)) { //from cleanTags
value = '<p>'
+ value.replace(/\n\n/g, '</p><p>')
.replace(/\n/g, '<br/>')
.replace(/\t/g, ' ')
.replace(/ /g, ' ')
+ '</p>';
}
break;
case "OP":
if (item.pages) {
if (item.pages.indexOf('-') == -1) {
item.pages = item.pages + '-' + value;
} else {
item.backupNumPages = value;
}
value = undefined;
} else {
item.backupEndPage = value; //store this for an odd case where SP comes after OP
value = undefined;
}
break;
//See how YR works compared to other date formats
case "YR":
item.backupDate = {
field: zField,
value: dateRWtoZotero(value)
};
value = undefined;
processFields = false;
break;
}
//zField based manipulations
if (processFields){
switch (zField[0]) {
case "backupPublicationTitle":
item.backupPublicationTitle = value;
value = undefined;
break;
case "creators":
var creator = value.split(/\s*,\s*/);
value = {lastName: creator[0], firstName:creator[1], creatorType:zField[1]};
break;
case "date":
case "accessDate":
case "filingDate":
case "issueDate":
case "dateEnacted":
case "dateDecided":
value = dateRWtoZotero(value);
break;
case "tags":
//allow new lines or semicolons. Commas, might be more problematic
value = value.split(/\s*(?:[\r\n]+\s*)+|\s*(?:;\s*)+/);
//the regex will take care of double semicolons and newlines
//but it will still allow a blank tag if there is a newline or
//semicolon at the begining or the end
if (!value[0]) value.shift();
if (value.length && !value[value.length-1]) value.pop();
if (!value.length) {
value = undefined;
}
break;
case "notes":
value = {note:value};
//we can specify note title in the field mapping table. See VL for patent
if (zField[1]) {
value.note = zField[1] + ': ' + value.note;
}
break;
case "attachments":
var domain = value.match(/^https?:\/\/([^\/]+)/i);
domain = domain ? domain[1] + ' ' : '';
value = {
path:value,
title: domain + 'Link',
mimeType: 'text/html'
};
break;
case "unsupported": //unsupported fields
//we can convert a RIS tag to something more useful though
if (zField[1]) {
value = zField[1] + ': ' + value;
}
break;
}
}
applyValue(item, zField[0], value, rawLine);
}
function applyValue(item, zField, value, rawLine) {
if (!value) return;
if (!zField || zField == 'unknown') {
if (!Zotero.parentTranslator) {
Z.debug("Entry stored as note: " + rawLine);
item.unknownFields.push(rawLine);
}
return;
}
if (zField == 'unsupported') {
if (!Zotero.parentTranslator) {
Z.debug("Unsupported field will be stored in note: " + value);
item.unsupportedFields.push(value);
}
return;
}
//check if field is valid for item type
if (zField != 'creators' && zField != 'tags' && zField != 'notes'
&& zField != 'attachments'
&& !ZU.fieldIsValidForType(zField, item.itemType)) {
Z.debug("Invalid field '" + zField + "' for item type '" + item.itemType + "'.");
if (!Zotero.parentTranslator) {
Z.debug("Entry stored in note: " + rawLine);
item.unknownFields.push(rawLine);
return;
}
//otherwise, we can still store them and they will get dropped automatically
}
//special processing for certain fields
switch (zField) {
case 'notes':
case 'attachments':
case 'creators':
case 'tags':
if (!(value instanceof Array)) {
value = [value];
}
item[zField] = item[zField].concat(value);
break;
case 'extra':
if (item.extra) {
item.extra += '; ' + value;
} else {
item.extra = value;
}
break;
default:
//check if value already exists
if (item[zField]) {
//if it's not the new value is not the same as existing value, store it as note
if (!Zotero.parentTranslator && item[zField] != value) {
item.notes.push({note:rawLine});
}
} else {
item[zField] = value;
}
}
}
function dateRWtoZotero(risDate) {
var value = risDate.split(/\s*\/\s*(?:0*(?=\d))?/); //and also drop leading 0s
if (value.length == 1) {
return risDate;
}
//sometimes unknown parts of date are given as 0. Drop these and anything that follows
var i;
for (i=0; i<3; i++) {
if (!value[i] || !parseInt(value[i], 10)) {
break;
}
}
for (; i<3; i++) {
value[i] = undefined;
}
//adjust month (it's 0 based)
if (value[1]) {
value[1] = parseInt(value[1], 10);
if (value[1]) value[1]--;
}
return ZU.formatDate({
'year': value[0],
'month': value[1],
'day': value[2],
'part': value[3]
});
}
function completeItem(item) {
// if backup publication title exists but not proper, use backup
// (hack to get newspaper titles from EndNote)
if (item.backupPublicationTitle) {
if (!item.publicationTitle) {
item.publicationTitle = item.backupPublicationTitle;
}
item.backupPublicationTitle = undefined;
}
if (item.backupNumPages) {
if (!item.numPages) {
item.numPages = item.backupNumPages;
}
item.backupNumPages = undefined;
}
if (item.backupEndPage) {
if (!item.pages) {
item.pages = item.backupEndPage;
} else if (item.pages.indexOf('-') == -1) {
item.pages += '-' + item.backupEndPage;
} else if (!item.numPages) { //should we do this?
item.numPages = item.backupEndPage;
}
item.backupEndPage = undefined;
}
//see if we have a backup date
if (item.backupDate) {
if (!item[item.backupDate.field]) {
item[item.backupDate.field] = item.backupDate.value;
}
//in RW the freeform date field seems to often lack the year - take that from the year field.
else if (item[item.backupDate.field].search(/\d{4}/) == -1){
item[item.backupDate.field] = item[item.backupDate.field] + " " + item.backupDate.value;
}
item.backupDate = undefined;
}
// Clean up DOI
if (item.DOI) {
item.DOI = ZU.cleanDOI(item.DOI);
}
// hack for sites like Nature, which only use JA, journal abbreviation
if (item.journalAbbreviation && !item.publicationTitle){
item.publicationTitle = item.journalAbbreviation;
}
// Hack for Endnote exports missing full title
if (item.shortTitle && !item.title){
item.title = item.shortTitle;
}
//if we only have one tag, try splitting it by comma
//odds of this this backfiring are pretty low
if (item.tags.length == 1) {
item.tags = item.tags[0].split(/\s*(?:,\s*)+/);
if (!item.tags[0]) item.tags.shift();
if (item.tags.length && !item.tags[item.tags.length-1]) item.tags.pop();
}
//don't pass access date if this is called from (most likely) a web translator
if (Zotero.parentTranslator) {
item.accessDate = undefined;
}
//store unsupported and unknown fields in a single note
if (!Zotero.parentTranslator) {
var note = '';
for (var i=0, n=item.unsupportedFields.length; i<n; i++) {
note += item.unsupportedFields[i] + '<br/>';
}
for (var i=0, n=item.unknownFields.length; i<n; i++) {
note += item.unknownFields[i] + '<br/>';
}
if (note) {
note = "The following values have no corresponding Zotero field:<br/>" + note;
item.notes.push({note: note.trim(), tags: ['_RW import']});
}
}
item.unsupportedFields = undefined;
item.unknownFields = undefined;
item.complete();
}
//get the next RW entry that matches the RW format
//returns an array in the format [raw "line", tag, value]
//lines may be combined into one entry
var RW_format = /^([A-Z][A-Z0-9]) (?:(.*))?$/; //allow empty entries
function getLine() {
var entry, lastLineLength;
if (getLine.buffer) {
entry = getLine.buffer.match(RW_format); //this should always match
if (entry[2] === undefined) entry[2] = '';
lastLineLength = entry[2].length;
getLine.buffer = undefined;
}
var nextLine, temp;
while ((nextLine = Zotero.read()) !== false) {
temp = nextLine.match(RW_format);
if (temp && temp[2] === undefined) temp[2] = '';
//if we are already processing an entry, then this is the next entry
//store this line for later and return
if (temp && entry) {
getLine.buffer = temp[0];
return entry;
//otherwise this is a new entry
} else if (temp) {
entry = temp;
lastLineLength = entry[2].length;
//if this line didn't match, then we just attach it to the current value
//Try to figure out if this is supposed to be on a new line or not
} else if (entry) {
//new lines would probably only be meaningful in notes and abstracts
if (entry[1] == 'AB' || entry[1] == 'NO') {
//if previous line was short, this would probably be on a new line
//Might consider looking for periods and capital letters
if (lastLineLength < 60) {
nextLine = "\r\n" + nextLine;
}
}
//don't remove new lines from keywords
if (entry[1] == 'K1') {
nextLine = "\r\n" + nextLine;
}
//check if we need to add a space
if (entry[2].substr(entry[2].length-1) != ' ') {
nextLine = ' ' + nextLine;
}
entry[0] += nextLine;
entry[2] += nextLine;
}
}
return entry;
}
//creates a new item of specified type
function getNewItem(type) {
var item = new Zotero.Item(type);
item.unknownFields = [];
item.unsupportedFields = [];
return item;
}
function doImport(attachments){
var entry;
//skip to the first RT entry
do {
entry = getLine();
} while (entry && entry[1] != 'RT');
var item;
var i = -1; //item counter for attachments
while (entry) {
switch (entry[1]) {
//new item
case 'RT':
if (item) completeItem(item);
var type = exportedOptions.itemType || importTypeMap[entry[2].trim()];
if (!type) {
type = DEFAULT_IMPORT_TYPE;
Z.debug("Unknown RW item type: " + entry[2] + ". Defaulting to " + type);
}
var item = getNewItem(type);
//add attachments
i++;
if (attachments && attachments[i]) {
item.attachments = attachments[i];
}
break;
default:
processTag(item, entry);
}
entry = getLine();
}
if (item) completeItem(item);
}
/********************
* Export Functions *
********************/
//[Not sure if this is true for RW but doesn't hurt] RW files have a certain structure, which is often meaningful
//Records always start with RT. This is hardcoded below
var exportOrder = {
"__default": ["T1", "A1", "T2", "A2", "T3", "A3", "A4", "AB", "U1", "U2", "U3",
"U4", "U5", "U6", "CN", "PP", "FD", "YR", "DO", "SL", "LL", "ED", "VO", "IS", "SP", "OP,",
"JO", "LA", "CL", "PB", "SN", "ST", "UL", "RD", "LK", "NO", "K1"],
//in bill sponsor (A2) and cosponsor (A3) should be together and not split by legislativeBody (T3)
"bill": ["T1", "A1", "T2", "A2", "A3", "T3", "A4", "AB", "U1", "U2", "U3",
"U4", "U5", "U6", "CN", "PP", "FD", "YR", "DO", "SL", "LL", "ED", "VO", "IS", "SP", "OP",
"JO", "LA", "CL", "PB", "SN", "ST", "UL", "RD", "LK", "NO", "K1"]
};
var newLineChar = "\r\n"; //from spec
//set up export field mapping
var exportFields = new TagMapper([fieldMap]);
function addTag(tag, value) {
if (!(value instanceof Array)) value = [value];
for (var i=0, n=value.length; i<n; i++) {
if (value[i] === undefined) return;
//don't export empty strings
var v = (value[i] + '').trim();
if (!v) continue;
Zotero.write(tag + " " + v + newLineChar);
}
}
function doExport() {
var item, order, tag, fields, field, value;
while (item = Zotero.nextItem()) {
// can't store independent notes in RW
if (item.itemType == "note" || item.itemType == "attachment") {
continue;
}
// type
var type = exportTypeMap[item.itemType];
if (!type) {
type = DEFAULT_EXPORT_TYPE;
Z.debug("Unknown item type: " + item.itemType + ". Defaulting to " + type);
}
addTag("RT", type);
//before we begin, pre-sort attachments based on type
var attachments = {
PDF: [],
HTML: [],
other: []
};
for (var i=0, n=item.attachments.length; i<n; i++) {
switch (item.attachments[i].mimeType) {
case 'application/pdf':
attachments.PDF.push(item.attachments[i]);
break;
case 'text/html':
attachments.HTML.push(item.attachments[i]);
break;
default:
attachments.other.push(item.attachments[i]);
}
}
order = exportOrder[item.itemType] || exportOrder["__default"];
for (var i=0, n=order.length; i<n; i++) {
tag = order[i];
//find the appropriate field to export for this item type
field = exportFields.getFields(item.itemType, tag)[0];
//if we didn't get anything, we don't need to export this tag for this item type
if (!field) continue;
value = undefined;
//we can define fields that are nested (i.e. creators) using slashes
field = field.split('/');
//handle special cases based on item field
switch (field[0]) {
case "creators":
//according to spec, one author per line in the "Lastname, Firstname, Suffix" format
//Zotero does not store suffixes in a separate field
value = [];
var name;
for (var j=0, m=item.creators.length; j<m; j++) {
name = [];
if (item.creators[j].creatorType == field[1]) {
name.push(item.creators[j].lastName);
if (item.creators[j].firstName) name.push(item.creators[j].firstName);
value.push(name.join(', '));
}
}
if (!value.length) value = undefined;
break;
case "notes":
value = item.notes.map(function(n) { return n.note.replace(/(?:\r\n?|\n)/g, "\r\n"); });
break;
case "tags":
value = item.tags.map(function(t) { return t.tag; });
break;
case "attachments":
value = [];
var att = attachments[field[1]];
for (var j=0, m=att.length; j<m; j++) {
if (att[j].saveFile) { //local file
value.push(att[j].defaultPath);
att[j].saveFile(att[j].defaultPath);
} else { //link to remote file
value.push(att[j].url);
}
}
break;
case "pages":
if (tag == "SP" && item.pages) {
var m = item.pages.trim().match(/(.+?)[\u002D\u00AD\u2010-\u2015\u2212\u2E3A\u2E3B\s]+(.+)/);
if (m) {
addTag(tag, m[1]);
tag = "OP";
value = m[2];
}
}
break;
default:
value = item[field];
}
//handle special cases based on RW tag
switch (tag) {
case "YR":
var date = ZU.strToDate(item[field]);
if (date.year) {
value = ('000' + date.year).substr(-4); //since this is in export, this should not be a problem with MS JavaScript implementation of substr
} else {
value = item[field];
}
break;
case "RD":
var date = ZU.strToDate(item[field]);
if (date.year) {
date.year = ('000' + date.year).substr(-4);
date.month = (date.month || date.month===0 || date.month==="0")?('0' + (date.month+1)).substr(-2):'';
date.day = date.day?('0' + date.day).substr(-2):'';
if (!date.part) date.part = '';
value = date.year + '/' + date.month + '/' + date.day + '/' + date.part;
} else {
value = item[field];
}
break;
}
addTag(tag, value);
}
Zotero.write(newLineChar + newLineChar);
}
}
var exports = {
"doExport": doExport,
"doImport": doImport,
"options": exportedOptions
}
/** BEGIN TEST CASES **/
var testCases = [
{
"type": "import",
"input": "RT Book, Section\nSR Electronic(1)\nID 206\nA1 Stansfeld,Stephen\nA1 Fuhrer,Rebecca\nT1 Depression and coronary heart disease\nYR 2002\nVO 1\nIS 3\nSP 101\nOP 123\nK1 Etiology\nK1 Heart Disorders\nK1 Major Depression\nK1 Psychosocial Factors\nK1 Risk Factors\nK1 Anxiety\nK1 Prediction\nK1 coronary heart disease\nK1 psychosocial risk factors\nK1 Plants Red Blue\nAB (From the chapter) This chapter discusses the evidence for the proposition that depression is an aetiological factor in coronary heart disease, and 2 of the possible pathways by which this might occur: 1 in which social factors predict coronary heart disease, and depression and its associated psychophysiological changes are an intervening step; and the 2nd in which social factors predict coronary heart disease and depression, but depression is not on the pathway. This is followed by a discussion of anxiety as an aetiological factor in coronary heart disease. ( PsycINFO Database Record ( c) 2002 APA, all rights reserved)\nNO Williston, VT, US: BMJ Books. xi, 304 pp.; PO: Human; FE: References; TA: Psychology: Professional & Research; UD: 20020306; A1: 20020306\nA2 Gulford, C.T.\nT2 Stress and the heart: Psychosocial pathways to coronary heart disease\nPB BMJ Books\nPP Williston, VT, US\nSN 0727912771 (paperback)\nAD U London, Queen Mary's School of Medicine & Dentistry, London, England\nAN 2002-00714-006\nLA English\nCL 3200 Psychological & Physical Disorders\nOL English (30)",
"items": [
{
"itemType": "bookSection",
"title": "Depression and coronary heart disease",
"creators": [
{
"lastName": "Stansfeld",
"firstName": "Stephen",
"creatorType": "author"
},
{
"lastName": "Fuhrer",
"firstName": "Rebecca",
"creatorType": "author"
},
{
"lastName": "Gulford",