1Writer タイムスタンプ
行頭にタイムスタンプを追加
[[YYYY-MM-DD]] hh:mm 形式
箇条書き対応
code:js
function addTimestampToSelectedLine() {
// Get the current date and time
const now = new Date();
const yyyy = now.getFullYear();
const mm = String(now.getMonth() + 1).padStart(2, '0');
const dd = String(now.getDate()).padStart(2, '0');
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
// Format as YYYY-MM-DD hh:mm
const timestamp = [[${yyyy}-${mm}-${dd}]] ${hours}:${minutes} ;
// Get the selected line range
// Get the text of the selected line
const lineText = editor.getTextInRange(lineStart, lineEnd);
// Check if the line is "- " only
if (lineText.trim() === "-") {
// Insert timestamp after "- "
const newLineText = - ${timestamp};
editor.replaceTextInRange(lineStart, lineEnd, newLineText);
editor.setSelectedRange(lineStart + 2 + timestamp.length); // Move cursor after the timestamp
} else if (lineText.startsWith("- ")) {
// If the line starts with "- ", insert timestamp after it
const newLineText = - ${timestamp}${lineText.slice(2)};
editor.replaceTextInRange(lineStart, lineEnd, newLineText);
// If the selection is at the start of the line, move the cursor after the timestamp
const start = editor.getSelectedRange(); if (start === lineStart) {
editor.setSelectedRange(lineStart + 2 + timestamp.length);
}
} else {
// Insert the timestamp at the beginning of the line
const newLineText = ${timestamp}${lineText};
editor.replaceTextInRange(lineStart, lineEnd, newLineText);
// If the selection starts at the beginning of the line, move the cursor after the timestamp
const start = editor.getSelectedRange(); if (start === lineStart) {
editor.setSelectedRange(lineStart + timestamp.length);
}
}
}
// Execute the function to add the timestamp
addTimestampToSelectedLine();
code:js
const start, end = editor.getSelectedLineRange(); // 現在の選択行の範囲を取得 var timestamp = function() {
function pad2(n) { return n < 10 ? '0' + n : n };
var date = new Date();
var timestamp =
"[[" +
date.getFullYear().toString() +
"-" +
pad2( date.getMonth() + 1) +
"-" +
pad2( date.getDate()) +
"]] " +
pad2( date.getHours() ) +
":" +
pad2( date.getMinutes() )+
" ";
return( timestamp );
}
editor.setSelectedRange(start); // カーソル位置に戻る
editor.replaceSelection( timestamp() );
editor.setSelectedRange(end + timestamp().length); // カーソルを挿入後の位置に移動