Skip to content

Instantly share code, notes, and snippets.

@atnartur
Last active December 1, 2020 15:51
Show Gist options
  • Save atnartur/346d11bdd559bc175815644e0473e820 to your computer and use it in GitHub Desktop.
Save atnartur/346d11bdd559bc175815644e0473e820 to your computer and use it in GitHub Desktop.
Генератор списка источников для Google Docs

Генератор списка источников для Google Docs

Скрипт генерирует список источников в виде отдельного списка, который вставляется в конце документа. Работает с помощью комментариев Google Docs.

Установка

  1. Открыть документ в Google Docs
  2. В верхнем меню нажать Инструменты / Редактор скриптов
  3. Вставить содержимое файла app_script.gs
  4. Сохранить файл
  5. Обновить документ

Использование

  1. В тексте вставить цифру для ссылки (например, [1])
  2. К ней добавить комментарий в Google Docs
  3. Вставить в комментарий ссылку в формате: Link: (библиографическая ссылка)
  4. Поставить курсор в место, где должен появиться список источников
  5. Нажать Sources / Insert sources list в верхнем меню
  6. Для того, чтобы к вставленному куску текста применить форматирование остального документа, нажмите CTRL(CMD)+\

TODO

  1. Автонумерация ссылок в тексте

Источники

  1. https://developers.google.com/apps-script/reference/document/list-item
  2. https://developers.google.com/apps-script/reference/drive/drive-app
  3. https://developers.google.com/drive/api/v3/reference/comments#resource
  4. https://developers.google.com/drive/api/v2/reference/comments/list#javascript
  5. https://gist.github.com/kibotu/36374763a9884ec3ba29622a74249147
  6. https://stackoverflow.com/questions/50913184/access-google-docs-comments-from-google-app-scripts
  7. https://stackoverflow.com/questions/54903568/inserting-template-text-in-a-google-doc-in-google-apps-script
  8. https://stackoverflow.com/questions/21466589/how-to-append-a-list-item-at-a-specific-position-in-google-docs
  9. https://stackoverflow.com/questions/39926899/google-apps-script-to-find-urls-in-body-and-format-them-as-hyperlinks
  10. https://gist.github.com/gigamonkey/c9899710ec9cca4c102c761aaa5c70e5
function insertLink(body, offset) {
return function internal(item) {
var listItem = body.insertListItem(offset, item).setGlyphType(DocumentApp.GlyphType.NUMBER);
var link = listItem.findText("https?:\/\/");
if (link != null) {
var foundLink = link.getElement().asText();
var text = foundLink.getText();
var start = link.getStartOffset();
var end = start;
while (end < text.length - 1){
if (text[end] == ' ') {
break;
}
end += 1;
}
var correctLink = text.slice(start, end);
foundLink.setLinkUrl(start, end - 1, correctLink);
}
}
}
function instruction() {
DocumentApp.getUi().alert('Add a comment with "Link:" in the beginning for add source entry.');
}
function generateSourcesList() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var sourcesSet = new Set();
var sourcesOrder = {};
var text = body.getText();
var doublingNumbers = new Set();
var comments = Drive.Comments.list(doc.getId(), {maxResults: 100})
if (comments.items && comments.items.length > 0) {
for (var i = 0; i < comments.items.length; i++) {
var comment = comments.items[i];
var commentContent = comment.content;
if (comment.deleted || comment.status !== 'open' || commentContent.indexOf('Link:') === -1) {
continue;
}
var value = parseInt(comment.context.value);
if (sourcesOrder[value] !== undefined) {
doublingNumbers.add(value);
continue;
}
commentContent = commentContent.replace('Link:', '').trim();
sourcesOrder[value] = commentContent;
}
}
var sortedSourcesList = [];
var maxNumber = Math.max.apply(null, Object.keys(sourcesOrder));
for (var i = 1; i <= maxNumber; i++) {
sortedSourcesList.push(sourcesOrder[i] || '');
}
var cursor = DocumentApp.getActiveDocument().getCursor();
var offset = body.getChildIndex(cursor.getElement());
sortedSourcesList.reverse().forEach(insertLink(body, offset));
DocumentApp.getUi().alert('Дублирующиеся номера: ' + Array.from(doublingNumbers).join(", "));
}
function onOpen() {
DocumentApp.getUi().createMenu('Sources')
.addItem('Insert sources list', 'generateSourcesList')
.addItem('Instruction', 'instruction')
.addToUi();
}
@azinit
Copy link

azinit commented Dec 1, 2020

Надо глянуть как-нибудь)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment