diff --git a/CHANGELOG.md b/CHANGELOG.md index 6d4fb5ff2867..2d79466e7624 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,6 +33,7 @@ Note that this project **does not** adhere to [Semantic Versioning](https://semv - We fixed an issue where back navigation selected a deleted entry instead of skipping it. [#17353](https://github.com/JabRef/jabref/issues/17353) - We fixed the linked file tooltip showing the old file name after renaming or moving the file. [#9277](https://github.com/JabRef/jabref/issues/9277) - We fixed an issue where citationcount, day, and dayfiled columns were sorted alphabetically instead of numerically. [#17459](https://github.com/JabRef/jabref/issues/17459) +- We fixed MODS contributor name and role handling, including names containing “and”, organizations, suffixes, and patent assignees. [#17898](https://github.com/JabRef/jabref/issues/17898) ## [6.0-beta.1] - 2026-09-21 diff --git a/_typos.toml b/_typos.toml new file mode 100644 index 000000000000..0ab59b1594d1 --- /dev/null +++ b/_typos.toml @@ -0,0 +1,156 @@ +# Spell checking with https://github.com/crate-ci/typos +[files] +extend-exclude = [ + # Submodules and data files + "jablib/src/main/abbrv.jabref.org/", + "jablib/src/main/resources/csl-styles/", + "jablib/src/main/resources/csl-locales/", + "jabgui/src/main/themes.jabref.org/", + "jablib/src/main/resources/ltwa/", + "jablib/src/main/resources/icore/", + "*.terms", + "reachability-metadata.json", + # Translations are maintained at Crowdin + "JabRef_*.properties", + "**/src/test/resources/", + "*.bib", + # Third-party files + "*.bst", + "*.xsl", + "harvard.readme", + "jablib/src/main/resources/xslt/mathml_latex/README", + "jablib/src/main/resources/resource/layout/din1505/README.txt", + "org.citationstyles.*.txt", + # Keys defined by Eclipse + "config/*Code Style*", + # Diagrams (SVG generated from BPMN) + "docs/images/", +] + +[default.extend-words] +# BibTeX field name +annote = "annote" +# "and" separators in BibTeX author lists +ands = "ands" +# .sav backup file extension +sav = "sav" +# LaTeX environments +multline = "multline" +# Spelling used by external APIs (LibreOffice UNO, JAX-RS, xmpbox) +removeable = "removeable" +writeable = "writeable" +prefered = "prefered" +unparseable = "unparseable" +# Real words +afterwords = "afterwords" +bigrading = "bigrading" +# Ordinals, abbreviations, field codes and variable names +nd = "nd" +edn = "edn" +thes = "thes" +ths = "ths" +rin = "rin" +ein = "ein" +ot = "ot" +pn = "pn" +thm = "thm" +fre = "fre" +curren = "curren" +ket = "ket" +mis = "mis" +ser = "ser" +serie = "serie" +ofr = "ofr" +ois = "ois" +# Names in test data +aache = "aache" +aks = "aks" +alue = "alue" +ba = "ba" +bui = "bui" +malins = "malins" +ned = "ned" +noe = "noe" +ome = "ome" +ove = "ove" +rech = "rech" +thi = "thi" +tung = "tung" +vas = "vas" +wich = "wich" +wil = "wil" +# Word fragments in test data +allo = "allo" +caf = "caf" +ded = "ded" +fo = "fo" +hel = "hel" +ine = "ine" +lene = "lene" +lik = "lik" +lso = "lso" +mananger = "mananger" +metada = "metada" +nto = "nto" +ower = "ower" +pagent = "pagent" +perfor = "perfor" +plas = "plas" +potatoe = "potatoe" +pplication = "pplication" +prining = "prining" +quantit = "quantit" +rela = "rela" +sur = "sur" +tme = "tme" +ue = "ue" +urrent = "urrent" +wrapp = "wrapp" +# Non-English test data +abstrakt = "abstrakt" +alle = "alle" +als = "als" +apostroph = "apostroph" +archiv = "archiv" +commentaires = "commentaires" +commun = "commun" +dito = "dito" +exemple = "exemple" +funktional = "funktional" +ges = "ges" +informe = "informe" +ist = "ist" +mesure = "mesure" +nam = "nam" +oder = "oder" +philosophiae = "philosophiae" +plattform = "plattform" +problemas = "problemas" +"prozeß" = "prozeß" +publikation = "publikation" +sais = "sais" +sie = "sie" +varios = "varios" +varius = "varius" +vor = "vor" +januar = "januar" +februar = "februar" +juni = "juni" +juli = "juli" +oktober = "oktober" +dezember = "dezember" +titel = "titel" + +[default] +extend-ignore-re = [ + # Ignore lines that end with `// spellchecker:disable-line`. + "(?Rm)^.*(#|//)\\s*spellchecker:disable-line$", + # Ignore the line after `// spellchecker:ignore-next-line`. + "(#|//)\\s*spellchecker:ignore-next-line\\n.*", + # Ignore blocks between `// spellchecker:off` and `// spellchecker:on`. + "(?s)(#|//)\\s*spellchecker:off.*?\\n\\s*(#|//)\\s*spellchecker:on", +] + +[default.extend-identifiers] +# Former command line parameter, mentioned in CHANGELOG.md +embeddBibfileInPdf = "embeddBibfileInPdf" diff --git a/docs/requirements/export.md b/docs/requirements/export.md new file mode 100644 index 000000000000..1b0643284d50 --- /dev/null +++ b/docs/requirements/export.md @@ -0,0 +1,81 @@ +--- +parent: Requirements +--- + +# Export + +## Export BIBFRAME 2.0 RDF/XML +`req~export.bibframe.rdfxml~1` + +JabRef exports each entry as a linked BIBFRAME 2.0 Work and Instance in striped RDF/XML. Resource identifiers are deterministic for unchanged bibliographic content, unique for duplicate entries within one file, and independent of citation keys. + +See [ADR 0076](../decisions/0076-support-bibframe-alongside-marc21.md) for the decision to support BIBFRAME alongside MARC 21. + +Needs: impl, utest + +## User can export a Markdown publication list +`feat~export.markdown-publications~1` + +The "Markdown publications" export format produces a publication list for use on Markdown websites. +Entries include available authors, title, publication venue, year, and links. + +See [issue 12729](https://github.com/JabRef/jabref/issues/12729). + +Needs: impl, utest + +## Markdown publications must appear newest first +`req~export.markdown-publications.date-order~1` + +Publication dates determine descending order using year, month, and day where available. +Entries without a usable publication date appear last. +The recent publications section contains at most five entries. + +Needs: impl, utest + +## Markdown publication sections must reflect Export subgroups +`req~export.markdown-publications.groups~1` + +Subgroups beneath the group named "Export" produce sections containing matching exported entries. +A subgroup description supplies its heading, with the group name as the fallback. +Empty sections are omitted unless they contain a nonempty descendant section. + +Needs: impl, utest + +## Markdown full publication list must group entries by entry type +`req~export.markdown-publications.type-headings~1` + +The "All publications" section shows a heading for each entry type, one level below the section heading. +Within a type, entries keep the newest-first order. +The recent publications section and the Export subgroup sections remain flat lists, because the Export subgroups already define the grouping. +The type heading is defined in the layout using grouped output (`\begingroup{entrytype}`), see [issue 12729](https://github.com/JabRef/jabref/issues/12729). + +Needs: impl, utest + +## Markdown publication links must support portable output +`req~export.markdown-publications.links~1` + +Titles use a DOI link when available, otherwise a URL. +PDF links use online locations or local paths relative to the exported Markdown file. +Local attachments that cannot be resolved or represented relatively are omitted. + +Needs: impl, utest + +## MODS exports must preserve supported contributor names +`req~export.mods.names~1` + +MODS exports preserve supported contributor names without incorrectly splitting names containing "and". +Brace-protected organizations are exported as corporate names, personal suffixes as `termsOfAddress`, and the BibTeX `and others` placeholder is omitted. +Exports preserve initial punctuation and attached prefixes. Explicit initials supply the given name when it is unavailable, and an extended name with no standard parts is exported as literal name text. +See the [MODS name guidelines](https://www.loc.gov/standards/mods/userguide/name.html) and the [MODS 3.6 to MARC 21 mapping](https://www.loc.gov/standards/mods/v3/mods2marc-mapping-3-6.html). + +Each supported contributor field is exported with its corresponding [MARC relator code](https://www.loc.gov/marc/relators/relaterm.html). +Re-importing the export restores each supported contributor role to its corresponding field. +Composer (`cmp`), illustrator (`ill`), and thesis advisor (`ths`) use custom fields. Generic contributors (`ctb`) and names with only unmapped roles use the `contributor` field. +Patent assignees and patent holders share the `pth` relator and re-import as patent holders. + +See [issue 17898](https://github.com/JabRef/jabref/issues/17898). + +Needs: impl, utest + + + diff --git a/jablib/src/main/java/org/jabref/logic/exporter/ModsExporter.java b/jablib/src/main/java/org/jabref/logic/exporter/ModsExporter.java index 7e6c0c1f2d81..62a0e3bc51e4 100644 --- a/jablib/src/main/java/org/jabref/logic/exporter/ModsExporter.java +++ b/jablib/src/main/java/org/jabref/logic/exporter/ModsExporter.java @@ -12,6 +12,7 @@ import java.util.List; import java.util.Map; import java.util.TreeMap; +import java.util.regex.Pattern; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; @@ -24,12 +25,16 @@ import javax.xml.transform.stream.StreamSource; import org.jabref.logic.util.StandardFileType; +import org.jabref.logic.util.strings.StringUtil; import org.jabref.model.database.BibDatabaseContext; +import org.jabref.model.entry.Author; +import org.jabref.model.entry.AuthorList; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.field.UnknownField; import org.jabref.model.entry.types.EntryType; +import org.jabref.model.entry.types.IEEETranEntryType; import org.jspecify.annotations.NonNull; import org.slf4j.Logger; @@ -42,6 +47,25 @@ class ModsExporter extends Exporter { private static final String MINUS = "-"; private static final String DOUBLE_MINUS = "--"; private static final String MODS_SCHEMA_LOCATION = "http://www.loc.gov/standards/mods/v3/mods-3-6.xsd"; + private static final Pattern REPEATED_HORIZONTAL_WHITESPACE = Pattern.compile("\\h{2,}"); + private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+"); + // https://www.loc.gov/marc/relators/relaterm.html + private static final Map PERSON_NAME_ROLES = Map.ofEntries( + Map.entry(StandardField.AFTERWORD, "waw"), + Map.entry(StandardField.ANNOTATOR, "ann"), + Map.entry(StandardField.ASSIGNEE, "asg"), + Map.entry(StandardField.AUTHOR, "aut"), + Map.entry(StandardField.COMMENTATOR, "cwt"), + Map.entry(new UnknownField("composer"), "cmp"), + Map.entry(new UnknownField("contributor"), "ctb"), + Map.entry(StandardField.EDITOR, "edt"), + Map.entry(StandardField.FOREWORD, "wfw"), + Map.entry(StandardField.HOLDER, "pth"), + Map.entry(new UnknownField("illustrator"), "ill"), + Map.entry(StandardField.INTRODUCTION, "win"), + Map.entry(new UnknownField("thesisadvisor"), "ths"), + Map.entry(StandardField.TRANSLATOR, "trl") + ); private static final Logger LOGGER = LoggerFactory.getLogger(ModsExporter.class); @@ -82,8 +106,12 @@ public void export(@NonNull final BibDatabaseContext databaseContext, Field field = entry.getKey(); String value = entry.getValue(); - if (StandardField.AUTHOR == field) { - handleAuthors(writer, value); + if (PERSON_NAME_ROLES.containsKey(field)) { + // MARC asg denotes a printing or publishing license assignee. + String role = field == StandardField.ASSIGNEE && bibEntry.getType() == IEEETranEntryType.Patent + ? "pth" + : PERSON_NAME_ROLES.get(field); + handleNames(writer, value, role); } else if (new UnknownField("affiliation").equals(field)) { addAffiliation(writer, value); } else if (StandardField.ABSTRACT == field) { @@ -359,44 +387,65 @@ private void addKeyWords(XMLStreamWriter writer, String value) throws XMLStreamE } } - private void handleAuthors(XMLStreamWriter writer, String value) throws XMLStreamException { - String[] authors = value.split("and"); - for (String author : authors) { + // [impl->req~export.mods.names~1] + private void handleNames(XMLStreamWriter writer, String value, String role) throws XMLStreamException { + // BibTeX names use "and" as a separator. The shared parser also accepts repeated spaces in pasted lists. + String names = REPEATED_HORIZONTAL_WHITESPACE.matcher(value).replaceAll(" "); + for (Author author : AuthorList.parse(names).getNamedAuthors()) { writer.writeStartElement("mods", "name", MODS_NAMESPACE_URI); - writer.writeAttribute("type", "personal"); - - if (author.contains(",")) { - // if author contains "," then this indicates that the author has a forename and family name - int commaIndex = author.indexOf(','); - String familyName = author.substring(0, commaIndex); - writer.writeStartElement("mods", "namePart", MODS_NAMESPACE_URI); - writer.writeAttribute("type", "family"); - writer.writeCharacters(familyName); - writer.writeEndElement(); - - // now take care of the forenames - String forename = author.substring(commaIndex + 1); - String[] forenames = forename.split(" "); - for (String given : forenames) { - if (!given.isEmpty()) { - writer.writeStartElement("mods", "namePart", MODS_NAMESPACE_URI); - writer.writeAttribute("type", "given"); - writer.writeCharacters(given); - writer.writeEndElement(); - } - } - writer.writeEndElement(); + String familyName = author.getNamePrefixAndFamilyNameForDisplay(); + String givenName = author.getGivenNameWithOriginalPunctuation() + .or(() -> author.getExplicitGivenNameInitials().filter(initials -> !initials.isEmpty())) + .orElse(""); + String suffix = author.getNameSuffix().orElse(""); + // https://www.loc.gov/standards/mods/userguide/name.html + if (StringUtil.isInCurlyBrackets(familyName) && givenName.isEmpty() && suffix.isEmpty()) { + writer.writeAttribute("type", "corporate"); + writeNamePart(writer, "", Author.FORMATTER.format(familyName)); + } else if (familyName.isEmpty() && givenName.isEmpty() && suffix.isEmpty()) { + // A custom extended name may have no standard BibLaTeX name parts. + writeNamePart(writer, "", author.getAsBibtex()); } else { - // no "," indicates that there should only be a family name - writer.writeStartElement("mods", "namePart", MODS_NAMESPACE_URI); - writer.writeAttribute("type", "family"); - writer.writeCharacters(author); - writer.writeEndElement(); - writer.writeEndElement(); + writer.writeAttribute("type", "personal"); + writePersonalNameParts(writer, familyName, givenName, suffix); } + + writer.writeStartElement("mods", "role", MODS_NAMESPACE_URI); + writer.writeStartElement("mods", "roleTerm", MODS_NAMESPACE_URI); + writer.writeAttribute("type", "code"); + writer.writeAttribute("authority", "marcrelator"); + writer.writeCharacters(role); + writer.writeEndElement(); + writer.writeEndElement(); + writer.writeEndElement(); } } + private void writePersonalNameParts(XMLStreamWriter writer, String familyName, String givenName, String suffix) throws XMLStreamException { + if (!familyName.isEmpty()) { + writeNamePart(writer, "family", familyName); + } + if (!givenName.isEmpty()) { + for (String given : WHITESPACE_PATTERN.split(givenName)) { + writeNamePart(writer, "given", given); + } + } + if (!suffix.isEmpty()) { + // termsOfAddress maps to MARC 100/700 $c. + // https://www.loc.gov/standards/mods/v3/mods2marc-mapping-3-6.html + writeNamePart(writer, "termsOfAddress", suffix); + } + } + + private void writeNamePart(XMLStreamWriter writer, String type, String name) throws XMLStreamException { + writer.writeStartElement("mods", "namePart", MODS_NAMESPACE_URI); + if (!type.isEmpty()) { + writer.writeAttribute("type", type); + } + writer.writeCharacters(name); + writer.writeEndElement(); + } + private void addIdentifier(XMLStreamWriter writer, Field field, String value) throws XMLStreamException { if (new UnknownField("citekey").equals(field)) { diff --git a/jablib/src/main/java/org/jabref/logic/importer/fileformat/ModsImporter.java b/jablib/src/main/java/org/jabref/logic/importer/fileformat/ModsImporter.java index 70798aedb877..d11956d85852 100644 --- a/jablib/src/main/java/org/jabref/logic/importer/fileformat/ModsImporter.java +++ b/jablib/src/main/java/org/jabref/logic/importer/fileformat/ModsImporter.java @@ -8,12 +8,15 @@ import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; +import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.Set; +import java.util.StringJoiner; import java.util.regex.Pattern; +import java.util.stream.Collectors; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; @@ -30,6 +33,7 @@ import org.jabref.logic.importer.fileformat.mods.RecordInfo; import org.jabref.logic.l10n.Localization; import org.jabref.logic.util.StandardFileType; +import org.jabref.logic.util.strings.StringUtil; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.Date; import org.jabref.model.entry.field.Field; @@ -106,11 +110,9 @@ private void parseModsCollection(List bibItems, XMLStreamReader reader } private void parseModsGroup(Map fields, XMLStreamReader reader, BibEntry entry) throws XMLStreamException { - // These elements (subject, keywords and authors) can appear more than once, - // so they are collected in lists List notes = new ArrayList<>(); List keywords = new ArrayList<>(); - List authors = new ArrayList<>(); + Map> contributors = new HashMap<>(); TypeHints typeHints = new TypeHints(); while (reader.hasNext()) { @@ -163,7 +165,7 @@ private void parseModsGroup(Map fields, XMLStreamReader reader, B case "originInfo" -> parseOriginInfo(reader, fields, typeHints, false); case "name" -> - parseName(reader, fields, authors); + parseName(reader, fields, contributors); case "relatedItem" -> parseRelatedItem(reader, fields, typeHints); } @@ -176,7 +178,7 @@ private void parseModsGroup(Map fields, XMLStreamReader reader, B putIfListIsNotEmpty(fields, notes, StandardField.NOTE, ", "); putIfListIsNotEmpty(fields, keywords, StandardField.KEYWORDS, this.keywordSeparator); - putIfListIsNotEmpty(fields, authors, StandardField.AUTHOR, " and "); + contributors.forEach((field, names) -> putIfListIsNotEmpty(fields, names, field, " and ")); inferEntryType(typeHints) .ifPresent(entry::setType); @@ -296,8 +298,12 @@ private void handleDetail(XMLStreamReader reader, Map fields) thr } } - private void parseName(XMLStreamReader reader, Map fields, List authors) throws XMLStreamException { + // [impl->req~export.mods.names~1] + private void parseName(XMLStreamReader reader, Map fields, Map> contributors) throws XMLStreamException { + boolean corporate = "corporate".equals(reader.getAttributeValue(null, "type")); List names = new ArrayList<>(); + Set contributorFields = new LinkedHashSet<>(); + boolean hasRoleTerm = false; while (reader.hasNext()) { reader.next(); @@ -314,6 +320,12 @@ private void parseName(XMLStreamReader reader, Map fields, List fields, List contributorNames = new ArrayList<>(); + if (corporate) { + // MODS uses successive name parts for organizational subdivisions. + // https://www.loc.gov/standards/mods/userguide/name.html + String organization = names.stream() + .filter(name -> StringUtil.isBlank(name.type())) + .map(Name::value) + .map(String::strip) + .filter(value -> !value.isEmpty()) + .collect(Collectors.joining(". ")); + if (!organization.isEmpty()) { + contributorNames.add("{" + organization + "}"); + } + } else { + handleAuthorsInNamePart(names, contributorNames); + } + for (Field field : contributorFields) { + contributors.computeIfAbsent(field, _ -> new ArrayList<>()).addAll(contributorNames); + } + } + + private Optional contributorField(String role) { + return switch (role) { + case "ann", + "annotator" -> + Optional.of(StandardField.ANNOTATOR); + case "asg", + "assignee" -> + Optional.of(StandardField.ASSIGNEE); + case "aut", + "author", + "cre", + "creator" -> + Optional.of(StandardField.AUTHOR); + case "cmp", + "composer" -> + Optional.of(new UnknownField("composer")); + case "ctb", + "contributor" -> + Optional.of(new UnknownField("contributor")); + case "cwt", + "commentator for written text" -> + Optional.of(StandardField.COMMENTATOR); + case "edt", + "editor" -> + Optional.of(StandardField.EDITOR); + case "ill", + "illustrator" -> + Optional.of(new UnknownField("illustrator")); + case "pth", + "patent holder" -> + Optional.of(StandardField.HOLDER); + case "ths", + "thesis advisor" -> + Optional.of(new UnknownField("thesisadvisor")); + case "trl", + "translator" -> + Optional.of(StandardField.TRANSLATOR); + case "waw", + "writer of afterword" -> + Optional.of(StandardField.AFTERWORD); + case "wfw", + "writer of foreword" -> + Optional.of(StandardField.FOREWORD); + case "win", + "writer of introduction" -> + Optional.of(StandardField.INTRODUCTION); + default -> + Optional.empty(); + }; } private void parseOriginInfo(XMLStreamReader reader, Map fields, TypeHints typeHints, boolean hostOriginInfo) throws XMLStreamException { @@ -656,9 +740,9 @@ private void putIfListIsNotEmpty(Map fields, List list, F } private void handleAuthorsInNamePart(List names, List authors) { - List foreName = new ArrayList<>(); + List givenNames = new ArrayList<>(); + List termsOfAddress = new ArrayList<>(); String familyName = ""; - String author = ""; for (Name name : names) { String type = name.type(); // date, family, given, termsOfAddress @@ -668,31 +752,41 @@ private void handleAuthorsInNamePart(List names, List authors) { namePartValue = namePartValue.replaceAll(",$", ""); authors.add(namePartValue); } else if ("family".equals(type) && (name.value() != null)) { - // family should come first, so if family appears we can set the author then comes before - // we have to check if forename and family name are not empty in case it's the first author - if (!foreName.isEmpty() && !familyName.isEmpty()) { - // now set and add the old author - author = familyName + ", " + String.join(" ", foreName); - authors.add(author); - // remove old forenames - foreName.clear(); - } else if (foreName.isEmpty() && !familyName.isEmpty()) { - authors.add(familyName); + if (!familyName.isEmpty()) { + addPersonalName(authors, familyName, termsOfAddress, givenNames); + termsOfAddress.clear(); + givenNames.clear(); } familyName = name.value(); } else if ("given".equals(type) && (name.value() != null)) { - foreName.add(name.value()); + givenNames.add(name.value()); + } else if ("termsOfAddress".equals(type) && (name.value() != null)) { + termsOfAddress.add(name.value()); } } - // last author is not added, so do it here - if (!foreName.isEmpty() && !familyName.isEmpty()) { - author = familyName + ", " + String.join(" ", foreName); - authors.add(author.trim()); - foreName.clear(); - } else if (foreName.isEmpty() && !familyName.isEmpty()) { + if (!familyName.isEmpty()) { + addPersonalName(authors, familyName, termsOfAddress, givenNames); + } + } + + private void addPersonalName(List authors, String familyName, List termsOfAddress, List givenNames) { + String givenName = String.join(" ", givenNames); + if (givenName.isBlank()) { + // BibTeX removes trailing name commas, which would make the suffix a given name. + // See section 387 of the BibTeX source. + // https://mirror.las.iastate.edu/tex-archive/info/knuth-pdf/bibtex/bibtex.pdf authors.add(familyName.trim()); + return; + } + + StringJoiner name = new StringJoiner(", "); + name.add(familyName); + if (!termsOfAddress.isEmpty()) { + name.add(String.join(" ", termsOfAddress)); } + name.add(givenName); + authors.add(name.toString().trim()); } private void putIfValueNotNull(Map fields, Field field, String value) { diff --git a/jablib/src/main/java/org/jabref/model/entry/Author.java b/jablib/src/main/java/org/jabref/model/entry/Author.java index bf854445579e..a7b4228f50b4 100644 --- a/jablib/src/main/java/org/jabref/model/entry/Author.java +++ b/jablib/src/main/java/org/jabref/model/entry/Author.java @@ -21,7 +21,17 @@ public class Author { public static final RemoveWordEnclosingAndOuterEnclosingBracesFormatter FORMATTER = new RemoveWordEnclosingAndOuterEnclosingBracesFormatter(); +<<<<<<< HEAD private final String givenName; +======= + private static final Set EXTENDED_NAME_KEYS = Set.of( + "family", "family-i", "given", "given-i", "prefix", "prefix-i", "suffix", "suffix-i"); + + private static final RemoveEnclosingBracesFormatter ENCLOSING_BRACES_FORMATTER = new RemoveEnclosingBracesFormatter(); + + private final @Nullable String givenName; + private final @Nullable String givenNameWithOriginalPunctuation; +>>>>>>> b5a8d8f4a4 (Fix author and editor name export in MODS format (#17936)) private final String givenNameAbbreviated; private final String namePrefix; private final String familyName; @@ -40,11 +50,8 @@ public class Author { public Author(String givenName, String givenNameAbbreviated, String namePrefix, String familyName, String nameSuffix) { boolean keepBracesAtLastPart = StringUtil.isBlank(givenName) && StringUtil.isBlank(givenNameAbbreviated) && StringUtil.isBlank(namePrefix) && !StringUtil.isBlank(familyName) && StringUtil.isBlank(nameSuffix); - if (!StringUtil.isBlank(givenName)) { - this.givenName = addDotIfAbbreviation(FORMATTER.format(givenName)); - } else { - this.givenName = null; - } + this.givenNameWithOriginalPunctuation = StringUtil.isBlank(givenName) ? null : FORMATTER.format(givenName); + this.givenName = addDotIfAbbreviation(givenNameWithOriginalPunctuation); if (!StringUtil.isBlank(givenNameAbbreviated)) { this.givenNameAbbreviated = FORMATTER.format(givenNameAbbreviated); } else { @@ -73,7 +80,29 @@ public Author(String givenName, String givenNameAbbreviated, String namePrefix, } } +<<<<<<< HEAD public static String addDotIfAbbreviation(String name) { +======= + private Author(Author author, Optional listUsePrefix) { + this.givenName = author.givenName; + this.givenNameWithOriginalPunctuation = author.givenNameWithOriginalPunctuation; + this.givenNameAbbreviated = author.givenNameAbbreviated; + this.namePrefix = author.namePrefix; + this.familyName = author.familyName; + this.nameSuffix = author.nameSuffix; + this.extendedNameParts = author.extendedNameParts; + this.extendedNameSource = author.extendedNameSource; + this.nameUsePrefix = author.nameUsePrefix; + this.listUsePrefix = listUsePrefix; + } + + /// Applies the list option as a default while preserving the name's original storage representation. + public Author withListUsePrefix(Optional usePrefix) { + return equals(OTHERS) ? this : new Author(this, usePrefix); + } + + public static @Nullable String addDotIfAbbreviation(@Nullable String name) { +>>>>>>> b5a8d8f4a4 (Fix author and editor name export in MODS format (#17936)) if ((name == null) || name.isEmpty()) { return name; } @@ -189,6 +218,11 @@ public Optional getGivenName() { return Optional.ofNullable(givenName); } + /// Returns the given name before normalizing punctuation and spacing between initials. + public @NonNull Optional getGivenNameWithOriginalPunctuation() { + return Optional.ofNullable(givenNameWithOriginalPunctuation); + } + /// Returns the abbreviated first name of the author stored in this object ("F."). /// /// @return abbreviated first name of the author (may consist of several tokens) @@ -228,6 +262,44 @@ public String getNamePrefixAndFamilyName() { } } +<<<<<<< HEAD +======= + /// Returns the family-name label for display. Explicit `useprefix=false` excludes the prefix; + /// absent or invalid options retain the existing prefix-inclusive display convention. + // [impl->req~ui.names.display-extended~1] + public String getFamilyNameForDisplay() { + if (!getUsePrefix().orElse(true)) { + return getFamilyName().orElse(""); + } + return getNamePrefixAndFamilyNameForDisplay(); + } + + /// Returns the family name with its prefix, respecting punctuation that attaches the two parts. + public @NonNull String getNamePrefixAndFamilyNameForDisplay() { + if (extendedNameParts.isEmpty()) { + return getNamePrefixAndFamilyName(); + } + String family = getFamilyName().orElse(""); + return getNamePrefix() + .map(prefix -> prefix + ((family.isEmpty() || prefix.endsWith("'") || prefix.endsWith("’")) ? "" : " ") + family) + .orElse(family); + } + + private Optional getGivenNameForDisplay(boolean abbreviated) { + if (!abbreviated) { + return getGivenName(); + } + // A latexFree Author keeps the original metadata for serialization; decode only the display value. + return getExplicitGivenNameInitials() + .map(initials -> latexFreeAuthor == this ? LatexToUnicodeAdapter.format(initials) : initials) + .or(this::getGivenNameAbbreviated); + } + + private static String joinDisplayParts(String... parts) { + return Stream.of(parts).filter(part -> !part.isEmpty()).collect(Collectors.joining(" ")); + } + +>>>>>>> b5a8d8f4a4 (Fix author and editor name export in MODS format (#17936)) /// Returns the author's name in form 'von Last, Jr., First' with the first name full or abbreviated depending on parameter. /// /// @param abbr `true` - abbreviate first name, `false` - do not abbreviate @@ -248,6 +320,18 @@ public String getFamilyGiven(boolean abbr) { /// @param abbr `true` - abbreviate first name, `false` - do not abbreviate /// @return 'First von Last, Jr.' (if `abbr==false`) or 'F. von Last, Jr.' (if `abbr==true`) public String getGivenFamily(boolean abbr) { +<<<<<<< HEAD +======= + if (!extendedNameParts.isEmpty()) { + StringJoiner result = new StringJoiner(", "); + String name = joinDisplayParts(getGivenNameForDisplay(abbr).orElse(""), getNamePrefixAndFamilyNameForDisplay()); + if (!name.isEmpty()) { + result.add(name); + } + getNameSuffix().ifPresent(result::add); + return result.toString(); + } +>>>>>>> b5a8d8f4a4 (Fix author and editor name export in MODS format (#17936)) StringBuilder res = new StringBuilder(); if (abbr) { getGivenNameAbbreviated().map(firstA -> firstA + ' ').ifPresent(res::append); @@ -274,7 +358,15 @@ public String toString() { /// @return "Last, Jr, F." as described above or "" if all these parts are empty. public String getNameForAlphabetization() { StringBuilder res = new StringBuilder(); +<<<<<<< HEAD getFamilyName().ifPresent(res::append); +======= + if (getUsePrefix().orElse(false)) { + res.append(getNamePrefixAndFamilyNameForDisplay()); + } else { + getFamilyName().ifPresent(res::append); + } +>>>>>>> b5a8d8f4a4 (Fix author and editor name export in MODS format (#17936)) getNameSuffix().ifPresent(jr -> res.append(", ").append(jr)); getGivenNameAbbreviated().ifPresent(firstA -> res.append(", ").append(firstA)); while ((!res.isEmpty()) && (res.charAt(0) == '{')) { @@ -286,7 +378,7 @@ public String getNameForAlphabetization() { /// Returns a LaTeX-free version of this `Author`. public Author latexFree() { if (latexFreeAuthor == null) { - String first = getGivenName().map(LatexToUnicodeAdapter::format).orElse(null); + String first = getGivenNameWithOriginalPunctuation().map(LatexToUnicodeAdapter::format).orElse(null); String givenNameAbbreviated = getGivenNameAbbreviated().map(LatexToUnicodeAdapter::format).orElse(null); String von = getNamePrefix().map(LatexToUnicodeAdapter::format).orElse(null); String last = getFamilyName().map(LatexToUnicodeAdapter::format).orElse(null); diff --git a/jablib/src/test/java/org/jabref/logic/exporter/ModsExportFormatTest.java b/jablib/src/test/java/org/jabref/logic/exporter/ModsExportFormatTest.java index 6dae5ed27760..32acb4edec6d 100644 --- a/jablib/src/test/java/org/jabref/logic/exporter/ModsExportFormatTest.java +++ b/jablib/src/test/java/org/jabref/logic/exporter/ModsExportFormatTest.java @@ -1,15 +1,25 @@ package org.jabref.logic.exporter; import java.io.IOException; -import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +import javax.xml.parsers.DocumentBuilderFactory; import org.jabref.logic.importer.ImportFormatPreferences; -import org.jabref.logic.importer.fileformat.BibtexImporter; +import org.jabref.logic.importer.fileformat.ModsImporter; import org.jabref.model.database.BibDatabaseContext; -import org.jabref.model.util.DummyFileUpdateMonitor; +import org.jabref.model.entry.BibEntry; +import org.jabref.model.entry.field.Field; +import org.jabref.model.entry.field.StandardField; +import org.jabref.model.entry.field.UnknownField; +import org.jabref.model.entry.types.IEEETranEntryType; +import org.jabref.model.entry.types.StandardEntryType; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -17,7 +27,11 @@ import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; import org.junit.jupiter.api.parallel.ResourceLock; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Answers; +import org.w3c.dom.Element; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; @@ -28,13 +42,14 @@ class ModsExportFormatTest { private ModsExporter modsExportFormat; private BibDatabaseContext databaseContext; + private DocumentBuilderFactory documentBuilderFactory; @BeforeEach - void setUp() throws URISyntaxException { + void setUp() { databaseContext = new BibDatabaseContext(); modsExportFormat = new ModsExporter(); - new BibtexImporter(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS), new DummyFileUpdateMonitor()); - Path.of(ModsExportFormatTest.class.getResource("ModsExportFormatTestAllFields.bib").toURI()); + documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); } @Test @@ -44,4 +59,257 @@ final void exportForNoEntriesWritesNothing(@TempDir Path tempFile) throws IOExce modsExportFormat.export(databaseContext, tempFile, List.of()); assertEquals(List.of(), Files.readAllLines(file)); } + + static Stream authorAndEditorNames() { + return Stream.of( + Arguments.of( + "Sandra Sanders and John Smith", + "Sam Flanders and Alice Johnson", + List.of( + "Sanders|Sandra|aut", + "Smith|John|aut", + "Flanders|Sam|edt", + "Johnson|Alice|edt" + ) + ), + Arguments.of( + "Doe, John and Smith, Sandra and Sanders, Bill", + "Flanders, Sam", + List.of( + "Doe|John|aut", + "Smith|Sandra|aut", + "Sanders|Bill|aut", + "Flanders|Sam|edt" + ) + ), + Arguments.of( + "Sandra Sanders", + "Sam Flanders and Alice Johnson", + List.of( + "Sanders|Sandra|aut", + "Flanders|Sam|edt", + "Johnson|Alice|edt" + ) + ), + Arguments.of( + "Sandra Sanders\nJohn Smith", + "Sam Flanders", + List.of( + "Sanders|Sandra|aut", + "Smith|John|aut", + "Flanders|Sam|edt" + ) + ) + ); + } + + // [utest->req~export.mods.names~1] + @ParameterizedTest + @MethodSource("authorAndEditorNames") + void exportNamesWithAuthorAndEditorRoles( + String authors, + String editors, + List expected, + @TempDir Path tempDir) throws Exception { + BibEntry entry = new BibEntry(StandardEntryType.Book) + .withField(StandardField.TITLE, "Sands") + .withField(StandardField.AUTHOR, authors) + .withField(StandardField.EDITOR, editors) + .withField(StandardField.DATE, "2026") + .withField(StandardField.PUBLISHER, "Sanders Academic"); + + Path file = tempDir.resolve("names.xml"); + modsExportFormat.export(databaseContext, file, List.of(entry)); + + var document = documentBuilderFactory.newDocumentBuilder().parse(file.toFile()); + String namespace = "http://www.loc.gov/mods/v3"; + var names = document.getElementsByTagNameNS(namespace, "name"); + + assertEquals(expected.size(), names.getLength()); + + for (int i = 0; i < names.getLength(); i++) { + Element name = (Element) names.item(i); + var parts = name.getElementsByTagNameNS(namespace, "namePart"); + + assertEquals(2, parts.getLength()); + + Element family = (Element) parts.item(0); + Element given = (Element) parts.item(1); + Element role = (Element) name.getElementsByTagNameNS(namespace, "roleTerm").item(0); + + assertEquals("personal", name.getAttribute("type")); + assertEquals("family", family.getAttribute("type")); + assertEquals("given", given.getAttribute("type")); + assertEquals("code", role.getAttribute("type")); + assertEquals("marcrelator", role.getAttribute("authority")); + + assertEquals(expected.get(i), + family.getTextContent() + "|" + given.getTextContent() + "|" + role.getTextContent()); + } + } + + // [utest->req~export.mods.names~1] + @Test + void roundTripKeepsAuthorsAndEditorsInTheirFields(@TempDir Path tempDir) throws Exception { + Map contributors = Map.of( + StandardField.AUTHOR, "Sanders, Sandra and Smith, Jr., John and {Research and Development}", + StandardField.EDITOR, "Flanders, Sam and Johnson, Alice", + StandardField.TRANSLATOR, "Doe, Jane" + ); + BibEntry entry = new BibEntry(StandardEntryType.Book); + contributors.forEach(entry::withField); + entry.withField(StandardField.AUTHOR, contributors.get(StandardField.AUTHOR) + " and others") + .withField(StandardField.EDITOR, contributors.get(StandardField.EDITOR) + " and others"); + Path file = tempDir.resolve("contributors.xml"); + modsExportFormat.export(databaseContext, file, List.of(entry)); + + var document = documentBuilderFactory.newDocumentBuilder().parse(file.toFile()); + String namespace = "http://www.loc.gov/mods/v3"; + var names = document.getElementsByTagNameNS(namespace, "name"); + assertEquals(6, names.getLength()); + + Element personalName = (Element) names.item(1); + Element suffix = (Element) personalName.getElementsByTagNameNS(namespace, "namePart").item(2); + assertEquals("termsOfAddress", suffix.getAttribute("type")); + assertEquals("Jr.", suffix.getTextContent()); + + Element corporateName = (Element) names.item(2); + assertEquals("corporate", corporateName.getAttribute("type")); + var corporateParts = corporateName.getElementsByTagNameNS(namespace, "namePart"); + assertEquals(1, corporateParts.getLength()); + Element namePart = (Element) corporateParts.item(0); + assertEquals("", namePart.getAttribute("type")); + assertEquals("Research and Development", namePart.getTextContent()); + + ModsImporter importer = new ModsImporter(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS)); + try (var reader = Files.newBufferedReader(file)) { + BibEntry imported = importer.importDatabase(reader).getDatabase().getEntries().getFirst(); + contributors.forEach((field, expectedNames) -> assertEquals(Optional.of(expectedNames), imported.getField(field))); + } + } + + // [utest->req~export.mods.names~1] + @Test + void exportsPatentAssigneeAsPatentHolder(@TempDir Path tempDir) throws Exception { + BibEntry entry = new BibEntry(IEEETranEntryType.Patent) + .withField(StandardField.ASSIGNEE, "{Example Research}"); + Path file = tempDir.resolve("patent.xml"); + modsExportFormat.export(databaseContext, file, List.of(entry)); + + var document = documentBuilderFactory.newDocumentBuilder().parse(file.toFile()); + var roles = document.getElementsByTagNameNS("http://www.loc.gov/mods/v3", "roleTerm"); + + assertEquals(1, roles.getLength()); + assertEquals("pth", roles.item(0).getTextContent()); + + ModsImporter importer = new ModsImporter(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS)); + try (var reader = Files.newBufferedReader(file)) { + BibEntry imported = importer.importDatabase(reader).getDatabase().getEntries().getFirst(); + assertEquals(Optional.of("{Example Research}"), imported.getField(StandardField.HOLDER)); + } + } + + static Stream contributorRoles() { + return Stream.of( + Arguments.of(StandardField.AFTERWORD, "waw"), + Arguments.of(StandardField.ANNOTATOR, "ann"), + Arguments.of(StandardField.ASSIGNEE, "asg"), + Arguments.of(StandardField.AUTHOR, "aut"), + Arguments.of(StandardField.COMMENTATOR, "cwt"), + Arguments.of(new UnknownField("composer"), "cmp"), + Arguments.of(new UnknownField("contributor"), "ctb"), + Arguments.of(StandardField.EDITOR, "edt"), + Arguments.of(StandardField.FOREWORD, "wfw"), + Arguments.of(StandardField.HOLDER, "pth"), + Arguments.of(new UnknownField("illustrator"), "ill"), + Arguments.of(StandardField.INTRODUCTION, "win"), + Arguments.of(new UnknownField("thesisadvisor"), "ths"), + Arguments.of(StandardField.TRANSLATOR, "trl") + ); + } + + // [utest->req~export.mods.names~1] + @ParameterizedTest + @MethodSource("contributorRoles") + void exportNamesWithContributorRoles( + Field field, + String expectedRole, + @TempDir Path tempDir) throws Exception { + BibEntry entry = new BibEntry(StandardEntryType.Book) + .withField(StandardField.TITLE, "Sands") + .withField(field, "Sandra Sanders") + .withField(StandardField.DATE, "2026") + .withField(StandardField.PUBLISHER, "Sanders Academic"); + + Path file = tempDir.resolve("names.xml"); + modsExportFormat.export(databaseContext, file, List.of(entry)); + + var document = documentBuilderFactory.newDocumentBuilder().parse(file.toFile()); + String namespace = "http://www.loc.gov/mods/v3"; + var names = document.getElementsByTagNameNS(namespace, "name"); + + assertEquals(1, names.getLength()); + + Element name = (Element) names.item(0); + var parts = name.getElementsByTagNameNS(namespace, "namePart"); + + assertEquals(2, parts.getLength()); + + Element family = (Element) parts.item(0); + Element given = (Element) parts.item(1); + Element role = (Element) name.getElementsByTagNameNS(namespace, "roleTerm").item(0); + + assertEquals("personal", name.getAttribute("type")); + assertEquals("family", family.getAttribute("type")); + assertEquals("given", given.getAttribute("type")); + assertEquals("code", role.getAttribute("type")); + assertEquals("marcrelator", role.getAttribute("authority")); + + assertEquals("Sanders", family.getTextContent()); + assertEquals("Sandra", given.getTextContent()); + assertEquals(expectedRole, role.getTextContent()); + + ModsImporter importer = new ModsImporter(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS)); + try (var reader = Files.newBufferedReader(file)) { + BibEntry imported = importer.importDatabase(reader).getDatabase().getEntries().getFirst(); + assertEquals(Optional.of("Sanders, Sandra"), imported.getField(field)); + } + } + + static Stream namePartsWithOriginalSpelling() { + return Stream.of( + Arguments.of("family=Antin, given=Guy, prefix=d’, useprefix=true", List.of("family|d’Antin", "given|Guy")), + Arguments.of("family=Antin, given=Guy, prefix=d', useprefix=false", List.of("family|d'Antin", "given|Guy")), + Arguments.of("nickname=Jane", List.of("|nickname=Jane")), + Arguments.of("Smith, J", List.of("family|Smith", "given|J")), + Arguments.of("Smith, A.A.", List.of("family|Smith", "given|A.A.")), + Arguments.of("given-i={JPS}, family=Harman", List.of("family|Harman", "given|JPS")), + Arguments.of("given=Jean, given-i=J, family=Harman", List.of("family|Harman", "given|Jean")) + ); + } + + // [utest->req~export.mods.names~1] + @ParameterizedTest + @MethodSource("namePartsWithOriginalSpelling") + void exportsNamePartsWithOriginalSpelling(String input, List expected, @TempDir Path tempDir) throws Exception { + BibEntry entry = new BibEntry(StandardEntryType.Book) + .withField(StandardField.AUTHOR, input) + .withField(StandardField.EDITOR, input); + Path file = tempDir.resolve("names.xml"); + modsExportFormat.export(databaseContext, file, List.of(entry)); + + var document = documentBuilderFactory.newDocumentBuilder().parse(file.toFile()); + String namespace = "http://www.loc.gov/mods/v3"; + var names = document.getElementsByTagNameNS(namespace, "name"); + assertEquals(2, names.getLength()); + for (int index = 0; index < names.getLength(); index++) { + Element name = (Element) names.item(index); + var parts = name.getElementsByTagNameNS(namespace, "namePart"); + assertEquals(expected, IntStream.range(0, parts.getLength()) + .mapToObj(parts::item) + .map(Element.class::cast) + .map(part -> part.getAttribute("type") + "|" + part.getTextContent()) + .toList()); + } + } } diff --git a/jablib/src/test/java/org/jabref/logic/importer/fileformat/ModsImporterFilesTest.java b/jablib/src/test/java/org/jabref/logic/importer/fileformat/ModsImporterFilesTest.java index 67197a02d08c..143bee447661 100644 --- a/jablib/src/test/java/org/jabref/logic/importer/fileformat/ModsImporterFilesTest.java +++ b/jablib/src/test/java/org/jabref/logic/importer/fileformat/ModsImporterFilesTest.java @@ -3,11 +3,17 @@ import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; +import java.util.Optional; import java.util.function.Predicate; import java.util.stream.Stream; import org.jabref.logic.importer.ImportException; import org.jabref.logic.importer.ImportFormatPreferences; +import org.jabref.model.entry.Author; +import org.jabref.model.entry.AuthorList; +import org.jabref.model.entry.BibEntry; +import org.jabref.model.entry.field.StandardField; +import org.jabref.model.entry.field.UnknownField; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -15,6 +21,7 @@ import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Answers; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -47,6 +54,95 @@ void importEntries(String fileName) throws ImportException, IOException { ImporterTestEngine.testImportEntries(new ModsImporter(importFormatPreferences), fileName, FILE_ENDING); } + @Test + void importsLegacyNamesAndDeduplicatesEquivalentRoleTerms() throws IOException { + String xml = """ + + + Doe, John + + + Sanders, Sandra + + edt + Editor + + + trl + + + + Smith, Jane + + ill + + + + Reed, Robert + Thesis advisor + + + Jones, Alice + ctb + + + Baker, Alex + Custom credit + + + """; + ModsImporter importer = new ModsImporter(importFormatPreferences); + + BibEntry entry = importer.importDatabase(new BufferedReader(Reader.of(xml))).getDatabase().getEntries().getFirst(); + + assertEquals(Optional.of("Doe, John"), entry.getField(StandardField.AUTHOR)); + assertEquals(Optional.of("Sanders, Sandra"), entry.getField(StandardField.EDITOR)); + assertEquals(Optional.of("Sanders, Sandra"), entry.getField(StandardField.TRANSLATOR)); + assertEquals(Optional.of("Smith, Jane"), entry.getField(new UnknownField("illustrator"))); + assertEquals(Optional.of("Reed, Robert"), entry.getField(new UnknownField("thesisadvisor"))); + assertEquals(Optional.of("Jones, Alice and Baker, Alex"), entry.getField(new UnknownField("contributor"))); + } + + @Test + void importsCorporateNameWithoutTypedDatePart() throws IOException { + String xml = """ + + + Example University + Research Institute + 1890-1940 + + + """; + ModsImporter importer = new ModsImporter(importFormatPreferences); + + BibEntry entry = importer.importDatabase(new BufferedReader(Reader.of(xml))).getDatabase().getEntries().getFirst(); + + assertEquals(Optional.of("{Example University. Research Institute}"), entry.getField(StandardField.AUTHOR)); + } + + @Test + void importsFamilyNameWhenOnlySuffixIsPresent() throws IOException { + String xml = """ + + + Smith + Jr. + + + """; + ModsImporter importer = new ModsImporter(importFormatPreferences); + + BibEntry entry = importer.importDatabase(new BufferedReader(Reader.of(xml))).getDatabase().getEntries().getFirst(); + + String authorField = entry.getField(StandardField.AUTHOR).orElseThrow(); + assertEquals("Smith", authorField); + Author author = AuthorList.parse(authorField).getAuthor(0); + assertEquals(Optional.of("Smith"), author.getFamilyName()); + assertEquals(Optional.empty(), author.getNameSuffix()); + assertEquals(Optional.empty(), author.getGivenName()); + } + @Test void rejectsExternalEntities() throws IOException { String xmlWithExternalEntity = """ diff --git a/jablib/src/test/java/org/jabref/model/entry/AuthorTest.java b/jablib/src/test/java/org/jabref/model/entry/AuthorTest.java index 0139bfa9dd9e..ca33c93fe39a 100644 --- a/jablib/src/test/java/org/jabref/model/entry/AuthorTest.java +++ b/jablib/src/test/java/org/jabref/model/entry/AuthorTest.java @@ -11,6 +11,87 @@ import static org.junit.jupiter.api.Assertions.assertEquals; class AuthorTest { +<<<<<<< HEAD +======= + @Test + void absentUsePrefixDoesNotImposeADefault() { + Author author = new Author("Hado P.", "H. P.", "van", "Hasselt", ""); + + assertEquals(Optional.empty(), author.getUsePrefix()); + assertEquals(Optional.empty(), author.getInvalidUsePrefix()); + } + + @Test + void readsExplicitInitialsWithoutGeneratingOrRepunctuatingThem() { + Map parts = Map.of("family", "Hasselt", "given-i", "{HP}", + "family-i", "H", "prefix-i", "v.", "suffix-i", "{Jr}"); + Author author = new Author("Hado P.", "H. P.", "van", "Hasselt", "Junior", parts); + + assertEquals(Optional.of("HP"), author.getExplicitGivenNameInitials()); + assertEquals(parts, author.getExtendedNameParts()); + assertEquals(Optional.of("H. P."), author.getGivenNameAbbreviated()); + } + + @Test + void retainsOriginalGivenNamePunctuationAlongsideDisplayForm() { + Author author = AuthorList.parse("Smith, A.A.").getAuthor(0); + + assertEquals(Optional.of("A.A."), author.getGivenNameWithOriginalPunctuation()); + assertEquals(Optional.of("A. A."), author.getGivenName()); + assertEquals(Optional.of("A.A."), author.latexFree().getGivenNameWithOriginalPunctuation()); + } + + @Test + void absentInitialsRemainDistinctFromExplicitlyEmptyInitials() { + Author conventional = new Author("Hado P.", "H. P.", "van", "Hasselt", ""); + Author extended = new Author("Hado P.", "H. P.", "van", "Hasselt", "", + Map.of("family", "Hasselt", "given-i", "{}")); + + assertEquals(Optional.empty(), conventional.getExplicitGivenNameInitials()); + assertEquals(Optional.of(""), extended.getExplicitGivenNameInitials()); + } + + @Test + void parserKeepsOptionsAndInitialsSeparateForEachAuthor() { + AuthorList authors = AuthorList.parse("family=Hasselt, given=Hado P., prefix=van, given-i=HP, useprefix=false" + + " and family=Ree, given=Michiel, prefix=van der, given-i=M, useprefix=true and Guez, Arthur"); + + assertEquals(Optional.of(false), authors.getAuthor(0).getUsePrefix()); + assertEquals(Optional.of("HP"), authors.getAuthor(0).getExplicitGivenNameInitials()); + assertEquals(Optional.of(true), authors.getAuthor(1).getUsePrefix()); + assertEquals(Optional.of("M"), authors.getAuthor(1).getExplicitGivenNameInitials()); + assertEquals(Optional.empty(), authors.getAuthor(2).getUsePrefix()); + assertEquals(authors, AuthorList.parse(authors.getAsBibtex())); + assertEquals(Optional.of("HP"), authors.latexFree().getAuthor(0).getExplicitGivenNameInitials()); + } + + @Test + void differentNameOptionsDistinguishAuthors() { + Author withoutPrefix = AuthorList.parse("family=Hasselt, prefix=van, useprefix=false").getAuthor(0); + Author withPrefix = AuthorList.parse("family=Hasselt, prefix=van, useprefix=true").getAuthor(0); + Author reparsed = AuthorList.parse(withoutPrefix.getAsBibtex()).getAuthor(0); + + assertNotEquals(withoutPrefix, withPrefix); + assertEquals(withoutPrefix, reparsed); + assertEquals(withoutPrefix.hashCode(), reparsed.hashCode()); + } + + @Test + void latexFreeDisplayRetainsExtendedPartsForStorage() { + Author author = AuthorList.parse("family={García}, given=José, useprefix=false").getAuthor(0); + + assertEquals(author.getExtendedNameParts(), author.latexFree().getExtendedNameParts()); + assertEquals(author.getAsBibtex(), author.latexFree().getAsBibtex()); + } + + @Test + void conventionalNamesKeepTheirStorageFormat() { + Author author = new Author("John", "J.", "von", "Smith", "Jr."); + + assertEquals(Map.of(), author.getExtendedNameParts()); + assertEquals("von Smith, Jr., John", author.getAsBibtex()); + } +>>>>>>> b5a8d8f4a4 (Fix author and editor name export in MODS format (#17936)) @ParameterizedTest @CsvSource( diff --git a/jablib/src/test/resources/org/jabref/logic/exporter/ModsExportFormatTestAllFields.xml b/jablib/src/test/resources/org/jabref/logic/exporter/ModsExportFormatTestAllFields.xml index ae20411840c1..c6e20b156f01 100644 --- a/jablib/src/test/resources/org/jabref/logic/exporter/ModsExportFormatTestAllFields.xml +++ b/jablib/src/test/resources/org/jabref/logic/exporter/ModsExportFormatTestAllFields.xml @@ -9,11 +9,17 @@ Don't know + + aut + - Realy + Realy don't know + + aut + someDoi diff --git a/jablib/src/test/resources/org/jabref/logic/exporter/ModsExportFormatTestMultipleEntries.xml b/jablib/src/test/resources/org/jabref/logic/exporter/ModsExportFormatTestMultipleEntries.xml index 1a3adf63b4b1..e2d8f675306f 100644 --- a/jablib/src/test/resources/org/jabref/logic/exporter/ModsExportFormatTestMultipleEntries.xml +++ b/jablib/src/test/resources/org/jabref/logic/exporter/ModsExportFormatTestMultipleEntries.xml @@ -6,13 +6,22 @@ Shruthi Basavaradhya Sahukar + + aut + - Vinodhkumar + Vinodhkumar Palani + + aut + - Selvamani + Selvamani + + aut + Biomarkers @@ -60,13 +69,22 @@ Shruthi Basavaradhya Sahukar + + aut + - Vinodhkumar + Vinodhkumar Palani + + aut + - Selvamani + Selvamani + + aut + Proteomics: A new perspective for cancer. diff --git a/jablib/src/test/resources/org/jabref/logic/exporter/ModsExportFormatTestOnlyRequiredFields.xml b/jablib/src/test/resources/org/jabref/logic/exporter/ModsExportFormatTestOnlyRequiredFields.xml index 90424c9ceadb..a7d44249eca9 100644 --- a/jablib/src/test/resources/org/jabref/logic/exporter/ModsExportFormatTestOnlyRequiredFields.xml +++ b/jablib/src/test/resources/org/jabref/logic/exporter/ModsExportFormatTestOnlyRequiredFields.xml @@ -7,13 +7,22 @@ Shruthi Basavaradhya Sahukar + + aut + - Vinodhkumar + Vinodhkumar Palani + + aut + - Selvamani + Selvamani + + aut + Proteomics: A new perspective for cancer. diff --git a/jablib/src/test/resources/org/jabref/logic/exporter/ModsExportFormatTestTotalPages.xml b/jablib/src/test/resources/org/jabref/logic/exporter/ModsExportFormatTestTotalPages.xml index e940664884b9..63c367684a96 100644 --- a/jablib/src/test/resources/org/jabref/logic/exporter/ModsExportFormatTestTotalPages.xml +++ b/jablib/src/test/resources/org/jabref/logic/exporter/ModsExportFormatTestTotalPages.xml @@ -5,6 +5,9 @@ inbook Mustermann + + aut + keyword diff --git a/jablib/src/test/resources/org/jabref/logic/importer/fileformat/MODSImporterTestModsCollection.bib b/jablib/src/test/resources/org/jabref/logic/importer/fileformat/MODSImporterTestModsCollection.bib index e95c59df9b55..5e0252273850 100644 --- a/jablib/src/test/resources/org/jabref/logic/importer/fileformat/MODSImporterTestModsCollection.bib +++ b/jablib/src/test/resources/org/jabref/logic/importer/fileformat/MODSImporterTestModsCollection.bib @@ -28,8 +28,8 @@ @article{Schewe+Soltwedel2003 @book{Thomas+Dieckmann2003, address = {Oxford}, - author = {Thomas, DN and Dieckmann, GS}, date = {2003}, + editor = {Thomas, DN and Dieckmann, GS}, isbn = {0-632-05808-0}, keywords = {zoology, sea ice}, publisher = {Blackwell Science Ltd},