Skip to content

Commit

Permalink
enable custom output format, update readme
Browse files Browse the repository at this point in the history
  • Loading branch information
hucorz committed Sep 1, 2023
1 parent 0e6ea91 commit e191c21
Show file tree
Hide file tree
Showing 16 changed files with 117 additions and 118 deletions.
35 changes: 31 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,21 +8,48 @@ Welcome any suggestions.

## How to use

This plugin has not been included in the official list yet, so it needs to be cloned locally for usage.
Download from Obsidian community plugins:

- open settings
- turn on community plugins and browse plugins
- search `autoliterature` and install

Download source code:

- clone this repo to the path: vault/.obsidian
- turn on community plugins in obsidian
- enable autoLiterature

## ScreenShot

This plugin supports arXiv IDs,bio,medRXiv,BioRXiv.
This plugin supports arXiv ID,boi ID,medRXiv ID,BioRXiv ID.

This plugin will Auto-detection the string "- {xxx}".


When the note file includes "- {paper_id}", the information of that literature will be downloaded.
When the note file includes "- {paper_id}", the information of that literature will replace.

![](./imgs/screenshot.gif)

## Settings

**Output format**: let you customize your paperInfo foramt.
- ${title} will be replaced by paper's title
- ${url}, ${author}, ${journal}, ${pubDate} as the same
- \n means the new line, \t means the tab

>Note: different themes will have different effects
example1 (default setting):
```
- **${title}** ([link](${url}))\n\t- *${author} et.al.*\n\t- ${journal}\n\t- ${pubDate}
```

![](screenshot.gif)
![Alt text](./imgs/format_example1.png)

example2:
```
------\n**${title}** ([link](${url}))\n\t- *${author} et.al.*\n\t- ${journal}\n\t- ${pubDate}\n\n------\n
```

![Alt text](./imgs/format_example2.png)
4 changes: 2 additions & 2 deletions autoliter/patternRecognizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ class PatternRecognizer {
findAll(input: string): RegExpExecArray[] | null {
const matches: RegExpExecArray[] = [];
let match: RegExpExecArray | null;

while ((match = this.pattern.exec(input)) !== null) {
matches.push(match);
matches.push(match);
}
return matches;
}
Expand Down
30 changes: 30 additions & 0 deletions autoliter/settings.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import AutoLiter from "../main";
import { App, PluginSettingTab, Setting } from "obsidian";

export class AutoLiterSettingTab extends PluginSettingTab {
plugin: AutoLiter;

constructor(app: App, plugin: AutoLiter) {
super(app, plugin);
this.plugin = plugin;
}

display(): void {
let { containerEl } = this;

containerEl.empty();

new Setting(containerEl)
.setName("Output format")
.setDesc("output format after update the note")
.addText((text) =>
text
.setPlaceholder("output format")
.setValue(this.plugin.settings.outputFormat)
.onChange(async (value) => {
this.plugin.settings.outputFormat = value;
await this.plugin.saveSettings();
})
);
}
}
2 changes: 1 addition & 1 deletion autoliter/spiders/arxivInfo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import parser from 'rss-parser';
import { assert } from 'autoliter/utils';
import type { Dict } from 'autoliter/types';
import {requestUrl} from 'obsidian'
import { requestUrl } from 'obsidian'

class ArxivInfo {
private base_url: string;
Expand Down
2 changes: 1 addition & 1 deletion autoliter/spiders/bmInfo.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import CrossrefInfo from "./crossrefInfo";
import { Dict } from "autoliter/types";
import {requestUrl} from 'obsidian'
import { requestUrl } from 'obsidian'


class BMInfo {
Expand Down
4 changes: 2 additions & 2 deletions autoliter/spiders/crossrefInfo.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { Dict } from 'autoliter/types';
import {requestUrl} from 'obsidian'
import { requestUrl } from 'obsidian'

// const HEADERS = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:27.0) Gecko/20100101 Firefox/43.0'};

Expand All @@ -21,7 +21,7 @@ class CrossrefInfo {
}
}

extractInfo(data: any): Dict {
extractInfo(data: any): Dict {
const title: string = data['title'][0];
const author: string = data['author'] && data['author'].length > 0 ? data['author'][0]['given'] : "No author";
const journal = data['short-container-title']?.[0] || data['container-title']?.[0] || "No journal";
Expand Down
4 changes: 2 additions & 2 deletions autoliter/spiders/spider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,12 @@ class Spider {
return "medbiorxivId";
} else if (identifier.match(/[0-9]{2}[0-1][0-9]\.[0-9]{3,}.*|.*\/[0-9]{2}[0-1][0-9]{4}/)) {
return 'arxivId';
}else {
} else {
return "unrecognized";
}
}

async getPaperInfo(paperID: string): Promise<Dict>{
async getPaperInfo(paperID: string): Promise<Dict> {
/*
paperID: the paper id like 2022.12345
*/
Expand Down
2 changes: 1 addition & 1 deletion autoliter/types.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
type Dict = { [key: string]: string | number | boolean};
type Dict = { [key: string]: string | number | boolean };

export type { Dict };
18 changes: 13 additions & 5 deletions autoliter/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import Spider from './spiders/spider';
import type { Dict } from 'autoliter/types';


async function getReplaceDict(m: RegExpExecArray[], file: TFile): Promise<{ [key: string]: string }> {
async function getReplaceDict(m: RegExpExecArray[], file: TFile, outputFormat: string): Promise<{ [key: string]: string }> {
/*
get replace dict in the form of {old: new} for the given md file
*/
Expand All @@ -21,18 +21,26 @@ async function getReplaceDict(m: RegExpExecArray[], file: TFile): Promise<{ [key
paperInfo.id = paperID;
return paperInfo;
} catch (error) {
return {id: paperID, error: `Error in getReplaceDict: ${error.message}`};
return { id: paperID, error: `Error in getReplaceDict: ${error.message}` };
}
}));
results.forEach((result: Dict) => {
const {id} = result;
const { id } = result;
const origin_string = `- {${id}}`;
if (result.error) {
const e = result.error;
replaceDict[origin_string] = `${origin_string} **${e}**`;
} else {
const {title, author, journal, pubDate, url} = result;
replaceDict[origin_string] = `- **${title}** ([link](${url}))\n\t- ${author} et.al.\n\t- **${journal}**\n\t- **${pubDate}**`
const { title, author, journal, pubDate, url } = result;
// replaceDict[origin_string] = `- **${title}** ([link](${url}))\n\t- *${author} et.al.*\n\t- ${journal}\n\t- ${pubDate}`
replaceDict[origin_string] = outputFormat
.replace("${title}", title as string)
.replace("${author}", author as string)
.replace("${journal}", journal as string)
.replace("${pubDate}", pubDate as string)
.replace("${url}", url as string)
.replace(/\\n/g, '\n') // replace \n with newline, this step is must
.replace(/\\t/g, '\t');
}
});
progressNotice.setMessage(`Updating ${file.path}: ${total}/${total}`);
Expand Down
Binary file added imgs/format_example1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added imgs/format_example2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
File renamed without changes
34 changes: 30 additions & 4 deletions main.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,26 @@
import { App, Editor, MarkdownView, Modal, Notice, Plugin, PluginSettingTab, Setting, TFile, Vault} from 'obsidian';
import { App, Editor, MarkdownView, Modal, Notice, Plugin, PluginSettingTab, Setting, TFile, Vault } from 'obsidian';
import PatternRecognizer from 'autoliter/patternRecognizer';
import {getReplaceDict} from 'autoliter/utils'
import { getReplaceDict } from 'autoliter/utils'
import { AutoLiterSettingTab } from 'autoliter/settings'

interface AutoLiterSettings {
outputFormat: string;
}


const DEFAULT_SETTINGS: Partial<AutoLiterSettings> = {
// example: "------\n**${title}** ([link](${url}))\n\t- *${author} et.al.*\n\t- ${journal}\n\t- ${pubDate}\n\n------\n"
outputFormat: "- **${title}** ([link](${url}))\n\t- *${author} et.al.*\n\t- ${journal}\n\t- ${pubDate}",
}

export default class AutoLiter extends Plugin {
settings: AutoLiterSettings;

async onload() {
await this.loadSettings();

this.addSettingTab(new AutoLiterSettingTab(this.app, this));

const paperRecognizer = new PatternRecognizer(/- \{.{3,}\}/g); // g is must

// This creates an icon in the left ribbon.
Expand All @@ -21,19 +38,28 @@ export default class AutoLiter extends Plugin {
async updateNote(file: TFile, paperRecognizer: PatternRecognizer) {
const content = await this.app.vault.read(file);
const m = paperRecognizer.findAll(content);

if (m && m.length != 0) {
const replaceDict = await getReplaceDict(m, file);
const replaceDict = await getReplaceDict(m, file, this.settings.outputFormat);
this.update(this.app.vault, file, replaceDict);
}
}

update(vault: Vault, file: TFile, repalceDict: { [key: string]: string }): Promise<string> {
return vault.process(file, (data) => {
Object.keys(repalceDict).forEach( key => {
Object.keys(repalceDict).forEach(key => {
data = data.replace(key, repalceDict[key]);
})
return data;
})
}

async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}

async saveSettings() {
await this.saveData(this.settings);
}
}

2 changes: 1 addition & 1 deletion manifest.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"id": "auto-literature",
"name": "autoLiterature",
"version": "1.0.9",
"version": "1.1.0",
"minAppVersion": "0.15.0",
"description": "Assist you in taking notes for your literature.",
"author": "hucorz",
Expand Down
Loading

0 comments on commit e191c21

Please sign in to comment.