88 lines
2.6 KiB
TypeScript
88 lines
2.6 KiB
TypeScript
import { exec } from "child_process";
|
|
import { IncomingMessage, request } from "http";
|
|
import { window } from "vscode";
|
|
import { findReferences, Reference } from "./reference";
|
|
|
|
// when called as command using keyboard, reference argument is undefined
|
|
// in that case, try to find one under the current cursor.
|
|
function resolveReferenceArgument(reference: Reference | undefined): Reference|undefined {
|
|
if (reference === undefined) {
|
|
const editor = window.activeTextEditor;
|
|
if (!editor) {
|
|
console.log("No active editor to run command");
|
|
return;
|
|
}
|
|
const position = editor.selection.active;
|
|
const referencesAtCursor = findReferences(editor.document).filter(ref => ref.range.contains(position));
|
|
if (referencesAtCursor.length < 1) {
|
|
window.showWarningMessage("No reference at cursor position.");
|
|
return;
|
|
}
|
|
return referencesAtCursor[0];
|
|
}
|
|
return reference;
|
|
}
|
|
|
|
async function showInZotero(reference?: Reference) {
|
|
const ref = resolveReferenceArgument(reference);
|
|
if (!ref) { return; }
|
|
openUrl("zotero://select/items/@" + ref.citekey);
|
|
}
|
|
|
|
async function openZoteroPDF(reference?: Reference) {
|
|
const ref = resolveReferenceArgument(reference);
|
|
if (!ref) {
|
|
return;
|
|
}
|
|
|
|
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
|
|
|
|
const pagenr = ref.pagenr !== null ? "?page=" + ref.pagenr : "";
|
|
openUrl(result['open'] + pagenr);
|
|
break; // only open a single attachement
|
|
}
|
|
}
|
|
});
|
|
}
|
|
});
|
|
|
|
req.end('{"jsonrpc": "2.0", "method": "item.attachments", "params": ["' + ref.citekey + '"]}', 'binary');
|
|
}
|
|
|
|
function openUrl(url: string) {
|
|
// console.log('open', url);
|
|
switch (process.platform) {
|
|
case 'darwin':
|
|
exec('open "' + url + '"');
|
|
break;
|
|
case 'linux':
|
|
exec('xdg-open "' + url + '"');
|
|
break;
|
|
default:
|
|
exec('"' + url + '"');
|
|
}
|
|
|
|
}
|
|
|
|
export { openZoteroPDF, showInZotero };
|