-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
BracketedPattern.java
1349 lines (1230 loc) · 58.5 KB
/
BracketedPattern.java
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
package org.jabref.logic.citationkeypattern;
import java.math.BigInteger;
import java.text.Normalizer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import java.util.Scanner;
import java.util.StringJoiner;
import java.util.StringTokenizer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.jabref.logic.cleanup.Formatter;
import org.jabref.logic.formatter.Formatters;
import org.jabref.logic.formatter.casechanger.Word;
import org.jabref.logic.layout.format.RemoveLatexCommandsFormatter;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.entry.Author;
import org.jabref.model.entry.AuthorList;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.Keyword;
import org.jabref.model.entry.KeywordList;
import org.jabref.model.entry.field.FieldFactory;
import org.jabref.model.entry.field.InternalField;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.strings.LatexToUnicodeAdapter;
import org.jabref.model.strings.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class provides methods to expand bracketed expressions, such as
* <code>[year]_[author]_[firstpage]</code>, using information from a provided BibEntry. The above-mentioned expression would yield
* <code>2017_Kitsune_123</code> when expanded using the BibTeX entry <code>@Article{ authors = {O. Kitsune}, year = {2017},
* pages={123-6}}</code>.
* <p>
* The embedding in JabRef is explained at <a href="https://docs.jabref.org/setup/citationkeypattern">Customize the citation key generator</a>.
* </p>
*/
public class BracketedPattern {
private static final Logger LOGGER = LoggerFactory.getLogger(BracketedPattern.class);
/**
* The maximum number of characters in the first author's last name.
*/
private static final int CHARS_OF_FIRST = 5;
/**
* The maximum number of name abbreviations that can be used. If there are more authors, {@code MAX_ALPHA_AUTHORS -
* 1} name abbreviations will be displayed, and a + sign will be appended at the end.
*/
private static final int MAX_ALPHA_AUTHORS = 4;
/**
* Matches everything that is not a unicode decimal digit.
*/
private static final Pattern NOT_DECIMAL_DIGIT = Pattern.compile("\\P{Nd}");
/**
* Matches everything that is not an uppercase ASCII letter. The intended use is to remove all lowercase letters
*/
private static final Pattern NOT_CAPITAL_CHARACTER = Pattern.compile("[^A-Z]");
/**
* Matches uppercase english letters between "({" and "})", which should be used to abbreviate the name of an institution
*/
private static final Pattern INLINE_ABBREVIATION = Pattern.compile("(?<=\\(\\{)[A-Z]+(?=}\\))");
/**
* Matches with "dep"/"dip", case-insensitive
*/
private static final Pattern DEPARTMENTS = Pattern.compile("^d[ei]p.*", Pattern.CASE_INSENSITIVE);
private static final Pattern WHITESPACE = Pattern.compile("\\p{javaWhitespace}");
private enum Institution {
SCHOOL,
DEPARTMENT,
UNIVERSITY,
TECHNOLOGY;
/**
* Matches "uni" followed by "v" or "b", at the start of a string or after a space, case insensitive
*/
private static final Pattern UNIVERSITIES = Pattern.compile("^uni(v|b|$).*", Pattern.CASE_INSENSITIVE);
/**
* Matches with "tech", case-insensitive
*/
private static final Pattern TECHNOLOGICAL_INSTITUTES = Pattern.compile("^tech.*", Pattern.CASE_INSENSITIVE);
/**
* Matches with "dep"/"dip"/"lab", case insensitive
*/
private static final Pattern DEPARTMENTS_OR_LABS = Pattern.compile("^(d[ei]p|lab).*", Pattern.CASE_INSENSITIVE);
/**
* Find which types of institutions have words in common with the given name parts.
*
* @param nameParts a list of words that constitute parts of an institution's name.
* @return set containing all types that matches
*/
public static EnumSet<Institution> findTypes(List<String> nameParts) {
EnumSet<Institution> parts = EnumSet.noneOf(Institution.class);
// Deciding about a part type…
for (String namePart : nameParts) {
if (UNIVERSITIES.matcher(namePart).matches()) {
parts.add(Institution.UNIVERSITY);
} else if (TECHNOLOGICAL_INSTITUTES.matcher(namePart).matches()) {
parts.add(Institution.TECHNOLOGY);
} else if (StandardField.SCHOOL.getName().equalsIgnoreCase(namePart)) {
parts.add(Institution.SCHOOL);
} else if (DEPARTMENTS_OR_LABS.matcher(namePart).matches()) {
parts.add(Institution.DEPARTMENT);
}
}
if (parts.contains(Institution.TECHNOLOGY)) {
parts.remove(Institution.UNIVERSITY); // technology institute isn't university :-)
}
return parts;
}
}
private final String pattern;
public BracketedPattern() {
this.pattern = null;
}
public BracketedPattern(String pattern) {
this.pattern = pattern;
}
@Override
public String toString() {
return this.getClass().getName() + "[pattern=" + pattern + "]";
}
public String expand(BibEntry bibentry) {
return expand(bibentry, null);
}
/**
* Expands the current pattern using the given bibentry and database. ";" is used as keyword delimiter.
*
* @param bibentry The bibentry to expand.
* @param database The database to use for string-lookups and cross-refs. May be null.
* @return The expanded pattern. The empty string is returned, if it could not be expanded.
*/
public String expand(BibEntry bibentry, BibDatabase database) {
Objects.requireNonNull(bibentry);
Character keywordDelimiter = ';';
return expand(bibentry, keywordDelimiter, database);
}
/**
* Expands the current pattern using the given bibentry, keyword delimiter, and database.
*
* @param bibentry The bibentry to expand.
* @param keywordDelimiter The keyword delimiter to use.
* @param database The database to use for string-lookups and cross-refs. May be null.
* @return The expanded pattern. The empty string is returned, if it could not be expanded.
*/
public String expand(BibEntry bibentry, Character keywordDelimiter, BibDatabase database) {
Objects.requireNonNull(bibentry);
return expandBrackets(this.pattern, keywordDelimiter, bibentry, database);
}
/**
* Expands a pattern
*
* @param pattern The pattern to expand
* @param keywordDelimiter The keyword delimiter to use
* @param entry The bibentry to use for expansion
* @param database The database for field resolving. May be null.
* @return The expanded pattern. Not null.
*/
public static String expandBrackets(String pattern, Character keywordDelimiter, BibEntry entry, BibDatabase database) {
Objects.requireNonNull(pattern);
Objects.requireNonNull(entry);
return expandBrackets(pattern, expandBracketContent(keywordDelimiter, entry, database));
}
/**
* Utility method creating a function taking the string representation of the content of a bracketed expression and
* expanding it.
*
* @param keywordDelimiter The keyword delimiter to use
* @param entry The {@link BibEntry} to use for expansion
* @param database The {@link BibDatabase} for field resolving. May be null.
* @return a function accepting a bracketed expression and returning the result of expanding it
*/
public static Function<String, String> expandBracketContent(Character keywordDelimiter, BibEntry entry, BibDatabase database) {
return (String bracket) -> {
String expandedPattern;
List<String> fieldParts = parseFieldAndModifiers(bracket);
// check whether there is a modifier on the end such as
// ":lower":
expandedPattern = getFieldValue(entry, fieldParts.getFirst(), keywordDelimiter, database);
if (fieldParts.size() > 1) {
// apply modifiers:
expandedPattern = applyModifiers(expandedPattern, fieldParts, 1, expandBracketContent(keywordDelimiter, entry, database));
}
return expandedPattern;
};
}
/**
* Expands a pattern.
*
* @param pattern The pattern to expand
* @param bracketContentHandler A function taking the string representation of the content of a bracketed pattern
* and expanding it
* @return The expanded pattern. Not null.
*/
public static String expandBrackets(String pattern, Function<String, String> bracketContentHandler) {
Objects.requireNonNull(pattern);
StringBuilder expandedPattern = new StringBuilder();
StringTokenizer parsedPattern = new StringTokenizer(pattern, "\\[]\"", true);
while (parsedPattern.hasMoreTokens()) {
String token = parsedPattern.nextToken();
switch (token) {
case "\"" -> appendQuote(expandedPattern, parsedPattern);
case "[" -> {
String fieldMarker = contentBetweenBrackets(parsedPattern, pattern);
expandedPattern.append(bracketContentHandler.apply(fieldMarker));
}
case "\\" -> {
if (parsedPattern.hasMoreTokens()) {
expandedPattern.append(parsedPattern.nextToken());
} else {
LOGGER.warn("Found a \"\\\" that is not part of an escape sequence");
}
}
default -> expandedPattern.append(token);
}
}
return expandedPattern.toString();
}
/**
* Returns the content enclosed between brackets, including enclosed quotes, and excluding the paired enclosing brackets.
* There may be brackets in it.
* Intended to be used by {@link BracketedPattern#expandBrackets(String, Character, BibEntry, BibDatabase)} when a [
* is encountered, and has been consumed, by the {@code StringTokenizer}.
*
* @param pattern pattern used by {@code expandBrackets}, used for logging
* @param tokenizer the tokenizer producing the tokens
* @return the content enclosed by brackets
*/
private static String contentBetweenBrackets(StringTokenizer tokenizer, final String pattern) {
StringBuilder bracketContent = new StringBuilder();
boolean foundClosingBracket = false;
int subBrackets = 0;
// make sure to read until the paired ']'
while (tokenizer.hasMoreTokens() && !foundClosingBracket) {
String token = tokenizer.nextToken();
// If the beginning of a quote is found, append the content
switch (token) {
case "\"" -> appendQuote(bracketContent, tokenizer);
case "]" -> {
if (subBrackets == 0) {
foundClosingBracket = true;
} else {
subBrackets--;
bracketContent.append(token);
}
}
case "[" -> {
subBrackets++;
bracketContent.append(token);
}
default -> bracketContent.append(token);
}
}
if (!foundClosingBracket) {
LOGGER.warn("Missing closing bracket ']' in '{}'", pattern);
} else if (bracketContent.length() == 0) {
LOGGER.warn("Found empty brackets \"[]\" in '{}'", pattern);
}
return bracketContent.toString();
}
/**
* Appends the content between, and including, two \" to the provided <code>StringBuilder</code>. Intended to be
* used by {@link BracketedPattern#expandBrackets(String, Character, BibEntry, BibDatabase)} when a \" is
* encountered by the StringTokenizer.
*
* @param stringBuilder the <code>StringBuilder</code> to which tokens will be appended
* @param tokenizer the tokenizer producing the tokens
*/
private static void appendQuote(StringBuilder stringBuilder, StringTokenizer tokenizer) {
stringBuilder.append("\""); // We know that the previous token was \"
String token = "";
while (tokenizer.hasMoreTokens() && !"\"".equals(token)) {
token = tokenizer.nextToken();
stringBuilder.append(token);
}
}
/**
* Evaluates the given pattern to the given bibentry and database
*
* @param entry The entry to get the field value from
* @param pattern A pattern string (such as auth, pureauth, authorLast)
* @param keywordDelimiter The de
* @param database The database to use for field resolving. May be null.
* @return String containing the evaluation result. Empty string if the pattern cannot be resolved.
*/
public static String getFieldValue(BibEntry entry, String pattern, Character keywordDelimiter, BibDatabase database) {
try {
if (pattern.startsWith("auth") || pattern.startsWith("pureauth")) {
// result the author
String unparsedAuthors = entry.getResolvedFieldOrAlias(StandardField.AUTHOR, database).orElse("");
if (pattern.startsWith("pure")) {
// "pure" is used in the context of authors to resolve to authors only and not fallback to editors
// The other functionality of the pattern "ForeIni", ... is the same
// Thus, remove the "pure" prefix so the remaining code in this section functions correctly
//
pattern = pattern.substring(4);
} else if (unparsedAuthors.isEmpty()) {
// special feature: A pattern starting with "auth" falls back to the editor
unparsedAuthors = entry.getResolvedFieldOrAlias(StandardField.EDITOR, database).orElse("");
}
AuthorList authorList = createAuthorList(unparsedAuthors);
// Gather all author-related checks, so we don't
// have to check all the time.
switch (pattern) {
case "auth":
return firstAuthor(authorList);
case "authForeIni":
return firstAuthorForenameInitials(authorList);
case "authFirstFull":
return firstAuthorVonAndLast(authorList);
case "authors":
return allAuthors(authorList);
case "authorsAlpha":
return authorsAlpha(authorList);
case "authorLast":
return lastAuthor(authorList);
case "authorLastForeIni":
return lastAuthorForenameInitials(authorList);
case "authorIni":
return oneAuthorPlusInitials(authorList);
case "auth.auth.ea":
return authAuthEa(authorList);
case "auth.etal":
return authEtal(authorList, ".", ".etal");
case "authEtAl":
return authEtal(authorList, "", "EtAl");
case "authshort":
return authShort(authorList);
}
if (pattern.matches("authIni[\\d]+")) {
int num = Integer.parseInt(pattern.substring(7));
return authIniN(authorList, num);
} else if (pattern.matches("auth[\\d]+_[\\d]+")) {
String[] nums = pattern.substring(4).split("_");
return authNofMth(authorList, Integer.parseInt(nums[0]),
Integer.parseInt(nums[1]));
} else if (pattern.matches("auth\\d+")) {
// authN. First N chars of the first author's last name.
int num = Integer.parseInt(pattern.substring(4));
return authN(authorList, num);
} else if (pattern.matches("authors\\d+")) {
return nAuthors(authorList, Integer.parseInt(pattern.substring(7)));
} else {
// This "auth" business was a dead end, so just
// use it literally:
return entry.getResolvedFieldOrAlias(FieldFactory.parseField(pattern), database).orElse("");
}
} else if (pattern.startsWith("ed")) {
// Gather all markers starting with "ed" here, so we
// don't have to check all the time.
String unparsedEditors = entry.getResolvedFieldOrAlias(StandardField.EDITOR, database).orElse("");
AuthorList editorList = createAuthorList(unparsedEditors);
switch (pattern) {
case "edtr":
return firstAuthor(editorList);
case "edtrForeIni":
return firstAuthorForenameInitials(editorList);
case "editors":
return allAuthors(editorList);
case "editorLast":
return lastAuthor(editorList); // Last author's last name
case "editorLastForeIni":
return lastAuthorForenameInitials(editorList);
case "editorIni":
return oneAuthorPlusInitials(editorList);
case "edtr.edtr.ea":
return authAuthEa(editorList);
case "edtrshort":
return authShort(editorList);
}
if (pattern.matches("edtrIni[\\d]+")) {
int num = Integer.parseInt(pattern.substring(7));
return authIniN(editorList, num);
} else if (pattern.matches("edtr[\\d]+_[\\d]+")) {
String[] nums = pattern.substring(4).split("_");
return authNofMth(editorList,
Integer.parseInt(nums[0]),
Integer.parseInt(nums[1]));
} else if (pattern.matches("edtr\\d+")) {
String fa = firstAuthor(editorList);
int num = Integer.parseInt(pattern.substring(4));
if (num > fa.length()) {
num = fa.length();
}
return fa.substring(0, num);
} else {
// This "ed" business was a dead end, so just
// use it literally:
return entry.getResolvedFieldOrAlias(FieldFactory.parseField(pattern), database).orElse("");
}
} else if ("firstpage".equals(pattern)) {
return firstPage(entry.getResolvedFieldOrAlias(StandardField.PAGES, database).orElse(""));
} else if ("pageprefix".equals(pattern)) {
return pagePrefix(entry.getResolvedFieldOrAlias(StandardField.PAGES, database).orElse(""));
} else if ("lastpage".equals(pattern)) {
return lastPage(entry.getResolvedFieldOrAlias(StandardField.PAGES, database).orElse(""));
} else if ("title".equals(pattern)) {
return camelizeSignificantWordsInTitle(entry.getResolvedFieldOrAlias(StandardField.TITLE, database).orElse(""));
} else if ("fulltitle".equals(pattern)) {
return entry.getResolvedFieldOrAlias(StandardField.TITLE, database).orElse("");
} else if ("shorttitle".equals(pattern)) {
return getTitleWords(3,
removeSmallWords(entry.getResolvedFieldOrAlias(StandardField.TITLE, database).orElse("")));
} else if ("shorttitleINI".equals(pattern)) {
return keepLettersAndDigitsOnly(
applyModifiers(getTitleWordsWithSpaces(3, entry.getResolvedFieldOrAlias(StandardField.TITLE, database).orElse("")),
Collections.singletonList("abbr"), 0, Function.identity()));
} else if ("veryshorttitle".equals(pattern)) {
return getTitleWords(1,
removeSmallWords(entry.getResolvedFieldOrAlias(StandardField.TITLE, database).orElse("")));
} else if (pattern.matches("camel[\\d]+")) {
int num = Integer.parseInt(pattern.substring(5));
return getCamelizedTitle_N(entry.getResolvedFieldOrAlias(StandardField.TITLE, database).orElse(""), num);
} else if ("camel".equals(pattern)) {
return getCamelizedTitle(entry.getResolvedFieldOrAlias(StandardField.TITLE, database).orElse(""));
} else if ("shortyear".equals(pattern)) {
String yearString = entry.getResolvedFieldOrAlias(StandardField.YEAR, database).orElse("");
if (yearString.isEmpty()) {
return yearString;
// In press/in preparation/submitted
} else if (yearString.startsWith("in") || yearString.startsWith("sub")) {
return "IP";
} else if (yearString.length() > 2) {
return yearString.substring(yearString.length() - 2);
} else {
return yearString;
}
} else if ("entrytype".equals(pattern)) {
return entry.getResolvedFieldOrAlias(InternalField.TYPE_HEADER, database).orElse("");
} else if (pattern.matches("keyword\\d+")) {
// according to LabelPattern.php, it returns keyword number n
int num = Integer.parseInt(pattern.substring(7));
KeywordList separatedKeywords = entry.getResolvedKeywords(keywordDelimiter, database);
if (separatedKeywords.size() < num) {
// not enough keywords
return "";
} else {
// num counts from 1 to n, but index in arrayList count from 0 to n-1
return separatedKeywords.get(num - 1).toString();
}
} else if (pattern.matches("keywords\\d*")) {
// return all keywords, not separated
int num;
if (pattern.length() > 8) {
num = Integer.parseInt(pattern.substring(8));
} else {
num = Integer.MAX_VALUE;
}
KeywordList separatedKeywords = entry.getResolvedKeywords(keywordDelimiter, database);
StringBuilder sb = new StringBuilder();
int i = 0;
for (Keyword keyword : separatedKeywords) {
// remove all spaces
sb.append(keyword.toString().replaceAll("\\s+", ""));
i++;
if (i >= num) {
break;
}
}
return sb.toString();
} else {
// we haven't seen any special demands
return entry.getResolvedFieldOrAlias(FieldFactory.parseField(pattern), database).orElse("");
}
} catch (NullPointerException ex) {
LOGGER.debug("Problem making expanding bracketed expression", ex);
return "";
}
}
/**
* Parses the provided string to an {@link AuthorList}, which are then formatted by {@link LatexToUnicodeAdapter}.
* Afterward, any institutions are formatted into an institution key.
*
* @param unparsedAuthors a string representation of authors or editors
* @return an {@link AuthorList} consisting of authors and institution keys with resolved latex.
*/
private static AuthorList createAuthorList(String unparsedAuthors) {
return AuthorList.parse(unparsedAuthors).getAuthors().stream()
.map(author -> {
// If the author is an institution, use an institution key instead of the full name
String lastName = author.getFamilyName()
.map(lastPart -> isInstitution(author) ?
generateInstitutionKey(lastPart) :
LatexToUnicodeAdapter.format(lastPart))
.orElse(null);
return new Author(
author.getGivenName().map(LatexToUnicodeAdapter::format).orElse(null),
author.getGivenNameAbbreviated().map(LatexToUnicodeAdapter::format).orElse(null),
author.getNamePrefix().map(LatexToUnicodeAdapter::format).orElse(null),
lastName,
author.getNameSuffix().map(LatexToUnicodeAdapter::format).orElse(null));
})
.collect(AuthorList.collect());
}
/**
* Checks if an author is an institution which can get a citation key from {@link #generateInstitutionKey(String)}.
*
* @param author the checked author
* @return true if only the last name is present and it contains at least one whitespace character.
*/
private static boolean isInstitution(Author author) {
return author.getGivenName().isEmpty() && author.getGivenNameAbbreviated().isEmpty() && author.getNameSuffix().isEmpty()
&& author.getNamePrefix().isEmpty() && author.getFamilyName().isPresent()
&& WHITESPACE.matcher(author.getFamilyName().get()).find();
}
/**
* Applies modifiers to a label generated based on a field marker.
*
* @param label The generated label.
* @param parts String array containing the modifiers.
* @param offset The number of initial items in the modifiers array to skip.
* @param expandBracketContent a function to expand the content in the parentheses.
* @return The modified label.
*/
static String applyModifiers(final String label, final List<String> parts, final int offset, Function<String, String> expandBracketContent) {
String resultingLabel = label;
for (int j = offset; j < parts.size(); j++) {
String modifier = parts.get(j);
if ("abbr".equals(modifier)) {
// Abbreviate - that is,
StringBuilder abbreviateSB = new StringBuilder();
String[] words = resultingLabel.replaceAll("[\\{\\}']", "")
.split("[\\(\\) \r\n\"]");
for (String word : words) {
if (!word.isEmpty()) {
abbreviateSB.append(word.charAt(0));
}
}
resultingLabel = abbreviateSB.toString();
} else {
Optional<Formatter> formatter = Formatters.getFormatterForModifier(modifier);
if (formatter.isPresent()) {
resultingLabel = formatter.get().format(resultingLabel);
} else if (!modifier.isEmpty() && (modifier.length() >= 2) && (modifier.charAt(0) == '(') && modifier.endsWith(")")) {
// Alternate text modifier in parentheses. Should be inserted if the label is empty
if (label.isEmpty() && (modifier.length() > 2)) {
resultingLabel = expandBrackets(modifier.substring(1, modifier.length() - 1), expandBracketContent);
}
} else {
LOGGER.warn("Key generator warning: unknown modifier '{}'.", modifier);
}
}
}
return resultingLabel;
}
/**
* Determines "number" words out of the "title" field in the given BibTeX entry
*/
public static String getTitleWords(int number, String title) {
return getTitleWordsWithSpaces(number, title);
}
/**
* Removes any '-', unnecessary whitespace and latex commands formatting
*/
private static String formatTitle(String title) {
String ss = new RemoveLatexCommandsFormatter().format(title);
StringBuilder stringBuilder = new StringBuilder();
StringBuilder current;
int piv = 0;
while (piv < ss.length()) {
current = new StringBuilder();
// Get the next word:
while ((piv < ss.length()) && !Character.isWhitespace(ss.charAt(piv))
&& (ss.charAt(piv) != '-')) {
current.append(ss.charAt(piv));
piv++;
}
piv++;
// Check if it is ok:
String word = current.toString().trim();
if (word.isEmpty()) {
continue;
}
// If we get here, the word was accepted.
if (stringBuilder.length() > 0) {
stringBuilder.append(' ');
}
stringBuilder.append(word);
}
return stringBuilder.toString();
}
/**
* Capitalises and concatenates the words out of the "title" field in the given BibTeX entry
*/
public static String getCamelizedTitle(String title) {
return keepLettersAndDigitsOnly(camelizeTitle(title));
}
private static String camelizeTitle(String title) {
StringBuilder stringBuilder = new StringBuilder();
String formattedTitle = formatTitle(title);
try (Scanner titleScanner = new Scanner(formattedTitle)) {
while (titleScanner.hasNext()) {
String word = titleScanner.next();
// Camelize the word
word = word.substring(0, 1).toUpperCase(Locale.ROOT) + word.substring(1);
if (stringBuilder.length() > 0) {
stringBuilder.append(' ');
}
stringBuilder.append(word);
}
}
return stringBuilder.toString();
}
/**
* Capitalises and concatenates the words out of the "title" field in the given BibTeX entry, to a maximum of N words.
*/
public static String getCamelizedTitle_N(String title, int number) {
return keepLettersAndDigitsOnly(camelizeTitle_N(title, number));
}
private static String camelizeTitle_N(String title, int number) {
StringBuilder stringBuilder = new StringBuilder();
String formattedTitle = formatTitle(title);
try (Scanner titleScanner = new Scanner(formattedTitle)) {
while (titleScanner.hasNext()) {
String word = titleScanner.next();
// Camelize the word
word = word.substring(0, 1).toUpperCase(Locale.ROOT) + word.substring(1);
if (stringBuilder.length() > 0) {
stringBuilder.append(' ');
}
stringBuilder.append(word);
}
}
String camelString = stringBuilder.toString();
return getSomeWords(number, camelString);
}
/**
* Capitalises the significant words of the "title" field in the given BibTeX entry
*/
public static String camelizeSignificantWordsInTitle(String title) {
StringJoiner stringJoiner = new StringJoiner(" ");
String formattedTitle = formatTitle(title);
try (Scanner titleScanner = new Scanner(formattedTitle)) {
while (titleScanner.hasNext()) {
String word = titleScanner.next();
// Camelize the word if it is significant
boolean camelize = !Word.SMALLER_WORDS.contains(word.toLowerCase(Locale.ROOT));
// We want to capitalize significant words and the first word of the title
if (camelize || (stringJoiner.length() == 0)) {
word = word.substring(0, 1).toUpperCase(Locale.ROOT) + word.substring(1);
} else {
word = word.substring(0, 1).toLowerCase(Locale.ROOT) + word.substring(1);
}
stringJoiner.add(word);
}
}
return stringJoiner.toString();
}
public static String removeSmallWords(String title) {
String formattedTitle = formatTitle(title);
try (Scanner titleScanner = new Scanner(formattedTitle)) {
return titleScanner.tokens()
.filter(Predicate.not(
Word::isSmallerWord))
.collect(Collectors.joining(" "));
}
}
private static String getTitleWordsWithSpaces(int number, String title) {
String formattedTitle = formatTitle(title);
return getSomeWords(number, formattedTitle);
}
private static String getSomeWords(int number, String string) {
try (Scanner titleScanner = new Scanner(string)) {
return titleScanner.tokens()
.limit(number)
.collect(Collectors.joining(" "));
}
}
private static String keepLettersAndDigitsOnly(String in) {
return in.codePoints()
.filter(Character::isLetterOrDigit)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
}
/**
* Gets the last name of the first author/editor
*
* @param authorList an {@link AuthorList}
* @return the surname of an author/editor or the von part if no lastname is prsent or "" if no author was found or both firstname+lastname are empty
* This method is guaranteed to never return null.
*/
private static String firstAuthor(AuthorList authorList) {
return authorList.getAuthors().stream()
.findFirst()
.flatMap(author -> author.getFamilyName().isPresent() ? author.getFamilyName() : author.getNamePrefix())
.orElse("");
}
/**
* Gets the first name initials of the first author/editor
*
* @param authorList an {@link AuthorList}
* @return the first name initial of an author/editor or "" if no author was found This method is guaranteed to
* never return null.
*/
private static String firstAuthorForenameInitials(AuthorList authorList) {
return authorList.getAuthors().stream()
.findFirst()
.flatMap(Author::getGivenNameAbbreviated)
.map(s -> s.substring(0, 1))
.orElse("");
}
/**
* Gets the von part and the last name of the first author/editor. No spaces are returned.
*
* @param authorList an {@link AuthorList}
* @return the von part and surname of an author/editor or "" if no author was found. This method is guaranteed to
* never return null.
*/
private static String firstAuthorVonAndLast(AuthorList authorList) {
return authorList.isEmpty() ? "" :
authorList.getAuthor(0).getNamePrefixAndFamilyName().replace(" ", "");
}
/**
* Gets the last name of the last author/editor
*
* @param authorList an {@link AuthorList}
* @return the surname of an author/editor
*/
private static String lastAuthor(AuthorList authorList) {
if (authorList.isEmpty()) {
return "";
}
return authorList.getAuthors().get(authorList.getNumberOfAuthors() - 1).getFamilyName().orElse("");
}
/**
* Gets the forename initials of the last author/editor
*
* @param authorList an {@link AuthorList}
* @return the forename initial of an author/editor or "" if no author was found This method is guaranteed to never
* return null.
*/
private static String lastAuthorForenameInitials(AuthorList authorList) {
if (authorList.isEmpty()) {
return "";
}
return authorList.getAuthor(authorList.getNumberOfAuthors() - 1).getGivenNameAbbreviated().map(s -> s.substring(0, 1))
.orElse("");
}
/**
* Gets the last name of all authors/editors.
* Pattern <code>[authors]</code>.
* <p>
* <code>and others</code> is converted to <code>EtAl</code>
* </p>
*
* @param authorList an {@link AuthorList}
* @return the surname of all authors/editors
*/
static String allAuthors(AuthorList authorList) {
return joinAuthorsOnLastName(authorList, authorList.getNumberOfAuthors(), "", "EtAl");
}
/**
* Returns the authors according to the BibTeX-alpha-Style
*
* @param authorList an {@link AuthorList}
* @return the initials of all authors' names
*/
static String authorsAlpha(AuthorList authorList) {
StringBuilder alphaStyle = new StringBuilder();
int maxAuthors;
final boolean maxAuthorsExceeded;
if (authorList.getNumberOfAuthors() <= MAX_ALPHA_AUTHORS) {
maxAuthors = authorList.getNumberOfAuthors();
maxAuthorsExceeded = false;
} else {
maxAuthors = MAX_ALPHA_AUTHORS - 1;
maxAuthorsExceeded = true;
}
if (authorList.getNumberOfAuthors() == 1) {
String[] firstAuthor = authorList.getAuthor(0).getNamePrefixAndFamilyName()
.replaceAll("\\s+", " ").trim().split(" ");
// take first letter of any "prefixes" (e.g. van der Aalst -> vd)
for (int j = 0; j < (firstAuthor.length - 1); j++) {
alphaStyle.append(firstAuthor[j], 0, 1);
}
// append last part of last name completely
alphaStyle.append(firstAuthor[firstAuthor.length - 1], 0,
Math.min(3, firstAuthor[firstAuthor.length - 1].length()));
} else {
boolean andOthersPresent = authorList.getAuthor(maxAuthors - 1).equals(Author.OTHERS);
if (andOthersPresent) {
maxAuthors--;
}
List<String> vonAndLastNames = authorList.getAuthors().stream()
.limit(maxAuthors)
.map(Author::getNamePrefixAndFamilyName)
.collect(Collectors.toList());
for (String vonAndLast : vonAndLastNames) {
// replace all whitespaces by " "
// split the lastname at " "
String[] nameParts = vonAndLast.replaceAll("\\s+", " ").trim().split(" ");
for (String part : nameParts) {
// use first character of each part of lastname
alphaStyle.append(part, 0, 1);
}
}
if (andOthersPresent || maxAuthorsExceeded) {
alphaStyle.append("+");
}
}
return alphaStyle.toString();
}
/**
* Creates a string with all last names separated by a `delimiter`. If the number of authors are larger than
* `maxAuthors`, replace all excess authors with `suffix`.
*
* @param authorList the list of authors
* @param maxAuthors the maximum number of authors in the string
* @param delimiter delimiter separating the last names of the authors
* @param suffix to replace excess authors with. Also used to replace <code>and others</code>.
* @return a string consisting of authors' last names separated by a `delimiter` and with any authors excess of
* `maxAuthors` replaced with `suffix`
*/
private static String joinAuthorsOnLastName(AuthorList authorList, int maxAuthors, String delimiter, final String suffix) {
final String finalSuffix = authorList.getNumberOfAuthors() > maxAuthors ? suffix : "";
return authorList.getAuthors().stream()
.map(author -> {
if (author.equals(Author.OTHERS)) {
if (suffix.startsWith(delimiter)) {
return Optional.of(suffix.substring(delimiter.length()));
} else {
return Optional.of(suffix);
}
} else {
return author.getFamilyName();
}
})
.flatMap(Optional::stream)
.limit(maxAuthors)
.collect(Collectors.joining(delimiter, "", finalSuffix));
}
/**
* Gets the surnames of the first N authors and appends EtAl if there are more than N authors
*
* @param authorList an {@link AuthorList}
* @param n the number of desired authors
* @return Gets the surnames of the first N authors and appends EtAl if there are more than N authors
*/
private static String nAuthors(AuthorList authorList, int n) {
return joinAuthorsOnLastName(authorList, n, "", "EtAl");
}
/**
* Gets the first part of the last name of the first author/editor, and appends the last name initial of the
* remaining authors/editors. Maximum 5 characters
*
* @param authorList an <{@link AuthorList}
* @return the surname of all authors/editors
*/
static String oneAuthorPlusInitials(AuthorList authorList) {
if (authorList.isEmpty()) {
return "";
}
StringBuilder authorSB = new StringBuilder();
// authNofMth start index at 1 instead of 0
authorSB.append(authNofMth(authorList, CHARS_OF_FIRST, 1));
for (int i = 2; i <= authorList.getNumberOfAuthors(); i++) {
authorSB.append(authNofMth(authorList, 1, i));
}
return authorSB.toString();
}
static String authAuthEa(AuthorList authorList) {
return joinAuthorsOnLastName(authorList, 2, ".", ".ea");
}
/**
* auth.etal, authEtAl, ... format
*/
static String authEtal(AuthorList authorList, String delim, String append) {
if (authorList.isEmpty()) {
return "";
}
if ((authorList.getNumberOfAuthors() <= 2)
&& ((authorList.getNumberOfAuthors() == 1) || !authorList.getAuthor(1).equals(Author.OTHERS))) {
// in case 1 or two authors, just name them
// exception: If the second author is "and others", then do the appendix handling (in the other branch)
return joinAuthorsOnLastName(authorList, 2, delim, "");
} else {
return authorList.getAuthor(0).getFamilyName().orElse("") + append;
}
}
/**
* The first N characters of the Mth author's or editor's last name. M starts counting from 1.
* In case the Mth author is {@link Author#OTHERS}, <code>+</code> is returned.
*/
private static String authNofMth(AuthorList authorList, int n, int m) {
// have m counting from 0
int mminusone = m - 1;
if ((authorList.getNumberOfAuthors() <= mminusone) || (n < 0) || (mminusone < 0)) {
return "";
}
Author lastAuthor = authorList.getAuthor(mminusone);
if (lastAuthor.equals(Author.OTHERS)) {
return "+";
}
String lastName = lastAuthor.getFamilyName()
.map(CitationKeyGenerator::removeDefaultUnwantedCharacters).orElse("");
return lastName.length() > n ? lastName.substring(0, n) : lastName;
}
/**
* First N chars of the first author's last name.
*/