From bb96e41a197976295f266df45c594aeea6754c69 Mon Sep 17 00:00:00 2001 From: Stefano Pagliari Date: Sun, 16 Oct 2022 15:49:07 +0100 Subject: [PATCH] Added inline citation --- .DS_Store | Bin 8196 -> 10244 bytes CHANGELOG.md | 53 +++-- README.md | 2 +- manifest.json | 2 +- package.json | 4 +- src/main.ts | 574 ++++++++++++++++++++++++++---------------------- src/modal.ts | 50 +++-- src/settings.ts | 4 +- src/types.ts | 7 + src/utils.ts | 19 +- 10 files changed, 393 insertions(+), 322 deletions(-) diff --git a/.DS_Store b/.DS_Store index 9c8de459fac9b22d8977ec68ec71bf8542bac874..8a0a6441b7f4acc21a6b3dede02c0ba7f9cad012 100644 GIT binary patch delta 262 zcmZp1XbF&DU|?W$DortDU{C-uIe-{M3-C-V6q~50$jG@dU^hP_=VU=anavskY>fQr zhQZ1CxdlKq3?g19LN^Nv=CX<8=DWBg<>V&;1%W0sEKTq`;t0|Llt{rUAyANkFh{f| zfdQm?a-DeR#s&{|L1vKYK!75)U PICpcAC=V0KP7wnD8w5I` delta 113 zcmZn(XmOBWU|?W$DortDU;r^WfEYvza8E20o2aMA$ht9LH$NlmWI;ih%^Cu1jGLnb z1K1{;NpuP_1C;@R1UHay1?kvW_?>w&ze*qnBg7nr$?-f>C$AGM-8@f}hY6^s4FF<4 B7100y diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d0d51a..eda9825 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,17 +1,28 @@ # Changelog -All notable changes to this project will be documented in this file. +All notable changes to this project will be documented in this file. + +## [0.9.21] + +### Improvement + +- Added placeholder {{citationInLine}} in the template which generates a citation in the format "AUTHOR (YEAR)". This can be added as an alias in the metadata of the note generated by bibnotes to add an in-text citation to that note + ## [0.9.2] + ### Improvement + +- Added notice error when the json file is not found at the path specified in the settings. - The plugin extracts tags added usiong the Zotero PDF Reader. "In order to extract tags added from the Zotero PDF reader, open Zotero -> Preferences -> Advanced -> Config Editor -> extensions.zotero.annotations.noteTemplates.highlight
Replace default value with:

{{highlight quotes='true'}} {{citation}} {{comment}} {{if tags}} Tag: {{tags join='; '}}{{endif}}

" - Different formatting options have been added to the tags extracted from the zotero pdf reader (e.g. hash, bold, bullet point, italic, highlight) - The tag extracted from the zotero pdf reader can be used to trigger transformations in the text (e.g. heading, todo), using the same keywords found in the first word of the text - Added settings that allows to define the placement of the highlight, comments and tags extracted from Zotero. Placeholder include {{highlight}}, {{comment}}, {{tag}}". This setting allows you to define the order of these elements and to include an elements in between them (e.g. line break). In addition to the general placement setting, it is also possible to define specific arrangements for the highlights of a given colour. This replaces the previous settings "text dividing the highlight and the related comment" and "Text dividing the highlight and the related comment when the comment is moved before the highlight". This custom tgext now can be included in the general setting in between the {{highlight}} and {{comment}} placeholder. - + ## [0.9.14] + ### Improvement -- The plugin also extracts the colour of highlights made with external PDF annotations and imported by Zotero (instead of Zotfile) using the "Add Note from Annotation". The plugin converts the HEX colour of the annotation into a palette comprising of ten colours (https://github.com/wadackel/color-classifier/blob/master/src/palette/rainbow.js) +- The plugin also extracts the colour of highlights made with external PDF annotations and imported by Zotero (instead of Zotfile) using the "Add Note from Annotation". The plugin converts the HEX colour of the annotation into a palette comprising of ten colours () - Added the possibility of specifying a custom hex colour in the highlight setting and the transformation associated with this colour. Added a "{{CustomHex}}" placeholder in the template gathering all the highlight using that colour - The backlink now directs to the specific annotation rather than the page in the pdf file (thanks to @CaoKang-David) - It is possible to name the notes with the author (thanks to @ThomasFKJorna) @@ -19,6 +30,7 @@ All notable changes to this project will be documented in this file. - Added setting to specify the text between a highlight and a comment. This allows the user to set the comment related to a highlight in a different line (using
) ### Bugs + - Fixed bugs that prevented notes added in Zotero using markdown from being formatted properly - Fixed code to manually select the folder where the images are located - Fixed bug in the modal updating the library. The plugin now recognizes changes also to existing notes rather than only to the metadata @@ -27,9 +39,10 @@ All notable changes to this project will be documented in this file. - Added line break when adding a new line to an existing note - Corrected bug that prevented the use of `<` in notes - ## [0.9.10] + ### Improvement + - Added placeholder for {{creator}} which includes all the named entities (e.g. author, editor, etc...) - Added setting to activate "debugging mode". This will print the console log from the processing of an entry into a txt file that can be easily shared to debug a problem with the plugin - Added setting to place the comments made to an highlight in front of the text of the highlight the default option @@ -38,31 +51,32 @@ All notable changes to this project will be documented in this file. - Added support for exporting in-line references in a pandoc format ([@citationkey, p. pagenumber]) ### Bugs + - Fixed filepath of images on Windows - Fixed filepath of images on Linux (thanks to @MichaBrugger) - Fixed bug related to the formatting of comments - Fixed filepath of images on Windows -- Fixed bug that prevented export of user-notes when there was no PDF attached to the same note +- Fixed bug that prevented export of user-notes when there was no PDF attached to the same note - Fixed bug that preventex export of notes when $& was found in the text - -## [0.9] +## [0.9] ### Improvement + - Instead of automatically exporting the extracted annotation at the end of the note, the position in the note can be defined in the template using the placeholder {{PDFNotes}}. This is a breaking change from the previous version. In order to retain the same output as in the previous versions, add "## Extracted Annotations" followed by "{{PDFNotes}}" in the custom template. - In addition to extracting all the highlights/comments in a sequential order, it is also possible to extract groups of highlights based on the highlight colour using the following placeholder: - - {{Yellow}} - - {{Red}} - - {{Green}} - - {{Black} - - {{White}} - - {{Gray}} - - {{Cyan}} - - {{Magenta}} - - {{Orange}} + - {{Yellow}} + - {{Red}} + - {{Green}} + - {{Black} + - {{White}} + - {{Gray}} + - {{Cyan}} + - {{Magenta}} + - {{Orange}} - Added capacity to export notes stored within Zotero that have been generated manually rather than exported from the pdf. The position in the text can be defined by adding to the template the placeholder {{UserNotes}} - Added capacity to import images that are extracted from the PDF using the Zotero native pdf Reader. In the settings, you can select whether to link to the image that is stored in the Zotero main folder or copy this image inside your Obsidian vault, and the location. Comments made on an image can be placed above or below the image inside the note by changing the setting. It is also possible to extract the images in a specific location of the note adding the placeholder {{Images}} in the template. -- Added new setting to decide whether 1) updating an existing note will over-write the existing note completely ("Overwrite Entire Note"), only add non-overlapping sentences ("Save Entire Note"), or adding non-overlapping sentences in a specific section, while over-writing the rest (""Select Section"). When the "Select Section" is chosen, the plugin will ask for a string identifying the beginning and/or end of the section to be updated (rather than overwritten). +- Added new setting to decide whether 1) updating an existing note will over-write the existing note completely ("Overwrite Entire Note"), only add non-overlapping sentences ("Save Entire Note"), or adding non-overlapping sentences in a specific section, while over-writing the rest (""Select Section"). When the "Select Section" is chosen, the plugin will ask for a string identifying the beginning and/or end of the section to be updated (rather than overwritten). If the "start" field is left empty, the existing text will be preserved from to the beginning of the note. If the "end" field is left empty, the existing text will be preserved until the end of the note. For instance, in order to over-write the metadata but maintain changes made manually to the extracted annotations, the start of the section to be preserved should be set to the unique title used in the template before the metadata (e.g. "## Extracted Annotations"). - Added suggester field in the settings to select the folder to export the note (credit to Templater plugin and Periodic Notes Plugin.) - Added settings to control whether updating an existing slide will overwrite the changes made manually within Obsidian or preserve them (default) @@ -74,12 +88,9 @@ If the "start" field is left empty, the existing text will be preserved from to - Introduced the setting to control the format of the in-line reference at the end of a highlight extracted from the PDF. Three default options are provided: "Author, year, page number", "Only page number", "Empty" - Introduced the setting to control whether to include next to each extracted highlight, comment, and figure a link opening within the Zotero reader the page of the pdf file where this element is extracted from. - - ### Debugging + - Fixed bug where the code exporting notes did not allow for underscores and other non-alphanumeric characters in the title of the exported notes - Fixed bug in the function creating tasks when both a comment and a highlight are present. - Move the cursor to the search bar when launching the "Create/Update Literature Note" command - Changes to the json file exported by Zotero are ready by Obsidian without having to restart the application - - \ No newline at end of file diff --git a/README.md b/README.md index ee4e335..748dcfc 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ In order to import your references and notes from Zotero, you need to export you - select "Export Notes" if you would like to import into Obsidian the annotation. - *(Optional)* select "Keep updated" to automatically update the exported library once an entry is added/deleted/amended - save the BetterBibTex JSON file in a folder **within** your Obsidian Vault -- in the plugin settings within Obsidian add the relative path within your vault of the library to be imported, as well as the relative path within your vault of the folder where you would like the literature notes to be stored. +- in the plugin settings within Obsidian add the relative path within your vault of the library to be imported, as well as the relative path within your vault of the folder where you would like the literature notes to be stored. For instance, add `library.json` if the file (library.json) is in the root folder. Instead, if the file is in a subfolder, specify first the subfolder followed by the name of the file (e.g. 'zotero/library.json' if the json file is located in a subfolder of your vault called 'zotero'. ![](/images/Export_Zotero.jpg) diff --git a/manifest.json b/manifest.json index d12842b..206c979 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "id": "bibnotes", "name": "BibNotes Formatter", - "version": "0.9.209", + "version": "0.9.210", "minAppVersion": "0.12.0", "description": "Plugin to import and format annotations from Zotero.", "author": "Stefano Pagliari", diff --git a/package.json b/package.json index e5f67be..f82ecde 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "bibnotes", - "version": "0.9.209", + "version": "0.9.210", "description": "Plugin to export and format annotations from Zotero into Obsidian", "main": "main.js", "scripts": { @@ -30,4 +30,4 @@ "tslint": "^6.1.3", "turndown": "^7.1.1" } -} +} \ No newline at end of file diff --git a/src/main.ts b/src/main.ts index 78f92f9..b97e1fe 100755 --- a/src/main.ts +++ b/src/main.ts @@ -8,13 +8,11 @@ import ColorClassifier, { Palette, AlgorithmTypes } from "color-classifier" //import { info, setLevel } from "loglevel"; import { Plugin, Notice, normalizePath } from "obsidian"; -//import { App, Plugin, Notice, normalizePath, Vault } from "obsidian"; +///import { App, Plugin, Notice, normalizePath, Vault } from "obsidian"; import path from "path"; -import 'turndown' - - +import 'turndown' import { DEFAULT_SETTINGS, @@ -28,7 +26,7 @@ import { fuzzySelectEntryFromJson, updateLibrary } from "./modal"; //Import sample settings from /settings.ts import { SettingTab } from "./settings"; import { - AnnotationElements, + AnnotationElements, MyPluginSettings, Reference, Collection, @@ -86,7 +84,7 @@ export default class MyPlugin extends Plugin { }); } - onunload() {} + onunload() { } async loadSettings() { this.settings = Object.assign( @@ -139,14 +137,14 @@ export default class MyPlugin extends Plugin { highlightQuoteOpen, highlightQuoteClose, ] = [ - isHighlightItalic ? "*" : "", - isHighlightBold ? "**" : "", - isHighlightHighlighted ? "==" : "", - isHighlightBullet ? "- " : "", - isHighlightBlockquote ? "> " : "", - isHighlightQuote ? "“" : "", - isHighlightQuote ? "”" : "", - ]; + isHighlightItalic ? "*" : "", + isHighlightBold ? "**" : "", + isHighlightHighlighted ? "==" : "", + isHighlightBullet ? "- " : "", + isHighlightBlockquote ? "> " : "", + isHighlightQuote ? "“" : "", + isHighlightQuote ? "”" : "", + ]; const highlightFormatBefore = highlightHighlighted + @@ -161,12 +159,14 @@ export default class MyPlugin extends Plugin { highlightHighlighted + highlightCustomTextAfter; - let highlightPrepend = "" - if(highlightBullet != "" || highlightBlockquote != ""){highlightPrepend = - "\n" + - highlightBullet + - highlightBlockquote + - highlightCustomTextBefore} + let highlightPrepend = "" + if (highlightBullet != "" || highlightBlockquote != "") { + highlightPrepend = + "\n" + + highlightBullet + + highlightBlockquote + + highlightCustomTextBefore + } //Set the formatting variables based on the comments settings const commentItalic = isCommentItalic ? "*" : ""; @@ -187,16 +187,17 @@ export default class MyPlugin extends Plugin { commentBold + commentHighlighted + commentCustomTextAfter; - - let commentPrepend = "" - if(commentBullet != "" || commentBlockquote != ""){ - commentPrepend = - "\n" + - commentBullet + - commentBlockquote + - commentCustomTextBefore}; - - + + let commentPrepend = "" + if (commentBullet != "" || commentBlockquote != "") { + commentPrepend = + "\n" + + commentBullet + + commentBlockquote + + commentCustomTextBefore + }; + + //Set the tag formatting variables based on the tag settings const [ tagHash, @@ -208,15 +209,15 @@ export default class MyPlugin extends Plugin { tagQuoteOpen, tagQuoteClose, ] = [ - isTagHash ? "#" : "", - isTagItalic ? "*" : "", - isTagBold ? "**" : "", - isTagHighlighted ? "==" : "", - isTagBullet ? "- " : "", - isTagBlockquote ? "> " : "", - isTagQuote ? "“" : "", - isTagQuote ? "”" : "", - ]; + isTagHash ? "#" : "", + isTagItalic ? "*" : "", + isTagBold ? "**" : "", + isTagHighlighted ? "==" : "", + isTagBullet ? "- " : "", + isTagBlockquote ? "> " : "", + isTagQuote ? "“" : "", + isTagQuote ? "”" : "", + ]; const tagFormatBefore = tagHash + @@ -232,10 +233,13 @@ export default class MyPlugin extends Plugin { tagHighlighted + tagCustomTextAfter; - let tagPrepend = "" - if(tagBullet != "" || tagBlockquote != ""){tagPrepend = "\n" + - tagBullet + tagBlockquote + tagCustomTextBefore;} else { - tagPrepend = tagBullet + tagBlockquote + tagCustomTextBefore;} + let tagPrepend = "" + if (tagBullet != "" || tagBlockquote != "") { + tagPrepend = "\n" + + tagBullet + tagBlockquote + tagCustomTextBefore; + } else { + tagPrepend = tagBullet + tagBlockquote + tagCustomTextBefore; + } return { highlightFormatBefore, @@ -293,32 +297,64 @@ export default class MyPlugin extends Plugin { selectedEntry.localLibrary = "[Zotero](" + selectedEntry.select + ")"; selectedEntry.localLibraryLink = selectedEntry.select; - + } - + //Fix itemType - if(selectedEntry.itemType == "journalArticle"){selectedEntry.itemType = "Journal Article"} - if(selectedEntry.itemType == "report"){selectedEntry.itemType = "Report"} - if(selectedEntry.itemType == "bookSection"){selectedEntry.itemType = "Book Section"} - if(selectedEntry.itemType == "newspaperArticle"){selectedEntry.itemType = "Newspaper Article"} - if(selectedEntry.itemType == "book"){selectedEntry.itemType = "Book"} + if (selectedEntry.itemType == "journalArticle") { selectedEntry.itemType = "Journal Article" } + if (selectedEntry.itemType == "report") { selectedEntry.itemType = "Report" } + if (selectedEntry.itemType == "bookSection") { selectedEntry.itemType = "Book Section" } + if (selectedEntry.itemType == "newspaperArticle") { selectedEntry.itemType = "Newspaper Article" } + if (selectedEntry.itemType == "book") { selectedEntry.itemType = "Book" } //Capitalize the first letter selectedEntry.itemType = selectedEntry.itemType.charAt(0).toUpperCase() + selectedEntry.itemType.slice(1); - - - - + + // Replace in-line citation + selectedEntry.citationInLine = createAuthorKey(selectedEntry.creators) + + " " + + "(" + + selectedEntry.year + + ")" + selectedEntry.citationInLine = selectedEntry.citationInLine.replace("()", "") + // Replace short and full citation + console.log(Object.keys(selectedEntry)) + if (selectedEntry.itemType == "Journal Article") { + selectedEntry.citationShort = selectedEntry.citationInLine + + " " + + "'" + + selectedEntry.title + + "'"; + selectedEntry.citationFull = selectedEntry.citationShort + + ", " + + "*" + + selectedEntry.publicationTitle + + "*" + + ", " + + selectedEntry.volume + + "(" + + selectedEntry.issue + + "), " + + "pp. " + + selectedEntry.pages + + "." + } + selectedEntry.citationFull = selectedEntry.citationFull.replace("() ", "") + selectedEntry.citationShort = selectedEntry.citationShort.replace("** ", "") + selectedEntry.citationFull = selectedEntry.citationFull.replace("** ", "") + selectedEntry.citationFull = selectedEntry.citationFull.replace("pp. ", "") //create field file //if (selectedEntry.hasOwnProperty("attachment.")){ selectedEntry.file = createLocalFileLink(selectedEntry); - // Create an array with all the fields + // Create an array with all the fields const entriesArray = Object.keys(selectedEntry); + //replace the single-value placeholders with the value of the field - note = replaceAllTemplates(entriesArray, note, selectedEntry); - + + + //remove single backticks but retain triple backticks note = note.replace(/```/g, "HEREISAPLACEHOLDERFORBACKTICK"); note = note.replace(/`/g, "'"); @@ -364,7 +400,7 @@ export default class MyPlugin extends Plugin { } //Crety empty lineElements - const lineElements: AnnotationElements = { + const lineElements: AnnotationElements = { highlightText: "", highlightColour: "", annotationType: "", @@ -389,9 +425,9 @@ export default class MyPlugin extends Plugin { //Extract the citeKey lineElements.citeKey = String(selectedLine.match(/\(([^)]+)\)+$/g)); - if (lineElements.citeKey == `null`){lineElements.citeKey = String(selectedLine.match(/\(([^D+]+) \d+\S+\)/g))}; + if (lineElements.citeKey == `null`) { lineElements.citeKey = String(selectedLine.match(/\(([^D+]+) \d+\S+\)/g)) }; - const posCiteKeyBegins = selectedLine.indexOf(lineElements.citeKey); + const posCiteKeyBegins = selectedLine.indexOf(lineElements.citeKey); let extractedText = ""; if (posCiteKeyBegins !== -1) { @@ -402,22 +438,22 @@ export default class MyPlugin extends Plugin { // Remove quotation marks from extractedText ["“", '"', "`", "'"].forEach( (quote) => - (extractedText = removeQuoteFromStart( - quote, - extractedText - )) + (extractedText = removeQuoteFromStart( + quote, + extractedText + )) ); ["”", '"', "`", "'"].forEach( (quote) => - (extractedText = removeQuoteFromEnd( - quote, - extractedText - )) + (extractedText = removeQuoteFromEnd( + quote, + extractedText + )) ); } //Extract the colour - + if (extractedText.startsWith("(Yellow) - ")) { lineElements.highlightColour = "yellow"; extractedText = extractedText.replace("(Yellow) - ", ""); @@ -505,7 +541,7 @@ export default class MyPlugin extends Plugin { // } //Identify if the text is highlight or comment. if it is a comment extract the type of comment - + const annotationCommentAll = ""; if (lineElements.citeKey.includes("(note on p.")) { lineElements.commentText = extractedText; @@ -539,11 +575,11 @@ export default class MyPlugin extends Plugin { lineElements.annotationType === "noKey" ? lineElements.commentText : lineElements.commentText - .substring( - firstBlank, - lineElements.commentText.length - ) - .trim(); + .substring( + firstBlank, + lineElements.commentText.length + ) + .trim(); //If a comment includes the key for a transformation, apply that to the previous element @@ -551,7 +587,7 @@ export default class MyPlugin extends Plugin { if ( lineElements.annotationType != "noKey" && noteElements[noteElements.length - 1].annotationType === - "noKey" && + "noKey" && noteElements[noteElements.length - 1].commentText === "" ) { noteElements[noteElements.length - 1].annotationType = @@ -570,13 +606,13 @@ export default class MyPlugin extends Plugin { parseAnnotationLinesintoElementsUserNote(note: string) { - + // Replace html formatting with markdown formatting const turndownService = new TurndownService() note = turndownService.turndown(note) - note = note + note = note // Replace backticks .replace(/`/g, "'") // Correct when zotero exports wrong key (e.g. Author, date, p. p. pagenum) @@ -591,12 +627,12 @@ export default class MyPlugin extends Plugin { for (let indexLines = 0; indexLines < lengthLines; indexLines++) { const selectedLineOriginal = unescape(lines[indexLines]); - + // Replace backticks with single quote let selectedLine = replaceTemplate(selectedLineOriginal, "`", "'"); - + // Correct encoding issues with special character showing incorrectly - selectedLine = replaceTemplate(selectedLine, "&", "&").replace(/</g,'<').replace(/>/g,'>').replace(/&/g,'&'); + selectedLine = replaceTemplate(selectedLine, "&", "&").replace(/</g, '<').replace(/>/g, '>').replace(/&/g, '&'); const lineElements: AnnotationElements = { @@ -711,8 +747,8 @@ export default class MyPlugin extends Plugin { highlightColour = highlightColour.replace('"', ""); lineElements.highlightColour = highlightColour; - - + + } //Extracte the page of the pdf @@ -785,12 +821,12 @@ export default class MyPlugin extends Plugin { lineElements.attachmentURI = attachmentURI; } } - - if ( + + if ( /"uris":\["http:\/\/zotero\.org\/users\/\d+\/items\/\w+/gm.test( selectedLineOriginal ) && lineElements.attachmentURI == "" - ){ + ) { let attachmentURI = String( selectedLineOriginal.match( /"uris":\["http:\/\/zotero\.org\/users\/\d+\/items\/\w+/g @@ -805,11 +841,11 @@ export default class MyPlugin extends Plugin { ); lineElements.attachmentURI = attachmentURI; } - + } - - //Create the zotero backlink + + //Create the zotero backlink if (/"annotationKey":"[a-zA-Z0-9]+/gm.test(selectedLineOriginal)) { let annotationKey = String(selectedLineOriginal.match(/"annotationKey":"[a-zA-Z0-9]+/gm)); if (annotationKey === null) { @@ -821,7 +857,7 @@ export default class MyPlugin extends Plugin { } if (lineElements.attachmentURI !== null && lineElements.pagePDF !== null && lineElements.annotationKey !== null) { lineElements.zoteroBackLink = "zotero://open-pdf/library/items/" + lineElements.attachmentURI + "?page=" + lineElements.pagePDF + "&annotation=" + lineElements.annotationKey; - + } //Extract the citation within bracket if ( @@ -860,17 +896,17 @@ export default class MyPlugin extends Plugin { // Remove quotation marks from annotationHighlight ["“", '"', "`", "'"].forEach( (quote) => - (lineElements.highlightText = removeQuoteFromStart( - quote, - lineElements.highlightText - )) + (lineElements.highlightText = removeQuoteFromStart( + quote, + lineElements.highlightText + )) ); ["”", '"', "`", "'"].forEach( (quote) => - (lineElements.highlightText = removeQuoteFromEnd( - quote, - lineElements.highlightText - )) + (lineElements.highlightText = removeQuoteFromEnd( + quote, + lineElements.highlightText + )) ); } @@ -901,76 +937,76 @@ export default class MyPlugin extends Plugin { } lineElements.commentText = lineElements.annotationType === "noKey" || - lineElements.annotationType === "typeImage" + lineElements.annotationType === "typeImage" ? annotationCommentAll : annotationCommentAll - .substring( - firstBlank, - annotationCommentAll.length - ) - .trim(); - + .substring( + firstBlank, + annotationCommentAll.length + ) + .trim(); + //Extract the tags //check if the inline tags are found in the text of the comment - if (lineElements.commentText.includes(this.settings.TagBeginningConfig)){ + if (lineElements.commentText.includes(this.settings.TagBeginningConfig)) { //if the tags are at the end of the comment, tehn extract the text between the beginning of the tag and the end of the comment - if(this.settings.TagEndConfig.length==0){ + if (this.settings.TagEndConfig.length == 0) { lineElements.inlineTagsText = lineElements.commentText.slice( lineElements.commentText.indexOf(this.settings.TagBeginningConfig), lineElements.commentText.length, - ); + ); } else { //if the tags are in the middle/beginning of the comment, tehn extract the text between the beginning of the tag and the specified end of the tag lineElements.inlineTagsText = lineElements.commentText.slice( - lineElements.commentText.indexOf(this.settings.TagBeginningConfig), - lineElements.commentText.lastIndexOf(this.settings.TagEndConfig), + lineElements.commentText.indexOf(this.settings.TagBeginningConfig), + lineElements.commentText.lastIndexOf(this.settings.TagEndConfig), ); } - - //Remove the tags from the comment - lineElements.commentText = lineElements.commentText.replace(lineElements.inlineTagsText,"").trim() + + //Remove the tags from the comment + lineElements.commentText = lineElements.commentText.replace(lineElements.inlineTagsText, "").trim() } //Check if there are any tags before performing manipulations of inlineTagsText - - if(typeof lineElements.inlineTagsText !== `undefined`){ + + if (typeof lineElements.inlineTagsText !== `undefined`) { //Remove the tag beginning and end marker from the inlineTagsText - lineElements.inlineTagsText = lineElements.inlineTagsText.replace(this.settings.TagBeginningConfig,""); - - if(this.settings.TagEndConfig.length!=0){ - lineElements.inlineTagsText = lineElements.inlineTagsText.replace(this.settings.TagEndConfig,""); + lineElements.inlineTagsText = lineElements.inlineTagsText.replace(this.settings.TagBeginningConfig, ""); + + if (this.settings.TagEndConfig.length != 0) { + lineElements.inlineTagsText = lineElements.inlineTagsText.replace(this.settings.TagEndConfig, ""); } - + //Split the different tags in an array if there are tags lineElements.inlineTagsArray = lineElements.inlineTagsText.split(this.settings.TagDividerConfig) // Identify what type of annotation is based on the tags word. Loop through each of the tags - if (lineElements.annotationType !== "typeImage") { - for (let indexTag = 0; indexTag < lineElements.inlineTagsArray.length; indexTag++) { - const tempAnnotationType = this.getAnnotationType( - lineElements.inlineTagsArray[indexTag], - annotationCommentAll); - //Currently bibnotes can only incorporate one transformation. So as soon as one of the tags matches one transformation this is applied to the code (superseding the first character) and the loop is interrupted. The tag is removed from the list that is printed after the comment - if (tempAnnotationType != "noKey") { - lineElements.annotationType = tempAnnotationType; - - //Remove this from the array - lineElements.inlineTagsArray.splice(indexTag,1) - - break + if (lineElements.annotationType !== "typeImage") { + for (let indexTag = 0; indexTag < lineElements.inlineTagsArray.length; indexTag++) { + const tempAnnotationType = this.getAnnotationType( + lineElements.inlineTagsArray[indexTag], + annotationCommentAll); + //Currently bibnotes can only incorporate one transformation. So as soon as one of the tags matches one transformation this is applied to the code (superseding the first character) and the loop is interrupted. The tag is removed from the list that is printed after the comment + if (tempAnnotationType != "noKey") { + lineElements.annotationType = tempAnnotationType; + + //Remove this from the array + lineElements.inlineTagsArray.splice(indexTag, 1) + + break + } } } } - } } else { lineElements.rowEdited = selectedLine; } //Add the element to the array containing all the elements noteElements.push(lineElements); - } + } return noteElements; } @@ -1001,42 +1037,42 @@ export default class MyPlugin extends Plugin { //fix the label of the annotation colour - Zotfile and other annotators that are not the Zotero native reader else { - const HexRegex = new RegExp(/#([a-fA-F0-9]{6})/g); - - if(HexRegex.test(lineElements.highlightColour)){ + const HexRegex = new RegExp(/#([a-fA-F0-9]{6})/g); + + if (HexRegex.test(lineElements.highlightColour)) { const colorClassifier = new ColorClassifier(Palette.RAINBOW, AlgorithmTypes.HSV); - lineElements.highlightColour = colorClassifier.classify(String(lineElements.highlightColour.match(HexRegex)), "hex"); - } - - - - if (["##000000", "#000000"].some(colorStr=>lineElements.highlightColour.includes(colorStr))){ + lineElements.highlightColour = colorClassifier.classify(String(lineElements.highlightColour.match(HexRegex)), "hex"); + } + + + + if (["##000000", "#000000"].some(colorStr => lineElements.highlightColour.includes(colorStr))) { lineElements.highlightColour = "black"; - } else if (["##FFFFFF", "#ffffff"].some(colorStr=>lineElements.highlightColour.includes(colorStr))){ + } else if (["##FFFFFF", "#ffffff"].some(colorStr => lineElements.highlightColour.includes(colorStr))) { lineElements.highlightColour = "white"; - } else if (["##808080", "#808080"].some(colorStr=>lineElements.highlightColour.includes(colorStr))){ + } else if (["##808080", "#808080"].some(colorStr => lineElements.highlightColour.includes(colorStr))) { lineElements.highlightColour = "gray"; - } else if (["##FF0000", "#ff0000"].some(colorStr=>lineElements.highlightColour.includes(colorStr))){ + } else if (["##FF0000", "#ff0000"].some(colorStr => lineElements.highlightColour.includes(colorStr))) { lineElements.highlightColour = "red"; - } else if (["##FFA500", "#ffa500"].some(colorStr=>lineElements.highlightColour.includes(colorStr))){ + } else if (["##FFA500", "#ffa500"].some(colorStr => lineElements.highlightColour.includes(colorStr))) { lineElements.highlightColour = "orange"; - } else if (["##FFFF00", "#ffff00"].some(colorStr=>lineElements.highlightColour.includes(colorStr))){ + } else if (["##FFFF00", "#ffff00"].some(colorStr => lineElements.highlightColour.includes(colorStr))) { lineElements.highlightColour = "yellow"; - } else if (["##00FF00", "#008000", "#00ff00"].some(colorStr=>lineElements.highlightColour.includes(colorStr))){ + } else if (["##00FF00", "#008000", "#00ff00"].some(colorStr => lineElements.highlightColour.includes(colorStr))) { lineElements.highlightColour = "green"; - } else if (["##00FFFF", "#00ffff"].some(colorStr=>lineElements.highlightColour.includes(colorStr))){ + } else if (["##00FFFF", "#00ffff"].some(colorStr => lineElements.highlightColour.includes(colorStr))) { lineElements.highlightColour = "cyan"; - } else if (["##0000FF", "#0000ff"].some(colorStr=>lineElements.highlightColour.includes(colorStr))){ + } else if (["##0000FF", "#0000ff"].some(colorStr => lineElements.highlightColour.includes(colorStr))) { lineElements.highlightColour = "blue"; - } else if(["##FF00FF", "#800080", "#ff00ff"].some(colorStr=>lineElements.highlightColour.includes(colorStr))){ + } else if (["##FF00FF", "#800080", "#ff00ff"].some(colorStr => lineElements.highlightColour.includes(colorStr))) { lineElements.highlightColour = "magenta"; - } - + } + } - - - + + + //Zotfile Default //{"Black": "#000000", @@ -1089,10 +1125,10 @@ export default class MyPlugin extends Plugin { else if (lineElements.highlightColour == "customHex") { colourTransformation = this.settings.colourCustomHexText; } - - //extract the transformation from the highlight colour + + //extract the transformation from the highlight colour if (lineElements.annotationType == "noKey") { if (colourTransformation.toLowerCase() === "h1") { lineElements.annotationType = "typeH1"; @@ -1116,26 +1152,26 @@ export default class MyPlugin extends Plugin { lineElements.annotationType = "typeTask"; } } - - // Extract the colour template - const arr = ['{{highlight}}', '{{comment}}', '{{tag}}']; - const containsHighlightCommentTag = arr.some(element => { - if (colourTransformation.includes(element)) { - return true; - // if a specific template has not been set for the specific colour, then import the default template - } - return false; - }); - - if (containsHighlightCommentTag == true){lineElements.colourTemplate = colourTransformation} - else {lineElements.colourTemplate = this.settings.highlightExportTemplate} - - - - - - //extract the text to be pre-pended/appended - + + // Extract the colour template + const arr = ['{{highlight}}', '{{comment}}', '{{tag}}']; + const containsHighlightCommentTag = arr.some(element => { + if (colourTransformation.includes(element)) { + return true; + // if a specific template has not been set for the specific colour, then import the default template + } + return false; + }); + + if (containsHighlightCommentTag == true) { lineElements.colourTemplate = colourTransformation } + else { lineElements.colourTemplate = this.settings.highlightExportTemplate } + + + + + + //extract the text to be pre-pended/appended + if (colourTransformation.includes("{{highlight}}")) { lineElements.colourTextBefore = String( colourTransformation.match(/.+?(?={{highlight}})/) @@ -1210,7 +1246,7 @@ export default class MyPlugin extends Plugin { ) { if ( this.settings.highlightCitationsFormat === - "Only page number" && + "Only page number" && lineElements.pageLabel !== undefined ) { lineElements.citeKey = @@ -1220,7 +1256,7 @@ export default class MyPlugin extends Plugin { lineElements.pageLabel !== undefined ) { lineElements.citeKey = - "[@" + citeKey + ", p. " + lineElements.pageLabel + "]" + "[@" + citeKey + ", p. " + lineElements.pageLabel + "]" } else if ( this.settings.highlightCitationsFormat === "Pandoc" && lineElements.pageLabel === undefined @@ -1271,7 +1307,7 @@ export default class MyPlugin extends Plugin { } else { lineElements.zoteroBackLink = ""; } - + //Extract the custom language assocaited with the highlight colour @@ -1295,70 +1331,71 @@ export default class MyPlugin extends Plugin { lineElements.rowEdited = "**" + lineElements.rowOriginal.toUpperCase() + "**"; } - + // ADD FORMATTING TO THE HIGHLIGHTS - if(lineElements.highlightText != ""){ - lineElements.highlightFormatted = + if (lineElements.highlightText != "") { + lineElements.highlightFormatted = highlightPrepend + highlightFormatBefore + lineElements.highlightText + highlightFormatAfter + " " + - lineElements.citeKey + + lineElements.citeKey + " "; - lineElements.highlightFormattedNoPrepend = + lineElements.highlightFormattedNoPrepend = highlightFormatBefore + lineElements.highlightText + highlightFormatAfter + " " + - lineElements.citeKey + + lineElements.citeKey + " "; - + } else { lineElements.highlightFormatted = ""; - lineElements.highlightFormattedNoPrepend= ""} + lineElements.highlightFormattedNoPrepend = "" + } // ADD FORMATTING TO THE COMMENTS - if(lineElements.commentText != "" && lineElements.highlightText!=""){ - lineElements.commentFormatted = + if (lineElements.commentText != "" && lineElements.highlightText != "") { + lineElements.commentFormatted = commentPrepend + commentFormatBefore + lineElements.commentText + commentFormatAfter + " "; - lineElements.commentFormattedNoPrepend = + lineElements.commentFormattedNoPrepend = commentFormatBefore + lineElements.commentText + - commentFormatAfter + " "; - } + commentFormatAfter + " "; + } //Add Citation to the comment if the highlight is empty - else if (lineElements.commentText != "" && lineElements.highlightText==""){ - lineElements.commentFormatted = + else if (lineElements.commentText != "" && lineElements.highlightText == "") { + lineElements.commentFormatted = commentPrepend + commentFormatBefore + lineElements.commentText + - commentFormatAfter + + commentFormatAfter + " " + - lineElements.zoteroBackLink + + lineElements.zoteroBackLink + " "; - lineElements.commentFormattedNoPrepend = + lineElements.commentFormattedNoPrepend = commentFormatBefore + lineElements.commentText + - commentFormatAfter + + commentFormatAfter + " " + - lineElements.zoteroBackLink + - " "; - } else { - lineElements.commentFormatted = ""; - lineElements.commentFormattedNoPrepend = "" - } - + lineElements.zoteroBackLink + + " "; + } else { + lineElements.commentFormatted = ""; + lineElements.commentFormattedNoPrepend = "" + } + // ADD FORMATTING TO THE ZOTERO INLINE TAGS //if the hash is added to the tag, then remove empty spaces - if (typeof lineElements.inlineTagsArray == 'undefined'){lineElements.inlineTagsArray= []} + if (typeof lineElements.inlineTagsArray == 'undefined') { lineElements.inlineTagsArray = [] } - if(this.settings.isTagHash==true){ + if (this.settings.isTagHash == true) { for (let index = 0; index < lineElements.inlineTagsArray.length; index++) { lineElements.inlineTagsArray[index] = lineElements.inlineTagsArray[index].replace(/ /g, "") } @@ -1366,30 +1403,30 @@ export default class MyPlugin extends Plugin { } const TempTag = lineElements.inlineTagsArray - .map(i => tagPrepend + tagFormatBefore + i + tagFormatAfter); + .map(i => tagPrepend + tagFormatBefore + i + tagFormatAfter); // if there are two tags, remove one - + //format the tags so that only the hash sign is added only if there was not one already for (let index = 0; index < TempTag.length; index++) { TempTag[index] = TempTag[index].replace("##", "#"); //if(this.settings.isTagHash==true){TempTag[index] = TempTag[index].replace(" ", "")} } - - + + const TempTagNoPrepend = lineElements.inlineTagsArray - .map(i => tagFormatBefore + i + tagFormatAfter); + .map(i => tagFormatBefore + i + tagFormatAfter); for (let index = 0; index < TempTagNoPrepend.length; index++) { TempTagNoPrepend[index] = TempTagNoPrepend[index].replace("##", "#"); //if(this.settings.isTagHash==true){TempTagNoPrepend[index] = TempTagNoPrepend[index].replace(" ", "")} - } - + } + // Check if there are any inline tags - function allAreEmpty(arr:string[]) {return arr.every(element => element == "");} + function allAreEmpty(arr: string[]) { return arr.every(element => element == ""); } // If there are inline tags, format them. otherwise create empty element - if (allAreEmpty(lineElements.inlineTagsArray)==false){ + if (allAreEmpty(lineElements.inlineTagsArray) == false) { lineElements.inlineTagsFormatted = TempTag.join(' '); // lineElements.inlineTagsFormatted = lineElements.inlineTagsFormatted + this.settings.tagCustomTextAfterLast; @@ -1400,32 +1437,32 @@ export default class MyPlugin extends Plugin { lineElements.inlineTagsFormatted = ""; lineElements.inlineTagsFormattedNoPrepend = ""; } - + // - + //Extract from the setting the template for exporitng the highlight/comment/tag for different colours - if (typeof lineElements.colourTemplate == 'undefined'){lineElements.colourTemplate = this.settings.highlightExportTemplate} + if (typeof lineElements.colourTemplate == 'undefined') { lineElements.colourTemplate = this.settings.highlightExportTemplate } - if(lineElements.colourTemplate.length==0){lineElements.colourTemplate= ""} + if (lineElements.colourTemplate.length == 0) { lineElements.colourTemplate = "" } lineElements.colourTemplateFormatted = lineElements.colourTemplate.replace("{{highlight}}", lineElements.highlightFormatted) lineElements.colourTemplateFormatted = lineElements.colourTemplateFormatted.replace("{{comment}}", lineElements.commentFormatted) lineElements.colourTemplateFormatted = lineElements.colourTemplateFormatted.replace("{{tag}}", lineElements.inlineTagsFormatted) //lineElements.colourTemplate = lineElements.colourTemplate + "\n" - lineElements.colourTemplateFormatted=lineElements.colourTemplateFormatted.replace(/^\s+/g, ''); + lineElements.colourTemplateFormatted = lineElements.colourTemplateFormatted.replace(/^\s+/g, ''); ////Extract from the setting the template for exporitng the highlight/comment/tag for different colours but without prepend signs. This can be used to create tasks/heading lineElements.colourTemplateNoPrepend = lineElements.colourTemplate.replace("{{highlight}}", lineElements.highlightFormattedNoPrepend) lineElements.colourTemplateNoPrepend = lineElements.colourTemplateNoPrepend.replace("{{comment}}", lineElements.commentFormattedNoPrepend) lineElements.colourTemplateNoPrepend = lineElements.colourTemplateNoPrepend.replace("{{tag}}", lineElements.inlineTagsFormattedNoPrepend) //lineElements.colourTemplate = lineElements.colourTemplate + "\n" - lineElements.colourTemplateNoPrepend=lineElements.colourTemplateNoPrepend.replace(/^\s+/g, ''); + lineElements.colourTemplateNoPrepend = lineElements.colourTemplateNoPrepend.replace(/^\s+/g, ''); - - //FORMAT HIGHLIGHTED SENTENCES WITHOUT ANY COMMENT + + //FORMAT HIGHLIGHTED SENTENCES WITHOUT ANY COMMENT //OR WITHOUT ANY SPECIAL CONSIDERATIONS - if (lineElements.annotationType === "noKey") {lineElements.rowEdited = lineElements.colourTemplateFormatted} + if (lineElements.annotationType === "noKey") { lineElements.rowEdited = lineElements.colourTemplateFormatted } //FORMAT IMAGES if (lineElements.annotationType === "typeImage") { @@ -1439,36 +1476,37 @@ export default class MyPlugin extends Plugin { base: "image.png", }); - + // If the path of the existing images has been defined in the settings, then take that - if(this.settings.zoteroStoragePathManual.length>0){ - pathImageOld = path.format({ - dir: this.settings.zoteroStoragePathManual + lineElements.imagePath, - base: "image.png", + if (this.settings.zoteroStoragePathManual.length > 0) { + pathImageOld = path.format({ + dir: this.settings.zoteroStoragePathManual + lineElements.imagePath, + base: "image.png", + + }) + } - })} - pathImageNew = path.normalize( path.format({ dir: normalizePath( // create new path with the rootpath + settings.imagesPath this.app.vault.adapter.getBasePath() + - "\\" + - this.settings.imagesPath - ), + "\\" + + this.settings.imagesPath + ), base: citeKey + "_" + lineElements.imagePath + ".png", - }) + }) ); if (this.zoteroBuildWindows == false) { pathImageNew = "/" + pathImageNew; } - + //Check if the image exists within Zotero or already within the vault if ( // replaced fs.existsSync with the obsidian adapter - fs.existsSync(pathImageOld) + fs.existsSync(pathImageOld) ) { //if the settings is to link to the image in the zotero folder if (this.settings.imagesCopy === false) { @@ -1486,10 +1524,10 @@ export default class MyPlugin extends Plugin { if (err) throw err; } ); - } - lineElements.rowEdited = "![[" + citeKey + "_" + lineElements.imagePath + ".png]] " + - lineElements.citeKey; - } + } + lineElements.rowEdited = "![[" + citeKey + "_" + lineElements.imagePath + ".png]] " + + lineElements.citeKey; + } } else { new Notice( `Cannot find image at "${pathImageOld}". Provide the correct zotero data directory location in the settings` @@ -1521,10 +1559,10 @@ export default class MyPlugin extends Plugin { // MERGE HIGHLIGHT WITH THE PREVIOUS ONE ABOVE if (lineElements.annotationType === "typeMergeAbove") { noteElements[i].rowEdited = (noteElements[i - 1].rowEdited.replace(/\[.*\)/, '')).replace(/\s+$/g, '') + " " + - lineElements.highlightFormattedNoPrepend.replace(/^\s+/g, '') + + lineElements.highlightFormattedNoPrepend.replace(/^\s+/g, '') + lineElements.commentFormatted + lineElements.inlineTagsFormatted - + //Add the highlighted text to the previous one @@ -1555,7 +1593,7 @@ export default class MyPlugin extends Plugin { if (/typeH\d/.test(lineElements.annotationType)) { const lastChar = lineElements.annotationType[ - lineElements.annotationType.length - 1 + lineElements.annotationType.length - 1 ]; const level = parseInt(lastChar); const hashes = "#".repeat(level); @@ -1607,7 +1645,7 @@ export default class MyPlugin extends Plugin { // lineElements.zoteroBackLink + // lineElements.inlineTagsFormatted;; // } - + } //FORMAT KEYWORDS @@ -1622,8 +1660,8 @@ export default class MyPlugin extends Plugin { indexRowsToBeRemoved.push(i); } - - + + //Copy the edited text into an array to be exported @@ -1642,7 +1680,7 @@ export default class MyPlugin extends Plugin { ) { noteElementsArray.splice(indexRowsToBeRemoved[index], 1); } - } + } //Add rowEdited into different arrays for the export for (let index = 0; index < noteElementsArray.length; index++) { @@ -1680,7 +1718,7 @@ export default class MyPlugin extends Plugin { if (selectedLine.annotationType === "typeImage") { imagesArray.push(selectedLine.rowEdited); } - + } @@ -1807,7 +1845,7 @@ export default class MyPlugin extends Plugin { let pathZoteroStorage = ""; let zoteroBuildWindows: boolean = undefined; - + //check if the base path where the attachment is stored is in Zotero/storage const zoteroStorageMac = new RegExp( @@ -1869,14 +1907,14 @@ export default class MyPlugin extends Plugin { // Remove special characters that would break the replacement of the text in the template - //lineElements.rowEdited = lineElements.rowEdited.replaceAll("$>", '$$'); - note = note.replaceAll("$&", '$ &'); + //lineElements.rowEdited = lineElements.rowEdited.replaceAll("$>", '$$'); + note = note.replaceAll("$&", '$ &'); //Identify the extraction Type (Zotero vs. Zotfile) let extractionType = undefined; if (unescape(note).includes(" { config: Record; items: Reference[]; version: string; - __proto__: Record; + __proto__: Record; }; keyWordArray: string[]; noteElements: AnnotationElements[]; @@ -45,16 +45,20 @@ export class fuzzySelectEntryFromJson extends FuzzySuggestModal { //Check sqlite 3 this.plugin.checkSQLite(); - + //Load the Json file + // Check if the json file exists + const jsonPath = this.app.vault.adapter.getBasePath() + "/" + this.plugin.settings.bibPath + if (!fs.existsSync(jsonPath)) { new Notice("No BetterBibTex Json file found at " + jsonPath) } + //Create the full path //const data = require(this.app.vault.adapter.getBasePath() + "/" + this.plugin.settings.bibPath) const rawdata = fs.readFileSync( - this.app.vault.adapter.getBasePath() + - "/" + - this.plugin.settings.bibPath + this.app.vault.adapter.getBasePath() + + "/" + + this.plugin.settings.bibPath ); const data = JSON.parse(rawdata.toString()); // rawdata is a buffer, convert to string @@ -75,7 +79,7 @@ export class fuzzySelectEntryFromJson extends FuzzySuggestModal { // Extract the date bibtexArrayItem.date = selectedEntry.date - if (selectedEntry.hasOwnProperty("date")){ + if (selectedEntry.hasOwnProperty("date")) { selectedEntry.year = selectedEntry.date.match(/\d\d\d\d/gm) bibtexArrayItem.date = selectedEntry.year } @@ -118,6 +122,10 @@ export class fuzzySelectEntryFromJson extends FuzzySuggestModal { dateModified: "", itemKey: "", title: "", + citationFull: "", + citationInLine: "", + citationShort: "", + localLibraryLink: "", creators: [], // added the missing properties itemID: 0, @@ -155,7 +163,7 @@ export class fuzzySelectEntryFromJson extends FuzzySuggestModal { ) { //Create an array where you store the citekey to be processed let citeKeyToBeProcessed: string[] = []; - + //If the entire library has been selected, then add all the if (referenceSelected.citationKey === "Entire Library") { @@ -210,10 +218,14 @@ export class updateLibrary extends Modal { console.log("Updating Zotero library"); //const data = require(this.app.vault.adapter.getBasePath() + "/" + this.plugin.settings.bibPath) + // Check if the json file exists + const jsonPath = this.app.vault.adapter.getBasePath() + "/" + this.plugin.settings.bibPath + if (!fs.existsSync(jsonPath)) { new Notice("No BetterBibTex Json file found at " + jsonPath) } + const rawdata = fs.readFileSync( this.app.vault.adapter.getBasePath() + - "/" + - this.plugin.settings.bibPath + "/" + + this.plugin.settings.bibPath ); const data = JSON.parse(rawdata.toString()); // rawdata is a buffer, converted to string @@ -237,16 +249,18 @@ export class updateLibrary extends Modal { noteDateModifiedArray.push(selectedEntry.dateModified) for (let index = 0; index < selectedEntry.notes.length; index++) { noteDateModifiedArray.push(selectedEntry.notes[index].dateModified); - noteDateModifiedArray.sort((firstElement, secondElement) => { if (firstElement > secondElement) { - return -1; - } - if (firstElement < secondElement) { - return 1; + noteDateModifiedArray.sort((firstElement, secondElement) => { + if (firstElement > secondElement) { + return -1; + } + if (firstElement < secondElement) { + return 1; + } + return 0; } - return 0; } ); } - + const datemodified = new Date(noteDateModifiedArray[0]); if (datemodified < lastUpdate) continue; //skip if it was modified before the last update @@ -254,7 +268,7 @@ export class updateLibrary extends Modal { //skip if the setting is to update only existing note and th enote is not found at the give folder if ( this.plugin.settings.updateLibrary === - "Only update existing notes" && + "Only update existing notes" && !fs.existsSync( createNoteTitle( selectedEntry, @@ -279,5 +293,5 @@ export class updateLibrary extends Modal { } - onClose() {} + onClose() { } } diff --git a/src/settings.ts b/src/settings.ts index 2046d93..52dacf7 100755 --- a/src/settings.ts +++ b/src/settings.ts @@ -27,8 +27,8 @@ export class SettingTab extends PluginSettingTab { importLibrary.createEl("summary", {text: "" }); new Setting(importLibrary) - .setName("Bibtex File") - .setDesc("Add Path to the *BetterBibTex Json* file to be imported") + .setName("BetterBibTex Json File") + .setDesc("Add relative path from the vault folder to the *BetterBibTex Json* file to be imported. For instance, add `library.json` if the file (library.json) is in the root folder. Instead, if the file is in a subfolder, specify first the subfolder followed by the name of the file (e.g. 'zotero/library.json' if the json file is located in a subfolder of your vault called 'zotero') ") .addText((text) => text .setPlaceholder("/path/to/BetterBibTex.json") diff --git a/src/types.ts b/src/types.ts index b0fd21c..9307474 100755 --- a/src/types.ts +++ b/src/types.ts @@ -89,6 +89,9 @@ export interface Reference { id: number; citationKey: string; year: string; + citationInLine: string; + citationShort: string; + citationFull: string; itemType: string; inlineReference: string; date: string; @@ -96,6 +99,10 @@ export interface Reference { itemKey: string; itemID: number; title: string; + publicationTitle: string; + volume: number; + issue: number; + pages: string; creators: { creatorType: string; firstName: string; diff --git a/src/utils.ts b/src/utils.ts index 32df34b..779d505 100755 --- a/src/utils.ts +++ b/src/utils.ts @@ -111,6 +111,7 @@ export const createAuthorKey = (creators: CreatorArray) => { if (authorKey.length > 2) { authorKeyFixed = authorKey[0] + " et al."; } + console.log(authorKeyFixed) return authorKeyFixed; }; @@ -148,12 +149,12 @@ export function formatCreatorsName(creator: Creator, nameCustom: string) { ) { nameCustom = nameCustom.replace("{{lastName}}", creator.lastName); nameCustom = nameCustom.replace("{{firstName}}", creator.firstName); - const getInitials = function (string:string) { + const getInitials = function (string: string) { let names = string.split(' '), - initials = names[0].substring(0, 1).toUpperCase()+"."; - + initials = names[0].substring(0, 1).toUpperCase() + "."; + if (names.length > 1) { - initials += names[names.length - 1].substring(0, 1).toUpperCase()+"."; + initials += names[names.length - 1].substring(0, 1).toUpperCase() + "."; } return initials; }; @@ -199,7 +200,7 @@ export const createCreatorList = ( creatorList.push(formatCreatorsName(creator, nameFormat)); } } - + console.log(creatorList) const creatorListBracket = creatorList.map(makeWiki); @@ -309,7 +310,7 @@ export function replaceMissingFields( const lines = copy.split(/\r?\n/); // run function to determine where we still have double curly brackets for (let j = 0; j < lines.length; j++) { - + if (lines[j].match(TEMPLATE_REG)) { lines.splice(j, 1); j--; @@ -360,15 +361,15 @@ export function createLocalFileLink(reference: Reference) { if (reference.attachments[attachmentindex].path == undefined) { reference.attachments[attachmentindex].path = ""; } - + const selectedfile: string = "[" + reference.attachments[attachmentindex].title + "](file:///" + // added an extra "/" to make it work on Linux encodeURI(reference.attachments[attachmentindex].path.replaceAll(" ", " ")) + ")"; //select the author - - + + filesList.push(selectedfile); } //turn the array into a string