Skip to content

Instantly share code, notes, and snippets.

@howar31
Created February 6, 2018 08:37
Show Gist options
  • Save howar31/c8e153a382c0544877de0cab48ca8c14 to your computer and use it in GitHub Desktop.
Save howar31/c8e153a382c0544877de0cab48ca8c14 to your computer and use it in GitHub Desktop.
Heading Numbering script for Google Docs
function onOpen() {
// Add a menu with some items, some separators, and a sub-menu.
DocumentApp.getUi().createMenu('章節編號')
.addItem('自動章節編號', 'numberHeadingsAdd')
.addItem('清除章節編號', 'numberHeadingsClear')
.addToUi();
}
function numberHeadingsAdd(){
numberHeadings(true);
}
function numberHeadingsClear(){
numberHeadings(false);
}
function numberHeadings(add){
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var p = doc.getParagraphs();
var numbers = [0,0,0,0,0,0,0];
for (var i in p) {
var e = p[i];
var eText = e.getText()+'';
var eTypeString = e.getHeading()+'';
if (!eTypeString.match(/Heading \d/)) {
continue;
}
if (add == true) {
var patt = new RegExp(/Heading (\d)/);
var eLevel = patt.exec(eTypeString)[1];
var txt = '';
if (eLevel == 1) {
var spacing = '';
} else {
var spacing = ' ';
}
numbers[eLevel]++;
for (var l = 2; l<=6; l++) {
if (l <= eLevel) {
txt += numbers[l]+'.';
} else {
numbers[l] = 0;
}
}
Logger.log(eText);
var newText = txt+spacing+eText.replace(/^[0-9\.\s]+/, '');
e.setText(newText);
Logger.log([newText]);
} else {
Logger.log(eText);
var newText = eText.replace(/^[0-9\.\s]+/, '');
e.setText(newText);
}
}
}
@howar31
Copy link
Author

howar31 commented Feb 6, 2018

使用方式:
(在 Google 文件內)

  1. 工具 > 指令碼編輯器...
  2. 貼上上面的程式碼然後存檔 (檔名隨意)
  3. 重新整理 Google 文件

--

Usage:
(In Google Docs)

  1. Tools > Script editor...
  2. Paste the snippet above and save. (with whatever name)
  3. Reload your Google Docs

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