diff --git a/src/main/java/org/jabref/gui/openoffice/ConnectionLostException.java b/src/main/java/org/jabref/gui/openoffice/ConnectionLostException.java index 36fc16e5e3f..df0264be0de 100644 --- a/src/main/java/org/jabref/gui/openoffice/ConnectionLostException.java +++ b/src/main/java/org/jabref/gui/openoffice/ConnectionLostException.java @@ -5,7 +5,7 @@ */ class ConnectionLostException extends RuntimeException { - public ConnectionLostException(String s) { - super(s); + public ConnectionLostException(String msg) { + super(msg); } } diff --git a/src/main/java/org/jabref/logic/openoffice/OOUtil.java b/src/main/java/org/jabref/logic/openoffice/OOUtil.java index 9efab82773c..a5976cb3342 100644 --- a/src/main/java/org/jabref/logic/openoffice/OOUtil.java +++ b/src/main/java/org/jabref/logic/openoffice/OOUtil.java @@ -127,13 +127,13 @@ public static void insertOOFormattedTextAtCurrentLocation(XText text, XTextCurso List formatting = new ArrayList<>(); // We need to extract formatting. Use a simple regexp search iteration: int piv = 0; - Matcher m = OOUtil.HTML_TAG.matcher(lText); - while (m.find()) { - String currentSubstring = lText.substring(piv, m.start()); + Matcher matcher = OOUtil.HTML_TAG.matcher(lText); + while (matcher.find()) { + String currentSubstring = lText.substring(piv, matcher.start()); if (!currentSubstring.isEmpty()) { OOUtil.insertTextAtCurrentLocation(text, cursor, currentSubstring, formatting); } - String tag = m.group(); + String tag = matcher.group(); // Handle tags: if ("".equals(tag)) { formatting.add(Formatting.BOLD); @@ -169,7 +169,7 @@ public static void insertOOFormattedTextAtCurrentLocation(XText text, XTextCurso formatting.remove(Formatting.STRIKEOUT); } - piv = m.end(); + piv = matcher.end(); } if (piv < lText.length()) { @@ -276,10 +276,9 @@ public static void insertTextAtCurrentLocation(XText text, XTextCursor cursor, S cursor.collapseToEnd(); } - public static Object getProperty(Object o, String property) + public static Object getProperty(Object object, String property) throws UnknownPropertyException, WrappedTargetException { - XPropertySet props = UnoRuntime.queryInterface( - XPropertySet.class, o); + XPropertySet props = UnoRuntime.queryInterface(XPropertySet.class, object); return props.getPropertyValue(property); } } diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java index 0016e5e4510..4a0d8d05e0e 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Backend52.java @@ -196,17 +196,6 @@ public CitationGroup createCitationGroup(XTextDocument doc, throw new IllegalArgumentException(); } - /* - * Backend52 uses reference marks to (1) mark the location of the citation in the text and (2) to encode - * the citation keys and citation type in the name of the reference mark. The name of the reference mark - * has to be unique in the document. - */ - String markName = Codec52.getUniqueMarkName(new HashSet<>(citationStorageManager.getUsedNames(doc)), - citationKeys, - citationType); - - CitationGroupId groupId = new CitationGroupId(markName); - final int numberOfCitations = citationKeys.size(); final int last = numberOfCitations - 1; @@ -236,6 +225,17 @@ public CitationGroup createCitationGroup(XTextDocument doc, } } + /* + * Backend52 uses reference marks to (1) mark the location of the citation in the text and (2) to encode + * the citation keys and citation type in the name of the reference mark. The name of the reference mark + * has to be unique in the document. + */ + final String markName = Codec52.getUniqueMarkName(new HashSet<>(citationStorageManager.getUsedNames(doc)), + citationKeys, + citationType); + + final CitationGroupId groupId = new CitationGroupId(markName); + /* * Apply to document */ diff --git a/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java b/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java index f567a3e459e..45f3bd3ca04 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/Codec52.java @@ -32,16 +32,16 @@ private Codec52() { */ public static class ParsedMarkName { /** "", "0", "1" ... */ - public final String i; + public final String index; /** in-text-citation type */ public final CitationType citationType; /** Citation keys embedded in the reference mark. */ public final List citationKeys; - ParsedMarkName(String i, CitationType citationType, List citationKeys) { - Objects.requireNonNull(i); + ParsedMarkName(String index, CitationType citationType, List citationKeys) { + Objects.requireNonNull(index); Objects.requireNonNull(citationKeys); - this.i = i; + this.index = index; this.citationType = citationType; this.citationKeys = citationKeys; } @@ -50,8 +50,8 @@ public static class ParsedMarkName { /** * Integer representation was written into the document in JabRef52, keep it for compatibility. */ - private static CitationType citationTypeFromInt(int i) { - return switch (i) { + private static CitationType citationTypeFromInt(int code) { + return switch (code) { case 1 -> CitationType.AUTHORYEAR_PAR; case 2 -> CitationType.AUTHORYEAR_INTEXT; case 3 -> CitationType.INVISIBLE_CIT; @@ -59,8 +59,8 @@ private static CitationType citationTypeFromInt(int i) { }; } - private static int citationTypeToInt(CitationType i) { - return switch (i) { + private static int citationTypeToInt(CitationType type) { + return switch (type) { case AUTHORYEAR_PAR -> 1; case AUTHORYEAR_INTEXT -> 2; case INVISIBLE_CIT -> 3; @@ -86,12 +86,12 @@ public static String getUniqueMarkName(Set usedNames, String citationKeysPart = String.join(",", citationKeys); - int i = 0; + int index = 0; int citTypeCode = citationTypeToInt(citationType); String name = BIB_CITATION + '_' + citTypeCode + '_' + citationKeysPart; while (usedNames.contains(name)) { - name = BIB_CITATION + i + '_' + citTypeCode + '_' + citationKeysPart; - i++; + name = BIB_CITATION + index + '_' + citTypeCode + '_' + citationKeysPart; + index++; } return name; } @@ -110,10 +110,10 @@ public static Optional parseMarkName(String refMarkName) { } List keys = Arrays.asList(citeMatcher.group(3).split(",")); - String i = citeMatcher.group(1); + String index = citeMatcher.group(1); int citTypeCode = Integer.parseInt(citeMatcher.group(2)); CitationType citationType = citationTypeFromInt(citTypeCode); - return (Optional.of(new Codec52.ParsedMarkName(i, citationType, keys))); + return (Optional.of(new Codec52.ParsedMarkName(index, citationType, keys))); } /** diff --git a/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java b/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java index cfabb1e2de0..324b984377c 100644 --- a/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java +++ b/src/main/java/org/jabref/logic/openoffice/backend/NamedRangeReferenceMark.java @@ -35,14 +35,14 @@ class NamedRangeReferenceMark implements NamedRange { private static final Logger LOGGER = LoggerFactory.getLogger(NamedRangeReferenceMark.class); - private String id; /* reference mark name */ + private String rangeId; /* reference mark name */ - private NamedRangeReferenceMark(String id) { - this.id = id; + private NamedRangeReferenceMark(String rangeId) { + this.rangeId = rangeId; } String getId() { - return id; + return rangeId; } /** @@ -156,7 +156,7 @@ public void removeFromDocument(XTextDocument doc) @Override public String getRangeName() { - return id; + return rangeId; } /** @@ -217,8 +217,6 @@ public XTextCursor getFillCursor(XTextDocument doc) String name = this.getRangeName(); - final String left = NamedRangeReferenceMark.REFERENCE_MARK_LEFT_BRACKET; - final String right = NamedRangeReferenceMark.REFERENCE_MARK_RIGHT_BRACKET; final boolean debugThisFun = false; XTextCursor full = null; @@ -279,6 +277,8 @@ public XTextCursor getFillCursor(XTextDocument doc) beta.goRight((short) (fullText.length() - 2), true); LOGGER.debug("getFillCursor: beta(1) covers '{}'", beta.getString()); + final String left = NamedRangeReferenceMark.REFERENCE_MARK_LEFT_BRACKET; + final String right = NamedRangeReferenceMark.REFERENCE_MARK_RIGHT_BRACKET; final short rightLength = (short) right.length(); if (fullText.startsWith(left) && fullText.endsWith(right)) { beta.setString(""); @@ -345,7 +345,6 @@ public XTextCursor getFillCursor(XTextDocument doc) */ public static void checkFillCursor(XTextCursor cursor) { final String left = REFERENCE_MARK_LEFT_BRACKET; - final String right = REFERENCE_MARK_RIGHT_BRACKET; XTextCursor alpha = cursor.getText().createTextCursorByRange(cursor); alpha.collapseToStart(); @@ -364,6 +363,7 @@ public static void checkFillCursor(XTextCursor cursor) { } } + final String right = REFERENCE_MARK_RIGHT_BRACKET; final short rightLength = (short) right.length(); if (rightLength > 0) { omega.goRight(rightLength, true); @@ -395,27 +395,26 @@ public void cleanFillCursor(XTextDocument doc) // removeBracketsFromEmpty is intended to force removal if we are working on an "Empty citation" (INVISIBLE_CIT). final boolean removeBracketsFromEmpty = false; - final String left = REFERENCE_MARK_LEFT_BRACKET; - final String right = REFERENCE_MARK_RIGHT_BRACKET; - final short leftLength = (short) left.length(); - final short rightLength = (short) right.length(); - String name = this.getRangeName(); XTextCursor full = this.getRawCursor(doc).orElseThrow(IllegalStateException::new); final String fullText = full.getString(); - final int fullTextLength = fullText.length(); + final String left = REFERENCE_MARK_LEFT_BRACKET; if (!fullText.startsWith(left)) { String msg = String.format("cleanFillCursor: (%s) does not start with REFERENCE_MARK_LEFT_BRACKET", name); throw new IllegalStateException(msg); } + final String right = REFERENCE_MARK_RIGHT_BRACKET; if (!fullText.endsWith(right)) { String msg = String.format("cleanFillCursor: (%s) does not end with REFERENCE_MARK_RIGHT_BRACKET", name); throw new IllegalStateException(msg); } + final int fullTextLength = fullText.length(); + final short leftLength = (short) left.length(); + final short rightLength = (short) right.length(); final int contentLength = (fullTextLength - (leftLength + rightLength)); if (contentLength < 0) { String msg = String.format("cleanFillCursor: length(%s) < 0", name); diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java new file mode 100644 index 00000000000..58057c382e7 --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/frontend/OOFrontend.java @@ -0,0 +1,555 @@ +package org.jabref.logic.openoffice.frontend; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.stream.Collectors; + +import org.jabref.logic.JabRefException; +import org.jabref.logic.l10n.Localization; +import org.jabref.logic.openoffice.backend.Backend52; +import org.jabref.model.openoffice.CitationEntry; +import org.jabref.model.openoffice.ootext.OOText; +import org.jabref.model.openoffice.rangesort.FunctionalTextViewCursor; +import org.jabref.model.openoffice.rangesort.RangeOverlap; +import org.jabref.model.openoffice.rangesort.RangeOverlapBetween; +import org.jabref.model.openoffice.rangesort.RangeOverlapWithin; +import org.jabref.model.openoffice.rangesort.RangeSort; +import org.jabref.model.openoffice.rangesort.RangeSortEntry; +import org.jabref.model.openoffice.rangesort.RangeSortVisual; +import org.jabref.model.openoffice.rangesort.RangeSortable; +import org.jabref.model.openoffice.style.CitationGroup; +import org.jabref.model.openoffice.style.CitationGroupId; +import org.jabref.model.openoffice.style.CitationGroups; +import org.jabref.model.openoffice.style.CitationType; +import org.jabref.model.openoffice.style.OODataModel; +import org.jabref.model.openoffice.uno.CreationException; +import org.jabref.model.openoffice.uno.NoDocumentException; +import org.jabref.model.openoffice.uno.UnoCursor; +import org.jabref.model.openoffice.uno.UnoTextRange; +import org.jabref.model.openoffice.util.OOListUtil; +import org.jabref.model.openoffice.util.OOVoidResult; + +import com.sun.star.beans.IllegalTypeException; +import com.sun.star.beans.NotRemoveableException; +import com.sun.star.beans.PropertyVetoException; +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.text.XTextCursor; +import com.sun.star.text.XTextDocument; +import com.sun.star.text.XTextRange; + +public class OOFrontend { + + public final Backend52 backend; + public final CitationGroups citationGroups; + + public OOFrontend(XTextDocument doc) + throws + NoDocumentException, + WrappedTargetException { + + // TODO: dataModel should come from looking at the document and preferences. + this.backend = new Backend52(); + + // Get the citationGroupNames + List citationGroupNames = this.backend.getJabRefReferenceMarkNames(doc); + + Map citationGroups = + readCitationGroupsFromDocument(this.backend, doc, citationGroupNames); + this.citationGroups = new CitationGroups(citationGroups); + } + + public OODataModel getDataModel() { + return backend.dataModel; + } + + public Optional healthReport(XTextDocument doc) + throws + NoDocumentException { + return backend.healthReport(doc); + } + + private static Map + readCitationGroupsFromDocument(Backend52 backend, + XTextDocument doc, + List citationGroupNames) + throws + WrappedTargetException, + NoDocumentException { + + Map citationGroups = new HashMap<>(); + for (String name : citationGroupNames) { + CitationGroup group = backend.readCitationGroupFromDocumentOrThrow(doc, name); + citationGroups.put(group.groupId, group); + } + return citationGroups; + } + + /** + * Creates a list of {@code RangeSortable} values for our {@code CitationGroup} + * values. Originally designed to be passed to {@code visualSort}. + * + * The elements of the returned list are actually of type {@code RangeSortEntry}. + * + * The result is sorted within {@code XTextRange.getText()} partitions of the citation groups + * according to their {@code XTextRange} (before mapping to footnote marks). + * + * In the result, RangeSortable.getIndexInPosition() contains unique indexes within the original + * partition (not after mapFootnotesToFootnoteMarks). + * + * @param mapFootnotesToFootnoteMarks If true, replace ranges in footnotes with the range of the + * corresponding footnote mark. This is used for numbering the citations. + * + */ + private List> + createVisualSortInput(XTextDocument doc, boolean mapFootnotesToFootnoteMarks) + throws + NoDocumentException, + WrappedTargetException { + + List> sortables = new ArrayList<>(); + for (CitationGroup group : citationGroups.getCitationGroupsUnordered()) { + XTextRange range = (this + .getMarkRange(doc, group) + .orElseThrow(IllegalStateException::new)); + sortables.add(new RangeSortEntry<>(range, 0, group)); + } + + /* + * At this point we are almost ready to return sortables. + * + * But we may want to number citations in a footnote as if it appeared where the footnote + * mark is. + * + * The following code replaces ranges within footnotes with the range for the corresponding + * footnote mark. + * + * This brings further ambiguity if we have multiple citation groups within the same + * footnote: for the comparison they become indistinguishable. Numbering between them is + * not controlled. Also combineCiteMarkers will see them in the wrong order (if we use this + * comparison), and will not be able to merge. To avoid these, we sort textually within + * each .getText() partition and add indexInPosition accordingly. + * + */ + + // Sort within partitions + RangeSort.RangePartitions> partitions = + RangeSort.partitionAndSortRanges(sortables); + + // build final list + List> result = new ArrayList<>(); + for (List> partition : partitions.getPartitions()) { + + int indexInPartition = 0; + for (RangeSortEntry sortable : partition) { + sortable.setIndexInPosition(indexInPartition++); + if (mapFootnotesToFootnoteMarks) { + Optional footnoteMarkRange = + UnoTextRange.getFootnoteMarkRange(sortable.getRange()); + // Adjust range if we are inside a footnote: + if (footnoteMarkRange.isPresent()) { + sortable.setRange(footnoteMarkRange.get()); + } + } + result.add(sortable); + } + } + return result.stream().map(e -> e).collect(Collectors.toList()); + } + + /** + * @param mapFootnotesToFootnoteMarks If true, sort reference marks in footnotes as if they + * appeared at the corresponding footnote mark. + * + * @return citation groups sorted by their visual positions. + * + * Limitation: for two column layout visual (top-down, left-right) order does not match the + * expected (textual) order. + * + */ + private List getVisuallySortedCitationGroups(XTextDocument doc, + boolean mapFootnotesToFootnoteMarks, + FunctionalTextViewCursor fcursor) + throws + WrappedTargetException, + NoDocumentException { + + List> sortables = createVisualSortInput(doc, mapFootnotesToFootnoteMarks); + + List> sorted = RangeSortVisual.visualSort(sortables, doc, fcursor); + + return (sorted.stream() + .map(RangeSortable::getContent) + .collect(Collectors.toList())); + } + + /** + * Return citation groups in visual order within (but not across) XText partitions. + * + * This is (1) sufficient for combineCiteMarkers which looks for consecutive XTextRanges within + * each XText, (2) not confused by multicolumn layout or multipage display. + */ + public List + getCitationGroupsSortedWithinPartitions(XTextDocument doc, boolean mapFootnotesToFootnoteMarks) + throws + NoDocumentException, + WrappedTargetException { + // This is like getVisuallySortedCitationGroups, + // but we skip the visualSort part. + List> sortables = + createVisualSortInput(doc, mapFootnotesToFootnoteMarks); + + return (sortables.stream().map(e -> e.getContent()).collect(Collectors.toList())); + } + + /** + * Create a citation group for the given citation keys, at the end of position. + * + * On return {@code position} is collapsed, and is after the inserted space, or at the end of + * the reference mark. + * + * @param citationKeys In storage order + * @param pageInfos In storage order + * @param citationType + * @param position Collapsed to its end. + * @param insertSpaceAfter If true, we insert a space after the mark, that carries on format of + * characters from the original position. + */ + public CitationGroup createCitationGroup(XTextDocument doc, + List citationKeys, + List> pageInfos, + CitationType citationType, + XTextCursor position, + boolean insertSpaceAfter) + throws + CreationException, + NoDocumentException, + WrappedTargetException, + NotRemoveableException, + PropertyVetoException, + IllegalTypeException { + + Objects.requireNonNull(pageInfos); + if (pageInfos.size() != citationKeys.size()) { + throw new IllegalArgumentException("pageInfos.size != citationKeys.size"); + } + CitationGroup group = backend.createCitationGroup(doc, + citationKeys, + pageInfos, + citationType, + position, + insertSpaceAfter); + + this.citationGroups.afterCreateCitationGroup(group); + return group; + } + + /** + * Remove {@code group} both from the document and notify {@code citationGroups} + */ + public void removeCitationGroup(CitationGroup group, XTextDocument doc) + throws + WrappedTargetException, + NoDocumentException, + NotRemoveableException { + + backend.removeCitationGroup(group, doc); + this.citationGroups.afterRemoveCitationGroup(group); + } + + public void removeCitationGroups(List cgs, XTextDocument doc) + throws + WrappedTargetException, + NoDocumentException, + NotRemoveableException { + + for (CitationGroup group : cgs) { + removeCitationGroup(group, doc); + } + } + + /** + * ranges controlled by citation groups should not overlap with each other. + * + * @return Optional.empty() if the reference mark is missing. + * + */ + public Optional getMarkRange(XTextDocument doc, CitationGroup group) + throws + NoDocumentException, + WrappedTargetException { + return backend.getMarkRange(group, doc); + } + + public XTextCursor getFillCursorForCitationGroup(XTextDocument doc, CitationGroup group) + throws + NoDocumentException, + WrappedTargetException, + CreationException { + return backend.getFillCursorForCitationGroup(group, doc); + } + + /** + * Remove brackets added by getFillCursorForCitationGroup. + */ + public void cleanFillCursorForCitationGroup(XTextDocument doc, CitationGroup group) + throws + NoDocumentException, + WrappedTargetException { + + backend.cleanFillCursorForCitationGroup(group, doc); + } + + /** + * @return A RangeForOverlapCheck for each citation group. + * + * result.size() == nRefMarks + */ + public List> citationRanges(XTextDocument doc) + throws + NoDocumentException, + WrappedTargetException { + + List> result = + new ArrayList<>(citationGroups.numberOfCitationGroups()); + + for (CitationGroup group : citationGroups.getCitationGroupsUnordered()) { + XTextRange range = this.getMarkRange(doc, group).orElseThrow(IllegalStateException::new); + String description = group.groupId.citationGroupIdAsString(); + result.add(new RangeForOverlapCheck<>(range, + group.groupId, + RangeForOverlapCheck.REFERENCE_MARK_KIND, + description)); + } + return result; + } + + public List> bibliographyRanges(XTextDocument doc) + throws + NoDocumentException, + WrappedTargetException { + + List> result = new ArrayList<>(); + + Optional range = UpdateBibliography.getBibliographyRange(doc); + if (range.isPresent()) { + String description = "bibliography"; + result.add(new RangeForOverlapCheck<>(range.get(), + new CitationGroupId("bibliography"), + RangeForOverlapCheck.BIBLIOGRAPHY_MARK_KIND, + description)); + } + return result; + } + + public List> viewCursorRanges(XTextDocument doc) { + + List> result = new ArrayList<>(); + + Optional range = UnoCursor.getViewCursor(doc).map(e -> e); + if (range.isPresent()) { + String description = "cursor"; + result.add(new RangeForOverlapCheck<>(range.get(), + new CitationGroupId("cursor"), + RangeForOverlapCheck.CURSOR_MARK_KIND, + description)); + } + return result; + } + + /** + * @return A range for each footnote mark where the footnote contains at least one citation group. + * + * Purpose: We do not want markers of footnotes containing reference marks to overlap with + * reference marks. Overwriting these footnote marks might kill our reference marks in the + * footnote. + * + * Note: Here we directly communicate to the document, not through the backend. This is because + * mapping ranges to footnote marks does not depend on how do we mark or structure those + * ranges. + */ + public List> + footnoteMarkRanges(XTextDocument doc, List> citationRanges) { + + // We partition by XText and use a single range from + // each partition to get at the corresponding footnotemark range. + + List> result = new ArrayList<>(); + RangeSort.RangePartitions> partitions = + RangeSort.partitionRanges(citationRanges); + + // Each partition corresponds to an XText, and each footnote has a single XText. + // (This latter ignores the possibility of XTextContents inserted into footnotes.) + // Also: different footnotes cannot share a footnotemark range, we are not creating duplicates. + for (List> partition : partitions.getPartitions()) { + if (partition.isEmpty()) { + continue; + } + RangeForOverlapCheck citationRange = partition.get(0); + + Optional footnoteMarkRange = UnoTextRange.getFootnoteMarkRange(citationRange.range); + + if (footnoteMarkRange.isEmpty()) { + // not in footnote + continue; + } + + result.add(new RangeForOverlapCheck<>(footnoteMarkRange.get(), + citationRange.idWithinKind, + RangeForOverlapCheck.FOOTNOTE_MARK_KIND, + "FootnoteMark for " + citationRange.format())); + } + return result; + } + + static String rangeOverlapsToMessage(List>> overlaps) { + + if (overlaps.isEmpty()) { + return "(*no overlaps*)"; + } + + StringBuilder msg = new StringBuilder(); + for (RangeOverlap> overlap : overlaps) { + String listOfRanges = (overlap.valuesForOverlappingRanges.stream() + .map(v -> String.format("'%s'", v.format())) + .collect(Collectors.joining(", "))); + msg.append( + switch (overlap.kind) { + case EQUAL_RANGE -> Localization.lang("Found identical ranges"); + case OVERLAP -> Localization.lang("Found overlapping ranges"); + case TOUCH -> Localization.lang("Found touching ranges"); + }); + msg.append(": "); + msg.append(listOfRanges); + msg.append("\n"); + } + return msg.toString(); + } + + /** + * Check for any overlap between userRanges and protected ranges. + * + * Assume userRanges is small (usually 1 elements for checking the cursor) + * + * Returns on first problem found. + */ + public OOVoidResult + checkRangeOverlapsWithCursor(XTextDocument doc, + List> userRanges, + boolean requireSeparation) + throws + NoDocumentException, + WrappedTargetException { + + List> citationRanges = citationRanges(doc); + List> ranges = new ArrayList<>(); + + // ranges.addAll(userRanges); + ranges.addAll(bibliographyRanges(doc)); + ranges.addAll(citationRanges); + ranges.addAll(footnoteMarkRanges(doc, citationRanges)); + + List>> overlaps = + RangeOverlapBetween.findFirst(doc, + userRanges, + ranges, + requireSeparation); + + if (overlaps.isEmpty()) { + return OOVoidResult.ok(); + } + return OOVoidResult.error(new JabRefException("Found overlapping or touching ranges", + rangeOverlapsToMessage(overlaps))); + } + + /** + * @param requireSeparation Report range pairs that only share a boundary. + * @param reportAtMost Limit number of overlaps reported (0 for no limit) + * + */ + public OOVoidResult checkRangeOverlaps(XTextDocument doc, + List> userRanges, + boolean requireSeparation, + int reportAtMost) + throws + NoDocumentException, + WrappedTargetException { + + List> citationRanges = citationRanges(doc); + List> ranges = new ArrayList<>(); + ranges.addAll(userRanges); + ranges.addAll(bibliographyRanges(doc)); + ranges.addAll(citationRanges); + ranges.addAll(footnoteMarkRanges(doc, citationRanges)); + + List>> overlaps = + RangeOverlapWithin.findOverlappingRanges(doc, ranges, requireSeparation, reportAtMost); + + if (overlaps.isEmpty()) { + return OOVoidResult.ok(); + } + return OOVoidResult.error(new JabRefException("Found overlapping or touching ranges", + rangeOverlapsToMessage(overlaps))); + } + + /** + * GUI: Get a list of CitationEntry objects corresponding to citations + * in the document. + * + * Called from: ManageCitationsDialogViewModel constructor. + * + * @return A list with entries corresponding to citations in the text, in arbitrary order (same + * order as from getJabRefReferenceMarkNames). + * + * Note: visual or alphabetic order could be more manageable for the user. We + * could provide these here, but switching between them needs change on GUI + * (adding a toggle or selector). + * + * Note: CitationEntry implements Comparable, where compareTo() and equals() are + * based on refMarkName. The order used in the "Manage citations" dialog + * does not seem to use that. + * + * The 1st is labeled "Citation" (show citation in bold, and some context + * around it). + * + * The columns can be sorted by clicking on the column title. For the + * "Citation" column, the sorting is based on the content, (the context + * before the citation), not on the citation itself. + * + * In the "Extra information ..." column some visual indication of the + * editable part could be helpful. + * + * Wish: selecting an entry (or a button in the line) in the GUI could move the cursor + * in the document to the entry. + */ + public List getCitationEntries(XTextDocument doc) + throws + WrappedTargetException, + NoDocumentException { + return this.backend.getCitationEntries(doc, citationGroups); + } + + public void applyCitationEntries(XTextDocument doc, List citationEntries) + throws + PropertyVetoException, + IllegalTypeException, + IllegalArgumentException, + WrappedTargetException { + this.backend.applyCitationEntries(doc, citationEntries); + } + + public void imposeGlobalOrder(XTextDocument doc, FunctionalTextViewCursor fcursor) + throws + WrappedTargetException, + NoDocumentException { + + boolean mapFootnotesToFootnoteMarks = true; + List sortedCitationGroups = + getVisuallySortedCitationGroups(doc, mapFootnotesToFootnoteMarks, fcursor); + List sortedCitationGroupIds = OOListUtil.map(sortedCitationGroups, group -> group.groupId); + citationGroups.setGlobalOrder(sortedCitationGroupIds); + } +} diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/RangeForOverlapCheck.java b/src/main/java/org/jabref/logic/openoffice/frontend/RangeForOverlapCheck.java new file mode 100644 index 00000000000..6cbf560ec62 --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/frontend/RangeForOverlapCheck.java @@ -0,0 +1,49 @@ +package org.jabref.logic.openoffice.frontend; + +import org.jabref.model.openoffice.rangesort.RangeHolder; + +import com.sun.star.text.XTextRange; + +/** + * Describe a protected range for overlap checking and reporting. + * + * To check that our protected ranges do not overlap, we collect + * these ranges. To check for overlaps between these, we need the + * {@code range} itself. To report the results of overlap + * checking, we need a {@code description} that can be understood + * by the user. + * + * To be able to refer back to more extended data, we might need to + * identify its {@code kind}, and its index in the corresponding + * tables or other identifier within its kind ({@code idWithinKind}) + * + */ +public class RangeForOverlapCheck implements RangeHolder { + + public final static int REFERENCE_MARK_KIND = 0; + public final static int FOOTNOTE_MARK_KIND = 1; + public final static int CURSOR_MARK_KIND = 2; + public final static int BIBLIOGRAPHY_MARK_KIND = 3; + + public final XTextRange range; + + public final int kind; + public final T idWithinKind; + private final String description; + + public RangeForOverlapCheck(XTextRange range, T idWithinKind, int kind, String description) { + this.range = range; + this.kind = kind; + this.idWithinKind = idWithinKind; + this.description = description; + } + + public String format() { + return description; + } + + @Override + public XTextRange getRange() { + return range; + } +} diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/UpdateBibliography.java b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateBibliography.java new file mode 100644 index 00000000000..ebda8359ba5 --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateBibliography.java @@ -0,0 +1,144 @@ +package org.jabref.logic.openoffice.frontend; + +import java.util.Optional; + +import org.jabref.logic.openoffice.style.OOBibStyle; +import org.jabref.logic.openoffice.style.OOFormatBibliography; +import org.jabref.model.openoffice.ootext.OOText; +import org.jabref.model.openoffice.ootext.OOTextIntoOO; +import org.jabref.model.openoffice.style.CitedKeys; +import org.jabref.model.openoffice.uno.CreationException; +import org.jabref.model.openoffice.uno.NoDocumentException; +import org.jabref.model.openoffice.uno.UnoBookmark; +import org.jabref.model.openoffice.uno.UnoTextSection; + +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.text.XTextCursor; +import com.sun.star.text.XTextDocument; +import com.sun.star.text.XTextRange; + +/* + * Update document: citation marks and bibliography + */ +public class UpdateBibliography { + + private static final String BIB_SECTION_NAME = "JR_bib"; + private static final String BIB_SECTION_END_NAME = "JR_bib_end"; + + private UpdateBibliography() { + /**/ + } + + public static Optional getBibliographyRange(XTextDocument doc) + throws + NoDocumentException, + WrappedTargetException { + return UnoTextSection.getAnchor(doc, BIB_SECTION_NAME); + } + + /** + * Rebuilds the bibliography. + */ + public static void rebuildBibTextSection(XTextDocument doc, + OOFrontend frontend, + CitedKeys bibliography, + OOBibStyle style, + boolean alwaysAddCitedOnPages) + throws + WrappedTargetException, + CreationException, + NoDocumentException { + + clearBibTextSectionContent2(doc); + + populateBibTextSection(doc, + frontend, + bibliography, + style, + alwaysAddCitedOnPages); + } + + /** + * Insert a paragraph break and create a text section for the bibliography. + * + * Only called from `clearBibTextSectionContent2` + */ + private static void createBibTextSection2(XTextDocument doc) + throws + CreationException { + + // Always creating at the end of the document. + // Alternatively, we could receive a cursor. + XTextCursor textCursor = doc.getText().createTextCursor(); + textCursor.gotoEnd(false); + UnoTextSection.create(doc, BIB_SECTION_NAME, textCursor, false); + } + + /** + * Find and clear the text section BIB_SECTION_NAME to "", + * or create it. + * + * Only called from: `rebuildBibTextSection` + * + */ + private static void clearBibTextSectionContent2(XTextDocument doc) + throws + CreationException, + NoDocumentException, + WrappedTargetException { + + // Optional sectionRange = UnoTextSection.getAnchor(doc, BIB_SECTION_NAME); + Optional sectionRange = getBibliographyRange(doc); + if (sectionRange.isEmpty()) { + createBibTextSection2(doc); + return; + } else { + // Clear it + XTextCursor cursor = doc.getText().createTextCursorByRange(sectionRange.get()); + cursor.setString(""); + } + } + + /** + * Only called from: `rebuildBibTextSection` + * + * Assumes the section named BIB_SECTION_NAME exists. + */ + private static void populateBibTextSection(XTextDocument doc, + OOFrontend frontend, + CitedKeys bibliography, + OOBibStyle style, + boolean alwaysAddCitedOnPages) + throws + CreationException, + IllegalArgumentException, + NoDocumentException, + WrappedTargetException { + + XTextRange sectionRange = getBibliographyRange(doc).orElseThrow(IllegalStateException::new); + + XTextCursor cursor = doc.getText().createTextCursorByRange(sectionRange); + + // emit the title of the bibliography + OOTextIntoOO.removeDirectFormatting(cursor); + OOText bibliographyText = OOFormatBibliography.formatBibliography(frontend.citationGroups, + bibliography, + style, + alwaysAddCitedOnPages); + OOTextIntoOO.write(doc, cursor, bibliographyText); + cursor.collapseToEnd(); + + // remove the initial empty paragraph from the section. + sectionRange = getBibliographyRange(doc).orElseThrow(IllegalStateException::new); + XTextCursor initialParagraph = doc.getText().createTextCursorByRange(sectionRange); + initialParagraph.collapseToStart(); + initialParagraph.goRight((short) 1, true); + initialParagraph.setString(""); + + UnoBookmark.removeIfExists(doc, BIB_SECTION_END_NAME); + UnoBookmark.create(doc, BIB_SECTION_END_NAME, cursor, true); + + cursor.collapseToEnd(); + } + +} diff --git a/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java new file mode 100644 index 00000000000..834fce1d0ce --- /dev/null +++ b/src/main/java/org/jabref/logic/openoffice/frontend/UpdateCitationMarkers.java @@ -0,0 +1,162 @@ +package org.jabref.logic.openoffice.frontend; + +import java.util.List; +import java.util.Objects; +import java.util.Optional; + +import org.jabref.logic.openoffice.style.OOBibStyle; +import org.jabref.model.openoffice.ootext.OOText; +import org.jabref.model.openoffice.ootext.OOTextIntoOO; +import org.jabref.model.openoffice.style.CitationGroup; +import org.jabref.model.openoffice.style.CitationGroups; +import org.jabref.model.openoffice.style.CitationType; +import org.jabref.model.openoffice.uno.CreationException; +import org.jabref.model.openoffice.uno.NoDocumentException; + +import com.sun.star.beans.IllegalTypeException; +import com.sun.star.beans.NotRemoveableException; +import com.sun.star.beans.PropertyVetoException; +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.text.XTextCursor; +import com.sun.star.text.XTextDocument; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/* + * Update document: citation marks and bibliography + */ +public class UpdateCitationMarkers { + + private static final Logger LOGGER = LoggerFactory.getLogger(UpdateCitationMarkers.class); + + private UpdateCitationMarkers() { + /**/ + } + + /** + * Visit each reference mark in referenceMarkNames, overwrite its + * text content. + * + * After each fillCitationMarkInCursor call check if we lost the + * BIB_SECTION_NAME bookmark and recreate it if we did. + * + * @param frontend + * + * @param style Bibliography style to use. + * + */ + public static void applyNewCitationMarkers(XTextDocument doc, OOFrontend frontend, OOBibStyle style) + throws + NoDocumentException, + CreationException, + WrappedTargetException { + + CitationGroups citationGroups = frontend.citationGroups; + + for (CitationGroup group : citationGroups.getCitationGroupsUnordered()) { + + boolean withText = (group.citationType != CitationType.INVISIBLE_CIT); + Optional marker = group.getCitationMarker(); + + if (!marker.isPresent()) { + LOGGER.warn("applyNewCitationMarkers: no marker for {}", + group.groupId.citationGroupIdAsString()); + continue; + } + + if (withText && marker.isPresent()) { + + XTextCursor cursor = frontend.getFillCursorForCitationGroup(doc, group); + + fillCitationMarkInCursor(doc, cursor, marker.get(), withText, style); + + frontend.cleanFillCursorForCitationGroup(doc, group); + } + + } + } + + public static void fillCitationMarkInCursor(XTextDocument doc, + XTextCursor cursor, + OOText citationText, + boolean withText, + OOBibStyle style) + throws + WrappedTargetException, + CreationException, + IllegalArgumentException { + + Objects.requireNonNull(cursor); + Objects.requireNonNull(citationText); + Objects.requireNonNull(style); + + if (withText) { + OOText citationText2 = style.decorateCitationMarker(citationText); + // inject a ZERO_WIDTH_SPACE to hold the initial character format + final String ZERO_WIDTH_SPACE = "\u200b"; + citationText2 = OOText.fromString(ZERO_WIDTH_SPACE + citationText2.toString()); + OOTextIntoOO.write(doc, cursor, citationText2); + } else { + cursor.setString(""); + } + } + + /** + * Inserts a citation group in the document: creates and fills it. + * + * @param citationKeys BibTeX keys of + * @param pageInfos + * @param citationType + * + * @param citationText Text for the citation. A citation mark or + * placeholder if not yet available. + * + * @param position Location to insert at. + * @param style + * @param insertSpaceAfter A space inserted after the reference + * mark makes it easier to separate from the text + * coming after. But is not wanted when we recreate a + * reference mark. + */ + public static void createAndFillCitationGroup(OOFrontend frontend, + XTextDocument doc, + List citationKeys, + List> pageInfos, + CitationType citationType, + OOText citationText, + XTextCursor position, + OOBibStyle style, + boolean insertSpaceAfter) + throws + NotRemoveableException, + WrappedTargetException, + PropertyVetoException, + IllegalArgumentException, + CreationException, + NoDocumentException, + IllegalTypeException { + + Objects.requireNonNull(pageInfos); + if (pageInfos.size() != citationKeys.size()) { + throw new IllegalArgumentException("pageInfos.size != citationKeys.size"); + } + CitationGroup group = frontend.createCitationGroup(doc, + citationKeys, + pageInfos, + citationType, + position, + insertSpaceAfter); + + final boolean withText = citationType.withText(); + + if (withText) { + XTextCursor fillCursor = frontend.getFillCursorForCitationGroup(doc, group); + + UpdateCitationMarkers.fillCitationMarkInCursor(doc, fillCursor, citationText, withText, style); + + frontend.cleanFillCursorForCitationGroup(doc, group); + } + position.collapseToEnd(); + } + +} diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java index 082d94a7fdf..5108c94c8b3 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyle.java @@ -291,20 +291,20 @@ private boolean isUpToDate() { } } - private void readFormatFile(Reader in) throws IOException { + private void readFormatFile(Reader input) throws IOException { // First read all the contents of the file: - StringBuilder sb = new StringBuilder(); - int c; - while ((c = in.read()) != -1) { - sb.append((char) c); + StringBuilder stringBuilder = new StringBuilder(); + int chr; + while ((chr = input.read()) != -1) { + stringBuilder.append((char) chr); } // Store a local copy for viewing - localCopy = sb.toString(); + localCopy = stringBuilder.toString(); // Break into separate lines: - String[] lines = sb.toString().split("\n"); + String[] lines = stringBuilder.toString().split("\n"); BibStyleMode mode = BibStyleMode.NONE; for (String line1 : lines) { @@ -386,11 +386,12 @@ private void handleStructureLine(String line) { if ((index > 0) && (index < (line.length() - 1))) { try { - String formatString = line.substring(index + 1); + final String typeName = line.substring(0, index); + final String formatString = line.substring(index + 1); Layout layout = new LayoutHelper(new StringReader(formatString), this.prefs).getLayoutFromText(); - EntryType type = EntryTypeFactory.parse(line.substring(0, index)); + EntryType type = EntryTypeFactory.parse(typeName); - if (!isDefaultLayoutPresent && line.substring(0, index).equals(OOBibStyle.DEFAULT_MARK)) { + if (!isDefaultLayoutPresent && OOBibStyle.DEFAULT_MARK.equals(typeName)) { isDefaultLayoutPresent = true; defaultBibLayout = layout; } else { @@ -437,11 +438,11 @@ private void handleJournalsLine(String line) { } public Layout getReferenceFormat(EntryType type) { - Layout l = bibLayout.get(type); - if (l == null) { + Layout layout = bibLayout.get(type); + if (layout == null) { return defaultBibLayout; } else { - return l; + return layout; } } @@ -464,7 +465,7 @@ public String getNumCitationMarker(List number, int minGroupingCount, b // Sort the numbers: List lNum = new ArrayList<>(number); Collections.sort(lNum); - StringBuilder sb = new StringBuilder(bracketBefore); + StringBuilder stringBuilder = new StringBuilder(bracketBefore); int combineFrom = -1; int written = 0; for (int i = 0; i < lNum.size(); i++) { @@ -476,9 +477,9 @@ public String getNumCitationMarker(List number, int minGroupingCount, b } else { // Add single entry: if (i > 0) { - sb.append(getStringCitProperty(CITATION_SEPARATOR)); + stringBuilder.append(getStringCitProperty(CITATION_SEPARATOR)); } - sb.append(lNum.get(i) > 0 ? String.valueOf(lNum.get(i)) : OOBibStyle.UNDEFINED_CITATION_MARKER); + stringBuilder.append(lNum.get(i) > 0 ? String.valueOf(lNum.get(i)) : OOBibStyle.UNDEFINED_CITATION_MARKER); written++; } } else { @@ -486,20 +487,20 @@ public String getNumCitationMarker(List number, int minGroupingCount, b // Check if it ends here: if ((i == (lNum.size() - 1)) || (lNum.get(i + 1) != (i1 + 1))) { if (written > 0) { - sb.append(getStringCitProperty(CITATION_SEPARATOR)); + stringBuilder.append(getStringCitProperty(CITATION_SEPARATOR)); } if ((minGroupingCount > 0) && (((i1 + 1) - combineFrom) >= minGroupingCount)) { - sb.append(combineFrom); - sb.append(getStringCitProperty(GROUPED_NUMBERS_SEPARATOR)); - sb.append(i1); + stringBuilder.append(combineFrom); + stringBuilder.append(getStringCitProperty(GROUPED_NUMBERS_SEPARATOR)); + stringBuilder.append(i1); written++; } else { // Either we should never group, or there aren't enough // entries in this case to group. Output all: for (int jj = combineFrom; jj <= i1; jj++) { - sb.append(jj); + stringBuilder.append(jj); if (jj < i1) { - sb.append(getStringCitProperty(CITATION_SEPARATOR)); + stringBuilder.append(getStringCitProperty(CITATION_SEPARATOR)); } written++; } @@ -509,8 +510,8 @@ public String getNumCitationMarker(List number, int minGroupingCount, b // If it doesn't end here, just keep iterating. } } - sb.append(bracketAfter); - return sb.toString(); + stringBuilder.append(bracketAfter); + return stringBuilder.toString(); } /* end_old */ @@ -591,13 +592,13 @@ public String getCitationMarker(List entries, Map entries, String[] uniquefiers, int from, int to) { String separator = getStringCitProperty(UNIQUEFIER_SEPARATOR); - StringBuilder sb = new StringBuilder(uniquefiers[from]); + StringBuilder stringBuilder = new StringBuilder(uniquefiers[from]); for (int i = from + 1; i <= to; i++) { - sb.append(separator); - sb.append(uniquefiers[i]); + stringBuilder.append(separator); + stringBuilder.append(uniquefiers[i]); entries.set(i, null); } - uniquefiers[from] = sb.toString(); + uniquefiers[from] = stringBuilder.toString(); } /* end_old */ @@ -622,7 +623,7 @@ private String getAuthorYearParenthesisMarker(List entries, Map entries, Map 0) { - sb.append(citationSeparator); + stringBuilder.append(citationSeparator); } BibDatabase currentDatabase = database.get(currentEntry); @@ -641,17 +642,17 @@ private String getAuthorYearParenthesisMarker(List entries, Map entries, Map entries, Map 0 ? unlimA : maxA; if (i > 0) { - sb.append(citationSeparator); + stringBuilder.append(citationSeparator); } String author = getCitationMarkerField(currentEntry, currentDatabase, authorField); String authorString = createAuthorList(author, maxAuthors, andString, yearSep); - sb.append(authorString); - sb.append(startBrace); + stringBuilder.append(authorString); + stringBuilder.append(startBrace); String year = getCitationMarkerField(currentEntry, currentDatabase, yearField); if (year != null) { - sb.append(year); + stringBuilder.append(year); } if ((uniquefiers != null) && (uniquefiers[i] != null)) { - sb.append(uniquefiers[i]); + stringBuilder.append(uniquefiers[i]); } - sb.append(endBrace); + stringBuilder.append(endBrace); } - return sb.toString(); + return stringBuilder.toString(); } /* end_old */ @@ -757,15 +758,15 @@ private String getCitationMarkerField(BibEntry entry, BibDatabase database, Stri * @return The author name, or an empty String if inapplicable. */ private String getAuthorLastName(AuthorList al, int number) { - StringBuilder sb = new StringBuilder(); + StringBuilder stringBuilder = new StringBuilder(); if (al.getNumberOfAuthors() > number) { Author a = al.getAuthor(number); - a.getVon().filter(von -> !von.isEmpty()).ifPresent(von -> sb.append(von).append(' ')); - sb.append(a.getLast().orElse("")); + a.getVon().filter(von -> !von.isEmpty()).ifPresent(von -> stringBuilder.append(von).append(' ')); + stringBuilder.append(a.getLast().orElse("")); } - return sb.toString(); + return stringBuilder.toString(); } /* end_old */ @@ -896,12 +897,12 @@ public int compareTo(OOBibStyle other) { } @Override - public boolean equals(Object o) { - if (this == o) { + public boolean equals(Object object) { + if (this == object) { return true; } - if (o instanceof OOBibStyle) { - OOBibStyle otherStyle = (OOBibStyle) o; + if (object instanceof OOBibStyle) { + OOBibStyle otherStyle = (OOBibStyle) object; return Objects.equals(path, otherStyle.path) && Objects.equals(name, otherStyle.name) && Objects.equals(citProperties, otherStyle.citProperties) @@ -923,28 +924,28 @@ private String createAuthorList(String author, int maxAuthors, String andString, String etAlString = getStringCitProperty(ET_AL_STRING); // The String to represent authors that are not mentioned, e.g. " et al." String authorSep = getStringCitProperty(AUTHOR_SEPARATOR); // The String to add between author names except the last two, e.g. ", ". String oxfordComma = getStringCitProperty(OXFORD_COMMA); // The String to put after the second to last author in case of three or more authors - StringBuilder sb = new StringBuilder(); + StringBuilder stringBuilder = new StringBuilder(); AuthorList al = AuthorList.parse(author); if (!al.isEmpty()) { - sb.append(getAuthorLastName(al, 0)); + stringBuilder.append(getAuthorLastName(al, 0)); } if ((al.getNumberOfAuthors() > 1) && ((al.getNumberOfAuthors() <= maxAuthors) || (maxAuthors < 0))) { int j = 1; while (j < (al.getNumberOfAuthors() - 1)) { - sb.append(authorSep); - sb.append(getAuthorLastName(al, j)); + stringBuilder.append(authorSep); + stringBuilder.append(getAuthorLastName(al, j)); j++; } if (al.getNumberOfAuthors() > 2) { - sb.append(oxfordComma); + stringBuilder.append(oxfordComma); } - sb.append(andString); - sb.append(getAuthorLastName(al, al.getNumberOfAuthors() - 1)); + stringBuilder.append(andString); + stringBuilder.append(getAuthorLastName(al, al.getNumberOfAuthors() - 1)); } else if (al.getNumberOfAuthors() > maxAuthors) { - sb.append(etAlString); + stringBuilder.append(etAlString); } - sb.append(yearSep); - return sb.toString(); + stringBuilder.append(yearSep); + return stringBuilder.toString(); } /* end_old */ @@ -1078,8 +1079,8 @@ public OOText getNumCitationMarkerForBibliography(CitationMarkerNumericBibEntry return OOBibStyleGetNumCitationMarker.getNumCitationMarkerForBibliography(this, entry); } - public OOText getNormalizedCitationMarker(CitationMarkerNormEntry ce) { - return OOBibStyleGetCitationMarker.getNormalizedCitationMarker(this, ce, Optional.empty()); + public OOText getNormalizedCitationMarker(CitationMarkerNormEntry entry) { + return OOBibStyleGetCitationMarker.getNormalizedCitationMarker(this, entry, Optional.empty()); } /** @@ -1158,10 +1159,6 @@ public String getGroupedNumbersSeparator() { return getStringCitProperty(OOBibStyle.GROUPED_NUMBERS_SEPARATOR); } - private boolean getBooleanProperty(String propName) { - return (Boolean) properties.get(propName); - } - private String getStringProperty(String propName) { return (String) properties.get(propName); } @@ -1308,12 +1305,9 @@ public OOText getFormattedBibliographyTitle() { OOBibStyle style = this; OOText title = style.getReferenceHeaderText(); String parStyle = style.getReferenceHeaderParagraphFormat(); - if (parStyle != null) { - title = OOFormat.paragraph(title, parStyle); - } else { - title = OOFormat.paragraph(title); - } - return title; + return (parStyle == null + ? OOFormat.paragraph(title) + : OOFormat.paragraph(title, parStyle)); } } diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetCitationMarker.java index deb1a306913..2e5227d080e 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetCitationMarker.java @@ -38,21 +38,21 @@ private OOBibStyleGetCitationMarker() { * @return The author name, or an empty String if inapplicable. */ private static String getAuthorLastName(AuthorList authorList, int number) { - StringBuilder sb = new StringBuilder(); + StringBuilder stringBuilder = new StringBuilder(); if (authorList.getNumberOfAuthors() > number) { Author author = authorList.getAuthor(number); // "von " if von exists Optional von = author.getVon(); if (von.isPresent() && !von.get().isEmpty()) { - sb.append(von.get()); - sb.append(' '); + stringBuilder.append(von.get()); + stringBuilder.append(' '); } // last name if it exists - sb.append(author.getLast().orElse("")); + stringBuilder.append(author.getLast().orElse("")); } - return sb.toString(); + return stringBuilder.toString(); } private static String markupAuthorName(OOBibStyle style, String name) { @@ -127,7 +127,7 @@ private static String formatAuthorList(OOBibStyle style, // of three or more authors: (A, B[,] and C) String oxfordComma = style.getOxfordComma(); - StringBuilder sb = new StringBuilder(); + StringBuilder stringBuilder = new StringBuilder(); final int nAuthors = authorList.getNumberOfAuthors(); @@ -149,11 +149,11 @@ private static String formatAuthorList(OOBibStyle style, : Math.min(maxAuthorsBeforeEtAl, nAuthors)); if (nAuthorsToEmit >= 1) { - sb.append(style.getAuthorsPartMarkupBefore()); - sb.append(style.getAuthorNamesListMarkupBefore()); + stringBuilder.append(style.getAuthorsPartMarkupBefore()); + stringBuilder.append(style.getAuthorNamesListMarkupBefore()); // The first author String name = getAuthorLastName(authorList, 0); - sb.append(markupAuthorName(style, name)); + stringBuilder.append(markupAuthorName(style, name)); } if (nAuthors >= 2) { @@ -162,19 +162,19 @@ private static String formatAuthorList(OOBibStyle style, // Emit last names, except for the last author int j = 1; while (j < (nAuthors - 1)) { - sb.append(authorSep); + stringBuilder.append(authorSep); String name = getAuthorLastName(authorList, j); - sb.append(markupAuthorName(style, name)); + stringBuilder.append(markupAuthorName(style, name)); j++; } // oxfordComma if at least 3 authors if (nAuthors >= 3) { - sb.append(oxfordComma); + stringBuilder.append(oxfordComma); } // Emit " and "+"LastAuthor" - sb.append(andString); + stringBuilder.append(andString); String name = getAuthorLastName(authorList, nAuthors - 1); - sb.append(markupAuthorName(style, name)); + stringBuilder.append(markupAuthorName(style, name)); } else { // Emit last names up to nAuthorsToEmit. @@ -185,9 +185,9 @@ private static String formatAuthorList(OOBibStyle style, if (maxAuthorsBeforeEtAl > 1) { int j = 1; while (j < nAuthorsToEmit) { - sb.append(authorSep); + stringBuilder.append(authorSep); String name = getAuthorLastName(authorList, j); - sb.append(markupAuthorName(style, name)); + stringBuilder.append(markupAuthorName(style, name)); j++; } } @@ -195,15 +195,15 @@ private static String formatAuthorList(OOBibStyle style, } if (nAuthorsToEmit >= 1) { - sb.append(style.getAuthorNamesListMarkupAfter()); + stringBuilder.append(style.getAuthorNamesListMarkupAfter()); } if (nAuthors >= 2 && !emitAllAuthors) { - sb.append(etAlString); + stringBuilder.append(etAlString); } - sb.append(style.getAuthorsPartMarkupAfter()); - return sb.toString(); + stringBuilder.append(style.getAuthorsPartMarkupAfter()); + return stringBuilder.toString(); } /** @@ -279,15 +279,15 @@ private static String getCitationMarkerField(OOBibStyle style, return ""; } - FieldAndContent fc = optionalFieldAndContent.get(); - String result = style.getFieldFormatter().format(fc.content); + FieldAndContent fieldAndContent = optionalFieldAndContent.get(); + String result = style.getFieldFormatter().format(fieldAndContent.content); // If the field we found is mentioned in authorFieldNames and // content has a pair of braces around it, we add a pair of // braces around the result, so that AuthorList.parse does not split // the content. final OrFields fieldsToRebrace = style.getAuthorFieldNames(); - if (fieldsToRebrace.contains(fc.field) && StringUtil.isInCurlyBrackets(fc.content)) { + if (fieldsToRebrace.contains(fieldAndContent.field) && StringUtil.isInCurlyBrackets(fieldAndContent.content)) { result = "{" + result + "}"; } return result; @@ -406,11 +406,11 @@ private static OOText getAuthorYearParenthesisMarker2(OOBibStyle style, String pageInfoSeparator = style.getPageInfoSeparator(); String uniquefierSeparator = style.getUniquefierSeparator(); - StringBuilder sb = new StringBuilder(); - sb.append(style.getCitationGroupMarkupBefore()); + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append(style.getCitationGroupMarkupBefore()); if (inParenthesis) { - sb.append(startBrace); // shared parenthesis + stringBuilder.append(startBrace); // shared parenthesis } for (int j = 0; j < entries.size(); j++) { @@ -422,19 +422,19 @@ private static OOText getAuthorYearParenthesisMarker2(OOBibStyle style, // Just add our uniqueLetter String uniqueLetter = entry.getUniqueLetter().orElse(null); if (uniqueLetter != null) { - sb.append(uniquefierSeparator); - sb.append(uniqueLetter); + stringBuilder.append(uniquefierSeparator); + stringBuilder.append(uniqueLetter); } // And close the brace, if we are the last in the group. if (!inParenthesis && endingAGroup) { - sb.append(endBrace); + stringBuilder.append(endBrace); } continue; } if (j > 0) { - sb.append(citationSeparator); + stringBuilder.append(citationSeparator); } StringBuilder pageInfoPart = new StringBuilder(""); @@ -449,9 +449,9 @@ private static OOText getAuthorYearParenthesisMarker2(OOBibStyle style, final boolean isUnresolved = entry.getLookupResult().isEmpty(); if (isUnresolved) { - sb.append(String.format("Unresolved(%s)", entry.getCitationKey())); + stringBuilder.append(String.format("Unresolved(%s)", entry.getCitationKey())); if (purpose != AuthorYearMarkerPurpose.NORMALIZED) { - sb.append(pageInfoPart); + stringBuilder.append(pageInfoPart); } } else { @@ -467,40 +467,40 @@ private static OOText getAuthorYearParenthesisMarker2(OOBibStyle style, AuthorList authorList = getAuthorList(style, db); String authorString = formatAuthorList(style, authorList, maxAuthors, andString); - sb.append(authorString); - sb.append(yearSep); + stringBuilder.append(authorString); + stringBuilder.append(yearSep); if (!inParenthesis) { - sb.append(startBrace); // parenthesis before year + stringBuilder.append(startBrace); // parenthesis before year } String year = getCitationMarkerField(style, db, yearFieldNames); if (year != null) { - sb.append(year); + stringBuilder.append(year); } if (purpose != AuthorYearMarkerPurpose.NORMALIZED) { String uniqueLetter = entry.getUniqueLetter().orElse(null); if (uniqueLetter != null) { - sb.append(uniqueLetter); + stringBuilder.append(uniqueLetter); } } if (purpose != AuthorYearMarkerPurpose.NORMALIZED) { - sb.append(pageInfoPart); + stringBuilder.append(pageInfoPart); } if (!inParenthesis && endingAGroup) { - sb.append(endBrace); // parenthesis after year + stringBuilder.append(endBrace); // parenthesis after year } } } // for j if (inParenthesis) { - sb.append(endBrace); // shared parenthesis + stringBuilder.append(endBrace); // shared parenthesis } - sb.append(style.getCitationGroupMarkupAfter()); - return OOText.fromString(sb.toString()); + stringBuilder.append(style.getCitationGroupMarkupAfter()); + return OOText.fromString(stringBuilder.toString()); } /** @@ -638,9 +638,9 @@ static OOText getNormalizedCitationMarker(OOBibStyle style, int[] nAuthorsToEmitRevised = new int[nEntries]; for (int i = 0; i < nEntries; i++) { CitationMarkerEntry entry = citationMarkerEntries.get(i); - int n = calculateNAuthorsToEmit(style, entry); - nAuthorsToEmit[i] = n; - nAuthorsToEmitRevised[i] = n; + int nAuthors = calculateNAuthorsToEmit(style, entry); + nAuthorsToEmit[i] = nAuthors; + nAuthorsToEmitRevised[i] = nAuthors; } boolean[] startsNewGroup = new boolean[nEntries]; diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetNumCitationMarker.java b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetNumCitationMarker.java index 5dce4e8caa1..60b5222cf5b 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetNumCitationMarker.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOBibStyleGetNumCitationMarker.java @@ -53,23 +53,23 @@ public static OOText getNumCitationMarkerForBibliography(OOBibStyle style, // prefer BRACKET_BEFORE_IN_LIST and BRACKET_AFTER_IN_LIST String bracketBefore = style.getBracketBeforeInListWithFallBack(); String bracketAfter = style.getBracketAfterInListWithFallBack(); - StringBuilder sb = new StringBuilder(); - sb.append(style.getCitationGroupMarkupBefore()); - sb.append(bracketBefore); + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append(style.getCitationGroupMarkupBefore()); + stringBuilder.append(bracketBefore); final Optional current = entry.getNumber(); - sb.append(current.isPresent() + stringBuilder.append(current.isPresent() ? String.valueOf(current.get()) : (OOBibStyle.UNDEFINED_CITATION_MARKER + entry.getCitationKey())); - sb.append(bracketAfter); - sb.append(style.getCitationGroupMarkupAfter()); - return OOText.fromString(sb.toString()); + stringBuilder.append(bracketAfter); + stringBuilder.append(style.getCitationGroupMarkupAfter()); + return OOText.fromString(stringBuilder.toString()); } /* * emitBlock : a helper for getNumCitationMarker2 * * Given a block containing either a single entry or two or more - * entries that are joinable into an "i-j" form, append to {@code sb} the + * entries that are joinable into an "i-j" form, append to {@code stringBuilder} the * formatted text. * * Assumes: @@ -91,7 +91,7 @@ public static OOText getNumCitationMarkerForBibliography(OOBibStyle style, private static void emitBlock(List block, OOBibStyle style, int minGroupingCount, - StringBuilder sb) { + StringBuilder stringBuilder) { final int blockSize = block.size(); if (blockSize == 0) { @@ -102,14 +102,14 @@ private static void emitBlock(List block, // Add single entry: CitationMarkerNumericEntry entry = block.get(0); final Optional num = entry.getNumber(); - sb.append(num.isEmpty() - ? (OOBibStyle.UNDEFINED_CITATION_MARKER + entry.getCitationKey()) - : String.valueOf(num.get())); + stringBuilder.append(num.isEmpty() + ? (OOBibStyle.UNDEFINED_CITATION_MARKER + entry.getCitationKey()) + : String.valueOf(num.get())); // Emit pageInfo Optional pageInfo = entry.getPageInfo(); if (pageInfo.isPresent()) { - sb.append(style.getPageInfoSeparator()); - sb.append(OOText.toString(pageInfo.get())); + stringBuilder.append(style.getPageInfoSeparator()); + stringBuilder.append(OOText.toString(pageInfo.get())); } return; } @@ -146,17 +146,17 @@ private static void emitBlock(List block, } // Emit: "first-last" - sb.append(first); - sb.append(style.getGroupedNumbersSeparator()); - sb.append(last); + stringBuilder.append(first); + stringBuilder.append(style.getGroupedNumbersSeparator()); + stringBuilder.append(last); } else { // Emit: first, first+1,..., last for (int j = 0; j < blockSize; j++) { if (j > 0) { - sb.append(style.getCitationSeparator()); + stringBuilder.append(style.getCitationSeparator()); } - sb.append(block.get(j).getNumber().get()); + stringBuilder.append(block.get(j).getNumber().get()); } } return; @@ -194,15 +194,15 @@ public static OOText getNumCitationMarker2(OOBibStyle style, final boolean joinIsDisabled = (minGroupingCount <= 0); final int nCitations = entries.size(); - String bracketBefore = style.getBracketBefore(); - String bracketAfter = style.getBracketAfter(); + final String bracketBefore = style.getBracketBefore(); + final String bracketAfter = style.getBracketAfter(); // Sort a copy of entries List sorted = OOListUtil.map(entries, e -> e); sorted.sort(OOBibStyleGetNumCitationMarker::compareCitationMarkerNumericEntry); // "[" - StringBuilder sb = new StringBuilder(bracketBefore); + StringBuilder stringBuilder = new StringBuilder(bracketBefore); /* * Original: @@ -248,12 +248,12 @@ public static OOText getNumCitationMarker2(OOBibStyle style, } } - if (nextBlock.size() > 0) { + if (!nextBlock.isEmpty()) { // emit current block if (blocksEmitted) { - sb.append(style.getCitationSeparator()); + stringBuilder.append(style.getCitationSeparator()); } - emitBlock(currentBlock, style, minGroupingCount, sb); + emitBlock(currentBlock, style, minGroupingCount, stringBuilder); blocksEmitted = true; currentBlock = nextBlock; nextBlock = new ArrayList<>(); @@ -261,21 +261,21 @@ public static OOText getNumCitationMarker2(OOBibStyle style, } - if (nextBlock.size() != 0) { + if (!nextBlock.isEmpty()) { throw new IllegalStateException("impossible: (nextBlock.size() != 0) after loop"); } - if (currentBlock.size() > 0) { + if (!currentBlock.isEmpty()) { // We are emitting a block if (blocksEmitted) { - sb.append(style.getCitationSeparator()); + stringBuilder.append(style.getCitationSeparator()); } - emitBlock(currentBlock, style, minGroupingCount, sb); + emitBlock(currentBlock, style, minGroupingCount, stringBuilder); } // Emit: "]" - sb.append(bracketAfter); - return OOText.fromString(sb.toString()); + stringBuilder.append(bracketAfter); + return OOText.fromString(stringBuilder.toString()); } } diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java b/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java index 4bc3fac6191..ea311193068 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOFormatBibliography.java @@ -49,8 +49,8 @@ public static OOText formatBibliographyBody(CitationGroups cgs, StringBuilder stringBuilder = new StringBuilder(); - for (CitedKey ck : bibliography.values()) { - OOText entryText = formatBibliographyEntry(cgs, ck, style, alwaysAddCitedOnPages); + for (CitedKey citedKey : bibliography.values()) { + OOText entryText = formatBibliographyEntry(cgs, citedKey, style, alwaysAddCitedOnPages); stringBuilder.append(entryText.toString()); } @@ -61,29 +61,29 @@ public static OOText formatBibliographyBody(CitationGroups cgs, * @return A paragraph. Includes label and "Cited on pages". */ public static OOText formatBibliographyEntry(CitationGroups cgs, - CitedKey ck, + CitedKey citedKey, OOBibStyle style, boolean alwaysAddCitedOnPages) { - StringBuilder sb = new StringBuilder(); + StringBuilder stringBuilder = new StringBuilder(); // insert marker "[1]" if (style.isNumberEntries()) { - sb.append(style.getNumCitationMarkerForBibliography(ck).toString()); + stringBuilder.append(style.getNumCitationMarkerForBibliography(citedKey).toString()); } else { // !style.isNumberEntries() : emit no prefix // Note: We might want [citationKey] prefix for style.isCitationKeyCiteMarkers(); } // Add entry body - sb.append(formatBibliographyEntryBody(ck, style).toString()); + stringBuilder.append(formatBibliographyEntryBody(citedKey, style).toString()); // Add "Cited on pages" - if (ck.getLookupResult().isEmpty() || alwaysAddCitedOnPages) { - sb.append(formatCitedOnPages(cgs, ck).toString()); + if (citedKey.getLookupResult().isEmpty() || alwaysAddCitedOnPages) { + stringBuilder.append(formatCitedOnPages(cgs, citedKey).toString()); } // Add paragraph - OOText entryText = OOText.fromString(sb.toString()); + OOText entryText = OOText.fromString(stringBuilder.toString()); String parStyle = style.getReferenceParagraphFormat(); return OOFormat.paragraph(entryText, parStyle); } @@ -91,20 +91,20 @@ public static OOText formatBibliographyEntry(CitationGroups cgs, /** * @return just the body of a bibliography entry. No label, "Cited on pages" or paragraph. */ - public static OOText formatBibliographyEntryBody(CitedKey ck, OOBibStyle style) { - if (ck.getLookupResult().isEmpty()) { + public static OOText formatBibliographyEntryBody(CitedKey citedKey, OOBibStyle style) { + if (citedKey.getLookupResult().isEmpty()) { // Unresolved entry - return OOText.fromString(String.format("Unresolved(%s)", ck.citationKey)); + return OOText.fromString(String.format("Unresolved(%s)", citedKey.citationKey)); } else { // Resolved entry, use the layout engine - BibEntry bibentry = ck.getLookupResult().get().entry; + BibEntry bibentry = citedKey.getLookupResult().get().entry; Layout layout = style.getReferenceFormat(bibentry.getType()); layout.setPostFormatter(POSTFORMATTER); return formatFullReferenceOfBibEntry(layout, bibentry, - ck.getLookupResult().get().database, - ck.getUniqueLetter().orElse(null)); + citedKey.getLookupResult().get().database, + citedKey.getUniqueLetter().orElse(null)); } } @@ -147,27 +147,27 @@ private static OOText formatFullReferenceOfBibEntry(Layout layout, } /** - * Format links to citations of the source (ck). + * Format links to citations of the source (citedKey). * * Requires reference marks for the citation groups. * * - The links are created as references that show page numbers of the reference marks. * - We do not control the text shown, that is provided by OpenOffice. */ - private static OOText formatCitedOnPages(CitationGroups cgs, CitedKey ck) { + private static OOText formatCitedOnPages(CitationGroups cgs, CitedKey citedKey) { if (!cgs.citationGroupsProvideReferenceMarkNameForLinking()) { return OOText.fromString(""); } - StringBuilder sb = new StringBuilder(); + StringBuilder stringBuilder = new StringBuilder(); - String prefix = String.format(" (%s: ", Localization.lang("Cited on pages")); - String suffix = ")"; - sb.append(prefix); + final String prefix = String.format(" (%s: ", Localization.lang("Cited on pages")); + final String suffix = ")"; + stringBuilder.append(prefix); List citationGroups = new ArrayList<>(); - for (CitationPath p : ck.getCitationPaths()) { + for (CitationPath p : citedKey.getCitationPaths()) { CitationGroupId groupId = p.group; Optional group = cgs.getCitationGroup(groupId); if (group.isEmpty()) { @@ -183,18 +183,18 @@ private static OOText formatCitedOnPages(CitationGroups cgs, CitedKey ck) { return (aa.compareTo(bb)); }); - int i = 0; + int index = 0; for (CitationGroup group : citationGroups) { - if (i > 0) { - sb.append(", "); + if (index > 0) { + stringBuilder.append(", "); } String markName = group.getReferenceMarkNameForLinking().orElseThrow(IllegalStateException::new); OOText xref = OOFormat.formatReferenceToPageNumberOfReferenceMark(markName); - sb.append(xref.toString()); - i++; + stringBuilder.append(xref.toString()); + index++; } - sb.append(suffix); - return OOText.fromString(sb.toString()); + stringBuilder.append(suffix); + return OOText.fromString(stringBuilder.toString()); } } diff --git a/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java b/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java index 1aaeb538930..affbc7584ae 100644 --- a/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java +++ b/src/main/java/org/jabref/logic/openoffice/style/OOProcessAuthorYearMarkers.java @@ -88,8 +88,8 @@ private static void createUniqueLetters(CitedKeys sortedCitedKeys, CitationGroup // according to their order in clashingKeys. int nextUniqueLetter = 'a'; for (String citationKey : clashingKeys) { - String ul = String.valueOf((char) nextUniqueLetter); - sortedCitedKeys.get(citationKey).setUniqueLetter(Optional.of(ul)); + String uniqueLetter = String.valueOf((char) nextUniqueLetter); + sortedCitedKeys.get(citationKey).setUniqueLetter(Optional.of(uniqueLetter)); nextUniqueLetter++; } } diff --git a/src/main/java/org/jabref/model/openoffice/CitationEntry.java b/src/main/java/org/jabref/model/openoffice/CitationEntry.java index 219e71eb0d1..0d702c860ab 100644 --- a/src/main/java/org/jabref/model/openoffice/CitationEntry.java +++ b/src/main/java/org/jabref/model/openoffice/CitationEntry.java @@ -37,12 +37,12 @@ public int compareTo(CitationEntry other) { } @Override - public boolean equals(Object o) { - if (this == o) { + public boolean equals(Object object) { + if (this == object) { return true; } - if (o instanceof CitationEntry) { - CitationEntry other = (CitationEntry) o; + if (object instanceof CitationEntry) { + CitationEntry other = (CitationEntry) object; return Objects.equals(this.refMarkName, other.refMarkName); } return false; diff --git a/src/main/java/org/jabref/model/openoffice/style/CitationGroupId.java b/src/main/java/org/jabref/model/openoffice/style/CitationGroupId.java index 6ba6b760cb6..baaa931214c 100644 --- a/src/main/java/org/jabref/model/openoffice/style/CitationGroupId.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitationGroupId.java @@ -4,15 +4,15 @@ * Identifies a citation group in a document. */ public class CitationGroupId { - String id; - public CitationGroupId(String id) { - this.id = id; + String groupId; + public CitationGroupId(String groupId) { + this.groupId = groupId; } /** * CitationEntry needs some string identifying the group that it can pass back later. */ public String citationGroupIdAsString() { - return id; + return groupId; } } diff --git a/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java b/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java index b03028b76ef..e5e642fa652 100644 --- a/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java @@ -131,10 +131,9 @@ public void setGlobalOrder(List globalOrder) { this.globalOrder = Optional.of(globalOrder); // Propagate to each CitationGroup - int i = 0; - for (CitationGroupId groupId : globalOrder) { + for (int i = 0; i < globalOrder.size(); i++) { + CitationGroupId groupId = globalOrder.get(i); citationGroupsUnordered.get(groupId).setIndexInGlobalOrder(Optional.of(i)); - i++; } } diff --git a/src/main/java/org/jabref/model/openoffice/style/CitedKeys.java b/src/main/java/org/jabref/model/openoffice/style/CitedKeys.java index 898fadbebe9..059c1b6123a 100644 --- a/src/main/java/org/jabref/model/openoffice/style/CitedKeys.java +++ b/src/main/java/org/jabref/model/openoffice/style/CitedKeys.java @@ -45,11 +45,11 @@ void sortByComparator(Comparator entryComparator) { } void numberCitedKeysInCurrentOrder() { - int i = 1; + int index = 1; for (CitedKey ck : data.values()) { if (ck.getLookupResult().isPresent()) { - ck.setNumber(Optional.of(i)); - i++; + ck.setNumber(Optional.of(index)); + index++; } else { // Unresolved citations do not get a number. ck.setNumber(Optional.empty()); diff --git a/src/main/java/org/jabref/model/openoffice/style/PageInfo.java b/src/main/java/org/jabref/model/openoffice/style/PageInfo.java index ec3a8436dcf..1ff87569a3b 100644 --- a/src/main/java/org/jabref/model/openoffice/style/PageInfo.java +++ b/src/main/java/org/jabref/model/openoffice/style/PageInfo.java @@ -19,7 +19,7 @@ public static Optional normalizePageInfo(Optional optionalText) } String str = OOText.toString(optionalText.get()); String trimmed = str.trim(); - if (trimmed.equals("")) { + if ("".equals(trimmed)) { return Optional.empty(); } return Optional.of(OOText.fromString(trimmed)); diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoCursor.java b/src/main/java/org/jabref/model/openoffice/uno/UnoCursor.java index 1770b6957c5..e761a56e12f 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoCursor.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoCursor.java @@ -39,7 +39,7 @@ public static Optional getTextCursorOfTextContentAnchor(XTextConten return Optional.of(markAnchor.getText().createTextCursorByRange(markAnchor)); } - public static XTextCursor createTextCursorByRange(XTextRange r) { - return r.getText().createTextCursorByRange(r); + public static XTextCursor createTextCursorByRange(XTextRange range) { + return range.getText().createTextCursorByRange(range); } } diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoStyle.java b/src/main/java/org/jabref/model/openoffice/uno/UnoStyle.java index dece8978713..cd4065ba8b3 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoStyle.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoStyle.java @@ -25,10 +25,10 @@ private static Optional getStyleFromFamily(XTextDocument doc, String fam WrappedTargetException { XStyleFamiliesSupplier fss = UnoCast.cast(XStyleFamiliesSupplier.class, doc).get(); - XNameAccess fs = UnoCast.cast(XNameAccess.class, fss.getStyleFamilies()).get(); + XNameAccess families = UnoCast.cast(XNameAccess.class, fss.getStyleFamilies()).get(); XNameContainer xFamily; try { - xFamily = UnoCast.cast(XNameContainer.class, fs.getByName(familyName)).get(); + xFamily = UnoCast.cast(XNameContainer.class, families.getByName(familyName)).get(); } catch (NoSuchElementException ex) { String msg = String.format("Style family name '%s' is not recognized", familyName); throw new java.lang.IllegalArgumentException(msg, ex); diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoUndo.java b/src/main/java/org/jabref/model/openoffice/uno/UnoUndo.java index b75bee17f3e..4f08bb0ed5c 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoUndo.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoUndo.java @@ -25,17 +25,17 @@ public static Optional getXUndoManager(XTextDocument doc) { * document's undo stack is left in an inconsistent state. */ public static void enterUndoContext(XTextDocument doc, String title) { - Optional um = getXUndoManager(doc); - if (um.isPresent()) { - um.get().enterUndoContext(title); + Optional undoManager = getXUndoManager(doc); + if (undoManager.isPresent()) { + undoManager.get().enterUndoContext(title); } } public static void leaveUndoContext(XTextDocument doc) { - Optional um = getXUndoManager(doc); - if (um.isPresent()) { + Optional undoManager = getXUndoManager(doc); + if (undoManager.isPresent()) { try { - um.get().leaveUndoContext(); + undoManager.get().leaveUndoContext(); } catch (InvalidStateException ex) { throw new IllegalStateException("leaveUndoContext reported InvalidStateException"); } diff --git a/src/main/java/org/jabref/model/openoffice/uno/UnoUserDefinedProperty.java b/src/main/java/org/jabref/model/openoffice/uno/UnoUserDefinedProperty.java index 634edb0c57b..f5ec43f3211 100644 --- a/src/main/java/org/jabref/model/openoffice/uno/UnoUserDefinedProperty.java +++ b/src/main/java/org/jabref/model/openoffice/uno/UnoUserDefinedProperty.java @@ -61,8 +61,8 @@ public static Optional getStringValue(XTextDocument doc, String property throw new java.lang.IllegalArgumentException("getting UserDefinedProperties as XPropertySet failed"); } try { - String v = propertySet.get().getPropertyValue(property).toString(); - return Optional.ofNullable(v); + String value = propertySet.get().getPropertyValue(property).toString(); + return Optional.ofNullable(value); } catch (UnknownPropertyException ex) { return Optional.empty(); } diff --git a/src/main/java/org/jabref/model/openoffice/util/OOListUtil.java b/src/main/java/org/jabref/model/openoffice/util/OOListUtil.java index 1fe617ed99a..59295c798fe 100644 --- a/src/main/java/org/jabref/model/openoffice/util/OOListUtil.java +++ b/src/main/java/org/jabref/model/openoffice/util/OOListUtil.java @@ -13,19 +13,19 @@ public static List map(List list, Function fun) { return list.stream().map(e -> fun.apply(e)).collect(Collectors.toList()); } - /** Integers 0..(n-1) */ - public static List makeIndices(int n) { - return Stream.iterate(0, i -> i + 1).limit(n).collect(Collectors.toList()); + /** Integers 0..(len-1) */ + public static List makeIndices(int len) { + return Stream.iterate(0, i -> i + 1).limit(len).collect(Collectors.toList()); } /** Return indices so that list.get(indices.get(i)) is sorted. */ public static List order(List list, Comparator comparator) { - List ii = makeIndices(list.size()); - Collections.sort(ii, new Comparator() { - @Override public int compare(final Integer o1, final Integer o2) { - return comparator.compare((U) list.get(o1), (U) list.get(o2)); + List indices = makeIndices(list.size()); + Collections.sort(indices, new Comparator() { + @Override public int compare(final Integer a, final Integer b) { + return comparator.compare((U) list.get(a), (U) list.get(b)); } }); - return ii; + return indices; } } diff --git a/src/main/resources/l10n/JabRef_en.properties b/src/main/resources/l10n/JabRef_en.properties index caf1cce5572..d041dabdbd5 100644 --- a/src/main/resources/l10n/JabRef_en.properties +++ b/src/main/resources/l10n/JabRef_en.properties @@ -1547,6 +1547,10 @@ Custom=Custom Export\ cited=Export cited Unable\ to\ generate\ new\ library=Unable to generate new library +Found\ identical\ ranges=Found identical ranges +Found\ overlapping\ ranges=Found overlapping ranges +Found\ touching\ ranges=Found touching ranges + Note\:\ Use\ the\ placeholder\ %DIR%\ for\ the\ location\ of\ the\ opened\ library\ file.=Note: Use the placeholder %DIR% for the location of the opened library file. Error\ occured\ while\ executing\ the\ command\ \"%0\".=Error occured while executing the command \"%0\". Reformat\ ISSN=Reformat ISSN