Skip to content

Instantly share code, notes, and snippets.

@haughki
Created November 13, 2020 19:55
Show Gist options
  • Save haughki/470be1b9b074073d62dc3e2a81ea2bd4 to your computer and use it in GitHub Desktop.
Save haughki/470be1b9b074073d62dc3e2a81ea2bd4 to your computer and use it in GitHub Desktop.
A google apps script for google doc to a) create a new menu to insert the current date b) insert the date
/**
* The onOpen function runs automatically when the Google Docs document is
* 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('Custom Utils')
.addItem('Insert Date', 'insertAtCursor')
.addToUi();
}
/**
* Inserts the date at the current cursor location in boldface.
*/
function insertAtCursor() {
var doc = DocumentApp.getActiveDocument()
var cursor = doc.getCursor();
if (cursor) {
// Insert current date, bolded, at cursor position. Move cursor to end of date.
// Insert newline, disable bold, move cursor one line down.
var date = formatDate(new Date)
var date_element = cursor.insertText(date);
if (date_element) {
date_element.setBold(true);
var end_of_date_str_pos = doc.newPosition(date_element, date.length)
if (end_of_date_str_pos) {
doc.setCursor(end_of_date_str_pos)
var newline_element = cursor.insertText("\n");
if (newline_element) {
newline_element.setBold(false);
var newline_pos = doc.newPosition(newline_element, 1)
if (newline_pos) {
doc.setCursor(newline_pos)
} else {
DocumentApp.getUi().alert('Cannot move cursor to this position ' + newline_pos + '.');
}
} else {
DocumentApp.getUi().alert('Cannot insert text at this cursor location.');
}
} else {
DocumentApp.getUi().alert('Cannot move cursor to this position ' + end_of_date_str_pos + '.');
}
} else {
DocumentApp.getUi().alert('Cannot insert text at this cursor location.');
}
} else {
DocumentApp.getUi().alert('Cannot find a cursor in the document.');
}
}
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
return [year, month, day].join('.');
}
@superresistant
Copy link

I can't make it work idk why.
It says finished script but nothing's happening.

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