Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MingweiSamuel/82d65b3199ded3637f4277a788fdab55 to your computer and use it in GitHub Desktop.
Save MingweiSamuel/82d65b3199ded3637f4277a788fdab55 to your computer and use it in GitHub Desktop.
function onOpen() {
const ui = DocumentApp.getUi();
// Or DocumentApp or FormApp.
ui.createAddonMenu()
.addItem('Invert Selected', 'doInvertSelected')
.addToUi();
}
function invertColor(val) {
return '#' + ('00000' + (0xFFFFFF - parseInt(val.substr(1), 16)).toString(16)).substr(-6);
}
function doInvertSelected() {
const doc = DocumentApp.getActiveDocument();
const selection = doc.getSelection();
if (!selection)
return;
const rangeElements = selection.getRangeElements();
for (const rangeElement of rangeElements) {
const element = rangeElement.getElement();
rinvert(element);
}
}
function rinvert(element) {
if (element.getNumChildren) {
console.log(element.getNumChildren());
for (let i = 0; i < element.getNumChildren(); i++) {
rinvert(element.getChild(i));
}
return;
}
const oldStyle = element.getAttributes();
const oldBackground = oldStyle[DocumentApp.Attribute.BACKGROUND_COLOR];
const style = {};
if (oldBackground) {
style[DocumentApp.Attribute.BACKGROUND_COLOR] = invertColor(oldBackground);
}
element.setAttributes(style);
if (element.getForegroundColor) {
for (let i = 0; i < element.getText().length; i++) {
element.setForegroundColor(i, i, invertColor(element.getForegroundColor(i)));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment