forked from lpanebr/autoNumberHeadings
-
Notifications
You must be signed in to change notification settings - Fork 0
/
code.gs
58 lines (50 loc) · 1.48 KB
/
code.gs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
function onOpen() {
DocumentApp.getUi().createMenu('Headings Tools')
.addItem('Auto Number Headings', 'numberHeadingsAdd')
.addItem('Clear Heading Numbers', 'numberHeadingsClear')
.addToUi();
}
function numberHeadingsAdd(){
numberHeadings(true);
}
function numberHeadingsClear(){
numberHeadings(false);
}
function numberHeadings(add){
var document = DocumentApp.getActiveDocument();
var body = document.getBody();
var paragraphs = document.getParagraphs();
var numbers = [0,0,0,0,0,0,0];
for (var i in paragraphs) {
var element = paragraphs[i];
var text = element.getText()+'';
var type = element.getHeading()+'';
// exclude everything but headings
if (!type.match(/Heading \d/)) {
continue;
}
// exclude empty headings (e.g. page breaks generate these)
if( text.match(/^\s*$/)){
continue;
}
if (add == true) {
var level = new RegExp(/Heading (\d)/).exec(type)[1];
var numbering = '';
numbers[level]++;
for (var currentLevel = 1; currentLevel <= 6; currentLevel++) {
if (currentLevel <= level) {
numbering += numbers[currentLevel] + '.';
} else {
numbers[currentLevel] = 0;
}
}
Logger.log(text);
var newText = numbering + ' ' + text.replace(/^[0-9\.\s]+/, '');
element.setText(newText);
Logger.log([newText]);
} else {
Logger.log(text);
element.setText(text.replace(/^[0-9\.\s]+/, ''));
}
}
}