Created
February 6, 2018 08:37
-
-
Save howar31/c8e153a382c0544877de0cab48ca8c14 to your computer and use it in GitHub Desktop.
Heading Numbering script for Google Docs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
使用方式:
(在 Google 文件內)
--
Usage:
(In Google Docs)