Сценарии приложений заменяют строку в Google Doc новыми элементами списка на том же уровне без изменения стиля списка

#google-apps-script #google-docs

Вопрос:

У меня есть длинный список в документе Google в стиле, похожем на этот:

  1. Раздел 1

1.1. Apple

1.2. Банан

1.3. Груша

  1. Раздел 2

2.1. Кошка

2.2. Собака

2.3. Кролик

  1. Раздел 3

3.1. Дождь

3.2. Снег

3.3. Гром

Этот стиль является третьим в документах Google:

введите описание изображения здесь

Я хочу иметь возможность заменить любой из элементов списка второго/третьего/первого уровня строкой (например, {{ReplaceMe}} ) и запустить скрипт, который заменит этот элемент и продолжит добавлять новые элементы списка под этим из массива.

Я использовал решение из другого ответа на переполнение стека, чтобы добавить следующие две функции:

 function findListItemWithText(text, doc, body) {
  var index = -1;

  for (var i=0; i<body.getNumChildren(); i  ) {
    var child = body.getChild(i);

    if (child.getType() ==  DocumentApp.ElementType.LIST_ITEM) {

      var listItem = child.asListItem();
      if (listItem.getText() == text) {
         index = i;
      }
    }
  }
  return index;
}
 

and

 function replaceListItem (placeholder, list, doc, body) {

  var index = findListItemWithText(placeholder, doc, body);
  var listItem = body.getChild(index).asListItem();

  // replace the text in the placeholder ListItem
  listItem.setText(list[0]);

  // append the rest of the list after the placeholder ListItem
  for (var i=1; i<list.length; i  ) {
    body.insertListItem(index   i, list[i]);  
  }
}
 

I then call this function when creating the document, passing the document references, string to replace, and array:

 replaceListItem("{{ReplaceMe}}", listItemsArray, doc, body);
 

This gives a solution which almost works, however there are 2 flaws:

(a) This changes the style of my list in the whole document to the default (1. 2. a. b. i. ii. etc); and

(b) Whilst the first array item is added correctly, the next ones appear to be at the previous list level but still indented correctly (i.e. the first may be in level 2 and item c. but then the rest continue the parent level i.e. 3. 4. etc but indented to match the a. b. c. level).

I would like to be able to add a string to replace anywhere in a list and at any level and have this function add to it so that I can call it as required to alter lists in the document.

EDIT

Here‘s a rudimentary version of the document.

Here’s the list before running the script:

enter image description here

Here’s the script in full edited for this example:

 function findListItemWithText(text, doc, body) {
  var index = -1;

  for (var i=0; i<body.getNumChildren(); i  ) {
    var child = body.getChild(i);

    if (child.getType() ==  DocumentApp.ElementType.LIST_ITEM) {

      var listItem = child.asListItem();
      if (listItem.getText() == text) {
         index = i;
      }
    }
  }
  return index;
}
function replaceListItem (placeholder, list, doc, body) {

  var index = findListItemWithText(placeholder, doc, body);
  var listItem = body.getChild(index).asListItem();

  // replace the text in the placeholder ListItem
  listItem.setText(list[0]);

  // append the rest of the list after the placeholder ListItem
  for (var i=1; i<list.length; i  ) {
    body.insertListItem(index   i, list[i]);  
  }
}

function replaceText() {
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();

  var replacementItems = ["Tuesday", "Wednesday", "Thursday", "Friday"];

  replaceListItem("{{ReplaceMe}}", replacementItems, doc, body);
}
 

Here’s the outcome I get:

введите описание изображения здесь

И вот результат, которого я жду:

введите описание изображения здесь

Комментарии:

1. Было бы полезно, если бы вы могли поделиться своим файлом doc, чтобы члены сообщества могли правильно воспроизвести проблему и лучше ее визуализировать. Кроме того, пожалуйста, поделитесь изображением/скриншотом текущей проблемы и вашим желаемым результатом.

2. @Ирвинджайг. — Я добавил эти сведения для справки 🙂

3. Похоже, это связано с активной ошибкой, связанной с тем, что элемент списка теряет форматирование после запуска сценария приложений на issuetracker.google.com/issues/36762602 поскольку я также могу воспроизвести поведение со своей стороны. Вы также можете запустить ошибку, чтобы получить прямые обновления по электронной почте или оставить комментарий к сообщению об ошибке.

4. @Ирвинджайг. спасибо; Я снял его и добавил комментарий, что, похоже, он также работает с insertListItem (). Можете ли вы подтвердить это, но из-за ошибки код должен работать так, чтобы получить ожидаемый результат? И если да, то есть ли какая-либо альтернатива этому, чтобы получить ожидаемый результат?