vscode-next-note/extension.js

91 lines
No EOL
3.2 KiB
JavaScript

// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
var vscode = require('vscode');
var fs = require('fs');
var dateFormat = require('dateformat');
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
function activate(context) {
console.log('next-note: activated');
context.subscriptions.push(vscode.commands.registerTextEditorCommand('extension.nextNoteInsertDate', function () {
var editor = vscode.window.activeTextEditor;
if (!editor) {
console.error("next-note: no active editor");
return;
};
//editor.document.getWordRangeAtPosition
var cursorEnd = editor.selection.end;
if (editor.document.lineCount > cursorEnd.line+1) {
cursorEnd.line += 1;
}
editor.edit(editBuilder => {
editBuilder.insert(cursorEnd, dateLine());
});
}));
context.subscriptions.push(vscode.commands.registerTextEditorCommand('extension.nextNoteOpenCurrentWeek', function () {
var basedir = process.env["NOTEDIR"];
if (!basedir) {
basedir = process.env["HOME"]+"/Notes";
console.log("next-note: no basedir. Using "+basedir);
console.log("next-note: set NOTEDIR to use a diferent basedir");
}
try {
fs.statSync(basedir);
} catch(e) {
try {
fs.mkdirSync(basedir);
} catch(e) {
vscode.window.showErrorMessage("next-note: failed to make directory: "+basedir);
return
}
}
var notepath = basedir +"/"+ currentWeekFilename();
fs.access(notepath, fs.constants.R_OK | fs.constants.W_OK, (err) => {
if (err) {
try {
fs.writeFileSync(notepath, dateLine());
} catch (e) {
vscode.window.showErrorMessage("next-note: failed to create "+ notepath);
console.error(e);
return;
}
}
});
vscode.workspace.openTextDocument(notepath).then(doc => {
vscode.window.showTextDocument(doc);
vscode.window.activeTextEditor.selection.active.line += 1;
});
}));
}
exports.activate = activate;
function dateLine() {
var d = new Date();
return "## "+ dateFormat(d,"ddd mmm dd HH:MM:ss Z yyyy") +"\n";
}
function currentWeekFilename() {
return "Tasks-"+currentWeek()+".md";
}
function currentWeek() {
var d = new Date();
var beginDate = new Date();
beginDate.setDate(d.getDate()-d.getDay()); // This will be sunday of current current week
d.setDate(beginDate.getDate()+6); // this is a week from that sunday
return dateFormat(beginDate, "yyyymmdd")+"-"+dateFormat(d,"yyyymmdd");
//return String(beginDate.getFullYear())+String(beginDate.getMonth())+String(beginDate.getDate()) +"-"+ String(d.getFullYear())+String(d.getMonth())+String(d.getDate());
}
// this method is called when your extension is deactivated
function deactivate() {
console.log("next-note: deactivated")
}
exports.deactivate = deactivate;