-
Notifications
You must be signed in to change notification settings - Fork 30
/
autonumber.gs
281 lines (240 loc) · 8.79 KB
/
autonumber.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
/**
* @OnlyCurrentDoc
*
* The above comment directs Apps Script to limit the scope of file
* access for this add-on. It specifies that this add-on will only
* attempt to read or modify the files in which the add-on is used,
* and not all of the user's files. The authorization request message
* presented to users will reflect this limited scope.
*/
/**
* Creates a menu entry in the Google Docs UI when the document is opened.
* This method is only used by the regular add-on, and is never called by
* the mobile add-on version.
*
* @param {object} e The event parameter for a simple onOpen trigger. To
* determine which authorization mode (ScriptApp.AuthMode) the trigger is
* running in, inspect e.authMode.
*/
function onOpen(e) {
DocumentApp.getUi().createAddonMenu()
.addItem('Open sidebar', 'showSidebar')
.addSeparator()
.addItem('Add Headings Numbers', 'numberHeadingsAdd')
.addItem('Remove Heading Numbers', 'numberHeadingsRemove')
.addSeparator()
.addItem('Promote Headings (H1➙Title ... H6➙H5)', 'increaseHeadingLevels')
.addItem('Demote Headings (Title➙Title, H1➙H2 ... H6➙Normal)', 'decreaseHeadingLevels')
.addToUi();
DocumentApp.getUi().createMenu('Heading Tools')
.addItem('Open sidebar', 'showSidebar')
.addSeparator()
.addItem('Add Headings Numbers', 'numberHeadingsAdd')
.addItem('Remove Heading Numbers', 'numberHeadingsRemove')
.addSeparator()
.addItem('Promote Headings (H1➙Title ... H6➙H5)', 'increaseHeadingLevels')
.addItem('Demote Headings (Title➙Title, H1➙H2 ... H6➙Normal)', 'decreaseHeadingLevels')
.addToUi();
}
/**
* Runs when the add-on is installed.
* This method is only used by the regular add-on, and is never called by
* the mobile add-on version.
*
* @param {object} e The event parameter for a simple onInstall trigger. To
* determine which authorization mode (ScriptApp.AuthMode) the trigger is
* running in, inspect e.authMode. (In practice, onInstall triggers always
* run in AuthMode.FULL, but onOpen triggers may be AuthMode.LIMITED or
* AuthMode.NONE.)
*/
function onInstall(e) {
onOpen(e);
}
/**
* Opens a sidebar in the document containing the add-on's user interface.
* This method is only used by the regular add-on, and is never called by
* the mobile add-on version.
*/
function showSidebar() {
const ui = HtmlService.createHtmlOutputFromFile('sidebar')
.setTitle('Auto number headings');
DocumentApp.getUi().showSidebar(ui);
}
/**
*
* ////////////////////////////////////////////////////////////////////////////
* MY FUNCTIONS
* ////////////////////////////////////////////////////////////////////////////
*/
function numberHeadingsAdd() {
numberHeadings(true);
}
function numberHeadingsRemove() {
numberHeadings(false);
}
function increaseHeadingLevels() {
changeHeadingLevels("up")
}
function decreaseHeadingLevels() {
changeHeadingLevels("down")
}
/**
* Gets the user options and calls the required function to process headings
*
* @param {string} action The single word description of the action to perform.
* @param {boolean} skipHeadings Whether to process all or only on some levels.
* @param {boolean} savePrefs Whether to save the current options.
* @return {Object} Not implemented: Object containing the resulting text and the result of the
* operation (success or error).
*/
function processHeadings(action, skipHeadings, skippedLevels, titlesRestartNumbering, selectionOnly, savePrefs) {
if (savePrefs) {
if (skippedLevels.match(/^[1-6,; e and y-]+$/) == null)
return false
skippedLevels = skippedLevels.replace(/\D/g, '')
PropertiesService.getUserProperties()
.setProperty('action', action)
.setProperty('skipHeadings', skipHeadings)
.setProperty('skippedLevels', skippedLevels)
.setProperty('titlesRestartNumbering', titlesRestartNumbering)
.setProperty('selectionOnly', selectionOnly);
}
let result
switch (action) {
case 'promote':
//
result = changeHeadingLevels("up", skipHeadings, skippedLevels, selectionOnly);
break
case 'demote':
//
result = changeHeadingLevels("down", skipHeadings, skippedLevels, selectionOnly);
break
case 'remove':
//
result = numberHeadings(false, skipHeadings, skippedLevels, titlesRestartNumbering, selectionOnly);
break
default:
//
result = numberHeadings(true, skipHeadings, skippedLevels, titlesRestartNumbering, selectionOnly);
break
}
// const text = getSelectedText().join('\n');
return result;
}
function numberHeadings(add = false, skipHeadings = false, skippedLevels, titlesRestartNumbering, selectionOnly) {
let document = DocumentApp.getActiveDocument();
let paragraphs = selectionOnly ? document.getSelection().getRangeElements().map(re => re.getElement().asParagraph()) : document.getParagraphs();
let numbers = [0, 0, 0, 0, 0, 0, 0];
let headingsToProcessRegex = /HEADING\d/
let before = []
let after = []
if (skipHeadings) {
headingsToProcessRegex = eval('/HEADING[' + skippedLevels + ']/')
}
for (let i in paragraphs) {
let element = paragraphs[i];
let text = element.getText() + '';
let type = element.getHeading() + '';
if (type === 'TITLE' && titlesRestartNumbering) {
numbers = [0, 0, 0, 0, 0, 0, 0];
}
// exclude everything but headings
if (!type.match(headingsToProcessRegex)) {
continue;
}
// exclude empty headings (e.g. page breaks generate these)
if (text.match(/^\s*$/)) {
continue;
}
before.push(element.getText())
element.replaceText("^[0-9]+(\\.[0-9]+)*\\. ", "")
if (add == true) {
let level = new RegExp(/HEADING(\d)/).exec(type)[1];
let numbering = '';
numbers[level]++;
for (let currentLevel = 1; currentLevel <= 6; currentLevel++) {
if (currentLevel <= level) {
numbering += numbers[currentLevel] + '.';
} else {
numbers[currentLevel] = 0;
}
}
element.insertText(0, numbering + ' ')
}
after.push(element.getText())
}
return {
before: before.join("\n"),
after: after.join("\n")
}
}
function changeHeadingLevels(direction = '', skipHeadings = false, skippedLevels, selectionOnly) {
let document = DocumentApp.getActiveDocument()
let body = document.getBody()
let paragraphs = selectionOnly ? document.getSelection().getRangeElements().map(re => re.getElement().asParagraph()) : document.getParagraphs();
let headingsToProcessRegex = /HEADING\d/
let before = []
let after = []
if (skipHeadings) {
headingsToProcessRegex = eval('/HEADING[' + skippedLevels + ']/')
}
let inserted_paragraph
for (let i in paragraphs) {
let current_paragraph = paragraphs[i];
let text = current_paragraph.getText() + '';
let type = current_paragraph.getHeading() + '';
// exclude everything but headings
if (!type.match(headingsToProcessRegex)) {
continue;
}
// exclude empty headings (e.g. page breaks generate these)
if (text.match(/^\s*$/)) {
continue;
}
console.log(type)
before.push(current_paragraph.getText())
// as integer
let currentLevel = new RegExp(/HEADING(\d)/).exec(type)[1] * 1;
let problemCurrentLevel = 6
let newLevel = currentLevel + 1
let problemLevelFix = "NORMAL"
if (direction == "up") {
problemCurrentLevel = 1
newLevel = currentLevel - 1
problemLevelFix = "TITLE"
}
let newHeadingLevel = eval("DocumentApp.ParagraphHeading.HEADING" + newLevel)
if (currentLevel == problemCurrentLevel) {
newHeadingLevel = eval("DocumentApp.ParagraphHeading." + problemLevelFix)
}
let style = {};
style[DocumentApp.Attribute.HEADING] = newHeadingLevel
let curr_para_id = body.getChildIndex(current_paragraph)
let new_paragraph = current_paragraph.copy().setText(" ")
inserted_paragraph = body.insertParagraph(curr_para_id + 1, new_paragraph).setAttributes(style).merge()
// current_paragraph.setAttributes(style)
after.push(inserted_paragraph.getText())
}
return {
before: before.join("\n"),
after: after.join("\n")
}
}
/**
* Gets the stored user preferences for the origin and destination languages,
* if they exist.
* This method is only used by the regular add-on, and is never called by
* the mobile add-on version.
*
* @return {Object} The user's origin and destination language preferences, if
* they exist.
*/
function getPreferences() {
const userProperties = PropertiesService.getUserProperties();
return {
action: userProperties.getProperty('action'),
skipHeadings: userProperties.getProperty('skipHeadings'),
skippedLevels: userProperties.getProperty('skippedLevels'),
titlesRestartNumbering: userProperties.getProperty('titlesRestartNumbering')
};
}