3

所以我想知道如何将谷歌应用程序脚本所做的更改更改为可逆文档。特别是,我正在编写一个脚本,该脚本将自定义样式应用于 Google Docs 文档中的选定元素。这不是一件难事。问题是脚本所做的更改没有反映在文档的历史记录中,因此无法撤消。据我所知,也没有可逆编辑会话的概念。

那么有没有办法撤消脚本所做的更改?

function onOpen() {
  DocumentApp.getUi()
  .createMenu('Extras')
  .addItem('Apply code style', 'applyCodeStyle')
  .addToUi();
}

function applyCodeStyle() {
  var selection = DocumentApp.getActiveDocument().getSelection();
  if (selection) {
   var elements = selection.getSelectedElements();
   for (var i = 0; i < elements.length; i++) {
     var element = elements[i];

     // Only modify elements that can be edited as text; skip images and other non-text elements.
     if (element.getElement().editAsText) {
       var text = element.getElement().editAsText();

       // Bold the selected part of the element, or the full element if it's completely selected.
       if (element.isPartial()) {
         text.setBold(element.getStartOffset(), element.getEndOffsetInclusive(), true);
       } else {
         text.setBold(true);
       }
     }
   }
 }
}
4

1 回答 1

1

The closest I can imagine it to create a backup copy of your file in a specific folder every 5 minutes or so when you are modifying it so you have at least a copy of this doc version. Not ideal but it works...

Here is a piece of code that does it, starting from your code I just added the timer/copy stuff, you can try it by changing the folder ID.

EDIT : added a try/catch for first execution without error.

function applyCodeStyle() {
  var selection = DocumentApp.getActiveDocument().getSelection();
  try{
    var x = new Date().getTime()/60000-new Date(Utilities.jsonParse(ScriptProperties.getProperty('lastBKP'))).getTime()/60000 ;
  }catch(e){
    ScriptProperties.setProperty('lastBKP', Utilities.jsonStringify(new Date()));
    var x = 0
    }    
  Logger.log(x+' minutes')
  if (selection) {
    if(x > 5){
      var docId = DocumentApp.getActiveDocument().getId();
      DriveApp.getFileById(docId).makeCopy(DriveApp.getFolderById('0B3qSFd3iikE3NWd5TmRZdjdmMEk')).setName('backup_of_'+DocumentApp.getActiveDocument().getName()+'_on_'+Utilities.formatDate(new Date(),'GMT','yyyy-MMM-dd-HH-mm'));
      Logger.log("file copied because new Date().getTime()/3600-new Date(Utilities.jsonParse(ScriptProperties.getProperty('lastBKP'))).getTime()/3600 ="+x);
      ScriptProperties.setProperty('lastBKP', Utilities.jsonStringify(new Date()));
    }
    var elements = selection.getSelectedElements();
    for (var i = 0; i < elements.length; i++) {
      var element = elements[i];
      if (element.getElement().editAsText) {
        var text = element.getElement().editAsText();
        if (element.isPartial()) {
          text.setBold(element.getStartOffset(), element.getEndOffsetInclusive(), true);
        } else {
          text.setBold(true);
        }
      }
    }
  }
}
于 2013-11-05T18:27:59.930 回答