Last active
July 17, 2020 15:11
-
-
Save ekohilas/6c5c26b906c675f4d753d1f0a99c0133 to your computer and use it in GitHub Desktop.
Inserts an RFC2822 Timestamp at the cursor location of a Google Document
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
// https://developers.google.com/apps-script/reference/document | |
function insertTimeStampAtCursor() { | |
const doc = DocumentApp.getActiveDocument(); | |
const selection = doc.getSelection(); | |
const cursor = doc.getCursor(); | |
const dateTimeString = rfc2822Datetime(); | |
if (selection) { | |
const selectedElements = selection.getRangeElements(); | |
// might break if it's not text | |
selectedElements[0] | |
.getElement() | |
.asText() | |
.setText(dateTimeString) | |
.setFontFamily("Roboto Mono"); | |
for (var i = 1; i < selectedElements.length; i++) { | |
const selectedElement = selectedElements[i]; | |
const element = selectedElement.getElement(); | |
if (selectedElement.isPartial()) { | |
element | |
.asText() | |
.deleteText( | |
selectedElement.getStartOffset(), | |
selectedElement.getEndOffsetInclusive() | |
); | |
} else { | |
element.removeFromParent(); | |
} | |
} | |
} else if (cursor) { | |
const element = cursor.insertText(dateTimeString); | |
if (element) { | |
element.setFontFamily("Roboto Mono"); | |
} else { | |
DocumentApp.getUi().alert("Cannot insert text at this cursor location."); | |
} | |
} else { | |
DocumentApp.getUi().alert("Cannot find a cursor or selection in the document."); | |
} | |
} | |
function rfc2822Datetime() { | |
const now = new Date(); | |
const timeZone = Session.getScriptTimeZone(); | |
const rfc2822Format = "EEE, dd MMM yyyy HH:mm:ss Z"; | |
const dateTimeString = Utilities.formatDate(now, timeZone, rfc2822Format); | |
return dateTimeString; | |
} | |
function menu() { | |
DocumentApp.getUi().createMenu("Utils") | |
.addItem("Insert timestamp", "insertTimeStampAtCursor") | |
.addToUi(); | |
} | |
function onOpen() { | |
menu(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment