-
-
Save superresistant/071c86d23ec1b541b474787f41bc13b5 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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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('.'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment