Initial commit

This commit is contained in:
Ruben van de Ven 2022-02-04 12:03:05 +01:00
commit 7edbd604e7
14 changed files with 4447 additions and 0 deletions

24
.eslintrc.json Normal file
View file

@ -0,0 +1,24 @@
{
"root": true,
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module"
},
"plugins": [
"@typescript-eslint"
],
"rules": {
"@typescript-eslint/naming-convention": "warn",
"@typescript-eslint/semi": "warn",
"curly": "warn",
"eqeqeq": "warn",
"no-throw-literal": "warn",
"semi": "off"
},
"ignorePatterns": [
"out",
"dist",
"**/*.d.ts"
]
}

5
.gitignore vendored Normal file
View file

@ -0,0 +1,5 @@
out
dist
node_modules
.vscode-test/
*.vsix

7
.vscode/extensions.json vendored Normal file
View file

@ -0,0 +1,7 @@
{
// See http://go.microsoft.com/fwlink/?LinkId=827846
// for the documentation about the extensions.json format
"recommendations": [
"dbaeumer.vscode-eslint"
]
}

34
.vscode/launch.json vendored Normal file
View file

@ -0,0 +1,34 @@
// A launch configuration that compiles the extension and then opens it inside a new window
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
{
"version": "0.2.0",
"configurations": [
{
"name": "Run Extension",
"type": "extensionHost",
"request": "launch",
"args": [
"--extensionDevelopmentPath=${workspaceFolder}"
],
"outFiles": [
"${workspaceFolder}/out/**/*.js"
],
"preLaunchTask": "${defaultBuildTask}"
},
{
"name": "Extension Tests",
"type": "extensionHost",
"request": "launch",
"args": [
"--extensionDevelopmentPath=${workspaceFolder}",
"--extensionTestsPath=${workspaceFolder}/out/test/suite/index"
],
"outFiles": [
"${workspaceFolder}/out/test/**/*.js"
],
"preLaunchTask": "${defaultBuildTask}"
}
]
}

11
.vscode/settings.json vendored Normal file
View file

@ -0,0 +1,11 @@
// Place your settings in this file to overwrite default and user settings.
{
"files.exclude": {
"out": false // set this to true to hide the "out" folder with the compiled JS files
},
"search.exclude": {
"out": true // set this to false to include "out" folder in search results
},
// Turn off tsc task auto detection since we have the necessary tasks as npm scripts
"typescript.tsc.autoDetect": "off"
}

20
.vscode/tasks.json vendored Normal file
View file

@ -0,0 +1,20 @@
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
{
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "watch",
"problemMatcher": "$tsc-watch",
"isBackground": true,
"presentation": {
"reveal": "never"
},
"group": {
"kind": "build",
"isDefault": true
}
}
]
}

10
.vscodeignore Normal file
View file

@ -0,0 +1,10 @@
.vscode/**
.vscode-test/**
src/**
.gitignore
.yarnrc
vsc-extension-quickstart.md
**/tsconfig.json
**/.eslintrc.json
**/*.map
**/*.ts

33
README.md Normal file
View file

@ -0,0 +1,33 @@
# zoterolens README
Zoterolens scans Markdown files for possible citationkeys and adds links open then with Zotero. Also a convenient option to immediately open the cited pdf-file.
I recommend using it in combination with an extension such as [Citation Picker for Zotero](https://marketplace.visualstudio.com/items?itemName=mblode.zotero), and/or [Pandoc Citer](https://marketplace.visualstudio.com/items?itemName=notZaki.pandocciter) to be able to easily add citations.
## Features
- CodeLens to open PDF's based on citekey
- CodeLens to select item in Zotero based on citekey
## Requirements
* Zotero
* Zotero's Better-Bibtex plugin
## Extension Settings
none.
## Known Issues / Wishlist
* It does not yet check if the citekey actually exists in Zotero, nor if it actually has any attachment.
* No error if Zotero isn't running, or the Better-Bibtex plugin is not configured.
* Does not yet consider the page number of the citation when opening the pdf.
* Zotero port cannot yet be configured.
## Release Notes
### 1.0.0
Initial release of Zoterolens

4071
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

49
package.json Normal file
View file

@ -0,0 +1,49 @@
{
"name": "zoterolens",
"displayName": "ZoteroLens",
"description": "Lens providing quick access to Zotero information and attachments from citations.",
"version": "0.0.1",
"engines": {
"vscode": "^1.63.0"
},
"categories": [
"Other"
],
"activationEvents": [
"onLanguage:markdown"
],
"main": "./out/extension.js",
"contributes": {
"commands": [
{
"command": "extension.showInZotero",
"title": "Select item in Zotero by citeref"
},
{
"command": "extension.openZoteroPDF",
"title": "Open PDF attached in Zotero by citeref."
}
]
},
"scripts": {
"vscode:prepublish": "npm run compile",
"compile": "tsc -p ./",
"watch": "tsc -watch -p ./",
"pretest": "npm run compile && npm run lint",
"lint": "eslint src --ext ts",
"test": "node ./out/test/runTest.js"
},
"devDependencies": {
"@types/glob": "^7.2.0",
"@types/mocha": "^9.0.0",
"@types/node": "14.x",
"@types/vscode": "^1.63.0",
"@typescript-eslint/eslint-plugin": "^5.9.1",
"@typescript-eslint/parser": "^5.9.1",
"@vscode/test-electron": "^2.0.3",
"eslint": "^8.6.0",
"glob": "^7.2.0",
"mocha": "^9.1.3",
"typescript": "^4.5.4"
}
}

59
src/commands.ts Normal file
View file

@ -0,0 +1,59 @@
import { exec } from "child_process";
import { IncomingMessage, request } from "http";
import Reference from "./zoteroCodeLensProvider";
async function showInZotero(reference: Reference) {
openUrl("zotero://select/items/@" + reference.citekey);
}
async function openZoteroPDF(reference: Reference) {
const req = request("http://127.0.0.1:23119/better-bibtex/json-rpc", {
'method': 'POST',
'headers': {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
req.on("response", (res: IncomingMessage) => {
if (res.statusCode != 200) {
console.error('Error with request. Is Zotero running and Better-BibTex installed?')
} else {
// console.log('test2', res.statusCode, res);
res.on('readable', () => {
const buffer: Buffer = res.read();
const s = buffer.toString();
const data = JSON.parse(s);
console.log('received from Zotero', data);
for (const result of data['result']) {
if (result['path'].toLowerCase().endsWith('.pdf')) {
// TODO add ?page=nr to open given page
openUrl(result['open']);
break; // only open a single attachement
}
}
});
}
});
req.end('{"jsonrpc": "2.0", "method": "item.attachments", "params": ["' + reference.citekey + '"]}', 'binary');
}
function openUrl(url: string) {
switch (process.platform) {
case 'darwin':
exec('open "' + url + '"');
break;
case 'linux':
exec('xdg-open "' + url + '"');
break;
default:
exec('"' + url + '"');
}
}
export { openZoteroPDF, showInZotero };

36
src/extension.ts Normal file
View file

@ -0,0 +1,36 @@
import { commands, ExtensionContext, languages } from "vscode";
import ZoteroCodeLensProvider from "./zoteroCodeLensProvider";
import { openZoteroPDF, showInZotero } from "./commands";
export function activate(context: ExtensionContext) {
// Register the command
let commandDisposable2 = commands.registerCommand(
"extension.showInZotero",
showInZotero
);
let commandDisposable3 = commands.registerCommand(
"extension.openZoteroPDF",
openZoteroPDF
);
// Get a document selector for the CodeLens provider
// This one is any file that has the language of javascript
let docSelector = {
language: "markdown",
scheme: "file"
};
// Register our CodeLens provider
let codeLensProviderDisposable = languages.registerCodeLensProvider(
docSelector,
new ZoteroCodeLensProvider()
);
// Push the command and CodeLens provider to the context so it can be disposed of later
context.subscriptions.push(commandDisposable2);
context.subscriptions.push(commandDisposable3);
context.subscriptions.push(codeLensProviderDisposable);
}
export function deactivate() {}

View file

@ -0,0 +1,71 @@
import {
CodeLensProvider,
TextDocument,
CodeLens,
Range,
Command
} from "vscode";
interface Reference {
document: TextDocument;
citekey: string;
pagenr: number | null;
range: Range;
}
class ZoteroCodeLensProvider implements CodeLensProvider {
// Each provider requires a provideCodeLenses function which will give the various documents
// the code lenses
async provideCodeLenses(document: TextDocument): Promise<CodeLens[]> {
// const txt = document.getText();
const references = this.findReferences(document);
return references.map(reference => [
new CodeLens(reference.range, {
title: '@' + reference.citekey,
command: 'extension.showInZotero',
arguments: [reference]
}),
new CodeLens(reference.range, {
title: '(pdf)',
command: 'extension.openZoteroPDF',
arguments: [reference]
})]).flat();
// let codeLens = new CodeLens(topOfDocument, c);
// return [codeLens];
}
// TODO match citations in brackets [@citation] inline @citatinon,
// but also page number in [see @citation p.23] and
// inlince @citation [p.23] (so brackets after inline)
// TODO possibly use https://github.com/martinring/markdown-it-citations/blob/ba82a511de047a2438b4ac060c4c71b5a5c82da9/src/index.ts#L43
findReferences(document: TextDocument): Reference[] {
const matches: Reference[] = [];
for (let lineNr = 0; lineNr < document.lineCount; lineNr++) {
const line = document.lineAt(lineNr);
let match: RegExpExecArray | null;
let regex = /(?<=@)\w+/g;
regex.lastIndex = 0;
const text = line.text;//.substring(0, 1000);
while ((match = regex.exec(text))) {
const result = {
document: document,
citekey: match[0],
pagenr: null,
range: new Range(lineNr, match.index, lineNr, match.index + match[0].length)
};
// if (result) {
matches.push(result);
// }
}
}
return matches;
}
}
export default ZoteroCodeLensProvider;

17
tsconfig.json Normal file
View file

@ -0,0 +1,17 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "ES2020",
"outDir": "out",
"lib": [
"ES2020"
],
"sourceMap": true,
"rootDir": "src",
"strict": true /* enable all strict type-checking options */
/* Additional Checks */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
}
}