Skip to content

Instantly share code, notes, and snippets.

@kibotu
Created July 16, 2018 15:04
Show Gist options
  • Save kibotu/36374763a9884ec3ba29622a74249147 to your computer and use it in GitHub Desktop.
Save kibotu/36374763a9884ec3ba29622a74249147 to your computer and use it in GitHub Desktop.
Google Document Script for insert at cursor: current date and last updated date
/* opened. Use it to add custom menus to Google Docs that allow the user to run
* custom scripts. For more information, please consult the following two
* resources.
*
* Extending Google Docs developer guide:
* https://developers.google.com/apps-script/guides/docs
*
* Document service reference documentation:
* https://developers.google.com/apps-script/reference/document/
*/
function onOpen() {
// Add a menu with some items, some separators, and a sub-menu.
DocumentApp.getUi().createMenu('Utilities')
.addItem('Insert Current Date', 'insertCurrentDate')
.addItem('Insert Last Updated Date', 'insertLastUpdatedDate')
.addToUi();
}
/**
* Inserts the date at the current cursor location in boldface.
*/
function insertCurrentDate() {
var cursor = DocumentApp.getActiveDocument().getCursor();
if (cursor) {
// Attempt to insert text at the cursor position. If insertion returns null,
// then the cursor's containing element doesn't allow text insertions.
var date = Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd"); // "yyyy-MM-dd'T'HH:mm:ss'Z'"
var element = cursor.insertText(date);
if (element) {
element.setBold(true);
} else {
DocumentApp.getUi().alert('Cannot insert text at this cursor location.');
}
} else {
DocumentApp.getUi().alert('Cannot find a cursor in the document.');
}
}
function insertLastUpdatedDate() {
var id = DocumentApp.getActiveDocument().getId();
var lastUpdated = DriveApp.getFileById(id).getLastUpdated();
var date = Utilities.formatDate(lastUpdated, "GMT", "yyyy-MM-dd"); // "yyyy-MM-dd'T'HH:mm:ss'Z'"
var cursor = DocumentApp.getActiveDocument().getCursor();
if (cursor) {
var element = cursor.insertText(date);
if (element) {
element.setBold(true);
} else {
DocumentApp.getUi().alert('Cannot insert text at this cursor location.');
}
} else {
DocumentApp.getUi().alert('Cannot find a cursor in the document.');
}
};
@stoufa
Copy link

stoufa commented Apr 18, 2022

Thanks for sharing! ๐ŸŽ‰
For some reason, the onEdit(e) doesn't work for Google Docs (and according to the documentation it only gets triggered when a Spreadsheet cell changes, so, no support for Google Docs, yet!), I wanted to run a replace-placeholder-with-content logic on edit, and adding a menu to manually do that was a good plan B. Thanks again. ๐Ÿ˜

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment